Search is not available for this dataset
text
string
meta
dict
/** * * @file qwrapper_zgemv.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 Mark Gates * @author Mathieu Faverge * @date 2010-11-15 * @precisions normal z -> c d s * **/ #include <cblas.h> #include "common.h" /***************************************************************************//** * **/ void QUARK_CORE_zgemv(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum trans, int m, int n, PLASMA_Complex64_t alpha, const PLASMA_Complex64_t *A, int lda, const PLASMA_Complex64_t *x, int incx, PLASMA_Complex64_t beta, PLASMA_Complex64_t *y, int incy) { DAG_CORE_GEMV; QUARK_Insert_Task(quark, CORE_zgemv_quark, task_flags, sizeof(PLASMA_enum), &trans, VALUE, sizeof(int), &m, VALUE, sizeof(int), &n, VALUE, sizeof(PLASMA_Complex64_t), &alpha, VALUE, sizeof(PLASMA_Complex64_t)*m*n, A, INPUT, sizeof(int), &lda, VALUE, sizeof(PLASMA_Complex64_t)*n, x, INPUT, sizeof(int), &incx, VALUE, sizeof(PLASMA_Complex64_t), &beta, VALUE, sizeof(PLASMA_Complex64_t)*m, y, INOUT, sizeof(int), &incy, VALUE, 0); } /***************************************************************************//** * **/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zgemv_quark = PCORE_zgemv_quark #define CORE_zgemv_quark PCORE_zgemv_quark #endif void CORE_zgemv_quark(Quark *quark) { PLASMA_enum trans; int m, n, lda, incx, incy; PLASMA_Complex64_t alpha, beta; const PLASMA_Complex64_t *A, *x; PLASMA_Complex64_t *y; quark_unpack_args_11( quark, trans, m, n, alpha, A, lda, x, incx, beta, y, incy ); cblas_zgemv( CblasColMajor, (CBLAS_TRANSPOSE)trans, m, n, CBLAS_SADDR(alpha), A, lda, x, incx, CBLAS_SADDR(beta), y, incy); }
{ "alphanum_fraction": 0.517739816, "avg_line_length": 33.5735294118, "ext": "c", "hexsha": "759f59a53da1aa4cfb72cf1bff1acb3ae10afaa4", "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_zgemv.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_zgemv.c", "max_line_length": 86, "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_zgemv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 638, "size": 2283 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <math.h> #include <float.h> #include "parmt_postProcess.h" #include "beachball.h" #ifdef PARMT_USE_INTEL #include <mkl_cblas.h> #else #include <cblas.h> #endif #include "compearth.h" static void argsort3(const double *__restrict__ x, int *__restrict__ iperm); static void sortUL(const double *__restrict__ lam, const double *__restrict__ U, double *__restrict__ lamSort, double *__restrict__ Usort); static void eigenvector2PrincipalAxis(const double eig, const double *__restrict__ ev, double *__restrict__ paxis); static void vecstrd(const double str, const double dip, double r[3]); static double dot3(const double *__restrict__ x, const double *__restrict__ y); static void gemv3(const double *__restrict__ A, const double *__restrict__ x, double *__restrict__ y); static void crossp(const double *__restrict__ u, const double *__restrict__ v, double *__restrict__ n); static void strdvec(double r[3], double *str, double *dip); int postprocess_tnp2beachballPolarity(const int nxp, const double xc, const double yc, const double rad, const double *__restrict__ pAxis, const double *__restrict__ nAxis, const double *__restrict__ tAxis, double *__restrict__ xw1, double *__restrict__ yw1, int8_t *__restrict__ pn1) { double ax1[3] __attribute__ ((aligned(64))); double ax2[3] __attribute__ ((aligned(64))); double ax3[3] __attribute__ ((aligned(64))); double rm[9] __attribute__ ((aligned(64))); double rmt[9] __attribute__ ((aligned(64))); double tm[9] __attribute__ ((aligned(64))); double pt[3] __attribute__ ((aligned(64))); double ptnew[3] __attribute__ ((aligned(64))); double ampMax, az, baz, baz1, bdp, bdp1, bev, bevI, dp, dx, dxc, dy, dyc, evI, fclvd, fIso, paz, paz1, pdp, pdp1, pev, pevI, plusMin, rad2, rpt, rpt2, taz, taz1, tdp, tdp1, tev, tevI, theta, x, x0, y, y0; int ix, iy, k, nx, ny; const double degradi = 180.0/M_PI; const double third = 1.0/3.0; const double sqrt2 = 1.4142135623730951; const double sqrt2i = 1.0/sqrt2; taz1 = tAxis[0]; tdp1 = tAxis[1]; tevI = tAxis[2]; baz1 = nAxis[0]; bdp1 = nAxis[1]; bevI = nAxis[2]; paz1 = pAxis[0]; pdp1 = pAxis[1]; pevI = pAxis[2]; // Avoid overwriting memory taz = taz1; tdp = tdp1; baz = baz1; bdp = bdp1; paz = paz1; pdp = pdp1; // Step 1: set up axes: // - D axis ('dominant' 1-axis - with largest absolute eigenvalue) // - M axis ('minor' 3-axis) // - B axis ( 2-axis) evI = (tevI + bevI + pevI)*third; tev = tevI - evI; bev = bevI - evI; pev = pevI - evI; vecstrd(paz, pdp, ax1); vecstrd(taz, tdp, ax3); fclvd = fabs(bev/pev); fIso = evI/pev; if (fabs(tev) > fabs(pev)) { vecstrd(taz, tdp, ax1); vecstrd(paz, pdp, ax3); fclvd = fabs(bev/tev); fIso = evI/tev; } //if (fabs(evI) > .03) //{ // write(6,901) evI //} crossp(ax1, ax3, ax2); strdvec(ax2, &baz, &bdp); cliffsNodes_mtensor(taz, tdp, paz, pdp, tevI, bevI, pevI, tm, rm, rmt, &ampMax); nx = nxp; ny = nxp; memset(xw1, 0, (size_t) (nx*ny)*sizeof(double)); memset(yw1, 0, (size_t) (nx*ny)*sizeof(double)); memset(pn1, 0, (size_t) (nx*ny)*sizeof(int8_t)); dx = 2.0*rad/(double) (nx - 1); dy = 2.0*rad/(double) (ny - 1); x0 = xc - rad; y0 = yc - rad; rad2 = rad*rad; // saves a sqrt computation when comparing distance // loop on pixel grid for (iy=0; iy<ny; iy++) { for (ix=0; ix<nx; ix++) { x = x0 + (double) ix*dx; y = y0 + (double) iy*dy; k = iy*nx + ix; pn1[k] = 0; xw1[k] = x; yw1[k] = y; // require (x,y) be in the focal sphere dxc = x - xc; dyc = y - yc; rpt2 = dxc*dxc + dyc*dyc; if (rpt2 < rad2) { rpt = sqrt(rpt2); // compute the azimuth theta = atan2(y - yc, x - xc); // measure from x axis az = (M_PI_2 - theta)*degradi; // az is measured from north if (az < 0.0){az = az + 360.0;} // convention is [0,360] // compute the dip dp = (M_PI_2 - 2.0*asin(rpt*sqrt2i))*degradi; vecstrd(az, dp, pt); gemv3(tm, pt, ptnew); plusMin = dot3(pt, ptnew); pn1[k] =-1; if (plusMin > 100.0*DBL_EPSILON*ampMax){pn1[k] = 1;} } // end check on location } // loop on x } // loop on y return 0; } /*! * @brief Converts a Tape and Tape 2015 tensor to tension, null, and * plunge eigenvectors in USE coordinates for plotting with * cliffsnodes * @param[in] beta colatitude (radians) * @param[in] gamma longitude (radians) * @param[in] kappa strike angle (radians) * @param[in] sigma slip angle (radians) * @param[in] theta dip angle (radians) * * @param[out] pAxis (azimuth, plunge, eigenvalue) of pressure axis [3] * @param[out] nAxis (azimuth, plunge, eigenvalue) of null axis [3] * @param[out] tAxis (azimuth, plunge, eigenvalue) of tension axis [3] * * @result 0 indicate success * * @author Ben Baker * * @copyright ISTI distributed under Apache 2 * */ int postprocess_tt2tnp(const double beta, const double gamma, const double kappa, const double sigma, const double theta, double *__restrict__ pAxis, double *__restrict__ nAxis, double *__restrict__ tAxis) { const double R[9] = { 0.7071067811865476, 0.0, -0.7071067811865476, -0.4082482904638631, 0.8164965809277261, -0.4082482904638631, 0.5773502691896258, 0.5773502691896258, 0.5773502691896258}; const double Yrot[9] = { 0.7071067811865475, 0.0, 0.7071067811865475, 0.0, 1.0, 0.0, -0.7071067811865475, 0.0, 0.7071067811865475}; // Convert NWU to USE const double Rot[9] = {0, -1, 0, 0, 0, -1, 1, 0, 0}; //const double RotInv[9] = {0, 0, 1, -1, 0, 0, 0, -1, 0}; double Zsigma[9], Xtheta[9], Zkappa[9], ZX[9], V[9], U[9], Uuse[9], Usort[9], Uw[9], lambda[3], v3[3], lamSort[3], cosb, cosg, sinb, sing, nKappaDeg, sigmaDeg, thetaDeg; const double toDeg = 180.0/M_PI; // Compute the eigenvalues from Eqn 7 sinb = sin(beta); sing = sin(gamma); cosb = cos(beta); cosg = cos(gamma); v3[0] = sinb*cosg; v3[1] = sinb*sing; v3[2] = cosb; // Compute R*lam lambda[0] = R[0]*v3[0] + R[3]*v3[1] + R[6]*v3[2]; lambda[1] = R[1]*v3[0] + R[4]*v3[1] + R[7]*v3[2]; lambda[2] = R[2]*v3[0] + R[5]*v3[1] + R[8]*v3[2]; // Eqn 9-10 sigmaDeg = sigma*toDeg; thetaDeg = theta*toDeg; nKappaDeg =-kappa*toDeg; compearth_eulerUtil_rotmat(1, &sigmaDeg, 3, Zsigma); compearth_eulerUtil_rotmat(1, &thetaDeg, 1, Xtheta); compearth_eulerUtil_rotmat(1, &nKappaDeg, 3, Zkappa); //compearth_eulerUtil_rotmatGen(1,-45.0, 2, Yrot); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3, 1.0, Zkappa, 3, Xtheta, 3, 0.0, ZX, 3); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3, 1.0, ZX, 3, Zsigma, 3, 0.0, V, 3); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3, 1.0, V, 3, Yrot, 3, 0.0, U, 3); // M could be computed by computing M = U*Lambda*inv(U) hence // U corresponds to the eigenvectors and lambda the scaling. // However, the current basis is NWU which must be converted to USE. // If performing a proper rotation of M to M_{use} we would compute: // R M inv(R) = R U Lambda inv(U) inv(R) // thus what we must be do is transform the eigenvectors into the // apropriate frame. Intuitively it is the rotation of each // eigenvector (column) of the U matrix which is indeed the matrix // matrix multiplication of R*U. cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3, 1.0, Rot, 3, U, 3, 0.0, Uuse, 3); // If I want to finish this I could compute: // R U Lambda inv(U) inv(R) = R U Lambda U^T R^T /* double lamMat[9], Temp[9], M[9], UtRt[9]; memset(lamMat, 0, 9*sizeof(double)); lamMat[0] = lambda[0]; lamMat[4] = lambda[1]; lamMat[8] = lambda[2]; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3, 1.0, Uuse, 3, lamMat, 3, 0.0, Temp, 3); cblas_dgemm(CblasColMajor, CblasTrans, CblasTrans, 3, 3, 3, 1.0, U, 3, Rot, 3, 0.0, UtRt, 3); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3, 1.0, Temp, 3, UtRt, 3, 0.0, M, 3); for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { printf("%f ", M[3*j+i]); } printf("\n"); } */ sortUL(lambda, Uuse, lamSort, Usort); //printf("%f %f %f\n", lamSort[0], lamSort[1], lamSort[2]); // Compute pressure, null, and tension axes eigenvector2PrincipalAxis(lamSort[0], &Usort[0], pAxis); eigenvector2PrincipalAxis(lamSort[1], &Usort[3], nAxis); eigenvector2PrincipalAxis(lamSort[2], &Usort[6], tAxis); // Explosion - simplification (all positive eigenvalues) if (lamSort[0] > 0.0) { pAxis[2] = 1.0; nAxis[2] = 1.0; tAxis[2] = 1.0; } // Implosion - simplification (all negative eigenvalues) if (lamSort[2] < 0.0) { pAxis[0] =-1.0; nAxis[1] =-1.0; tAxis[2] =-1.0; } //printf("%f %f %f\n", pAxis[0], pAxis[1], pAxis[2]); //printf("%f %f %f\n", nAxis[0], nAxis[1], nAxis[2]); //printf("%f %f %f\n", tAxis[0], tAxis[1], tAxis[2]); return 0; } /*! * @brief Convert pressure, null, and tension principal axes to azimuth, * plunge, and length. */ static void eigenvector2PrincipalAxis(const double eig, const double *__restrict__ ev, double *__restrict__ paxis) { const char *fcnm = "cmopad_Eigenvector2PrincipalAxis\0"; double v[3], az, plunge; double twopi = 2.0*M_PI; double pi180i = 180.0/M_PI; int ierr; //------------------------------------------------------------------------// // // Compute azimuth and plunge angles where ev is USE coordinates plunge = asin(-ev[0]); //arcsin(-z/r) az = atan2(ev[2],-ev[1]); //atan(x/y) if (plunge <= 0.0) { plunge =-plunge; az = az + M_PI; } if (az < 0.0){az = az + twopi;} //Shift to [0,360] if (az > twopi){az = az - twopi;} //Shift to [0,360] // Convert to degrees plunge = plunge*pi180i; az = az*pi180i; // Copy back result paxis[0] = az; //First value is azimuth (degrees) paxis[1] = plunge; //Second value is plunge (degrees) paxis[2] = eig; //Final value is eigenvalue (distance) return; } //===========================================================================// static void sortUL(const double *__restrict__ lam, const double *__restrict__ U, double *__restrict__ lamSort, double *__restrict__ Usort) { int perm[3], j; argsort3(lam, perm); lamSort[0] = lam[perm[0]]; lamSort[1] = lam[perm[1]]; lamSort[2] = lam[perm[2]]; for (j=0; j<3; j++) { Usort[3*j+0] = U[3*perm[j]+0]; Usort[3*j+1] = U[3*perm[j]+1]; Usort[3*j+2] = U[3*perm[j]+2]; } return; } //============================================================================// /*! * @brief Permutation to sort length 3 array into ascending order */ static void argsort3(const double *__restrict__ x, int *__restrict__ iperm) { const char *fcnm = "__cmopad_argsort3\0"; int i, temp; const int a = 0; const int b = 1; const int c = 2; // Copy iperm[a] = a; iperm[b] = b; iperm[c] = c; if (x[iperm[a]] > x[iperm[c]]) { temp = iperm[c]; iperm[c] = iperm[a]; iperm[a] = temp; } if (x[iperm[a]] > x[iperm[b]]) { temp = iperm[b]; iperm[b] = iperm[a]; iperm[a] = temp; } //Now the smallest element is the first one. Just check the 2-nd and 3-rd if (x[iperm[b]] > x[iperm[c]]) { temp = iperm[c]; iperm[c] = iperm[b]; iperm[b] = temp; } return; } //============================================================================// /*! * @brief Find components of downward pointing unit vector pole from the * strike and dip angles. This is based on Cliff Frolich's vecstrd. * * @param[in] str strike angle of pole (degrees) * @param[in] dip dip angle of pole (degrees) * * @param[out] r corresponding unit vector pole (3) * * @author Ben Baker * * @copyright BSD * */ static void vecstrd(const double str, const double dip, double r[3]) { double cosdip, cosstr, diprad, sindip, sinstr, strrad; const double degrad = M_PI/180.0; // convert to radians strrad = str*degrad; diprad = dip*degrad; // compute cosines and sines sinstr = sin(strrad); cosstr = cos(strrad); cosdip = cos(diprad); sindip = sin(diprad); // compute (x,y,z) from strike and dip for unit radius r[0] = sinstr*cosdip; r[1] = cosstr*cosdip; r[2] =-sindip; return; } /*! * @brief Utility function for computing dot product of length 3 vector */ static double dot3(const double *__restrict__ x, const double *__restrict__ y) { double dot; dot = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return dot; } /*! * @brief Utility function for computing y = Ax for 3 x 3 matrix. */ static void gemv3(const double *__restrict__ A, const double *__restrict__ x, double *__restrict__ y) { y[0] = A[0]*x[0] + A[3]*x[1] + A[6]*x[2]; y[1] = A[1]*x[0] + A[4]*x[1] + A[7]*x[2]; y[2] = A[2]*x[0] + A[5]*x[1] + A[8]*x[2]; return; } /*! * @brief Cross product of 2 length 3 vectors u and v. Returns normal vector n. * * @param[in] u first vector in cross product u x v [3] * @param[in] v second vector in cross product u x v [3] * * @param[out] n normal vector n = u x v [3] * * @author Ben Baker * * @copyright BSD * */ static void crossp(const double *__restrict__ u, const double *__restrict__ v, double *__restrict__ n) { n[0] = u[1]*v[2] - u[2]*v[1]; n[1] = u[2]*v[0] - u[0]*v[2]; n[2] = u[0]*v[1] - u[1]*v[0]; return; } /*! * @brief Finds the strike and dip of downward pointing unit vector. This * is based on Cliff Frolich's strdvec. * * @param[in,out] r on input contains the downward pointing unit * vector. * if r[2] is > 0 then the unit vector is pointing * updward. in this case then on output r3 will * be negated. * * @param[out] str strike angle (degrees) \f$ s.t. \phi \in [0,360] \f$. * @param[out] dip dip angle (degrees) * * @author Ben Baker * * @copyright BSD * */ static void strdvec(double r[3], double *str, double *dip) { double rs; const double degradi = 180.0/M_PI; if (r[2] > 0.0) { r[0] =-r[0]; r[1] =-r[1]; r[2] =-r[2]; } *str = atan2(r[0], r[1])*degradi; if (*str < 0.){*str = *str + 360.;} rs = sqrt(r[0]*r[0] + r[1]*r[1]); *dip=atan2(-r[2], rs)*degradi; return; }
{ "alphanum_fraction": 0.5316239316, "avg_line_length": 34.4117647059, "ext": "c", "hexsha": "04a27309bdf28e0da68278f73b4df4974f34c73c", "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": "postprocess/tt2beachball.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": "postprocess/tt2beachball.c", "max_line_length": 86, "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": "postprocess/tt2beachball.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5400, "size": 16380 }
/* integration/qk.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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <float.h> #include <math.h> #include <gsl/gsl_integration.h> #include "err.c" void gsl_integration_qk (const int n, const double xgk[], const double wg[], const double wgk[], double fv1[], double fv2[], const gsl_function * f, double a, double b, double *result, double *abserr, double *resabs, double *resasc) { const double center = 0.5 * (a + b); const double half_length = 0.5 * (b - a); const double abs_half_length = fabs (half_length); const double f_center = GSL_FN_EVAL (f, center); double result_gauss = 0; double result_kronrod = f_center * wgk[n - 1]; double result_abs = fabs (result_kronrod); double result_asc = 0; double mean = 0, err = 0; int j; if (n % 2 == 0) { result_gauss = f_center * wg[n / 2 - 1]; } for (j = 0; j < (n - 1) / 2; j++) { const int jtw = j * 2 + 1; /* j=1,2,3 jtw=2,4,6 */ const double abscissa = half_length * xgk[jtw]; const double fval1 = GSL_FN_EVAL (f, center - abscissa); const double fval2 = GSL_FN_EVAL (f, center + abscissa); const double fsum = fval1 + fval2; fv1[jtw] = fval1; fv2[jtw] = fval2; result_gauss += wg[j] * fsum; result_kronrod += wgk[jtw] * fsum; result_abs += wgk[jtw] * (fabs (fval1) + fabs (fval2)); } for (j = 0; j < n / 2; j++) { int jtwm1 = j * 2; const double abscissa = half_length * xgk[jtwm1]; const double fval1 = GSL_FN_EVAL (f, center - abscissa); const double fval2 = GSL_FN_EVAL (f, center + abscissa); fv1[jtwm1] = fval1; fv2[jtwm1] = fval2; result_kronrod += wgk[jtwm1] * (fval1 + fval2); result_abs += wgk[jtwm1] * (fabs (fval1) + fabs (fval2)); }; mean = result_kronrod * 0.5; result_asc = wgk[n - 1] * fabs (f_center - mean); for (j = 0; j < n - 1; j++) { result_asc += wgk[j] * (fabs (fv1[j] - mean) + fabs (fv2[j] - mean)); } /* scale by the width of the integration region */ err = (result_kronrod - result_gauss) * half_length; result_kronrod *= half_length; result_abs *= abs_half_length; result_asc *= abs_half_length; *result = result_kronrod; *resabs = result_abs; *resasc = result_asc; *abserr = rescale_error (err, result_abs, result_asc); }
{ "alphanum_fraction": 0.6179066835, "avg_line_length": 30.7961165049, "ext": "c", "hexsha": "4b62a17365495ca9a189a3863dd0ad1fefc79d74", "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/integration/qk.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/integration/qk.c", "max_line_length": 78, "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/integration/qk.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": 991, "size": 3172 }
/* Implementation of the interface in orbital_state_vector.h. */ #include <assert.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_odeiv.h> #include "basic_types.h" #include "earth_constants.h" #include "orbital_state_vector.h" OrbitalStateVector * orbital_state_vector_new (double x, double y, double z, double vx, double vy, double vz) { OrbitalStateVector *self = malloc (sizeof (OrbitalStateVector)); self->position = vector_new (x, y, z); self->velocity = vector_new (vx, vy, vz); return self; } OrbitalStateVector * orbital_state_vector_copy (OrbitalStateVector *a) { OrbitalStateVector *new = malloc (sizeof (OrbitalStateVector)); new->position = vector_copy (a->position); new->velocity = vector_copy (a->velocity); return new; } void orbital_state_vector_get_keplerian_elements (OrbitalStateVector *self, double *a, double *e, double *i, double *capital_omega, double *lower_case_omega, double *nu, double *E, double *M) { /* Shorthand. */ static const double gm = EARTH_GRAVITATIONAL_CONSTANT; /* Fundamental vectors as described in "Satellite Geodesy". */ Vector *h = vector_cross (self->position, self->velocity); Vector *X = vector_new (1.0, 0.0, 0.0); Vector *Z = vector_new (0.0, 0.0, 1.0); Vector *n = vector_cross (Z, h); double r_dot_v = vector_dot (self->position, self->velocity); double r_mag = vector_magnitude (self->position); double v_mag = vector_magnitude (self->velocity); Vector *tmp1 = vector_copy (self->position); Vector *tmp2 = vector_copy (self->velocity); /* Fundamental vector 'e' ('_fv' is appended to dodge name clash). */ Vector *e_fv; double h_mag; double n_mag; vector_multiply (tmp1, pow (v_mag, 2) - gm / r_mag); vector_multiply (tmp2, r_dot_v); vector_subtract (tmp1, tmp2); vector_multiply (tmp1, (1.0 / gm)); e_fv = vector_copy (tmp1); /* Compute keplerian elements. */ *e = vector_magnitude (e_fv); h_mag = vector_magnitude (h); *a = (pow (h_mag, 2) / gm) / (1 - pow (*e, 2)); *i = acos (vector_dot (h, Z) / h_mag); n_mag = vector_magnitude (n); *capital_omega = acos (vector_dot (n, X) / n_mag); *lower_case_omega = acos (vector_dot (n, e_fv) / (n_mag * (*e))); *nu = acos (vector_dot (e_fv, self->position) / ((*e) * vector_magnitude (self->position))); *E = acos ((*e + cos (*nu)) / (1.0 + (*e) * cos (*nu))); *M = *E - (*e) * sin (*E); /* Free fundamental and temporary vectors used in computation. */ free (h); free (Z); free (X); free (n); free (tmp1); free (tmp2); free (e_fv); } double orbital_state_vector_height_above_ellipsoid (OrbitalStateVector *self) { double r = vector_magnitude (self->position); /* Compute height of satellite above the WGS84 ellipsoid. */ static Vector z_unit = {0.0, 0.0, 1.0}; /* Angle between position vector and equatorial plane. */ double eq_angle = M_PI / 2 - vector_angle (self->position, &z_unit); double ae = EARTH_SEMIMAJOR_AXIS; /* Earth semiminor axis. */ double be = sqrt (pow (ae, 2) * (1 - pow (EARTH_ECCENTRICITY, 2))); /* Radius of ellipsoid at point under satellite. */ double ellipsoid_radius = sqrt (pow (ae * cos (eq_angle), 2) + pow (be * sin (eq_angle), 2)); return r - ellipsoid_radius; } /* Compute derivatives f from functions y(t), t, and other miscellaneous parameters. Return GSL_SUCCESS after successful computation. This code mostly follows the example in the GNU Scientific Library documentation, which uses a y array for the function values. The y[1] value is the only one that corresponds to the y coordinate, and the y[4] vale the only one that corresponds to the y velocity. */ static int func (double t, const double y[], double f[], void *params) { /* Shorthand for some earth constants. */ static const double gm = EARTH_GRAVITATIONAL_CONSTANT; static const double ae = EARTH_SEMIMAJOR_AXIS; /* Create position and velocity vectors. We use static vectors to avoid allocation overhead. */ static Vector p_st; static Vector v_st; static Vector *p = &p_st; static Vector *v = &v_st; double r; double j2; double a_j2_x, a_j2_y, a_j2_z; double ksx, ksy, ksz; vector_set (p, y[0], y[1], y[2]); vector_set (v, y[3], y[4], y[5]); /* Current range to satellife from center of earth. */ r = vector_magnitude (p); double r3 = r*r*r; /* The so-called first zonal harmonic is used to account for the effects of earth oblatedness (see below for references). */ j2 = 1082.63e-6; /* First zonal harmonic coefficient. */ a_j2_x = (gm * p->x / r3) * j2 * (3.0 / 2) * (ae*ae / (r*r)) * (5.0 * (p->z * p->z) / (r*r) - 1.0); a_j2_y = (p->y / p->x) * a_j2_x; a_j2_z = (-gm * p->z / r3) * j2 * (3.0 / 2) * (ae*ae / (r*r)) * (3.0 - 5.0 * (p->z * p->z) / (r*r)); /* Total perturbations. */ ksx = a_j2_x; ksy = a_j2_y; ksz = a_j2_z; f[0] = v->x; f[1] = v->y; f[2] = v->z; f[3] = ksx - gm * (p->x / r3); f[4] = ksy - gm * (p->y / r3); f[5] = ksz - gm * (p->z / r3); return GSL_SUCCESS; } void orbital_state_vector_propagate (OrbitalStateVector *self, double time) { /* We need to solve the following six dimensional system of ordinary differential equations: dx/dt = vx dy/dt = vy dz/dt = vz dvx/dt = ksx - (GM / r^3) * x dvy/dt = ksy - (GM / r^3) * y dvz/dt = ksz - (GM / r^3) * z where r = sqrt (x^2 + y^2 + z^2) with initial conditions given by the current state. The values ksx, ksy, and ksz represent the perturbations due to earth oblatedness as described in section 3.2.2.3 respectively of "Satellite Geodesy", 2nd edition, by Gunter Seeber. An ordinary differential equation solver from the GNU Scientific Library (GSL) is used to solve the system. It is well described in the GSL documentation section "Ordinary Differential Equations". */ const int dimension = 6; /* Create some things the ODE solver uses. */ const gsl_odeiv_step_type *step_type = gsl_odeiv_step_rkf45; gsl_odeiv_step *ode_step = gsl_odeiv_step_alloc (step_type, dimension); /* Hold the absolute integration error for each coordinate for each step to within this value. This value was chosen using the following sophisticated methodology: Keep tightening the tolerance until the answer no longer changes with further tightenings, for an short (~2.5 minute) propagation. */ double mae = 0.000001; gsl_odeiv_control *ode_control = gsl_odeiv_control_y_new (mae, 0.0); gsl_odeiv_evolve *ode_evolve = gsl_odeiv_evolve_alloc (dimension); gsl_odeiv_system ode_system; double t0 = 0.0, t1 = time; /* Start and end times. */ /* Initial guess for step size. */ const double initial_step_size = GSL_SIGN (t1) * 1.0; double step_size = initial_step_size; double *y = malloc (dimension * sizeof (double)); double t = t0; /* Current time. */ ode_system.function = func; ode_system.jacobian = NULL; ode_system.dimension = dimension; ode_system.params = NULL; y[0] = self->position->x; y[1] = self->position->y; y[2] = self->position->z; y[3] = self->velocity->x; y[4] = self->velocity->y; y[5] = self->velocity->z; /* Here is the actual propagation. */ while ( fabs (t) < fabs (t1) ) { int status = gsl_odeiv_evolve_apply (ode_evolve, ode_control, ode_step, &ode_system, &t, t1, &step_size, y); assert (status == GSL_SUCCESS); } self->position->x = y[0]; self->position->y = y[1]; self->position->z = y[2]; self->velocity->x = y[3]; self->velocity->y = y[4]; self->velocity->z = y[5]; free (y); gsl_odeiv_evolve_free (ode_evolve); gsl_odeiv_control_free (ode_control); gsl_odeiv_step_free (ode_step); } void orbital_state_vector_propagate_interpolate (OrbitalStateVector *self, double time, OrbitalStateVector *other) { /* Not implemented. */ assert (FALSE); }
{ "alphanum_fraction": 0.6595505618, "avg_line_length": 31.9123505976, "ext": "c", "hexsha": "a7182289b4c16c0f2d82c600f74d0a64a06f630d", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/asf_meta/orbital_state_vector.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/asf_meta/orbital_state_vector.c", "max_line_length": 77, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/asf_meta/orbital_state_vector.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 2565, "size": 8010 }
#ifndef CURVATURE_H_LSXONAFA #define CURVATURE_H_LSXONAFA #include <cmath> #include <gsl/gsl> #include <type_traits> namespace sens_loc::math { /// This function calculates the gaussian curvature for a function given its /// derivatives. /// \tparam Real precision of the calculation /// \param f_u,f_v,f_uu,f_vv,f_uv partial derivatives of the depth values /// \returns gaussian curvature for these derivatives /// \sa conversion::depth_to_gaussian_curvature /// \note check https://en.wikipedia.org/wiki/Gaussian_curvature for more info template <typename Real> inline Real gaussian_curvature( Real f_u, Real f_v, Real f_uu, Real f_vv, Real f_uv) noexcept { static_assert(std::is_floating_point_v<Real>); return (f_uu * f_vv - f_uv * f_uv) / (Real(1.) + f_u * f_u + f_v * f_v); } /// This function calculates the mean curvature for a function given its /// derivatives. /// \tparam Real precicions of the calculation /// \param f_u,f_v,f_uu,f_vv,f_uv partial derivatives of the depth values /// \returns the mean curvature for these derivatives /// \sa conversion::depth_to_mean_curvature /// \note check https://en.wikipedia.org/wiki/Mean_curvature for more info template <typename Real> inline Real mean_curvature(Real f_u, Real f_v, Real f_uu, Real f_vv, Real f_uv) noexcept { static_assert(std::is_floating_point_v<Real>); using std::pow; using std::sqrt; // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) return ((Real(1.) + f_v * f_v) * f_uu - Real(2.) * f_u * f_v * f_uv + (Real(1.) + f_u * f_u) * f_vv) / // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) pow(Real(2.) * sqrt(Real(1.) + f_u * f_u + f_v * f_v), Real(3.)); } } // namespace sens_loc::math #endif /* end of include guard: CURVATURE_H_LSXONAFA */
{ "alphanum_fraction": 0.7127836193, "avg_line_length": 37.6458333333, "ext": "h", "hexsha": "b78f840fd7fbb7ab9c8210cbc7233ba9e5a82853", "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": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_path": "src/include/sens_loc/math/curvature.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "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": "JonasToth/depth-conversions", "max_issues_repo_path": "src/include/sens_loc/math/curvature.h", "max_line_length": 78, "max_stars_count": 2, "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_path": "src/include/sens_loc/math/curvature.h", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "num_tokens": 510, "size": 1807 }
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <math.h> #include <float.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include "common.h" #include "graph.h" #include "utils.h" void graph_init(graph *g, int vertices) { g->num_v = vertices; g->num_e = (int*)malloc(vertices * sizeof(int)); g->capacity = (int*)malloc(vertices * sizeof(int)); g->adj_list = (int**)malloc(vertices * sizeof(int*)); g->w_list = (double**)malloc(vertices * sizeof(double*)); int i = 0; for (; i < vertices; ++i) { g->num_e[i] = 0; g->capacity[i] = GRAPH_INIT_CAPACITY; g->adj_list[i] = (int*)malloc(GRAPH_INIT_CAPACITY * sizeof(int)); g->w_list[i] = (double*)malloc(GRAPH_INIT_CAPACITY * sizeof(double)); } } ORIGIN_INLINE int graph_edges(const graph *g) { const int num_v = g->num_v; int sum = 0; int v = 0; for (; v < num_v; ++v) { sum += g->num_e[v]; } return sum; } ORIGIN_INLINE int graph_proper_edges(const graph *g) { const int num_v = g->num_v; int sum = 0; int v = 0; for (; v < num_v; ++v) { int e = 0; for (; e < g->num_e[v]; ++e) { if (g->adj_list[v][e] != v) { ++sum; } } } return sum; } ORIGIN_INLINE int graph_loops(const graph *g) { const int num_v = g->num_v; int sum = 0; int v = 0; for (; v < num_v; ++v) { int e = 0; for (; e < g->num_e[v]; ++e) { if (g->adj_list[v][e] == v) { ++sum; } } } return sum; } ORIGIN_INLINE int graph_outdegree(const graph *g, int u) { return g->num_e[u]; } ORIGIN_INLINE int graph_indegree(const graph *g, int u) { const int num_v = g->num_v; int sum = 0; int v = 0; for (; v < num_v; ++v) { int e = 0; for (; e < g->num_e[v]; ++e) { if (g->adj_list[v][e] == u) { ++sum; } } } return sum; } ORIGIN_INLINE int graph_is_balanced(const graph *g) { const int num_v = g->num_v; int u = 0; for (; u < num_v; ++u) { if (graph_indegree(g, u) != graph_outdegree(g, u)) { return FALSE; } } return TRUE; } ORIGIN_INLINE void graph_add_edge(graph *g, int u, int v, double weight) { if (g->num_e[u] == g->capacity[u]) { graph_grow_lists(g, u); } g->adj_list[u][g->num_e[u]] = v; g->w_list[u][g->num_e[u]] = weight; g->num_e[u]++; } void graph_add_sym_edges(graph *g, int u, int v, double weight) { graph_add_edge(g, u, v, weight); graph_add_edge(g, v, u, weight); } int graph_rmv_edge(graph *g, int u, int v) { const int num_e = g->num_e[u]; int e = 0; for (; e < num_e; ++e) { if (g->adj_list[u][e] == v) { g->num_e[u]--; int f = e; for (; f < num_e - 1; ++f) { g->adj_list[u][f] = g->adj_list[u][f+1]; g->w_list[u][f] = g->w_list[u][f+1]; } return TRUE; } } return FALSE; } int graph_rmv_sym_edges(graph *g, int u, int v) { return (graph_rmv_edge(g, u, v) && graph_rmv_edge(g, v, u)); } int graph_has_edge(graph *g, int u, int v) { const int num_e = g->num_e[u]; int e = 0; for (; e < num_e; ++e) { if (g->adj_list[u][e] == v) { return TRUE; } } return FALSE; } int graph_strongly_connected(const graph *g) { const int num_v = g->num_v; int *group = (int*)malloc(num_v * sizeof(int)); int u = 0; for (; u < num_v; ++u) { int v = 0; for (; v < num_v; ++v) { group[v] = FALSE; } group[u] = TRUE; graph_test_cc(g, group, u); // Call recursive function for (v = 0; v < num_v; ++v) { if (group[v] == FALSE) { free(group); return FALSE; } } } free(group); return TRUE; } void graph_svg(const graph *g, double *x, double *y, double size, double offset, FILE *out) { fprintf(out, "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">"); const int num_v = g->num_v; for (int i = 0; i < num_v; ++i) { const int num_e = g->num_e[i]; for (int j = 0; j < num_e; ++j) { const int e = g->adj_list[i][j]; fprintf(out, " <line x1=\"%f\" y1=\"%f\" x2=\"%f\" y2=\"%f\" style=\"stroke:rgb(0,0,0);stroke-width:2\"/>\n", offset + x[i] * size, offset + y[i] * size, offset + x[e] * size, offset + y[e] * size); } } for (int i = 0; i < num_v; ++i) { fprintf(out, " <circle id=\"%d\" cx=\"%f\" cy=\"%f\" r=\"8\" fill=\"rgb(0,0,0)\"/>\n", i, offset + x[i] * size, offset + y[i] * size); } fprintf(out, "</svg>"); } void graph_svg_abun(const graph *g, double *x, double *y, double size, double offset, double *abun, int color, FILE *out) { fprintf(out, "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">"); const int num_v = g->num_v; for (int i = 0; i < num_v; ++i) { const int num_e = g->num_e[i]; for (int j = 0; j < num_e; ++j) { const int e = g->adj_list[i][j]; fprintf(out, " <line x1=\"%f\" y1=\"%f\" x2=\"%f\" y2=\"%f\" style=\"stroke:rgb(0,0,0);stroke-width:2\"/>\n", offset + x[i] * size, offset + y[i] * size, offset + x[e] * size, offset + y[e] * size); } } int clr[3] = {0, 0, 0}; for (int i = 0; i < num_v; ++i) { clr[color] = (int)(abun[i] * 255); fprintf(out, " <circle id=\"%d\" cx=\"%f\" cy=\"%f\" r=\"8\" stroke=\"black\" stroke-width=\"1\" fill=\"rgb(%d,%d,%d)\"/>\n", i, offset + x[i] * size, offset + y[i] * size, clr[0], clr[1], clr[2]); } fprintf(out, "</svg>"); } void graph_graphml(const graph *g, FILE *out, unsigned int id) { const int num_v = g->num_v; fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); fprintf(out, "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\""); fprintf(out, " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""); fprintf(out, " xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">\n"); fprintf(out, " <graph id=\"%u\" edgedefault=\"directed\">\n", id); for (int i = 0; i < num_v; ++i) { fprintf(out, " <node id=\"v%d\"/>\n", i); } for (int i = 0; i < num_v; ++i) { for (int e = 0; e < g->num_e[i]; ++e) { fprintf(out, " <edge source=\"v%d\" target=\"v%d\"/>\n", i, g->adj_list[i][e]); } } fprintf(out, " </graph>\n"); fprintf(out, "</graphml>\n"); } void graph_print(const graph *g, FILE *out) { for (int i = 0; i < g->num_v; ++i) { fprintf(out, "%5d -> ", i); for (int e = 0; e < g->num_e[i]; ++e) { fprintf(out, "%d ", g->adj_list[i][e]); } fprintf(out, "\n"); } } void graph_free(graph *g) { const int num_v = g->num_v; for (int i = 0; i < num_v; ++i) { free(g->adj_list[i]); free(g->w_list[i]); } free(g->adj_list); g->adj_list = NULL; free(g->w_list); g->w_list = NULL; free(g->num_e); g->num_e = NULL; free(g->capacity); g->capacity = NULL; } void graph_get_rgg(graph *g, int vertices, double r, double *x, double *y, gsl_rng *rng) { graph_init(g, vertices); for (int i = 0; i < vertices; ++i) { x[i] = gsl_rng_uniform(rng); y[i] = gsl_rng_uniform(rng); } double d; for (int i = 0; i < vertices; ++i) { for (int j = 0; j < vertices; ++j) { const double a = x[i] - x[j]; const double b = y[i] - y[j]; d = hypot(a, b); if (d < r) { graph_add_edge(g, i, j, r - d); } } } } void graph_get_crgg(graph *g, int vertices, double r, double *x, double *y, gsl_rng *rng) { graph_init(g, vertices); graph_get_rgg(g, vertices, r, x, y, rng); while (graph_strongly_connected(g) == FALSE) { graph_free(g); graph_get_rgg(g, vertices, r, x, y, rng); } } void graph_get_rec_rgg(graph *g, int vertices, double width, double r, double *x, double *y, gsl_rng *rng) { graph_init(g, vertices); const double length = 1.0 / width; // A = l * w so l = 1 / w for (int i = 0; i < vertices; ++i) { x[i] = gsl_rng_uniform(rng) * length; y[i] = gsl_rng_uniform(rng) * width; } double d; for (int i = 0; i < vertices; ++i) { for (int j = 0; j < vertices; ++j) { const double a = x[i] - x[j]; const double b = y[i] - y[j]; d = hypot(a, b); if (d < r) { graph_add_edge(g, i, j, r - d); } } } } void graph_get_rec_crgg(graph *g, int vertices, double width, double r, double *x, double *y, gsl_rng *rng) { graph_init(g, vertices); graph_get_rec_rgg(g, vertices, width, r, x, y, rng); while (graph_strongly_connected(g) == FALSE) { graph_free(g); graph_get_rec_rgg(g, vertices, width, r, x, y, rng); } } void graph_get_complete(graph *g, int vertices) { graph_init(g, vertices); for (int i = 0; i < vertices; ++i) { for (int j = 0; j < vertices; ++j) { graph_add_edge(g, i, j, 1.0); } } } void graph_get_circle(graph *g, int vertices) { graph_init(g, vertices); graph_add_edge(g, vertices - 1, vertices - 1, 1.0); graph_add_sym_edges(g, 0, vertices - 1, 1.0); for (int u = 0; u < vertices - 1; ++u) { graph_add_edge(g, u, u, 1.0); graph_add_sym_edges(g, u, u + 1, 1.0); } } void graph_get_star(graph *g, int vertices) { graph_init(g, vertices); for (int u = 0; u < vertices; ++u) { graph_add_edge(g, u, u, 1.0); graph_add_sym_edges(g, u, 0, 1.0); } } /////////////////////////////////////////////////////////////// // 'Private' functions void graph_test_cc(const graph *g, int *group, int u) { const int num_e = g->num_e[u]; int e = 0; for (; e < num_e; ++e) { const int head = g->adj_list[u][e]; if (head != u && group[head] == FALSE) { group[head] = TRUE; graph_test_cc(g, group, head); } } } // Grow the edge list of some vertex v. void graph_grow_lists(graph *g, int u) { g->capacity[u] <<= 1; int *tmp_adj = (int*)malloc(g->capacity[u] * sizeof(int)); double *tmp_w = (double*)malloc(g->capacity[u] * sizeof(double)); const int num_e = g->num_e[u]; int e = 0; for (; e < num_e; ++e) { tmp_adj[e] = g->adj_list[u][e]; tmp_w[e] = g->w_list[u][e]; } int *swap_adj = g->adj_list[u]; double *swap_w = g->w_list[u]; g->adj_list[u] = tmp_adj; g->w_list[u] = tmp_w; free(swap_adj); free(swap_w); }
{ "alphanum_fraction": 0.4871499468, "avg_line_length": 24.6375545852, "ext": "c", "hexsha": "7e3f73e58093c549eb693582b05687003b62e3bc", "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": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "PhDP/Origin", "max_forks_repo_path": "src/graph.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712", "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": "PhDP/Origin", "max_issues_repo_path": "src/graph.c", "max_line_length": 211, "max_stars_count": null, "max_stars_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "PhDP/Origin", "max_stars_repo_path": "src/graph.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3617, "size": 11284 }
/* File: set_cosmo_dist.c */ /* This file is a part of the Corrfunc package Copyright (C) 2015-- Manodeep Sinha (manodeep@gmail.com) License: MIT LICENSE. See LICENSE file under the top-level directory at https://github.com/manodeep/Corrfunc/ */ /* function set_cosmo_dist (modelled after cosmodist.c) --- Computes the comoving distance as a function of redshift for a given cosmological model. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_integration.h> #include "set_cosmo_dist.h" #include "cosmology_params.h" #define SQR(x) ((x)*(x)) #define CUBE(x) ((x)*(x)*(x)) #define epsilon 1e-10 int set_cosmo_dist(const double zmax,const int max_size,double *zc,double *dc,const int lasdamas_cosmology) { /* First, initialize cosmology*/ int status = init_cosmology(lasdamas_cosmology); if(status != EXIT_SUCCESS) { return -1; } int i = 0; double Omegak; double smallh = 1.0;//Andreas pointed out that I don't need the real value of LITTLE_H Omegak = 1.0 - OMEGA_M - OMEGA_L; const double Dh = SPEED_OF_LIGHT*0.01/smallh ;// c/(100) -> in units of little h^-1 Mpc const double Deltaz = 1.0/max_size; const double dz = 1e-2*Deltaz; double Eint = 0.0; double E2 = 1.0 ; double z2 = Deltaz ; for(double z=2.0*dz;z<zmax;z+=2.0*dz) { double E0 = E2 ; double E1 = 1.0/sqrt(OMEGA_M * CUBE(1+z-dz) + Omegak *(1+z-dz) + OMEGA_L); E2 = 1.0/sqrt(OMEGA_M * CUBE(1+z) + Omegak *(1+z) + OMEGA_L); Eint += dz*(E0 + 4.*E1 + E2)/3. ; if(z>(z2-epsilon) && z<(z2+epsilon)) { if( i >= max_size ) break ; const double Dc = Eint*Dh ; zc[i] = z ; dc[i] = Dc ; z2 += Deltaz ; i++ ; } } #ifdef DEBUG fprintf(stderr,"%s> (Omega_m, Omega_L, Omega_k, h, zmax) = (%4.2f, %4.2f, %4.2f, %4.2f,%4.2lf)\n", __FUNCTION__, OMEGA_M,OMEGA_L,Omegak,LITTLE_H,zmax) ; fprintf(stderr,"%s> tabulated redshift: %g to %g (distance: %g to %g Mpc)\n", __FUNCTION__, zc[0], zc[i-1], dc[0], dc[i-1]) ; #endif return i ; }
{ "alphanum_fraction": 0.6023255814, "avg_line_length": 29.8611111111, "ext": "c", "hexsha": "51ea3c9b8713dca934eacee7e93aa05e823f3af1", "lang": "C", "max_forks_count": 58, "max_forks_repo_forks_event_max_datetime": "2022-03-22T09:38:27.000Z", "max_forks_repo_forks_event_min_datetime": "2016-03-15T07:25:33.000Z", "max_forks_repo_head_hexsha": "3064f82df0b9ecba0898ee5d2731b44149849f23", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "laperezNYC/Corrfunc", "max_forks_repo_path": "utils/set_cosmo_dist.c", "max_issues_count": 227, "max_issues_repo_head_hexsha": "3064f82df0b9ecba0898ee5d2731b44149849f23", "max_issues_repo_issues_event_max_datetime": "2022-02-03T21:12:36.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-13T06:31:46.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "laperezNYC/Corrfunc", "max_issues_repo_path": "utils/set_cosmo_dist.c", "max_line_length": 156, "max_stars_count": 139, "max_stars_repo_head_hexsha": "3064f82df0b9ecba0898ee5d2731b44149849f23", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "laperezNYC/Corrfunc", "max_stars_repo_path": "utils/set_cosmo_dist.c", "max_stars_repo_stars_event_max_datetime": "2022-03-31T10:33:38.000Z", "max_stars_repo_stars_event_min_datetime": "2016-02-10T01:41:55.000Z", "num_tokens": 736, "size": 2150 }
#include <stdio.h> #include <stdlib.h> #include <gsl/gsl_rstat.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sort.h> int main(void) { const size_t N = 10000; double *data = malloc(N * sizeof(double)); gsl_rstat_quantile_workspace *work_25 = gsl_rstat_quantile_alloc(0.25); gsl_rstat_quantile_workspace *work_50 = gsl_rstat_quantile_alloc(0.5); gsl_rstat_quantile_workspace *work_75 = gsl_rstat_quantile_alloc(0.75); gsl_rng *r = gsl_rng_alloc(gsl_rng_default); double exact_p25, exact_p50, exact_p75; double val_p25, val_p50, val_p75; size_t i; /* add data to quantile accumulators; also store data for exact * comparisons */ for (i = 0; i < N; ++i) { data[i] = gsl_ran_rayleigh(r, 1.0); gsl_rstat_quantile_add(data[i], work_25); gsl_rstat_quantile_add(data[i], work_50); gsl_rstat_quantile_add(data[i], work_75); } /* exact values */ gsl_sort(data, 1, N); exact_p25 = gsl_stats_quantile_from_sorted_data(data, 1, N, 0.25); exact_p50 = gsl_stats_quantile_from_sorted_data(data, 1, N, 0.5); exact_p75 = gsl_stats_quantile_from_sorted_data(data, 1, N, 0.75); /* estimated values */ val_p25 = gsl_rstat_quantile_get(work_25); val_p50 = gsl_rstat_quantile_get(work_50); val_p75 = gsl_rstat_quantile_get(work_75); printf ("The dataset is %g, %g, %g, %g, %g, ...\n", data[0], data[1], data[2], data[3], data[4]); printf ("0.25 quartile: exact = %.5f, estimated = %.5f, error = %.6e\n", exact_p25, val_p25, (val_p25 - exact_p25) / exact_p25); printf ("0.50 quartile: exact = %.5f, estimated = %.5f, error = %.6e\n", exact_p50, val_p50, (val_p50 - exact_p50) / exact_p50); printf ("0.75 quartile: exact = %.5f, estimated = %.5f, error = %.6e\n", exact_p75, val_p75, (val_p75 - exact_p75) / exact_p75); gsl_rstat_quantile_free(work_25); gsl_rstat_quantile_free(work_50); gsl_rstat_quantile_free(work_75); gsl_rng_free(r); free(data); return 0; }
{ "alphanum_fraction": 0.6843137255, "avg_line_length": 33.4426229508, "ext": "c", "hexsha": "85c192ab8fab71a4ed240fd6575cee6b9836b104", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/rquantile.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/doc/examples/rquantile.c", "max_line_length": 74, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/doc/examples/rquantile.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": 682, "size": 2040 }
#pragma once #include <gsl\gsl> #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include "DrawableGameComponent.h" #include "MatrixHelper.h" #include "PointLight.h" #include "DepthMap.h" #include "Rectangle.h" #include "ProjectiveTextureMappingMaterial.h" #include "RenderStateHelper.h" namespace DirectX { class SpriteBatch; } namespace Library { class ProxyModel; class RenderableFrustum; class DepthMapMaterial; } namespace Rendering { class ProjectiveTextureMappingDemo final : public Library::DrawableGameComponent { public: ProjectiveTextureMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); ProjectiveTextureMappingDemo(const ProjectiveTextureMappingDemo&) = delete; ProjectiveTextureMappingDemo(ProjectiveTextureMappingDemo&&) = default; ProjectiveTextureMappingDemo& operator=(const ProjectiveTextureMappingDemo&) = default; ProjectiveTextureMappingDemo& operator=(ProjectiveTextureMappingDemo&&) = default; ~ProjectiveTextureMappingDemo(); ProjectiveTextureMappingDrawModes DrawMode() const; const std::string& DrawModeString() const; void SetDrawMode(ProjectiveTextureMappingDrawModes drawMode); float AmbientLightIntensity() const; void SetAmbientLightIntensity(float intensity); float PointLightIntensity() const; void SetPointLightIntensity(float intensity); float PointLightRadius() const; void SetPointLightRadius(float radius); const DirectX::XMFLOAT3& ProjectorPosition() const; const DirectX::XMVECTOR ProjectorPositionVector() const; void SetProjectorPosition(const DirectX::XMFLOAT3& position); void SetProjectorPosition(DirectX::FXMVECTOR position); const DirectX::XMFLOAT3& ProjectorDirection() const; void RotateProjector(const DirectX::XMFLOAT2& amount); virtual void Initialize() override; virtual void Update(const Library::GameTime& gameTime) override; virtual void Draw(const Library::GameTime& gameTime) override; private: inline static const std::uint32_t DepthMapWidth{ 1024 }; inline static const std::uint32_t DepthMapHeight{ 1024 }; static inline const RECT DepthMapDestinationRectangle{ 0, 512, 256, 768 }; void DrawWithDepthMap(); void DrawWithoutDepthMap(); void UpdateTransforms(ProjectiveTextureMappingMaterial::VertexCBufferPerObject& transforms, DirectX::FXMMATRIX worldViewProjectionMatrix, DirectX::CXMMATRIX worldMatrix, DirectX::CXMMATRIX projectiveTextureMatrix); void InitializeProjectedTextureScalingMatrix(uint32_t textureWidth, uint32_t textureHeight); ProjectiveTextureMappingMaterial::VertexCBufferPerObject mPlaneTransforms; ProjectiveTextureMappingMaterial::VertexCBufferPerObject mTeapotTransforms; DirectX::XMFLOAT4X4 mPlaneWorldMatrix{ Library::MatrixHelper::Identity }; DirectX::XMFLOAT4X4 mTeapotWorldMatrix{ Library::MatrixHelper::Identity }; DirectX::XMFLOAT4X4 mProjectedTextureScalingMatrix{ Library::MatrixHelper::Zero }; Library::PointLight mPointLight; Library::DepthMap mDepthMap; Library::RenderStateHelper mRenderStateHelper; std::shared_ptr<ProjectiveTextureMappingMaterial> mMaterial; std::shared_ptr<Library::DepthMapMaterial> mDepthMapMaterial; winrt::com_ptr<ID3D11Buffer> mPlaneVertexBuffer; winrt::com_ptr<ID3D11Buffer> mTeapotVertexBuffer; winrt::com_ptr<ID3D11Buffer> mTeapotPositionOnlyVertexBuffer; winrt::com_ptr<ID3D11Buffer> mTeapotIndexBuffer; std::uint32_t mPlaneVertexCount{ 0 }; std::uint32_t mTeapotIndexCount{ 0 }; std::unique_ptr<Library::ProxyModel> mProxyModel; std::unique_ptr<Library::Camera> mProjector; std::unique_ptr<Library::RenderableFrustum> mRenderableProjectorFrustum; std::unique_ptr<DirectX::SpriteBatch> mSpriteBatch; bool mUpdateMaterial{ true }; }; }
{ "alphanum_fraction": 0.8091541756, "avg_line_length": 39.3263157895, "ext": "h", "hexsha": "06e5dd84feea8d140350aa5ff68fa7aa17d8f081", "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/8.1_Projective_Texture_Mapping/ProjectiveTextureMappingDemo.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/8.1_Projective_Texture_Mapping/ProjectiveTextureMappingDemo.h", "max_line_length": 216, "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/8.1_Projective_Texture_Mapping/ProjectiveTextureMappingDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 932, "size": 3736 }
/* movstat/test_Sn.c * * Copyright (C) 2018 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_statistics.h> #include <gsl/gsl_sort_vector.h> #include <gsl/gsl_test.h> /* calculate S_n statistic for input vector using slow/naive algorithm */ static int slow_movSn(const gsl_movstat_end_t etype, const gsl_vector * x, gsl_vector * y, const int H, const int J) { const size_t n = x->size; const int K = H + J + 1; double *window = malloc(K * sizeof(double)); double *work = malloc(K * sizeof(double)); size_t i; for (i = 0; i < n; ++i) { size_t wsize = gsl_movstat_fill(etype, x, i, H, J, window); double Sn; gsl_sort(window, 1, wsize); Sn = gsl_stats_Sn_from_sorted_data(window, 1, wsize, work); gsl_vector_set(y, i, Sn); } free(window); free(work); return GSL_SUCCESS; } static double func_Sn(const size_t n, double x[], void * params) { double *work = malloc(n * sizeof(double)); double Sn; (void) params; gsl_sort(x, 1, n); Sn = gsl_stats_Sn_from_sorted_data(x, 1, n, work); free(work); return Sn; } static void test_Sn_proc(const double tol, const size_t n, const size_t H, const size_t J, const gsl_movstat_end_t etype, gsl_rng *rng_p) { gsl_movstat_workspace *w; gsl_vector *x = gsl_vector_alloc(n); gsl_vector *y = gsl_vector_alloc(n); gsl_vector *z = gsl_vector_alloc(n); gsl_movstat_function F; char buf[2048]; F.function = func_Sn; F.params = NULL; if (H == J) w = gsl_movstat_alloc(2*H + 1); else w = gsl_movstat_alloc2(H, J); /* test moving median with random input */ random_vector(x, rng_p); /* y = S_n(x) with slow brute force algorithm */ slow_movSn(etype, x, y, H, J); /* z = S_n(x) */ gsl_movstat_Sn(etype, x, z, w); /* test y = z */ sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u Sn random", n, H, J, etype); compare_vectors(tol, z, y, buf); /* z = S_n(x) in-place */ gsl_vector_memcpy(z, x); gsl_movstat_Sn(etype, z, z, w); sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u Sn random in-place", n, H, J, etype); compare_vectors(tol, z, y, buf); /* z = S_n(x) with user-defined function */ gsl_movstat_apply(etype, &F, x, z, w); sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u Sn user", n, H, J, etype); compare_vectors(tol, z, y, buf); gsl_vector_free(x); gsl_vector_free(y); gsl_vector_free(z); gsl_movstat_free(w); } static void test_Sn(gsl_rng * rng_p) { test_Sn_proc(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_PADZERO, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 1000, 5, 5, GSL_MOVSTAT_END_PADZERO, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 1000, 5, 2, GSL_MOVSTAT_END_PADZERO, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 1000, 2, 5, GSL_MOVSTAT_END_PADZERO, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 2000, 50, 0, GSL_MOVSTAT_END_PADZERO, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 2000, 0, 50, GSL_MOVSTAT_END_PADZERO, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_PADZERO, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 20, 1, 50, GSL_MOVSTAT_END_PADZERO, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 20, 50, 1, GSL_MOVSTAT_END_PADZERO, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_PADVALUE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 1000, 5, 5, GSL_MOVSTAT_END_PADVALUE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 1000, 5, 2, GSL_MOVSTAT_END_PADVALUE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 1000, 2, 5, GSL_MOVSTAT_END_PADVALUE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 2000, 50, 0, GSL_MOVSTAT_END_PADVALUE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 2000, 0, 50, GSL_MOVSTAT_END_PADVALUE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_PADVALUE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 20, 1, 50, GSL_MOVSTAT_END_PADVALUE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 20, 50, 1, GSL_MOVSTAT_END_PADVALUE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 1000, 0, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 1000, 5, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 1000, 5, 2, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 1000, 2, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 2000, 50, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 2000, 0, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 20, 50, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 20, 1, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p); test_Sn_proc(GSL_DBL_EPSILON, 20, 50, 1, GSL_MOVSTAT_END_TRUNCATE, rng_p); }
{ "alphanum_fraction": 0.7154135338, "avg_line_length": 34.7712418301, "ext": "c", "hexsha": "51b1a76126523731d8abdd30810171f74bd2ecba", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "karanbirsandhu/nu-sense", "max_forks_repo_path": "test/lib/gsl-2.6/movstat/test_Sn.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/movstat/test_Sn.c", "max_line_length": 82, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/movstat/test_Sn.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": 1826, "size": 5320 }
/* Author: G. Jungman */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_errno.h> #include "gsl_qrng.h" gsl_qrng * gsl_qrng_alloc (const gsl_qrng_type * T, unsigned int dimension) { gsl_qrng * r = (gsl_qrng *) malloc (sizeof (gsl_qrng)); if (r == 0) { GSL_ERROR_VAL ("allocation failed for qrng struct", GSL_ENOMEM, 0); }; r->dimension = dimension; r->state_size = T->state_size(dimension); r->state = malloc (r->state_size); if (r->state == 0) { free (r); GSL_ERROR_VAL ("allocation failed for qrng state", GSL_ENOMEM, 0); }; r->type = T; T->init_state(r->state, r->dimension); return r; } int gsl_qrng_memcpy (gsl_qrng * dest, const gsl_qrng * src) { if (dest->type != src->type) { GSL_ERROR ("generators must be of the same type", GSL_EINVAL); } dest->dimension = src->dimension; dest->state_size = src->state_size; memcpy (dest->state, src->state, src->state_size); return GSL_SUCCESS; } gsl_qrng * gsl_qrng_clone (const gsl_qrng * q) { gsl_qrng * r = (gsl_qrng *) malloc (sizeof (gsl_qrng)); if (r == 0) { GSL_ERROR_VAL ("failed to allocate space for rng struct", GSL_ENOMEM, 0); }; r->dimension = q->dimension; r->state_size = q->state_size; r->state = malloc (r->state_size); if (r->state == 0) { free (r); GSL_ERROR_VAL ("failed to allocate space for rng state", GSL_ENOMEM, 0); }; r->type = q->type; memcpy (r->state, q->state, q->state_size); return r; } #ifndef HIDE_INLINE_STATIC int gsl_qrng_get (const gsl_qrng * r, double x[]) { return (r->type->get) (r->state, r->dimension, x); } #endif const char * gsl_qrng_name (const gsl_qrng * r) { return r->type->name; } size_t gsl_qrng_size (const gsl_qrng * r) { return r->state_size; } void * gsl_qrng_state (const gsl_qrng * r) { return r->state; } void gsl_qrng_free (gsl_qrng * r) { if(r != 0) { if(r->state != 0) free (r->state); free (r); } }
{ "alphanum_fraction": 0.617357002, "avg_line_length": 16.487804878, "ext": "c", "hexsha": "45e4e7ee17edcd87bd72a175a576f13a08f7d0ea", "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/qrng/qrng.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/qrng/qrng.c", "max_line_length": 68, "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/qrng/qrng.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": 661, "size": 2028 }
//This computes "the" IDCT (inverse discrete cosine transformation) along dim of matrix X. //This uses a CBLAS matrix multiplication by the DCT-III matrix. #include <stdio.h> #include <stdlib.h> #include <math.h> #include <cblas.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef M_SQRT1_2 #define M_SQRT1_2 0.707106781186547524401 #endif #ifdef __cplusplus namespace codee { extern "C" { #endif int idct_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 idct_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 idct_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 idct_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 idct_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 idct_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 idct_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 xsc = (sc) ? (float)(2.0*M_SQRT1_2) : 1.0f; const float ysc = (sc) ? 2.0f/sqrtf((float)(2u*ndct)) : 2.0f/(float)(2u*ndct); const float dcsc = 0.5f * xsc * ysc; //Initialize DCT-III matrix const size_t LN = Lx * ndct; const float P_N = (float)(M_PI/(double)ndct); float *DCT, x0; DCT = (float *)aligned_alloc(sizeof(float),LN*sizeof(float)); if (!DCT) { fprintf(stderr,"error in idct_cblas_s: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t n=0u; n<ndct; ++n) { *DCT++ = xsc * ysc; for (size_t l=1u; l<Lx; ++l, ++DCT) { *DCT = ysc * cosf(P_N*(0.5f+(float)n)*(float)l); } } DCT -= LN; if (Lx==N) { x0 = dcsc * *X; cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X,1,0.0f,Y,1); for (size_t n=ndct; n>0u; --n, ++Y) { *Y -= x0; } } 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=V; v>0u; --v, X+=Lx) { x0 = dcsc * *X; cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X,1,0.0f,Y,1); for (size_t n=ndct; n>0u; --n, ++Y) { *Y -= x0; } } } 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-=K*ndct-1u) { x0 = dcsc * *X; cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X,(int)K,0.0f,Y,(int)K); for (size_t n=ndct; n>0u; --n, Y+=K) { *Y -= x0; } } } } } free(DCT); } return 0; } int idct_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 idct_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 idct_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 xsc = (sc) ? 2.0*M_SQRT1_2 : 1.0; const double ysc = (sc) ? 2.0/sqrt((double)(2u*ndct)) : 2.0/(double)(2u*ndct); const double dcsc = 0.5 * xsc * ysc; //Initialize DCT-III matrix const size_t LN = Lx * ndct; const double P_N = M_PI/(double)ndct; double *DCT, x0; DCT = (double *)aligned_alloc(sizeof(double),LN*sizeof(double)); if (!DCT) { fprintf(stderr,"error in idct_cblas_d: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t n=0u; n<ndct; ++n) { *DCT++ = xsc * ysc; for (size_t l=1u; l<Lx; ++l, ++DCT) { *DCT = ysc * cos(P_N*(0.5+(double)n)*(double)l); } } DCT -= LN; if (Lx==N) { x0 = dcsc * *X; cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X,1,0.0,Y,1); for (size_t n=ndct; n>0u; --n, ++Y) { *Y -= x0; } } 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=V; v>0u; --v, X+=Lx) { x0 = dcsc * *X; cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X,1,0.0,Y,1); for (size_t n=ndct; n>0u; --n, ++Y) { *Y -= x0; } } } 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-=K*ndct-1u) { x0 = dcsc * *X; cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X,(int)K,0.0,Y,(int)K); for (size_t n=ndct; n>0u; --n, Y+=K) { *Y -= x0; } } } } } free(DCT); } return 0; } int idct_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 idct_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 idct_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 xsc = (sc) ? (float)(2.0*M_SQRT1_2) : 1.0f; const float ysc = (sc) ? 2.0f/sqrtf((float)(2u*ndct)) : 2.0f/(float)(2u*ndct); const float dcsc = 0.5f * xsc * ysc; //Initialize DCT-III matrix const size_t LN = Lx * ndct; const float P_N = (float)(M_PI/(double)ndct); float *DCT, x0r, x0i; DCT = (float *)aligned_alloc(sizeof(float),LN*sizeof(float)); if (!DCT) { fprintf(stderr,"error in idct_cblas_s: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t n=0u; n<ndct; ++n) { *DCT++ = xsc * ysc; for (size_t l=1u; l<Lx; ++l, ++DCT) { *DCT = ysc * cosf(P_N*(0.5f+(float)n)*(float)l); } } DCT -= LN; if (Lx==N) { x0r = dcsc * *X; x0i = dcsc * *(X+1); 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); for (size_t n=ndct; n>0u; --n, ++Y) { *Y -= x0r; *++Y -= x0i; } } 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) { x0r = dcsc * *X; x0i = dcsc * *(X+1); 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); for (size_t n=ndct; n>0u; --n, ++Y) { *Y -= x0r; *++Y -= x0i; } } } 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+=2u, Y-=2u*K*ndct-2u) { x0r = dcsc * *X; x0i = dcsc * *(X+1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X,2*(int)K,0.0f,Y,2*(int)K); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0f,DCT,(int)Lx,X+1,2*(int)K,0.0f,Y+1,2*(int)K); for (size_t n=ndct; n>0u; --n, Y+=2u*K) { *Y -= x0r; *(Y+1) -= x0i; } } } } } free(DCT); } return 0; } int idct_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 idct_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 idct_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 xsc = (sc) ? 2.0*M_SQRT1_2 : 1.0; const double ysc = (sc) ? 2.0/sqrt((double)(2u*ndct)) : 2.0/(double)(2u*ndct); const double dcsc = 0.5 * xsc * ysc; //Initialize DCT-III matrix const size_t LN = Lx * ndct; const double P_N = M_PI/(double)ndct; double *DCT, x0r, x0i; DCT = (double *)aligned_alloc(sizeof(double),LN*sizeof(double)); if (!DCT) { fprintf(stderr,"error in idct_cblas_z: problem with aligned_alloc. "); perror("aligned_alloc"); return 1; } for (size_t n=0u; n<ndct; ++n) { *DCT++ = xsc * ysc; for (size_t l=1u; l<Lx; ++l, ++DCT) { *DCT = ysc * cos(P_N*(0.5+(double)n)*(double)l); } } DCT -= LN; if (Lx==N) { x0r = dcsc * *X; x0i = dcsc * *(X+1); 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); for (size_t n=ndct; n>0u; --n, ++Y) { *Y -= x0r; *++Y -= x0i; } } 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) { x0r = dcsc * *X; x0i = dcsc * *(X+1); 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); for (size_t n=ndct; n>0u; --n, ++Y) { *Y -= x0r; *++Y -= x0i; } } } 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+=2u, Y-=2u*K*ndct-2u) { x0r = dcsc * *X; x0i = dcsc * *(X+1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X,2*(int)K,0.0,Y,2*(int)K); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)ndct,(int)Lx,1.0,DCT,(int)Lx,X+1,2*(int)K,0.0,Y+1,2*(int)K); for (size_t n=ndct; n>0u; --n, Y+=2u*K) { *Y -= x0r; *(Y+1) -= x0i; } } } } } free(DCT); } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.4771014493, "avg_line_length": 39.8843930636, "ext": "c", "hexsha": "f9ba8f6e9d7965fefbc318f6fb3d474876cee468", "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/idct.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/idct.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/idct.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": 5113, "size": 13800 }
#include <assert.h> #include <stdio.h> #include <string.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_sf_gamma.h> int main(int argc, char *argv[]){ gsl_permutation *P; size_t l; if(2!=argc){ return 1; } l=strlen(argv[1]); if(GSL_SF_FACT_NMAX<l){ printf("String too long\n"); return 1; } P=gsl_permutation_calloc(l); assert(NULL!=P); do{ size_t *d=gsl_permutation_data(P),i; for(i=0;i<l;i++) printf("%c",argv[1][d[i]]); printf("\n"); }while(GSL_SUCCESS==gsl_permutation_next(P)); return 0; }
{ "alphanum_fraction": 0.646728972, "avg_line_length": 14.4594594595, "ext": "c", "hexsha": "1d6cb55cf104a13a55f03000eab8e70c0bbd587e", "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": "3686e1c674845fd9679ed02c25b8d3e0fad73373", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "blindsay7/gsl-tools", "max_forks_repo_path": "permutation/permutation.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3686e1c674845fd9679ed02c25b8d3e0fad73373", "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": "blindsay7/gsl-tools", "max_issues_repo_path": "permutation/permutation.c", "max_line_length": 46, "max_stars_count": null, "max_stars_repo_head_hexsha": "3686e1c674845fd9679ed02c25b8d3e0fad73373", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "blindsay7/gsl-tools", "max_stars_repo_path": "permutation/permutation.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 175, "size": 535 }
#pragma once #include <csignal> #include <iostream> #include <sstream> #include <cassert> #include <vector> #include <algorithm> #include <array> #include <memory> #include <iomanip> #include <fstream> #include <filesystem> #include <cstdarg> #include <unordered_set> #include <unordered_map> #include <bitset> #include <numeric> #include <cmath> #ifdef _MSC_VER # pragma warning(disable:4267) #endif #include <GLTFAsset.h> #include <GLTFScene.h> #include <GLTFBuffer.h> #include <GLTFBufferView.h> #include <GLTFAccessor.h> #include <GLTFMesh.h> #include <GLTFPrimitive.h> #ifdef _MSC_VER # pragma warning(default:4267) #endif #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" #include <gsl/span> #include <coveo/linq.h> #include <coveo/enumerable.h> #include <maya/MPxCommand.h> #include <maya/MFnPlugin.h> #include <maya/MIOStream.h> #include <maya/MGlobal.h> #include <maya/MArgList.h> #include <maya/MArgDatabase.h> #include <maya/MSyntax.h> #include <maya/MStreamUtils.h> #include <maya/MFileObject.h> #include <maya/MFileIO.h> #include <maya/MSelectionList.h> #include <maya/MFnMesh.h> #include <maya/MItMeshPolygon.h> #include <maya/MFloatPointArray.h> #include <maya/MFloatVectorArray.h> #include <maya/MDagPath.h> #include <maya/MPointArray.h> #include <maya/MFnAttribute.h> #include <maya/MFnStringArrayData.h> #include <maya/MFnMessageAttribute.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnTypedAttribute.h> #include <maya/MDagPathArray.h> #include <maya/MFnSet.h> #include <maya/MFnSingleIndexedComponent.h> #include <maya/MFnComponentListData.h> #include <maya/MDagModifier.h> #include <maya/MMatrix.h> #include <maya/MFnMatrixData.h> #include <maya/MFnTransform.h> #include <maya/MItDependencyGraph.h> #include <maya/MFnBlendShapeDeformer.h> #include <maya/MFnPhongShader.h> #include <maya/MFnLambertShader.h> #include <maya/MFnBlinnShader.h> #include <maya/MUuid.h> #include <maya/MImage.h> #include <maya/MFloatMatrix.h> #include <maya/MTime.h> #include <maya/MAnimControl.h> #include <maya/M3dView.h> #include <maya/MFnSkinCluster.h> #include <maya/MItGeometry.h> #include <maya/MItDependencyNodes.h> #include <maya/MItMeshFaceVertex.h>
{ "alphanum_fraction": 0.7667844523, "avg_line_length": 24.3440860215, "ext": "h", "hexsha": "2a9576c559177f321e0837c84f59320f3e688bef", "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": "14c09052bbe1437c9f4f26786284a7edf69df989", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "BigRoy/Maya2glTF", "max_forks_repo_path": "src/externals.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "14c09052bbe1437c9f4f26786284a7edf69df989", "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": "BigRoy/Maya2glTF", "max_issues_repo_path": "src/externals.h", "max_line_length": 43, "max_stars_count": 1, "max_stars_repo_head_hexsha": "26853c20484a2cb17f3d8c2594e76efecda3cb2b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hamilton555/gltf", "max_stars_repo_path": "src/externals.h", "max_stars_repo_stars_event_max_datetime": "2021-03-06T01:49:54.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-06T01:49:54.000Z", "num_tokens": 655, "size": 2264 }
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> void vnmr_svd(double **a, int irow, int jcol, double w[], double **v) { gsl_matrix *gA; gsl_matrix *gV; gsl_vector *gS; int i,j; int res; gA = gsl_matrix_alloc(irow,jcol); for (i=0; i<irow; i++) for (j=0; j<jcol; j++) gsl_matrix_set(gA, i, j, a[i+1][j+1]); gV = gsl_matrix_alloc(jcol,jcol); gS = gsl_vector_alloc(jcol); res = gsl_linalg_SV_decomp_jacobi(gA, gV, gS); for (i=0; i<irow; i++) for (j=0; j<jcol; j++) a[i+1][j+1] = gsl_matrix_get( gA, i, j); for (i=0; i<jcol; i++) for (j=0; j<jcol; j++) v[i+1][j+1] = gsl_matrix_get( gV, i, j); for (i=0; i<jcol; i++) w[i+1] = gsl_vector_get( gS, i); gsl_matrix_free(gA); gsl_matrix_free(gV); gsl_vector_free(gS); } void vnmr_svd_solve(double **u, double w[], double **v, int irow, int jcol, double b[], double x[]) { gsl_matrix *gU; gsl_matrix *gV; gsl_vector *gS; gsl_vector *gB; gsl_vector *gX; int i,j; int res; gU = gsl_matrix_alloc(irow,jcol); for (i=0; i<irow; i++) for (j=0; j<jcol; j++) gsl_matrix_set(gU, i, j, u[i+1][j+1]); gV = gsl_matrix_alloc(jcol,jcol); for (i=0; i<jcol; i++) for (j=0; j<jcol; j++) gsl_matrix_set( gV, i, j, v[i+1][j+1]); gS = gsl_vector_alloc(jcol); for (i=0; i<jcol; i++) gsl_vector_set( gS, i, w[i+1]); gB = gsl_vector_alloc(irow); for (i=0; i<irow; i++) gsl_vector_set( gB, i, b[i+1]); gX = gsl_vector_alloc(jcol); res = gsl_linalg_SV_solve(gU, gV, gS, gB, gX); for (i=0; i<jcol; i++) x[i+1] = gsl_vector_get( gX, i); gsl_matrix_free(gU); gsl_matrix_free(gV); gsl_vector_free(gS); gsl_vector_free(gB); gsl_vector_free(gX); fprintf(stderr,"solve m=%d n=%d\n",irow, jcol); for (i=1; i<=jcol; i++) fprintf(stderr," w[%d]: %g\n",i,w[i]); for (i=0; i<jcol; i++) fprintf(stderr," x[%d]: %g\n",i+1,x[i+1]); }
{ "alphanum_fraction": 0.5776014109, "avg_line_length": 24.652173913, "ext": "c", "hexsha": "b858530e7927bfefc5df902fc026662716ce9220", "lang": "C", "max_forks_count": 102, "max_forks_repo_forks_event_max_datetime": "2022-03-20T05:41:54.000Z", "max_forks_repo_forks_event_min_datetime": "2016-01-23T15:27:16.000Z", "max_forks_repo_head_hexsha": "f5e65eb2db4bded3437701f0fa91abd41928579c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "timburrow/openvnmrj-source", "max_forks_repo_path": "src/vnmrbg/vnmr_svd.c", "max_issues_count": 128, "max_issues_repo_head_hexsha": "f5e65eb2db4bded3437701f0fa91abd41928579c", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:53:52.000Z", "max_issues_repo_issues_event_min_datetime": "2016-07-13T17:09:02.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "timburrow/openvnmrj-source", "max_issues_repo_path": "src/vnmrbg/vnmr_svd.c", "max_line_length": 99, "max_stars_count": 32, "max_stars_repo_head_hexsha": "0db324603dbd8f618a6a9526b9477a999c5a4cc3", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "DanIverson/OpenVnmrJ", "max_stars_repo_path": "src/vnmrbg/vnmr_svd.c", "max_stars_repo_stars_event_max_datetime": "2022-03-28T17:54:44.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-17T05:04:26.000Z", "num_tokens": 840, "size": 2268 }
#pragma once #include <gsl\gsl> #include <winrt\Windows.Foundation.h> #include <d3d11.h> #include "DrawableGameComponent.h" #include "MatrixHelper.h" #include "SpotLight.h" namespace Library { class ProxyModel; } namespace Rendering { class SpotLightMaterial; class SpotLightDemo final : public Library::DrawableGameComponent { public: SpotLightDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); SpotLightDemo(const SpotLightDemo&) = delete; SpotLightDemo(SpotLightDemo&&) = default; SpotLightDemo& operator=(const SpotLightDemo&) = default; SpotLightDemo& operator=(SpotLightDemo&&) = default; ~SpotLightDemo(); float AmbientLightIntensity() const; void SetAmbientLightIntensity(float intensity); float SpotLightIntensity() const; void SetSpotLightIntensity(float intensity); const DirectX::XMFLOAT3& LightPosition() const; const DirectX::XMVECTOR LightPositionVector() const; void SetLightPosition(const DirectX::XMFLOAT3& position); void SetLightPosition(DirectX::FXMVECTOR position); const DirectX::XMFLOAT3& LightLookAt() const; void RotateSpotLight(const DirectX::XMFLOAT2& amount); float LightRadius() const; void SetLightRadius(float radius); float SpecularIntensity() const; void SetSpecularIntensity(float intensity); float SpecularPower() const; void SetSpecularPower(float power); float SpotLightInnerAngle() const; void SetSpotLightInnerAngle(float angle); float SpotLightOuterAngle() const; void SetSpotLightOuterAngle(float angle); virtual void Initialize() override; virtual void Update(const Library::GameTime& gameTime) override; virtual void Draw(const Library::GameTime& gameTime) override; private: std::shared_ptr<SpotLightMaterial> mMaterial; DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity }; winrt::com_ptr<ID3D11Buffer> mVertexBuffer; std::uint32_t mVertexCount{ 0 }; Library::SpotLight mSpotLight; std::unique_ptr<Library::ProxyModel> mProxyModel; float mModelRotationAngle{ 0.0f }; bool mUpdateMaterial{ true }; }; }
{ "alphanum_fraction": 0.7711132438, "avg_line_length": 28.9444444444, "ext": "h", "hexsha": "ac4d8856cca5f861baf765957eae6207ca8626a7", "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/4.2_Spot_Light/SpotLightDemo.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/4.2_Spot_Light/SpotLightDemo.h", "max_line_length": 85, "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/4.2_Spot_Light/SpotLightDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 524, "size": 2084 }
/* matrix/gsl_matrix_double.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MATRIX_DOUBLE_H__ #define __GSL_MATRIX_DOUBLE_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_double.h> #include <gsl/gsl_blas_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 typedef struct { size_t size1; size_t size2; size_t tda; double * data; gsl_block * block; int owner; } gsl_matrix; typedef struct { gsl_matrix matrix; } _gsl_matrix_view; typedef _gsl_matrix_view gsl_matrix_view; typedef struct { gsl_matrix matrix; } _gsl_matrix_const_view; typedef const _gsl_matrix_const_view gsl_matrix_const_view; /* Allocation */ GSL_FUN gsl_matrix * gsl_matrix_alloc (const size_t n1, const size_t n2); GSL_FUN gsl_matrix * gsl_matrix_calloc (const size_t n1, const size_t n2); GSL_FUN gsl_matrix * gsl_matrix_alloc_from_block (gsl_block * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_FUN gsl_matrix * gsl_matrix_alloc_from_matrix (gsl_matrix * m, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_FUN gsl_vector * gsl_vector_alloc_row_from_matrix (gsl_matrix * m, const size_t i); GSL_FUN gsl_vector * gsl_vector_alloc_col_from_matrix (gsl_matrix * m, const size_t j); GSL_FUN void gsl_matrix_free (gsl_matrix * m); /* Views */ GSL_FUN _gsl_matrix_view gsl_matrix_submatrix (gsl_matrix * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUN _gsl_vector_view gsl_matrix_row (gsl_matrix * m, const size_t i); GSL_FUN _gsl_vector_view gsl_matrix_column (gsl_matrix * m, const size_t j); GSL_FUN _gsl_vector_view gsl_matrix_diagonal (gsl_matrix * m); GSL_FUN _gsl_vector_view gsl_matrix_subdiagonal (gsl_matrix * m, const size_t k); GSL_FUN _gsl_vector_view gsl_matrix_superdiagonal (gsl_matrix * m, const size_t k); GSL_FUN _gsl_vector_view gsl_matrix_subrow (gsl_matrix * m, const size_t i, const size_t offset, const size_t n); GSL_FUN _gsl_vector_view gsl_matrix_subcolumn (gsl_matrix * m, const size_t j, const size_t offset, const size_t n); GSL_FUN _gsl_matrix_view gsl_matrix_view_array (double * base, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_view gsl_matrix_view_array_with_tda (double * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_view gsl_matrix_view_vector (gsl_vector * v, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_view gsl_matrix_view_vector_with_tda (gsl_vector * v, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_const_view gsl_matrix_const_submatrix (const gsl_matrix * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUN _gsl_vector_const_view gsl_matrix_const_row (const gsl_matrix * m, const size_t i); GSL_FUN _gsl_vector_const_view gsl_matrix_const_column (const gsl_matrix * m, const size_t j); GSL_FUN _gsl_vector_const_view gsl_matrix_const_diagonal (const gsl_matrix * m); GSL_FUN _gsl_vector_const_view gsl_matrix_const_subdiagonal (const gsl_matrix * m, const size_t k); GSL_FUN _gsl_vector_const_view gsl_matrix_const_superdiagonal (const gsl_matrix * m, const size_t k); GSL_FUN _gsl_vector_const_view gsl_matrix_const_subrow (const gsl_matrix * m, const size_t i, const size_t offset, const size_t n); GSL_FUN _gsl_vector_const_view gsl_matrix_const_subcolumn (const gsl_matrix * m, const size_t j, const size_t offset, const size_t n); GSL_FUN _gsl_matrix_const_view gsl_matrix_const_view_array (const double * base, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_const_view gsl_matrix_const_view_array_with_tda (const double * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_const_view gsl_matrix_const_view_vector (const gsl_vector * v, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_const_view gsl_matrix_const_view_vector_with_tda (const gsl_vector * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_FUN void gsl_matrix_set_zero (gsl_matrix * m); GSL_FUN void gsl_matrix_set_identity (gsl_matrix * m); GSL_FUN void gsl_matrix_set_all (gsl_matrix * m, double x); GSL_FUN int gsl_matrix_fread (FILE * stream, gsl_matrix * m) ; GSL_FUN int gsl_matrix_fwrite (FILE * stream, const gsl_matrix * m) ; GSL_FUN int gsl_matrix_fscanf (FILE * stream, gsl_matrix * m); GSL_FUN int gsl_matrix_fprintf (FILE * stream, const gsl_matrix * m, const char * format); GSL_FUN int gsl_matrix_memcpy(gsl_matrix * dest, const gsl_matrix * src); GSL_FUN int gsl_matrix_swap(gsl_matrix * m1, gsl_matrix * m2); GSL_FUN int gsl_matrix_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * dest, const gsl_matrix * src); GSL_FUN int gsl_matrix_swap_rows(gsl_matrix * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_swap_columns(gsl_matrix * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_swap_rowcol(gsl_matrix * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_transpose (gsl_matrix * m); GSL_FUN int gsl_matrix_transpose_memcpy (gsl_matrix * dest, const gsl_matrix * src); GSL_FUN int gsl_matrix_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix * dest, const gsl_matrix * src); GSL_FUN double gsl_matrix_max (const gsl_matrix * m); GSL_FUN double gsl_matrix_min (const gsl_matrix * m); GSL_FUN void gsl_matrix_minmax (const gsl_matrix * m, double * min_out, double * max_out); GSL_FUN void gsl_matrix_max_index (const gsl_matrix * m, size_t * imax, size_t *jmax); GSL_FUN void gsl_matrix_min_index (const gsl_matrix * m, size_t * imin, size_t *jmin); GSL_FUN void gsl_matrix_minmax_index (const gsl_matrix * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax); GSL_FUN int gsl_matrix_equal (const gsl_matrix * a, const gsl_matrix * b); GSL_FUN int gsl_matrix_isnull (const gsl_matrix * m); GSL_FUN int gsl_matrix_ispos (const gsl_matrix * m); GSL_FUN int gsl_matrix_isneg (const gsl_matrix * m); GSL_FUN int gsl_matrix_isnonneg (const gsl_matrix * m); GSL_FUN double gsl_matrix_norm1 (const gsl_matrix * m); GSL_FUN int gsl_matrix_add (gsl_matrix * a, const gsl_matrix * b); GSL_FUN int gsl_matrix_sub (gsl_matrix * a, const gsl_matrix * b); GSL_FUN int gsl_matrix_mul_elements (gsl_matrix * a, const gsl_matrix * b); GSL_FUN int gsl_matrix_div_elements (gsl_matrix * a, const gsl_matrix * b); GSL_FUN int gsl_matrix_scale (gsl_matrix * a, const double x); GSL_FUN int gsl_matrix_scale_rows (gsl_matrix * a, const gsl_vector * x); GSL_FUN int gsl_matrix_scale_columns (gsl_matrix * a, const gsl_vector * x); GSL_FUN int gsl_matrix_add_constant (gsl_matrix * a, const double x); GSL_FUN int gsl_matrix_add_diagonal (gsl_matrix * a, const double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_FUN int gsl_matrix_get_row(gsl_vector * v, const gsl_matrix * m, const size_t i); GSL_FUN int gsl_matrix_get_col(gsl_vector * v, const gsl_matrix * m, const size_t j); GSL_FUN int gsl_matrix_set_row(gsl_matrix * m, const size_t i, const gsl_vector * v); GSL_FUN int gsl_matrix_set_col(gsl_matrix * m, const size_t j, const gsl_vector * v); /***********************************************************************/ /* inline functions if you are using GCC */ GSL_FUN INLINE_DECL double gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j); GSL_FUN INLINE_DECL void gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x); GSL_FUN INLINE_DECL double * gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j); GSL_FUN INLINE_DECL const double * gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j); #ifdef HAVE_INLINE INLINE_FUN double gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { 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] ; } INLINE_FUN void gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { 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 ; } INLINE_FUN double * gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { 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 (double *) (m->data + (i * m->tda + j)) ; } INLINE_FUN const double * gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { 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 double *) (m->data + (i * m->tda + j)) ; } #endif __END_DECLS #endif /* __GSL_MATRIX_DOUBLE_H__ */
{ "alphanum_fraction": 0.6208245326, "avg_line_length": 34.7364130435, "ext": "h", "hexsha": "7f93ec322c940647c3f630c4b79a0a7096c138f0", "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": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_matrix_double.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_matrix_double.h", "max_line_length": 127, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_path": "vendor/gsl/gsl/gsl_matrix_double.h", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "num_tokens": 3150, "size": 12783 }
#ifndef VKST_PLAT_LOG_H #define VKST_PLAT_LOG_H #include <plat/core.h> #include <plat/filesystem.h> #include <gsl.h> #include <string> namespace plat { // Initialize logging with output to a given path. // Must be called before logging output will occur. void init_logging(plat::filesystem::path logfile, std::error_code& ec) noexcept; enum class log_severities : uint8_t { trace = 1, debug, info, warn, error, fatal, none }; inline constexpr gsl::czstring to_string(log_severities severity) noexcept { switch(severity) { case log_severities::trace: return "TRACE"; case log_severities::debug: return "DEBUG"; case log_severities::info: return "INFO"; case log_severities::warn: return "WARN"; case log_severities::error: return "ERROR"; case log_severities::fatal: return "FATAL"; case log_severities::none: return "NONE"; } PLAT_MARK_UNREACHABLE; } void log(log_severities severity, gsl::czstring fmt, ...) noexcept; #define LOG_TRACE(...) ::plat::log(::plat::log_severities::trace, __VA_ARGS__) #define LOG_DEBUG(...) ::plat::log(::plat::log_severities::debug, __VA_ARGS__) #define LOG_INFO(...) ::plat::log(::plat::log_severities::info, __VA_ARGS__) #define LOG_WARN(...) ::plat::log(::plat::log_severities::warn, __VA_ARGS__) #define LOG_ERROR(...) ::plat::log(::plat::log_severities::error, __VA_ARGS__) #define LOG_FATAL(...) ::plat::log(::plat::log_severities::fatal, __VA_ARGS__) #define LOG_ENTER \ ::plat::log(::plat::log_severities::trace, "enter: %s (%s:%d)", __func__, \ __FILE__, __LINE__) #define LOG_LEAVE \ ::plat::log(::plat::log_severities::trace, "leave: %s (%s:%d)", __func__, \ __FILE__, __LINE__) } // namespace plat #endif // VKST_PLAT_LOG_H
{ "alphanum_fraction": 0.6550802139, "avg_line_length": 33.3928571429, "ext": "h", "hexsha": "5ffaad508acac09cd545da44433f286acfe8c509", "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": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_forks_repo_licenses": [ "Zlib" ], "max_forks_repo_name": "wesleygriffin/vkst", "max_forks_repo_path": "src/plat/log.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Zlib" ], "max_issues_repo_name": "wesleygriffin/vkst", "max_issues_repo_path": "src/plat/log.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c", "max_stars_repo_licenses": [ "Zlib" ], "max_stars_repo_name": "wesleygriffin/vkst", "max_stars_repo_path": "src/plat/log.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 490, "size": 1870 }
#pragma once #include "text_parser.h" #include "width_cache.h" #include <string> #include <vector> #include <gsl/span> namespace terminal_editor { enum class GraphemeKind { NORMAL, ///< Normal, displayable characters. INVALID, ///< Invalid characters for given encoding. REPLACEMENT, ///< Replacement representation of valid (possibly control) characters (such as 4 spaces for tabs, or [NUL] for 0x00). }; /// Each grapheme represents one logical 'image' on the screen. /// It can consist of many actual characters (either because we have combining characters, or because we replaced bytes with some special string, like "[CR]"). /// It is produced from one or more bytes in the underlying byte data. /// It can have a width of 0 or more (either because actual characters take two columns, or because replacement string is longer, like "[x66]" or "[TAB]"). struct Grapheme { GraphemeKind kind; ///< Kind of grapheme: normal grapheme, invalid bytes or replacement. std::string rendered; ///< Valid UTF-8 string to display on the screen. std::string info; ///< Valid UTF-8 string. Can contain arbitrary informational text about the grapheme. Will contain error description in case of invalid graphemes. int width; ///< Width (in terminal cells) of the 'rendered' string, once it will be displayed on the terminal. gsl::span<const char> consumedInput; ///< Span of input data that was rendered into this grapheme. }; /// Converts given span of CodePoinInfos into a Grapheme, by concatenating their representations. /// @param codePoinInfos A span of CodePoinInfos. /// @note If codePoinInfos is empty a NORMAL, but zero width grapheme is returned. Grapheme renderGrapheme(gsl::span<const CodePointInfo> codePointInfos); /// CodePointWidthCache used by renderLine(). /// @todo This should not be a gloabl variable. extern CodePointWidthCache textRendererWidthCache; /// Renders data into Graphemes. /// Each byte of invalid CodePointInfos are rendered as separate graphemes. /// Valid CodePointInfos are grouped into maximal chunks where only first CodePointInfo can have non-zero wcwidth() (after processing replacements). One grapheme is created for /// each such group. /// @note Some resulting graphemes can have zero-width. /// @note Result can be empty. /// @note Width of characters is computed using global CodePointWidthCache. /// @param data Input string to render. It is assumed to be in UTF-8, but can contain invalid characters (which will be rendered as special Graphemes). /// @note Any control characters (including new line characters) will be rendered as a replacement string (i.e. [LF]). std::vector<Grapheme> renderLine(gsl::span<CodePointInfo> codePointInfos); /// Returns concatenation of rendered property of all graphemes. /// @param graphemes Span of graphemes to concatenate. /// @param useBrackets If true all invalid and replacement sequences will be enclosed with brackets. std::string renderGraphemes(gsl::span<const Grapheme> graphemes, bool useBrackets); /// Returns width of given text after rendering on screen. /// @note This functions takes into consideration replacement strings, and thus differs from wcswidth(). /// @note This function is very slow, as it needs to convert text to graphemes first. /// @param text UTF-8 string, can be invalid. int getRenderedWidth(gsl::span<const char> text); /// Returns width of given line of graphemes after rendering on screen. /// @param graphemes A span of graphemes. int getRenderedWidth(gsl::span<const Grapheme> graphemes); } // namespace terminal_editor
{ "alphanum_fraction": 0.7414687415, "avg_line_length": 54.671641791, "ext": "h", "hexsha": "35256836e9d3e9aa645f6b44fe428d03ec637321", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-12-21T00:37:06.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-21T00:37:06.000Z", "max_forks_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Zbyl/terminal-editor", "max_forks_repo_path": "editorlib/text_renderer.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "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": "Zbyl/terminal-editor", "max_issues_repo_path": "editorlib/text_renderer.h", "max_line_length": 176, "max_stars_count": null, "max_stars_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Zbyl/terminal-editor", "max_stars_repo_path": "editorlib/text_renderer.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 807, "size": 3663 }
#include <stdio.h> #include <math.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_odeiv.h> #define DIM 1 #define NPTS 100 #define abserr 1e-5 #define relerr 1e-5 #define mem 10000 typedef double (* function) (double x, void * params); double integrate(function f, void * params, double lower_bound, double upper_bound); //int func (double t, const double y[], double f[], void *params); //void gsl_ode(gsl_odeiv_system sys, double Xo, double maxtime);
{ "alphanum_fraction": 0.7346221441, "avg_line_length": 28.45, "ext": "h", "hexsha": "e1a9fdf1c96a6a46473e09a91c8c60f761dbeca8", "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": "3b0711e06a05b4808b16688ab68c745365005ec3", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "cboettig/AdaptiveDynamics", "max_forks_repo_path": "src/integrate.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3b0711e06a05b4808b16688ab68c745365005ec3", "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": "cboettig/AdaptiveDynamics", "max_issues_repo_path": "src/integrate.h", "max_line_length": 84, "max_stars_count": null, "max_stars_repo_head_hexsha": "3b0711e06a05b4808b16688ab68c745365005ec3", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "cboettig/AdaptiveDynamics", "max_stars_repo_path": "src/integrate.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 171, "size": 569 }
//CELL operation: does output side of Elman RNN layer. //There is no strict definition of Elman RNN in the literature. //For example, the Wikipedia article doesn't specify the dims of the hidden or other vectors. //Here I implement an interpretation where there are N neurons and thus N inputs/outputs. //The inputs here are from the IN stage, so reduced to N driving input time-series in X. //Again, this is not an "Elman network", rather a layer of N neurons //that I have named "Elman" neurons due to their great similarity to an Elman RNN. //To do: should I allow other output activations other than logistic? #include <stdio.h> #include <stdlib.h> #include <math.h> #include <cblas.h> #ifdef __cplusplus namespace codee { extern "C" { #endif int elman_s (float *Y, const float *X, const float *U, float *H, const float *W, const float *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim); int elman_d (double *Y, const double *X, const double *U, double *H, const double *W, const double *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim); int elman_s (float *Y, const float *X, const float *U, float *H, const float *W, const float *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim) { const float o = 1.0f; if (N==1u) { for (size_t t=0u; t<T; ++t) { H[0] = 1.0f / (1.0f+expf(-X[t]-U[0]*H[0])); Y[t] = 1.0f / (1.0f+expf(-B[0]-W[0]*H[0])); } } else { float *tmp; if (!(tmp=(float *)malloc(N*sizeof(float)))) { fprintf(stderr,"error in elman_s: problem with malloc. "); perror("malloc"); return 1; } if (dim==0u) { if (iscolmajor) { for (size_t t=0u; t<T; ++t) { cblas_scopy((int)N,&X[t*N],1,tmp,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-tmp[n])); } //cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,&X[t*N],1); //for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-X[t*N+n])); } //for (size_t n=0u; n<N; ++n) { Y[t*N+n] = 1.0f/(1.0f+expf(-cblas_sdot((int)N,&W[n],(int)N,H,1)-B[n])); } cblas_scopy((int)N,B,1,tmp,1); cblas_sgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,W,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { Y[t*N+n] = 1.0f/(1.0f+expf(-tmp[n])); } } } else { for (size_t t=0u; t<T; ++t) { cblas_scopy((int)N,&X[t],(int)T,tmp,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-tmp[n])); } cblas_scopy((int)N,B,1,tmp,1); cblas_sgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,W,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { Y[t+n*T] = 1.0f/(1.0f+expf(-tmp[n])); } } } } else if (dim==1u) { if (iscolmajor) { for (size_t t=0u; t<T; ++t) { cblas_scopy((int)N,&X[t],(int)T,tmp,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-tmp[n])); } cblas_scopy((int)N,B,1,tmp,1); cblas_sgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,W,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { Y[t+n*T] = 1.0f/(1.0f+expf(-tmp[n])); } } } else { for (size_t t=0u; t<T; ++t) { cblas_scopy((int)N,&X[t*N],1,tmp,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0f/(1.0f+expf(-tmp[n])); } cblas_scopy((int)N,B,1,tmp,1); cblas_sgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,W,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { Y[t*N+n] = 1.0f/(1.0f+expf(-tmp[n])); } } } } else { fprintf(stderr,"error in elman_s: dim must be 0 or 1.\n"); return 1; } } return 0; } int elman_d (double *Y, const double *X, const double *U, double *H, const double *W, const double *B, const size_t N, const size_t T, const char iscolmajor, const size_t dim) { const double o = 1.0; if (N==1u) { for (size_t t=0u; t<T; ++t) { H[0] = 1.0 / (1.0+exp(-X[t]-U[0]*H[0])); Y[t] = 1.0 / (1.0+exp(-B[0]-W[0]*H[0])); } } else { double *tmp; if (!(tmp=(double *)malloc(N*sizeof(double)))) { fprintf(stderr,"error in elman_d: problem with malloc. "); perror("malloc"); return 1; } if (dim==0u) { if (iscolmajor) { for (size_t t=0u; t<T; ++t) { cblas_dcopy((int)N,&X[t*N],1,tmp,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0/(1.0+exp(-tmp[n])); } cblas_dcopy((int)N,B,1,tmp,1); cblas_dgemv(CblasColMajor,CblasNoTrans,(int)N,(int)N,o,W,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { Y[t*N+n] = 1.0/(1.0+exp(-tmp[n])); } } } else { for (size_t t=0u; t<T; ++t) { cblas_dcopy((int)N,&X[t],(int)T,tmp,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,U,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0/(1.0+exp(-tmp[n])); } cblas_dcopy((int)N,B,1,tmp,1); cblas_dgemv(CblasRowMajor,CblasNoTrans,(int)N,(int)N,o,W,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { Y[t+n*T] = 1.0/(1.0+exp(-tmp[n])); } } } } else if (dim==1u) { if (iscolmajor) { for (size_t t=0u; t<T; ++t) { cblas_dcopy((int)N,&X[t],(int)T,tmp,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0/(1.0+exp(-tmp[n])); } cblas_dcopy((int)N,B,1,tmp,1); cblas_dgemv(CblasColMajor,CblasTrans,(int)N,(int)N,o,W,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { Y[t+n*T] = 1.0/(1.0+exp(-tmp[n])); } } } else { for (size_t t=0u; t<T; ++t) { cblas_dcopy((int)N,&X[t*N],1,tmp,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,U,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { H[n] = 1.0/(1.0+exp(-tmp[n])); } cblas_dcopy((int)N,B,1,tmp,1); cblas_dgemv(CblasRowMajor,CblasTrans,(int)N,(int)N,o,W,(int)N,H,1,o,tmp,1); for (size_t n=0u; n<N; ++n) { Y[t*N+n] = 1.0/(1.0+exp(-tmp[n])); } } } } else { fprintf(stderr,"error in elman_d: dim must be 0 or 1.\n"); return 1; } } return 0; } #ifdef __cplusplus } } #endif
{ "alphanum_fraction": 0.4621604548, "avg_line_length": 40.5897435897, "ext": "c", "hexsha": "5dcff650f8c8ea49b160e89d072a02403f5bc6f6", "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/elman.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/elman.c", "max_line_length": 176, "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/elman.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": 2682, "size": 7915 }
/* linalg/qrc.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * Copyright (C) 2017 Christian Krueger * Copyright (C) 2020 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. */ /* Author: G. Jungman, modified by C. Krueger */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> /* Factorise a general complex-valued M x N matrix A into * * A = Q R * * where Q is unitary (M x M) and R is upper triangular (M x N). * * Q is stored as a packed set of Householder transformations in the * strict lower triangular part of the input matrix. * * R is stored in the diagonal and upper triangle of the input matrix. * * The full matrix for Q can be obtained as the product * * Q = Q_k .. Q_2 Q_1 * * where k = MIN(M,N) and * * Q_i = (I - tau_i * v_i * v_i') * * and where v_i is a Householder vector * * v_i = [1, m(i+1,i), m(i+2,i), ... , m(M,i)] * * This storage scheme is the same as in LAPACK. */ int gsl_linalg_complex_QR_decomp (gsl_matrix_complex * A, gsl_vector_complex * tau) { const size_t M = A->size1; const size_t N = A->size2; if (tau->size != N) { GSL_ERROR ("size of tau must be N", GSL_EBADLEN); } else { size_t i; for (i = 0; i < GSL_MIN (M, N); i++) { /* Compute the Householder transformation to reduce the j-th column of the matrix to a multiple of the j-th unit vector */ gsl_vector_complex_view c = gsl_matrix_complex_subcolumn (A, i, i, M - i); gsl_complex tau_i = gsl_linalg_complex_householder_transform (&(c.vector)); gsl_vector_complex_set (tau, i, tau_i); /* apply the transformation to the remaining columns and update the norms */ if (i + 1 < N) { gsl_matrix_complex_view m = gsl_matrix_complex_submatrix (A, i, i + 1, M - i, N - i - 1); gsl_complex tau_i_conj = gsl_complex_conjugate(tau_i); gsl_vector_complex_view work = gsl_vector_complex_subvector(tau, i + 1, N - i - 1); gsl_linalg_complex_householder_left(tau_i_conj, &(c.vector), &(m.matrix), &(work.vector)); } } return GSL_SUCCESS; } } /* Solves the system A x = b using the QR factorisation, * R x = Q^H b * * to obtain x. */ int gsl_linalg_complex_QR_solve (const gsl_matrix_complex * QR, const gsl_vector_complex * tau, const gsl_vector_complex * b, gsl_vector_complex * x) { if (QR->size1 != QR->size2) { GSL_ERROR ("QR matrix must be square", GSL_ENOTSQR); } else if (QR->size1 != b->size) { GSL_ERROR ("matrix size must match b size", GSL_EBADLEN); } else if (QR->size2 != x->size) { GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN); } else { /* copy x <- b */ gsl_vector_complex_memcpy (x, b); /* solve for x */ gsl_linalg_complex_QR_svx (QR, tau, x); return GSL_SUCCESS; } } /* Solves the system A x = b in place using the QR factorisation, * R x = Q^H b * * to obtain x. */ int gsl_linalg_complex_QR_svx (const gsl_matrix_complex * QR, const gsl_vector_complex * tau, gsl_vector_complex * x) { if (QR->size1 != QR->size2) { GSL_ERROR ("QR matrix must be square", GSL_ENOTSQR); } else if (QR->size1 != x->size) { GSL_ERROR ("matrix size must match x/rhs size", GSL_EBADLEN); } else { /* compute rhs = Q^H b */ gsl_linalg_complex_QR_QHvec (QR, tau, x); /* solve R x = rhs, storing x in-place */ gsl_blas_ztrsv (CblasUpper, CblasNoTrans, CblasNonUnit, QR, x); return GSL_SUCCESS; } } /* Find the least squares solution to the overdetermined system * * A x = b * * for M >= N using the QR factorization A = Q R. */ int gsl_linalg_complex_QR_lssolve (const gsl_matrix_complex * QR, const gsl_vector_complex * tau, const gsl_vector_complex * b, gsl_vector_complex * x, gsl_vector_complex * residual) { const size_t M = QR->size1; const size_t N = QR->size2; if (M < N) { GSL_ERROR ("QR matrix must have M>=N", GSL_EBADLEN); } else if (M != b->size) { GSL_ERROR ("matrix size must match b size", 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_complex_const_view R = gsl_matrix_complex_const_submatrix (QR, 0, 0, N, N); gsl_vector_complex_view c = gsl_vector_complex_subvector(residual, 0, N); gsl_vector_complex_memcpy(residual, b); /* compute rhs = Q^H b */ gsl_linalg_complex_QR_QHvec (QR, tau, residual); /* solve R x = rhs */ gsl_vector_complex_memcpy(x, &(c.vector)); gsl_blas_ztrsv (CblasUpper, CblasNoTrans, CblasNonUnit, &(R.matrix), x); /* compute residual = b - A x = Q (Q^H b - R x) */ gsl_vector_complex_set_zero(&(c.vector)); gsl_linalg_complex_QR_Qvec(QR, tau, residual); return GSL_SUCCESS; } } /* form the product v := Q^H v from a QR factorized matrix */ int gsl_linalg_complex_QR_QHvec (const gsl_matrix_complex * QR, const gsl_vector_complex * tau, gsl_vector_complex * v) { const size_t M = QR->size1; const size_t N = QR->size2; if (tau->size != N) { GSL_ERROR ("size of tau must be N", GSL_EBADLEN); } else if (v->size != M) { GSL_ERROR ("vector size must be M", GSL_EBADLEN); } else { size_t i; /* compute Q^H v */ for (i = 0; i < GSL_MIN (M, N); i++) { gsl_vector_complex_const_view h = gsl_matrix_complex_const_subcolumn (QR, i, i, M - i); gsl_vector_complex_view w = gsl_vector_complex_subvector (v, i, M - i); gsl_complex ti = gsl_vector_complex_get (tau, i); gsl_complex ti_conj = gsl_complex_conjugate(ti); gsl_linalg_complex_householder_hv (ti_conj, &(h.vector), &(w.vector)); } return GSL_SUCCESS; } } int gsl_linalg_complex_QR_Qvec (const gsl_matrix_complex * QR, const gsl_vector_complex * tau, gsl_vector_complex * v) { const size_t M = QR->size1; const size_t N = QR->size2; if (tau->size != GSL_MIN (M, N)) { GSL_ERROR ("size of tau must be MIN(M,N)", GSL_EBADLEN); } else if (v->size != M) { GSL_ERROR ("vector size must be M", GSL_EBADLEN); } else { size_t i; /* compute Q v */ for (i = GSL_MIN (M, N); i-- > 0;) { gsl_vector_complex_const_view c = gsl_matrix_complex_const_column (QR, i); gsl_vector_complex_const_view h = gsl_vector_complex_const_subvector (&(c.vector), i, M - i); gsl_vector_complex_view w = gsl_vector_complex_subvector (v, i, M - i); gsl_complex ti = gsl_vector_complex_get (tau, i); /* we do not need the conjugate of ti here */ gsl_linalg_complex_householder_hv (ti, &h.vector, &w.vector); } return GSL_SUCCESS; } } /* form the unitary matrix Q from the packed QR matrix */ int gsl_linalg_complex_QR_unpack (const gsl_matrix_complex * QR, const gsl_vector_complex * tau, gsl_matrix_complex * Q, gsl_matrix_complex * R) { const size_t M = QR->size1; const size_t N = QR->size2; if (Q->size1 != M || Q->size2 != M) { GSL_ERROR ("Q matrix must be M x M", GSL_ENOTSQR); } else if (R->size1 != M || R->size2 != N) { GSL_ERROR ("R matrix must be M x N", GSL_ENOTSQR); } else if (tau->size != N) { GSL_ERROR ("size of tau must be N", GSL_EBADLEN); } else { size_t i, j; /* initialize Q to the identity */ gsl_matrix_complex_set_identity (Q); for (i = GSL_MIN (M, N); i-- > 0;) { gsl_vector_complex_const_view c = gsl_matrix_complex_const_column (QR, i); gsl_vector_complex_const_view h = gsl_vector_complex_const_subvector (&c.vector, i, M - i); gsl_matrix_complex_view m = gsl_matrix_complex_submatrix (Q, i, i, M - i, M - i); gsl_complex ti = gsl_vector_complex_get (tau, i); gsl_vector_complex_view work = gsl_matrix_complex_subcolumn(R, 0, 0, M - i); /* we do not need the conjugate of ti here */ gsl_linalg_complex_householder_left (ti, &h.vector, &m.matrix, &work.vector); } /* form the right triangular matrix R from a packed QR matrix */ for (i = 0; i < M; i++) { for (j = 0; j < i && j < N; j++) gsl_matrix_complex_set (R, i, j, GSL_COMPLEX_ZERO); for (j = i; j < N; j++) gsl_matrix_complex_set (R, i, j, gsl_matrix_complex_get (QR, i, j)); } return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.6138223704, "avg_line_length": 28.8542274052, "ext": "c", "hexsha": "e24193735efe36de4357d177b37a27f87af7a858", "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/linalg/qrc.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/linalg/qrc.c", "max_line_length": 115, "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/linalg/qrc.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": 2754, "size": 9897 }
/* combination/gsl_combination.h * based on permutation/gsl_permutation.h by Brian Gough * * Copyright (C) 2001 Szymon Jaroszewicz * * 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_COMBINATION_H__ #define __GSL_COMBINATION_H__ #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_types.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_combination_struct { size_t n; size_t k; size_t *data; }; typedef struct gsl_combination_struct gsl_combination; gsl_combination *gsl_combination_alloc (const size_t n, const size_t k); gsl_combination *gsl_combination_calloc (const size_t n, const size_t k); void gsl_combination_init_first (gsl_combination * c); void gsl_combination_init_last (gsl_combination * c); void gsl_combination_free (gsl_combination * c); int gsl_combination_memcpy (gsl_combination * dest, const gsl_combination * src); int gsl_combination_fread (FILE * stream, gsl_combination * c); int gsl_combination_fwrite (FILE * stream, const gsl_combination * c); int gsl_combination_fscanf (FILE * stream, gsl_combination * c); int gsl_combination_fprintf (FILE * stream, const gsl_combination * c, const char *format); size_t gsl_combination_n (const gsl_combination * c); size_t gsl_combination_k (const gsl_combination * c); size_t * gsl_combination_data (const gsl_combination * c); size_t gsl_combination_get (const gsl_combination * c, const size_t i); int gsl_combination_valid (gsl_combination * c); int gsl_combination_next (gsl_combination * c); int gsl_combination_prev (gsl_combination * c); #ifdef HAVE_INLINE extern inline size_t gsl_combination_get (const gsl_combination * c, const size_t i) { #if GSL_RANGE_CHECK if (i >= c->k) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return c->data[i]; } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_COMBINATION_H__ */
{ "alphanum_fraction": 0.7656193572, "avg_line_length": 30.097826087, "ext": "h", "hexsha": "ece1b728754a8593db07f767a2ed3ef5b83e36f9", "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/combination/gsl_combination.h", "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/combination/gsl_combination.h", "max_line_length": 91, "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/combination/gsl_combination.h", "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": 721, "size": 2769 }
#ifndef _GLOBAL_SETTING_ #define _GLOBAL_SETTING_ #define MATRIX_WIDTH 128 #define MATRIX_HEIGHT 128 #define MATRIX_CHANNEL 64 #define MATRIX_DEPTH 1 #define KERNEL_WIDTH 3 #define KERNEL_HEIGHT 3 #define KERNEL_CHANNEL MATRIX_CHANNEL #define KERNEL_DEPTH 128 #define FEATURE_WIDTH (MATRIX_WIDTH - KERNEL_WIDTH + 1) #define FEATURE_HEIGHT (MATRIX_HEIGHT - KERNEL_HEIGHT + 1) #define FEATURE_CHANNEL 1 #define FEATURE_DEPTH 128 #ifdef CBLAS #include <cblas.h> #endif // #ifdef CBLAS #ifdef OMP #include <omp.h> #endif // #ifdef OMP #ifdef OPENCL #ifdef __APPLE__ #include <OpenCL/opencl.h> #elif linux #include <CL/cl.h> #elif __WIN32__ #include <cl.h> #else #include <CL/cl.h> #endif // #ifdef __APPLE__ #endif // #ifdef OPENCL #endif // _GLOBAL_SETTING_
{ "alphanum_fraction": 0.7414880202, "avg_line_length": 17.6222222222, "ext": "h", "hexsha": "e46ef88c41f83beb5cf562ce5d28e9963adb0c70", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-06-27T11:00:18.000Z", "max_forks_repo_forks_event_min_datetime": "2018-06-27T11:00:18.000Z", "max_forks_repo_head_hexsha": "d84bb3a285be184978a8a4185843ce860daa1866", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "yeephycho/Fast_Spatial_Convolution", "max_forks_repo_path": "src/Global_Setting.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d84bb3a285be184978a8a4185843ce860daa1866", "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": "yeephycho/Fast_Spatial_Convolution", "max_issues_repo_path": "src/Global_Setting.h", "max_line_length": 58, "max_stars_count": 1, "max_stars_repo_head_hexsha": "d84bb3a285be184978a8a4185843ce860daa1866", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "yeephycho/Fast_Spatial_Convolution", "max_stars_repo_path": "src/Global_Setting.h", "max_stars_repo_stars_event_max_datetime": "2018-06-27T11:00:18.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-27T11:00:18.000Z", "num_tokens": 216, "size": 793 }
/* bclsqr.c $Revision: 273 $ $Date: 2006-09-04 15:59:04 -0700 (Mon, 04 Sep 2006) $ ---------------------------------------------------------------------- This file is part of BCLS (Bound-Constrained Least Squares). Copyright (C) 2006 Michael P. Friedlander, Department of Computer Science, University of British Columbia, Canada. All rights reserved. E-mail: <mpf@cs.ubc.ca>. BCLS 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. BCLS 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 BCLS; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ---------------------------------------------------------------------- */ /*! \file Interface to LSQR routine. Used to compute a Newton step. */ #include <cblas.h> #include <string.h> #include <stdio.h> #include "bcls.h" #include "bclib.h" #include "bclsqr.h" #include "lsqr.h" /*! \brief Mat-vec routine called by LSQR. LSQR calls this routine, which in turn calls bcls_aprod: This routine is declared "static" so that it won't be confused with the user's own Aprod routine. - If mode = 1, - y(1:m) <- y(1:m) + A(:,ix) * dxFree. - y(m+1:) <- y(m+1:) + damp * dxFree - If mode = 2, - dxFree <- dxFree + A'* y(1:m) + damp y(m+1:). Note that mSubProb is the number of rows in the subproblem. This may or may not be equal to m, which is the number of rows in the original problem. If the subproblem is damped (because the user has either provided a linear term or an explicit damping parameter), then mSubProb = m + nFree. Otherwise, mSubProb = m. \param[in] mode Determines which producte with A is required. \param[in] mSubProb Number of rows in the matrix seen by LSQR. Also: - length of y. \param[in] nFree Number of columns in A(:,ix). Also: - length of ix - length of dxFree. \param[in,out] dxFree Primal variables \param[in,out] y Dual variables. \param[in,out] UsrWrk Transit pointer to the BCLS problem context. */ static void aprod_free_lsqr( const int mode, const int mSubProb, const int nFree, double dxFree[], double y[], void *UsrWrk) { int j; BCLS *ls = (BCLS *)UsrWrk; // Reclaim access to the BCLS workspace. const int m = ls->m; const int preconditioned = ls->Usolve != NULL; const int damped = ls->damp_actual > 0.0; const double damp = ls->damp_actual; int *ix = ls->ix; double *dx = ls->dx; // Used as workspace. double *dy = ls->wrk_u; // ... if (mode == 1) { // Solve U dy = dxFree. U is nFree-by-nFree, and so the // relevant part of dy has length nFree. if (preconditioned) bcls_usolve( ls, BCLS_PRECON_U, nFree, ix, dy, dxFree ); else cblas_dcopy( nFree, dxFree, 1, dy, 1 ); // y2 <- y2 + damp * dy(1:nFree). if (damped) cblas_daxpy( nFree, damp, dy, 1, &y[m], 1 ); // Scatter dy into dx: dx(ix) <- dy(1:nFree). for (j = 0; j < nFree; j++) dx[ ix[j] ] = dy[j]; // dy <- A(:,ix) * dx(ix). bcls_aprod( ls, BCLS_PROD_A, nFree, ix, dx, dy ); // y1 <- y1 + dy. cblas_daxpy( m, 1.0, dy, 1, y, 1 ); } else { // mode == 2 // dx <- A' * y1. bcls_aprod( ls, BCLS_PROD_At, nFree, ix, dx, y ); // Gather dx(ix) into dy: dy(1:nFree) <- dx(ix). for (j = 0; j < nFree; j++) dy[j] = dx[ ix[j] ]; // dy <- dy + damp * y2. if (damped) cblas_daxpy( nFree, damp, &y[m], 1, dy, 1 ); // Solve U' dx = dy. if (preconditioned) bcls_usolve( ls, BCLS_PRECON_Ut, nFree, ix, dy, dx ); else cblas_dcopy( nFree, dy, 1, dx, 1 ); // dxFree <- dxFree + dx. cblas_daxpy( nFree, 1.0, dx, 1, dxFree, 1 ); } return; } /*! \brief Compute a Newton step using LSQR. \see bcls_newton_step_cgls. \param[in,out] ls BCLS problem context. \param[in] m Number of rows in A. \param[in] nFree Number of columns in A(:,ix). Also: - length of ix and dxFree \param[in] ix Index of free variables. \param[in] damp Regularization parameter. \param[in] itnLim Iteration limit on current LSQR call. \param[in] tol LSQR's atol and btol. \param[in,out] dxFree Search direction on free variables. \param[in,out] x Current point. \param[in] c Linear term. \param[in,out] r Residual. Used as RHS for LSQR. \param[out] itns Number of LSQR iterations on current subproblem. \param[out] opt Optimality achieved by LSQR on current subproblem. \return - 0: Required accurace was achieved. - 1: The iteration limit (itnLim) was reached. - 2: A(:,ix) is excessively ill-conditioned. */ int bcls_newton_step_lsqr( BCLS *ls, int m, int nFree, int ix[], double damp, int itnLim, double tol, double dxFree[], double x[], double c[], double r[], int *itns, double *opt ) { int j, k; // Misc. counters. int mpn; // No. of rows in [ N; damp I ]. int unscale_dxFree = 0; const int rescaling_method = 1; const int linear = c != NULL; const int damped = damp > 0.0; const double damp_min = ls->damp_min; const double damp2 = damp * damp; const double zero = 0.0; double damp_actual; double beta1, beta2; // LSQR outputs int istop; // Termination flag. double anorm; // Estimate of Frobenious norm of Abar. double acond; // Estimate of condition no. of Abar. double rnorm; // Estimate of the final value of norm(rbar). double xnorm; // Estimate of the norm of the final solution dx. // Set r(m+1:) <- - 1/beta c + damp^2/beta x, where // beta = max(min_damp, damp). // Note that r is declared length (m+n), so there is always enough // space. The chosen damping parameter is stored in // ls->damp_actual so that it can be used in bcls_aprod_free. if (!damped && !linear) { mpn = m; ls->damp_actual = 0.0; } else { mpn = m + nFree; //-------------------------------------------------------------- // Rescale the RHS. Will need to unscale LSQR's solution later. //-------------------------------------------------------------- if (rescaling_method) { if (linear) { unscale_dxFree = 1; damp_actual = fmax( damp, damp_min ); ls->damp_actual = damp_actual; // r(1:m) = damp_actual * r(1:m) cblas_dscal( m, damp_actual, r, 1 ); // r(m+1:) = - c for (j = 0; j < nFree; j++ ) r[m+j] = - c[ ix[j] ]; // r(m+1:) = - c - damp^2 * x if (damped) for (j = 0; j < nFree; j++) r[m+j] -= damp2 * x[ ix[j] ]; } else { ls->damp_actual = damp; for (j = 0; j < nFree; j++) r[m+j] = - damp * x[ ix[j] ]; } } //-------------------------------------------------------------- // No rescaling. //-------------------------------------------------------------- else { if (damped && linear) { damp_actual = fmax( damp, damp_min ); beta1 = -1.0 / damp_actual; beta2 = -damp * damp / damp_actual; ls->damp_actual = damp_actual; for (j = 0; j < nFree; j++) { k = ix[j]; r[m+j] = beta1 * c[k] + beta2 * x[k]; } } else if ( damped && !linear ) { beta2 = - damp; ls->damp_actual = damp; for (j = 0; j < nFree; j++) r[m+j] = beta2 * x[ ix[j] ]; } else if (!damped && linear ) { beta1 = - 1.0 / damp_min; ls->damp_actual = damp_min; for (j = 0; j < nFree; j++) r[m+j] = beta1 * c[ ix[j] ]; } } } // ----------------------------------------------------------------- // Solve the subproblem with LSQR. // ----------------------------------------------------------------- bcls_timer( &(ls->stopwatch[BCLS_TIMER_LSQR]), BCLS_TIMER_START ); lsqr( mpn, nFree, aprod_free_lsqr, zero, (void *)ls, r, ls->wrk_v, ls->wrk_w, dxFree, NULL, tol, tol, ls->conlim, itnLim, ls->minor_file, &istop, itns, &anorm, &acond, &rnorm, opt, &xnorm ); bcls_timer( &(ls->stopwatch[BCLS_TIMER_LSQR]), BCLS_TIMER_STOP ); // ----------------------------------------------------------------- // Cleanup and exit. First unscale dxFree if needed. // ----------------------------------------------------------------- if (rescaling_method && unscale_dxFree) cblas_dscal( nFree, 1.0/damp_actual, dxFree, 1 ); if (istop <= 3) return 0; else if (istop == 5) return 1; else return 2; }
{ "alphanum_fraction": 0.5216933446, "avg_line_length": 32.8581314879, "ext": "c", "hexsha": "9dd3448e124a12271c5d4a3e4870989d3c035a02", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-24T13:00:19.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-05T07:46:30.000Z", "max_forks_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "echristakopoulou/glslim", "max_forks_repo_path": "bcls-0.1/src/bclsqr.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "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": "echristakopoulou/glslim", "max_issues_repo_path": "bcls-0.1/src/bclsqr.c", "max_line_length": 77, "max_stars_count": 3, "max_stars_repo_head_hexsha": "ad8e783e83b881042aaf97b985e5cba9aa1e9b9a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "echristakopoulou/glslim", "max_stars_repo_path": "bcls-0.1/src/bclsqr.c", "max_stars_repo_stars_event_max_datetime": "2022-01-04T04:45:41.000Z", "max_stars_repo_stars_event_min_datetime": "2019-12-16T01:56:55.000Z", "num_tokens": 2834, "size": 9496 }
#include "asf_sar.h" #include <asf.h> #include <asf_meta.h> #include <asf_raster.h> #include <glib.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_statistics_double.h> #include <assert.h> static double min2(double a, double b) { return a<b ? a : b; } static double min4(double a, double b, double c, double d) { return min2(min2(a,b), min2(c,d)); } static double max2(double a, double b) { return a>b ? a : b; } static double max4(double a, double b, double c, double d) { return max2(max2(a,b), max2(c,d)); } static void ts2ls(meta_parameters *meta, double time, double slant, double *pLine, double *pSamp) { double lat, lon; meta_timeSlantDop2latLon(meta, time, slant, 0, 0, &lat, &lon); meta_get_lineSamp(meta, lat, lon, 0, pLine, pSamp); //printf("ts2ls: %f,%f -> %f,%f -> %f,%f\n", // time,slant, lat,lon, *pLine,*pSamp); } static int proj_to_sr(const char *infile, const char *outfile, double pixel_size) { int ii, jj, kk; const float_image_sample_method_t sampling_method = FLOAT_IMAGE_SAMPLE_METHOD_BILINEAR; // overall algorithm: // 1. find extents in time/slant space // 2. for each pixel in output, resample in input space meta_parameters *inMeta = meta_read(infile); int nl = inMeta->general->line_count; int ns = inMeta->general->sample_count; if (!inMeta->projection && !inMeta->transform) asfPrintError("Expected a projection/transform block!\n"); if (!inMeta->state_vectors) asfPrintError("Input data does not have state vectors!\n"); //asfPrintStatus("Converting %s to slant range...\n", infile); // first, find extents in time/slant space // do this by projecting image corners to time/slant int tl_x=0, tl_y=0; int tr_x=ns-1, tr_y=0; int bl_x=0, bl_y=nl-1; int br_x=ns-1, br_y=nl-1; // we have to find the "real" corners of the image // do this using the first band of the input image as a reference if (inMeta->general->band_count == 1) asfPrintStatus("Tiling the input image...\n"); else asfPrintStatus("Tiling the reference band of the input image...\n"); FloatImage *in = float_image_new_from_metadata(inMeta, infile); // find top left pixel -- TOP-most non-no-data pixel in the image for (ii=0; ii<nl; ++ii) for (jj=0; jj<ns; ++jj) { double val = float_image_get_pixel(in, jj, ii); if (val != inMeta->general->no_data && val != 0.0) { tl_x = jj; tl_y = ii; goto found_tl; } } asfPrintError("Couldn't find top-left pixel! Entire image no data?\n"); found_tl: // find top right pixel -- RIGHT-most non-no-data pixel in the image for (jj=ns-1; jj>=0; --jj) for (ii=0; ii<nl; ++ii) { double val = float_image_get_pixel(in, jj, ii); if (val != inMeta->general->no_data && val != 0.0) { tr_x = jj; tr_y = ii; goto found_tr; } } asfPrintError("Couldn't find top-right pixel! Entire image no data?\n"); found_tr: // find bottom left pixel -- LEFT-most non-no-data pixel in the image for (jj=0; jj<ns; ++jj) for (ii=nl-1; ii>=0; --ii) { double val = float_image_get_pixel(in, jj, ii); if (val != inMeta->general->no_data && val != 0.0) { bl_x = jj; bl_y = ii; goto found_bl; } } asfPrintError("Couldn't find bottom-left pixel! Entire image no data?\n"); found_bl: // find bottom right pixel -- BOTTOM-most non-no-data pixel in the image for (ii=nl-1; ii>=0; --ii) for (jj=ns-1; jj>=0; --jj) { double val = float_image_get_pixel(in, jj, ii); if (val != inMeta->general->no_data && val != 0.0) { br_x = jj; br_y = ii; goto found_br; } } asfPrintError("Couldn't find bottom-right pixel! Entire image no data?\n"); found_br: asfPrintStatus("Determining image extents in time/slant coordinates.\n"); //asfPrintStatus("Corners are at: TL (%d,%d)\n", tl_y, tl_x); //asfPrintStatus(" (line,sample) TR (%d,%d)\n", tr_y, tr_x); //asfPrintStatus(" BL (%d,%d)\n", bl_y, bl_x); //asfPrintStatus(" BR (%d,%d)\n", br_y, br_x); double tl_time, tl_slant; double tr_time, tr_slant; double bl_time, bl_slant; double br_time, br_slant; meta_get_timeSlantDop(inMeta, tl_y, tl_x, &tl_time, &tl_slant, NULL); meta_get_timeSlantDop(inMeta, tr_y, tr_x, &tr_time, &tr_slant, NULL); meta_get_timeSlantDop(inMeta, bl_y, bl_x, &bl_time, &bl_slant, NULL); meta_get_timeSlantDop(inMeta, br_y, br_x, &br_time, &br_slant, NULL); //asfPrintStatus("Corners are at: TL (%f,%f)\n", tl_time, tl_slant); //asfPrintStatus(" (time,slant) TR (%f,%f)\n", tr_time, tr_slant); //asfPrintStatus(" BL (%f,%f)\n", bl_time, bl_slant); //asfPrintStatus(" BR (%f,%f)\n", br_time, br_slant); double slant_start = min4(tl_slant, tr_slant, bl_slant, br_slant); double slant_end = max4(tl_slant, tr_slant, bl_slant, br_slant); double time_min = min4(tl_time, tr_time, bl_time, br_time); double time_max = max4(tl_time, tr_time, bl_time, br_time); double slant_incr; double time_start, time_end, time_incr; int onl, ons; if (pixel_size > 0) { slant_incr = pixel_size; ons = (slant_end - slant_start) / slant_incr; if (inMeta->sar) { // in this case, the original data has a SAR block, we will use the // same azimuth time per pixel. time_incr = inMeta->sar->azimuth_time_per_pixel; // we always want to be DECREASING in time // latest time is on top (line 1), earliest on bottom (line ONL) if (time_incr > 0) { time_incr = -time_incr; inMeta->sar->azimuth_time_per_pixel = -inMeta->sar->azimuth_time_per_pixel; } time_start = time_max; time_end = time_min; onl = (time_end - time_start) / time_incr; } else { // here, no sar block in the original data, just make a square // image with decreasing time onl = ons; time_incr = (time_min - time_max) / (double)onl; time_start = time_max; time_end = time_min; } } else { // not provided a slant range pixel size, we'll figure something out if (inMeta->sar) { // use the same azimuth time per pixel. time_incr = inMeta->sar->azimuth_time_per_pixel; // we always want to be DECREASING in time // latest time is on top (line 1), earliest on bottom (line ONL) if (time_incr > 0) { time_incr = -time_incr; inMeta->sar->azimuth_time_per_pixel = -inMeta->sar->azimuth_time_per_pixel; } time_start = time_max; time_end = time_min; onl = (time_end - time_start) / time_incr; } else { // no info... determine azimuth time per pixel by keeping // the height the same as in the original image onl = nl; time_incr = (time_min - time_max) / (double)onl; time_start = time_max; time_end = time_min; } // make it square, to get the slant range pixel size ons = onl; pixel_size = slant_incr = (slant_end - slant_start) / (double)ons; } asfRequire(onl > 0, "Internal Error: Invalid output line count: %d\n", onl); asfRequire(ons > 0, "Internal Error: Invalid output sample count: %d\n", ons); asfPrintStatus(" Slant range values: %f -> %f\n", slant_start, slant_end); asfPrintStatus(" Slant range pixel size: %f\n", pixel_size); asfPrintStatus(" Time values: %f -> %f\n", time_start, time_end); asfPrintStatus(" Output Image will be %5d x %5d LxS\n", onl, ons); asfPrintStatus(" (Input Image was %5d x %5d LxS)\n", nl, ns); // generate a grid over the image, to generate our splines // this grid size seems to work pretty well... int n = 120; asfPrintStatus("Creating %dx%d mapping grid...\n", n, n); double time_grid_incr = ((double)(onl))/((double)(n)) * time_incr; double slant_grid_incr = ((double)(ons))/((double)(n)) * slant_incr; // allocating memory for the splines, and the arrays to generate them gsl_interp_accel **samp_accels = MALLOC(sizeof(gsl_interp_accel *) * n); gsl_spline **samp_splines = MALLOC(sizeof(gsl_spline *) * n); gsl_interp_accel **line_accels = MALLOC(sizeof(gsl_interp_accel *) * n); gsl_spline **line_splines = MALLOC(sizeof(gsl_spline *) * n); double *slant_in = MALLOC(sizeof(double)*n); double *line_out = MALLOC(sizeof(double)*n); double *samp_out = MALLOC(sizeof(double)*n); // an alias -- use the same array (to save memory -- these are not used // at the same time), but create an alias for it, so it is not so confusing double *time_in = slant_in; //double max_err = 0; // set up the vertical splines for (jj=0; jj<n; ++jj) { double slant = slant_start + jj*slant_grid_incr; for (ii=0; ii<n; ++ii) { // splines need strictly increasing range variables if (time_grid_incr > 0) time_in[ii] = time_start + ii*time_grid_incr; else time_in[ii] = time_end - ii*time_grid_incr; ts2ls(inMeta, time_in[ii], slant, &line_out[ii], &samp_out[ii]); } samp_accels[jj] = gsl_interp_accel_alloc(); samp_splines[jj] = gsl_spline_alloc(gsl_interp_cspline, n); gsl_spline_init(samp_splines[jj], time_in, samp_out, n); line_accels[jj] = gsl_interp_accel_alloc(); line_splines[jj] = gsl_spline_alloc(gsl_interp_cspline, n); gsl_spline_init(line_splines[jj], time_in, line_out, n); } // now, we're on to the resampling stage.. loop through output pixels asfPrintStatus("Generating slant range image...\n"); double no_data_value = meta_is_valid_double(inMeta->general->no_data) ? inMeta->general->no_data : 0; // keep track of error sizes double max_error = 0; double avg_error = 0; int count = 0; // these stride values allow us to track when we're in between grid points int ii_n = onl/n; int jj_n = ons/n; int ii_n2 = ii_n/2; int jj_n2 = jj_n/2; // set up output metadata meta_parameters *outMeta = meta_read(infile); if (outMeta->transform) { FREE(outMeta->transform); outMeta->transform = NULL; } if (outMeta->projection) { FREE(outMeta->projection); outMeta->projection = NULL; } outMeta->general->line_count = onl; outMeta->general->sample_count = ons; if (!outMeta->sar) outMeta->sar = meta_sar_init(); outMeta->sar->image_type = 'S'; outMeta->sar->azimuth_time_per_pixel = time_incr; assert(outMeta->sar->azimuth_time_per_pixel < 0); outMeta->sar->time_shift = time_start; outMeta->general->y_pixel_size = inMeta->sar->azimuth_time_per_pixel / time_incr * inMeta->general->y_pixel_size; assert(outMeta->general->y_pixel_size > 0); outMeta->sar->slant_range_first_pixel = slant_start; outMeta->general->x_pixel_size = slant_incr; outMeta->sar->line_increment = outMeta->sar->sample_increment = 1; outMeta->general->start_sample = outMeta->general->start_line = 0; outMeta->general->no_data = no_data_value; char **band_name = extract_band_names(inMeta->general->bands, inMeta->general->band_count); // now generate output image char *img_file = appendExt(outfile, ".img"); float *out = MALLOC(sizeof(float) * ons); for (kk=0; kk<inMeta->general->band_count; ++kk) { if (inMeta->general->band_count != 1) asfPrintStatus("Working on band: %s\n", band_name[kk]); // for the 2nd and higher bands, free the band from the previous iteration, // and read in the next band from the input image if (kk>0) { float_image_free(in); asfPrintStatus("Loading input...\n"); in = float_image_band_new_from_metadata(inMeta, kk, infile); } FILE *ofp = FOPEN(img_file, kk==0 ? "wb" : "ab"); asfPrintStatus("Generating output...\n"); for (ii=0; ii<onl; ++ii) { asfLineMeter(ii,onl); double time = time_start + ii * time_incr; // set up horizontal splines for this row gsl_interp_accel *samp_accel = gsl_interp_accel_alloc(); gsl_spline *samp_spline = gsl_spline_alloc(gsl_interp_cspline, n); gsl_interp_accel *line_accel = gsl_interp_accel_alloc(); gsl_spline *line_spline = gsl_spline_alloc(gsl_interp_cspline, n); //printf("time: %f slant: %f\n", time, slant_start); for (jj=0; jj<n; ++jj) { slant_in[jj] = slant_start + jj * slant_grid_incr; //printf("time: %f slant: %f\n", time, slant_in[jj]); samp_out[jj] = gsl_spline_eval(samp_splines[jj], time, samp_accels[jj]); line_out[jj] = gsl_spline_eval(line_splines[jj], time, line_accels[jj]); //printf("samp_out: %f line_out: %f\n", samp_out[jj], line_out[jj]); } gsl_spline_init(samp_spline, slant_in, samp_out, n); gsl_spline_init(line_spline, slant_in, line_out, n); // use the splines to produce output pixels for (jj=0; jj<ons; ++jj) { double slant = slant_start + jj * slant_incr; double samp = gsl_spline_eval(samp_spline, slant, samp_accel); double line = gsl_spline_eval(line_spline, slant, line_accel); // check the spline every so often (halfway between grid points) // only do this on band #1 (the reference band) if (kk==0 && ii%ii_n2==0 && ii%ii_n!=0 && jj%jj_n2==0 && jj%jj_n!=0) { double samp_real, line_real; ts2ls(inMeta, time, slant, &line_real, &samp_real); double err = (line-line_real)*(line-line_real) + (samp-samp_real)*(samp-samp_real); //printf("(%d,%d) -- Actual: (%f,%f) Splined: (%f,%f)\n", // ii, jj, line_real, samp_real, line, samp); if (err > max_error) max_error = err; avg_error += err; ++count; } // now interpolate within the original image // if we are outside, use "no_data" from metadata double val = no_data_value; if (line > 0 && line < nl-1 && samp > 0 && samp < ns-1) val = float_image_sample(in, samp, line, sampling_method); out[jj] = (float)val; } gsl_interp_accel_free(samp_accel); gsl_spline_free(samp_spline); gsl_interp_accel_free(line_accel); gsl_spline_free(line_spline); put_float_line(ofp, outMeta, ii, out); } fclose(ofp); } // free the last band of the input float_image_free(in); FREE(slant_in); FREE(line_out); FREE(samp_out); for (ii=0; ii<n; ++ii) { gsl_interp_accel_free(samp_accels[ii]); gsl_spline_free(samp_splines[ii]); gsl_interp_accel_free(line_accels[ii]); gsl_spline_free(line_splines[ii]); } FREE(samp_accels); FREE(samp_splines); FREE(line_accels); FREE(line_splines); FREE(out); for (kk=0; kk<inMeta->general->band_count; ++kk) FREE(band_name[kk]); FREE(band_name); // see how bad our errors were avg_error /= (double)count; asfPrintStatus("Model max error: %f, avg: %f\n", max_error, avg_error); double thresh = 0.1; if (max_error > 100*thresh) asfPrintError("Maximum error exceeded threshold: %f > %f\n", max_error, 100*thresh); else if (avg_error > 10*thresh) asfPrintError("Average error exceeded threshold: %f > %f\n", avg_error, 10*thresh); if (max_error > 10*thresh) asfPrintWarning("Maximum error exceeds threshold: %f > %f\n", max_error, 10*thresh); if (avg_error > thresh) asfPrintWarning("Average error exceeds threshold: %f > %f\n", avg_error, thresh); char *meta_file = appendExt(outfile, ".meta"); asfPrintStatus("Writing %s\n", meta_file); meta_write(outMeta, meta_file); free(meta_file); free(img_file); meta_free(outMeta); meta_free(inMeta); return 0; //success } int to_sr_pixsiz(const char *infile, const char *outfile, double pixel_size) { meta_parameters *inMeta = meta_read(infile); int ret; if (inMeta->sar && inMeta->sar->image_type == 'G') { // ground range image ret = gr2sr_pixsiz(infile, outfile, pixel_size); } else if (inMeta->sar && inMeta->sar->image_type == 'S') { // already a slant range image, just copy it copyImgAndMeta(infile, outfile); ret = 0; // success } else if ((inMeta->sar && inMeta->sar->image_type == 'P') || (inMeta->projection)) { // projected image ret = proj_to_sr(infile, outfile, pixel_size); } else if (inMeta->sar && inMeta->transform && inMeta->sar->image_type == 'R') { // georeferenced, ALOS most likely ret = proj_to_sr(infile, outfile, pixel_size); } else { asfPrintError("Couldn't figure out what kind of image this is.\n"); ret = 1; } meta_free(inMeta); return ret; } int to_sr(const char *infile, const char *outfile) { char *img_in = MALLOC(sizeof(char)*(strlen(infile)+10)); char *img_out = MALLOC(sizeof(char)*(strlen(outfile)+10)); create_name(img_in, infile, ".img"); create_name(img_out, outfile, ".img"); int ret = to_sr_pixsiz(img_in, img_out, -1); FREE(img_in); FREE(img_out); return ret; }
{ "alphanum_fraction": 0.5859174508, "avg_line_length": 34.7012987013, "ext": "c", "hexsha": "8cb62f489f05b1722ea4e68bdae5136e024ce34b", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/libasf_sar/to_sr.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/libasf_sar/to_sr.c", "max_line_length": 84, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/libasf_sar/to_sr.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 5143, "size": 18704 }
#pragma once #include "icode_generator.h" #include <halley/data_structures/hash_map.h> #include <gsl/gsl> #include "halley/file/path.h" namespace YAML { class Node; } namespace Halley { class ECSData; class ComponentSchema; class SystemSchema; class MessageSchema; class CustomTypeSchema; class Codegen { struct Stats { int written = 0; int skipped = 0; Vector<Path> files; }; public: constexpr static int currentCodegenVersion = 105; using ProgressReporter = std::function<bool(float, String)>; static void run(Path inDir, Path outDir); static Vector<Path> generateCode(const ECSData& data, Path directory); private: static bool writeFile(const Path& path, gsl::span<const char> data, bool stub); static void writeFiles(const Path& directory, const CodeGenResult& files, Stats& stats); static int getHeaderVersion(gsl::span<const char> data, size_t& endOfHeader); }; }
{ "alphanum_fraction": 0.7318132465, "avg_line_length": 21.4186046512, "ext": "h", "hexsha": "905a50a41d8ffa6022be5986fb7c1c2e2ffd0465", "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": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "amrezzd/halley", "max_forks_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "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": "amrezzd/halley", "max_issues_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "amrezzd/halley", "max_stars_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 232, "size": 921 }
/* interpolation/bsearch.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 <stdlib.h> #include <gsl/gsl_interp.h> #ifndef HIDE_INLINE_STATIC size_t gsl_interp_bsearch ( const double x_array[], double x, size_t index_lo, size_t index_hi ) { size_t ilo = index_lo; size_t ihi = index_hi; while (ihi > ilo + 1) { size_t i = (ihi + ilo) / 2; if (x_array[i] > x) ihi = i; else ilo = i; } return ilo; } #endif
{ "alphanum_fraction": 0.6835341365, "avg_line_length": 25.9375, "ext": "c", "hexsha": "c4c05c0009edea45bef52c7532c6c365977c84ea", "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/interpolation/bsearch.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/interpolation/bsearch.c", "max_line_length": 72, "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/interpolation/bsearch.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": 348, "size": 1245 }
#include "cwc.h" #include "../ccv_internal.h" #ifdef HAVE_GSL #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #endif #include "cwc_ext.h" #ifdef USE_DISPATCH #include <dispatch/dispatch.h> #endif #ifdef HAVE_GSL static void _cwc_convnet_random_image_manipulation(gsl_rng* rng, ccv_dense_matrix_t* image, float image_manipulation) { assert(rng && CCV_GET_CHANNEL(image->type) == CCV_C3 && image_manipulation > 0 && image_manipulation <= 1); int ord[3] = {0, 1, 2}; gsl_ran_shuffle(rng, ord, 3, sizeof(int)); int i; for (i = 0; i < 3; i++) // change the applying order switch (ord[i]) { case 0: // introduce some brightness changes to the original image ccv_scale(image, (ccv_matrix_t**)&image, 0, gsl_rng_uniform_pos(rng) * image_manipulation * 2 + (1 - image_manipulation)); break; case 1: // introduce some saturation changes to the original image ccv_saturation(image, &image, 0, gsl_rng_uniform_pos(rng) * image_manipulation * 2 + (1 - image_manipulation)); break; case 2: // introduce some contrast changes to the original image ccv_contrast(image, &image, 0, gsl_rng_uniform_pos(rng) * image_manipulation * 2 + (1 - image_manipulation)); break; } } void cwc_convnet_batch_formation(gsl_rng* rng, ccv_array_t* categorizeds, ccv_dense_matrix_t* mean_activity, ccv_dense_matrix_t* eigenvectors, ccv_dense_matrix_t* eigenvalues, float image_manipulation, float color_gain, int* idx, ccv_size_t dim, int min_dim, int max_dim, int rows, int cols, int channels, int category_count, int symmetric, int batch, int offset, int size, float* b, int* c) { assert(size > 0 && size <= batch); assert(min_dim >= rows && min_dim >= cols); assert(max_dim >= min_dim); float* channel_gains = (float*)alloca(sizeof(float) * channels * size); memset(channel_gains, 0, sizeof(float) * channels * size); int i; gsl_rng** rngs = (gsl_rng**)alloca(sizeof(gsl_rng*) * size); memset(rngs, 0, sizeof(gsl_rng*) * size); if (rng) for (i = 0; i < size; i++) { rngs[i] = gsl_rng_alloc(gsl_rng_default); gsl_rng_set(rngs[i], gsl_rng_get(rng)); } parallel_for(i, size) { int j, k; assert(offset + i < categorizeds->rnum); ccv_categorized_t* categorized = (ccv_categorized_t*)ccv_array_get(categorizeds, idx ? idx[offset + i] : offset + i); assert(categorized->c < category_count && categorized->c >= 0); // now only accept classes listed if (c) c[i] = categorized->c; ccv_dense_matrix_t* image = 0; switch (categorized->type) { case CCV_CATEGORIZED_DENSE_MATRIX: image = categorized->matrix; break; case CCV_CATEGORIZED_FILE: image = 0; ccv_read(categorized->file.filename, &image, CCV_IO_ANY_FILE | CCV_IO_RGB_COLOR); break; } if (image) { // first resize to between min_dim and max_dim ccv_dense_matrix_t* input = 0; ccv_size_t resize = dim; if (rngs[i]) // randomize the resized dimensions { int d = gsl_rng_uniform_int(rngs[i], max_dim - min_dim + 1) + min_dim; resize = ccv_size(d, d); } // if neither side is the same as expected, we have to resize first if (resize.height != image->rows && resize.width != image->cols) ccv_convnet_input_formation(resize, image, &input); else input = image; if (rngs[i] && image_manipulation > 0) _cwc_convnet_random_image_manipulation(rngs[i], input, image_manipulation); ccv_dense_matrix_t* patch = 0; if (input->cols != cols || input->rows != rows) { int x = rngs[i] ? gsl_rng_uniform_int(rngs[i], input->cols - cols + 1) : (input->cols - cols + 1) / 2; int y = rngs[i] ? gsl_rng_uniform_int(rngs[i], input->rows - rows + 1) : (input->rows - rows + 1) / 2; ccv_slice(input, (ccv_matrix_t**)&patch, CCV_32F, y, x, rows, cols); } else ccv_shift(input, (ccv_matrix_t**)&patch, CCV_32F, 0, 0); // converting to 32f if (input != image) // only unload if we created new input ccv_matrix_free(input); // we loaded image in, deallocate it now if (categorized->type != CCV_CATEGORIZED_DENSE_MATRIX) ccv_matrix_free(image); // random horizontal reflection if (symmetric && rngs[i] && gsl_rng_uniform_int(rngs[i], 2) == 0) ccv_flip(patch, &patch, 0, CCV_FLIP_X); int x = rngs[i] ? gsl_rng_uniform_int(rngs[i], mean_activity->cols - cols + 1) : (mean_activity->cols - cols + 1) / 2; int y = rngs[i] ? gsl_rng_uniform_int(rngs[i], mean_activity->rows - rows + 1) : (mean_activity->rows - rows + 1) / 2; ccv_dense_matrix_t mean_patch = ccv_reshape(mean_activity, y, x, rows, cols); ccv_subtract(patch, &mean_patch, (ccv_matrix_t**)&patch, 0); assert(channels == CCV_GET_CHANNEL(patch->type)); if (color_gain > 0 && rngs[i] && eigenvectors && eigenvalues) { assert(channels == 3); // only support RGB color gain memset(channel_gains + channels * i, 0, sizeof(float) * channels); for (j = 0; j < channels; j++) { float alpha = gsl_ran_gaussian(rngs[i], color_gain) * eigenvalues->data.f64[j]; for (k = 0; k < channels; k++) channel_gains[k + i * channels] += eigenvectors->data.f64[j * channels + k] * alpha; } } for (j = 0; j < channels; j++) for (k = 0; k < rows * cols; k++) b[(j * rows * cols + k) * batch + i] = patch->data.f32[k * channels + j] + channel_gains[j + i * channels]; ccv_matrix_free(patch); } else PRINT(CCV_CLI_ERROR, "cannot load %s.\n", categorized->file.filename); } parallel_endfor if (rng) for (i = 0; i < size; i++) gsl_rng_free(rngs[i]); } #endif void cwc_convnet_mean_formation(ccv_array_t* categorizeds, ccv_size_t dim, int channels, int symmetric, ccv_dense_matrix_t** b) { int i, count = 0; ccv_dense_matrix_t* c = ccv_dense_matrix_new(dim.height, dim.width, channels | CCV_64F, 0, 0); ccv_zero(c); ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, dim.height, dim.width, channels | CCV_32F, channels | CCV_32F, 0); for (i = 0; i < categorizeds->rnum; i++) { if (i % 23 == 0 || i == categorizeds->rnum - 1) FLUSH(CCV_CLI_INFO, " - compute mean activity %d / %d", i + 1, categorizeds->rnum); ccv_categorized_t* categorized = (ccv_categorized_t*)ccv_array_get(categorizeds, i); ccv_dense_matrix_t* image = 0; switch (categorized->type) { case CCV_CATEGORIZED_DENSE_MATRIX: image = categorized->matrix; break; case CCV_CATEGORIZED_FILE: ccv_read(categorized->file.filename, &image, CCV_IO_ANY_FILE | CCV_IO_RGB_COLOR); break; } if (!image) { PRINT(CCV_CLI_ERROR, "cannot load %s.\n", categorized->file.filename); continue; } ccv_dense_matrix_t* patch = 0; if (image->cols != dim.width || image->rows != dim.height) { int x = (image->cols - dim.width + 1) / 2; int y = (image->rows - dim.height + 1) / 2; assert(x == 0 || y == 0); ccv_slice(image, (ccv_matrix_t**)&patch, CCV_32F, y, x, dim.height, dim.width); } else ccv_shift(image, (ccv_matrix_t**)&patch, CCV_32F, 0, 0); // converting to 32f if (categorized->type != CCV_CATEGORIZED_DENSE_MATRIX) ccv_matrix_free(image); ccv_add(patch, c, (ccv_matrix_t**)&c, CCV_64F); ++count; ccv_matrix_free(patch); } if (symmetric) { int j, k; double p = 0.5 / count; double* cptr = c->data.f64; float* dbptr = db->data.f32; for (i = 0; i < db->rows; i++) { for (j = 0; j < db->cols; j++) for (k = 0; k < channels; k++) dbptr[j * channels + k] = p * (cptr[j * channels + k] + cptr[(c->cols - j - 1) * channels + k]); dbptr += db->cols * channels; cptr += c->cols * channels; } } else { double p = 1.0 / count; for (i = 0; i < dim.height * dim.width * channels; i++) db->data.f32[i] = p * c->data.f64[i]; } ccv_matrix_free(c); PRINT(CCV_CLI_INFO, "\n"); } void cwc_convnet_channel_eigen(ccv_array_t* categorizeds, ccv_dense_matrix_t* mean_activity, ccv_size_t dim, int channels, ccv_dense_matrix_t** eigenvectors, ccv_dense_matrix_t** eigenvalues) { assert(channels == 3); // this function cannot handle anything other than 3x3 covariance matrix double* mean_value = (double*)alloca(sizeof(double) * channels); memset(mean_value, 0, sizeof(double) * channels); assert(CCV_GET_CHANNEL(mean_activity->type) == channels); assert(mean_activity->rows == dim.height); assert(mean_activity->cols == dim.width); int i, j, k, c, count = 0; for (i = 0; i < dim.height * dim.width; i++) for (k = 0; k < channels; k++) mean_value[k] += mean_activity->data.f32[i * channels + k]; for (i = 0; i < channels; i++) mean_value[i] = mean_value[i] / (dim.height * dim.width); double* covariance = (double*)alloca(sizeof(double) * channels * channels); memset(covariance, 0, sizeof(double) * channels * channels); for (c = 0; c < categorizeds->rnum; c++) { if (c % 23 == 0 || c == categorizeds->rnum - 1) FLUSH(CCV_CLI_INFO, " - compute covariance matrix for data augmentation (color gain) %d / %d", c + 1, categorizeds->rnum); ccv_categorized_t* categorized = (ccv_categorized_t*)ccv_array_get(categorizeds, c); ccv_dense_matrix_t* image = 0; switch (categorized->type) { case CCV_CATEGORIZED_DENSE_MATRIX: image = categorized->matrix; break; case CCV_CATEGORIZED_FILE: ccv_read(categorized->file.filename, &image, CCV_IO_ANY_FILE | CCV_IO_RGB_COLOR); break; } if (!image) { PRINT(CCV_CLI_ERROR, "cannot load %s.\n", categorized->file.filename); continue; } ccv_dense_matrix_t* patch = 0; if (image->cols != dim.width || image->rows != dim.height) { int x = (image->cols - dim.width + 1) / 2; int y = (image->rows - dim.height + 1) / 2; assert(x == 0 || y == 0); ccv_slice(image, (ccv_matrix_t**)&patch, CCV_32F, y, x, dim.height, dim.width); } else ccv_shift(image, (ccv_matrix_t**)&patch, CCV_32F, 0, 0); // converting to 32f if (categorized->type != CCV_CATEGORIZED_DENSE_MATRIX) ccv_matrix_free(image); for (i = 0; i < dim.width * dim.height; i++) for (j = 0; j < channels; j++) for (k = j; k < channels; k++) covariance[j * channels + k] += (patch->data.f32[i * channels + j] - mean_value[j]) * (patch->data.f32[i * channels + k] - mean_value[k]); ++count; ccv_matrix_free(patch); } for (i = 0; i < channels; i++) for (j = 0; j < i; j++) covariance[i * channels + j] = covariance[j * channels + i]; double p = 1.0 / ((double)count * dim.height * dim.width); for (i = 0; i < channels; i++) for (j = 0; j < channels; j++) covariance[i * channels + j] *= p; // scale down ccv_dense_matrix_t covm = ccv_dense_matrix(3, 3, CCV_64F | CCV_C1, covariance, 0); ccv_eigen(&covm, eigenvectors, eigenvalues, CCV_64F, 1e-8); PRINT(CCV_CLI_INFO, "\n"); }
{ "alphanum_fraction": 0.6598414795, "avg_line_length": 40.2965779468, "ext": "c", "hexsha": "0a1c5d32df1fe6511c9dbb8d92652d7d07eff2a2", "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": "7fb761f4d8188776dd42b8a06b07ecda7840cd3c", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "ChiahungTai/ccv", "max_forks_repo_path": "lib/cuda/cwc_convnet_ext.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "7fb761f4d8188776dd42b8a06b07ecda7840cd3c", "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": "ChiahungTai/ccv", "max_issues_repo_path": "lib/cuda/cwc_convnet_ext.c", "max_line_length": 391, "max_stars_count": null, "max_stars_repo_head_hexsha": "7fb761f4d8188776dd42b8a06b07ecda7840cd3c", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "ChiahungTai/ccv", "max_stars_repo_path": "lib/cuda/cwc_convnet_ext.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3471, "size": 10598 }
// clang -DHAVE_INLINE -O3 mussel.c -o mussel -lgsl -lgslcblas #include <stdio.h> #include <stdlib.h> #include <time.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> int main(int argc, char *argv[]) { // Setup the random number generator: gsl_rng_env_setup(); gsl_rng *rng = gsl_rng_alloc(gsl_rng_taus2); const unsigned int seed = (argc == 2)? atof(argv[1]) : time(NULL); gsl_rng_set(rng, seed); // Parameters: const int T = 1000; const double A0 = 0.5; const double A1 = 0.025; const double A2 = 0.2; const int N = 1000; const int TWO_N = N * N; // Allocate memory for the matrix: int **m = (int**)malloc(N * sizeof(int*)); int i; for (i = 0; i < N; ++i) { m[i] = (int*)malloc(N * sizeof(int)); } // Fill the matrix: int x0, y0; for (x0 = 0; x0 < N; ++x0) { for (y0 = 0; y0 < N; ++y0) { m[x0][y0] = (gsl_rng_uniform(rng) < 0.5) ? 0 : 2; } } // Main loop int n, x, y, x1, y1, t, cell; for (t = 0; t < T; ++t) { // Loop around the lattice at random to update cells; for (cell = 0; cell < TWO_N; ++cell) { // Select at random the cell to update x0 = (int)(gsl_rng_uniform(rng) * N); y0 = (int)(gsl_rng_uniform(rng) * N); // Update the mussels // Disturbed cells automatically transformed into empty cells if (m[x0][y0] == 0) { m[x0][y0] = 1; } else if (m[x0][y0] == 1) // If the cell is empty, test if there is colonization { // First calculate the number of neighbours n = 0; for (x = -1; x <= 1; ++x) { for (y = -1; y <= 1; ++y) { if (x0 + x == -1) { x1 = N - 1; } else if (x0 + x == N) { x1 = 0; } else { x1 = x0 + x; } if (y0 + y == -1) { y1 = N - 1; } else if (y0 + y == N) { y1 = 0; } else { y1 = y0 + y; } if (x != 0 && y != 0 && m[x1][y1] == 2) { ++n; } } } // Calculate if the status if the cell is changed if (gsl_rng_uniform(rng) < A2 * n * 0.125) { m[x0][y0] = 2; } } else if (m[x0][y0] == 2) { // If the cell is occupied, test if there is disturbance n = 0; for (x = -1; x <= 1; x++) { for (y = -1; y <= 1; y++) { if (x0 + x == -1) { x1 = N - 1; } else if (x0 + x == N) { x1 = 0; } else { x1 = x0 + x; } if (y0 + y == -1) { y1 = N - 1; } else if (y0 + y == N) { y1 = 0; } else { y1 = y0 + y; } if (x != 0 && y != 0 && m[x1][y1] == 0) { n = 1; } } } // Calculate if the status of the cell is changed if (gsl_rng_uniform(rng) < A0 * n * 0.125 + A1) { m[x0][y0] = 0; } } } } char buffer[100]; sprintf(buffer, "mussel-%u.txt", seed); FILE *out = fopen(buffer, "w"); for (x0 = 0; x0 < N; ++x0) { for (y0 = 0; y0 < N; ++y0) { fprintf(out, "%d ", m[x0][y0]); } fprintf(out, "\n"); } fclose(out); gsl_rng_free(rng); for (i = 0; i < N; ++i) { free(m[i]); } free(m); return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.29195449, "avg_line_length": 27.8079096045, "ext": "c", "hexsha": "7fd8ab96831e1b678ae842aa5a45e6e59a2df959", "lang": "C", "max_forks_count": 51, "max_forks_repo_forks_event_max_datetime": "2022-01-17T06:15:11.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-13T12:21:00.000Z", "max_forks_repo_head_hexsha": "ba09fe2f2274d89eb38d57bde9063d77ae789a7e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "bh6025/CUDA-training", "max_forks_repo_path": "ecology/mussel/mussel.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ba09fe2f2274d89eb38d57bde9063d77ae789a7e", "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": "bh6025/CUDA-training", "max_issues_repo_path": "ecology/mussel/mussel.c", "max_line_length": 91, "max_stars_count": 21, "max_stars_repo_head_hexsha": "ba09fe2f2274d89eb38d57bde9063d77ae789a7e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "vadmus/cuda_examples", "max_stars_repo_path": "ecology/mussel/mussel.c", "max_stars_repo_stars_event_max_datetime": "2022-03-15T14:32:35.000Z", "max_stars_repo_stars_event_min_datetime": "2015-06-08T03:18:33.000Z", "num_tokens": 1220, "size": 4922 }
#ifndef UTILITIES_H #define UTILITIES_H #include <vector> #include <math.h> #include <random> #include <iostream> #include <fstream> #include <eigen3/Eigen/Dense> #include <boost/random/mersenne_twister.hpp> #include <boost/random/normal_distribution.hpp> #include <boost/math/distributions/normal.hpp> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <opencv2/opencv.hpp> #include <opencv2/ml/ml.hpp> #include "Structures.h" #include <map> using namespace std; using namespace boost::math; using namespace Eigen; using namespace cv; namespace Eigen { namespace internal { template<typename Scalar> struct scalar_normal_dist_op { static boost::mt19937 rng; // The uniform pseudo-random algorithm mutable boost::normal_distribution<Scalar> norm; // The gaussian combinator EIGEN_EMPTY_STRUCT_CTOR(scalar_normal_dist_op) template<typename Index> inline const Scalar operator() (Index, Index = 0) const { return norm(rng); } }; template<typename Scalar> boost::mt19937 scalar_normal_dist_op<Scalar>::rng; template<typename Scalar> struct functor_traits<scalar_normal_dist_op<Scalar> >{ enum{ Cost = 50 * NumTraits<Scalar>::MulCost, PacketAccess = false, IsRepeatable = false }; }; } } class Utilities{ public: Utilities(); virtual ~Utilities(); //Read a file that has a specific number of dimensions for each attribute virtual vector < vector < vector<double> > > readFile(string CloudSeperator, string filepath); double multivariateNormalPDF(Vector3d instance, Vector3d mu, Matrix3d covar, int dimensionality); Eigen::MatrixXd sampleMultivariateNormal( Eigen::VectorXd mean, Eigen::MatrixXd covar, int numOfSamples, int dimensionality); Eigen::MatrixXd sampleMultinomial(vector<double> probabilities, int samples); int randcat( vector<double> * vec); Eigen::Matrix3d iwishrnd( Matrix3d tau, double nu, int dimensionality, int df); Eigen::VectorXd exprnd(double rate, int samples); double exppdf(double x , double lambda); double gammarnd(double alpha , double beta); RowVectorXd dirrnd(RowVectorXd q0); double catpdf(int index , vector<double> probabilities); // Exponential distribution distances double Expsquaredhellinger(double lambda1, double lambda2); double ExpKLDivergence(double lambda1, double lambda2); // Gaussian distribution distances double GaussKLDivergence(std::vector<double> mean1, Matrix3d covar1, std::vector<double> mean2, Matrix3d covar2 ); double Wasserstein(std::vector<double> mean1, Matrix3d covar1, std::vector<double> mean2, Matrix3d covar2 ); vector<float> categoricalhistogramCompare( float histA[], float histB[] , int N); float categoricalKLDivergence( cv::Mat * mat1, cv::Mat * mat2); protected: private: }; #endif // UTILITIES_H
{ "alphanum_fraction": 0.694435298, "avg_line_length": 41.602739726, "ext": "h", "hexsha": "cb5de0085e1f71ce85579dc4314468b7137b9b05", "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": "415dd5156dd2d7272b5e846940fce79e8407bf8c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hadjichristslave/SMC", "max_forks_repo_path": "include/Utilities.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "415dd5156dd2d7272b5e846940fce79e8407bf8c", "max_issues_repo_issues_event_max_datetime": "2015-07-13T13:12:04.000Z", "max_issues_repo_issues_event_min_datetime": "2015-05-27T12:34:03.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "hadjichristslave/SMC", "max_issues_repo_path": "include/Utilities.h", "max_line_length": 133, "max_stars_count": null, "max_stars_repo_head_hexsha": "415dd5156dd2d7272b5e846940fce79e8407bf8c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hadjichristslave/SMC", "max_stars_repo_path": "include/Utilities.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 688, "size": 3037 }
/** * * @file core_ssetvar.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Mark Gates * @date 2010-11-15 * @generated s Tue Jan 7 11:44:49 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_float * * CORE_ssetvar sets a single variable, x := alpha. * ******************************************************************************* * * @param[in] alpha * Scalar to set x to, passed by pointer so it can depend on runtime value. * * @param[out] x * On exit, x = alpha. * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_ssetvar = PCORE_ssetvar #define CORE_ssetvar PCORE_ssetvar #endif void CORE_ssetvar(const float *alpha, float *x) { *x = *alpha; }
{ "alphanum_fraction": 0.5019723866, "avg_line_length": 24.7317073171, "ext": "c", "hexsha": "6e87f5ee11b541a6c41848582a5cfb829f6da1fb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "core_blas/core_ssetvar.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "core_blas/core_ssetvar.c", "max_line_length": 83, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_ssetvar.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 246, "size": 1014 }
#include "../globals.h" #include <gsl/gsl_sort.h> #include <gsl/gsl_sort_vector.h> #include <gsl/gsl_vector.h> void setup_Sedov_Blast() { Problem.Boxsize[0] = 3; Problem.Boxsize[1] = 3; Problem.Boxsize[2] = 3; sprintf ( Problem.Name, "IC_SedovBlast" ); const double rho = 1.24E7; Problem.Rho_Max = rho; Density_Func_Ptr = &Sedov_Blast_Density; U_Func_Ptr = &Sedov_Blast_U; PostProcessing_Func_Ptr = &Sedov_Blast_PostProcessing; } float Sedov_Blast_Density ( const int ipart , const double bias ) { return 1.24E7; } // This function calculates the distance from each particle to the center of the Box. It returns the distance to the NNpart times furthest neighbour of zero. float Sedov_Blast_abs () { int NNpart = 296; gsl_vector *abs_of_zero = gsl_vector_alloc ( Param.Npart ); for ( int i = 0; i < Param.Npart; i++ ) { double r = sqrt ( ( P[i].Pos[0] - 0.5 * Problem.Boxsize[0] ) * ( P[i].Pos[0] - 0.5 * Problem.Boxsize[0] ) + ( P[i].Pos[1] * 0.5 * Problem.Boxsize[1] ) * ( P[i].Pos[1] - 0.5 * Problem.Boxsize[1] ) + ( P[i].Pos[2] - 0.5 * Problem.Boxsize[2] ) * ( P[i].Pos[2] - 0.5 * Problem.Boxsize[2] ) ); gsl_vector_set ( abs_of_zero, i, r ); } gsl_sort_vector ( abs_of_zero ); double dist = gsl_vector_get ( abs_of_zero, NNpart - 1 ); gsl_vector_free ( abs_of_zero ); return dist; } #ifdef KINETIC_SEDOV float Sedov_Blast_kinetic () { int NNpart = 32; Radius = double partpos[3][32]; float maxDistance = Sedov_Blast_abs (); if ( Radius <= maxDistance ) { for ( int i =; i < 3; i++ ) { for ( int j = 0; j < NNpart, j++ ) { double pos = P[i].Pos[j]; partpos[i][j] = pos; } } } } #endif // KINETIC_SEDOV float Sedov_Blast_U ( const int ipart ) { return 0.0; } //! @todo improvement: use gsl_sort_vector_index void Sedov_Blast_PostProcessing () { /*const double u_sn = 4.18971E5; int sn_count = pow ( Param.Npart / 3200., 3.0 ); sn_count = min ( sn_count, 1 ); //! @todo assign u_sn to sn_count innermost particles*/ float maxDistance = Sedov_Blast_abs (); for ( int ipart = 0; ipart < Param.Npart; ++ipart ) { const double x = P[ipart].Pos[0] - Problem.Boxsize[0] * 0.5; const double y = P[ipart].Pos[1] - Problem.Boxsize[1] * 0.5; const double z = P[ipart].Pos[2] - Problem.Boxsize[2] * 0.5; double Radius = sqrt ( x * x + y * y + z * z ); // int NNpart = 32; const double Supernova_Energy = 0.00502765; // This is the value of one supernova energy per unit mass in Gadget units 1e51 erg // const double hsml = SphP[i].Hsml; if ( Radius <= maxDistance ) { SphP[ipart].U = Supernova_Energy; } } }
{ "alphanum_fraction": 0.5905923345, "avg_line_length": 24.5299145299, "ext": "c", "hexsha": "e30f533034b1c729a1122ab1707d5fc3787754e9", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-19T12:31:56.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-29T09:38:57.000Z", "max_forks_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "elehcim/WVTICs", "max_forks_repo_path": "src/problems/sedov.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_issues_repo_issues_event_max_datetime": "2021-02-23T12:22:14.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-23T12:22:14.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "elehcim/WVTICs", "max_issues_repo_path": "src/problems/sedov.c", "max_line_length": 203, "max_stars_count": 5, "max_stars_repo_head_hexsha": "91a0e46425cb38ab81dd2d289a1e886abbb07c03", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "elehcim/WVTICs", "max_stars_repo_path": "src/problems/sedov.c", "max_stars_repo_stars_event_max_datetime": "2022-03-25T08:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-29T04:44:13.000Z", "num_tokens": 913, "size": 2870 }
/* ** random swap functions ** ** M. Kuhlmann, MPI-KYB, Sept 2015 **/ #include <viaio/Vlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_combination.h> /* binomial coefficient, n choose k */ double binom (int n,int k) { double prod,ix,nx,kx; int i; nx = (double)n; kx = (double)k; prod = ix = 1; for (i=1; i<=k; i++) { prod *= (nx-kx+ix)/ix; ix++; } return prod; } double factorial(int n) { int i; double ix = 1; double prod = 1; for (i=1; i<=n; i++) { prod *= ix; ix++; } return prod; } char **enumerate_swaps(int n) { size_t i,j,num,b; long maxiter = (size_t) gsl_pow_int(2.0,(int)n); char **swaps = (char **)VCalloc(maxiter,sizeof(char *)); for(i = 0; i < maxiter; i++) swaps[i] = (char *)VCalloc(n,sizeof(char)); /* generate swap table */ for (i=0; i<maxiter; i++) { /* decimal to binary */ j = 0; num = i; while(num > 0) { b=num%2; swaps[i][j] = b; num=num/2; j++; } } return swaps; } char **randomSwaps(long maxiter,int n,unsigned long int seed) { size_t i,j; char **swaps = (char **)VCalloc(maxiter,sizeof(char *)); for(i = 0; i < maxiter; i++) swaps[i] = (char *)VCalloc(n,sizeof(char)); gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; gsl_rng *rx = gsl_rng_alloc(T); gsl_rng_set(rx,(unsigned long int)seed); for(i = 0; i < maxiter; i++) for(j = 0; j < n; j++) swaps[i][j] = gsl_ran_bernoulli(rx, 0.5); return swaps; } char **randomSwaps_noduplicates(long maxiter,int n,unsigned long int seed) { size_t iter,i,j; /* if number of maxiter exceeds number of all possible combinations */ if(maxiter > (size_t) gsl_pow_int(2.0,(int)n)) VError("Error: Number of iterations larger than possible permutations!"); gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; gsl_rng *rx = gsl_rng_alloc(T); gsl_rng_set(rx,(unsigned long int)seed); char **swaps = (char **)VCalloc(maxiter,sizeof(char *)); for(i = 0; i < maxiter; i++) swaps[i] = (char *)VCalloc(n,sizeof(char)); /* generate swap table */ iter = 0; while (iter < maxiter) { for (j=0; j<n; j++) swaps[iter][j] = gsl_ran_bernoulli(rx,0.5); /* check if already there */ /* decrementing iter will result in overwriting the swaps */ /* since there are no duplicates in can only be decremented once */ for (j=0; j<iter; j++) if (memcmp(swaps[iter],swaps[j],n*sizeof(char)) == 0) iter--; iter++; } return swaps; } /* * shuffle blocks; needed for permutation_test */ int **randomBlocks(long int maxiter, int nimages, int block_size, unsigned long int seed) { int nblocks = nimages/block_size; int i,j,iter; /* ini with real order */ int **table = (int **)VCalloc(maxiter,sizeof(int*)); for(i = 0; i < maxiter; i++) { table[i] = (int *)VCalloc(2*nimages,sizeof(int)); for(j = 0; j < nimages; j++) { table[i][2*j] = j; table[i][2*j+1] = j+nimages; } } /* each row of table has order: 0, nimages, 1, nimages+1, ... */ /* shuffle blocks of size 2*block_size */ gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; gsl_rng *rx = gsl_rng_alloc(T); gsl_rng_set(rx,(unsigned long int)seed); for (iter=0; iter<maxiter; iter++) for (j=0; j<nblocks; j++) gsl_ran_shuffle(rx, (void *)&table[iter][j*2*block_size], 2*block_size, sizeof(int)); return table; } /* * shuffle blocks; needed for permutation_test * maxiter is the number of random permutations * nimages is the number of images in one condition (2*nimages in total) * block_size is the size of the permutation blocks */ int **randomBlocks_noduplicates(long int maxiter, int nimages, int block_size, unsigned long int seed) { int nblocks = nimages/block_size; int i,j,iter; /* ini with real order */ int **table = (int **)VCalloc(maxiter,sizeof(int*)); for(i = 0; i < maxiter; i++) { table[i] = (int *)VCalloc(2*nimages,sizeof(int)); for(j = 0; j < nimages; j++) { table[i][2*j] = j; table[i][2*j+1] = j+nimages; } } /* each row of table has order: 0, nimages, 1, nimages+1, ... */ /* shuffle blocks of size 2*block_size */ gsl_rng_env_setup(); const gsl_rng_type *T = gsl_rng_default; gsl_rng *rx = gsl_rng_alloc(T); gsl_rng_set(rx,(unsigned long int)seed); iter = 0; while (iter < maxiter) { /* shuffle */ for (j = 0; j<nblocks; j++) gsl_ran_shuffle(rx, (void *)&table[iter][j*2*block_size], 2*block_size, sizeof(int)); /* sort for one side */ int k, l, m; int index = 0; int temp = 0; for (m = 0; m < nblocks; m++) { for (k = 0; k < block_size-1; k++) { index = k; for (l = k+1; l < block_size; l++) { if (table[iter][m*2*block_size+2*index] < table[iter][m*2*block_size+2*l]) index = l; } /* swap pairs 'k' and 'index' */ temp = table[iter][m*2*block_size+2*k]; table[iter][m*2*block_size+2*k] = table[iter][m*2*block_size+2*index]; table[iter][m*2*block_size+2*index] = temp; temp = table[iter][m*2*block_size+2*k+1]; table[iter][m*2*block_size+2*k+1] = table[iter][m*2*block_size+2*index+1]; table[iter][m*2*block_size+2*index+1] = temp; } } /* * decrementing iter will result in overwriting the last swaps row * since there are no duplicates it can only be decremented once */ for(j=0; j<iter; j++) if (memcmp(table[iter],table[j],2*nimages*sizeof(int)) == 0) iter--; iter++; } return table; }
{ "alphanum_fraction": 0.6046633026, "avg_line_length": 25.3171806167, "ext": "c", "hexsha": "af02fbaf04f0da5fa820a3c5be81619656d0f1d7", "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/stats/utils/RandomCombinations.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/stats/utils/RandomCombinations.c", "max_line_length": 102, "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/stats/utils/RandomCombinations.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": 1868, "size": 5747 }
#if !defined(RANDOM_H_INCLUDED) #define RANDOM_H_INCLUDED #include <gsl/gsl> #include <iosfwd> class Random { public: static int usage(::std::ostream& strm, const ::std::string& progName, const char* pMsg); Random(::gsl::span<const char*const> args); int run() const; Random(const Random&) = delete; Random& operator=(const Random&) = delete; Random(Random&&) = delete; Random& operator=(Random&&) = delete; private: static long getRandomInteger(long low, long high); long m_lowerBound; long m_upperBound; long m_count; }; #endif // RANDOM_H_INCLUDED
{ "alphanum_fraction": 0.7132867133, "avg_line_length": 18.4516129032, "ext": "h", "hexsha": "33f1d8db227de44f8fe1131a3ea44de10156081a", "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": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "IanEmmons/CmdLineUtil", "max_forks_repo_path": "Random.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "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": "IanEmmons/CmdLineUtil", "max_issues_repo_path": "Random.h", "max_line_length": 70, "max_stars_count": null, "max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "IanEmmons/CmdLineUtil", "max_stars_repo_path": "Random.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 144, "size": 572 }
/* This section is aimed to calculate the gaussian integrals that occurs in everywhere This part is greatly inspired by May, Andrew James. Density fitting in explicitly correlated electronic structure theory. Diss. University of Bristol, 2006. */ /* Here is the table of the relation between the names and the definition: S <a|b> J (a|b) = <a|1/r_{12}|b> G (a|e^{-\gamma r_{12}^2}|b) F (a|f_{12}|b) = (a|c_i exp(-\gamma_i r_{12}^2)|b) GJ (a|e^{-\gamma r_{12}^2 r_12^{-1}}|b) FJ (a|f_{12} r_{12}^{-1}|b) FF (a|f_{12}^2|b) FT (ab|[\hat{t}_1, f_{12}]|c) = (ab|[- \frac{1}{2} \nabla ^2, f_{12}]|c) FTF (a|\frac{1}{2}[f_12,[\hat{t}_1 + \hat{t}_2, f_{12}]]|b) F-F (a|f_{12}|b|f_{23}|c) J-F (a|r_{12}^{-1}|b|f_{23}|c) X (ab|[\hat{t}_1,r_{12}]|c) Y (ab|[\hat{t}_1,r_{12}^{-1}]) Z (a|\frac{1}{r_{1Z}}|b) Currently only S integrals and J integrals are supported. */ #ifndef __BASIS_H__ #define __BASIS_H__ #include "basis.h" #endif #include <math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_sf.h> typedef struct gaussian_chain{ double R[3]; int a[3]; double exponent; double coefficient; gaussian_chain * NEXT; }gaussian_chain; gaussian_chain * gaussian_chain_calloc(); void gaussian_chain_free(gaussian_chain * HEAD); double gaussian_chain_get(gaussian_chain * HEAD,double x, double y, double z); double orbital_get(orbital * orbital,double x, double y, double z); double Gamma(double z); double Boys(double x, int n); double Binomials(int n, int k); double f(int k, int a, int b, double PA, double PB); double tranformation_coefficient(int a[3], int b[3], int p[3], double PA[3], double PB[3], double xi, double AB); double SIntegral(double ra[3], double rb[3], int ax, int ay, int az, int bx, int by, int bz, double alpha,double beta); double JIntegral(double ra[3], double rb[3], int ax, int ay, int az, int bx, int by, int bz, double alpha,double beta, int m); double ZIntegral(double ra[3], double rb[3], double rz[3], int ax, int ay, int az, int bx, int by, int bz, double alpha, double beta, int m); double gaussian_chain_SIntegral(gaussian_chain * a, gaussian_chain * b); double gaussian_chain_JIntegral(gaussian_chain * a, gaussian_chain * b); double gaussian_chain_ZIntegral(gaussian_chain * a, gaussian_chain * b, double rz[3]); double gaussian_chain_full_SIntegral(gaussian_chain * a_HEAD, gaussian_chain * b_HEAD); double gaussian_chain_full_JIntegral(gaussian_chain * a_HEAD, gaussian_chain * b_HEAD); double gaussian_chain_full_ZIntegral(gaussian_chain * a_HEAD, gaussian_chain * b_HEAD, double rz[3]); void gaussian_chain_derivative(gaussian_chain * dest, gaussian_chain * src, int key); void gaussian_chain_second_derivative(gaussian_chain * dest, gaussian_chain * src, int key); void gaussian_chain_laplacian(gaussian_chain * dest, gaussian_chain * src); double gaussian_chain_kinetic_energy(gaussian_chain * a_HEAD, gaussian_chain * b_HEAD); void single_electron_transform(gaussian_chain * HEAD, orbital * a); void two_electron_transform(gaussian_chain * HEAD, orbital * a, orbital * b); double orbital_SIntegral(orbital * a,orbital * b); double orbital_JIntegral(orbital * a,orbital * b); double orbital_ZIntegral(orbital * a,orbital * b, double rz[3]); //double orbital_GIntegral(orbital *,orbital *); //double orbital_FIntegral(orbital *,orbital *); //double orbital_GJIntegral(orbital *,orbital *); //double orbital_FJIntegral(orbital *,orbital *); //double orbital_FFIntegral(orbital *,orbital *); double two_electron_JIntegral(orbital * a_1, orbital * b_1, orbital * c_2, orbital * d_2); double orbital_kinetic_energy(orbital * a, orbital * b); void orbital_S_matrix(gsl_matrix * dest, orbital * HEAD);
{ "alphanum_fraction": 0.7212543554, "avg_line_length": 37.31, "ext": "h", "hexsha": "b06615368f409383ce1369aa91e16f123d51952f", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-10-16T03:11:07.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-18T13:50:13.000Z", "max_forks_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Walter-Feng/Hartree-Fock", "max_forks_repo_path": "include/integral.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "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": "Walter-Feng/Hartree-Fock", "max_issues_repo_path": "include/integral.h", "max_line_length": 160, "max_stars_count": 7, "max_stars_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Walter-Feng/Hartree-Fock", "max_stars_repo_path": "include/integral.h", "max_stars_repo_stars_event_max_datetime": "2022-03-23T18:50:05.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-23T21:27:21.000Z", "num_tokens": 1119, "size": 3731 }
/* pbrt source code is Copyright(c) 1998-2016 Matt Pharr, Greg Humphreys, and Wenzel Jakob. This file is part of pbrt. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - 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. */ #if defined(_MSC_VER) #define NOMINMAX #pragma once #endif #ifndef PBRT_CAMERAS_REALISTICEYE_H #define PBRT_CAMERAS_REALISTICEYE_H // cameras/realistic.h* #include "pbrt.h" #include "camera.h" #include "film.h" #include <gsl/gsl_randist.h> #include "spectrum.h" // This is necessary to declare Spectrum class in this header file. namespace pbrt { // This is slightly different than our normal lens class. We have more variables to be able to describe the elements of the eye including biconic surfaces and unique ocular mediums. struct LensElementEye{ float radiusX; float radiusY; float thickness; float mediumIndex; // Corresponds to the mediumElement. Describes media directly "behind" (-z direction, toward the retina) the surface. float semiDiameter; float conicConstantX; float conicConstantY; }; // RealisticCamera Declarations class RealisticEye : public Camera { public: // RealisticCamera Public Methods RealisticEye(const AnimatedTransform &CameraToWorld, Float shutterOpen, Float shutterClose, bool simpleWeighting, bool noWeighting, Film *film, const Medium *medium, std::string specfile, Float pupilDiameter, Float retinaDistance, Float retinaRadius, Float retinaSemiDiam, std::vector<Spectrum> iorSpectra, bool flipRad, bool mmUnits, bool diffractionEnabled); Float GenerateRay(const CameraSample &sample, Ray *) const; private: const bool simpleWeighting; const bool noWeighting; // Lens information std::vector<LensElementEye> lensEls; Float effectiveFocalLength; // Specific parameters for the human eye Float pupilDiameter; Float retinaDistance; Float retinaRadius; Float retinaSemiDiam; Float retinaDiag; // This will take the place of "film->diag" Float frontThickness; // The distance from the back of the lens to the front of the eye. std::vector<Spectrum> iorSpectra; // Flags for conventions bool diffractionEnabled; float lensScaling; // Private methods for tracing through lens bool IntersectLensElAspheric(const Ray &r, Float *tHit, LensElementEye currElement, Float zShift, Vector3f *n) const; void applySnellsLaw(Float n1, Float n2, Float lensRadius, Vector3f &normalVec, Ray * ray ) const; Float lookUpIOR(int mediumIndex, const Ray &ray) const; void diffractHURB(Point3f intersect, Float apertureRadius, const Float wavelength, const Vector3f oldDirection, Vector3f *newDirection) const; // Handy method to explicity solve for the z(x,y) at a given point (x,y), for the biconic SAG Float BiconicZ(Float x, Float y, LensElementEye currElement) const; // GSL seed(?) for random number generation gsl_rng * r; }; RealisticEye *CreateRealisticEye(const ParamSet &params, const AnimatedTransform &cam2world, Film *film, const Medium *medium); } // namespace pbrt #endif // PBRT_CAMERAS_REALISTICEYE_H
{ "alphanum_fraction": 0.6643045151, "avg_line_length": 38.8897637795, "ext": "h", "hexsha": "3218c1b8522c5aafe42244a506b68d754deeeaff", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-05-16T18:02:47.000Z", "max_forks_repo_forks_event_min_datetime": "2018-03-16T17:30:41.000Z", "max_forks_repo_head_hexsha": "58405f660ea3d1560f1b1bfbba8930d18eb0db99", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "Zhenyi-Liu/pbrt_singleSP", "max_forks_repo_path": "src/cameras/realisticEye.h", "max_issues_count": 4, "max_issues_repo_head_hexsha": "58405f660ea3d1560f1b1bfbba8930d18eb0db99", "max_issues_repo_issues_event_max_datetime": "2020-05-31T21:30:53.000Z", "max_issues_repo_issues_event_min_datetime": "2018-11-12T17:36:20.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "Zhenyi-Liu/pbrt_singleSP", "max_issues_repo_path": "src/cameras/realisticEye.h", "max_line_length": 185, "max_stars_count": 4, "max_stars_repo_head_hexsha": "58405f660ea3d1560f1b1bfbba8930d18eb0db99", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "Zhenyi-Liu/pbrt_singleSP", "max_stars_repo_path": "src/cameras/realisticEye.h", "max_stars_repo_stars_event_max_datetime": "2022-01-22T02:09:41.000Z", "max_stars_repo_stars_event_min_datetime": "2018-05-05T17:15:51.000Z", "num_tokens": 1048, "size": 4939 }
#ifndef _CCS_RNG_H #define _CCS_RNG_H #ifdef __cplusplus extern "C" { #endif #include <gsl/gsl_rng.h> /** * @file rng.h * CCS rng define random number generators. For now they are wrappers over gsl * random number generators. */ /** * Create a new random number generator using the gsl default type (see * gsl_rng_default). * @param [out] rng_ret a pointer to the variable that will contain the returned * random number generator * @return #CCS_SUCCESS on success * @return -#CCS_INVALID_VALUE if \p rng_ret is NULL * @return -#CCS_OUT_OF_MEMORY if there was not enough memory to allocate the * new random number generator */ extern ccs_result_t ccs_rng_create(ccs_rng_t *rng_ret); /** * Create a new random number generator using the provided gsl type (see * gsl_rng_type). * @param [in] rng_type a pointer to the type of gsl random number generator to * use. * @param [out] rng_ret a pointer to the variable that will contain the returned * random number generator * @return #CCS_SUCCESS on success * @return -#CCS_INVALID_VALUE if \p rng_ret or \p rng_type are NULL * @return -#CCS_OUT_OF_MEMORY if there was not enough memory to allocate the * new random number generator */ extern ccs_result_t ccs_rng_create_with_type(const gsl_rng_type *rng_type, ccs_rng_t *rng_ret); /** * Get the gsl type of a random number generator. * @param [in] rng * @param [out] rng_type_ret a pointer that will contained a pointer to the * returned gsl random number generator type. * @return #CCS_SUCCESS on success * @return -#CCS_INVALID_OBJECT if \p rng is not a valid CCS random number * generator * @return -#CCS_INVALID_VALUE if \p rng_type_ret is NULL */ extern ccs_result_t ccs_rng_get_type(ccs_rng_t rng, const gsl_rng_type **rng_type_ret); /** * Set the seed of a random number generator. * @param [in] rng * @param [in] seed the seed to use with the random number generator * @return #CCS_SUCCESS on success * @return -#CCS_INVALID_OBJECT if \p rng is not a valid CCS random number * generator */ extern ccs_result_t ccs_rng_set_seed(ccs_rng_t rng, unsigned long int seed); /** * Get a random integer from a random number generator. Integer is contained * between the value returned by #ccs_rng_min and #ccs_rng_max, both included. * @param [in] rng * @param [out] value_ret a pointer to the variable that will contain the * returned value * @return #CCS_SUCCESS on success * @return -#CCS_INVALID_OBJECT if \p rng is not a valid CCS random number * generator * @return -#CCS_INVALID_VALUE if \p value_ret is NULL */ extern ccs_result_t ccs_rng_get(ccs_rng_t rng, unsigned long int *value_ret); /** * Get a random floating point value uniformly sampled in the interval [0.0, * 1.0). * @param [in] rng * @param [out] value_ret a pointer to the variable that will contain the * returned value * @return #CCS_SUCCESS on success * @return -#CCS_INVALID_OBJECT if \p rng is not a valid CCS random number * generator * @return -#CCS_INVALID_VALUE if \p value_ret is NULL */ extern ccs_result_t ccs_rng_uniform(ccs_rng_t rng, ccs_float_t *value_ret); /** * Get the underlying gsl random number generator. * @param [in] rng * @param [out] gsl_rng_ret a pointer to the variable that will contain a * pointer to the underlying random number generator * @return #CCS_SUCCESS on success * @return -#CCS_INVALID_OBJECT if \p rng is not a valid CCS random number * generator * @return -#CCS_INVALID_VALUE if \p gsl_rng_ret is NULL */ extern ccs_result_t ccs_rng_get_gsl_rng(ccs_rng_t rng, gsl_rng **gsl_rng_ret); /** * Get the minimum value that can be returned by #ccs_rng_get. * @param [in] rng * @param [out] value_ret a pointer to the variable that will contain the * returned value * @return #CCS_SUCCESS on success * @return -#CCS_INVALID_OBJECT if \p rng is not a valid CCS random number * generator * @return -#CCS_INVALID_VALUE if \p value_ret is NULL */ extern ccs_result_t ccs_rng_min(ccs_rng_t rng, unsigned long int *value_ret); /** * Get the maximum value that can be returned by #ccs_rng_get. * @param [in] rng * @param [out] value_ret a pointer to the variable that will contain the * returned value * @return #CCS_SUCCESS on success * @return -#CCS_INVALID_OBJECT if \p rng is not a valid CCS random number * generator * @return -#CCS_INVALID_VALUE if \p value_ret is NULL */ extern ccs_result_t ccs_rng_max(ccs_rng_t rng, unsigned long int *value_ret); #ifdef __cplusplus } #endif #endif //_CCS_RNG_H
{ "alphanum_fraction": 0.6521485514, "avg_line_length": 34.75, "ext": "h", "hexsha": "c43e31c28d569815a422a1bb8a480a91ae862506", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-07T17:54:11.000Z", "max_forks_repo_forks_event_min_datetime": "2021-09-16T18:20:47.000Z", "max_forks_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "deephyper/CCS", "max_forks_repo_path": "include/cconfigspace/rng.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_issues_repo_issues_event_max_datetime": "2021-12-15T10:48:24.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-15T10:37:41.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "deephyper/CCS", "max_issues_repo_path": "include/cconfigspace/rng.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "deephyper/CCS", "max_stars_repo_path": "include/cconfigspace/rng.h", "max_stars_repo_stars_event_max_datetime": "2021-11-29T16:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2021-11-29T16:31:28.000Z", "num_tokens": 1248, "size": 5143 }
/* ** Kendall's coefficient of concordance - Kendall's W ** ** G.Lohmann, July 2010 */ #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sort_double.h> #include <gsl/gsl_math.h> #include <gsl/gsl_cdf.h> #include <math.h> #include <stdio.h> #include <string.h> extern void gsl_sort_vector_index (gsl_permutation *,gsl_vector *); #define SQR(x) ((x) * (x)) #define ABS(x) ((x) > 0 ? (x) : -(x)) double kendall(size_t **xrank,double *r,int n,int m,int otype) { int i,j; double S,W,R,chi_square=0; double nx=0,mx=0; nx = (double)n; mx = (double)m; for (i=0; i<n; i++) { r[i] = 0; for (j=0; j<m; j++) r[i] += xrank[j][i]; } R = 0; for (i=0; i<n; i++) R += r[i]; R /= nx; S = 0; for (i=0; i<n; i++) S += SQR(r[i] - R); W = 12.0*S/(mx*mx*(nx*nx-1)*nx); if (otype == 0) return W; /* by central limit theorem, chi_square is approx normal for large n */ /* see en.wikipedia.org/wiki/Chi-square_distribution */ chi_square = (nx-1)*mx*W; return (chi_square - nx)/(sqrt(2.0*nx)); } double VKendall_W(gsl_matrix *data,int nvoxels,int otype) { int i,j,n,m; double W0; static double *r=NULL; static gsl_vector *vec = NULL; static size_t **xrank=NULL; static gsl_permutation *perm=NULL,*rank=NULL; m = data->size1; n = nvoxels; if (vec == NULL) { r = (double *) calloc(data->size2,sizeof(double)); vec = gsl_vector_calloc(data->size2); perm = gsl_permutation_alloc(data->size2); rank = gsl_permutation_alloc(data->size2); xrank = (size_t **) calloc(m,sizeof(size_t *)); for (i=0; i<m; i++) xrank[i] = (size_t *) calloc(data->size2,sizeof(size_t)); } gsl_vector_set_all (vec,9999); for (i=0; i<m; i++) { for (j=0; j<n; j++) { gsl_vector_set(vec,j,gsl_matrix_get(data,i,j)); } gsl_sort_vector_index (perm, vec); gsl_permutation_inverse (rank, perm); for (j=0; j<n; j++) xrank[i][j] = rank->data[j]; } /* Kendall's W of measured data */ W0 = kendall(xrank,r,n,m,otype); return W0; }
{ "alphanum_fraction": 0.6073619632, "avg_line_length": 23.0326086957, "ext": "c", "hexsha": "1df96400e106de0939ebb4b264e12d3e6f978078", "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/nets/vccm/Kendall.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/nets/vccm/Kendall.c", "max_line_length": 81, "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/nets/vccm/Kendall.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": 733, "size": 2119 }
/* $Header$ */ /* Purpose: GSL functions that handle missing values - stubs only Extra NCO code derived from GSL removed 2020-04-02 to avoid license conflict between GSL GPL and NCO BSD code */ /* Copyright (C) 1995--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 */ #include <gsl/gsl_statistics.h> #include <gsl/gsl_fit.h> #include "nco_gsl.h" /* Missing value-aware GSL functions */ /* Fit the data (x_i, y_i) to the linear relationship Y = c0 + c1 x returning, c0, c1 -- coefficients cov00, cov01, cov11 -- variance-covariance matrix of c0 and c1, sumsq -- sum of squares of residuals This fit can be used in the case where the errors for the data are uknown, but assumed equal for all points. The resulting variance-covariance matrix estimates the error in the coefficients from the observed variance of the points around the best fit line. */ int nco_gsl_fit_linear (const double *x, const size_t xstride, const double *y, const size_t ystride, const size_t n, double *c0, double *c1, double *cov_00, double *cov_01, double *cov_11, double *sumsq, const double *mss_val) { return gsl_fit_linear(x, xstride, y, ystride, n, c0, c1, cov_00, cov_01, cov_11, sumsq); } static double compute_covariance (const double data1[], const size_t stride1, const double data2[], const size_t stride2, const size_t n, const double mean1, const double mean2, const double *mss_val) /* Missing value */ { /* takes a dataset and finds the covariance */ long double covariance = 0 ; size_t i; /* find the sum of the squares */ if (mss_val==NULL) { for (i = 0; i < n; i++) { const long double delta1 = (data1[i * stride1] - mean1); const long double delta2 = (data2[i * stride2] - mean2); covariance += (delta1 * delta2 - covariance) / (i + 1); } } else { for (i = 0; i < n; i++) { if (data2[i * stride2]!=*mss_val) { const long double delta1 = (data1[i * stride1] - mean1); const long double delta2 = (data2[i * stride2] - mean2); covariance += (delta1 * delta2 - covariance) / (i + 1); } } } return covariance ; } double nco_gsl_stats_covariance_m (const double data1[], const size_t stride1, const double data2[], const size_t stride2, const size_t n, const double mean1, const double mean2, const double *mss_val) /* Missing value */ { return gsl_stats_covariance_m(data1, stride1, data2,stride2,n,mean1,mean2); } double nco_gsl_stats_covariance (const double data1[], const size_t stride1, const double data2[], const size_t stride2, const size_t n, const double *mss_val) /* Missing value */ { return gsl_stats_covariance(data1, stride1, data2,stride2,n); } double nco_gsl_stats_mean (const double data[], const size_t stride, const size_t size, const double *mss_val) /* Missing value */ { return gsl_stats_mean(data, stride, size); }
{ "alphanum_fraction": 0.6789691378, "avg_line_length": 22.6115107914, "ext": "c", "hexsha": "0705b260b1767aac3bf3a3b87ebf72df053d3fab", "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": "d7cd7925bcc195f0fa4a301c5f1bf2d562d81f0d", "max_forks_repo_licenses": [ "BSD-3-Clause-Clear", "BSD-3-Clause" ], "max_forks_repo_name": "acchen/nco", "max_forks_repo_path": "src/nco++/nco_gsl.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d7cd7925bcc195f0fa4a301c5f1bf2d562d81f0d", "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": "acchen/nco", "max_issues_repo_path": "src/nco++/nco_gsl.c", "max_line_length": 115, "max_stars_count": null, "max_stars_repo_head_hexsha": "d7cd7925bcc195f0fa4a301c5f1bf2d562d81f0d", "max_stars_repo_licenses": [ "BSD-3-Clause-Clear", "BSD-3-Clause" ], "max_stars_repo_name": "acchen/nco", "max_stars_repo_path": "src/nco++/nco_gsl.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 894, "size": 3143 }
#pragma once #include "Core/Delegate.h" #include "Core/Pointers.h" #include "Scene/Entity.h" #include <gsl/span> #include <string> #include <unordered_map> #include <vector> class CameraComponent; class DirectionalLightComponent; class ModelComponent; class PointLightComponent; class SpotLightComponent; class Scene { public: Scene(); ~Scene(); void tick(float dt); float getTime() const { return time; } float getDeltaTime() const { return deltaTime; } template<typename... ComponentTypes> Entity* createEntity() { entities.push_back(Entity::create<ComponentTypes...>(*this)); return entities.back().get(); } Entity* createEntity(gsl::span<std::string> componentClassNames) { entities.push_back(Entity::create(componentClassNames, *this)); return entities.back().get(); } bool destroyEntity(Entity* entityToDestroy); const std::vector<UPtr<Entity>>& getEntities() const { return entities; } CameraComponent* getActiveCameraComponent() { return activeCameraComponent; } const CameraComponent* getActiveCameraComponent() const { return activeCameraComponent; } void setActiveCameraComponent(CameraComponent* newActiveCameraComponent); const std::vector<CameraComponent*>& getCameraComponents() const { return cameraComponents; } void registerCameraComponent(CameraComponent* cameraComponent); void unregisterCameraComponent(CameraComponent* cameraComponent); const std::vector<ModelComponent*>& getModelComponents() const { return modelComponents; } void registerModelComponent(ModelComponent* modelComponent); void unregisterModelComponent(ModelComponent* modelComponent); const std::vector<DirectionalLightComponent*>& getDirectionalLightComponents() const { return directionalLightComponents; } void registerDirectionalLightComponent(DirectionalLightComponent* directionalLightComponent); void unregisterDirectionalLightComponent(DirectionalLightComponent* directionalLightComponent); const std::vector<PointLightComponent*>& getPointLightComponents() const { return pointLightComponents; } void registerPointLightComponent(PointLightComponent* pointLightComponent); void unregisterPointLightComponent(PointLightComponent* pointLightComponent); const std::vector<SpotLightComponent*>& getSpotLightComponents() const { return spotLightComponents; } void registerSpotLightComponent(SpotLightComponent* spotLightComponent); void unregisterSpotLightComponent(SpotLightComponent* spotLightComponent); private: float time; float deltaTime; std::vector<UPtr<Entity>> entities; std::vector<CameraComponent*> cameraComponents; CameraComponent* activeCameraComponent; std::vector<ModelComponent*> modelComponents; std::vector<DirectionalLightComponent*> directionalLightComponents; std::vector<PointLightComponent*> pointLightComponents; std::vector<SpotLightComponent*> spotLightComponents; };
{ "alphanum_fraction": 0.7510534846, "avg_line_length": 24.8790322581, "ext": "h", "hexsha": "aa13c31dc56dce9a4eb0ad42998206dff80ef51b", "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": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "aaronmjacobs/Swap", "max_forks_repo_path": "Source/Scene/Scene.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "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": "aaronmjacobs/Swap", "max_issues_repo_path": "Source/Scene/Scene.h", "max_line_length": 98, "max_stars_count": null, "max_stars_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "aaronmjacobs/Swap", "max_stars_repo_path": "Source/Scene/Scene.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 634, "size": 3085 }
#include <cblas.h> int main() { double *x, *y; cblas_ddot(0, x, 0, y, 0); }
{ "alphanum_fraction": 0.5657894737, "avg_line_length": 25.3333333333, "ext": "c", "hexsha": "49b9b7a7279d89db2faf1d005cc3c810004fdbfa", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z", "max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z", "max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "t-sakashita/rokko", "max_forks_repo_path": "config/check_cblas.c", "max_issues_count": 514, "max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "t-sakashita/rokko", "max_issues_repo_path": "config/check_cblas.c", "max_line_length": 56, "max_stars_count": 16, "max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "t-sakashita/rokko", "max_stars_repo_path": "config/check_cblas.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z", "num_tokens": 35, "size": 76 }
/* specfunc/gsl_sf_psi.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 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_PSI_H__ #define __GSL_SF_PSI_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 /* Poly-Gamma Functions * * psi(m,x) := (d/dx)^m psi(0,x) = (d/dx)^{m+1} log(gamma(x)) */ /* Di-Gamma Function psi(n) = psi(0,n) * * n > 0 * exceptions: GSL_EDOM */ int gsl_sf_psi_int_e(const int n, gsl_sf_result * result); double gsl_sf_psi_int(const int n); /* Di-Gamma Function psi(x) = psi(0, x) * * x != 0.0, -1.0, -2.0, ... * exceptions: GSL_EDOM, GSL_ELOSS */ int gsl_sf_psi_e(const double x, gsl_sf_result * result); double gsl_sf_psi(const double x); /* Di-Gamma Function Re[psi(1 + I y)] * * exceptions: none */ int gsl_sf_psi_1piy_e(const double y, gsl_sf_result * result); double gsl_sf_psi_1piy(const double y); /* Di-Gamma Function psi(z) for general complex argument z = x + iy * * exceptions: GSL_EDOM */ int gsl_sf_complex_psi_e( const double x, const double y, gsl_sf_result * result_re, gsl_sf_result * result_im ); /* Tri-Gamma Function psi^(1)(n) * * n > 0 * exceptions: GSL_EDOM */ int gsl_sf_psi_1_int_e(const int n, gsl_sf_result * result); double gsl_sf_psi_1_int(const int n); /* Tri-Gamma Function psi^(1)(x) * * x != 0.0, -1.0, -2.0, ... * exceptions: GSL_EDOM, GSL_ELOSS */ int gsl_sf_psi_1_e(const double x, gsl_sf_result * result); double gsl_sf_psi_1(const double x); /* Poly-Gamma Function psi^(n)(x) * * n >= 0, x > 0.0 * exceptions: GSL_EDOM */ int gsl_sf_psi_n_e(const int n, const double x, gsl_sf_result * result); double gsl_sf_psi_n(const int n, const double x); __END_DECLS #endif /* __GSL_SF_PSI_H__ */
{ "alphanum_fraction": 0.6913902348, "avg_line_length": 23.5350877193, "ext": "h", "hexsha": "ec61179064badea3ab91c368f6d2d1b8286512e3", "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_psi.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_psi.h", "max_line_length": 81, "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_psi.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": 813, "size": 2683 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <pthread.h> #include <semaphore.h> #include <apop.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_multifit.h> /********************************HOPE: Sum of norm of residuals fitting for Hough Mode Extension Data*****************************************/ //Copyright (C) 2012 Daniel Strano /*'Hope' is an open-source project based on Oberheide and Forbes GEOPHYSICAL RESEARCH LETTERS, VOL. 35, L04816, doi:10.1029/2007GL032397, 2008. The program was originally designed for the purpose of handling the challenge of empirically fitting multi-component complex wave data, in situations where the goodness of fit of a least squares model is questionable. The program was originally designed to work with three self-consistent variables to fit simultaneously. The variances of the variables are first scaled to satisify the assumptions of constant variance and independence of errors, necessary for a consistent least squares model. Then, the program takes advantage of the finite phase domain to indirectly search for a maximization of the sum of absolute (norms of) residuals.*/ /*********************************************************************************************************************************************/ #define depVar 3 const int rawblock = 29; const int block = 33; const int heightsOut = 8; const int heightsIn = 8; const int HME_N = 2; const int HMEBlockCount = 8; const int satrows = 264; const double PI = 3.141592653589793; const double PHASE_INTERVAL = 0.001; const int PHASE_INT_INV = 1000; const double P_I_x_PI = 0.001 * 3.141592653589793; int outrows=0; double totalSumSqr; double TotalSN[depVar]; int global_phase_iter1 = 0; int global_phase_iter2 = 0; int threadtracker[4]; pthread_mutex_t iter_update; pthread_mutex_t compare; sem_t threadsAvail; gsl_matrix *Full_Descrip; gsl_vector *dependent; gsl_vector *BestModel; int minIndepOffset; double *threadIndep; double BestPhase1; double BestPhase2; double BestResid = 0; double BestRNorm = 0; int itemscount; void *threadParallel(void *arg) { int *threadNum = (int *)arg; //Argument is used for thread scheduling (used at bottom of thread function) int phase_iter1, phase_iter2; //Local phase iteration holder variables //Lock the current global phase iteration counters, pull the next value for the local iteration, and update global counters: pthread_mutex_lock(&iter_update); phase_iter1 = global_phase_iter1; phase_iter2 = global_phase_iter2; ++global_phase_iter1; if (global_phase_iter1 >= PHASE_INT_INV) { global_phase_iter1 = 0; ++global_phase_iter2; } pthread_mutex_unlock(&iter_update); int loop1, loop2, loop3, loop4, loop5; int returncode; float phase_shift[2]= {P_I_x_PI * phase_iter1, P_I_x_PI * phase_iter2}; //Phase shifts calculated from phase iteration counters float Rotation[8]; //Used to rotate complex vectors int holder, holder2, holder3, holder4, holder5, holder6; //For loop optimization double chiSqr; //Sum of squares of residuals of each iterative model float coeff_of_determ; //Normalized coefficient of determination "" //Calculate rotation factors to apply phase shift corresponding to the current iteration: for (loop1 = 0; loop1 < HME_N; loop1++) { holder = loop1 * 4; holder2 = holder + 2; for (loop2 = 0; loop2 < 2; loop2++) { Rotation[holder + loop2] = cos(phase_shift[loop1]); if (loop2) { Rotation[holder2 + loop2] = -1 * sin(phase_shift[loop1]); } else { Rotation[holder2 + loop2] = sin(phase_shift[loop1]); } } } //Declare objects for GSL least squares model for fixed phases: gsl_matrix *Local_Descrip = gsl_matrix_alloc(itemscount, HME_N); //Local description of amplitude-only model gsl_matrix *covariance = gsl_matrix_alloc(HME_N, HME_N); gsl_multifit_linear_workspace *modelspace = gsl_multifit_linear_alloc(itemscount, HME_N); gsl_vector *beta = gsl_vector_alloc(HME_N); //fitting parameters //Apply rotations and initialize 'Local_Descrip' for (loop5 = 0; loop5 < HME_N; loop5++) { holder = loop5 * 4; holder2 = holder + 1; holder3 = holder2 + 1; holder4 = holder3 + 1; holder6 = loop5 * minIndepOffset; for (loop1 = 0; loop1 < itemscount; loop1 += 2) { holder5 = loop1 + 1; gsl_matrix_set(Local_Descrip, loop1, loop5, Rotation[holder] * threadIndep[holder6 + loop1] + Rotation[holder4] * threadIndep[holder6 + holder5]); gsl_matrix_set(Local_Descrip, holder5, loop5, Rotation[holder2] * threadIndep[holder6 + holder5] + Rotation[holder3] * threadIndep[holder6 + loop1]); } } //Find least squares fit: returncode = gsl_multifit_linear(Local_Descrip, dependent, beta, covariance, &chiSqr, modelspace); coeff_of_determ = 1 - chiSqr/totalSumSqr; //Free model space for fit (covariance is also not used): gsl_matrix_free(covariance); gsl_multifit_linear_free(modelspace); //From partial model beta parameters, calculate equivalent full model parameters: double sumNormResid[3] = {0, 0, 0}; double R_norm = 0; double R_resid, I_resid; double Full_Beta[2 * HME_N]; for (loop1 = 0; loop1 < HME_N; loop1++) { Full_Beta[2 * loop1] = gsl_vector_get(beta, loop1) * cos(phase_shift[loop1]); Full_Beta[2 * loop1 + 1] = gsl_vector_get(beta, loop1) * sin(phase_shift[loop1]); } //Re-weight variables to equal total weight for sum of norms of residuals model, //calculate sum of norms of residuals for full model from least squares beta coefficients: int maxiter1 = 2 * outrows; int maxiter2 = maxiter1 * depVar; int maxiter3 = HME_N * 2; for (loop2 = 0; loop2 < maxiter2; loop2 += maxiter1) { holder3 = (int)(loop2/maxiter1); for (loop1 = 0; loop1 < maxiter1; loop1 += 2) { R_resid = gsl_vector_get(dependent, loop1 + loop2); holder = loop2 + loop1; holder2 = holder + 1; for (loop3 = 0; loop3 < maxiter3; loop3++) R_resid -= Full_Beta[loop3] * gsl_matrix_get(Full_Descrip, holder, loop3); I_resid = gsl_vector_get(dependent, holder2); for (loop3 = 0; loop3 < maxiter3; loop3++) I_resid -= Full_Beta[loop3] * gsl_matrix_get(Full_Descrip, holder2, loop3); sumNormResid[holder3] += sqrt((R_resid * R_resid) + (I_resid * I_resid)); } } //Calculated normalized coefficient of determination for sum of norms of residuals: for (loop1 = 0; loop1 < depVar; loop1++) R_norm -= sumNormResid[loop1]/TotalSN[loop1]; R_norm = R_norm/3; R_norm++; //Lock global best model comparisons and updates, //compare this thread's "R-norm" and update global best model if a better model has been found: pthread_mutex_lock(&compare); if (BestRNorm < R_norm) { BestRNorm = R_norm; BestResid = coeff_of_determ; BestPhase1 = phase_shift[0]; BestPhase2 = phase_shift[1]; for (loop1 = 0; loop1 < HME_N; loop1++) { gsl_vector_set(BestModel, loop1, gsl_vector_get(beta, loop1)); } } pthread_mutex_unlock(&compare); //Free remaining manually allocated memory objects: gsl_matrix_free(Local_Descrip); gsl_vector_free(beta); //Prepare to signal to loop in main() that this thread identity is becoming free, then post to semaphore: threadtracker[*threadNum] = 0; sem_post(&threadsAvail); return NULL; } int main(int argc, char *argv[]) { //Thread expects input files as specified below: if (argc != 4) { printf("usage: hope [saber_t] [tidi_e] [tidi_n]\n"); printf("Note: Satellite data should be in *.csv form, in a single column, aligned by row, with no column or row names. Dummy value is -999. \n"); } else { gsl_matrix *satellite[3]; double *minIndep[2]; int lev_rows; double height[heightsIn]; double latitudes[rawblock]; double *HME_ptr[8][HME_N]; double **uninterp[HME_N][depVar*2]; double **interp_lat[HME_N][depVar*2]; double **interp_lev[HME_N][depVar*2]; BestModel = gsl_vector_alloc(2); pthread_t zero; pthread_t one; pthread_t two; pthread_t three; sem_init(&threadsAvail, 0, 4); long long maxpage; long long pagein = 1; int comp, comp_int, tenth_percent_complete = 0, percent_complete = 0; int loop, loop1, loop2, loop3, loop4, loop5, loop6; int threadID[4]; double TotalSumSqr[depVar]; double Variance[depVar]; double AbsDeviance[depVar]; double Scale[depVar], DevScale[depVar]; double scaledRow; int holder; int holder2; for (loop = 0; loop < depVar; loop++) { TotalSumSqr[loop] = 0; TotalSN[loop] = 0; Variance[loop] = 0; //optional Scale[loop] = 0; //optional } for (loop = 0; loop < 4; loop++) { threadtracker[loop] = 0; threadID[loop] = loop; } //Read in raw data: //(Independent) descriptor data: apop_text_to_db(.text_file="HME1.csv", .tabname="X1", .has_row_names = 0, .has_col_names = 1); HME_ptr[0][0] = apop_vector_to_array(apop_query_to_vector("SELECT lat FROM X1")); HME_ptr[1][0] = apop_vector_to_array(apop_query_to_vector("SELECT lev FROM X1")); HME_ptr[2][0] = apop_vector_to_array(apop_query_to_vector("SELECT amp_t FROM X1")); HME_ptr[3][0] = apop_vector_to_array(apop_query_to_vector("SELECT phase_t FROM X1")); HME_ptr[4][0] = apop_vector_to_array(apop_query_to_vector("SELECT amp_e FROM X1")); HME_ptr[5][0] = apop_vector_to_array(apop_query_to_vector("SELECT phase_e FROM X1")); HME_ptr[6][0] = apop_vector_to_array(apop_query_to_vector("SELECT amp_n FROM X1")); HME_ptr[7][0] = apop_vector_to_array(apop_query_to_vector("SELECT phase_n FROM X1")); apop_text_to_db(.text_file="HME2.csv", .tabname="X2", .has_row_names = 0, .has_col_names = 1); HME_ptr[0][1] = apop_vector_to_array(apop_query_to_vector("SELECT lat FROM X2")); HME_ptr[1][1] = apop_vector_to_array(apop_query_to_vector("SELECT lev FROM X2")); HME_ptr[2][1] = apop_vector_to_array(apop_query_to_vector("SELECT amp_t FROM X2")); HME_ptr[3][1] = apop_vector_to_array(apop_query_to_vector("SELECT phase_t FROM X2")); HME_ptr[4][1] = apop_vector_to_array(apop_query_to_vector("SELECT amp_e FROM X2")); HME_ptr[5][1] = apop_vector_to_array(apop_query_to_vector("SELECT phase_e FROM X2")); HME_ptr[6][1] = apop_vector_to_array(apop_query_to_vector("SELECT amp_n FROM X2")); HME_ptr[7][1] = apop_vector_to_array(apop_query_to_vector("SELECT phase_n FROM X2")); //(Dependent) variable data: apop_text_to_db(.text_file=argv[1], .tabname="Y_t", .has_row_names = 0, .has_col_names = 1); satellite[0] = apop_query_to_matrix("SELECT * FROM Y_t"); apop_text_to_db(.text_file=argv[2], .tabname="Y_e", .has_row_names = 0, .has_col_names = 1); satellite[1] = apop_query_to_matrix("SELECT * FROM Y_e"); apop_text_to_db(.text_file=argv[3], .tabname="Y_n", .has_row_names = 0, .has_col_names = 1); satellite[2] = apop_query_to_matrix("SELECT * FROM Y_n"); //Need to know how many non-dummy rows are in satellite data //Calculate total sum of squares and total sum of norms of satellite data while tallying non-dummy rows in 'outrows': outrows = 0; for (loop1 = 0; loop1 < satrows; loop1++) { if (gsl_matrix_get(satellite[0], loop1, 0) > -990) { if (gsl_matrix_get(satellite[1], loop1, 0) > -990) { if (gsl_matrix_get(satellite[2], loop1, 0) > -990) { for (loop2 = 0; loop2 < depVar; loop2++) { for (loop3 = 0; loop3 < 2; loop3++) { TotalSumSqr[loop2] += (gsl_matrix_get(satellite[loop2], loop1, loop3) * gsl_matrix_get(satellite[loop2], loop1, loop3)); } TotalSN[loop2] += sqrt((gsl_matrix_get(satellite[loop2], loop1, 0) * gsl_matrix_get(satellite[loop2], loop1, 0)) + (gsl_matrix_get(satellite[loop2], loop1, 1) * gsl_matrix_get(satellite[loop2], loop1, 1))); } ++outrows; } } } } itemscount = outrows * depVar * 2; //Total number of data items (rows * columns) //Allocate arrays for uninterpolated data, lattitude interpolated data, and data interpolated by both lattitude and elevation: for (loop1 = 0; loop1 < HME_N; loop1++) { for (loop2 = 0; loop2 < depVar * 2; loop2++) { uninterp[loop1][loop2] = malloc(HMEBlockCount * sizeof(double *)); interp_lat[loop1][loop2] = malloc(block * sizeof(double *)); interp_lev[loop1][loop2] = malloc(block * sizeof(double *)); for (loop3 = 0; loop3 < HMEBlockCount; loop3++) { uninterp[loop1][loop2][loop3] = malloc(rawblock * sizeof(double)); } for (loop3 = 0; loop3 < block; loop3++) { interp_lat[loop1][loop2][loop3] = malloc(HMEBlockCount * sizeof(double)); interp_lev[loop1][loop2][loop3] = malloc(heightsOut * sizeof(double)); } } } //Initialize block of uninterpolated data: for (loop1 = 0; loop1 < HMEBlockCount; loop1++) { holder = rawblock * loop1; for (loop2 = 0; loop2 < 2 * depVar; loop2 += 2) { for (loop3 = 0; loop3 < HME_N; loop3++) { for (loop4 = 0; loop4 < rawblock; loop4++) { uninterp[loop3][0 + loop2][loop1][(rawblock - 1) - loop4] = *(HME_ptr[2 + loop2][loop3] + (holder + loop4)) * cos(*(HME_ptr[3 + loop2][loop3] + holder + loop4) / 12 * PI); uninterp[loop3][1 + loop2][loop1][(rawblock - 1) - loop4] = *(HME_ptr[2 + loop2][loop3] + (holder + loop4)) * sin(*(HME_ptr[3 + loop2][loop3] + holder + loop4) / 12 * PI); } } } } //Read lattitudes from input: for (loop1 = 0; loop1 < rawblock; loop1++) { latitudes[(rawblock - 1) - loop1] = *(HME_ptr[0][0] + loop1); } //Read elevations from input: for (loop1 = 0; loop1 < heightsIn; loop1++) { height[loop1] = *(HME_ptr[1][0] + (loop1 * rawblock)); } //GSL Spline Interpolation: //Lattitude interpolation: for (loop = 0; loop < HME_N; loop++) { for (loop3 = 0; loop3 < 2; loop3++) { for (loop2 = 0; loop2 < HMEBlockCount; loop2++) { for (loop4 = 0; loop4 < depVar * 2; loop4 += 2) { gsl_interp_accel *lat_acc = gsl_interp_accel_alloc(); gsl_spline *lat_spline = gsl_spline_alloc(gsl_interp_cspline, rawblock); gsl_spline_init(lat_spline, latitudes, uninterp[loop][loop4 + loop3][loop2], rawblock); for (loop1 = 0; loop1 < block; loop1++) { interp_lat[loop][loop4 + loop3][loop1][loop2] = gsl_spline_eval(lat_spline, (loop1 * 5) - 80, lat_acc); } gsl_spline_free (lat_spline); gsl_interp_accel_free (lat_acc); } } } } //Altitude ("lev") interpolation: holder = 0; for (loop = 0; loop < HME_N; loop++) { for (loop3 = 0; loop3 < 2; loop3++) { for (loop1 = 0; loop1 < block; loop1++) { for (loop4 = 0; loop4 < depVar * 2; loop4 += 2) { gsl_interp_accel *lev_acc = gsl_interp_accel_alloc(); gsl_spline *lev_spline = gsl_spline_alloc(gsl_interp_cspline, heightsIn); gsl_spline_init(lev_spline, height, interp_lat[loop][loop4 + loop3][loop1], heightsIn); for (loop2 = 0; loop2 < heightsOut; loop2++) { interp_lev[loop][loop4 + loop3][loop1][loop2] = gsl_spline_eval(lev_spline, 87.5 + (loop2 * 2.5), lev_acc); } gsl_spline_free (lev_spline); gsl_interp_accel_free (lev_acc); } } } } //Variance and deviance calculation (for normalizing different variables): for (loop1 = 0; loop1 < depVar; loop1++) { Variance[loop1] = TotalSumSqr[loop1] / (outrows/2); AbsDeviance[loop1] = TotalSN[loop1] / (outrows/2); } for (loop1 = 0; loop1 < depVar; loop1++) { Scale[loop1] = sqrt(Variance[0]/ Variance[loop1]); DevScale[loop1] = AbsDeviance[0] / AbsDeviance[loop1]; } //In interative fit, phases are held fixed while amplitudes are fit //Phases are incremented after each amplitude fit //Create an array with the minimum information from the independent matrix necessary to perform iterative fit: for (loop1 = 0; loop1 < HME_N; loop1++) { minIndep[loop1] = malloc(satrows * depVar * 2 * sizeof(double)); } loop4 = 0; for (loop1 = 0; loop1 < heightsOut; loop1++) { for (loop3 = 0; loop3 < depVar; loop3++) { for (loop4 = 0; loop4 < block; loop4++) { for (loop5 = 0; loop5 < HME_N; loop5++) { for (loop = 0; loop < 2; loop++) { minIndep[loop5][(loop3 * 2 * satrows) + (block * 2 * loop1) + (loop4 * 2) + loop] = interp_lev[loop5][2 * loop3 + loop][block - 1 - loop4][loop1]; } } } } } //Garbage collection after pre-processing: for (loop1 = 0; loop1 < HME_N; loop1++) { for (loop2 = 0; loop2 < depVar * 2; loop2++) { for (loop3 = 0; loop3 < HMEBlockCount; loop3++) { free(uninterp[loop1][loop2][loop3]); } for (loop3 = 0; loop3 < block; loop3++) { free(interp_lat[loop1][loop2][loop3]); free(interp_lev[loop1][loop2][loop3]); } free(uninterp[loop1][loop2]); free(interp_lat[loop1][loop2]); free(interp_lev[loop1][loop2]); } } //Dummy values in satellite data can not be passed to GSL fitting functions //Real and imaginary components alternate. //The dependent variables counted by "depVar" are concatenated as contigious blocks //Remove dummy values and concatenate satellite vectors; dependent = gsl_vector_alloc(2 * depVar * outrows); totalSumSqr = 0; for (loop2 = 0; loop2 < depVar; loop2++) { loop5 = 0; for (loop1 = 0; loop1 < satrows; loop1++) { if (gsl_matrix_get(satellite[0], loop1, 0) > -990) { if (gsl_matrix_get(satellite[1], loop1, 0) > -990) { if (gsl_matrix_get(satellite[2], loop1, 0) > -990) { for (loop3 = 0; loop3 < 2; loop3++) { scaledRow = Scale[loop2] * gsl_matrix_get(satellite[loop2], loop1, loop3); gsl_vector_set(dependent, (2 * outrows * loop2) + loop5 + loop3, scaledRow); totalSumSqr += scaledRow * scaledRow; for (loop4 = 0; loop4 < HME_N; loop4++){ minIndep[loop4][(2 * outrows * loop2) + loop5 + loop3] = Scale[loop2] * minIndep[loop4][(2 * satrows * loop2) + 2 * loop1 + loop3]; } } loop5+=2; } } } } } //Reallocate shrink minIndep once dummy values are removed: int *error_ptr; minIndepOffset = outrows * depVar * 2; for (loop1 = 0; loop1 < HME_N; loop1++) { error_ptr = realloc(minIndep[loop1], sizeof(double) * minIndepOffset); } //Create a 1D array of the minimum data that needs to be passed to threads for iterative fit: threadIndep = malloc(sizeof(double) * minIndepOffset * HME_N); for (loop1 = 0; loop1 < HME_N; loop1++) { for (loop2 = 0; loop2 < minIndepOffset; loop2++) { threadIndep[minIndepOffset * loop1 + loop2] = minIndep[loop1][loop2]; } } //Create an array with the full 'clean' independent data for an (analytical) R^2 fit to compare against: Full_Descrip = gsl_matrix_alloc((outrows * depVar) * 2, HME_N * 2); gsl_matrix *covariance = gsl_matrix_alloc(HME_N * 2, HME_N * 2); gsl_multifit_linear_workspace *modelspace = gsl_multifit_linear_alloc((outrows * depVar) * 2, HME_N * 2); gsl_vector *beta = gsl_vector_alloc(HME_N * 2); for (loop1 = 0; loop1 < 2 * outrows * depVar; loop1++) { for (loop2 = 0; loop2 < HME_N; loop2++) { for (loop3 = 0; loop3 < 2; loop3++) { if (loop3 && !(loop1 % 2)) { gsl_matrix_set(Full_Descrip, loop1, 2 * loop2 + loop3, -minIndep[loop2][loop1 + loop3]); } else { gsl_matrix_set(Full_Descrip, loop1, 2 * loop2 + loop3, minIndep[loop2][loop1 + loop3]); } } } } //'minIndep' is no longer needed //Release 'minIndep': for (loop1 = 0; loop1 < 2; loop1++) { free(minIndep[loop1]); } //Find R^2 fit for full independent array: double chiSqr; gsl_multifit_linear(Full_Descrip, dependent, beta, covariance, &chiSqr, modelspace); double coeff_of_determ = 1 - chiSqr/totalSumSqr; //Find sum of absolute norms of residuals for the returned least squares model (normalizing variables weights to new model moment): double sumNormResid[3] = {0, 0, 0}; double R_norm = 0; double R_resid, I_resid; double Full_Beta[2 * HME_N]; double amp_phase[2 * HME_N]; for (loop1 = 0; loop1 < HME_N * 2; loop1++) { Full_Beta[loop1] = gsl_vector_get(beta, loop1); } for (loop1 = 0; loop1 < HME_N * 2; loop1+=2) { amp_phase[loop1] = sqrt(Full_Beta[loop1] * Full_Beta[loop1] + Full_Beta[loop1 + 1] * Full_Beta[loop1 + 1]); amp_phase[loop1+1] = atan(Full_Beta[loop1 + 1] / Full_Beta[loop1]); } int maxiter1 = 2 * outrows; int maxiter2 = maxiter1 * depVar; for (loop2 = 0; loop2 < maxiter2; loop2 += maxiter1) { for (loop1 = 0; loop1 < maxiter1; loop1 += 2) { R_resid = gsl_vector_get(dependent, loop1 + loop2); for (loop3 = 0; loop3 < HME_N * 2; loop3++) R_resid -= Full_Beta[loop3] * gsl_matrix_get(Full_Descrip, loop2 + loop1, loop3); I_resid = gsl_vector_get(dependent, loop1 + loop2 + 1); for (loop3 = 0; loop3 < HME_N * 2; loop3++) I_resid -= Full_Beta[loop3] * gsl_matrix_get(Full_Descrip, loop2 + loop1 + 1, loop3); sumNormResid[(int)(loop2/maxiter1)] += sqrt((R_resid * R_resid) + (I_resid * I_resid)); } } for (loop1 = 0; loop1 < depVar; loop1++) R_norm -= sumNormResid[loop1]/TotalSN[loop1]; R_norm = R_norm/3; R_norm += 1; //Pre-processing has completed //Start calling iterative fitting threads for R-norm: sem_wait(&threadsAvail); threadtracker[0] = 1; pthread_create(&zero,NULL,threadParallel, &threadID[0]); ++pagein; sem_wait(&threadsAvail); threadtracker[1] = 1; pthread_create(&one,NULL,threadParallel, &threadID[1]); ++pagein; sem_wait(&threadsAvail); threadtracker[2] = 1; pthread_create(&two,NULL,threadParallel, &threadID[2]); ++pagein; sem_wait(&threadsAvail); threadtracker[3] = 1; pthread_create(&three,NULL,threadParallel, &threadID[3]); ++pagein; //With every thread initially called, begin thread scheduling: maxpage = (PHASE_INT_INV) * (PHASE_INT_INV); comp = floor(maxpage/1000); comp_int = comp; while (pagein < maxpage) { sem_wait(&threadsAvail); if (!threadtracker[0]) { threadtracker[0] = 1; pthread_join(zero, NULL); pthread_create(&zero,NULL,threadParallel, &threadID[0]); } else if (!threadtracker[1]) { threadtracker[1] = 1; pthread_join(one, NULL); pthread_create(&one,NULL,threadParallel, &threadID[1]); } else if (!threadtracker[2]) { threadtracker[2] = 1; pthread_join(two, NULL); pthread_create(&two,NULL,threadParallel, &threadID[2]); } else { threadtracker[3] = 1; pthread_join(three, NULL); pthread_create(&three, NULL, threadParallel, &threadID[3]); } ++pagein; //Output progress on percent or 1/10 of a percent of completion: if (pagein > comp) { comp = comp + comp_int; ++tenth_percent_complete; if (tenth_percent_complete > 9) { ++percent_complete; tenth_percent_complete = 0; //printf("Phase intercept 1: %f \n", BestPhase1); //printf("Phase intercept 2: %f \n", BestPhase2); //printf("R Squared average: %f \n", BestResid); //printf("%d.%d percent complete \n \n", percent_complete, tenth_percent_complete); } printf("Amplitude 1: %f \n", gsl_vector_get(BestModel, 0)); printf("Phase intercept 1: %f \n", BestPhase1); printf("Amplitude 2: %f \n", gsl_vector_get(BestModel, 1)); printf("Phase intercept 2: %f \n", BestPhase2); printf("Best R norm: %f \n", BestRNorm); printf("Corresponding R^2: %f \n", BestResid); printf("Best R^2: %f \n", coeff_of_determ); printf("Best R^2 Amplitude 1: %f \n", amp_phase[0]); printf("Best R^2 Phase intercept 1: %f \n", amp_phase[1]); printf("Best R^2 Amplitude 2: %f \n", amp_phase[2]); printf("Best R^2 Phase intercept 2: %f \n", amp_phase[3]); printf("R norm corresponding to analytical best R^2: %f \n", R_norm); printf("%d.%d percent complete \n \n", percent_complete, tenth_percent_complete); } } //All iterations have been called //Join last calls: pthread_join(zero, NULL); pthread_join(one, NULL); pthread_join(two, NULL); pthread_join(three, NULL); //Print final result: printf("Best phase 1 intercept: %f \n", BestPhase1); printf("Best phase 2 intercept: %f \n", BestPhase2); printf("Best R norm: %f \n", BestRNorm); printf("Best corresponding R squared: %f \n", BestResid); printf("Corresponding R^2: %f \n", BestResid); printf("Best R^2: %f \n", coeff_of_determ); printf("Best R^2 Amplitude 1: %f \n", amp_phase[0]); printf("Best R^2 Phase intercept 1: %f \n", amp_phase[1]); printf("Best R^2 Amplitude 2: %f \n", amp_phase[2]); printf("Best R^2 Phase intercept 2: %f \n", amp_phase[3]); printf("R norm corresponding to analytical best R^2: %f \n", R_norm); //Free remaining manually allocated memory objects: for (loop1 = 0; loop1 < depVar; loop1++) { gsl_matrix_free(satellite[loop1]); } gsl_vector_free(dependent); gsl_vector_free(BestModel); gsl_matrix_free(Full_Descrip); } return 0; }
{ "alphanum_fraction": 0.6527333728, "avg_line_length": 38.2703927492, "ext": "c", "hexsha": "595e34aad1fb51c148632ba44092fb2bf8f76c83", "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": "8b5809e34dc1453ce0dc96abeca1188d3fd03ca5", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "WrathfulSpatula/Hope", "max_forks_repo_path": "hope_r-norm.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8b5809e34dc1453ce0dc96abeca1188d3fd03ca5", "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": "WrathfulSpatula/Hope", "max_issues_repo_path": "hope_r-norm.c", "max_line_length": 787, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8b5809e34dc1453ce0dc96abeca1188d3fd03ca5", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "WrathfulSpatula/Hope", "max_stars_repo_path": "hope_r-norm.c", "max_stars_repo_stars_event_max_datetime": "2020-10-15T10:28:08.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-15T10:28:08.000Z", "num_tokens": 8119, "size": 25335 }
/* specfunc/gsl_sf_expint.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Author: G. Jungman */ #ifndef __GSL_SF_EXPINT_H__ #define __GSL_SF_EXPINT_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 /* E_1(x) := Re[ Integrate[ Exp[-xt]/t, {t,1,Infinity}] ] * * x != 0.0 * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_expint_E1_e(const double x, gsl_sf_result * result); double gsl_sf_expint_E1(const double x); /* E_2(x) := Re[ Integrate[ Exp[-xt]/t^2, {t,1,Infinity}] ] * * x != 0.0 * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_expint_E2_e(const double x, gsl_sf_result * result); double gsl_sf_expint_E2(const double x); /* Ei(x) := PV Integrate[ Exp[-t]/t, {t,-x,Infinity}] * * x != 0.0 * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_expint_Ei_e(const double x, gsl_sf_result * result); double gsl_sf_expint_Ei(const double x); /* Shi(x) := Integrate[ Sinh[t]/t, {t,0,x}] * * exceptions: GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_Shi_e(const double x, gsl_sf_result * result); double gsl_sf_Shi(const double x); /* Chi(x) := Re[ M_EULER + log(x) + Integrate[(Cosh[t]-1)/t, {t,0,x}] ] * * x != 0.0 * exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW */ int gsl_sf_Chi_e(const double x, gsl_sf_result * result); double gsl_sf_Chi(const double x); /* Ei_3(x) := Integral[ Exp[-t^3], {t,0,x}] * * x >= 0.0 * exceptions: GSL_EDOM */ int gsl_sf_expint_3_e(const double x, gsl_sf_result * result); double gsl_sf_expint_3(double x); /* Si(x) := Integrate[ Sin[t]/t, {t,0,x}] * * exceptions: none */ int gsl_sf_Si_e(const double x, gsl_sf_result * result); double gsl_sf_Si(const double x); /* Ci(x) := -Integrate[ Cos[t]/t, {t,x,Infinity}] * * x > 0.0 * exceptions: GSL_EDOM */ int gsl_sf_Ci_e(const double x, gsl_sf_result * result); double gsl_sf_Ci(const double x); /* AtanInt(x) := Integral[ Arctan[t]/t, {t,0,x}] * * * exceptions: */ int gsl_sf_atanint_e(const double x, gsl_sf_result * result); double gsl_sf_atanint(const double x); __END_DECLS #endif /* __GSL_SF_EXPINT_H__ */
{ "alphanum_fraction": 0.6837662338, "avg_line_length": 25.2459016393, "ext": "h", "hexsha": "055c6f5e6688059c363e0ccce9faa3c4cc786819", "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/gsl_sf_expint.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_expint.h", "max_line_length": 72, "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/gsl_sf_expint.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": 967, "size": 3080 }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "core/common/inlined_containers.h" #include "core/codegen/common/common.h" #include "core/graph/graph.h" #include "core/providers/nuphar/common/analysis/analysis.h" #include <gsl/gsl> namespace onnxruntime { namespace nuphar { class OutputAliasAnalysis : public NupharAnalysis { public: OutputAliasAnalysis() : NupharAnalysis("OutputAliasAnalysis") {} ~OutputAliasAnalysis() = default; void Evaluate(const onnxruntime::nuphar::NupharSubgraphUnit& graph) override; bool IsOutputNode(const onnxruntime::Node* node) const; bool IsOutputAlias(const onnxruntime::Node* node) const; const onnxruntime::NodeArg* SourceDefOfOutputAlias(const onnxruntime::NodeArg* node) const; private: // a set for output nodes std::set<NodeKey> output_nodes_; // a map from an output alias to its input std::map<NodeKey, const onnxruntime::NodeArg*> alias_use_defs_; void Traverse(gsl::span<const Node* const> nodes, const InlinedHashSet<std::string_view>& graph_inputs, const InlinedHashSet<std::string_view>& graph_outputs); private: ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(OutputAliasAnalysis); }; } // namespace nuphar } // namespace onnxruntime
{ "alphanum_fraction": 0.7482993197, "avg_line_length": 28.7608695652, "ext": "h", "hexsha": "31c617011975e910a0f0ef423859ded2ca5c4ec1", "lang": "C", "max_forks_count": 140, "max_forks_repo_forks_event_max_datetime": "2019-05-06T18:02:36.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-03T21:15:28.000Z", "max_forks_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SiriusKY/onnxruntime", "max_forks_repo_path": "onnxruntime/core/providers/nuphar/common/analysis/output_alias_analysis.h", "max_issues_count": 440, "max_issues_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_issues_repo_issues_event_max_datetime": "2019-05-06T20:47:23.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T21:09:56.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "SiriusKY/onnxruntime", "max_issues_repo_path": "onnxruntime/core/providers/nuphar/common/analysis/output_alias_analysis.h", "max_line_length": 93, "max_stars_count": 669, "max_stars_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "SiriusKY/onnxruntime", "max_stars_repo_path": "onnxruntime/core/providers/nuphar/common/analysis/output_alias_analysis.h", "max_stars_repo_stars_event_max_datetime": "2019-05-06T19:42:49.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-03T22:00:31.000Z", "num_tokens": 323, "size": 1323 }
//See http://www.gnu.org/software/gsl/doc/html/usage.html#an-example-program //T. Golfinopoulos, 29 Dec. 2017 #include <stdio.h> #include <gsl/gsl_sf_bessel.h> int main (void) { double x = 5.0; double y = gsl_sf_bessel_J0 (x); printf ("J0(%g) = %.18e\n", x, y); return 0; }
{ "alphanum_fraction": 0.6537102473, "avg_line_length": 20.2142857143, "ext": "c", "hexsha": "029686bbd733abdf4911e7d72511ba184b0c487b", "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": "8132d1b1f21611d13f332a3770f5a94dfdecbb0a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "golfit/C-Mod", "max_forks_repo_path": "test_gsl.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "8132d1b1f21611d13f332a3770f5a94dfdecbb0a", "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": "golfit/C-Mod", "max_issues_repo_path": "test_gsl.c", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "8132d1b1f21611d13f332a3770f5a94dfdecbb0a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "golfit/C-Mod", "max_stars_repo_path": "test_gsl.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 104, "size": 283 }
/* ode-initval/evolve.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <string.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv.h> #include "odeiv_util.h" gsl_odeiv_evolve * gsl_odeiv_evolve_alloc (size_t dim) { gsl_odeiv_evolve *e = (gsl_odeiv_evolve *) malloc (sizeof (gsl_odeiv_evolve)); if (e == 0) { GSL_ERROR_NULL ("failed to allocate space for evolve struct", GSL_ENOMEM); } e->y0 = (double *) malloc (dim * sizeof (double)); if (e->y0 == 0) { free (e); GSL_ERROR_NULL ("failed to allocate space for y0", GSL_ENOMEM); } e->yerr = (double *) malloc (dim * sizeof (double)); if (e->yerr == 0) { free (e->y0); free (e); GSL_ERROR_NULL ("failed to allocate space for yerr", GSL_ENOMEM); } e->dydt_in = (double *) malloc (dim * sizeof (double)); if (e->dydt_in == 0) { free (e->yerr); free (e->y0); free (e); GSL_ERROR_NULL ("failed to allocate space for dydt_in", GSL_ENOMEM); } e->dydt_out = (double *) malloc (dim * sizeof (double)); if (e->dydt_out == 0) { free (e->dydt_in); free (e->yerr); free (e->y0); free (e); GSL_ERROR_NULL ("failed to allocate space for dydt_out", GSL_ENOMEM); } e->dimension = dim; e->count = 0; e->failed_steps = 0; e->last_step = 0.0; return e; } int gsl_odeiv_evolve_reset (gsl_odeiv_evolve * e) { e->count = 0; e->failed_steps = 0; e->last_step = 0.0; return GSL_SUCCESS; } void gsl_odeiv_evolve_free (gsl_odeiv_evolve * e) { RETURN_IF_NULL (e); free (e->dydt_out); free (e->dydt_in); free (e->yerr); free (e->y0); free (e); } /* Evolution framework method. * * Uses an adaptive step control object */ int gsl_odeiv_evolve_apply (gsl_odeiv_evolve * e, gsl_odeiv_control * con, gsl_odeiv_step * step, const gsl_odeiv_system * dydt, double *t, double t1, double *h, double y[]) { const double t0 = *t; double h0 = *h; int step_status; int final_step = 0; double dt = t1 - t0; /* remaining time, possibly less than h */ if (e->dimension != step->dimension) { GSL_ERROR ("step dimension must match evolution size", GSL_EINVAL); } if ((dt < 0.0 && h0 > 0.0) || (dt > 0.0 && h0 < 0.0)) { GSL_ERROR ("step direction must match interval direction", GSL_EINVAL); } /* No need to copy if we cannot control the step size. */ if (con != NULL) { DBL_MEMCPY (e->y0, y, e->dimension); } /* Calculate initial dydt once if the method can benefit. */ if (step->type->can_use_dydt_in) { int status = GSL_ODEIV_FN_EVAL (dydt, t0, y, e->dydt_in); if (status) { return status; } } try_step: if ((dt >= 0.0 && h0 > dt) || (dt < 0.0 && h0 < dt)) { h0 = dt; final_step = 1; } else { final_step = 0; } if (step->type->can_use_dydt_in) { step_status = gsl_odeiv_step_apply (step, t0, h0, y, e->yerr, e->dydt_in, e->dydt_out, dydt); } else { step_status = gsl_odeiv_step_apply (step, t0, h0, y, e->yerr, NULL, e->dydt_out, dydt); } /* Check for stepper internal failure */ if (step_status != GSL_SUCCESS) { *h = h0; /* notify user of step-size which caused the failure */ *t = t0; /* restore original t value */ return step_status; } e->count++; e->last_step = h0; if (final_step) { *t = t1; } else { *t = t0 + h0; } if (con != NULL) { /* Check error and attempt to adjust the step. */ double h_old = h0; const int hadjust_status = gsl_odeiv_control_hadjust (con, step, y, e->yerr, e->dydt_out, &h0); if (hadjust_status == GSL_ODEIV_HADJ_DEC) { /* Check that the reported status is correct (i.e. an actual decrease in h0 occured) and the suggested h0 will change the time by at least 1 ulp */ double t_curr = GSL_COERCE_DBL(*t); double t_next = GSL_COERCE_DBL((*t) + h0); if (fabs(h0) < fabs(h_old) && t_next != t_curr) { /* Step was decreased. Undo step, and try again with new h0. */ DBL_MEMCPY (y, e->y0, dydt->dimension); e->failed_steps++; goto try_step; } else { h0 = h_old; /* keep current step size */ } } } *h = h0; /* suggest step size for next time-step */ return step_status; }
{ "alphanum_fraction": 0.5692032229, "avg_line_length": 23.5654008439, "ext": "c", "hexsha": "d61842a3dfc6dfb2e862336051ccc8dc116df9ed", "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/ode-initval/evolve.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/ode-initval/evolve.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/ode-initval/evolve.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 1673, "size": 5585 }
/* * Copyright 2021 The DAPHNE Consortium * * 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 SRC_RUNTIME_LOCAL_KERNELS_GEMV_H #define SRC_RUNTIME_LOCAL_KERNELS_GEMV_H #include <runtime/local/context/DaphneContext.h> #include <runtime/local/datastructures/DataObjectFactory.h> #include <runtime/local/datastructures/DenseMatrix.h> #include <cblas.h> // **************************************************************************** // Struct for partial template specialization // **************************************************************************** template<class DTRes, class DTMat, class DTVec> struct Gemv { static void apply(DTRes *& res, const DTMat * mat, const DTVec * vec, DCTX(ctx)) = delete; }; // **************************************************************************** // Convenience function // **************************************************************************** template<class DTRes, class DTMat, class DTVec> void gemv(DTRes *& res, const DTMat * mat, const DTVec * vec, DCTX(ctx)) { Gemv<DTRes, DTMat, DTVec>::apply(res, mat, vec, ctx); } // **************************************************************************** // (Partial) template specializations for different data/value types // **************************************************************************** // ---------------------------------------------------------------------------- // DenseMatrix <- DenseMatrix // ---------------------------------------------------------------------------- template<> struct Gemv<DenseMatrix<double>, DenseMatrix<double>, DenseMatrix<double>> { static void apply(DenseMatrix<double> *& res, const DenseMatrix<double> * mat, const DenseMatrix<double> * vec, DCTX(ctx)) { const size_t numRows = mat->getNumRows(); const size_t numCols = mat->getNumCols(); if(res == nullptr) res = DataObjectFactory::create<DenseMatrix<double>>(numCols, 1, false); cblas_dgemv(CblasRowMajor, CblasTrans, numRows, numCols, 1.0, mat->getValues(), mat->getRowSkip(), vec->getValues(), vec->getRowSkip(), 0.0, res->getValues(), res->getRowSkip() ); } }; template<> struct Gemv<DenseMatrix<float>, DenseMatrix<float>, DenseMatrix<float>> { static void apply(DenseMatrix<float> *& res, const DenseMatrix<float> * mat, const DenseMatrix<float> * vec, DCTX(ctx)) { const size_t numRows = mat->getNumRows(); const size_t numCols = mat->getNumCols(); if(res == nullptr) res = DataObjectFactory::create<DenseMatrix<float>>(numCols, 1, false); cblas_sgemv(CblasRowMajor, CblasTrans, numRows, numCols, 1.0, mat->getValues(), mat->getRowSkip(), vec->getValues(), vec->getRowSkip(), 0.0, res->getValues(), res->getRowSkip() ); } }; #endif //SRC_RUNTIME_LOCAL_KERNELS_GEMV_H
{ "alphanum_fraction": 0.5292811546, "avg_line_length": 35.3235294118, "ext": "h", "hexsha": "6ae6c080f3b7adca1c7fe17ef55293e15692166f", "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": "64d4040132cf4059efaf184c4e363dbb921c87d6", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "daphne-eu/daphne", "max_forks_repo_path": "src/runtime/local/kernels/Gemv.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "64d4040132cf4059efaf184c4e363dbb921c87d6", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:46:30.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-31T22:10:10.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "daphne-eu/daphne", "max_issues_repo_path": "src/runtime/local/kernels/Gemv.h", "max_line_length": 128, "max_stars_count": 10, "max_stars_repo_head_hexsha": "64d4040132cf4059efaf184c4e363dbb921c87d6", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "daphne-eu/daphne", "max_stars_repo_path": "src/runtime/local/kernels/Gemv.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:37:06.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-31T21:49:35.000Z", "num_tokens": 722, "size": 3603 }
#ifndef UTIL_H #define UTIL_H #include <iostream> #include <stdio.h> #include <vector> #include <Eigen/Core> #include <Eigen/SparseCore> #include <Eigen/Householder> #include <assert.h> #include <time.h> #include <sys/time.h> #include <random> #ifdef USE_MKL #include <mkl_cblas.h> #include <mkl_lapacke.h> #else #include <cblas.h> #include <lapacke.h> #endif typedef Eigen::SparseMatrix<double, 0, int> SpMat; typedef Eigen::VectorBlock<Eigen::Matrix<double, -1, 1, 0, -1, 1>, -1> Segment; typedef Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, -1, -1> MatrixBlock; bool are_connected(Eigen::VectorXi &a, Eigen::VectorXi &b, SpMat &A); bool should_be_disconnected(int lvl1, int lvl2, int sep1, int sep2); double elapsed(timeval& start, timeval& end); void swap2perm(Eigen::VectorXi* swap, Eigen::VectorXi* perm); bool isperm(Eigen::VectorXi* perm); SpMat symmetric_graph(SpMat& A); typedef timeval timer; timer wctime(); /** * C <- alpha A * B + beta C * C <- alpha A^T * B + beta C * C <- alpha A * B^T + beta C * C <- alpha A^T * B^T + beta C * Gemm */ void gemm(Eigen::MatrixXd* A, Eigen::MatrixXd* B, Eigen::MatrixXd* C, CBLAS_TRANSPOSE tA, CBLAS_TRANSPOSE tB, double alpha, double beta); /** Return a new * C <- alpha A^(/T) * B^(/T) **/ Eigen::MatrixXd* gemm_new(Eigen::MatrixXd* A, Eigen::MatrixXd* B, CBLAS_TRANSPOSE tA, CBLAS_TRANSPOSE tB, double alpha); /** * C <- C - A * A^T */ void syrk(Eigen::MatrixXd* A, Eigen::MatrixXd* C); /** * A <- L, L L^T = A * Return != 0 if potf failed (not spd) */ int potf(Eigen::MatrixXd* A); /** * A <- [L\U] (lower and upper) * p <- swap (NOT a permutation) * A[p] = L*U * L is unit diagonal * U is not * Return != 0 if getf failed (singular) */ int getf(Eigen::MatrixXd* A, Eigen::VectorXi* swap); /** * Compute an estimated 1-norm condition number of A using its LU or Cholesky factorization */ double rcond_1_getf(Eigen::MatrixXd* A_LU, double A_1_norm); double rcond_1_potf(Eigen::MatrixXd* A_LLT, double A_1_norm); /** * B <- B * L^(-1) * B <- B * L^(-T) * B <- B * U^(-1) * B <- B * U^(-T) */ void trsm_right(Eigen::MatrixXd* L, Eigen::MatrixXd* B, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag); /** * B <- L^(-1) * B * B <- L^(-T) * B * B <- U^(-1) * B * B <- U^(-T) * B */ void trsm_left(Eigen::MatrixXd* L, Eigen::MatrixXd* B, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag); /** * x <- L^(-1) * x * x <- L^(-T) * x * x <- U^(-1) * x * x <- U^(-T) * x */ void trsv(Eigen::MatrixXd* L, Segment* x, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag); /** * x <- L^T * x */ void trmv_trans(Eigen::MatrixXd* L, Segment* x); /** * A <- L^T * A */ void trmm_trans(Eigen::MatrixXd* L, Eigen::MatrixXd* A); /** * x2 <- x2 - A21 * x1 */ void gemv_notrans(Eigen::MatrixXd* A21, Segment* x1, Segment* x2); /** * x2 <- x2 - A12^T * x1 */ void gemv_trans(Eigen::MatrixXd* A12, Segment* x1, Segment* x2); /** * AP = QR */ void geqp3(Eigen::MatrixXd* A, Eigen::VectorXi* jpvt, Eigen::VectorXd* tau); /** * A = U S VT * Compute the full SVD, where if A is mxn, U is mxm, V is nxn, and S is min(M,N) * VT is V^T, *not* V. */ void gesvd(Eigen::MatrixXd* A, Eigen::MatrixXd* U, Eigen::VectorXd* S, Eigen::MatrixXd* VT); /** * A = U S U^T * A <- U * Full Symmetric EVD */ void syev(Eigen::MatrixXd* A, Eigen::VectorXd* S); /** * x <- Q * x */ void ormqr_notrans(Eigen::MatrixXd* v, Eigen::VectorXd* h, Segment* x); /** * x <- Q^T * x * A <- Q^T * A */ void ormqr_trans(Eigen::MatrixXd* v, Eigen::VectorXd* h, Segment* x); /** * A <- A * Q * A <- A * Q^T * A <- Q * A * A <- Q^T * A */ void ormqr(Eigen::MatrixXd* v, Eigen::VectorXd* h, Eigen::MatrixXd* A, char side, char trans); /** * Create the thin Q */ void orgqr(Eigen::MatrixXd* v, Eigen::VectorXd* h); /** * Create a square Q */ // void orgqr_fat(Eigen::MatrixXd* v, Eigen::VectorXd* h); /** * A = QR */ void geqrf(Eigen::MatrixXd* A, Eigen::VectorXd* tau); int choose_rank(Eigen::VectorXd& s, double tol); std::size_t hashv(std::vector<size_t> vals); // Hash function for Eigen matrix and vector. // The code is from `hash_combine` function of the Boost library. See // http://www.boost.org/doc/libs/1_55_0/doc/html/hash/reference.html#boost.hash_combine . template<typename T> struct matrix_hash : std::unary_function<T, size_t> { std::size_t operator()(T const& matrix) const { // Note that it is oblivious to the storage order of Eigen matrix (column- or // row-major). It will give you the same hash value for two different matrices if they // are the transpose of each other in different storage order. size_t seed = 0; for (size_t i = 0; i < matrix.size(); ++i) { auto elem = *(matrix.data() + i); seed ^= std::hash<typename T::Scalar>()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } return seed; } }; void block2dense(Eigen::VectorXi &rowval, Eigen::VectorXi &colptr, Eigen::VectorXd &nnzval, int i, int j, int li, int lj, Eigen::MatrixXd *dst, bool transpose); Eigen::MatrixXd linspace_nd(int n, int dim); // Returns A[p,p] SpMat symm_perm(SpMat &A, Eigen::VectorXi &p); // Random vector with seed Eigen::VectorXd random(int size, int seed); Eigen::MatrixXd random(int rows, int cols, int seed); // Print vector template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { for(auto v_ : v) { os << v_ << " " ; } os << std::endl; return os; } /** * Statistics and Logging **/ struct Profile { public: double elim; double scale; double spars; double merge; double mergealloc; double mergecopy; double geqp3; double geqrf; double potf; double trsm; double gemm; double buildq; double scattq; double perma; double scatta; double prese; double assmb; double phi; Profile() : elim(0), scale(0), spars(0), merge(0), mergealloc(0), mergecopy(0), geqp3(0), geqrf(0), potf(0), trsm(0), gemm(0), buildq(0), scattq(0), perma(0), scatta(0), prese(0), assmb(0), phi(0) {} }; template<typename T> struct Stats { private: T min; T max; T sum; int count; public: Stats(): min(std::numeric_limits<T>::max()), max(std::numeric_limits<T>::lowest()), sum(0), count(0) {}; void addData(T value) { this->min = (this->min < value ? this->min : value); this->max = (this->max > value ? this->max : value); this->sum += value; this->count += 1; } T getMin() const { return this->count == 0 ? 0 : this->min; } T getMax() const { return this->count == 0 ? 0 : this->max; } double getMean() const { return ((double)this->sum)/((double)this->count); } int getCount() const { return this->count; } T getSum() const { return this->sum; } }; struct Log { public: int dofs_nd; int dofs_left_nd; int dofs_left_elim; int dofs_left_spars; long long int fact_nnz; Stats<int> rank_before; Stats<int> rank_after; Stats<int> nbrs; Stats<double> cond_diag; Stats<double> norm_diag; Log() : dofs_nd(0), dofs_left_nd(0), dofs_left_elim(0), dofs_left_spars(0), fact_nnz(0), rank_before(Stats<int>()), rank_after(Stats<int>()), nbrs(Stats<int>()), cond_diag(Stats<double>()), norm_diag(Stats<double>()) {} }; #endif
{ "alphanum_fraction": 0.5922757906, "avg_line_length": 25.8060200669, "ext": "h", "hexsha": "7fd40a7a93828fb5f009d3b123e9fe0af609379b", "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": "5383ec0af835634bef7b2ff24c979794a2ef253b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "wuyou33/spaND_public", "max_forks_repo_path": "include/util.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5383ec0af835634bef7b2ff24c979794a2ef253b", "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": "wuyou33/spaND_public", "max_issues_repo_path": "include/util.h", "max_line_length": 160, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5383ec0af835634bef7b2ff24c979794a2ef253b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "wuyou33/spaND_public", "max_stars_repo_path": "include/util.h", "max_stars_repo_stars_event_max_datetime": "2019-06-23T12:04:30.000Z", "max_stars_repo_stars_event_min_datetime": "2019-06-23T12:04:30.000Z", "num_tokens": 2405, "size": 7716 }
#include <assert.h> #include <complex.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <math.h> #include "include/linear.h" #if defined(__cplusplus) extern "C" { #endif // __cplusplus #include <cblas.h> #include <lapacke.h> #if defined(DEBUG) #include <stdio.h> #define debug(fmt, ...) fprintf(stderr, "ccall: " fmt "\n", ##__VA_ARGS__) #else #define debug(...) #endif // DEBUG #define MAKE_API(V0, V1, V2, V3, V4, V5) \ switch (type) { \ case 1: \ MAKE_PROG(float, s##V0, s##V1, s##V2, s##V3, s##V4, s##V5) \ break; \ case 2: \ MAKE_PROG(double, d##V0, d##V1, d##V2, d##V3, d##V4, d##V5) \ break; \ case 3: \ MAKE_PROG(float complex, c##V0, c##V1, c##V2, c##V3, c##V4, c##V5) \ break; \ case 4: \ MAKE_PROG(double complex, z##V0, z##V1, z##V2, z##V3, z##V4, z##V5) \ break; \ default: \ break; \ } #define MAKE_API_REAL(V0, V1, V2, V3, V4, V5) \ switch (type) { \ case 1: \ MAKE_PROG(float, s##V0, s##V1, s##V2, s##V3, s##V4, s##V5); \ break; \ case 2: \ MAKE_PROG(double, d##V0, d##V1, d##V2, d##V3, d##V4, d##V5); \ default: \ break; \ } #define MAKE_API_COMPLEX(V0, V1, V2, V3, V4, V5) \ switch (type) { \ case 3: \ MAKE_PROG(float complex, c##V0, c##V1, c##V2, c##V3, c##V4, c##V5); \ break; \ case 4: \ MAKE_PROG(double complex, z##V0, z##V1, z##V2, z##V3, z##V4, z##V5); \ default: \ break; \ } /* max and min */ #define min(a, b) ((a) < (b) ? (a) : (b)) #define max(a, b) ((a) > (b) ? (a) : (b)) /* zero test */ static inline __attribute__((always_inline)) bool s_is_zero(float x) { return x > -1e-6 && x < 1e-6; } /* zero test */ static inline __attribute__((always_inline)) bool d_is_zero(double x) { return x > -1e-6 && x < 1e-6; } /* zero test */ static inline __attribute__((always_inline)) bool c_is_zero(float complex x) { return crealf(x) > -1e-6 && crealf(x) < 1e-6 && cimagf(x) > -1e-6 && cimagf(x) < 1e-6; } /* zero test */ static inline __attribute__((always_inline)) bool z_is_zero(double complex x) { return creal(x) > -1e-6 && creal(x) < 1e-6 && cimag(x) > -1e-6 && cimag(x) < 1e-6; } /* constant zero */ #define s_zero (0.) #define d_zero (0.) #define c_zero (0. + 0. * I) #define z_zero (0. + 0. * I) /* constant one */ #define s_one (1.) #define d_one (1.) #define c_one (1. + 0. * I) #define z_one (1. + 0. * I) int identity(int type, void *r, int m, int n) { int i, loop = m > n ? n : m; debug("identity is called."); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < loop; ++i) { \ ((T *)r)[i * n + i] = 1.; \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int random_(int type, void *r, int m, int n) { int i, loop = m * n; srand(time(NULL)); debug("random is called."); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < loop; ++i) { \ ((T *)r)[i] = (float)rand() / RAND_MAX; \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int diag(int type, void *r, int row, int column, const void *src) { int i; debug("diag is called."); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ memset(r, 0x00, row *column * sizeof(T)); \ for (i = 0; i < row; ++i) { \ ((T *)r)[i * column + i] = ((T *)src)[i]; \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int diagonal(int type, void *r, const void *src, int row, int column) { int i, loop = row > column ? column : row; debug("diagonal is called."); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < loop; ++i) { \ ((T *)r)[i] = ((T *)src)[i * column + i]; \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int sum(int type, void *r, const void *src, int row, int column) { int i; float srv = 0.; double drv = 0.; float complex crv = 0. + 0. * I; double complex zrv = 0. + 0. * I; debug("sum is called."); #define MAKE_PROG(T, ACC, V1, V2, V3, V4, V5) \ for (i = 0; i < row * column; ++i) { \ ACC += ((T *)src)[i]; \ } \ *((T *)r) = ACC; MAKE_API(rv, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int product(int type, void *r, const void *src, int row, int column) { int i; float srv = 1.; double drv = 1.; float complex crv = 1. + 0. * I; double complex zrv = 1. + 0. * I; debug("product is called."); #define MAKE_PROG(T, ACC, V1, V2, V3, V4, V5) \ for (i = 0; i < row * column; ++i) { \ ACC *= ((T *)src)[i]; \ } \ *((T *)r) = ACC; MAKE_API(rv, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int mean(int type, void *r, const void *src, int row, int column) { int i; float srv = 0.; double drv = 0.; float complex crv = 0. + 0. * I; double complex zrv = 0. + 0. * I; debug("mean is called."); #define MAKE_PROG(T, ACC, V1, V2, V3, V4, V5) \ for (i = 0; i < row * column; ++i) { \ ACC += ((T *)src)[i]; \ } \ *((T *)r) = ACC / (row * column); MAKE_API(rv, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int transpose(int type, void *r, const void *src, int row, int column) { int i, j; debug("transpose is called."); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < row; ++i) { \ for (j = 0; j < column; ++j) { \ ((T *)r)[j * row + i] = ((T *)src)[i * column + j]; \ } \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int conjugate(int type, void *r, const void *src, int row, int column) { int i, j; debug("conjugate is called."); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < row; ++i) { \ for (j = 0; j < column; ++j) { \ ((T *)r)[j * row + i] = creal(((T *)src)[i * column + j]) \ - cimag(((T *)src)[i * column + j]) * I; \ } \ } MAKE_API_COMPLEX(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int hermite(int type, void *r, const void *src, int row, int column) { debug("hermite is called."); conjugate(type, r, src, row, column); transpose(type, r, src, row, column); return 0; } int lower(int type, void *r, const void *src, int row, int column) { int i, j, loop = row > column ? column : row; debug("lower triangularize is called"); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ memcpy(r, src, row *column * sizeof(T)); \ for (i = 0; i < loop; ++i) { \ for (j = i; j < column; ++j) { \ ((T *)r)[i * column + j] = 0.; \ } \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int upper(int type, void *r, const void *src, int row, int column) { int i, j, loop = row > column ? column : row; debug("upper triangularize is called"); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < loop; ++i) { \ for (j = i; j < column; ++j) { \ ((T *)r)[i * column + j] = ((T *)src)[i * column + j]; \ } \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int shift(int type, void *r, void *x, const void *src, int row, int column) { int i; debug("shift is called."); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < row * column; ++i) { \ ((T *)r)[i] = ((T *)src)[i] + *(T *)x; \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int times(int type, void *r, void *x, const void *src, int row, int column) { float sscalar = *((float *)x); double dscalar = *((double *)x); float complex *cscalar = (float complex *)x; double complex *zscalar = (double complex *)x; debug("times is called."); #define MAKE_PROG(T, AXPY, SCALAR, V2, V3, V4, V5) \ memset(r, 0x00, row * column * sizeof(T)); \ cblas_##AXPY(row * column, SCALAR, (T *)src, 1, (T *)r, 1); MAKE_API(axpy, scalar, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int negative(int type, void *r, const void *src, int row, int column) { int i; #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < row * column; ++i) { \ ((T *)r)[i] = - ((T *)src)[i]; \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int add(int type, void *r, int m, int n, int k, const void *A, const void *B) { int i, loop = m * n; debug("add is called."); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < loop; ++i) { \ ((T *)r)[i] = ((T *)A)[i] + ((T *)B)[i]; \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int minus(int type, void *r, int m, int n, int k, const void *A, const void *B) { int i, loop = m * n; debug("minus is called."); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < loop; ++i) { \ ((T *)r)[i] = ((T *)A)[i] - ((T *)B)[i]; \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int mult(int type, void *r, int m, int n, int k, const void *A, const void *B) { int i, loop = m * n; debug("mult is called."); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < loop; ++i) { \ ((T *)r)[i] = ((T *)A)[i] * ((T *)B)[i]; \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int division(int type, void *r, int m, int n, int k, const void *A, const void *B) { int i, loop = m * n; debug("division is called."); #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < loop; ++i) { \ ((T *)r)[i] = ((T *)A)[i] / ((T *)B)[i]; \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int dot(int type, void *r, int m, int n, int k, const void *A, const void *B) { debug("dot is called: (%d, %d) x (%d, %d) -> (%d, %d).", m, k, k, n, m, n); float salpha = 1., sbeta = 0.; double dalpha = 1., dbeta = 0.; float complex _calpha = 1. + 0. * I, _cbeta = 0. + 0. * I; double complex _zalpha = 1. + 0. * I, _zbeta = 0. + 0. * I; float complex *calpha = &_calpha, *cbeta = &_cbeta; double complex *zalpha = &_zalpha, *zbeta = &_zbeta; #define MAKE_PROG(T, GEMM, ALPHA, BETA, V3, V4, V5) \ cblas_##GEMM(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, ALPHA, (const T *)A, k, \ (const T *)B, n, BETA, (T *)r, n); MAKE_API(gemm, alpha, beta, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int inner(int type, void *r, int n, const void *A, int stepa, int offa, const void *B, int stepb, int offb) { debug("inner is called: length of the vectors is %d.", n); #define MAKE_PROG(T, DOT, V1, V2, V3, V4, V5) \ *((T *)r) = cblas_##DOT(n, ((const T *)A) + offa, stepa, ((const T *)B) + offb, stepb); MAKE_API_REAL(dot, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG #define MAKE_PROG(T, DOTC_SUB, V1, V2, V3, V4, V5) \ cblas_##DOTC_SUB(n, ((const T *)A) + offa, stepa, ((const T *)B) + offb, stepb, r); MAKE_API_COMPLEX(dotc_sub, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int det(int type, void *r, const void *src, int row, int column) { float srv = 1.; double drv = 1.; float complex crv = 1. + 0. * I; double complex zrv = 1. + 0. * I; int i, singular = 0; int *ipiv = (int *)malloc(column * sizeof(int)); memset(ipiv, 0x00, column * sizeof(int)); float *sp = NULL; double *dp = NULL; float complex *cp = NULL; double complex *zp = NULL; debug("det is called."); // step 1: copy // // step 2: LU factorization by getrf, if singular > 0, then the input matrix is singular. // // step 3: multiply all pivots // // step 4: clear intermediate memory #define MAKE_PROG(T, COPY, GETRF, MA, ACC, V4, V5) \ MA = (T *)malloc(row * column * sizeof(T)); \ cblas_##COPY(row *column, (const T *)src, 1, MA, 1); \ singular = LAPACKE_##GETRF(CblasRowMajor, row, column, MA, column, ipiv); \ if (singular == 0) { \ for (i = 0; i < column; ++i) { \ if (ipiv[i] != i) { \ ACC *= -1.0; \ } \ ACC *= MA[i * column + i]; \ } \ } else { \ ACC = 0.; \ } \ *((T *)r) = ACC; \ if (MA != NULL) { \ free(MA); \ } MAKE_API(copy, getrf, p, rv, NULL, NULL); #undef MAKE_PROG free(ipiv); return 0; } int trace(int type, void *r, const void *src, int row, int column) { int i, loop = row > column ? column : row; float srv = 0.; double drv = 0.; float complex crv = 0. + 0. * I; double complex zrv = 0. + 0. * I; debug("trace is called."); #define MAKE_PROG(T, F, ACC, V2, V3, V4, V5) \ for (i = 0; i < loop; ++i) { \ ACC += ((T *)src)[i * column + i]; \ } \ *((T *)r) = ACC; MAKE_API(NULL, rv, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int rank(int type, int *r, const void *src, int row, int column) { int i; int *ipiv = (int *)malloc(column * sizeof(int)); memset(ipiv, 0x00, column * sizeof(int)); float *sp = NULL; double *dp = NULL; float complex *cp = NULL; double complex *zp = NULL; float *stau = NULL; double *dtau = NULL; float complex *ctau = NULL; double complex *ztau = NULL; debug("rank is called, original matrix: %d x %d.", row, column); *r = 0; // ref: http://people.sc.fsu.edu/~jburkardt/f_src/geqp3/geqp3.html // // step 1: copy // // step 2: LU factorization by getrf, if singular > 0, then the input matrix is singular. #define MAKE_PROG(T, COPY, GEQP3, _IS_ZERO, MA, TAU, V5) \ MA = (T *)malloc(row * column * sizeof(T)); \ cblas_##COPY(row *column, (T *)src, 1, MA, 1); \ TAU = (T *)malloc(min(row, column) * sizeof(T)); \ LAPACKE_##GEQP3(CblasRowMajor, row, column, MA, column, ipiv, TAU); \ for (i = 0; i < row && i < column; ++i) { \ if (!_IS_ZERO(MA[i * column + i])) { \ *r += 1; \ } \ } \ if (MA != NULL) { \ free(MA); \ } \ if (TAU != NULL) { \ free(TAU); \ } MAKE_API(copy, geqp3, _is_zero, p, tau, NULL) #undef MAKE_PROG free(ipiv); return 0; } // TODO int norm(int type, void *r, const void *src, int row, int column) { debug("norm is called."); return 0; } int inverse(int type, void *r, const void *src, int row, int column) { int singular = 0; int *ipiv = (int *)malloc(column * sizeof(int)); debug("inverse is called."); // step 1: do LU decomposition via getrf // // step 2: do inversion via getri #define MAKE_PROG(T, COPY, GETRF, GETRI, V3, V4, V5) \ cblas_##COPY(row *column, (T *)src, 1, (T *)r, 1); \ singular = LAPACKE_##GETRF(CblasRowMajor, row, column, (T *)r, column, ipiv); \ if (singular == 0) { \ LAPACKE_##GETRI(CblasRowMajor, row, (T *)r, column, ipiv); \ } else { \ memset(r, 0xff, row *column * sizeof(T)); \ } MAKE_API(copy, getrf, getri, NULL, NULL, NULL); #undef MAKE_PROG free(ipiv); return 0; } // // Compute the (Moore-Penrose) pseudo-inverse of a matrix. // int pinv(int type, void *r, const void *A, int row, int column, void *rcond) { // float scutoff = *((float *)rcond), ccutoff = *((float *)rcond); // double dcutoff = *((double *)rcond), zcutoff = *((double *)rcond); // void *u = NULL, *v = NULL, *ut = NULL, *vt = NULL, *S = NULL; // float *ssigma = NULL, *csigma = NULL; // double *dsigma = NULL, *zsigma = NULL; // int i = 0; // conjugate(type, *(void **)&A, A, row, column); // remove `const` qualifier. // #define MAKE_PROG(GESDD, CUTOFF, SIGMA) // u = malloc(row * row * sizeof(T)); // vt = malloc(column * column * sizeof(T)); // S = malloc(min(row, column) * sizeof(T)); // ssigma = csigma = (float *)S; // dsigma = zsigma = (double *)S; // LAPACKE_##GESDD(CblasRowMajor, 'A', r0, c0, (T *)A, c0, SIGMA, (T *)u, c1, (T *)vt, c3); // CUTOFF *= SIGMA[0]; // for () // } // Eigen system of ordinary matrix. // // + For every column vector x in right eigenvectors V, we have Ax = \lambda x. // + For every column vector x in left eigenvectors U, we have x^H * A = \lambda x^H. // // Noticing that eigenvectors are stored as column vectors in U^T and V. // // ref: https://software.intel.com/en-us/mkl-developer-reference-c-geev int eigen(int type, void *A, int r0, int c0, void *Lambda, int r1, int c1, void *UT, int r2, int c2, void *V, int r3, int c3) { int i, j; float *sp = NULL; double *dp = NULL; float complex *cp = NULL; double complex *zp = NULL; float complex *s_ut = (float complex *)UT, *s_v = (float complex *)V; double complex *d_ut = (double complex *)UT, *d_v = (double complex *)V; float *swr = NULL, *swi = NULL, *svl = NULL, *svr = NULL; double *dwr = NULL, *dwi = NULL, *dvl = NULL, *dvr = NULL; assert(r0 == c0); // square matrix. assert(r1 == 1 && c1 == c0); // Lambda is a vector. assert(r2 == 0 || (r0 == r2 && r0 == r3)); assert(r3 == 0 || (c0 == c2 && r0 == c3)); char jobvl = r2 == 0 ? 'N' : 'V'; char jobvr = r3 == 0 ? 'N' : 'V'; debug("eigen is called, jobvl: %c, jobvr: %c.", jobvl, jobvr); #define MAKE_PROG(T, COPY, MA, V2, V3, V4, V5) \ MA = (T *)malloc(r0 * c0 * sizeof(T)); \ cblas_##COPY(r0 *c0, (T *)A, 1, MA, 1); MAKE_API(copy, p, NULL, NULL, NULL, NULL) #undef MAKE_PROG #define MAKE_PROG(T, GEEV, MA, WR, WI, VL, VR) \ WR = (T *)malloc(r0 * sizeof(T)); \ WI = (T *)malloc(r0 * sizeof(T)); \ VL = (T *)malloc(r0 * c0 * sizeof(T)); \ VR = (T *)malloc(r0 * c0 * sizeof(T)); \ LAPACKE_##GEEV(CblasRowMajor, jobvl, jobvr, r0, MA, c0, WR, WI, VL, c2, VR, c3); \ /* Copy eigenvalues (Lambda) */ \ for (i = 0; i < r0; ++i) { \ ((T *)Lambda)[2 * i] = WR[i]; \ ((T *)Lambda)[2 * i + 1] = WI[i]; \ } MAKE_API_REAL(geev, p, wr, wi, vl, vr); #undef MAKE_PROG #define MAKE_PROG(T, _IS_ZERO, WI, VL, VR, _UT, _V) \ /* Copy left and right eigenvectors (UT and V) */ \ for (j = 0; j < r0; ++j) { \ if (_IS_ZERO(WI[j])) { /* eigenvector only has real value */ \ for (i = 0; i < r0; ++i) { \ _UT[i * c2 + j] = VL[i * c2 + j] + 0. * I; \ _V[i * c3 + j] = VR[i * c3 + j] + 0. * I; \ } \ } else { /* eigenvector has complex value */ \ for (i = 0; i < r0; ++i) { \ _UT[i * c2 + j] = VL[i * c2 + j] + VL[i * c2 + j + 1] * I; \ _V[i * c3 + j] = VR[i * c3 + j] + VR[i * c3 + j + 1] * I; \ _UT[i * c2 + j + 1] = VL[i * c2 + j] - VL[i * c2 + j + 1] * I; \ _V[i * c3 + j + 1] = VR[i * c3 + j] - VR[i * c3 + j + 1] * I; \ } \ j += 1; /* IMPORTANT: skip the conjugate eigenvalue */ \ } \ } MAKE_API_REAL(_is_zero, wi, vl, vr, _ut, _v); #undef MAKE_PROG #define MAKE_PROG(T, GEEV, MA, V2, V3, V4, V5) \ LAPACKE_##GEEV(CblasRowMajor, jobvl, jobvr, r0, MA, c0, (T *)Lambda, (T *)UT, c2, (T *)V, c3); MAKE_API_COMPLEX(geev, p, NULL, NULL, NULL, NULL); #undef MAKE_PROG #define MAKE_PROG(T, MA, V1, V2, V3, V4, V5) \ if (MA != NULL) { \ free(MA); \ } MAKE_API(p, NULL, NULL, NULL, NULL, NULL) #undef MAKE_PROG #define MAKE_PROG(T, WR, WI, VL, VR, V4, V5) \ if (WR != NULL) { \ free(WR); \ } \ if (WI != NULL) { \ free(WI); \ } \ if (VL != NULL) { \ free(VL); \ } \ if (VR != NULL) { \ free(VR); \ } MAKE_API_REAL(wr, wi, vl, vr, NULL, NULL) #undef MAKE_PROG return 0; } // Eigen system of symmetric matrix: A = Z \Lambda Z^T (or Z^H) // // Here \Lambda is a diagonal matrix whose diagonal elements are the eigenvalues \lambda_i, and Z is // the // orthogonal matrix whose columns are the eigenvectors. int eigenh(int type, void *A, int r0, int c0, void *Lambda, int r1, int c1, void *Z, int r2, int c2) { int i, j; float *sp = NULL; double *dp = NULL; float complex *cp = NULL; double complex *zp = NULL; assert(r0 == c0); // square matrix. assert(r1 == 1 && c1 == c0); // Lambda is a vector. assert(r2 == 0 || (r0 == r2 && c0 == c2)); char jobz = r2 == 0 ? 'N' : 'V'; debug("eigenh is called, jobz: %c.", jobz); #define MAKE_PROG(T, COPY, SYEVD, V2, V3, V4, V5) \ cblas_##COPY(r0 *c0, (T *)A, 1, (T *)Z, 1); \ LAPACKE_##SYEVD(CblasRowMajor, jobz, 'U', r0, (T *)Z, c0, Lambda); MAKE_API_REAL(copy, syevd, NULL, NULL, NULL, NULL) #undef MAKE_PROG #define MAKE_PROG(T, COPY, HEEVD, V2, V3, V4, V5) \ cblas_##COPY(r0 *c0, (T *)A, 1, (T *)Z, 1); \ LAPACKE_##HEEVD(CblasRowMajor, jobz, 'U', r0, (T *)Z, c0, Lambda); MAKE_API_COMPLEX(copy, heevd, NULL, NULL, NULL, NULL) #undef MAKE_PROG return 0; } // AP = LU, where rm1 is L, rm2 is U, rm3 is P and m is A. int lu(int type, void *rm1, int r1, int c1, void *rm2, int r2, int c2, void *rm3, int r3, int c3, const void *m) { int i, j, t; float *sp; double *dp; // int *ipiv = (int *)malloc(c2 * sizeof(int)); // int *permutation = (int *)malloc(c2 * sizeof(int)); // assert(c1 == r2); // assert(c2 == c3); // assert(r3 == c3); // memset(ipiv, 0xff, sizeof(int) * c2); // memset(permutation, 0x00, sizeof(int) * c2); // debug("lu decompose is called."); // #define MAKE_PROG(T, V, F) \ // if (r1 > c1) { \ // V = (T *)rm1; \ // } else { \ // V = (T *)rm2; \ // } \ // cblas_##F(r1 *c2, (T *)m, 1, V, 1); // MAKE_API(p, copy); // #undef MAKE_PROG // #define MAKE_PROG(T, V, F) \ // /* do LU decomposition, compute matrix L and U. */ \ // // if (r1 > c1) { \ // // clapack_##F(CblasRowMajor, r1, c1, V, c1, ipiv); \ // // for (i = 0; i < r1 && i < c2; ++i) { \ // // j = i; \ // // while (++j < c1) { \ // // ((T *)rm2)[i * c2 + j] = V[i * c1 + j]; \ // // V[i * c1 + j] = 0.0; \ // // } \ // // ((T *)rm2)[i * c2 + i] = 1.0; \ // // } \ // // } else { \ // // clapack_##F(CblasRowMajor, r2, c2, V, c2, ipiv); \ // // for (i = 0; i < r1 && i < c2; ++i) { \ // // for (j = 0; j <= i; ++j) { \ // // ((T *)rm1)[i * c1 + j] = V[i * c2 + j]; \ // // V[i * c2 + j] = 0.0; \ // // } \ // // ((T *)rm2)[i * c2 + i] = 1.0; \ // // } \ // // } // // MAKE_API(p, getrf); // #undef MAKE_PROG // /* Compute permutation matrix P according to ipiv. */ // for (i = 0; i < c2; ++i) { // permutation[i] = i; // } // for (i = 0; i < c2; ++i) { // if (ipiv[i] >= 0 && ipiv[i] != i) { // t = permutation[i]; // permutation[i] = permutation[ipiv[i]]; // permutation[ipiv[i]] = t; // } // } // #define MAKE_PROG(T, V, F) \ // for (i = 0; i < r3; ++i) { \ // ((T *)rm3)[permutation[i] * c3 + i] = 1.0; \ // } // MAKE_API(NULL, NULL); // #undef MAKE_PROG // free(ipiv); // free(permutation); return 0; } // A = QR // // The shape of result Q and R decided by the argument (r1, c2) and (r2, c2). // // + The reduced mode: (equals to numpy's numpy.linalg.qr(src, mode='reduced')) // // A: m x n // Q: m x min(m, n) orthogonal matrix, the min(m, n) leading columns forms an orthonormal basis // in the // space spanned by the columns of A. // R: min(m, n) x n upper trapezoidal matrix, when m >= n, R is upper triangular. // // + The complete mode: (equals to numpy's numpy.linalg.qr(src, mode='complete')) // // A: m x n // Q: m x m orthogonal matrix, the min(m, n) leading columns forms an orthonormal basis in the // space spanned by the columns of A. // R: m x n upper trapezoidal matrix, when m >= n, R is upper triangular. // int qr(int type, void *A, int r0, int c0, void *Q, int r1, int c1, void *R, int r2, int c2) { float *stau = NULL; double *dtau = NULL; float complex *ctau = NULL; double complex *ztau = NULL; float *sp = NULL; double *dp = NULL; float complex *cp = NULL; double complex *zp = NULL; int i, j; debug("QR decomposition is called."); // reduced mode: // // assert(r0 == r1); // assert(min(r0, c0) == c1); // assert(min(r0, c0) == r2); // assert(c0 == c2); // complete mode: // // assert(r0 == r1); // assert(r0 == c1); // assert(r0 == r2); // assert(c0 == c2); #define MAKE_PROG(T, COPY, GEQRF, MA, TAU, _ZERO, V5) \ MA = (T *)malloc(r0 * c0 * sizeof(T)); \ cblas_##COPY(r0 *c0, (T *)A, 1, (T *)MA, 1); \ TAU = (T *)malloc(c0 * sizeof(T)); \ LAPACKE_##GEQRF(CblasRowMajor, r0, c0, (T *)MA, c0, (T *)TAU); \ /* initialize as zero */ \ memset(Q, 0x00, r1 *c1 * sizeof(T)); \ memset(R, 0x00, r2 *c2 * sizeof(T)); \ /* copy Q and R */ \ for (i = 0; i < r0; ++i) { \ j = 0; \ while (j < i) { \ ((T *)Q)[i * c1 + j] = ((T *)MA)[i * c0 + j]; \ j++; \ } \ while (j < c0) { \ ((T *)R)[i * c2 + j] = ((T *)MA)[i * c0 + j]; \ j++; \ } \ } MAKE_API(copy, geqrf, p, tau, _zero, NULL) #undef MAKE_PROG /* make Q */ #define MAKE_PROG(T, ORGQR, TAU, V2, V3, V4, V5) \ LAPACKE_##ORGQR(CblasRowMajor, r1, c1, min(r0, c0), Q, c1, (T *)TAU); MAKE_API_REAL(orgqr, tau, NULL, NULL, NULL, NULL) #undef MAKE_PROG #define MAKE_PROG(T, UNGQR, TAU, V2, V3, V4, V5) \ LAPACKE_##UNGQR(CblasRowMajor, r1, c1, min(r0, c0), Q, c1, (T *)TAU); MAKE_API_COMPLEX(ungqr, tau, NULL, NULL, NULL, NULL) #undef MAKE_PROG #define MAKE_PROG(T, MA, TAU, V2, V3, V4, V5) \ if (MA != NULL) { \ free(MA); \ } \ if (TAU != NULL) { \ free(TAU); \ } MAKE_API(p, tau, NULL, NULL, NULL, NULL) #undef MAKE_PROG return 0; } // Singular value decomposition: A = U \Sigma V^T (or V^H) int svd(int type, void *A, int r0, int c0, void *U, int r1, int c1, void *Sigma, int r2, int c2, void *VT, int r3, int c3) { char job = (r1 == 0 && r3 == 0) ? 'N' : (r0 != c0 && r1 == c1) ? 'A' : 'S'; debug("svd is called, job is %c.", job); #define MAKE_PROG(T, GESDD, V1, V2, V3, V4, V5) \ LAPACKE_##GESDD(CblasRowMajor, job, r0, c0, (T *)A, c0, Sigma, (T *)U, c1, (T *)VT, c3); MAKE_API(gesdd, NULL, NULL, NULL, NULL, NULL) #undef MAKE_PROG return 0; } int jordan(int type, void *rm1, int r1, int c1, void *rm2, int r2, int c2, void *rm3, int r3, int c3, const void *m) { return 0; } int cholesky(int type, char uplo, void *A, int r0, int c0, void *U, int r1, int c1) { assert(r0 == c0); // square matrix. assert(r0 == r1); assert(c0 == c1); debug("cholesky is called."); #define MAKE_PROG(T, COPY, POTRF, V2, V3, V4, V5) \ cblas_##COPY(r0 *c0, (const T *)A, 1, (T *)U, 1); \ LAPACKE_##POTRF(CblasRowMajor, uplo, r0, (T *)U, c0); MAKE_API(copy, potrf, NULL, NULL, NULL, NULL) #undef MAKE_PROG return 0; } int schur(int type, void *rm1, int r1, int c1, void *rm2, int r2, int c2, void *rm3, int r3, int c3, const void *m) { return 0; } // Linear transformation: r = Av. int transform(int type, void *r, int row, int column, const void *A, const void *v) { float salpha = 1., sbeta = 0.; double dalpha = 1., dbeta = 0.; float complex _calpha = 1. + 0. * I, _cbeta = 0. + 0. * I; double complex _zalpha = 1. + 0. * I, _zbeta = 0. + 0. * I; float complex *calpha = &_calpha, *cbeta = &_cbeta; double complex *zalpha = &_zalpha, *zbeta = &_zbeta; debug("transform is called: matrix has size (%d, %d).", row, column); #define MAKE_PROG(T, GEMV, ALPHA, BETA, V3, V4, V5) \ cblas_##GEMV(CblasRowMajor, CblasNoTrans, row, column, ALPHA, (const T *)A, column, \ (const T *)v, 1, BETA, (T *)r, 1); MAKE_API(gemv, alpha, beta, NULL, NULL, NULL) #undef MAKE_PROG return 0; } // Linear array generation. int linspace(int type, void *r, float const start, float const end, int size) { float sep = (end - start) / (size - 1); float ssep = sep; double dsep = (double)sep; float complex csep = sep + 0. * I; double complex zsep = (double)sep + 0. * I; float sval = start; double dval = (double)start; float complex cval = start + 0. * I; double complex zval = (double)start + 0. * I; int i; #define MAKE_PROG(T, SEP, VAL, V2, V3, v4, V5) \ for (i = 0; i < size; ++i, VAL += SEP) { \ ((T *)r)[i] = VAL; \ } MAKE_API(sep, val, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } int replicate(int type, void *r, void const *value, int size) { int i; #define MAKE_PROG(T, V0, V1, V2, V3, V4, V5) \ for (i = 0; i < size; ++i) { \ ((T *)r)[i] = *((T *)value); \ } MAKE_API(NULL, NULL, NULL, NULL, NULL, NULL) #undef MAKE_PROG return 0; } // element-wise functions. int logistic(int type, void *r, const void *A, int row, int column) { int i; const float sunit = 1.; const double dunit = 1.; const float complex cunit = 1. + 0. * I; const double complex zunit = 1. + 0. * I; switch (type) { case 1: for (int i = 0; i < row * column; ++i) { ((float *)r)[i] = sunit / (sunit + exp(- ((float *)A)[i])); } break; case 2: for (int i = 0; i < row * column; ++i) { ((double *)r)[i] = dunit / (dunit + exp(- ((double *)A)[i])); } break; case 3: for (int i = 0; i < row * column; ++i) { ((float complex *)r)[i] = cunit / (cunit + cexp(- ((float complex *)A)[i])); } break; case 4: for (int i = 0; i < row * column; ++i) { ((double complex *)r)[i] = zunit / (zunit + cexp(- ((double complex *)A)[i])); } break; default: break; } return 0; } int logisticd(int type, void *r, const void *A, int row, int column) { int i; const float sunit = 1.; const double dunit = 1.; const float complex cunit = 1. + 0. * I; const double complex zunit = 1. + 0. * I; logistic(type, r, A, row, column); #define MAKE_PROG(T, UNIT, V1, V2, V3, V4, V5) \ for (i = 0; i < row * column; ++i) { \ ((T *)r)[i] = ((T *)r)[i] * (UNIT - ((T *)r)[i]); \ } MAKE_API(unit, NULL, NULL, NULL, NULL, NULL); #undef MAKE_PROG return 0; } #if defined(__cplusplus) } #endif // __cplusplus
{ "alphanum_fraction": 0.4227235633, "avg_line_length": 37.315324165, "ext": "c", "hexsha": "29735eea110783feafb45564ac5d474bd239df73", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-02-04T11:37:33.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-04T11:37:33.000Z", "max_forks_repo_head_hexsha": "f358abb136227912c94457e241d0966419d2b619", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sighingnow/computations", "max_forks_repo_path": "math-foreign/cbits/linear.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f358abb136227912c94457e241d0966419d2b619", "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": "sighingnow/computations", "max_issues_repo_path": "math-foreign/cbits/linear.c", "max_line_length": 100, "max_stars_count": 7, "max_stars_repo_head_hexsha": "f358abb136227912c94457e241d0966419d2b619", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sighingnow/computations", "max_stars_repo_path": "math-foreign/cbits/linear.c", "max_stars_repo_stars_event_max_datetime": "2019-11-27T05:57:33.000Z", "max_stars_repo_stars_event_min_datetime": "2017-09-08T11:42:53.000Z", "num_tokens": 11518, "size": 37987 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C code for the implementation of the Fourier-domain overlaps, likelihoods. * */ #define _XOPEN_SOURCE 500 #ifdef __GNUC__ #define UNUSED __attribute__ ((unused)) #else #define UNUSED #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <time.h> #include <unistd.h> #include <getopt.h> #include <stdbool.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_min.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_complex.h> #include "constants.h" #include "struct.h" #include "splinecoeffs.h" #include "fresnel.h" #include "likelihood.h" #include "wip.h" #include <time.h> /* for testing */ /* Number of points to be used in linear integration - hardcoded for now */ #define nbptsintdefault 32768 /* Default number of points to use for linear overlaps */ /********************************* Utilities ****************************************/ /* Function to evaluate a Noise function */ void EvaluateNoise( gsl_vector* noisevalues, /* Output: vector of the noise values */ gsl_vector* freq, /* Input: vector of frequencies on which to evaluate */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh) /* Upper bound of the frequency window for the detector */ { int nbpts = (int) freq->size; /* Checking the length */ if( freq->size != noisevalues->size) { printf("Error: incompatible sizes in EvaluateNoise.\n"); exit(1); } /* Checking the boundary frequencies */ if( gsl_vector_get(freq, 0) - fLow < -1e-15 || gsl_vector_get(freq, nbpts-1) > fHigh + 1e-15 ) { printf("Error: incompatible frequency range in EvaluateNoise.\n"); printf("freq[0]=%g vs fLow=%g, freq[max]=%g vs fHigh=%g\n",gsl_vector_get(freq, 0), fLow, gsl_vector_get(freq, nbpts-1), fHigh); printf(" %i, %i\n",gsl_vector_get(freq, 0) < fLow , gsl_vector_get(freq, nbpts-1) > fHigh); printf("%g\n",gsl_vector_get(freq, 0) - fLow); exit(1); } for(int i=0; i<nbpts; i++) { gsl_vector_set(noisevalues, i, ObjectFunctionCall(Snoise,gsl_vector_get(freq, i))); } } /* Function building a frequency vector with linear or logarithmic sampling */ void SetLinearFrequencies( gsl_vector* freqvector, /* Output pointer to gsl_vector, already allocated */ const double fmin, /* Lower bound of the frequency interval */ const double fmax, /* Upper bound of the frequency interval */ const int nbpts) /* Number of points */ { /* Vector of frequencies with logarithmic spacing */ double stepf = (fmax-fmin)/(nbpts-1.); for(int i=0; i<nbpts; i++) { gsl_vector_set(freqvector, i, fmin + i * stepf); } } void SetLogFrequencies( gsl_vector* freqvector, /* Output pointer to gsl_vector, already allocated */ const double fmin, /* Lower bound of the frequency interval */ const double fmax, /* Upper bound of the frequency interval */ const int nbpts) /* Number of points */ { /* Vector of frequencies with logarithmic spacing */ double lnratio = log(fmax/fmin); double lnfmin = log(fmin); for(int i=0; i<nbpts; i++) { gsl_vector_set(freqvector, i, exp(lnfmin + (double) i/(nbpts-1.) * lnratio)); } } /* Function determining logarithmically spaced frequencies from a waveform given as a list of modes, a minimal frequency and a number of points */ void ListmodesSetFrequencies( struct tagListmodesCAmpPhaseFrequencySeries *list, /* Waveform, list of modes in amplitude/phase form */ double fLow, /* Additional lower frequency limit */ double fHigh, /* Additional upper frequency limit */ int nbpts, /* Number of frequency samples */ int tagsampling, /* Tag for linear (0) or logarithmic (1) sampling */ gsl_vector* freqvector) /* Output: vector of frequencies, already allocated with nbpts */ { /* Checking the length */ if((int) freqvector->size != nbpts) { printf("Error: incompatible sizes in ListmodesSetFrequencies.\n"); exit(1); } /* Determining the frequency interval - from the lowest frequency of the 22 mode to the highest frequency covered by at least one mode */ double minf, maxf; ListmodesCAmpPhaseFrequencySeries* listelementmode22 = ListmodesCAmpPhaseFrequencySeries_GetMode(list, 2, 2); minf = gsl_vector_get(listelementmode22->freqseries->freq, 0); maxf = gsl_vector_get(list->freqseries->freq, (int) list->freqseries->freq->size - 1); ListmodesCAmpPhaseFrequencySeries* listelement = list; while(listelement) { maxf = fmax(maxf, gsl_vector_get(listelement->freqseries->freq, (int) listelement->freqseries->freq->size - 1)); listelement = listelement->next; } /* Checking that the waveform covers the fLow */ if(fLow < minf) printf("Warning: in ListmodesSetFrequencies, fLow not covered by the wave data.\n"); /* Actual boundaries of the frequency vector - cuts what is below fLow and above fHigh */ minf = fmax(minf, fLow); maxf = fmin(maxf, fHigh); /* Setting values of the vector of frequencies, linear or logarithmic sampling */ if(tagsampling==0) SetLinearFrequencies(freqvector, minf, maxf, nbpts); else if(tagsampling==1) SetLogFrequencies(freqvector, minf, maxf, nbpts); else { printf("Error: incorrect tagsampling in ListmodesSetFrequencies."); exit(1); } } /* Function computing a simple trapeze integration for real data */ static double TrapezeIntegrate(const gsl_vector* x, const gsl_vector* y) { if(x->size!=y->size) { printf("Error: trying to apply TrapezeIntegrate on vectors of different lengths.\n"); exit(1); } int N = ((int) x->size) - 1; double result = 0.; for(int i=0; i<N; i++){ result += (gsl_vector_get(x, i+1) - gsl_vector_get(x, i)) * (gsl_vector_get(y, i) + gsl_vector_get(y, i+1))/2.; } return result; } /***************************** Functions for overlaps using linear integration ******************************/ /* Function computing the overlap (h1|h2) between two given modes, for a given noise function - uses simple trapeze integration on logarithmically sampled frequencies */ double FDSinglemodeLogLinearOverlap( struct tagCAmpPhaseFrequencySeries *freqseries1, /* First mode h1, in amplitude/phase form */ struct tagCAmpPhaseFrequencySeries *freqseries2, /* Second mode h2, in amplitude/phase form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh) /* Upper bound of the frequency window for the detector */ { double res; int size1 = (int) freqseries1->freq->size; int size2 = (int) freqseries2->freq->size; int nbpts = nbptsintdefault; /* Minimal, maximal frequencies */ double fmin1 = gsl_vector_get(freqseries1->freq, 0); double fmin2 = gsl_vector_get(freqseries2->freq, 0); double fmax1 = gsl_vector_get(freqseries1->freq, size1 - 1); double fmax2 = gsl_vector_get(freqseries2->freq, size2 - 1); double fmin0 = fmax(fLow, fmax(fmin1, fmin2)); double fmax0 = fmin(fHigh, fmin(fmax1, fmax2)); /* Vector of frequencies with logarithmic spacing */ gsl_vector* freqvector = gsl_vector_alloc(nbpts); SetLogFrequencies(freqvector, fmin0, fmax0, nbpts); /* Initializing the splines */ /* Note: since this must also apply to mode contribution after processing, real and imaginary parts of the amplitude are present - but since they should differ for LLV detectors by a constant factor, they can be interpolated */ gsl_interp_accel* accel_amp1real = gsl_interp_accel_alloc(); gsl_interp_accel* accel_amp2real = gsl_interp_accel_alloc(); gsl_interp_accel* accel_amp1imag = gsl_interp_accel_alloc(); gsl_interp_accel* accel_amp2imag = gsl_interp_accel_alloc(); gsl_interp_accel* accel_phase1 = gsl_interp_accel_alloc(); gsl_interp_accel* accel_phase2 = gsl_interp_accel_alloc(); gsl_spline* amp1real = gsl_spline_alloc(gsl_interp_cspline, size1); gsl_spline* amp2real = gsl_spline_alloc(gsl_interp_cspline, size2); gsl_spline* amp1imag = gsl_spline_alloc(gsl_interp_cspline, size1); gsl_spline* amp2imag = gsl_spline_alloc(gsl_interp_cspline, size2); gsl_spline* phase1 = gsl_spline_alloc(gsl_interp_cspline, size1); gsl_spline* phase2 = gsl_spline_alloc(gsl_interp_cspline, size2); gsl_vector* valuesvector = gsl_vector_alloc(nbpts); gsl_spline_init(amp1real, gsl_vector_const_ptr(freqseries1->freq,0), gsl_vector_const_ptr(freqseries1->amp_real,0), size1); gsl_spline_init(amp1imag, gsl_vector_const_ptr(freqseries1->freq,0), gsl_vector_const_ptr(freqseries1->amp_imag,0), size1); gsl_spline_init(amp2real, gsl_vector_const_ptr(freqseries2->freq,0), gsl_vector_const_ptr(freqseries2->amp_real,0), size2); gsl_spline_init(amp2imag, gsl_vector_const_ptr(freqseries2->freq,0), gsl_vector_const_ptr(freqseries2->amp_imag,0), size2); gsl_spline_init(phase1, gsl_vector_const_ptr(freqseries1->freq,0), gsl_vector_const_ptr(freqseries1->phase,0), size1); gsl_spline_init(phase2, gsl_vector_const_ptr(freqseries2->freq,0), gsl_vector_const_ptr(freqseries2->phase,0), size2); /* Main loop - vector of values to be evaluated */ double f, phi1, phi2, Sn; double complex A1; double complex A2; double* freqvectordata = freqvector->data; double* valuesvectordata = valuesvector->data; int i=0; for(i=0; i<nbpts; i++){ if(i==0) {f = fmax(freqvectordata[i], fmin0);} else if(i==nbpts-1) {f = fmin(freqvectordata[i], fmax0);} else {f = freqvectordata[i];} A1 = gsl_spline_eval(amp1real, f, accel_amp1real) + I*gsl_spline_eval(amp1imag, f, accel_amp1imag); A2 = gsl_spline_eval(amp2real, f, accel_amp2real) + I*gsl_spline_eval(amp2imag, f, accel_amp2imag); phi1 = gsl_spline_eval(phase1, f, accel_phase1); phi2 = gsl_spline_eval(phase2, f, accel_phase2); Sn = ObjectFunctionCall(Snoise,f); valuesvectordata[i] = 4.*creal(A1*conj(A2)*cexp(I*(phi1-phi2))/Sn); } /* Trapeze integration */ res = TrapezeIntegrate(freqvector, valuesvector); /* Clean up */ gsl_vector_free(freqvector); gsl_vector_free(valuesvector); gsl_interp_accel_free(accel_amp1real); gsl_interp_accel_free(accel_amp2real); gsl_interp_accel_free(accel_amp1imag); gsl_interp_accel_free(accel_amp2imag); gsl_interp_accel_free(accel_phase1); gsl_interp_accel_free(accel_phase2); gsl_spline_free(amp1real); gsl_spline_free(amp2real); gsl_spline_free(amp1imag); gsl_spline_free(amp2imag); gsl_spline_free(phase1); gsl_spline_free(phase2); return res; } /* Function computing the overlap (h1|h2) between two waveforms given as lists of mode contributions (factos sYlm already included), for a given noise function - uses simple trapeze integration on logarithmically sampled frequencies - generates the frequency series in Re/Im form by summing the mode contributions first, then computes the overlap */ double FDListmodesLogLinearOverlap( struct tagListmodesCAmpPhaseFrequencySeries *list1, /* First waveform, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseFrequencySeries *list2, /* Second waveform, list of modes in amplitude/phase form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh, /* Upper bound of the frequency window for the detector */ double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */ double fstartobs2) /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */ { /* Number of points to use in the trapeze integration */ int nbpts = nbptsintdefault; /* Determining the frequency interval - from the lowest frequency of the 22 mode to the highest frequency covered by at least one mode */ double minf1, maxf1, minf2, maxf2, minf, maxf; ListmodesCAmpPhaseFrequencySeries* listelement1mode22 = ListmodesCAmpPhaseFrequencySeries_GetMode(list1, 2, 2); ListmodesCAmpPhaseFrequencySeries* listelement2mode22 = ListmodesCAmpPhaseFrequencySeries_GetMode(list2, 2, 2); minf1 = gsl_vector_get(listelement1mode22->freqseries->freq, 0); minf2 = gsl_vector_get(listelement2mode22->freqseries->freq, 0); maxf1 = ListmodesCAmpPhaseFrequencySeries_maxf(list1); maxf2 = ListmodesCAmpPhaseFrequencySeries_maxf(list2); /* Taking into account fLow, fHigh -- fstartobs, determined from 22 mode, is also used as a fLow */ if(!(fHigh==0.)) { maxf1 = fmin(maxf1, fHigh); maxf2 = fmin(maxf2, fHigh); } if(!(fLow==0.)) { minf1 = fmax(minf1, fLow); minf2 = fmax(minf2, fLow); } if(!(fstartobs1==0.)) minf1 = fmax(minf1, fstartobs1); if(!(fstartobs2==0.)) minf1 = fmax(minf2, fstartobs2); /* Actual boundaries to be used in the overlap - intersection of freqs covered by wf 1 and 2 */ minf = fmax(minf1, minf2); maxf = fmin(maxf1, maxf2); /* Vector of frequencies used for the overlap */ gsl_vector* freqoverlap = gsl_vector_alloc(nbpts); SetLogFrequencies(freqoverlap, minf, maxf, nbpts); /* Evaluating each frequency series by interpolating and summing the mode contributions */ ReImFrequencySeries* freqseries1 = NULL; ReImFrequencySeries_Init(&freqseries1, nbpts); ReImFrequencySeries_SumListmodesCAmpPhaseFrequencySeries(freqseries1, list1, freqoverlap, fLow, fHigh, fstartobs1); ReImFrequencySeries* freqseries2 = NULL; ReImFrequencySeries_Init(&freqseries2, nbpts); ReImFrequencySeries_SumListmodesCAmpPhaseFrequencySeries(freqseries2, list2, freqoverlap, fLow, fHigh, fstartobs2); /* Compute the integrand */ gsl_vector* valuesoverlap = gsl_vector_alloc(nbpts); double* hreal1data = freqseries1->h_real->data; double* himag1data = freqseries1->h_imag->data; double* hreal2data = freqseries2->h_real->data; double* himag2data = freqseries2->h_imag->data; double* freqdata = freqoverlap->data; for(int i=0; i<nbpts; i++) { gsl_vector_set(valuesoverlap, i, 4.*creal( (hreal1data[i] + I*himag1data[i]) * (hreal2data[i] - I*himag2data[i]) / ObjectFunctionCall(Snoise,freqdata[i]))); } /* Final trapeze integration */ double overlap = TrapezeIntegrate(freqoverlap, valuesoverlap); /* Clean up */ ReImFrequencySeries_Cleanup(freqseries1); ReImFrequencySeries_Cleanup(freqseries2); gsl_vector_free(freqoverlap); gsl_vector_free(valuesoverlap); return overlap; } /* Function computing the overlap (h1|h2) between h1 given in Re/Im form and h2 given as a list of mode contributions (factors sYlm already included), for a given vector of noise values - uses simple trapeze integration - generates the frequency series of h2 in Re/Im form by summing the mode contributions first, then computes the overlap */ double FDOverlapReImvsListmodesCAmpPhase( struct tagReImFrequencySeries *freqseries1, /* First waveform, in Re/Im form */ struct tagListmodesCAmpPhaseFrequencySeries *list2, /* Second waveform, list of modes in amplitude/phase form */ gsl_vector* noisevalues, /* Vector for the noise values on the freq of h1 */ double fLow, /* Minimal frequency - set to 0 to ignore */ double fHigh, /* Maximal frequency - set to 0 to ignore */ double fstartobs2) /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */ { /* Check the lengths */ if(freqseries1->freq->size != noisevalues->size) { printf("Error: inconsistent lengths in FDOverlapReImvsListmodesCAmpPhase.\n"); exit(1); } /* Frequencies used for the overlap */ int nbpts = (int) freqseries1->freq->size; gsl_vector* freqoverlap = freqseries1->freq; /* Evaluating frequency series 2 by interpolating and summing the mode contributions */ ReImFrequencySeries* freqseries2 = NULL; ReImFrequencySeries_Init(&freqseries2, nbpts); ReImFrequencySeries_SumListmodesCAmpPhaseFrequencySeries(freqseries2, list2, freqoverlap, fLow, fHigh, fstartobs2); /* Compute the integrand */ gsl_vector* valuesoverlap = gsl_vector_alloc(nbpts); double* hreal1data = freqseries1->h_real->data; double* himag1data = freqseries1->h_imag->data; double* hreal2data = freqseries2->h_real->data; double* himag2data = freqseries2->h_imag->data; double* noisedata = noisevalues->data; for(int i=0; i<nbpts; i++) { gsl_vector_set(valuesoverlap, i, 4.*creal( (hreal1data[i] + I*himag1data[i]) * (hreal2data[i] - I*himag2data[i]) / noisedata[i])); } /* Final trapeze integration */ double overlap = TrapezeIntegrate(freqoverlap, valuesoverlap); /* Clean up */ ReImFrequencySeries_Cleanup(freqseries2); gsl_vector_free(valuesoverlap); return overlap; } /* Function computing the overlap (h1|h2) between two waveforms given as Re/Im frequency series (common freq values assumed), for a given vector of noise values - uses simple trapeze integration */ double FDOverlapReImvsReIm( struct tagReImFrequencySeries *freqseries1, /* First waveform, frequency series in Re/Im form */ struct tagReImFrequencySeries *freqseries2, /* Second waveform, frequency series in Re/Im form */ gsl_vector* noisevalues) /* Vector for the noise values on common freq of the freqseries */ { /* Check the lengths */ if(freqseries1->freq->size != noisevalues->size || freqseries2->freq->size != noisevalues->size) { printf("Error: inconsistent lengths in FDOverlapReImvsReIm.\n"); exit(1); } /* Frequency vector - assuming they match beyond their mere lengths */ gsl_vector* freqoverlap = freqseries1->freq; int nbpts = (int) freqoverlap->size; /* Compute the integrand */ gsl_vector* valuesoverlap = gsl_vector_alloc((int) freqoverlap->size); double* hreal1data = freqseries1->h_real->data; double* himag1data = freqseries1->h_imag->data; double* hreal2data = freqseries2->h_real->data; double* himag2data = freqseries2->h_imag->data; double* noisedata = noisevalues->data; for(int i=0; i<nbpts; i++) { gsl_vector_set(valuesoverlap, i, 4.*creal( (hreal1data[i] + I*himag1data[i]) * (hreal2data[i] - I*himag2data[i]) / noisedata[i])); } /* Final trapeze integration */ double overlap = TrapezeIntegrate(freqoverlap, valuesoverlap); /* Clean up */ gsl_vector_free(valuesoverlap); return overlap; } /***************************** Functions for overlaps using amplitude/phase (wip) ******************************/ /* Function computing the overlap (h1|h2) between two given modes in amplitude/phase form, for a given noise function - uses the amplitude/phase representation (wip) */ double FDSinglemodeWIPOverlap( struct tagCAmpPhaseFrequencySeries *freqseries1, /* First mode h1, in amplitude/phase form */ struct tagCAmpPhaseFrequencySeries *freqseries2, /* Second mode h2, in amplitude/phase form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh) /* Upper bound of the frequency window for the detector */ { /* Should add some error checking */ CAmpPhaseFrequencySeries* h1 = freqseries1; CAmpPhaseFrequencySeries* h2 = freqseries2; double *f1 = h1->freq->data; int n1 = h1->freq->size; double *h1Ar = h1->amp_real->data; double *h1Ai = h1->amp_imag->data; double *h1p = h1->phase->data; double *f2 = h2->freq->data; int n2 = h2->freq->size; double *h2Ar = h2->amp_real->data; double *h2Ai = h2->amp_imag->data; double *h2p = h2->phase->data; /* fLow or fHigh <= 0 means use intersection of signal domains */ /* NOTE: factor 4 was previously missing */ double overlap = 4.*wip_phase(f1, n1, f2, n2, h1Ar, h1Ai, h1p, h2Ar, h2Ai, h2p, Snoise, 1.0, fLow, fHigh); return overlap; } /* Function computing the overlap (h1|h2) between two waveforms given as list of modes, for a given noise function - two additional parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */ double FDListmodesWIPOverlap( struct tagListmodesCAmpPhaseFrequencySeries *listh1, /* First waveform, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseFrequencySeries *listh2, /* Second waveform, list of modes in amplitude/phase form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh, /* Upper bound of the frequency window for the detector */ double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */ double fstartobs2) /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */ { double overlap = 0; /* Main loop over the modes - goes through all the modes present */ ListmodesCAmpPhaseFrequencySeries* listelementh1 = listh1; while(listelementh1) { ListmodesCAmpPhaseFrequencySeries* listelementh2 = listh2; while(listelementh2) { /* Scaling fstartobs1/2 with the appropriate factor of m (for the 21 mode we use m=2) - setting fmin in the overlap accordingly */ int mmax1 = max(2, listelementh1->m); int mmax2 = max(2, listelementh2->m); double fcutLow = fmax(fLow, fmax(((double) mmax1)/2. * fstartobs1, ((double) mmax2)/2. * fstartobs2)); overlap += FDSinglemodeWIPOverlap(listelementh1->freqseries, listelementh2->freqseries, Snoise, fcutLow, fHigh); listelementh2 = listelementh2->next; } listelementh1 = listelementh1->next; } return overlap; } /************** Functions for overlap/likelihood allowing to switch between wip and loglinear integration *****************/ /* Wrapping of FDListmodesWIPOverlap or FDListmodesLogLinearOverlap according to tagint */ double FDListmodesOverlap( struct tagListmodesCAmpPhaseFrequencySeries *listh1, /* First mode h1, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseFrequencySeries *listh2, /* Second mode h2, list of modes in amplitude/phase form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh, /* Upper bound of the frequency window for the detector */ double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */ double fstartobs2, /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */ int tagint) /* Tag choosing the integrator: 0 for wip, 1 for log linear integration */ { double overlap; if(tagint==0) { overlap = FDListmodesWIPOverlap(listh1, listh2, Snoise, fLow, fHigh, fstartobs1, fstartobs2); } else if(tagint==1) { overlap = FDListmodesLogLinearOverlap(listh1, listh2, Snoise, fLow, fHigh, fstartobs1, fstartobs2); } return overlap; } /* Function computing the log likelihood (h|s) - 1/2 (h|h) - 1/2 (s|s), with s the signal, h the template, and where we keep the constant term (s|s) - passed to the function as a parameter - all the cross-products between modes are taken into account - two additionals parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */ double FDLogLikelihood( struct tagListmodesCAmpPhaseFrequencySeries *lists, /* Input: list of modes for the signal s, in Frequency-domain amplitude and phase form */ struct tagListmodesCAmpPhaseFrequencySeries *listh, /* Input: list of modes for the template, in Frequency-domain amplitude and phase form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh, /* Upper bound of the frequency window for the detector */ double ss, /* Inner product (s|s), constant to be computed elsewhere and passed as an argument */ double hh, /* Inner product (h|h), constant to be computed elsewhere and passed as an argument */ double fstartobss, /* Starting frequency for the 22 mode of s - as determined from a limited duration of the observation - set to 0 to ignore */ double fstartobsh, /* Starting frequency for the 22 mode of h - as determined from a limited duration of the observation - set to 0 to ignore */ int tagint) /* Tag choosing the integrator: 0 for wip, 1 for log linear integration */ { double lnL; if(tagint==0) { lnL = FDListmodesWIPOverlap(lists, listh, Snoise, fLow, fHigh, fstartobss, fstartobsh) - 1./2 * hh - 1./2 * ss; } else if(tagint==1) { lnL = FDListmodesLogLinearOverlap(lists, listh, Snoise, fLow, fHigh, fstartobss, fstartobsh) - 1./2 * hh - 1./2 * ss; } return lnL; } /************** Functions for overlap/likelihood specific to loglinear integration *****************/ /* Function computing the log likelihood -1/2(h-s|h-s), with s the signal, h the template (both given as frequency series in Re/Im form) - h, s assumed to be given on the same set of frequencies - same for the vector of noise values - fstartobs for s, h has already been taken into account */ double FDLogLikelihoodReIm( struct tagReImFrequencySeries *s, /* First waveform (injection), frequency series in Re/Im form */ struct tagReImFrequencySeries *h, /* Second waveform (template), frequency series in Re/Im form */ gsl_vector* noisevalues) /* Vector for the noise values on common freq of the freqseries */ { /* Check the lengths */ if(s->freq->size != noisevalues->size || h->freq->size != noisevalues->size) { printf("Error: inconsistent lengths in FDLogLikelihoodReIm.\n"); exit(1); } /* Taking the difference between the frequency series: diff = h-s */ int nbpts = (int) s->freq->size; ReImFrequencySeries* diff = NULL; ReImFrequencySeries_Init(&diff, nbpts); gsl_vector_memcpy(diff->freq, s->freq); gsl_vector_memcpy(diff->h_real, h->h_real); gsl_vector_memcpy(diff->h_imag, h->h_imag); gsl_vector_sub(diff->h_real, s->h_real); gsl_vector_sub(diff->h_imag, s->h_imag); /* Likelihood lnL = -1/2(h-s|h-s) */ double lnL; lnL = -1./2 * FDOverlapReImvsReIm(diff, diff, noisevalues); /* Clean up */ ReImFrequencySeries_Cleanup(diff); return lnL; } /***************************** Functions for overlaps using amplitude/phase (Fresnel) ******************************/ /* Moved these to splinecoeffs.c // Note: for the spines in matrix form, the first column contains the x values, so the coeffs start at 1 static double EvalCubic( gsl_vector* coeffs, double eps, double eps2, double eps3) { double p0 = gsl_vector_get(coeffs, 1); double p1 = gsl_vector_get(coeffs, 2); double p2 = gsl_vector_get(coeffs, 3); double p3 = gsl_vector_get(coeffs, 4); return p0 + p1*eps + p2*eps2 + p3*eps3; } static double EvalQuad( gsl_vector* coeffs, double eps, double eps2) { double p0 = gsl_vector_get(coeffs, 1); double p1 = gsl_vector_get(coeffs, 2); double p2 = gsl_vector_get(coeffs, 3); return p0 + p1*eps + p2*eps2; } */ /* Quadratic Legendre approximation to compute values at minf and maxf when they do not fall on the grid of a freqseries, using the two first/last intervals */ static double EstimateBoundaryLegendreQuad( gsl_vector* vectx, /**/ gsl_vector* vecty, /**/ int j, /**/ double xvalue) /**/ { double x0 = 0; double x1 = gsl_vector_get(vectx, j+1) - gsl_vector_get(vectx, j); double x2 = gsl_vector_get(vectx, j+2) - gsl_vector_get(vectx, j); double x = xvalue - gsl_vector_get(vectx, j); double y0 = gsl_vector_get(vecty, j); double y1 = gsl_vector_get(vecty, j+1); double y2 = gsl_vector_get(vecty, j+2); if(!(x>=x0 && x<=x2)) { printf("Error: value out of bounds in EstimateBoundaryLegendreQuad.\n"); exit(1); } return y0*(x-x1)*(x-x2)/(x0-x1)/(x0-x2) + y1*(x-x0)*(x-x2)/(x1-x0)/(x1-x2) + y2*(x-x0)*(x-x1)/(x2-x0)/(x2-x1); } /* Function computing the integrand values */ void ComputeIntegrandValues( CAmpPhaseFrequencySeries** integrand, /* Output: values of the integrand on common frequencies (initialized in the function) */ CAmpPhaseFrequencySeries* freqseries1, /* Input: frequency series for wf 1 */ CAmpPhaseSpline* splines2, /* Input: splines in matrix form for wf 2 */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency - 0 to ignore */ double fHigh) /* Upper bound of the frequency - 0 to ignore */ { gsl_set_error_handler(&Err_Handler); /* Determining the boundaries of indices */ gsl_vector* freq1 = freqseries1->freq; int imin1 = 0; int imax1 = freq1->size - 1; double* f1 = freq1->data; double f2min = gsl_matrix_get(splines2->quadspline_phase, 0, 0); double f2max = gsl_matrix_get(splines2->quadspline_phase, splines2->quadspline_phase->size1 - 1, 0); if((fLow>0 && (f1[imax1]<=fLow || f2max<=fLow)) || (fHigh>0 && (f1[imin1]>=fHigh || f2min>=fHigh))) { printf("Error: range of frequencies incompatible with fLow, fHigh in IntegrandValues.\n"); printf("need one of {%g, %g} <= %g and one of {%g, %g}>=%g\n",f1[imax1],f2max,fLow,f1[imin1],f2min,fHigh); exit(1); } /* If starting outside, move the ends of the frequency series to be just outside the final minf and maxf */ double minf = fmax(f1[imin1], f2min); double maxf = fmin(f1[imax1], f2max); if(fLow>0) {minf = fmax(fLow, minf);} if(fHigh>0) {maxf = fmin(fHigh, maxf);} while(f1[imin1+1]<=minf) imin1++; while(f1[imax1-1]>=maxf) imax1--; /* Estimate locally values for freqseries1 at the boundaries */ double areal1minf = EstimateBoundaryLegendreQuad(freq1, freqseries1->amp_real, imin1, minf); double aimag1minf = EstimateBoundaryLegendreQuad(freq1, freqseries1->amp_imag, imin1, minf); double phi1minf = EstimateBoundaryLegendreQuad(freq1, freqseries1->phase, imin1, minf); double areal1maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1->amp_real, imax1-2, maxf); /* Note the imax1-2 */ double aimag1maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1->amp_imag, imax1-2, maxf); /* Note the imax1-2 */ double phi1maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1->phase, imax1-2, maxf); /* Note the imax1-2 */ /* Initializing output structure */ int nbpts = imax1 + 1 - imin1; CAmpPhaseFrequencySeries_Init(integrand, nbpts); /* Loop computing integrand values */ gsl_vector* freq = (*integrand)->freq; gsl_vector* ampreal = (*integrand)->amp_real; gsl_vector* ampimag = (*integrand)->amp_imag; gsl_vector* phase = (*integrand)->phase; double f, eps, eps2, eps3, ampreal1, ampimag1, phase1, ampreal2, ampimag2, phase2, invSn; double complex camp; double* areal1 = freqseries1->amp_real->data; double* aimag1 = freqseries1->amp_imag->data; double* phi1 = freqseries1->phase->data; gsl_matrix* splineAreal2 = splines2->spline_amp_real; gsl_matrix* splineAimag2 = splines2->spline_amp_imag; gsl_matrix* quadsplinephase2 = splines2->quadspline_phase; int i2 = 0; int j = 0; for(int i=imin1; i<=imax1; i++) { /* Distinguish the case where we are at minf or maxf */ if(i==imin1) { f = minf; ampreal1 = areal1minf; ampimag1 = aimag1minf; phase1 = phi1minf; } else if(i==imax1) { f = maxf; ampreal1 = areal1maxf; ampimag1 = aimag1maxf; phase1 = phi1maxf; } else { f = gsl_vector_get(freq1, i); ampreal1 = areal1[i]; ampimag1 = aimag1[i]; phase1 = phi1[i]; } /* Adjust the index in the spline if necessary and compute */ while(gsl_matrix_get(splines2->quadspline_phase, i2+1, 0)<f) i2++; eps = f - gsl_matrix_get(splines2->quadspline_phase, i2, 0); eps2 = eps*eps; eps3 = eps2*eps; gsl_vector_view coeffsampreal2 = gsl_matrix_row(splineAreal2, i2); gsl_vector_view coeffsampimag2 = gsl_matrix_row(splineAimag2, i2); gsl_vector_view coeffsphase2 = gsl_matrix_row(quadsplinephase2, i2); ampreal2 = EvalCubic(&coeffsampreal2.vector, eps, eps2, eps3); ampimag2 = EvalCubic(&coeffsampimag2.vector, eps, eps2, eps3); phase2 = EvalQuad(&coeffsphase2.vector, eps, eps2); invSn = 1./ObjectFunctionCall(Snoise,f); camp = invSn * (ampreal1 + I*ampimag1) * (ampreal2 - I*ampimag2); gsl_vector_set(freq, j, f); gsl_vector_set(ampreal, j, creal(camp)); gsl_vector_set(ampimag, j, cimag(camp)); gsl_vector_set(phase, j, phase1 - phase2); j++; } } /* Function computing the integrand values, combining three non-correlated channels */ int ComputeIntegrandValues3Chan( CAmpPhaseFrequencySeries** integrand, /* Output: values of the integrand on common frequencies (initialized in the function) */ CAmpPhaseFrequencySeries* freqseries1chan1, /* Input: frequency series for wf 1, channel 1 */ CAmpPhaseFrequencySeries* freqseries1chan2, /* Input: frequency series for wf 1, channel 2 */ CAmpPhaseFrequencySeries* freqseries1chan3, /* Input: frequency series for wf 1, channel 3 */ CAmpPhaseSpline* splines2chan1, /* Input: splines in matrix form for wf 2, channel 1 */ CAmpPhaseSpline* splines2chan2, /* Input: splines in matrix form for wf 2, channel 2 */ CAmpPhaseSpline* splines2chan3, /* Input: splines in matrix form for wf 2, channel 3 */ ObjectFunction * Snoise1, /* Noise function */ ObjectFunction * Snoise2, /* Noise function */ ObjectFunction * Snoise3, /* Noise function */ double fLow, /* Lower bound of the frequency - 0 to ignore */ double fHigh) /* Upper bound of the frequency - 0 to ignore */ { gsl_set_error_handler(&Err_Handler); /* Determining the boundaries of indices - frequency vectors assumed to be the same for channels 1,2,3 */ gsl_vector* freq1 = freqseries1chan1->freq; int imin1 = 0; int imax1 = freq1->size - 1; double* f1 = freq1->data; double f2min = gsl_matrix_get(splines2chan1->quadspline_phase, 0, 0); double f2max = gsl_matrix_get(splines2chan1->quadspline_phase, splines2chan1->quadspline_phase->size1 - 1, 0); if((fLow>0 && (f1[imax1]<=fLow || f2max<=fLow)) || (fHigh>0 && (f1[imin1]>=fHigh || f2min>=fHigh))) { //printf("Error: range of frequencies incompatible with fLow, fHigh in IntegrandValues.\n"); //printf("need both {%g, %g} > %g and both {%g, %g} < %g\n",f1[imax1],f2max,fLow,f1[imin1],f2min,fHigh); return -1; } /* If starting outside, move the ends of the frequency series to be just outside the final minf and maxf */ double minf = fmax(f1[imin1], f2min); double maxf = fmin(f1[imax1], f2max); if(fLow>0) {minf = fmax(fLow, minf);} if(fHigh>0) {maxf = fmin(fHigh, maxf);} while(f1[imin1+1]<=minf) imin1++; while(f1[imax1-1]>=maxf) imax1--; //printf("imin=%i, imax=%i\n",imin1,imax1); int nbpts = imax1 + 1 - imin1; //printf("nbpts=%i\n",nbpts); if(nbpts<4)return -1; /* Estimate locally values for freqseries1 at the boundaries - phase vectors assumed to be the same for channels 1,2,3 - this is still true now that the response-processed phase includes the signal phase + R-delay phase, which is the same for all channels */ double areal1chan1minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan1->amp_real, imin1, minf); double aimag1chan1minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan1->amp_imag, imin1, minf); double areal1chan2minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan2->amp_real, imin1, minf); double aimag1chan2minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan2->amp_imag, imin1, minf); double areal1chan3minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan3->amp_real, imin1, minf); double aimag1chan3minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan3->amp_imag, imin1, minf); double phi1minf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan1->phase, imin1, minf); double areal1chan1maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan1->amp_real, imax1-2, maxf); /* Note the imax1-2 */ double aimag1chan1maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan1->amp_imag, imax1-2, maxf); /* Note the imax1-2 */ double areal1chan2maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan2->amp_real, imax1-2, maxf); /* Note the imax1-2 */ double aimag1chan2maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan2->amp_imag, imax1-2, maxf); /* Note the imax1-2 */ double areal1chan3maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan3->amp_real, imax1-2, maxf); /* Note the imax1-2 */ double aimag1chan3maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan3->amp_imag, imax1-2, maxf); /* Note the imax1-2 */ double phi1maxf = EstimateBoundaryLegendreQuad(freq1, freqseries1chan1->phase, imax1-2, maxf); /* Note the imax1-2 */ /* Initializing output structure */ CAmpPhaseFrequencySeries_Init(integrand, nbpts); /* Loop computing integrand values - phases are the same for chan1, chan2 and chan3 */ gsl_vector* freq = (*integrand)->freq; gsl_vector* ampreal = (*integrand)->amp_real; gsl_vector* ampimag = (*integrand)->amp_imag; gsl_vector* phase = (*integrand)->phase; double f, eps, eps2, eps3, ampreal1chan1, ampimag1chan1, ampreal1chan2, ampimag1chan2, ampreal1chan3, ampimag1chan3, phase1, ampreal2chan1, ampimag2chan1, ampreal2chan2, ampimag2chan2, ampreal2chan3, ampimag2chan3, phase2, invSnchan1, invSnchan2, invSnchan3; double complex camp; double* areal1chan1 = freqseries1chan1->amp_real->data; double* aimag1chan1 = freqseries1chan1->amp_imag->data; double* areal1chan2 = freqseries1chan2->amp_real->data; double* aimag1chan2 = freqseries1chan2->amp_imag->data; double* areal1chan3 = freqseries1chan3->amp_real->data; double* aimag1chan3 = freqseries1chan3->amp_imag->data; double* phi1 = freqseries1chan1->phase->data; gsl_matrix* splinechan1real2chan1 = splines2chan1->spline_amp_real; gsl_matrix* splinechan1imag2chan1 = splines2chan1->spline_amp_imag; gsl_matrix* splinechan1real2chan2 = splines2chan2->spline_amp_real; gsl_matrix* splinechan1imag2chan2 = splines2chan2->spline_amp_imag; gsl_matrix* splinechan1real2chan3 = splines2chan3->spline_amp_real; gsl_matrix* splinechan1imag2chan3 = splines2chan3->spline_amp_imag; gsl_matrix* quadsplinephase2 = splines2chan1->quadspline_phase; int i2 = 0; int j = 0; for(int i=imin1; i<=imax1; i++) { /* Distinguish the case where we are at minf or maxf */ if(i==imin1) { f = minf; ampreal1chan1 = areal1chan1minf; ampimag1chan1 = aimag1chan1minf; ampreal1chan2 = areal1chan2minf; ampimag1chan2 = aimag1chan2minf; ampreal1chan3 = areal1chan3minf; ampimag1chan3 = aimag1chan3minf; phase1 = phi1minf; } else if(i==imax1) { f = maxf; ampreal1chan1 = areal1chan1maxf; ampimag1chan1 = aimag1chan1maxf; ampreal1chan2 = areal1chan2maxf; ampimag1chan2 = aimag1chan2maxf; ampreal1chan3 = areal1chan3maxf; ampimag1chan3 = aimag1chan3maxf; phase1 = phi1maxf; } else { f = gsl_vector_get(freq1, i); ampreal1chan1 = areal1chan1[i]; ampimag1chan1 = aimag1chan1[i]; ampreal1chan2 = areal1chan2[i]; ampimag1chan2 = aimag1chan2[i]; ampreal1chan3 = areal1chan3[i]; ampimag1chan3 = aimag1chan3[i]; phase1 = phi1[i]; } /* Adjust the index in the spline if necessary and compute */ while(gsl_matrix_get(splines2chan1->quadspline_phase, i2+1, 0)<f) i2++; eps = f - gsl_matrix_get(splines2chan1->quadspline_phase, i2, 0); eps2 = eps*eps; eps3 = eps2*eps; gsl_vector_view coeffsampreal2chan1 = gsl_matrix_row(splinechan1real2chan1, i2); gsl_vector_view coeffsampimag2chan1 = gsl_matrix_row(splinechan1imag2chan1, i2); gsl_vector_view coeffsampreal2chan2 = gsl_matrix_row(splinechan1real2chan2, i2); gsl_vector_view coeffsampimag2chan2 = gsl_matrix_row(splinechan1imag2chan2, i2); gsl_vector_view coeffsampreal2chan3 = gsl_matrix_row(splinechan1real2chan3, i2); gsl_vector_view coeffsampimag2chan3 = gsl_matrix_row(splinechan1imag2chan3, i2); gsl_vector_view coeffsphase2 = gsl_matrix_row(quadsplinephase2, i2); ampreal2chan1 = EvalCubic(&coeffsampreal2chan1.vector, eps, eps2, eps3); ampimag2chan1 = EvalCubic(&coeffsampimag2chan1.vector, eps, eps2, eps3); ampreal2chan2 = EvalCubic(&coeffsampreal2chan2.vector, eps, eps2, eps3); ampimag2chan2 = EvalCubic(&coeffsampimag2chan2.vector, eps, eps2, eps3); ampreal2chan3 = EvalCubic(&coeffsampreal2chan3.vector, eps, eps2, eps3); ampimag2chan3 = EvalCubic(&coeffsampimag2chan3.vector, eps, eps2, eps3); phase2 = EvalQuad(&coeffsphase2.vector, eps, eps2); invSnchan1 = 1./ObjectFunctionCall(Snoise1,f); invSnchan2 = 1./ObjectFunctionCall(Snoise2,f); invSnchan3 = 1./ObjectFunctionCall(Snoise3,f); camp = invSnchan1 * (ampreal1chan1 + I*ampimag1chan1) * (ampreal2chan1 - I*ampimag2chan1) + invSnchan2 * (ampreal1chan2 + I*ampimag1chan2) * (ampreal2chan2 - I*ampimag2chan2) + invSnchan3 * (ampreal1chan3 + I*ampimag1chan3) * (ampreal2chan3 - I*ampimag2chan3); //dump /* printf("j=%i, im=%g\n a11=(%g,%g), a12=(%g,%g), a13=(%g,%g)\n a11=(%g,%g), a12=(%g,%g), a13=(%g,%g)\n",j,cimag(camp), ampreal1chan1,ampimag1chan1,ampreal1chan2,ampimag1chan2,ampreal1chan3,ampimag1chan3, ampreal2chan1,ampimag2chan1,ampreal2chan2,ampimag2chan2,ampreal2chan3,ampimag2chan3); printf("in1=%g, in2=%g, in3=%g\n",invSnchan1,invSnchan2,invSnchan3); */ gsl_vector_set(freq, j, f); gsl_vector_set(ampreal, j, creal(camp)); gsl_vector_set(ampimag, j, cimag(camp)); gsl_vector_set(phase, j, phase1 - phase2); j++; } return 0; } /* Function computing the overlap (h1|h2) between two given modes in amplitude/phase form, one being already interpolated, for a given noise function - uses the amplitude/phase representation (Fresnel) */ double FDSinglemodeFresnelOverlap( struct tagCAmpPhaseFrequencySeries *freqseries1, /* First mode h1, in amplitude/phase form */ struct tagCAmpPhaseSpline *splines2, /* Second mode h2, already interpolated in matrix form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh) /* Upper bound of the frequency window for the detector */ { /* Computing the integrand values, on the frequency grid of h1 */ CAmpPhaseFrequencySeries* integrand = NULL; ComputeIntegrandValues(&integrand, freqseries1, splines2, Snoise, fLow, fHigh); /* Rescaling the integrand */ double scaling = 10./gsl_vector_get(integrand->freq, integrand->freq->size-1); gsl_vector_scale(integrand->freq, scaling); gsl_vector_scale(integrand->amp_real, 1./scaling); gsl_vector_scale(integrand->amp_imag, 1./scaling); /* Interpolating the integrand */ CAmpPhaseSpline* integrandspline = NULL; BuildSplineCoeffs(&integrandspline, integrand); /* Computing the integral - including here the factor 4 and the real part */ double overlap = 4.*creal(ComputeInt(integrandspline->spline_amp_real, integrandspline->spline_amp_imag, integrandspline->quadspline_phase)); /* Clean up */ CAmpPhaseSpline_Cleanup(integrandspline); CAmpPhaseFrequencySeries_Cleanup(integrand); return overlap; } /* Function computing the overlap (h1|h2) between two given modes in amplitude/phase form for each non-correlated channel 1,2,3, one being already interpolated, for a given noise function - uses the amplitude/phase representation (Fresnel) */ double FDSinglemodeFresnelOverlap3Chan( struct tagCAmpPhaseFrequencySeries *freqseries1chan1, /* First mode h1 for channel 1, in amplitude/phase form */ struct tagCAmpPhaseFrequencySeries *freqseries1chan2, /* First mode h1 for channel 2, in amplitude/phase form */ struct tagCAmpPhaseFrequencySeries *freqseries1chan3, /* First mode h1 for channel 3, in amplitude/phase form */ struct tagCAmpPhaseSpline *splines2chan1, /* Second mode h2 for channel 1, already interpolated in matrix form */ struct tagCAmpPhaseSpline *splines2chan2, /* Second mode h2 for channel 2, already interpolated in matrix form */ struct tagCAmpPhaseSpline *splines2chan3, /* Second mode h2 for channel 3, already interpolated in matrix form */ ObjectFunction * Snoisechan1, /* Noise function */ ObjectFunction * Snoisechan2, /* Noise function */ ObjectFunction * Snoisechan3, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh) /* Upper bound of the frequency window for the detector */ { /* Computing the integrand values, on the frequency grid of h1 */ CAmpPhaseFrequencySeries* integrand = NULL; if(0>ComputeIntegrandValues3Chan(&integrand, freqseries1chan1, freqseries1chan2, freqseries1chan3, splines2chan1, splines2chan2, splines2chan3, Snoisechan1, Snoisechan2, Snoisechan3, fLow, fHigh))return 0;//if allowed freq range does not exist, return 0 for overlap /* Rescaling the integrand */ double scaling = 10./gsl_vector_get(integrand->freq, integrand->freq->size-1); //TEST //scaling = 1.; gsl_vector_scale(integrand->freq, scaling); gsl_vector_scale(integrand->amp_real, 1./scaling); gsl_vector_scale(integrand->amp_imag, 1./scaling); //dump /* for(int ii=0;ii<integrand->freq->size;ii++) printf("ii=%i, f=%g, integrand = ( %g, %g, %g )\n",ii,gsl_vector_get(integrand->freq,ii),gsl_vector_get(integrand->amp_real,ii),gsl_vector_get(integrand->amp_imag,ii),gsl_vector_get(integrand->phase,ii)); */ /* Interpolating the integrand */ CAmpPhaseSpline* integrandspline = NULL; BuildSplineCoeffs(&integrandspline, integrand); /* Computing the integral - including here the factor 4 and the real part */ double overlap = 4.*creal(ComputeInt(integrandspline->spline_amp_real, integrandspline->spline_amp_imag, integrandspline->quadspline_phase)); /* Clean up */ CAmpPhaseSpline_Cleanup(integrandspline); CAmpPhaseFrequencySeries_Cleanup(integrand); return overlap; } /* Function computing the overlap (h1|h2) between two waveforms given as list of modes, one being already interpolated, for a given noise function - two additional parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */ double FDListmodesFresnelOverlap( struct tagListmodesCAmpPhaseFrequencySeries *listh1, /* First waveform, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseSpline *listsplines2, /* Second waveform, list of modes already interpolated in matrix form */ ObjectFunction * Snoise, /* Noise function */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh, /* Upper bound of the frequency window for the detector */ double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */ double fstartobs2) /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */ { double overlap = 0; /* Main loop over the modes - goes through all the modes present */ ListmodesCAmpPhaseFrequencySeries* listelementh1 = listh1; while(listelementh1) { ListmodesCAmpPhaseSpline* listelementsplines2 = listsplines2; while(listelementsplines2) { /* Scaling fstartobs1/2 with the appropriate factor of m (for the 21 mode we use m=2) - setting fmin in the overlap accordingly */ int mmax1 = max(2, listelementh1->m); int mmax2 = max(2, listelementsplines2->m); double fcutLow = fmax(fLow, fmax(((double) mmax1)/2. * fstartobs1, ((double) mmax2)/2. * fstartobs2)); overlap += FDSinglemodeFresnelOverlap(listelementh1->freqseries, listelementsplines2->splines, Snoise, fcutLow, fHigh); listelementsplines2 = listelementsplines2->next; } listelementh1 = listelementh1->next; } return overlap; } /* Function computing the overlap (h1|h2) between two waveforms given as list of modes for each non-correlated channel 1,2,3, one being already interpolated, for a given noise function - two additional parameters for the starting 22-mode frequencies (then properly scaled for the other modes) for a limited duration of the observations */ double FDListmodesFresnelOverlap3Chan( struct tagListmodesCAmpPhaseFrequencySeries *listh1chan1, /* First waveform channel channel 1, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseFrequencySeries *listh1chan2, /* First waveform channel channel 2, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseFrequencySeries *listh1chan3, /* First waveform channel channel 3, list of modes in amplitude/phase form */ struct tagListmodesCAmpPhaseSpline *listsplines2chan1, /* Second waveform channel channel 1, list of modes already interpolated in matrix form */ struct tagListmodesCAmpPhaseSpline *listsplines2chan2, /* Second waveform channel channel 2, list of modes already interpolated in matrix form */ struct tagListmodesCAmpPhaseSpline *listsplines2chan3, /* Second waveform channel channel 3, list of modes already interpolated in matrix form */ ObjectFunction * Snoise1, /* Noise function for channel 1 */ ObjectFunction * Snoise2, /* Noise function for channel 1 */ ObjectFunction * Snoise3, /* Noise function for channel 1 */ double fLow, /* Lower bound of the frequency window for the detector */ double fHigh, /* Upper bound of the frequency window for the detector */ double fstartobs1, /* Starting frequency for the 22 mode of wf 1 - as determined from a limited duration of the observation - set to 0 to ignore */ double fstartobs2) /* Starting frequency for the 22 mode of wf 2 - as determined from a limited duration of the observation - set to 0 to ignore */ { double overlap = 0; /* Main loop over the modes - goes through all the modes present, the same for all three channels 1,2,3 */ ListmodesCAmpPhaseFrequencySeries* listelementh1chan1 = listh1chan1; while(listelementh1chan1) { /* We use the structure for channel 1 to loop through modes */ ListmodesCAmpPhaseFrequencySeries* listelementh1chan2 = ListmodesCAmpPhaseFrequencySeries_GetMode(listh1chan2, listelementh1chan1->l, listelementh1chan1->m); ListmodesCAmpPhaseFrequencySeries* listelementh1chan3 = ListmodesCAmpPhaseFrequencySeries_GetMode(listh1chan3, listelementh1chan1->l, listelementh1chan1->m); ListmodesCAmpPhaseSpline* listelementsplines2chan1 = listsplines2chan1; while(listelementsplines2chan1) { /* We use the structure for channel 1 to loop through modes */ ListmodesCAmpPhaseSpline* listelementsplines2chan2 = ListmodesCAmpPhaseSpline_GetMode(listsplines2chan2, listelementsplines2chan1->l, listelementsplines2chan1->m); ListmodesCAmpPhaseSpline* listelementsplines2chan3 = ListmodesCAmpPhaseSpline_GetMode(listsplines2chan3, listelementsplines2chan1->l, listelementsplines2chan1->m); /* Scaling fstartobs1/2 with the appropriate factor of m (for the 21 mode we use m=2) - setting fmin in the overlap accordingly */ int mmax1 = max(2, listelementh1chan1->m); int mmax2 = max(2, listelementsplines2chan1->m); double fcutLow = fmax(fLow, fmax(((double) mmax1)/2. * fstartobs1, ((double) mmax2)/2. * fstartobs2)); double overlapmode = FDSinglemodeFresnelOverlap3Chan(listelementh1chan1->freqseries, listelementh1chan2->freqseries, listelementh1chan3->freqseries, listelementsplines2chan1->splines, listelementsplines2chan2->splines, listelementsplines2chan3->splines, Snoise1, Snoise2, Snoise3, fcutLow, fHigh); overlap += overlapmode; listelementsplines2chan1 = listelementsplines2chan1->next; } listelementh1chan1 = listelementh1chan1->next; } return overlap; }
{ "alphanum_fraction": 0.69663211, "avg_line_length": 54.1445663011, "ext": "c", "hexsha": "dbc86d28bfd8fc72f4c1ae6a5bfc5918e8caf17f", "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": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_path": "tools/likelihood.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "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": "titodalcanton/flare", "max_issues_repo_path": "tools/likelihood.c", "max_line_length": 405, "max_stars_count": null, "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_path": "tools/likelihood.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 15247, "size": 54307 }
#ifndef neo_hookean_h #define neo_hookean_h #include <petsc.h> #include "../include/structs.h" #ifndef PHYSICS_STRUCT_NH #define PHYSICS_STRUCT_NH typedef struct Physics_NH_ *Physics_NH; struct Physics_NH_ { CeedScalar nu; // Poisson's ratio CeedScalar E; // Young's Modulus }; #endif // PHYSICS_STRUCT_NH // Create context object PetscErrorCode PhysicsContext_NH(MPI_Comm comm, Ceed ceed, Units *units, CeedQFunctionContext *ctx); PetscErrorCode PhysicsSmootherContext_NH(MPI_Comm comm, Ceed ceed, CeedQFunctionContext ctx, CeedQFunctionContext *ctx_smoother); // Process physics options PetscErrorCode ProcessPhysics_NH(MPI_Comm comm, Physics_NH phys, Units units); #endif // neo_hookean_h
{ "alphanum_fraction": 0.7490039841, "avg_line_length": 28.9615384615, "ext": "h", "hexsha": "668a964359d5000f90061e059242885b771ce407", "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/solids/problems/neo-hookean.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/solids/problems/neo-hookean.h", "max_line_length": 78, "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/solids/problems/neo-hookean.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": 200, "size": 753 }
#ifndef Dark_Arts_Exception_h #define Dark_Arts_Exception_h #include "Exception_Types.h" #include <stdlib.h> #include <iostream> #include <sstream> #include <petsc.h> class Dark_Arts_Exception { public: Dark_Arts_Exception( EXCEPTION_TYPE ex_type , const std::string& ex_message); Dark_Arts_Exception( EXCEPTION_TYPE ex_type , const std::stringstream& ex_message); Dark_Arts_Exception(); virtual ~Dark_Arts_Exception(){} void message(void) const; void testing_message(void) const; private: std::string error_message; }; #endif
{ "alphanum_fraction": 0.7348353553, "avg_line_length": 20.6071428571, "ext": "h", "hexsha": "849138ce6ff0217469636de2e408252028ed13c9", "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": "f04b0a30dcac911ef06fe0916921020826f5c42b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "pgmaginot/DARK_ARTS", "max_forks_repo_path": "src/exceptions/Dark_Arts_Exception.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f04b0a30dcac911ef06fe0916921020826f5c42b", "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": "pgmaginot/DARK_ARTS", "max_issues_repo_path": "src/exceptions/Dark_Arts_Exception.h", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "f04b0a30dcac911ef06fe0916921020826f5c42b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "pgmaginot/DARK_ARTS", "max_stars_repo_path": "src/exceptions/Dark_Arts_Exception.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 130, "size": 577 }
#ifndef ROUNDING_H_ZL4GHC5J #define ROUNDING_H_ZL4GHC5J #include <cmath> #include <gsl/gsl> #include <type_traits> namespace sens_loc::math { /// Round the value \c val to the nth \c digit. /// /// \tparam Number arithmetic type that represents a number /// \param val number to be rounded /// \param digit The decimal digit the number shall be rounded to. Positive /// values indicate the position behind the comma for rational numbers, a /// negative number indicates a position before the comma. /// \pre \c std::is_arithmetic_v<Number> /// \post the result is rounded to the nth digit /// \post \f$digit == 0 => result == val\f$ /// \post \f$!std::isfinite(val) => result == val\f$ /// \code /// roundn(10.055, 2) == 10.06; /// roundn(10.055, 0) == 10.055; /// roundn(10.055, -1) == 10.00; /// roundn(1052.4, -2) == 1100.0; /// roundn(1052, -2) == 1100; /// roundn(1052, 2) == 1052; /// \endcode template <typename Number> Number roundn(Number val, int digit) noexcept { static_assert(std::is_arithmetic_v<Number>); if (digit == 0) return val; if constexpr (std::is_floating_point_v<Number>) { if (!std::isfinite(val)) return val; Number potence_10 = std::pow(Number(10), digit); return std::round(val * potence_10) / potence_10; } else { double potence_10 = std::pow(10., digit); double rounded = std::round(val * potence_10) / potence_10; return Number(std::round(rounded)); } } } // namespace sens_loc::math #endif /* end of include guard: ROUNDING_H_ZL4GHC5J */
{ "alphanum_fraction": 0.6462715105, "avg_line_length": 30.7647058824, "ext": "h", "hexsha": "d1980e3b2a2c25400c3350282896daf31e1374ef", "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": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_path": "src/include/sens_loc/math/rounding.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "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": "JonasToth/depth-conversions", "max_issues_repo_path": "src/include/sens_loc/math/rounding.h", "max_line_length": 75, "max_stars_count": 2, "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_path": "src/include/sens_loc/math/rounding.h", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "num_tokens": 472, "size": 1569 }
/** * @file aec.h * @brief Cancelation of a voice prompt based on either NLMS or Kalman filtering algorithms * @author John McDonough, Wei Chu and Kenichi Kumatani */ #ifndef AEC_H #define AEC_H #include <stdio.h> #include <assert.h> #include <gsl/gsl_block.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_blas.h> #include "common/jexception.h" #include <gsl/gsl_eigen.h> #include "stream/stream.h" #include "btk.h" #include "beamformer/tracker.h" /** * \defgroup NLMSAcousticEchoCancellationFeature NLMS Echo Cancellation Feature */ /*@{*/ // ----- definition for class `NLMSAcousticEchoCancellationFeature' ----- // class NLMSAcousticEchoCancellationFeature : public VectorComplexFeatureStream { public: NLMSAcousticEchoCancellationFeature(const VectorComplexFeatureStreamPtr& played, const VectorComplexFeatureStreamPtr& recorded, double delta = 100.0, double epsilon = 1.0E-04, double threshold = 100.0, const String& nm = "AEC"); virtual ~NLMSAcousticEchoCancellationFeature(); virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset() { played_->reset(); recorded_->reset(); gsl_vector_complex_set_zero(filterCoefficient_); } private: bool update_(const gsl_complex Vk); VectorComplexFeatureStreamPtr played_; // v(n) VectorComplexFeatureStreamPtr recorded_; // a(n) unsigned fftLen_; unsigned fftLen2_; gsl_vector_complex* filterCoefficient_; const double delta_; const double epsilon_; const double threshold_; }; typedef Inherit<NLMSAcousticEchoCancellationFeature, VectorComplexFeatureStreamPtr> NLMSAcousticEchoCancellationFeaturePtr; /*@}*/ /** * \defgroup KalmanFilterEchoCancellationFeature Kalman Filer Echo Cancellation Feature */ /*@{*/ // ----- definition for class `KalmanFilterEchoCancellationFeature' ----- // class KalmanFilterEchoCancellationFeature : public VectorComplexFeatureStream { public: KalmanFilterEchoCancellationFeature(const VectorComplexFeatureStreamPtr& played, const VectorComplexFeatureStreamPtr& recorded, double beta = 0.95, double sigma2 = 100.0, double threshold = 100.0, const String& nm = "KFEchoCanceller"); virtual ~KalmanFilterEchoCancellationFeature(); virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset() { played_->reset(); recorded_->reset(); gsl_vector_complex_set_zero(filterCoefficient_); } private: bool update_(const gsl_complex Vk); VectorComplexFeatureStreamPtr played_; // v(n) VectorComplexFeatureStreamPtr recorded_; // a(n) unsigned fftLen_; unsigned fftLen2_; gsl_vector_complex* filterCoefficient_; gsl_vector* sigma2_v_; gsl_vector* K_k_; const double beta_; const double threshold_; const double sigma2_u_; }; typedef Inherit<KalmanFilterEchoCancellationFeature, VectorComplexFeatureStreamPtr> KalmanFilterEchoCancellationFeaturePtr; /*@}*/ // ----- definition for class `BlockKalmanFilterEchoCancellationFeature' ----- // class BlockKalmanFilterEchoCancellationFeature : public VectorComplexFeatureStream { public: BlockKalmanFilterEchoCancellationFeature(const VectorComplexFeatureStreamPtr& played, const VectorComplexFeatureStreamPtr& recorded, unsigned sampleN = 1, double beta = 0.95, double sigmau2 = 10e-4, double sigmauk2 = 5.0, double threshold = 100.0, double amp4play = 1.0, const String& nm = "KFEchoCanceller"); virtual ~BlockKalmanFilterEchoCancellationFeature(); virtual const gsl_vector_complex* next(int frame_no = -5); virtual void reset() { played_->reset(); recorded_->reset(); } protected: class ComplexBuffer_ { public: /* @brief Construct a circular buffer to hold past and current subband samples It keeps nsamp arrays which is completely updated with the period 'nsamp'. Each array holds actual values of the samples. @param unsigned len[in] is the size of each vector of samples @param unsigned nsamp[in] is the period of the circular buffer */ ComplexBuffer_(unsigned len, unsigned sampleN) : len_(len), sampleN_(sampleN), zero_(sampleN_ - 1), samples_(new gsl_vector_complex*[sampleN_]), subbandSamples_(gsl_vector_complex_calloc(sampleN_)) { for (unsigned i = 0; i < sampleN_; i++) samples_[i] = gsl_vector_complex_calloc(len_); } ~ComplexBuffer_() { for (unsigned i = 0; i < sampleN_; i++) gsl_vector_complex_free(samples_[i]); delete[] samples_; gsl_vector_complex_free(subbandSamples_); } gsl_complex sample(unsigned timeX, unsigned binX) const { unsigned idx = index_(timeX); const gsl_vector_complex* vec = samples_[idx]; return gsl_vector_complex_get(vec, binX); } const gsl_vector_complex* get_samples(unsigned m) { for (unsigned timeX = 0; timeX < sampleN_; timeX++) gsl_vector_complex_set(subbandSamples_, timeX, sample(timeX, m)); return subbandSamples_; } void next_sample(const gsl_vector_complex* s = NULL, double amp4play = 1.0 ) { zero_ = (zero_ + 1) % sampleN_; gsl_vector_complex* nextBlock = samples_[zero_]; if (s == NULL) { gsl_vector_complex_set_zero(nextBlock); } else { if (s->size != len_) throw jdimension_error("'ComplexBuffer_': Sizes do not match (%d vs. %d)", s->size, len_); assert( s->size == len_ ); gsl_vector_complex_memcpy(nextBlock, s); if( amp4play != 1.0 ) gsl_blas_zdscal( amp4play, nextBlock ); } } void zero() { for (unsigned i = 0; i < sampleN_; i++) gsl_vector_complex_set_zero(samples_[i]); zero_ = sampleN_ - 1; } private: unsigned index_(unsigned idx) const { assert(idx < sampleN_); unsigned ret = (zero_ + sampleN_ - idx) % sampleN_; return ret; } const unsigned len_; const unsigned sampleN_; unsigned zero_; // index of most recent sample gsl_vector_complex** samples_; gsl_vector_complex* subbandSamples_; }; static gsl_complex ComplexOne_; static gsl_complex ComplexZero_; bool update_(const gsl_vector_complex* Vk); void conjugate_(gsl_vector_complex* dest, const gsl_vector_complex* src) const; VectorComplexFeatureStreamPtr played_; // v(n) VectorComplexFeatureStreamPtr recorded_; // a(n) unsigned fftLen_; unsigned fftLen2_; unsigned sampleN_; ComplexBuffer_ buffer_; gsl_vector_complex** filterCoefficient_; gsl_vector* sigma2_v_; gsl_matrix_complex** K_k_; gsl_matrix_complex* K_k_k1_; const double beta_; const double threshold_; gsl_matrix_complex** Sigma2_u_; gsl_vector_complex* Gk_; gsl_vector_complex* scratch_; gsl_vector_complex* scratch2_; gsl_matrix_complex* scratchMatrix_; gsl_matrix_complex* scratchMatrix2_; double amp4play_; double floorVal_; int skippedN_; int maxSkippedN_; }; typedef Inherit<BlockKalmanFilterEchoCancellationFeature, VectorComplexFeatureStreamPtr> BlockKalmanFilterEchoCancellationFeaturePtr; /*@}*/ /** * \defgroup DTDBlockKalmanFilterEchoCancellationFeature Block Kalman Filer Echo Cancellation Feature */ /*@{*/ // ----- definition for class `InformationFilterEchoCancellationFeature' ----- // class InformationFilterEchoCancellationFeature : public BlockKalmanFilterEchoCancellationFeature { public: InformationFilterEchoCancellationFeature(const VectorComplexFeatureStreamPtr& played, const VectorComplexFeatureStreamPtr& recorded, unsigned sampleN = 1, double beta = 0.95, double sigmau2 = 10e-4, double sigmauk2 = 5.0, double snrTh = 2.0, double engTh = 100.0, double smooth = 0.9, double loading = 1.0e-02, double amp4play = 1.0, const String& nm = "Information Echo Canceller"); virtual ~InformationFilterEchoCancellationFeature(); virtual const gsl_vector_complex* next(int frame_no = -5); protected: static double _EigenValueThreshold; double update_band_(const gsl_complex Ak, const gsl_complex Ek, int frame_no, unsigned m); void invert_(gsl_matrix_complex* matrix); static void print_matrix_(const gsl_matrix_complex* mat); static void print_vector_(const gsl_vector_complex* vec); const double smoothEk_; // for smoothing the error signal, ->1, less smooth const double smoothSk_; // for smoothing the estimated signal const double engTh_; // threshold of energy double* snr_; double* EkEnergy_; double* SkEnergy_; const double loading_; gsl_matrix_complex* inverse_; gsl_eigen_hermv_workspace* eigenWorkSpace_; gsl_vector* evalues_; gsl_vector_complex* scratchInverse_; gsl_matrix_complex* scratchMatrixInverse_; gsl_matrix_complex* scratchMatrixInverse2_; gsl_matrix_complex* matrixCopy_; }; typedef Inherit<InformationFilterEchoCancellationFeature, BlockKalmanFilterEchoCancellationFeaturePtr> InformationFilterEchoCancellationFeaturePtr; // ----- definition for class `SquareRootInformationFilterEchoCancellationFeature' ----- // class SquareRootInformationFilterEchoCancellationFeature : public InformationFilterEchoCancellationFeature { public: SquareRootInformationFilterEchoCancellationFeature(const VectorComplexFeatureStreamPtr& played, const VectorComplexFeatureStreamPtr& recorded, unsigned sampleN = 1, double beta = 0.95, double sigmau2 = 10e-4, double sigmauk2 = 5.0, double snrTh = 2.0, double engTh = 100.0, double smooth = 0.9, double loading = 1.0e-02, double amp4play = 1.0, const String& nm = "Square Root Information Echo Canceller"); virtual ~SquareRootInformationFilterEchoCancellationFeature(); virtual const gsl_vector_complex* next(int frame_no = -5); private: const gsl_complex load_; static gsl_complex calc_givens_rotation_(const gsl_complex& v1, const gsl_complex& v2, gsl_complex& c, gsl_complex& s); static void apply_givens_rotation_(const gsl_complex& v1, const gsl_complex& v2, const gsl_complex& c, const gsl_complex& s, gsl_complex& v1p, gsl_complex& v2p); void negative_(gsl_matrix_complex* dest, const gsl_matrix_complex* src); void extract_covariance_state_(const gsl_matrix_complex* K_k, const gsl_vector_complex* sk, gsl_vector_complex* xk); void temporal_update_(unsigned m); void observational_update_(unsigned m, const gsl_complex& Ak, double sigma2_v); void diagonal_loading_(unsigned m); gsl_vector_complex** informationState_; }; typedef Inherit<SquareRootInformationFilterEchoCancellationFeature, InformationFilterEchoCancellationFeaturePtr> SquareRootInformationFilterEchoCancellationFeaturePtr; // ----- definition for class `DTDBlockKalmanFilterEchoCancellationFeature' ----- // class DTDBlockKalmanFilterEchoCancellationFeature : public BlockKalmanFilterEchoCancellationFeature { public: DTDBlockKalmanFilterEchoCancellationFeature(const VectorComplexFeatureStreamPtr& played, const VectorComplexFeatureStreamPtr& recorded, unsigned sampleN = 1, double beta = 0.95, double sigmau2 = 10e-4, double sigmauk2 = 5.0, double snrTh = 2.0, double engTh = 100.0, double smooth = 0.9, double amp4play = 1.0, const String& nm = "DTDKFEchoCanceller"); virtual ~DTDBlockKalmanFilterEchoCancellationFeature(); virtual const gsl_vector_complex* next(int frame_no = -5); private: double update_band_(const gsl_complex Ak, const gsl_complex Ek, int frame_no); void conjugate_(gsl_vector_complex* dest, const gsl_vector_complex* src) const; const double smoothSk_; // for smoothing the estimated signal const double smoothEk_; // for smoothing the error signal, ->1, less smooth const double engTh_; // threshold of energy double snr_; double EkEnergy_; double SkEnergy_; FILE* fdb_; }; typedef Inherit<DTDBlockKalmanFilterEchoCancellationFeature, BlockKalmanFilterEchoCancellationFeaturePtr> DTDBlockKalmanFilterEchoCancellationFeaturePtr; /*@}*/ #endif // AEC_H
{ "alphanum_fraction": 0.6597778922, "avg_line_length": 40.9548192771, "ext": "h", "hexsha": "152a598f038b1ba67b26af53ab64c29f5f9bdc0a", "lang": "C", "max_forks_count": 68, "max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z", "max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "musiclvme/distant_speech_recognition", "max_forks_repo_path": "btk20_src/aec/aec.h", "max_issues_count": 25, "max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "musiclvme/distant_speech_recognition", "max_issues_repo_path": "btk20_src/aec/aec.h", "max_line_length": 407, "max_stars_count": 136, "max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "musiclvme/distant_speech_recognition", "max_stars_repo_path": "btk20_src/aec/aec.h", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z", "num_tokens": 2965, "size": 13597 }
#pragma once #include <imageview/IsPixelFormat.h> #include <imageview/internal/ImageViewStorage.h> #include <gsl/span> namespace imageview { namespace detail { template <class PixelFormat> class PixelRef { public: static_assert(IsPixelFormat<PixelFormat>::value, "Not a PixelFormat."); using color_type = typename PixelFormat::color_type; constexpr PixelRef(gsl::span<std::byte, PixelFormat::kBytesPerPixel> pixel_data, std::reference_wrapper<const PixelFormat> pixel_format); constexpr PixelRef(const PixelRef& other) = default; constexpr PixelRef(PixelRef&&) = default; ~PixelRef() = default; // Implicit conversion to color_type. // \return the color of the referenced pixel. constexpr operator color_type() const; // Assigns the specified color to the referenced pixel. // \param color - color to assign. // \return *this. constexpr PixelRef& operator=(const color_type& color); // Assigns the specified color to the referenced pixel. // Note: PixelRef has reference semantics: copy and move assignment operators change the value of the // referenced pixel rather than PixelRef object itself. constexpr PixelRef& operator=(const PixelRef& other); constexpr PixelRef& operator=(PixelRef&& other); private: // TODO: store PixelFormat by reference if it's not eligible for empty base optimization, // otherwise by value (as an empty base). detail::ImageViewStorage<PixelFormat, true> storage_; }; template <class PixelFormat> constexpr PixelRef<PixelFormat>::PixelRef(gsl::span<std::byte, PixelFormat::kBytesPerPixel> pixel_data, std::reference_wrapper<const PixelFormat> pixel_format) : storage_(pixel_data.data(), pixel_format.get()) {} template <class PixelFormat> constexpr PixelRef<PixelFormat>::operator color_type() const { constexpr std::size_t kBytesPerPixel = PixelFormat::kBytesPerPixel; const gsl::span<const std::byte, kBytesPerPixel> pixel_data(storage_.data_, kBytesPerPixel); return storage_.pixelFormat().read(pixel_data); } template <class PixelFormat> constexpr PixelRef<PixelFormat>& PixelRef<PixelFormat>::operator=(const color_type& color) { constexpr std::size_t kBytesPerPixel = PixelFormat::kBytesPerPixel; const gsl::span<std::byte, kBytesPerPixel> pixel_data(storage_.data_, kBytesPerPixel); storage_.pixelFormat().write(color, pixel_data); return *this; } template <class PixelFormat> constexpr PixelRef<PixelFormat>& PixelRef<PixelFormat>::operator=(const PixelRef& other) { // TODO: In theory, we could just memcpy() the binary data. However, if PixelFormat is stateful, // and the state of our PixelFormat differs from the state of @other, then simply copying the binary // data might lead to the wrong result. // Possible workaround: add a constexpr if for the case when PixelFormat is an empty class. return *this = static_cast<color_type>(other); } template <class PixelFormat> constexpr PixelRef<PixelFormat>& PixelRef<PixelFormat>::operator=(PixelRef&& other) { return *this = static_cast<color_type>(other); } } // namespace detail } // namespace imageview
{ "alphanum_fraction": 0.7483338623, "avg_line_length": 38.4268292683, "ext": "h", "hexsha": "6c6df690933091c37b2ce1af2927f3f7bf403fce", "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": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alexanderbelous/imageview", "max_forks_repo_path": "include/imageview/internal/PixelRef.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "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": "alexanderbelous/imageview", "max_issues_repo_path": "include/imageview/internal/PixelRef.h", "max_line_length": 103, "max_stars_count": null, "max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alexanderbelous/imageview", "max_stars_repo_path": "include/imageview/internal/PixelRef.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 707, "size": 3151 }
#pragma once #if WIN32 #define LAPACK_COMPLEX_CUSTOM #define lapack_complex_float float #define lapack_complex_double double #endif #include <cblas.h> #include <lapacke.h> #undef I // undefine this def due to complex.h that causes issues later #define BLAS(x,X) cblas_ ## x #define LAPACK(x,X) LAPACKE_ ## x #define CLAPACK_INTERFACE #define UNUSED(expr) do{(void)(expr);}while(0) #define DLANGE(X1,X2,X3,X4,X5,X6) LAPACK(dlange,DLANGE)(LAPACK_COL_MAJOR,X1,X2,X3,X4,X5);UNUSED(X6) #define DSPTRF(X1,X2,X3,X4,X5) LAPACK(dsptrf,DSPTRF)(LAPACK_COL_MAJOR,X1,X2,X3,X4) #define DSPTRS(X1,X2,X3,X4,X5,X6,X7,X8) LAPACK(dsptrs,DSPTRS)(LAPACK_COL_MAJOR,X1,X2,X3,X4,X5,X6,X7) #define DSPTRI(X1,X2,X3,X4,X5,X6) LAPACK(dsptri,DSPTRI)(LAPACK_COL_MAJOR,X1,X2,X3,X4) #define DPPTRF(X1,X2,X3,X4) LAPACK(dpptrf,DPPTRF)(LAPACK_COL_MAJOR,X1,X2,X3) #define DPPTRI(X1,X2,X3,X4) LAPACK(dpptri,DPPTRI)(LAPACK_COL_MAJOR,X1,X2,X3) #define DGETRF(X1,X2,X3,X4,X5) LAPACK(dgetrf,DGETRF)(LAPACK_COL_MAJOR,X1,X2,X3,X4,X5) #define DGETRI(X1,X2,X3,X4) LAPACK(dgetri,DGETRI)(LAPACK_COL_MAJOR,X1,X2,X3,X4) #define DGESDD(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,X13,X14) LAPACK(dgesdd,DGESDD)(LAPACK_COL_MAJOR,X1,X2,X3,X4,X5,X6,X7,X8,X9,X10) #include <BlasLapackImplementations/OpenMEEGMathsCBlasLapack.h>
{ "alphanum_fraction": 0.7232472325, "avg_line_length": 42.34375, "ext": "h", "hexsha": "41a826f1c7cf00d2b75252c2cc6956214015820e", "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": "3eea0ae55a19e47b32106ebb5b8141ed7f9e8fb6", "max_forks_repo_licenses": [ "Intel", "CECILL-B" ], "max_forks_repo_name": "Tobitta/openmeeg", "max_forks_repo_path": "OpenMEEGMaths/include/BlasLapackImplementations/OpenMEEGMathsOpenBLASConfig.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3eea0ae55a19e47b32106ebb5b8141ed7f9e8fb6", "max_issues_repo_issues_event_max_datetime": "2019-09-13T08:28:25.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-13T08:28:25.000Z", "max_issues_repo_licenses": [ "Intel", "CECILL-B" ], "max_issues_repo_name": "Tobitta/openmeeg", "max_issues_repo_path": "OpenMEEGMaths/include/BlasLapackImplementations/OpenMEEGMathsOpenBLASConfig.h", "max_line_length": 133, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3eea0ae55a19e47b32106ebb5b8141ed7f9e8fb6", "max_stars_repo_licenses": [ "Intel", "CECILL-B" ], "max_stars_repo_name": "Tobitta/openmeeg", "max_stars_repo_path": "OpenMEEGMaths/include/BlasLapackImplementations/OpenMEEGMathsOpenBLASConfig.h", "max_stars_repo_stars_event_max_datetime": "2019-09-09T13:41:53.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-09T13:41:53.000Z", "num_tokens": 530, "size": 1355 }
/** * * @file example_sgelqf.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @brief Example using LQ factorization * * @version 2.6.0 * @author Bilel Hadri * @date 2010-11-15 * @generated s Tue Jan 7 11:45:20 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> #ifndef max #define max(a, b) ((a) > (b) ? (a) : (b)) #endif #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #endif int check_orthogonality(int, int, int, float*); int check_factorization(int, int, float*, float*, int, float*); int IONE=1; int ISEED[4] = {0,0,0,1}; /* initial seed for slarnv() */ int main () { int cores = 2; int M = 10; int N = 15; int LDA = 10; int K = min(M, N); int info; int info_ortho, info_factorization; int i,j; int LDAxN = LDA*N; float *A1 = (float *)malloc(LDA*N*sizeof(float)); float *A2 = (float *)malloc(LDA*N*sizeof(float)); float *Q = (float *)malloc(LDA*N*sizeof(float)); PLASMA_desc *T; /* Check if unable to allocate memory */ if ((!A1)||(!A2)||(!Q)){ printf("Out of Memory \n "); return EXIT_SUCCESS; } /* Plasma Initialization */ PLASMA_Init(cores); printf("-- PLASMA is initialized to run on %d cores. \n",cores); /* Allocate T */ PLASMA_Alloc_Workspace_sgelqf(M, N, &T); /* Initialize A1 and A2 */ LAPACKE_slarnv_work(IONE, ISEED, LDAxN, A1); for (i = 0; i < M; i++) for (j = 0; j < N; j++) A2[LDA*j+i] = A1[LDA*j+i] ; /* Factorization QR of the matrix A2 */ info = PLASMA_sgelqf(M, N, A2, LDA, T); /* Building the economy-size Q */ memset((void*)Q, 0, LDA*N*sizeof(float)); for (i = 0; i < K; i++) Q[LDA*i+i] = 1.0; PLASMA_sorglq(M, N, K, A2, LDA, T, Q, LDA); /* Check the orthogonality, factorization and the solution */ info_ortho = check_orthogonality(M, N, LDA, Q); info_factorization = check_factorization(M, N, A1, A2, LDA, Q); if ((info_ortho != 0)|(info_factorization != 0)|(info != 0)) printf("-- Error in SGELQF example ! \n"); else printf("-- Run of SGELQF example successful ! \n"); free(A1); free(A2); free(Q); free(T); PLASMA_Finalize(); return EXIT_SUCCESS; } /*------------------------------------------------------------------- * Check the orthogonality of Q */ int check_orthogonality(int M, int N, int LDQ, float *Q) { float alpha, beta; float normQ; int info_ortho; int i; int minMN = min(M, N); float eps; float *work = (float *)malloc(minMN*sizeof(float)); eps = LAPACKE_slamch_work('e'); alpha = 1.0; beta = -1.0; /* Build the idendity matrix USE DLASET?*/ float *Id = (float *) malloc(minMN*minMN*sizeof(float)); memset((void*)Id, 0, minMN*minMN*sizeof(float)); for (i = 0; i < minMN; i++) Id[i*minMN+i] = (float)1.0; /* Perform Id - Q'Q */ if (M >= N) cblas_ssyrk(CblasColMajor, CblasUpper, CblasTrans, N, M, alpha, Q, LDQ, beta, Id, N); else cblas_ssyrk(CblasColMajor, CblasUpper, CblasNoTrans, M, N, alpha, Q, LDQ, beta, Id, M); normQ = LAPACKE_slansy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), 'u', minMN, Id, minMN, work); printf("============\n"); printf("Checking the orthogonality of Q \n"); printf("||Id-Q'*Q||_oo / (N*eps) = %e \n",normQ/(minMN*eps)); if ( isnan(normQ / (minMN * eps)) || (normQ / (minMN * eps) > 10.0) ) { printf("-- Orthogonality is suspicious ! \n"); info_ortho=1; } else { printf("-- Orthogonality is CORRECT ! \n"); info_ortho=0; } free(work); free(Id); return info_ortho; } /*------------------------------------------------------------ * Check the factorization QR */ int check_factorization(int M, int N, float *A1, float *A2, int LDA, float *Q) { float Anorm, Rnorm; float alpha, beta; int info_factorization; int i,j; float eps; eps = LAPACKE_slamch_work('e'); float *Ql = (float *)malloc(M*N*sizeof(float)); float *Residual = (float *)malloc(M*N*sizeof(float)); float *work = (float *)malloc(max(M,N)*sizeof(float)); alpha=1.0; beta=0.0; if (M >= N) { /* Extract the R */ float *R = (float *)malloc(N*N*sizeof(float)); memset((void*)R, 0, N*N*sizeof(float)); LAPACKE_slacpy_work(LAPACK_COL_MAJOR,'u', M, N, A2, LDA, R, N); /* Perform Ql=Q*R */ memset((void*)Ql, 0, M*N*sizeof(float)); cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, N, (alpha), Q, LDA, R, N, (beta), Ql, M); free(R); } else { /* Extract the L */ float *L = (float *)malloc(M*M*sizeof(float)); memset((void*)L, 0, M*M*sizeof(float)); LAPACKE_slacpy_work(LAPACK_COL_MAJOR,'l', M, N, A2, LDA, L, M); /* Perform Ql=LQ */ memset((void*)Ql, 0, M*N*sizeof(float)); cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, M, (alpha), L, M, Q, LDA, (beta), Ql, M); free(L); } /* Compute the Residual */ for (i = 0; i < M; i++) for (j = 0 ; j < N; j++) Residual[j*M+i] = A1[j*LDA+i]-Ql[j*M+i]; Rnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Residual, M, work); Anorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, A2, LDA, work); if (M >= N) { printf("============\n"); printf("Checking the QR Factorization \n"); printf("-- ||A-QR||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); } else { printf("============\n"); printf("Checking the LQ Factorization \n"); printf("-- ||A-LQ||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); } if (isnan(Rnorm / (Anorm * N *eps)) || (Rnorm / (Anorm * N * eps) > 10.0) ) { printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else { printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } free(work); free(Ql); free(Residual); return info_factorization; }
{ "alphanum_fraction": 0.5518698169, "avg_line_length": 27.9082969432, "ext": "c", "hexsha": "a28324c337d9d9b72fda774f25025f623817d4c0", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "examples/example_sgelqf.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "examples/example_sgelqf.c", "max_line_length": 110, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "examples/example_sgelqf.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2093, "size": 6391 }
/***************************************************************************** * * Rokko: Integrated Interface for libraries of eigenvalue decomposition * * Copyright (C) 2012-2019 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp> * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * *****************************************************************************/ #include <stdio.h> #include <cblas.h> #include <rokko/cmatrix.h> int main() { int n = 4; double** a = alloc_dmatrix(n, n); mat_elem(a, 0, 0) = 0.959291425205444; mat_elem(a, 0, 1) = 0.257508254123736; mat_elem(a, 0, 2) = 0.243524968724989; mat_elem(a, 0, 3) = 0.251083857976031; mat_elem(a, 1, 0) = 0.547215529963803; mat_elem(a, 1, 1) = 0.840717255983663; mat_elem(a, 1, 2) = 0.929263623187228; mat_elem(a, 1, 3) = 0.616044676146639; mat_elem(a, 2, 0) = 0.138624442828679; mat_elem(a, 2, 1) = 0.254282178971531; mat_elem(a, 2, 2) = 0.349983765984809; mat_elem(a, 2, 3) = 0.473288848902729; mat_elem(a, 3, 0) = 0.149294005559057; mat_elem(a, 3, 1) = 0.814284826068816; mat_elem(a, 3, 2) = 0.196595250431208; mat_elem(a, 3, 3) = 0.351659507062997; double** b = alloc_dmatrix(n, n); mat_elem(b, 0, 0) = 0.567821640725221; mat_elem(b, 0, 1) = 0.779167230102011; mat_elem(b, 0, 2) = 0.469390641058206; mat_elem(b, 0, 3) = 0.794284540683907; mat_elem(b, 1, 0) = 0.0758542895630636; mat_elem(b, 1, 1) = 0.934010684229183; mat_elem(b, 1, 2) = 0.0119020695012414; mat_elem(b, 1, 3) = 0.311215042044805; mat_elem(b, 2, 0) = 0.0539501186666072; mat_elem(b, 2, 1) = 0.129906208473730; mat_elem(b, 2, 2) = 0.337122644398882; mat_elem(b, 2, 3) = 0.528533135506213; mat_elem(b, 3, 0) = 0.530797553008973; mat_elem(b, 3, 1) = 0.568823660872193; mat_elem(b, 3, 2) = 0.162182308193243; mat_elem(b, 3, 3) = 0.165648729499781; double** c = alloc_dmatrix(n, n); mat_elem(c, 0, 0) = 0.601981941401637; mat_elem(c, 0, 1) = 0.748151592823710; mat_elem(c, 0, 2) = 0.913337361501670; mat_elem(c, 0, 3) = 0.996134716626886; mat_elem(c, 1, 0) = 0.262971284540144; mat_elem(c, 1, 1) = 0.450541598502498; mat_elem(c, 1, 2) = 0.152378018969223; mat_elem(c, 1, 3) = 0.0781755287531837; mat_elem(c, 2, 0) = 0.654079098476782; mat_elem(c, 2, 1) = 0.0838213779969326; mat_elem(c, 2, 2) = 0.825816977489547; mat_elem(c, 2, 3) = 0.442678269775446; mat_elem(c, 3, 0) = 0.689214503140008; mat_elem(c, 3, 1) = 0.228976968716819; mat_elem(c, 3, 2) = 0.538342435260057; mat_elem(c, 3, 3) = 0.106652770180584; double alpha = 2.1; double beta = 0.8; printf("a: "); fprint_dmatrix(stdout, n, n, a); printf("b: "); fprint_dmatrix(stdout, n, n, b); printf("c: "); fprint_dmatrix(stdout, n, n, c); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, alpha, mat_ptr(a), n, mat_ptr(b), n, beta, mat_ptr(c), n); printf("%10.5f * a * b + %10.5f * c: ", alpha, beta); fprint_dmatrix(stdout, n, n, c); free_dmatrix(a); free_dmatrix(b); free_dmatrix(c); } /* gemm.m A = [0.959291425205444,0.257508254123736,0.243524968724989,0.251083857976031;0.547215529963803,0.840717255983663,0.929263623187228,0.616044676146639;0.138624442828679,0.254282178971531,0.349983765984809,0.473288848902729;0.149294005559057,0.814284826068816,0.196595250431208,0.351659507062997] B = [0.567821640725221,0.779167230102011,0.469390641058206,0.794284540683907;0.0758542895630636,0.934010684229183,0.0119020695012414,0.311215042044805;0.0539501186666072,0.129906208473730,0.337122644398882,0.528533135506213;0.530797553008973,0.568823660872193,0.162182308193243,0.165648729499781] C = [0.601981941401637,0.748151592823710,0.913337361501670,0.996134716626886;0.262971284540144,0.450541598502498,0.152378018969223,0.0781755287531837;0.654079098476782,0.0838213779969326,0.825816977489547,0.442678269775446;0.689214503140008,0.228976968716819,0.538342435260057,0.106652770180584] 2.1 * A * B + 0.8 * C */
{ "alphanum_fraction": 0.6757291152, "avg_line_length": 43.0425531915, "ext": "c", "hexsha": "272954bc71c9e9c6e97517ec52e72ea2041fe281", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z", "max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z", "max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "t-sakashita/rokko", "max_forks_repo_path": "example/blas/dgemm.c", "max_issues_count": 514, "max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "t-sakashita/rokko", "max_issues_repo_path": "example/blas/dgemm.c", "max_line_length": 296, "max_stars_count": 16, "max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "t-sakashita/rokko", "max_stars_repo_path": "example/blas/dgemm.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z", "num_tokens": 1768, "size": 4046 }
/** * \file BaseFilter.h */ #ifndef ATK_CORE_BASEFILTER_H #define ATK_CORE_BASEFILTER_H #include <cstdint> #include <string> #include <vector> #include <boost/dynamic_bitset/dynamic_bitset.hpp> #include <gsl/gsl> #include <ATK/config.h> #include <ATK/Core/config.h> #if ATK_PROFILING == 1 #include <chrono> #endif #if ATK_USE_THREADPOOL == 1 #include <tbb/queuing_mutex.h> #endif namespace ATK { /// Base class for all filters class BaseFilter { public: BaseFilter(const BaseFilter&) = delete; BaseFilter& operator=(const BaseFilter&) = delete; /*! * @brief Constructor for the core filter * @param nb_input_ports is the total number of input ports of this filter * @param nb_output_ports is the total number of output ports of this filter */ ATK_CORE_EXPORT BaseFilter(gsl::index nb_input_ports, gsl::index nb_output_ports); /// Move constructor ATK_CORE_EXPORT BaseFilter(BaseFilter&& other) noexcept; /// Destructor virtual ATK_CORE_EXPORT ~BaseFilter(); /*! * @brief Links this filter port to another filter's output port * @param input_port is the port number where this filter will receive something * @param filter is a pointer to the previous filter * @param output_port is the port number where this filter will be connected */ ATK_CORE_EXPORT virtual void set_input_port(gsl::index input_port, gsl::not_null<BaseFilter*> filter, gsl::index output_port) = 0; ATK_CORE_EXPORT virtual void set_input_port(gsl::index input_port, BaseFilter& filter, gsl::index output_port); /// Starts processing after calling reset ATK_CORE_EXPORT void process(gsl::index size); /// As process, but doesn't call process_impl ATK_CORE_EXPORT void dryrun(gsl::index size); #if ATK_USE_THREADPOOL == 1 /// Allows threaded processing ATK_CORE_EXPORT void process_parallel(gsl::index size); #endif /*! * @brief Setup the input sampling rate, must be in sync with the rest of the pipeline * @param rate is the input sampling rate of the plugin */ ATK_CORE_EXPORT void set_input_sampling_rate(gsl::index rate); /// Returns this filter internal input sampling rate ATK_CORE_EXPORT gsl::index get_input_sampling_rate() const; /*! * @brief Setup the output sampling rate, must be in sync with the rest of the pipeline * @param rate is the output sampling rate of the plugin */ ATK_CORE_EXPORT void set_output_sampling_rate(gsl::index rate); /// Returns this filter internal output sampling rate ATK_CORE_EXPORT gsl::index get_output_sampling_rate() const; /// Returns this filter number of input ports ATK_CORE_EXPORT gsl::index get_nb_input_ports() const; /*! * @brief Changes the number of input ports * Will trigger a full setup * @param nb_ports is the new number of input ports of the plugin */ ATK_CORE_EXPORT virtual void set_nb_input_ports(gsl::index nb_ports); /// Returns this filter number of input ports ATK_CORE_EXPORT gsl::index get_nb_output_ports() const; /*! * @brief Changes the number of output ports * Will trigger a full setup * @param nb_ports is the new number of output ports of the plugin */ ATK_CORE_EXPORT virtual void set_nb_output_ports(gsl::index nb_ports); /// Returns this filter input delay (additional pre-0 samples) ATK_CORE_EXPORT void set_input_delay(gsl::index delay); /// Returns this filter input delay (additional pre-0 samples) ATK_CORE_EXPORT gsl::index get_input_delay() const; /// Returns this filter output delay (additional pre-0 samples) ATK_CORE_EXPORT void set_output_delay(gsl::index delay); /// Returns this filter output delay (additional pre-0 samples) ATK_CORE_EXPORT gsl::index get_output_delay() const; /*! * @brief Changes the filter's latency * @param latency is the new latency */ ATK_CORE_EXPORT virtual void set_latency(gsl::index latency); /// Returns this filter latency ATK_CORE_EXPORT gsl::index get_latency() const; /// Returns the pipeline global latency from this plugin ATK_CORE_EXPORT gsl::index get_global_latency() const; /// Resets the internal state of the filter (mandatory before processing a new clip in a DAW for instance) ATK_CORE_EXPORT virtual void full_setup(); /// Resets the filter so that it will process something if needed void reset(); /// Returns the type that the filter processes virtual int get_type() const = 0; /// Starts processing without calling reset template<bool must_process> void process_conditionnally(gsl::index size); #if ATK_USE_THREADPOOL == 1 /// Starts parallel processing without calling reset void process_conditionnally_parallel(gsl::index size); #endif protected: /// The actual filter processing part virtual void process_impl(gsl::index size) const = 0; /// Prepares the filter by retrieving the inputs arrays virtual void prepare_process(gsl::index size) = 0; /// Prepares the filter by resizing the outputs arrays virtual void prepare_outputs(gsl::index size) = 0; /// Changes the internal check to allow a disconnected input port void allow_inactive_connection(unsigned int port); /// Use this call to recompute internal parameters ATK_CORE_EXPORT virtual void setup(); /// Number of input ports gsl::index nb_input_ports = 0; /// Number of output ports gsl::index nb_output_ports = 0; /// Input sampling rate of the plugin gsl::index input_sampling_rate = 0; /// Output sampling rate of the plugin gsl::index output_sampling_rate = 0; /// The connections to the output pins of some filters std::vector<std::pair<gsl::index, BaseFilter*> > connections; /// Input delay of the input port gsl::index input_delay = 0; /// Output delay of the input port gsl::index output_delay = 0; /// Latency of the plugin gsl::index latency = 0; /// Last processed size gsl::index last_size = 0; private: boost::dynamic_bitset<> input_mandatory_connection; bool is_reset = false; #if ATK_PROFILING == 1 std::string class_name; std::chrono::steady_clock::duration input_conversion_time; std::chrono::steady_clock::duration output_conversion_time; std::chrono::steady_clock::duration process_time; #endif #if ATK_USE_THREADPOOL == 1 tbb::queuing_mutex mutex; #endif }; } #endif
{ "alphanum_fraction": 0.7144613493, "avg_line_length": 36.15, "ext": "h", "hexsha": "e13fbaa86ecfbe7e363c594c816936a08ef825f9", "lang": "C", "max_forks_count": 48, "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_path": "ATK/Core/BaseFilter.h", "max_issues_count": 22, "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_path": "ATK/Core/BaseFilter.h", "max_line_length": 134, "max_stars_count": 249, "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_path": "ATK/Core/BaseFilter.h", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "num_tokens": 1500, "size": 6507 }
#include <gsl/gsl_randist.h> #include <time.h> gsl_rng *r; void initialiseStatistics() { r = gsl_rng_alloc(gsl_rng_ranlxs0); gsl_rng_set(r, time(NULL)); } void cleanupStatistics() { free(r); } double denormalise(double standardNormalValue, double mean, double stddev) { return (standardNormalValue * stddev) + mean; } double getRandomGaussian(double mean, double stddev, double *min, double *max) { double v = gsl_ran_gaussian(r, 1.0); double d = denormalise(v, mean, stddev); if (min != NULL) { if (d <= *min) { return getRandomGaussian(mean, stddev, min, max); } } if (max != NULL) { if (d >= *max) { return getRandomGaussian(mean, stddev, min, max); } } return d; }
{ "alphanum_fraction": 0.643537415, "avg_line_length": 18.375, "ext": "c", "hexsha": "c7313736e68794d5feb39408ce63e01e97970f6e", "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": "574b1d6ff87d6b0a51385fde22710e6a60ed0169", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kunal-mandalia/economic-model", "max_forks_repo_path": "src/statistics.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "574b1d6ff87d6b0a51385fde22710e6a60ed0169", "max_issues_repo_issues_event_max_datetime": "2019-09-16T23:39:47.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-16T23:39:47.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kunal-mandalia/economic-model", "max_issues_repo_path": "src/statistics.c", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "574b1d6ff87d6b0a51385fde22710e6a60ed0169", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kunal-mandalia/economic-model", "max_stars_repo_path": "src/statistics.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 214, "size": 735 }
#ifndef SCANMATCHERPROCESSOR_H #define SCANMATCHERPROCESSOR_H // #include <log/sensorlog.h> #include "sensor/sensor_range/rangereading.h" #include "sensor/sensor_range/rangesensor.h" //#include <gsl/gsl_eigen.h> #include "scanmatcher.h" namespace GMapping { class ScanMatcherProcessor { public: ScanMatcherProcessor(const ScanMatcherMap& m); ScanMatcherProcessor(double xmin, double ymin, double xmax, double ymax, double delta, double patchdelta, bool use_icp); virtual ~ScanMatcherProcessor(); virtual void processScan(const RangeReading& reading); void setSensorMap(const SensorMap& smap, std::string sensorName = "FLASER"); void init(); void setMatchingParameters(double urange, double range, double sigma, int kernsize, double lopt, double aopt, int iterations, bool computeCovariance = false); void setRegistrationParameters(double regScore, double critScore); OrientedPoint getPose() const; inline const ScanMatcherMap& getMap() const { return m_map; } inline ScanMatcher& matcher() { return m_matcher; } inline void setmaxMove(double mmove) { m_maxMove = mmove; } bool useICP; protected: ScanMatcher m_matcher; bool m_computeCovariance; bool m_first; SensorMap m_sensorMap; double m_regScore, m_critScore; unsigned int m_beams; double m_maxMove; // state ScanMatcherMap m_map; OrientedPoint m_pose; OrientedPoint m_odoPose; int m_count; // gsl_eigen_symmv_workspace * m_eigenspace; }; }; // namespace GMapping #endif
{ "alphanum_fraction": 0.7313337588, "avg_line_length": 31.34, "ext": "h", "hexsha": "5d48cfa6a5862fb0fe4b939815abe2b8836d36ee", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-11-18T21:30:38.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-18T21:30:38.000Z", "max_forks_repo_head_hexsha": "574e40a7b9a2cd529e8c9ba4802c9f849923251d", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "yangliu-nv/openslam_gmapping", "max_forks_repo_path": "scanmatcher/scanmatcherprocessor.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "574e40a7b9a2cd529e8c9ba4802c9f849923251d", "max_issues_repo_issues_event_max_datetime": "2019-11-18T21:33:00.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-18T21:33:00.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "yangliu-nv/openslam_gmapping", "max_issues_repo_path": "scanmatcher/scanmatcherprocessor.h", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "574e40a7b9a2cd529e8c9ba4802c9f849923251d", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "yangliu-nv/openslam_gmapping", "max_stars_repo_path": "scanmatcher/scanmatcherprocessor.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 389, "size": 1567 }
#include <math.h> #include <stdio.h> #include <mpfr.h> #include <gmp.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <gsl/gsl_sf_legendre.h> #include <petsc.h> #undef __FUNCT__ #define __FUNCT__ "DEwk" PetscErrorCode DEwk(PetscInt k, mpfr_t h, mpfr_t *wk) { PetscErrorCode ierr; mpfr_t kh, msinh, mcosh, piOver2, tmp; PetscFunctionBegin; mpfr_inits(kh, msinh, mcosh, piOver2, tmp, NULL); //init piOver2 mpfr_const_pi(piOver2, MPFR_RNDN); mpfr_mul_d(piOver2, piOver2, 0.5, MPFR_RNDN); mpfr_set_d(kh, (double) k, MPFR_RNDN); mpfr_mul(kh, kh, h, MPFR_RNDN); mpfr_set(*wk, h, MPFR_RNDN); mpfr_sinh_cosh(msinh, mcosh, kh, MPFR_RNDN); mpfr_mul(msinh, msinh, piOver2, MPFR_RNDN); mpfr_mul(mcosh, mcosh, piOver2, MPFR_RNDN); mpfr_cosh(tmp, msinh, MPFR_RNDN); mpfr_sqr(tmp, tmp, MPFR_RNDN); mpfr_mul(*wk, *wk, mcosh, MPFR_RNDN); mpfr_div(*wk, *wk, tmp, MPFR_RNDN); PetscFunctionReturn(0); } /* have to make single exponential */ #undef __FUNCT__ #define __FUNCT__ "SEwk" PetscErrorCode SEwk(PetscInt k, mpfr_t h, mpfr_t *wk) { PetscErrorCode ierr; mpfr_t kh, msinh, mcosh, piOver2, tmp; PetscFunctionBegin; mpfr_inits(kh, msinh, mcosh, piOver2, tmp, NULL); //init piOver2 mpfr_const_pi(piOver2, MPFR_RNDN); mpfr_mul_d(piOver2, piOver2, 0.5, MPFR_RNDN); mpfr_set_d(kh, (double) k, MPFR_RNDN); mpfr_mul(kh, kh, h, MPFR_RNDN); //printf("wow kh: %15.15f\n", mpfr_get_d(kh, MPFR_RNDN)); mpfr_tanh(*wk, kh, MPFR_RNDN); //printf("wow wk: %15.15f\n", mpfr_get_d(*wk, MPFR_RNDN)); mpfr_mul(*wk, *wk, *wk, MPFR_RNDN); mpfr_d_sub(*wk, 1.0, *wk, MPFR_RNDN); mpfr_mul(*wk, *wk, h, MPFR_RNDN); //mpfr_set(*wk, h, MPFR_RNDN); //mpfr_sinh_cosh(msinh, mcosh, kh, MPFR_RNDN); //mpfr_mul(msinh, msinh, piOver2, MPFR_RNDN); //mpfr_mul(mcosh, mcosh, piOver2, MPFR_RNDN); //mpfr_cosh(tmp, msinh, MPFR_RNDN); //mpfr_sqr(tmp, tmp, MPFR_RNDN); //mpfr_mul(*wk, *wk, mcosh, MPFR_RNDN); //mpfr_div(*wk, *wk, tmp, MPFR_RNDN); PetscFunctionReturn(0); } /* have to make single exponential */ #undef __FUNCT__ #define __FUNCT__ "ERFwk" PetscErrorCode ERFwk(PetscInt k, mpfr_t h, mpfr_t *wk) { PetscErrorCode ierr; mpfr_t kh, msinh, mcosh, piOver2, tmp; PetscFunctionBegin; mpfr_inits(kh, msinh, mcosh, piOver2, tmp, NULL); // init constant mpfr_const_pi(piOver2, MPFR_RNDN); mpfr_sqrt(piOver2, piOver2, MPFR_RNDN); mpfr_d_div(piOver2, 2.0, piOver2, MPFR_RNDN); mpfr_set_d(kh, (double) k, MPFR_RNDN); mpfr_mul(kh, kh, h, MPFR_RNDN); mpfr_mul(tmp, kh, kh, MPFR_RNDN); mpfr_mul_d(tmp, tmp, -1.0, MPFR_RNDN); mpfr_exp(*wk, tmp, MPFR_RNDN); mpfr_mul(*wk, *wk, h, MPFR_RNDN); mpfr_mul(*wk, *wk, piOver2, MPFR_RNDN); PetscFunctionReturn(0); } /* generates n weights spaced h apart in the positive direction */ /* includes "center" n=0 weight as first entry */ #undef __FUNCT__ #define __FUNCT__ "DExkwk" PetscErrorCode DExkwk(PetscInt n, mpfr_t h, mpfr_t **xk, mpfr_t **wk) { PetscErrorCode ierr; PetscInt k; mpfr_t kh, msinh, mcosh, piOver2, tmp; PetscReal alp, bet; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; mpfr_inits(kh, msinh, mcosh, piOver2, tmp, NULL); // init piOver2 mpfr_const_pi(piOver2, MPFR_RNDN); mpfr_mul_d(piOver2, piOver2, 0.5, MPFR_RNDN); flopCount ++; for(k=0; k<n; ++k) { /* calculate wk */ mpfr_set_d(kh, (double) k, MPFR_RNDN); mpfr_mul(kh, kh, h, MPFR_RNDN); mpfr_set((*wk)[k], h, MPFR_RNDN); mpfr_sinh_cosh(msinh, mcosh, kh, MPFR_RNDN); mpfr_mul(msinh, msinh, piOver2, MPFR_RNDN); mpfr_mul(mcosh, mcosh, piOver2, MPFR_RNDN); mpfr_cosh(tmp, msinh, MPFR_RNDN); mpfr_sqr(tmp, tmp, MPFR_RNDN); mpfr_mul((*wk)[k], (*wk)[k], mcosh, MPFR_RNDN); mpfr_div((*wk)[k], (*wk)[k], tmp, MPFR_RNDN); flopCount += 9; /* calculate xk */ mpfr_set_d((*xk)[k], 1.0, MPFR_RNDZ); mpfr_cosh(tmp, msinh, MPFR_RNDN); mpfr_div((*xk)[k], (*xk)[k], tmp, MPFR_RNDZ); mpfr_exp(tmp, msinh, MPFR_RNDN); mpfr_div((*xk)[k], (*xk)[k], tmp, MPFR_RNDZ); flopCount += 4; } mpfr_clears(kh, msinh, mcosh, piOver2, tmp, NULL); ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); PetscFunctionReturn(0); } /* generates n weights spaced h apart in the positive direction */ /* includes "center" n=0 weight as first entry */ #undef __FUNCT__ #define __FUNCT__ "SExkwk" PetscErrorCode SExkwk(PetscInt n, mpfr_t h, mpfr_t **xk, mpfr_t **wk) { PetscErrorCode ierr; PetscInt k; mpfr_t kh, msinh, mcosh, piOver2, tmp; PetscReal alp, bet; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; mpfr_inits(kh, msinh, mcosh, piOver2, tmp, NULL); // init piOver2 mpfr_const_pi(piOver2, MPFR_RNDN); mpfr_mul_d(piOver2, piOver2, 0.5, MPFR_RNDN); flopCount ++; for(k=0; k<n; ++k) { /* calculate wk */ mpfr_set_d(kh, (double) k, MPFR_RNDN); mpfr_mul(kh, kh, h, MPFR_RNDN); mpfr_tanh((*wk)[k], kh, MPFR_RNDN); mpfr_mul((*wk)[k], (*wk)[k], (*wk)[k], MPFR_RNDN); mpfr_d_sub((*wk)[k], 1.0, (*wk)[k], MPFR_RNDN); mpfr_mul((*wk)[k], (*wk)[k], h, MPFR_RNDN); flopCount += 5; /* calculate xk */ mpfr_tanh((*xk)[k], kh, MPFR_RNDN); flopCount += 1; //mpfr_set_d((*xk)[k], 1.0, MPFR_RNDZ); //mpfr_cosh(tmp, msinh, MPFR_RNDN); //mpfr_div((*xk)[k], (*xk)[k], tmp, MPFR_RNDZ); //mpfr_exp(tmp, msinh, MPFR_RNDN); //mpfr_div((*xk)[k], (*xk)[k], tmp, MPFR_RNDZ); flopCount += 4; //mpfr_d_sub(tmp, 1.0, (*xk)[k], MPFR_RNDN); //printf("xk: %15.15e\n1-xk: %15.15e\nwk: %3.3e\n\n", mpfr_get_d((*xk)[k], MPFR_RNDN), mpfr_get_d(tmp, MPFR_RNDN), mpfr_get_d((*wk)[k], MPFR_RNDN)); } mpfr_clears(kh, msinh, mcosh, piOver2, tmp, NULL); ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); PetscFunctionReturn(0); } /* generates n weights spaced h apart in the positive direction */ /* includes "center" n=0 weight as first entry */ #undef __FUNCT__ #define __FUNCT__ "ERFxkwk" PetscErrorCode ERFxkwk(PetscInt n, mpfr_t h, mpfr_t **xk, mpfr_t **wk) { PetscErrorCode ierr; PetscInt k; mpfr_t kh, msinh, mcosh, piOver2, tmp; PetscReal alp, bet; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; mpfr_inits(kh, msinh, mcosh, piOver2, tmp, NULL); // init piOver2 mpfr_const_pi(piOver2, MPFR_RNDN); mpfr_sqrt(piOver2, piOver2, MPFR_RNDN); mpfr_d_div(piOver2, 2.0, piOver2, MPFR_RNDN); //mpfr_mul_d(piOver2, piOver2, 0.5, MPFR_RNDN); flopCount ++; for(k=0; k<n; ++k) { /* calculate wk */ mpfr_set_d(kh, (double) k, MPFR_RNDN); mpfr_mul(kh, kh, h, MPFR_RNDN); mpfr_mul(tmp, kh, kh, MPFR_RNDN); mpfr_mul_d(tmp, tmp, -1.0, MPFR_RNDN); mpfr_exp((*wk)[k], tmp, MPFR_RNDN); mpfr_mul((*wk)[k], (*wk)[k], h, MPFR_RNDN); mpfr_mul((*wk)[k], (*wk)[k], piOver2, MPFR_RNDN); /* calculate xk */ mpfr_erf((*xk)[k], kh, MPFR_RNDN); } mpfr_clears(kh, msinh, mcosh, piOver2, tmp, NULL); ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "inte" PetscErrorCode inte(mpfr_t *x, mpfr_t *val, void *ctx) { PetscErrorCode ierr; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; //mpfr_mul(*val, *x, *x, MPFR_RNDN); //mpfr_mul(*val, *val, *x, MPFR_RNDN); flopCount += 2; mpfr_const_pi(*val, MPFR_RNDN); mpfr_mul_d(*val, *val, 2.0, MPFR_RNDN); mpfr_mul(*val, *val, *x, MPFR_RNDN); mpfr_sin(*val, *val, MPFR_RNDN); mpfr_mul(*val, *val, *x, MPFR_RNDN); //printf("xk: %15.15f\n", mpfr_get_d(*x, MPFR_RNDN)); //printf("val: %15.15f\n", mpfr_get_d(*val, MPFR_RNDN)); //mpfr_set_d(*val, 1.0, MPFR_RNDN); //mpfr_set(*val, *x, MPFR_RNDN); ierr = PetscLogFlops(flopCount);CHKERRQ(ierr); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "FindStepSize" PetscErrorCode FindStepSize(PetscInt prec, PetscInt nPts, mpfr_t *step) { PetscErrorCode ierr; const PetscReal tol = 1e-10; mpfr_t wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error; PetscInt cont; PetscFunctionBegin; if(prec < 1) { printf("prec should be positive\n"); PetscFunctionReturn(1); } mpfr_inits(wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error, NULL); mpfr_set_d(hl, 0.0, MPFR_RNDN); mpfr_set_d(hr, 2.0, MPFR_RNDN); /* make hr large enough */ mpfr_set_d(hr, 1.0, MPFR_RNDN); cont = 1; while(cont == 1) { ierr = DEwk(nPts, hr, &rwk);CHKERRQ(ierr); mpfr_log10(srwk, rwk, MPFR_RNDN); if(mpfr_get_d(srwk, MPFR_RNDN) < -2*prec) cont = 0; else mpfr_mul_d(hr, hr, 2.0, MPFR_RNDN); // make hr larger if value not small } //printf("hr: %15.15f\n", mpfr_get_d(hr, MPFR_RNDN)); /* make hl small enough */ mpfr_mul_d(hl, hr, 0.5, MPFR_RNDN); cont = 1; while(cont == 1) { ierr = DEwk(nPts, hl, &lwk);CHKERRQ(ierr); mpfr_log10(slwk, lwk, MPFR_RNDN); if(mpfr_get_d(slwk, MPFR_RNDN) > -2*prec) cont = 0; else mpfr_mul_d(hl, hl, 0.5, MPFR_RNDN); // make hl larger if value not small } //printf("hl: %15.15f\n", mpfr_get_d(hl, MPFR_RNDN)); //ierr = DEwk(nPts, hl, &lwk);CHKERRQ(ierr); //ierr = DEwk(nPts, hr, &rwk);CHKERRQ(ierr); cont = 1; while(cont == 1) { // average hl and hr mpfr_add(h, hl, hr, MPFR_RNDN); mpfr_mul_d(h, h, 0.5, MPFR_RNDN); // calculate weight and size ierr = DEwk(nPts, h, &wk);CHKERRQ(ierr); ierr = DEwk(nPts, hl, &lwk);CHKERRQ(ierr); ierr = DEwk(nPts, hr, &rwk);CHKERRQ(ierr); mpfr_log10(swk, wk, MPFR_RNDN); mpfr_log10(slwk, lwk, MPFR_RNDN); mpfr_log10(srwk, rwk, MPFR_RNDN); if( mpfr_get_d(swk, MPFR_RNDN) < -2*prec) mpfr_set(hr, h, MPFR_RNDN); else mpfr_set(hl, h, MPFR_RNDN); // calculate maximum possible error mpfr_sub(error, slwk, srwk, MPFR_RNDN); mpfr_abs(error, error, MPFR_RNDN); if(mpfr_get_d(error, MPFR_RNDN) < tol) cont = 0; } mpfr_set(*step, h, MPFR_RNDN); mpfr_clears(wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error, NULL); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "FindStepSizeSE" PetscErrorCode FindStepSizeSE(PetscInt prec, PetscInt nPts, mpfr_t *step) { PetscErrorCode ierr; const PetscReal tol = 1e-25; mpfr_t wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error; PetscInt cont; PetscFunctionBegin; if(prec < 1) { printf("prec should be positive\n"); PetscFunctionReturn(1); } mpfr_inits(wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error, NULL); mpfr_set_d(hl, 0.0, MPFR_RNDN); mpfr_set_d(hr, 2.0, MPFR_RNDN); /* make hr large enough */ mpfr_set_d(hr, 1.0, MPFR_RNDN); cont = 1; while(cont == 1) { ierr = SEwk(nPts, hr, &rwk);CHKERRQ(ierr); mpfr_log10(srwk, rwk, MPFR_RNDN); if(mpfr_get_d(srwk, MPFR_RNDN) < -2*prec) cont = 0; else mpfr_mul_d(hr, hr, 2.0, MPFR_RNDN); // make hr larger if value not small } //printf("hr: %15.15f\n", mpfr_get_d(hr, MPFR_RNDN)); /* make hl small enough */ mpfr_mul_d(hl, hr, 0.5, MPFR_RNDN); cont = 1; while(cont == 1) { ierr = SEwk(nPts, hl, &lwk);CHKERRQ(ierr); mpfr_log10(slwk, lwk, MPFR_RNDN); if(mpfr_get_d(slwk, MPFR_RNDN) > -2*prec) cont = 0; else mpfr_mul_d(hl, hl, 0.5, MPFR_RNDN); // make hl larger if value not small } //printf("hl: %15.15f\n", mpfr_get_d(hl, MPFR_RNDN)); ierr = SEwk(nPts, hl, &lwk);CHKERRQ(ierr); ierr = SEwk(nPts, hr, &rwk);CHKERRQ(ierr); //printf("lwk: %3.3e\n", mpfr_get_d(lwk, MPFR_RNDN)); //printf("rwk: %3.3e\n", mpfr_get_d(rwk, MPFR_RNDN)); cont = 1; while(cont == 1) { // average hl and hr mpfr_add(h, hl, hr, MPFR_RNDN); mpfr_mul_d(h, h, 0.5, MPFR_RNDN); // calculate weight and size ierr = SEwk(nPts, h, &wk);CHKERRQ(ierr); ierr = SEwk(nPts, hl, &lwk);CHKERRQ(ierr); ierr = SEwk(nPts, hr, &rwk);CHKERRQ(ierr); mpfr_log10(swk, wk, MPFR_RNDN); mpfr_log10(slwk, lwk, MPFR_RNDN); mpfr_log10(srwk, rwk, MPFR_RNDN); if( mpfr_get_d(swk, MPFR_RNDN) < -2*prec) mpfr_set(hr, h, MPFR_RNDN); else mpfr_set(hl, h, MPFR_RNDN); // calculate maximum possible error mpfr_sub(error, slwk, srwk, MPFR_RNDN); mpfr_abs(error, error, MPFR_RNDN); if(mpfr_get_d(error, MPFR_RNDN) < tol) cont = 0; //printf("h: %15.15f\nlwk: %3.3e\nrwk: %3.3e\n", mpfr_get_d(h, MPFR_RNDN), mpfr_get_d(lwk, MPFR_RNDN), mpfr_get_d(rwk, MPFR_RNDN)); } mpfr_set(*step, h, MPFR_RNDN); mpfr_clears(wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error, NULL); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "FindStepSizeERF" PetscErrorCode FindStepSizeERF(PetscInt prec, PetscInt nPts, mpfr_t *step) { PetscErrorCode ierr; const PetscReal tol = 1e-25; mpfr_t wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error; PetscInt cont; PetscFunctionBegin; if(prec < 1) { printf("prec should be positive\n"); PetscFunctionReturn(1); } mpfr_inits(wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error, NULL); mpfr_set_d(hl, 0.0, MPFR_RNDN); mpfr_set_d(hr, 2.0, MPFR_RNDN); /* make hr large enough */ mpfr_set_d(hr, 1.0, MPFR_RNDN); cont = 1; while(cont == 1) { ierr = ERFwk(nPts, hr, &rwk);CHKERRQ(ierr); mpfr_log10(srwk, rwk, MPFR_RNDN); if(mpfr_get_d(srwk, MPFR_RNDN) < -2*prec) cont = 0; else mpfr_mul_d(hr, hr, 2.0, MPFR_RNDN); // make hr larger if value not small } //printf("hr: %15.15f\n", mpfr_get_d(hr, MPFR_RNDN)); /* make hl small enough */ mpfr_mul_d(hl, hr, 0.5, MPFR_RNDN); cont = 1; while(cont == 1) { ierr = ERFwk(nPts, hl, &lwk);CHKERRQ(ierr); mpfr_log10(slwk, lwk, MPFR_RNDN); if(mpfr_get_d(slwk, MPFR_RNDN) > -2*prec) cont = 0; else mpfr_mul_d(hl, hl, 0.5, MPFR_RNDN); // make hl larger if value not small } //printf("hl: %15.15f\n", mpfr_get_d(hl, MPFR_RNDN)); ierr = ERFwk(nPts, hl, &lwk);CHKERRQ(ierr); ierr = ERFwk(nPts, hr, &rwk);CHKERRQ(ierr); //printf("lwk: %3.3e\n", mpfr_get_d(lwk, MPFR_RNDN)); //printf("rwk: %3.3e\n", mpfr_get_d(rwk, MPFR_RNDN)); cont = 1; while(cont == 1) { // average hl and hr mpfr_add(h, hl, hr, MPFR_RNDN); mpfr_mul_d(h, h, 0.5, MPFR_RNDN); // calculate weight and size ierr = ERFwk(nPts, h, &wk);CHKERRQ(ierr); ierr = ERFwk(nPts, hl, &lwk);CHKERRQ(ierr); ierr = ERFwk(nPts, hr, &rwk);CHKERRQ(ierr); mpfr_log10(swk, wk, MPFR_RNDN); mpfr_log10(slwk, lwk, MPFR_RNDN); mpfr_log10(srwk, rwk, MPFR_RNDN); if( mpfr_get_d(swk, MPFR_RNDN) < -2*prec) mpfr_set(hr, h, MPFR_RNDN); else mpfr_set(hl, h, MPFR_RNDN); // calculate maximum possible error mpfr_sub(error, slwk, srwk, MPFR_RNDN); mpfr_abs(error, error, MPFR_RNDN); if(mpfr_get_d(error, MPFR_RNDN) < tol) cont = 0; //printf("h: %15.15f\n", mpfr_get_d(h, MPFR_RNDN)); } //printf("h: %15.15f\n", mpfr_get_d(h, MPFR_RNDN)); //printf("h: %15.15f\nlwk: %3.3e\nrwk: %3.3e\n", mpfr_get_d(h, MPFR_RNDN), mpfr_get_d(lwk, MPFR_RNDN), mpfr_get_d(rwk, MPFR_RNDN)); mpfr_set(*step, h, MPFR_RNDN); mpfr_clears(wk, tmp, h, hl, hr, lwk, rwk, swk, slwk, srwk, error, NULL); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "DEQuad" PetscErrorCode DEQuad(PetscErrorCode (*f)(mpfr_t*,mpfr_t*,void*), mpfr_t a, mpfr_t b, PetscInt prec, PetscInt nPts, PetscReal *integral, void *ctx) { PetscErrorCode ierr; PetscInt k; PetscInt nSide; mpfr_t alpha, beta; mpfr_t leftXk, rightXk; mpfr_t wk; mpfr_t *wkVals; mpfr_t *xkVals; mpfr_t lx, rx; mpfr_t leftFx, rightFx; mpfr_t pi2; mpfr_t kh, h; mpfr_t sum; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; if(nPts % 2 == 0) { nSide = nPts/2; flopCount++; } if(nPts % 2 == 1) { nSide = (nPts-1)/2; flopCount++; } /* initializations */ mpfr_inits(alpha, beta, leftXk, rightXk, wk, leftFx, rightFx, pi2, kh, h, sum, lx, rx, NULL); wkVals = (mpfr_t*) malloc(sizeof(mpfr_t)*(nSide+1)); xkVals = (mpfr_t*) malloc(sizeof(mpfr_t)*(nSide+1)); for(k=0; k<nSide+1; ++k) mpfr_inits(xkVals[k], wkVals[k], NULL); // init alpha, beta mpfr_set(alpha, b, MPFR_RNDN); mpfr_sub(alpha, alpha, a, MPFR_RNDN); mpfr_mul_d(alpha, alpha, 0.5, MPFR_RNDN); mpfr_set(beta, b, MPFR_RNDN); mpfr_add(beta, beta, a, MPFR_RNDN); mpfr_mul_d(beta, beta, 0.5, MPFR_RNDN); flopCount += 4; /* determine right step size */ ierr = FindStepSize(prec, nSide, &h); // not including in flop count //printf("DE step size: %15.15f\n", mpfr_get_d(h, MPFR_RNDN)); //mpfr_set_d(h, 0.04, MPFR_RNDN); /* calculate abscissas, weights */ ierr = DExkwk(nSide+1, h, &xkVals, &wkVals);CHKERRQ(ierr); /* center term */ mpfr_set_d(sum, 0.0, MPFR_RNDN); mpfr_set(lx, b, MPFR_RNDN); mpfr_add(lx, lx, a, MPFR_RNDN); mpfr_mul_d(lx, lx, .5, MPFR_RNDN); f(&lx, &sum, ctx); mpfr_mul(sum, sum, wkVals[0], MPFR_RNDN); mpfr_mul(sum, sum, alpha, MPFR_RNDN); flopCount += 4; for(k=1; k <= nSide; ++k) { // adjust xk to [a,b] mpfr_sub_d(lx, xkVals[k], 1.0, MPFR_RNDZ); mpfr_mul(lx, lx, alpha, MPFR_RNDU); mpfr_add(lx, lx, beta, MPFR_RNDU); mpfr_d_sub(rx, 1.0, xkVals[k], MPFR_RNDZ); mpfr_mul(rx, rx, alpha, MPFR_RNDD); mpfr_add(rx, rx, beta , MPFR_RNDD); flopCount += 6; double left = mpfr_get_d(lx, MPFR_RNDN); double right = mpfr_get_d(rx, MPFR_RNDN); double xk = mpfr_get_d(xkVals[k], MPFR_RNDN); /* calculate function values */ f(&lx, &leftFx , ctx); f(&rx, &rightFx, ctx); /* update sum */ mpfr_mul(leftFx, leftFx, wkVals[k], MPFR_RNDN); mpfr_mul(rightFx, rightFx, wkVals[k], MPFR_RNDN); mpfr_mul(leftFx, leftFx, alpha, MPFR_RNDN); mpfr_mul(rightFx, rightFx, alpha, MPFR_RNDN); //double l1 = mpfr_get_d(leftFx, MPFR_RNDN); //double l2 = mpfr_get_d(rightFx, MPFR_RNDN); //printf("leftval: %15.15f\n", l1); //printf("rightval: %15.15f\n", l2); mpfr_add(sum, sum, leftFx, MPFR_RNDN); mpfr_add(sum, sum, rightFx, MPFR_RNDN); flopCount += 6; } PetscReal prog = mpfr_get_d(sum, MPFR_RNDN); //printf("sum: %15.15f\n", prog); *integral = prog; mpfr_clears(alpha, beta, leftXk, rightXk, wk, leftFx, rightFx, pi2, kh, h, sum, lx, rx, NULL); for(k=0; k<nSide+1; ++k) mpfr_clears(wkVals[k], xkVals[k], NULL); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "SEQuad" PetscErrorCode SEQuad(PetscErrorCode (*f)(mpfr_t*,mpfr_t*,void*), mpfr_t a, mpfr_t b, PetscInt prec, PetscInt nPts, PetscReal *integral, void *ctx) { PetscErrorCode ierr; PetscInt k; PetscInt nSide; mpfr_t alpha, beta; mpfr_t leftXk, rightXk; mpfr_t wk; mpfr_t *wkVals; mpfr_t *xkVals; mpfr_t lx, rx; mpfr_t leftFx, rightFx; mpfr_t pi2; mpfr_t kh, h; mpfr_t sum; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; if(nPts % 2 == 0) { nSide = nPts/2; flopCount++; } if(nPts % 2 == 1) { nSide = (nPts-1)/2; flopCount++; } /* initializations */ mpfr_inits(alpha, beta, leftXk, rightXk, wk, leftFx, rightFx, pi2, kh, h, sum, lx, rx, NULL); wkVals = (mpfr_t*) malloc(sizeof(mpfr_t)*(nSide+1)); xkVals = (mpfr_t*) malloc(sizeof(mpfr_t)*(nSide+1)); for(k=0; k<nSide+1; ++k) mpfr_inits(xkVals[k], wkVals[k], NULL); // init alpha, beta mpfr_set(alpha, b, MPFR_RNDN); mpfr_sub(alpha, alpha, a, MPFR_RNDN); mpfr_mul_d(alpha, alpha, 0.5, MPFR_RNDN); mpfr_set(beta, b, MPFR_RNDN); mpfr_add(beta, beta, a, MPFR_RNDN); mpfr_mul_d(beta, beta, 0.5, MPFR_RNDN); flopCount += 4; /* determine right step size */ ierr = FindStepSizeSE(prec, nSide, &h); // not including in flop count //printf("step size: %15.15f\n", mpfr_get_d(h, MPFR_RNDN)); //printf("step size: %15.15f\n", mpfr_get_d(h, MPFR_RNDN)); //mpfr_set_d(h, 0.04, MPFR_RNDN); /* calculate abscissas, weights */ ierr = SExkwk(nSide+1, h, &xkVals, &wkVals);CHKERRQ(ierr); /* center term */ mpfr_set_d(sum, 0.0, MPFR_RNDN); mpfr_set(lx, b, MPFR_RNDN); mpfr_add(lx, lx, a, MPFR_RNDN); mpfr_mul_d(lx, lx, .5, MPFR_RNDN); f(&lx, &sum, ctx); mpfr_mul(sum, sum, wkVals[0], MPFR_RNDN); mpfr_mul(sum, sum, alpha, MPFR_RNDN); flopCount += 4; for(k=1; k <= nSide; ++k) { // adjust xk to [a,b] //mpfr_sub_d(lx, xkVals[k], 1.0, MPFR_RNDZ); mpfr_mul_d(lx, xkVals[k], -1.0, MPFR_RNDN); mpfr_mul(lx, lx, alpha, MPFR_RNDU); mpfr_add(lx, lx, beta, MPFR_RNDU); //mpfr_d_sub(rx, 1.0, xkVals[k], MPFR_RNDZ); mpfr_set(rx, xkVals[k], MPFR_RNDN); mpfr_mul(rx, rx, alpha, MPFR_RNDD); mpfr_add(rx, rx, beta , MPFR_RNDD); flopCount += 6; double left = mpfr_get_d(lx, MPFR_RNDN); double right = mpfr_get_d(rx, MPFR_RNDN); double xk = mpfr_get_d(xkVals[k], MPFR_RNDN); /* calculate function values */ f(&lx, &leftFx , ctx); f(&rx, &rightFx, ctx); /* update sum */ mpfr_mul(leftFx, leftFx, wkVals[k], MPFR_RNDN); mpfr_mul(rightFx, rightFx, wkVals[k], MPFR_RNDN); mpfr_mul(leftFx, leftFx, alpha, MPFR_RNDN); mpfr_mul(rightFx, rightFx, alpha, MPFR_RNDN); //double l1 = mpfr_get_d(leftFx, MPFR_RNDN); //double l2 = mpfr_get_d(rightFx, MPFR_RNDN); //printf("leftval: %15.15f\n", l1); //printf("rightval: %15.15f\n", l2); mpfr_add(sum, sum, leftFx, MPFR_RNDN); mpfr_add(sum, sum, rightFx, MPFR_RNDN); flopCount += 6; //printf("sum[%d] = %15.15f\n", k, mpfr_get_d(sum, MPFR_RNDN)); //printf("wk[%d] = %3.3e\n\n", k, mpfr_get_d(wkVals[k], MPFR_RNDN)); } PetscReal prog = mpfr_get_d(sum, MPFR_RNDN); //printf("sum: %15.15f\n", prog); *integral = prog; mpfr_clears(alpha, beta, leftXk, rightXk, wk, leftFx, rightFx, pi2, kh, h, sum, lx, rx, NULL); for(k=0; k<nSide+1; ++k) mpfr_clears(wkVals[k], xkVals[k], NULL); PetscFunctionReturn(0); } #undef __FUNCT__ #define __FUNCT__ "ERFQuad" PetscErrorCode ERFQuad(PetscErrorCode (*f)(mpfr_t*,mpfr_t*,void*), mpfr_t a, mpfr_t b, PetscInt prec, PetscInt nPts, PetscReal *integral, void *ctx) { PetscErrorCode ierr; PetscInt k; PetscInt nSide; mpfr_t alpha, beta; mpfr_t leftXk, rightXk; mpfr_t wk; mpfr_t *wkVals; mpfr_t *xkVals; mpfr_t lx, rx; mpfr_t leftFx, rightFx; mpfr_t pi2; mpfr_t kh, h; mpfr_t sum; PetscInt flopCount; PetscFunctionBegin; flopCount = 0; if(nPts % 2 == 0) { nSide = nPts/2; flopCount++; } if(nPts % 2 == 1) { nSide = (nPts-1)/2; flopCount++; } /* initializations */ mpfr_inits(alpha, beta, leftXk, rightXk, wk, leftFx, rightFx, pi2, kh, h, sum, lx, rx, NULL); wkVals = (mpfr_t*) malloc(sizeof(mpfr_t)*(nSide+1)); xkVals = (mpfr_t*) malloc(sizeof(mpfr_t)*(nSide+1)); for(k=0; k<nSide+1; ++k) mpfr_inits(xkVals[k], wkVals[k], NULL); // init alpha, beta mpfr_set(alpha, b, MPFR_RNDN); mpfr_sub(alpha, alpha, a, MPFR_RNDN); mpfr_mul_d(alpha, alpha, 0.5, MPFR_RNDN); mpfr_set(beta, b, MPFR_RNDN); mpfr_add(beta, beta, a, MPFR_RNDN); mpfr_mul_d(beta, beta, 0.5, MPFR_RNDN); flopCount += 4; /* determine right step size */ ierr = FindStepSizeERF(prec, nSide, &h); // not including in flop count //mpfr_mul_d(h, h, 0.3, MPFR_RNDN); //printf("step size: %15.15f\n", mpfr_get_d(h, MPFR_RNDN)); //printf("step size: %15.15f\n", mpfr_get_d(h, MPFR_RNDN)); //mpfr_set_d(h, 0.04, MPFR_RNDN); /* calculate abscissas, weights */ ierr = ERFxkwk(nSide+1, h, &xkVals, &wkVals);CHKERRQ(ierr); /* center term */ mpfr_set_d(sum, 0.0, MPFR_RNDN); mpfr_set(lx, b, MPFR_RNDN); mpfr_add(lx, lx, a, MPFR_RNDN); mpfr_mul_d(lx, lx, .5, MPFR_RNDN); f(&lx, &sum, ctx); mpfr_mul(sum, sum, wkVals[0], MPFR_RNDN); mpfr_mul(sum, sum, alpha, MPFR_RNDN); flopCount += 4; for(k=1; k <= nSide; ++k) { // adjust xk to [a,b] //mpfr_sub_d(lx, xkVals[k], 1.0, MPFR_RNDZ); mpfr_mul_d(lx, xkVals[k], -1.0, MPFR_RNDN); mpfr_mul(lx, lx, alpha, MPFR_RNDU); mpfr_add(lx, lx, beta, MPFR_RNDU); //mpfr_d_sub(rx, 1.0, xkVals[k], MPFR_RNDZ); mpfr_mul(rx, xkVals[k], alpha, MPFR_RNDD); mpfr_add(rx, rx, beta , MPFR_RNDD); flopCount += 6; double left = mpfr_get_d(lx, MPFR_RNDN); double right = mpfr_get_d(rx, MPFR_RNDN); double xk = mpfr_get_d(xkVals[k], MPFR_RNDN); //printf("left: %15.15f\n", left); //printf("right: %15.15f\n", right); //printf("\n"); /* calculate function values */ f(&lx, &leftFx , ctx); f(&rx, &rightFx, ctx); /* update sum */ mpfr_mul(leftFx, leftFx, wkVals[k], MPFR_RNDN); mpfr_mul(rightFx, rightFx, wkVals[k], MPFR_RNDN); mpfr_mul(leftFx, leftFx, alpha, MPFR_RNDN); mpfr_mul(rightFx, rightFx, alpha, MPFR_RNDN); //double l1 = mpfr_get_d(leftFx, MPFR_RNDN); //double l2 = mpfr_get_d(rightFx, MPFR_RNDN); //printf("leftval: %15.15f\n", l1); //printf("rightval: %15.15f\n", l2); mpfr_add(sum, sum, leftFx, MPFR_RNDN); mpfr_add(sum, sum, rightFx, MPFR_RNDN); flopCount += 6; //printf("sum[%d] = %15.15f\n", k, mpfr_get_d(sum, MPFR_RNDN)); //printf("wk[%d] = %3.3e\n\n", k, mpfr_get_d(wkVals[k], MPFR_RNDN)); } PetscReal prog = mpfr_get_d(sum, MPFR_RNDN); //printf("sum: %15.15f\n", prog); *integral = prog; mpfr_clears(alpha, beta, leftXk, rightXk, wk, leftFx, rightFx, pi2, kh, h, sum, lx, rx, NULL); for(k=0; k<nSide+1; ++k) mpfr_clears(wkVals[k], xkVals[k], NULL); PetscFunctionReturn(0); }
{ "alphanum_fraction": 0.6413497126, "avg_line_length": 30.6, "ext": "c", "hexsha": "c6740472d04cf8ea22ba8e41fecf12bd82ee0138", "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": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "tom-klotz/ellipsoid-solvation", "max_forks_repo_path": "src/tanhsinh.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "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": "tom-klotz/ellipsoid-solvation", "max_issues_repo_path": "src/tanhsinh.c", "max_line_length": 152, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "tom-klotz/ellipsoid-solvation", "max_stars_repo_path": "src/tanhsinh.c", "max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z", "max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z", "num_tokens": 9852, "size": 25398 }
#ifndef LIC_RUNTIME_TYPE #define LIC_RUNTIME_TYPE #include <string> #include <gsl/gsl> #include <format/Opcodes.h> namespace lic { class RuntimeType { public: virtual ~RuntimeType(); virtual std::string Name() const = 0; virtual std::string ToString(gsl::byte* data) const = 0; virtual void PerformUnaryOp(Opcode op, gsl::byte* data) const; virtual void PerformBinaryOp(Opcode op, gsl::byte* leftData, RuntimeType* rightType, gsl::byte* rightData) const; protected: RuntimeType(); }; } #endif // !LIC_RUNTIME_TYPE
{ "alphanum_fraction": 0.7129798903, "avg_line_length": 18.2333333333, "ext": "h", "hexsha": "7273d3632096d5fa8f96fba773d1c5f528466884", "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": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "roberthusak/lic", "max_forks_repo_path": "src/types/RuntimeType.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "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": "roberthusak/lic", "max_issues_repo_path": "src/types/RuntimeType.h", "max_line_length": 117, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "roberthusak/lic", "max_stars_repo_path": "src/types/RuntimeType.h", "max_stars_repo_stars_event_max_datetime": "2017-05-18T11:44:16.000Z", "max_stars_repo_stars_event_min_datetime": "2017-05-18T11:44:16.000Z", "num_tokens": 141, "size": 547 }
/* interpolation/interp_poly.c * * Copyright (C) 2001 DAN, HO-JIN * Copyright (C) 2013 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. */ /* Modified for standalone use in polynomial directory, B.Gough 2001 */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_poly.h> int gsl_poly_dd_init (double dd[], const double xa[], const double ya[], size_t size) { size_t i, j; /* Newton's divided differences */ dd[0] = ya[0]; for (j = size - 1; j >= 1; j--) { dd[j] = (ya[j] - ya[j - 1]) / (xa[j] - xa[j - 1]); } for (i = 2; i < size; i++) { for (j = size - 1; j >= i; j--) { dd[j] = (dd[j] - dd[j - 1]) / (xa[j] - xa[j - i]); } } return GSL_SUCCESS; } int gsl_poly_dd_taylor (double c[], double xp, const double dd[], const double xa[], size_t size, double w[]) { size_t i, j; for (i = 0; i < size; i++) { c[i] = 0.0; w[i] = 0.0; } w[size - 1] = 1.0; c[0] = dd[0]; for (i = size - 1; i-- > 0;) { w[i] = -w[i + 1] * (xa[size - 2 - i] - xp); for (j = i + 1; j < size - 1; j++) { w[j] = w[j] - w[j + 1] * (xa[size - 2 - i] - xp); } for (j = i; j < size; j++) { c[j - i] += w[j] * dd[size - i - 1]; } } return GSL_SUCCESS; } /* gsl_poly_dd_hermite_init() Compute divided difference representation of data for Hermite polynomial interpolation Inputs: dd - (output) array of size 2*size containing divided differences, dd[k] = f[z_0,z_1,...,z_k] za - (output) array of size 2*size containing z values xa - x data ya - y data dya - dy/dx data size - size of xa,ya,dya arrays Return: success */ int gsl_poly_dd_hermite_init (double dd[], double za[], const double xa[], const double ya[], const double dya[], const size_t size) { const size_t N = 2 * size; size_t i, j; /* Hermite divided differences */ dd[0] = ya[0]; /* compute: dd[j] = f[z_{j-1},z_j] for j \in [1,N-1] */ for (j = 0; j < size; ++j) { za[2*j] = xa[j]; za[2*j + 1] = xa[j]; if (j != 0) { dd[2*j] = (ya[j] - ya[j - 1]) / (xa[j] - xa[j - 1]); dd[2*j - 1] = dya[j - 1]; } } dd[N - 1] = dya[size - 1]; for (i = 2; i < N; i++) { for (j = N - 1; j >= i; j--) { dd[j] = (dd[j] - dd[j - 1]) / (za[j] - za[j - i]); } } return GSL_SUCCESS; } /* gsl_poly_dd_hermite_init() */
{ "alphanum_fraction": 0.52079566, "avg_line_length": 23.5319148936, "ext": "c", "hexsha": "73b2bf91f908d8224ce9dfd2e722a326b05034e0", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/poly/dd.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/poly/dd.c", "max_line_length": 89, "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/poly/dd.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": 1069, "size": 3318 }
#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; class AnimationPlayer; class Model; class AnimationClip; } namespace Rendering { class SkinnedModelMaterial; class AnimationDemo final : public Library::DrawableGameComponent { public: AnimationDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera); AnimationDemo(const AnimationDemo&) = delete; AnimationDemo(AnimationDemo&&) = default; AnimationDemo& operator=(const AnimationDemo&) = default; AnimationDemo& operator=(AnimationDemo&&) = default; ~AnimationDemo(); bool ManualAdvanceEnabled() const; void SetManualAdvanceEnabled(bool enabled); void ToggleManualAdvance(); const std::unique_ptr<Library::AnimationPlayer>& AnimationPlayer() const; void TogglePause(); void RestartClip(); void IncrementCurrentKeyframe(); void DecrementCurrentKeyframe(); bool InterpolationEnabled() const; void SetInterpolationEnabled(bool enabled); void ToggleInterpolation(); float AmbientLightIntensity() const; void SetAmbientLightIntensity(float intensity); float DirectionalLightIntensity() const; void SetDirectionalLightIntensity(float intensity); const DirectX::XMFLOAT3& LightDirection() const; void RotateDirectionalLight(DirectX::XMFLOAT2 amount); 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<SkinnedModelMaterial> mMaterial; DirectX::XMFLOAT4X4 mWorldMatrix{ Library::MatrixHelper::Identity }; winrt::com_ptr<ID3D11Buffer> mVertexBuffer; winrt::com_ptr<ID3D11Buffer> mIndexBuffer; std::uint32_t mIndexCount{ 0 }; Library::DirectionalLight mDirectionalLight; std::unique_ptr<Library::ProxyModel> mProxyModel; bool mUpdateMaterial{ true }; bool mUpdateMaterialBoneTransforms{ true }; std::unique_ptr<Library::AnimationPlayer> mAnimationPlayer; bool mManualAdvanceEnabled{ false }; std::shared_ptr<Library::Model> mSkinnedModel; }; }
{ "alphanum_fraction": 0.7758241758, "avg_line_length": 29.9342105263, "ext": "h", "hexsha": "5fb3eec222230f1d37c2f63c3157003633960748", "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/9.1_Animation/AnimationDemo.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/9.1_Animation/AnimationDemo.h", "max_line_length": 85, "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/9.1_Animation/AnimationDemo.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 548, "size": 2275 }
// // View.hpp // PretendToWork // // Created by tqtifnypmb on 14/12/2017. // Copyright © 2017 tqtifnypmb. All rights reserved. // #pragma once #include "../rope/Range.h" #include "../types.h" #include "../editor/Editor.h" #include <memory> #include <utility> #include <gsl/gsl> #include <map> #include <string> namespace brick { class View { public: using UpdateCb = std::function<void(View* view, const Editor::DeltaList&)>; View(size_t viewId, UpdateCb cb); View(size_t viewId, View* parent, UpdateCb cb); View(size_t viewId, const std::string& filePath, UpdateCb cb); ~View(); void scroll(size_t begRow, size_t endRow); template<class Converter> void insert(gsl::span<const char> bytes); void insert(const detail::CodePointList& cplist); void erase(); void undo(); void select(Range sel); Range selection() const { return sel_; } void save(); void save(const std::string& filePath); template <class Converter> std::map<size_t, std::string> region() { return region<Converter>(visibleRange_.first, visibleRange_.second); } template <class Converter> std::map<size_t, std::string> region(size_t begRow, size_t endRow); size_t viewId() const { return viewId_; } size_t viewSize() const { return viewSize_; } bool hasChildren() const { return !children_.empty(); } void removeChild(const View* child) { auto found = std::find_if(children_.begin(), children_.end(), [child](const auto& v) { return v->viewId_ == child->viewId_; }); if (found != children_.end()) { children_.erase(found); } } const std::vector<View*>& children() const { return children_; } const std::string filePath() const { return filePath_; } bool hasParent() const { return parent() != nullptr; } const View* parent() const { return parent_; } private: void editor_sync_cb(const Editor::DeltaList& deltaList); void update(std::vector<View*>& src); std::map<size_t, detail::CodePointList> regionImpl(size_t begRow, size_t endRow); std::map<size_t, detail::CodePointList> regionImpl() { return regionImpl(visibleRange_.first, visibleRange_.second); } UpdateCb update_cb_; std::pair<size_t, size_t> visibleRange_; size_t viewId_; size_t viewSize_; View* parent_; Range sel_; std::vector<View*> children_; std::unique_ptr<Editor> editor_; std::string filePath_; }; template<class Converter> void View::insert(gsl::span<const char> bytes) { insert(Converter::encode(bytes)); } template <class Converter> std::map<size_t, std::string> View::region(size_t begRow, size_t endRow) { auto lines = regionImpl(begRow, endRow); std::map<size_t, std::string> ret; for (const auto& line : lines) { ret[line.first] = Converter::decode(line.second); } return ret; } }
{ "alphanum_fraction": 0.6171648987, "avg_line_length": 23.7480916031, "ext": "h", "hexsha": "5dfea6789c3fa04d762c849a10e91e2be62844cc", "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": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tqtifnypmb/brick", "max_forks_repo_path": "src/view/View.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "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": "tqtifnypmb/brick", "max_issues_repo_path": "src/view/View.h", "max_line_length": 135, "max_stars_count": null, "max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tqtifnypmb/brick", "max_stars_repo_path": "src/view/View.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 788, "size": 3111 }
/* * Copyright 2020 Makani Technologies LLC * * 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 SIM_MATH_INTERP_H_ #define SIM_MATH_INTERP_H_ #include <gsl/gsl_interp.h> #include <math.h> #include <vector> #include "common/c_math/vec3.h" #include "common/macros.h" namespace sim { // A TimeseriesInterpolator performs linear interpolation at timepoints within // the bounds of t, and 0th order extrapolation past the endpoints. class TimeseriesInterpolator { public: explicit TimeseriesInterpolator(const std::vector<double> &t); ~TimeseriesInterpolator(); double Interp(double t, const std::vector<double> &data); Vec3 InterpVec3(double t, const std::vector<Vec3> &data); double WrapInterp(double t, const std::vector<double> &data, double lower, double upper); Vec3 WrapInterpVec3(double t, const std::vector<Vec3> &data, double lower, double upper); private: double WrapInterpInternal(const std::vector<double> &values, const std::vector<double> &weights, double lower, double upper); struct InterpParams { InterpParams(const std::vector<int32_t> &indices__, const std::vector<double> &weights__) : indices(indices__), weights(weights__) {} ~InterpParams() {} std::vector<int32_t> indices; std::vector<double> weights; }; const std::vector<double> &t_; gsl_interp_accel *interp_accel_; InterpParams GetInterpParams(double t); DISALLOW_COPY_AND_ASSIGN(TimeseriesInterpolator); }; } // namespace sim #endif // SIM_MATH_INTERP_H_
{ "alphanum_fraction": 0.7029053421, "avg_line_length": 30.4857142857, "ext": "h", "hexsha": "d9cb9cb1cebc7e71b7afc44894d4e4ba8cfab577", "lang": "C", "max_forks_count": 107, "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "leozz37/makani", "max_forks_repo_path": "sim/math/interp.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "leozz37/makani", "max_issues_repo_path": "sim/math/interp.h", "max_line_length": 78, "max_stars_count": 1178, "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "leozz37/makani", "max_stars_repo_path": "sim/math/interp.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "num_tokens": 486, "size": 2134 }
/***************************************************************************** * * Rokko: Integrated Interface for libraries of eigenvalue decomposition * * Copyright (C) 2012-2017 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp> * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * *****************************************************************************/ #include <cblas.h> #include <lapacke.h> #include <rokko/cmatrix.h> int imin(int x, int y) { return (x < y) ? x : y; } int imax(int x, int y) { return (x > y) ? x : y; } int main(int argc, char** argv) { int m = 3; int n = 5; int r, lwork, i, j, info; double norm; double *s, *work; double **a, **u, **vt, **t; if (argc > 2) { m = atoi(argv[1]); n = atoi(argv[2]); } r = imin(m, n); /* generate matrix */ a = alloc_dmatrix(m, n); for (j = 0; j < n; ++j) { for (i = 0; i < m; ++i) { mat_elem(a, i, j) = n - imax(i, j); } } printf("Matrix A: "); fprint_dmatrix(stdout, m, n, a); /* singular value decomposition */ u = alloc_dmatrix(m, r); vt = alloc_dmatrix(r, n); s = alloc_dvector(r); t = alloc_dmatrix(m, n); cblas_dcopy(m * n, mat_ptr(a), 1, mat_ptr(t), 1); lwork = imax(3 * r + imax(m, n), 5 * r); work = alloc_dvector(lwork); info = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'S', 'S', m, n, mat_ptr(t), m, vec_ptr(s), mat_ptr(u), m, mat_ptr(vt), r, vec_ptr(work), lwork); if (info != 0) { fprintf(stderr, "Error: dgesvd fails\n"); exit(255); } free_dmatrix(t); printf("Matrix U: "); fprint_dmatrix(stdout, m, r, u); printf("Singular values: "); fprint_dvector(stdout, r, s); printf("Matrix Vt: "); fprint_dmatrix(stdout, r, n, vt); /* orthogonality check */ t = alloc_dmatrix(r, r); cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, r, r, m, 1, mat_ptr(u), m, mat_ptr(u), m, 0, mat_ptr(t), r); for (i = 0; i < r; ++i) mat_elem(t, i, i) -= 1; norm = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', r, r, mat_ptr(t), r); printf("|| U^t U - I || = %e\n", norm); if (norm > 1e-10) { fprintf(stderr, "Error: orthogonality check\n"); exit(255); } cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, r, r, n, 1, mat_ptr(vt), r, mat_ptr(vt), r, 0, mat_ptr(t), r); for (i = 0; i < r; ++i) mat_elem(t, i, i) -= 1; norm = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', r, r, mat_ptr(t), r); printf("|| V^t V - I || = %e\n", norm); if (norm > 1e-10) { fprintf(stderr, "Error: orthogonality check\n"); exit(255); } free_dmatrix(t); /* solution check */ t = alloc_dmatrix(m, r); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, m, r, n, 1, mat_ptr(a), m, mat_ptr(vt), r, 0, mat_ptr(t), m); free_dmatrix(vt); vt = alloc_dmatrix(r, r); cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, r, r, m, 1, mat_ptr(u), m, mat_ptr(t), m, 0, mat_ptr(vt), r); for (i = 0; i < r; ++i) mat_elem(vt, i, i) -= s[i]; norm = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', r, r, mat_ptr(vt), r); printf("|| U^t A V - diag(S) || = %e\n", norm); if (norm > 1e-10) { fprintf(stderr, "Error: solution check\n"); exit(255); } free_dmatrix(t); free_dmatrix(a); free_dmatrix(u); free_dmatrix(vt); free_dvector(s); return 0; }
{ "alphanum_fraction": 0.5466977015, "avg_line_length": 30.6875, "ext": "c", "hexsha": "03598b9354466773ae9be90783d9134ddb660e56", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z", "max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z", "max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "t-sakashita/rokko", "max_forks_repo_path": "example/lapack/dgesvd.c", "max_issues_count": 514, "max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "t-sakashita/rokko", "max_issues_repo_path": "example/lapack/dgesvd.c", "max_line_length": 82, "max_stars_count": 16, "max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "t-sakashita/rokko", "max_stars_repo_path": "example/lapack/dgesvd.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z", "num_tokens": 1214, "size": 3437 }
/* ============================================================ * * cosebi_demo.c * * Martin Kilbinger, Liping Fu 2012. * * 2013. Tomography. * * Reference: * * Schneider, Eifler, Krause 2010 * * ============================================================ */ #include <stdio.h> #include <stdlib.h> #include "errorlist.h" #include "io.h" #include "maths.h" #include "cosmo.h" #include "lensing.h" #include "nofz.h" #include "decomp_eb.h" #include <getopt.h> #include <gsl/gsl_sf_gamma.h> void write_tpmlog(int n, double thmin, double thmax, const double *c, error **err) { FILE *F; double z, theta, tp, tm, dth; char name[128]; sprintf(name, "T_%d_%.3f_%.3f.dat", n, thmin/arcmin, thmax/arcmin); F = fopen_err(name, "w", err); forwardError(*err, __LINE__,); fprintf(F, "# z=log(thmax/thmin) theta[arcmin] T_+^log T_-^log, (n, thmin, thmax = %d, %g, %g)\n", n, thmin/arcmin, thmax/arcmin); dth = 1.01; for (theta=thmin; theta<=thmax; theta*=dth) { z = log(theta / thmin); tp = Tplog_c(z, c, n, err); forwardError(*err, __LINE__,); tm = Tmlog(z, c, n, err); forwardError(*err, __LINE__,); fprintf(F, "%f %g % g % g\n", z, theta/arcmin, tp, tm); } fclose(F); } void write_xi_pm_EB(int N, double thmin, double thmax, const double *c_cosebi, const double *E_cos, const double *B_cos, error **err) { double xi_pm_EB[4], theta, fth; const char name[128] = "xi_pm_EB.dat"; int n; FILE *F; F = fopen_err(name, "w", err); forwardError(*err, __LINE__,); fprintf(F, "# theta[arcmin] E+ E- B+ B-\n"); fth = 1.1; for (theta=thmin; theta<=thmax; theta *= fth) { xipmEB(theta, thmin, thmax, c_cosebi, E_cos, B_cos, N, xi_pm_EB, err); forwardError(*err, __LINE__,); fprintf(F, "%12.3g ", theta/arcmin); for (n=0; n<4; n++) fprintf(F, " % g", xi_pm_EB[n]); fprintf(F, "\n"); } fclose(F); } double E_cosebi_data(const double *xip, const double *xim, const double *theta, int Nxi, int n, double Psimin, double Psimax, const double *c_cosebi, double *B_cosebi, error **err) { double z, delta_theta, rp, rm, summand; int i; testErrorRetVA(Psimin < theta[0], mr_range, "COSEBI theta_min = %g' is smaller than xi theta_min = %g'", *err, __LINE__, -1.0, Psimin / arcmin, theta[0] / arcmin); testErrorRetVA(Psimax > theta[Nxi-1], mr_range, "COSEBI theta_max = %g' is larger than xi theta_max = %g'", *err, __LINE__, -1.0, Psimax / arcmin, theta[Nxi-1] / arcmin); rp = rm = 0.0; for (i=0; i<Nxi; i++) { if (theta[i] < Psimin) continue; if (theta[i] > Psimax) break; if (i > 0) { delta_theta = theta[i] - theta[i-1]; } else { delta_theta = theta[1] - theta[0]; } z = log(theta[i] / Psimin); summand = xip[i]; summand *= theta[i] * delta_theta; summand *= Tplog_c(z, c_cosebi, n, err); forwardError(*err, __LINE__, -1.0); rp += summand; summand = xim[i]; summand *= theta[i] * delta_theta; summand *= Tmlog(z, c_cosebi, n, err); forwardError(*err, __LINE__, -1.0); rm += summand; //printf("%g %g %g %g\n", theta[i]/arcmin, z, xip[i], xim[i]); } if (B_cosebi != NULL) { *B_cosebi = 0.5 * (rp - rm); } return 0.5 * (rp + rm); } void usage(int ex) { fprintf(stderr, "Calculates the COSEBIs from Schneider, Eifler, Krause 2010\n"); fprintf(stderr, "Usage: coseb_demo [OPTIONS]\n"); fprintf(stderr, "OPTIONS\n"); fprintf(stderr, " -N N Maximum COSEBIs mode N\n"); fprintf(stderr, " -m THMIN Minimum COSEBIs scale THMIN (in arcmin; default 1)\n"); fprintf(stderr, " -M THMAX Maximum COSEBIs scale THMAX (in arcmin; default 400)\n"); fprintf(stderr, " -d XI Data file XI (cosmo_pmc input ['xipm'] format; default none)\n"); fprintf(stderr, " -T Write filter functions to files 'T_n_thmin_thmax.dat'\n"); fprintf(stderr, " -X Write EB correlation functions to files 'xEB_n_thmin_thmax.dat'\n"); fprintf(stderr, " -P PATH Path for coefficient files ('cosebi_tplog_rN_N_thmin_thmax';\n"); fprintf(stderr, " default $COSMOPMC/par_files/COSEBIs)\n"); fprintf(stderr, " -h This message\n"); if (ex >= 0) exit(ex); } int main(int argc, char* argv[]) { error *myerr = NULL, **err; double *E_cos, *B_cos; double Psimin, Psimax; int c, N, n, Nxi, write_T, write_X, i_bin, j_bin, Nzbin; cosmo_lens *model; char *xi_name, *path, *strp; FILE *F; datcov *dc; double *xip, *xim, *theta, *theta2, *c_cosebi; fprintf(stderr, "# cosebi_demo (M. Kilbinger, L. Fu, 2012)\n"); err = &myerr; /* Command line arguments */ Psimin = 0.174; Psimax = 200.0; N = 10; xi_name = NULL; write_T = write_X = 0; path = NULL; while (1) { static struct option long_options[] = { {"", required_argument, 0, 'N'}, {"", required_argument, 0, 'd'}, {"", required_argument, 0, 'P'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long(argc, argv, "N:d:m:M:TXP:h", long_options, &option_index); switch (c) { case 'N' : N = atoi(optarg); break; case 'd' : xi_name = optarg; break; case 'P' : path = optarg; break; case 'm' : Psimin = atof(optarg); break; case 'M' : Psimax = atof(optarg); break; case 'T' : write_T = 1; break; case 'X' : write_X = 1; break; case 'h' : usage(0); case -1 : goto end_arg; default : usage(1); } } end_arg: if (N<0 || N>NMAX_COSEBI) { fprintf(stderr, "N=%d out of range [0; %d]", N, NMAX_COSEBI); exit(4); } if (path == NULL) { strp = getenv("COSMOPMC"); if (strp == NULL) { strp = "."; } path = malloc_err(sizeof(char) * 1024, err); quitOnError(*err, __LINE__, stderr); sprintf(path, "%s/par_files/COSEBIs", strp); } E_cos = malloc_err(sizeof(double) * (N+1), err); quitOnError(*err, __LINE__, stderr); B_cos = malloc_err(sizeof(double) * (N+1), err); quitOnError(*err, __LINE__, stderr); if (xi_name == NULL) { /* COSEBIs from theoretical model */ F = fopen_err("cosmo_lens.par", "r", err); quitOnError(*err, __LINE__, stderr); read_cosmological_parameters_lens(&model, F, err); quitOnError(*err, __LINE__, stderr); fclose(F); Nzbin = model->redshift->Nzbin; dump_param(model->cosmo, stdout); fprintf(stdout, "# n E_n^{ij} B_n^{ij}\n# n"); for (i_bin=0; i_bin<Nzbin; i_bin++) { for (j_bin=i_bin; j_bin<Nzbin; j_bin++) { if (model->tomo==tomo_auto_only && i_bin!=j_bin) continue; if (model->tomo==tomo_cross_only && i_bin==j_bin) continue; fprintf(stdout, " E_n^{%d%d} B_n^{%d%d}", i_bin, j_bin, i_bin, j_bin); } } fprintf(stdout, "\n"); for (n=1; n<=N; n++) { fprintf(stdout, "%3d", n); for (i_bin=0; i_bin<Nzbin; i_bin++) { for (j_bin=i_bin; j_bin<Nzbin; j_bin++) { if (model->tomo==tomo_auto_only && i_bin!=j_bin) continue; if (model->tomo==tomo_cross_only && i_bin==j_bin) continue; E_cos[n] = E_cosebi(model, n, Psimin*arcmin, Psimax*arcmin, i_bin, j_bin, path, B_cos+n, err); quitOnError(*err, __LINE__, stderr); fprintf(stdout, " % 15.6g % 15.6g", E_cos[n], B_cos[n]); } } fprintf(stdout, "\n"); } c_cosebi = model->c_cosebi; } else { /* COSEBIs from data */ c_cosebi = read_zeros_norm_cosebi_auto_check(Psimin*arcmin, Psimax*arcmin, path, err); quitOnError(*err, __LINE__, stderr); dc = malloc_err(sizeof(datcov), err); quitOnError(*err, __LINE__, stderr); dc->format = angle_center; /* Reading xi file */ read_data_tomo(dc, xi_name, 0, second_order, err); quitOnError(*err, __LINE__, stderr); Nzbin = dc->Nzbin; dc->type = xipm; /* Header */ fprintf(stdout, "# n E_n^{ij} B_n^{ij}\n# n "); for (i_bin=0; i_bin<Nzbin; i_bin++) { for (j_bin=i_bin; j_bin<Nzbin; j_bin++) { fprintf(stdout, "E_n^{%d%d} B_n^{%d%d} ", i_bin, j_bin, i_bin, j_bin); } } fprintf(stdout, "\n"); for (n=1; n<=N; n++) { fprintf(stdout, "%3d", n); for (i_bin=0; i_bin<Nzbin; i_bin++) { for (j_bin=i_bin; j_bin<Nzbin; j_bin++) { datcov2xipm(dc, i_bin, j_bin, &xip, &xim, &theta, &theta2, &Nxi, err); quitOnError(*err, __LINE__, stderr); E_cos[n] = E_cosebi_data(xip, xim, theta, Nxi, n, Psimin*arcmin, Psimax*arcmin, c_cosebi, B_cos+n, err); quitOnError(*err, __LINE__, stderr); fprintf(stdout, " % .9g % .9g", E_cos[n], B_cos[n]); } } fprintf(stdout, "\n"); free(xip); free(xim); free(theta); } del_data_cov(&dc); } if (write_T) { /* Write filter functions to file */ for (n=1; n<=N; n++) { write_tpmlog(n, Psimin*arcmin, Psimax*arcmin, c_cosebi, err); quitOnError(*err, __LINE__, stderr); } } if (write_X) { /* Calculate xipmEB according to SEK 10 eq (40) */ write_xi_pm_EB(N, Psimin*arcmin, Psimax*arcmin, c_cosebi, E_cos, B_cos, err); } free(E_cos); free(B_cos); return 0; }
{ "alphanum_fraction": 0.551868086, "avg_line_length": 27.2991452991, "ext": "c", "hexsha": "a46651291ff79dfb2efb5cadca1096a24bda9570", "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": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "danielgruen/ccv", "max_forks_repo_path": "src/nicaea_2.5/Demo/cosebi_demo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "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": "danielgruen/ccv", "max_issues_repo_path": "src/nicaea_2.5/Demo/cosebi_demo.c", "max_line_length": 112, "max_stars_count": 2, "max_stars_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "danielgruen/ccv", "max_stars_repo_path": "src/nicaea_2.5/Demo/cosebi_demo.c", "max_stars_repo_stars_event_max_datetime": "2021-01-08T03:19:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-08-11T20:38:17.000Z", "num_tokens": 3168, "size": 9582 }
/* Copyright 2014-2018 The PySCF Developers. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include<stdio.h> #include<stdlib.h> #include <omp.h> //#include <cblas.h> /* ! ! !Compute Y += A*X for CSR matrix A and dense vectors X,Y ! From scipy/sparse/sparsetools/csr.h ! ! ! Input Arguments: ! I n_row - number of rows in A ! I n_col - number of columns in A ! I Ap[n_row+1] - row pointer ! I Aj[nnz(A)] - column indices ! T Ax[nnz(A)] - nonzeros ! T Xx[n_col] - input vector ! ! Output Arguments: ! T Yx[n_row] - output vector ! ! Note: ! Output array Yx must be preallocated ! ! Complexity: Linear. Specifically O(nnz(A) + n_row) */ void scsr_matvec(int nrow, int ncol, int nnz, int *Ap, int *Aj, float *Ax, float *Xx, float *Yx) { int i, jj; float sum = 0.0; # pragma omp parallel \ shared (nrow, Yx, Ap, Ax, Xx, Aj) \ private (i, jj, sum) { #pragma omp for for(i = 0; i < nrow; i++){ sum = Yx[i]; for(jj = Ap[i]; jj < Ap[i+1]; jj++){ sum += Ax[jj] * Xx[Aj[jj]]; } Yx[i] = sum; } } } void dcsr_matvec(int nrow, int ncol, int nnz, int *Ap, int *Aj, double *Ax, double *Xx, double *Yx) { int i, jj; double sum = 0.0; # pragma omp parallel \ shared (nrow, Yx, Ap, Ax, Xx, Aj) \ private (i, jj, sum) { #pragma omp for for(i = 0; i < nrow; i++){ sum = Yx[i]; for(jj = Ap[i]; jj < Ap[i+1]; jj++){ sum += Ax[jj] * Xx[Aj[jj]]; } Yx[i] = sum; } } } /* * Compute Y += A*X for CSC matrix A and dense vectors X,Y * From scipy/sparse/sparsetools/csc.h * * * Input Arguments: * I n_row - number of rows in A * I n_col - number of columns in A * I Ap[n_row+1] - column pointer * I Ai[nnz(A)] - row indices * T Ax[n_col] - nonzeros * T Xx[n_col] - input vector * * Output Arguments: * T Yx[n_row] - output vector * * Note: * Output array Yx must be preallocated * * Complexity: Linear. Specifically O(nnz(A) + n_col) * */ void scsc_matvec(int n_row, int n_col, int nnz, int *Ap, int *Ai, float *Ax, float *Xx, float *Yx) { int col_start, col_end, j, ii, i; for( j = 0; j < n_col; j++){ col_start = Ap[j]; col_end = Ap[j+1]; for( ii = col_start; ii < col_end; ii++){ i = Ai[ii]; Yx[i] += Ax[ii] * Xx[j]; } } } void dcsc_matvec(int n_row, int n_col, int nnz, int *Ap, int *Ai, double *Ax, double *Xx, double *Yx) { int col_start, col_end, j, ii, i; for( j = 0; j < n_col; j++){ col_start = Ap[j]; col_end = Ap[j+1]; for( ii = col_start; ii < col_end; ii++){ i = Ai[ii]; Yx[i] += Ax[ii] * Xx[j]; } } } /* * Compute Y += A*X for CSC matrix A and dense block vectors X,Y * From scipy/sparse/sparsetools/csc.h * * * Input Arguments: * I n_row - number of rows in A * I n_col - number of columns in A * I n_vecs - number of column vectors in X and Y * I Ap[n_row+1] - row pointer * I Aj[nnz(A)] - column indices * T Ax[nnz(A)] - nonzeros * T Xx[n_col,n_vecs] - input vector * * Output Arguments: * T Yx[n_row,n_vecs] - output vector * * Note: * Output array Yx must be preallocated * */ void scsc_matvecs(int n_row, int n_col, int n_vecs, int *Ap, int *Ai, float *Ax, float *Xx, float *Yx) { int i, j, ii; printf("dcsc_matvecs not working in m_sparsetools.c\n"); exit(1); /* # pragma omp parallel \ shared (n_row, n_col, n_vecs, Ap, Ai, Ax, Xx, Yx) \ private (i, ii, j) { #pragma omp for for( j = 0; j < n_col; j++){ for( ii = Ap[j]; ii < Ap[j+1]; ii++){ i = Ai[ii]; //axpy(n_vecs, Ax[ii], Xx + (int)n_vecs * j, Yx + (int)n_vecs * i); cblas_saxpy (n_vecs, Ax[ii], &Xx[n_vecs*j], 1, &Yx[n_vecs*i], 1); } } //} */ } void dcsc_matvecs(int n_row, int n_col, int n_vecs, int *Ap, int *Ai, double *Ax, double *Xx, double *Yx) { int i, j, ii; printf("dcsc_matvecs not working in m_sparsetools.c\n"); exit(1); /* # pragma omp parallel \ shared (n_row, n_col, n_vecs, Ap, Ai, Ax, Xx, Yx) \ private (i, ii, j) { #pragma omp for for( j = 0; j < n_col; j++){ for( ii = Ap[j]; ii < Ap[j+1]; ii++){ i = Ai[ii]; //axpy(n_vecs, Ax[ii], Xx + (int)n_vecs * j, Yx + (int)n_vecs * i); cblas_daxpy (n_vecs, Ax[ii], &Xx[n_vecs*j], 1, &Yx[n_vecs*i], 1); } } //} */ }
{ "alphanum_fraction": 0.5469688166, "avg_line_length": 24.4691943128, "ext": "c", "hexsha": "d4d5ea08dce9d4e40718f632ed61a962ed5893f6", "lang": "C", "max_forks_count": 273, "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:25:28.000Z", "max_forks_repo_forks_event_min_datetime": "2018-11-26T10:10:24.000Z", "max_forks_repo_head_hexsha": "cdc56e168cb15f47e8cdc791a92d689fa9b655af", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "robert-anderson/pyscf", "max_forks_repo_path": "pyscf/lib/sparsetools/m_sparsetools.c", "max_issues_count": 710, "max_issues_repo_head_hexsha": "cdc56e168cb15f47e8cdc791a92d689fa9b655af", "max_issues_repo_issues_event_max_datetime": "2022-03-30T03:53:12.000Z", "max_issues_repo_issues_event_min_datetime": "2018-11-26T22:04:52.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "robert-anderson/pyscf", "max_issues_repo_path": "pyscf/lib/sparsetools/m_sparsetools.c", "max_line_length": 76, "max_stars_count": 501, "max_stars_repo_head_hexsha": "cdc56e168cb15f47e8cdc791a92d689fa9b655af", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "robert-anderson/pyscf", "max_stars_repo_path": "pyscf/lib/sparsetools/m_sparsetools.c", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:53:18.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T23:48:17.000Z", "num_tokens": 1757, "size": 5163 }
#ifndef __e23673_LIBRARIES_H #define __e23673_LIBRARIES_H #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <limits.h> /* GNU Scientific library: */ #include <gsl/gsl_rng.h> #include "parsing.h" #include "dev_random.h" #include "mersenne_twister.h" #include "random_numbers.h" #endif
{ "alphanum_fraction": 0.7400611621, "avg_line_length": 15.5714285714, "ext": "h", "hexsha": "c026eb7272ab949c0823ffa6069026f8ebcae1df", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-06-22T14:27:12.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-22T18:51:14.000Z", "max_forks_repo_head_hexsha": "7174845b0614b6a20e48834d5a76579cfbf80bd6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gmagannaDevelop/TousAntiCovid", "max_forks_repo_path": "reference/26_Mersenne_Twister/src/libraries.h", "max_issues_count": 5, "max_issues_repo_head_hexsha": "7174845b0614b6a20e48834d5a76579cfbf80bd6", "max_issues_repo_issues_event_max_datetime": "2021-01-17T11:51:06.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-25T16:51:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gmagannaDevelop/TousAntiCovid", "max_issues_repo_path": "reference/26_Mersenne_Twister/src/libraries.h", "max_line_length": 29, "max_stars_count": 4, "max_stars_repo_head_hexsha": "7174845b0614b6a20e48834d5a76579cfbf80bd6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gmagannaDevelop/TousAntiCovid", "max_stars_repo_path": "reference/26_Mersenne_Twister/src/libraries.h", "max_stars_repo_stars_event_max_datetime": "2021-11-09T23:00:30.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-09T00:10:32.000Z", "num_tokens": 88, "size": 327 }
/* gsl_histogram_calloc_range.c * Copyright (C) 2000 Simone Piccardi * * This library 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 library; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /*************************************************************** * * File gsl_histogram_calloc_range.c: * Routine to create a variable binning histogram providing * an input range vector. Need GSL library and header. * Do range check and allocate the histogram data. * * Author: S. Piccardi * Jan. 2000 * ***************************************************************/ #include <config.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram.h> gsl_histogram * gsl_histogram_calloc_range (size_t n, double *range) { size_t i; gsl_histogram *h; /* check arguments */ if (n == 0) { GSL_ERROR_VAL ("histogram length n must be positive integer", GSL_EDOM, 0); } /* check ranges */ for (i = 0; i < n; i++) { if (range[i] >= range[i + 1]) { GSL_ERROR_VAL ("histogram bin extremes must be " "in increasing order", GSL_EDOM, 0); } } /* Allocate histogram */ h = (gsl_histogram *) malloc (sizeof (gsl_histogram)); if (h == 0) { GSL_ERROR_VAL ("failed to allocate space for histogram struct", GSL_ENOMEM, 0); } h->range = (double *) malloc ((n + 1) * sizeof (double)); if (h->range == 0) { /* exception in constructor, avoid memory leak */ free (h); GSL_ERROR_VAL ("failed to allocate space for histogram ranges", GSL_ENOMEM, 0); } h->bin = (double *) malloc (n * sizeof (double)); if (h->bin == 0) { /* exception in constructor, avoid memory leak */ free (h->range); free (h); GSL_ERROR_VAL ("failed to allocate space for histogram bins", GSL_ENOMEM, 0); } /* initialize ranges */ for (i = 0; i <= n; i++) { h->range[i] = range[i]; } /* clear contents */ for (i = 0; i < n; i++) { h->bin[i] = 0; } h->n = n; return h; }
{ "alphanum_fraction": 0.5750269881, "avg_line_length": 25.7314814815, "ext": "c", "hexsha": "6549b73d35d742f98fea7c56b44417b428e7eb90", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/histogram/calloc_range.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/histogram/calloc_range.c", "max_line_length": 74, "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/histogram/calloc_range.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": 691, "size": 2779 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> void read_matrix(int** index, int** matrix, double scaling, int N_kw, char* input_fileName) { FILE *fp = fopen(input_fileName, "r"); fscanf(fp, "%*[^\n]\n"); for (int ii = 0; ii < N_kw; ii++) fscanf(fp, "%d,", &((*index)[ii])); fscanf(fp, "%*[^\n]\n"); int tmp; for (int ii = 0; ii < N_kw; ii++) { for (int jj = 0; jj < N_kw; jj++) { fscanf(fp, "%d,", &tmp); (*matrix)[ii*N_kw + jj] = (int) (tmp * scaling); } fscanf(fp, "%*[^\n]\n"); } fclose(fp); } void pad_matrix(int** matrix_padded, int** matrix, double lambda, int N_kw, int N_doc) { // Initialising RNG const gsl_rng_type * T; gsl_rng *r1, *r2; gsl_rng_env_setup(); r1 = gsl_rng_alloc(gsl_rng_default); r2 = gsl_rng_alloc (gsl_rng_taus); // perform padding int ii, jj; int max_resp_len = 0; for (ii = 0; ii < N_kw; ii++) if ((*matrix)[ii*N_kw + ii] > max_resp_len) max_resp_len = (*matrix)[ii*N_kw + ii]; #pragma omp parallel for private(ii) for (ii = 0; ii < N_kw; ii++) (*matrix_padded)[ii*N_kw + ii] = (int) (lambda * (max_resp_len)) + gsl_rng_uniform_int(r2, max_resp_len+1); #pragma omp parallel for private(ii, jj) for (ii = 0; ii < N_kw; ii++) { for (jj = 0; jj < N_kw; jj++) { if (ii > jj) { int n1, n2, n3; n3 = 0; if ((*matrix_padded)[ii*N_kw + ii] > (*matrix)[ii*N_kw + ii]) { n1 = (*matrix)[ii*N_kw + jj]; n3 += gsl_ran_hypergeometric(r1, (*matrix_padded)[ii*N_kw + ii] - (*matrix)[ii*N_kw + ii], N_doc, (*matrix_padded)[jj*N_kw + jj]); } else n1 = gsl_ran_hypergeometric(r1, (*matrix)[ii*N_kw + jj], (*matrix)[ii*N_kw + ii] - (*matrix)[ii*N_kw + jj], (*matrix_padded)[ii*N_kw + ii] - (*matrix)[ii*N_kw + jj]); if ((*matrix_padded)[jj*N_kw + jj] > (*matrix)[jj*N_kw + jj]) { n2 = n1; n3 += gsl_ran_hypergeometric(r1, (*matrix_padded)[jj*N_kw + jj] - (*matrix)[jj*N_kw + jj], N_doc, (*matrix_padded)[ii*N_kw + ii] - (*matrix)[ii*N_kw + jj]); } else n2 = gsl_ran_hypergeometric(r1, n1, (*matrix)[jj*N_kw + jj] - n1, (*matrix_padded)[jj*N_kw + jj]); (*matrix_padded)[ii*N_kw + jj] = n2 + n3; (*matrix_padded)[jj*N_kw + ii] = n2 + n3; } } } gsl_rng_free(r1); gsl_rng_free(r2); } void observe_matrix(gsl_matrix* matrix_obs, int** matrix_padded, int N_kw) { // perform observed count generation for (int ii = 0; ii < N_kw; ii++) for (int jj = 0; jj < N_kw; jj++) gsl_matrix_set(matrix_obs, ii, jj, (double) ((*matrix_padded)[ii*N_kw + jj])); } void permutation_generation(int* idx1, int* idx2, int** permutation_tmp, int** permutation, int** permutation_inv, int N_kw, int N_obs) { int count = 0; *idx1 = rand() % N_obs; *idx2 = -1; int idx_old = (*permutation)[*idx1]; int idx_new = rand() % N_kw; (*permutation_tmp)[*idx1] = idx_new; if ((*permutation_inv)[idx_new] >= 0) { *idx2 = (*permutation_inv)[idx_new]; (*permutation_tmp)[*idx2] = idx_old; } }
{ "alphanum_fraction": 0.5182623132, "avg_line_length": 31.1551724138, "ext": "c", "hexsha": "c51cc4f72e45f9a04a4ff0b9220f83e46857a247", "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": "39602b0912b21afc45e73008e598f4377ba237eb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_forks_repo_path": "PRT-EMM/util.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "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": "RethinkingSSE/Attacks-on-SSE", "max_issues_repo_path": "PRT-EMM/util.c", "max_line_length": 186, "max_stars_count": null, "max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE", "max_stars_repo_path": "PRT-EMM/util.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1104, "size": 3614 }
// @file ker2col_conv.c // // \date Created on: Sep 24, 2017 // \author Gopalakrishna Hegde // // Description: // // // #include <stdbool.h> #include <cblas.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include "common_types.h" #include "data_reshape.h" #include "utils.h" #include "conv_layers.h" bool Kn2ColConvLayer(const float *in_data, const float *filters, const float *bias, TensorDim in_dim, TensorDim filt_dim, int stride, int pad, int group, float *output) { // Currently we have limited support. assert(group == 1); assert((pad == 0) || (pad == filt_dim.w / 2)); assert(in_dim.n == 1); assert(filt_dim.h == filt_dim.w); assert(stride == 1); // Output dimensions. TensorDim out_dim; out_dim.w = (in_dim.w + (pad + pad) - filt_dim.w) / stride + 1; out_dim.h = (in_dim.h + (pad + pad) - filt_dim.h) / stride + 1; out_dim.c = filt_dim.n; out_dim.n = in_dim.n; // Reshape filters in CHWN (ker_size x ker_size x no_in_ch x no_out_ch) format float *kkcm_filters = malloc(filt_dim.n * filt_dim.c * filt_dim.h * filt_dim.w * sizeof(float)); NCHW2HWCN(filters, filt_dim.n, filt_dim.c, filt_dim.h, filt_dim.w, kkcm_filters); // Just for convenience int H = in_dim.h; int W = in_dim.w; float alpha = 1.0; float beta = 0.0; // We need separate buffer because GEMM output will have width = H*W even // if there is no padding (pad = 0). float *gemm_output = malloc(out_dim.c * H * W * sizeof(float)); float *nchw_gemm_output = malloc(out_dim.c * H * W * sizeof(float)); // Prefill output buffer with bias if present else set to zero. if (bias) { for (int m = 0; m < out_dim.c; ++m) { for (int a = 0; a < out_dim.h * out_dim.w; ++a) { output[m * out_dim.h * out_dim.w + a] = bias[m]; } // For batch size > 1 for (int b = 1; b < out_dim.n; ++b) { memcpy(output + b * out_dim.c * out_dim.h * out_dim.w, output, out_dim.c * out_dim.h * out_dim.w * sizeof(float)); } } } else { memset(output, 0, out_dim.n * out_dim.c * out_dim.h * out_dim.w * sizeof(float)); } for (int kr = 0; kr < filt_dim.h; kr++) { int row_shift = pad - kr; for (int kc = 0; kc < filt_dim.w; kc++) { int group_no = kr * filt_dim.w + kc; int col_shift = pad - kc; // Matrix dimensions - A -> mxk B -> kxn C --> mxn int m = in_dim.h * in_dim.w; int k = filt_dim.c; int n = filt_dim.n; // output is in H x W x C format. cblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, m, n, k, alpha, in_data, m, kkcm_filters + group_no * filt_dim.c * filt_dim.n, n, beta, gemm_output, n); // convert to CxHxW format. // FIXME: this will be slow. Need to find other ways :( NHWC2NCHW(gemm_output, 1, filt_dim.n, H, W, nchw_gemm_output); for (int omap = 0; omap < filt_dim.n; omap++) { MatrixShiftAdd(output + omap * out_dim.h * out_dim.w, out_dim.h, out_dim.w, nchw_gemm_output + omap * H * W, H, W, row_shift, col_shift); } } } free(kkcm_filters); free(gemm_output); free(nchw_gemm_output); return true; }
{ "alphanum_fraction": 0.5712596097, "avg_line_length": 32.2095238095, "ext": "c", "hexsha": "adee7eb66f1920c78383bab2b45d527be66d9b89", "lang": "C", "max_forks_count": 23, "max_forks_repo_forks_event_max_datetime": "2021-12-21T14:16:14.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-24T05:17:21.000Z", "max_forks_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "chayitw/convolution-flavors", "max_forks_repo_path": "src/kn2col_conv.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_issues_repo_issues_event_max_datetime": "2021-10-16T02:49:23.000Z", "max_issues_repo_issues_event_min_datetime": "2021-10-16T02:49:23.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "chayitw/convolution-flavors", "max_issues_repo_path": "src/kn2col_conv.c", "max_line_length": 80, "max_stars_count": 54, "max_stars_repo_head_hexsha": "c5f612d35888e224aa610408a7fc9f08f232147c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gplhegde/convolution-flavors", "max_stars_repo_path": "src/kn2col_conv.c", "max_stars_repo_stars_event_max_datetime": "2022-01-12T06:38:50.000Z", "max_stars_repo_stars_event_min_datetime": "2017-10-03T18:10:24.000Z", "num_tokens": 1010, "size": 3382 }
#ifndef LIC_OPCODES #define LIC_OPCODES #include <gsl/gsl> namespace lic { constexpr uint8_t MethodHeaderFormatMask = 0x3; enum class HeaderFormat : uint8_t { Tiny = 0x2, Fat = 0x3 }; enum class Opcode : uint8_t { Nop = 0x00, Break = 0x01, Ldarg_0 = 0x02, Ldarg_1 = 0x03, Ldarg_2 = 0x04, Ldarg_3 = 0x05, Ldloc_0 = 0x06, Ldloc_1 = 0x07, Ldloc_2 = 0x08, Ldloc_3 = 0x09, Stloc_0 = 0x0a, Stloc_1 = 0x0b, Stloc_2 = 0x0c, Stloc_3 = 0x0d, Ldarg_S = 0x0e, Ldarga_S = 0x0f, Starg_S = 0x10, Ldloc_S = 0x11, Ldloca_S = 0x12, Stloc_S = 0x13, Ldnull = 0x14, Ldc_I4_M1 = 0x15, Ldc_I4_0 = 0x16, Ldc_I4_1 = 0x17, Ldc_I4_2 = 0x18, Ldc_I4_3 = 0x19, Ldc_I4_4 = 0x1a, Ldc_I4_5 = 0x1b, Ldc_I4_6 = 0x1c, Ldc_I4_7 = 0x1d, Ldc_I4_8 = 0x1e, Ldc_I4_S = 0x1f, Ldc_I4 = 0x20, Ldc_I8 = 0x21, Ldc_R4 = 0x22, Ldc_R8 = 0x23, Dup = 0x25, Pop = 0x26, Jmp = 0x27, Call = 0x28, Calli = 0x29, Ret = 0x2a, Br_S = 0x2b, Brfalse_S = 0x2c, Brtrue_S = 0x2d, Beq_S = 0x2e, Bge_S = 0x2f, Bgt_S = 0x30, Ble_S = 0x31, Blt_S = 0x32, Bne_Un_S = 0x33, Bge_Un_S = 0x34, Bgt_Un_S = 0x35, Ble_Un_S = 0x36, Blt_Un_S = 0x37, Br = 0x38, Brfalse = 0x39, Brtrue = 0x3a, Beq = 0x3b, Bge = 0x3c, Bgt = 0x3d, Ble = 0x3e, Blt = 0x3f, Bne_Un = 0x40, Bge_Un = 0x41, Bgt_Un = 0x42, Ble_Un = 0x43, Blt_Un = 0x44, Switch = 0x45, Ldind_I1 = 0x46, Ldind_U1 = 0x47, Ldind_I2 = 0x48, Ldind_U2 = 0x49, Ldind_I4 = 0x4a, Ldind_U4 = 0x4b, Ldind_I8 = 0x4c, Ldind_I = 0x4d, Ldind_R4 = 0x4e, Ldind_R8 = 0x4f, Ldind_Ref = 0x50, Stind_Ref = 0x51, Stind_I1 = 0x52, Stind_I2 = 0x53, Stind_I4 = 0x54, Stind_I8 = 0x55, Stind_R4 = 0x56, Stind_R8 = 0x57, Add = 0x58, Sub = 0x59, Mul = 0x5a, Div = 0x5b, Div_Un = 0x5c, Rem = 0x5d, Rem_Un = 0x5e, And = 0x5f, Or = 0x60, Xor = 0x61, Shl = 0x62, Shr = 0x63, Shr_Un = 0x64, Neg = 0x65, Not = 0x66, Conv_I1 = 0x67, Conv_I2 = 0x68, Conv_I4 = 0x69, Conv_I8 = 0x6a, Conv_R4 = 0x6b, Conv_R8 = 0x6c, Conv_U4 = 0x6d, Conv_U8 = 0x6e, Callvirt = 0x6f, Cpobj = 0x70, Ldobj = 0x71, Ldstr = 0x72, Newobj = 0x73, Castclass = 0x74, Isinst = 0x75, Conv_R_Un = 0x76, Unbox = 0x79, Throw = 0x7a, Ldfld = 0x7b, Ldflda = 0x7c, Stfld = 0x7d, Ldsfld = 0x7e, Ldsflda = 0x7f, Stsfld = 0x80, Stobj = 0x81, Conv_Ovf_I1_Un = 0x82, Conv_Ovf_I2_Un = 0x83, Conv_Ovf_I4_Un = 0x84, Conv_Ovf_I8_Un = 0x85, Conv_Ovf_U1_Un = 0x86, Conv_Ovf_U2_Un = 0x87, Conv_Ovf_U4_Un = 0x88, Conv_Ovf_U8_Un = 0x89, Conv_Ovf_I_Un = 0x8a, Conv_Ovf_U_Un = 0x8b, Box = 0x8c, Newarr = 0x8d, Ldlen = 0x8e, Ldelema = 0x8f, Ldelem_I1 = 0x90, Ldelem_U1 = 0x91, Ldelem_I2 = 0x92, Ldelem_U2 = 0x93, Ldelem_I4 = 0x94, Ldelem_U4 = 0x95, Ldelem_I8 = 0x96, Ldelem_I = 0x97, Ldelem_R4 = 0x98, Ldelem_R8 = 0x99, Ldelem_Ref = 0x9a, Stelem_I = 0x9b, Stelem_I1 = 0x9c, Stelem_I2 = 0x9d, Stelem_I4 = 0x9e, Stelem_I8 = 0x9f, Stelem_R4 = 0xa0, Stelem_R8 = 0xa1, Stelem_Ref = 0xa2, Conv_Ovf_I1 = 0xb3, Conv_Ovf_U1 = 0xb4, Conv_Ovf_I2 = 0xb5, Conv_Ovf_U2 = 0xb6, Conv_Ovf_I4 = 0xb7, Conv_Ovf_U4 = 0xb8, Conv_Ovf_I8 = 0xb9, Conv_Ovf_U8 = 0xba, Refanyval = 0xc2, Ckfinite = 0xc3, Mkrefany = 0xc6, Ldtoken = 0xd0, Conv_U2 = 0xd1, Conv_U1 = 0xd2, Conv_I = 0xd3, Conv_Ovf_I = 0xd4, Conv_Ovf_U = 0xd5, Add_Ovf = 0xd6, Add_Ovf_Un = 0xd7, Mul_Ovf = 0xd8, Mul_Ovf_Un = 0xd9, Sub_Ovf = 0xda, Sub_Ovf_Un = 0xdb, Endfinally = 0xdc, Leave = 0xdd, Leave_S = 0xde, Stind_I = 0xdf, Conv_U = 0xe0, LongOpcodePrefix = 0xfe }; enum class LongOpcodeSuffix: uint8_t { Arglist = 0x00, Ceq = 0x01, Cgt = 0x02, Cgt_Un = 0x03, Clt = 0x04, Clt_Un = 0x05, Ldftn = 0x06, Ldvirtftn = 0x07, Ldarg = 0x09, Ldarga = 0x0a, Starg = 0x0b, Ldloc = 0x0c, Ldloca = 0x0d, Stloc = 0x0e, Localloc = 0x0f, Endfilter = 0x11, Unaligned_ = 0x12, Volatile_ = 0x13, Tail_ = 0x14, Initobj = 0x15, Cpblk = 0x17, Initblk = 0x18, Rethrow = 0x1a, Sizeof = 0x1c, Refanytype = 0x1d, InvalidOpcode = 0xff }; const char* OpcodeName(Opcode first, LongOpcodeSuffix second = LongOpcodeSuffix::InvalidOpcode); } #endif // !LIC_OPCODES
{ "alphanum_fraction": 0.5694092827, "avg_line_length": 19.1902834008, "ext": "h", "hexsha": "272795aedd9cbc449ca0cc315341190a9196ea34", "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": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "roberthusak/lic", "max_forks_repo_path": "src/format/Opcodes.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "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": "roberthusak/lic", "max_issues_repo_path": "src/format/Opcodes.h", "max_line_length": 96, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "roberthusak/lic", "max_stars_repo_path": "src/format/Opcodes.h", "max_stars_repo_stars_event_max_datetime": "2017-05-18T11:44:16.000Z", "max_stars_repo_stars_event_min_datetime": "2017-05-18T11:44:16.000Z", "num_tokens": 2410, "size": 4740 }
#ifndef VISCOUSVORTEXDOMAINSOLVER_H #define VISCOUSVORTEXDOMAINSOLVER_H #include <stdio.h> #include <stdlib.h> #include <common_functions.h> #include <string.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <vector> #include <algorithm> //#include <parallel/algorithm> #include "pstl/execution" #include "pstl/algorithm" #include "tbb/parallel_for_each.h" #include <mutex> #include <omp.h> #include <streamline.h> #include <vortex.h> #include <vortexmotion.h> //ToDo: add resumption of calculations mechanism class ViscousVortexDomainSolver { int NumberOfPanels; int MaxVortexes; int Niterations; double nu; double tau; double rho; double vx_inf; double vy_inf; double *PanelLength; double **PanelNodes, **PanelMids, **PanelNorms, **PanelTaus, **DeployPoints; gsl_matrix *OriginalVortexGenerationMatrix; gsl_matrix *VortexGenerationMatrix; gsl_matrix *VortexGenerationMatrix_Inversed; gsl_vector *VelocityProjections; gsl_vector *NewVorticities; gsl_permutation *Permutation; std::vector <Vortex> Flow; std::vector <VortexMotion> FlowEvolution; std::mutex SyncFlowEvolution; std::vector <Vortex> InBodyVortexes; std::vector <ControlPointOfFlow> StreamLine1; std::vector <ControlPointOfFlow> StreamLine2; void StepInTimeForStreamLines(); void UpdateControlPointsOfStreamLine(std::vector<ControlPointOfFlow> &StreamLine); void MoveSingleControlPoint(ControlPointOfFlow &UpdatingPoint); int isVortexInBody(double x, double y); //ToDo: update to be virtual void DivideProfileToPanels(); void CompletingGeneratingMatrix(); void ComputeAssociatedVortexes(); void AppendAssociatedVortexesToFlow(); void UpdateVotexPositions(); void ComputeVortexMotion(Vortex &Considered); double UpdateEpsilon(Vortex Considered, double InitialEpsilon); int LeakageControl(Vortex Checking); public: ViscousVortexDomainSolver(); ~ViscousVortexDomainSolver(); void Solve(); double xVelocityAt(double x, double y); double yVelocityAt(double x, double y); void Output_ParaView_Field(const char *FileName); void Output_ParaView_Field_with_exclusions(const char *FileName); void Output_ParaView_AllVortexes(const char *FileName); void Output_StreamLines(const char *FileName); }; #endif // VISCOUSVORTEXDOMAINSOLVER_H
{ "alphanum_fraction": 0.736411933, "avg_line_length": 26.311827957, "ext": "h", "hexsha": "e2719eb78e6c1f20c07633a3100b69ecd3092e1c", "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": "9666c4488c611b211337c1a00f181bd75b7daf0c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "VVBondarenko/CFD_MoDV", "max_forks_repo_path": "c_src/MVE_cpp/viscousvortexdomainsolver.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9666c4488c611b211337c1a00f181bd75b7daf0c", "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": "VVBondarenko/CFD_MoDV", "max_issues_repo_path": "c_src/MVE_cpp/viscousvortexdomainsolver.h", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "9666c4488c611b211337c1a00f181bd75b7daf0c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "VVBondarenko/CFD_MoDV", "max_stars_repo_path": "c_src/MVE_cpp/viscousvortexdomainsolver.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 615, "size": 2447 }
/* ieee-utils/fp-darwin86.c * * Copyright (C) 2006 Erik Schnetter * * 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 <gsl/gsl_ieee_utils.h> #include <gsl/gsl_errno.h> /* Here is the dirty part. Set up your 387 through the control word * (cw) register. * * 15-13 12 11-10 9-8 7-6 5 4 3 2 1 0 * | reserved | IC | RC | PC | reserved | PM | UM | OM | ZM | DM | IM * * IM: Invalid operation mask * DM: Denormalized operand mask * ZM: Zero-divide mask * OM: Overflow mask * UM: Underflow mask * PM: Precision (inexact result) mask * * Mask bit is 1 means no interrupt. * * PC: Precision control * 11 - round to extended precision * 10 - round to double precision * 00 - round to single precision * * RC: Rounding control * 00 - rounding to nearest * 01 - rounding down (toward - infinity) * 10 - rounding up (toward + infinity) * 11 - rounding toward zero * * IC: Infinity control * That is for 8087 and 80287 only. * * The hardware default is 0x037f which we use. */ /* masking of interrupts */ #define _FPU_MASK_IM 0x01 #define _FPU_MASK_DM 0x02 #define _FPU_MASK_ZM 0x04 #define _FPU_MASK_OM 0x08 #define _FPU_MASK_UM 0x10 #define _FPU_MASK_PM 0x20 /* precision control */ #define _FPU_EXTENDED 0x300 /* libm requires double extended precision. */ #define _FPU_DOUBLE 0x200 #define _FPU_SINGLE 0x0 /* rounding control */ #define _FPU_RC_NEAREST 0x0 /* RECOMMENDED */ #define _FPU_RC_DOWN 0x400 #define _FPU_RC_UP 0x800 #define _FPU_RC_ZERO 0xC00 #define _FPU_RESERVED 0xF0C0 /* Reserved bits in cw */ /* The fdlibm code requires strict IEEE double precision arithmetic, and no interrupts for exceptions, rounding to nearest. */ #define _FPU_DEFAULT 0x037f /* IEEE: same as above. */ #define _FPU_IEEE 0x037f /* Type of the control word. */ typedef unsigned int fpu_control_t __attribute__ ((__mode__ (__HI__))); /* Macros for accessing the hardware control word. Note that the use of these macros is no sufficient anymore with recent hardware. Some floating point operations are executed in the SSE/SSE2 engines which have their own control and status register. */ #define _FPU_GETCW(cw) __asm__ __volatile__ ("fnstcw %0" : "=m" (*&cw)) #define _FPU_SETCW(cw) __asm__ __volatile__ ("fldcw %0" : : "m" (*&cw)) /* Default control word set at startup. */ extern fpu_control_t __fpu_control; #define _FPU_GETMXCSR(cw_sse) asm volatile ("stmxcsr %0" : "=m" (cw_sse)) #define _FPU_SETMXCSR(cw_sse) asm volatile ("ldmxcsr %0" : : "m" (cw_sse)) int gsl_ieee_set_mode (int precision, int rounding, int exception_mask) { fpu_control_t mode, mode_sse; _FPU_GETCW (mode) ; mode &= _FPU_RESERVED ; switch (precision) { case GSL_IEEE_SINGLE_PRECISION: mode |= _FPU_SINGLE ; break ; case GSL_IEEE_DOUBLE_PRECISION: mode |= _FPU_DOUBLE ; break ; case GSL_IEEE_EXTENDED_PRECISION: mode |= _FPU_EXTENDED ; break ; default: mode |= _FPU_EXTENDED ; } switch (rounding) { case GSL_IEEE_ROUND_TO_NEAREST: mode |= _FPU_RC_NEAREST ; break ; case GSL_IEEE_ROUND_DOWN: mode |= _FPU_RC_DOWN ; break ; case GSL_IEEE_ROUND_UP: mode |= _FPU_RC_UP ; break ; case GSL_IEEE_ROUND_TO_ZERO: mode |= _FPU_RC_ZERO ; break ; default: mode |= _FPU_RC_NEAREST ; } if (exception_mask & GSL_IEEE_MASK_INVALID) mode |= _FPU_MASK_IM ; if (exception_mask & GSL_IEEE_MASK_DENORMALIZED) mode |= _FPU_MASK_DM ; if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO) mode |= _FPU_MASK_ZM ; if (exception_mask & GSL_IEEE_MASK_OVERFLOW) mode |= _FPU_MASK_OM ; if (exception_mask & GSL_IEEE_MASK_UNDERFLOW) mode |= _FPU_MASK_UM ; if (exception_mask & GSL_IEEE_TRAP_INEXACT) { mode &= ~ _FPU_MASK_PM ; } else { mode |= _FPU_MASK_PM ; } _FPU_SETCW (mode) ; _FPU_GETMXCSR (mode_sse) ; mode_sse &= 0xFFFF0000 ; if (exception_mask & GSL_IEEE_MASK_INVALID) mode_sse |= _FPU_MASK_IM << 7 ; if (exception_mask & GSL_IEEE_MASK_DENORMALIZED) mode_sse |= _FPU_MASK_DM << 7 ; if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO) mode_sse |= _FPU_MASK_ZM << 7 ; if (exception_mask & GSL_IEEE_MASK_OVERFLOW) mode_sse |= _FPU_MASK_OM << 7 ; if (exception_mask & GSL_IEEE_MASK_UNDERFLOW) mode_sse |= _FPU_MASK_UM << 7 ; if (exception_mask & GSL_IEEE_TRAP_INEXACT) { mode_sse &= ~ _FPU_MASK_PM << 7 ; } else { mode_sse |= _FPU_MASK_PM << 7 ; } _FPU_SETMXCSR (mode_sse) ; return GSL_SUCCESS ; }
{ "alphanum_fraction": 0.6852782431, "avg_line_length": 26.2097560976, "ext": "c", "hexsha": "ddd4dbec03153fad18aadb2455e505c202125c98", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-darwin86.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-darwin86.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/ieee-utils/fp-darwin86.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 1610, "size": 5373 }
//========================================= // Main driver for the proper time integral //========================================= #include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> #include <builtin_types.h> #include "intT.h" double* transformT(double t, void* p, int* order) //Transforms the integral [0,infinity) to [0,1] //x=(1-t)/t { struct Wparams *params = (struct Wparams *) p; double* tfunc; double x = (1.0-t)/t; int i; tfunc = Tfunc(x,p, order); //loop over groups of worldlines for(i = 0; i < params->ng; i++) { tfunc[i] = (tfunc[i]/t)/t; } return tfunc; } void testval(double *val, int n, double t) //used for outputting debugging information { int i; double avg = 0.0; for(i = 0; i < n; i++) { if(isnan(val[i])) printf("for t=%f val[%d]=nan\n",t, i); avg += val[i]; } avg /= n; printf("mean for Tt=%f, %f\n",t,avg); } void Tintout(double *val, int n, double rho, int fermion) //Produces output about the T-integral { int i; double avg = 0.0, SEM = 0.0; for(i = 0; i < n; i++) { if(isnan(val[i])) printf("for rho=%f val[%d]=nan\n",rho, i); avg += val[i]; } avg /= n; for(i = 0; i < n; i++) { SEM += (val[i]-avg)*(val[i]-avg); } SEM = sqrt(SEM/((double)n*((double)n-1.0))); //rho Leff SEM-Leff if(fermion == 1) printf("Leffvsrho: %e %e %e\n", rho, avg/(4.0*pi), SEM/(4.0*pi)); else printf("Leffvsrho: %e %e %e\n", rho, avg/(-2.0*pi), SEM/(2.0*pi)); } int* shuffleWL(int Nl) //Returns a vector representing a shuffled order of worldlines { gsl_rng * r; int i; // select random number generator r = gsl_rng_alloc (gsl_rng_mt19937); int* order=(int*)malloc(Nl*sizeof(*order)); for (i = 0; i < Nl; i++) { order[i] = i; } //gsl_ran_shuffle (r, order, Nl, sizeof (int)); free(r); return order; } double* integrateT(int n, void * p) //Performs the proper time integral using Simpson's Method //n = number of points to use for Simpson's method //p = Wparams parameters for the integrand { double* val; //value of the integral for each group double* trt; //Integrands evaluated at three points double* trtphalf; double* trtp1; int* order; //Stores the order of worldlines struct Wparams *params = (struct Wparams *) p; int inx, ig, i; val = (double *)calloc(params->ng,sizeof(*val)); double h = 1.0/((double) n); // double t; if(!val) printf("integrate(): malloc failed\n"); //initialize val to zero for(ig = 0; ig < params->ng; ig++) { val[ig] = 0.0; } //main integration loop for(inx = 0; inx < n; inx++) { printf("T integrate inx=%d\n",inx); //shuffle worldlines order=shuffleWL(params->Nl); t=h*((double)inx+1.0); trt=transformT(t,p,order); trtphalf=transformT(h*((double)inx + 0.5), p, order); trtp1=transformT(h*((double) inx+1.0), p, order); //A kludge to ignore possible infinities or nans for(ig = 0; ig < params->ng; ig++) { if(isinf(trt[ig])) { printf("Warning: trt[%d]=%f. Setting to zero.\n",ig,trt[ig]); trt[ig]=0.0; } if(isinf(trtphalf[ig])) { printf("Warning: trtphalf[%d]=%f. Setting to zero.\n",ig,trtphalf[ig]); trtphalf[ig]=0.0; } if(isinf(trtp1[ig])) { printf("Warning: trtp1[%d]=%f. Setting to zero.\n",ig,trtp1[ig]); trtp1[ig]=0.0; } val[ig]+=h/6.0*( trt[ig] + 4.0*trtphalf[ig] +trtp1[ig]); if(isinf(val[ig])){ printf("trt[%d]=%e\n",ig, trt[ig]); printf("trtphalf[%d]=%e\n",ig,trtphalf[ig]); printf("trtp1[%d]=%e\n",ig,trtp1[ig]); printf("val[%d]=%e\n",ig,val[ig]); } //printf("val[%d]=%e\n",ig,val[ig]); } testval(val, params->ng, t); free(order); } Tintout(val, params->ng, params->xcm.x, params->fermion); free(trt); free(trtphalf); free(trtp1); return val; }
{ "alphanum_fraction": 0.568321392, "avg_line_length": 22.2045454545, "ext": "c", "hexsha": "966aa0314c64f29f28cb07d965d08b5299721978", "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": "81cdf2bbb91e50cfe60e0ed81e6c93079a176cc8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "QEDan/Worldline-Flux-Tube-Lattice", "max_forks_repo_path": "Tint.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "81cdf2bbb91e50cfe60e0ed81e6c93079a176cc8", "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": "QEDan/Worldline-Flux-Tube-Lattice", "max_issues_repo_path": "Tint.c", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "81cdf2bbb91e50cfe60e0ed81e6c93079a176cc8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "QEDan/Worldline-Flux-Tube-Lattice", "max_stars_repo_path": "Tint.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1412, "size": 3908 }
#ifndef ARRUS_CORE_DEVICES_US4R_US4ROUTPUTBUFFER_H #define ARRUS_CORE_DEVICES_US4R_US4ROUTPUTBUFFER_H #include <mutex> #include <condition_variable> #include <gsl/span> #include <chrono> #include <iostream> #include "arrus/core/api/common/types.h" #include "arrus/core/api/common/exceptions.h" #include "arrus/common/asserts.h" #include "arrus/common/format.h" #include "arrus/core/common/logging.h" #include "arrus/core/api/framework/DataBuffer.h" namespace arrus::devices { using ::arrus::framework::Buffer; using ::arrus::framework::BufferElement; class Us4ROutputBuffer; /** * Buffer element owns the data arrrays, which then are returned to user. */ class Us4ROutputBufferElement : public BufferElement { public: using AccumulatorType = uint16; using SharedHandle = std::shared_ptr<Us4ROutputBufferElement>; Us4ROutputBufferElement(int16 *address, size_t size, const framework::NdArray::Shape &elementShape, const framework::NdArray::DataType elementDataType, AccumulatorType filledAccumulator, size_t position) : data(address, elementShape, elementDataType, DeviceId(DeviceType::Us4R, 0)), size(size), filledAccumulator(filledAccumulator), position(position) {} void release() override { std::unique_lock<std::mutex> guard(mutex); this->accumulator = 0; releaseFunction(); } int16 *getAddress() { validateState(); return data.get<int16>(); } framework::NdArray &getData() override { validateState(); return data; } size_t getSize() override { return size; } size_t getPosition() override { return position; } void registerReleaseFunction(std::function<void()> &func) { releaseFunction = func; } [[nodiscard]] bool isElementReady() { std::unique_lock<std::mutex> guard(mutex); return accumulator == filledAccumulator; } void signal(Ordinal n) { std::unique_lock<std::mutex> guard(mutex); AccumulatorType us4oemPattern = 1ul << n; if((accumulator & us4oemPattern) != 0) { throw IllegalStateException("Detected data overflow, buffer is in invalid state."); } accumulator |= us4oemPattern; } void resetState() { accumulator = 0; } void markAsInvalid() { this->isInvalid = true; } void validateState() { if(this->isInvalid) { throw ::arrus::IllegalStateException( "The buffer is in invalid state " "(probably some data transfer overflow happened)."); } } private: std::mutex mutex; framework::NdArray data; size_t size; AccumulatorType accumulator; /** A pattern of the filled accumulator, which indicates that the * whole element is ready. */ AccumulatorType filledAccumulator; std::function<void()> releaseFunction; bool isInvalid{false}; size_t position; }; /** * Us4R system's output circular FIFO buffer. * * The buffer has the following relationships: * - buffer contains **elements** * - the **element** is filled by many us4oems (with given ordinal) * * A single element is the output of a single data transfer (the result of running a complete sequence once). * * The state of each buffer element is determined by the field accumulators: * - accumulators[element] == 0 means that the buffer element was processed and is ready for new data from the producer. * - accumulators[element] > 0 && accumulators[element] != filledAccumulator means that the buffer element is partially * confirmed by some of us4oems * - accumulators[element] == filledAccumulator means that the buffer element is ready to be processed by a consumer. * * The assumption is here that each element of the buffer has the same size (and the same us4oem offsets). */ class Us4ROutputBuffer : public framework::DataBuffer { public: static constexpr size_t DATA_ALIGNMENT = 4096; using DataType = int16; /** * Buffer's constructor. * * @param us4oemOutputSizes number of bytes to allocate for each of the * us4oem output. That is, the i-th value describes how many bytes will * be written by i-th us4oem to generate a single buffer element. */ Us4ROutputBuffer(const std::vector<size_t> &us4oemOutputSizes, const framework::NdArray::Shape &elementShape, const framework::NdArray::DataType elementDataType, const unsigned nElements) : elementSize(0) { ARRUS_REQUIRES_TRUE(us4oemOutputSizes.size() <= 16, "Currently Us4R data buffer supports up to 16 us4oem modules."); size_t nus4oems = us4oemOutputSizes.size(); Us4ROutputBufferElement::AccumulatorType filledAccumulator((1ul << nus4oems) - 1); // Calculate us4oem write offsets for each buffer element. size_t us4oemOffset = 0; Ordinal us4oemOrdinal = 0; for(auto s : us4oemOutputSizes) { us4oemOffsets.emplace_back(us4oemOffset); us4oemOffset += s; if(s == 0) { // We should not expect any response from modules, which do not acquire any data. filledAccumulator &= ~(1ul << us4oemOrdinal); } ++us4oemOrdinal; } elementSize = us4oemOffset; // Allocate buffer with an appropriate size. dataBuffer = reinterpret_cast<DataType *>(operator new[](elementSize * nElements, std::align_val_t(DATA_ALIGNMENT))); getDefaultLogger()->log(LogSeverity::DEBUG, ::arrus::format( "Allocated {} ({}, {}) bytes of memory, address: {}", elementSize * nElements, elementSize, nElements, (size_t) dataBuffer)); for(unsigned i = 0; i < nElements; ++i) { auto elementAddress = reinterpret_cast<DataType *>(reinterpret_cast<int8 *>(dataBuffer) + i * elementSize); elements.push_back(std::make_shared<Us4ROutputBufferElement>(elementAddress, elementSize, elementShape, elementDataType, filledAccumulator, i)); } this->initialize(); } ~Us4ROutputBuffer() override { ::operator delete(dataBuffer, std::align_val_t(DATA_ALIGNMENT)); getDefaultLogger()->log(LogSeverity::DEBUG, "Released the output buffer."); } void registerOnNewDataCallback(framework::OnNewDataCallback &callback) override { this->onNewDataCallback = callback; } [[nodiscard]] const framework::OnNewDataCallback &getOnNewDataCallback() const { return this->onNewDataCallback; } void registerOnOverflowCallback(framework::OnOverflowCallback &callback) override { this->onOverflowCallback = callback; } void registerShutdownCallback(framework::OnShutdownCallback &callback) override { this->onShutdownCallback = callback; } [[nodiscard]] size_t getNumberOfElements() const override { return elements.size(); } BufferElement::SharedHandle getElement(size_t i) override { return std::static_pointer_cast<BufferElement>(elements[i]); } uint8 *getAddress(uint16 elementNumber, Ordinal us4oem) { return reinterpret_cast<uint8 *>(this->elements[elementNumber]->getAddress()) + us4oemOffsets[us4oem]; } /** * Returns a total size of the buffer, the number of bytes. */ [[nodiscard]] size_t getElementSize() const override { return elementSize; } /** * Signals the readiness of new data acquired by the n-th Us4OEM module. * * This function should be called by us4oem interrupt callbacks. * * @param n us4oem ordinal number * * @return true if the buffer signal was successful, false otherwise (e.g. the queue was shut down). */ bool signal(Ordinal n, uint16 elementNr) { std::unique_lock<std::mutex> guard(mutex); if(this->state != State::RUNNING) { getDefaultLogger()->log(LogSeverity::DEBUG, "Signal queue shutdown."); return false; } this->validateState(); auto &element = this->elements[elementNr]; try { element->signal(n); } catch(const IllegalArgumentException &e) { this->markAsInvalid(); throw e; } if(element->isElementReady()) { guard.unlock(); onNewDataCallback(elements[elementNr]); } else { guard.unlock(); } return true; } void markAsInvalid() { std::unique_lock<std::mutex> guard(mutex); if(this->state != State::INVALID) { this->state = State::INVALID; for(auto &element: elements) { element->markAsInvalid(); } this->onOverflowCallback(); } } void shutdown() { std::unique_lock<std::mutex> guard(mutex); this->onShutdownCallback(); this->state = State::SHUTDOWN; guard.unlock(); } void resetState() { this->state = State::INVALID; this->initialize(); this->state = State::RUNNING; } void initialize() { for(auto &element: elements) { element->resetState(); } } void registerReleaseFunction(size_t element, std::function<void()> &releaseFunction) { this->elements[element]->registerReleaseFunction(releaseFunction); } private: std::mutex mutex; /** A size of a single element IN number of BYTES. */ size_t elementSize; /** Total size in the number of elements. */ int16 *dataBuffer; /** Host buffer elements */ std::vector<Us4ROutputBufferElement::SharedHandle> elements; /** Relative addresses where us4oem modules will write. IN NUMBER OF BYTES. */ std::vector<size_t> us4oemOffsets; // Callback that should be called once new data arrive. framework::OnNewDataCallback onNewDataCallback; framework::OnOverflowCallback onOverflowCallback{[]() {}}; framework::OnShutdownCallback onShutdownCallback{[]() {}}; // State management enum class State { RUNNING, SHUTDOWN, INVALID }; State state{State::RUNNING}; /** * Throws IllegalStateException when the buffer is in invalid state. * * @return true if the queue execution should continue, false otherwise. */ void validateState() { if(this->state == State::INVALID) { throw ::arrus::IllegalStateException( "The buffer is in invalid state " "(probably some data transfer overflow happened)."); } else if(this->state == State::SHUTDOWN) { throw ::arrus::IllegalStateException( "The data buffer has been turned off."); } } }; } #endif //ARRUS_CORE_DEVICES_US4R_US4ROUTPUTBUFFER_H
{ "alphanum_fraction": 0.6156408908, "avg_line_length": 34.1497005988, "ext": "h", "hexsha": "c47dcc8bd904a9aa961e805b9e006957c9a8f109", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-12-13T08:53:31.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-22T16:13:06.000Z", "max_forks_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_forks_repo_licenses": [ "BSL-1.0", "MIT" ], "max_forks_repo_name": "us4useu/arrus", "max_forks_repo_path": "arrus/core/devices/us4r/Us4ROutputBuffer.h", "max_issues_count": 60, "max_issues_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_issues_repo_issues_event_max_datetime": "2022-03-12T17:39:06.000Z", "max_issues_repo_issues_event_min_datetime": "2020-11-06T04:59:06.000Z", "max_issues_repo_licenses": [ "BSL-1.0", "MIT" ], "max_issues_repo_name": "us4useu/arrus", "max_issues_repo_path": "arrus/core/devices/us4r/Us4ROutputBuffer.h", "max_line_length": 120, "max_stars_count": 11, "max_stars_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064", "max_stars_repo_licenses": [ "BSL-1.0", "MIT" ], "max_stars_repo_name": "us4useu/arrus", "max_stars_repo_path": "arrus/core/devices/us4r/Us4ROutputBuffer.h", "max_stars_repo_stars_event_max_datetime": "2022-02-18T09:41:51.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-04T19:56:08.000Z", "num_tokens": 2501, "size": 11406 }
#include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_poly.h> void mgsl_poly_complex_eval(const double c[], const int len, const gsl_complex *z, gsl_complex *ret) { *ret = gsl_poly_complex_eval(c, len, *z); } void mgsl_complex_poly_complex_eval(gsl_complex **c, const int len, const gsl_complex *z, gsl_complex *ret) { gsl_complex *zc = calloc(len, sizeof(gsl_complex)); int i; for(i=0; i<len; i++) zc[i] = *c[i]; *ret = gsl_complex_poly_complex_eval(zc, len, *z); }
{ "alphanum_fraction": 0.7134387352, "avg_line_length": 29.7647058824, "ext": "c", "hexsha": "4f2bb4e56539be07dd19e4db2c8050169352b65c", "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": "0695d9d36be997c6805bc68afd64e178cbd96f8f", "max_forks_repo_licenses": [ "Artistic-2.0" ], "max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Polynomial", "max_forks_repo_path": "src/polynomial.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0695d9d36be997c6805bc68afd64e178cbd96f8f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Artistic-2.0" ], "max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Polynomial", "max_issues_repo_path": "src/polynomial.c", "max_line_length": 107, "max_stars_count": null, "max_stars_repo_head_hexsha": "0695d9d36be997c6805bc68afd64e178cbd96f8f", "max_stars_repo_licenses": [ "Artistic-2.0" ], "max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Polynomial", "max_stars_repo_path": "src/polynomial.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 155, "size": 506 }
/* * Evaluation of the scheduling algorithms HET, RTA, RTA2 and RTA3. * v1.0 -- 12/01/2017 -- initial version. * v2.0 -- 16/05/2017 -- second version. */ #include <libxml/xmlreader.h> #include <libxml/parser.h> #include <libxml/xpath.h> #include <math.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <getopt.h> #include <gsl/gsl_statistics.h> /* * Ceil and floor operations without using the library math, when period * and wcet values are integers. */ #define U_CEIL( x, y ) ( ( x / y ) + ( x % y != 0 ) ) #define U_FLOOR( x, y ) ( x / y ) /* * Elementos en el archivo XML. */ #define ELEMENT 1 // Tag end #define END_ELEMENT 15 // Tag start #define SET_TAG (const xmlChar*) "Set" // <Set> tag -- set #define S_TAG (const xmlChar*) "S" // <S> tag -- rts #define I_TAG (const xmlChar*) "i" // <i> tag -- task #define SET_SIZE_ATTR (const xmlChar*) "size" // "size" attribute in <Set> tag #define SET_RTS_SIZE_ATTR (const xmlChar*) "n" // "n" attribute in <Set> tag #define SET_UF_ATTR (const xmlChar*) "u" // "u" attribute in <Set> tag #define RTS_ID_ATTR (const xmlChar*) "count" // "count" attribute in <S> tag #define RTS_UF_ATTR (const xmlChar*) "U" // "U" attribute in <S> tag #define ID_ATTR (const xmlChar*) "nro" // "nro" attribute in <i> tag #define WCET_ATTR (const xmlChar*) "C" // "C" attribute in <i> tag #define T_ATTR (const xmlChar*) "T" // "T" attribute in <i> tag #define D_ATTR (const xmlChar*) "D" // "D" attribute in <i> tag /* * Number of schedulability methods to test. */ #define NUM_SCHED_METHODS 4 /* * Name of the schedulability methods to evaluate. */ #define HET "het" #define RTA "rta" #define RTA2 "rta2" #define RTA3 "rta3" /* * Position of the method in the schedulable array. */ #define HET_ID 0 #define RTA_ID 1 #define RTA2_ID 2 #define RTA3_ID 3 /* * Return value for the schedulability methods. */ #define SCHED 1 #define NON_SCHED 0 /* * Global variables. */ int rts_founded = 0; // Number of RTS in the XML file evaluated. int verbose = 0; // Print addtional info to stderr FILE* out_file; // Result file // Tarea struct task_t { int id; // task id int c; // wcet int t; // period int d; // deadline int tmc; // t - c int wcrt[NUM_SCHED_METHODS]; // wcrt int cc[NUM_SCHED_METHODS]; // cc int loops_w[NUM_SCHED_METHODS]; // number of while loops int loops_f[NUM_SCHED_METHODS]; // number of for loops int a_rta2; int b_rta2; int a_rta3; int b_rta3; int last_psi; // het int last_workload; // het }; // rts struct rts_t { int rts_id; int rts_uf; int rts_ntask; int *schedulable; struct task_t **tasks; }; // set of rts struct set_t { int set_size; int set_uf; int set_rts_ntask; struct rts_t **rts_list; }; // prototipe for scheduling analysis methods typedef int (*sched_test_method) (struct rts_t*); // test method result struct result_t { double *cc; double *loops; double cc_mean; double cc_std; double loops_mean; double loops_std; }; struct method_t { char* method_name; int method_id; sched_test_method method; struct result_t *result; }; /* * Prototipes */ int rta_wcrt(struct rts_t*); int rta2_wcrt(struct rts_t*); int rta3_wcrt(struct rts_t*); int het_workload(int i, int b, int n, struct task_t**); int het_wcrt(struct rts_t*); int het_workload(int i, int b, int n, struct task_t **tasks) { tasks[n]->loops_w[HET_ID] += 1; double tmp = (double) b / (double) tasks[i]->t; int f = (int) floor(tmp); int c = (int) ceil(tmp); tasks[n]->cc[HET_ID] += 2; int branch0 = b - f * (tasks[i]->t - tasks[i]->c); int branch1 = c * tasks[i]->c; if (i > 0) { int l_w = tasks[i - 1]->last_workload; int tmp = f * tasks[i]->t; if (tmp > tasks[i - 1]->last_psi) { l_w = het_workload(i - 1, tmp, n, tasks); } branch0 += l_w; branch1 += het_workload(i - 1, b, n, tasks); } tasks[i]->last_psi = b; if (branch0 <= branch1) { tasks[i]->last_workload = branch0; } else { tasks[i]->last_workload = branch1; } return tasks[i]->last_workload; } /* * HET * "Schedulability Analysis of Periodic Fixed Priority Systems" * http://ieeexplore.ieee.org/document/1336766/ * -- * See also: * "Efficient Exact Schedulability Tests for Fixed Priority Real-Time Systems" * http://ieeexplore.ieee.org/document/4487061/ */ int het_wcrt(struct rts_t *rts) { struct task_t **tasks = rts->tasks; int i; for (i = 1; i < rts->rts_ntask; i++) { tasks[i]->loops_f[HET_ID] += 1; int w = het_workload(i - 1, tasks[i]->d, i, tasks); if ((w + tasks[i]->c) > tasks[i]->d) { rts->schedulable[HET_ID] = NON_SCHED; return NON_SCHED; } tasks[i]->wcrt[HET_ID] = w + tasks[i]->c; } rts->schedulable[HET_ID] = SCHED; return SCHED; } /* * RTA * "Improved Response-Time Analysis Calculations" * http://doi.ieeecomputersociety.org/10.1109/REAL.1998.739773 */ int rta_wcrt(struct rts_t *rts) { struct task_t **tasks = rts->tasks; int w = 0; int tr = 0; int t = tasks[0]->c; tasks[0]->wcrt[RTA_ID] = tasks[0]->c; int i, j; for (i = 1; i < rts->rts_ntask; i++) { tr = t + tasks[i]->c; tasks[i]->loops_f[RTA_ID] += 1; do { tasks[i]->loops_w[RTA_ID] += 1; t = tr; w = tasks[i]->c; for (j = 0; j < i; j++) { tasks[i]->loops_f[RTA_ID] += 1; int c_j = tasks[j]->c; int t_j = tasks[j]->t; int a = (int) ceil( ((double) tr) / ((double) t_j) ); tasks[i]->cc[RTA_ID] += 1; w = w + (a * c_j); if (w > tasks[i]->d) { rts->schedulable[RTA_ID] = NON_SCHED; return NON_SCHED; } } tr = w; } while (t != tr); tasks[i]->wcrt[RTA_ID] = t; } rts->schedulable[RTA_ID] = SCHED; return SCHED; } /* * RTA2 * "Reduced computational cost in the calculation of worst case response time for real time systems" * http://sedici.unlp.edu.ar/handle/10915/9654 */ int rta2_wcrt(struct rts_t *rts) { struct task_t **tasks = rts->tasks; int tr = 0; int t = tasks[0]->c; tasks[0]->wcrt[RTA2_ID] = tasks[0]->c; int i, j; for (i = 1; i < rts->rts_ntask; i++) { tr = t + tasks[i]->c; tasks[i]->loops_f[RTA2_ID] += 1; do { tasks[i]->loops_w[RTA2_ID] += 1; t = tr; for (j = 0; j < i; j++) { tasks[i]->loops_f[RTA2_ID] += 1; int a = (int) ceil( ((double) tr) / ((double) tasks[j]->t) ); tasks[i]->cc[RTA2_ID] += 1; a = a * tasks[j]->c; if (a > tasks[j]->a_rta2) { tr = tr + a - tasks[j]->a_rta2; tasks[j]->a_rta2 = a; if (tr > tasks[i]->d) { rts->schedulable[RTA2_ID] = NON_SCHED; return NON_SCHED; } } } } while (t != tr); tasks[i]->wcrt[RTA2_ID] = t; } rts->schedulable[RTA2_ID] = SCHED; return SCHED; } /* * RTA3 * "Computational Cost Reduction for Real-Time Schedulability Tests Algorithms" * http://ieeexplore.ieee.org/document/7404899/ */ int rta3_wcrt(struct rts_t *rts) { struct task_t **tasks = rts->tasks; int tr = 0; int t = tasks[0]->c; tasks[0]->wcrt[RTA3_ID] = tasks[0]->c; int i, j; for (i = 1; i < rts->rts_ntask; i++) { tr = t + tasks[i]->c; tasks[i]->loops_f[RTA3_ID] += 1; do { tasks[i]->loops_w[RTA3_ID] += 1; t = tr; for (j = i - 1; j >= 0; j--) { tasks[i]->loops_f[RTA3_ID] += 1; if (tr > tasks[j]->b_rta3) { int a_t = (int) ceil( ((double)tr) / ((double)tasks[j]->t) ); tasks[i]->cc[RTA3_ID] += 1; int a = a_t * tasks[j]->c; tr = tr + a - tasks[j]->a_rta3; tasks[j]->a_rta3 = a; tasks[j]->b_rta3 = a_t * tasks[j]->t; // verifica vencimiento if (tr > tasks[i]->d) { rts->schedulable[RTA3_ID] = NON_SCHED; return NON_SCHED; } } } } while (t != tr); tasks[i]->wcrt[RTA3_ID] = t; } rts->schedulable[RTA3_ID] = SCHED; return SCHED; } void reset_rts(struct rts_t *rts) { int i, j; for (i = 0; i < rts->rts_ntask; i++) { struct task_t *task = rts->tasks[i]; task->a_rta2 = task->c; task->b_rta2 = task->t; task->a_rta3 = task->c; task->b_rta3 = task->t; task->last_psi = 0; task->last_workload = 0; for (j = 0; j < NUM_SCHED_METHODS; j++) { task->cc[j] = 0; task->loops_w[j] = 0; task->loops_f[j] = 0; task->wcrt[j] = 0; } } } /* * Parse the XML file. If a new RTS is found, it is evalutad with the methods in method array. */ void processXmlFile(xmlTextReaderPtr reader, struct set_t *rts_set, struct method_t *methods) { xmlChar *name = xmlTextReaderLocalName(reader); // Tag <Set> -- initial tag if (xmlStrcasecmp(name, SET_TAG) == 0) { if (xmlTextReaderNodeType(reader) == ELEMENT) { xmlChar *c_set_rts_uf = xmlTextReaderGetAttribute(reader, SET_UF_ATTR); xmlChar *c_set_rts_size = xmlTextReaderGetAttribute(reader, SET_SIZE_ATTR); xmlChar *c_set_rts_ntask = xmlTextReaderGetAttribute(reader, SET_RTS_SIZE_ATTR); rts_set->set_uf = atoi((char*) c_set_rts_uf); rts_set->set_size = atoi((char*) c_set_rts_size); rts_set->set_rts_ntask = atoi((char*) c_set_rts_ntask); xmlFree(c_set_rts_uf); xmlFree(c_set_rts_size); xmlFree(c_set_rts_ntask); } } // Tag <S> -- RTS if (xmlStrcasecmp(name, S_TAG) == 0) { if (xmlTextReaderNodeType(reader) == ELEMENT) { xmlChar *c_rts_id = xmlTextReaderGetAttribute(reader, RTS_ID_ATTR); xmlChar *c_rts_uf = xmlTextReaderGetAttribute(reader, RTS_UF_ATTR); // reserve memory for the rts and add it to rts_list struct rts_t *new_rts = malloc(sizeof(struct rts_t)); // reserve memory for the methods results new_rts->schedulable = malloc(sizeof(int) * NUM_SCHED_METHODS); // reserve memory for the rts tasks new_rts->tasks = malloc(sizeof(struct task_t*) * rts_set->set_rts_ntask); // complete data about this rts new_rts->rts_id = atoi((char*) c_rts_id); new_rts->rts_uf = atoi((char*) c_rts_uf); new_rts->rts_ntask = rts_set->set_rts_ntask; // add rts to set rts_set->rts_list[rts_founded] = new_rts; // free memory xmlFree(c_rts_id); xmlFree(c_rts_uf); } if (xmlTextReaderNodeType(reader) == END_ELEMENT) { struct rts_t *rts = rts_set->rts_list[rts_founded]; reset_rts(rts); // evaluate the methods int i, j; for (i = 0; i < NUM_SCHED_METHODS; i++) { int method_id = methods[i].method_id; rts->schedulable[method_id] = (*methods[i].method)(rts); // store totals for (j = 0; j < rts->rts_ntask; j++) { struct task_t *task = rts->tasks[j]; methods[i].result->cc[rts_founded] += task->cc[method_id]; methods[i].result->loops[rts_founded] += task->loops_w[method_id] + task->loops_f[method_id]; } } rts_founded = rts_founded + 1; } } // Tag <i> -- a real-time task if (xmlStrcasecmp(name, I_TAG) == 0) { xmlChar *c_id = xmlTextReaderGetAttribute(reader, ID_ATTR); xmlChar *wcet = xmlTextReaderGetAttribute(reader, WCET_ATTR); xmlChar *t = xmlTextReaderGetAttribute(reader, T_ATTR); xmlChar *d = xmlTextReaderGetAttribute(reader, D_ATTR); int id = atoi((char*) c_id) - 1; struct rts_t *rts = rts_set->rts_list[rts_founded]; // reserve memory for the task struct task_t *task = malloc(sizeof(struct task_t)); // complete the basic task data task->id = id + 1; task->c = atoi((char*) wcet); task->t = atoi((char*) t); task->d = atoi((char*) d); task->tmc = task->t - task->c; // add the task to rts rts->tasks[id] = task; xmlFree(c_id); xmlFree(wcet); xmlFree(t); xmlFree(d); } xmlFree(name); } void testRtsInXml(char *file, struct set_t* rts_set, struct method_t *methods, int limit) { // get read pointer xmlTextReaderPtr reader = xmlNewTextReaderFilename(file); if (reader == NULL) { fprintf(stderr, "Unable to open %s\n", file); exit(EXIT_FAILURE); } // parse xml file and evaluate schedulability methods int ret = xmlTextReaderRead(reader); while (ret == 1) { if (limit > 0 && rts_founded == limit) { break; } processXmlFile(reader, rts_set, methods); ret = xmlTextReaderRead(reader); } if (rts_set->set_size < limit) { fprintf(stderr, "Warning: %d str in file according to XML info, but %d to be tested.\n", rts_set->set_size, limit); } xmlFreeTextReader(reader); } /* * Print method results to out_file. */ void save_result(char* method, struct result_t* result, int use_csv, char *csv_sep) { if (use_csv == 0) { fprintf(out_file, "%10s%15f%15f%15f%15f\n", method, result->cc_mean, result->cc_std, result->loops_mean, result->loops_std); } else { fprintf(out_file, "%2$s%1$s%3$f%1$s%4$f%1$s%5$f%1$s%6$f\n", csv_sep, method, result->cc_mean, result->cc_std, result->loops_mean, result->loops_std); } } /* * Print help and usage information. */ void printUsage(char* progName, int exitCode) { fprintf(stderr, "Usage: %s [options] file\n", progName); fprintf(stderr, "\t-v --verbose\tDisplay additional information about the clock used.\n" "\t-h --help\tDisplay this information.\n" "\t-l --limit\tTest first n RTS in file.\n" "\t-c --csv\tCSV output with specified line separator.\n"); exit(exitCode); } int main(int argc, char **argv) { int i, j, k; if (argc <= 1) { printUsage(argv[0], EXIT_FAILURE); } // options -- short format const char *shortOpts = "hvl:c:"; // options -- long format const struct option longOpts[] = { {"help", no_argument, NULL, 'h'}, {"verbose", no_argument, NULL, 'v'}, {"limit", required_argument, NULL, 'l'}, {"csv", required_argument, NULL, 'c'}, {0, 0, 0, 0} }; verbose = 0; rts_founded = 0; int limit = 0; int use_csv = 0; char* csv_sep; int nextOption; do { nextOption = getopt_long(argc, argv, shortOpts, longOpts, NULL); switch (nextOption) { case 'h': // -h or --help printUsage(argv[0], EXIT_SUCCESS); case 'v': // -v or --verbose verbose = 1; break; case 'l': // -l or --limit limit = atoi(optarg); break; case 'c': // -c or --csv use_csv = 1; csv_sep = optarg; break; case '?': // invalid option printUsage(argv[0], EXIT_FAILURE); case -1: // no more options break; default: abort(); } } while (nextOption != -1); // print info to stderr if requested if (verbose == 1) { fprintf(stderr, "Testing %s...\n", argv[optind]); } // stdout as default output file out_file = stdout; // reserve memory for the set struct set_t *rts_set = malloc(sizeof(struct set_t)); rts_set->set_uf = 0; rts_set->set_size = 0; rts_set->set_rts_ntask = 0; // reserve memory to store the rts to test rts_set->rts_list = malloc(sizeof(struct rts_t*) * limit); // reserve memory for test results struct result_t* het_results = malloc(sizeof(struct result_t)); struct result_t* rta_results = malloc(sizeof(struct result_t)); struct result_t* rta2_results = malloc(sizeof(struct result_t)); struct result_t* rta3_results = malloc(sizeof(struct result_t)); // methods to test struct method_t methods[] = {[RTA_ID] {RTA, RTA_ID, rta_wcrt, rta_results}, [RTA2_ID] {RTA2, RTA2_ID, rta2_wcrt, rta2_results}, [RTA3_ID] {RTA3, RTA3_ID, rta3_wcrt, rta3_results}, [HET_ID] {HET, HET_ID, het_wcrt, het_results} }; for (i = 0; i < NUM_SCHED_METHODS; i++) { methods[i].result->cc = calloc(limit, sizeof(double)); methods[i].result->loops = calloc(limit, sizeof(double)); } if (verbose == 1) { fprintf(stderr, "Testing %d rts.\n", limit); } // read rts from xml file into rts_set char *filename = argv[optind]; testRtsInXml(filename, rts_set, methods, limit); // compute means and stdev for (i = 0; i < NUM_SCHED_METHODS; i++) { methods[i].result->cc_mean = gsl_stats_mean(methods[i].result->cc, 1, rts_founded); methods[i].result->cc_std = gsl_stats_sd_m(methods[i].result->cc, 1, rts_founded, methods[i].result->cc_mean); methods[i].result->loops_mean = gsl_stats_mean(methods[i].result->loops, 1, rts_founded); methods[i].result->loops_std = gsl_stats_sd_m(methods[i].result->loops, 1, rts_founded, methods[i].result->loops_mean); } int rts_sched_cnt = 0; int rts_nonsched_cnt = 0; // verify that all methods give the same result for (i = 0; i < rts_founded; i++) { struct rts_t *rts = rts_set->rts_list[i]; int sum = 0; for (j = 0; j < NUM_SCHED_METHODS; j++) { sum += rts->schedulable[j]; } if (sum > 0 && sum < NUM_SCHED_METHODS) { fprintf(stderr, "Error! Method results are not the same. RTS %d\n", i); for (j = 0; j < NUM_SCHED_METHODS; j++) { fprintf(stderr, "%s: %d\n", methods[j].method_name, rts->schedulable[j]); } break; } if (rts->schedulable[RTA_ID] == SCHED) { rts_sched_cnt += 1; } else { rts_nonsched_cnt += 1; } } // verify that all wcrt are the same (only RTA methods) for (j = 0; j < rts_founded; j++) { struct rts_t *rts = rts_set->rts_list[j]; for (k = 0; k < rts->rts_ntask; k++) { struct task_t *task = rts->tasks[k]; int ref_wcrt = task->wcrt[RTA_ID]; if (ref_wcrt != task->wcrt[RTA2_ID] || ref_wcrt != task->wcrt[RTA3_ID]) { fprintf(stderr, "Error! WCRT are not the same. RTS %d, task %d\n", j, k); int i = 0; fprintf(stderr, "%13s%10s%10s%10s%10s\n", "RTA", "RTA2", "RTA3", "C_i", "D_i"); for (i = 0; i < rts->rts_ntask; i++) { fprintf(stderr, "%3d%10d%10d%10d%10d%10d\n", i, rts->tasks[i]->wcrt[RTA_ID], rts->tasks[i]->wcrt[RTA2_ID], rts->tasks[i]->wcrt[RTA3_ID], rts->tasks[i]->c, rts->tasks[i]->d ); } return(EXIT_FAILURE); } } } // get timestamp for the test char test_date[50]; time_t current_time = time(NULL); strftime(test_date, 50, "%R %d/%m/%Y", localtime(&current_time)); // print header fprintf(out_file, "%s\n", filename); fprintf(out_file, "%s\n", test_date); fprintf(out_file, "Total: %d\n", rts_founded); fprintf(out_file, "Sched: %d\n", rts_sched_cnt); fprintf(out_file, "Non sched: %d\n", rts_nonsched_cnt); // print column names if (use_csv == 0) { fprintf(out_file, "%10s%15s%15s%15s%15s\n", "method", "cc_mean", "cc_mean_std", "loops_mean", "loops_mean_std"); } else { fprintf(out_file, "method%1$scc_mean%1$scc_mean_std%1$sloops_mean%1$sloops_mean_std\n", csv_sep); } // print the results for (i = 0; i < NUM_SCHED_METHODS; i++) { save_result(methods[i].method_name, methods[i].result, use_csv, csv_sep); } return(EXIT_SUCCESS); }
{ "alphanum_fraction": 0.5207234023, "avg_line_length": 30.967877095, "ext": "c", "hexsha": "76096717d4882cd838287ffa8659d80fdfd8a81f", "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": "31b4a1148020dbeb4269d087cf65f4485bfa6c44", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "unpsjb-rtsg/wcrt", "max_forks_repo_path": "wcrt-test-sim.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "31b4a1148020dbeb4269d087cf65f4485bfa6c44", "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": "unpsjb-rtsg/wcrt", "max_issues_repo_path": "wcrt-test-sim.c", "max_line_length": 135, "max_stars_count": null, "max_stars_repo_head_hexsha": "31b4a1148020dbeb4269d087cf65f4485bfa6c44", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "unpsjb-rtsg/wcrt", "max_stars_repo_path": "wcrt-test-sim.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6327, "size": 22173 }
#include <stdio.h> #include <unistd.h> #include <assert.h> #include <math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_rng.h> #include "dlib.h" #include "svec.h" #include "rng.h" const char *usage = "Usage: scode [OPTIONS] < file\n" "file should have columns of arbitrary tokens\n" "-r RESTART: number of restarts (default 1)\n" "-i NITER: number of iterations over data (default UINT32_MAX)\n" "-t THRESHOLD: quit if logL increase for iter <= this (default .001)\n" "-d NDIM: number of dimensions (default 25)\n" "-z Z: partition function approximation (default 0.166)\n" "-p PHI0: learning rate parameter (default 50.0)\n" "-u ETA0: learning rate parameter (default 0.2)\n" "-s SEED: random seed (default 0)\n" "-c calculate real Z (default false)\n" "-w The first line of the input is weights (default false)\n" "-v verbose messages (default false)\n"; //typedef uint32_t u32; //typedef uint64_t u64; u32 RESTART = 1; u32 NITER = UINT32_MAX; double THRESHOLD = 0.001; u32 NDIM = 25; double Z = 0.166; double PHI0 = 50.0; double ETA0 = 0.2; unsigned long int SEED = 0; bool CALCZ = false; bool WEIGHT = false; bool VERBOSE = false; u32 NTOK = 0; u64 NTUPLE = 0; const gsl_rng_type *rng_T; gsl_rng *rng_R = NULL; darr_t data; u64 **update_cnt; double * weight = NULL; double * uweight = NULL; /*Updated weights*/ u64 **cnt; #define frq(i,j) ((double)cnt[i][j]*NTOK/len(data)) svec **vec; svec **best_vec; svec dummy_vec; sym_t qmax; sym_t NULLFEATID; #define NULLFEATMARKER "/XX/" int main(int argc, char **argv); void init_rng(); void free_rng(); u64 init_data(); u32 init_weight(); void free_weight(); void randomize_vectors(); void copy_best_vec(); void free_data(); void update_tuple(sym_t *t); double logL(); double calcZ(); #define vmsg(...) if(VERBOSE)msg(__VA_ARGS__) int main(int argc, char **argv) { int opt; while((opt = getopt(argc, argv, "r:i:t:d:z:p:u:s:cwv")) != -1) { switch(opt) { case 'r': RESTART = atoi(optarg); break; case 'i': NITER = atoi(optarg); break; case 't': THRESHOLD = atof(optarg); break; case 'd': NDIM = atoi(optarg); break; case 'z': Z = atof(optarg); break; case 'p': PHI0 = atof(optarg); break; case 'u': ETA0 = atof(optarg); break; case 's': SEED = atoi(optarg); break; case 'c': CALCZ = true; break; case 'w': WEIGHT = true; break; case 'v': VERBOSE = true; break; default: die("%s",usage); } } vmsg("scode -r %u -i %u -t %g -d %u -z %g -p %g -u %g -s %lu %s%s%s", RESTART, NITER, THRESHOLD, NDIM, Z, PHI0, ETA0, SEED, (CALCZ ? "-c " : ""), (WEIGHT ? "-w " : ""), (VERBOSE ? "-v " : "")); init_rng(); if (SEED) gsl_rng_set(rng_R, SEED); if (WEIGHT) NTOK = init_weight(); NTUPLE = init_data(); vmsg("Read %zu tuples %u uniq tokens", NTUPLE, qmax); double best_logL = 0; for (u32 start = 0; start < RESTART; start++) { randomize_vectors(); double ll = logL(); vmsg("Restart %u/%u logL0=%g best=%g", 1+start, RESTART, ll, best_logL); if (CALCZ) vmsg("Z=%g (approx %g)", calcZ(), Z); for (u32 iter = 0; iter < NITER; iter++) { for (u64 di = 0; di < NTUPLE; di++) { update_tuple(&val(data, di * NTOK, sym_t)); } double ll0 = ll; ll = logL(); vmsg("Iteration %u/%u logL=%g", 1+iter, NITER, ll); if (ll - ll0 <= THRESHOLD) break; } if (start == 0 || ll > best_logL) { vmsg("Updating best_vec with logL=%g", ll); best_logL = ll; copy_best_vec(); } vmsg("Restart %u/%u logL1=%g best=%g", 1+start, RESTART, ll, best_logL); if (CALCZ) vmsg("Z=%g (approx %g)", calcZ(), Z); } for (u32 t = 0; t < NTOK; t++) { for (sym_t q = 1; q <= qmax; q++) { if (best_vec[t][q] == NULL) continue; printf("%u:%s\t%zu\t", t, sym2str(q), cnt[t][q]); svec_print(best_vec[t][q]); putchar('\n'); } } fflush(stdout); free_data(); free_rng(); if (WEIGHT) free_weight(); symtable_free(); dfreeall(); fprintf(stderr, "%f\n", best_logL); vmsg("bye"); } double logL() { double l = 0; for (u64 i = 0; i < NTUPLE; i++) { sym_t *t = &val(data, i * NTOK, sym_t); sym_t x = t[0]; sym_t y = t[1]; float px = frq(0, x); float py = frq(1, y); svec vx = vec[0][x]; svec vy = vec[1][y]; float xy = svec_sqdist(vx, vy); l += log(px * py) - xy; } return (l / NTUPLE - log(Z)); } double calcZ() { double z = 0; for (sym_t x = 1; x <= qmax; x++) { if (VERBOSE && (x % 1000 == 0)) fputc('.', stderr); if (cnt[0][x] == 0) continue; float px = frq(0, x); svec vx = vec[0][x]; for (sym_t y = 1; y <= qmax; y++) { if (cnt[1][y] == 0) continue; float py = frq(1, y); svec vy = vec[1][y]; float xy = svec_sqdist(vx, vy); z += px * py * exp(-xy); } } if (VERBOSE) fputc('\n', stderr); return z; } void update_tuple(sym_t *t) { /*weighted update*/ static svec *u = NULL; static svec *v = NULL; static svec dx = NULL; if (u == NULL) u = _d_malloc(NTOK * sizeof(svec)); if (v == NULL) v = _d_malloc(NTOK * sizeof(svec)); if (dx == NULL) dx = svec_alloc(NDIM); for (u32 i = 0; i < NTOK; i++) u[i] = vec[i][t[i]]; for (u32 i = 0; i < NTOK; i++) { /* Sampling values from the marginal distributions. */ /* Can this be done once, or do we have to resample for every x? */ if(i > 0 && t[i] == NULLFEATID) continue; for (u32 j = 0; j < NTOK; j++) { if (j==i) { v[j] = u[i]; continue;} u64 r = gsl_rng_get(rng_R); r = (r << 32) | gsl_rng_get(rng_R); r = r % NTUPLE; sym_t y = val(data, r * NTOK + j, sym_t); v[j] = vec[j][y]; if(i > 0) break; } /* Compute the move for u[i] */ svec_set_zero(dx); double ww; for (u32 j = 0; j < NTOK; j++) { if (j == i) continue; ww = weight == NULL ? 1 : (i > 0 ? weight[i] : weight[j]); double push = 0, pull = 0; if (v[j] == NULL) v[j] = dummy_vec; else push = exp(-svec_sqdist(u[i], v[j])) / Z; if(u[j] == NULL) u[j] = dummy_vec; else pull = 1; if(push != 0 || pull != 0){ for (u32 d = 0; d < NDIM; d++) { float dxd = svec_get(dx, d); float x = svec_get(u[i], d); float y = svec_get(u[j], d); float z = svec_get(v[j], d); svec_set(dx, d, dxd + ww * ( pull * (y - x) + push * (x - z))); } } /*restore the vectors to original forms*/ if(push == 0) v[j] = NULL; if(pull == 0) u[j] = NULL; if(i > 0) break; } /* Apply the move scaled by learning parameter */ u64 cx = update_cnt[i][t[i]]++; float nx = ETA0 * (PHI0 / (PHI0 + cx)); svec_scale(dx, nx); svec_add(u[i], dx); svec_normalize(u[i]); } } u32 init_weight(){ u32 size = 100, i = 0; weight = _d_malloc(size * sizeof(double)); forline (buf, NULL) { fortok (tok, buf) { weight[i] = atof(tok); assert(weight[i++] >= 0); if(i >= 100) { size *= 2; weight = _d_realloc(weight, size); } } assert(i > 0); break; } return i; } void free_weight() { if (weight != NULL) _d_free(weight); } u64 init_data() { qmax = 0; data = darr(0, sym_t); forline (buf, NULL) { u32 ntok = 0; fortok (tok, buf) { sym_t q = str2sym(tok, true); if (q > qmax) qmax = q; size_t lendata = len(data); val(data, lendata, sym_t) = q; if(strcmp(tok, NULLFEATMARKER) == 0) NULLFEATID = q; ntok++; } if(NTOK == 0) NTOK = ntok; assert(ntok == NTOK); //Each line has equal number of tokens } assert(NTOK > 0); update_cnt = _d_malloc(NTOK * sizeof(ptr_t)); cnt = _d_malloc(NTOK * sizeof(ptr_t)); vec = _d_malloc(NTOK * sizeof(ptr_t)); best_vec = _d_malloc(NTOK * sizeof(ptr_t)); dummy_vec = svec_alloc(NDIM); svec_zero(dummy_vec); uweight = _d_calloc(NTOK, sizeof(double)); for (u32 i = 0; i < NTOK; i++) { update_cnt[i] = _d_calloc(qmax+1, sizeof(u64)); cnt[i] = _d_calloc(qmax+1, sizeof(u64)); vec[i] = _d_calloc(qmax+1, sizeof(svec)); best_vec[i] = _d_calloc(qmax+1, sizeof(svec)); } u64 N = len(data) / NTOK; for (u64 i = 0; i < N; i++) { sym_t *p = &val(data, i * NTOK, sym_t); for (u32 j = 0; j < NTOK; j++) { sym_t k = p[j]; assert(k <= qmax); cnt[j][k]++; if(k == NULLFEATID){ vec[j][k] = best_vec[j][k] = NULL; } else if (vec[j][k] == NULL) { vec[j][k] = svec_alloc(NDIM); best_vec[j][k] = svec_alloc(NDIM); } } } return N; } void free_data() { for (u32 i = 0; i < NTOK; i++) { for (sym_t j = 0; j <= qmax; j++) { if (vec[i][j] != NULL) { svec_free(vec[i][j]); svec_free(best_vec[i][j]); } } _d_free(best_vec[i]); _d_free(vec[i]); _d_free(cnt[i]); _d_free(update_cnt[i]); } _d_free(uweight); svec_free(dummy_vec); _d_free(best_vec); _d_free(vec); _d_free(cnt); _d_free(update_cnt); darr_free(data); } void randomize_vectors() { for (u32 j = 0; j < NTOK; j++) { for (sym_t q = 1; q <= qmax; q++) { if (vec[j][q] != NULL) { svec_randomize(vec[j][q]); update_cnt[j][q] = 0; } } } } void copy_best_vec() { for (u32 j = 0; j < NTOK; j++) { for (sym_t q = 1; q <= qmax; q++) { if (vec[j][q] != NULL) { svec_memcpy(best_vec[j][q], vec[j][q]); } } } } void init_rng() { gsl_rng_env_setup(); rng_T = gsl_rng_mt19937; rng_R = gsl_rng_alloc(rng_T); } void free_rng() { gsl_rng_free(rng_R); }
{ "alphanum_fraction": 0.5529003053, "avg_line_length": 26.6078431373, "ext": "c", "hexsha": "41d31075531fed357b24d59f99d7ef19f179fe5f", "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": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ai-ku/scode", "max_forks_repo_path": "scode.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4", "max_issues_repo_issues_event_max_datetime": "2015-02-03T17:43:04.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-06T18:20:04.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ai-ku/scode", "max_issues_repo_path": "scode.c", "max_line_length": 76, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ai-ku/scode", "max_stars_repo_path": "scode.c", "max_stars_repo_stars_event_max_datetime": "2016-07-21T18:29:03.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T16:46:05.000Z", "num_tokens": 3362, "size": 9499 }
#include <stdio.h> #include <stdlib.h> #include <cblas.h> #include "utils.h" int main() { int success_flag = 1; char * data_path = "../Test_Data/linear.csv"; int cols = column_count(data_path); int rows = row_count(data_path) - 1; double data[rows][cols]; int success = read_data(data_path, rows, cols, data); if(success != 0){ return 1; } double *x = (double *) malloc(sizeof(double)*rows); double *y = (double *) malloc(sizeof(double)*rows); fetch_column(x, data, 1, rows, cols); fetch_column(y, data, 2, rows, cols); double xTx[rows]; /* optimization: reuse x as read from data, dont read for each vector used */ cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 1, 1, rows, 1, x, rows, x, rows, 0.0, xTx, 1 ); double xTy[rows]; cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, 1, 1, rows, 1, x, rows, y, rows, 0.0, xTy, 1 ); printf("C: %.30f\n", xTx[0]); printf("C: %.30f\n", xTy[0]); free(x); free(y); return success_flag; }
{ "alphanum_fraction": 0.6101532567, "avg_line_length": 25.4634146341, "ext": "c", "hexsha": "4e7e478b78258b2f5076ae8f568fb7af0ba3ce76", "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": "e7eaed520a3a0e717534a1f8e2f7cf7c371295b1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "looyclark/code_sandbox", "max_forks_repo_path": "C/OLS/src/main.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e7eaed520a3a0e717534a1f8e2f7cf7c371295b1", "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": "looyclark/code_sandbox", "max_issues_repo_path": "C/OLS/src/main.c", "max_line_length": 104, "max_stars_count": null, "max_stars_repo_head_hexsha": "e7eaed520a3a0e717534a1f8e2f7cf7c371295b1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "looyclark/code_sandbox", "max_stars_repo_path": "C/OLS/src/main.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 337, "size": 1044 }
#include "uavsar.h" #include "asf_meta.h" #include "asf_endian.h" #include <ctype.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multiroots.h> #define SQR(x) (x*x) #define FLOAT_COMPARE_TOLERANCE(a, b, t) (fabs (a - b) <= t ? 1: 0) #define ASF_EXPORT_FLOAT_MICRON 0.000000001 #define FLOAT_EQUIVALENT(a, b) (FLOAT_COMPARE_TOLERANCE \ (a, b, ASF_EXPORT_FLOAT_MICRON)) #define MAX_LINE 512 char **get_uavsar_products(const char *data_type, char *type, int *num_product) { char *rest, *token; int ii, product_count; char *tmp = (char *) MALLOC(sizeof(char)*60); strcpy(tmp, data_type); if (strcmp_case(type, "POLSAR") == 0) { product_count = 5; if (strcmp_case(tmp, "ALL") == 0) sprintf(tmp, "SLC,MLC,DAT,GRD,HGT"); } else if (strcmp_case(type, "INSAR") == 0) { product_count = 9; if (strcmp_case(tmp, "ALL") == 0) sprintf(tmp, "AMP,INT,UNW,COR,AMP_GRD,INT_GRD,UNW_GRD,COR_GRD,HGT_GRD"); } char **product = (char **) MALLOC(sizeof(char*) * product_count); for (ii = 0; ii < product_count; ii++) { product[ii] = (char *) MALLOC(sizeof(char)*10); strcpy(product[ii], ""); } ii = 0; while ((token = strtok_r(tmp, ",", &rest))) { strcpy(product[ii], token); tmp = rest; ii++; } *num_product = ii; return product; } int parse_annotation_line(char *line, char *key, char *value) { char *ks = line, *ke = line, *vs = line, *ve = line, *b = line; while(isspace(*b)) ks = ++b; // Move forward past the whitespace to the beginning of the key if(*b == ';' || *b == '\0') { // This line has nothing interesting, return nothing *key = *value = '\0'; return 1; } while(*b != '(' && *b != '\0' && *b != '=') ++b; // Advance to a delimiter; either an equals sign, a '(' (to denote the beginning of the unit specification) or the end of the line if(*b == '\0') return 0; // Unexpected end-of-line ke = b - 1; while(isspace(*ke)) --ke; // Back up until we hit the end of the key while(*b != '\0' && *b != '=') b++; // Advance to the equals sign if(*b == '\0') return 0; // Unexpected end-of-line b++; while(isspace(*b) && *b != '\0') b++; // Move forward past the whitespace to the beginning of the value if(*b == '\0') return 0; // Unexpected end-of-line vs = b++; while(*b != ';' && *b != '\0') ++b; // Move forward to the end of the line or the beginning of a comment ve = b - 1; while(isspace(*ve)) --ve; // Back up until we hit the end of the key strncpy(key, ks, ke - ks + 1); key[ke-ks+1] = '\0'; strncpy(value, vs, ve - vs + 1); value[ve-vs+1] = '\0'; return 1; } int check_file(const char *path, char *line, char **fileName) { char *p, *r; p = strchr(line, '='); char *file = (char *) MALLOC(sizeof(char)*255); strcpy(file, p+1); r = strchr(file, ';'); if (r) r[0] = '\0'; *fileName = MALLOC(sizeof(char)*(strlen(path) + strlen(file) + 32)); strcpy(*fileName, path); char *trimmed_file = trim_spaces(file); strcat(*fileName, trimmed_file); FREE(file); FREE(trimmed_file); p = strchr(line, ';'); long long size; sscanf(p+12, "%lld", &size); if (fileExists(*fileName) && fileSize(*fileName) == size) return TRUE; else return FALSE; } void get_uavsar_file_names(const char *dataFile, uavsar_type_t type, char ***pDataName, char ***pElement, int **pDataType, int *nBands) { int ii, slc = 0, mlc = 0, dat = 0, grd = 0, hgt = 0; int igram = 0, unw = 0, cor = 0, amp = 0; int igram_grd = 0, unw_grd = 0, cor_grd = 0, amp_grd = 0, hgt_grd = 0; char *file = (char *) MALLOC(sizeof(char) * 1024); char **dataName = (char **) MALLOC(6 * sizeof(char *)); char **element = (char **) MALLOC(6 * sizeof(char *)); int *dataType = (int *) MALLOC(6 * sizeof(int)); for (ii = 0; ii < 6; ii++) { dataName[ii] = (char *) MALLOC(sizeof(char) * 512); element[ii] = (char *) MALLOC(sizeof(char) * 10); } *pDataName = dataName; *pElement = element; *pDataType = dataType; *nBands = 0; char *path = get_dirname(dataFile); char line[MAX_LINE], key[MAX_LINE], value[MAX_LINE]; FILE *fp = FOPEN(dataFile, "r"); while (fgets(line, MAX_LINE, fp)) { if(!parse_annotation_line(line, key, value)) { asfPrintWarning("Unable to parse line in annotation file: %s", line); continue; } if (!strcmp(key, "")) continue; if (type == POLSAR_SLC) { if (!strcmp(key, "slcHH")) { if (check_file(path, line, &file)) { strcpy(dataName[slc], file); strcpy(element[slc], "HH"); dataType[slc] = 1; slc++; } } else if (!strcmp(key, "slcHV")) { if (check_file(path, line, &file)) { strcpy(dataName[slc], file); strcpy(element[slc], "HV"); dataType[slc] = 1; slc++; } } else if (!strcmp(key, "slcVH")) { if (check_file(path, line, &file)) { strcpy(dataName[slc], file); strcpy(element[slc], "VH"); dataType[slc] = 1; slc++; } } else if (!strcmp(key, "slcVV")) { if (check_file(path, line, &file)) { strcpy(dataName[slc], file); strcpy(element[slc], "VV"); dataType[slc] = 1; slc++; } } *nBands = slc; } else if (type == POLSAR_MLC) { if (!strcmp(key, "mlcHHHH")) { if (check_file(path, line, &file)) { strcpy(dataName[mlc], file); strcpy(element[mlc], "C11"); dataType[mlc] = 0; mlc++; } } else if (!strcmp(key, "mlcHVHV")) { if (check_file(path, line, &file)) { strcpy(dataName[mlc], file); strcpy(element[mlc], "C22"); dataType[mlc] = 0; mlc++; } } else if (!strcmp(key, "mlcVVVV")) { if (check_file(path, line, &file)) { strcpy(dataName[mlc], file); strcpy(element[mlc], "C33"); dataType[mlc] = 0; mlc++; } } else if (!strcmp(key, "mlcHHHV")) { if (check_file(path, line, &file)) { strcpy(dataName[mlc], file); strcpy(element[mlc], "C12"); dataType[mlc] = 1; mlc++; } } else if (!strcmp(key, "mlcHHVV")) { if (check_file(path, line, &file)) { strcpy(dataName[mlc], file); strcpy(element[mlc], "C13"); dataType[mlc] = 1; mlc++; } } else if (!strcmp(key, "mlcHVVV")) { if (check_file(path, line, &file)) { strcpy(dataName[mlc], file); strcpy(element[mlc], "C23"); dataType[mlc] = 1; mlc++; } } *nBands = mlc; } else if (type == POLSAR_DAT) { if (!strcmp(key, "dat")) { if (check_file(path, line, &file)) { strcpy(dataName[dat], file); dat++; } } *nBands = dat; } else if (type == POLSAR_GRD) { if (!strcmp(key, "grdHHHH")) { if (check_file(path, line, &file)) { strcpy(dataName[grd], file); strcpy(element[grd], "C11"); dataType[grd] = 0; grd++; } } else if (!strcmp(key, "grdHVHV")) { if (check_file(path, line, &file)) { strcpy(dataName[grd], file); strcpy(element[grd], "C22"); dataType[grd] = 0; grd++; } } else if (!strcmp(key, "grdVVVV")) { if (check_file(path, line, &file)) { strcpy(dataName[grd], file); strcpy(element[grd], "C33"); dataType[grd] = 0; grd++; } } else if (!strcmp(key, "grdHHHV")) { if (check_file(path, line, &file)) { strcpy(dataName[grd], file); strcpy(element[grd], "C12"); dataType[grd] = 1; grd++; } } else if (!strcmp(key, "grdHHVV")) { if (check_file(path, line, &file)) { strcpy(dataName[grd], file); strcpy(element[grd], "C13"); dataType[grd] = 1; grd++; } } else if (!strcmp(key, "grdHVVV")) { if (check_file(path, line, &file)) { strcpy(dataName[grd], file); strcpy(element[grd], "C23"); dataType[grd] = 1; grd++; } } *nBands = grd; } else if (type == POLSAR_HGT) { if (!strcmp(key, "hgt")) { if (check_file(path, line, &file)) { strcpy(dataName[hgt], file); strcpy(element[hgt], "HH"); dataType[hgt] = 0; hgt++; } } *nBands = hgt; } else if (type == INSAR_AMP) { if (!strcmp(key, "Slant Range Amplitude of Pass 1")) { if (check_file(path, line, &file)) { strcpy(dataName[amp], file); strcpy(element[amp], "HH"); dataType[amp] = 0; amp++; } } else if (!strcmp(key, "Slant Range Amplitude of Pass 2")) { if (check_file(path, line, &file)) { strcpy(dataName[amp], file); strcpy(element[amp], "HH"); dataType[amp] = 0; amp++; } } *nBands = amp; } else if (type == INSAR_AMP_GRD) { if (!strcmp(key, "Ground Range Amplitude of Pass 1")) { if (check_file(path, line, &file)) { strcpy(dataName[amp_grd], file); strcpy(element[amp_grd], "HH"); dataType[amp_grd] = 0; amp_grd++; } } else if (!strcmp(key, "Ground Range Amplitude of Pass 2")) { if (check_file(path, line, &file)) { strcpy(dataName[amp_grd], file); strcpy(element[amp_grd], "HH"); dataType[amp_grd] = 0; amp_grd++; } } *nBands = amp_grd; } else if (type == INSAR_INT) { if (!strcmp(key, "Slant Range Interferogram")) { if (check_file(path, line, &file)) { strcpy(dataName[igram], file); strcpy(element[igram], "HH"); dataType[igram] = 1; igram++; } } *nBands = igram; } else if (type == INSAR_INT_GRD) { if (!strcmp(key, "Ground Range Interferogram")) { if (check_file(path, line, &file)) { strcpy(dataName[igram_grd], file); strcpy(element[igram_grd], "HH"); dataType[igram_grd] = 1; igram_grd++; } } *nBands = igram_grd; } else if (type == INSAR_UNW) { if (!strcmp(key, "Slant Range Unwrapped Phase")) { if (check_file(path, line, &file)) { strcpy(dataName[unw], file); strcpy(element[unw], "HH"); dataType[unw] = 0; unw++; } } *nBands = unw; } else if (type == INSAR_UNW_GRD) { if (!strcmp(key, "Ground Range Unwrapped Phase")) { if (check_file(path, line, &file)) { strcpy(dataName[unw_grd], file); strcpy(element[unw_grd], "HH"); dataType[unw_grd] = 0; unw_grd++; } } *nBands = unw_grd; } else if (type == INSAR_COR) { if (!strcmp(key, "Slant Range Correlation")) { if (check_file(path, line, &file)) { strcpy(dataName[cor], file); strcpy(element[cor], "HH"); dataType[cor] = 0; cor++; } } *nBands = cor; } else if (type == INSAR_COR_GRD) { if (!strcmp(key, "Ground Range Correlation")) { if (check_file(path, line, &file)) { strcpy(dataName[cor_grd], file); strcpy(element[cor_grd], "HH"); dataType[cor_grd] = 0; cor_grd++; } } *nBands = cor_grd; } else if (type == INSAR_HGT_GRD) { if (!strcmp(key, "DEM Used in Ground Projection")) { if (check_file(path, line, &file)) { strcpy(dataName[hgt_grd], file); strcpy(element[hgt_grd], "HH"); dataType[hgt_grd] = 0; hgt_grd++; } } *nBands = hgt_grd; } } FCLOSE(fp); FREE(file); } uavsar_polsar * read_uavsar_polsar_params(const char *dataFile, uavsar_type_t type) { uavsar_polsar *params = (uavsar_polsar *) MALLOC(sizeof(uavsar_polsar)); // Determine ID char *dirName = (char *) MALLOC(sizeof(char) * 1024); char *fileName = (char *) MALLOC(sizeof(char) * 1024); split_dir_and_file(dataFile, dirName, fileName); sprintf(params->id, "%s", stripExt(fileName)); // Read annotation file char line[MAX_LINE], key[MAX_LINE], value[MAX_LINE]; FILE *fp = FOPEN(dataFile, "r"); while (fgets(line, MAX_LINE, fp)) { if(!parse_annotation_line(line, key, value)) { asfPrintWarning("Unable to parse line in annotation file: %s", line); continue; } if (!strcmp(key, "")) continue; if (!strcmp(key, "Site Description")) strcpy(params->site, value); if (!strcmp(key, "Acquisition Mode")) strcpy(params->acquisition_mode, value); if (type == POLSAR_SLC) { params->type = POLSAR_SLC; if (!strcmp(key, "slc_mag.set_rows")) params->row_count = atoi(value); else if (!strcmp(key, "slc_mag.set_cols")) params->column_count = atoi(value); else if (!strcmp(key, "slc_mag.set_proj")) strcpy(params->projection, value); else if (!strcmp(key, "slc_mag.row_addr")) params->along_track_offset = atof(value); else if (!strcmp(key, "slc_mag.col_addr")) params->cross_track_offset = atof(value); else if (!strcmp(key, "slc_mag.row_mult")) params->azimuth_pixel_spacing = atof(value); else if (!strcmp(key, "slc_mag.col_mult")) params->range_pixel_spacing = atof(value); else if (!strcmp(key, "slc_mag.val_size")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "slc_mag.val_frmt")) strcpy(params->value_format, value); params->range_look_count = 1; params->azimuth_look_count = 1; if (!strcmp(key, "SLC Data Units")) strcpy(params->data_units, value); } else if (type == POLSAR_MLC) { params->type = POLSAR_MLC; if (!strcmp(key, "mlc_pwr.set_rows")) params->row_count = atoi(value); else if (!strcmp(key, "mlc_pwr.set_cols")) params->column_count = atoi(value); else if (!strcmp(key, "mlc_pwr.set_proj")) strcpy(params->projection, value); else if (!strcmp(key, "mlc_pwr.row_addr")) params->along_track_offset = atof(value); else if (!strcmp(key, "mlc_pwr.col_addr")) params->cross_track_offset = atof(value); else if (!strcmp(key, "mlc_pwr.row_mult")) params->azimuth_pixel_spacing = atof(value); else if (!strcmp(key, "mlc_pwr.col_mult")) params->range_pixel_spacing = atof(value); else if (!strcmp(key, "mlc_pwr.val_size")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "mlc_pwr.val_frmt")) strcpy(params->value_format, value); else if (!strcmp(key, "Number of Range Looks in MLC")) params->range_look_count = atoi(value); else if (!strcmp(key, "Number of Azimuth Looks in MLC")) params->azimuth_look_count = atoi(value); else if (!strcmp(key, "MLC Data Units")) strcpy(params->data_units, value); params->range_look_count = 1; params->azimuth_look_count = 1; } else if (type == POLSAR_DAT) { params->type = POLSAR_DAT; if (!strcmp(key, "dat.set_rows")) params->row_count = atoi(value); else if (!strcmp(key, "dat.set_cols")) params->column_count = atoi(value); else if (!strcmp(key, "dat.set_proj")) strcpy(params->projection, value); else if (!strcmp(key, "dat.row_addr")) params->along_track_offset = atof(value); else if (!strcmp(key, "dat.col_addr")) params->cross_track_offset = atof(value); else if (!strcmp(key, "dat.row_mult")) params->azimuth_pixel_spacing = atof(value); else if (!strcmp(key, "dat.col_mult")) params->range_pixel_spacing = atof(value); else if (!strcmp(key, "dat.val_size")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "dat.val_frmt")) strcpy(params->value_format, value); params->range_look_count = 1; params->azimuth_look_count = 1; strcpy(params->data_units, MAGIC_UNSET_STRING); } else if (type == POLSAR_GRD) { params->type = POLSAR_GRD; if (!strcmp(key, "grd_pwr.set_rows")) params->row_count = atoi(value); else if (!strcmp(key, "grd_pwr.set_cols")) params->column_count = atoi(value); else if (!strcmp(key, "grd_pwr.set_proj")) strcpy(params->projection, value); else if (!strcmp(key, "grd_pwr.row_addr")) params->along_track_offset = atof(value); else if (!strcmp(key, "grd_pwr.col_addr")) params->cross_track_offset = atof(value); else if (!strcmp(key, "grd_pwr.row_mult")) params->azimuth_pixel_spacing = atof(value); else if (!strcmp(key, "grd_pwr.col_mult")) params->range_pixel_spacing = atof(value); else if (!strcmp(key, "grd_pwr.val_size")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "grd_pwr.val_frmt")) strcpy(params->value_format, value); else if (!strcmp(key, "Number of Range Looks in MLC")) params->range_look_count = atoi(value); else if (!strcmp(key, "Number of Azimuth Looks in MLC")) params->azimuth_look_count = atoi(value); else if (!strcmp(key, "GRD Data Units")) strcpy(params->data_units, value); } else if (type == POLSAR_HGT) { params->type = POLSAR_HGT; if (!strcmp(key, "hgt.set_rows")) params->row_count = atoi(value); else if (!strcmp(key, "hgt.set_cols")) params->column_count = atoi(value); else if (!strcmp(key, "hgt.set_proj")) strcpy(params->projection, value); else if (!strcmp(key, "hgt.row_addr")) params->along_track_offset = atof(value); else if (!strcmp(key, "hgt.col_addr")) params->cross_track_offset = atof(value); else if (!strcmp(key, "hgt.row_mult")) params->azimuth_pixel_spacing = atof(value); else if (!strcmp(key, "hgt.col_mult")) params->range_pixel_spacing = atof(value); else if (!strcmp(key, "hgt.val_size")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "hgt.val_frmt")) strcpy(params->value_format, value); params->range_look_count = 1; params->azimuth_look_count = 1; if (!strcmp(key, "HGT Data Units")) strcpy(params->data_units, value); } if (!strcmp(key, "set_hddr")) params->header_bytes = atoi(value); else if (!strcmp(key, "set_tail")) params->tail_bytes = atoi(value); else if (!strcmp(key, "set_plat")) params->lat_peg_point = atof(value); else if (!strcmp(key, "set_plon")) params->lon_peg_point = atof(value); else if (!strcmp(key, "set_phdg")) params->head_peg_point = atof(value); else if (!strcmp(key, "val_endi")) strcpy(params->endianess, value); else if (!strcmp(key, "val_mult")) params->data_scale = atof(value); else if (!strcmp(key, "val_addr")) params->data_shift = atof(value); else if (!strcmp(key, "val_minv")) params->min_value = atof(value); else if (!strcmp(key, "val_maxv")) params->max_value = atof(value); else if (!strcmp(key, "Center Wavelength")) params->wavelength = atof(value); else if (!strcmp(key, "Ellipsoid Semi-major Axis")) params->semi_major = atof(value); else if (!strcmp(key, "Ellipsoid Eccentricity Squared")) params->eccentricity = atof(value); else if (!strcmp(key, "Look Direction")) strcpy(params->look_direction, value); else if (!strcmp(key, "Range Spacing per Bin")) params->range_spacing = atof(value); else if (!strcmp(key, "Azimuth Spacing")) params->azimuth_spacing = atof(value); else if (!strcmp(key, "Image Starting Range")) params->slant_range_first_pixel = atof(value); else if (!strcmp(key, "Global Average Yaw")) params->yaw = atof(value); else if (!strcmp(key, "Global Average Pitch")) params->pitch = atof(value); else if (!strcmp(key, "Global Average Roll")) params->roll = atof(value); else if (!strcmp(key, "Global Average Altitude")) params->altitude = atof(value); else if (!strcmp(key, "Average GPS Altitude")) params->altitude = atof(value); else if (!strcmp(key, "Global Average Terrain Height")) params->terrain_height = atof(value); else if (!strcmp(key, "Global Average Squint Angle")) params->squint_angle = atof(value); else if (!strcmp(key, "Pulse Length")) params->pulse_length = atof(value); else if (!strcmp(key, "Steering Angle")) params->steering_angle = atof(value); else if (!strcmp(key, "Bandwidth")) params->bandwidth = atof(value); else if (!strcmp(key, "Approximate Upper Left Latitude")) params->lat_upper_left = atof(value); else if (!strcmp(key, "Approximate Upper Left Longitude")) params->lon_upper_left = atof(value); else if (!strcmp(key, "Approximate Upper Right Latitude")) params->lat_upper_right = atof(value); else if (!strcmp(key, "Approximate Upper Right Longitude")) params->lon_upper_right = atof(value); else if (!strcmp(key, "Approximate Lower Left Latitude")) params->lat_lower_left = atof(value); else if (!strcmp(key, "Approximate Lower Left Longitude")) params->lon_lower_left = atof(value); else if (!strcmp(key, "Approximate Lower Right Latitude")) params->lat_lower_right = atof(value); else if (!strcmp(key, "Approximate Lower Right Longitude")) params->lon_lower_right = atof(value); else if (!strcmp(key, "Date of Acquisition")) strcpy(params->acquisition_date, value); else if (!strcmp(key, "Processor Version Number")) strcpy(params->processor, value); } FCLOSE(fp); return params; } uavsar_insar * read_uavsar_insar_params(const char *dataFile, uavsar_type_t type) { uavsar_insar *params = (uavsar_insar *) MALLOC(sizeof(uavsar_insar)); char time1[50], time2[50]; // Determine ID char *dirName = (char *) MALLOC(sizeof(char) * 1024); char *fileName = (char *) MALLOC(sizeof(char) * 1024); split_dir_and_file(dataFile, dirName, fileName); sprintf(params->id, "%s", stripExt(fileName)); // Read annotation file char line[MAX_LINE], key[MAX_LINE], value[MAX_LINE]; FILE *fp = FOPEN(dataFile, "r"); while (fgets(line, MAX_LINE, fp)) { if(!parse_annotation_line(line, key, value)) { asfPrintWarning("Unable to parse line in annotation file: %s", line); continue; } if(!strcmp(key, "")) continue; if (!strcmp(key, "Site Description")) strcpy(params->site, value); if (!strcmp(key, "Processing Mode")) strcpy(params->processing_mode, value); if (!strcmp(key, "Polarization")) strcpy(params->polarization, value); if (!strcmp(key, "Number of Looks in Range")) params->range_look_count = atoi(value); if (!strcmp(key, "Number of Looks in Azimuth")) params->azimuth_look_count = atoi(value); if (type == INSAR_INT) { params->type = INSAR_INT; if (!strcmp(key, "Interferogram Bytes Per Pixel")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "Interferogram Pixel Format")) strcpy(params->value_format, value); else if (!strcmp(key, "Interferogram Units")) strcpy(params->data_units, value); } else if (type == INSAR_UNW) { params->type = INSAR_UNW; if (!strcmp(key, "Unwrapped Phase Bytes Per Pixel")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "Unwrapped Phase Pixel Format")) strcpy(params->value_format, value); else if (!strcmp(key, "Unwrapped Phase Units")) strcpy(params->data_units, value); } else if (type == INSAR_COR) { params->type = INSAR_COR; if (!strcmp(key, "Correlation Bytes Per Pixel")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "Correlation Pixel Format")) strcpy(params->value_format, value); else if (!strcmp(key, "Correlation Units")) strcpy(params->data_units, value); } else if (type == INSAR_AMP) { params->type = INSAR_AMP; if (!strcmp(key, "Amplitude Bytes Per Pixel")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "Amplitude Pixel Format")) strcpy(params->value_format, value); else if (!strcmp(key, "Amplitude Units")) strcpy(params->data_units, value); } if (type >= INSAR_AMP && type <= INSAR_COR) { if (!strcmp(key, "Slant Range Data Azimuth Lines")) params->row_count = atoi(value); else if (!strcmp(key, "Slant Range Data Range Samples")) params->column_count = atoi(value); else if (!strcmp(key, "slt.set_proj")) strcpy(params->projection, value); else if (!strcmp(key, "slt.row_addr")) params->along_track_offset = atof(value); else if (!strcmp(key, "slt.col_addr")) params->cross_track_offset = atof(value); else if (!strcmp(key, "Slant Range Data at Near Range")) { params->slant_range_first_pixel = atof(value); params->slant_range_first_pixel /= 1000.0; } else if (!strcmp(key, "Slant Range Data Azimuth Spacing")) params->azimuth_pixel_spacing = atof(value); else if (!strcmp(key, "Slant Range Data Range Spacing")) params->range_pixel_spacing = atof(value); } else if (type >= INSAR_AMP_GRD && type <= INSAR_HGT_GRD) { if (!strcmp(key, "Ground Range Data Latitude Lines")) params->row_count = atoi(value); else if (!strcmp(key, "Ground Range Data Longitude Samples")) params->column_count = atoi(value); else if (!strcmp(key, "grd.set_proj")) strcpy(params->projection, value); else if (!strcmp(key, "grd.row_addr")) params->along_track_offset = atof(value); else if (!strcmp(key, "grd.col_addr")) params->cross_track_offset = atof(value); else if (!strcmp(key, "Ground Range Data Latitude Spacing")) params->azimuth_pixel_spacing = atof(value); else if (!strcmp(key, "Ground Range Data Longitude Spacing")) params->range_pixel_spacing = atof(value); } if (type == INSAR_INT_GRD) { params->type = INSAR_INT_GRD; if (!strcmp(key, "Interferogram Bytes Per Pixel")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "Interferogram Pixel Format")) strcpy(params->value_format, value); else if (!strcmp(key, "Interferogram Units")) strcpy(params->data_units, value); } else if (type == INSAR_UNW_GRD) { params->type = INSAR_UNW_GRD; if (!strcmp(key, "Unwrapped Phase Bytes Per Pixel")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "Unwrapped Phase Pixel Format")) strcpy(params->value_format, value); else if (!strcmp(key, "Unwrapped Phase Units")) strcpy(params->data_units, value); } else if (type == INSAR_COR_GRD) { params->type = INSAR_COR_GRD; if (!strcmp(key, "Correlation Bytes Per Pixel")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "Correlation Pixel Format")) strcpy(params->value_format, value); else if (!strcmp(key, "Correlation Units")) strcpy(params->data_units, value); } else if (type == INSAR_AMP_GRD) { params->type = INSAR_AMP_GRD; if (!strcmp(key, "Amplitude Bytes Per Pixel")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "Amplitude Pixel Format")) strcpy(params->value_format, value); else if (!strcmp(key, "Amplitude Units")) strcpy(params->data_units, value); } else if (type == INSAR_HGT_GRD) { params->type = INSAR_HGT_GRD; if (!strcmp(key, "DEM Bytes Per Pixel")) params->bytes_per_pixel = atoi(value); else if (!strcmp(key, "DEM Pixel Format")) strcpy(params->value_format, value); else if (!strcmp(key, "DEM Units")) strcpy(params->data_units, value); } if (!strcmp(key, "set_hddr")) params->header_bytes = atoi(value); else if (!strcmp(key, "set_tail")) params->tail_bytes = atoi(value); else if (!strcmp(key, "set_plat")) params->lat_peg_point = atof(value); else if (!strcmp(key, "set_plon")) params->lon_peg_point = atof(value); else if (!strcmp(key, "set_phdg")) params->head_peg_point = atof(value); else if (!strcmp(key, "val_endi")) strcpy(params->endianess, value); else if (!strcmp(key, "val_mult")) params->data_scale = atof(value); else if (!strcmp(key, "val_addr")) params->data_shift = atof(value); else if (!strcmp(key, "val_minv")) params->min_value = atof(value); else if (!strcmp(key, "val_maxv")) params->max_value = atof(value); else if (!strcmp(key, "Center Wavelength")) params->wavelength = atof(value); else if (!strcmp(key, "Ellipsoid Semi-major Axis")) params->semi_major = atof(value); else if (!strcmp(key, "Ellipsoid Eccentricity Squared")) params->eccentricity = atof(value); else if (!strcmp(key, "Look Direction")) strcpy(params->look_direction, value); else if (!strcmp(key, "Range Spacing per Bin")) params->range_spacing = atof(value); else if (!strcmp(key, "Azimuth Spacing")) params->azimuth_spacing = atof(value); else if (!strcmp(key, "Image Starting Range")) params->slant_range_first_pixel = atof(value); else if (!strcmp(key, "Global Average Yaw")) params->yaw = atof(value); else if (!strcmp(key, "Global Average Pitch")) params->pitch = atof(value); else if (!strcmp(key, "Global Average Roll")) params->roll = atof(value); else if (!strcmp(key, "Global Average Altitude")) params->altitude = atof(value); else if (!strcmp(key, "Average GPS Altitude")) params->altitude = atof(value); else if (!strcmp(key, "Global Average Terrain Height")) params->terrain_height = atof(value); else if (!strcmp(key, "Global Average Squint Angle")) params->squint_angle = atof(value); else if (!strcmp(key, "Pulse Length")) params->pulse_length = atof(value); else if (!strcmp(key, "Steering Angle")) params->steering_angle = atof(value); else if (!strcmp(key, "Bandwidth")) params->bandwidth = atof(value); else if (!strcmp(key, "Approximate Upper Left Latitude")) { if (strcmp_case(value, "N/A") == 0) params->lat_upper_left = MAGIC_UNSET_DOUBLE; else params->lat_upper_left = atof(value); } else if (!strcmp(key, "Approximate Upper Left Longitude")) { if (strcmp_case(value, "N/A") == 0) params->lon_upper_left = MAGIC_UNSET_DOUBLE; else params->lon_upper_left = atof(value); } else if (!strcmp(key, "Approximate Upper Right Latitude")) { if (strcmp_case(value, "N/A") == 0) params->lat_upper_right = MAGIC_UNSET_DOUBLE; else params->lat_upper_right = atof(value); } else if (!strcmp(key, "Approximate Upper Right Longitude")) { if (strcmp_case(value, "N/A") == 0) params->lon_upper_right = MAGIC_UNSET_DOUBLE; else params->lon_upper_right = atof(value); } else if (!strcmp(key, "Approximate Lower Left Latitude")) { if (strcmp_case(value, "N/A") == 0) params->lat_lower_left = MAGIC_UNSET_DOUBLE; else params->lat_lower_left = atof(value); } else if (!strcmp(key, "Approximate Lower Left Longitude")) { if (strcmp_case(value, "N/A") == 0) params->lon_lower_left = MAGIC_UNSET_DOUBLE; else params->lon_lower_left = atof(value); } else if (!strcmp(key, "Approximate Lower Right Latitude")) { if (strcmp_case(value, "N/A") == 0) params->lat_lower_right = MAGIC_UNSET_DOUBLE; else params->lat_lower_right = atof(value); } else if (!strcmp(key, "Approximate Lower Right Longitude")) { if (strcmp_case(value, "N/A") == 0) params->lon_lower_right = MAGIC_UNSET_DOUBLE; else params->lon_lower_right = atof(value); } else if (!strcmp(key, "Time of Acquisition for Pass 1")) strcpy(time1, value); else if (!strcmp(key, "Time of Acquisition for Pass 2")) strcpy(time2, value); else if (!strcmp(key, "Processor Version Number")) strcpy(params->processor, value); } FCLOSE(fp); sprintf(params->acquisition_date, "%s, %s", time1, time2); return params; } int sign(char byteBuf) { if (byteBuf < 0) return -1; else return 1; } char *check_data_type(const char *inFileName) { char line[MAX_LINE], key[MAX_LINE], value[MAX_LINE]; char *type = (char *) MALLOC(sizeof(char)*25); FILE *fp = FOPEN(inFileName, "r"); while (fgets(line, MAX_LINE, fp)) { if(!parse_annotation_line(line, key, value)) { asfPrintWarning("Unable to parse line in annotation file: %s", line); continue; } if (!strcmp(key, "")) continue; if (!strcmp(key, "Acquisition Mode")) strcpy(type, value); else if (!strcmp(key, "Processing Mode")) strcpy(type, value); else if (strcmp_case(type, "RPI") == 0) sprintf(type, "InSAR"); } FCLOSE(fp); return type; } void import_uavsar(const char *inFileName, int line, int sample, int width, int height, radiometry_t radiometry, const char *data_type, const char *outBaseName) { // UAVSAR comes in two flavors: InSAR and PolSAR // Things look similar to AirSAR data, just organized a little different. // There does not seem to be a consistent identifier in the annotation file, // that would allow us to easily identify the data set as UAVSAR. No mention // of UAVSAR whatsoever. // The data can come in a large variety of flavors (single look versus multi- // look, derived magnitude and phase, etc.). I assume we can take anything or // nothing from this menu. The different files have different dimensions, // so we will need to generate several output images to accommodate that. // PolSAR data // slc - Single look complex slant range data // mlc - Multilook cross product slant range data // dat - Compressed Stokes matrix of multilooked data // grd - Ground range projected (equi-rectangular) and multilooked data // hgt - Digital elevation model projected in projection // slc_mag and slc_phase - 8 bytes per pixel derived from slc // mlc_mag and mlc_phase - 8 bytes per pixel derived from mlc // InSAR data // int - Slant range interferogram // unw - Slant range unwrapped phase // cor - Slant range correlation // amp - Slant range amplitudes // int_grd - Ground range interferogram // unw_grd - Ground range unwrapped phase // cor_grd - Ground range correlation // amp_grd - Ground range amplitudes // hgt_grd - Digital elevation model in ground projection FILE *fpIn, *fpOut; int ii, kk, ll, nn, pp, nBands, ns, *dataType, product_count; int multi = FALSE; float *floatAmp, *floatPhase, *floatAmpBuf, *amp, re, im; float *floatComplexReal, *floatComplexImag; float *floatComplexBuf; char **dataName, **element, **product, tmp[50]; char *type; char *outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); uavsar_polsar *polsar_params; uavsar_insar *insar_params; meta_parameters *metaIn, *metaOut; type = check_data_type(inFileName); asfPrintStatus(" Data type: %s\n", type); product = get_uavsar_products(data_type, type, &product_count); if (product_count > 1) multi = TRUE; for (pp = 0; pp < product_count; pp++) { // InSAR data // Ground range interferogram if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "INT_GRD") == 0) { get_uavsar_file_names(inFileName, INSAR_INT_GRD, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Ground range interferogram does not exist. " "Will skip the ingest.\n"); continue; } insar_params = read_uavsar_insar_params(inFileName, INSAR_INT_GRD); metaIn = uavsar_insar2meta(insar_params); metaOut = uavsar_insar2meta(insar_params); ns = metaIn->general->sample_count; nn = 0; floatAmp = (float *) CALLOC(ns, sizeof(float)); floatPhase = (float *) CALLOC(ns, sizeof(float)); floatComplexBuf = (float *) CALLOC(2*ns, sizeof(float)); outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); metaOut->general->band_count = 2; if (multi) outName = appendToBasename(outBaseName, "_int_grd.img"); else outName = appendExt(outBaseName, ".img"); asfPrintStatus("\nGround range interferogram:\n"); fpOut = FOPEN(outName, "wb"); char *filename = get_filename(dataName[nn]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); fpIn = FOPEN(dataName[nn], "rb"); sprintf(metaOut->general->bands, "INTERFEROGRAM_AMP,INTERFEROGRAM_PHASE"); for (ii=0; ii<metaIn->general->line_count; ii++) { metaIn->general->sample_count = 2*ns; get_float_line(fpIn, metaIn, ii, floatComplexBuf); for (kk=0; kk<ns; kk++) { re = floatComplexBuf[kk*2]; im = floatComplexBuf[kk*2+1]; ieee_big32(re); ieee_big32(im); floatAmp[kk] = hypot(re,im); floatPhase[kk] = atan2_check(im,re); } put_band_float_line(fpOut, metaOut, 0, ii, floatAmp); put_band_float_line(fpOut, metaOut, 1, ii, floatPhase); asfLineMeter(ii, metaIn->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); meta_write(metaOut, outName); FREE(floatAmp); FREE(floatPhase); FREE(floatComplexBuf); FREE(outName); meta_free(metaIn); meta_free(metaOut); FREE(insar_params); } // Ground range unwrapped phase if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "UNW_GRD") == 0) { get_uavsar_file_names(inFileName, INSAR_UNW_GRD, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Ground range unwrapped phase does not exist. " "Will skip the ingest.\n"); continue; } insar_params = read_uavsar_insar_params(inFileName, INSAR_UNW_GRD); metaIn = uavsar_insar2meta(insar_params); metaOut = uavsar_insar2meta(insar_params); ns = metaOut->general->sample_count; nn = 0; floatAmpBuf = (float *) MALLOC(sizeof(float)*ns); outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); if (multi) outName = appendToBasename(outBaseName, "_unw_grd.img"); else outName = appendExt(outBaseName, ".img"); asfPrintStatus("\nGround range unwrapped phase:\n"); char *filename = get_filename(dataName[nn]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); fpIn = FOPEN(dataName[nn], "rb"); fpOut = FOPEN(outName, "wb"); strcpy(metaOut->general->bands, "UNWRAPPED_PHASE"); for (ii=0; ii<metaIn->general->line_count; ii++) { get_float_line(fpIn, metaIn, ii, floatAmpBuf); for (kk=0; kk<metaIn->general->sample_count; kk++) ieee_big32(floatAmpBuf[kk]); put_float_line(fpOut, metaOut, ii, floatAmpBuf); asfLineMeter(ii, metaIn->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); meta_write(metaOut, outName); FREE(floatAmpBuf); FREE(outName); meta_free(metaIn); meta_free(metaOut); FREE(insar_params); } // Ground range correlation image if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "COR_GRD") == 0) { get_uavsar_file_names(inFileName, INSAR_COR_GRD, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Ground range correlation image does not exist. " "Will skip the ingest.\n"); continue; } insar_params = read_uavsar_insar_params(inFileName, INSAR_COR_GRD); metaIn = uavsar_insar2meta(insar_params); metaOut = uavsar_insar2meta(insar_params); ns = metaOut->general->sample_count; nn = 0; floatAmpBuf = (float *) MALLOC(sizeof(float)*ns); if (multi) outName = appendToBasename(outBaseName, "_cor_grd.img"); else outName = appendExt(outBaseName, ".img"); asfPrintStatus("\nGround range correlation image:\n"); char *filename = get_filename(dataName[nn]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); fpIn = FOPEN(dataName[nn], "rb"); fpOut = FOPEN(outName, "wb"); strcpy(metaOut->general->bands, "COHERENCE"); for (ii=0; ii<metaIn->general->line_count; ii++) { get_float_line(fpIn, metaIn, ii, floatAmpBuf); for (kk=0; kk<metaIn->general->sample_count; kk++) ieee_big32(floatAmpBuf[kk]); put_float_line(fpOut, metaOut, ii, floatAmpBuf); asfLineMeter(ii, metaIn->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); meta_write(metaOut, outName); FREE(floatAmpBuf); FREE(outName); meta_free(metaIn); meta_free(metaOut); FREE(insar_params); } // Ground range amplitude images if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "AMP_GRD") == 0) { get_uavsar_file_names(inFileName, INSAR_AMP_GRD, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Ground range amplitude images does not exist. " "Will skip the ingest.\n"); continue; } insar_params = read_uavsar_insar_params(inFileName, INSAR_AMP_GRD); metaIn = uavsar_insar2meta(insar_params); metaOut = uavsar_insar2meta(insar_params); metaOut->general->band_count = 2; ns = metaOut->general->sample_count; nn = 0; floatAmpBuf = (float *) MALLOC(sizeof(float)*ns); outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); if (multi) outName = appendToBasename(outBaseName, "_amp_grd.img"); else outName = appendExt(outBaseName, ".img"); fpOut = FOPEN(outName, "wb"); strcpy(metaOut->general->bands, "AMP1,AMP2"); asfPrintStatus("\nGround range amplitude images:\n"); for (nn=0; nn<nBands; nn++) { char *filename = get_filename(dataName[nn]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); fpIn = FOPEN(dataName[nn], "rb"); for (ii=0; ii<metaIn->general->line_count; ii++) { get_float_line(fpIn, metaIn, ii, floatAmpBuf); for (kk=0; kk<metaIn->general->sample_count; kk++) ieee_big32(floatAmpBuf[kk]); put_band_float_line(fpOut, metaOut, nn, ii, floatAmpBuf); asfLineMeter(ii, metaIn->general->line_count); } FCLOSE(fpIn); } FCLOSE(fpOut); meta_write(metaOut, outName); FREE(floatAmpBuf); FREE(outName); meta_free(metaIn); meta_free(metaOut); FREE(insar_params); } // Ground range digital elevation model if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "HGT_GRD") == 0) { get_uavsar_file_names(inFileName, INSAR_HGT_GRD, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Ground range digital elevation model does not exist. " "Will skip the ingest.\n"); continue; } insar_params = read_uavsar_insar_params(inFileName, INSAR_HGT_GRD); metaIn = uavsar_insar2meta(insar_params); metaOut = uavsar_insar2meta(insar_params); ns = metaOut->general->sample_count; nn = 0; floatAmpBuf = (float *) MALLOC(sizeof(float)*ns); outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); if (multi) outName = appendToBasename(outBaseName, "_hgt_grd.img"); else outName = appendExt(outBaseName, ".img"); fpOut = FOPEN(outName, "wb"); strcpy(metaOut->general->bands, "HEIGHT"); asfPrintStatus("\nGround range digital elevation model:\n"); for (nn=0; nn<nBands; nn++) { char *filename = get_filename(dataName[nn]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); fpIn = FOPEN(dataName[nn], "rb"); for (ii=0; ii<metaIn->general->line_count; ii++) { get_float_line(fpIn, metaIn, ii, floatAmpBuf); for (kk=0; kk<metaIn->general->sample_count; kk++) ieee_big32(floatAmpBuf[kk]); put_band_float_line(fpOut, metaOut, nn, ii, floatAmpBuf); asfLineMeter(ii, metaIn->general->line_count); } FCLOSE(fpIn); } FCLOSE(fpOut); meta_write(metaOut, outName); FREE(floatAmpBuf); FREE(outName); meta_free(metaIn); meta_free(metaOut); FREE(insar_params); } // Slant range interferogram if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "INT") == 0) { get_uavsar_file_names(inFileName, INSAR_INT, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Slant range interferogram does not exist. " "Will skip the ingest.\n"); continue; } insar_params = read_uavsar_insar_params(inFileName, INSAR_INT); metaIn = uavsar_insar2meta(insar_params); metaOut = uavsar_insar2meta(insar_params); ns = metaIn->general->sample_count; nn = 0; floatAmp = (float *) CALLOC(ns, sizeof(float)); floatPhase = (float *) CALLOC(ns, sizeof(float)); floatComplexBuf = (float *) CALLOC(2*ns, sizeof(float)); outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); if (multi) outName = appendToBasename(outBaseName, "_int.img"); else outName = appendExt(outBaseName, ".img"); metaOut->general->band_count = 2; if (multi) outName = appendToBasename(outBaseName, "_int.img"); else outName = appendExt(outBaseName, ".img"); asfPrintStatus("\nSlant range interferogram:\n"); fpOut = FOPEN(outName, "wb"); char *filename = get_filename(dataName[nn]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); fpIn = FOPEN(dataName[nn], "rb"); sprintf(metaOut->general->bands, "INTERFEROGRAM_AMP,INTERFEROGRAM_PHASE"); for (ii=0; ii<metaIn->general->line_count; ii++) { metaIn->general->sample_count = 2*ns; get_float_line(fpIn, metaIn, ii, floatComplexBuf); for (kk=0; kk<ns; kk++) { re = floatComplexBuf[kk*2]; im = floatComplexBuf[kk*2+1]; ieee_big32(re); ieee_big32(im); floatAmp[kk] = hypot(re,im); floatPhase[kk] = atan2_check(im,re); } put_band_float_line(fpOut, metaOut, 0, ii, floatAmp); put_band_float_line(fpOut, metaOut, 1, ii, floatPhase); asfLineMeter(ii, metaIn->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); meta_write(metaOut, outName); FREE(floatAmp); FREE(floatPhase); FREE(floatComplexBuf); FREE(outName); meta_free(metaIn); meta_free(metaOut); FREE(insar_params); } // Slant range unwrapped phase if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "UNW") == 0) { get_uavsar_file_names(inFileName, INSAR_UNW, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Slant range unwrapped phase does not exist. " "Will skip the ingest.\n"); continue; } insar_params = read_uavsar_insar_params(inFileName, INSAR_UNW); metaIn = uavsar_insar2meta(insar_params); metaOut = uavsar_insar2meta(insar_params); ns = metaOut->general->sample_count; nn = 0; floatAmpBuf = (float *) MALLOC(sizeof(float)*ns); outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); if (multi) outName = appendToBasename(outBaseName, "_unw.img"); else outName = appendExt(outBaseName, ".img"); asfPrintStatus("\nSlant range unwrapped phase:\n"); char *filename = get_filename(dataName[nn]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); fpIn = FOPEN(dataName[nn], "rb"); fpOut = FOPEN(outName, "wb"); strcpy(metaOut->general->bands, "UNWRAPPED_PHASE"); for (ii=0; ii<metaIn->general->line_count; ii++) { get_float_line(fpIn, metaIn, ii, floatAmpBuf); for (kk=0; kk<metaIn->general->sample_count; kk++) ieee_big32(floatAmpBuf[kk]); put_float_line(fpOut, metaOut, ii, floatAmpBuf); asfLineMeter(ii, metaIn->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); meta_write(metaOut, outName); FREE(floatAmpBuf); FREE(outName); meta_free(metaIn); meta_free(metaOut); FREE(insar_params); } // Slant range correlation image if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "COR") == 0) { get_uavsar_file_names(inFileName, INSAR_COR, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Slant range correlation image does not exist. " "Will skip the ingest.\n"); continue; } insar_params = read_uavsar_insar_params(inFileName, INSAR_COR); metaIn = uavsar_insar2meta(insar_params); metaOut = uavsar_insar2meta(insar_params); ns = metaOut->general->sample_count; nn = 0; floatAmpBuf = (float *) MALLOC(sizeof(float)*ns); outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); if (multi) outName = appendToBasename(outBaseName, "_cor.img"); else outName = appendExt(outBaseName, ".img"); asfPrintStatus("\nSlant range correlation image:\n"); char *filename = get_filename(dataName[nn]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); fpIn = FOPEN(dataName[nn], "rb"); fpOut = FOPEN(outName, "wb"); strcpy(metaOut->general->bands, "COHERENCE"); for (ii=0; ii<metaIn->general->line_count; ii++) { get_float_line(fpIn, metaIn, ii, floatAmpBuf); for (kk=0; kk<metaIn->general->sample_count; kk++) ieee_big32(floatAmpBuf[kk]); put_float_line(fpOut, metaOut, ii, floatAmpBuf); asfLineMeter(ii, metaIn->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); meta_write(metaOut, outName); FREE(floatAmpBuf); FREE(outName); meta_free(metaIn); meta_free(metaOut); FREE(insar_params); } // Slant range amplitude images if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "AMP") == 0) { get_uavsar_file_names(inFileName, INSAR_AMP, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Slant range amplitude images does not exist. " "Will skip the ingest.\n"); continue; } insar_params = read_uavsar_insar_params(inFileName, INSAR_AMP); metaIn = uavsar_insar2meta(insar_params); metaOut = uavsar_insar2meta(insar_params); metaOut->general->band_count = 2; ns = metaOut->general->sample_count; nn = 0; floatAmpBuf = (float *) MALLOC(sizeof(float)*ns); outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); if (multi) outName = appendToBasename(outBaseName, "_amp.img"); else outName = appendExt(outBaseName, ".img"); fpOut = FOPEN(outName, "wb"); strcpy(metaOut->general->bands, "AMP1,AMP2"); asfPrintStatus("\nSlant range amplitude images:\n"); for (nn=0; nn<nBands; nn++) { char *filename = get_filename(dataName[nn]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); fpIn = FOPEN(dataName[nn], "rb"); for (ii=0; ii<metaIn->general->line_count; ii++) { get_float_line(fpIn, metaIn, ii, floatAmpBuf); for (kk=0; kk<metaIn->general->sample_count; kk++) ieee_big32(floatAmpBuf[kk]); put_band_float_line(fpOut, metaOut, nn, ii, floatAmpBuf); asfLineMeter(ii, metaIn->general->line_count); } FCLOSE(fpIn); } FCLOSE(fpOut); meta_write(metaOut, outName); FREE(floatAmpBuf); FREE(outName); meta_free(metaIn); meta_free(metaOut); FREE(insar_params); } // PolSAR data // Single look complex data if (strcmp_case(type, "PolSAR") == 0 && strcmp_case(product[pp], "SLC") == 0) { asfPrintWarning("Ingest of SLC data is currently not supported!\n"); /* get_uavsar_file_names(inFileName, POLSAR_SLC, &dataName, &element, &dataType, &nBands); polsar_params = read_uavsar_polsar_params(inFileName, POLSAR_SLC); metaIn = uavsar_polsar2meta(polsar_params); metaOut = uavsar_polsar2meta(polsar_params); if (multi) outName = appendToBasename(outBaseName, "_slc.img"); else outName = appendExt(outBaseName, ".img"); for (ii=0; ii<nBands; ii++) printf("file: %s\n", dataName[ii]); //meta_write(metaOut, outName); meta_free(metaIn); meta_free(metaOut); FREE(polsar_params); */ } // Multilooked data if (strcmp_case(type, "PolSAR") == 0 && strcmp_case(product[pp], "MLC") == 0) { get_uavsar_file_names(inFileName, POLSAR_MLC, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Slant range multilooked data do not exist. " "Will skip the ingest.\n"); continue; } polsar_params = read_uavsar_polsar_params(inFileName, POLSAR_MLC); metaIn = uavsar_polsar2meta(polsar_params); metaOut = uavsar_polsar2meta(polsar_params); ns = metaIn->general->sample_count; amp = (float *) MALLOC(sizeof(float)*ns); floatAmp = (float *) MALLOC(sizeof(float)*ns); floatAmpBuf = (float *) MALLOC(sizeof(float)*ns); floatComplexReal = (float *) MALLOC(sizeof(float)*ns); floatComplexImag = (float *) MALLOC(sizeof(float)*ns); floatComplexBuf = (float *) MALLOC(sizeof(float)*2*ns); outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); metaOut->general->band_count = ll = 1; if (multi) outName = appendToBasename(outBaseName, "_mlc.img"); else outName = appendExt(outBaseName, ".img"); asfPrintStatus("\nMultilooked data:\n"); fpOut = FOPEN(outName, "wb"); for (nn=0; nn<nBands; nn++) { char *filename = get_filename(dataName[nn]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); if (dataType[nn] == 0) metaOut->general->band_count += 1; else metaOut->general->band_count += 2; fpIn = FOPEN(dataName[nn], "rb"); if (nn == 0) sprintf(metaOut->general->bands, "AMP,%s", element[0]); else { if (dataType[nn]) sprintf(tmp, ",%s_real,%s_imag", element[nn], element[nn]); else sprintf(tmp, ",%s", element[nn]); strcat(metaOut->general->bands, tmp); } for (ii=0; ii<metaIn->general->line_count; ii++) { if (dataType[nn]) { metaIn->general->sample_count = 2*ns; get_float_line(fpIn, metaIn, ii, floatComplexBuf); for (kk=0; kk<ns; kk++) { floatComplexReal[kk] = floatComplexBuf[kk*2]; floatComplexImag[kk] = floatComplexBuf[kk*2+1]; ieee_big32(floatComplexReal[kk]); ieee_big32(floatComplexImag[kk]); } put_band_float_line(fpOut, metaOut, ll, ii, floatComplexReal); put_band_float_line(fpOut, metaOut, ll+1, ii, floatComplexImag); } else { metaIn->general->sample_count = ns; get_float_line(fpIn, metaIn, ii, floatAmpBuf); if (nn == 0) { for (kk=0; kk<ns; kk++) { ieee_big32(floatAmpBuf[kk]); floatAmp[kk] = sqrt(floatAmpBuf[kk]); } } else { for (kk=0; kk<ns; kk++) ieee_big32(floatAmpBuf[kk]); } put_band_float_line(fpOut, metaOut, ll, ii, floatAmpBuf); } asfLineMeter(ii, metaIn->general->line_count); } if (dataType[nn]) ll += 2; else ll++; FCLOSE(fpIn); } FCLOSE(fpOut); meta_write(metaOut, outName); FREE(amp); FREE(floatAmp); FREE(floatAmpBuf); FREE(floatComplexReal); FREE(floatComplexImag); FREE(floatComplexBuf); FREE(outName); meta_free(metaIn); meta_free(metaOut); FREE(polsar_params); } // Compressed Stokes matrix if (strcmp_case(type, "PolSAR") == 0 && strcmp_case(product[pp], "DAT") == 0) { get_uavsar_file_names(inFileName, POLSAR_DAT, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Slant range Stokes matrix does not exist. " "Will skip the ingest.\n"); continue; } polsar_params = read_uavsar_polsar_params(inFileName, POLSAR_DAT); metaIn = uavsar_polsar2meta(polsar_params); metaOut = uavsar_polsar2meta(polsar_params); outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); if (multi) outName = appendToBasename(outBaseName, "_dat.img"); else outName = appendExt(outBaseName, ".img"); metaOut->general->band_count = 9; asfPrintStatus("\nCompressed Stokes matrix:\n"); char *filename = get_filename(dataName[0]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); if (radiometry == r_AMP) strcpy(metaOut->general->bands, "AMP,AMP_HH,PHASE_HH,AMP_HV,PHASE_HV,AMP_VH,PHASE_VH," \ "AMP_VV,PHASE_VV"); else if (radiometry == r_SIGMA) strcpy(metaOut->general->bands, "AMP,SIGMA-AMP-HH,SIGMA-PHASE-HH,SIGMA-AMP-HV,SIGMA-PHASE-HV," \ "SIGMA-AMP-VH,SIGMA-PHASE-VH,SIGMA-AMP-VV,SIGMA-PHASE-VV"); else if (radiometry == r_SIGMA_DB) strcpy(metaOut->general->bands, "AMP,SIGMA_DB-AMP-HH,SIGMA_DB-PHASE-HH,SIGMA_DB-AMP-HV," \ "SIGMA_DB-PHASE-HV,SIGMA_DB-AMP-VH,SIGMA_DB-PHASE-VH," \ "SIGMA_DB-AMP-VV,SIGMA_DB-PHASE-VV"); int ns = metaOut->general->sample_count; float total_power, ysca, amp, phase; complexFloat cpx; float *power = (float *) MALLOC(sizeof(float)*ns); float *shh_amp = (float *) MALLOC(sizeof(float)*ns); float *shh_phase = (float *) MALLOC(sizeof(float)*ns); float *shv_amp = (float *) MALLOC(sizeof(float)*ns); float *shv_phase = (float *) MALLOC(sizeof(float)*ns); float *svh_amp = (float *) MALLOC(sizeof(float)*ns); float *svh_phase = (float *) MALLOC(sizeof(float)*ns); float *svv_amp = (float *) MALLOC(sizeof(float)*ns); float *svv_phase = (float *) MALLOC(sizeof(float)*ns); char *byteBuf = (char *) MALLOC(sizeof(char)*10); fpIn = FOPEN(dataName[0], "rb"); fpOut = FOPEN(outName, "wb"); for (ii=0; ii<metaOut->general->line_count; ii++) { for (kk=0; kk<metaOut->general->sample_count; kk++) { FREAD(byteBuf, sizeof(char), 10, fpIn); //float m11, m12, m13, m14, m22, m23, m24, m33, m34, m44; // Scale is always 1.0 according to Bruce Chapman //m11 = ((float)byteBuf[1]/254.0 + 1.5) * pow(2, byteBuf[0]); //m12 = (float)byteBuf[2] * m11 / 127.0; //m13 = sign(byteBuf[3]) * SQR((float)byteBuf[3] / 127.0) * m11; //m14 = sign(byteBuf[4]) * SQR((float)byteBuf[4] / 127.0) * m11; //m23 = sign(byteBuf[5]) * SQR((float)byteBuf[5] / 127.0) * m11; //m24 = sign(byteBuf[6]) * SQR((float)byteBuf[6] / 127.0) * m11; //m33 = (float)byteBuf[7] * m11 / 127.0; //m34 = (float)byteBuf[8] * m11 / 127.0; //m44 = (float)byteBuf[9] * m11 / 127.0; //m22 = 1 - m33 -m44; total_power = ((float)byteBuf[1]/254.0 + 1.5) * pow(2, byteBuf[0]); ysca = 2.0 * sqrt(total_power); power[kk] = sqrt(total_power); cpx.real = (float)byteBuf[2] * ysca / 127.0; cpx.imag = (float)byteBuf[3] * ysca / 127.0; amp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag); phase = atan2(cpx.imag, cpx.real); if (radiometry == r_AMP) { shh_amp[kk] = amp; shh_phase[kk] = phase; } else if (radiometry == r_SIGMA) { shh_amp[kk] = amp*amp; shh_phase[kk] = phase; } else if (radiometry == r_SIGMA_DB) { shh_amp[kk] = amp; shh_phase[kk] = phase; } cpx.real = (float)byteBuf[4] * ysca / 127.0; cpx.imag = (float)byteBuf[5] * ysca / 127.0; amp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag); phase = atan2(cpx.imag, cpx.real); if (radiometry == r_AMP) { shv_amp[kk] = amp; shv_phase[kk] = phase; } else if (radiometry == r_SIGMA) { shv_amp[kk] = amp*amp; shv_phase[kk] = phase; } else if (radiometry == r_SIGMA_DB) { shv_amp[kk] = amp; shv_phase[kk] = phase; } cpx.real = (float)byteBuf[6] * ysca / 127.0; cpx.imag = (float)byteBuf[7] * ysca / 127.0; amp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag); phase = atan2(cpx.imag, cpx.real); if (radiometry == r_AMP) { svh_amp[kk] = amp; svh_phase[kk] = phase; } else if (radiometry == r_SIGMA) { svh_amp[kk] = amp*amp; svh_phase[kk] = phase; } else if (radiometry == r_SIGMA_DB) { svh_amp[kk] = amp; svh_phase[kk] = phase; } cpx.real = (float)byteBuf[8] * ysca / 127.0; cpx.imag = (float)byteBuf[9] * ysca / 127.0; amp = sqrt(cpx.real*cpx.real + cpx.imag*cpx.imag); phase = atan2(cpx.imag, cpx.real); if (radiometry == r_AMP) { svv_amp[kk] = amp; svv_phase[kk] = phase; } else if (radiometry == r_SIGMA) { svv_amp[kk] = amp*amp; svv_phase[kk] = phase; } else if (radiometry == r_SIGMA_DB) { svv_amp[kk] = amp; svv_phase[kk] = phase; } } put_band_float_line(fpOut, metaOut, 0, ii, power); put_band_float_line(fpOut, metaOut, 1, ii, shh_amp); put_band_float_line(fpOut, metaOut, 2, ii, shh_phase); put_band_float_line(fpOut, metaOut, 3, ii, shv_amp); put_band_float_line(fpOut, metaOut, 4, ii, shv_phase); put_band_float_line(fpOut, metaOut, 5, ii, svh_amp); put_band_float_line(fpOut, metaOut, 6, ii, svh_phase); put_band_float_line(fpOut, metaOut, 7, ii, svv_amp); put_band_float_line(fpOut, metaOut, 8, ii, svv_phase); asfLineMeter(ii, metaOut->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); FREE(power); FREE(shh_amp); FREE(shh_phase); FREE(shv_amp); FREE(shv_phase); FREE(svh_amp); FREE(svh_phase); FREE(svv_amp); FREE(svv_phase); meta_write(metaOut, outName); meta_free(metaIn); meta_free(metaOut); FREE(outName); FREE(polsar_params); } // Ground range projected data if (strcmp_case(type, "PolSAR") == 0 && strcmp_case(product[pp], "GRD") == 0) { get_uavsar_file_names(inFileName, POLSAR_GRD, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Ground range projected data do not exist. " "Will skip the ingest.\n"); continue; } polsar_params = read_uavsar_polsar_params(inFileName, POLSAR_GRD); metaIn = uavsar_polsar2meta(polsar_params); metaOut = uavsar_polsar2meta(polsar_params); ns = metaIn->general->sample_count; floatAmpBuf = (float *) CALLOC(ns, sizeof(float)); floatComplexReal = (float *) CALLOC(ns, sizeof(float)); floatComplexImag = (float *) CALLOC(ns, sizeof(float)); floatComplexBuf = (float *) CALLOC(2*ns, sizeof(float)); outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); metaOut->general->band_count = ll = 0; if (multi) outName = appendToBasename(outBaseName, "_grd.img"); else outName = appendExt(outBaseName, ".img"); asfPrintStatus("\nGround range projected data:\n"); fpOut = FOPEN(outName, "wb"); for (nn=0; nn<nBands; nn++) { char *filename = get_filename(dataName[nn]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); if (dataType[nn]) metaOut->general->band_count += 2; else metaOut->general->band_count += 1; fpIn = FOPEN(dataName[nn], "rb"); if (nn == 0) sprintf(metaOut->general->bands, "%s", element[0]); else { if (dataType[nn]) sprintf(tmp, ",%s_real,%s_imag", element[nn], element[nn]); else sprintf(tmp, ",%s", element[nn]); strcat(metaOut->general->bands, tmp); } if (dataType[nn]) { for (ii=0; ii<metaIn->general->line_count; ii++) { metaIn->general->sample_count = 2*ns; get_float_line(fpIn, metaIn, ii, floatComplexBuf); for (kk=0; kk<ns; kk++) { floatComplexReal[kk] = floatComplexBuf[kk*2]; floatComplexImag[kk] = floatComplexBuf[kk*2+1]; ieee_big32(floatComplexReal[kk]); ieee_big32(floatComplexImag[kk]); } put_band_float_line(fpOut, metaOut, ll, ii, floatComplexReal); put_band_float_line(fpOut, metaOut, ll+1, ii, floatComplexImag); asfLineMeter(ii, metaIn->general->line_count); } } else { for (ii=0; ii<metaIn->general->line_count; ii++) { metaIn->general->sample_count = ns; get_float_line(fpIn, metaIn, ii, floatAmpBuf); for (kk=0; kk<ns; kk++) ieee_big32(floatAmpBuf[kk]); put_band_float_line(fpOut, metaOut, ll, ii, floatAmpBuf); asfLineMeter(ii, metaIn->general->line_count); } } FCLOSE(fpIn); if (dataType[nn]) ll += 2; else ll++; } FCLOSE(fpOut); meta_write(metaOut, outName); FREE(floatAmpBuf); FREE(floatComplexReal); FREE(floatComplexImag); FREE(floatComplexBuf); FREE(outName); meta_free(metaIn); meta_free(metaOut); FREE(polsar_params); } // Digital elevation model if (strcmp_case(type, "PolSAR") == 0 && strcmp_case(product[pp], "HGT") == 0) { get_uavsar_file_names(inFileName, POLSAR_HGT, &dataName, &element, &dataType, &nBands); if (!nBands) { asfPrintWarning("Digital elevation model does not exist. " "Will skip the ingest.\n"); continue; } polsar_params = read_uavsar_polsar_params(inFileName, POLSAR_HGT); metaIn = uavsar_polsar2meta(polsar_params); metaOut = uavsar_polsar2meta(polsar_params); ns = metaOut->general->sample_count; floatAmpBuf = (float *) MALLOC(sizeof(float)*ns); outName = (char *) MALLOC(sizeof(char)*(strlen(outBaseName)+15)); if (multi) outName = appendToBasename(outBaseName, "_hgt.img"); else outName = appendExt(outBaseName, ".img"); asfPrintStatus("\nDigital elevation model:\n"); nn=0; char *filename = get_filename(dataName[nn]); asfPrintStatus("Ingesting %s ...\n", filename); FREE(filename); fpIn = FOPEN(dataName[nn], "rb"); fpOut = FOPEN(outName, "wb"); strcpy(metaOut->general->bands, "HEIGHT"); for (ii=0; ii<metaIn->general->line_count; ii++) { get_float_line(fpIn, metaIn, ii, floatAmpBuf); for (kk=0; kk<metaIn->general->sample_count; kk++) ieee_big32(floatAmpBuf[kk]); put_float_line(fpOut, metaOut, ii, floatAmpBuf); asfLineMeter(ii, metaIn->general->line_count); } FCLOSE(fpIn); FCLOSE(fpOut); meta_write(metaOut, outName); FREE(floatAmpBuf); FREE(outName); meta_free(metaIn); meta_free(metaOut); FREE(polsar_params); } } if (strcmp_case(type, "PolSAR") == 0) product_count = 5; else if (strcmp_case(type, "InSAR") == 0) product_count = 9; for (pp=0; pp<product_count; pp++) FREE(product[pp]); FREE(product); FREE(type); } void read_meta_uavsar(const char *inFileName, const char *outBaseName) { int pp, product_count, *dataType, nBands; char *type = check_data_type(inFileName); char **product = get_uavsar_products("ALL", type, &product_count); char **dataName, **element; char *outName = (char *) MALLOC(sizeof(char)*255); uavsar_polsar *polsar_params; uavsar_insar *insar_params; meta_parameters *meta; for (pp = 0; pp < product_count; pp++) { // InSAR if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "INT_GRD") == 0) { get_uavsar_file_names(inFileName, INSAR_INT_GRD, &dataName, &element, &dataType, &nBands); if (!nBands) continue; insar_params = read_uavsar_insar_params(inFileName, INSAR_INT_GRD); meta = uavsar_insar2meta(insar_params); sprintf(outName, "%s_int_grd.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "UNW_GRD") == 0) { get_uavsar_file_names(inFileName, INSAR_UNW_GRD, &dataName, &element, &dataType, &nBands); if (!nBands) continue; insar_params = read_uavsar_insar_params(inFileName, INSAR_UNW_GRD); meta = uavsar_insar2meta(insar_params); sprintf(outName, "%s_unw_grd.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "COR_GRD") == 0) { get_uavsar_file_names(inFileName, INSAR_COR_GRD, &dataName, &element, &dataType, &nBands); if (!nBands) continue; insar_params = read_uavsar_insar_params(inFileName, INSAR_COR_GRD); meta = uavsar_insar2meta(insar_params); sprintf(outName, "%s_cor_grd.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "AMP_GRD") == 0) { get_uavsar_file_names(inFileName, INSAR_AMP_GRD, &dataName, &element, &dataType, &nBands); if (!nBands) continue; insar_params = read_uavsar_insar_params(inFileName, INSAR_AMP_GRD); meta = uavsar_insar2meta(insar_params); sprintf(outName, "%s_amp_grd.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "HGT_GRD") == 0) { get_uavsar_file_names(inFileName, INSAR_HGT_GRD, &dataName, &element, &dataType, &nBands); if (!nBands) continue; insar_params = read_uavsar_insar_params(inFileName, INSAR_HGT_GRD); meta = uavsar_insar2meta(insar_params); sprintf(outName, "%s_hgt_grd.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "INT") == 0) { get_uavsar_file_names(inFileName, INSAR_INT, &dataName, &element, &dataType, &nBands); if (!nBands) continue; insar_params = read_uavsar_insar_params(inFileName, INSAR_INT); meta = uavsar_insar2meta(insar_params); sprintf(outName, "%s_int.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "UNW") == 0) { get_uavsar_file_names(inFileName, INSAR_UNW, &dataName, &element, &dataType, &nBands); if (!nBands) continue; insar_params = read_uavsar_insar_params(inFileName, INSAR_UNW); meta = uavsar_insar2meta(insar_params); sprintf(outName, "%s_unw.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "COR") == 0) { get_uavsar_file_names(inFileName, INSAR_COR, &dataName, &element, &dataType, &nBands); if (!nBands) continue; insar_params = read_uavsar_insar_params(inFileName, INSAR_COR); meta = uavsar_insar2meta(insar_params); sprintf(outName, "%s_cor.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } if (strcmp_case(type, "InSAR") == 0 && strcmp_case(product[pp], "AMP") == 0) { get_uavsar_file_names(inFileName, INSAR_AMP, &dataName, &element, &dataType, &nBands); if (!nBands) continue; insar_params = read_uavsar_insar_params(inFileName, INSAR_AMP); meta = uavsar_insar2meta(insar_params); sprintf(outName, "%s_amp.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } // PolSAR if (strcmp_case(type, "PolSAR") == 0 && strcmp_case(product[pp], "MLC") == 0) { get_uavsar_file_names(inFileName, POLSAR_MLC, &dataName, &element, &dataType, &nBands); if (!nBands) continue; polsar_params = read_uavsar_polsar_params(inFileName, POLSAR_MLC); meta = uavsar_polsar2meta(polsar_params); sprintf(outName, "%s_mlc.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } if (strcmp_case(type, "PolSAR") == 0 && strcmp_case(product[pp], "DAT") == 0) { get_uavsar_file_names(inFileName, POLSAR_DAT, &dataName, &element, &dataType, &nBands); if (!nBands) continue; polsar_params = read_uavsar_polsar_params(inFileName, POLSAR_DAT); meta = uavsar_polsar2meta(polsar_params); sprintf(outName, "%s_dat.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } if (strcmp_case(type, "PolSAR") == 0 && strcmp_case(product[pp], "GRD") == 0) { get_uavsar_file_names(inFileName, POLSAR_GRD, &dataName, &element, &dataType, &nBands); if (!nBands) continue; polsar_params = read_uavsar_polsar_params(inFileName, POLSAR_GRD); meta = uavsar_polsar2meta(polsar_params); sprintf(outName, "%s_grd.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } if (strcmp_case(type, "PolSAR") == 0 && strcmp_case(product[pp], "HGT") == 0) { get_uavsar_file_names(inFileName, POLSAR_HGT, &dataName, &element, &dataType, &nBands); if (!nBands) continue; polsar_params = read_uavsar_polsar_params(inFileName, POLSAR_HGT); meta = uavsar_polsar2meta(polsar_params); sprintf(outName, "%s_hgt.xml", outBaseName); meta_write_xml(meta, outName); FREE(outName); meta_free(meta); FREE(insar_params); FREE(dataType); } } for (pp=0; pp<product_count; pp++) FREE(product[pp]); FREE(product); FREE(type); }
{ "alphanum_fraction": 0.6147624132, "avg_line_length": 35.157203191, "ext": "c", "hexsha": "5978d4272a0286cc6ceb88b9496cfa0f88e8c618", "lang": "C", "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z", "max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "glshort/MapReady", "max_forks_repo_path": "src/libasf_import/import_uavsar.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "glshort/MapReady", "max_issues_repo_path": "src/libasf_import/import_uavsar.c", "max_line_length": 181, "max_stars_count": 3, "max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "glshort/MapReady", "max_stars_repo_path": "src/libasf_import/import_uavsar.c", "max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z", "max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z", "num_tokens": 21669, "size": 74920 }
/*****************************************************************************/ /* Solvers for the Least squares problem min_x || B - A*x || */ /*****************************************************************************/ #include <lah.h> /* lah_solveLS * ------------ * Solves the least squares problem by applying the Lapack routine gels * which uses QR or LQ factorization. * Params: - A, B, X: Matrices of the LS problem min_x || B - A*x || */ #ifdef HAVE_LAPACK /* Use a LAPACK package to do the heavy work */ #include <lapacke.h> lah_Return lah_solveLS(koop_mat *A, *B, *X) { lah result = 0; gels('N', A->nR, A->nC, NRHS, A->data, LDA, B, LDB, WORK, LWORK, result); /* Alternative: used for ill conditioned problems * ca. 5 times slower. Could check residuum output to determine which precision to use*/ /* gelsd () */ return result; } #endif
{ "alphanum_fraction": 0.501618123, "avg_line_length": 35.6538461538, "ext": "c", "hexsha": "8a789a2004a5e5c919327161630bb4f4e984d5b0", "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_solveLS.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_solveLS.c", "max_line_length": 92, "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_solveLS.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 221, "size": 927 }
// // ePDF // #pragma once #include <gsl/gsl_integration.h> namespace ePDF { struct int_params { double z; int nl; }; /** * @brief The "NumericIntegrals" class */ class NumericIntegrals { public: /** * @brief The "NumericIntegrals" constructor. * @param flv: 0 = singlet, 1 = photon, 2 = nonsinglet * @param nl: number of leptons (needed for singlet) */ NumericIntegrals(int const& iflv, int const& nl); /** * @brief The "NumericIntegrals" destructor. */ ~NumericIntegrals(); /** * @brief Perform the integration * @param z: momentum fraction */ double integrate(double const& z) const; private: int const _iflv; int const _nl; double const _epsabs; double const _epsrel; gsl_integration_workspace *_w; }; }
{ "alphanum_fraction": 0.6009501188, "avg_line_length": 17.1836734694, "ext": "h", "hexsha": "d90b0981559d3392b5c9c36f9ab13f30a9eb99c5", "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": "e9ffa1fd977bb67e8212b84e5cea297b7604f9b8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gstagnit/ePDF", "max_forks_repo_path": "inc/ePDF/numericintegrals.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e9ffa1fd977bb67e8212b84e5cea297b7604f9b8", "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": "gstagnit/ePDF", "max_issues_repo_path": "inc/ePDF/numericintegrals.h", "max_line_length": 58, "max_stars_count": 2, "max_stars_repo_head_hexsha": "e9ffa1fd977bb67e8212b84e5cea297b7604f9b8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "vbertone/ePDF", "max_stars_repo_path": "inc/ePDF/numericintegrals.h", "max_stars_repo_stars_event_max_datetime": "2022-03-04T17:37:13.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-01T16:50:25.000Z", "num_tokens": 240, "size": 842 }
#pragma once #include <memory> #include <gsl/span> #include "halley/time/halleytime.h" #include "../session/network_session.h" #include "entity_network_remote_peer.h" #include "halley/bytes/serialization_dictionary.h" namespace Halley { class EntityFactory; class Resources; class World; class NetworkSession; class EntitySessionSharedData : public SharedData { public: }; class EntityClientSharedData : public SharedData { public: std::optional<Rect4i> viewRect; void serialize(Serializer& s) const override; void deserialize(Deserializer& s) override; }; class EntityNetworkSession : NetworkSession::IListener, NetworkSession::ISharedDataHandler { public: class IEntityNetworkSessionListener { public: virtual ~IEntityNetworkSessionListener() = default; virtual void onRemoteEntityCreated(EntityRef entity, NetworkSession::PeerId peerId) {} virtual void onPreSendDelta(EntityDataDelta& delta) {} virtual bool isEntityInView(EntityRef entity, const EntityClientSharedData& clientData) = 0; }; EntityNetworkSession(std::shared_ptr<NetworkSession> session, Resources& resources, std::set<String> ignoreComponents, IEntityNetworkSessionListener* listener); ~EntityNetworkSession() override; void setWorld(World& world); void sendUpdates(Time t, Rect4i viewRect, gsl::span<const std::pair<EntityId, uint8_t>> entityIds); // Takes pairs of entity id and owner peer id void receiveUpdates(); World& getWorld() const; EntityFactory& getFactory() const; NetworkSession& getSession() const; bool hasWorld() const; const EntityFactory::SerializationOptions& getEntitySerializationOptions() const; const EntityDataDelta::Options& getEntityDeltaOptions() const; const SerializerOptions& getByteSerializationOptions() const; Time getMinSendInterval() const; void onRemoteEntityCreated(EntityRef entity, NetworkSession::PeerId peerId); void onPreSendDelta(EntityDataDelta& delta); bool isReadyToStart() const; bool isEntityInView(EntityRef entity, const EntityClientSharedData& clientData) const; std::vector<Rect4i> getRemoteViewPorts() const; protected: void onStartSession(NetworkSession::PeerId myPeerId) override; void onPeerConnected(NetworkSession::PeerId peerId) override; void onPeerDisconnected(NetworkSession::PeerId peerId) override; std::unique_ptr<SharedData> makeSessionSharedData() override; std::unique_ptr<SharedData> makePeerSharedData() override; private: struct QueuedPacket { NetworkSession::PeerId fromPeerId; EntityNetworkHeaderType type; InboundNetworkPacket packet; }; Resources& resources; std::shared_ptr<EntityFactory> factory; IEntityNetworkSessionListener* listener = nullptr; EntityFactory::SerializationOptions entitySerializationOptions; EntityDataDelta::Options deltaOptions; SerializerOptions byteSerializationOptions; SerializationDictionary serializationDictionary; std::shared_ptr<NetworkSession> session; std::vector<EntityNetworkRemotePeer> peers; std::vector<QueuedPacket> queuedPackets; bool readyToStart = false; void onReceiveEntityUpdate(NetworkSession::PeerId fromPeerId, EntityNetworkHeaderType type, InboundNetworkPacket packet); void onReceiveReady(NetworkSession::PeerId fromPeerId); void setupDictionary(); }; }
{ "alphanum_fraction": 0.790171842, "avg_line_length": 32.2038834951, "ext": "h", "hexsha": "3cda999aa635109d19dfce668f8ba16746c7679d", "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": "a093ed9c26a5141db87b560186c609cfe4810695", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "JoelOtter/halley", "max_forks_repo_path": "src/engine/net/include/halley/net/entity/entity_network_session.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a093ed9c26a5141db87b560186c609cfe4810695", "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": "JoelOtter/halley", "max_issues_repo_path": "src/engine/net/include/halley/net/entity/entity_network_session.h", "max_line_length": 162, "max_stars_count": null, "max_stars_repo_head_hexsha": "a093ed9c26a5141db87b560186c609cfe4810695", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "JoelOtter/halley", "max_stars_repo_path": "src/engine/net/include/halley/net/entity/entity_network_session.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 763, "size": 3317 }
/* * ----------------------------------------------------------------- * Binary Search Tree Library --- bst_lib.h * Version: 1.6180 * Date: Feb 19, 2010 * ----------------------------------------------------------------- * Programmer: Americo Barbosa da Cunha Junior * americo.cunhajr@gmail.com * ----------------------------------------------------------------- * Copyright (c) 2010 by Americo Barbosa da Cunha Junior * * 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. * * A copy of the GNU General Public License is available in * LICENSE.txt or http://www.gnu.org/licenses/. * ----------------------------------------------------------------- * This is the header file for a library with * to operates a binary search tree. * ----------------------------------------------------------------- */ #ifndef __BST_LIB_H__ #define __BST_LIB_H__ #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #undef RIGHT #define RIGHT 1 #undef LEFT #define LEFT 0 /* *------------------------------------------------------------ * structure of binary search tree leaf * * last update: Feb 2, 2009 *------------------------------------------------------------ */ typedef struct leaf { gsl_vector *phi; /* composition */ gsl_vector *Rphi; /* reaction mapping */ gsl_matrix *A; /* mapping gradient matrix */ gsl_matrix *L; /* ellipsoid Cholesky matrix */ } bst_leaf; /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * structure of binary search tree node * * last update: Feb 2, 2009 *------------------------------------------------------------ */ typedef struct node { gsl_vector *v; /* cutting plane normal vector */ double a; /* scalar a */ struct node *r_node; /* right node */ struct node *l_node; /* left node */ struct leaf *r_leaf; /* right leaf */ struct leaf *l_leaf; /* left leaf */ } bst_node; /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * function prototypes *------------------------------------------------------------ */ bst_leaf *bst_leaf_alloc(); bst_node* bst_node_alloc(); void bst_leaf_free(void **leaf_bl); void bst_node_free(void **node_bl); int bst_leaf_set(gsl_vector *phi, gsl_vector *Rphi, gsl_matrix *A, gsl_matrix *L, bst_leaf *leaf); double bst_cutplane(gsl_vector *phi_l, gsl_vector *phi_r, gsl_vector *v); int bst_node_set(bst_leaf *l_leaf, bst_leaf *r_leaf, bst_node *node); int bst_node_add(int side, bst_node *old_node, bst_node *new_node); int bst_search(bst_node *root, gsl_vector *phi, bst_node **end_node, bst_leaf **end_leaf); int bst_height(bst_node *root); #endif /* __BST_LIB_H__ */
{ "alphanum_fraction": 0.4821886577, "avg_line_length": 25.9925925926, "ext": "h", "hexsha": "dc69a0d455167108f66bfd4a0a264de8de0b2fae", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_path": "CRFlowLib-1.0/include/bst_lib.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "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": "americocunhajr/CRFlowLib", "max_issues_repo_path": "CRFlowLib-1.0/include/bst_lib.h", "max_line_length": 68, "max_stars_count": 1, "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_path": "CRFlowLib-1.0/include/bst_lib.h", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "num_tokens": 712, "size": 3509 }
#ifndef _RMSD_H_ #define _RMSD_H_ #include <algorithm> #include <map> #include <cmath> #include <iostream> #include <vector> #include <gsl/gsl_matrix.h> #include "pdb.h" #include "atom.h" #include "align.h" #include "contact.h" // Indicates that, when calculating the ligand rmsd between a receptor/ligand pair // only atoms (in the ligand) closer than 10 angstroms to any receptor atom should // be considered #define LIGAND_RMSD_THRESHOLD 10 /* * This version of the RMSD calculation method assumes that both vectors * are the same size and that each position in each array corresponds to * the actual alignment of atoms */ double calculate_allatom_rmsd(vector<atom>& S, vector<atom>& T); double calculate_lrms(vector<atom>&, vector<atom>&, map<int, int>&); double calculate_irmsd(vector<atom>&, vector<atom>&, vector<atom>&, vector<atom>&, map<int, int>&, map<int, int>&, int, int); void get_fnat(vector<string>& target, vector<string>& predicted, double& fnat, double& fnon_nat); // overloaded version that not only calculates fnat fot a target/prediction, but for each of the chains too // according to the per-chain information given to it void get_fnat(vector<string>& target, vector<string>& predicted, vector< vector<string> >& target_per_chain, vector< vector<string> >& predicted_per_chain, double& fnat, double& fnon_nat, double* fnat_per_chain, double* fnon_nat_per_chain); // This function takes a multiple chain target and its prediction and calculates the global c-alpha rmsd // between them. It directly returns the total rmsd but it also returns the specific rmsd for each chain // in the output parameter named rmsd_by_chain. The memory for this parameter should have been allocated previously double calculate_multiple_rmsd(vector< vector<atom> >& target, vector< vector<atom> >& predicted, double* rmsd_by_chain, bool interface_only); #endif
{ "alphanum_fraction": 0.757240653, "avg_line_length": 48.6923076923, "ext": "h", "hexsha": "b016034a8a9611ba514ed7092556af6e1ed0a4d6", "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": "9b5286d3375fff691a80ceb44172549e9a6bdee5", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "tecdatalab/legacy", "max_forks_repo_path": "core/proteinstructure/rmsd.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9b5286d3375fff691a80ceb44172549e9a6bdee5", "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": "tecdatalab/legacy", "max_issues_repo_path": "core/proteinstructure/rmsd.h", "max_line_length": 155, "max_stars_count": null, "max_stars_repo_head_hexsha": "9b5286d3375fff691a80ceb44172549e9a6bdee5", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "tecdatalab/legacy", "max_stars_repo_path": "core/proteinstructure/rmsd.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 461, "size": 1899 }
/* specfunc/transport.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_transport.h> #include "error.h" #include "check.h" #include "chebyshev.h" #include "cheb_eval.c" static double transport2_data[18] = { 1.671760446434538503, -0.147735359946794490, 0.148213819946936338e-01, -0.14195330326305613e-02, 0.1306541324415708e-03, -0.117155795867579e-04, 0.10333498445756e-05, -0.901911304223e-07, 0.78177169833e-08, -0.6744565684e-09, 0.579946394e-10, -0.49747619e-11, 0.425961e-12, -0.36422e-13, 0.3111e-14, -0.265e-15, 0.23e-16, -0.19e-17 }; static cheb_series transport2_cs = { transport2_data, 17, -1, 1, 9 }; static double transport3_data[18] = { 0.762012543243872007, -0.105674387705058533, 0.119778084819657810e-01, -0.12144015203698307e-02, 0.1155099769392855e-03, -0.105815992124423e-04, 0.9474663385302e-06, -0.836221212858e-07, 0.73109099278e-08, -0.6350594779e-09, 0.549118282e-10, -0.47321395e-11, 0.4067695e-12, -0.348971e-13, 0.29892e-14, -0.256e-15, 0.219e-16, -0.19e-17 }; static cheb_series transport3_cs = { transport3_data, 17, -1, 1, 9 }; static double transport4_data[18] = { 0.4807570994615110579, -0.8175378810321083956e-01, 0.1002700665975162973e-01, -0.10599339359820151e-02, 0.1034506245030405e-03, -0.96442705485899e-05, 0.8745544408515e-06, -0.779321207981e-07, 0.68649886141e-08, -0.5999571076e-09, 0.521366241e-10, -0.45118382e-11, 0.3892159e-12, -0.334936e-13, 0.28767e-14, -0.2467e-15, 0.211e-16, -0.18e-17 }; static cheb_series transport4_cs = { transport4_data, 17, -1, 1, 9 }; static double transport5_data[18] = { 0.347777777133910789, -0.66456988976050428e-01, 0.8611072656883309e-02, -0.9396682223755538e-03, 0.936324806081513e-04, -0.88571319340833e-05, 0.811914989145e-06, -0.72957654233e-07, 0.646971455e-08, -0.568490283e-09, 0.49625598e-10, -0.4310940e-11, 0.373100e-12, -0.32198e-13, 0.2772e-14, -0.238e-15, 0.21e-16, -0.18e-17 }; static cheb_series transport5_cs = { transport5_data, 17, -1, 1, 9 }; static double transport_sumexp(const int numexp, const int order, const double t, double x) { double rk = (double)numexp; double sumexp = 0.0; int k; for(k=1; k<=numexp; k++) { double sum2 = 1.0; double xk = 1.0/(rk*x); double xk1 = 1.0; int j; for(j=1; j<=order; j++) { sum2 = sum2*xk1*xk + 1.0; xk1 += 1.0; } sumexp *= t; sumexp += sum2; rk -= 1.0; } return sumexp; } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_transport_2_e(const double x, gsl_sf_result * result) { const double val_infinity = 3.289868133696452873; /* CHECK_POINTER(result) */ if(x < 0.0) { DOMAIN_ERROR(result); } else if(x < 3.0*GSL_SQRT_DBL_EPSILON) { result->val = x; result->err = GSL_DBL_EPSILON*fabs(x) + x*x/2.0; return GSL_SUCCESS; } else if(x <= 4.0) { double t = (x*x/8.0 - 0.5) - 0.5; gsl_sf_result result_c; cheb_eval_e(&transport2_cs, t, &result_c); result->val = x * result_c.val; result->err = x * result_c.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < -GSL_LOG_DBL_EPSILON) { const int numexp = (int)((-GSL_LOG_DBL_EPSILON)/x) + 1; const double sumexp = transport_sumexp(numexp, 2, exp(-x), x); const double t = 2.0 * log(x) - x + log(sumexp); if(t < GSL_LOG_DBL_EPSILON) { result->val = val_infinity; result->err = 2.0 * GSL_DBL_EPSILON * val_infinity; } else { const double et = exp(t); result->val = val_infinity - et; result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + fabs(t) * et); } return GSL_SUCCESS; } else if(x < 2.0/GSL_DBL_EPSILON) { const int numexp = 1; const double sumexp = transport_sumexp(numexp, 2, 1.0, x); const double t = 2.0 * log(x) - x + log(sumexp); if(t < GSL_LOG_DBL_EPSILON) { result->val = val_infinity; result->err = 2.0 * GSL_DBL_EPSILON * val_infinity; } else { const double et = exp(t); result->val = val_infinity - et; result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et); } return GSL_SUCCESS; } else { const double t = 2.0 * log(x) - x; if(t < GSL_LOG_DBL_EPSILON) { result->val = val_infinity; result->err = 2.0 * GSL_DBL_EPSILON * val_infinity; } else { const double et = exp(t); result->val = val_infinity - et; result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et); } return GSL_SUCCESS; } } int gsl_sf_transport_3_e(const double x, gsl_sf_result * result) { const double val_infinity = 7.212341418957565712; /* CHECK_POINTER(result) */ if(x < 0.0) { DOMAIN_ERROR(result); } else if(x == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(x < 3.0*GSL_SQRT_DBL_EPSILON) { result->val = 0.5*x*x; result->err = 2.0 * GSL_DBL_EPSILON * result->val; CHECK_UNDERFLOW(result); return GSL_SUCCESS; } else if(x <= 4.0) { const double x2 = x*x; const double t = (x2/8.0 - 0.5) - 0.5; gsl_sf_result result_c; cheb_eval_e(&transport3_cs, t, &result_c); result->val = x2 * result_c.val; result->err = x2 * result_c.err; result->err += GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < -GSL_LOG_DBL_EPSILON) { const int numexp = (int)((-GSL_LOG_DBL_EPSILON)/x) + 1; const double sumexp = transport_sumexp(numexp, 3, exp(-x), x); const double t = 3.0 * log(x) - x + log(sumexp); if(t < GSL_LOG_DBL_EPSILON) { result->val = val_infinity; result->err = 2.0 * GSL_DBL_EPSILON * val_infinity; } else { const double et = exp(t); result->val = val_infinity - et; result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + fabs(t) * et); } return GSL_SUCCESS; } else if(x < 3.0/GSL_DBL_EPSILON) { const int numexp = 1; const double sumexp = transport_sumexp(numexp, 3, 1.0, x); const double t = 3.0 * log(x) - x + log(sumexp); if(t < GSL_LOG_DBL_EPSILON) { result->val = val_infinity; result->err = 2.0 * GSL_DBL_EPSILON * val_infinity; } else { const double et = exp(t); result->val = val_infinity - et; result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et); } return GSL_SUCCESS; } else { const double t = 3.0 * log(x) - x; if(t < GSL_LOG_DBL_EPSILON) { result->val = val_infinity; result->err = 2.0 * GSL_DBL_EPSILON * val_infinity; } else { const double et = exp(t); result->val = val_infinity - et; result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et); } return GSL_SUCCESS; } } int gsl_sf_transport_4_e(const double x, gsl_sf_result * result) { const double val_infinity = 25.97575760906731660; /* CHECK_POINTER(result) */ if(x < 0.0) { DOMAIN_ERROR(result); } else if(x == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(x < 3.0*GSL_SQRT_DBL_EPSILON) { result->val = x*x*x/3.0; result->err = 3.0 * GSL_DBL_EPSILON * result->val; CHECK_UNDERFLOW(result); return GSL_SUCCESS; } else if(x <= 4.0) { const double x2 = x*x; const double t = (x2/8.0 - 0.5) - 0.5; gsl_sf_result result_c; cheb_eval_e(&transport4_cs, t, &result_c); result->val = x2*x * result_c.val; result->err = x2*x * result_c.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < -GSL_LOG_DBL_EPSILON) { const int numexp = (int)((-GSL_LOG_DBL_EPSILON)/x) + 1; const double sumexp = transport_sumexp(numexp, 4, exp(-x), x); const double t = 4.0 * log(x) - x + log(sumexp); if(t < GSL_LOG_DBL_EPSILON) { result->val = val_infinity; result->err = 2.0 * GSL_DBL_EPSILON * val_infinity; } else { const double et = exp(t); result->val = val_infinity - et; result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et); } return GSL_SUCCESS; } else if(x < 3.0/GSL_DBL_EPSILON) { const int numexp = 1; const double sumexp = transport_sumexp(numexp, 4, 1.0, x); const double t = 4.0 * log(x) - x + log(sumexp); if(t < GSL_LOG_DBL_EPSILON) { result->val = val_infinity; result->err = 2.0 * GSL_DBL_EPSILON * val_infinity; } else { const double et = exp(t); result->val = val_infinity - et; result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et); } return GSL_SUCCESS; } else { const double t = 4.0 * log(x) - x; if(t < GSL_LOG_DBL_EPSILON) { result->val = val_infinity; result->err = 2.0 * GSL_DBL_EPSILON * val_infinity; } else { const double et = exp(t); result->val = val_infinity - et; result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et); } return GSL_SUCCESS; } } int gsl_sf_transport_5_e(const double x, gsl_sf_result * result) { const double val_infinity = 124.4313306172043912; /* CHECK_POINTER(result) */ if(x < 0.0) { DOMAIN_ERROR(result); } else if(x == 0.0) { result->val = 0.0; result->err = 0.0; return GSL_SUCCESS; } else if(x < 3.0*GSL_SQRT_DBL_EPSILON) { result->val = x*x*x*x/4.0; result->err = 4.0 * GSL_DBL_EPSILON * result->val; CHECK_UNDERFLOW(result); return GSL_SUCCESS; } else if(x <= 4.0) { const double x2 = x*x; const double t = (x2/8.0 - 0.5) - 0.5; gsl_sf_result result_c; cheb_eval_e(&transport5_cs, t, &result_c); result->val = x2*x2 * result_c.val; result->err = x2*x2 * result_c.err; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(x < -GSL_LOG_DBL_EPSILON) { const int numexp = (int)((-GSL_LOG_DBL_EPSILON)/x) + 1; const double sumexp = transport_sumexp(numexp, 5, exp(-x), x); const double t = 5.0 * log(x) - x + log(sumexp); if(t < GSL_LOG_DBL_EPSILON) { result->val = val_infinity; result->err = 2.0 * GSL_DBL_EPSILON * val_infinity; } else { const double et = exp(t); result->val = val_infinity - et; result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et); } return GSL_SUCCESS; } else if(x < 3.0/GSL_DBL_EPSILON) { const int numexp = 1; const double sumexp = transport_sumexp(numexp, 5, 1.0, x); const double t = 5.0 * log(x) - x + log(sumexp); if(t < GSL_LOG_DBL_EPSILON) { result->val = val_infinity; result->err = 2.0 * GSL_DBL_EPSILON * val_infinity; } else { const double et = exp(t); result->val = val_infinity - et; result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et); } return GSL_SUCCESS; } else { const double t = 5.0 * log(x) - x; if(t < GSL_LOG_DBL_EPSILON) { result->val = val_infinity; result->err = 2.0 * GSL_DBL_EPSILON * val_infinity; } else { const double et = exp(t); result->val = val_infinity - et; result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et); } return GSL_SUCCESS; } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_transport_2(const double x) { EVAL_RESULT(gsl_sf_transport_2_e(x, &result)); } double gsl_sf_transport_3(const double x) { EVAL_RESULT(gsl_sf_transport_3_e(x, &result)); } double gsl_sf_transport_4(const double x) { EVAL_RESULT(gsl_sf_transport_4_e(x, &result)); } double gsl_sf_transport_5(const double x) { EVAL_RESULT(gsl_sf_transport_5_e(x, &result)); }
{ "alphanum_fraction": 0.6178899797, "avg_line_length": 26.0324543611, "ext": "c", "hexsha": "c55c13c10090e6f4ad37eeb5cc1f2dd4106324a9", "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/specfunc/transport.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/transport.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/specfunc/transport.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 4628, "size": 12834 }
#define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define DefaultWorkSize 1e9 // 1GB #define NumSplitDefaultMax 20 #define OUTPUT stdout // stderr #include <cmath> #include <cstdio> #include <cstdlib> #include <cmath> #include <iostream> #include <typeinfo> #define __STDC_FORMAT_MACROS #include <inttypes.h> #include <sys/time.h> #include <float.h> #if defined (MKL) #include <mkl_cblas.h> #include <mkl_trans.h> #include <mkl_spblas.h> #else #include <cblas.h> #endif #include <omp.h> #if defined (FLOAT128) #if defined (ARM) #define __float128 long double #define FLT128_MAX LDBL_MAX #define FLT128_MIN LDBL_MIN #else #include <quadmath.h> #endif //#ifdef __INTEL_COMPILER //__float128 std::abs (const __float128 x); //#endif #include <mplapack/mpblas__Float128.h> #endif #if defined (CUBLAS) #include <cuda.h> #include <cuda_runtime_api.h> #include <cublas_v2.h> #endif #include "../../include/ozblas.h" #include "ozblas_internal.h" // ------------------------------------- // constexpr functions // ------------------------------------- // ------------------------------------- // getEmin // ------------------------------------- template <typename TYPE> constexpr int32_t getEmin () { fprintf (OUTPUT, "OzBLAS error: TYPE is not specified in getEmin.\n"); exit (1); return 0; } template <> constexpr int32_t getEmin <float> () { return -126; } template <> constexpr int32_t getEmin <double> () { return -1022; } #if defined (FLOAT128) template <> constexpr int32_t getEmin <__float128> () { return -16382; } #endif // ------------------------------------- // getEpse // ------------------------------------- template <typename TYPE> constexpr int32_t getEpse () { fprintf (OUTPUT, "OzBLAS error: TYPE is not specified in getEpse.\n"); exit (1); return 0; } template <> constexpr int32_t getEpse <float> () { return 24; } template <> constexpr int32_t getEpse <double> () { return 53; } #if defined (FLOAT128) template <> constexpr int32_t getEpse <__float128> () { return 113; } #endif // ------------------------------------- // getTypeMax // ------------------------------------- template <typename TYPE> constexpr TYPE getTypeMax () { fprintf (OUTPUT, "OzBLAS error: TYPE is not specified in getTypeMax.\n"); exit (1); return 0; } template <> constexpr float getTypeMax <float> () { return FLT_MAX; } template <> constexpr double getTypeMax <double> () { return DBL_MAX; } #if defined (FLOAT128) template <> constexpr __float128 getTypeMax <__float128> () { return FLT128_MAX; } #endif // ------------------------------------- // getTypeMin // ------------------------------------- template <typename TYPE> constexpr TYPE getTypeMin () { fprintf (OUTPUT, "OzBLAS error: TYPE is not specified in getTypeMin.\n"); exit (1); return 0; } template <> constexpr float getTypeMin <float> () { return FLT_MIN; } template <> constexpr double getTypeMin <double> () { return DBL_MIN; } #if defined (FLOAT128) template <> constexpr __float128 getTypeMin <__float128> () { return FLT128_MIN; } #endif /* #define SCALBN scalbnl #define LOG2 log2l #define LOG logl #define CEIL ceill #define FABS fabsl */
{ "alphanum_fraction": 0.617007874, "avg_line_length": 19.7204968944, "ext": "h", "hexsha": "c77ae4ec9c82c99e1cab6547d5290e0d38e6a1e6", "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": "src/cpu/ozblas_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": "src/cpu/ozblas_common.h", "max_line_length": 74, "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": "src/cpu/ozblas_common.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 811, "size": 3175 }
//////////////////////////////////////////////////////////// // // Copyright (c) 2018 Jan Filipowicz, Filip Turobos // // 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 GENETIC_ALGORITHM_LIBRARY_GENETIC_ALGORITHM_H #define GENETIC_ALGORITHM_LIBRARY_GENETIC_ALGORITHM_H #include <algorithm> #include <functional> #include <iterator> #include <utility> #include <vector> #include <gsl/gsl_assert> #include "evaluated_specimen.h" #include "repeat.h" template<class Specimen, class Rating> class genetic_algorithm { public: using specimen_type = Specimen; using rating_type = Rating; using evaluated_specimen_type = evaluated_specimen<Specimen, Rating>; struct context_type; enum struct stage_type { generated, selected, bred }; explicit genetic_algorithm(const context_type& context); explicit genetic_algorithm(context_type&& context); template<class... Functions> evaluated_specimen_type operator()(Functions&&... observers) const; private: template<class... Functions> void communicate_stage(stage_type stage, const std::vector<evaluated_specimen_type>& specimens, Functions&&... observers) const; void evaluate(std::vector<evaluated_specimen_type>& specimens) const; std::vector<evaluated_specimen_type> breed(const std::vector<evaluated_specimen_type>& specimens) const; context_type context; }; template<class Specimen, class Rating> struct genetic_algorithm<Specimen, Rating>::context_type { std::size_t initial_population_size = 1; std::size_t breeding_population_size = 1; std::size_t max_iterations = 0; std::function<specimen_type()> generator; std::function<rating_type(const specimen_type&)> evaluator; std::function<void(std::vector<evaluated_specimen_type>&, std::size_t)> selector; std::function<specimen_type(const specimen_type&, const specimen_type&)> breeder; std::function<bool(rating_type, rating_type)> comparator; }; template<class Context> constexpr bool valid(const Context& context) noexcept { return context.initial_population_size > 0 && context.breeding_population_size > 0 && context.generator != nullptr && context.evaluator != nullptr && context.selector != nullptr && context.breeder != nullptr && context.comparator != nullptr ; } template<class Specimen, class Rating> inline genetic_algorithm<Specimen, Rating>::genetic_algorithm(const context_type& context) : context(context) {} template<class Specimen, class Rating> inline genetic_algorithm<Specimen, Rating>::genetic_algorithm(context_type&& context) : context(std::move(context)) {} template<class Specimen, class Rating> template<class... Functions> inline auto genetic_algorithm<Specimen, Rating>::operator()(Functions&&... observers) const -> evaluated_specimen_type { Expects(valid(context)); std::vector<evaluated_specimen_type> specimens(context.initial_population_size); for (auto&& specimen : specimens) { specimen.value() = context.generator(); } evaluate(specimens); communicate_stage(stage_type::generated, specimens, std::forward<Functions>(observers)...); repeat(context.max_iterations, [&] { context.selector(specimens, context.breeding_population_size); communicate_stage(stage_type::selected, specimens, std::forward<Functions>(observers)...); specimens = breed(specimens); evaluate(specimens); communicate_stage(stage_type::bred, specimens, std::forward<Functions>(observers)...); }); return std::move(*std::max_element(specimens.begin(), specimens.end(), [this](const evaluated_specimen_type& lhs, const evaluated_specimen_type& rhs) { return context.comparator(lhs.rating(), rhs.rating()); })); } template<class Specimen, class Rating> template<class... Functions> inline void genetic_algorithm<Specimen, Rating>::communicate_stage(stage_type stage, const std::vector<evaluated_specimen_type>& specimens, Functions&&... observers) const { (void)stage; (void)specimens; ((void)observers(*this, stage, specimens), ...); } template<class Specimen, class Rating> inline void genetic_algorithm<Specimen, Rating>::evaluate(std::vector<evaluated_specimen_type>& specimens) const { for (auto&& specimen : specimens) { specimen.evaluate(context.evaluator); } } template<class Specimen, class Rating> inline auto genetic_algorithm<Specimen, Rating>::breed(const std::vector<evaluated_specimen_type>& specimens) const -> std::vector<evaluated_specimen_type> { const std::size_t specimen_count = specimens.size(); std::vector<evaluated_specimen_type> result; const std::size_t reserve = specimen_count * (specimen_count - 1) / 2; result.reserve(reserve); for (auto it = specimens.begin(); it != specimens.end(); ++it) { const specimen_type& father = it->value(); std::for_each(std::next(it), specimens.end(), [&](const evaluated_specimen_type& mother) { result.emplace_back(evaluated_specimen_type {context.breeder(father, mother.value())}); }); } Ensures(result.size() == reserve); return result; } #endif
{ "alphanum_fraction": 0.7541694463, "avg_line_length": 41.9300699301, "ext": "h", "hexsha": "db19cd4bfc4e98ecd5b444c97f6e0e89fdd7f5df", "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": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SirEmentaler/Eugenics-Wars", "max_forks_repo_path": "Genetic-Algorithm-Library/genetic_algorithm.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "SirEmentaler/Eugenics-Wars", "max_issues_repo_path": "Genetic-Algorithm-Library/genetic_algorithm.h", "max_line_length": 173, "max_stars_count": null, "max_stars_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "SirEmentaler/Eugenics-Wars", "max_stars_repo_path": "Genetic-Algorithm-Library/genetic_algorithm.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1321, "size": 5996 }
#ifndef PyGSL_BLOCK_HELPERS_H #define PyGSL_BLOCK_HELPERS_H 1 /* * Author: Pierre Schnizer * * */ /***************************************************************************** * The functions in this file are implemented in src/init/block_helpers* * * These functions try to simplify the conversion between the PyArrayObjects * * and the gsl_vector and gsl_matrix types. Further they try to provide a * * compatibility layer for the different implementations of the * * PyArrayObjects (Numeric, numarray, numpy). All code using the functions * * must: * * Use these functions here :-) * * Declare all varibales referencing dimensions and indexing arrays * * "PyGSL_array_index_t" * * Expect these variables to be either of type int or long. This most * * probable is only noticable on 64bit architectures. * *****************************************************************************/ /* #define PY_ARRAY_UNIQUE_SYMBOL PyGSL_PY_ARRAY_API */ #ifndef _PyGSL_API_MODULE /* * Not possible to just import the declaration of the PyArrayObject struct. The * pointer comes along as well ... * */ #ifndef PyGSL_IMPORT_ARRAY #define NO_IMPORT_ARRAY #endif #endif /* _PyGSL_API_MODULE */ #include <pygsl/intern.h> #include <pygsl/utils.h> #include <pygsl/general_helpers.h> #include <limits.h> /* * Build array info out of various parts. * * array_flag */ #if ULONG_MAX < 0xffffff #error "unsigned long not big enough for array info" #else typedef unsigned long PyGSL_array_info_t; #endif /* typedef Py_ssize_t PyGSL_array_index_t; */ /* #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #endif */ #include <pygsl/arrayobject.h> #ifdef PyGSL_NUMPY #include <numpy/arrayobject.h> #endif #ifdef PyGSL_NUMERIC #include <Numeric/arrayobject.h> #endif #ifdef PyGSL_NUMARRAY #include <numarray/libnumarray.h> #endif #if (!defined PyGSL_NUMPY) && (!defined PyGSL_NUMERIC) && (!defined PyGSL_NUMARRAY) #error "Neither numpy nor numarray nor Numeric is defined!" #endif /* * required for 64 bit machines; backward compability. I rather perfer * to declare it as a long as its just my functions. * * For now I keep it as the same type as the underlaying array package * uses for its conversions. */ #ifdef PyGSL_NUMERIC typedef int PyGSL_array_index_t; #endif #ifdef PyGSL_NUMARRAY typedef maybelong PyGSL_array_index_t; #endif #ifdef PyGSL_NUMPY /* typedef intp PyGSL_array_index_t; */ typedef npy_intp PyGSL_array_index_t; #endif #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> enum PyGSL_Array_Flags { PyGSL_NON_CONTIGUOUS = 0, PyGSL_CONTIGUOUS = 1, /* Additional flags needed for numarray and numpy */ PyGSL_INPUT_ARRAY = 2, PyGSL_OUTPUT_ARRAY = 4, PyGSL_IO_ARRAY = 8, }; /* * Convienience functions for handling the flags */ #define PyGSL_GET_ARRAYFLAG(flag) (( (flag) >> 0) & 0x000000ff) #define PyGSL_GET_ARRAYTYPE(flag) (( (flag) >> 8) & 0x000000ff) #define PyGSL_GET_TYPESIZE(flag) (( (flag) >> 16) & 0x000000ff) #define PyGSL_GET_ARGNUM(flag) (( (flag) >> 24) & 0x000000ff) #define PyGSL_BUILD_ARRAY_INFO(array_flag, array_type, type_size, argnum) \ (\ ( ((array_flag) & 0x000000ff) << 0) + \ ( ((array_type) & 0x000000ff) << 8) + \ ( ((type_size) & 0x000000ff) << 16) + \ ( ((argnum) & 0x000000ff) << 24) \ ) #define PyGSL_DARRAY_INFO(array_flag, argnum) \ PyGSL_BUILD_ARRAY_INFO(array_flag, PyArray_DOUBLE, sizeof(double), argnum) #define PyGSL_DARRAY_CINPUT(argnum) PyGSL_DARRAY_INFO(PyGSL_CONTIGUOUS | PyGSL_INPUT_ARRAY, argnum) #define PyGSL_DARRAY_INPUT(argnum) PyGSL_DARRAY_INFO(PyGSL_NON_CONTIGUOUS | PyGSL_INPUT_ARRAY, argnum) /* * PyGSL_New_Array: * Generate an new array with the specified dimensions. * * The numpy backend expects an array of int, whereas * the numarray backend expects an array of long */ PyGSL_API_EXTERN PyArrayObject * PyGSL_New_Array(int nd, PyGSL_array_index_t *dimensions, int type); /* * PyGSL_Copy_Array: * * Copy an array. The output array will have the same * size as the input array. */ PyGSL_API_EXTERN PyArrayObject * PyGSL_Copy_Array(PyArrayObject *, int type); /* * PyGSL_STRIDE_RECALC: * Recalc a stride and check if it is okay * * Numpy calculates strides in bytes, gsl as multiple of the basis type size * * Return value: * -1: Conversion Failed * pos : recalculated stride */ PyGSL_API_EXTERN int PyGSL_stride_recalc(PyGSL_array_index_t strides, int basis_type_size, PyGSL_array_index_t * stride_recalc); /* * PyGSL_PyArray_generate_gsl_vector_view : * Generate an new array of given dimensions . * * This function will try to convert the object, to a Python integer and * generate an apropriate one dimensional numpy array. * * Input : * object : a general python object * array_type : the required C type for the array * argument number : The argument number. Used for error reporting * * Output: * : a pointer to a PyArrayObject or NULL in case * of error. This object must be dereferenced. */ PyGSL_API_EXTERN PyArrayObject * PyGSL_PyArray_generate_gsl_vector_view(PyObject *src, int array_type, int argnum); /* * PyGSL_PyArray_generate_gsl_matrix_view : * Generate an new array of given dimensions . * * This function will try to convert the object, to a sequence of two Python * integer and generate an apropriate two dimensional numpy array. * * Input : * object : a general python object * array_type : the required C type for the array * argument number : The argument number. Used for error reporting * * Output: * : a pointer to a PyArrayObject or NULL in case * of error. This object must be dereferenced. */ PyGSL_API_EXTERN PyArrayObject * PyGSL_PyArray_generate_gsl_matrix_view(PyObject *src, int array_type, int argnum); /* * Check if a python object can be used as a vector. If so return an * approbriate python array object. * * * Input: * src ... the python object * size ... the required size. Pass -1 if it should not be checked. * * array_type ... the required type. * flag ... shall be an input or output or inout array? * ... shall it be contiguous? * argnum ... the positional argument number. Used when reporting an * error * * Information if the stride of the vector should be * recalulated to the native C type. * type_size ... the size of the native C type (typically sizeof(type)). * If stride is NULL this value is without meaning. * * *stride ... the recalculated stride. If NULL stride will not be * recalulated, and the following items can be of any value * * info ... info structure passed by callbacks for reporting an error * * Convienience macros: * PyGSL_DVECTOR_CHECK(src, size, flag, argnum, stride, info) */ PyGSL_API_EXTERN PyArrayObject * PyGSL_vector_check(PyObject *src, PyGSL_array_index_t size, PyGSL_array_info_t ainfo, PyGSL_array_index_t *stride, PyGSL_error_info * info); /* * Check if a python object can be used as a vector. If so return an * approbriate python array object. * * * Input: * src ... the python object * * size1 ... the required size of the first dimension. Pass -1 if it * should not be checked. * size2 ... the required size of the second dimension. Pass -1 if it * should not be checked. * * array_type ... the required type. * flag ... shall be an input or output or inout array? * shall it be contiguous? * argnum ... the positional argument number. Used when reporting an * error * * Information if the stride of the vector should be * recalulated to the native C type. * type_size ... the size of the native C type (typically sizeof(type)). * If stride is NULL this value is without meaning. * * *stride1 ... the recalculated stride. If NULL stride will not be * recalulated, and the following items can be of any value * *stride2 ... the recalculated stride. If NULL stride will not be * recalulated, and the following items can be of any value * * info ... info structure passed by callbacks for reporting an error * * Convienience macros: * PyGSL_DMATRIX_CHECK(src, size1, size2, flag, argnum, stride1, stride2, info) */ PyGSL_API_EXTERN PyArrayObject * PyGSL_matrix_check(PyObject *src, PyGSL_array_index_t size1, PyGSL_array_index_t size2, PyGSL_array_info_t ainfo, PyGSL_array_index_t *stride1, PyGSL_array_index_t *stride2, PyGSL_error_info * info); /* * PyGSL_copy_pyarray_to_gslvector * Copy the contents of a pyarray to a gsl_vector. * * * Input : * f : a pointer to the target vector * object : a general python object * n : number of elements * info : a PyGSL_Error_info struct. Used for error * reporting during callback evaluation. Pass * NULL if not needed. * * Output: * : GSL_SUCCESS | GSL_FAILURE * */ PyGSL_API_EXTERN int PyGSL_copy_pyarray_to_gslvector(gsl_vector *f, PyObject *object, PyGSL_array_index_t n, PyGSL_error_info * info); /* * PyGSL_copy_pyarray_to_gslmatrix * Copy the contents of a pyarray to a gsl_matrix. * * * Input : * f : a pointer to the target gsl_vector * object : a general python object referring to a numpy * array * n : number of elements in the first dimension * p : number of elements in the second dimension * info : a PyGSL_error_info struct. Used for error * reporting during callback evaluation. Pass * NULL if not needed. * * Output: * : GSL_SUCCESS | GSL_FAILURE * */ PyGSL_API_EXTERN int PyGSL_copy_pyarray_to_gslmatrix(gsl_matrix *f, PyObject *object, PyGSL_array_index_t n, PyGSL_array_index_t p, PyGSL_error_info * info); PyGSL_API_EXTERN PyArrayObject * PyGSL_vector_or_double(PyObject *src, PyGSL_array_info_t ainfo, PyGSL_array_index_t size, PyGSL_error_info * info); /* * PyGSL_copy_gslvector_to_pyarrary : * Generate a new numpy array of approbriate size and copy the * data of the vector to it. * * * Input : * x : a gsl_vector * Output: * : a pointer to a PyArrayObject or NULL in case * of error. This object must be dereferenced. */ PyGSL_API_EXTERN PyArrayObject * PyGSL_copy_gslvector_to_pyarray(const gsl_vector *x); /* * PyGSL_copy_gslmatrix_to_pyarrary : * Generate a new numpy array of approbriate size and copy the * data of the matrix to it. * * * Input : * x : a gsl_matrix * Output: * : a pointer to a PyArrayObject or NULL in case * of error. This object must be dereferenced. */ PyGSL_API_EXTERN PyArrayObject * PyGSL_copy_gslmatrix_to_pyarray(const gsl_matrix *x); #ifndef _PyGSL_API_MODULE #define PyGSL_stride_recalc \ (*(int (*)(PyGSL_array_index_t, int, PyGSL_array_index_t * )) PyGSL_API[PyGSL_stride_recalc_NUM]) #define PyGSL_New_Array \ (*(PyArrayObject * (*)(int, PyGSL_array_index_t *, int)) PyGSL_API[PyGSL_PyArray_new_NUM]) #define PyGSL_Copy_Array \ (*(PyArrayObject * (*)(PyArrayObject *)) PyGSL_API[PyGSL_PyArray_copy_NUM]) #ifdef NO_PyGSL_LEGACY #define PyGSL_PyArray_prepare_gsl_vector_view \ (*(PyArrayObject * (*)(PyObject *, int, int, PyGSL_array_index_t, int, PyGSL_error_info *)) \ PyGSL_API[PyGSL_PyArray_prepare_gsl_vector_view_NUM]) #define PyGSL_PyArray_prepare_gsl_matrix_view \ (*(PyArrayObject * (*)(PyObject *, int, int, PyGSL_array_index_t, PyGSL_array_index_t, int, PyGSL_error_info *)) \ PyGSL_API[PyGSL_PyArray_prepare_gsl_matrix_view_NUM]) #endif /* NO_PyGSL_LEGACY */ #define PyGSL_PyArray_generate_gsl_vector_view \ (*(PyArrayObject *(*)(PyObject *, int, int)) PyGSL_API[PyGSL_PyArray_generate_gsl_vector_view_NUM]) #define PyGSL_PyArray_generate_gsl_matrix_view \ (*(PyArrayObject *(*)(PyObject *, int, int)) PyGSL_API[PyGSL_PyArray_generate_gsl_matrix_view_NUM]) #define PyGSL_copy_pyarray_to_gslvector \ (*(int (*) (gsl_vector *, PyObject *, PyGSL_array_index_t, PyGSL_error_info *)) PyGSL_API[PyGSL_copy_pyarray_to_gslvector_NUM]) #define PyGSL_copy_pyarray_to_gslmatrix \ (*(int (*) (gsl_matrix *, PyObject *, PyGSL_array_index_t, PyGSL_array_index_t, PyGSL_error_info *)) PyGSL_API[PyGSL_copy_pyarray_to_gslmatrix_NUM]) #define PyGSL_copy_gslvector_to_pyarray \ (*(PyArrayObject * (*)(const gsl_vector *)) PyGSL_API[ PyGSL_copy_gslvector_to_pyarray_NUM]) #define PyGSL_copy_gslmatrix_to_pyarray \ (*(PyArrayObject * (*)(const gsl_matrix *)) PyGSL_API[ PyGSL_copy_gslmatrix_to_pyarray_NUM]) #define PyGSL_vector_or_double \ (*(PyArrayObject * (*)(PyObject *, PyGSL_array_info_t , PyGSL_array_index_t, PyGSL_error_info *)) \ PyGSL_API[PyGSL_vector_or_double_NUM]) #define PyGSL_vector_check \ (*(PyArrayObject * (*) (PyObject *, PyGSL_array_index_t, \ PyGSL_array_info_t, PyGSL_array_index_t *, PyGSL_error_info *)) \ PyGSL_API[PyGSL_vector_check_NUM]) #define PyGSL_matrix_check \ (*(PyArrayObject * (*) (PyObject *, PyGSL_array_index_t, PyGSL_array_index_t, \ PyGSL_array_info_t, PyGSL_array_index_t *, PyGSL_array_index_t *, PyGSL_error_info *)) \ PyGSL_API[PyGSL_matrix_check_NUM]) #define PyGSL_array_check (*(int (*)(PyObject *)) PyGSL_API[PyGSL_array_check_NUM]) #define PyGSL_array_return(ob) ((PyObject *) ob) #endif /* _PyGSL_API_MODULE */ #define PyGSL_STRIDE_RECALC(strides, basis_type_size, stride_recalc) \ ( \ (((strides) % (basis_type_size)) == 0) \ ? \ ( ((*(stride_recalc)) = (strides) / (basis_type_size)), GSL_SUCCESS ) \ : \ PyGSL_stride_recalc(strides, basis_type_size, stride_recalc) \ ) /* #define PyGSL_DVECTOR_CHECK(src, size, info, stride, info) \ PyGSL_vector_check(src, size, PyArray_DOUBLE, sizeof(double), flag, argnum, stride, info) #define PyGSL_DMATRIX_CHECK(src, size1, size2, flag, argnum, stride1, stride2, info) \ PyGSL_vector_check(src, size1, size2, PyArray_DOUBLE, sizeof(double), flag, argnum, stride1, stride2, info) */ #ifdef PyGSL_NUMPY #include <pygsl/block_helpers_numpy.h> #endif #ifdef PyGSL_NUMERIC #include <pygsl/block_helpers_numeric.h> #endif #ifdef PyGSL_NUMARRAY #include <pygsl/block_helpers_numarray.h> #endif #endif /* PyGSL_BLOCK_HELPERS_H */
{ "alphanum_fraction": 0.62833764, "avg_line_length": 37.1945080092, "ext": "h", "hexsha": "1e9bade888d0827a4f723637767a2909475c0614", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/Include/pygsl/block_helpers.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "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": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/Include/pygsl/block_helpers.h", "max_line_length": 148, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/Include/pygsl/block_helpers.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3983, "size": 16254 }
#ifndef SVD_H #define SVD_H #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_multimin.h> /** * Computes, stores, and maintains a singular value decomposition of a gsl_matrix. * * A matrix-pointer is passed to the SVD on construction. This pointer is kept through * the life-time of the SVD object (but ownership is not assumed). If the contents * of the matrix is changed, the SVD can be update to reflect the change using the * abstract UpdateFromMatrix function. This is not automatically done on construction. */ class SVD{ protected: const int m, n; ///< Dimensions of matrix /** Decomposes M into U*S*V^t. */ SVD(gsl_matrix* M); public: gsl_matrix * const matrix; //TODO: Make private gsl_matrix * const U; //TODO: Make private gsl_matrix * const V; //TODO: Make private gsl_vector * const S; //TODO: Make private /** Constructs an SVD object. If MKL is available it will be an MKLSVD and if GSL * is available it will be GSLSVD */ static SVD* createSVD(gsl_matrix* M); virtual ~SVD(); /** Update U, V_t and S to reflect the decomposition of matrix. */ virtual void UpdateFromMatrix() = 0; /** Compute the pseudo-inverse of matrix */ gsl_matrix* PseudoInverse() const; /** Compute the pseudo-inverse of matrix using a damping factor of lambda. */ gsl_matrix* PseudoInverse(double lambda) const; /** Print the SVD to standard out */ void print() const; }; #endif
{ "alphanum_fraction": 0.6994680851, "avg_line_length": 28.3773584906, "ext": "h", "hexsha": "37d5877322c62e1faecbb3943ca6d059dfc6bde7", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_forks_repo_path": "src/math/SVD.h", "max_issues_count": 8, "max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z", "max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_issues_repo_path": "src/math/SVD.h", "max_line_length": 86, "max_stars_count": 1, "max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy", "max_stars_repo_path": "src/math/SVD.h", "max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z", "num_tokens": 393, "size": 1504 }
/* * agentlib.h * * Created on: Jul. 5, 2019 * Author: takis */ #ifndef MY_INCLUDES_AGENTLIB_H_ #define MY_INCLUDES_AGENTLIB_H_ /******************************************************************************************************** * INCLUDES * ****************************************************************************************************** */ #include <vector> #include <string> #include <fstream> // my own includes #include <gsl/gsl_blas.h> #include <gsl/gsl_math.h> #include <math.h> /******************************************************************************************************** * MACROS * ****************************************************************************************************** */ #define Nx 100 // number of columns in physical environment #define Ny 100 // number of rows in physical environment #define MaxMapEntries 48 // maximum number of contexts #define MaxIterations 9999 // maximum number of times main mapping loop can execute #define SenseRange 75 // units of distance that the agent can "see" #define MinVectorNorm 0.01 // a landmark must be further away than 1 cm from the agent #define MATSIZE 8 // matrix dimension (MATSIZE x MATSIZE) for analysis /******************************************************************************************************** * TYPEDEFs * ****************************************************************************************************** */ typedef std::vector<std::vector<std::string> > vvs_t; // 2D vector type for the // physical environment typedef vvs_t::size_type vvs_sz_t; // size_type for 2D vector type typedef enum e_region_t // enumerate the possible regions { R0, R1, R2, R3, R4, R5 } region_t; typedef enum e_orient_t // enumerate the possible directions { North, NorthEast, East, SouthEast, South, SouthWest, West, NorthWest } orient_t; typedef enum e_scan_direction_t // scan goes from top left to bottom right, // or from bottom right to top left { SE, NW } scan_direction_t; struct loc_t // type for a location in the physical environment { vvs_sz_t X; vvs_sz_t Y; }; struct read_data_t // type for storing data read from file { std::string context; region_t region; }; struct dprec_t // define a type to store dot products and corresponding directions { orient_t dir; double dp; }; /******************************************************************************************************** * FUNCTION PROTOTYPES * ****************************************************************************************************** */ /* * function: sgn * purpose: determines the sign of a double variable * parameters: a real number (double) * returns: +1 or -1 (short int) * */ short int sgn(double); /* * function: load_known_contexts_from_file * purpose: reads pairs of tokens from a file of the form <string, unsigned_integer> <newline> * parameters: string consisting of the file name * returns: a vector of read_data_t elements * */ std::vector<read_data_t> loadKnownContextsfromFile(const std::string); /* * function: load_global_map_with_file_data * purpose: fills contextual/associative map data structure with information in vector of read_data_t elements * parameters: the associate map (passed by reference), and the vector of read_data_t elements, passed by constant reference * returns: nothing (void function)space * */ void loadGlobalMapwithFileData(std::map<std::string, region_t>&, const std::vector<read_data_t>&); /* * function: convertContextStringtoMatrix * purpose: takes a key string associated with the spatial associative map, and converts it into a matrix * parameters: the context string * returns: a matrix (of type gsl_matrix_float*) */ gsl_matrix_float *convertContextStringtoMatrix(const std::string&); /* * function: mat2Norm * purpose: compute the 2-norm of a matrix from the definition on page 291 of * Matrix Analysis, Horn & Johnson * parameters: a matrix of type gsl_matrix_float* * returns: the matrix 2-norm value */ float mat2Norm(const gsl_matrix_float); /* * function: matTr * purpose: yields the transformation matrix we need, T_k, where k=0,+/-1,+/-2,... * parameters: an integer (k) * returns: a matrix of type gsl_matrix_float* * */ gsl_matrix_float *matTr(int); /* * function: compareContexts * purpose: compare context matrices, return the closeness value * parameters: two matrices to be compared, of type gsl_matrix_float* * returns: a closeness value, the greater, the closer the matrices are */ float compareContexts(const gsl_matrix_float*, const gsl_matrix_float*); /* * function: alphaK * purpose: implements a continuous monotonically decreasing function * parameters: a real number, x (float) * returns: (float) exp(-x) */ float alphaK(const float); /* * function: agentScan360 * purpose: at a fixed position (loc_t, first parameter) in the physical environment, deduce the context string, * which consists of relative position data, e.g., lm_A to East, lm_B to SW, to be identified * as the key AEBSW for the associative map; * parameters: the agent's location, the associative map, the physical map, and the landmark locations * returns: nothing (changes are made to the associative map) */ void agentScan360(loc_t, std::map<std::string, region_t>&, const vvs_t&, const std::vector<loc_t>&, const std::vector<std::string>&); /* * function: scan * purpose: survey a rectangular subset of 2D space, either in a SE or a NW sense, using recursion * parameters: rA (top left corner of scan), rB (bottom right corner of scan), r0 (agent current location) * spatial_mem (associative map of space), physmap (physical map of space) * returns: nothing (void type, but changes are made to the spatial memory, a.k.a., the associate map) */ void scan(bool& done, const scan_direction_t, loc_t, loc_t, loc_t, std::map<std::string, region_t>&, const vvs_t&, const std::map<char, loc_t>&, const std::vector<std::string>&); // scan(bool& done, const scan_direction_t dir, loc_t rA, loc_t rB, loc_t r0, std::map<std::string, region_t>& spatial_mem, const vvs_t& physmap, const std::map<char, loc_t>& landmarks, const std::vector<std::string>& orient_str) #endif /* MY_INCLUDES_AGENTLIB_H_ */
{ "alphanum_fraction": 0.6116907027, "avg_line_length": 31.9509803922, "ext": "h", "hexsha": "8b2de9b302ab3e05b91ef06b33b4a044eedebcec", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-11-17T15:29:51.000Z", "max_forks_repo_forks_event_min_datetime": "2020-11-17T15:29:51.000Z", "max_forks_repo_head_hexsha": "04837a23af6e37757dd2291cb8feedc2fcf305ee", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "takiszourntos/accelerated-cpp", "max_forks_repo_path": "chp7/proj_tz_chp7_map_self-guided_0/my_includes/agentlib.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "04837a23af6e37757dd2291cb8feedc2fcf305ee", "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": "takiszourntos/accelerated-cpp", "max_issues_repo_path": "chp7/proj_tz_chp7_map_self-guided_0/my_includes/agentlib.h", "max_line_length": 237, "max_stars_count": 1, "max_stars_repo_head_hexsha": "04837a23af6e37757dd2291cb8feedc2fcf305ee", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "takiszourntos/accelerated-cpp", "max_stars_repo_path": "chp7/proj_tz_chp7_map_self-guided_0/my_includes/agentlib.h", "max_stars_repo_stars_event_max_datetime": "2020-07-11T04:09:30.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-11T04:09:30.000Z", "num_tokens": 1603, "size": 6518 }
#include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf_gamma.h> #include <time.h> #include <math.h> #include <stdlib.h> #ifndef RANFUN_H #define RANFUN_H #define min(x,y) ((x) < (y) ? (x) : (y)) #define max(x,y) ((x) > (y) ? (x) : (y)) inline double sqr( double x) { return (x*x);} //interface for gsl_compare // x==y, 0, x<y, -1, x>y, 1. int fcmp (double x, double y, double epsilon = 0.00000000001); /*Interface with gsl*/ /*Available random number generators from gsl gsl_rng_taus see http://sourceware.cygnus.com/gsl/ref/gsl-ref_5.html*/ #define GENERATOR gsl_rng_taus /*to use inline functions in gsl (in c++)*/ /*define DHAVE_INLINE at compile time*/ #ifdef DHAVE_INLINE #define INLINE inline #endif #ifndef DHAVE_INLINE #define INLINE /*nothing*/ #endif void Seed(unsigned long int s); unsigned long int GetSeed(); double Un01(); /*Un01() */ double Unab(double a, double b); /*U(a,b]*/ unsigned int Un0n(int n); /*Uniform integer in { 0, 1, ..., n-1 }*/ int Sign(); /*random -1 or 1*/ double NorSim(double m, double sigma); /*Normal*/ double ExpSim(double mu); /*p(x) dx = {1 \over \mu} \exp(-x/\mu) dx*/ double GammaSim(double a, double b); /*Gamma: p(x) dx = K x^{a-1} e^{-x/b} dx*/ double GammaDens(double x, double a, double b); /*density for beta, as above */ double BetaSim(double a, double b); /*Beta: p(x) dx = K x^{a-1} (1-x)^{b-1} dx */ double BetaDens(double x, double a, double b); /*density for beta, as above */ unsigned int BiSim( double p, int n); /*Binomial: p^k (1-p)^{n-k} */ /*Log of Special function Gamma*/ double LogGamma(double x); #endif
{ "alphanum_fraction": 0.6428145498, "avg_line_length": 20.4512195122, "ext": "h", "hexsha": "6061b46baf8095f445b891a79a3aa4cdb0f3f471", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2019-06-14T13:27:02.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-07T03:10:31.000Z", "max_forks_repo_head_hexsha": "ef2857caddb1be9faac0173ad15d030684780ade", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SFlantua/Workshops", "max_forks_repo_path": "UW_ACES2016/cpp/ranfun.h", "max_issues_count": 9, "max_issues_repo_head_hexsha": "ef2857caddb1be9faac0173ad15d030684780ade", "max_issues_repo_issues_event_max_datetime": "2016-12-14T18:14:40.000Z", "max_issues_repo_issues_event_min_datetime": "2016-07-25T19:44:00.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "SFlantua/Workshops", "max_issues_repo_path": "UW_ACES2016/cpp/ranfun.h", "max_line_length": 81, "max_stars_count": 3, "max_stars_repo_head_hexsha": "ef2857caddb1be9faac0173ad15d030684780ade", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "SFlantua/Workshops", "max_stars_repo_path": "UW_ACES2016/cpp/ranfun.h", "max_stars_repo_stars_event_max_datetime": "2021-01-14T22:49:11.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-25T16:00:10.000Z", "num_tokens": 527, "size": 1677 }
/* multiroots/test.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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_test.h> #include <gsl/gsl_multiroots.h> #include <gsl/gsl_ieee_utils.h> #include "test_funcs.h" int test_fdf (const char * desc, gsl_multiroot_function_fdf * function, initpt_function initpt, double factor, const gsl_multiroot_fdfsolver_type * T); int test_f (const char * desc, gsl_multiroot_function_fdf * fdf, initpt_function initpt, double factor, const gsl_multiroot_fsolver_type * T); int main (void) { const gsl_multiroot_fsolver_type * fsolvers[5] ; const gsl_multiroot_fsolver_type ** T1 ; const gsl_multiroot_fdfsolver_type * fdfsolvers[5] ; const gsl_multiroot_fdfsolver_type ** T2 ; double f; fsolvers[0] = gsl_multiroot_fsolver_dnewton; fsolvers[1] = gsl_multiroot_fsolver_broyden; fsolvers[2] = gsl_multiroot_fsolver_hybrid; fsolvers[3] = gsl_multiroot_fsolver_hybrids; fsolvers[4] = 0; fdfsolvers[0] = gsl_multiroot_fdfsolver_newton; fdfsolvers[1] = gsl_multiroot_fdfsolver_gnewton; fdfsolvers[2] = gsl_multiroot_fdfsolver_hybridj; fdfsolvers[3] = gsl_multiroot_fdfsolver_hybridsj; fdfsolvers[4] = 0; gsl_ieee_env_setup(); f = 1.0 ; T1 = fsolvers ; while (*T1 != 0) { test_f ("Rosenbrock", &rosenbrock, rosenbrock_initpt, f, *T1); test_f ("Roth", &roth, roth_initpt, f, *T1); test_f ("Powell badly scaled", &powellscal, powellscal_initpt, f, *T1); test_f ("Brown badly scaled", &brownscal, brownscal_initpt, f, *T1); test_f ("Powell singular", &powellsing, powellsing_initpt, f, *T1); test_f ("Wood", &wood, wood_initpt, f, *T1); test_f ("Helical", &helical, helical_initpt, f, *T1); test_f ("Discrete BVP", &dbv, dbv_initpt, f, *T1); test_f ("Trig", &trig, trig_initpt, f, *T1); T1++; } T2 = fdfsolvers ; while (*T2 != 0) { test_fdf ("Rosenbrock", &rosenbrock, rosenbrock_initpt, f, *T2); test_fdf ("Roth", &roth, roth_initpt, f, *T2); test_fdf ("Powell badly scaled", &powellscal, powellscal_initpt, f, *T2); test_fdf ("Brown badly scaled", &brownscal, brownscal_initpt, f, *T2); test_fdf ("Powell singular", &powellsing, powellsing_initpt, f, *T2); test_fdf ("Wood", &wood, wood_initpt, f, *T2); test_fdf ("Helical", &helical, helical_initpt, f, *T2); test_fdf ("Discrete BVP", &dbv, dbv_initpt, f, *T2); test_fdf ("Trig", &trig, trig_initpt, f, *T2); T2++; } exit (gsl_test_summary ()); } void scale (gsl_vector * x, double factor); void scale (gsl_vector * x, double factor) { size_t i, n = x->size; if (gsl_vector_isnull(x)) { for (i = 0; i < n; i++) { gsl_vector_set (x, i, factor); } } else { for (i = 0; i < n; i++) { double xi = gsl_vector_get(x, i); gsl_vector_set(x, i, factor * xi); } } } int test_fdf (const char * desc, gsl_multiroot_function_fdf * function, initpt_function initpt, double factor, const gsl_multiroot_fdfsolver_type * T) { int status; double residual = 0; size_t i, n = function->n, iter = 0; gsl_vector *x = gsl_vector_alloc (n); gsl_matrix *J = gsl_matrix_alloc (n, n); gsl_multiroot_fdfsolver *s; (*initpt) (x); if (factor != 1.0) scale(x, factor); s = gsl_multiroot_fdfsolver_alloc (T, n); gsl_multiroot_fdfsolver_set (s, function, x); do { iter++; status = gsl_multiroot_fdfsolver_iterate (s); if (status) break ; status = gsl_multiroot_test_residual (s->f, 0.0000001); } while (status == GSL_CONTINUE && iter < 1000); #ifdef DEBUG printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); printf("\n"); printf("f "); gsl_vector_fprintf (stdout, s->f, "%g"); printf("\n"); #endif #ifdef TEST_JACOBIAN { double r,sum; size_t j; gsl_multiroot_function f1 ; f1.f = function->f ; f1.n = function->n ; f1.params = function->params ; gsl_multiroot_fdjacobian (&f1, s->x, s->f, GSL_SQRT_DBL_EPSILON, J); /* compare J and s->J */ r=0;sum=0; for (i = 0; i < n; i++) for (j = 0; j< n ; j++) { double u = gsl_matrix_get(J,i,j); double su = gsl_matrix_get(s->J, i, j); r = fabs(u - su)/(1e-6 + 1e-6 * fabs(u)); sum+=r; if (fabs(u - su) > 1e-6 + 1e-6 * fabs(u)) printf("broken jacobian %g\n", r); } printf("avg r = %g\n", sum/(n*n)); } #endif for (i = 0; i < n ; i++) { residual += fabs(gsl_vector_get(s->f, i)); } gsl_multiroot_fdfsolver_free (s); gsl_matrix_free(J); gsl_vector_free(x); gsl_test(status, "%s on %s (%g), %u iterations, residual = %.2g", T->name, desc, factor, iter, residual); return status; } int test_f (const char * desc, gsl_multiroot_function_fdf * fdf, initpt_function initpt, double factor, const gsl_multiroot_fsolver_type * T) { int status; size_t i, n = fdf->n, iter = 0; double residual = 0; gsl_vector *x; gsl_multiroot_fsolver *s; gsl_multiroot_function function; function.f = fdf->f; function.params = fdf->params; function.n = n ; x = gsl_vector_alloc (n); (*initpt) (x); if (factor != 1.0) scale(x, factor); s = gsl_multiroot_fsolver_alloc (T, n); gsl_multiroot_fsolver_set (s, &function, x); /* printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); printf("\n"); */ /* printf("f "); gsl_vector_fprintf (stdout, s->f, "%g"); printf("\n"); */ do { iter++; status = gsl_multiroot_fsolver_iterate (s); if (status) break ; status = gsl_multiroot_test_residual (s->f, 0.0000001); } while (status == GSL_CONTINUE && iter < 1000); #ifdef DEBUG printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); printf("\n"); printf("f "); gsl_vector_fprintf (stdout, s->f, "%g"); printf("\n"); #endif for (i = 0; i < n ; i++) { residual += fabs(gsl_vector_get(s->f, i)); } gsl_multiroot_fsolver_free (s); gsl_vector_free(x); gsl_test(status, "%s on %s (%g), %u iterations, residual = %.2g", T->name, desc, factor, iter, residual); return status; }
{ "alphanum_fraction": 0.6275822767, "avg_line_length": 26.8927203065, "ext": "c", "hexsha": "dd1bb672838f62ce9a1d1c9094b009a5ec50001f", "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/multiroots/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/multiroots/test.c", "max_line_length": 151, "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/multiroots/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": 2247, "size": 7019 }
#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_math.h> #include <sys/stat.h> #include <sys/types.h> #include "allvars.h" #include "proto.h" #ifdef SUBFIND #include "fof.h" #include "subfind.h" /*! Structure for communication during the density computation. Holds data that is sent to other processors. */ static struct densdata_in { MyDouble Pos[3]; MyFloat Hsml; int NodeList[NODELISTLENGTH]; } *DensDataIn, *DensDataGet; static struct densdata_out { MyFloat Rho; MyFloat VelDisp, Vx, Vy, Vz; int Ngb; } *DensDataResult, *DensDataOut; static MyFloat *DM_Vx, *DM_Vy, *DM_Vz; static long long Ntotal; #ifdef DENSITY_SPLIT_BY_TYPE void subfind_density(int j_in) #else void subfind_density(void) #endif { long long ntot; int i, j, ndone, ndone_flag, npleft, dummy, iter = 0; MyFloat *Left, *Right; char *Todo; int ngrp, sendTask, recvTask, place, nexport, nimport; double vel_to_phys, dmax1, dmax2, t0, t1; #ifdef DENSITY_SPLIT_BY_TYPE int j_target; if(j_in < 0) j_target = -j_in - 1; else j_target = j_in; #endif if(ThisTask == 0) { #ifdef DENSITY_SPLIT_BY_TYPE printf("finding densities, mode %d \n", j_in); #else printf("finding densities for all particles\n"); #endif fflush(stdout); } /* allocate buffers to arrange communication */ Ngblist = (int *) mymalloc(NumPart * sizeof(int)); Dist2list = (double *) mymalloc(NumPart * sizeof(double)); All.BunchSize = (int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) + sizeof(struct densdata_in) + sizeof(struct densdata_out) + sizemax(sizeof(struct densdata_in), sizeof(struct densdata_out)))); DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index)); DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist)); Left = mymalloc(sizeof(MyFloat) * NumPart); Right = mymalloc(sizeof(MyFloat) * NumPart); Todo = mymalloc(sizeof(char) * NumPart); DM_Vx = mymalloc(sizeof(MyFloat) * NumPart); DM_Vy = mymalloc(sizeof(MyFloat) * NumPart); DM_Vz = mymalloc(sizeof(MyFloat) * NumPart); for(i = 0; i < NumPart; i++) { Left[i] = Right[i] = 0; P[i].DM_NumNgb = 0; Todo[i] = 1; } /* we will repeat the whole thing for those particles where we didn't find enough neighbours */ do { t0 = second(); i = 0; /* begin with this index */ do { for(j = 0; j < NTask; j++) { Send_count[j] = 0; Exportflag[j] = -1; } /* do local particles and prepare export list */ for(nexport = 0; i < NumPart; i++) { if(Todo[i]) #ifdef DENSITY_SPLIT_BY_TYPE if(P[i].Type == j_target) { if(subfind_density_evaluate(i, 0, &nexport, Send_count, j_in) < 0) break; } #else if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES))) { if(subfind_density_evaluate(i, 0, &nexport, Send_count) < 0) break; } #endif } qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare); MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD); for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++) { Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask]; nimport += Recv_count[j]; if(j > 0) { Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1]; Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1]; } } DensDataGet = (struct densdata_in *) mymalloc(nimport * sizeof(struct densdata_in)); DensDataIn = (struct densdata_in *) mymalloc(nexport * sizeof(struct densdata_in)); /* prepare particle data for export */ for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; DensDataIn[j].Pos[0] = P[place].Pos[0]; DensDataIn[j].Pos[1] = P[place].Pos[1]; DensDataIn[j].Pos[2] = P[place].Pos[2]; DensDataIn[j].Hsml = P[place].DM_Hsml; memcpy(DensDataIn[j].NodeList, DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int)); } /* exchange particle data */ for(ngrp = 1; ngrp < (1 << PTask); ngrp++) { sendTask = ThisTask; recvTask = ThisTask ^ ngrp; if(recvTask < NTask) { if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0) { /* get the particles */ MPI_Sendrecv(&DensDataIn[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct densdata_in), MPI_BYTE, recvTask, TAG_DENS_A, &DensDataGet[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct densdata_in), MPI_BYTE, recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } myfree(DensDataIn); DensDataResult = (struct densdata_out *) mymalloc(nimport * sizeof(struct densdata_out)); DensDataOut = (struct densdata_out *) mymalloc(nexport * sizeof(struct densdata_out)); /* now do the particles that were sent to us */ for(j = 0; j < nimport; j++) #ifdef DENSITY_SPLIT_BY_TYPE subfind_density_evaluate(j, 1, &dummy, &dummy, j_in); #else subfind_density_evaluate(j, 1, &dummy, &dummy); #endif if(i >= NumPart) ndone_flag = 1; else ndone_flag = 0; MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); /* get the result */ for(ngrp = 1; ngrp < (1 << PTask); ngrp++) { sendTask = ThisTask; recvTask = ThisTask ^ ngrp; if(recvTask < NTask) { if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0) { /* send the results */ MPI_Sendrecv(&DensDataResult[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct densdata_out), MPI_BYTE, recvTask, TAG_DENS_B, &DensDataOut[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct densdata_out), MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } /* add the result to the local particles */ for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; P[place].DM_NumNgb += DensDataOut[j].Ngb; P[place].u.DM_Density += DensDataOut[j].Rho; #ifdef DENSITY_SPLIT_BY_TYPE if(j_in >= 0) /* sum up VelDisp only for own species */ #endif P[place].v.DM_VelDisp += DensDataOut[j].VelDisp; DM_Vx[place] += DensDataOut[j].Vx; DM_Vy[place] += DensDataOut[j].Vy; DM_Vz[place] += DensDataOut[j].Vz; } myfree(DensDataOut); myfree(DensDataResult); myfree(DensDataGet); } while(ndone < NTask); #ifdef DENSITY_SPLIT_BY_TYPE if(ThisTask == 0) printf("checking smoothing lenghs ... \n"); #endif /* do final operations on results */ for(i = 0, npleft = 0; i < NumPart; i++) { /* now check whether we had enough neighbours */ #ifdef DENSITY_SPLIT_BY_TYPE if(j_in < 0) Todo[i] = 0; if((P[i].Type != j_target) || (j_in < 0)) continue; #else if(!((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES))) continue; #endif if(Todo[i]) { if(P[i].DM_NumNgb != All.DesNumNgb && ((Right[i] - Left[i]) > 1.0e-4 * Left[i] || Left[i] == 0 || Right[i] == 0)) { /* need to redo this particle */ npleft++; if(P[i].DM_NumNgb < All.DesNumNgb) Left[i] = DMAX(P[i].DM_Hsml, Left[i]); else { if(Right[i] != 0) { if(P[i].DM_Hsml < Right[i]) Right[i] = P[i].DM_Hsml; } else Right[i] = P[i].DM_Hsml; } if(iter >= MAXITER - 10) { printf ("i=%d task=%d ID=%d Hsml=%g Left=%g Right=%g Ngbs=%g Right-Left=%g\n pos=(%g|%g|%g)\n", i, ThisTask, (int) P[i].ID, P[i].DM_Hsml, Left[i], Right[i], (double) P[i].DM_NumNgb, Right[i] - Left[i], P[i].Pos[0], P[i].Pos[1], P[i].Pos[2]); fflush(stdout); } if(Right[i] > 0 && Left[i] > 0) P[i].DM_Hsml = pow(0.5 * (pow(Left[i], 3) + pow(Right[i], 3)), 1.0 / 3); else { if(Right[i] == 0 && Left[i] == 0) endrun(8187); /* can't occur */ if(Right[i] == 0 && Left[i] > 0) P[i].DM_Hsml *= 1.26; if(Right[i] > 0 && Left[i] == 0) P[i].DM_Hsml /= 1.26; } } else Todo[i] = 0; } } sumup_large_ints(1, &npleft, &ntot); t1 = second(); if(ntot > 0) { iter++; if(iter > 0 && ThisTask == 0) { printf("ngb iteration %d: need to repeat for %d%09d particles. (took %g sec)\n", iter, (int) (ntot / 1000000000), (int) (ntot % 1000000000), timediff(t0, t1)); fflush(stdout); } if(iter > MAXITER) { printf("failed to converge in neighbour iteration in density()\n"); fflush(stdout); endrun(1155); } } } while(ntot > 0); vel_to_phys = 1.0 / All.Time; #ifdef DENSITY_SPLIT_BY_TYPE if(ThisTask == 0) printf("final operations ... \n"); #endif for(i = 0; i < NumPart; i++) #ifdef DENSITY_SPLIT_BY_TYPE if(P[i].Type == j_target && j_in >= 0) #else if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES))) #endif { #ifdef DENSITY_SPLIT_BY_TYPE if(P[i].DM_NumNgb == 0) endrun(5621); #endif DM_Vx[i] /= P[i].DM_NumNgb; DM_Vy[i] /= P[i].DM_NumNgb; DM_Vz[i] /= P[i].DM_NumNgb; P[i].v.DM_VelDisp /= P[i].DM_NumNgb; P[i].v.DM_VelDisp = vel_to_phys * sqrt(P[i].v.DM_VelDisp - DM_Vx[i] * DM_Vx[i] - DM_Vy[i] * DM_Vy[i] - DM_Vz[i] * DM_Vz[i]); } myfree(DM_Vz); myfree(DM_Vy); myfree(DM_Vx); myfree(Todo); myfree(Right); myfree(Left); myfree(DataNodeList); myfree(DataIndexTable); myfree(Dist2list); myfree(Ngblist); } /*! This function represents the core of the SPH density computation. The * target particle may either be local, or reside in the communication * buffer. */ #ifdef DENSITY_SPLIT_BY_TYPE int subfind_density_evaluate(int target, int mode, int *nexport, int *nsend_local, int tp) #else int subfind_density_evaluate(int target, int mode, int *nexport, int *nsend_local) #endif { int j, n; int startnode, numngb, ngb, listindex = 0; double hmax; double h, h2, hinv, hinv3; double rho, wk; double r, r2, u, mass_j, v2, vx, vy, vz; MyDouble *pos; rho = 0; numngb = 0; v2 = vx = vy = vz = 0; if(mode == 0) { pos = P[target].Pos; h = P[target].DM_Hsml; } else { pos = DensDataGet[target].Pos; h = DensDataGet[target].Hsml; } #ifdef DENSITY_SPLIT_BY_TYPE if(h == 0) endrun(5622); #endif h2 = h * h; hinv = 1.0 / h; hinv3 = hinv * hinv * hinv; if(mode == 0) { startnode = All.MaxPart; /* root node */ } else { startnode = DensDataGet[target].NodeList[0]; startnode = Nodes[startnode].u.d.nextnode; /* open it */ } numngb = 0; while(startnode >= 0) { while(startnode >= 0) { #ifdef DENSITY_SPLIT_BY_TYPE if(tp < 0) ngb = subfind_ngb_treefind_linkpairs(pos, h, target, &startnode, mode, &hmax, nexport, nsend_local); else ngb = subfind_ngb_treefind_linkngb(pos, h, target, &startnode, mode, &hmax, nexport, nsend_local); #else ngb = subfind_ngb_treefind_linkngb(pos, h, target, &startnode, mode, &hmax, nexport, nsend_local); #endif if(ngb < 0) return -1; #ifdef DENSITY_SPLIT_BY_TYPE if(tp >= 0) #endif if(mode == 0 && hmax > 0) { P[target].DM_Hsml = hmax; h = hmax; h2 = h * h; hinv = 1.0 / h; hinv3 = hinv * hinv * hinv; if(ngb != All.DesNumNgb) endrun(121); } numngb += ngb; for(n = 0; n < ngb; n++) { j = Ngblist[n]; r2 = Dist2list[n]; #ifdef DENSITY_SPLIT_BY_TYPE if(tp < 0) { h = P[j].DM_Hsml; if(h == 0) endrun(5622); h2 = h * h; hinv = 1.0 / h; hinv3 = hinv * hinv * hinv; } #endif if(r2 < h2) { r = sqrt(r2); u = r * hinv; if(u < 0.5) wk = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u); else wk = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u); mass_j = P[j].Mass; rho += (mass_j * wk); } vx += P[j].Vel[0]; vy += P[j].Vel[1]; vz += P[j].Vel[2]; v2 += P[j].Vel[0] * P[j].Vel[0] + P[j].Vel[1] * P[j].Vel[1] + P[j].Vel[2] * P[j].Vel[2]; } } if(mode == 1) { listindex++; if(listindex < NODELISTLENGTH) { startnode = DensDataGet[target].NodeList[listindex]; if(startnode >= 0) startnode = Nodes[startnode].u.d.nextnode; /* open it */ } } } if(mode == 0) { P[target].DM_NumNgb = numngb; P[target].u.DM_Density = rho; #ifdef DENSITY_SPLIT_BY_TYPE if(tp >= 0) /* sum up VelDisp only for own species */ #endif P[target].v.DM_VelDisp = v2; DM_Vx[target] = vx; DM_Vy[target] = vy; DM_Vz[target] = vz; } else { DensDataResult[target].Ngb = numngb; DensDataResult[target].Rho = rho; DensDataResult[target].VelDisp = v2; DensDataResult[target].Vx = vx; DensDataResult[target].Vy = vy; DensDataResult[target].Vz = vz; } return 0; } #ifdef DENSITY_SPLIT_BY_TYPE void subfind_setup_smoothinglengths(int j) #else void subfind_setup_smoothinglengths(void) #endif { int i, no, p; for(i = 0; i < NumPart; i++) { #ifdef DENSITY_SPLIT_BY_TYPE if(P[i].Type == j) #else if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES))) #endif { no = Father[i]; /* Not a good guess for gas/stars component, need more thought ! */ while(10 * All.DesNumNgb * P[i].Mass > Nodes[no].u.d.mass) { p = Nodes[no].u.d.father; if(p < 0) break; no = p; } #ifdef DENSITY_SPLIT_BY_TYPE if(P[i].Type == 0) P[i].DM_Hsml = PPP[i].Hsml; else #ifdef KEEP_DM_HSML_AS_GUESS if(P[i].DM_Hsml < 0) #endif P[i].DM_Hsml = pow(3.0 / (4 * M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 3) * Nodes[no].len; #else P[i].DM_Hsml = pow(3.0 / (4 * M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 3) * Nodes[no].len; #endif } } } static int Nhsml; static struct hsml_data { float Hsml; float Density; float VelDisp; MyIDType ID; } *Hsml_list; int subfind_compare_hsml_data(const void *a, const void *b) { if(((struct hsml_data *) a)->ID < ((struct hsml_data *) b)->ID) return -1; if(((struct hsml_data *) a)->ID > ((struct hsml_data *) b)->ID) return +1; return 0; } void subfind_save_densities(int num) { int i, nprocgroup, masterTask, groupTask; char buf[1000]; double t0, t1; if(ThisTask == 0) { printf("start saving smoothing lengths and densities\n"); fflush(stdout); } for(i = 0, Nhsml = 0; i < NumPart; i++) #ifdef DENSITY_SPLIT_BY_TYPE if(((1 << P[i].Type) & (DENSITY_SPLIT_BY_TYPE))) #else if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES))) #endif Nhsml++; MPI_Allgather(&Nhsml, 1, MPI_INT, Send_count, 1, MPI_INT, MPI_COMM_WORLD); for(i = 1, Send_offset[0] = 0; i < NTask; i++) Send_offset[i] = Send_offset[i - 1] + Send_count[i - 1]; sumup_large_ints(1, &Nhsml, &Ntotal); Hsml_list = mymalloc(Nhsml * sizeof(struct hsml_data)); for(i = 0, Nhsml = 0; i < NumPart; i++) #ifdef DENSITY_SPLIT_BY_TYPE if(((1 << P[i].Type) & (DENSITY_SPLIT_BY_TYPE))) #else if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES))) #endif { Hsml_list[Nhsml].Hsml = P[i].DM_Hsml; Hsml_list[Nhsml].Density = P[i].u.DM_Density; Hsml_list[Nhsml].VelDisp = P[i].v.DM_VelDisp; #ifdef SAVE_HSML_IN_IC_ORDER Hsml_list[Nhsml].ID = P[i].ID_ic_order; #else Hsml_list[Nhsml].ID = P[i].ID; #endif Nhsml++; } t0 = second(); parallel_sort(Hsml_list, Nhsml, sizeof(struct hsml_data), subfind_compare_hsml_data); t1 = second(); if(ThisTask == 0) { printf("Sorting of densities in ID sequence took = %g sec\n", timediff(t0, t1)); fflush(stdout); } if(ThisTask == 0) { sprintf(buf, "%s/hsmldir_%03d", All.OutputDir, num); mkdir(buf, 02755); } MPI_Barrier(MPI_COMM_WORLD); if(NTask < All.NumFilesWrittenInParallel) { printf ("Fatal error.\nNumber of processors must be a smaller or equal than `NumFilesWrittenInParallel'.\n"); endrun(241931); } nprocgroup = NTask / All.NumFilesWrittenInParallel; if((NTask % All.NumFilesWrittenInParallel)) nprocgroup++; masterTask = (ThisTask / nprocgroup) * nprocgroup; for(groupTask = 0; groupTask < nprocgroup; groupTask++) { if(ThisTask == (masterTask + groupTask)) /* ok, it's this processor's turn */ subfind_save_local_densities(num); MPI_Barrier(MPI_COMM_WORLD); /* wait inside the group */ } myfree(Hsml_list); } void subfind_save_local_densities(int num) { char fname[1000]; int i; float *tmp; FILE *fd; sprintf(fname, "%s/hsmldir_%03d/%s_%03d.%d", All.OutputDir, num, "hsml", num, ThisTask); if(!(fd = fopen(fname, "w"))) { printf("can't open file `%s`\n", fname); endrun(1183); } my_fwrite(&Nhsml, sizeof(int), 1, fd); my_fwrite(&Send_offset[ThisTask], sizeof(int), 1, fd); /* this is the number of IDs in previous files */ my_fwrite(&Ntotal, sizeof(long long), 1, fd); my_fwrite(&NTask, sizeof(int), 1, fd); tmp = mymalloc(Nhsml * sizeof(float)); for(i = 0; i < Nhsml; i++) tmp[i] = Hsml_list[i].Hsml; my_fwrite(tmp, sizeof(float), Nhsml, fd); for(i = 0; i < Nhsml; i++) tmp[i] = Hsml_list[i].Density; my_fwrite(tmp, sizeof(float), Nhsml, fd); for(i = 0; i < Nhsml; i++) tmp[i] = Hsml_list[i].VelDisp; my_fwrite(tmp, sizeof(float), Nhsml, fd); myfree(tmp); fclose(fd); } #endif
{ "alphanum_fraction": 0.5981413686, "avg_line_length": 23.5165562914, "ext": "c", "hexsha": "c7767a644ee5b758fdd9650833a15453c638c21a", "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/subfind_density.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/subfind_density.c", "max_line_length": 108, "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/subfind_density.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5973, "size": 17755 }