Search is not available for this dataset
text
string
meta
dict
#ifndef _PS_ #define _PS_ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <ctype.h> #include <math.h> #include <unistd.h> #include "../Parameter_files/COSMOLOGY.H" #include "../Parameter_files/INIT_PARAMS.H" #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include "cosmo_progs.c" #include "misc.c" /* New in v1.1 */ #define ERFC_NPTS (int) 75 #define ERFC_PARAM_DELTA (float) 0.1 static double log_erfc_table[ERFC_NPTS], erfc_params[ERFC_NPTS]; static gsl_interp_accel *erfc_acc; static gsl_spline *erfc_spline; double sigma_norm, R, theta_cmb, omhh, z_equality, y_d, sound_horizon, alpha_nu, f_nu, f_baryon, beta_c, d2fact, R_CUTOFF, DEL_CURR, SIG_CURR; /***** FUNCTION PROTOTYPES *****/ double init_ps(); /* initialize global variables, MUST CALL THIS FIRST!!! returns R_CUTOFF */ void free_ps(); /* deallocates the gsl structures from init_ps */ double splined_erfc(double); /* returns erfc for x>=0, using cubic spline in logy-x space */ double deltolindel(float del, float z); /* converts a non-linear overdensity, del, at z to a linear overdensity at z=0 */ double lindeltodel(float lindel, float z); /* converts a linear overdensity, del, at z=0 to a non-linear overdensity at redshift z */ double power_in_k(double k); /* Returns the value of the linear power spectrum density (i.e. <|delta_k|^2>/V) at a given k mode at z=0 */ double RtoM(double); /* R in Mpc, M in Msun */ double MtoR(double); /* R in Mpc, M in Msun */ double M_J_WDM(); /* returns the "effective Jeans mass" corresponding to the gas analog of WDM ; eq. 10 in BHO 2001 */ double sheth_delc(double del, double sig); double dNdM_st(double z, double M); double dNdM(double z, double M); double dnbiasdM(double M, float z, double M_o, float del_o); /* dnbiasdM */ double FgtrM(double z, double M); //calculates the fraction of mass contained in haloes with mass > M at redshift z double FgtrM_st(double z, double M); //calculates the fraction of mass contained in haloes with mass > M at redshift z, with Sheth-Tormen correction double FgtrM_bias(double z, double M, double del_bias, double sig_bias); //calculates the fraction of mass contained in haloes with mass > M at redshift z, in regions with a linear overdensity of del_bias, and standard deviation sig_bias double sigmaparam_FgtrM_bias(float z, float sigsmallR, float del_bias, float sig_bias);/* Uses sigma parameters instead of Mass for scale */ double FgtrM_bias_BL08(double z, double M, double del_bias, double sig_bias); // as above, but this version uses the hybrid perscription of Barkana & Loeb 2004 (specifically the separate integral version of eq. 2 in Barkana & Loeb 2008) double dicke(double z); //calculates the dicke growth function at redshift z double ddickedz(double z); /* Redshift derivative of the growth function at z */ double ddickedt(double z); /* Time derivative of the growth function at z */ double sigma_z0(double M); //calculates sigma at z=0 (no dicke) double dsigmasqdm_z0(double M); //calculates d(sigma^2)/dm at z=0 (i.e. does not include dicke growth) double TFmdm(double k); //Eisenstien & Hu power spectrum transfer function void TFset_parameters(); float get_R_c(); // returns R_CUTOFF double get_M_min_ion(float z); /***************************************/ /* Returns the minimum source mass for ionizing sources, according to user specifications */ double get_M_min_ion(float z){ double MMIN; if (ION_M_MIN < 0){ // use the virial temperature for Mmin if (ION_Tvir_MIN < 9.99999e3) // neutral IGM MMIN = TtoM(z, ION_Tvir_MIN, 1.22); else // ionized IGM MMIN = TtoM(z, ION_Tvir_MIN, 0.6); } else if (ION_Tvir_MIN < 0){ // use the mass MMIN = ION_M_MIN; } else{ fprintf(stderr, "You have to \"turn-off\" either the ION_M_MIN or \ the ION_Tvir_MIN option in ANAL_PARAMS.H\nAborting...\n"); return -1; } // check for WDM if (P_CUTOFF && ( MMIN < M_J_WDM())) MMIN = M_J_WDM(); // printf("Mmin is %e\n", MMIN); return MMIN; } /* Returns the minimum source mass for x-ray sources, according to user specifications */ double get_M_min_xray(float z){ double MMIN; if (X_RAY_Tvir_MIN < 9.99999e3) //neutral IGM MMIN = TtoM(z, X_RAY_Tvir_MIN, 1.22); else // ionized IGM MMIN = TtoM(z, X_RAY_Tvir_MIN, 0.6); // check for WDM if (P_CUTOFF && ( MMIN < M_J_WDM())) MMIN = M_J_WDM(); // printf("Mmin is %e\n", MMIN); return MMIN; } /* returns the "effective Jeans mass" in Msun corresponding to the gas analog of WDM ; eq. 10 in Barkana+ 2001 */ double M_J_WDM(){ double z_eq, fudge=60; if (!P_CUTOFF) return 0; z_eq = 3600*(OMm-OMb)*hlittle*hlittle/0.15; return fudge*3.06e8 * (1.5/g_x) * sqrt((OMm-OMb)*hlittle*hlittle/0.15) * pow(M_WDM, -4) * pow(z_eq/3000.0, 1.5); } /* converts a non-linear overdensity, del, at z to a linear overdensity at z=0 */ double deltolindel(float del, float z){ float onepdel = 1.0+del; return ( 1.68647 - 1.35*pow(onepdel,-2/3.0) + 0.78785*pow(onepdel,-0.58661) - 1.12431*pow(onepdel,-0.5) )/dicke(z); } /* converts a linear overdensity, del, at z=0 to a non-linear overdensity at redshift z */ double lindeltodel(float lindel, float z){ float prev_lindelguess, delcrit, delguess; float lindelguess, delmin, delmax, epsilon = 1.0e-7; // set the critical density corresponding to virialization // this will be maximum allowed del delcrit = Deltac_nonlinear(z)*rho_critz(z)/(OMm*RHOcrit*pow(1+z, 3)) - 1; delmin = -1; delmax = 500; prev_lindelguess = -1e10; while (1){ delguess = 0.5*(delmax+delmin); lindelguess = deltolindel(delguess, z); //fprintf(stderr, "%e\t%e\n", delmin, delmax); // fprintf(stderr, "%e\t%e\t%e\n\n", delguess, lindelguess, lindel); if ((fabs((lindelguess-lindel)/lindel) < epsilon ) || (fabs(lindelguess-lindel) < epsilon ) || (fabs(prev_lindelguess - lindelguess) < TINY ))// close enough, or resolution loop return delguess; if (lindelguess > lindel) delmax = delguess; else delmin = delguess; // check if we are above delcrit (see above) if (delmin > delcrit){ // printf("exced max at lindel=%e\n", lindel); return delcrit; } prev_lindelguess = lindelguess; } } /* R in Mpc, M in Msun */ double RtoM(double R){ // set M according to M<->R conversion defined by the filter type in ../Parameter_files/COSMOLOGY.H if (FILTER == 0) //top hat M = (4/3) PI <rho> R^3 return (4.0/3.0)*PI*pow(R,3)*(OMm*RHOcrit); else if (FILTER == 1) //gaussian: M = (2PI)^1.5 <rho> R^3 return pow(2*PI, 1.5) * OMm*RHOcrit * pow(R, 3); else // filter not defined fprintf(stderr, "No such filter = %i.\nResults are bogus.\n", FILTER); return -1; } /* R in Mpc, M in Msun */ double MtoR(double M){ // set R according to M<->R conversion defined by the filter type in ../Parameter_files/COSMOLOGY.H if (FILTER == 0) //top hat M = (4/3) PI <rho> R^3 return pow(3*M/(4*PI*OMm*RHOcrit), 1.0/3.0); else if (FILTER == 1) //gaussian: M = (2PI)^1.5 <rho> R^3 return pow( M/(pow(2*PI, 1.5) * OMm * RHOcrit), 1.0/3.0 ); else // filter not defined fprintf(stderr, "No such filter = %i.\nResults are bogus.\n", FILTER); return -1; } /* equation (5) from jenkis et al. (2001) */ double f_jenkins(float del, double sigsq){ if (del < 0){ fprintf(stderr, "ERROR: In function f_jenkins del_o must be less than del_1 = del_crit/dicke(z)!\nAborting...\n"); return 0; } // fprintf(stderr, "%f\t%f\n", del, sqrt(sigsq)); return sqrt(2/PI) * del/sqrt(sigsq) * pow(E, -0.5*del*del/sigsq); } float get_R_c(){ return R_CUTOFF; } /* sheth correction to delta crit */ double sheth_delc(double del, double sig){ return sqrt(SHETH_a)*del*(1 + SHETH_b*pow(sig*sig/(SHETH_a*del*del), SHETH_c)); } /* dnbiasdM */ double dnbiasdM(double M, float z, double M_o, float del_o){ double sigsq, del, sig_one, sig_o; if ((M_o-M) < TINY){ fprintf(stderr, "WARNING: In function dnbiasdM: M must be less than M_o!\nAborting...\n"); return -1; } del = Deltac/dicke(z) - del_o; if (del < 0){ fprintf(stderr, "ERROR: In function dnbiasdM: del_o must be less than del_1 = del_crit/dicke(z)!\nAborting...\n"); return 0; } sig_o = sigma_z0(M_o); sig_one = sigma_z0(M); sigsq = sig_one*sig_one - sig_o*sig_o; return -(RHOcrit*OMm)/M /sqrt(2*PI) *del*pow(sigsq,-1.5)*pow(E, -0.5*del*del/sigsq)*dsigmasqdm_z0(M); } /* FUNCTION dNdM(z, M) Computes the Press_schechter mass function with Sheth-Torman correction for ellipsoidal collapse at redshift z, and dark matter halo mass M (in solar masses). The return value is the number density per unit mass of halos in the mass range M to M+dM in units of: comoving Mpc^-3 Msun^-1 Reference: Sheth, Mo, Torman 2001 */ double dNdM_st(double z, double M){ double sigma, dsigmadm, nuhat, dicke_growth; dicke_growth = dicke(z); sigma = sigma_z0(M) * dicke_growth; dsigmadm = dsigmasqdm_z0(M) * dicke_growth*dicke_growth/(2.0*sigma); nuhat = sqrt(SHETH_a) * Deltac / sigma; return (-OMm*RHOcrit/M) * (dsigmadm/sigma) * sqrt(2/PI)*SHETH_A * (1+ pow(nuhat, -2*SHETH_p)) * nuhat * pow(E, -nuhat*nuhat/2.0); } /* FUNCTION dNdM(z, M) Computes the Press_schechter mass function at redshift z, and dark matter halo mass M (in solar masses). The return value is the number density per unit mass of halos in the mass range M to M+dM in units of: comoving Mpc^-3 Msun^-1 Reference: Padmanabhan, pg. 214 */ double dNdM(double z, double M){ double sigma, dsigmadm, dicke_growth; dicke_growth = dicke(z); sigma = sigma_z0(M) * dicke_growth; dsigmadm = dsigmasqdm_z0(M) * (dicke_growth*dicke_growth/(2*sigma)); return (-OMm*RHOcrit/M) * sqrt(2/PI) * (Deltac/(sigma*sigma)) * dsigmadm * pow(E, -(Deltac*Deltac)/(2*sigma*sigma)); } /* FUNCTION FgtrM_st(z, M) Computes the fraction of mass contained in haloes with mass > M at redshift z Uses Sheth-Torman correction */ double dFdlnM_st (double lnM, void *params){ double z = *(double *)params; double M = exp(lnM); return dNdM_st(z, M) * M * M; } double FgtrM_st(double z, double M){ double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = 0.001; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); F.function = &dFdlnM_st; F.params = &z; lower_limit = log(M); upper_limit = log(FMAX(1e16, M*100)); // printf("%f %f\n",lower_limit, upper_limit); gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); gsl_integration_workspace_free (w); return result / (OMm*RHOcrit); } /* FUNCTION FgtrM(z, M) Computes the fraction of mass contained in haloes with mass > M at redshift z */ double FgtrM(double z, double M){ double del, sig; del = Deltac/dicke(z); //regular spherical collapse delta sig = sigma_z0(M); return splined_erfc(del / (sqrt(2)*sig)); } /* calculates the fraction of mass contained in haloes with mass > M at redshift z, in regions with a linear overdensity of del_bias, and standard deviation sig_bias */ double FgtrM_bias(double z, double M, double del_bias, double sig_bias){ double del, sig, sigsmallR; sigsmallR = sigma_z0(M); if (!(sig_bias < sigsmallR)){ // biased region is smaller that halo! fprintf(stderr, "FgtrM_bias: Biased region is smaller than halo!\nResult is bogus.\n"); return 0; } del = Deltac/dicke(z) - del_bias; sig = sqrt(sigsmallR*sigsmallR - sig_bias*sig_bias); return splined_erfc(del / (sqrt(2)*sig)); } /* Uses sigma parameters instead of Mass for scale */ double sigmaparam_FgtrM_bias(float z, float sigsmallR, float del_bias, float sig_bias){ double del, sig; if (!(sig_bias < sigsmallR)){ // biased region is smaller that halo! fprintf(stderr, "local_FgtrM_bias: Biased region is smaller than halo!\nResult is bogus.\n"); return 0; } del = Deltac/dicke(z) - del_bias; sig = sqrt(sigsmallR*sigsmallR - sig_bias*sig_bias); return splined_erfc(del / (sqrt(2)*sig)); } /* Calculates the fraction of mass contained in haloes with mass > M at redshift z, in regions with a linear overdensity of del_bias, and standard deviation sig_bias. This version uses the hybrid perscription of Barkana & Loeb 2004 (specifically the separate integral version of eq. 2 in Barkana & Loeb 2008) */ double FgtrM_bias_BL08(double z, double M, double del_bias, double sig_bias){ return FgtrM_st(z, M) / FgtrM(z, M) * FgtrM_bias(z, M, del_bias, sig_bias); } /* FUNCTION dicke(z) Computes the dicke growth function at redshift z, i.e. the z dependance part of sigma References: Peebles, "Large-Scale...", pg.53 (eq. 11.16). Includes omega<=1 Nonzero Lambda case from Liddle et al, astro-ph/9512102, eqs. 6-8. and quintessence case from Wang et al, astro-ph/9804015 Normalized to dicke(z=0)=1 */ double dicke(double z){ double omegaM_z, dick_z, dick_0, x, x_0; double tiny = 1e-4; if (fabs(OMm-1.0) < tiny){ //OMm = 1 (Einstein de-Sitter) return 1.0/(1.0+z); } else if ( (OMl > (-tiny)) && (fabs(OMl+OMm+OMr-1.0) < 0.01) && (fabs(wl+1.0) < tiny) ){ //this is a flat, cosmological CONSTANT universe, with only lambda, matter and radiation //it is taken from liddle et al. omegaM_z = OMm*pow(1+z,3) / ( OMl + OMm*pow(1+z,3) + OMr*pow(1+z,4) ); dick_z = 2.5*omegaM_z / ( 1.0/70.0 + omegaM_z*(209-omegaM_z)/140.0 + pow(omegaM_z, 4.0/7.0) ); dick_0 = 2.5*OMm / ( 1.0/70.0 + OMm*(209-OMm)/140.0 + pow(OMm, 4.0/7.0) ); return dick_z / (dick_0 * (1.0+z)); } else if ( (OMtot < (1+tiny)) && (fabs(OMl) < tiny) ){ //open, zero lambda case (peebles, pg. 53) x_0 = 1.0/(OMm+0.0) - 1.0; dick_0 = 1 + 3.0/x_0 + 3*log(sqrt(1+x_0)-sqrt(x_0))*sqrt(1+x_0)/pow(x_0,1.5); x = fabs(1.0/(OMm+0.0) - 1.0) / (1+z); dick_z = 1 + 3.0/x + 3*log(sqrt(1+x)-sqrt(x))*sqrt(1+x)/pow(x,1.5); return dick_z/dick_0; } else if ( (OMl > (-tiny)) && (fabs(OMtot-1.0) < tiny) && (fabs(wl+1) > tiny) ){ fprintf(stderr, "IN WANG\n"); return -1; } fprintf(stderr, "No growth function!!! Output will be fucked up."); return -1; } /* redshift derivative of the growth function at z */ double ddicke_dz(double z){ float dz = 1e-10; double omegaM_z, ddickdz, dick_0, x, x_0, domegaMdz; return (dicke(z+dz)-dicke(z))/dz; } /* Time derivative of the growth function at z */ double ddickedt(double z){ float dz = 1e-10; double omegaM_z, ddickdz, dick_0, x, x_0, domegaMdz; double tiny = 1e-4; return (dicke(z+dz)-dicke(z))/dz/dtdz(z); // lazy non-analytic form getting if (fabs(OMm-1.0) < tiny){ //OMm = 1 (Einstein de-Sitter) return -pow(1+z,-2)/dtdz(z); } else if ( (OMl > (-tiny)) && (fabs(OMl+OMm+OMr-1.0) < 0.01) && (fabs(wl+1.0) < tiny) ){ //this is a flat, cosmological CONSTANT universe, with only lambda, matter and radiation //it is taken from liddle et al. omegaM_z = OMm*pow(1+z,3) / ( OMl + OMm*pow(1+z,3) + OMr*pow(1+z,4) ); domegaMdz = omegaM_z*3/(1+z) - OMm*pow(1+z,3)*pow(OMl + OMm*pow(1+z,3) + OMr*pow(1+z,4), -2) * (3*OMm*(1+z)*(1+z) + 4*OMr*pow(1+z,3)); dick_0 = OMm / ( 1.0/70.0 + OMm*(209-OMm)/140.0 + pow(OMm, 4.0/7.0) ); ddickdz = (domegaMdz/(1+z)) * (1.0/70.0*pow(omegaM_z,-2) + 1.0/140.0 + 3.0/7.0*pow(omegaM_z, -10.0/3.0)) * pow(1.0/70.0/omegaM_z + (209.0-omegaM_z)/140.0 + pow(omegaM_z, -3.0/7.0) , -2); ddickdz -= pow(1+z,-2)/(1.0/70.0/omegaM_z + (209.0-omegaM_z)/140.0 + pow(omegaM_z, -3.0/7.0)); return ddickdz / dick_0 / dtdz(z); } fprintf(stderr, "No growth function!!! Output will be fucked up."); return -1; } /* FUNCTION sigma_z0(M) Returns the standard deviation of the normalized, density excess (delta(x)) field, smoothed on the comoving scale of M (see filter definitions for M<->R conversion). The sigma is evaluated at z=0, with the time evolution contained in the dicke(z) factor, i.e. sigma(M,z) = sigma_z0(m) * dicke(z) normalized so that sigma_z0(M->8/h Mpc) = SIGMA8 in ../Parameter_files/COSMOLOGY.H NOTE: volume is normalized to = 1, so this is equvalent to the mass standard deviation M is in solar masses References: Padmanabhan, pg. 210, eq. 5.107 */ double dsigma_dk(double k, void *params){ double p, w, T, gamma, q, aa, bb, cc, kR; // get the power spectrum.. choice of 5: if (POWER_SPECTRUM == 0){ // Eisenstein & Hu T = TFmdm(k); // check if we should cuttoff power spectrum according to Bode et al. 2000 transfer function if (P_CUTOFF) T *= pow(1 + pow(BODE_e*k*R_CUTOFF, 2*BODE_v), -BODE_n/BODE_v); p = pow(k, POWER_INDEX) * T * T; } else if (POWER_SPECTRUM == 1){ // BBKS gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm); q = k / (hlittle*gamma); T = (log(1.0+2.34*q)/(2.34*q)) * pow( 1.0+3.89*q + pow(16.1*q, 2) + pow( 5.46*q, 3) + pow(6.71*q, 4), -0.25); p = pow(k, POWER_INDEX) * T * T; } else if (POWER_SPECTRUM == 2){ // Efstathiou,G., Bond,J.R., and White,S.D.M., MNRAS,258,1P (1992) gamma = 0.25; aa = 6.4/(hlittle*gamma); bb = 3.0/(hlittle*gamma); cc = 1.7/(hlittle*gamma); p = pow(k, POWER_INDEX) / pow( 1+pow( aa*k + pow(bb*k, 1.5) + pow(cc*k,2), 1.13), 2.0/1.13 ); } else if (POWER_SPECTRUM == 3){ // Peebles, pg. 626 gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm); aa = 8.0 / (hlittle*gamma); bb = 4.7 / pow(hlittle*gamma, 2); p = pow(k, POWER_INDEX) / pow(1 + aa*k + bb*k*k, 2); } else if (POWER_SPECTRUM == 4){ // White, SDM and Frenk, CS, 1991, 379, 52 gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm); aa = 1.7/(hlittle*gamma); bb = 9.0/pow(hlittle*gamma, 1.5); cc = 1.0/pow(hlittle*gamma, 2); p = pow(k, POWER_INDEX) * 19400.0 / pow(1 + aa*k + bb*pow(k, 1.5) + cc*k*k, 2); } else{ fprintf(stderr, "No such power spectrum defined: %i\nOutput is bogus.\n", POWER_SPECTRUM); p = 0; } // now get the value of the window function // NOTE: only use top hat for SIGMA8 normalization kR = k*R; if ( (FILTER == 0) || (sigma_norm < 0) ){ // top hat if ( (kR) < 1.0e-4 ){ w = 1.0;} // w converges to 1 as (kR) -> 0 else { w = 3.0 * (sin(kR)/pow(kR, 3) - cos(kR)/pow(kR, 2));} } else if (FILTER == 1){ // gaussian of width 1/R w = pow(E, -kR*kR/2.0); } else { fprintf(stderr, "No such filter: %i\nOutput is bogus.\n", FILTER); w=0; } return k*k*p*w*w; } double sigma_z0(double M){ double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = FRACT_FLOAT_ERR*10; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); double kstart, kend; R = MtoR(M); // now lets do the integral for sigma and scale it with sigma_norm kstart = 1.0e-99/R; kend = 350.0/R; lower_limit = kstart;//log(kstart); upper_limit = kend;//log(kend); F.function = &dsigma_dk; gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); gsl_integration_workspace_free (w); return sigma_norm * sqrt(result); } /* Returns the value of the linear power spectrum DENSITY (i.e. <|delta_k|^2>/V) at a given k mode linearly extrapolated to z=0 */ double power_in_k(double k){ double p, T, gamma, q, aa, bb, cc; // get the power spectrum.. choice of 5: if (POWER_SPECTRUM == 0){ // Eisenstein & Hu T = TFmdm(k); // check if we should cuttoff power spectrum according to Bode et al. 2000 transfer function if (P_CUTOFF) T *= pow(1 + pow(BODE_e*k*R_CUTOFF, 2*BODE_v), -BODE_n/BODE_v); p = pow(k, POWER_INDEX) * T * T; //p = pow(k, POWER_INDEX - 0.05*log(k/0.05)) * T * T; //running, alpha=0.05 } else if (POWER_SPECTRUM == 1){ // BBKS gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm); q = k / (hlittle*gamma); T = (log(1.0+2.34*q)/(2.34*q)) * pow( 1.0+3.89*q + pow(16.1*q, 2) + pow( 5.46*q, 3) + pow(6.71*q, 4), -0.25); p = pow(k, POWER_INDEX) * T * T; } else if (POWER_SPECTRUM == 2){ // Efstathiou,G., Bond,J.R., and White,S.D.M., MNRAS,258,1P (1992) gamma = 0.25; aa = 6.4/(hlittle*gamma); bb = 3.0/(hlittle*gamma); cc = 1.7/(hlittle*gamma); p = pow(k, POWER_INDEX) / pow( 1+pow( aa*k + pow(bb*k, 1.5) + pow(cc*k,2), 1.13), 2.0/1.13 ); } else if (POWER_SPECTRUM == 3){ // Peebles, pg. 626 gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm); aa = 8.0 / (hlittle*gamma); bb = 4.7 / pow(hlittle*gamma, 2); p = pow(k, POWER_INDEX) / pow(1 + aa*k + bb*k*k, 2); } else if (POWER_SPECTRUM == 4){ // White, SDM and Frenk, CS, 1991, 379, 52 gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm); aa = 1.7/(hlittle*gamma); bb = 9.0/pow(hlittle*gamma, 1.5); cc = 1.0/pow(hlittle*gamma, 2); p = pow(k, POWER_INDEX) * 19400.0 / pow(1 + aa*k + bb*pow(k, 1.5) + cc*k*k, 2); } else{ fprintf(stderr, "No such power spectrum defined: %i\nOutput is bogus.\n", POWER_SPECTRUM); p = 0; } return p*TWOPI*PI*sigma_norm*sigma_norm; } /* FUNCTION dsigmasqdm_z0(M) returns d/dm (sigma^2) (see function sigma), in units of Msun^-1 */ double dsigmasq_dm(double k, void *params){ double p, w, T, gamma, q, aa, bb, cc, dwdr, drdm, kR; // get the power spectrum.. choice of 5: if (POWER_SPECTRUM == 0){ // Eisenstein & Hu ApJ, 1999, 511, 5 T = TFmdm(k); // check if we should cuttoff power spectrum according to Bode et al. 2000 transfer function if (P_CUTOFF) T *= pow(1 + pow(BODE_e*k*R_CUTOFF, 2*BODE_v), -BODE_n/BODE_v); p = pow(k, POWER_INDEX) * T * T; //p = pow(k, POWER_INDEX - 0.05*log(k/0.05)) * T * T; //running, alpha=0.05 } else if (POWER_SPECTRUM == 1){ // BBKS gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm); q = k / (hlittle*gamma); T = (log(1.0+2.34*q)/(2.34*q)) * pow( 1.0+3.89*q + pow(16.1*q, 2) + pow( 5.46*q, 3) + pow(6.71*q, 4), -0.25); p = pow(k, POWER_INDEX) * T * T; } else if (POWER_SPECTRUM == 2){ // Efstathiou,G., Bond,J.R., and White,S.D.M., MNRAS,258,1P (1992) gamma = 0.25; aa = 6.4/(hlittle*gamma); bb = 3.0/(hlittle*gamma); cc = 1.7/(hlittle*gamma); p = pow(k, POWER_INDEX) / pow( 1+pow( aa*k + pow(bb*k, 1.5) + pow(cc*k,2), 1.13), 2.0/1.13 ); } else if (POWER_SPECTRUM == 3){ // Peebles, pg. 626 gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm); aa = 8.0 / (hlittle*gamma); bb = 4.7 / (hlittle*gamma); p = pow(k, POWER_INDEX) / pow(1 + aa*k + bb*k*k, 2); } else if (POWER_SPECTRUM == 4){ // White, SDM and Frenk, CS, 1991, 379, 52 gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm); aa = 1.7/(hlittle*gamma); bb = 9.0/pow(hlittle*gamma, 1.5); cc = 1.0/pow(hlittle*gamma, 2); p = pow(k, POWER_INDEX) * 19400.0 / pow(1 + aa*k + pow(bb*k, 1.5) + cc*k*k, 2); } else{ fprintf(stderr, "No such power spectrum defined: %i\nOutput is bogus.\n", POWER_SPECTRUM); p = 0; } // now get the value of the window function kR = k * R; if (FILTER == 0){ // top hat if ( (kR) < 1.0e-4 ){ w = 1.0; }// w converges to 1 as (kR) -> 0 else { w = 3.0 * (sin(kR)/pow(kR, 3) - cos(kR)/pow(kR, 2));} // now do d(w^2)/dm = 2 w dw/dr dr/dm if ( (kR) < 1.0e-10 ){ dwdr = 0;} else{ dwdr = 9*cos(kR)*k/pow(kR,3) + 3*sin(kR)*(1 - 3/(kR*kR))/(kR*R);} //3*k*( 3*cos(kR)/pow(kR,3) + sin(kR)*(-3*pow(kR, -4) + 1/(kR*kR)) );} // dwdr = -1e8 * k / (R*1e3); drdm = 1.0 / (4.0*PI * OMm*RHOcrit * R*R); } else if (FILTER == 1){ // gaussian of width 1/R w = pow(E, -kR*kR/2.0); dwdr = - k*kR * w; drdm = 1.0 / (pow(2*PI, 1.5) * OMm*RHOcrit * 3*R*R); } else { fprintf(stderr, "No such filter: %i\nOutput is bogus.\n", FILTER); w=0; } // printf("%e\t%e\t%e\t%e\t%e\t%e\t%e\n", k, R, p, w, dwdr, drdm, dsigmadk[1]); return k*k*p*2*w*dwdr*drdm * d2fact; } double dsigmasqdm_z0(double M){ double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = FRACT_FLOAT_ERR*10; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); double kstart, kend; R = MtoR(M); // now lets do the integral for sigma and scale it with sigma_norm kstart = 1.0e-99/R; kend = 350.0/R; lower_limit = kstart;//log(kstart); upper_limit = kend;//log(kend); d2fact = M*10000/sigma_z0(M); F.function = &dsigmasq_dm; gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); gsl_integration_workspace_free (w); return sigma_norm * sigma_norm * result /d2fact; } /* FUNCTION TFmdm is the power spectrum transfer function from Eisenstein & Hu ApJ, 1999, 511, 5 */ double TFmdm(double k){ double q, gamma_eff, q_eff, TF_m, q_nu; q = k*pow(theta_cmb,2)/omhh; gamma_eff=sqrt(alpha_nu) + (1.0-sqrt(alpha_nu))/(1.0+pow(0.43*k*sound_horizon, 4)); q_eff = q/gamma_eff; TF_m= log(E+1.84*beta_c*sqrt(alpha_nu)*q_eff); TF_m /= TF_m + pow(q_eff,2) * (14.4 + 325.0/(1.0+60.5*pow(q_eff,1.11))); q_nu = 3.92*q/sqrt(f_nu/N_nu); TF_m *= 1.0 + (1.2*pow(f_nu,0.64)*pow(N_nu,0.3+0.6*f_nu)) / (pow(q_nu,-1.6)+pow(q_nu,0.8)); // printf("%f %e %f %f %f %f\n",omhh,f_nu,f_baryon,N_nu,y_d,alpha_nu); // printf("%f %f %f %f\n", beta_c,sound_horizon,theta_cmb,z_equality); //printf("%f %e %f %f %f\n\n",q, k, gamma_eff, q_nu, TF_m); return TF_m; } void TFset_parameters(){ double z_drag, R_drag, R_equality, p_c, p_cb, f_c, f_cb, f_nub, k_equality; z_equality = 25000*omhh*pow(theta_cmb, -4) - 1.0; k_equality = 0.0746*omhh/(theta_cmb*theta_cmb); z_drag = 0.313*pow(omhh,-0.419) * (1 + 0.607*pow(omhh, 0.674)); z_drag = 1 + z_drag*pow(OMb*hlittle*hlittle, 0.238*pow(omhh, 0.223)); z_drag *= 1291 * pow(omhh, 0.251) / (1 + 0.659*pow(omhh, 0.828)); y_d = (1 + z_equality) / (1.0 + z_drag); R_drag = 31.5 * OMb*hlittle*hlittle * pow(theta_cmb, -4) * 1000 / (1.0 + z_drag); R_equality = 31.5 * OMb*hlittle*hlittle * pow(theta_cmb, -4) * 1000 / (1.0 + z_equality); sound_horizon = 2.0/3.0/k_equality * sqrt(6.0/R_equality) * log( (sqrt(1+R_drag) + sqrt(R_drag+R_equality)) / (1.0 + sqrt(R_equality)) ); p_c = -(5 - sqrt(1 + 24*(1 - f_nu-f_baryon)))/4.0; p_cb = -(5 - sqrt(1 + 24*(1 - f_nu)))/4.0; f_c = 1 - f_nu - f_baryon; f_cb = 1 - f_nu; f_nub = f_nu+f_baryon; alpha_nu = (f_c/f_cb) * (2*(p_c+p_cb)+5)/(4*p_cb+5.0); alpha_nu *= 1 - 0.553*f_nub+0.126*pow(f_nub,3); alpha_nu /= 1-0.193*sqrt(f_nu)+0.169*f_nu; alpha_nu *= pow(1+y_d, p_c-p_cb); alpha_nu *= 1+ (p_cb-p_c)/2.0 * (1.0+1.0/(4.0*p_c+3.0)/(4.0*p_cb+7.0))/(1.0+y_d); beta_c = 1.0/(1.0-0.949*f_nub); } double init_ps(){ double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = FRACT_FLOAT_ERR*10; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); double kstart, kend; int i; double x; // Set cuttoff scale for WDM (eq. 4 in Barkana et al. 2001) in comoving Mpc R_CUTOFF = 0.201*pow((OMm-OMb)*hlittle*hlittle/0.15, 0.15)*pow(g_x/1.5, -0.29)*pow(M_WDM, -1.15); // fprintf(stderr, "For M_DM = %.2e keV, R_CUTOFF is: %.2e comoving Mpc\n", M_WDM, R_CUTOFF); if (!P_CUTOFF) // fprintf(stderr, "But you have selected CDM, so this is ignored\n"); omhh = OMm*hlittle*hlittle; theta_cmb = T_cmb / 2.7; // Translate Parameters into forms GLOBALVARIABLES form f_nu = OMn/OMm; f_baryon = OMb/OMm; if (f_nu < TINY) f_nu = 1e-10; if (f_baryon < TINY) f_baryon = 1e-10; TFset_parameters(); sigma_norm = -1; R = 8.0/hlittle; kstart = 1.0e-99/R; kend = 350.0/R; lower_limit = kstart;//log(kstart); upper_limit = kend;//log(kend); F.function = &dsigma_dk; gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); gsl_integration_workspace_free (w); sigma_norm = SIGMA8/sqrt(result); //takes care of volume factor /* initialize the lookup table for erfc */ /* for (i=0; i<=ERFC_NPTS; i++){ erfc_params[i] = i*ERFC_PARAM_DELTA; log_erfc_table[i] = log(erfcc(erfc_params[i])); } // Set up spline table erfc_acc = gsl_interp_accel_alloc (); erfc_spline = gsl_spline_alloc (gsl_interp_cspline, ERFC_NPTS); gsl_spline_init(erfc_spline, erfc_params, log_erfc_table, ERFC_NPTS); */ return R_CUTOFF; } void free_ps(){ /* gsl_spline_free (erfc_spline); gsl_interp_accel_free(erfc_acc); */ return; } double splined_erfc(double x){ if (x < 0){ //printf("WARNING: Negative value %e passed to splined_erfc. Returning 1\n", x); return 1; } return erfcc(x); // the interpolation below doesn't seem to be stable in Ts.c if (x > ERFC_PARAM_DELTA*(ERFC_NPTS-1)) return erfcc(x); else return exp(gsl_spline_eval(erfc_spline, x, erfc_acc)); } #endif
{ "alphanum_fraction": 0.6385912767, "avg_line_length": 35.2853658537, "ext": "c", "hexsha": "25096a8768c39a15061af3ce7111e9a423d0ea13", "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": "5819f960e1d01df32ca5c4a6c8231046fe097a06", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "BellaNasirudin/py21cmmc", "max_forks_repo_path": "src/py21cmmc/_21cmfast/Cosmo_c_files/ps.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5819f960e1d01df32ca5c4a6c8231046fe097a06", "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": "BellaNasirudin/py21cmmc", "max_issues_repo_path": "src/py21cmmc/_21cmfast/Cosmo_c_files/ps.c", "max_line_length": 238, "max_stars_count": null, "max_stars_repo_head_hexsha": "5819f960e1d01df32ca5c4a6c8231046fe097a06", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "BellaNasirudin/py21cmmc", "max_stars_repo_path": "src/py21cmmc/_21cmfast/Cosmo_c_files/ps.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 10725, "size": 28934 }
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: Paul R. C. Kent, kentpr@ornl.gov, Oak Ridge National Laboratory // Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory // // File created by: Paul R. C. Kent, kentpr@ornl.gov, Oak Ridge National Laboratory ////////////////////////////////////////////////////////////////////////////////////// // http://pathintegrals.info // ///////////////////////////////////////////////////////////// #ifndef VECTOR_OPS_H #define VECTOR_OPS_H // extern "C"{ // #ifdef USE_MKL // #include <mkl_cblas.h> // #else // #include <cblas.h> // #endif // } #include "Blitz.h" #include "../config.h" typedef TinyVector<int, 3> Int3; typedef Array<std::complex<double>, 1> zVec; typedef Array<cVec3, 1> zVecVec; typedef Array<cMat3, 1> zMatVec; #ifdef USE_CBLAS extern "C" { #ifdef USE_MKL_CBLAS #include <mkl_cblas.h> #else #include <cblas.h> #endif } #else #define F77_DZNRM2 F77_FUNC(dznrm2, DZNRM2) #define F77_ZDSCAL F77_FUNC(zdscal, ZDSCAL) #define F77_ZDOTC F77_FUNC(zdotc, ZDOTC) #define F77_ZGEMV F77_FUNC(zgemv, ZGEMV) #define F77_ZAXPY F77_FUNC(zaxpy, ZAXPY) extern "C" double F77_DZNRM2(const int* N, const void* X, const int* INC); extern "C" void F77_ZDSCAL(const int* N, double* ALPHA, const void* X, const int* INC); // extern "C" void F77_ZDOTC (std::complex<double> *z, const int *N, // const void *X, const int *INCX, // const void *Y, const int *INCY); extern "C" std::complex<double> F77_ZDOTC(const int* N, const void* X, const int* INCX, const void* Y, const int* INCY); extern "C" void F77_ZGEMV(char* TRANS, const int* M, const int* N, std::complex<double>* alpha, const void* A, const int* LDA, const void* X, const int* INCX, std::complex<double>* beta, const void* Y, const int* INCY); extern "C" void F77_ZAXPY(const int* N, std::complex<double>* ALPHA, void* X, int* INCX, void* Y, int* INCY); #endif #ifdef USE_CBLAS inline void Normalize(zVec& c) { double norm = cblas_dznrm2(c.size(), c.data(), 1); norm = 1.0 / norm; cblas_zdscal(c.size(), norm, c.data(), 1); } inline double norm(const zVec& c) { return cblas_dznrm2(c.size(), c.data(), 1); } inline std::complex<double> conjdot(zVec& cA, zVec& cB) { std::complex<double> z; cblas_zdotc_sub(cA.size(), cA.data(), 1, cB.data(), 1, &z); return z; } inline void Orthogonalize(const Array<std::complex<double>, 2>& A, zVec& x) { int m = A.rows(); int n = A.cols(); assert(n == x.size()); std::complex<double> zero(0.0, 0.0); std::complex<double> one(1.0, 0.0); std::complex<double> minusone(-1.0, 0.0); Array<std::complex<double>, 1> S(m); cblas_zgemv(CblasColMajor, CblasConjTrans, n, m, &one, A.data(), n, x.data(), 1, &zero, S.data(), 1); cblas_zgemv(CblasRowMajor, CblasTrans, m, n, &minusone, A.data(), n, S.data(), 1, &one, x.data(), 1); } #else inline void Normalize(zVec& c) { const int inc = 1; int n = c.size(); double norm = F77_DZNRM2(&n, c.data(), &inc); norm = 1.0 / norm; F77_ZDSCAL(&n, &norm, c.data(), &inc); } inline double norm(const zVec& c) { double norm; int n = c.size(); const int inc = 1; return F77_DZNRM2(&n, c.data(), &inc); } inline std::complex<double> conjdot(zVec& cA, zVec& cB) { const int n = cA.size(); const int incA = 1; const int incB = 1; return F77_ZDOTC(&n, cA.data(), &incA, cB.data(), &incB); // std::complex<double> z; // F77_ZDOTC (&z, &n, cA.data(), &incA, cB.data(), &incB); // return z; } inline void Orthogonalize(const Array<std::complex<double>, 2>& A, zVec& x) { int m = A.rows(); int n = A.cols(); assert(n == x.size()); std::complex<double> zero(0.0, 0.0); std::complex<double> one(1.0, 0.0); std::complex<double> minusone(-1.0, 0.0); Array<std::complex<double>, 1> S(m); // Calculate overlaps // Calling with column major and ConjTrans is equivalent to // conjugate of untransposed row major char trans = 'C'; const int inc = 1; F77_ZGEMV(&trans, &n, &m, &one, A.data(), &n, x.data(), &inc, &zero, S.data(), &inc); // cblas_zgemv(CblasColMajor, CblasConjTrans, n, m, &one, // A.data(), n, x.data(), 1, &zero, S.data(), 1); // for (int i=0; i<m; i++) { // fprintf (stderr, "S[%d] = %18.14f + %18.14fi\n", // real(S[i]), imag(S[i])); // Now, subtract off components * overlaps trans = 'T'; F77_ZGEMV(&trans, &m, &n, &minusone, A.data(), &n, S.data(), &inc, &one, x.data(), &inc); // cblas_zgemv(CblasRowMajor, CblasTrans, m, n, &minusone, // A.data(), n, S.data(), 1, &one, x.data(), 1); } #endif inline double realconjdot(zVec& cA, zVec& cB) { return conjdot(cA, cB).real(); } inline double mag(std::complex<double> x) { return (x.real() * x.real() + x.imag() * x.imag()); } inline void Orthogonalize2(Array<std::complex<double>, 2>& A, zVec& x, int lastBand) { int m = A.rows(); int n = A.cols(); assert(n == x.size()); zVec Ar; Array<std::complex<double>, 1> S(m); for (int row = 0; row <= lastBand; row++) { Ar.reference(A(row, Range::all())); S(row) = conjdot(Ar, x); } for (int row = 0; row <= lastBand; row++) x -= S(row) * A(row, Range::all()); // for (int row=0; row<=lastBand; row++) { // Ar.reference (A(row,Range::all())); // S(row) = conjdot (Ar, x); // if (mag(S(row)) > 1.0e-14) { // std::cerr << "row = " << row << " lastband = " << lastBand << std::endl; // std::cerr << "Error in Orthogonalize2!, s = " << S(row) << std::endl; // double norm = realconjdot (Ar, Ar); // std::cerr << "norm = " << norm << std::endl; // } // } } inline void OrthogExcluding(const Array<std::complex<double>, 2>& A, zVec& x, int excluding) { int m = A.rows(); int n = A.cols(); assert(n == x.size()); zVec Ar; #ifndef __INTEL_COMPILER std::complex<double> S[m]; for (int row = 0; row < m; row++) { Ar.reference(A(row, Range::all())); S[row] = conjdot(Ar, x); } for (int row = 0; row < m; row++) if (row != excluding) x -= S[row] * A(row, Range::all()); #else double Sre[m], Sim[m]; for (int row = 0; row < m; row++) { Ar.reference(A(row, Range::all())); std::complex<double> S = conjdot(Ar, x); Sre[row] = real(S); Sim[row] = imag(S); } for (int row = 0; row < m; row++) if (row != excluding) x -= std::complex<double>(Sre[row], Sim[row]) * A(row, Range::all()); #endif } inline void OrthogLower(const Array<std::complex<double>, 2>& A, zVec& x, int currBand) { int m = currBand; int n = A.cols(); assert(n == x.size()); zVec Ar; std::complex<double> S; for (int row = 0; row < m; row++) { Ar.reference(A(row, Range::all())); S = conjdot(Ar, x); x -= S * A(row, Range::all()); } } inline void GramSchmidt(Array<std::complex<double>, 2>& A) { zVec a, b; for (int i = 0; i < A.rows(); i++) { a.reference(A(i, Range::all())); Normalize(a); for (int j = i + 1; j < A.rows(); j++) { b.reference(A(j, Range::all())); b = b - (conjdot(a, b) * a); Normalize(b); } } } inline void Orthogonalize(Array<std::complex<double>, 2>& A) { zVec x, y; Array<std::complex<double>, 1> S(A.rows()); for (int iter = 0; iter < 40; iter++) { for (int i = 0; i < A.rows(); i++) { x.reference(A(i, Range::all())); for (int j = i + 1; j < A.rows(); j++) { y.reference(A(j, Range::all())); S(j) = conjdot(y, x); } for (int j = i + 1; j < A.rows(); j++) { y.reference(A(j, Range::all())); x -= S(j) * y; } Normalize(x); } } } inline void CheckOrthog(const Array<std::complex<double>, 2>& A, zVec& x) { zVec Ai; double normInv = 1.0 / norm(x); for (int i = 0; i < A.rows(); i++) { Ai.reference(A(i, Range::all())); if (normInv * mag(conjdot(Ai, x)) > 1.0e-13) { std::cerr << "CheckOrthog failed for i=" << i << ".\n"; exit(1); } } } inline void zaxpy(std::complex<double> alpha, const Array<std::complex<double>, 1>& x, const std::complex<double> y, Array<std::complex<double>, 1>& axpy) {} // inline Array<std::complex<double>,3>& // operator*= (Array<std::complex<double>,3> &A, const Array<std::complex<double>,3> &B) // { // } #endif
{ "alphanum_fraction": 0.5404862815, "avg_line_length": 27.2522796353, "ext": "h", "hexsha": "15bb58450ee315f7c6423e1365b09d6398fb63bf", "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": "280f67e638bae280448b47fa618f05b848c530d2", "max_forks_repo_licenses": [ "NCSA" ], "max_forks_repo_name": "djstaros/qmcpack", "max_forks_repo_path": "src/QMCTools/ppconvert/src/common/VectorOps.h", "max_issues_count": 11, "max_issues_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_issues_repo_issues_event_max_datetime": "2020-06-10T00:00:17.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-09T20:57:21.000Z", "max_issues_repo_licenses": [ "NCSA" ], "max_issues_repo_name": "djstaros/qmcpack", "max_issues_repo_path": "src/QMCTools/ppconvert/src/common/VectorOps.h", "max_line_length": 120, "max_stars_count": null, "max_stars_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_stars_repo_licenses": [ "NCSA" ], "max_stars_repo_name": "djstaros/qmcpack", "max_stars_repo_path": "src/QMCTools/ppconvert/src/common/VectorOps.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2907, "size": 8966 }
#ifndef __ESTIMATE_INC_ #define __ESTIMATE__INC_ #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> double getLogLikelyhood(gsl_matrix *cinverse, double det_cmatrix, gsl_matrix *xmodel, gsl_vector *trainingvector, gsl_vector *thetas, gsl_matrix *h_matrix, int nmodel_points, int nthetas, int nparams, int nregression_fns, void (*makeHVector)(gsl_vector *, gsl_vector*, int)); #endif
{ "alphanum_fraction": 0.724537037, "avg_line_length": 30.8571428571, "ext": "h", "hexsha": "46820577324858099f162f791fefaee115e35b44", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z", "max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MADAI/MADAIEmulator", "max_forks_repo_path": "src/libEmu/estimator-fns.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MADAI/MADAIEmulator", "max_issues_repo_path": "src/libEmu/estimator-fns.h", "max_line_length": 101, "max_stars_count": 2, "max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jackdawjackdaw/emulator", "max_stars_repo_path": "src/libEmu/estimator-fns.h", "max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z", "num_tokens": 118, "size": 432 }
/* vector/gsl_vector_long.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_LONG_H__ #define __GSL_VECTOR_LONG_H__ #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_block_long.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; long *data; gsl_block_long *block; int owner; } gsl_vector_long; typedef struct { gsl_vector_long vector; } _gsl_vector_long_view; typedef _gsl_vector_long_view gsl_vector_long_view; typedef struct { gsl_vector_long vector; } _gsl_vector_long_const_view; typedef const _gsl_vector_long_const_view gsl_vector_long_const_view; /* Allocation */ gsl_vector_long *gsl_vector_long_alloc (const size_t n); gsl_vector_long *gsl_vector_long_calloc (const size_t n); gsl_vector_long *gsl_vector_long_alloc_from_block (gsl_block_long * b, const size_t offset, const size_t n, const size_t stride); gsl_vector_long *gsl_vector_long_alloc_from_vector (gsl_vector_long * v, const size_t offset, const size_t n, const size_t stride); void gsl_vector_long_free (gsl_vector_long * v); /* Views */ _gsl_vector_long_view gsl_vector_long_view_array (long *v, size_t n); _gsl_vector_long_view gsl_vector_long_view_array_with_stride (long *base, size_t stride, size_t n); _gsl_vector_long_const_view gsl_vector_long_const_view_array (const long *v, size_t n); _gsl_vector_long_const_view gsl_vector_long_const_view_array_with_stride (const long *base, size_t stride, size_t n); _gsl_vector_long_view gsl_vector_long_subvector (gsl_vector_long *v, size_t i, size_t n); _gsl_vector_long_view gsl_vector_long_subvector_with_stride (gsl_vector_long *v, size_t i, size_t stride, size_t n); _gsl_vector_long_const_view gsl_vector_long_const_subvector (const gsl_vector_long *v, size_t i, size_t n); _gsl_vector_long_const_view gsl_vector_long_const_subvector_with_stride (const gsl_vector_long *v, size_t i, size_t stride, size_t n); /* Operations */ void gsl_vector_long_set_zero (gsl_vector_long * v); void gsl_vector_long_set_all (gsl_vector_long * v, long x); int gsl_vector_long_set_basis (gsl_vector_long * v, size_t i); int gsl_vector_long_fread (FILE * stream, gsl_vector_long * v); int gsl_vector_long_fwrite (FILE * stream, const gsl_vector_long * v); int gsl_vector_long_fscanf (FILE * stream, gsl_vector_long * v); int gsl_vector_long_fprintf (FILE * stream, const gsl_vector_long * v, const char *format); int gsl_vector_long_memcpy (gsl_vector_long * dest, const gsl_vector_long * src); int gsl_vector_long_reverse (gsl_vector_long * v); int gsl_vector_long_swap (gsl_vector_long * v, gsl_vector_long * w); int gsl_vector_long_swap_elements (gsl_vector_long * v, const size_t i, const size_t j); long gsl_vector_long_max (const gsl_vector_long * v); long gsl_vector_long_min (const gsl_vector_long * v); void gsl_vector_long_minmax (const gsl_vector_long * v, long * min_out, long * max_out); size_t gsl_vector_long_max_index (const gsl_vector_long * v); size_t gsl_vector_long_min_index (const gsl_vector_long * v); void gsl_vector_long_minmax_index (const gsl_vector_long * v, size_t * imin, size_t * imax); int gsl_vector_long_add (gsl_vector_long * a, const gsl_vector_long * b); int gsl_vector_long_sub (gsl_vector_long * a, const gsl_vector_long * b); int gsl_vector_long_mul (gsl_vector_long * a, const gsl_vector_long * b); int gsl_vector_long_div (gsl_vector_long * a, const gsl_vector_long * b); int gsl_vector_long_scale (gsl_vector_long * a, const double x); int gsl_vector_long_add_constant (gsl_vector_long * a, const double x); int gsl_vector_long_equal (const gsl_vector_long * u, const gsl_vector_long * v); int gsl_vector_long_isnull (const gsl_vector_long * v); int gsl_vector_long_ispos (const gsl_vector_long * v); int gsl_vector_long_isneg (const gsl_vector_long * v); int gsl_vector_long_isnonneg (const gsl_vector_long * v); INLINE_DECL long gsl_vector_long_get (const gsl_vector_long * v, const size_t i); INLINE_DECL void gsl_vector_long_set (gsl_vector_long * v, const size_t i, long x); INLINE_DECL long * gsl_vector_long_ptr (gsl_vector_long * v, const size_t i); INLINE_DECL const long * gsl_vector_long_const_ptr (const gsl_vector_long * v, const size_t i); #ifdef HAVE_INLINE INLINE_FUN long gsl_vector_long_get (const gsl_vector_long * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return v->data[i * v->stride]; } INLINE_FUN void gsl_vector_long_set (gsl_vector_long * v, const size_t i, long x) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif v->data[i * v->stride] = x; } INLINE_FUN long * gsl_vector_long_ptr (gsl_vector_long * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (long *) (v->data + i * v->stride); } INLINE_FUN const long * gsl_vector_long_const_ptr (const gsl_vector_long * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (const long *) (v->data + i * v->stride); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_LONG_H__ */
{ "alphanum_fraction": 0.6717941737, "avg_line_length": 31.8008658009, "ext": "h", "hexsha": "aa530989383f21533239137c8a041e7814a13077", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_path": "gsl-2.6/gsl/gsl_vector_long.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "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": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/gsl/gsl_vector_long.h", "max_line_length": 95, "max_stars_count": null, "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/gsl/gsl_vector_long.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1751, "size": 7346 }
#ifndef _RICO_ #define _RICO_ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <ctype.h> #include <math.h> #include <unistd.h> #include "../Parameter_files/COSMOLOGY.H" #include "../Parameter_files/INIT_PARAMS.H" #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include "cosmo_progs.c" #include "misc.c" #include "ps.c" #define A_NPTS (int) (60) /*Warning: the calculation of the MHR model parameters is valid only from redshift 2 to A_NPTS+2*/ static double A_table[A_NPTS], A_params[A_NPTS]; static gsl_interp_accel *A_acc; static gsl_spline *A_spline; #define C_NPTS (int) (12) static double C_table[C_NPTS], C_params[C_NPTS]; static gsl_interp_accel *C_acc; static gsl_spline *C_spline; #define beta_NPTS (int) (5) static double beta_table[beta_NPTS], beta_params[beta_NPTS]; static gsl_interp_accel *beta_acc; static gsl_spline *beta_spline; #define RR_Z_NPTS (int) (300) // number of points in redshift axis; we will only interpolate over gamma, and just index sample in redshift #define RR_DEL_Z (float) (0.2) #define RR_lnGamma_NPTS (int) (150) // number of samples of gamma for the interpolation tables #define RR_lnGamma_min (double) (-10) // min ln gamma12 used #define RR_DEL_lnGamma (float) (0.1) static double RR_table[RR_Z_NPTS][RR_lnGamma_NPTS], lnGamma_values[RR_lnGamma_NPTS]; static gsl_interp_accel *RR_acc[RR_Z_NPTS]; static gsl_spline *RR_spline[RR_Z_NPTS]; /*** FUNCTION PROTOTYPES ***/ double splined_recombination_rate(double z_eff, double gamma12_bg); // assumes T=1e4 and case B double recombination_rate(double z_eff, double gamma12_bg, double T4, int usecaseB); void init_MHR(); /*initializes the lookup table for the PDF density integral in MHR00 model at redshift z*/ void free_MHR(); /* deallocates the gsl structures from init_MHR */ double Gamma_SS(double Gamma_bg, double Delta, double T_4, double z);//ionization rate w. self shielding double MHR_rr (double D, void *params); double A_MHR(double z); /*returns the A parameter in MHR00model*/ double C_MHR(double z); /*returns the C parameter in MHR00model*/ double beta_MHR(double z); /*returns the beta parameter in MHR00model*/ double splined_A_MHR(double z); /*returns the splined A parameter in MHR00model*/ double splined_C_MHR(double z); /*returns the splined C parameter in MHR00model*/ double splined_beta_MHR(double z);/*returns the splined beta parameter in MHR00*/ void free_A_MHR(); /* deallocates the gsl structures from init_A */ void free_C_MHR(); /* deallocates the gsl structures from init_C */ void free_beta_MHR(); /* deallocates the gsl structures from init_beta */ void init_A_MHR(); /*initializes the lookup table for the A paremeter in MHR00 model*/ void init_C_MHR(); /*initializes the lookup table for the C paremeter in MHR00 model*/ void init_beta_MHR(); /*initializes the lookup table for the beta paremeter in MHR00 model*/ double splined_recombination_rate(double z_eff, double gamma12_bg){ int z_ct = (int) (z_eff / RR_DEL_Z + 0.5); // round to nearest int double lnGamma = log(gamma12_bg); // check out of bounds if ( z_ct < 0 ){ // out of array bounds // fprintf(stderr, "WARNING: splined_recombination_rate: effective redshift %g is outside of array bouds\n", z_eff); z_ct = 0; } else if (z_ct >= RR_Z_NPTS){ // fprintf(stderr, "WARNING: splined_recombination_rate: effective redshift %g is outside of array bouds\n", z_eff); z_ct = RR_Z_NPTS-1; } if (lnGamma < RR_lnGamma_min){ return 0; } else if (lnGamma >= (RR_lnGamma_min + RR_DEL_lnGamma * RR_lnGamma_NPTS) ){ // fprintf(stderr, "WARNING: splined_recombination_rate: Gamma12 of %g is outside of interpolation array\n", gamma12_bg); lnGamma = RR_lnGamma_min + RR_DEL_lnGamma * RR_lnGamma_NPTS - FRACT_FLOAT_ERR; } return gsl_spline_eval(RR_spline[z_ct], lnGamma, RR_acc[z_ct]); } void init_MHR(){ int z_ct, gamma_ct; float z, gamma; // first initialize the MHR parameter look up tables init_C_MHR(); /*initializes the lookup table for the C paremeter in MHR00 model*/ init_beta_MHR(); /*initializes the lookup table for the beta paremeter in MHR00 model*/ init_A_MHR(); /*initializes the lookup table for the A paremeter in MHR00 model*/ // now the recombination rate look up tables for (z_ct=0; z_ct < RR_Z_NPTS; z_ct++){ z = z_ct * RR_DEL_Z; // redshift corresponding to index z_ct of the array // Intialize the Gamma values for (gamma_ct=0; gamma_ct < RR_lnGamma_NPTS; gamma_ct++){ lnGamma_values[gamma_ct] = RR_lnGamma_min + gamma_ct*RR_DEL_lnGamma; // ln of Gamma12 gamma = exp(lnGamma_values[gamma_ct]); RR_table[z_ct][gamma_ct] = recombination_rate(z, gamma, 1, 1); // CHANGE THIS TO INCLUDE TEMPERATURE } // set up the spline in gamma RR_acc[z_ct] = gsl_interp_accel_alloc(); RR_spline[z_ct] = gsl_spline_alloc (gsl_interp_cspline, RR_lnGamma_NPTS); gsl_spline_init(RR_spline[z_ct], lnGamma_values, RR_table[z_ct], RR_lnGamma_NPTS); } // go to next redshift return; } void free_MHR(){ int z_ct; free_A_MHR(); free_C_MHR(); free_beta_MHR(); // now the recombination rate look up tables for (z_ct=0; z_ct < RR_Z_NPTS; z_ct++){ gsl_spline_free (RR_spline[z_ct]); gsl_interp_accel_free(RR_acc[z_ct]); } return; } //calculates the attenuated photoionization rate due to self-shielding (in units of 1e-12 s^-1) // input parameters are the background ionization rate, overdensity, temperature (in 10^4k), redshift, respectively // Uses the fitting formula from Rahmati et al, assuming a UVB power law index of alpha=5 double Gamma_SS(double Gamma_bg, double D, double T_4, double z){ double D_ss = 26.7*pow(T_4, 0.17) * pow( (1+z)/10.0, -3) * pow(Gamma_bg, 2.0/3.0); return Gamma_bg * (0.98 * pow( (1.0+pow(D/D_ss, 1.64)), -2.28) + 0.02*pow( 1.0+D/D_ss, -0.84)); } typedef struct {double z, gamma12_bg, T4, A, C_0, beta, avenH; int usecaseB;} RR_par; double MHR_rr (double lnD, void *params){ double D=exp(lnD); double alpha; RR_par p = *(RR_par *) params; double z = p.z; double gamma = Gamma_SS(p.gamma12_bg, D, p.T4, z); double n_H = p.avenH*D; double x_e = 1.0 - neutral_fraction(n_H, p.T4, gamma, p.usecaseB); double PDelta; PDelta = p.A * exp( - 0.5*pow((pow(D,-2.0/3.0)- p.C_0 ) / ((2.0*7.61/(3.0*(1.0+z)))), 2)) * pow(D, p.beta); if (p.usecaseB) alpha = alpha_B(p.T4*1e4); else alpha = alpha_A(p.T4*1e4); // fprintf(stderr, "%g\t%g\t%g\t%g\t%g\n", n_H, PDelta, alpha, x_e, D); return n_H * PDelta * alpha * x_e * x_e * D * D;//note extra D since we are integrating over lnD } // returns the recombination rate per baryon (1/s), integrated over the MHR density PDF, // given an ionizing background of gamma12_bg // temeperature T4 (in 1e4 K), and usecaseB rate coefficient // Assumes self-shielding according to Rahmati+ 2013 double recombination_rate(double z, double gamma12_bg, double T4, int usecaseB){ double result, error, lower_limit, upper_limit, A, C_0, beta, avenH; gsl_function F; double rel_tol = 0.01; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); RR_par p = {z, gamma12_bg, T4, A_MHR(z), C_MHR(z), beta_MHR(z), No*pow( 1+z, 3), usecaseB}; F.function = &MHR_rr; F.params=&p; lower_limit = log(0.01); upper_limit = log(200); gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); gsl_integration_workspace_free (w); return result; } double aux_function(double D, void *params){ double result; double z = *(double *) params; result = exp(-(pow(D,-2.0/3.0)-C_MHR(z))*(pow(D,-2.0/3.0)-C_MHR(z))/(2.0*(2.0*7.61/(3.0*(1.0+z)))*(2.0*7.61/(3.0*(1.0+z)))))*pow(D, beta_MHR(z)); return result; } double A_aux_integral(double z){ double result, error, lower_limit, upper_limit; gsl_function F; double rel_tol = 0.001; //<- relative tolerance gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); F.function = &aux_function; F.params = &z; lower_limit = 1e-25; upper_limit = 1e25; gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol, 1000, GSL_INTEG_GAUSS61, w, &result, &error); gsl_integration_workspace_free (w); return result; } double A_MHR(double z){ double result; if(z>=2.0+(float)A_NPTS) result = splined_A_MHR(2.0+(float)A_NPTS); else if(z<=2.0) result = splined_A_MHR(2.0); else result = splined_A_MHR(z); return result; } void init_A_MHR(){ /* initialize the lookup table for the parameter A in the MHR00 model */ int i; for (i=0; i<A_NPTS; i++){ A_params[i] = 2.0+(float)i; A_table[i] = 1.0/A_aux_integral(2.0+(float)i); } // Set up spline table A_acc = gsl_interp_accel_alloc(); A_spline = gsl_spline_alloc (gsl_interp_cspline, A_NPTS); gsl_spline_init(A_spline, A_params, A_table, A_NPTS); return; } double splined_A_MHR(double x){ return gsl_spline_eval(A_spline, x, A_acc); } void free_A_MHR(){ gsl_spline_free (A_spline); gsl_interp_accel_free(A_acc); return; } double C_MHR(double z){ double result; if(z>=13.0) result = 1.0; else if(z<=2.0) result = 0.558; else result = splined_C_MHR(z); return result; } void init_C_MHR(){ /* initialize the lookup table for the parameter C in the MHR00 model */ int i; for (i=0; i<C_NPTS; i++) C_params[i] = (float)i+2.0; C_table[0] = 0.558; C_table[1] = 0.599; C_table[2] = 0.611; C_table[3] = 0.769; C_table[4] = 0.868; C_table[5] = 0.930; C_table[6] = 0.964; C_table[7] = 0.983; C_table[8] = 0.993; C_table[9] = 0.998; C_table[10] = 0.999; C_table[11] = 1.00; // Set up spline table C_acc = gsl_interp_accel_alloc (); C_spline = gsl_spline_alloc (gsl_interp_cspline, C_NPTS); gsl_spline_init(C_spline, C_params, C_table, C_NPTS); return; } double splined_C_MHR(double x){ return gsl_spline_eval(C_spline, x, C_acc); } void free_C_MHR(){ gsl_spline_free (C_spline); gsl_interp_accel_free(C_acc); return; } double beta_MHR(double z){ double result; if(z>=6.0) result = -2.50; else if(z<=2.0) result = -2.23; else result = splined_beta_MHR(z); return result; } void init_beta_MHR(){ /* initialize the lookup table for the parameter C in the MHR00 model */ int i; for (i=0; i<beta_NPTS; i++) beta_params[i] = (float)i+2.0; beta_table[0] = -2.23; beta_table[1] = -2.35; beta_table[2] = -2.48; beta_table[3] = -2.49; beta_table[4] = -2.50; // Set up spline table beta_acc = gsl_interp_accel_alloc (); beta_spline = gsl_spline_alloc (gsl_interp_cspline, beta_NPTS); gsl_spline_init(beta_spline, beta_params, beta_table, beta_NPTS); return; } double splined_beta_MHR(double x){ return gsl_spline_eval(beta_spline, x, beta_acc); } void free_beta_MHR(){ gsl_spline_free(beta_spline); gsl_interp_accel_free(beta_acc); return; } #endif
{ "alphanum_fraction": 0.6963914262, "avg_line_length": 30.0461956522, "ext": "c", "hexsha": "8d6e9d1dc391b1cca083b923aac6c09a22a04381", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-12-08T17:16:53.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-14T13:54:46.000Z", "max_forks_repo_head_hexsha": "8f015427f3609a3051b4fa185bdbe55b379c930f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "NNSSA/21cmvFAST", "max_forks_repo_path": "public_21CMvFAST_MC/Cosmo_c_files/recombinations.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "8f015427f3609a3051b4fa185bdbe55b379c930f", "max_issues_repo_issues_event_max_datetime": "2019-12-18T19:59:55.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-17T05:27:25.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "NNSSA/21cmvFAST", "max_issues_repo_path": "public_21CMvFAST_MC/Cosmo_c_files/recombinations.c", "max_line_length": 147, "max_stars_count": 5, "max_stars_repo_head_hexsha": "8f015427f3609a3051b4fa185bdbe55b379c930f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "NNSSA/21cmvFAST", "max_stars_repo_path": "public_21CMvFAST_MC/Cosmo_c_files/recombinations.c", "max_stars_repo_stars_event_max_datetime": "2020-11-15T03:29:14.000Z", "max_stars_repo_stars_event_min_datetime": "2019-04-18T11:31:34.000Z", "num_tokens": 3506, "size": 11057 }
/* multilarge_nlinear/test.c * * Copyright (C) 2015, 2016 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* These tests are based on the NIST Statistical Reference Datasets See http://www.nist.gov/itl/div898/strd/index.html for more information. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_test.h> #include <gsl/gsl_multilarge_nlinear.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_ieee_utils.h> #include "test_fdf.c" static void test_proc(const gsl_multilarge_nlinear_trs *trs, const gsl_multilarge_nlinear_scale *scale, const int fdtype) { gsl_multilarge_nlinear_parameters fdf_params = gsl_multilarge_nlinear_default_parameters(); fdf_params.trs = trs; fdf_params.scale = scale; fdf_params.fdtype = fdtype; if (trs == gsl_multilarge_nlinear_trs_lm || trs == gsl_multilarge_nlinear_trs_lmaccel) fdf_params.solver = gsl_multilarge_nlinear_solver_cholesky; else fdf_params.solver = gsl_multilarge_nlinear_solver_mcholesky; test_fdf_main(&fdf_params); } int main (void) { const gsl_multilarge_nlinear_trs **nlinear_trs[7]; const gsl_multilarge_nlinear_scale **nlinear_scales[3]; const gsl_multilarge_nlinear_trs **trs; const gsl_multilarge_nlinear_scale **scale; int fdtype; size_t i = 0; gsl_ieee_env_setup(); /* initialize arrays */ nlinear_trs[0] = &gsl_multilarge_nlinear_trs_lm; nlinear_trs[1] = &gsl_multilarge_nlinear_trs_lmaccel; nlinear_trs[2] = &gsl_multilarge_nlinear_trs_dogleg; nlinear_trs[3] = &gsl_multilarge_nlinear_trs_ddogleg; nlinear_trs[4] = &gsl_multilarge_nlinear_trs_subspace2D; nlinear_trs[5] = &gsl_multilarge_nlinear_trs_cgst; nlinear_trs[6] = NULL; nlinear_scales[0] = &gsl_multilarge_nlinear_scale_levenberg; nlinear_scales[1] = &gsl_multilarge_nlinear_scale_more; nlinear_scales[2] = NULL; /* run testsuite over all parameter combinations */ for (trs = nlinear_trs[i]; trs != NULL; trs = nlinear_trs[++i]) { size_t j = 0; fprintf(stderr, "trs = %s\n", (*trs)->name); for (scale = nlinear_scales[j]; scale != NULL; scale = nlinear_scales[++j]) { for (fdtype = GSL_MULTILARGE_NLINEAR_FWDIFF; fdtype <= GSL_MULTILARGE_NLINEAR_CTRDIFF; ++fdtype) { test_proc(*trs, *scale, fdtype); } } } exit (gsl_test_summary ()); }
{ "alphanum_fraction": 0.7215108835, "avg_line_length": 30.6274509804, "ext": "c", "hexsha": "3013ec821708b06f4fb0ebac6a4c8bd0e4fab478", "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/multilarge_nlinear/test.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/multilarge_nlinear/test.c", "max_line_length": 81, "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/multilarge_nlinear/test.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": 919, "size": 3124 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C header for functions windowing and computing FFT/IFFT of time/frequency series. * */ #ifndef _FFT_H #define _FFT_H #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 <fftw3.h> /* Note: when included AFTER complex.h, fftw_complex type defaults to the native double complex */ #include "constants.h" #include "struct.h" /* Window functions */ double WindowFunction(double x, double xi, double xf, double deltaxi, double deltaxf); double WindowFunctionLeft(double x, double xf, double deltaxf); double WindowFunctionRight(double x, double xi, double deltaxi); /* FFT of real time series */ /* Note: FFT uses flipped convention (i.e. h(f) = int e^(+2ipift)h(t)) */ int FFTRealTimeSeries( ReImFrequencySeries** freqseries, /* Output: frequency series */ RealTimeSeries* timeseries, /* Input: real time series */ double twindowbeg, /* Extent of the window at beginning (starts at the first point) */ double twindowend, /* Extent of the window at the end (end at the last point) */ int nzeropad); /* For 0-padding: length will be (upper power of 2)*2^nzeropad */ /* FFT of Re/Im time series */ /* Note: FFT uses flipped convention (i.e. h(f) = int e^(+2ipift)h(t)) */ int FFTTimeSeries( ReImFrequencySeries** freqseries, /* Output: frequency series */ ReImTimeSeries* timeseries, /* Input: Re/Im time series */ double twindowbeg, /* Extent of the window at beginning (starts at the first point) */ double twindowend, /* Extent of the window at the end (end at the last point) */ int nzeropad); /* For 0-padding: length will be (upper power of 2)*2^nzeropad */ /* IFFT of frequency series */ /* Note: assumes frequency series is FT of real data */ /* Note: FFT uses flipped convention (i.e. h(f) = int e^(+2ipift)h(t)) */ int IFFTFrequencySeriesReal( RealTimeSeries** timeseries, /* Output: real time series*/ ReImFrequencySeries* freqseries, /* Input: complex frequency series, assumed to be the FT of a real time series */ double f1windowbeg, /* Start of window at the beginning */ double f2windowbeg, /* End of window at the beginning */ double f1windowend, /* Start of window at the end */ double f2windowend, /* End of window at the end */ int nzeropad); /* For 0-padding: length will be (upper power of 2)*2^nzeropad */ /* IFFT of frequency series */ /* Note: assumes frequency series is FT of complex data - produces complex output */ /* Note: FFT uses flipped convention (i.e. h(f) = int e^(+2ipift)h(t)) */ int IFFTFrequencySeries( ReImTimeSeries** timeseries, /* Output: complex time series */ ReImFrequencySeries* freqseries, /* Input: complex frequency series, assumed to be the FT of a real time series */ double f1windowbeg, /* Start of window at the beginning */ double f2windowbeg, /* End of window at the beginning */ double f1windowend, /* Start of window at the end */ double f2windowend, /* End of window at the end */ int nzeropad); /* For 0-padding: length will be (upper power of 2)*2^nzeropad */ #if 0 { /* so that editors will match succeeding brace */ #elif defined(__cplusplus) } #endif #endif /* _FFT_H */
{ "alphanum_fraction": 0.6569737519, "avg_line_length": 40.9052631579, "ext": "h", "hexsha": "809b655c7e3f5cb2c92ef2682a2540400c01b7da", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "titodalcanton/flare", "max_forks_repo_path": "tools/fft.h", "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/fft.h", "max_line_length": 118, "max_stars_count": 3, "max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "titodalcanton/flare", "max_stars_repo_path": "tools/fft.h", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "num_tokens": 992, "size": 3886 }
#ifndef AMGIF_H #define AMGIF_H #include <memory> #include <utility> #include <vector> #include <gsl/gsl_math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include "constants.h" #include "operators_buffer.h" using std::pair; using std::shared_ptr; using std::tuple; using std::vector; // Smart pointer to matrix // Shorthand for template types using VecTriplet = tuple<gsl_vector *, gsl_vector *, gsl_vector *>; using OpBuf = OperatorBuffer; // Compute the AM-GIF estimates VecTriplet computeAMGIF( OpBuf& Cbuf, gsl_vector *me, gsl_vector *pe, const gsl_matrix *L, const double alpha, const double beta, const double tau, const double eps ); #endif // AMGIF_H
{ "alphanum_fraction": 0.6809078772, "avg_line_length": 18.2682926829, "ext": "h", "hexsha": "18f30f49c39e45ca9bdfc0e89ab38544d02e9736", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z", "max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z", "max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ichi-rika/glottal-inverse", "max_forks_repo_path": "inc/amgif.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "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": "ichi-rika/glottal-inverse", "max_issues_repo_path": "inc/amgif.h", "max_line_length": 67, "max_stars_count": 6, "max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ichi-rika/glottal-inverse", "max_stars_repo_path": "inc/amgif.h", "max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z", "num_tokens": 192, "size": 749 }
/** * * @file core_zhegst.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Hatem Ltaief * @date 2010-11-15 * @precisions normal z -> c d s * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_PLASMA_Complex64_t * * CORE_zhegst - reduces a complex Hermitian-definite generalized * eigenproblem to standard form. * If PlasmaItype == 1, the problem is A*x = lambda*B*x, and A is * overwritten by inv(U**H)*A*inv(U) or inv(L)*A*inv(L**H) * If PlasmaItype == 2 or 3, the problem is A*B*x = lambda*x or B*A*x * = lambda*x, and A is overwritten by U*A*U**H or L**H*A*L. B must * have been previously factorized as U**H*U or L*L**H by * CORE_zpotrf. * ******************************************************************************* * * @param[in] itype * Intended usage: * = 1: A*x=(lambda)*B*x * = 2: A*Bx=(lambda)*x * = 3: B*A*x=(lambda)*x * * @param[in] uplo * Specifies whether the matrix A is upper triangular or * lower triangular: * = PlasmaUpper: Upper triangle of A is stored; * = PlasmaLower: Lower triangle of A is stored. * * @param[in] N * The order of the matrices A and B. N >= 0. * * @param[in,out] A * On entry, the symmetric (or Hermitian) matrix A. * If uplo = PlasmaUpper, the leading N-by-N upper triangular * part of A contains the upper triangular part of the matrix * A, and the strictly lower triangular part of A is not * referenced. * If uplo = PlasmaLower, the leading N-by-N lower triangular * part of A contains the lower triangular part of the matrix * A, and the strictly upper triangular part of A is not * referenced. * On exit, if return value == 0, the transformed matrix, * stored in the same format as A. * * @param[in] LDA * The leading dimension of the array A. LDA >= max(1,N). * * @param[in,out] B * On entry, the triangular factor from the Cholesky * factorization of B, as returned by PLASMA_ZPOTRF. * * @param[in] LDB * The leading dimension of the array B. LDB >= max(1,N). * * @param[out] INFO * - 0 on successful exit * - <0 if -i, the i-th argument had an illegal value * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zhegst = PCORE_zhegst #define CORE_zhegst PCORE_zhegst #endif void CORE_zhegst(int itype, PLASMA_enum uplo, int N, PLASMA_Complex64_t *A, int LDA, PLASMA_Complex64_t *B, int LDB, int *INFO) { *INFO = LAPACKE_zhegst_work( LAPACK_COL_MAJOR, itype, lapack_const(uplo), N, A, LDA, B, LDB ); }
{ "alphanum_fraction": 0.5573447256, "avg_line_length": 33.8111111111, "ext": "c", "hexsha": "968e7685968972781eaa38562b2cd9ca515f1646", "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_zhegst.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_zhegst.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "core_blas/core_zhegst.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 833, "size": 3043 }
/* ieee-utils/fp-solaris.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <math.h> #include <ieeefp.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_errno.h> int gsl_ieee_set_mode (int precision, int rounding, int exception_mask) { fp_except mode = 0 ; fp_rnd rnd = 0 ; switch (precision) { case GSL_IEEE_SINGLE_PRECISION: GSL_ERROR ("solaris only supports default precision rounding", GSL_EUNSUP) ; break ; case GSL_IEEE_DOUBLE_PRECISION: GSL_ERROR ("solaris only supports default precision rounding", GSL_EUNSUP) ; break ; case GSL_IEEE_EXTENDED_PRECISION: GSL_ERROR ("solaris only supports default precision rounding", GSL_EUNSUP) ; break ; } switch (rounding) { case GSL_IEEE_ROUND_TO_NEAREST: rnd = FP_RN ; fpsetround (rnd) ; break ; case GSL_IEEE_ROUND_DOWN: rnd = FP_RM ; fpsetround (rnd) ; break ; case GSL_IEEE_ROUND_UP: rnd = FP_RP ; fpsetround (rnd) ; break ; case GSL_IEEE_ROUND_TO_ZERO: rnd = FP_RZ ; fpsetround (rnd) ; break ; default: rnd = FP_RN ; fpsetround (rnd) ; } /* Turn on all the exceptions apart from 'inexact' */ mode = FP_X_INV | FP_X_DZ | FP_X_OFL | FP_X_UFL ; if (exception_mask & GSL_IEEE_MASK_INVALID) mode &= ~ FP_X_INV ; if (exception_mask & GSL_IEEE_MASK_DENORMALIZED) { /* do nothing */ } else { GSL_ERROR ("solaris does not support the denormalized operand exception. " "Use 'mask-denormalized' to work around this.", GSL_EUNSUP) ; } if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO) mode &= ~ FP_X_DZ ; if (exception_mask & GSL_IEEE_MASK_OVERFLOW) mode &= ~ FP_X_OFL ; if (exception_mask & GSL_IEEE_MASK_UNDERFLOW) mode &= ~ FP_X_UFL ; if (exception_mask & GSL_IEEE_TRAP_INEXACT) { mode |= FP_X_IMP ; } else { mode &= ~ FP_X_IMP ; } fpsetmask (mode) ; return GSL_SUCCESS ; }
{ "alphanum_fraction": 0.6471618781, "avg_line_length": 25.7117117117, "ext": "c", "hexsha": "2c3db01e1849cf506b64fd88f78c5d39efd4cfad", "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-solaris.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-solaris.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-solaris.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": 769, "size": 2854 }
/* specfunc/gsl_sf_ellint.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #ifndef __GSL_SF_ELLINT_H__ #define __GSL_SF_ELLINT_H__ #include <gsl/gsl_mode.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 /* Legendre form of complete elliptic integrals * * K(k) = Integral[1/Sqrt[1 - k^2 Sin[t]^2], {t, 0, Pi/2}] * E(k) = Integral[ Sqrt[1 - k^2 Sin[t]^2], {t, 0, Pi/2}] * * exceptions: GSL_EDOM */ int gsl_sf_ellint_Kcomp_e(double k, gsl_mode_t mode, gsl_sf_result * result); double gsl_sf_ellint_Kcomp(double k, gsl_mode_t mode); int gsl_sf_ellint_Ecomp_e(double k, gsl_mode_t mode, gsl_sf_result * result); double gsl_sf_ellint_Ecomp(double k, gsl_mode_t mode); int gsl_sf_ellint_Pcomp_e(double k, double n, gsl_mode_t mode, gsl_sf_result * result); double gsl_sf_ellint_Pcomp(double k, double n, gsl_mode_t mode); int gsl_sf_ellint_Dcomp_e(double k, gsl_mode_t mode, gsl_sf_result * result); double gsl_sf_ellint_Dcomp(double k, gsl_mode_t mode); /* Legendre form of incomplete elliptic integrals * * F(phi,k) = Integral[1/Sqrt[1 - k^2 Sin[t]^2], {t, 0, phi}] * E(phi,k) = Integral[ Sqrt[1 - k^2 Sin[t]^2], {t, 0, phi}] * P(phi,k,n) = Integral[(1 + n Sin[t]^2)^(-1)/Sqrt[1 - k^2 Sin[t]^2], {t, 0, phi}] * D(phi,k,n) = R_D(1-Sin[phi]^2, 1-k^2 Sin[phi]^2, 1.0) * * F: [Carlson, Numerische Mathematik 33 (1979) 1, (4.1)] * E: [Carlson, ", (4.2)] * P: [Carlson, ", (4.3)] * D: [Carlson, ", (4.4)] * * exceptions: GSL_EDOM */ int gsl_sf_ellint_F_e(double phi, double k, gsl_mode_t mode, gsl_sf_result * result); double gsl_sf_ellint_F(double phi, double k, gsl_mode_t mode); int gsl_sf_ellint_E_e(double phi, double k, gsl_mode_t mode, gsl_sf_result * result); double gsl_sf_ellint_E(double phi, double k, gsl_mode_t mode); int gsl_sf_ellint_P_e(double phi, double k, double n, gsl_mode_t mode, gsl_sf_result * result); double gsl_sf_ellint_P(double phi, double k, double n, gsl_mode_t mode); int gsl_sf_ellint_D_e(double phi, double k, gsl_mode_t mode, gsl_sf_result * result); double gsl_sf_ellint_D(double phi, double k, gsl_mode_t mode); /* Carlson's symmetric basis of functions * * RC(x,y) = 1/2 Integral[(t+x)^(-1/2) (t+y)^(-1)], {t,0,Inf}] * RD(x,y,z) = 3/2 Integral[(t+x)^(-1/2) (t+y)^(-1/2) (t+z)^(-3/2), {t,0,Inf}] * RF(x,y,z) = 1/2 Integral[(t+x)^(-1/2) (t+y)^(-1/2) (t+z)^(-1/2), {t,0,Inf}] * RJ(x,y,z,p) = 3/2 Integral[(t+x)^(-1/2) (t+y)^(-1/2) (t+z)^(-1/2) (t+p)^(-1), {t,0,Inf}] * * exceptions: GSL_EDOM */ int gsl_sf_ellint_RC_e(double x, double y, gsl_mode_t mode, gsl_sf_result * result); double gsl_sf_ellint_RC(double x, double y, gsl_mode_t mode); int gsl_sf_ellint_RD_e(double x, double y, double z, gsl_mode_t mode, gsl_sf_result * result); double gsl_sf_ellint_RD(double x, double y, double z, gsl_mode_t mode); int gsl_sf_ellint_RF_e(double x, double y, double z, gsl_mode_t mode, gsl_sf_result * result); double gsl_sf_ellint_RF(double x, double y, double z, gsl_mode_t mode); int gsl_sf_ellint_RJ_e(double x, double y, double z, double p, gsl_mode_t mode, gsl_sf_result * result); double gsl_sf_ellint_RJ(double x, double y, double z, double p, gsl_mode_t mode); __END_DECLS #endif /* __GSL_SF_ELLINT_H__ */
{ "alphanum_fraction": 0.7047367156, "avg_line_length": 36.8053097345, "ext": "h", "hexsha": "7f68f0e2989f3e802903d59a6dc10b7764c771fb", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.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_ellint.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_ellint.h", "max_line_length": 104, "max_stars_count": 7, "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_ellint.h", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "num_tokens": 1369, "size": 4159 }
/* examples/C/ssmfe/precond_core.f90 */ /* Laplacian on a square grid (using SPRAL_SSMFE_CORE routines) */ #include "spral.h" #include <math.h> #include <stdlib.h> #include <stdio.h> #include <cblas.h> /* Header that implements Laplacian and preconditioners */ #include "laplace2d.h" int main(void) { const int ngrid = 20; /* grid points along each side */ const int n = ngrid*ngrid; /* problem size */ const int nep = 5; /* eigenpairs wanted */ const int m = 3; /* dimension of the iterated subspace */ const double tol = 1.e-6; /* eigenvector tolerance */ int state = SPRAL_RANDOM_INITIAL_SEED; /* PRNG state */ int ind[m]; /* permutation index */ double lambda[n]; /* eigenvalues */ double X[n][n]; /* eigenvectors */ /* Work arrays */ double lmd[m]; double rr[3][2*m][2*m]; double W[7][m][n]; double U[m][n]; /* Derived types */ struct spral_ssmfe_rcid rci; /* reverse communication data */ struct spral_ssmfe_core_options options; /* options */ void *keep; /* private data */ struct spral_ssmfe_inform inform; /* information */ /* Initialize options to default values */ spral_ssmfe_core_default_options(&options); /* Initialize W to lin indep vectors by randomizing */ for(int i=0; i<n; i++) for(int j=0; j<m; j++) W[0][j][i] = spral_random_real(&state, true); int ncon = 0; /* number of converged eigenpairs */ rci.job = 0; keep = NULL; while(true) { /* reverse communication loop */ spral_ssmfe_double(&rci, 0, nep, 0, m, lmd, &rr[0][0][0], ind, &keep, &options, &inform); switch ( rci.job ) { case 1: apply_laplacian( ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0], &W[rci.ky][rci.jy][0] ); break; case 2: apply_gauss_seidel_step ( ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0], &W[rci.ky][rci.jy][0] ); break; case 4: for(int j=0; j<m; j++) { if ( inform.converged[j] != 0 ) continue; if ( inform.err_X[j] > 0 && inform.err_X[j] < tol ) inform.converged[j] = 1; } break; case 5: if ( rci.i < 0 ) continue; for(int k=0; k<rci.nx; k++) { int j = ncon + k; lambda[j] = lmd[rci.jx + k]; cblas_dcopy( n, &W[0][rci.jx+k][0], 1, &X[j][0], 1 ); } ncon += rci.nx; if ( ncon >= nep || inform.iteration > 300 ) goto finished; break; case 11: if ( rci.i == 0 ) { if ( rci.kx != rci.ky || rci.jx > rci.jy ) { cblas_dcopy(n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1); } else if ( rci.jx < rci.jy ) { for(int j=rci.nx-1; j>=0; j--) cblas_dcopy(n, &W[rci.kx][rci.jx+j][0], 1, &W[rci.ky][rci.jy+j][0], 1); } } else { for(int i=0; i<n; i++) { for(int j=0; j<rci.nx; j++) U[j][i] = W[rci.kx][ind[j]][i]; for(int j=0; j<rci.nx; j++) W[rci.kx][j][i] = U[j][i]; if(rci.ky != rci.kx) { for(int j=0; j<rci.nx; j++) U[j][i] = W[rci.ky][ind[j]][i]; for(int j=0; j<rci.nx; j++) W[rci.ky][j][i] = U[j][i]; } } } break; case 12: for(int i=0; i<rci.nx; i++) rr[rci.k][rci.j+i][rci.i+i] = cblas_ddot(n, &W[rci.kx][rci.jx+i][0], 1, &W[rci.ky][rci.jy+i][0], 1); break; case 13: for(int i=0; i<rci.nx; i++) { if( rci.kx == rci.ky ) { double s = cblas_dnrm2(n, &W[rci.kx][rci.jx+i][0], 1); if( s > 0 ) cblas_dscal(n, 1/s, &W[rci.kx][rci.jx+i][0], 1); } else { double s = sqrt(fabs(cblas_ddot( n, &W[rci.kx][rci.jx+i][0], 1, &W[rci.ky][rci.jy+i][0], 1) )); if ( s > 0 ) { cblas_dscal(n, 1/s, &W[rci.kx][rci.jx+i][0], 1); cblas_dscal(n, 1/s, &W[rci.ky][rci.jy+i][0], 1); } else { for(int j=0; j<n; j++) W[rci.ky][rci.jy+i][j] = 0.0; } } } break; case 14: for(int i=0; i<rci.nx; i++) { double s = -rr[rci.k][rci.j+i][rci.i+i]; cblas_daxpy(n, s, &W[rci.kx][rci.jx+i][0], 1, &W[rci.ky][rci.jy+i][0], 1); } break; case 15: if ( rci.nx > 0 && rci.ny > 0 ) cblas_dgemm( CblasColMajor, CblasTrans, CblasNoTrans, rci.nx, rci.ny, n, rci.alpha, &W[rci.kx][rci.jx][0], n, &W[rci.ky][rci.jy][0], n, rci.beta, &rr[rci.k][rci.j][rci.i], 2*m ); break; case 16: // Fall through to 17 case 17: if( rci.ny < 1 ) continue; if( rci.nx < 1 ) { if( rci.job == 17 ) continue; if( rci.beta == 1.0 ) continue; for(int j=rci.jy; j<rci.jy+rci.ny; j++) cblas_dscal(n, rci.beta, &W[rci.ky][j][0], 1); continue; } if( rci.job == 17 ) { cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.ny, rci.nx, 1.0, &W[rci.kx][rci.jx][0], n, &rr[rci.k][rci.j][rci.i], 2*m, 0.0, &W[rci.ky][rci.jy][0], n ); cblas_dcopy(n*rci.ny, &W[rci.ky][rci.jy][0], 1, &W[rci.kx][rci.jx][0], 1); } else { cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.ny, rci.nx, rci.alpha, &W[rci.kx][rci.jx][0], n, &rr[rci.k][rci.j][rci.i], 2*m, rci.beta, &W[rci.ky][rci.jy][0], n ); } break; case 21: // Fall through to 22 case 22: if( ncon > 0 ) { cblas_dgemm( CblasColMajor, CblasTrans, CblasNoTrans, ncon, rci.nx, n, 1.0, &X[0][0], n, &W[rci.ky][rci.jy][0], n, 0.0, &U[0][0], n ); cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.nx, ncon, -1.0, &X[0][0], n, &U[0][0], n, 1.0, &W[rci.kx][rci.jx][0], n ); } break; default: goto finished; } } finished: if(inform.flag != 0) printf("inform.flag = %d\n", inform.flag); printf("%3d eigenpairs converged in %d iterations\n", ncon, inform.iteration); for(int i=0; i<ncon; i++) printf(" lambda[%1d] = %13.7e\n", i, lambda[i]); spral_ssmfe_core_free(&keep, &inform); /* Success */ return 0; }
{ "alphanum_fraction": 0.4487642723, "avg_line_length": 36.2251308901, "ext": "c", "hexsha": "1c2a30bedee42a6fa6b6a85f2e2cb16a8cef1bb0", "lang": "C", "max_forks_count": 19, "max_forks_repo_forks_event_max_datetime": "2022-02-28T14:58:37.000Z", "max_forks_repo_forks_event_min_datetime": "2016-09-30T20:52:47.000Z", "max_forks_repo_head_hexsha": "9bf003b2cc199928ec18c967ce0e009d98790898", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "mjacobse/spral", "max_forks_repo_path": "examples/C/ssmfe/precond_core.c", "max_issues_count": 51, "max_issues_repo_head_hexsha": "9bf003b2cc199928ec18c967ce0e009d98790898", "max_issues_repo_issues_event_max_datetime": "2022-03-11T12:52:21.000Z", "max_issues_repo_issues_event_min_datetime": "2016-09-20T19:01:18.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "mjacobse/spral", "max_issues_repo_path": "examples/C/ssmfe/precond_core.c", "max_line_length": 89, "max_stars_count": 76, "max_stars_repo_head_hexsha": "9bf003b2cc199928ec18c967ce0e009d98790898", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mjacobse/spral", "max_stars_repo_path": "examples/C/ssmfe/precond_core.c", "max_stars_repo_stars_event_max_datetime": "2022-03-14T00:11:34.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-03T13:58:37.000Z", "num_tokens": 2419, "size": 6919 }
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file local_trajectory_regression.h * \author Jong Jin Park and Collin Johnson * * Declaration of LocalTrajectoryRegression. */ #ifndef TRACKER_MOTIONS_LOCAL_TRAJECTORY_REGRESSION_H #define TRACKER_MOTIONS_LOCAL_TRAJECTORY_REGRESSION_H #include <tracker/object_state.h> #include <core/point.h> #include <boost/optional.hpp> #include <nlopt.h> #include <deque> #include <vector> #include <memory> namespace vulcan { namespace tracker { struct regression_data_t { int64_t timestamp; float x; float y; explicit regression_data_t(int64_t timestamp = 0, float x = 0.0f, float y = 0.0f) : timestamp(timestamp) , x(x) , y(y) { } }; /** * LocalTrajectoryRegression */ class LocalTrajectoryRegression { public: static const int kRegressionDimension = 4; static const int kIdxX = 0; static const int kIdxY = 1; static const int kIdxVX = 2; static const int kIdxVY = 3; // constructor LocalTrajectoryRegression(void); // Copy constructor LocalTrajectoryRegression(const LocalTrajectoryRegression& rhs); // destructor ~LocalTrajectoryRegression(void); // fit trajectory. Estimated velocity and trajectory are the outputs boost::optional<velocity_t> fitTrajectory(const std::deque<regression_data_t>& recentTrajectory, std::vector<Position>* estimatedTrajectory = nullptr); // cost funtion for fitting the trajectory double evaluate(const double x[kRegressionDimension], double* grad); private: void initializeData (const std::deque<regression_data_t>& recentTrajectory); // construct estimated trajectory using series of timestamps from data void predictTrajectory(double x0, double y0, double vx, double vy, std::vector<Position>& estimatedTrajectory); // computing energy and gradient double computeCost(void); void computeGradient(double* grad); // setting up the optimizer void setupNLOpt(void); // optimizer nlopt_opt optimizer_; // data members std::vector<regression_data_t> data_; std::vector<Position> prediction_; Position prior_; Point<double> priorWeights_; int numIter_; bool haveEnoughData_; // parameters // regression_params_t params_; // NOTE: hard coded for now }; } // namespace mpepc } // namespace vulcan #endif // TRACKER_MOTIONS_LOCAL_TRAJECTORY_REGRESSION_H
{ "alphanum_fraction": 0.683976768, "avg_line_length": 26.3693693694, "ext": "h", "hexsha": "2605af58c776fc9f91c255009fd6d03b56611721", "lang": "C", "max_forks_count": 11, "max_forks_repo_forks_event_max_datetime": "2022-01-20T08:56:38.000Z", "max_forks_repo_forks_event_min_datetime": "2019-05-13T00:04:38.000Z", "max_forks_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "h2ssh/Vulcan", "max_forks_repo_path": "src/tracker/motions/local_trajectory_regression.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_issues_repo_issues_event_max_datetime": "2021-03-05T08:00:50.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-05T08:00:50.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "h2ssh/Vulcan", "max_issues_repo_path": "src/tracker/motions/local_trajectory_regression.h", "max_line_length": 115, "max_stars_count": 6, "max_stars_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "h2ssh/Vulcan", "max_stars_repo_path": "src/tracker/motions/local_trajectory_regression.h", "max_stars_repo_stars_event_max_datetime": "2022-01-20T08:56:31.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-29T09:37:01.000Z", "num_tokens": 688, "size": 2927 }
/************************************************************* Generalized-ICP Copyright (c) 2009 Aleksandr Segal. All rights reserved. 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. * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. *************************************************************/ #ifndef OPTIMIZE_H_ #define OPTIMIZE_H_ #include <ANN.h> #include "gicp.h" #include <vector> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_multifit_nlin.h> namespace dgc { namespace gicp { inline void print_gsl_matrix(gsl_matrix *mat, const char * name) { std::cout << name << "= ["; for(unsigned int i = 0; i < mat->size1; i++) { for(unsigned int j = 0; j < mat->size2; j++) { std::cout << gsl_matrix_get(mat, i, j) << " "; } std::cout << ";" << std::endl; } std::cout << "]" << std::endl; } struct GICPOptData { GICPPointSet *p1; GICPPointSet *p2; ANNidx *nn_indecies; // nearest point indecies gicp_mat_t *M; // mahalanobis matrices for each pair dgc_transform_t base_t; int num_matches; bool solve_rotation; }; class GICPOptimizer { public: GICPOptimizer(); ~GICPOptimizer(); int Iterations() { return iter; } const char* Status() { return gsl_strerror(status); } bool Optimize(dgc_transform_t t, GICPOptData &opt_data); bool OptimizeLM(dgc_transform_t t, GICPOptData &opt_data); void SetDebug(bool d) { debug = d; } void SetMaxIterations(int iter) { max_iter = iter; } void PlotError(dgc_transform_t t, GICPOptData &opt_data, const char* filename); private: static double f(const gsl_vector * x, void * params); static void df(const gsl_vector * x, void * params, gsl_vector * g); static void fdf(const gsl_vector * x, void * params, double * f, gsl_vector * g); static void compute_dr(gsl_vector const* x, gsl_matrix const* gsl_temp_mat_r, gsl_vector *g); static double mat_inner_prod(gsl_matrix const* mat1, gsl_matrix const* mat2); static void apply_state(dgc_transform_t t, gsl_vector const* x); gsl_multimin_fdfminimizer *gsl_minimizer; gsl_vector *x; int max_iter; int iter; int status; bool debug; const static int N = 6; const gsl_multimin_fdfminimizer_type *T_min; }; } } #endif
{ "alphanum_fraction": 0.6922032057, "avg_line_length": 31.7327586207, "ext": "h", "hexsha": "10be2900d7a544e182e883e2d43416b5b7780edc", "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": "48941767c1dddec514c0fe16b222d379d866cc53", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "raandoom/gicp", "max_forks_repo_path": "optimize.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "48941767c1dddec514c0fe16b222d379d866cc53", "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": "raandoom/gicp", "max_issues_repo_path": "optimize.h", "max_line_length": 97, "max_stars_count": null, "max_stars_repo_head_hexsha": "48941767c1dddec514c0fe16b222d379d866cc53", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "raandoom/gicp", "max_stars_repo_path": "optimize.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 913, "size": 3681 }
#include <gsl/gsl_interp.h> #include "gsl_wrapper.h" typedef struct tag_IntWrapper { gsl_interp* pInterpolator; gsl_interp_accel *acc; double* pX; double* pY; int nPts; } IntWrapper; void* makeIntWrapper( double* x, double* y, int nPts) { IntWrapper* pNewWrapper = (IntWrapper*) malloc( sizeof(IntWrapper)); pNewWrapper->pInterpolator = gsl_interp_alloc (gsl_interp_linear, nPts ); gsl_interp_init(pNewWrapper->pInterpolator, x,y, nPts ); pNewWrapper->acc = gsl_interp_accel_alloc (); //Copy the data: pNewWrapper->pX = (double*) malloc( sizeof(double) * nPts); pNewWrapper->pY = (double*) malloc( sizeof(double) * nPts); int i; for(i=0;i< nPts;i++) { pNewWrapper->pX[i] = x[i]; pNewWrapper->pY[i] = y[i]; } pNewWrapper->nPts = nPts; return pNewWrapper; } double interpolate2( double x0, void * pInterpolator) { //printf("%lf\n",x0); IntWrapper* pInt = (IntWrapper*) pInterpolator; if(x0 <= pInt->pX[0]) return pInt->pY[0]; if(x0 >= pInt->pX[pInt->nPts-1]) return pInt->pY[pInt->nPts-1]; return gsl_interp_eval ( pInt->pInterpolator, pInt->pX, pInt->pY, x0, pInt->acc); } int hello() { return 0; } float MyInf() { return 0.5; }
{ "alphanum_fraction": 0.6247068022, "avg_line_length": 19.6769230769, "ext": "c", "hexsha": "b29cfeace16ee31fc4bc9dfb06cee33b33641e1d", "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": "2a95096f144ed4ea487decb735ce66706357d3c7", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "mikehulluk/morphforge", "max_forks_repo_path": "src/morphforgecontrib/simulation/neuron_gsl/cpp/gsl_wrapper.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2a95096f144ed4ea487decb735ce66706357d3c7", "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": "mikehulluk/morphforge", "max_issues_repo_path": "src/morphforgecontrib/simulation/neuron_gsl/cpp/gsl_wrapper.c", "max_line_length": 85, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2a95096f144ed4ea487decb735ce66706357d3c7", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "mikehulluk/morphforge", "max_stars_repo_path": "src/morphforgecontrib/simulation/neuron_gsl/cpp/gsl_wrapper.c", "max_stars_repo_stars_event_max_datetime": "2021-01-21T11:31:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-21T11:31:59.000Z", "num_tokens": 404, "size": 1279 }
/* matrix/gsl_matrix_short.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef __GSL_MATRIX_SHORT_H__ #define __GSL_MATRIX_SHORT_H__ #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector_short.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; short * data; gsl_block_short * block; int owner; } gsl_matrix_short; typedef struct { gsl_matrix_short matrix; } _gsl_matrix_short_view; typedef _gsl_matrix_short_view gsl_matrix_short_view; typedef struct { gsl_matrix_short matrix; } _gsl_matrix_short_const_view; typedef const _gsl_matrix_short_const_view gsl_matrix_short_const_view; /* Allocation */ gsl_matrix_short * gsl_matrix_short_alloc (const size_t n1, const size_t n2); gsl_matrix_short * gsl_matrix_short_calloc (const size_t n1, const size_t n2); gsl_matrix_short * gsl_matrix_short_alloc_from_block (gsl_block_short * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); gsl_matrix_short * gsl_matrix_short_alloc_from_matrix (gsl_matrix_short * m, const size_t k1, const size_t k2, const size_t n1, const size_t n2); gsl_vector_short * gsl_vector_short_alloc_row_from_matrix (gsl_matrix_short * m, const size_t i); gsl_vector_short * gsl_vector_short_alloc_col_from_matrix (gsl_matrix_short * m, const size_t j); void gsl_matrix_short_free (gsl_matrix_short * m); /* Views */ _gsl_matrix_short_view gsl_matrix_short_submatrix (gsl_matrix_short * m, const size_t i, const size_t j, const size_t n1, const size_t n2); _gsl_vector_short_view gsl_matrix_short_row (gsl_matrix_short * m, const size_t i); _gsl_vector_short_view gsl_matrix_short_column (gsl_matrix_short * m, const size_t j); _gsl_vector_short_view gsl_matrix_short_diagonal (gsl_matrix_short * m); _gsl_vector_short_view gsl_matrix_short_subdiagonal (gsl_matrix_short * m, const size_t k); _gsl_vector_short_view gsl_matrix_short_superdiagonal (gsl_matrix_short * m, const size_t k); _gsl_matrix_short_view gsl_matrix_short_view_array (short * base, const size_t n1, const size_t n2); _gsl_matrix_short_view gsl_matrix_short_view_array_with_tda (short * base, const size_t n1, const size_t n2, const size_t tda); _gsl_matrix_short_view gsl_matrix_short_view_vector (gsl_vector_short * v, const size_t n1, const size_t n2); _gsl_matrix_short_view gsl_matrix_short_view_vector_with_tda (gsl_vector_short * v, const size_t n1, const size_t n2, const size_t tda); _gsl_matrix_short_const_view gsl_matrix_short_const_submatrix (const gsl_matrix_short * m, const size_t i, const size_t j, const size_t n1, const size_t n2); _gsl_vector_short_const_view gsl_matrix_short_const_row (const gsl_matrix_short * m, const size_t i); _gsl_vector_short_const_view gsl_matrix_short_const_column (const gsl_matrix_short * m, const size_t j); _gsl_vector_short_const_view gsl_matrix_short_const_diagonal (const gsl_matrix_short * m); _gsl_vector_short_const_view gsl_matrix_short_const_subdiagonal (const gsl_matrix_short * m, const size_t k); _gsl_vector_short_const_view gsl_matrix_short_const_superdiagonal (const gsl_matrix_short * m, const size_t k); _gsl_matrix_short_const_view gsl_matrix_short_const_view_array (const short * base, const size_t n1, const size_t n2); _gsl_matrix_short_const_view gsl_matrix_short_const_view_array_with_tda (const short * base, const size_t n1, const size_t n2, const size_t tda); _gsl_matrix_short_const_view gsl_matrix_short_const_view_vector (const gsl_vector_short * v, const size_t n1, const size_t n2); _gsl_matrix_short_const_view gsl_matrix_short_const_view_vector_with_tda (const gsl_vector_short * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ short gsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j); void gsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x); short * gsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j); const short * gsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j); void gsl_matrix_short_set_zero (gsl_matrix_short * m); void gsl_matrix_short_set_identity (gsl_matrix_short * m); void gsl_matrix_short_set_all (gsl_matrix_short * m, short x); int gsl_matrix_short_fread (FILE * stream, gsl_matrix_short * m) ; int gsl_matrix_short_fwrite (FILE * stream, const gsl_matrix_short * m) ; int gsl_matrix_short_fscanf (FILE * stream, gsl_matrix_short * m); int gsl_matrix_short_fprintf (FILE * stream, const gsl_matrix_short * m, const char * format); int gsl_matrix_short_memcpy(gsl_matrix_short * dest, const gsl_matrix_short * src); int gsl_matrix_short_swap(gsl_matrix_short * m1, const gsl_matrix_short * m2); int gsl_matrix_short_swap_rows(gsl_matrix_short * m, const size_t i, const size_t j); int gsl_matrix_short_swap_columns(gsl_matrix_short * m, const size_t i, const size_t j); int gsl_matrix_short_swap_rowcol(gsl_matrix_short * m, const size_t i, const size_t j); int gsl_matrix_short_transpose (gsl_matrix_short * m); int gsl_matrix_short_transpose_memcpy (gsl_matrix_short * dest, const gsl_matrix_short * src); short gsl_matrix_short_max (const gsl_matrix_short * m); short gsl_matrix_short_min (const gsl_matrix_short * m); void gsl_matrix_short_minmax (const gsl_matrix_short * m, short * min_out, short * max_out); void gsl_matrix_short_max_index (const gsl_matrix_short * m, size_t * imax, size_t *jmax); void gsl_matrix_short_min_index (const gsl_matrix_short * m, size_t * imin, size_t *jmin); void gsl_matrix_short_minmax_index (const gsl_matrix_short * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax); int gsl_matrix_short_isnull (const gsl_matrix_short * m); int gsl_matrix_short_add (gsl_matrix_short * a, const gsl_matrix_short * b); int gsl_matrix_short_sub (gsl_matrix_short * a, const gsl_matrix_short * b); int gsl_matrix_short_mul_elements (gsl_matrix_short * a, const gsl_matrix_short * b); int gsl_matrix_short_div_elements (gsl_matrix_short * a, const gsl_matrix_short * b); int gsl_matrix_short_scale (gsl_matrix_short * a, const double x); int gsl_matrix_short_add_constant (gsl_matrix_short * a, const double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ int gsl_matrix_short_get_row(gsl_vector_short * v, const gsl_matrix_short * m, const size_t i); int gsl_matrix_short_get_col(gsl_vector_short * v, const gsl_matrix_short * m, const size_t j); int gsl_matrix_short_set_row(gsl_matrix_short * m, const size_t i, const gsl_vector_short * v); int gsl_matrix_short_set_col(gsl_matrix_short * m, const size_t j, const gsl_vector_short * v); extern int gsl_check_range ; /* inline functions if you are using GCC */ #ifdef HAVE_INLINE extern inline short gsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j) { #ifndef GSL_RANGE_CHECK_OFF if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ; } #endif return m->data[i * m->tda + j] ; } extern inline void gsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x) { #ifndef GSL_RANGE_CHECK_OFF if (i >= m->size1) { GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ; } #endif m->data[i * m->tda + j] = x ; } extern inline short * gsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j) { #ifndef GSL_RANGE_CHECK_OFF if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (short *) (m->data + (i * m->tda + j)) ; } extern inline const short * gsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j) { #ifndef GSL_RANGE_CHECK_OFF if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } #endif return (const short *) (m->data + (i * m->tda + j)) ; } #endif __END_DECLS #endif /* __GSL_MATRIX_SHORT_H__ */
{ "alphanum_fraction": 0.6616008105, "avg_line_length": 34.3575949367, "ext": "h", "hexsha": "9b6d237495dd045d6977838e7235009f6ae701b2", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/matrix/gsl_matrix_short.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/matrix/gsl_matrix_short.h", "max_line_length": 124, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/matrix/gsl_matrix_short.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": 2573, "size": 10857 }
#include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "tests.h" void test_her2k (void) { const double flteps = 1e-4, dbleps = 1e-6; { int order = 101; int uplo = 121; int trans = 111; int N = 1; int K = 2; float alpha[2] = {0.0f, 0.1f}; float beta = 0.1f; float A[] = { 0.531f, 0.721f, -0.848f, 0.826f }; int lda = 2; float B[] = { -0.711f, -0.2f, -0.92f, -0.676f }; int ldb = 2; float C[] = { -0.447f, 0.701f }; int ldc = 1; float C_expected[] = { 0.30322f, 0.0f }; cblas_cher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cher2k(case 1654) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cher2k(case 1654) imag"); }; }; }; { int order = 101; int uplo = 122; int trans = 111; int N = 1; int K = 2; float alpha[2] = {0.0f, 0.1f}; float beta = 0.1f; float A[] = { 0.68f, 0.079f, 0.837f, -0.814f }; int lda = 2; float B[] = { -0.986f, 0.024f, 0.584f, -0.248f }; int ldb = 2; float C[] = { 0.477f, -0.551f }; int ldc = 1; float C_expected[] = { 0.120103f, 0.0f }; cblas_cher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cher2k(case 1655) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cher2k(case 1655) imag"); }; }; }; { int order = 102; int uplo = 121; int trans = 111; int N = 1; int K = 2; float alpha[2] = {0.0f, 0.1f}; float beta = 0.1f; float A[] = { 0.354f, -0.63f, -0.85f, 0.426f }; int lda = 1; float B[] = { 0.787f, -0.228f, -0.568f, 0.83f }; int ldb = 1; float C[] = { 0.428f, -0.388f }; int ldc = 1; float C_expected[] = { 0.0331132f, 0.0f }; cblas_cher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cher2k(case 1656) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cher2k(case 1656) imag"); }; }; }; { int order = 102; int uplo = 122; int trans = 111; int N = 1; int K = 2; float alpha[2] = {0.0f, 0.1f}; float beta = 0.1f; float A[] = { -0.49f, 0.224f, -0.606f, 0.46f }; int lda = 1; float B[] = { -0.191f, -0.815f, 0.464f, 0.066f }; int ldb = 1; float C[] = { 0.302f, 0.023f }; int ldc = 1; float C_expected[] = { 0.0679396f, 0.0f }; cblas_cher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cher2k(case 1657) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cher2k(case 1657) imag"); }; }; }; { int order = 101; int uplo = 121; int trans = 113; int N = 1; int K = 2; float alpha[2] = {-1.0f, 0.0f}; float beta = 0.0f; float A[] = { 0.943f, 0.075f, 0.15f, -0.141f }; int lda = 1; float B[] = { -0.962f, 0.422f, -0.592f, -0.789f }; int ldb = 1; float C[] = { 0.728f, 0.601f }; int ldc = 1; float C_expected[] = { 1.70613f, 0.0f }; cblas_cher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cher2k(case 1658) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cher2k(case 1658) imag"); }; }; }; { int order = 101; int uplo = 122; int trans = 113; int N = 1; int K = 2; float alpha[2] = {-1.0f, 0.0f}; float beta = 0.0f; float A[] = { -0.93f, -0.386f, 0.565f, 0.141f }; int lda = 1; float B[] = { -0.801f, 0.022f, 0.558f, -0.932f }; int ldb = 1; float C[] = { 0.068f, 0.501f }; int ldc = 1; float C_expected[] = { -1.84059f, 0.0f }; cblas_cher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cher2k(case 1659) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cher2k(case 1659) imag"); }; }; }; { int order = 102; int uplo = 121; int trans = 113; int N = 1; int K = 2; float alpha[2] = {-1.0f, 0.0f}; float beta = 0.0f; float A[] = { -0.383f, 0.124f, 0.458f, -0.221f }; int lda = 2; float B[] = { -0.107f, 0.199f, 0.18f, 0.122f }; int ldb = 2; float C[] = { 0.896f, -0.874f }; int ldc = 1; float C_expected[] = { -0.24227f, 0.0f }; cblas_cher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cher2k(case 1660) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cher2k(case 1660) imag"); }; }; }; { int order = 102; int uplo = 122; int trans = 113; int N = 1; int K = 2; float alpha[2] = {-1.0f, 0.0f}; float beta = 0.0f; float A[] = { 0.131f, 0.692f, 0.533f, -0.672f }; int lda = 2; float B[] = { -0.435f, -0.453f, 0.195f, -0.579f }; int ldb = 2; float C[] = { -0.547f, 0.736f }; int ldc = 1; float C_expected[] = { -0.245124f, 0.0f }; cblas_cher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "cher2k(case 1661) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "cher2k(case 1661) imag"); }; }; }; { int order = 101; int uplo = 121; int trans = 111; int N = 1; int K = 2; double alpha[2] = {-0.3, 0.1}; double beta = 0.1; double A[] = { 0.972, -0.353, 0.712, -0.53 }; int lda = 2; double B[] = { 0.787, -0.379, 0.889, 0.901 }; int ldb = 2; double C[] = { 0.002, 0.266 }; int ldc = 1; double C_expected[] = { -0.4278924, 0.0 }; cblas_zher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zher2k(case 1662) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zher2k(case 1662) imag"); }; }; }; { int order = 101; int uplo = 122; int trans = 111; int N = 1; int K = 2; double alpha[2] = {-0.3, 0.1}; double beta = 0.1; double A[] = { -0.36, 0.192, 0.539, 0.198 }; int lda = 2; double B[] = { -0.673, 0.781, 0.792, 0.335 }; int ldb = 2; double C[] = { 0.719, -0.339 }; int ldc = 1; double C_expected[] = { -0.485009, 0.0 }; cblas_zher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zher2k(case 1663) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zher2k(case 1663) imag"); }; }; }; { int order = 102; int uplo = 121; int trans = 111; int N = 1; int K = 2; double alpha[2] = {-0.3, 0.1}; double beta = 0.1; double A[] = { -0.143, 0.456, 0.677, -0.522 }; int lda = 1; double B[] = { 0.851, 0.196, 0.586, 0.64 }; int ldb = 1; double C[] = { 0.617, 0.118 }; int ldc = 1; double C_expected[] = { 0.1081226, 0.0 }; cblas_zher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zher2k(case 1664) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zher2k(case 1664) imag"); }; }; }; { int order = 102; int uplo = 122; int trans = 111; int N = 1; int K = 2; double alpha[2] = {-0.3, 0.1}; double beta = 0.1; double A[] = { 0.801, 0.91, 0.376, -0.006 }; int lda = 1; double B[] = { -0.613, -0.758, -0.966, 0.194 }; int ldb = 1; double C[] = { -0.723, -0.765 }; int ldc = 1; double C_expected[] = { 0.8583678, 0.0 }; cblas_zher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zher2k(case 1665) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zher2k(case 1665) imag"); }; }; }; { int order = 101; int uplo = 121; int trans = 113; int N = 1; int K = 2; double alpha[2] = {-0.3, 0.1}; double beta = 0.1; double A[] = { -0.359, 0.913, 0.738, -0.227 }; int lda = 1; double B[] = { 0.787, 0.745, 0.036, -0.606 }; int ldb = 1; double C[] = { -0.652, -0.281 }; int ldc = 1; double C_expected[] = { -0.1172608, 0.0 }; cblas_zher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zher2k(case 1666) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zher2k(case 1666) imag"); }; }; }; { int order = 101; int uplo = 122; int trans = 113; int N = 1; int K = 2; double alpha[2] = {-0.3, 0.1}; double beta = 0.1; double A[] = { -0.933, 0.598, 0.952, 0.25 }; int lda = 1; double B[] = { -0.508, -0.461, -0.727, 0.162 }; int ldb = 1; double C[] = { 0.215, 0.943 }; int ldc = 1; double C_expected[] = { 0.0795166, 0.0 }; cblas_zher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zher2k(case 1667) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zher2k(case 1667) imag"); }; }; }; { int order = 102; int uplo = 121; int trans = 113; int N = 1; int K = 2; double alpha[2] = {-0.3, 0.1}; double beta = 0.1; double A[] = { -0.735, 0.372, -0.251, -0.168 }; int lda = 2; double B[] = { 0.217, 0.863, -0.179, -0.057 }; int ldb = 2; double C[] = { 0.579, -0.305 }; int ldc = 1; double C_expected[] = { 0.0744312, 0.0 }; cblas_zher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zher2k(case 1668) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zher2k(case 1668) imag"); }; }; }; { int order = 102; int uplo = 122; int trans = 113; int N = 1; int K = 2; double alpha[2] = {-0.3, 0.1}; double beta = 0.1; double A[] = { -0.587, -0.994, -0.625, 0.681 }; int lda = 2; double B[] = { -0.577, -0.014, -0.434, 0.204 }; int ldb = 2; double C[] = { 0.256, 0.093 }; int ldc = 1; double C_expected[] = { -0.3526202, 0.0 }; cblas_zher2k(order, uplo, trans, N, K, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 1; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zher2k(case 1669) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zher2k(case 1669) imag"); }; }; }; }
{ "alphanum_fraction": 0.5044468161, "avg_line_length": 26.2710280374, "ext": "c", "hexsha": "615e67858a1968230d702bb8bde9dd9b370e2415", "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/cblas/test_her2k.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/cblas/test_her2k.c", "max_line_length": 83, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_her2k.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": 4973, "size": 11244 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 SINGA_CORE_TENSOR_TENSOR_MATH_CPP_H_ #define SINGA_CORE_TENSOR_TENSOR_MATH_CPP_H_ #include "./tensor_math.h" //#include "./stacktrace.h" #include <math.h> #include <algorithm> #include <cfloat> #include <iostream> #include <iterator> #include <sstream> #include "singa/core/common.h" #include "singa/core/tensor.h" #ifdef USE_CBLAS #include <cblas.h> #endif namespace singa { // ===================== Helper Functions ============================= // generate a traversal_info vector based on the tensor's shape for the // traverse_next function to work vector<int> generate_traversal_info(const Tensor &x) { vector<int> traversal_info = {}; for (size_t n = 0; n < (x.shape().size() + 2); ++n) { traversal_info.push_back(0); } return traversal_info; }; // generate shape multipliers // for e.g. tensor of shape (3,3), stride (1,3) will have shape multipliers of // (3,1) // for e.g. tensor of shape (3,3), stride (3,1) will also have shape multipliers // of (3,1) // this means that the 3rd, 6th, and 9th index of the array will always be the // starting element of their respective rows // so we need to need use the inner stride when jumping from 1st->2nd element, // and outer stride when jumping from 2nd->3rd vector<int> generate_shape_multipliers(const Tensor &x) { Shape y_shape = x.shape(); if (y_shape.size() == 0) { return {1}; } vector<int> shape_multipliers = {1}; int cumulative_product = 1; for (size_t n = 0; n < (y_shape.size() - 1); ++n) { cumulative_product = cumulative_product * y_shape[y_shape.size() - 1 - n]; shape_multipliers.insert(shape_multipliers.begin(), cumulative_product); } return shape_multipliers; }; // ****************************************************************************************** // CPP traversal operations (works on const declarations without modifying // tensor variables) // ****************************************************************************************** // this function checks whether the next index falls on a special multiplier of // the outer shape // so the algorithm knows when to jump over/back to a starting element of the // outer shape // for e.g. in [[1,4,7], [2,5,8], [3,6,9]], elements 1,2,3 are the starting // elements of their respective rows // this additional check only has 1 loop for 2d matrix // but runtime performance might degrade to O(nlog(n)) for higher dimensional // tensors int determine_order(vector<int> &shape_multipliers, int counter) { for (size_t n = 0; n < (shape_multipliers.size() - 1); ++n) { if ((counter % shape_multipliers[n]) == 0) { return ((shape_multipliers.size()) - 1 - n); } } return 0; }; // this function updates the base indexes with the current index after every // single traversal step, // can be generalized beyond 2d cases void update_base_index(const Tensor &x, vector<int> &traversal_info) { for (int n = 0; n < (traversal_info[x.shape().size() + 1] + 1); ++n) { traversal_info[n] = traversal_info[x.shape().size()]; } }; // function to traverse a const strided tensor object // it requires an additional vector, traversal_info {0,0,0,0 ...}, comprising // (x.shape().size()+2) elements of 0 // for e.g. 2d matrix: // index 0 and 1 store the base row and column index respectively // index 2 stores the current index of the traversal // index 3 stores the order of the traversal for e.g. if the order is 0, // it means the next element can be navigated to using the innermost stride void traverse_next(const Tensor &x, vector<int> &shape_multipliers, vector<int> &traversal_info, int counter) { update_base_index(x, traversal_info); traversal_info[x.shape().size() + 1] = determine_order(shape_multipliers, counter); traversal_info[x.shape().size()] = traversal_info[traversal_info[x.shape().size() + 1]] + x.stride()[x.stride().size() - traversal_info[x.shape().size() + 1] - 1]; }; inline int next_offset(int offset, const vector<size_t> &shape, const vector<int> &stride, vector<int> *index) { for (int k = shape.size() - 1; k >= 0; k--) { if (index->at(k) + 1 < int(shape.at(k))) { offset += stride.at(k); index->at(k) += 1; break; } index->at(k) = 0; offset -= stride.at(k) * (shape.at(k) - 1); } return offset; } template <typename DType> void traverse_unary(const Tensor &in, Tensor *out, std::function<DType(DType)> func) { DType *outPtr = static_cast<DType *>(out->block()->mutable_data()); const DType *inPtr = static_cast<const DType *>(in.block()->data()); /* vector<int> traversal_info = generate_traversal_info(in); vector<int> shape_multipliers = generate_shape_multipliers(in); for (size_t i = 0; i < in.Size(); i++) { outPtr[i] = func(inPtr[traversal_info[in.shape().size()]]); traverse_next(in, shape_multipliers, traversal_info, i + 1); } */ CHECK(in.shape() == out->shape()); if (in.stride() == out->stride()) { for (size_t i = 0; i < in.Size(); i++) outPtr[i] = func(inPtr[i]); } else { // LOG(INFO) << "not equal stride"; size_t in_offset = 0, out_offset = 0; vector<int> in_idx(in.nDim(), 0), out_idx(out->nDim(), 0); for (size_t i = 0; i < Product(in.shape()); i++) { outPtr[out_offset] = func(inPtr[in_offset]); out_offset = next_offset(out_offset, out->shape(), out->stride(), &out_idx); in_offset = next_offset(in_offset, in.shape(), in.stride(), &in_idx); } } } template <typename DType> void traverse_binary(const Tensor &in1, const Tensor &in2, Tensor *out, std::function<DType(DType, DType)> func) { DType *outPtr = static_cast<DType *>(out->block()->mutable_data()); const DType *in1Ptr = static_cast<const DType *>(in1.block()->data()); const DType *in2Ptr = static_cast<const DType *>(in2.block()->data()); /* vector<int> traversal_info_in1 = generate_traversal_info(in1); vector<int> traversal_info_in2 = generate_traversal_info(in2); vector<int> shape_multipliers_in1 = generate_shape_multipliers(in1); vector<int> shape_multipliers_in2 = generate_shape_multipliers(in2); for (size_t i = 0; i < in1.Size(); i++) { outPtr[i] = func(in1Ptr[traversal_info_in1[in1.shape().size()]], in2Ptr[traversal_info_in2[in2.shape().size()]]); traverse_next(in1, shape_multipliers_in1, traversal_info_in1, i + 1); traverse_next(in2, shape_multipliers_in2, traversal_info_in2, i + 1); } */ auto prod = Product(in1.shape()); CHECK(in1.shape() == out->shape()); CHECK(in2.shape() == out->shape()); if ((in1.stride() == out->stride()) && (in2.stride() == in1.stride())) { for (size_t i = 0; i < prod; i++) outPtr[i] = func(in1Ptr[i], in2Ptr[i]); } else { /* LOG(INFO) << "not equal stride"; std::ostringstream s1, s2, s3, s4, s5, s6; std::copy(in1.stride().begin(), in1.stride().end(), std::ostream_iterator<int>(s1, ", ")); std::copy(in2.stride().begin(), in2.stride().end(), std::ostream_iterator<int>(s2, ", ")); std::copy(out->stride().begin(), out->stride().end(), std::ostream_iterator<int>(s3, ", ")); std::copy(in1.shape().begin(), in1.shape().end(), std::ostream_iterator<int>(s4, ", ")); std::copy(in2.shape().begin(), in2.shape().end(), std::ostream_iterator<int>(s5, ", ")); std::copy(out->shape().begin(), out->shape().end(), std::ostream_iterator<int>(s6, ", ")); LOG(INFO) << s1.str() << ": " << s4.str(); LOG(INFO) << s2.str() << ": " << s5.str(); LOG(INFO) << s3.str() << ": " << s6.str(); LOG(INFO) << Backtrace(); */ size_t in1_offset = 0, in2_offset = 0, out_offset = 0; vector<int> in1_idx(in1.nDim(), 0), in2_idx(in2.nDim(), 0), out_idx(out->nDim(), 0); for (size_t i = 0; i < prod; i++) { outPtr[out_offset] = func(in1Ptr[in1_offset], in2Ptr[in2_offset]); out_offset = next_offset(out_offset, out->shape(), out->stride(), &out_idx); in1_offset = next_offset(in1_offset, in1.shape(), in1.stride(), &in1_idx); in2_offset = next_offset(in2_offset, in2.shape(), in2.stride(), &in2_idx); // LOG(INFO) << in1_offset << ", " << in2_offset << ", " << out_offset; } } } // ****************************************************************************************** // traversal operations end // ****************************************************************************************** // ===================== CUDA Functions ============================= template <> void Abs<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { traverse_unary<float>(in, out, [](float x) { return fabs(x); }); } template <> void Erf<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { traverse_unary<float>(in, out, [](float x) { return erff(x); }); } template <> void CastCopy<float, half_float::half, lang::Cpp>(const Tensor *src, Tensor *dst, Context *ctx) { half_float::half *dst_array = static_cast<half_float::half *>(dst->block()->mutable_data()); const float *src_array = static_cast<const float *>(src->block()->data()); for (int i = 0; i < dst->Size(); ++i) dst_array[i] = static_cast<half_float::half>(src_array[i]); } template <> void CastCopy<half_float::half, float, lang::Cpp>(const Tensor *src, Tensor *dst, Context *ctx) { float *dst_array = static_cast<float *>(dst->block()->mutable_data()); const half_float::half *src_array = static_cast<const half_float::half *>(src->block()->data()); for (int i = 0; i < dst->Size(); ++i) dst_array[i] = static_cast<float>(src_array[i]); } template <> void CastCopy<float, int, lang::Cpp>(const Tensor *src, Tensor *dst, Context *ctx) { int *dst_array = static_cast<int *>(dst->block()->mutable_data()); const float *src_array = static_cast<const float *>(src->block()->data()); for (int i = 0; i < dst->Size(); ++i) dst_array[i] = (int)src_array[i]; } template <> void CastCopy<int, float, lang::Cpp>(const Tensor *src, Tensor *dst, Context *ctx) { float *dst_array = static_cast<float *>(dst->block()->mutable_data()); const int *src_array = static_cast<const int *>(src->block()->data()); for (int i = 0; i < dst->Size(); ++i) dst_array[i] = (float)src_array[i]; } template <> void Ceil<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { traverse_unary<float>(in, out, [](float x) { return std::ceil(x); }); } template <> void Floor<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { traverse_unary<float>(in, out, [](float x) { return std::floor(x); }); } template <> void Round<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { traverse_unary<float>(in, out, [](float x) { return std::round(x); }); } template <> void RoundE<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { traverse_unary<float>(in, out, [](float x) { float doub = x * 2; if (ceilf(doub) == doub) { return std::round(x / 2) * 2; } else { return std::round(x); } }); } #ifdef USE_DNNL template <> void SoftMax<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { auto md = dnnl::memory::desc({static_cast<long long>(in.shape()[0]), static_cast<long long>(in.shape()[1])}, dnnl::memory::data_type::f32, dnnl::memory::format_tag::ab); auto in_mem = dnnl::memory(md, ctx->dnnl_engine, in.block()->mutable_data()); auto out_mem = dnnl::memory(md, ctx->dnnl_engine, out->block()->mutable_data()); auto softmax_desc = dnnl::softmax_forward::desc(dnnl::prop_kind::forward_scoring, md, 1); auto softmax_prim_desc = dnnl::softmax_forward::primitive_desc(softmax_desc, ctx->dnnl_engine); auto softmax = dnnl::softmax_forward(softmax_prim_desc); softmax.execute(ctx->dnnl_stream, {{DNNL_ARG_SRC, in_mem}, {DNNL_ARG_DST, out_mem}}); ctx->dnnl_stream.wait(); } template <> void SoftMaxBackward<float, lang::Cpp>(const Tensor &in, Tensor *out, const Tensor &fdout, Context *ctx) { auto md = dnnl::memory::desc({static_cast<long long>(in.shape()[0]), static_cast<long long>(in.shape()[1])}, dnnl::memory::data_type::f32, dnnl::memory::format_tag::ab); auto in_mem = dnnl::memory(md, ctx->dnnl_engine, in.block()->mutable_data()); auto fdout_mem = dnnl::memory(md, ctx->dnnl_engine, fdout.block()->mutable_data()); auto out_mem = dnnl::memory(md, ctx->dnnl_engine, out->block()->mutable_data()); auto softmax_desc = dnnl::softmax_forward::desc(dnnl::prop_kind::forward_scoring, md, 1); auto softmax_prim_desc = dnnl::softmax_forward::primitive_desc(softmax_desc, ctx->dnnl_engine); auto softmaxbwd_desc = dnnl::softmax_backward::desc(md, md, 1); auto softmaxbwd_prim_desc = dnnl::softmax_backward::primitive_desc( softmaxbwd_desc, ctx->dnnl_engine, softmax_prim_desc); auto softmaxbwd = dnnl::softmax_backward(softmaxbwd_prim_desc); softmaxbwd.execute(ctx->dnnl_stream, {{DNNL_ARG_DIFF_SRC, out_mem}, {DNNL_ARG_DIFF_DST, in_mem}, {DNNL_ARG_DST, fdout_mem}}); ctx->dnnl_stream.wait(); } #else // native Softmax without DNNL template <> void SoftMax<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { CHECK_LE(in.nDim(), 2u) << "Axis is required for SoftMax on multi dimemsional tensor"; out->CopyData(in); size_t nrow = 1, ncol = in.Size(), size = ncol; if (in.nDim() == 2u) { nrow = in.shape(0); ncol = size / nrow; out->Reshape(Shape{nrow, ncol}); } Tensor tmp = RowMax(*out); SubColumn(tmp, out); Exp(*out, out); SumColumns(*out, &tmp); DivColumn(tmp, out); out->Reshape(in.shape()); } #endif // USE_DNNL template <> void Add<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out, Context *ctx) { auto add_lambda = [&x](float a) { return (a + x); }; traverse_unary<float>(in, out, add_lambda); } template <> void Add<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { // CHECK_EQ(ctx->stream, nullptr); auto add_lambda_binary = [](float a, float b) { return (a + b); }; traverse_binary<float>(in1, in2, out, add_lambda_binary); } template <> void Clamp<float, lang::Cpp>(const float low, const float high, const Tensor &in, Tensor *out, Context *ctx) { auto clamp_lambda = [&low, &high](float a) { if (a < low) { return low; } else if (a > high) { return high; } else { return a; } }; traverse_unary<float>(in, out, clamp_lambda); } template <> void Div<float, lang::Cpp>(const float x, const Tensor &in, Tensor *out, Context *ctx) { auto const_div = [&x](float a) { CHECK_NE(a, 0.f); return x / a; }; traverse_unary<float>(in, out, const_div); } template <> void Div<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto binary_div = [](float a, float b) { CHECK_NE(b, 0.f); return a / b; }; traverse_binary<float>(in1, in2, out, binary_div); } template <> void EltwiseMult<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out, Context *ctx) { auto eltwisemult_lambda = [&x](float a) { return (a * x); }; traverse_unary<float>(in, out, eltwisemult_lambda); } template <> void EltwiseMult<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto eltwisemult_lambda_binary = [](float a, float b) { return (a * b); }; traverse_binary<float>(in1, in2, out, eltwisemult_lambda_binary); } template <> void ReLUBackward<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto relubackward_lambda = [](float a, float b) { return (b > 0) ? a : 0.f; }; traverse_binary<float>(in1, in2, out, relubackward_lambda); } template <> void Exp<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { traverse_unary<float>(in, out, [](float x) { return exp(x); }); } template <> void GE<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out, Context *ctx) { auto ge_lambda = [&x](float a) { return (a >= x) ? 1.f : 0.f; }; traverse_unary<float>(in, out, ge_lambda); } template <> void GE<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto ge_lambda_binary = [](float a, float b) { return (a >= b) ? 1.f : 0.f; }; traverse_binary<float>(in1, in2, out, ge_lambda_binary); } template <> void GE<int, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto ge_lambda_binary = [](int a, int b) { return (a >= b) ? 1.f : 0.f; }; traverse_binary<int>(in1, in2, out, ge_lambda_binary); } template <> void GT<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out, Context *ctx) { auto gt_lambda = [&x](float a) { return (a > x) ? 1.f : 0.f; }; traverse_unary<float>(in, out, gt_lambda); } template <> void GT<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto gt_lambda_binary = [](float a, float b) { return (a > b) ? 1.f : 0.f; }; traverse_binary<float>(in1, in2, out, gt_lambda_binary); } template <> void GT<int, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto gt_lambda_binary = [](int a, int b) { return (a > b) ? 1.f : 0.f; }; traverse_binary<int>(in1, in2, out, gt_lambda_binary); } template <> void LE<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out, Context *ctx) { auto le_lambda = [&x](float a) { return (a <= x) ? 1.f : 0.f; }; traverse_unary<float>(in, out, le_lambda); } template <> void LE<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto le_lambda_binary = [](float a, float b) { return (a <= b) ? 1.f : 0.f; }; traverse_binary<float>(in1, in2, out, le_lambda_binary); } template <> void LE<int, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto le_lambda_binary = [](int a, int b) { return (a <= b) ? 1.f : 0.f; }; traverse_binary<int>(in1, in2, out, le_lambda_binary); } template <> void Log<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { auto ulog = [](float a) { CHECK_GT(a, 0.f); return log(a); }; traverse_unary<float>(in, out, ulog); } template <> void LT<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out, Context *ctx) { auto lt_lambda = [&x](float a) { return (a < x) ? 1.f : 0.f; }; traverse_unary<float>(in, out, lt_lambda); } template <> void LT<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto lt_lambda_binary = [](float a, float b) { return (a < b) ? 1.f : 0.f; }; traverse_binary<float>(in1, in2, out, lt_lambda_binary); } template <> void LT<int, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto lt_lambda_binary = [](int a, int b) { return (a < b) ? 1.f : 0.f; }; traverse_binary<int>(in1, in2, out, lt_lambda_binary); } template <> void EQ<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out, Context *ctx) { auto eq_lambda = [&x](float a) { return (a == x) ? 1.f : 0.f; }; traverse_unary<float>(in, out, eq_lambda); } template <> void EQ<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto eq_lambda_binary = [](float a, float b) { return (a == b) ? 1.f : 0.f; }; traverse_binary<float>(in1, in2, out, eq_lambda_binary); } template <> void EQ<int, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto eq_lambda_binary = [](int a, int b) { return (a == b) ? 1.f : 0.f; }; traverse_binary<int>(in1, in2, out, eq_lambda_binary); } template <> void Pow<float, lang::Cpp>(const Tensor &in, const float x, Tensor *out, Context *ctx) { traverse_unary<float>(in, out, [x](float y) { return pow(y, x); }); } template <> void Pow<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { auto pow_lambda_binary = [](float a, float b) { return pow(a, b); }; traverse_binary<float>(in1, in2, out, pow_lambda_binary); } template <> void ReLU<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { auto relu_lambda = [](float a) { return (a >= 0.f) ? a : 0.f; }; traverse_unary<float>(in, out, relu_lambda); } template <> void Set<float, lang::Cpp>(const float x, Tensor *out, Context *ctx) { float *outPtr = static_cast<float *>(out->block()->mutable_data()); for (size_t i = 0; i < out->Size(); i++) outPtr[i] = x; } template <> void Set<int, lang::Cpp>(const int x, Tensor *out, Context *ctx) { int *outPtr = static_cast<int *>(out->block()->mutable_data()); for (size_t i = 0; i < out->Size(); i++) outPtr[i] = x; } template <> void Set<half_float::half, lang::Cpp>(const half_float::half x, Tensor *out, Context *ctx) { half_float::half *outPtr = static_cast<half_float::half *>(out->block()->mutable_data()); for (size_t i = 0; i < out->Size(); i++) outPtr[i] = x; } template <> void Sigmoid<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { auto sigmoid_lambda = [](float a) { return 1.f / (1.f + exp(-a)); }; traverse_unary<float>(in, out, sigmoid_lambda); } template <> void Sign<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { auto sign_lambda = [](float a) { return (a > 0) - (a < 0); }; traverse_unary<float>(in, out, sign_lambda); } template <> void SoftPlus<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { auto softplus_lambda = [](float a) { return log(1.f + exp(a)); }; traverse_unary<float>(in, out, softplus_lambda); } template <> void SoftSign<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { auto softsign_lambda = [](float a) { return a / (1.f + fabs(a)); }; traverse_unary<float>(in, out, softsign_lambda); } template <> void Sqrt<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { auto usqrt = [](float a) { CHECK_GE(a, 0.f); return sqrt(a); }; traverse_unary<float>(in, out, usqrt); } template <> void Sub<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { // CHECK_EQ(ctx->stream, nullptr); auto sub_lambda_binary = [](float a, float b) { return (a - b); }; traverse_binary<float>(in1, in2, out, sub_lambda_binary); } // sum all elements of input into out // TODO(wangwei) optimize using omp template <> void Sum<float, lang::Cpp>(const Tensor &in, float *out, Context *ctx) { float s = 0.f; const float *inPtr = static_cast<const float *>(in.block()->data()); for (size_t i = 0; i < in.Size(); i++) { s += inPtr[i]; } *out = s; } #define GenUnaryTensorCppFn(fn, cppfn) \ template <> \ void fn<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { \ auto fn_lambda = [](float a) { return cppfn(a); }; \ traverse_unary<float>(in, out, fn_lambda); \ } GenUnaryTensorCppFn(Cos, cos); GenUnaryTensorCppFn(Cosh, cosh); GenUnaryTensorCppFn(Acos, acos); GenUnaryTensorCppFn(Acosh, acosh); GenUnaryTensorCppFn(Sin, sin); GenUnaryTensorCppFn(Sinh, sinh); GenUnaryTensorCppFn(Asin, asin); GenUnaryTensorCppFn(Asinh, asinh); GenUnaryTensorCppFn(Tan, tan); GenUnaryTensorCppFn(Tanh, tanh); GenUnaryTensorCppFn(Atan, atan); GenUnaryTensorCppFn(Atanh, atanh); template <> void Transform<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { auto identity = [](float a) { return a; }; traverse_unary<float>(in, out, identity); } template <> void Transform<int, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { auto identity = [](int a) { return a; }; traverse_unary<int>(in, out, identity); } template <> void Transform<half_float::half, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { auto identity = [](half_float::half a) { return a; }; traverse_unary<half_float::half>(in, out, identity); } template <> void Bernoulli<float, lang::Cpp>(const float p, Tensor *out, Context *ctx) { std::bernoulli_distribution distribution(p); float *outPtr = static_cast<float *>(out->block()->mutable_data()); for (size_t i = 0; i < out->Size(); i++) { outPtr[i] = distribution(ctx->random_generator) ? 1.0f : 0.0f; } } template <> void Gaussian<float, lang::Cpp>(const float mean, const float std, Tensor *out, Context *ctx) { std::normal_distribution<float> distribution(mean, std); float *outPtr = static_cast<float *>(out->block()->mutable_data()); for (size_t i = 0; i < out->Size(); i++) { outPtr[i] = static_cast<float>(distribution(ctx->random_generator)); } } template <> void Gaussian<half_float::half, lang::Cpp>(const half_float::half mean, const half_float::half std, Tensor *out, Context *ctx) { Tensor tmp(out->shape(), out->device(), kFloat32); Gaussian<float, lang::Cpp>(static_cast<float>(mean), static_cast<float>(std), &tmp, ctx); CastCopy<float, half_float::half, lang::Cpp>(&tmp, out, ctx); } template <> void Uniform<float, lang::Cpp>(const float low, const float high, Tensor *out, Context *ctx) { std::uniform_real_distribution<float> distribution(low, high); float *outPtr = static_cast<float *>(out->block()->mutable_data()); for (size_t i = 0; i < out->Size(); i++) { outPtr[i] = static_cast<float>(distribution(ctx->random_generator)); } } // ====================Blas operations====================================== // warning, this function has block M overwritting to block M itself template <> void DGMM<float, lang::Cpp>(const bool side_right, const Tensor &M, const Tensor &v, Tensor *out, Context *ctx) { const float *MPtr = static_cast<const float *>(M.block()->data()); const float *vPtr = static_cast<const float *>(v.block()->data()); float *outPtr = static_cast<float *>(out->block()->mutable_data()); const size_t nrow = M.shape(0); const size_t ncol = M.shape(1); if (side_right) { for (size_t r = 0; r < nrow; r++) { size_t in_offset = M.stride()[0] * r, out_offset = out->stride()[0] * r; for (size_t c = 0; c < ncol; c++) { outPtr[out_offset] = MPtr[in_offset] * vPtr[c]; in_offset += M.stride()[1]; out_offset += out->stride()[1]; } } } else { for (size_t r = 0; r < nrow; r++) { size_t in_offset = M.stride()[0] * r, out_offset = out->stride()[0] * r; for (size_t c = 0; c < ncol; c++) { outPtr[out_offset] = MPtr[in_offset] * vPtr[r]; in_offset += M.stride()[1]; out_offset += out->stride()[1]; } } } } #ifdef USE_CBLAS template <> void Amax<float, lang::Cpp>(const Tensor &in, size_t *out, Context *ctx) { const float *inPtr = static_cast<const float *>(in.block()->data()); *out = cblas_isamax(in.Size(), inPtr, 1); // not using strided traversal } template <> void Asum<float, lang::Cpp>(const Tensor &in, float *out, Context *ctx) { const float *inPtr = static_cast<const float *>(in.block()->data()); *out = cblas_sasum(in.Size(), inPtr, 1); // not using strided traversal } // template <> // void Axpy<float, lang::Cpp>(const float alpha, // const Tensor& in, Tensor *out, Context *ctx) { // //check input tensor for strides first // if (in.stride() == out->stride()) { // const float *inPtr = static_cast<const float *>(in.block()->data()); // float *outPtr = static_cast<float *>(out->block()->mutable_data()); // cblas_saxpy(in.Size(), alpha, inPtr, 1, outPtr, 1); // } else { // //LOG(FATAL) << "Axpy, input and output strides do not match." ; // EltwiseMult<float, lang::Cpp>(in, alpha, out, ctx); // } // } template <> void Axpy<float, lang::Cpp>(const float alpha, const Tensor &in, Tensor *out, Context *ctx) { // check input tensor for strides first const float *inPtr = static_cast<const float *>(in.block()->data()); float *outPtr = static_cast<float *>(out->block()->mutable_data()); if (in.stride() == out->stride()) { cblas_saxpy(in.Size(), alpha, inPtr, 1, outPtr, 1); } else { // LOG(FATAL) << "Axpy, input and output strides do not match." ; Tensor t(in.shape(), in.device(), in.data_type()); EltwiseMult<float, lang::Cpp>(in, alpha, &t, ctx); float *tPtr = static_cast<float *>(t.block()->mutable_data()); cblas_saxpy(in.Size(), 1, tPtr, 1, outPtr, 1); } } // template <> // void Axpy<float, lang::Cpp>(const float alpha, // const Tensor& in, Tensor *out, Context *ctx) { // //check input tensor for strides first // if (in.stride() == out->stride()) { // const float *inPtr = static_cast<const float *>(in.block()->data()); // float *outPtr = static_cast<float *>(out->block()->mutable_data()); // cblas_saxpy(in.Size(), alpha, inPtr, 1, outPtr, 1); // } else if(out->transpose()) { // LOG(FATAL) << "output is already transposed." ; // } else { // LOG(FATAL) << "Axpy, input and output strides do not match." ; // } // } template <> void Dot<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, float *out, Context *ctx) { // check input tensor for strides first if (!(in1.transpose()) && !(in2.transpose())) { const float *in1Ptr = static_cast<const float *>(in1.block()->data()); const float *in2Ptr = static_cast<const float *>(in2.block()->data()); *out = cblas_sdot(in1.Size(), in1Ptr, 1, in2Ptr, 1); } else { LOG(FATAL) << "Dot, one of the input is tranposed. Not implemented yet."; } } template <> void Dot<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, Tensor *out, Context *ctx) { // check input tensor for strides first if (!(in1.transpose()) && !(in2.transpose())) { const float *in1Ptr = static_cast<const float *>(in1.block()->data()); const float *in2Ptr = static_cast<const float *>(in2.block()->data()); float *outPtr = static_cast<float *>(out->block()->mutable_data()); *outPtr = cblas_sdot(in1.Size(), in1Ptr, 1, in2Ptr, 1); } else { LOG(FATAL) << "Dot, one of the input is tranposed. Not implemented yet."; } } template <> void Scale<float, lang::Cpp>(const float x, Tensor *out, Context *ctx) { float *outPtr = static_cast<float *>(out->block()->mutable_data()); cblas_sscal(out->Size(), x, outPtr, 1); // not using strided traversal } template <> void Nrm2<float, lang::Cpp>(const Tensor &in, float *out, Context *ctx) { const float *inPtr = static_cast<const float *>(in.block()->data()); *out = cblas_snrm2(in.Size(), inPtr, 1); // not using strided traversal } template <> void GEMV<float, lang::Cpp>(const float alpha, const Tensor &A, const Tensor &v, const float beta, Tensor *out, Context *ctx) { const float *APtr = static_cast<const float *>(A.block()->data()); const float *vPtr = static_cast<const float *>(v.block()->data()); float *outPtr = static_cast<float *>(out->block()->mutable_data()); const size_t m = A.shape()[0]; const size_t n = A.shape()[1]; if (A.transpose()) { cblas_sgemv(CblasRowMajor, CblasTrans, n, m, alpha, APtr, m, vPtr, 1, beta, outPtr, 1); } else { cblas_sgemv(CblasRowMajor, CblasNoTrans, m, n, alpha, APtr, n, vPtr, 1, beta, outPtr, 1); } } template <> void GEMM<float, lang::Cpp>(const float alpha, const Tensor &A, const Tensor &B, const float beta, Tensor *C, Context *ctx) { auto transA = A.transpose(); auto transa = transA ? CblasTrans : CblasNoTrans; auto transB = B.transpose(); auto transb = transB ? CblasTrans : CblasNoTrans; const size_t nrowA = A.shape()[0]; const size_t ncolA = A.shape()[1]; const size_t ncolB = B.shape()[1]; auto lda = transA ? nrowA : ncolA; auto ldb = transB ? ncolA : ncolB; auto ldc = ncolB; const float *APtr = static_cast<const float *>(A.block()->data()); const float *BPtr = static_cast<const float *>(B.block()->data()); float *CPtr = static_cast<float *>(C->block()->mutable_data()); cblas_sgemm(CblasRowMajor, transa, transb, nrowA, ncolB, ncolA, alpha, APtr, lda, BPtr, ldb, beta, CPtr, ldc); } /* * implement matmul for 3d 4d tensor * simulate cblas_sgemm_batch(); * which is only available in intel cblas */ template <> void GEMMBatched<float, lang::Cpp>(const float alpha, const Tensor &A, const Tensor &B, const float beta, Tensor *C, Context *ctx) { const float *APtr = static_cast<const float *>(A.block()->data()); const float *BPtr = static_cast<const float *>(B.block()->data()); float *CPtr = static_cast<float *>(C->block()->mutable_data()); auto transA = A.transpose(); auto transa = transA ? CblasTrans : CblasNoTrans; auto transB = B.transpose(); auto transb = transB ? CblasTrans : CblasNoTrans; const size_t ncolB = B.shape().end()[-1]; const size_t nrowA = A.shape().end()[-2]; const size_t ncolA = A.shape().end()[-1]; auto lda = transA ? nrowA : ncolA; auto ldb = transB ? ncolA : ncolB; auto ldc = ncolB; const int group_count = 1; size_t group_size = A.shape()[0]; // 3d if (A.nDim() == 4u) group_size *= A.shape()[1]; // 4d auto matrix_stride_A = A.shape().end()[-1] * A.shape().end()[-2]; auto matrix_stride_B = B.shape().end()[-1] * B.shape().end()[-2]; auto matrix_stride_C = C->shape().end()[-1] * C->shape().end()[-2]; auto offset_A = 0; auto offset_B = 0; auto offset_C = 0; for (int i = 0; i < group_size; i++) { cblas_sgemm(CblasRowMajor, transa, transb, nrowA, ncolB, ncolA, alpha, APtr + offset_A, lda, BPtr + offset_B, ldb, beta, CPtr + offset_C, ldc); offset_A += matrix_stride_A; offset_B += matrix_stride_B; offset_C += matrix_stride_C; } } #else template <> void Amax<float, lang::Cpp>(const Tensor &in, size_t *out, Context *ctx) { size_t maxPos = 0; float maxVal = 0; const float *inPtr = static_cast<const float *>(in.block()->data()); for (size_t i = 0; i < in.Size(); i++) { // not using strided traversal if (i == 0) { maxVal = inPtr[i]; } else if (inPtr[i] > maxVal) { maxVal = inPtr[i]; maxPos = i; } } *out = maxPos; } template <> void Amin<float, lang::Cpp>(const Tensor &in, size_t *out, Context *ctx) { size_t minPos = 0; float minVal = 0; const float *inPtr = static_cast<const float *>(in.block()->data()); for (size_t i = 0; i < in.Size(); i++) { // not using strided traversal if (i == 0) { minVal = inPtr[i]; } else if (inPtr[i] > minVal) { minVal = inPtr[i]; minPos = i; } } *out = minPos; } template <> void Asum<float, lang::Cpp>(const Tensor &in, float *out, Context *ctx) { float sum = 0; const float *inPtr = static_cast<const float *>(in.block()->data()); for (size_t i = 0; i < in.Size(); i++) { sum += fabs(inPtr[i]); // not using strided traversal } } template <> void Axpy<float, lang::Cpp>(const float alpha, const Tensor &in, Tensor *out, Context *ctx) { float *outPtr = static_cast<float *>(out->block()->mutable_data()); const float *inPtr = static_cast<const float *>(in.block()->data()); vector<int> traversal_info = generate_traversal_info(in); vector<int> shape_multipliers = generate_shape_multipliers(in); for (size_t i = 0; i < in.Size(); i++) { outPtr[i] += alpha * inPtr[traversal_info[in.shape().size()]]; traverse_next(in, shape_multipliers, traversal_info, i + 1); } } template <> void Scale<float, lang::Cpp>(const float x, Tensor *out, Context *ctx) { float *outPtr = static_cast<float *>(out->block()->mutable_data()); for (size_t i = 0; i < out->Size(); i++) { outPtr[i] *= x; // not using strided traversal } } template <> void Dot<float, lang::Cpp>(const Tensor &in1, const Tensor &in2, float *out, Context *ctx) { float sum = 0; // const float *in1Ptr = static_cast<const float *>(in1.data()); // const float *in2Ptr = static_cast<const float *>(in2.data()); // for (size_t i = 0; i < in.Size(); i++) { // sum += in1Ptr[i] * in2Ptr[i]; // } float *outPtr = static_cast<float *>(out->block()->mutable_data()); const float *in1Ptr = static_cast<const float *>(in1.block()->data()); const float *in2Ptr = static_cast<const float *>(in2.block()->data()); vector<int> traversal_info_in1 = generate_traversal_info(in1); vector<int> traversal_info_in2 = generate_traversal_info(in2); vector<int> shape_multipliers_in1 = generate_shape_multipliers(in1); vector<int> shape_multipliers_in2 = generate_shape_multipliers(in2); for (size_t i = 0; i < in1.Size(); i++) { sum += in1Ptr[traversal_info_in1[in1.shape().size()]] * in2Ptr[traversal_info_in2[in2.shape().size()]]; traverse_next(in1, shape_multipliers_in1, traversal_info_in1, i + 1); traverse_next(in2, shape_multipliers_in2, traversal_info_in2, i + 1); } } template <> void GEMV<float, lang::Cpp>(const float alpha, const Tensor &A, const Tensor &v, const float beta, Tensor *out, Context *ctx) { float *outPtr = static_cast<float *>(out->block()->mutable_data()); const float *APtr = static_cast<const float *>(A.block()->data()); const float *vPtr = static_cast<const float *>(v.block()->data()); bool trans = A.transpose(); const size_t m = A.shape(0); const size_t n = A.shape(1); for (size_t r = 0; r < m; r++) { float sum = 0; for (size_t c = 0; c < n; c++) { size_t idx = trans ? c * m + r : r * n + c; sum += APtr[idx] * vPtr[c]; } outPtr[r] = alpha * sum + beta * outPtr[r]; } } #endif // USE_CBLAS template <> void ComputeCrossEntropy<float, lang::Cpp>(bool int_target, const size_t batchsize, const size_t dim, const Tensor &p, const Tensor &t, Tensor *loss, Context *ctx) { const float *pPtr = static_cast<const float *>(p.block()->data()); const int *tPtr = static_cast<const int *>(t.block()->data()); float *lossPtr = static_cast<float *>(loss->block()->mutable_data()); if (int_target) { for (size_t i = 0; i < batchsize; i++) { int truth_idx = tPtr[i]; CHECK_GE(truth_idx, 0); float prob_of_truth = pPtr[i * dim + truth_idx]; lossPtr[i] = -std::log((std::max)(prob_of_truth, FLT_MIN)); } } else { for (size_t i = 0; i < batchsize; i++) { float sum = 0.f; for (size_t j = 0; j < dim; j++) { sum += tPtr[i * dim + j]; } float loss_value = 0.f; for (size_t j = 0, offset = i * dim; j < dim; j++, offset++) { loss_value -= tPtr[offset] / sum * std::log((std::max)(pPtr[offset], FLT_MIN)); } lossPtr[i] = loss_value; } } } template <> void SoftmaxCrossEntropyBwd<float, lang::Cpp>(bool int_target, const size_t batchsize, const size_t dim, const Tensor &p, const Tensor &t, Tensor *grad, Context *ctx) { CHECK_EQ(p.block(), grad->block()) << "Use the same pointer to optimize performance"; // const float* pPtr = static_cast<const float*>(p->data()); const int *tPtr = static_cast<const int *>(t.block()->data()); float *gradPtr = static_cast<float *>(grad->block()->mutable_data()); if (int_target) { for (size_t i = 0; i < batchsize; i++) { int truth_idx = static_cast<int>(tPtr[i]); CHECK_GE(truth_idx, 0); gradPtr[i * dim + truth_idx] -= 1.0; } } else { for (size_t i = 0; i < batchsize; i++) { float sum = 0.f; for (size_t j = 0; j < dim; j++) { sum += tPtr[i * dim + j]; } for (size_t j = 0, offset = i * dim; j < dim; j++, offset++) { gradPtr[offset] -= tPtr[offset] / sum; } } } } template <> void RowMax<float, lang::Cpp>(const Tensor &in, Tensor *out, Context *ctx) { const float *inPtr = static_cast<const float *>(in.block()->data()); float *outPtr = static_cast<float *>(out->block()->mutable_data()); const size_t nrow = in.shape()[0]; const size_t ncol = in.shape()[1]; vector<int> traversal_info = generate_traversal_info(in); vector<int> shape_multipliers = generate_shape_multipliers(in); for (size_t r = 0; r < nrow; r++) { int counter_offset = (r * ncol); float maxval = 0; for (size_t c = 0; c < ncol; c++) { maxval = (std::max)(maxval, inPtr[traversal_info[in.shape().size()]]); traverse_next(in, shape_multipliers, traversal_info, counter_offset + c + 1); } outPtr[r] = maxval; } } // =========Matrix operations ================================================ /* template <> void SoftMax<float, lang::Cpp>(const Tensor &in, Tensor *out, Context* ctx) { CHECK_LE(in.nDim(), 2u) << "Axis is required for SoftMax on multi dimemsional tensor"; out->CopyData(in); size_t nrow = 1, ncol = in.Size(), size = ncol; if (in.nDim() == 2u) { nrow = in.shape(0); ncol = size / nrow; out->Reshape(Shape{nrow, ncol}); } Tensor tmp = RowMax(*out); SubColumn(tmp, out); Exp(*out, out); SumColumns(*out, &tmp); DivColumn(tmp, out); out->Reshape(in.shape()); } template <> void AddCol<float, lang::Cpp>(const size_t nrow, const size_t ncol, const Tensor& A, const Tensor& v, Tensor* out, Context *ctx) { float *outPtr = static_cast<float *>(out->mutable_data()); const float *APtr = static_cast<const float *>(A.data()); const float *vPtr = static_cast<const float *>(v.data()); for (size_t r = 0; r < nrow; r++) { size_t offset = r * ncol; for (size_t c = 0; c < ncol; c++) { outPtr[offset + c] = APtr[offset + c] + vPtr[r]; } } } template <> void AddRow<float, lang::Cpp>(const size_t nrow, const size_t ncol, const Tensor& A, const Tensor& v, Tensor* out, Context *ctx) { float *outPtr = static_cast<float *>(out->mutable_data()); const float *APtr = static_cast<const float *>(A.data()); const float *vPtr = static_cast<const float *>(v.data()); for (size_t r = 0; r < nrow; r++) { size_t offset = r * ncol; for (size_t c = 0; c < ncol; c++) { outPtr[offset + c] = APtr[offset + c] + vPtr[c]; } } } template <> void Outer<float, lang::Cpp>(const size_t m, const size_t n, const Tensor& in1, const Tensor& in2, Tensor* out, Context *ctx) { float *outPtr = static_cast<float *>(out->mutable_data()); const float *in1Ptr = static_cast<const float *>(in1.data()); const float *in2Ptr = static_cast<const float *>(in2.data()); for (size_t r = 0; r < m; r++) { size_t offset = r * n; for (size_t c = 0; c < n; c++) { outPtr[offset + c] = in1Ptr[r] * in2Ptr[c]; } } } template <> void Softmax<float, lang::Cpp>(const size_t nrow, const size_t ncol, const Tensor& in, Tensor* out, Context *ctx) { float *outPtr = static_cast<float *>(out->mutable_data()); const float *inPtr = static_cast<const float *>(in.data()); float *bPtr = new float[ncol]; for (size_t r = 0; r < nrow; r++) { size_t offset = r * ncol; float denom = 0.f; for (size_t c = 0; c < ncol; c++) { bPtr[c] = exp(inPtr[offset + c]); denom += bPtr[c]; } for (size_t c = 0; c < ncol; c++) { size_t idx = offset + c; outPtr[idx] = bPtr[c] / denom; } } delete bPtr; } template <> void SumColumns<float, lang::Cpp>(const size_t nrow, const size_t ncol, const Tensor& in, Tensor* out, Context *ctx) { float *outPtr = static_cast<float *>(out->mutable_data()); const float *inPtr = static_cast<const float *>(in.data()); for (size_t c = 0; c < ncol; c++) { outPtr[c] = 0.f; } for (size_t r = 0; r < nrow; r++) { size_t offset = r * ncol; for (size_t c = 0; c < ncol; c++) { outPtr[c] += inPtr[offset + c]; } } } template <> void SumRows<float, lang::Cpp>(const size_t nrow, const size_t ncol, const Tensor& in, Tensor* out, Context *ctx) { float *outPtr = static_cast<float *>(out->mutable_data()); const float *inPtr = static_cast<const float *>(in.data()); for (size_t r = 0; r < nrow; r++) { size_t offset = r * ncol; outPtr[r] = 0.f; for (size_t c = 0; c < ncol; c++) { outPtr[r] += inPtr[offset + c]; } } } */ } // namespace singa #endif // SINGA_CORE_TENSOR_TENSOR_MATH_CPP_H_
{ "alphanum_fraction": 0.5951626958, "avg_line_length": 37.0772261623, "ext": "h", "hexsha": "2c06f632416580a3c0f3264a2a4192ae048d1526", "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": "a1622a9a036d68c39f8999123d60b68b17c58672", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "fukien/incubator-singa", "max_forks_repo_path": "src/core/tensor/tensor_math_cpp.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "a1622a9a036d68c39f8999123d60b68b17c58672", "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": "fukien/incubator-singa", "max_issues_repo_path": "src/core/tensor/tensor_math_cpp.h", "max_line_length": 93, "max_stars_count": 1, "max_stars_repo_head_hexsha": "a1622a9a036d68c39f8999123d60b68b17c58672", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "fukien/incubator-singa", "max_stars_repo_path": "src/core/tensor/tensor_math_cpp.h", "max_stars_repo_stars_event_max_datetime": "2020-05-25T08:50:51.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-25T08:50:51.000Z", "num_tokens": 13271, "size": 47051 }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <mpi.h> /* Pull in the CBLAS header. */ #ifdef _MACOSX #include <Accelerate/Accelerate.h> #else #ifdef _ATLAS #include <cblas.h> #else #include <gsl_cblas.h> #endif /* _ATLAS */ #endif /* _MACOSX */ /* These headers are provided by ScaleME. */ #include "ScaleME.h" #include "precision.h" #include "mlfma.h" #include "direct.h" #include "itsolver.h" #include "util.h" int matvec (cplx *out, cplx *in, cplx *cur, int id) { long i, nelt = (long)fmaconf.numbases * (long)fmaconf.bspboxvol; /* Compute the contrast pressure. */ #pragma omp parallel for default(shared) private(i) for (i = 0; i < nelt; ++i) cur[i] = in[i] * fmaconf.contrast[i]; /* Reset the direct-interaction buffer and compute * the matrix-vector product for the Green's matrix. */ clrdircache(); ScaleME_applyParFMA (cur, out); if (!id) return 0; /* Add in the identity portion. */ #pragma omp parallel for default(shared) private(i) for (i = 0; i < nelt; ++i) out[i] = fmaconf.cellvol * in[i] - out[i]; return 0; } int gmres (cplx *rhs, cplx *sol, int guess, int mit, real tol, int quiet, augspace *aug) { long j, nelt = (long)fmaconf.numbases * (long)fmaconf.bspboxvol, lwork; int i, rank, one = 1, mred = mit; cplx *h, *v, *mvp, *beta, *vp, *hp, *s, cr, cone = 1., czero = 0., *azp, *zp; real rhn, err, *c; MPI_Comm_rank (MPI_COMM_WORLD, &rank); /* Allocate space for all required complex vectors. */ lwork = (mit + 1) * (mit + nelt + 1) + nelt + mit; v = calloc (lwork, sizeof(cplx)); /* The Krylov subspace. */ beta = v + nelt * (mit + 1); /* The least-squares RHS. */ mvp = beta + mit + 1; /* Buffer for matrix-vector product. */ h = mvp + nelt; /* The upper Hessenberg matrix. */ s = h + (mit + 1) * mit; /* Givens rotation sines. */ /* Allocate space for the Givens rotation cosines. */ c = malloc (mit * sizeof(real)); /* Compute the norm of the RHS for residual scaling. */ rhn = parnorm(rhs, nelt); /* Compute the initial matrix-vector product for the input guess. */ if (guess) matvec (v, sol, mvp, 1); /* Subtract from the RHS to form the residual. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < nelt; ++j) v[j] = rhs[j] - v[j]; /* Zero the initial guess if one wasn't provided. */ if (!guess) memset (sol, 0, nelt * sizeof(cplx)); /* Find the norm of the initial residual. */ err = parnorm(v, nelt); /* Construct the initial Arnoldi vector by normalizing the residual. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < nelt; ++j) v[j] /= err; /* Construct the vector beta for the minimization problem. */ beta[0] = err; /* Report the RRE. */ err /= rhn; if (!rank && !quiet) printf ("True residual: %g\n", err); /* The reduced number of iterations, if the space is augmented. */ if (aug) mred = mit - aug->ntot; for (i = 0; i < mit && err > tol; ++i) { /* Point to the working space for this iteration. */ vp = v + i * nelt; hp = h + i * (mit + 1); /* Compute the next expansion of the Krylov space. */ if (!aug || i < mred) matvec (vp + nelt, vp, mvp, 1); else { /* Update with the next augmented vector. */ azp = aug->az + nelt * ((aug->nmax + aug->start + mred - i) % aug->nmax); /* Use the augmented space. */ memcpy (vp + nelt, azp, nelt * sizeof(cplx)); } /* Perform modified Gram-Schmidt to orthogonalize the basis. */ /* This also builds the Hessenberg matrix column, including * the 2-norm of the next basis vector. */ cmgs (vp + nelt, hp, v, nelt, i + 1); /* Watch for breakdown. */ if (cabs(hp[i + 1]) < REAL_EPSILON) { ++i; break; } /* Apply previous Givens rotations to the Hessenberg column. */ for (j = 0; j < i; ++j) ROT (&one, hp + j, &one, hp + j + 1, &one, c + j, s + j); /* Compute the Givens rotation for the current iteration. */ LARTG (hp + i, hp + i + 1, c + i, s + i, &cr); /* Apply the current Givens rotation to the Hessenberg column. */ hp[i] = cr; hp[i + 1] = 0; /* Perform the rotation on the vector beta. */ ROT (&one, beta + i, &one, beta + i + 1, &one, c + i, s + i); /* Estimate the RRE for this iteration. */ err = cabs(beta[i + 1]) / rhn; if (!rank && !quiet) printf ("GMRES(%d): %g\n", i, err); /* Flush the output buffers. */ fflush (stdout); fflush (stderr); } /* If there were any GMRES iterations, update the solution. */ if (i > 0 && aug) { /* Compute the optimum solution in the Krylov basis. */ cplx *ys; ys = malloc(i * sizeof(cplx)); memcpy (ys, beta, i * sizeof(cplx)); TRSV (CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, i, h, mit + 1, ys, 1); /* Compute the next Krylov vector in the augmented space. */ aug->start = (aug->start + 1) % aug->nmax; if (aug->ntot < aug->nmax) ++(aug->ntot); azp = aug->az + nelt * aug->start; beta[i] = 0; for (j = i - 1; j >= 0; --j) { /* Invert the Givens rotations. */ s[j] = -s[j]; ROT (&one, beta + j, &one, beta + j + 1, &one, c + j, s + j); } GEMV (CblasColMajor, CblasNoTrans, nelt, i + 1, &cone, v, nelt, beta, 1, &czero, azp, 1); /* Overwrite the Krylov subspace with the augmented subspace. * The start pointer has already been incremented! */ for (j = mred; j < i; ++j) { zp = aug->z + nelt * ((aug->nmax + aug->start + mred - j - 1) % aug->nmax); memcpy(v + j * nelt, zp, nelt * sizeof(cplx)); } /* Compute the solution update. */ zp = aug->z + nelt * aug->start; GEMV (CblasColMajor, CblasNoTrans, nelt, i, &cone, v, nelt, ys, 1, &czero, zp, 1); for (j = 0; j < nelt; ++j) sol[j] += zp[j]; free(ys); } else if (i > 0) { /* Compute the minimizer of the least-squares problem. */ TRSV (CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, i, h, mit + 1, beta, 1); /* Compute the solution update in place. */ GEMV (CblasColMajor, CblasNoTrans, nelt, i, &cone, v, nelt, beta, 1, &cone, sol, 1); } free (v); free (c); return i; } int bicgstab (cplx *rhs, cplx *sol, int guess, int mit, real tol, int quiet) { long j, nelt = (long)fmaconf.numbases * (long)fmaconf.bspboxvol; int i, rank; cplx *r, *rhat, *v, *p, *mvp, *t; cplx rho, alpha, omega, beta; real err, rhn; MPI_Comm_rank (MPI_COMM_WORLD, &rank); rho = alpha = omega = 1.; /* Allocate and zero the work arrays. */ r = calloc (6L * nelt, sizeof(cplx)); rhat = r + nelt; v = rhat + nelt; p = v + nelt; t = p + nelt; mvp = t + nelt; /* Compute the norm of the right-hand side for residual scaling. */ rhn = parnorm(rhs, nelt); /* Compute the inital matrix-vector product for the input guess. */ if (guess) matvec (r, sol, mvp, 1); /* Subtract from the RHS to form the residual. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < nelt; ++j) r[j] = rhs[j] - r[j]; if (!guess) memset (sol, 0, nelt * sizeof(cplx)); /* Copy the initial residual as the test vector. */ memcpy (rhat, r, nelt * sizeof(cplx)); /* Find the norm of the initial residual. */ err = parnorm(r, nelt) / rhn; if (!rank && !quiet) printf ("True residual: %g\n", err); /* Run iterations until convergence or the maximum is reached. */ for (i = 0; i < mit && err > tol; ++i) { /* Pre-compute portion of beta from previous iteration. */ beta = alpha / (rho * omega); /* Compute rho for this iteration. */ rho = pardot (rhat, r, nelt); /* Include the missing factor in beta. */ beta *= rho; /* Update the search vector. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < nelt; ++j) p[j] = r[j] + beta * (p[j] - omega * v[j]); /* Compute the first search step, v = A * p. */ matvec (v, p, mvp, 1); /* Compute the next alpha. */ alpha = rho / pardot (rhat, v, nelt); #pragma omp parallel for default(shared) private(j) for (j = 0; j < nelt; ++j) { /* Update the solution vector. */ sol[j] += alpha * p[j]; /* Update the residual vector. */ r[j] -= alpha * v[j]; } /* Compute the scaled residual norm and stop if convergence * has been achieved. */ err = parnorm(r, nelt) / rhn; if (!rank && !quiet) printf ("BiCG-STAB(%0.1f): %g\n", 0.5 + i, err); /* Flush the output buffers. */ fflush (stdout); fflush (stderr); if (err < tol) break; /* Compute the next search step, t = A * r. */ matvec (t, r, mvp, 1); /* Compute the update direction. */ omega = pardot (t, r, nelt) / pardot (t, t, nelt); /* Update both the residual and the solution guess. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < nelt; ++j) { /* Update the solution vector. */ sol[j] += omega * r[j]; /* Update the residual vector. */ r[j] -= omega * t[j]; } /* Compute the scaled residual norm. */ err = parnorm(r, nelt) / rhn; if (!rank && !quiet) printf ("BiCG-STAB(%d): %g\n", i + 1, err); fflush (stdout); fflush (stderr); } free (r); return i; }
{ "alphanum_fraction": 0.6019722098, "avg_line_length": 29.2590163934, "ext": "c", "hexsha": "476e08b91b87054306ecabab03f77cc218111aa7", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-06-08T10:23:36.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-12T17:29:05.000Z", "max_forks_repo_head_hexsha": "4cce650b07341234402096dea3c8ab04deb7375f", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ahesford/afma", "max_forks_repo_path": "itsolver.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "4cce650b07341234402096dea3c8ab04deb7375f", "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": "ahesford/afma", "max_issues_repo_path": "itsolver.c", "max_line_length": 72, "max_stars_count": null, "max_stars_repo_head_hexsha": "4cce650b07341234402096dea3c8ab04deb7375f", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ahesford/afma", "max_stars_repo_path": "itsolver.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3064, "size": 8924 }
#ifndef UTILS_H #define UTILS_H #ifdef __cplusplus extern "C" { #endif #include <stdio.h> // for printf #include <stdlib.h> // for posix_memalign #include <string.h> // for memset #include <math.h> // for sqrt #include <float.h> //for FLT_MAX #include <time.h> // for clock_gettime #include <cblas.h> #define STACK_SIZE_TOTAL 0x8000000 // 128Mbytes typedef struct { int index; float score; }score_index_struct; typedef struct { float x; float y; float w; float h; }box_struct; typedef struct { void *stack_starting_address; char *stack_current_address; unsigned int stack_current_alloc_size; }stack_struct; void init_stack ( void ); void free_stack ( void ); void *alloc_from_stack ( unsigned int len ); void partial_free_from_stack ( unsigned int len ); unsigned int get_stack_current_alloc_size ( void ); void reset_stack_ptr_to_assigned_position ( unsigned int assigned_size ); double what_time_is_it_now ( void ); #ifdef __cplusplus } #endif #endif // UTILS_H
{ "alphanum_fraction": 0.6583629893, "avg_line_length": 14.05, "ext": "h", "hexsha": "d90691875b3f02204a9234eea6fd89c637da8631", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-02-23T05:43:42.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-23T05:43:42.000Z", "max_forks_repo_head_hexsha": "2d8e671431e1f53ef0e30b5185805c45edf38cfc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lincolnhard/mobilenetssd-C-scratch", "max_forks_repo_path": "utils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2d8e671431e1f53ef0e30b5185805c45edf38cfc", "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": "lincolnhard/mobilenetssd-C-scratch", "max_issues_repo_path": "utils.h", "max_line_length": 47, "max_stars_count": 2, "max_stars_repo_head_hexsha": "2d8e671431e1f53ef0e30b5185805c45edf38cfc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lincolnhard/mobilenetssd-C-scratch", "max_stars_repo_path": "utils.h", "max_stars_repo_stars_event_max_datetime": "2019-10-14T01:54:18.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-18T06:14:31.000Z", "num_tokens": 291, "size": 1124 }
#pragma once #include <gsl/gsl> #include "halley/file_formats/config_file.h" namespace YAML { class Node; class Emitter; } namespace Halley { class Path; class YAMLConvert { public: class EmitOptions { public: Vector<String> mapKeyOrder; }; static void parseConfig(ConfigFile& config, gsl::span<const gsl::byte> data); static ConfigNode parseYAMLNode(const YAML::Node& node); static ConfigFile parseConfig(gsl::span<const gsl::byte> data); static ConfigFile parseConfig(const Bytes& data); static ConfigNode parseConfig(const String& str); static String generateYAML(const ConfigFile& config, const EmitOptions& options); static String generateYAML(const ConfigNode& node, const EmitOptions& options); private: static void emitNode(const ConfigNode& node, YAML::Emitter& emitter, const EmitOptions& options); static void emitSequence(const ConfigNode& node, YAML::Emitter& emitter, const EmitOptions& options); static void emitMap(const ConfigNode& node, YAML::Emitter& emitter, const EmitOptions& options); static bool isCompactSequence(const ConfigNode& node, int depth); }; }
{ "alphanum_fraction": 0.7573073516, "avg_line_length": 29.7105263158, "ext": "h", "hexsha": "d3afa84ee26a7a847ad49047e1fd09b1045f536e", "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/engine/utils/include/halley/file_formats/yaml_convert.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/engine/utils/include/halley/file_formats/yaml_convert.h", "max_line_length": 103, "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/engine/utils/include/halley/file_formats/yaml_convert.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 264, "size": 1129 }
#include <math.h> #include <stdio.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_vector.h> #include <qdm.h> gsl_vector * qdm_knots_vector(size_t spline_df, gsl_vector *interior_knots) { size_t size = spline_df * 2 + interior_knots->size; gsl_vector *knots = gsl_vector_alloc(size); // Fill front with zeros. for (size_t i = 0; i < spline_df; i++) { gsl_vector_set(knots, i, 0); } // Fill middle with interior knots. gsl_vector_view view = gsl_vector_subvector(knots, spline_df, interior_knots->size); gsl_blas_dcopy(interior_knots, &view.vector); // Fill end with ones. for (size_t i = spline_df + interior_knots->size; i < knots->size; i++) { gsl_vector_set(knots, i, 1); } return knots; } int qdm_knots_rss( double *rss, gsl_vector *sorted_data, gsl_vector *middle, gsl_vector *interior_knots, size_t spline_df ) { int status = 0; gsl_vector *m_knots = qdm_knots_vector(spline_df, interior_knots); size_t m = spline_df + interior_knots->size; gsl_matrix *ix = gsl_matrix_alloc(middle->size, m + 1); gsl_vector *emperical_quantiles = qdm_vector_quantile(sorted_data, middle); gsl_vector *theta = gsl_vector_alloc(ix->size2); gsl_vector *spline_quantiles = gsl_vector_alloc(emperical_quantiles->size); /* Build the true quantile function. */ qdm_ispline_matrix(ix, middle, spline_df, m_knots); /* Check if the matrix is full rank. */ double det = 0; status = qdm_matrix_det_tmm(ix, &det); if (status != 0) { goto cleanup; } if (det <= 0) { goto cleanup; } status = qdm_theta_optimize(theta, emperical_quantiles, ix); if (status != 0) { goto cleanup; } status = gsl_blas_dgemv(CblasNoTrans , 1.0, ix, theta, 0.0, spline_quantiles); if (status != 0) { goto cleanup; } *rss = qdm_vector_rss(emperical_quantiles, spline_quantiles); cleanup: gsl_vector_free(spline_quantiles); gsl_vector_free(theta); gsl_vector_free(emperical_quantiles); gsl_matrix_free(ix); gsl_vector_free(m_knots); return status; } int qdm_knots_optimize( gsl_vector *result, gsl_rng *rng, gsl_vector *sorted_data, gsl_vector *middle, gsl_vector *possible_knots, size_t iterate_n, size_t spline_df ) { int status = 0; double rss = INFINITY; double rss_found = 0; gsl_vector *interior_knots = gsl_vector_alloc(result->size); for (size_t i = 0; i < iterate_n; i++) { status = gsl_ran_choose( rng, interior_knots->data, interior_knots->size, possible_knots->data, possible_knots->size, sizeof(double) ); if (status != 0) { goto cleanup; } status = qdm_knots_rss( &rss_found, sorted_data, middle, interior_knots, spline_df ); if (status != 0) { goto cleanup; } if (rss_found < rss) { rss = rss_found; status = gsl_vector_memcpy(result, interior_knots); if (status != 0) { goto cleanup; } } } cleanup: gsl_vector_free(interior_knots); return status; }
{ "alphanum_fraction": 0.666025641, "avg_line_length": 20.5263157895, "ext": "c", "hexsha": "7e76f28b02cafe5b81e57458b07870247ad64597", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_path": "src/knots.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_path": "src/knots.c", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_path": "src/knots.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 945, "size": 3120 }
/** * * @file core_cgelqt.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Hatem Ltaief * @author Mathieu Faverge * @author Jakub Kurzak * @date 2010-11-15 * @generated c Tue Jan 7 11:44:45 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_PLASMA_Complex32_t * * CORE_cgelqt - computes a LQ factorization of a complex M-by-N tile A: A = L * Q. * * The tile Q is represented as a product of elementary reflectors * * Q = H(k)' . . . H(2)' H(1)', where k = min(M,N). * * Each H(i) has the form * * H(i) = I - tau * v * v' * * where tau is a complex scalar, and v is a complex vector with * v(1:i-1) = 0 and v(i) = 1; conjfg(v(i+1:n)) is stored on exit in * A(i,i+1:n), and tau in TAU(i). * ******************************************************************************* * * @param[in] M * The number of rows of the tile A. M >= 0. * * @param[in] N * The number of columns of the tile A. N >= 0. * * @param[in] IB * The inner-blocking size. IB >= 0. * * @param[in,out] A * On entry, the M-by-N tile A. * On exit, the elements on and below the diagonal of the array * contain the M-by-min(M,N) lower trapezoidal tile L (L is * lower triangular if M <= N); the elements above the diagonal, * with the array TAU, represent the unitary tile Q as a * product of elementary reflectors (see Further Details). * * @param[in] LDA * The leading dimension of the array A. LDA >= max(1,M). * * @param[out] T * The IB-by-N triangular factor T of the block reflector. * T is upper triangular by block (economic storage); * The rest of the array is not referenced. * * @param[in] LDT * The leading dimension of the array T. LDT >= IB. * * @param[out] TAU * The scalar factors of the elementary reflectors (see Further * Details). * * @param[out] WORK * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if -i, the i-th argument had an illegal value * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_cgelqt = PCORE_cgelqt #define CORE_cgelqt PCORE_cgelqt #endif int CORE_cgelqt(int M, int N, int IB, PLASMA_Complex32_t *A, int LDA, PLASMA_Complex32_t *T, int LDT, PLASMA_Complex32_t *TAU, PLASMA_Complex32_t *WORK) { int i, k, sb; /* Check input arguments */ if (M < 0) { coreblas_error(1, "Illegal value of M"); return -1; } if (N < 0) { coreblas_error(2, "Illegal value of N"); return -2; } if ((IB < 0) || ( (IB == 0) && ((M > 0) && (N > 0)) )) { coreblas_error(3, "Illegal value of IB"); return -3; } if ((LDA < max(1,M)) && (M > 0)) { coreblas_error(5, "Illegal value of LDA"); return -5; } if ((LDT < max(1,IB)) && (IB > 0)) { coreblas_error(7, "Illegal value of LDT"); return -7; } /* Quick return */ if ((M == 0) || (N == 0) || (IB == 0)) return PLASMA_SUCCESS; k = min(M, N); for(i = 0; i < k; i += IB) { sb = min(IB, k-i); LAPACKE_cgelq2_work(LAPACK_COL_MAJOR, sb, N-i, &A[LDA*i+i], LDA, &TAU[i], WORK); LAPACKE_clarft_work(LAPACK_COL_MAJOR, lapack_const(PlasmaForward), lapack_const(PlasmaRowwise), N-i, sb, &A[LDA*i+i], LDA, &TAU[i], &T[LDT*i], LDT); if (M > i+sb) { LAPACKE_clarfb_work( LAPACK_COL_MAJOR, lapack_const(PlasmaRight), lapack_const(PlasmaNoTrans), lapack_const(PlasmaForward), lapack_const(PlasmaRowwise), M-i-sb, N-i, sb, &A[LDA*i+i], LDA, &T[LDT*i], LDT, &A[LDA*i+(i+sb)], LDA, WORK, M-i-sb); } } return PLASMA_SUCCESS; }
{ "alphanum_fraction": 0.4960469844, "avg_line_length": 29.5133333333, "ext": "c", "hexsha": "c1495dba67890c1a8faf11673aa98adc10f409a4", "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_cgelqt.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_cgelqt.c", "max_line_length": 84, "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_cgelqt.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1274, "size": 4427 }
#pragma once #include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_integration.h> double integrator_qag(gsl_function *, double, double, double, double, size_t, double *,int *); double integrator_cquad(gsl_function *,double,double,double,double,size_t,double *,int *); double integrator_qags(gsl_function *,double,double,double,double,size_t,double *,int *);
{ "alphanum_fraction": 0.7738419619, "avg_line_length": 45.875, "ext": "h", "hexsha": "a1b88fb2f299d5f84cb2bc03908526926e639d62", "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": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_path": "src/lib/nrMath/integrators.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "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": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_path": "src/lib/nrMath/integrators.h", "max_line_length": 94, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_path": "src/lib/nrMath/integrators.h", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "num_tokens": 89, "size": 367 }
/* Copyright (c) 2017 Bradley Worley <geekysuavo@gmail.com> * Released under the MIT License */ /* ensure once-only inclusion. */ #ifndef __MATTE_BLAS_H__ #define __MATTE_BLAS_H__ /* include the vector and matrix headers. */ #include <matte/vector.h> #include <matte/matrix.h> /* include the complex vector and matrix headers. */ #include <matte/complex-vector.h> #include <matte/complex-matrix.h> /* include the atlas blas header. */ #include <cblas.h> /* function declarations, level 1, double (blas.c): */ int matte_daxpy (double alpha, Vector x, Vector y); int matte_dscal (double alpha, Vector x); int matte_dcopy (Vector x, Vector y); int matte_dswap (Vector x, Vector y); int matte_ddot (Vector x, Vector y, double *out); int matte_dnrm2 (Vector x, double *out); /* function declarations, level 1, complex double (blas.c): */ int matte_zaxpy (complex double alpha, ComplexVector x, ComplexVector y); int matte_zscal (complex double alpha, ComplexVector x); int matte_zcopy (ComplexVector x, ComplexVector y); int matte_zswap (ComplexVector x, ComplexVector y); int matte_zdotu (ComplexVector x, ComplexVector y, complex double *out); int matte_zdotc (ComplexVector x, ComplexVector y, complex double *out); int matte_znrm2 (ComplexVector x, double *out); /* function declarations, level 2, double (blas.c): */ int matte_dgemv (MatteTranspose trans, double alpha, Matrix A, Vector x, double beta, Vector y); int matte_dsymv (MatteTriangle uplo, double alpha, Matrix A, Vector x, double beta, Vector y); int matte_dtrmv (MatteTriangle uplo, MatteTranspose trans, MatteDiagonal diag, Matrix A, Vector x); int matte_dtrsv (MatteTriangle uplo, MatteTranspose trans, MatteDiagonal diag, Matrix A, Vector x); int matte_dger (double alpha, Vector x, Vector y, Matrix A); int matte_dsyr (MatteTriangle uplo, double alpha, Vector x, Matrix A); int matte_dsyr2 (MatteTriangle uplo, double alpha, Vector x, Vector y, Matrix A); /* function declarations, level 2, complex double (blas.c): */ int matte_zgemv (MatteTranspose trans, complex double alpha, ComplexMatrix A, ComplexVector x, complex double beta, ComplexVector y); int matte_zhemv (MatteTriangle uplo, complex double alpha, ComplexMatrix A, ComplexVector x, complex double beta, ComplexVector y); int matte_ztrmv (MatteTriangle uplo, MatteTranspose trans, MatteDiagonal diag, ComplexMatrix A, ComplexVector x); int matte_ztrsv (MatteTriangle uplo, MatteTranspose trans, MatteDiagonal diag, ComplexMatrix A, ComplexVector x); int matte_zher (MatteTriangle uplo, double alpha, ComplexVector x, ComplexMatrix A); int matte_zher2 (MatteTriangle uplo, complex double alpha, ComplexVector x, ComplexVector y, ComplexMatrix A); /* function declarations, level 3, double (blas.c): */ int matte_dgemm (MatteTranspose transA, MatteTranspose transB, double alpha, Matrix A, Matrix B, double beta, Matrix C); /* FIXME */ /* function declarations, level 3, complex double (blas.c): */ int matte_zgemm (MatteTranspose transA, MatteTranspose transB, complex double alpha, ComplexMatrix A, ComplexMatrix B, complex double beta, ComplexMatrix C); /* FIXME */ #endif /* !__MATTE_BLAS_H__ */
{ "alphanum_fraction": 0.6943645773, "avg_line_length": 30.7787610619, "ext": "h", "hexsha": "bbe15c46375d57064d318862183b03bb16cda852", "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": "5bfbddb5aa3c9ff7451b47cbf6561b7f000a7cff", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "geekysuavo/matte", "max_forks_repo_path": "matte/blas.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5bfbddb5aa3c9ff7451b47cbf6561b7f000a7cff", "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": "geekysuavo/matte", "max_issues_repo_path": "matte/blas.h", "max_line_length": 77, "max_stars_count": 2, "max_stars_repo_head_hexsha": "5bfbddb5aa3c9ff7451b47cbf6561b7f000a7cff", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "geekysuavo/matte", "max_stars_repo_path": "matte/blas.h", "max_stars_repo_stars_event_max_datetime": "2020-09-03T23:47:43.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-03T07:58:09.000Z", "num_tokens": 835, "size": 3478 }
#include <cblas.h> #include "tasks.h" void solve_task_seq(void *ptr) { struct solve_task_arg *arg = (struct solve_task_arg*) ptr; int n = arg->n; int nrhs = arg->nrhs; double *L = arg->L; int ldL = arg->ldL; double *X = arg->X; int ldX = arg->ldX; // Solve L * X = B, where B and X share the same memory. cblas_dtrsm(CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasNonUnit, n, nrhs, 1.0, L, ldL, X, ldX); }
{ "alphanum_fraction": 0.5452793834, "avg_line_length": 22.5652173913, "ext": "c", "hexsha": "ec2564c4861b1fb740fcdaa91a7d66da576941cb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "NLAFET/pcp-runtime", "max_forks_repo_path": "src/examples/dtrsm/task-solve-seq.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "NLAFET/pcp-runtime", "max_issues_repo_path": "src/examples/dtrsm/task-solve-seq.c", "max_line_length": 81, "max_stars_count": null, "max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "NLAFET/pcp-runtime", "max_stars_repo_path": "src/examples/dtrsm/task-solve-seq.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 167, "size": 519 }
/* * 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_PHYSICS_ROTOR_DATABASE_3D_H_ #define SIM_PHYSICS_ROTOR_DATABASE_3D_H_ #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <string> #include "common/macros.h" class RotorDatabase3d { public: explicit RotorDatabase3d(const std::string &filename); virtual ~RotorDatabase3d(); // The rotor force prime frame is attached to an isolated rotor, and is // defined as follows: // X_prime: The rotor shaft axis, positive in the thrusting direction. // Y_prime: The in-plane axis in the Z_prime cross X_prime direction. // Z_prime: The in-plane axis aligned with the apparent edgewise wind // direction. Positive is into the wind. // Z_prime force [N] is a rotor in-plane force [N]. double CalcForceZPrime(double angular_rate, double axial_vel, double edgewise_vel, double air_density) const; // Y_prime force [N] is the rotor in-plane side force [N]. // The sign is flipped if rotor direction does not match direction the // the database was created assuming. double CalcForceYPrime(double angular_rate, double axial_vel, double edgewise_vel, double air_density, int dir) const; // Roll moment [N-m] is the right-handed moment about the Z_prime force axis. double CalcMomZPrime(double angular_rate, double axial_vel, double edgewise_vel, double air_density, int dir) const; // Pitch moment [N-m] is the right-handed moment about the Y_prime axis: // positive is pitch up/back. double CalcMomYPrime(double angular_rate, double axial_vel, double edgewise_vel, double air_density) const; // Thrust [N] is positive for propulsive/motoring, and is equivalent // to the rotor X or X_prime axis force. double CalcThrust(double angular_rate, double axial_vel, double edgewise_vel, double air_density) const; // Torque [N-m] is aerodynamic moment about thrust axis (opposes rotation // direction for positive thrusts). double CalcTorque(double angular_rate, double axial_vel, double edgewise_vel, double air_density, int dir) const; double LookupZForceCoeff(double angular_rate, double axial_vel, double edgewise_vel) const; double LookupYForceCoeff(double angular_rate, double axial_vel, double edgewise_vel) const; double LookupZMomCoeff(double angular_rate, double axial_vel, double edgewise_vel) const; double LookupYMomCoeff(double angular_rate, double axial_vel, double edgewise_vel) const; double LookupThrustCoeff(double angular_rate, double axial_vel, double edgewise_vel) const; double LookupTorqueCoeff(double angular_rate, double axial_vel, double edgewise_vel) const; double CalcThrustScaleFactor(double angular_rate, double axial_vel, double edgewise_vel) const; double CalcTorqueScaleFactor(double angular_rate, double axial_vel, double edgewise_vel) const; private: double radius_; double radius_pow4_; double radius_pow5_; int32_t spin_; gsl_vector *angular_rates_; gsl_vector *axial_vels_; gsl_vector *edgewise_vels_; gsl_vector *z_prime_force_coeffs_; gsl_vector *y_prime_force_coeffs_; gsl_vector *z_prime_mom_coeffs_; gsl_vector *y_prime_mom_coeffs_; gsl_vector *thrust_coeffs_; gsl_vector *torque_coeffs_; DISALLOW_COPY_AND_ASSIGN(RotorDatabase3d); }; #endif // SIM_PHYSICS_ROTOR_DATABASE_3D_H_
{ "alphanum_fraction": 0.708687441, "avg_line_length": 39.5887850467, "ext": "h", "hexsha": "f124ee091b64a4d62c3df083b4b068e2ffb7a477", "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/physics/rotor_database_3d.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/physics/rotor_database_3d.h", "max_line_length": 79, "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/physics/rotor_database_3d.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": 955, "size": 4236 }
// CONSTANTIN MIHAI - 336CA // TEMA 2 ASC #include <cblas.h> #include "utils.h" double* copy(int N, double *A) { int i, j; double *B = malloc(N * N * sizeof(double)); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { B[i * N + j] = A[i * N + j]; } } return B; } double* add_matrix(int N, double *A, double *B) { int i, j; double *C = calloc(N * N, sizeof(double)); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { C[i * N + j] = A[i * N + j] + B[i * N + j]; } } return C; } double* my_solver(int N, double *A, double *B) { /* A - matrice superior triunghiulara B - matrice normala Vrem C = B * A^t + A^2 * B */ /* CblasRowMajor - matrice stocata pe o singura linie CblasRight - facem B * A^t CblasUpper - matrice superior triunghiulara CblasTrans - folosim A^t CblasNoTrans - folosim A, nu A^t CblasNonUnit - A nu e matrice unitara */ // B2 <- B2 * A^t double *B2 = copy(N, B); cblas_dtrmm(CblasRowMajor, CblasRight, CblasUpper, CblasTrans, CblasNonUnit, N, N, 1.0, A, N, B2, N); // A2 <- A2 * A double *A2 = copy(N, A); cblas_dtrmm(CblasRowMajor, CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, N, N, 1.0, A, N, A2, N); // B <- A2 * B cblas_dtrmm(CblasRowMajor, CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, N, N, 1.0, A2, N, B, N); // result <- B2 + B double *result = add_matrix(N, B2, B); return result; }
{ "alphanum_fraction": 0.583273767, "avg_line_length": 20.2753623188, "ext": "c", "hexsha": "00c8daf93b6a528bf354c696263d248a1b8727aa", "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": "098c99d82dad8fb5d0e909da930c72f1185a99e2", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "mihai-constantin/ACS", "max_forks_repo_path": "ASC/Teme/tema2/solver_blas.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "098c99d82dad8fb5d0e909da930c72f1185a99e2", "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": "mihai-constantin/ACS", "max_issues_repo_path": "ASC/Teme/tema2/solver_blas.c", "max_line_length": 104, "max_stars_count": null, "max_stars_repo_head_hexsha": "098c99d82dad8fb5d0e909da930c72f1185a99e2", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "mihai-constantin/ACS", "max_stars_repo_path": "ASC/Teme/tema2/solver_blas.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 568, "size": 1399 }
/* * vbHmmGaussIntensity.c * Model-specific core functions for VB-HMM-GAUSS. * * Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN * Copyright 2011-2016 * Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan. * All rights reserved. * * Ver. 1.0.0 * Last modified on 2016.02.08 */ #include "vbHmmGaussIntensity.h" #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_psi.h> #include <string.h> #include "rand.h" #ifdef _OPENMP #include "omp.h" #endif #define MAX(a,b) ((a)>(b)?(a):(b)) #define MIN(a,b) ((a)<(b)?(a):(b)) static int isGlobalAnalysis = 0; void setFunctions_gaussInt(){ commonFunctions funcs; funcs.newModelParameters = newModelParameters_gaussInt; funcs.freeModelParameters = freeModelParameters_gaussInt; funcs.newModelStats = newModelStats_gaussInt; funcs.freeModelStats = freeModelStats_gaussInt; funcs.initializeVbHmm = initializeVbHmm_gaussInt; funcs.pTilde_z1 = pTilde_z1_gaussInt; funcs.pTilde_zn_zn1 = pTilde_zn_zn1_gaussInt; funcs.pTilde_xn_zn = pTilde_xn_zn_gaussInt; funcs.calcStatsVars = calcStatsVars_gaussInt; funcs.maximization = maximization_gaussInt; funcs.varLowerBound = varLowerBound_gaussInt; funcs.reorderParameters = reorderParameters_gaussInt; funcs.outputResults = outputResults_gaussInt; setFunctions( funcs ); } void setGFunctions_gaussInt(){ gCommonFunctions funcs; funcs.newModelParameters = newModelParameters_gaussInt; funcs.freeModelParameters = freeModelParameters_gaussInt; funcs.newModelStats = newModelStats_gaussInt; funcs.freeModelStats = freeModelStats_gaussInt; funcs.newModelStatsG = newModelStatsG_gaussInt; funcs.freeModelStatsG = freeModelStatsG_gaussInt; funcs.initializeVbHmmG = initializeVbHmmG_gaussInt; funcs.pTilde_z1 = pTilde_z1_gaussInt; funcs.pTilde_zn_zn1 = pTilde_zn_zn1_gaussInt; funcs.pTilde_xn_zn = pTilde_xn_zn_gaussInt; funcs.calcStatsVarsG = calcStatsVarsG_gaussInt; funcs.maximizationG = maximizationG_gaussInt; funcs.varLowerBoundG = varLowerBoundG_gaussInt; funcs.reorderParametersG = reorderParametersG_gaussInt; funcs.outputResultsG = outputResultsG_gaussInt; setGFunctions( funcs ); isGlobalAnalysis = 1; } void outputResults_gaussInt( xn, gv, iv, logFP ) xnDataSet *xn; globalVars *gv; indVars *iv; FILE *logFP; { outputGaussIntResults( xn, gv, iv, logFP ); } void outputResultsG_gaussInt( xns, gv, ivs, logFP ) xnDataBundle *xns; globalVars *gv; indVarBundle *ivs; FILE *logFP; { outputGaussIntResultsG( xns, gv, ivs, logFP ); } void *newModelParameters_gaussInt( xn, sNo ) xnDataSet *xn; int sNo; { int i; gaussIntParameters *p = (gaussIntParameters*)malloc( sizeof(gaussIntParameters) ); p->uPiArr = (double*)malloc( sNo * sizeof(double) ); p->sumUPi = 0.0; p->uAMat = (double**)malloc( sNo * sizeof(double*) ); for( i = 0 ; i < sNo ; i++ ){ p->uAMat[i] = (double*)malloc( sNo * sizeof(double) ); } p->sumUAArr = (double*)malloc( sNo * sizeof(double) ); p->avgPi = (double *)malloc( sNo * sizeof(double) ); p->avgLnPi = (double *)malloc( sNo * sizeof(double) ); p->avgA = (double **)malloc( sNo * sizeof(double*) ); p->avgLnA = (double **)malloc( sNo * sizeof(double*) ); for( i = 0 ; i < sNo ; i++ ){ p->avgA[i] = (double *)malloc( sNo * sizeof(double) ); p->avgLnA[i] = (double *)malloc( sNo * sizeof(double) ); } return p; } void freeModelParameters_gaussInt( p, xn, sNo ) void **p; xnDataSet *xn; int sNo; { gaussIntParameters *gp = *p; int i; free( gp->uPiArr ); for( i = 0 ; i < sNo ; i++ ){ free( gp->uAMat[i] ); } free( gp->uAMat ); free( gp->sumUAArr ); free( gp->avgPi ); free( gp->avgLnPi ); for( i = 0 ; i < sNo ; i++ ){ free( gp->avgA[i] ); free( gp->avgLnA[i] ); } free( gp->avgA ); free( gp->avgLnA ); free( gp ); *p = NULL; } void *newModelStats_gaussInt( xn, gv, iv ) xnDataSet *xn; globalVars *gv; indVars *iv; { if( isGlobalAnalysis == 0 ){ int sNo = gv->sNo; gaussIntStats *s = (gaussIntStats*)malloc( sizeof(gaussIntStats) ); int i; s->Ni = (double *)malloc( sNo * sizeof(double) ); s->Nij = (double **)malloc( sNo * sizeof(double*) ); for( i = 0 ; i < sNo ; i++ ) { s->Nij[i] = (double *)malloc( sNo * sizeof(double) ); } s->Nii = (double *)malloc( sNo * sizeof(double) ); return s; } else { return NULL; } } void freeModelStats_gaussInt( s, xn, gv, iv ) void **s; xnDataSet *xn; globalVars *gv; indVars *iv; { if( isGlobalAnalysis == 0 ){ int sNo = gv->sNo; gaussIntStats *gs = *s; int i; free( gs->Ni ); for( i = 0 ; i < sNo ; i++ ) { free( gs->Nij[i] ); } free( gs->Nij ); free( gs->Nii ); free( gs ); *s = NULL; } } void *newModelStatsG_gaussInt( xns, gv, ivs) xnDataBundle *xns; globalVars *gv; indVarBundle *ivs; { int sNo = gv->sNo; gaussIntGlobalStats *gs = (gaussIntGlobalStats*)malloc( sizeof(gaussIntGlobalStats) ); int i; gs->NijR = (double **)malloc( sNo * sizeof(double*) ); for( i = 0 ; i < sNo ; i++ ) { gs->NijR[i] = (double *)malloc( sNo * sizeof(double) ); } gs->NiiR = (double *)malloc( sNo * sizeof(double) ); gs->NiR = (double *)malloc( sNo * sizeof(double) ); gs->z1iR = (double *)malloc( sNo * sizeof(double) ); return gs; } void freeModelStatsG_gaussInt( gs, xns, gv, ivs ) void **gs; xnDataBundle *xns; globalVars *gv; indVarBundle *ivs; { int sNo = gv->sNo; gaussIntGlobalStats *ggs = *gs; int i; free( ggs->NiR ); for( i = 0 ; i < sNo ; i++ ) { free( ggs->NijR[i] ); } free( ggs->NijR ); free( ggs->NiiR ); free( ggs->z1iR ); free( *gs ); *gs = NULL; } void initializeVbHmm_gaussInt( xn, gv, iv ) xnDataSet *xn; globalVars *gv; indVars *iv; { gaussIntData *d = xn->data; size_t dLen = xn->N; int sNo = gv->sNo; gaussIntParameters *p = gv->params; int i, j; double totalX = 0.0, precX, varX = 0.0; for( i = 0 ; i < dLen ; i++ ){ totalX += d->v[i]; } double meanX = totalX / (double)dLen; for( i = 0 ; i < dLen ; i++ ){ varX += pow(d->v[i] - meanX, 2.0); } varX /= (double)(dLen - 1); precX = 1.0 / varX; // hyper parameter for p( pi(i) ) p->sumUPi = 0.0; for( i = 0 ; i < sNo ; i++ ){ p->uPiArr[i] = 1.0; p->sumUPi += p->uPiArr[i]; } // hyper parameter for p( A(i,j) ) for( i = 0 ; i < sNo ; i++ ){ p->sumUAArr[i] = 0.0; for( j = 0 ; j < sNo ; j++ ){ if( j == i ){ p->uAMat[i][j] = 5.0; } else { p->uAMat[i][j] = 1.0; } p->sumUAArr[i] += p->uAMat[i][j]; } } // hyper parameter for p( mu(k), lm(k) ) for( i = 0 ; i < sNo ; i++ ){ p->uBt = 1.0; p->uMu = meanX * 2.0 / (double)sNo; p->uA = 1.0; p->uB = p->uA / precX ; } initialize_indVars_gaussInt( xn, gv, iv ); calcStatsVars_gaussInt( xn, gv, iv ); maximization_gaussInt( xn, gv, iv ); } void initializeVbHmmG_gaussInt( xns, gv, ivs ) xnDataBundle *xns; globalVars *gv; indVarBundle *ivs; { gaussIntData *d; size_t dLen, totalN; int sNo = gv->sNo, rNo = xns->R; gaussIntParameters *p = gv->params; int i, j, r; double totalX, precX, varX, meanX; totalX = 0.0; totalN = 0; for( r = 0 ; r < rNo ; r++ ){ d = xns->xn[r]->data; dLen = xns->xn[r]->N; for( i = 0 ; i < dLen ; i++ ){ totalX += d->v[i]; } totalN += dLen; } meanX = totalX / (double)totalN; varX = 0.0; for( r = 0 ; r < rNo ; r++ ){ d = xns->xn[r]->data; dLen = xns->xn[r]->N; for( i = 0 ; i < dLen ; i++ ){ varX += pow(d->v[i] - meanX, 2.0); } } varX /= (double)(totalN - 1); precX = 1.0 / varX; p->sumUPi = 0.0; for( i = 0 ; i < sNo ; i++ ){ p->uPiArr[i] = 1.0; p->sumUPi += p->uPiArr[i]; } for( i = 0 ; i < sNo ; i++ ){ p->sumUAArr[i] = 0.0; for( j = 0 ; j < sNo ; j++ ){ if( j == i ){ p->uAMat[i][j] = 5.0; } else { p->uAMat[i][j] = 1.0; } p->sumUAArr[i] += p->uAMat[i][j]; } } // hyper parameter for p( mu(k), lm(k) ) for( i = 0 ; i < sNo ; i++ ){ p->uBt = 1.0; p->uMu = meanX * 2.0 / (double)sNo; p->uA = 1.0; p->uB = p->uA / precX ; } for( r = 0 ; r < rNo ; r++ ){ initialize_indVars_gaussInt( xns->xn[r], gv, ivs->indVars[r] ); } calcStatsVarsG_gaussInt( xns, gv, ivs ); maximizationG_gaussInt( xns, gv, ivs ); } void initialize_indVars_gaussInt( xn, gv, iv ) xnDataSet *xn; globalVars *gv; indVars *iv; { size_t dLen = xn->N; int sNo = gv->sNo; double **gmMat = iv->gmMat; int i; size_t n; double sumPar; for( n = 0 ; n < dLen ; n++ ){ sumPar = 0.0; for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = enoise(1.0) + 1.0; sumPar += gmMat[n][i]; } for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] /= sumPar; } } } xnDataSet *newXnDataSet_gaussInt( filename ) const char *filename; { xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) ); xn->name = (char*)malloc( strlen(filename) + 2 ); strncpy( xn->name, filename, strlen(filename)+1 ); xn->data = (gaussIntData*)malloc( sizeof(gaussIntData) ); gaussIntData *d = (gaussIntData*)xn->data; d->v = NULL; return xn; } void freeXnDataSet_gaussInt( xn ) xnDataSet **xn; { gaussIntData *d = (gaussIntData*)(*xn)->data; free( d->v ); free( (*xn)->data ); free( (*xn)->name ); free( *xn ); *xn = NULL; } double pTilde_z1_gaussInt( i, params ) int i; void *params; { gaussIntParameters *p = (gaussIntParameters*)params; return exp( p->avgLnPi[i] ); } double pTilde_zn_zn1_gaussInt( i, j, params ) int i, j; void *params; { gaussIntParameters *p = (gaussIntParameters*)params; return exp( p->avgLnA[i][j] ); } double pTilde_xn_zn_gaussInt( xnWv, n, i, params ) xnDataSet *xnWv; size_t n; int i; void *params; { gaussIntParameters *p = (gaussIntParameters*)params; gaussIntData *xn = (gaussIntData*)xnWv->data; double val, di = (double)(i+1); val = p->avgLnLm - log(2.0 * M_PI * di); val -= di/p->btMu + p->aLm * pow(xn->v[n] - di * p->mu0, 2.0) / di / p->bLm; return exp(val / 2.0); } void calcStatsVars_gaussInt( xn, gv, iv ) xnDataSet *xn; globalVars *gv; indVars *iv; { gaussIntData *d = (gaussIntData*)xn->data; gaussIntStats *s = (gaussIntStats*)iv->stats; size_t dLen = xn->N; int sNo = gv->sNo; double **gmMat = iv->gmMat, ***xiMat = iv->xiMat; double *Nii = s->Nii, **Nij = s->Nij, *Ni = s->Ni; size_t n; int i, j; s->N0 = (double)xn->N; s->N0i = 1e-10; s->Nx = 1e-10; for( i = 0 ; i < sNo ; i++ ){ Ni[i] = 1e-10; Nii[i] = 1e-10; for( j = 0 ; j < sNo ; j++ ){ Nij[i][j] = 1e-10; } for( n = 0 ; n < dLen ; n++ ){ Ni[i] += gmMat[n][i]; s->Nx += gmMat[n][i] * d->v[n]; for( j = 0 ; j < sNo ; j++ ){ Nii[i] += xiMat[n][i][j]; Nij[i][j] += xiMat[n][i][j]; } } s->N0i += (double)(i+1) * Ni[i]; } } void calcStatsVarsG_gaussInt( xns, gv, ivs ) xnDataBundle *xns; globalVars *gv; indVarBundle *ivs; { gaussIntData *d; gaussIntGlobalStats *gs = (gaussIntGlobalStats*)ivs->stats; int sNo = gv->sNo, rNo = xns->R; double **gmMat, ***xiMat; double *NiiR = gs->NiiR, **NijR = gs->NijR, *NiR = gs->NiR, *z1iR = gs->z1iR; size_t dLen, n; int i, j, r; gs->N0R = 0.0; gs->N0iR = 1e-10; gs->NxR = 1e-10; for( i = 0 ; i < sNo ; i++ ){ NiR[i] = 1e-10; NiiR[i] = 1e-10; for( j = 0 ; j < sNo ; j++ ){ NijR[i][j] = 1e-10; } z1iR[i] = 1e-10; } for( r = 0 ; r < rNo ; r++ ){ d = (gaussIntData*)xns->xn[r]->data; dLen = xns->xn[r]->N; gmMat = ivs->indVars[r]->gmMat; xiMat = ivs->indVars[r]->xiMat; for( i = 0 ; i < sNo ; i++ ){ z1iR[i] += gmMat[0][i]; for( n = 0 ; n < dLen ; n++ ){ NiR[i] += gmMat[n][i]; gs->NxR += gmMat[n][i] * d->v[n]; for( j = 0 ; j < sNo ; j++ ){ NiiR[i] += xiMat[n][i][j]; NijR[i][j] += xiMat[n][i][j]; } } } gs->N0R += (double)xns->xn[r]->N; } for( i = 0 ; i < sNo ; i++ ){ gs->N0iR += (double)(i+1) * NiR[i]; } } void maximization_gaussInt( xn, gv, iv ) xnDataSet *xn; globalVars *gv; indVars *iv; { gaussIntParameters *p = (gaussIntParameters*)gv->params; gaussIntStats *s = (gaussIntStats*)iv->stats; gaussIntData *d = (gaussIntData*)xn->data; size_t dLen = xn->N; int sNo = gv->sNo; double **gmMat = iv->gmMat; double *uPiArr = p->uPiArr, sumUPi = p->sumUPi; double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr; double uBt = p->uBt, uMu = p->uMu, uA = p->uA, uB = p->uB; double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA; double *Nii = s->Nii, **Nij = s->Nij, N0 = s->N0, N0i = s->N0i, Nx = s->Nx; int i, j, m; double bLm = 0.0, di; for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 ); avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 ); for( j = 0 ; j < sNo ; j++ ){ avgA[i][j] = ( uAMat[i][j] + Nij[i][j] ) / ( sumUAArr[i] + Nii[i] ); avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + Nij[i][j] ) - gsl_sf_psi( sumUAArr[i] + Nii[i] ); } di = (double)(i+1); for( m = 0 ; m < dLen ; m++ ){ bLm += gmMat[m][i] * d->v[m] * d->v[m] / di; } } bLm /= 2.0; p->btMu = uBt + N0i; p->mu0 = (uBt * uMu + Nx) / p->btMu; p->aLm = uA + (N0 / 2.0); bLm += uB + (uBt * uMu * uMu / 2.0); bLm -= p->btMu * p->mu0 * p->mu0 / 2.0; p->bLm = bLm; p->avgMu = p->mu0; p->avgLm = p->aLm / p->bLm; p->avgLnLm = gsl_sf_psi( p->aLm ) - log( p->bLm ); } void maximizationG_gaussInt( xns, gv, ivs ) xnDataBundle *xns; globalVars *gv; indVarBundle *ivs; { gaussIntParameters *p = (gaussIntParameters*)gv->params; double *uPiArr = p->uPiArr, sumUPi = p->sumUPi; double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr; double uBt = p->uBt, uMu = p->uMu, uA = p->uA, uB = p->uB; double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA; gaussIntGlobalStats *gs = (gaussIntGlobalStats*)ivs->stats; double *NiiR = gs->NiiR, **NijR = gs->NijR, N0R = gs->N0R, N0iR = gs->N0iR, NxR = gs->NxR; double *z1iR = gs->z1iR, dR = (double)(xns->R), di, bLm = 0.0; int sNo = gv->sNo, rNo = xns->R; int i, j, m, r; for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = ( uPiArr[i] + z1iR[i] ) / ( sumUPi + dR ); avgLnPi[i] = gsl_sf_psi( uPiArr[i] + z1iR[i] ) - gsl_sf_psi( sumUPi + dR ); for( j = 0 ; j < sNo ; j++ ){ avgA[i][j] = ( uAMat[i][j] + NijR[i][j] ) / ( sumUAArr[i] + NiiR[i] ); avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + NijR[i][j] ) - gsl_sf_psi( sumUAArr[i] + NiiR[i] ); } di = (double)(i+1); for( r = 0 ; r < rNo ; r++ ){ size_t dLen = xns->xn[r]->N; gaussIntData *d = (gaussIntData*)xns->xn[r]->data; double **gmMat = ivs->indVars[r]->gmMat; for( m = 0 ; m < dLen ; m++ ){ bLm += gmMat[m][i] * d->v[m] * d->v[m] / di; } } } bLm /= 2.0; p->btMu = uBt + N0iR; p->mu0 = (uBt * uMu + NxR) / p->btMu; p->aLm = uA + N0R / 2.0; bLm += uB + uBt * uMu * uMu / 2.0; bLm -= p->btMu * p->mu0 * p->mu0 / 2.0; p->bLm = bLm; p->avgMu = p->mu0; p->avgLm = p->aLm / p->bLm; p->avgLnLm = gsl_sf_psi( p->aLm ) - log( p->bLm ); } double varLowerBound_gaussInt( xn, gv, iv ) xnDataSet *xn; globalVars *gv; indVars *iv; { gaussIntParameters *p = (gaussIntParameters*)gv->params; size_t dLen = xn->N; int sNo = gv->sNo; double **gmMat = iv->gmMat, *cn = iv->cn; double *uPiArr = p->uPiArr, sumUPi = p->sumUPi; double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr; double uBt = p->uBt, uMu = p->uMu, uA = p->uA, uB = p->uB; double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA; double avgLm = p->avgLm, avgLnLm = p->avgLnLm; double mu0 = p->mu0, btMu = p->btMu, aLm = p->aLm, bLm = p->bLm; gaussIntStats *s = (gaussIntStats*)iv->stats; double *Nii = s->Nii, **Nij = s->Nij; size_t n; int i, j; double lnpPi = gsl_sf_lngamma(sumUPi); double lnpA = 0.0; double lnpMuLm = log(uBt) / 2.0; lnpMuLm -= uBt * (1.0 / btMu + aLm * pow(mu0 - uMu, 2.0) / bLm ) / 2.0; lnpMuLm += - gsl_sf_lngamma(uA) + uA * log(uB); lnpMuLm += (uA - 0.5) * avgLnLm - uB * avgLm; double lnqPi = gsl_sf_lngamma(sumUPi + 1.0); double lnqA = 0.0; double lnqMuLm = (log(btMu) - 1.0) / 2.0 - gsl_sf_lngamma(aLm) + aLm * log(bLm); lnqMuLm += (aLm - 0.5) * avgLnLm - aLm; for( i = 0 ; i < sNo ; i++ ){ lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]); lnqPi += (uPiArr[i]+gmMat[0][i]-1.0) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1.0)); lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]); lnpA += gsl_sf_lngamma(sumUAArr[i]); lnqA += gsl_sf_lngamma(sumUAArr[i] + Nii[i]); for( j = 0 ; j < sNo ; j++ ){ lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]); lnqA += (uAMat[i][j] + Nij[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+Nij[i][j]) - gsl_sf_psi(sumUAArr[i]+Nii[i])); lnqA -= gsl_sf_lngamma( uAMat[i][j] + Nij[i][j] ); } } double lnpX = 0.0; for( n = 0 ; n < dLen ; n++ ){ lnpX += log( cn[n] ); } double val; val = lnpPi + lnpA + lnpMuLm; val -= lnqPi + lnqA + lnqMuLm; val += lnpX; val += log(gsl_sf_fact(sNo)); return val; } double varLowerBoundG_gaussInt( xns, gv, ivs ) xnDataBundle *xns; globalVars *gv; indVarBundle *ivs; { gaussIntParameters *p = (gaussIntParameters*)gv->params; double *uPiArr = p->uPiArr, sumUPi = p->sumUPi; double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr; double uBt = p->uBt, uMu = p->uMu, uA = p->uA, uB = p->uB; double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA; double avgLm = p->avgLm, avgLnLm = p->avgLnLm; double mu0 = p->mu0, btMu = p->btMu, aLm = p->aLm, bLm = p->bLm; gaussIntGlobalStats *gs = (gaussIntGlobalStats*)ivs->stats; double *NiiR = gs->NiiR, **NijR = gs->NijR, *z1iR = gs->z1iR, dR = (double)xns->R; size_t n; int sNo = gv->sNo, rNo = xns->R; int i, j, r; double lnpPi = gsl_sf_lngamma(sumUPi); double lnpA = 0.0; double lnpMuLm = log(uBt) / 2.0; lnpMuLm -= uBt * (1.0 / btMu + aLm * pow(mu0 - uMu, 2.0) / bLm ) / 2.0; lnpMuLm += - gsl_sf_lngamma(uA) + uA * log(uB); lnpMuLm += (uA - 0.5) * avgLnLm - uB * avgLm; double lnqPi = gsl_sf_lngamma(sumUPi + dR); double lnqA = 0.0; double lnqMuLm = (log(btMu) - 1.0) / 2.0 - gsl_sf_lngamma(aLm) + aLm * log(bLm); lnqMuLm += (aLm - 0.5) * avgLnLm - aLm; for( i = 0 ; i < sNo ; i++ ){ lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]); lnqPi += (uPiArr[i]+z1iR[i]-1.0) * (gsl_sf_psi(uPiArr[i]+z1iR[i]) - gsl_sf_psi(sumUPi+dR)); lnqPi -= gsl_sf_lngamma(uPiArr[i] + z1iR[i]); lnpA += gsl_sf_lngamma(sumUAArr[i]); lnqA += gsl_sf_lngamma(sumUAArr[i] + NiiR[i]); for( j = 0 ; j < sNo ; j++ ){ lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]); lnqA += (uAMat[i][j] + NijR[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+NijR[i][j]) - gsl_sf_psi(sumUAArr[i]+NiiR[i])); lnqA -= gsl_sf_lngamma( uAMat[i][j] + NijR[i][j] ); } } double lnpX = 0.0; for( r = 0 ; r < rNo ; r++ ){ size_t dLen = xns->xn[r]->N; for( n = 0 ; n < dLen ; n++ ){ lnpX += log( ivs->indVars[r]->cn[n] ); } } double val; val = lnpPi + lnpA + lnpMuLm; val -= lnqPi + lnqA + lnqMuLm; val += lnpX; val += log(gsl_sf_fact(sNo)); return val; } void reorderParameters_gaussInt( xn, gv, iv ) xnDataSet *xn; globalVars *gv; indVars *iv; { } void reorderParametersG_gaussInt( xns, gv, ivs ) xnDataBundle *xns; globalVars *gv; indVarBundle *ivs; { } void outputGaussIntResults( xn, gv, iv, logFP ) xnDataSet *xn; globalVars *gv; indVars *iv; FILE *logFP; { gaussIntParameters *p = (gaussIntParameters*)gv->params; int sNo = gv->sNo; int i, j; fprintf(logFP, " results: K = %d \n", sNo); fprintf(logFP, " mean: ( %g ) \n", p->avgMu); fprintf(logFP, " lambda: ( %g ) \n", p->avgLm); fprintf(logFP, " pi: ( %g", p->avgPi[0]); for( i = 1 ; i < sNo ; i++ ){ fprintf(logFP, ", %g", p->avgPi[i]); } fprintf(logFP, " ) \n"); fprintf(logFP, " A_matrix: ["); for( i = 0 ; i < sNo ; i++ ){ fprintf(logFP, " ( %g", p->avgA[i][0]); for( j = 1 ; j < sNo ; j++ ) { fprintf(logFP, ", %g", p->avgA[i][j]); } fprintf(logFP, ")"); } fprintf(logFP, " ] \n\n"); char fn[256]; FILE *fp; size_t n; sprintf( fn, "%s.param%03d", xn->name, sNo ); if( (fp = fopen( fn, "w")) != NULL ){ fprintf(fp, "mu, lambda, pi"); for( i = 0 ; i < sNo ; i++ ) { fprintf(fp, ", A%dx", i); } fprintf(fp, "\n"); for( i = 0 ; i < sNo ; i++ ){ fprintf(fp, "%g, %g, %g", (double)(i+1)*p->avgMu, (double)(i+1)*p->avgLm, p->avgPi[i]); for( j = 0 ; j < sNo ; j++ ) { fprintf(fp, ", %g", p->avgA[j][i]); } fprintf(fp, "\n"); } fclose(fp); } sprintf( fn, "%s.Lq%03d", xn->name, sNo ); if( (fp = fopen( fn, "w")) != NULL ){ for( n = 0 ; n < gv->iteration ; n++ ){ fprintf( fp, "%24.20e\n", gv->LqArr[n] ); } fclose(fp); } sprintf( fn, "%s.maxS%03d", xn->name, sNo ); if( (fp = fopen( fn, "w")) != NULL ){ for( n = 0 ; n < xn->N ; n++ ){ fprintf( fp, "%d\n", iv->stateTraj[n] ); } fclose(fp); } } void outputGaussIntResultsG( xns, gv, ivs, logFP ) xnDataBundle *xns; globalVars *gv; indVarBundle *ivs; FILE *logFP; { int sNo = gv->sNo, rNo = xns->R; gaussIntParameters *p = (gaussIntParameters*)gv->params; int i, j, r; fprintf(logFP, " results: K = %d \n", sNo); fprintf(logFP, " mean: ( %g ) \n", p->avgMu); fprintf(logFP, " lambda: ( %g ) \n", p->avgLm); fprintf(logFP, " pi: ( %g", p->avgPi[0]); for( i = 1 ; i < sNo ; i++ ){ fprintf(logFP, ", %g", p->avgPi[i]); } fprintf(logFP, " ) \n"); fprintf(logFP, " A_matrix: ["); for( i = 0 ; i < sNo ; i++ ){ fprintf(logFP, " ( %g", p->avgA[i][0]); for( j = 1 ; j < sNo ; j++ ) { fprintf(logFP, ", %g", p->avgA[i][j]); } fprintf(logFP, ")"); } fprintf(logFP, " ] \n\n"); char fn[256]; FILE *fp; size_t n; sprintf( fn, "%s.param%03d", xns->xn[0]->name, sNo ); if( (fp = fopen( fn, "w")) != NULL ){ fprintf(fp, "mu, lambda, pi"); for( i = 0 ; i < sNo ; i++ ) { fprintf(fp, ", A%dx", i); } fprintf(fp, "\n"); for( i = 0 ; i < sNo ; i++ ){ fprintf(fp, "%g, %g, %g", (double)(i+1)*p->avgMu, (double)(i+1)*p->avgLm, p->avgPi[i]); for( j = 0 ; j < sNo ; j++ ) { fprintf(fp, ", %g", p->avgA[j][i]); } fprintf(fp, "\n"); } fclose(fp); } sprintf( fn, "%s.Lq%03d", xns->xn[0]->name, sNo ); if( (fp = fopen( fn, "w")) != NULL ){ for( n = 0 ; n < gv->iteration ; n++ ){ fprintf( fp, "%24.20e\n", gv->LqArr[n] ); } fclose(fp); } sprintf( fn, "%s.maxS%03d", xns->xn[0]->name, sNo ); int flag = 0; if( (fp = fopen( fn, "w")) != NULL ){ n = 0; do{ flag = 1; for( r = 0 ; r < rNo ; r++ ){ xnDataSet *xn = xns->xn[r]; indVars *iv = ivs->indVars[r]; if( r > 0 ){ fprintf( fp, "," ); } if( n < xn->N ){ fprintf( fp, "%d", iv->stateTraj[n] ); } flag &= (n >= (xn->N - 1)); } fprintf( fp, "\n" ); n++; }while( !flag ); fclose(fp); } } //
{ "alphanum_fraction": 0.4989906832, "avg_line_length": 28.0304678999, "ext": "c", "hexsha": "fcc3a699ba51b21b99e8f726ab5032525bff86f5", "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": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "okamoto-kenji/varBayes-HMM", "max_forks_repo_path": "C/vbHmmGaussIntensity.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "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": "okamoto-kenji/varBayes-HMM", "max_issues_repo_path": "C/vbHmmGaussIntensity.c", "max_line_length": 126, "max_stars_count": 7, "max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "okamoto-kenji/varBayes-HMM", "max_stars_repo_path": "C/vbHmmGaussIntensity.c", "max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z", "max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z", "num_tokens": 9826, "size": 25760 }
/* ieee-utils/fp-gnuc99.c * * Copyright (C) 2003, 2004, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define _GNU_SOURCE 1 #include <math.h> #include <stdio.h> #include <fenv.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_errno.h> int gsl_ieee_set_mode (int precision, int rounding, int exception_mask) { int mode; switch (precision) { case GSL_IEEE_SINGLE_PRECISION: GSL_ERROR ("single precision rounding is not supported by <fenv.h>", GSL_EUNSUP) ; break ; case GSL_IEEE_DOUBLE_PRECISION: GSL_ERROR ("double precision rounding is not supported by <fenv.h>", GSL_EUNSUP) ; break ; case GSL_IEEE_EXTENDED_PRECISION: GSL_ERROR ("extended precision rounding is not supported by <fenv.h>", GSL_EUNSUP) ; break ; } switch (rounding) { case GSL_IEEE_ROUND_TO_NEAREST: #ifdef FE_TONEAREST fesetround (FE_TONEAREST) ; #else GSL_ERROR ("round-to-nearest is not supported by <fenv.h>", GSL_EUNSUP) ; #endif break ; case GSL_IEEE_ROUND_DOWN: #ifdef FE_DOWNWARD fesetround (FE_DOWNWARD) ; #else GSL_ERROR ("round-down is not supported by <fenv.h>", GSL_EUNSUP) ; #endif break ; case GSL_IEEE_ROUND_UP: #ifdef FE_UPWARD fesetround (FE_UPWARD) ; #else GSL_ERROR ("round-up is not supported by <fenv.h>", GSL_EUNSUP) ; #endif break ; case GSL_IEEE_ROUND_TO_ZERO: #ifdef FE_TOWARDZERO fesetround (FE_TOWARDZERO) ; #else GSL_ERROR ("round-toward-zero is not supported by <fenv.h>", GSL_EUNSUP) ; #endif break ; default: #ifdef FE_TONEAREST fesetround (FE_TONEAREST) ; #else GSL_ERROR ("default round-to-nearest mode is not supported by <fenv.h>", GSL_EUNSUP) ; #endif } /* Turn on all the exceptions apart from 'inexact' */ mode = 0; #ifdef FE_INVALID mode |= FE_INVALID; #endif #ifdef FE_DIVBYZERO mode |= FE_DIVBYZERO; #endif #ifdef FE_OVERFLOW mode |= FE_OVERFLOW ; #endif #ifdef FE_UNDERFLOW mode |= FE_UNDERFLOW ; #endif if (exception_mask & GSL_IEEE_MASK_INVALID) { #ifdef FE_INVALID mode &= ~ FE_INVALID ; #else GSL_ERROR ("invalid operation exception not supported by <fenv.h>", GSL_EUNSUP); #endif } if (exception_mask & GSL_IEEE_MASK_DENORMALIZED) { /* do nothing */ } else { GSL_ERROR ("denormalized operand exception not supported by <fenv.h>. " "Use 'mask-denormalized' to work around this.", GSL_EUNSUP) ; } if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO) { #ifdef FE_DIVBYZERO mode &= ~ FE_DIVBYZERO ; #else GSL_ERROR ("division by zero exception not supported by <fenv.h>", GSL_EUNSUP); #endif } if (exception_mask & GSL_IEEE_MASK_OVERFLOW) { #ifdef FE_OVERFLOW mode &= ~ FE_OVERFLOW ; #else GSL_ERROR ("overflow exception not supported by <fenv.h>", GSL_EUNSUP); #endif } if (exception_mask & GSL_IEEE_MASK_UNDERFLOW) { #ifdef FE_UNDERFLOW mode &= ~ FE_UNDERFLOW ; #else GSL_ERROR ("underflow exception not supported by <fenv.h>", GSL_EUNSUP); #endif } if (exception_mask & GSL_IEEE_TRAP_INEXACT) { #ifdef FE_INEXACT mode |= FE_INEXACT ; #else GSL_ERROR ("inexact exception not supported by <fenv.h>", GSL_EUNSUP); #endif } else { #ifdef FE_INEXACT mode &= ~ FE_INEXACT ; #else /* do nothing */ #endif } #if HAVE_DECL_FEENABLEEXCEPT feenableexcept (mode) ; #elif HAVE_DECL_FESETTRAPENABLE fesettrapenable (mode); #else GSL_ERROR ("unknown exception trap method", GSL_EUNSUP) #endif return GSL_SUCCESS ; }
{ "alphanum_fraction": 0.6725, "avg_line_length": 24.043715847, "ext": "c", "hexsha": "70dcbefd91031cc8e01e3b4a5e07e6ca65fc9038", "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-gnuc99.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-gnuc99.c", "max_line_length": 92, "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-gnuc99.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": 1168, "size": 4400 }
/* Modified from SUPOLAR, Copyright (c) Colorado School of Mines, 2011.*/ /* All rights reserved. */ /* SUPOLAR_PS: $Revision: 1.9 $ ; $Date: Sat, 23 Jul 2016 00:10:26 -0700 */ #include <omp.h> #include <stdio.h> #include <gsl/gsl_statistics_float.h> #include "su.h" #include "segy.h" #include "header.h" /*********************** self documentation *****************************/ char *sdoc[] = { " ", " SUPOLAR_PS - POLarization analysis of three-component data ", " - to provide P and S arrivals ", " - Modification of SUPOLAR ", " ", " supolar_PS <stdin [optional parameters] ", " ", " Required parameters: ", " -ntr (number of traces) needs to be specified in the SU file ", " ", " Optional parameters: ", " dt=(from header) time sampling interval in seconds ", " wl=0.1 correlation window length in seconds ", " win=boxcar correlation window shape, choose \"boxcar\", ", " \"hanning\", \"bartlett\", or \"welsh\" ", " file=polar base of output file name(s) ", " rl=1 1 = rectilinearity evaluating 2 eigenvalues, ", " 2, 3 = rectilinearity evaluating 3 eigenvalues ", " rlq=1.0 contrast parameter for rectilinearity ", " dir=1 1 = 3 components of direction of polarization ", " (the only three-component output file) ", " tau=0 1 = global polarization parameter ", " ellip=0 1 = principal, subprincipal, and transverse ", " ellipticities e21, e31, and e32 ", " pln=0 1 = planarity measure ", " f1=0 1 = flatness or oblateness coefficient ", " l1=0 1 = linearity coefficient ", " amp=0 1 = amplitude parameters: instantaneous, ", " quadratic, and eigenresultant ir, qr, and er ", " theta=0 1, 2, 3 = incidence angle of principal axis ", " phi=0 1, 2, 3 = horizontal azimuth of principal axis ", " angle=rad unit of angles theta and phi, choose \"rad\", ", " \"deg\", or \"gon\" ", " all=0 1, 2, 3 = set all output flags to that value ", " verbose=0 1 = echo additional information ", " kwl=5*(1/dt) kurtosis window length, samples ", " ", " Notes: ", " Three adjacent traces are considered as one three-component ", " dataset. ", " Correct calculation of angles theta and phi requires the first of ", " these traces to be the vertical component, followed by the two ", " horizontal components (e.g. Z, N, E, or Z, inline, crossline). ", " Significant signal energy on Z is necessary to resolve the 180 deg ", " ambiguity of phi (options phi=2,3 only). ", " ", " Each calculated polarization attribute is written into its own ", " SU file. These files get the same base name (set with \"file=\") ", " and the parameter flag as an extension (e.g. polar.rl). ", " ", " In case of a tapered correlation window, the window length wl may ", " have to be increased compared to the boxcar case, because of their ", " smaller effective widths (Bartlett, Hanning: 1/2, Welsh: 1/3). ", " ", " Range of values: ", " parameter option interval ", " rl 1, 2 0.0 ... 1.0 (1.0: linear polarization) ", " rl 3 -1.0 ... 1.0 ", " tau, l1 1 0.0 ... 1.0 (1.0: linear polarization) ", " pln, f1 1 0.0 ... 1.0 (1.0: planar polarization) ", " e21, e31, e32 1 0.0 ... 1.0 (0.0: linear polarization) ", " theta 1 -pi/2... pi/2 rad ", " theta 2, 3 0.0 ... pi/2 rad ", " phi 1 -pi/2... pi/2 rad ", " phi 2 -pi ... pi rad (see notes above) ", " phi 3 0.0 ... 2 pi rad (see notes above) ", " ", " ", NULL}; /* * Author: Nils Maercklin, * GeoForschungsZentrum (GFZ) Potsdam, Germany, 1998-2001. * E-mail: nils@gfz-potsdam.de * * * References: * Jurkevics, A., 1988: Polarization analysis of three-component * array data. Bulletin of the Seismological Society of America, * vol. 78, no. 5. * Kanasewich, E. R., 1981: Time Sequence Analysis in Geophysics. * The University of Alberta Press. * Kanasewich, E. R., 1990: Seismic Noise Attenuation. * Handbook of Geophysical Exploration, Pergamon Press, Oxford. * Meyer, J. H. 1988: First Comparative Results of Integral and * Instantaneous Polarization Attributes for Multicomponent Seismic * Data. Institut Francais du Petrole. * Press, W. H., Teukolsky, S. A., Vetterling, W. T., and Flannery, B. P. * 1996: Numerical Recipes in C - The Art of Scientific Computing. * Cambridge University Press, Cambridge. * Samson, J. C., 1973: Description of the Polarisation States of Vector * Processes: Application to ULF Electromagnetic Fields. * Geophysical Journal vol. 34, p. 403-419. * Sheriff, R. E., 1991: Encyclopedic Dictionary of Exploration * Geophysics. 3rd ed., Society of Exploration Geophysicists, Tulsa. * * Trace header fields accessed: ns, dt * Trace header fields modified: none */ /**************** end self doc *******************************************/ /* prototypes of functions used internally */ float calc_ellip(float *d, int d1, int d2); float calc_er(float *d); float calc_f1(float *d); float calc_l1(float *d); float calc_phi(float **v, int opt); float calc_plan(float *d); float calc_rl(float d[], float q, int opt); float calc_tau(float *d); float calc_theta(float **v, int opt); float covar(float *data1, float *data2, int istart, int iwl, float *w); float calc_pfilt(float rl, float theta); float calc_sfilt(float rl, float theta); float kurtosiswindow(float *data, float *data_kwl, int it, int kwl, int nt); void ampparams(float **indata, float *data_ir, float *data_qr, int nt, int iwl); void calc_dir(float **data3c_dir, float **v, int it); void calc_window(float *w, int iwl, int iwin); void fputdata(FILE *fileptr, FILE *headerptr, float outdata[], int nt); void fputdata3c(FILE *fileptr, FILE *headerptr, float **outdata3c, int nt); /* window shape identifiers */ #define WBOXCAR 0 #define WBARTLETT 1 #define WHANNING 2 #define WWELSH 3 segy tr; /* SEG-Y record (trace and header) */ int main(int argc, char **argv) { /* output file pointers */ FILE *rlfp=NULL, *taufp=NULL, *e21fp=NULL; FILE *e31fp=NULL, *e32fp=NULL, *plnfp=NULL; FILE *f1fp=NULL, *l1fp=NULL; FILE *thetafp=NULL, *phifp=NULL, *dirfp=NULL; FILE *erfp=NULL, *irfp=NULL, *qrfp=NULL; FILE *headerfp=NULL, *pfiltfp=NULL, *sfiltfp=NULL; FILE *nfiltfp=NULL, *efiltfp=NULL; // FILE *pkur=NULL, *skur=NULL; /* temporary file for trace headers */ /* (one 3C station only) */ char *file=NULL; /* base of output file name(s) */ char *fname=NULL; /* complete output file name */ char *angle=NULL; /* unit used for angles theta and phi */ char *win=NULL; /* shape of used time window */ float fangle=0.0; /* unit conversion factor applied to angles theta and phi */ int iwin=0; /* time window shape identifier */ /* flags (see selfdoc) */ int rl,theta,phi,tau,ellip,pln,f1,l1,dir,amp,verbose,all; int i,j,icomp; /* indices for components (in loops) */ int it; /* index for time sample in main loop */ int iwl; /* correlation window length in samples */ int nstat; /* number of 3-component datasets */ int nt; /* number of time samples in one trace */ // int kwl; /* kurtosis window length in seconds */ float **data3c; /* three-component data ([1..3][0..nt-1]) */ float **a; /* covariance matrix (a[1..3][1..3]) */ float **v; /* eigenvectors of covariance matrix (v[1..3][1..3]) */ float *d; /* the corresponding eigenvalues (d[1..3]) */ float *w; /* time window weights for correlation window */ float dt; /* sampling interval in seconds */ float rlq; /* contrast factor of rectilinearity */ float wl; /* correlation window length in seconds */ float *data_e21=NULL; /* main ellipticity */ float *data_e31=NULL; /* second ellipticity */ float *data_e32=NULL; /* transverse ellipticity */ float *data_er=NULL; /* eigenresultant */ float *data_f1=NULL; /* flatness coefficient */ float *data_ir=NULL; /* instantaneous resultant */ float *data_l1=NULL; /* linearity coefficient */ float *data_phi=NULL; /* horizontal azimuth phi */ float *data_pln=NULL; /* planarity */ float *data_qr=NULL; /* quadratic resultant */ float *data_rl=NULL; /* rectilinearity factor */ float *data_tau=NULL; /* polarization parameter tau */ float *data_theta=NULL; /* inclination angle theta */ float *data_pfilt=NULL; /* P (vertical) polarization filter */ float *data_sfilt=NULL; /* S (horizontal) polarization filter */ float *data_zfilt=NULL; /* Z Filtered Trace */ float *data_nfilt=NULL; /* N Filtered Trace */ float *data_efilt=NULL; /* E Filtered Trace */ // float *data_kwl=NULL; /* Data for Kurtosis Window */ // float *data_pkur=NULL; /* Kurtosis detector for P */ // float *data_skur=NULL; /* Kurtosis detector for S */ float **data3c_dir=NULL; /* 3 components of direction of polarization ([1..3][0..nt-1]) */ /* initialize */ initargs(argc, argv); requestdoc(1); /* get info from first trace */ if(!gettr(&tr)) err("can't get first trace"); nt = tr.ns; /* get parameters ... */ if (!getparstring("file", &file)) file="polar"; if (!getparstring("angle", &angle)) angle="rad"; if (!getparstring("win", &win)) win="boxcar"; if (!getparfloat("wl", &wl)) wl = 0.1; if (!getparfloat("dt", &dt)) dt = ((double) tr.dt)/1000000.0; if (!getparfloat("rlq", &rlq)) rlq = 1.0; if (!getparint("verbose", &verbose)) verbose = 0; // if (!getparint("kwl", &kwl)) kwl = 5 * ((int) 1/dt); /* ... and output flags */ if (!getparint("all", &all)) all = 0; if (!getparint("rl", &rl)) rl = (all) ? all : 1; if (!getparint("dir", &dir)) dir = (all) ? 1 : 1; if (!getparint("theta", &theta)) theta = (all) ? all : 0; if (!getparint("phi", &phi)) phi = (all) ? all : 0; if (!getparint("tau", &tau)) tau = (all) ? 1 : 0; if (!getparint("ellip", &ellip)) ellip = (all) ? 1 : 0; if (!getparint("pln", &pln)) pln = (all) ? 1 : 0; if (!getparint("f1", &f1)) f1 = (all) ? 1 : 0; if (!getparint("l1", &l1)) l1 = (all) ? 1 : 0; if (!getparint("amp", &amp)) amp = (all) ? 1 : 0; checkpars(); /* get time window shape */ if (STREQ(win, "boxcar")) iwin=WBOXCAR; else if (STREQ(win, "bartlett")) iwin=WBARTLETT; else if (STREQ(win, "hanning")) iwin=WHANNING; else if (STREQ(win, "welsh")) iwin=WWELSH; else err("unknown win=%s", win); /* get unit conversion factor for angles */ if (STREQ(angle, "rad")) fangle=1.0; else if (STREQ(angle, "deg")) fangle=180.0/PI; else if (STREQ(angle, "gon")) fangle=200.0/PI; else err("unknown angle=%s", angle); /* convert seconds to samples */ if (!dt) { dt = 0.004; warn("dt not set, assuming dt=0.004"); } iwl = NINT(wl/dt); /* data validation */ if (iwl<1) err("wl=%g must be positive", wl); if (iwl>nt) err("wl=%g too long for trace", wl); if (!strlen(file)) err("file= not set and default overridden"); /* echo some information */ if (verbose && (theta || phi)) warn("computing angles in %s", angle); if (verbose) warn("%s window length = %d samples\n", win, iwl); if (rl && theta) warn("computing filtered phase"); /* open temporary file for trace headers */ headerfp = etmpfile(); /* set filenames and open files */ fname = malloc( strlen(file)+7 ); sprintf(fname, "%s.rl", file); if (rl) rlfp = efopen(fname, "w"); sprintf(fname, "%s.theta", file); if (theta) thetafp = efopen(fname, "w"); sprintf(fname, "%s.phi", file); if (phi) phifp = efopen(fname, "w"); sprintf(fname, "%s.tau", file); if (tau) taufp = efopen(fname, "w"); sprintf(fname, "%s.e21", file); if (ellip) e21fp = efopen(fname, "w"); sprintf(fname, "%s.e31", file); if (ellip) e31fp = efopen(fname, "w"); sprintf(fname, "%s.e32", file); if (ellip) e32fp = efopen(fname, "w"); sprintf(fname, "%s.pln", file); if (pln) plnfp = efopen(fname, "w"); sprintf(fname, "%s.f1", file); if (f1) f1fp = efopen(fname, "w"); sprintf(fname, "%s.l1", file); if (l1) l1fp = efopen(fname, "w"); sprintf(fname, "%s.dir", file); if (dir) dirfp = efopen(fname, "w"); sprintf(fname, "%s.er", file); if (amp) erfp = efopen(fname, "w"); sprintf(fname, "%s.ir", file); if (amp) irfp = efopen(fname, "w"); sprintf(fname, "%s.qr", file); if (amp) qrfp = efopen(fname, "w"); sprintf(fname, "%s.pfilt", file); if (rl && theta) pfiltfp = efopen(fname, "w"); sprintf(fname, "%s.sfilt", file); if (rl && theta) sfiltfp = efopen(fname, "w"); sprintf(fname, "%s.nfilt", file); if (rl && theta) nfiltfp = efopen(fname, "w"); sprintf(fname, "%s.efilt", file); if (rl && theta) efiltfp = efopen(fname, "w"); // sprintf(fname, "%s.pkur", file); if (rl && theta) pkur = efopen(fname, "w"); // sprintf(fname, "%s.skur", file); if (rl && theta) skur = efopen(fname, "w"); free(fname); /* allocate space for input data and analysis matrices */ /* index ranges used here: data3c[1..3][0..nt-1], */ /* a[1..3][1..3], v[1..3][1..3], d[1..3] */ data3c = ealloc2float(nt,3); data3c-=1; a = ealloc2float(3,3); a[0]-=1; a-=1; v = ealloc2float(3,3); v[0]-=1; v-=1; d = ealloc1float(3); d-=1; /* calculate time window weights */ w = ealloc1float(iwl); memset((void *) w, 0, iwl*FSIZE); calc_window(w, iwl, iwin); /* allocate and zero out space for output data */ if (rl) { data_rl = ealloc1float(nt); memset((void *) data_rl, 0, nt*FSIZE); } if (theta) { data_theta = ealloc1float(nt); memset((void *) data_theta, 0, nt*FSIZE); } if (phi) { data_phi = ealloc1float(nt); memset((void *) data_phi, 0, nt*FSIZE); } if (tau) { data_tau = ealloc1float(nt); memset((void *) data_tau, 0, nt*FSIZE); } if (ellip) { data_e21 = ealloc1float(nt); data_e31 = ealloc1float(nt); data_e32 = ealloc1float(nt); memset((void *) data_e21, 0, nt*FSIZE); memset((void *) data_e31, 0, nt*FSIZE); memset((void *) data_e32, 0, nt*FSIZE); } if (pln) { data_pln = ealloc1float(nt); memset((void *) data_pln, 0, nt*FSIZE); } if (f1) { data_f1 = ealloc1float(nt); memset((void *) data_f1, 0, nt*FSIZE); } if (l1) { data_l1 = ealloc1float(nt); memset((void *) data_l1, 0, nt*FSIZE); } if (amp) { data_er = ealloc1float(nt); data_ir = ealloc1float(nt); data_qr = ealloc1float(nt); memset((void *) data_er, 0, nt*FSIZE); memset((void *) data_ir, 0, nt*FSIZE); memset((void *) data_qr, 0, nt*FSIZE); } if (dir) { data3c_dir = ealloc2float(nt,3); data3c_dir-=1; for (i=1;i<=3;i++) memset((void *) data3c_dir[i], 0, nt*FSIZE); } if (rl && theta) { data_pfilt = ealloc1float(nt); memset((void *) data_pfilt, 0, nt*FSIZE); data_sfilt = ealloc1float(nt); memset((void *) data_pfilt, 0, nt*FSIZE); /* data_3Cfilt = ealloc2float(nt,3); for (i=1;i<=3;i++) memset((void *) data_3Cfilt[i], 0, nt*FSIZE); */ data_zfilt = ealloc1float(nt); data_nfilt = ealloc1float(nt); data_efilt = ealloc1float(nt); memset((void *) data_zfilt, 0, nt*FSIZE); memset((void *) data_nfilt, 0, nt*FSIZE); memset((void *) data_efilt, 0, nt*FSIZE); // data_pkur = ealloc1float(nt); // data_skur = ealloc1float(nt); // memset((void *) data_pkur, 0, nt*FSIZE); // memset((void *) data_skur, 0, nt*FSIZE); /* Allocate data for kurtosis window arrays */ // data_kwl = ealloc1float(iwl); // memset((void *) data_kwl, 0, kwl*FSIZE); } /* ************************ BEGIN CALCULATION ******************************* */ /* loop over traces */ icomp=0; nstat=0; // Need to convert this do while loop into a for loop so as to be easier // to parallelize warn("Trace Start Time: %d %d %d %d %d", tr.year, tr.day, tr.hour, tr.minute, tr.sec); do { /* store trace header in temporary file and read data */ efwrite(&tr, HDRBYTES, 1, headerfp); icomp++; memcpy((void *)data3c[icomp], (const void *) tr.data, nt*FSIZE); /* process 3-component dataset */ if (icomp==3) { erewind(headerfp); icomp = 0; nstat++; if (verbose) fprintf(stderr,"%s: analyzing station %d \r",argv[0], nstat); /* start loop over samples */ for (it=iwl/2;it<nt-iwl/2;it++) { //warn("Sample %d", it); /* covariance matrix */ for (i=1;i<=3;i++) { for (j=i;j<=3;j++) { a[i][j]=a[j][i]=covar(data3c[i], data3c[j], it-iwl/2, iwl, w); } } /* compute eigenvalues and vectors */ eig_jacobi(a,d,v,3); sort_eigenvalues(d,v,3); /* polarization parameters */ if (rl) data_rl[it]=calc_rl(d,rlq,rl); if (theta) data_theta[it]=calc_theta(v, theta) * fangle; if (phi) data_phi[it]=calc_phi(v, phi) * fangle; if (tau) data_tau[it]=calc_tau(d); if (ellip) { data_e21[it]=calc_ellip(d,2,1); data_e31[it]=calc_ellip(d,3,1); data_e32[it]=calc_ellip(d,3,2); } if (pln) data_pln[it]=calc_plan(d); if (f1) data_f1[it]=calc_f1(d); if (l1) data_l1[it]=calc_l1(d); if (amp) data_er[it]=calc_er(d); if (dir) calc_dir(data3c_dir,v,it); if (rl && theta) { data_zfilt[it] = data3c[1][it] * calc_pfilt(rl, theta); data_nfilt[it] = data3c[2][it] * calc_sfilt(rl, theta); data_efilt[it] = data3c[3][it] * calc_sfilt(rl, theta); data_pfilt[it] = data_zfilt[it]; data_sfilt[it] = (data_nfilt[it] + data_efilt[it]) / 2; // data_pkur[it] = kurtosiswindow(data_pfilt,data_kwl,it - kwl/2,kwl,nt); // data_skur[it] = kurtosiswindow(data_sfilt,data_kwl,it - kwl/2,kwl,nt); } } /* end loop over samples */ /* compute amplitude parameters */ if (amp) ampparams(data3c, data_ir, data_qr, nt, iwl); /* *************************** END CALCULATION ****************************** */ /* ***************************** BEGIN WRITE ******************************** */ /* write polarization attributes to files */ if (rl) fputdata(rlfp, headerfp, data_rl, nt); if (theta) fputdata(thetafp, headerfp, data_theta, nt); if (phi) fputdata(phifp, headerfp, data_phi, nt); if (tau) fputdata(taufp, headerfp, data_tau, nt); if (ellip) { fputdata(e21fp, headerfp, data_e21, nt); fputdata(e31fp, headerfp, data_e31, nt); fputdata(e32fp, headerfp, data_e32, nt); } if (pln) fputdata(plnfp, headerfp, data_pln, nt); if (f1) fputdata(f1fp, headerfp, data_f1, nt); if (l1) fputdata(l1fp, headerfp, data_l1, nt); if (amp) { fputdata(erfp, headerfp, data_er, nt); fputdata(irfp, headerfp, data_ir, nt); fputdata(qrfp, headerfp, data_qr, nt); } if (dir) fputdata3c(dirfp, headerfp, data3c_dir, nt); if (rl && theta) { fputdata(pfiltfp, headerfp, data_pfilt, nt); fputdata(sfiltfp, headerfp, data_sfilt, nt); fputdata(nfiltfp, headerfp, data_nfilt, nt); fputdata(efiltfp, headerfp, data_efilt, nt); // fputdata(pkur, headerfp, data_pkur, nt); // fputdata(skur, headerfp, data_skur, nt); } /* ****************************** END WRITE ********************************* */ } /* end of processing three-component dataset */ } while (gettr(&tr)); /* end loop over traces */ if (verbose) { fprintf(stderr,"\n"); if (icomp) warn("last %d trace(s) skipped", icomp); } /* close files */ efclose(headerfp); if (rl) efclose(rlfp); if (theta) efclose(thetafp); if (phi) efclose(phifp); if (tau) efclose(taufp); if (ellip) { efclose(e21fp); efclose(e31fp); efclose(e32fp); } if (pln) efclose(plnfp); if (f1) efclose(f1fp); if (l1) efclose(l1fp); if (amp) { efclose(erfp); efclose(irfp); efclose(qrfp); } if (dir) efclose(dirfp); if (rl && theta) { efclose(pfiltfp); efclose(sfiltfp); // efclose(pkur); // efclose(skur); } return(CWP_Exit()); } /**********************************************************************/ /* Functions used internally */ /**********************************************************************/ /* calculate time window weights for a smooth time window, */ /* after Sheriff, 1991, p. 335; tapered windows are suggested by */ /* Jurkevics, 1988 */ void calc_window(float *w, int iwl, int iwin) { int i,j; /* loop indices within window */ float m; /* half of time window (iwl/2) */ m = (float) iwl/2; switch (iwin) { case WBOXCAR : for (i=-iwl/2,j=0;i<iwl/2;i++,j++) { w[j] = 1.0; } if (j<iwl) w[iwl-1] = w[0]; break; case WBARTLETT : for (i=-iwl/2,j=0;i<iwl/2;i++,j++) { w[j] = 1.0 - (fabs((float) i) / m); } if (j<iwl) w[iwl-1] = w[0]; break; case WHANNING : for (i=-iwl/2,j=0;i<iwl/2;i++,j++) { w[j] = 0.5 + 0.5*cos(PI*fabs((float) i) / m); } if (j<iwl) w[iwl-1] = w[0]; break; case WWELSH : for (i=-iwl/2,j=0;i<iwl/2;i++,j++) { w[j] = fabs( fabs((float) i) / m - 1.0); w[j] *= w[j]; } if (j<iwl) w[iwl-1] = w[0]; break; } } /* covariance of two time sequences *data1 and *data2, */ /* calculated in a window of length iwl, */ /* weighted with factors *w and starting at index istart */ float covar(float *data1, float *data2, int istart, int iwl, float *w) { register int i, j; float cov=0.0; float mean1=0.0; float mean2=0.0; for (i=istart,j=0;i<(istart+iwl);i++,j++) { mean1 += data1[i] * w[j]; mean2 += data2[i] * w[j]; } mean1 = mean1 / (float) iwl; mean2 = mean2 / (float) iwl; for (i=istart,j=0;i<(istart+iwl);i++,j++) { /* modified by Mega G. Baitoff 6 May 2015 */ /* cov += (data1[i]-mean1) * (data2[i]-mean2) * w[j]; */ cov += (data1[i] * w[j] - mean1) * (data2[i] * w[j] - mean2); } cov = cov / (float) iwl; return cov; } float kurtosiswindow(float *data, float *data_kwl, int it, int kwl, int nt) { int i, j; for (i=it, j=0; i<(it+kwl); i++, j++) { data_kwl[j] = data[i]; } return gsl_stats_float_kurtosis(data_kwl,1,kwl); } /**********************************************************************/ /* Functions defining polarization attributes and angles */ /**********************************************************************/ /* rectilinearity factor rl (3 different definitions) */ float calc_rl(float *d, float rlq, int opt) { float rl; if (d[1]!=0.0) { switch (opt) { default: /* case 1: */ /* rl definition after Kanasewich, 1981 */ rl = 1 - pow(fabs(d[2]/d[1]), rlq); break; case 2: /* rl definition after Jurkevics, 1988 */ /* case used by Z. Ross et. al., 2014 */ rl = 1 - pow( 0.5*(fabs(d[2]/d[1]) + fabs(d[3]/d[1]) ), rlq); break; case 3: /* rl definition after Meyer, 1988 */ rl = 1 - pow(fabs(d[2]/d[1]) + fabs(d[3]/d[1]), rlq); break; } return rl; } else { return 0.0; } } /* vertical (incidence) angle theta (different definitions) */ /* assumes a right handed coordinate system starting */ /* with the vertical component Z (Z=1, N,R=2, E,T=3) */ float calc_theta(float **v, int opt) { float theta, horiz; switch (opt) { default: /* case 1: */ /* definition after Kanasewich, 1981 */ /* interval -pi/2 <= theta <= pi/2 */ if (v[1][1]) { horiz = sqrt( v[2][1]*v[2][1] + v[3][1]*v[3][1] ); theta = atan( horiz / v[1][1] ); } else { theta = 0.0; } break; case 2: case 3: /* definition after Jurkevics, 1988 */ /* interval 0.0 <= theta <= pi/2 */ /* case used by Z. Ross et. al., 2014 */ theta = acos( fabs(v[1][1]) ); break; } return theta; } /* horizontal azimuth phi (different definitions) */ /* assumes a right handed coordinate system starting */ /* with the vertical component Z (Z=1, N,R=2, E,T=3) */ /* Note: The SIGN function is introduced to resolve */ /* the 180 deg ambiguity by taking the positive */ /* vertical component of v[1][1] (Jurkevics, 1988). */ #define VSIGN ( (v[1][1]<0.0) ? -1.0 : 1.0 ) float calc_phi(float **v, int opt) { float phi; switch (opt) { default: /* case 1: */ /* definition after Kanasewich, 1981 */ /* interval -pi/2 <= phi <= pi/2 */ if (v[1][2]) { phi = atan( v[3][1] / v[2][1] ); } else { phi = (v[3][1]>0.0) ? 0.5*PI : -0.5*PI; } break; case 2: case 3: /* definitions after Jurkevics, 1988 */ /* interval -pi <= phi <= pi */ if (v[2][1]) { phi = atan2( v[3][1]*VSIGN, v[2][1]*VSIGN); } else { phi = (v[3][1]>0.0) ? 0.5*PI*VSIGN : -0.5*PI*VSIGN; } /* interval 0.0 <= phi <= 2*pi */ if (phi<0.0 && opt==3) phi += 2.0*PI; break; } return phi; } #undef VSIGN /* global polarization parameter tau (Samson, 1973) */ float calc_tau(float *d) { float x1, x2, x3, x4, tau; if (d[1]) { x1 = pow(( 1 - fabs(d[2]/d[1])), 2.); x2 = pow(( 1 - fabs(d[3]/d[1])), 2.); x3 = pow(( fabs(d[2]/d[1]) - fabs(d[3]/d[1]) ), 2.); x4 = pow(( 1 + fabs(d[2]/d[1]) + fabs(d[3]/d[1])), 2.); tau = sqrt( (x1+x2+x3) / (2*x4) ); return tau; } else return 0.0; } /* ellipticities e_ik */ float calc_ellip(float *d, int d1, int d2) { float ellip; if (d[d2]) { ellip = sqrt( fabs(d[d1]/d[d2]) ); return ellip; } else return 0.0; } /* planarity after Jurkevics, 1988 */ float calc_plan(float *d) { float pln; if (d[1]+d[2]) { pln = 1.0 - 2.0*d[3] / (d[1] + d[2]); return pln; } else return 0.0; } /* flatness coefficient f1 after Benhama et. al, 1988 */ float calc_f1(float *d) { float f1,x1,x2; x1 = 3.0 * calc_ellip(d,3,1); x2 = 1.0 + calc_ellip(d,2,1) + calc_ellip(d,3,1); f1 = 1.0 - x1 / x2; return f1; } /* linearity coefficient l1 */ float calc_l1(float *d) { float l1,x1,x2; x1 = 3. * ( calc_ellip(d,2,1) + calc_ellip(d,3,1) ); x2 = 2. * ( 1 + calc_ellip(d,2,1) + calc_ellip(d,3,1)); l1 = 1. - x1 / x2; return l1; } /* direction cosines or directivity functions (3 components) */ void calc_dir(float **data3c_dir, float **v, int it) { int i; for (i=1;i<=3;i++) { data3c_dir[i][it]=v[i][1]; } } /* amplitude parameters */ /* eigenresultant */ float calc_er(float *d) { float er; er = sqrt(fabs(d[1])); return er; } /* instantaneous and quadratic resultant (Meyer, 1988) */ void ampparams(float **indata, float *data_ir, float *data_qr, int nt, int iwl) { int i,it; float sqrsum; for (it=0;it<nt;it++) { /* instantaneous resultant */ data_ir[it] = sqrt(indata[1][it]*indata[1][it]+ \ indata[2][it]*indata[2][it]+indata[3][it]*indata[3][it]); /* quadratic resultant */ if ( (it >= iwl/2) && (it < nt-iwl/2) ) { sqrsum=0.0; for (i=it-iwl/2;i<(it+iwl);i++) { sqrsum += indata[1][i]*indata[1][i]+ \ indata[2][i]*indata[2][i]+indata[3][i]*indata[3][i]; } data_qr[it] = sqrsum / (float) iwl; } } } /* P, S detection parameters */ /* P-Wave energy filter */ float calc_pfilt(float rl, float theta) { float pfilt; pfilt = rl*cos(theta); return pfilt; } /* S-Wave energy filter */ float calc_sfilt(float rl, float theta) { float sfilt; sfilt = rl * (1 - cos(theta)); return sfilt; } /**********************************************************************/ /* Functions for data output */ /**********************************************************************/ /* write one-component data into file */ void fputdata(FILE *fileptr, FILE *headerptr, float *outdata, int nt) { efread(&tr, 1, HDRBYTES, headerptr); erewind(headerptr); memcpy((void *)tr.data, (const void *) outdata, nt*FSIZE); fputtr(fileptr, &tr); } /* write three-component data into file */ void fputdata3c(FILE *fileptr, FILE *headerptr, float **outdata3c, int nt) { int i; for(i=1;i<=3;i++) { efread(&tr, 1, HDRBYTES, headerptr); memcpy((void *)tr.data, (const void *) outdata3c[i], nt*FSIZE); fputtr(fileptr, &tr); } erewind(headerptr); } /* END OF FILE */
{ "alphanum_fraction": 0.4851556193, "avg_line_length": 37.3709497207, "ext": "c", "hexsha": "3865f4f95a338fd2a51c087318adc3e9e9a667bb", "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": "25499b24352fe2ee8b1cba3d44f078723093055c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "captainobvious62/3CPolar", "max_forks_repo_path": "supolar_PS.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "25499b24352fe2ee8b1cba3d44f078723093055c", "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": "captainobvious62/3CPolar", "max_issues_repo_path": "supolar_PS.c", "max_line_length": 106, "max_stars_count": null, "max_stars_repo_head_hexsha": "25499b24352fe2ee8b1cba3d44f078723093055c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "captainobvious62/3CPolar", "max_stars_repo_path": "supolar_PS.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 9528, "size": 33447 }
#include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "cblas.h" #include "error_cblas_l3.h" void cblas_ssymm (const enum CBLAS_ORDER Order, const enum CBLAS_SIDE Side, const enum CBLAS_UPLO Uplo, const int M, const int N, const float alpha, const float *A, const int lda, const float *B, const int ldb, const float beta, float *C, const int ldc) { #define BASE float #include "source_symm_r.h" #undef BASE }
{ "alphanum_fraction": 0.6864035088, "avg_line_length": 28.5, "ext": "c", "hexsha": "79e05e655b64d7da21ba9182a1aacd77fe009f32", "lang": "C", "max_forks_count": 173, "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_path": "gsl-an/cblas/ssymm.c", "max_issues_count": 208, "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_path": "gsl-an/cblas/ssymm.c", "max_line_length": 78, "max_stars_count": 460, "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": [ "Net-SNMP", "Xnet" ], "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_path": "gsl-an/cblas/ssymm.c", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "num_tokens": 130, "size": 456 }
static char help[] = "Compute ln 2 in serial with PETSc, using random\n" "permutation of sum order. Shows that floating-point arithmetic is not\n" "associative.\n\n"; #include <petsc.h> #include <time.h> int main(int argc, char **args) { PetscErrorCode ierr; PetscMPIInt size; PetscInt i, j, n=10; PetscReal v, tmp, *a, sum; PetscRandom r; PetscInitialize(&argc,&args,NULL,help); ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size); CHKERRQ(ierr); if (size > 1) { SETERRQ(PETSC_COMM_SELF,1,"lntwo only works in serial\n"); } ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"","options for lntwo",""); CHKERRQ(ierr); ierr = PetscOptionsInt("-n","number of terms in sum", "lntwo.c",n,&n,NULL); CHKERRQ(ierr); ierr = PetscOptionsEnd(); CHKERRQ(ierr); ierr = PetscRandomCreate(PETSC_COMM_WORLD,&r); CHKERRQ(ierr); ierr = PetscRandomSetType(r,PETSCRAND48); CHKERRQ(ierr); ierr = PetscRandomSetSeed(r,(int)time(NULL)); CHKERRQ(ierr); ierr = PetscRandomSeed(r); CHKERRQ(ierr); // fill array with the terms (-1)^i / (i+1) for i=0 .. n ierr = PetscMalloc1(n,&a); CHKERRQ(ierr); for (i=0; i<n; i++) { a[i] = pow(-1.0,(double)i) / (double)(i+1); } // shuffle the terms for (i=n-1; i>0; i--) { ierr = PetscRandomGetValueReal(r,&v); CHKERRQ(ierr); j = (int)floor(i*v); tmp = a[i]; a[i] = a[j]; a[j] = tmp; } // sum the terms sum = 0.0; for (i=0; i<n; i++) { sum += a[i]; } // print the result ierr = PetscPrintf(PETSC_COMM_WORLD,"ln 2 is approximately %18.16f\n",sum); CHKERRQ(ierr); PetscRandomDestroy(&r); PetscFree(a); return PetscFinalize(); }
{ "alphanum_fraction": 0.6140247496, "avg_line_length": 28.2833333333, "ext": "c", "hexsha": "bb9c8524e1c7a5b94aee03c402c0a18970bff351", "lang": "C", "max_forks_count": 46, "max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z", "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_path": "c/ch8/solns/lntwo.c", "max_issues_count": 52, "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_path": "c/ch8/solns/lntwo.c", "max_line_length": 92, "max_stars_count": 115, "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_path": "c/ch8/solns/lntwo.c", "max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z", "num_tokens": 536, "size": 1697 }
/* interpolation/interp2d.c * * Copyright 2012 David Zaslavsky * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_interp2d.h> /** * Triggers a GSL error if the argument is not equal to GSL_SUCCESS. * If the argument is GSL_SUCCESS, this does nothing. */ #define DISCARD_STATUS(s) if ((s) != GSL_SUCCESS) { GSL_ERROR_VAL("interpolation error", (s), GSL_NAN); } #define IDX2D(i, j, w) ((j) * ((w)->xsize) + (i)) gsl_interp2d * gsl_interp2d_alloc(const gsl_interp2d_type * T, const size_t xsize, const size_t ysize) { gsl_interp2d * interp; if (xsize < T->min_size || ysize < T->min_size) { GSL_ERROR_NULL ("insufficient number of points for interpolation type", GSL_EINVAL); } interp = (gsl_interp2d *) calloc(1, sizeof(gsl_interp2d)); if (interp == NULL) { GSL_ERROR_NULL ("failed to allocate space for gsl_interp2d struct", GSL_ENOMEM); } interp->type = T; interp->xsize = xsize; interp->ysize = ysize; if (interp->type->alloc == NULL) { interp->state = NULL; return interp; } interp->state = interp->type->alloc(xsize, ysize); if (interp->state == NULL) { free(interp); GSL_ERROR_NULL ("failed to allocate space for gsl_interp2d state", GSL_ENOMEM); } return interp; } /* gsl_interp2d_alloc() */ void gsl_interp2d_free (gsl_interp2d * interp) { RETURN_IF_NULL(interp); if (interp->type->free) interp->type->free(interp->state); free(interp); } /* gsl_interp2d_free() */ int gsl_interp2d_init (gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const size_t xsize, const size_t ysize) { size_t i; if (xsize != interp->xsize || ysize != interp->ysize) { GSL_ERROR("data must match size of interpolation object", GSL_EINVAL); } for (i = 1; i < xsize; i++) { if (xarr[i-1] >= xarr[i]) { GSL_ERROR("x values must be strictly increasing", GSL_EINVAL); } } for (i = 1; i < ysize; i++) { if (yarr[i-1] >= yarr[i]) { GSL_ERROR("y values must be strictly increasing", GSL_EINVAL); } } interp->xmin = xarr[0]; interp->xmax = xarr[xsize - 1]; interp->ymin = yarr[0]; interp->ymax = yarr[ysize - 1]; { int status = interp->type->init(interp->state, xarr, yarr, zarr, xsize, ysize); return status; } } /* gsl_interp2d_init() */ /* * A wrapper function that checks boundary conditions, calls an evaluator * which implements the actual calculation of the function value or * derivative etc., and checks the return status. */ static int interp2d_eval(int (*evaluator)(const void *, const double xa[], const double ya[], const double za[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel *, gsl_interp_accel *, double * z), const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * result) { if (x < interp->xmin || x > interp->xmax) { GSL_ERROR ("interpolation x value out of range", GSL_EDOM); } else if (y < interp->ymin || y > interp->ymax) { GSL_ERROR ("interpolation y value out of range", GSL_EDOM); } return evaluator(interp->state, xarr, yarr, zarr, interp->xsize, interp->ysize, x, y, xa, ya, result); } /* * Another wrapper function that serves as a drop-in replacement for * interp2d_eval but does not check the bounds. This can be used * for extrapolation. */ static int interp2d_eval_extrap(int (*evaluator)(const void *, const double xa[], const double ya[], const double za[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel *, gsl_interp_accel *, double * z), const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * result) { return evaluator(interp->state, xarr, yarr, zarr, interp->xsize, interp->ysize, x, y, xa, ya, result); } double gsl_interp2d_eval (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { double z; int status = gsl_interp2d_eval_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z); DISCARD_STATUS(status) return z; } /* gsl_interp2d_eval() */ double gsl_interp2d_eval_extrap (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { double z; int status = interp2d_eval_extrap(interp->type->eval, interp, xarr, yarr, zarr, x, y, xa, ya, &z); DISCARD_STATUS(status) return z; } int gsl_interp2d_eval_e (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return interp2d_eval(interp->type->eval, interp, xarr, yarr, zarr, x, y, xa, ya, z); } /* gsl_interp2d_eval_e() */ int gsl_interp2d_eval_e_extrap (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return interp2d_eval_extrap(interp->type->eval, interp, xarr, yarr, zarr, x, y, xa, ya, z); } double gsl_interp2d_eval_deriv_x (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { double z; int status = gsl_interp2d_eval_deriv_x_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z); DISCARD_STATUS(status) return z; } int gsl_interp2d_eval_deriv_x_e (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return interp2d_eval(interp->type->eval_deriv_x, interp, xarr, yarr, zarr, x, y, xa, ya, z); } double gsl_interp2d_eval_deriv_y (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { double z; int status = gsl_interp2d_eval_deriv_y_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z); DISCARD_STATUS(status) return z; } int gsl_interp2d_eval_deriv_y_e (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return interp2d_eval(interp->type->eval_deriv_y, interp, xarr, yarr, zarr, x, y, xa, ya, z); } double gsl_interp2d_eval_deriv_xx (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { double z; int status = gsl_interp2d_eval_deriv_xx_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z); DISCARD_STATUS(status) return z; } int gsl_interp2d_eval_deriv_xx_e (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return interp2d_eval(interp->type->eval_deriv_xx, interp, xarr, yarr, zarr, x, y, xa, ya, z); } double gsl_interp2d_eval_deriv_yy (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { double z; int status = gsl_interp2d_eval_deriv_yy_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z); DISCARD_STATUS(status) return z; } int gsl_interp2d_eval_deriv_yy_e (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return interp2d_eval(interp->type->eval_deriv_yy, interp, xarr, yarr, zarr, x, y, xa, ya, z); } double gsl_interp2d_eval_deriv_xy (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya) { double z; int status = gsl_interp2d_eval_deriv_xy_e(interp, xarr, yarr, zarr, x, y, xa, ya, &z); DISCARD_STATUS(status) return z; } int gsl_interp2d_eval_deriv_xy_e (const gsl_interp2d * interp, const double xarr[], const double yarr[], const double zarr[], const double x, const double y, gsl_interp_accel * xa, gsl_interp_accel * ya, double * z) { return interp2d_eval(interp->type->eval_deriv_xy, interp, xarr, yarr, zarr, x, y, xa, ya, z); } size_t gsl_interp2d_type_min_size(const gsl_interp2d_type * T) { return T->min_size; } size_t gsl_interp2d_min_size(const gsl_interp2d * interp) { return interp->type->min_size; } const char * gsl_interp2d_name(const gsl_interp2d * interp) { return interp->type->name; } size_t gsl_interp2d_idx(const gsl_interp2d * interp, const size_t i, const size_t j) { if (i >= interp->xsize) { GSL_ERROR_VAL ("x index out of range", GSL_ERANGE, 0); } else if (j >= interp->ysize) { GSL_ERROR_VAL ("y index out of range", GSL_ERANGE, 0); } else { return IDX2D(i, j, interp); } } /* gsl_interp2d_idx() */ int gsl_interp2d_set(const gsl_interp2d * interp, double zarr[], const size_t i, const size_t j, const double z) { if (i >= interp->xsize) { GSL_ERROR ("x index out of range", GSL_ERANGE); } else if (j >= interp->ysize) { GSL_ERROR ("y index out of range", GSL_ERANGE); } else { zarr[IDX2D(i, j, interp)] = z; return GSL_SUCCESS; } } /* gsl_interp2d_set() */ double gsl_interp2d_get(const gsl_interp2d * interp, const double zarr[], const size_t i, const size_t j) { if (i >= interp->xsize) { GSL_ERROR_VAL ("x index out of range", GSL_ERANGE, 0); } else if (j >= interp->ysize) { GSL_ERROR_VAL ("y index out of range", GSL_ERANGE, 0); } else { return zarr[IDX2D(i, j, interp)]; } } /* gsl_interp2d_get() */ #undef IDX2D
{ "alphanum_fraction": 0.5778131876, "avg_line_length": 31.9878640777, "ext": "c", "hexsha": "6389ebf0e833f5407ee2a9be6bb1098ce80187fa", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/interp2d.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/interp2d.c", "max_line_length": 106, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/interpolation/interp2d.c", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "num_tokens": 3305, "size": 13179 }
/** * * @generated c Tue Jan 7 11:45:26 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <cblas.h> #include <lapacke.h> #include <plasma.h> #include <core_blas.h> #include "auxiliary.h" /*------------------------------------------------------------------- * Check the orthogonality of Q */ int c_check_orthogonality(int M, int N, int LDQ, PLASMA_Complex32_t *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?*/ PLASMA_Complex32_t *Id = (PLASMA_Complex32_t *) malloc(minMN*minMN*sizeof(PLASMA_Complex32_t)); memset((void*)Id, 0, minMN*minMN*sizeof(PLASMA_Complex32_t)); for (i = 0; i < minMN; i++) Id[i*minMN+i] = (PLASMA_Complex32_t)1.0; /* Perform Id - Q'Q */ if (M >= N) cblas_cherk(CblasColMajor, CblasUpper, CblasConjTrans, N, M, alpha, Q, LDQ, beta, Id, N); else cblas_cherk(CblasColMajor, CblasUpper, CblasNoTrans, M, N, alpha, Q, LDQ, beta, Id, M); normQ = LAPACKE_clansy_work(LAPACK_COL_MAJOR, 'i', 'u', minMN, Id, minMN, work); printf("============\n"); printf("Checking the orthogonality of Q \n"); printf("||Id-Q'*Q||_oo / (N*eps) = %e \n",normQ/(minMN*eps)); if ( isnan(normQ / (minMN * eps)) || (normQ / (minMN * eps) > 10.0) ) { printf("-- Orthogonality is suspicious ! \n"); info_ortho=1; } else { printf("-- Orthogonality is CORRECT ! \n"); info_ortho=0; } free(work); free(Id); return info_ortho; } /*------------------------------------------------------------ * Check the factorization QR */ int c_check_QRfactorization(int M, int N, PLASMA_Complex32_t *A1, PLASMA_Complex32_t *A2, int LDA, PLASMA_Complex32_t *Q) { float Anorm, Rnorm; PLASMA_Complex32_t alpha, beta; int info_factorization; int i,j; float eps; eps = LAPACKE_slamch_work('e'); PLASMA_Complex32_t *Ql = (PLASMA_Complex32_t *)malloc(M*N*sizeof(PLASMA_Complex32_t)); PLASMA_Complex32_t *Residual = (PLASMA_Complex32_t *)malloc(M*N*sizeof(PLASMA_Complex32_t)); float *work = (float *)malloc(max(M,N)*sizeof(float)); alpha=1.0; beta=0.0; if (M >= N) { /* Extract the R */ PLASMA_Complex32_t *R = (PLASMA_Complex32_t *)malloc(N*N*sizeof(PLASMA_Complex32_t)); memset((void*)R, 0, N*N*sizeof(PLASMA_Complex32_t)); LAPACKE_clacpy_work(LAPACK_COL_MAJOR,'u', M, N, A2, LDA, R, N); /* Perform Ql=Q*R */ memset((void*)Ql, 0, M*N*sizeof(PLASMA_Complex32_t)); cblas_cgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, N, CBLAS_SADDR(alpha), Q, LDA, R, N, CBLAS_SADDR(beta), Ql, M); free(R); } else { /* Extract the L */ PLASMA_Complex32_t *L = (PLASMA_Complex32_t *)malloc(M*M*sizeof(PLASMA_Complex32_t)); memset((void*)L, 0, M*M*sizeof(PLASMA_Complex32_t)); LAPACKE_clacpy_work(LAPACK_COL_MAJOR,'l', M, N, A2, LDA, L, M); /* Perform Ql=LQ */ memset((void*)Ql, 0, M*N*sizeof(PLASMA_Complex32_t)); cblas_cgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, M, CBLAS_SADDR(alpha), L, M, Q, LDA, CBLAS_SADDR(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_clange_work(LAPACK_COL_MAJOR, 'i', M, N, Residual, M, work); Anorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, A2, LDA, work); if (M >= N) { printf("============\n"); printf("Checking the QR Factorization \n"); printf("-- ||A-QR||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); } else { printf("============\n"); printf("Checking the LQ Factorization \n"); printf("-- ||A-LQ||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); } if (isnan(Rnorm / (Anorm * N *eps)) || (Rnorm / (Anorm * N * eps) > 10.0) ) { printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else { printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } free(work); free(Ql); free(Residual); return info_factorization; } /*------------------------------------------------------------------------ * Check the factorization of the matrix A2 */ int c_check_LLTfactorization(int N, PLASMA_Complex32_t *A1, PLASMA_Complex32_t *A2, int LDA, int uplo) { float Anorm, Rnorm; PLASMA_Complex32_t alpha; int info_factorization; int i,j; float eps; eps = LAPACKE_slamch_work('e'); PLASMA_Complex32_t *Residual = (PLASMA_Complex32_t *)malloc(N*N*sizeof(PLASMA_Complex32_t)); PLASMA_Complex32_t *L1 = (PLASMA_Complex32_t *)malloc(N*N*sizeof(PLASMA_Complex32_t)); PLASMA_Complex32_t *L2 = (PLASMA_Complex32_t *)malloc(N*N*sizeof(PLASMA_Complex32_t)); float *work = (float *)malloc(N*sizeof(float)); memset((void*)L1, 0, N*N*sizeof(PLASMA_Complex32_t)); memset((void*)L2, 0, N*N*sizeof(PLASMA_Complex32_t)); alpha= 1.0; LAPACKE_clacpy_work(LAPACK_COL_MAJOR,' ', N, N, A1, LDA, Residual, N); /* Dealing with L'L or U'U */ if (uplo == PlasmaUpper){ LAPACKE_clacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L1, N); LAPACKE_clacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L2, N); cblas_ctrmm(CblasColMajor, CblasLeft, CblasUpper, CblasConjTrans, CblasNonUnit, N, N, CBLAS_SADDR(alpha), L1, N, L2, N); } else{ LAPACKE_clacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L1, N); LAPACKE_clacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L2, N); cblas_ctrmm(CblasColMajor, CblasRight, CblasLower, CblasConjTrans, CblasNonUnit, N, N, CBLAS_SADDR(alpha), L1, N, L2, N); } /* Compute the Residual || A -L'L|| */ for (i = 0; i < N; i++) for (j = 0; j < N; j++) Residual[j*N+i] = L2[j*N+i] - Residual[j*N+i]; Rnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', N, N, Residual, N, work); Anorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', N, N, A1, LDA, work); printf("============\n"); printf("Checking the Cholesky Factorization \n"); printf("-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps)); if ( isnan(Rnorm/(Anorm*N*eps)) || (Rnorm/(Anorm*N*eps) > 10.0) ){ printf("-- Factorization is suspicious ! \n"); info_factorization = 1; } else{ printf("-- Factorization is CORRECT ! \n"); info_factorization = 0; } free(Residual); free(L1); free(L2); free(work); return info_factorization; } /*-------------------------------------------------------------- * Check the gemm */ float c_check_gemm(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K, PLASMA_Complex32_t alpha, PLASMA_Complex32_t *A, int LDA, PLASMA_Complex32_t *B, int LDB, PLASMA_Complex32_t beta, PLASMA_Complex32_t *Cplasma, PLASMA_Complex32_t *Cref, int LDC, float *Cinitnorm, float *Cplasmanorm, float *Clapacknorm ) { PLASMA_Complex32_t beta_const = -1.0; float Rnorm; float *work = (float *)malloc(max(K,max(M, N))* sizeof(float)); *Cinitnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work); *Cplasmanorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, Cplasma, LDC, work); cblas_cgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K, CBLAS_SADDR(alpha), A, LDA, B, LDB, CBLAS_SADDR(beta), Cref, LDC); *Clapacknorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work); cblas_caxpy(LDC * N, CBLAS_SADDR(beta_const), Cplasma, 1, Cref, 1); Rnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work); free(work); return Rnorm; } /*-------------------------------------------------------------- * Check the trsm */ float c_check_trsm(PLASMA_enum side, PLASMA_enum uplo, PLASMA_enum trans, PLASMA_enum diag, int M, int NRHS, PLASMA_Complex32_t alpha, PLASMA_Complex32_t *A, int LDA, PLASMA_Complex32_t *Bplasma, PLASMA_Complex32_t *Bref, int LDB, float *Binitnorm, float *Bplasmanorm, float *Blapacknorm ) { PLASMA_Complex32_t beta_const = -1.0; float Rnorm; float *work = (float *)malloc(max(M, NRHS)* sizeof(float)); /*float eps = LAPACKE_slamch_work('e');*/ *Binitnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, Bref, LDB, work); *Bplasmanorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bplasma, LDB, work); cblas_ctrsm(CblasColMajor, (CBLAS_SIDE)side, (CBLAS_UPLO)uplo, (CBLAS_TRANSPOSE)trans, (CBLAS_DIAG)diag, M, NRHS, CBLAS_SADDR(alpha), A, LDA, Bref, LDB); *Blapacknorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bref, LDB, work); cblas_caxpy(LDB * NRHS, CBLAS_SADDR(beta_const), Bplasma, 1, Bref, 1); Rnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bref, LDB, work); Rnorm = Rnorm / *Blapacknorm; /* max(M,NRHS) * eps);*/ free(work); return Rnorm; } /*-------------------------------------------------------------- * Check the solution */ float c_check_solution(int M, int N, int NRHS, PLASMA_Complex32_t *A, int LDA, PLASMA_Complex32_t *B, PLASMA_Complex32_t *X, int LDB, float *anorm, float *bnorm, float *xnorm ) { /* int info_solution; */ float Rnorm = -1.00; PLASMA_Complex32_t zone = 1.0; PLASMA_Complex32_t mzone = -1.0; float *work = (float *)malloc(max(M, N)* sizeof(float)); *anorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, N, A, LDA, work); *xnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, X, LDB, work); *bnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work); cblas_cgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, NRHS, N, CBLAS_SADDR(zone), A, LDA, X, LDB, CBLAS_SADDR(mzone), B, LDB); Rnorm = LAPACKE_clange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work); free(work); return Rnorm; }
{ "alphanum_fraction": 0.5899705015, "avg_line_length": 35.2651006711, "ext": "c", "hexsha": "d122839d6ba644faa10141ba3bf8da980b36af80", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "timing/cauxiliary.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "timing/cauxiliary.c", "max_line_length": 134, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "timing/cauxiliary.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3563, "size": 10509 }
/* specfunc/laguerre.c * * Copyright (C) 2007 Brian Gough * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_exp.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_laguerre.h> #include "error.h" /*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/ /* based on the large 2b-4a asymptotic for 1F1 * [Abramowitz+Stegun, 13.5.21] * L^a_n(x) = (a+1)_n / n! 1F1(-n,a+1,x) * * The second term (ser_term2) is from Slater,"The Confluent * Hypergeometric Function" p.73. I think there may be an error in * the first term of the expression given there, comparing with AS * 13.5.21 (cf sin(a\pi+\Theta) vs sin(a\pi) + sin(\Theta)) - but the * second term appears correct. * */ static int laguerre_large_n(const int n, const double alpha, const double x, gsl_sf_result * result) { const double a = -n; const double b = alpha + 1.0; const double eta = 2.0*b - 4.0*a; const double cos2th = x/eta; const double sin2th = 1.0 - cos2th; const double eps = asin(sqrt(cos2th)); /* theta = pi/2 - eps */ const double pre_h = 0.25*M_PI*M_PI*eta*eta*cos2th*sin2th; gsl_sf_result lg_b; gsl_sf_result lnfact; int stat_lg = gsl_sf_lngamma_e(b+n, &lg_b); int stat_lf = gsl_sf_lnfact_e(n, &lnfact); double pre_term1 = 0.5*(1.0-b)*log(0.25*x*eta); double pre_term2 = 0.25*log(pre_h); double lnpre_val = lg_b.val - lnfact.val + 0.5*x + pre_term1 - pre_term2; double lnpre_err = lg_b.err + lnfact.err + GSL_DBL_EPSILON * (fabs(pre_term1)+fabs(pre_term2)); double phi1 = 0.25*eta*(2*eps + sin(2.0*eps)); double ser_term1 = -sin(phi1); double A1 = (1.0/12.0)*(5.0/(4.0*sin2th)+(3.0*b*b-6.0*b+2.0)*sin2th - 1.0); double ser_term2 = -A1 * cos(phi1)/(0.25*eta*sin(2.0*eps)); double ser_val = ser_term1 + ser_term2; double ser_err = ser_term2*ser_term2 + GSL_DBL_EPSILON * (fabs(ser_term1) + fabs(ser_term2)); int stat_e = gsl_sf_exp_mult_err_e(lnpre_val, lnpre_err, ser_val, ser_err, result); result->err += 2.0 * GSL_SQRT_DBL_EPSILON * fabs(result->val); return GSL_ERROR_SELECT_3(stat_e, stat_lf, stat_lg); } /* Evaluate polynomial based on confluent hypergeometric representation. * * L^a_n(x) = (a+1)_n / n! 1F1(-n,a+1,x) * * assumes n > 0 and a != negative integer greater than -n */ static int laguerre_n_cp(const int n, const double a, const double x, gsl_sf_result * result) { gsl_sf_result lnfact; gsl_sf_result lg1; gsl_sf_result lg2; double s1, s2; int stat_f = gsl_sf_lnfact_e(n, &lnfact); int stat_g1 = gsl_sf_lngamma_sgn_e(a+1.0+n, &lg1, &s1); int stat_g2 = gsl_sf_lngamma_sgn_e(a+1.0, &lg2, &s2); double poly_1F1_val = 1.0; double poly_1F1_err = 0.0; int stat_e; int k; double lnpre_val = (lg1.val - lg2.val) - lnfact.val; double lnpre_err = lg1.err + lg2.err + lnfact.err + 2.0 * GSL_DBL_EPSILON * fabs(lnpre_val); for(k=n-1; k>=0; k--) { double t = (-n+k)/(a+1.0+k) * (x/(k+1)); double r = t + 1.0/poly_1F1_val; if(r > 0.9*GSL_DBL_MAX/poly_1F1_val) { /* internal error only, don't call the error handler */ INTERNAL_OVERFLOW_ERROR(result); } else { /* Collect the Horner terms. */ poly_1F1_val = 1.0 + t * poly_1F1_val; poly_1F1_err += GSL_DBL_EPSILON + fabs(t) * poly_1F1_err; } } stat_e = gsl_sf_exp_mult_err_e(lnpre_val, lnpre_err, poly_1F1_val, poly_1F1_err, result); return GSL_ERROR_SELECT_4(stat_e, stat_f, stat_g1, stat_g2); } /* Evaluate the polynomial based on the confluent hypergeometric * function in a safe way, with no restriction on the arguments. * * assumes x != 0 */ static int laguerre_n_poly_safe(const int n, const double a, const double x, gsl_sf_result * result) { const double b = a + 1.0; const double mx = -x; const double tc_sgn = (x < 0.0 ? 1.0 : (GSL_IS_ODD(n) ? -1.0 : 1.0)); gsl_sf_result tc; int stat_tc = gsl_sf_taylorcoeff_e(n, fabs(x), &tc); if(stat_tc == GSL_SUCCESS) { double term = tc.val * tc_sgn; double sum_val = term; double sum_err = tc.err; int k; for(k=n-1; k>=0; k--) { term *= ((b+k)/(n-k))*(k+1.0)/mx; sum_val += term; sum_err += 4.0 * GSL_DBL_EPSILON * fabs(term); } result->val = sum_val; result->err = sum_err + 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(stat_tc == GSL_EOVRFLW) { result->val = 0.0; /* FIXME: should be Inf */ result->err = 0.0; return stat_tc; } else { result->val = 0.0; result->err = 0.0; return stat_tc; } } /*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*/ int gsl_sf_laguerre_1_e(const double a, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ { result->val = 1.0 + a - x; result->err = 2.0 * GSL_DBL_EPSILON * (1.0 + fabs(a) + fabs(x)); return GSL_SUCCESS; } } int gsl_sf_laguerre_2_e(const double a, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(a == -2.0) { result->val = 0.5*x*x; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { double c0 = 0.5 * (2.0+a)*(1.0+a); double c1 = -(2.0+a); double c2 = -0.5/(2.0+a); result->val = c0 + c1*x*(1.0 + c2*x); result->err = 2.0 * GSL_DBL_EPSILON * (fabs(c0) + 2.0 * fabs(c1*x) * (1.0 + 2.0 * fabs(c2*x))); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_laguerre_3_e(const double a, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(a == -2.0) { double x2_6 = x*x/6.0; result->val = x2_6 * (3.0 - x); result->err = x2_6 * (3.0 + fabs(x)) * 2.0 * GSL_DBL_EPSILON; result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if(a == -3.0) { result->val = -x*x/6.0; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else { double c0 = (3.0+a)*(2.0+a)*(1.0+a) / 6.0; double c1 = -c0 * 3.0 / (1.0+a); double c2 = -1.0/(2.0+a); double c3 = -1.0/(3.0*(3.0+a)); result->val = c0 + c1*x*(1.0 + c2*x*(1.0 + c3*x)); result->err = 1.0 + 2.0 * fabs(c3*x); result->err = 1.0 + 2.0 * fabs(c2*x) * result->err; result->err = 2.0 * GSL_DBL_EPSILON * (fabs(c0) + 2.0 * fabs(c1*x) * result->err); result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } } int gsl_sf_laguerre_n_e(const int n, const double a, const double x, gsl_sf_result * result) { /* CHECK_POINTER(result) */ if(n < 0) { DOMAIN_ERROR(result); } else if(n == 0) { result->val = 1.0; result->err = 0.0; return GSL_SUCCESS; } else if(n == 1) { result->val = 1.0 + a - x; result->err = 2.0 * GSL_DBL_EPSILON * (1.0 + fabs(a) + fabs(x)); return GSL_SUCCESS; } else if(x == 0.0) { double product = a + 1.0; int k; for(k=2; k<=n; k++) { product *= (a + k)/k; } result->val = product; result->err = 2.0 * (n + 1.0) * GSL_DBL_EPSILON * fabs(product) + GSL_DBL_EPSILON; return GSL_SUCCESS; } else if(x < 0.0 && a > -1.0) { /* In this case all the terms in the polynomial * are of the same sign. Note that this also * catches overflows correctly. */ return laguerre_n_cp(n, a, x, result); } else if(n < 5 || (x > 0.0 && a < -n-1)) { /* Either the polynomial will not lose too much accuracy * or all the terms are negative. In any case, * the error estimate here is good. We try both * explicit summation methods, as they have different * characteristics. One may underflow/overflow while the * other does not. */ if(laguerre_n_cp(n, a, x, result) == GSL_SUCCESS) return GSL_SUCCESS; else return laguerre_n_poly_safe(n, a, x, result); } else if(n > 1.0e+07 && x > 0.0 && a > -1.0 && x < 2.0*(a+1.0)+4.0*n) { return laguerre_large_n(n, a, x, result); } else if(a >= 0.0 || (x > 0.0 && a < -n-1)) { gsl_sf_result lg2; int stat_lg2 = gsl_sf_laguerre_2_e(a, x, &lg2); double Lkm1 = 1.0 + a - x; double Lk = lg2.val; double Lkp1; int k; for(k=2; k<n; k++) { Lkp1 = (-(k+a)*Lkm1 + (2.0*k+a+1.0-x)*Lk)/(k+1.0); Lkm1 = Lk; Lk = Lkp1; } result->val = Lk; result->err = (fabs(lg2.err/lg2.val) + GSL_DBL_EPSILON) * n * fabs(Lk); return stat_lg2; } else { /* Despair... or magic? */ return laguerre_n_poly_safe(n, a, x, result); } } /*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/ #include "eval.h" double gsl_sf_laguerre_1(double a, double x) { EVAL_RESULT(gsl_sf_laguerre_1_e(a, x, &result)); } double gsl_sf_laguerre_2(double a, double x) { EVAL_RESULT(gsl_sf_laguerre_2_e(a, x, &result)); } double gsl_sf_laguerre_3(double a, double x) { EVAL_RESULT(gsl_sf_laguerre_3_e(a, x, &result)); } double gsl_sf_laguerre_n(int n, double a, double x) { EVAL_RESULT(gsl_sf_laguerre_n_e(n, a, x, &result)); }
{ "alphanum_fraction": 0.6120004027, "avg_line_length": 29.5625, "ext": "c", "hexsha": "53dfa6e38bb8250d06cf012e9f7c0d43795b8d13", "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/specfunc/laguerre.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/specfunc/laguerre.c", "max_line_length": 100, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/specfunc/laguerre.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": 3549, "size": 9933 }
#include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "cblas.h" void cblas_zhpmv (const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const void *alpha, const void *Ap, const void *X, const int incX, const void *beta, void *Y, const int incY) { #define BASE double #include "source_hpmv.h" #undef BASE }
{ "alphanum_fraction": 0.7117647059, "avg_line_length": 24.2857142857, "ext": "c", "hexsha": "85179ddcfe51f02b5cf9ce37038f3c4354b011f0", "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/cblas/zhpmv.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/cblas/zhpmv.c", "max_line_length": 70, "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/cblas/zhpmv.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": 107, "size": 340 }
/* ODE: a program to get optime Runge-Kutta and multi-steps methods. Copyright 2011-2019, Javier Burguete Tolosa. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``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 Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file rk_5_3.c * \brief Source file to optimize Runge-Kutta 5 steps 3rd order methods. * \author Javier Burguete Tolosa. * \copyright Copyright 2011-2019. */ #define _GNU_SOURCE #include <string.h> #include <math.h> #include <libxml/parser.h> #include <glib.h> #include <libintl.h> #include <gsl/gsl_rng.h> #include "config.h" #include "utils.h" #include "optimize.h" #include "rk.h" #include "rk_5_3.h" #define DEBUG_RK_5_3 0 ///< macro to debug. /** * Function to obtain the coefficients of a 5 steps 3rd order Runge-Kutta * method. */ int rk_tb_5_3 (Optimize * optimize) ///< Optimize struct. { long double A[3], B[3], C[3], D[3]; long double *tb, *r; #if DEBUG_RK_5_3 fprintf (stderr, "rk_tb_5_3: start\n"); #endif tb = optimize->coefficient; r = optimize->random_data; t5 (tb) = 1.L; t1 (tb) = r[0]; t2 (tb) = r[1]; b21 (tb) = r[2]; t3 (tb) = r[3]; b31 (tb) = r[4]; b32 (tb) = r[5]; t4 (tb) = r[6]; b41 (tb) = r[7]; b42 (tb) = r[8]; b43 (tb) = r[9]; b54 (tb) = r[10]; A[0] = t1 (tb); B[0] = t2 (tb); C[0] = t3 (tb); D[0] = 0.5L - b54 (tb) * t4 (tb); A[1] = A[0] * t1 (tb); B[1] = B[0] * t2 (tb); C[1] = C[0] * t3 (tb); D[1] = 1.L / 3.L - b54 (tb) * sqr (t4 (tb)); A[2] = 0.L; B[2] = b21 (tb) * t1 (tb); C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb); D[2] = 1.L / 6.L - b54 (tb) * (b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb) + b43 (tb) * t3 (tb)); solve_3 (A, B, C, D); if (isnan (D[0]) || isnan (D[1]) || isnan (D[2])) return 0; b53 (tb) = D[2]; b52 (tb) = D[1]; b51 (tb) = D[0]; rk_b_5 (tb); #if DEBUG_RK_5_3 fprintf (stderr, "rk_tb_5_3: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 5 steps 3rd order, 4th order in * equations depending only in time, Runge-Kutta method. */ int rk_tb_5_3t (Optimize * optimize) ///< Optimize struct. { long double A[4], B[4], C[4], D[4], E[4]; long double *tb, *r; #if DEBUG_RK_5_3 fprintf (stderr, "rk_tb_5_3t: start\n"); #endif tb = optimize->coefficient; r = optimize->random_data; t5 (tb) = 1.L; t1 (tb) = r[0]; t2 (tb) = r[1]; b21 (tb) = r[2]; t3 (tb) = r[3]; b31 (tb) = r[4]; b32 (tb) = r[5]; t4 (tb) = r[6]; b41 (tb) = r[7]; b42 (tb) = r[8]; b43 (tb) = r[9]; A[0] = t1 (tb); B[0] = t2 (tb); C[0] = t3 (tb); D[0] = t4 (tb); E[0] = 0.5L; A[1] = A[0] * t1 (tb); B[1] = B[0] * t2 (tb); C[1] = C[0] * t3 (tb); D[1] = D[0] * t4 (tb); E[1] = 1.L / 3.L; A[2] = A[1] * t1 (tb); B[2] = B[1] * t2 (tb); C[2] = C[1] * t3 (tb); D[2] = D[1] * t4 (tb); E[2] = 0.25L; A[3] = 0.L; B[3] = b21 (tb) * t1 (tb); C[3] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb); D[3] = b41 (tb) * t1 (tb) + b42 (tb) * t2 (tb) + b43 (tb) * t3 (tb); E[3] = 1.L / 6.L; solve_4 (A, B, C, D, E); if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3])) return 0; b54 (tb) = E[3]; b53 (tb) = E[2]; b52 (tb) = E[1]; b51 (tb) = E[0]; rk_b_5 (tb); #if DEBUG_RK_5_3 fprintf (stderr, "rk_tb_5_3t: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 5 steps 2nd-3rd order Runge-Kutta * pair. */ int rk_tb_5_3p (Optimize * optimize) ///< Optimize struct. { long double *tb; #if DEBUG_RK_5_3 fprintf (stderr, "rk_tb_5_3p: start\n"); #endif if (!rk_tb_5_3 (optimize)) return 0; tb = optimize->coefficient; e51 (tb) = 0.5L / t1 (tb); e52 (tb) = e53 (tb) = 0.L; rk_e_5 (tb); #if DEBUG_RK_5_3 fprintf (stderr, "rk_tb_5_3p: end\n"); #endif return 1; } /** * Function to obtain the coefficients of a 5 steps 2nd-3rd order, 3rd-4th order * in equations depending only in time, Runge-Kutta pair. */ int rk_tb_5_3tp (Optimize * optimize) ///< Optimize struct. { long double *tb; #if DEBUG_RK_5_3 fprintf (stderr, "rk_tb_5_3tp: start\n"); #endif if (!rk_tb_5_3t (optimize)) return 0; tb = optimize->coefficient; e53 (tb) = 0.L; e52 (tb) = (1.L / 3.L - 0.5L * t1 (tb)) / (t2 (tb) * (t2 (tb) - t1 (tb))); if (isnan (e52 (tb))) return 0; e51 (tb) = (0.5L - e52 (tb) * t2 (tb)) / t1 (tb); if (isnan (e51 (tb))) return 0; rk_e_5 (tb); #if DEBUG_RK_5_3 fprintf (stderr, "rk_tb_5_3tp: end\n"); #endif return 1; } /** * Function to calculate the objective function of a 5 steps 3rd order * Runge-Kutta method. * * \return objective function value. */ long double rk_objective_tb_5_3 (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_5_3 fprintf (stderr, "rk_objective_tb_5_3: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b30 (tb) < 0.L) o += b30 (tb); if (b40 (tb) < 0.L) o += b40 (tb); if (b50 (tb) < 0.L) o += b50 (tb); if (b51 (tb) < 0.L) o += b51 (tb); if (b52 (tb) < 0.L) o += b52 (tb); if (b53 (tb) < 0.L) o += b53 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb))))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_5_3 fprintf (stderr, "rk_objective_tb_5_3: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_5_3: end\n"); #endif return o; } /** * Function to calculate the objective function of a 5 steps 3rd order, 4th * order in equations depending only in time, Runge-Kutta method. * * \return objective function value. */ long double rk_objective_tb_5_3t (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_5_3 fprintf (stderr, "rk_objective_tb_5_3t: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b30 (tb) < 0.L) o += b30 (tb); if (b40 (tb) < 0.L) o += b40 (tb); if (b50 (tb) < 0.L) o += b50 (tb); if (b51 (tb) < 0.L) o += b51 (tb); if (b52 (tb) < 0.L) o += b52 (tb); if (b53 (tb) < 0.L) o += b53 (tb); if (b54 (tb) < 0.L) o += b54 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb))))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_5_3 fprintf (stderr, "rk_objective_tb_5_3t: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_5_3t: end\n"); #endif return o; } /** * Function to calculate the objective function of a 5 steps 2nd-3rd order * Runge-Kutta pair. * * \return objective function value. */ long double rk_objective_tb_5_3p (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_5_3 fprintf (stderr, "rk_objective_tb_5_3p: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b30 (tb) < 0.L) o += b30 (tb); if (b40 (tb) < 0.L) o += b40 (tb); if (b50 (tb) < 0.L) o += b50 (tb); if (b51 (tb) < 0.L) o += b51 (tb); if (b52 (tb) < 0.L) o += b52 (tb); if (b53 (tb) < 0.L) o += b53 (tb); if (e50 (tb) < 0.L) o += e50 (tb); if (e51 (tb) < 0.L) o += e51 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb))))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_5_3 fprintf (stderr, "rk_objective_tb_5_3p: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_5_3p: end\n"); #endif return o; } /** * Function to calculate the objective function of a 5 steps 2nd-3rd order, * 3rd-4th order in equations depending only in time, Runge-Kutta pair. * * \return objective function value. */ long double rk_objective_tb_5_3tp (RK * rk) ///< RK struct. { long double *tb; long double o; #if DEBUG_RK_5_3 fprintf (stderr, "rk_objective_tb_5_3tp: start\n"); #endif tb = rk->tb->coefficient; o = fminl (0.L, b20 (tb)); if (b30 (tb) < 0.L) o += b30 (tb); if (b40 (tb) < 0.L) o += b40 (tb); if (b50 (tb) < 0.L) o += b50 (tb); if (b51 (tb) < 0.L) o += b51 (tb); if (b52 (tb) < 0.L) o += b52 (tb); if (b53 (tb) < 0.L) o += b53 (tb); if (b54 (tb) < 0.L) o += b54 (tb); if (e50 (tb) < 0.L) o += e50 (tb); if (e51 (tb) < 0.L) o += e51 (tb); if (e52 (tb) < 0.L) o += e52 (tb); if (o < 0.L) { o = 40.L - o; goto end; } o = 30.L + fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb))))); if (rk->strong) { rk_bucle_ac (rk); o = fminl (o, *rk->ac0->optimal); } end: #if DEBUG_RK_5_3 fprintf (stderr, "rk_objective_tb_5_3tp: optimal=%Lg\n", o); fprintf (stderr, "rk_objective_tb_5_3tp: end\n"); #endif return o; }
{ "alphanum_fraction": 0.5692672797, "avg_line_length": 24.3100961538, "ext": "c", "hexsha": "857828d71ad9bf7c2b551e3071dbf095e4cbd97f", "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": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/ode", "max_forks_repo_path": "rk_5_3.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "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": "jburguete/ode", "max_issues_repo_path": "rk_5_3.c", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/ode", "max_stars_repo_path": "rk_5_3.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4079, "size": 10113 }
#ifndef UTILS_H #define UTILS_H #include <gsl/gsl_vector.h> #include <gsl/gsl_sort_vector.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_permutation.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_eigen.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_sf_psi.h> #include <math.h> #include <assert.h> #include <time.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <dirent.h> #include <memory.h> #define outlog(format, args...) \ fprintf(stderr, format, args); \ fprintf(stderr, "\n"); int compare (const void * a, const void * b); inline double safe_log(double x) { if (x <= 0) return(-10000); else return(log(x)); } double log_sum(double, double); inline double vget(const gsl_vector* v, int i) { return(gsl_vector_get(v, i)); } inline void vset(gsl_vector* v, int i, double x) { gsl_vector_set(v, i, x); } // Increment a vector element by a double. inline void vinc(gsl_vector* v, int i, double x) { vset(v, i, vget(v, i) + x); } inline double mget(const gsl_matrix* m, int i, int j) { return(gsl_matrix_get(m, i, j)); } inline void mset(gsl_matrix* m, int i, int j, double x) { gsl_matrix_set(m, i, j, x); } // Increment a matrix element by a double. void minc(gsl_matrix*, int, int, double); void col_sum(const gsl_matrix*, gsl_vector*); void row_sum(const gsl_matrix*, gsl_vector*); void vct_fprintf(FILE* file, const gsl_vector* v); void mtx_fprintf(FILE* file, const gsl_matrix* m); void mtx_fscanf(FILE* file, gsl_matrix* m); inline bool check_sym(const gsl_matrix *m) { for (size_t i = 0; i < m->size1-1; i ++) for (size_t j=i; j < m->size2; j ++) if (mget(m, i, j) != mget(m, j, i)) { printf("not sym\n"); return false; } return true; } double log_det(const gsl_matrix*); void matrix_inverse(const gsl_matrix*, gsl_matrix*); void matrix_vector_solve(const gsl_matrix* m, const gsl_vector* b, gsl_vector* v); void sym_eigen(gsl_matrix*, gsl_vector*, gsl_matrix*); inline double vsum(const gsl_vector* v) { double val = 0; int i, size = v->size; for (i = 0; i < size; i++) val += vget(v, i); return(val); } double vnorm(const gsl_vector * v); void gsl_vector_apply(gsl_vector* x, double(*fun)(double)); void vct_log(gsl_vector* v); void mtx_log(gsl_matrix* x); void vct_exp(gsl_vector* x); void mtx_exp(gsl_matrix* x); double mahalanobis_distance(const gsl_matrix * m, const gsl_vector* u, const gsl_vector* v); double mahalanobis_prod(const gsl_matrix * m, const gsl_vector* u, const gsl_vector* v); double matrix_dot_prod(const gsl_matrix * m1, const gsl_matrix* m2); void choose_k_from_n(int k, int n, int* result, int* src); double log_normalize(gsl_vector* x); double vnormalize(gsl_vector* x); int dir_exists(const char *dname); bool file_exists(const char * filename); void make_directory(const char* name); double digamma(double x); unsigned int rmultinomial(const gsl_vector* v); double rgamma(double a, double b); double rbeta(double a, double b); unsigned int rbernoulli(double p); double runiform(); void rshuffle (void* base, size_t n, size_t size); unsigned long int runiform_int(unsigned long int n); // new and free random number generator gsl_rng* new_random_number_generator(long seed); void free_random_number_generator(gsl_rng * random_number_generator); #endif
{ "alphanum_fraction": 0.708912037, "avg_line_length": 27.4285714286, "ext": "h", "hexsha": "c41f4dcc7f2c8c8b8ca0f219ee610cd4aa2b84a9", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-07-21T09:56:48.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-21T09:56:48.000Z", "max_forks_repo_head_hexsha": "8d214517a1fc3c8fbdf990b9da30f3e9c8b32c5f", "max_forks_repo_licenses": [ "Python-2.0", "OLDAP-2.7" ], "max_forks_repo_name": "SergiuTripon/irdm-collaborative-filtering", "max_forks_repo_path": "ctr/utils.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8d214517a1fc3c8fbdf990b9da30f3e9c8b32c5f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Python-2.0", "OLDAP-2.7" ], "max_issues_repo_name": "SergiuTripon/irdm-collaborative-filtering", "max_issues_repo_path": "ctr/utils.h", "max_line_length": 92, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8d214517a1fc3c8fbdf990b9da30f3e9c8b32c5f", "max_stars_repo_licenses": [ "Python-2.0", "OLDAP-2.7" ], "max_stars_repo_name": "SergiuTripon/irdm-collaborative-filtering", "max_stars_repo_path": "ctr/utils.h", "max_stars_repo_stars_event_max_datetime": "2020-04-17T16:08:04.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-17T16:08:04.000Z", "num_tokens": 992, "size": 3456 }
/* randist/binomial_tpe.c * * Copyright (C) 1996, 2003, 2007 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_pow_int.h> #include <gsl/gsl_sf_gamma.h> /* The binomial distribution has the form, f(x) = n!/(x!(n-x)!) * p^x (1-p)^(n-x) for integer 0 <= x <= n = 0 otherwise This implementation follows the public domain ranlib function "ignbin", the bulk of which is the BTPE (Binomial Triangle Parallelogram Exponential) algorithm introduced in Kachitvichyanukul and Schmeiser[1]. It has been translated to use modern C coding standards. If n is small and/or p is near 0 or near 1 (specifically, if n*min(p,1-p) < SMALL_MEAN), then a different algorithm, called BINV, is used which has an average runtime that scales linearly with n*min(p,1-p). But for larger problems, the BTPE algorithm takes the form of two functions b(x) and t(x) -- "bottom" and "top" -- for which b(x) < f(x)/f(M) < t(x), with M = floor(n*p+p). b(x) defines a triangular region, and t(x) includes a parallelogram and two tails. Details (including a nice drawing) are in the paper. [1] Kachitvichyanukul, V. and Schmeiser, B. W. Binomial Random Variate Generation. Communications of the ACM, 31, 2 (February, 1988) 216. Note, Bruce Schmeiser (personal communication) points out that if you want very fast binomial deviates, and you are happy with approximate results, and/or n and n*p are both large, then you can just use gaussian estimates: mean=n*p, variance=n*p*(1-p). This implementation by James Theiler, April 2003, after obtaining permission -- and some good advice -- from Drs. Kachitvichyanukul and Schmeiser to use their code as a starting point, and then doing a little bit of tweaking. Additional polishing for GSL coding standards by Brian Gough. */ #define SMALL_MEAN 14 /* If n*p < SMALL_MEAN then use BINV algorithm. The ranlib implementation used cutoff=30; but on my computer 14 works better */ #define BINV_CUTOFF 110 /* In BINV, do not permit ix too large */ #define FAR_FROM_MEAN 20 /* If ix-n*p is larger than this, then use the "squeeze" algorithm. Ranlib used 20, and this seems to be the best choice on my machine as well */ #define LNFACT(x) gsl_sf_lnfact(x) inline static double Stirling (double y1) { double y2 = y1 * y1; double s = (13860.0 - (462.0 - (132.0 - (99.0 - 140.0 / y2) / y2) / y2) / y2) / y1 / 166320.0; return s; } unsigned int gsl_ran_binomial_tpe (const gsl_rng * rng, double p, unsigned int n) { return gsl_ran_binomial (rng, p, n); } unsigned int gsl_ran_binomial (const gsl_rng * rng, double p, unsigned int n) { int ix; /* return value */ int flipped = 0; double q, s, np; if (n == 0) return 0; if (p > 0.5) { p = 1.0 - p; /* work with small p */ flipped = 1; } q = 1 - p; s = p / q; np = n * p; /* Inverse cdf logic for small mean (BINV in K+S) */ if (np < SMALL_MEAN) { double f0 = gsl_pow_uint (q, n); /* f(x), starting with x=0 */ while (1) { /* This while(1) loop will almost certainly only loop once; but * if u=1 to within a few epsilons of machine precision, then it * is possible for roundoff to prevent the main loop over ix to * achieve its proper value. following the ranlib implementation, * we introduce a check for that situation, and when it occurs, * we just try again. */ double f = f0; double u = gsl_rng_uniform (rng); for (ix = 0; ix <= BINV_CUTOFF; ++ix) { if (u < f) goto Finish; u -= f; /* Use recursion f(x+1) = f(x)*[(n-x)/(x+1)]*[p/(1-p)] */ f *= s * (n - ix) / (ix + 1); } /* It should be the case that the 'goto Finish' was encountered * before this point was ever reached. But if we have reached * this point, then roundoff has prevented u from decreasing * all the way to zero. This can happen only if the initial u * was very nearly equal to 1, which is a rare situation. In * that rare situation, we just try again. * * Note, following the ranlib implementation, we loop ix only to * a hardcoded value of SMALL_MEAN_LARGE_N=110; we could have * looped to n, and 99.99...% of the time it won't matter. This * choice, I think is a little more robust against the rare * roundoff error. If n>LARGE_N, then it is technically * possible for ix>LARGE_N, but it is astronomically rare, and * if ix is that large, it is more likely due to roundoff than * probability, so better to nip it at LARGE_N than to take a * chance that roundoff will somehow conspire to produce an even * larger (and more improbable) ix. If n<LARGE_N, then once * ix=n, f=0, and the loop will continue until ix=LARGE_N. */ } } else { /* For n >= SMALL_MEAN, we invoke the BTPE algorithm */ int k; double ffm = np + p; /* ffm = n*p+p */ int m = (int) ffm; /* m = int floor[n*p+p] */ double fm = m; /* fm = double m; */ double xm = fm + 0.5; /* xm = half integer mean (tip of triangle) */ double npq = np * q; /* npq = n*p*q */ /* Compute cumulative area of tri, para, exp tails */ /* p1: radius of triangle region; since height=1, also: area of region */ /* p2: p1 + area of parallelogram region */ /* p3: p2 + area of left tail */ /* p4: p3 + area of right tail */ /* pi/p4: probability of i'th area (i=1,2,3,4) */ /* Note: magic numbers 2.195, 4.6, 0.134, 20.5, 15.3 */ /* These magic numbers are not adjustable...at least not easily! */ double p1 = floor (2.195 * sqrt (npq) - 4.6 * q) + 0.5; /* xl, xr: left and right edges of triangle */ double xl = xm - p1; double xr = xm + p1; /* Parameter of exponential tails */ /* Left tail: t(x) = c*exp(-lambda_l*[xl - (x+0.5)]) */ /* Right tail: t(x) = c*exp(-lambda_r*[(x+0.5) - xr]) */ double c = 0.134 + 20.5 / (15.3 + fm); double p2 = p1 * (1.0 + c + c); double al = (ffm - xl) / (ffm - xl * p); double lambda_l = al * (1.0 + 0.5 * al); double ar = (xr - ffm) / (xr * q); double lambda_r = ar * (1.0 + 0.5 * ar); double p3 = p2 + c / lambda_l; double p4 = p3 + c / lambda_r; double var, accept; double u, v; /* random variates */ TryAgain: /* generate random variates, u specifies which region: Tri, Par, Tail */ u = gsl_rng_uniform (rng) * p4; v = gsl_rng_uniform (rng); if (u <= p1) { /* Triangular region */ ix = (int) (xm - p1 * v + u); goto Finish; } else if (u <= p2) { /* Parallelogram region */ double x = xl + (u - p1) / c; v = v * c + 1.0 - fabs (x - xm) / p1; if (v > 1.0 || v <= 0.0) goto TryAgain; ix = (int) x; } else if (u <= p3) { /* Left tail */ ix = (int) (xl + log (v) / lambda_l); if (ix < 0) goto TryAgain; v *= ((u - p2) * lambda_l); } else { /* Right tail */ ix = (int) (xr - log (v) / lambda_r); if (ix > (double) n) goto TryAgain; v *= ((u - p3) * lambda_r); } /* At this point, the goal is to test whether v <= f(x)/f(m) * * v <= f(x)/f(m) = (m!(n-m)! / (x!(n-x)!)) * (p/q)^{x-m} * */ /* Here is a direct test using logarithms. It is a little * slower than the various "squeezing" computations below, but * if things are working, it should give exactly the same answer * (given the same random number seed). */ #ifdef DIRECT var = log (v); accept = LNFACT (m) + LNFACT (n - m) - LNFACT (ix) - LNFACT (n - ix) + (ix - m) * log (p / q); #else /* SQUEEZE METHOD */ /* More efficient determination of whether v < f(x)/f(M) */ k = abs (ix - m); if (k <= FAR_FROM_MEAN) { /* * If ix near m (ie, |ix-m|<FAR_FROM_MEAN), then do * explicit evaluation using recursion relation for f(x) */ double g = (n + 1) * s; double f = 1.0; var = v; if (m < ix) { int i; for (i = m + 1; i <= ix; i++) { f *= (g / i - s); } } else if (m > ix) { int i; for (i = ix + 1; i <= m; i++) { f /= (g / i - s); } } accept = f; } else { /* If ix is far from the mean m: k=ABS(ix-m) large */ var = log (v); if (k < npq / 2 - 1) { /* "Squeeze" using upper and lower bounds on * log(f(x)) The squeeze condition was derived * under the condition k < npq/2-1 */ double amaxp = k / npq * ((k * (k / 3.0 + 0.625) + (1.0 / 6.0)) / npq + 0.5); double ynorm = -(k * k / (2.0 * npq)); if (var < ynorm - amaxp) goto Finish; if (var > ynorm + amaxp) goto TryAgain; } /* Now, again: do the test log(v) vs. log f(x)/f(M) */ #if USE_EXACT /* This is equivalent to the above, but is a little (~20%) slower */ /* There are five log's vs three above, maybe that's it? */ accept = LNFACT (m) + LNFACT (n - m) - LNFACT (ix) - LNFACT (n - ix) + (ix - m) * log (p / q); #else /* USE STIRLING */ /* The "#define Stirling" above corresponds to the first five * terms in asymptoic formula for * log Gamma (y) - (y-0.5)log(y) + y - 0.5 log(2*pi); * See Abramowitz and Stegun, eq 6.1.40 */ /* Note below: two Stirling's are added, and two are * subtracted. In both K+S, and in the ranlib * implementation, all four are added. I (jt) believe that * is a mistake -- this has been confirmed by personal * correspondence w/ Dr. Kachitvichyanukul. Note, however, * the corrections are so small, that I couldn't find an * example where it made a difference that could be * observed, let alone tested. In fact, define'ing Stirling * to be zero gave identical results!! In practice, alv is * O(1), ranging 0 to -10 or so, while the Stirling * correction is typically O(10^{-5}) ...setting the * correction to zero gives about a 2% performance boost; * might as well keep it just to be pendantic. */ { double x1 = ix + 1.0; double w1 = n - ix + 1.0; double f1 = fm + 1.0; double z1 = n + 1.0 - fm; accept = xm * log (f1 / x1) + (n - m + 0.5) * log (z1 / w1) + (ix - m) * log (w1 * p / (x1 * q)) + Stirling (f1) + Stirling (z1) - Stirling (x1) - Stirling (w1); } #endif #endif } if (var <= accept) { goto Finish; } else { goto TryAgain; } } Finish: return (flipped) ? (n - ix) : (unsigned int)ix; }
{ "alphanum_fraction": 0.5205723125, "avg_line_length": 33.8481675393, "ext": "c", "hexsha": "d32423ccf35e78c7beb1ae3ab1c001cc076b6da7", "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/randist/binomial_tpe.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/binomial_tpe.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/randist/binomial_tpe.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": 3670, "size": 12930 }
/* monte/gsl_monte_plain.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 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. */ /* Plain Monte-Carlo. */ /* Author: MJB */ #ifndef __GSL_MONTE_PLAIN_H__ #define __GSL_MONTE_PLAIN_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 <stdio.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_rng.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 dim; double *x; } gsl_monte_plain_state; GSL_FUN int gsl_monte_plain_integrate (const gsl_monte_function * f, const double xl[], const double xu[], const size_t dim, const size_t calls, gsl_rng * r, gsl_monte_plain_state * state, double *result, double *abserr); GSL_FUN gsl_monte_plain_state* gsl_monte_plain_alloc(size_t dim); GSL_FUN int gsl_monte_plain_init(gsl_monte_plain_state* state); GSL_FUN void gsl_monte_plain_free (gsl_monte_plain_state* state); __END_DECLS #endif /* __GSL_MONTE_PLAIN_H__ */
{ "alphanum_fraction": 0.6942764076, "avg_line_length": 28.2763157895, "ext": "h", "hexsha": "a62879650bc67801f863cb9c46c93ab9de484c42", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_monte_plain.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_monte_plain.h", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_monte_plain.h", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "num_tokens": 541, "size": 2149 }
#pragma once #include <tuple> #include "arcana/threading/dispatcher.h" #include "router.h" #include <gsl/gsl> namespace arcana { // // A mediator is an event pool that ensures all events are sent // through the right dispatcher (execution context). // This is usefull when you want anyone to be able to send // events but only want to process the events from one thread. // template<typename DispatcherT, typename... EventTs> class mediator { using router_t = router<EventTs...>; public: using dispatcher_t = DispatcherT; explicit mediator(dispatcher_t& dispatcher) : m_dispatcher{ dispatcher } {} template<typename T> void send(T&& evt) { m_dispatcher.queue([ this, evt = std::forward<T>(evt) ]() { m_router.fire(evt); }); } template<typename EventT, typename T> ticket add_listener(T&& listener) { GSL_CONTRACT_CHECK("thread affinity", m_dispatcher.get_affinity().check()); return m_router.template add_listener<EventT>(std::forward<T>(listener)); } dispatcher_t& dispatcher() { return m_dispatcher; } private: dispatcher_t& m_dispatcher; router_t m_router; }; }
{ "alphanum_fraction": 0.6068181818, "avg_line_length": 24.4444444444, "ext": "h", "hexsha": "5a28911375818020a3d40039ff48d24f9e482b13", "lang": "C", "max_forks_count": 18, "max_forks_repo_forks_event_max_datetime": "2021-12-26T14:24:29.000Z", "max_forks_repo_forks_event_min_datetime": "2019-05-09T23:07:44.000Z", "max_forks_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andrei-datcu/arcana.cpp", "max_forks_repo_path": "Source/Shared/arcana/messaging/mediator.h", "max_issues_count": 12, "max_issues_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_issues_repo_issues_event_max_datetime": "2022-01-03T20:12:24.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-13T03:18:30.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "andrei-datcu/arcana.cpp", "max_issues_repo_path": "Source/Shared/arcana/messaging/mediator.h", "max_line_length": 95, "max_stars_count": 65, "max_stars_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andrei-datcu/arcana.cpp", "max_stars_repo_path": "Source/Shared/arcana/messaging/mediator.h", "max_stars_repo_stars_event_max_datetime": "2022-03-25T15:05:38.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-08T01:53:22.000Z", "num_tokens": 280, "size": 1320 }
/** * * @file core_dlatro.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Azzam Haidar * @date 2010-11-15 * @generated d Tue Jan 7 11:44:49 2014 * **/ #include <lapacke.h> #include "common.h" /***************************************************************************//** * * @ingroup CORE_double * * CORE_dlatro transposes a m-by-n matrix out of place. * ******************************************************************************* * * @param[in] uplo * Specifies whether the matrix A is upper triangular or lower * triangular: * = PlasmaUpper: the upper triangle of A and the lower triangle of B * are referenced. * = PlasmaLower: the lower triangle of A and the upper triangle of B * are referenced. * = PlasmaUpperLower: All A and B are referenced. * * @param[in] trans * Specifies whether the matrix A is transposed, not transposed or * ugate transposed: * = PlasmaNoTrans: B is a copy of A (equivalent to dlacpy); * = PlasmaTrans: B is the transpose of A; * = PlasmaTrans: B is the ugate transpose of A. * * @param[in] M * Number of rows of the matrix A and number of columns of the matrix B, if trans == Pasma[Conj]Trans. * Number of rows of the matrix A and the matrix B, if trans == PasmaNoTrans. * * @param[in] N * Number of columns of the matrix A and number of rows of the matrix B, if trans == Pasma[Conj]Trans. * Number of columns of the matrix A and of the matrix B, if trans == PlasmaNoTrans. * * @param[in] A * Matrix of size LDA-by-N, if trans == Pasma[Conj]Trans. * Matrix of size LDA-by-M, if trans == PasmaNoTrans. * * @param[in] LDA * The leading dimension of the array A. * LDA >= max(1,M), if trans == Pasma[Conj]Trans. * LDA >= max(1,N), if trans == PasmaNoTrans. * * @param[out] B * Matrix of size LDB-by-M, if trans == Pasma[Conj]Trans. * Matrix of size LDB-by-N, if trans == PasmaNoTrans. * * @param[in] LDB * The leading dimension of the array B. * LDB >= max(1,N), if trans == Pasma[Conj]Trans. * LDB >= max(1,M), if trans == PasmaNoTrans. * * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if INFO = -k, the k-th argument had an illegal value * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_dlatro = PCORE_dlatro #define CORE_dlatro PCORE_dlatro #endif int CORE_dlatro(PLASMA_enum uplo, PLASMA_enum trans, int M, int N, const double *A, int LDA, double *B, int LDB) { int i, j; /* Check input arguments */ if ((uplo != PlasmaUpper) && (uplo != PlasmaLower) && (uplo != PlasmaUpperLower) ) { coreblas_error(1, "Illegal value of uplo"); return -1; } if ((trans != PlasmaTrans) && (trans != PlasmaNoTrans) && (trans != PlasmaTrans) ) { coreblas_error(2, "Illegal value of trans"); return -2; } if (M < 0) { coreblas_error(3, "Illegal value of M"); return -3; } if (N < 0) { coreblas_error(4, "Illegal value of N"); return -4; } if ( (LDA < max(1,M)) && (M > 0) ) { coreblas_error(6, "Illegal value of LDA"); return -6; } if ( (LDB < max(1,N)) && (N > 0) ) { coreblas_error(8, "Illegal value of LDB"); return -8; } if (trans == PlasmaNoTrans) { CORE_dlacpy(uplo, M, N, A, LDA, B, LDB); } else { if (trans == PlasmaTrans) { if(uplo == PlasmaUpper) { for(j=0; j<N; j++) for(i=0; i<min(j+1,M); i++) B[j+i*LDB] = (A[i+j*LDA]); } else if(uplo == PlasmaLower) { for(j=0;j<N;j++) for(i=j;i<M;i++) B[j+i*LDB] = (A[i+j*LDA]); } else { for(j=0;j<N;j++) for(i=0;i<M;i++) B[j+i*LDB] = (A[i+j*LDA]); } } else { if(uplo==PlasmaUpper) { for(j=0;j<N;j++) for(i=0;i<min(j+1,M);i++) B[j+i*LDB] = A[i+j*LDA]; } else if(uplo==PlasmaLower) { for(j=0;j<N;j++) for(i=j;i<M;i++) B[j+i*LDB] = A[i+j*LDA]; } else { for(j=0;j<N;j++) for(i=0;i<M;i++) B[j+i*LDB] = A[i+j*LDA]; } } } return PLASMA_SUCCESS; }
{ "alphanum_fraction": 0.471092504, "avg_line_length": 32.3612903226, "ext": "c", "hexsha": "23aa5161a11ef4e0d77b1590a3e9f203934ddcac", "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_dlatro.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_dlatro.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": "core_blas/core_dlatro.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1346, "size": 5016 }
/* * TableFunction.h * * Author: * Oleg Kalashev * * Copyright (c) 2020 Institute for Nuclear Research, RAS * * 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 TABLEFUNCTION_H_ #define TABLEFUNCTION_H_ #include <iostream> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include "MathUtils.h" #include "TableReader.h" namespace Utils { template<typename X = double > class IScale { public: virtual X ToScale(X aX) = 0; virtual X FromScale(X aXprime) = 0; virtual IScale<X>* Clone() const = 0; virtual ~IScale(){} }; template<typename X = double > class LogScaleX : public IScale<X> { public: X ToScale(X aX); X FromScale(X aXprime); IScale<X>* Clone() const; }; typedef LogScaleX<double> LogScale; template<typename X = double > class TableFunctionX : public SmartReferencedObj, virtual public FunctionX<X>{ public: static int FindLeftX(const std::vector<X>&, X xValue); TableFunctionX(const std::vector<X>& _x, const std::vector<X>& _y, X _leftVal=0., X _rightVal=0.); //takes ownership of aXscale and aYscale TableFunctionX(const std::vector<X>& _x, const std::vector<X>& _y, IScale<X>* aXscale, IScale<X>* aYscale, X _leftVal=0., X _rightVal=0.); //stores smart ref to aReader TableFunctionX(TableReaderX<X>* aReader, X _leftVal=0., X _rightVal=0.); bool InTableRange(X aArg) const; virtual X f(X _x) const; virtual X f_scaled(X _x) const = 0; virtual X Xmin() const; virtual X Xmax() const; void SetAutoLimits(); void Print(std::ostream& aOut, X aXcoef=1., X aYcoef=1.); private: //common part of constructors void Init(); protected: int FindLeftX(X xValue) const; //used for cloning TableFunctionX(const TableFunctionX<X>& aTableFunction); std::vector<X> fCloneX; std::vector<X> fCloneY; const std::vector<X>& m_x; const std::vector<X>& m_y; X m_leftVal; X m_rightVal; SafePtr<IScale<X> > fXscale; SafePtr<IScale<X> > fYscale; SmartPtr<TableReaderX<X> > fTable; X fXmin; X fXmax; }; typedef TableFunctionX<double> TableFunction; template<typename X = double > class LinearFuncX : public TableFunctionX<X> { public: LinearFuncX(const std::vector<X>& _x,const std::vector<X>& _y, X _leftVal=0., X _rightVal=0.): TableFunctionX<X>(_x, _y, _leftVal, _rightVal) {}; //stores smart ref to aReader LinearFuncX(TableReaderX<X>* aReader, X _leftVal=0., X _rightVal=0.): TableFunctionX<X>(aReader,_leftVal,_rightVal) {}; //takes ownership of aXscale and aYscale LinearFuncX(const std::vector<X>& _x,const std::vector<X>& _y, IScale<X>* aXscale, IScale<X>* aYscale, X _leftVal=0., X _rightVal=0.): TableFunctionX<X>(_x, _y, aXscale, aYscale, _leftVal, _rightVal) {} X f_scaled(X _x) const; FunctionX<X>* Clone() const { return new LinearFuncX<X>(*this); } protected: LinearFuncX(const TableFunctionX<X>& aTableFunction): TableFunctionX<X>(aTableFunction) {}; }; typedef LinearFuncX<double> LinearFunc; class GSLTableFunc : public TableFunction { public: GSLTableFunc(const Vector& _x, const Vector& _y, const gsl_interp_type * aInterpType=gsl_interp_linear, double _leftVal=0., double _rightVal=0.): TableFunction(_x, _y, _leftVal, _rightVal),fAcc(0),fSpline(0) {Init(aInterpType);} //stores smart ref to aReader GSLTableFunc(TableReader *aReader, const gsl_interp_type * aInterpType=gsl_interp_linear, double _leftVal=0., double _rightVal=0.): TableFunction(aReader,_leftVal,_rightVal),fAcc(0),fSpline(0) {Init(aInterpType);} //takes ownership of aXscale and aYscale //_x and _y are values are modified with scale functions given by aXscale and aYscale parameters GSLTableFunc(const Vector& _x, const Vector& _y, IScale<double>* aXscale, IScale<double>* aYscale, const gsl_interp_type * aInterpType=gsl_interp_linear, double _leftVal=0., double _rightVal=0.): TableFunction(_x, _y, aXscale, aYscale, _leftVal, _rightVal) {Init(aInterpType);} virtual ~GSLTableFunc(); double f_scaled(double _x) const; Function* Clone() const { return new GSLTableFunc(*this); } protected: GSLTableFunc(const GSLTableFunc& aTableFunction): TableFunction(aTableFunction) {Init(aTableFunction.fSpline->interp->type);}; private: void Init(const gsl_interp_type * aInterpType); gsl_interp_accel *fAcc; gsl_spline *fSpline; const gsl_interp_type *fInterpType; }; template<typename X = double > class MatrixFunctionX : public Function2X<X> { public: MatrixFunctionX(const std::string& aFile) { std::ifstream dataFile(aFile.c_str()); if(!dataFile) Exception::Throw("Failed to open " + aFile); std::string header; std::getline(dataFile, header); int logscX,logscY; const char* headerFormat = "# minX=%lg stepX=%lg logscaleX=%d minY=%lg stepY=%lg logscaleY=%d"; if(sscanf(header.c_str(),headerFormat, &xMin,&xStep,&logscX,&yMin,&yStep,&logscY)!=6) Exception::Throw("Invalid header format in " + aFile + "\nExpected format: " + headerFormat); logScaleX = (bool)logscX; logScaleY = (bool)logscY; if((logScaleX && (xMin<=0 || xStep<=1.))||xStep<=0.) Exception::Throw("Invalid X scale in " + aFile); if((logScaleY && (yMin<=0 || yStep<=1.))||yStep<=0.) Exception::Throw("Invalid Y scale in " + aFile); fData = new TableReaderX<X>(dataFile, TableReader::Auto); nCols = fData->numberOfColumns(); if(logScaleX) { xMax = xMin*pow(xStep,nCols-1); xStep = log(xStep);//convert multiplier to log step } else{ xMax = xMin + xStep*(nCols-1); } nRows = fData->getColumn(0).size(); if(logScaleY){ yMax = yMin*pow(yStep,nRows-1); yStep = log(yStep);//convert multiplier to log step } else{ yMax = yMin + yStep*(nRows-1); } } X f(double x, double y) const { double binX, binY; if(logScaleX) {//log scale binX = log(x/xMin)/xStep; } else {//linear scale binX = (x-xMin)/xStep; } if(binX<0. || binX>nCols-1) return 0.; if(logScaleY) {//log scale binY = log(y/yMin)/yStep; } else {//linear scale binY = (y-yMin)/yStep; } if(binY<0. || binY>nRows-1) return 0.; int iX = floor(binX); int iY = floor(binY); double weightX = 1.-binX+iX; double weightY = 1.-binY+iY; //linear f interpolation //TODO implement logscale f interpolation double f_11 = fData->getColumn(iX)[iY]*weightX*weightY; double f_21 = (weightX<1.)? (fData->getColumn(iX+1)[iY]*(1.-weightX)*weightY) : 0.; double f_12 = (weightY<1.)? (fData->getColumn(iX)[iY+1]*weightX*(1.-weightY)) : 0.; double f_22 = (weightX<1.&&weightY<1.)?(fData->getColumn(iX+1)[binY+1]*(1.-weightX)*(1.-weightY)) : 0.; double result = f_11 + f_21 + f_12 + f_22; return result; } virtual X MinArg(int aArgNo) const {return aArgNo==1?xMin:yMin;}; virtual X MaxArg(int aArgNo) const {return aArgNo==1?xMax:yMax;} private: SafePtr<TableReaderX<X> > fData; X xMin; X yMin; X xMax; X yMax; X xStep; X yStep; int nCols; int nRows; bool logScaleX; bool logScaleY; }; typedef MatrixFunctionX<double> MatrixFunction; } /* namespace Utils */ #endif /* TABLEFUNCTION_H_ */
{ "alphanum_fraction": 0.7054205607, "avg_line_length": 30.6297709924, "ext": "h", "hexsha": "f29c7d38dde01184b3236a6ba10f36e0379cdf41", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-01-10T21:05:54.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-16T08:23:34.000Z", "max_forks_repo_head_hexsha": "2cfa58d2cd6f872612f6396d65781ad83211c06c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alexkorochkin/mcray", "max_forks_repo_path": "src/lib/TableFunction.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2cfa58d2cd6f872612f6396d65781ad83211c06c", "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": "alexkorochkin/mcray", "max_issues_repo_path": "src/lib/TableFunction.h", "max_line_length": 196, "max_stars_count": 7, "max_stars_repo_head_hexsha": "2cfa58d2cd6f872612f6396d65781ad83211c06c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alexkorochkin/mcray", "max_stars_repo_path": "src/lib/TableFunction.h", "max_stars_repo_stars_event_max_datetime": "2022-01-15T22:56:26.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-16T08:23:31.000Z", "num_tokens": 2498, "size": 8025 }
#ifndef VMICORE_VMIINITDATA_H #define VMICORE_VMIINITDATA_H #include <filesystem> #include <gsl/pointers> #include <libvmi/libvmi.h> class VmiInitData { public: gsl::owner<vmi_init_data_t*> data{}; explicit VmiInitData(const std::filesystem::path& socketPath); ~VmiInitData(); }; #endif // VMICORE_VMIINITDATA_H
{ "alphanum_fraction": 0.7432024169, "avg_line_length": 17.4210526316, "ext": "h", "hexsha": "a5e95e7f24513586fc8b061b1829452edb4da46a", "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": "68c9d9791c3b291ec2b49ffd8191c9cdf335baf3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "GDATASoftwareAG/smartvmi", "max_forks_repo_path": "vmicore/src/vmi/VmiInitData.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "68c9d9791c3b291ec2b49ffd8191c9cdf335baf3", "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": "GDATASoftwareAG/smartvmi", "max_issues_repo_path": "vmicore/src/vmi/VmiInitData.h", "max_line_length": 66, "max_stars_count": 5, "max_stars_repo_head_hexsha": "68c9d9791c3b291ec2b49ffd8191c9cdf335baf3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "GDATASoftwareAG/smartvmi", "max_stars_repo_path": "vmicore/src/vmi/VmiInitData.h", "max_stars_repo_stars_event_max_datetime": "2022-02-21T12:36:45.000Z", "max_stars_repo_stars_event_min_datetime": "2022-02-17T23:35:08.000Z", "num_tokens": 101, "size": 331 }
/* * 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. */ #include "common/c_math/linalg.h" #include <assert.h> #include <float.h> #include <math.h> #include <stddef.h> #include <stdint.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_permute_vector.h> #include <gsl/gsl_vector.h> #include "common/c_math/gsl_linalg_extra.h" #include "common/c_math/linalg_common.h" #if defined(__arm__) // Turn off any error handling by the GSL library. The standard way // of doing this is with gsl_set_error_handler_off; however this // method does not require bringing in more components of GSL. void gsl_error(const char *reason, const char *file, int line, int gsl_errno) { (void)reason; (void)file; (void)line; (void)gsl_errno; } #endif // defined(__arm__) // Operations on vectors with any number of elements. bool VecIsSize(const Vec *v, int32_t l) { return v != NULL && l == v->length; } double *VecPtr(const Vec *v, int32_t i) { assert(0 <= i && i < v->length); return &v->d[i]; } double VecGet(const Vec *v, int32_t i) { assert(0 <= i && i < v->length); return v->d[i]; } // v = [0, 0, ... ] const Vec *VecZero(Vec *v) { for (int32_t i = 0; i < v->length; ++i) { v->d[i] = 0.0; } return v; } // v_out = a*v + v_out const Vec *VecAxpy(double a, const Vec *v, Vec *v_out) { assert(v->length == v_out->length); for (int32_t i = 0; i < v->length; ++i) { v_out->d[i] += a * v->d[i]; } return v_out; } // Changes the length of a vector. Returns true on success, false // otherwise. bool VecResize(int32_t length, Vec *v) { if (v->length == length) { return true; } else if (v->variable_len && 0 <= length && length <= v->max_length) { v->length = length; return true; } assert(false); return false; } // v_out = v_in const Vec *VecCopy(const Vec *v_in, Vec *v_out) { VecResize(v_in->length, v_out); for (int32_t i = 0; i < v_out->length; ++i) { v_out->d[i] = v_in->d[i]; } return v_out; } // Copy the contents of an array in a Vec. const Vec *VecInit(const double a_in[], int32_t length, Vec *v_out) { VecResize(length, v_out); for (int32_t i = 0; i < v_out->length; ++i) { v_out->d[i] = a_in[i]; } return v_out; } // v_out = scale * v_in const Vec *VecScale(const Vec *v_in, double scale, Vec *v_out) { VecResize(v_in->length, v_out); for (int32_t i = 0; i < v_in->length; ++i) { v_out->d[i] = scale * v_in->d[i]; } return v_out; } // v_out = v0 + v1 const Vec *VecAdd(const Vec *v0, const Vec *v1, Vec *v_out) { assert(v0->length == v1->length); VecResize(v0->length, v_out); for (int32_t i = 0; i < v_out->length; ++i) { v_out->d[i] = v0->d[i] + v1->d[i]; } return v_out; } // v_out = v0 + v1 + v2 const Vec *VecAdd3(const Vec *v0, const Vec *v1, const Vec *v2, Vec *v_out) { assert(v0->length == v1->length && v0->length == v2->length); VecResize(v0->length, v_out); for (int32_t i = 0; i < v_out->length; ++i) { v_out->d[i] = v0->d[i] + v1->d[i] + v2->d[i]; } return v_out; } // v_out = v0 - v1 const Vec *VecSub(const Vec *v0, const Vec *v1, Vec *v_out) { assert(v0->length == v1->length); VecResize(v0->length, v_out); for (int32_t i = 0; i < v_out->length; ++i) { v_out->d[i] = v0->d[i] - v1->d[i]; } return v_out; } // v_out = c0 * v0 + c1 * v1 const Vec *VecLinComb(double c0, const Vec *v0, double c1, const Vec *v1, Vec *v_out) { assert(v0->length == v1->length); VecResize(v0->length, v_out); for (int32_t i = 0; i < v_out->length; ++i) { v_out->d[i] = c0 * v0->d[i] + c1 * v1->d[i]; } return v_out; } // v_out = c0 * v0 + c1 * v1 + c2 * v2 const Vec *VecLinComb3(double c0, const Vec *v0, double c1, const Vec *v1, double c2, const Vec *v2, Vec *v_out) { assert(v0->length == v1->length && v0->length == v2->length); VecResize(v0->length, v_out); for (int32_t i = 0; i < v_out->length; ++i) { v_out->d[i] = c0 * v0->d[i] + c1 * v1->d[i] + c2 * v2->d[i]; } return v_out; } // v_out = v0 .* v1 const Vec *VecMult(const Vec *v0, const Vec *v1, Vec *v_out) { assert(v0->length == v1->length); VecResize(v0->length, v_out); for (int32_t i = 0; i < v_out->length; ++i) { v_out->d[i] = v0->d[i] * v1->d[i]; } return v_out; } // v0^T * v1 double VecDot(const Vec *v0, const Vec *v1) { assert(v0->length == v1->length); double tmp = 0.0; for (int32_t i = 0; i < v0->length; ++i) { tmp += v0->d[i] * v1->d[i]; } return tmp; } // Computes the 2-norm of a vector. // // TODO: This does not yet handle overflow and underflow // gracefully. double VecNorm(const Vec *v) { return sqrt(VecNormSquared(v)); } double VecNormBound(const Vec *v, double low) { return fmax(low, VecNorm(v)); } double VecNormSquared(const Vec *v) { return VecDot(v, v); } const Vec *VecNormalize(const Vec *v_in, Vec *v_out) { return VecScale(v_in, 1.0 / VecNormBound(v_in, 1e-9), v_out); } // Return the elements of v_in where inds != 0. The MATLAB logical indexing // equivalent is: v_out = v_in(inds). const Vec *VecSlice(const Vec *v_in, const int32_t inds[], Vec *v_out) { int32_t i_out = 0; for (int32_t i = 0; i < v_in->length; ++i) { if (inds[i]) { assert(i_out < v_out->max_length); // Don't use VecPtr here because we haven't set v_out->length yet. v_out->d[i_out] = VecGet(v_in, i); i_out++; } } // Do not resize v_out until the end of the function if you want to // be able to reuse and input as an output. VecResize(i_out, v_out); return v_out; } // Assigns elements of a larger vector with those from a smaller one. The // MATLAB logical indexing equivalent is: v_out(inds) = v_in. The sum(inds != 0) // must be equal to length(v_in). Warning: there is no check that // length(inds) == length(v_out). const Vec *VecSliceSet(const Vec *v_in, const int32_t inds[], Vec *v_out) { assert(v_in != v_out); int32_t i_in = 0; for (int32_t i = 0; i < v_out->length; ++i) { if (inds[i]) { *VecPtr(v_out, i) = VecGet(v_in, i_in); i_in++; } } // Assert that the sum(inds != 0) is equal to length(v_in). assert(v_in->length == i_in); return v_out; } // Operations on arbitrary matrices. bool MatIsSize(const Mat *m, int32_t nr, int32_t nc) { return m != NULL && m->nr == nr && m->nc == nc; } double *MatPtr(const Mat *m, int32_t i, int32_t j) { assert(i < m->nr && j < m->nc); return &m->d[i * m->nc + j]; } double MatGet(const Mat *m, int32_t i, int32_t j) { assert(i < m->nr && j < m->nc); return m->d[i * m->nc + j]; } bool MatResize(int32_t nr, int32_t nc, Mat *m) { if (m->nr == nr && m->nc == nc) { return true; } else if (m->variable_dim && nr * nc <= m->max_size) { m->nr = nr; m->nc = nc; return true; } assert(false); return false; } // Copy the contents of an array into a Mat. const Mat *MatInit(const double *d, int32_t nr, int32_t nc, Mat *m) { MatResize(nr, nc, m); for (int32_t i = 0; i < m->nr; ++i) { for (int32_t j = 0; j < m->nc; ++j) { *MatPtr(m, i, j) = d[i * m->nc + j]; } } return m; } // m_out = scale * m_in const Mat *MatScale(const Mat *m_in, double scale, Mat *m_out) { MatResize(m_in->nr, m_in->nc, m_out); for (int32_t i = 0; i < m_out->nr; ++i) { for (int32_t j = 0; j < m_out->nc; ++j) { *MatPtr(m_out, i, j) = scale * MatGet(m_in, i, j); } } return m_out; } const Mat *MatZero(Mat *m) { MatArrZero(m->nr, m->nc, m->d); return m; } const Mat *MatCopy(const Mat *a, Mat *b) { if (a != b) { // No work to do if the Mat pointers are equal. MatResize(a->nr, a->nc, b); // This is still safe if the data pointers are equal. MatArrCopy(a->d, a->nr, a->nc, b->d); } return b; } // Copies the sub-matrix src(start_row + (1:num_rows), start_col + (1:num_cols)) // into dest(dest_row + (1:num_rows), dest_col + (1:num_cols)). // // It is not safe for src and dest to share any memory. // // Returns: // A pointer to dest. const Mat *MatSubmatSet(const Mat *src, int32_t start_row, int32_t start_col, int32_t num_rows, int32_t num_cols, int32_t dest_row, int32_t dest_col, Mat *dest) { assert(src != dest && src->d != dest->d); assert(start_row >= 0 && start_col >= 0); assert(num_rows >= 0 && num_cols >= 0); assert(dest_row >= 0 && dest_col >= 0); // Make sure there is sufficient data and sufficient room. assert(src->nr >= start_row + num_rows && src->nc >= start_col + num_cols); assert(dest->nr >= dest_row + num_rows && dest->nc >= dest_col + num_cols); for (int32_t i = 0; i < num_rows; ++i) { for (int32_t j = 0; j < num_cols; ++j) { *MatPtr(dest, dest_row + i, dest_col + j) = MatGet(src, i + start_row, j + start_col); } } return dest; } const Mat *MatI(int32_t n, Mat *m) { MatResize(n, n, m); MatArrI(n, m->d); return m; } const Mat *MatMult(const Mat *m1, const Mat *m2, Mat *m_out) { assert(m1->nc == m2->nr); MatResize(m1->nr, m2->nc, m_out); MatArrMult(m1->d, m1->nr, m1->nc, m2->d, m2->nc, m_out->d); return m_out; } // Generalized matrix-vector multiply. // // z = alpha*op(a)*x + beta*y. // // Args: // ta: Indicates if a should be transposed. // alpha, a, x, beta: See formula above. // y: Can be NULL if beta = 0.0. // z: Resulting vector. It is safe to reuse y as z. const Vec *MatVecGenMult(TransposeType ta, double alpha, const Mat *a, const Vec *x, double beta, const Vec *y, Vec *z) { assert(a != NULL && x != NULL && z != NULL); assert((ta == kNoTrans ? a->nc : a->nr) == x->length); const int32_t zl = (ta == kNoTrans) ? a->nr : a->nc; assert(y == NULL || y->length == zl); assert(y != NULL || beta == 0.0); if (y == NULL) beta = 0.0; if (y == NULL || beta == 0.0) { VecResize(zl, z); } else { VecCopy(y, z); } MatArrGemv(ta, alpha, a->d, a->nr, a->nc, x->d, beta, z->d); return z; } // Generalized matrix-matrix multiply. // // d = alpha*op(a)*op(b) + beta*c. // // Args: // ta: Indicates if a should be transposed. // tb: Indicates if b should be transposed. // alpha, a, b, beta: See above formula. // c: Can be NULL if beta = 0.0. // d: Resulting matrix. It is safe to reuse c as d. const Mat *MatGenMult(TransposeType ta, TransposeType tb, double alpha, const Mat *a, const Mat *b, double beta, const Mat *c, Mat *d) { assert(a != NULL && b != NULL && d != NULL); assert((ta == kNoTrans ? a->nc : a->nr) == (tb == kNoTrans ? b->nr : b->nc)); const int32_t nr_d = (ta == kNoTrans ? a->nr : a->nc); const int32_t nc_d = (tb == kNoTrans ? b->nc : b->nr); assert(c == NULL || (c->nr == nr_d && c->nc == nc_d)); assert(c != NULL || beta == 0.0); if (c == NULL) beta = 0.0; if (c == NULL || beta == 0.0) MatResize(nr_d, nc_d, d); else MatCopy(c, d); MatArrGemm(ta, tb, alpha, a->d, a->nr, a->nc, b->d, nc_d, beta, d->d); return d; } const Mat *MatMult3(const Mat *m0, const Mat *m1, const Mat *m2, Mat *m_out) { assert(m0->nc == m1->nr && m1->nc == m2->nr); MatResize(m0->nr, m2->nc, m_out); MAT(m0->nr, m1->nc, m0m1); return MatMult(MatMult(m0, m1, &m0m1), m2, m_out); } const Vec *MatVecMult(const Mat *m, const Vec *v_in, Vec *v_out) { assert(m->nc == v_in->length); VecResize(m->nr, v_out); MatArrMult(m->d, m->nr, m->nc, v_in->d, 1, v_out->d); return v_out; } const Vec *MatTransVecMult(const Mat *m, const Vec *v_in, Vec *v_out) { assert(m->nr == v_in->length); VecResize(m->nc, v_out); MatArrGemm(kTrans, kNoTrans, 1.0, m->d, m->nr, m->nc, v_in->d, 1, 0.0, v_out->d); return v_out; } const Mat *MatTrans(const Mat *m, Mat *m_out) { MatResize(m->nc, m->nr, m_out); MatArrTrans(m->d, m->nr, m->nc, m_out->d); return m_out; } const Mat *MatAdd(const Mat *m0, const Mat *m1, Mat *m_out) { assert(m0->nr == m1->nr && m0->nc == m1->nc); MatResize(m0->nr, m0->nc, m_out); for (int32_t i = 0; i < m0->nr; ++i) { for (int32_t j = 0; j < m0->nc; ++j) { *MatPtr(m_out, i, j) = MatGet(m0, i, j) + MatGet(m1, i, j); } } return m_out; } const Mat *MatSub(const Mat *m0, const Mat *m1, Mat *m_out) { assert(m0->nr == m1->nr && m0->nc == m1->nc); MatResize(m0->nr, m0->nc, m_out); for (int32_t i = 0; i < m0->nr; ++i) { for (int32_t j = 0; j < m0->nc; ++j) { *MatPtr(m_out, i, j) = MatGet(m0, i, j) - MatGet(m1, i, j); } } return m_out; } void MatQrDecomp(const Mat *A, Mat *Q, Mat *R) { MatResize(A->nr, A->nc, R); double *Qd = NULL; if (Q != NULL) { MatResize(A->nr, A->nr, Q); Qd = Q->d; } MatArrQrDecomp(A->d, A->nr, A->nc, Qd, R->d); } // Calculates the "thin" singular value decomposition of an m x n // matrix A, defined by: // // A = U * S * V' // // where U is an m x n column-orthogonal matrix (i.e. U'*U = I), S is // an n x n diagonal matrix with non-decreasing elements, and V is an // n x n orthogonal matrix (i.e. V'*V = V*V' = I). The "thin" aspect // is equivalent to MATLAB's "economy" SVD. // // Args: // A: Input m x n matrix with m >= n. // U: Output m x n column-orthogonal matrix. // s: Output n length vector of the diagonal elements of S. // V: Output n x n orthogonal matrix. // // Returns: // kLinalgErrorNone on success and kLinalgErrorMaxIter if GSL's // solver reached its maximum number of iterations. int32_t MatThinSvDecomp(const Mat *A, Mat *U, Vec *s, Mat *V) { assert(A != NULL && U != NULL && s != NULL && V != NULL); assert(A->nc <= VEC_MAX_ELEMENTS); assert(A->nr >= A->nc); MatCopy(A, U); VecResize(A->nc, s); MatResize(A->nc, A->nc, V); double work_data[VEC_MAX_ELEMENTS]; gsl_matrix_view U_gsl = gsl_matrix_view_array(U->d, (size_t)U->nr, (size_t)U->nc); gsl_matrix_view V_gsl = gsl_matrix_view_array(V->d, (size_t)V->nr, (size_t)V->nc); gsl_vector_view s_gsl = gsl_vector_view_array(s->d, (size_t)s->length); gsl_vector_view work = gsl_vector_view_array(work_data, (size_t)s->length); int32_t ret = gsl_linalg_SV_decomp(&U_gsl.matrix, &V_gsl.matrix, &s_gsl.vector, &work.vector); // These are the only errors that gsl_linalg_SV_decomp should ever // return, assuming we're passing in matrices and vectors of the // appropriate sizes. assert(ret == GSL_SUCCESS || ret == GSL_EMAXITER); if (ret == GSL_EMAXITER) { assert(false); return kLinalgErrorMaxIter; } return kLinalgErrorNone; } // Calculates the rank of a matrix. Performs a QR decomposition (with // pivoting) of the input matrix and finds the number of diagonal // elements of R with magnitude greater than a specified tolerance. // // Args: // A: Input matrix. // tol: Tolerance for checking linear independence of vectors. // // Returns: // Rank of the matrix. int32_t MatRank(const Mat *A, double tol) { assert(A != NULL); assert(A->nr * A->nc <= MAT_MAX_ELEMENTS); assert(A->nr <= VEC_MAX_ELEMENTS && A->nc <= VEC_MAX_ELEMENTS); assert(tol >= DBL_EPSILON); int32_t min_dim = (A->nr < A->nc) ? A->nr : A->nc; if (min_dim == 0) return 0; double qr_data[MAT_MAX_ELEMENTS]; double tau_data[VEC_MAX_ELEMENTS]; double norm_data[VEC_MAX_ELEMENTS]; size_t perm_data[VEC_MAX_ELEMENTS]; int signum; gsl_matrix_const_view A_gsl = gsl_matrix_const_view_array(A->d, (size_t)A->nr, (size_t)A->nc); gsl_matrix_view QR = gsl_matrix_view_array(qr_data, (size_t)A->nr, (size_t)A->nc); gsl_vector_view tau = gsl_vector_view_array(tau_data, (size_t)min_dim); gsl_permutation p = {(size_t)A->nc, perm_data}; gsl_vector_view norm = gsl_vector_view_array(norm_data, (size_t)A->nc); gsl_matrix_memcpy(&QR.matrix, &A_gsl.matrix); int32_t ret = gsl_linalg_QRPT_decomp(&QR.matrix, &tau.vector, &p, &signum, &norm.vector); assert(ret == GSL_SUCCESS); (void)ret; int32_t rank = 0; while (rank < min_dim) { if (fabs(gsl_matrix_get(&QR.matrix, (size_t)rank, (size_t)rank)) <= tol) { break; } rank++; } return rank; } // Solves A*x = b for x similar to x = A \ b. int32_t MatVecLeftDivide(const Mat *A, const Vec *b, Vec *x) { assert(A != NULL && b != NULL && x != NULL); assert(b != x); assert(A->nr == b->length && A->nr > 0); VecResize(A->nc, x); if (A->nc == 0) return kLinalgErrorNone; size_t m = (size_t)A->nr, n = (size_t)A->nc; gsl_matrix_const_view A_gsl = gsl_matrix_const_view_array(A->d, m, n); gsl_matrix_const_view b_gsl = gsl_matrix_const_view_array(b->d, m, 1U); gsl_matrix_view x_gsl = gsl_matrix_view_array(x->d, n, 1U); int32_t ret = GslMatrixDivide(CblasLeft, &A_gsl.matrix, &b_gsl.matrix, &x_gsl.matrix); assert(ret == GSL_SUCCESS || ret == GSL_ESING); return (ret == GSL_ESING) ? kLinalgErrorSingularMat : kLinalgErrorNone; } // Solves x*A = b for x similar to x = b / A. int32_t MatVecRightDivide(const Mat *A, const Vec *b, Vec *x) { assert(A != NULL && b != NULL && x != NULL); assert(b != x); assert(A->nc == b->length && A->nc > 0); VecResize(A->nr, x); if (A->nr == 0) return kLinalgErrorNone; size_t m = (size_t)A->nr, n = (size_t)A->nc; gsl_matrix_const_view A_gsl = gsl_matrix_const_view_array(A->d, m, n); gsl_matrix_const_view b_gsl = gsl_matrix_const_view_array(b->d, 1U, n); gsl_matrix_view x_gsl = gsl_matrix_view_array(x->d, 1U, m); int32_t ret = GslMatrixDivide(CblasRight, &A_gsl.matrix, &b_gsl.matrix, &x_gsl.matrix); assert(ret == GSL_SUCCESS || ret == GSL_ESING); return (ret == GSL_ESING) ? kLinalgErrorSingularMat : kLinalgErrorNone; } // Solves A*X = b for X similar to X = A \ B. int32_t MatMatLeftDivide(const Mat *A, const Mat *B, Mat *X) { assert(A != NULL && B != NULL && X != NULL); assert(A != X && B != X); assert(A->nr == B->nr && A->nr > 0); MatResize(A->nc, B->nc, X); if (A->nc == 0) return kLinalgErrorNone; size_t m = (size_t)A->nr, n = (size_t)A->nc, k = (size_t)B->nc; gsl_matrix_const_view A_gsl = gsl_matrix_const_view_array(A->d, m, n); gsl_matrix_const_view B_gsl = gsl_matrix_const_view_array(B->d, m, k); gsl_matrix_view X_gsl = gsl_matrix_view_array(X->d, n, k); int32_t ret = GslMatrixDivide(CblasLeft, &A_gsl.matrix, &B_gsl.matrix, &X_gsl.matrix); assert(ret == GSL_SUCCESS || ret == GSL_ESING); return (ret == GSL_ESING) ? kLinalgErrorSingularMat : kLinalgErrorNone; } // Solves X*A = B for X similar to X = B / A. int32_t MatMatRightDivide(const Mat *A, const Mat *B, Mat *X) { assert(A != NULL && B != NULL && X != NULL); assert(A != X && B != X); assert(A->nc == B->nc && A->nc > 0); MatResize(B->nr, A->nr, X); if (A->nr == 0) return kLinalgErrorNone; size_t m = (size_t)A->nr, n = (size_t)A->nc, k = (size_t)B->nr; gsl_matrix_const_view A_gsl = gsl_matrix_const_view_array(A->d, m, n); gsl_matrix_const_view B_gsl = gsl_matrix_const_view_array(B->d, k, n); gsl_matrix_view X_gsl = gsl_matrix_view_array(X->d, k, m); int32_t ret = GslMatrixDivide(CblasRight, &A_gsl.matrix, &B_gsl.matrix, &X_gsl.matrix); assert(ret == GSL_SUCCESS || ret == GSL_ESING); return (ret == GSL_ESING) ? kLinalgErrorSingularMat : kLinalgErrorNone; } bool MatIsUpperTriangular(const Mat *r) { return MatArrIsUpperTriangular(r->d, r->nr, r->nc); } bool MatIsLowerTriangular(const Mat *l) { return MatArrIsLowerTriangular(l->d, l->nr, l->nc); } bool MatHasNonnegDiag(const Mat *m) { assert(m != NULL); for (int32_t i = 0; i < m->nc && i < m->nr; ++i) { if (MatGet(m, i, i) < 0.0) return false; } return true; } // Calculates the matrix square root of P = A'*A + B'*B by calculating a QR // decomposition, Q*R = [A ; B]. It is assumed that the matrix [A ; B] is full // row rank (i.e. has linearly independent columns). // // Q is an orthogonal matrix and R "trapezoidal matrix", i.e. R = [sqrt_P ; 0] // where sqrt_P is upper triangular. Thus: // P = A'*A + B'*B = [A ; B]'*[A ; B] = [sqrT_P ; 0]'*Q'*Q*[sqrt_P ; 0]. // // Args: // A: na-by-nc matrix. // B: nb-by-nc matrix. // sqrt_P: Upper-triangular matrix with positive diagonal elements such that // sqrt_P'*sqrt_P = P. // // Note: it is safe to reuse A or B as sqrt_P (assuming shapes match). void MatSqrtSum(const Mat *A, const Mat *B, Mat *sqrt_P) { assert(A != NULL && B != NULL && sqrt_P != NULL); assert(A->nc == B->nc); assert(A->nr + B->nr >= A->nc); // This is required for full row rank. MatResize(A->nc, A->nc, sqrt_P); // Define a temporary matrix, stack = [A ; B]. MAT(A->nr + B->nr, A->nc, stack); MatSubmatSet(A, 0, 0, A->nr, A->nc, 0, 0, &stack); MatSubmatSet(B, 0, 0, B->nr, B->nc, A->nr, 0, &stack); MatQrDecomp(&stack, NULL, &stack); MatSubmatSet(&stack, 0, 0, A->nc, A->nc, 0, 0, sqrt_P); // Next, enforce a non-negative diagonal. for (int32_t i = 0; i < sqrt_P->nr; ++i) { if (MatGet(sqrt_P, i, i) < 0.0) { for (int32_t j = i; j < sqrt_P->nc; ++j) { *MatPtr(sqrt_P, i, j) *= -1.0; } } } } int32_t MatMatBackSub(const Mat *R, const Mat *b, Mat *x) { assert(b->nr == R->nr && b->nc == x->nc); assert(x->nr == R->nc); return MatArrBackSub(R->d, R->nr, R->nc, b->d, b->nc, x->d); } int32_t MatMatForwardSub(const Mat *L, const Mat *b, Mat *x) { assert(b->nr == L->nr && b->nc == x->nc); assert(x->nr == L->nc); return MatArrForwardSub(L->d, L->nr, L->nc, b->d, b->nc, x->d); } int32_t MatVecBackSub(const Mat *R, const Vec *b, Vec *x) { assert(b->length == R->nr); assert(x->length == R->nc); return MatArrBackSub(R->d, R->nr, R->nc, b->d, 1, x->d); } int32_t MatVecForwardSub(const Mat *L, const Vec *b, Vec *x) { assert(b->length == L->nr); assert(x->length == L->nc); return MatArrForwardSub(L->d, L->nr, L->nc, b->d, 1, x->d); } // Returns the rows and columns of m where rows != 0 and cols != 0 const Mat *MatSlice(const Mat *m, const int32_t rows[], const int32_t cols[], Mat *m_out) { int32_t nr_out = 0, nc_out = 0; if (rows == NULL) { nr_out = m->nr; } else { for (int32_t i = 0; i < m->nr; ++i) if (rows[i]) nr_out++; } if (cols == NULL) { nc_out = m->nc; } else { for (int32_t i = 0; i < m->nc; ++i) if (cols[i]) nc_out++; } if (m_out->variable_dim) { assert(nr_out * nc_out <= m_out->max_size); } else { assert(m_out->nr == nr_out && m_out->nc == nc_out); } int32_t i_out = 0; for (int32_t i = 0; i < m->nr; ++i) { if (rows == NULL || rows[i]) { int32_t j_out = 0; for (int32_t j = 0; j < m->nc; ++j) { if (cols == NULL || cols[j]) { // Don't use MatPtr here because we haven't set m_out->nc yet. m_out->d[i_out * nc_out + j_out] = MatGet(m, i, j); j_out++; } } i_out++; } } // Do not resize m until the end of the function if you want to be // able to reuse the input as the output. Otherwise, the matrix // indexing in MatGet will be off. MatResize(nr_out, nc_out, m_out); return m_out; } const double *MatArrMult(const double *m1, int32_t nr1, int32_t nc1, const double *m2, int32_t nc2, double *m_out) { assert(m_out != m1 && m_out != m2); return MatArrGemm(kNoTrans, kNoTrans, 1.0, m1, nr1, nc1, m2, nc2, 0.0, m_out); } // This is modeled after the BLAS function GEMV, which calculates: // y <-- alpha*op(A)*x + beta*y, // where op either returns the matrix or its transpose. // // Args: // ta: Whether to transpose A. // alpha: See above formula. // a: Data for A. // nra: Number of rows of A without transpose applied. // nca: Number of columns of A without transpose applied. // x: Data for x. // beta: See above formula. // c: Data for y. const double *MatArrGemv(TransposeType ta, double alpha, const double *a, int32_t nra, int32_t nca, const double *x, double beta, double *y) { assert(x != y); int32_t ly = ((ta == kNoTrans) ? nra : nca); int32_t lx = ((ta == kNoTrans) ? nca : nra); double aij, axj; for (int32_t i = 0; i < ly; ++i) { // For each entry of y. axj = 0.0; for (int32_t j = 0; j < lx; ++j) { // Walk down the row of op(A). aij = (ta == kNoTrans) ? a[i * nca + j] : a[j * nca + i]; axj += aij * x[j]; } if (beta == 0.0) { y[i] = alpha * axj; } else { y[i] = alpha * axj + beta * y[i]; } } return y; } // This is modeled after the BLAS function GEMM, which calculates: // C <-- alpha*op(A)*op(B) + beta*C, // where op either returns the matrix or its transpose. // // Args: // ta: Whether to transpose A. // tb: Whether to transpose B. // alpha: See above formula. // a: Data for A. // nra: Number of rows of A without transpose applied. // nca: Number of columns of A without transpose applied. // b: Data for B. // ncc: Number of columns of C. // beta: See above formula. // c: Data for C. const double *MatArrGemm(TransposeType ta, TransposeType tb, double alpha, const double *a, int32_t nra, int32_t nca, const double *b, int32_t ncc, double beta, double *c) { assert(a != c && b != c); int32_t nrc = (ta == kNoTrans) ? nra : nca; int32_t nk = (ta == kNoTrans) ? nca : nra; double ABij, aik, bkj; for (int32_t i = 0; i < nrc; ++i) { for (int32_t j = 0; j < ncc; ++j) { ABij = 0.0; for (int32_t k = 0; k < nk; ++k) { aik = (ta == kNoTrans) ? a[i * nca + k] : a[k * nca + i]; bkj = (tb == kNoTrans) ? b[k * ncc + j] : b[j * nk + k]; ABij += aik * bkj; } if (beta == 0.0) { c[i * ncc + j] = alpha * ABij; } else { c[i * ncc + j] = alpha * ABij + beta * c[i * ncc + j]; } } } return c; } const double *MatArrZero(int32_t nr, int32_t nc, double *m_out) { for (int32_t i = 0; i < nr; ++i) { for (int32_t j = 0; j < nc; ++j) { m_out[i * nc + j] = 0.0; } } return m_out; } void MatArrCopy(const double *d_in, int32_t nr, int32_t nc, double *d_out) { for (int32_t i = 0; i < nr; ++i) { for (int32_t j = 0; j < nc; ++j) { d_out[i * nc + j] = d_in[i * nc + j]; } } } void MatArrTrans(const double *m_in, int32_t nr, int32_t nc, double *m_out) { assert(m_out != m_in && m_out != NULL); for (int32_t i = 0; i < nr; ++i) { for (int32_t j = 0; j < nc; ++j) { m_out[j * nr + i] = m_in[i * nc + j]; } } } const double *MatArrI(int32_t nr, double *m_out) { MatArrZero(nr, nr, m_out); for (int32_t i = 0; i < nr; ++i) { m_out[i * nr + i] = 1.0; } return m_out; } // QR decomposition. Decompose a matrix into orthogonal and // upper-right-triangular components. // // You may reuse a as r, and you may skip calculating q by passing a // NULL pointer. void MatArrQrDecomp(const double *a, int32_t nr, int32_t nc, double *q, double *r) { assert(q != a && r != q && r != NULL); assert(nr <= VEC_MAX_ELEMENTS && nc <= VEC_MAX_ELEMENTS); double tau_data[VEC_MAX_ELEMENTS]; gsl_matrix_const_view A = gsl_matrix_const_view_array(a, (size_t)nr, (size_t)nc); gsl_matrix_view QR = gsl_matrix_view_array(r, (size_t)nr, (size_t)nc); gsl_vector_view tau = gsl_vector_view_array(tau_data, (nr < nc) ? (size_t)nr : (size_t)nc); gsl_matrix_memcpy(&QR.matrix, &A.matrix); gsl_linalg_QR_decomp(&QR.matrix, &tau.vector); if (q != NULL) { gsl_matrix_view Q = gsl_matrix_view_array(q, (size_t)nr, (size_t)nr); gsl_matrix_view R = gsl_matrix_view_array(r, (size_t)nr, (size_t)nc); gsl_linalg_QR_unpack(&QR.matrix, &tau.vector, &Q.matrix, &R.matrix); } else { for (int32_t i = 1; i < nr; ++i) { for (int32_t j = 0; j < i && j < nc; ++j) { r[i * nc + j] = 0.0; } } } } bool MatArrIsUpperTriangular(const double *r, int32_t nr, int32_t nc) { for (int32_t i = 1; i < nr; ++i) { for (int32_t j = 0; j < i && j < nc; ++j) { if (fabs(r[i * nc + j]) >= DBL_EPSILON) { return false; } } } return true; } bool MatArrIsLowerTriangular(const double *l, int32_t nr, int32_t nc) { for (int32_t i = 0; i < nr; ++i) { for (int32_t j = i + 1; j < nc; ++j) { if (fabs(l[i * nc + j]) >= DBL_EPSILON) { return false; } } } return true; } // Solves R*X = B using back substitution where R is an upper // triangular matrix. If the triangular matrix contains a zero // diagonal element (i.e. the matrix is singular), we set the // corresponding x element to zero. // // Returns kLinalgErrorNone on success and kLinalgErrorSingularMat // if the matrix was singular. // // Note: Confirmed safe to reuse b as x. int32_t MatArrBackSub(const double *r, int32_t nr, int32_t nc, const double *b, int32_t nc_b, double *x) { assert(r != x); assert(nr >= nc); assert(nr >= 0 && nc >= 0 && nc_b >= 0); assert(MatArrIsUpperTriangular(r, nr, nc)); (void)nr; int32_t err = kLinalgErrorNone; // Solve for the k-th column of x. for (int32_t k = 0; k < nc_b; ++k) { // Iterate over the rows of r. for (int32_t i = nc - 1; i >= 0; --i) { if (fabs(r[i * nc + i]) <= DBL_EPSILON) { err = kLinalgErrorSingularMat; x[i * nc_b + k] = 0.0; } else { double sum = 0.0; for (int32_t j = nc - 1; j > i; --j) { sum += x[j * nc_b + k] * r[i * nc + j]; } x[i * nc_b + k] = (b[i * nc_b + k] - sum) / r[i * nc + i]; } } // TODO: If nr > nc, then the bottom of r is all zeros. // Should we test if b has non-zero elements for these rows? } return err; } // Solves L*X = B using forward substitution where L is a lower // triangular matrix. If the triangular matrix contains a zero // diagonal element (i.e. the matrix is singular), we set the // corresponding x element to zero. // // Returns kLinalgErrorNone on success and kLinalgErrorSingularMat // if the matrix is singular. // // Note: Confirmed safe to reuse b as x. int32_t MatArrForwardSub(const double *l, int32_t nr, int32_t nc, const double *b, int32_t nc_b, double *x) { assert(nr <= nc); assert(MatArrIsLowerTriangular(l, nr, nc)); int32_t err = kLinalgErrorNone; for (int32_t k = 0; k < nc_b; ++k) { // Solve for the k-th column of x. for (int32_t i = 0; i < nr; ++i) { // Iterate over the rows of l. if (fabs(l[i * nc + i]) <= DBL_EPSILON) { err = kLinalgErrorSingularMat; x[i * nc_b + k] = 0.0; } else { double sum = 0.0; for (int32_t j = 0; j < i; ++j) { sum += x[j * nc_b + k] * l[i * nc + j]; } x[i * nc_b + k] = (b[i * nc_b + k] - sum) / l[i * nc + i]; } } for (int32_t i = nr; i < nc; ++i) { x[i * nc_b + k] = 0.0; } } return err; }
{ "alphanum_fraction": 0.5940112527, "avg_line_length": 31.4904904905, "ext": "c", "hexsha": "0246d36202731d91f7b4536d70f3ab74d4a0120b", "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": "common/c_math/linalg.c", "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": "common/c_math/linalg.c", "max_line_length": 80, "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": "common/c_math/linalg.c", "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": 10905, "size": 31459 }
/** * * @file testing_ssygv.c * * PLASMA testing routines * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.6.0 * @author Azzam Haidar * @author Hatem Ltaief * @date 2010-11-15 * @generated s Tue Jan 7 11:45:18 2014 * **/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <plasma.h> #include <cblas.h> #include <lapacke.h> #include <core_blas.h> #include "testing_smain.h" #undef COMPLEX #define REAL static int check_orthogonality(int itype, int uplo, int N, float *Z, int LDZ, float *B, float *CHOLB, int LDB, float eps); static int check_reduction(int itype, int uplo, int N, float *D, float *A, int LDA, float *B, int LDB, float *Z, int LDZ, float eps ); static int check_solution(int N, float *E1, float *E2, float eps); int testing_ssygv(int argc, char **argv) { /* Check for number of arguments*/ if (argc != 3) { USAGE("HEGV", "N LDA LDB", " - N : size of the matrices A and B\n" " - LDA : leading dimension of the matrix A\n" " - LDB : leading dimension of the matrix B\n"); return -1; } float eps = LAPACKE_slamch_work('e'); PLASMA_enum vec = PlasmaVec; int N = atoi(argv[0]); int LDA = atoi(argv[1]); int LDB = atoi(argv[2]); int LDQ = LDA; int LDAxN = LDA*N; int LDBxN = LDB*N; int LDQxN = LDQ*N; int info_ortho = 0; int info_solution = 0; int info_reduction = 0; int i, u; float *A1 = (float *)malloc(LDAxN*sizeof(float)); float *A2 = (float *)malloc(LDAxN*sizeof(float)); float *B1 = (float *)malloc(LDBxN*sizeof(float)); float *B2 = (float *)malloc(LDBxN*sizeof(float)); float *Q = (float *)malloc(LDQxN*sizeof(float)); float *Ainit = (float *)malloc(LDAxN*sizeof(float)); float *Binit = (float *)malloc(LDBxN*sizeof(float)); float *W1 = (float *)malloc(N*sizeof(float)); float *W2 = (float *)malloc(N*sizeof(float)); float *work = (float *)malloc(3*N* sizeof(float)); PLASMA_desc *T; /* Check if unable to allocate memory */ if ((!A1)||(!A2)||(!B1)||(!B2)||(!Q)||(!Ainit)||(!Binit)){ printf("Out of Memory \n "); return -2; } PLASMA_Disable(PLASMA_AUTOTUNING); PLASMA_Set(PLASMA_TILE_SIZE, 120); PLASMA_Set(PLASMA_INNER_BLOCK_SIZE, 20); PLASMA_Enable(PLASMA_WARNINGS); PLASMA_Enable(PLASMA_ERRORS); PLASMA_Alloc_Workspace_ssygv(N, N, &T); /*---------------------------------------------------------- * TESTING SSYGV */ /* Initialize A1 and Ainit */ PLASMA_splgsy(0., N, A1, LDA, 5198); PLASMA_slacpy(PlasmaUpperLower, N, N, A1, LDA, Ainit, LDA); /* Initialize B1 and Binit */ PLASMA_splgsy((float)N, N, B1, LDB, 4321 ); PLASMA_slacpy(PlasmaUpperLower, N, N, B1, LDB, Binit, LDB); printf("\n"); printf("------ TESTS FOR PLASMA SSYGV ROUTINE ------- \n"); printf(" Size of the Matrix %d by %d\n", N, N); printf("\n"); printf(" The matrix A is randomly generated for each test.\n"); printf("============\n"); printf(" The relative machine precision (eps) is to be %e \n",eps); printf(" Computational tests pass if scaled residuals are less than 60.\n"); /*---------------------------------------------------------- * TESTING SSYGV */ for (i=0; i<3; i++) { for (u=0; u<2; u++) { memcpy(A2, Ainit, LDAxN*sizeof(float)); memcpy(B2, Binit, LDBxN*sizeof(float)); /* CALL SSYGV with itype= 1, 2, 3 and uplo= L,U */ PLASMA_ssygv(itype[i], vec, uplo[u], N, A2, LDA, B2, LDB, W2, T, Q, LDQ); /* CALL LAPACK to compute eigenvalues. */ memcpy(A1, Ainit, LDAxN*sizeof(float)); memcpy(B1, Binit, LDBxN*sizeof(float)); LAPACKE_ssygv( LAPACK_COL_MAJOR, itype[i], lapack_const(vec), lapack_const(uplo[u]), N, A1, LDA, B1, LDB, W1); /* CHECK */ info_solution = check_solution(N, W1, W2, eps); /* Check the orthogonality, reduction and the eigen solutions */ if (vec == PlasmaVec){ info_ortho = check_orthogonality(itype[i], uplo[u], N, Q, LDQ, Binit, B1, LDB, eps); info_reduction = check_reduction(itype[i], uplo[u], N, W2, Ainit, LDA, Binit, LDB, Q, LDQ, eps ); } if ( (info_ortho == 0) & (info_reduction == 0) & (info_solution == 0)) { printf("***************************************************\n"); printf(" ---- TESTING SSYGV (%s, %s) ...................... PASSED !\n", itypestr[i], uplostr[u]); printf("***************************************************\n"); } else { printf("************************************************\n"); printf(" - TESTING SSYGV (%s, %s) ... FAILED !\n", itypestr[i], uplostr[u]); printf("************************************************\n"); } } } PLASMA_Dealloc_Handle_Tile(&T); free(A1); free(A2); free(B1); free(B2); free(Q); free(Ainit); free(Binit); free(W1); free(W2); free(work); return 0; } /*------------------------------------------------------------------- * Check the orthogonality of Z */ static int check_orthogonality(int itype, int uplo, int N, float *Z, int LDZ, float *B, float *CHOLB, int LDB, float eps) { static float zone = 1.0; static float mzone = -1.0; static float zzero = 0.0; static float done = 1.0; static float mdone = -1.0; PLASMA_enum trans; float normQ, result; int info_ortho; float *work = (float *)malloc(N*sizeof(float)); float *TEMP = (float *)malloc(N*N*sizeof(float)); float *Id = (float *) malloc(N*N*sizeof(float)); char *str; /* Build the idendity matrix */ LAPACKE_slaset_work(LAPACK_COL_MAJOR, 'A', N, N, 0., 1., Id, N); /* Perform orth test*/ if ( itype == 3 ) { /* * if ITYPE = 3, Z**T*inv(B)*Z = I. * inv(B) = inv(L)**T * inv(L) or inv(U)*inv(U)**T */ str = "Z**T*inv(B)*Z"; if( uplo==PlasmaUpper ) { trans = PlasmaTrans; } else { trans = PlasmaNoTrans; } /* Compute inv(L)*Z or inv(U)**T*Z */ LAPACKE_slacpy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpperLower), N, N, Z, LDZ, TEMP, N); cblas_strsm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, (CBLAS_TRANSPOSE)trans, CblasNonUnit, N, N, (zone), CHOLB, LDB, TEMP, N); /* * Compute Z**T*inv(B)*Z-Id = (Z**T*inv(L)**T) * (inv(L)*Z) - Id * * Note: Z**T*inv(L)**T is the ConjTranspose of the previous result, so we use SSYRK */ cblas_ssyrk(CblasColMajor, (CBLAS_UPLO)uplo, CblasTrans, N, N, done, TEMP, N, mdone, Id, N); } else { /* * if ITYPE = 1 or 2, Z**T*B*Z = I; */ str = "Z**T*B*Z"; cblas_ssymm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N, (zone), B, LDB, Z, LDZ, (zzero), TEMP, N); cblas_sgemm(CblasColMajor, CblasTrans, CblasNoTrans, N, N, N, (zone), Z, LDZ, TEMP, N, (mzone), Id , N); } normQ = LAPACKE_slansy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), 'U', N, Id, N, work); result = normQ / (N * eps); printf(" ======================================================\n"); printf(" | Id-%s |_oo / (N*eps) : %15.3E \n",str, result ); printf(" ======================================================\n"); if ( isnan(result) || isinf(result) || (result > 60.0) ) { printf("-- Orthogonality is suspicious ! \n"); info_ortho=1; } else { printf("-- Orthogonality is CORRECT ! \n"); info_ortho=0; } free(work); free(Id); free(TEMP); return info_ortho; } /*------------------------------------------------------------ * Check the reduction */ static int check_reduction(int itype, int uplo, int N, float *D, float *A, int LDA, float *B, int LDB, float *Z, int LDZ, float eps ) { float zone = 1.0; float zzero = 0.0; float mzone = -1.0; float Anorm, Znorm, Rnorm, result; int info_reduction; int i; char *str; float *TEMP = (float *)malloc(N*N*sizeof(float)); float *Residual = (float *)malloc(N*N*sizeof(float)); float *work = (float *)malloc(N*sizeof(float)); if( itype == 1 ) { /* * | A Z - B Z D | / ( |A| |Z| n ulp ) */ str = " A Z - B Z D "; /* Compute TEMP = Z*D */ LAPACKE_slacpy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpperLower), N, N, Z, LDZ, TEMP, N); for (i=0; i<N; i++) { cblas_sscal(N, D[i], TEMP + i*N, 1); } /* Compute Residual = B*Z*D = B*TEMP */ cblas_ssymm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N, (zone), B, LDB, TEMP, N, (zzero), Residual, N); /* Compute A*Z - B*Z*D */ cblas_ssymm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N, (zone), A, LDA, Z, LDZ, (mzone), Residual, N); } else if( itype == 2 ) { /* * | A B Z - Z D | / ( |A| |Z| n ulp ) */ str = " A B Z - Z D "; /* Compute Residual = Z*D */ LAPACKE_slacpy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpperLower), N, N, Z, LDZ, Residual, N); for (i=0; i<N; i++) { cblas_sscal(N, D[i], Residual + i*N, 1); } /* Compute TEMP = B*Z */ cblas_ssymm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N, (zone), B, LDB, Z, LDZ, (zzero), TEMP, N); /* Compute A*B*Z - Z*D = A*TEMP-Residual */ cblas_ssymm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N, (zone), A, LDA, TEMP, N, (mzone), Residual, N); } else { /* * | B A Z - Z D | / ( |A| |Z| n ulp ) */ str = " B A Z - Z D "; /* Compute Residual = Z*D */ LAPACKE_slacpy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpperLower), N, N, Z, LDZ, Residual, N); for (i=0; i<N; i++) { cblas_sscal(N, D[i], Residual + i*N, 1); } /* Compute TEMP = A*Z */ cblas_ssymm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N, (zone), A, LDA, Z, LDZ, (zzero), TEMP, N); /* Compute B*A*Z - Z*D = B*TEMP-Residual */ cblas_ssymm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, N, N, (zone), B, LDB, TEMP, N, (mzone), Residual, N); } Rnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaOneNorm), N, N, Residual, N, work); Anorm = LAPACKE_slansy_work(LAPACK_COL_MAJOR, lapack_const(PlasmaOneNorm), lapack_const(uplo), N, A, LDA, work); Znorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaOneNorm), N, N, Z, LDZ, work); result = Rnorm / ( Anorm * Znorm * N * eps); printf(" ======================================================\n"); printf(" | %s |_oo/(|A|_oo.|Z|_oo.N.eps) : %15.3E \n", str, result ); printf(" ======================================================\n"); if ( isnan(result) || isinf(result) || (result > 60.0) ) { printf("-- Reduction is suspicious ! \n"); info_reduction = 1; } else { printf("-- Reduction is CORRECT ! \n"); info_reduction = 0; } free(TEMP); free(Residual); free(work); return info_reduction; } /*-------------------------------------------------------------- * Check the solution */ static int check_solution(int N, float *E1, float *E2, float eps) { int info_solution, i; float resid; float maxtmp; float maxel = fabs( fabs(E1[0]) - fabs(E2[0]) ); float maxeig = max( fabs(E1[0]), fabs(E2[0]) ); for (i=1; i<N; i++) { resid = fabs(fabs(E1[i])-fabs(E2[i])); maxtmp = max(fabs(E1[i]), fabs(E2[i])); /* Update */ maxeig = max(maxtmp, maxeig); maxel = max(resid, maxel ); } maxel = maxel / (maxeig * N * eps); printf(" ======================================================\n"); printf(" | D - eigcomputed | / (|D| * N * eps) : %15.3E \n", maxel ); printf(" ======================================================\n"); printf("============\n"); printf("Checking the eigenvalues of A\n"); if ( isnan(maxel) || isinf(maxel) || (maxel > 100) ) { printf("-- The eigenvalues are suspicious ! \n"); info_solution = 1; } else{ printf("-- The eigenvalues are CORRECT ! \n"); info_solution = 0; } return info_solution; }
{ "alphanum_fraction": 0.4561712314, "avg_line_length": 34.4733009709, "ext": "c", "hexsha": "c869e95d83758fef5bacacd719d375ecd3b7c4a7", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_path": "testing/testing_ssygv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_path": "testing/testing_ssygv.c", "max_line_length": 123, "max_stars_count": null, "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_path": "testing/testing_ssygv.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4103, "size": 14203 }
#ifndef Two_Group_Diffusion_h #define Two_Group_Diffusion_h #include <vector> // Trilinos includes #include "Kokkos_DefaultNode.hpp" #include "Teuchos_ParameterList.hpp" #include "Teuchos_RCP.hpp" #include "Tpetra_CrsGraph.hpp" #include "Tpetra_CrsMatrix.hpp" #include "Tpetra_MultiVector.hpp" #include "Tpetra_Operator.hpp" #include "Tpetra_RowMatrix.hpp" #include "Tpetra_Vector.hpp" // SCALE includes #include "Nemesis/comm/global.hh" // vendored includes #include <gsl/gsl> // enrico includes #include "Assembly_Model.h" #include "Neutronics_Solver.h" #include "Two_Group_Cross_Sections.h" namespace enrico { //===========================================================================// /*! * \class Two_Group_Diffusion * \brief Two-group, 3D neutron diffusion solver. */ //===========================================================================// class Two_Group_Diffusion : public Neutronics_Solver { public: enum BC_TYPE { VACUUM, REFLECT }; enum FACE { LO_X, HI_X, LO_Y, HI_Y, LO_Z, HI_Z }; //@{ //! Typedefs using XS = Two_Group_Cross_Sections; using XS_Data = XS::XS_Data; using Vec_Dbl = std::vector<double>; using Vec_Int = std::vector<int>; using Vec_BC = std::vector<BC_TYPE>; using SP_Assembly = std::shared_ptr<Assembly_Model>; using Pin_Map = std::vector<Assembly_Model::PIN_TYPE>; using ST = double; using LO = int; using GO = int; using NODE = KokkosClassic::DefaultNode::DefaultNodeType; using MV = Tpetra::MultiVector<ST, LO, GO, NODE>; using VECTOR = Tpetra::Vector<ST, LO, GO, NODE>; using OP = Tpetra::Operator<ST, LO, GO, NODE>; using MAP = Tpetra::Map<LO, GO, NODE>; using MATRIX = Tpetra::CrsMatrix<ST, LO, GO, NODE>; using GRAPH = Tpetra::CrsGraph<LO, GO, NODE>; using RCP_PL = Teuchos::RCP<Teuchos::ParameterList>; //@} private: // >>> DATA SP_Assembly d_assembly; Vec_Dbl d_dx; Vec_Dbl d_dy; Vec_Dbl d_dz; Pin_Map d_pin_map; XS d_xs; size_t d_Nx, d_Ny, d_Nz, d_num_cells; // Solver parameters double d_tol; int d_max_iters; // Boundary conditions Vec_BC d_bcs; // Data stored over single group Teuchos::RCP<MAP> d_map; Teuchos::RCP<GRAPH> d_graph; Teuchos::RCP<MATRIX> d_A_therm, d_A_fast; Teuchos::RCP<VECTOR> d_x_therm, d_x_fast; Teuchos::RCP<VECTOR> d_b_therm, d_b_fast; public: // Constructor Two_Group_Diffusion(SP_Assembly assembly, RCP_PL params, const Vec_Dbl& dz); // Solve virtual void solve(const Vec_Dbl& temperatures, const Vec_Dbl& densities, Vec_Dbl& power) override; private: int cellid(int ix, int iy, int iz) { Expects(ix >= 0); Expects(ix < d_Nx); Expects(iy >= 0); Expects(iy < d_Ny); Expects(iz >= 0); Expects(iz < d_Nz); int cell = ix + d_Nx * (iy + d_Ny * iz); Ensures(cell >= 0); Ensures(cell < d_num_cells); return cell; } void build_matrices(const std::vector<XS_Data>& xs_data); // Compute 2-norm of vector double vec_norm(const Teuchos::ArrayRCP<double>& vec) { double nrm = 0.0; for (auto val : vec) nrm += val * val; return std::sqrt(nrm); } // Apply scale factor to vector data void scale_vec(Teuchos::ArrayRCP<double>& vec, double factor) { for (auto& val : vec) val *= factor; } }; //---------------------------------------------------------------------------// } // end namespace enrico //---------------------------------------------------------------------------// #endif // Two_Group_Diffusion_h //---------------------------------------------------------------------------// // end of Two_Group_Diffusion.h //---------------------------------------------------------------------------//
{ "alphanum_fraction": 0.5943980609, "avg_line_length": 26.3333333333, "ext": "h", "hexsha": "e99e650068fb353a0dd88ef9fda21977f6ecef7f", "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": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "pshriwise/enrico", "max_forks_repo_path": "include/smrt/Two_Group_Diffusion.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "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": "pshriwise/enrico", "max_issues_repo_path": "include/smrt/Two_Group_Diffusion.h", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "pshriwise/enrico", "max_stars_repo_path": "include/smrt/Two_Group_Diffusion.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1017, "size": 3713 }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 LIBHE_H #define LIBHE_H #include <cassert> #include <algorithm> #include <optional> #include <gsl/span> #include "seal/seal.h" #include "seal/util/common.h" #include "seal/util/rlwe.h" #include "seal/util/polyarithsmallmod.h" using namespace std; using namespace seal; class RawPolynomData { vector<uint64_t > _data; size_t _size; public: explicit RawPolynomData(const SEALContext& context); SEAL_NODISCARD inline const size_t& size() const { return _size; }; SEAL_NODISCARD inline uint64_t* data() { return _data.data(); }; SEAL_NODISCARD inline gsl::span<uint64_t > data_span() { return { data(), size() }; }; void set_data(vector<uint64_t >& data); }; gsl::span<Ciphertext::ct_coeff_type > data_span(Ciphertext& c, size_t n); RawPolynomData generate_a(const SEALContext& context); EncryptionParameters generateParameters(); size_t get_slot_count(const SEALContext& ctx); // returns a vector filled with random double values between 0 and 1 vector<double> random_plaintext_data(size_t count); struct GlobalState { SEALContext context; RawPolynomData a; double scale; explicit GlobalState(double _scale); }; class Client { GlobalState _gs; CKKSEncoder _encoder; SecretKey _partial_secret_key; PublicKey _partial_public_key; std::optional<PublicKey> _public_key = std::nullopt; std::unique_ptr<Encryptor> _encryptor = nullptr; SEAL_NODISCARD static PublicKey generate_partial_public_key(const SecretKey &secret_key, const SEALContext &context, RawPolynomData& a); public: explicit Client(GlobalState global_state); SEAL_NODISCARD inline const SEALContext& context() const { return _gs.context; }; SEAL_NODISCARD inline const PublicKey& partial_public_key() const { return _partial_public_key; }; SEAL_NODISCARD inline const CKKSEncoder& encoder() const { return _encoder; }; SEAL_NODISCARD inline CKKSEncoder& encoder() { return _encoder; }; SEAL_NODISCARD inline const Encryptor& encryptor() const { assert(_encryptor != nullptr); return *_encryptor; }; SEAL_NODISCARD inline const PublicKey& public_key() { return *_public_key; }; inline void set_public_key(const PublicKey& pk) { _public_key = make_optional(pk); }; Ciphertext encrypted_data(gsl::span<const double> plain_data); Plaintext partial_decryption(const Ciphertext& encrypted); }; // adds b to a in place template<typename T> void sum_first_poly_inplace(const SEALContext& context, T& a, const T& b) { auto &context_data = *context.get_context_data(a.parms_id()); auto &parms = context_data.parms(); auto &coeff_modulus = parms.coeff_modulus(); size_t coeff_count = parms.poly_modulus_degree(); size_t coeff_modulus_size = coeff_modulus.size(); // by dereferencing we get only the first poly auto summand_iter = *util::ConstPolyIter(b.data(), coeff_count, coeff_modulus_size); auto sum_iter = *util::ConstPolyIter(a.data(), coeff_count, coeff_modulus_size); auto result_iter = *util::PolyIter(a.data(), coeff_count, coeff_modulus_size); // see Evaluator::add_inplace util::add_poly_coeffmod(sum_iter, summand_iter, coeff_modulus_size, coeff_modulus, result_iter); } // This function adds the first polys in summands to sum (either Ciphertext or Plaintext). template<typename T> T sum_first_polys_inplace(const SEALContext& context, T& sum, gsl::span<const T> summands) { for (size_t i = 0; i < summands.size(); i++) { sum_first_poly_inplace(context, sum, summands[i]); } return sum; } // This function sums the first polys in summands (either Ciphertext or Plaintext). template<typename T> T sum_first_polys(const SEALContext& context, gsl::span<const T> summands) { T sum = summands[0]; sum_first_polys_inplace(context, sum, gsl::span(&summands.data()[1], summands.size() - 1)); return sum; } class Server { GlobalState _gs; PublicKey _public_key; public: explicit Server(GlobalState global_state); SEAL_NODISCARD inline RawPolynomData& a() { return _gs.a; }; SEAL_NODISCARD inline const SEALContext& context() const { return _gs.context; }; SEAL_NODISCARD inline const PublicKey& public_key() const { return _public_key; }; void accumulate_partial_public_keys(gsl::span<const Ciphertext> partial_pub_keys); Ciphertext sum_data(vector<Ciphertext>&& data) const; vector<double> average(const Ciphertext& encrypted_sum, gsl::span<const Plaintext> partial_decryptions) const; }; #endif //LIBHE_H
{ "alphanum_fraction": 0.7421655095, "avg_line_length": 36.7517241379, "ext": "h", "hexsha": "25774a80a434415143fec79e9a251f9c2cd666e7", "lang": "C", "max_forks_count": 190, "max_forks_repo_forks_event_max_datetime": "2020-06-15T12:26:12.000Z", "max_forks_repo_forks_event_min_datetime": "2017-06-08T19:32:54.000Z", "max_forks_repo_head_hexsha": "cc8eb951358320a984ea6798d3d252b4eed5c80c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Baunsgaard/systemml", "max_forks_repo_path": "src/main/cpp/he/libhe.h", "max_issues_count": 418, "max_issues_repo_head_hexsha": "cc8eb951358320a984ea6798d3d252b4eed5c80c", "max_issues_repo_issues_event_max_datetime": "2020-06-25T12:15:54.000Z", "max_issues_repo_issues_event_min_datetime": "2017-06-08T16:27:44.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Baunsgaard/systemml", "max_issues_repo_path": "src/main/cpp/he/libhe.h", "max_line_length": 140, "max_stars_count": 372, "max_stars_repo_head_hexsha": "697e381a84bf3e19b2c2cac29b9c2d5c8daa7fc0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "apache/systemml", "max_stars_repo_path": "src/main/cpp/he/libhe.h", "max_stars_repo_stars_event_max_datetime": "2020-06-24T05:45:00.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-09T01:02:53.000Z", "num_tokens": 1312, "size": 5329 }
#include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "tests.h" void test_symm (void) { const double flteps = 1e-4, dbleps = 1e-6; { int order = 101; int side = 141; int uplo = 121; int M = 1; int N = 2; float alpha = -0.3f; float beta = -1.0f; float A[] = { -0.581f }; int lda = 1; float B[] = { 0.157f, 0.451f }; int ldb = 2; float C[] = { -0.869f, -0.871f }; int ldc = 2; float C_expected[] = { 0.896365f, 0.949609f }; cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "ssymm(case 1518)"); } }; }; { int order = 102; int side = 141; int uplo = 121; int M = 1; int N = 2; float alpha = -0.3f; float beta = -1.0f; float A[] = { 0.874f }; int lda = 1; float B[] = { 0.085f, 0.069f }; int ldb = 1; float C[] = { -0.495f, -0.828f }; int ldc = 1; float C_expected[] = { 0.472713f, 0.809908f }; cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "ssymm(case 1519)"); } }; }; { int order = 101; int side = 142; int uplo = 121; int M = 1; int N = 2; float alpha = -1.0f; float beta = 0.0f; float A[] = { -0.671f, -0.343f, 0.6f, 0.177f }; int lda = 2; float B[] = { 0.043f, 0.01f }; int ldb = 2; float C[] = { 0.988f, 0.478f }; int ldc = 2; float C_expected[] = { 0.032283f, 0.012979f }; cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "ssymm(case 1520)"); } }; }; { int order = 102; int side = 142; int uplo = 121; int M = 1; int N = 2; float alpha = -1.0f; float beta = 0.0f; float A[] = { 0.069f, 0.096f, 0.139f, -0.044f }; int lda = 2; float B[] = { -0.448f, 0.07f }; int ldb = 1; float C[] = { 0.361f, 0.995f }; int ldc = 1; float C_expected[] = { 0.021182f, 0.065352f }; cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "ssymm(case 1521)"); } }; }; { int order = 101; int side = 141; int uplo = 122; int M = 1; int N = 2; float alpha = 0.0f; float beta = -0.3f; float A[] = { 0.745f }; int lda = 1; float B[] = { -0.269f, 0.448f }; int ldb = 2; float C[] = { -0.986f, 0.2f }; int ldc = 2; float C_expected[] = { 0.2958f, -0.06f }; cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "ssymm(case 1522)"); } }; }; { int order = 102; int side = 141; int uplo = 122; int M = 1; int N = 2; float alpha = 0.0f; float beta = -0.3f; float A[] = { 0.96f }; int lda = 1; float B[] = { 0.392f, -0.07f }; int ldb = 1; float C[] = { -0.235f, 0.554f }; int ldc = 1; float C_expected[] = { 0.0705f, -0.1662f }; cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "ssymm(case 1523)"); } }; }; { int order = 101; int side = 142; int uplo = 122; int M = 1; int N = 2; float alpha = -0.3f; float beta = 0.1f; float A[] = { -0.839f, 0.498f, -0.215f, -0.314f }; int lda = 2; float B[] = { -0.66f, 0.593f }; int ldb = 2; float C[] = { -0.806f, 0.525f }; int ldc = 2; float C_expected[] = { -0.208474f, 0.0657906f }; cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "ssymm(case 1524)"); } }; }; { int order = 102; int side = 142; int uplo = 122; int M = 1; int N = 2; float alpha = -0.3f; float beta = 0.1f; float A[] = { 0.994f, -0.117f, -0.639f, 0.925f }; int lda = 2; float B[] = { -0.478f, 0.147f }; int ldb = 1; float C[] = { -0.814f, 0.316f }; int ldc = 1; float C_expected[] = { 0.0662993f, -0.0259703f }; cblas_ssymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], flteps, "ssymm(case 1525)"); } }; }; { int order = 101; int side = 141; int uplo = 121; int M = 1; int N = 2; double alpha = -0.3; double beta = 1; double A[] = { -0.981 }; int lda = 1; double B[] = { -0.823, 0.83 }; int ldb = 2; double C[] = { 0.991, 0.382 }; int ldc = 2; double C_expected[] = { 0.7487911, 0.626269 }; cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dsymm(case 1526)"); } }; }; { int order = 102; int side = 141; int uplo = 121; int M = 1; int N = 2; double alpha = -0.3; double beta = 1; double A[] = { -0.248 }; int lda = 1; double B[] = { 0.74, 0.068 }; int ldb = 1; double C[] = { -0.905, 0.742 }; int ldc = 1; double C_expected[] = { -0.849944, 0.7470592 }; cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dsymm(case 1527)"); } }; }; { int order = 101; int side = 142; int uplo = 121; int M = 1; int N = 2; double alpha = -1; double beta = 1; double A[] = { 0.591, -0.01, -0.192, -0.376 }; int lda = 2; double B[] = { 0.561, 0.946 }; int ldb = 2; double C[] = { 0.763, 0.189 }; int ldc = 2; double C_expected[] = { 0.440909, 0.550306 }; cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dsymm(case 1528)"); } }; }; { int order = 102; int side = 142; int uplo = 121; int M = 1; int N = 2; double alpha = -1; double beta = 1; double A[] = { -0.786, 0.87, 0.222, -0.043 }; int lda = 2; double B[] = { -0.503, -0.526 }; int ldb = 1; double C[] = { -0.027, -0.391 }; int ldc = 1; double C_expected[] = { -0.305586, -0.301952 }; cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dsymm(case 1529)"); } }; }; { int order = 101; int side = 141; int uplo = 122; int M = 1; int N = 2; double alpha = 0.1; double beta = 0.1; double A[] = { -0.468 }; int lda = 1; double B[] = { -0.881, 0.692 }; int ldb = 2; double C[] = { -0.812, -0.395 }; int ldc = 2; double C_expected[] = { -0.0399692, -0.0718856 }; cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dsymm(case 1530)"); } }; }; { int order = 102; int side = 141; int uplo = 122; int M = 1; int N = 2; double alpha = 0.1; double beta = 0.1; double A[] = { 0.849 }; int lda = 1; double B[] = { -0.887, 0.518 }; int ldb = 1; double C[] = { 0.414, -0.251 }; int ldc = 1; double C_expected[] = { -0.0339063, 0.0188782 }; cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dsymm(case 1531)"); } }; }; { int order = 101; int side = 142; int uplo = 122; int M = 1; int N = 2; double alpha = -1; double beta = 1; double A[] = { 0.457, 0.624, 0.807, 0.349 }; int lda = 2; double B[] = { -0.609, 0.03 }; int ldb = 2; double C[] = { 0.719, -0.624 }; int ldc = 2; double C_expected[] = { 0.973103, -0.143007 }; cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dsymm(case 1532)"); } }; }; { int order = 102; int side = 142; int uplo = 122; int M = 1; int N = 2; double alpha = -1; double beta = 1; double A[] = { -0.133, -0.117, -0.163, 0.795 }; int lda = 2; double B[] = { -0.882, 0.549 }; int ldb = 1; double C[] = { 0.715, -0.327 }; int ldc = 1; double C_expected[] = { 0.661927, -0.866649 }; cblas_dsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[i], C_expected[i], dbleps, "dsymm(case 1533)"); } }; }; { int order = 101; int side = 141; int uplo = 121; int M = 1; int N = 2; float alpha[2] = {-1.0f, 0.0f}; float beta[2] = {1.0f, 0.0f}; float A[] = { 0.476f, 0.816f }; int lda = 1; float B[] = { 0.282f, 0.852f, -0.891f, -0.588f }; int ldb = 2; float C[] = { 0.9f, 0.486f, -0.78f, -0.637f }; int ldc = 2; float C_expected[] = { 1.461f, -0.149664f, -0.835692f, 0.369944f }; cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csymm(case 1534) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csymm(case 1534) imag"); }; }; }; { int order = 102; int side = 141; int uplo = 121; int M = 1; int N = 2; float alpha[2] = {-1.0f, 0.0f}; float beta[2] = {1.0f, 0.0f}; float A[] = { 0.048f, 0.172f }; int lda = 1; float B[] = { 0.786f, 0.783f, 0.809f, -0.569f }; int ldb = 1; float C[] = { -0.227f, -0.215f, 0.881f, 0.233f }; int ldc = 1; float C_expected[] = { -0.130052f, -0.387776f, 0.7443f, 0.121164f }; cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csymm(case 1535) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csymm(case 1535) imag"); }; }; }; { int order = 101; int side = 142; int uplo = 121; int M = 1; int N = 2; float alpha[2] = {0.0f, 1.0f}; float beta[2] = {0.0f, 1.0f}; float A[] = { -0.495f, -0.012f, 0.843f, -0.986f, -0.243f, 0.833f, 0.921f, 0.004f }; int lda = 2; float B[] = { 0.876f, 0.612f, 0.805f, -0.57f }; int ldb = 2; float C[] = { 0.938f, -0.24f, -0.874f, -0.062f }; int ldc = 2; float C_expected[] = { 1.82769f, 0.628319f, 0.93157f, 1.21158f }; cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csymm(case 1536) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csymm(case 1536) imag"); }; }; }; { int order = 102; int side = 142; int uplo = 121; int M = 1; int N = 2; float alpha[2] = {0.0f, 1.0f}; float beta[2] = {0.0f, 1.0f}; float A[] = { -0.812f, 0.83f, 0.705f, 0.15f, -0.463f, 0.901f, -0.547f, -0.483f }; int lda = 2; float B[] = { -0.808f, -0.664f, 0.352f, -0.102f }; int ldb = 1; float C[] = { -0.64f, 0.399f, 0.896f, -0.163f }; int ldc = 1; float C_expected[] = { -0.631906f, 0.496142f, 0.697798f, 1.62656f }; cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csymm(case 1537) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csymm(case 1537) imag"); }; }; }; { int order = 101; int side = 141; int uplo = 122; int M = 1; int N = 2; float alpha[2] = {-1.0f, 0.0f}; float beta[2] = {0.0f, 1.0f}; float A[] = { 0.342f, -0.906f }; int lda = 1; float B[] = { 0.676f, 0.863f, -0.517f, -0.138f }; int ldb = 2; float C[] = { 0.274f, 0.388f, -0.271f, 0.205f }; int ldc = 2; float C_expected[] = { -1.40107f, 0.59131f, 0.096842f, -0.692206f }; cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csymm(case 1538) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csymm(case 1538) imag"); }; }; }; { int order = 102; int side = 141; int uplo = 122; int M = 1; int N = 2; float alpha[2] = {-1.0f, 0.0f}; float beta[2] = {0.0f, 1.0f}; float A[] = { 0.418f, 0.354f }; int lda = 1; float B[] = { -0.74f, 0.018f, 0.395f, 0.248f }; int ldb = 1; float C[] = { -0.162f, 0.175f, -0.853f, 0.652f }; int ldc = 1; float C_expected[] = { 0.140692f, 0.092436f, -0.729318f, -1.09649f }; cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csymm(case 1539) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csymm(case 1539) imag"); }; }; }; { int order = 101; int side = 142; int uplo = 122; int M = 1; int N = 2; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {0.0f, 0.1f}; float A[] = { 0.12f, 0.496f, 0.313f, -0.136f, 0.987f, 0.532f, 0.58f, -0.687f }; int lda = 2; float B[] = { -0.587f, 0.278f, 0.857f, 0.136f }; int ldb = 2; float C[] = { 0.162f, 0.249f, -0.665f, 0.456f }; int ldc = 2; float C_expected[] = { -0.22769f, -0.0269913f, 0.0502096f, 0.0841558f }; cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csymm(case 1540) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csymm(case 1540) imag"); }; }; }; { int order = 102; int side = 142; int uplo = 122; int M = 1; int N = 2; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {0.0f, 0.1f}; float A[] = { 0.579f, -0.859f, 0.192f, -0.737f, 0.396f, -0.498f, 0.751f, -0.379f }; int lda = 2; float B[] = { 0.84f, -0.755f, -0.019f, -0.063f }; int ldb = 1; float C[] = { 0.04f, 0.639f, -0.876f, -0.778f }; int ldc = 1; float C_expected[] = { 0.115459f, 0.329813f, 0.288206f, 0.110315f }; cblas_csymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csymm(case 1541) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csymm(case 1541) imag"); }; }; }; { int order = 101; int side = 141; int uplo = 121; int M = 1; int N = 2; double alpha[2] = {0, 0}; double beta[2] = {0, 0}; double A[] = { 0.511, -0.486 }; int lda = 1; double B[] = { 0.985, -0.923, -0.234, -0.756 }; int ldb = 2; double C[] = { -0.16, 0.049, 0.618, -0.349 }; int ldc = 2; double C_expected[] = { 0.0, 0.0, 0.0, 0.0 }; cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsymm(case 1542) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsymm(case 1542) imag"); }; }; }; { int order = 102; int side = 141; int uplo = 121; int M = 1; int N = 2; double alpha[2] = {0, 0}; double beta[2] = {0, 0}; double A[] = { 0.46, -0.816 }; int lda = 1; double B[] = { 0.404, 0.113, -0.904, -0.627 }; int ldb = 1; double C[] = { 0.114, 0.318, 0.636, -0.839 }; int ldc = 1; double C_expected[] = { 0.0, 0.0, 0.0, 0.0 }; cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsymm(case 1543) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsymm(case 1543) imag"); }; }; }; { int order = 101; int side = 142; int uplo = 121; int M = 1; int N = 2; double alpha[2] = {-1, 0}; double beta[2] = {-0.3, 0.1}; double A[] = { -0.835, 0.344, 0.975, 0.634, 0.312, -0.659, -0.624, -0.175 }; int lda = 2; double B[] = { -0.707, -0.846, 0.825, -0.661 }; int ldb = 2; double C[] = { 0.352, -0.499, 0.267, 0.548 }; int ldc = 2; double C_expected[] = { -2.160518, -0.156877, 0.648536, 0.867299 }; cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsymm(case 1544) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsymm(case 1544) imag"); }; }; }; { int order = 102; int side = 142; int uplo = 121; int M = 1; int N = 2; double alpha[2] = {-1, 0}; double beta[2] = {-0.3, 0.1}; double A[] = { -0.409, 0.013, -0.308, -0.317, -0.535, -0.697, -0.385, 0.119 }; int lda = 2; double B[] = { 0.299, -0.233, 0.093, 0.664 }; int ldb = 1; double C[] = { 0.699, 0.47, -0.347, -0.182 }; int ldc = 1; double C_expected[] = { -0.550491, 0.249777, 0.559487, 0.348221 }; cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsymm(case 1545) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsymm(case 1545) imag"); }; }; }; { int order = 101; int side = 141; int uplo = 122; int M = 1; int N = 2; double alpha[2] = {1, 0}; double beta[2] = {0, 1}; double A[] = { -0.151, 0.635 }; int lda = 1; double B[] = { 0.711, -0.869, 0.153, 0.647 }; int ldb = 2; double C[] = { -0.299, 0.43, -0.307, 0.133 }; int ldc = 2; double C_expected[] = { 0.014454, 0.283704, -0.566948, -0.307542 }; cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsymm(case 1546) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsymm(case 1546) imag"); }; }; }; { int order = 102; int side = 141; int uplo = 122; int M = 1; int N = 2; double alpha[2] = {1, 0}; double beta[2] = {0, 1}; double A[] = { 0.793, -0.543 }; int lda = 1; double B[] = { 0.054, -0.045, 0.989, 0.453 }; int ldb = 1; double C[] = { 0.443, -0.641, -0.809, -0.83 }; int ldc = 1; double C_expected[] = { 0.659387, 0.377993, 1.860256, -0.986798 }; cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsymm(case 1547) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsymm(case 1547) imag"); }; }; }; { int order = 101; int side = 142; int uplo = 122; int M = 1; int N = 2; double alpha[2] = {1, 0}; double beta[2] = {-1, 0}; double A[] = { -0.432, -0.293, -0.819, 0.44, -0.818, -0.258, -0.836, 0.683 }; int lda = 2; double B[] = { -0.259, -0.878, 0.161, 0.744 }; int ldb = 2; double C[] = { 0.436, -0.655, -0.61, -0.875 }; int ldc = 2; double C_expected[] = { -0.521112, 0.460053, -0.04741, 1.148005 }; cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsymm(case 1548) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsymm(case 1548) imag"); }; }; }; { int order = 102; int side = 142; int uplo = 122; int M = 1; int N = 2; double alpha[2] = {1, 0}; double beta[2] = {-1, 0}; double A[] = { -0.656, 0.378, -0.688, 0.676, 0.967, -0.804, 0.455, -0.425 }; int lda = 2; double B[] = { 0.791, -0.947, -0.945, -0.444 }; int ldb = 1; double C[] = { 0.014, -0.814, -0.091, -0.417 }; int ldc = 1; double C_expected[] = { 0.775374, 1.400882, -0.431711, 1.802857 }; cblas_zsymm(order, side, uplo, M, N, alpha, A, lda, B, ldb, beta, C, ldc); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsymm(case 1549) real"); gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsymm(case 1549) imag"); }; }; }; }
{ "alphanum_fraction": 0.4950410071, "avg_line_length": 25.3285024155, "ext": "c", "hexsha": "88a672a7ae5635002b096f571a29c3b4f9ff9b5f", "lang": "C", "max_forks_count": 224, "max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z", "max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "utdsimmons/ohpc", "max_forks_repo_path": "tests/libs/gsl/tests/cblas/test_symm.c", "max_issues_count": 1096, "max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "utdsimmons/ohpc", "max_issues_repo_path": "tests/libs/gsl/tests/cblas/test_symm.c", "max_line_length": 86, "max_stars_count": 692, "max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "utdsimmons/ohpc", "max_stars_repo_path": "tests/libs/gsl/tests/cblas/test_symm.c", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z", "num_tokens": 9238, "size": 20972 }
// // Author: Valerio Bertone: valerio.bertone@cern.ch // #pragma once #include <string> #include <vector> #include <utility> #include <apfel/apfelxx.h> #include <yaml-cpp/yaml.h> #include <gsl/gsl_rng.h> namespace NangaParbat { /** * @brief The "DataHandler" class provides a common interface to all * datasets. It provides methods to get kinematics, central values, * uncertainties, etc. */ class DataHandler { public: /** * @brief The process enumerator */ enum Process: int {UnknownProcess = -1, DY = 0, SIDIS = 1, SIA = 2, DIA = 3}; /** * @brief The observable enumerator */ enum Observable: int {UnknownObservable = -1, dsigma_dxdydz = 0, dsigma_dxdQdz = 1, multiplicity = 2}; /** * @brief Structure containing the kinematic information of one * single data set. */ struct Kinematics { Kinematics(); bool empty() const; int ndata; //!< Number of data points double Vs; //!< Center of mass energy std::vector<double> qTv; //!< Vector of qT values std::vector<std::pair<double, double>> qTmap; //!< Map of qT bounds to associate to the single bins std::vector<double> qTfact; //!< Possible bin-by-bin prefactors to multiply the theoretical predictions std::pair<double, double> var1b; //!< Variable 1 integration bounds std::pair<double, double> var2b; //!< Variable 2 integration bounds std::pair<double, double> var3b; //!< Variable 3 integration bounds bool IntqT; //!< Whether the bins in qTv are integrated over bool Intv1; //!< Whether the bins variable 1 are integrated over bool Intv2; //!< Whether the bins variable 2 are integrated over bool Intv3; //!< Whether the bins variable 3 are integrated over bool PSRed; //!< Whether there is a final-state PS reduction double pTMin; //!< Minimum pT of the final-state leptons std::pair<double, double> etaRange; //!< Allowed range in eta of the final-state leptons }; /** * @brief Structure containing the single bin information. This is * currently used only for the FF_SIDIS project. * @todo Integrate it better in the rest of the class. */ struct Binning { Binning(); double zmin; double zmax; double zav; bool Intz; double xmin; double xmax; double xav; bool Intx; double Qmin; double Qmax; double Qav; bool IntQ; double ymin; double ymax; double yav; bool Inty; }; /** * @brief The "DataHandler" copy constructor. */ DataHandler(DataHandler const &DH); /** * @brief The "DataHandler" constructor. * @param name: the name associated to the data set * @param datafile: the YAML:Node with the interpolation table * @param rng: GSL random number object * @param fluctuation: ID of the fluctuation (i.e. Monte-Carlo replica ID) (default: 0, i.e. no fluctuations) * @param t0: vector of predictions to be used for the t0-prescription */ DataHandler(std::string const& name, YAML::Node const& datafile, gsl_rng* rng = nullptr, int const& fluctuation = 0, std::vector<double> const& t0 = {}); /** * @brief Function that fluctuates data * @param rng: GSL random number object * @param fluctuation: ID of the fluctuation (i.e. Monte-Carlo replica ID) (default: 0, i.e. no fluctuations) */ void FluctuateData(gsl_rng *rng, int const &fluctuation); /** * @brief Function that sets the data central values replacing that * introduced in the constructor. * @param means: the new means */ void SetMeans(std::vector<double> const& means, gsl_rng* rng = nullptr, int const& fluctuation = 0); /** * @brief Function that returns the name of the dataset */ std::string GetName() const { return _name; }; /** * @brief Function that returns the datafile in YAML format */ YAML::Node GetDataFile() const { return _datafile; }; /** * @brief Function that returns the process code */ Process GetProcess() const { return _proc; }; /** * @brief Function that returns the observable code */ Observable GetObservable() const { return _obs; }; /** * @brief Function that returns the target isoscalarity * @note The code always assumes that one of the hadrons has * isoscalarity 1, meaning that it's a single hadron whose * distributions don't need to be manipulated. */ double GetTargetIsoscalarity() const { return _targetiso; }; /** * @brief Function that returns the possible identified hadron * species in the final state. */ std::string GetHadron() const { return _hadron; }; /** * @brief Function that returns the charge of the identified final * state. */ int GetCharge() const { return _charge; }; /** * @brief Function that returns the quark-tagged compoments. Zero * corresponds to total. */ std::vector<apfel::QuarkFlavour> GetTagging() const { return _tagging; }; /** * @brief Function that returns any possible constant prefactor to * be used to multiply the theoretical predictions. */ double GetPrefactor() const { return _prefact; }; /** * @brief Function that returns the kinematic object */ Kinematics GetKinematics() const { return _kin; }; /** * @brief Function that returns the mean values */ std::vector<double> GetMeanValues() const { return _means; }; /** * @brief Function that returns the fluctuated data */ std::vector<double> GetFluctutatedData() const { return _fluctuations; }; /** * @brief Function that returns the sum in quadrature of the * uncorrelated uncertainties. */ std::vector<double> GetUncorrelatedUnc() const { return _uncor; }; /** * @brief Function that returns the additive correlated systematic * uncertainties. */ std::vector<std::vector<double>> GetAddCorrelatedUnc() const { return _corra; }; /** * @brief Function that returns the multiplicative correlated * systematic uncertainties. */ std::vector<std::vector<double>> GetMultCorrelatedUnc() const { return _corrm; }; /** * @brief Function that returns the all the correlated systematic * uncertainties (additive first and multiplicative second). */ std::vector<std::vector<double>> GetCorrelatedUnc() const { return _corr; }; /** * @brief Function that returns the covariance matrix of the * correlated uncertainties. */ apfel::matrix<double> GetCovarianceMatrix() const { return _covmat; }; /** * @brief Function that returns the Cholesky decomposition of the * covariance matrix. */ apfel::matrix<double> GetCholeskyDecomposition() const { return _CholL; }; /** * @brief Function that returns the set of t0 predictions */ std::vector<double> GetT0() const { return _t0; }; /** * @brief Function that returns the plotting labels. */ std::map<std::string, std::string> GetLabels() const { return _labels; }; /** * @brief Get vector of bins. This is currently used only for the * FF_SIDIS project. * @todo Integrate it better in the rest of the * class. */ std::vector<Binning> GetBinning() const { return _bins; } protected: std::string _name; //!< Name of the dataset YAML::Node _datafile; //!< Datafile in YAML Process _proc; //!< The process Observable _obs; //!< The observable double _targetiso; //!< Isoscalarity of the target std::string _hadron; //!< Hadron species identified in the final state double _charge; //!< Charge of the identified final state std::vector<apfel::QuarkFlavour> _tagging; //!< Possible quark-tagged components double _prefact; //!< Possible overall prefactor to multiply the theoretical predictions Kinematics _kin; //!< Kinematics block std::vector<double> _means; //!< Vector of central values std::vector<double> _uncor; //!< Vector of uncorrelated uncertainties std::vector<std::vector<double>> _corra; //!< Additive correlated uncertainties std::vector<std::vector<double>> _corrm; //!< Multiplicative correlated uncertainties std::vector<std::vector<double>> _corr; //!< All correlated uncertainties apfel::matrix<double> _covmat; //!< Covariance matrix apfel::matrix<double> _CholL; //!< Cholesky decomposition of the covariance matrix std::map<std::string, std::string> _labels; //!< Labels used for plotting std::vector<double> _fluctuations; //!< Vector of fluctuated data std::vector<double> _t0; //!< Vector of t0-predictions std::vector<Binning> _bins; //!< Vector of bins (currently used only for the FF_SIDIS project) friend std::ostream& operator << (std::ostream& os, DataHandler const& DH); }; std::ostream& operator << (std::ostream &os, DataHandler const& DH); }
{ "alphanum_fraction": 0.5933360096, "avg_line_length": 37.4586466165, "ext": "h", "hexsha": "6aaae932b1188cfc7ae5571d68eea8b3ef49aed3", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2020-08-01T18:42:36.000Z", "max_forks_repo_forks_event_min_datetime": "2020-01-18T22:10:02.000Z", "max_forks_repo_head_hexsha": "49529d0a2e810dfe0ec676c8e96081be39a8800d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "vbertone/NangaParbat", "max_forks_repo_path": "inc/NangaParbat/datahandler.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "49529d0a2e810dfe0ec676c8e96081be39a8800d", "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": "vbertone/NangaParbat", "max_issues_repo_path": "inc/NangaParbat/datahandler.h", "max_line_length": 157, "max_stars_count": 3, "max_stars_repo_head_hexsha": "49529d0a2e810dfe0ec676c8e96081be39a8800d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "vbertone/NangaParbat", "max_stars_repo_path": "inc/NangaParbat/datahandler.h", "max_stars_repo_stars_event_max_datetime": "2020-01-17T10:59:39.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-16T17:15:54.000Z", "num_tokens": 2331, "size": 9964 }
// -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt #ifndef MESH_PROCESSING_LIBHH_MY_LAPACK_H_ #define MESH_PROCESSING_LIBHH_MY_LAPACK_H_ #include "libHh/Hh.h" // HH_REFERENCE_LIB() #if defined(HH_HAVE_LAPACK) #if defined(HH_USE_LAPACK_INTEGER) // Google #include <lapack.h> using lapack_int = lapack::integer; #elif !(defined(_WIN32) || defined(__CYGWIN__)) // unix #if defined(__GNUC__) #pragma GCC diagnostic ignored "-Wredundant-decls" #endif #include <lapacke.h> // in either /usr/include/ or /usr/include/lapacke/ #else // cygwin or WIN32 #if defined(__CYGWIN__) // cygwin: c:/cygwin/usr/src/lapack-3.5.0.tgz // lapacke_config.h // #ifndef lapack_int // #if defined(LAPACK_ILP64) // #define lapack_int long // #else // #define lapack_int int // #endif // #endif // // lapacke.h: "#define lapack_int int" // #define LAPACK_sgelss LAPACK_GLOBAL(sgelss, SGELSS) // void LAPACK_sgelss( lapack_int* m, lapack_int* n, lapack_int* nrhs, float* a, // lapack_int* lda, float* b, lapack_int* ldb, float* s, // float* rcond, lapack_int* rank, float* work, // lapack_int* lwork, lapack_int* info ); // c:/cygwin/usr/src/lapack-3.5.0.tgz!lapack-3.5.0/lapacke/example/example_DGELS_colmajor.c // #include <lapacke.h> // { // double A[5][3] = {1, 2, 3, 4, 5, 1, 3, 5, 2, 4, 1, 4, 2, 5, 3}; // double b[5][2] = {-10, 12, 14, 16, 18, -3, 14, 12, 16, 16}; // lapack_int m = 5, n = 3, lda = 5, ldb = 5, nrhs = 2; // lapack_int info = LAPACKE_dgels(LAPACK_COL_MAJOR, 'N', m, n, nrhs, *A, lda, *b, ldb); // } using lapack_int = int; #else // _WIN32 using lapack_int = long; // was defined as "integer" in f2c.h #endif // Continue: cygwin or WIN32 // clapack routines in liblapack extern "C" { // http://www.netlib.org/lapack/explore-html/d0/db8/group__real_g_esolve.html#ga206e3084597d088b31dc054a69aec93f // SGELSS solves overdetermined or underdetermined systems for GE matrices, using SVD. // ~/git/lib_src/CLAPACK/SRC/sgelss.c lapack_int sgelss_(lapack_int* m, lapack_int* n, lapack_int* nrhs, float* a, lapack_int* lda, float* b, lapack_int* ldb, float* s, float* rcond, lapack_int* irank, float* work, lapack_int* lwork, lapack_int* info); // same for double-precision lapack_int dgelss_(lapack_int* m, lapack_int* n, lapack_int* nrhs, double* a, lapack_int* lda, double* b, lapack_int* ldb, double* s, double* rcond, lapack_int* irank, double* work, lapack_int* lwork, lapack_int* info); // http://www.netlib.org/lapack/explore-html/d0/d2a/sgelsx_8f.html // SGELSX solves overdetermined or underdetermined systems for GE matrices, using QR. // This routine is deprecated and has been replaced by routine SGELSY. // ~/git/lib_src/CLAPACK/SRC/sgelsx.c // lapack_int sgelsx_(lapack_int* m, lapack_int* n, lapack_int* nrhs, float* a, lapack_int* lda, // float* b, lapack_int* ldb, lapack_int* jpvt, float* rcond, lapack_int* irank, // float* work, lapack_int* info); // http://www.netlib.org/lapack/explore-html/dc/db6/sgelsy_8f.html lapack_int sgelsy_(lapack_int* m, lapack_int* n, lapack_int* nrhs, float* a, lapack_int* lda, float* b, lapack_int* ldb, lapack_int* jpvt, float* rcond, lapack_int* irank, float* work, lapack_int* lwork, lapack_int* info); // http://www.netlib.org/lapack/explore-html/d4/dca/group__real_g_esing.html // subroutine SGESVD (JOBU, JOBVT, M, N, A, LDA, S, U, LDU, VT, LDVT, WORK, LWORK, INFO) // SGESVD computes the singular value decomposition (SVD) for GE matrices // ~/git/lib_src/CLAPACK/SRC/sgesvd.c lapack_int sgesvd_(char* jobu, char* jobvt, lapack_int* m, lapack_int* n, float* a, lapack_int* lda, float* s, float* u, lapack_int* ldu, float* vt, lapack_int* ldvt, float* work, lapack_int* lwork, lapack_int* info); // http://www.netlib.org/lapack/explore-html/d8/ddc/group__real_g_ecomputational.html#ga7cb54fa1727bf0166523036f4948bc56 // subroutine SGEQRF (M, N, A, LDA, TAU, WORK, LWORK, INFO) // SGEQRF computes a QR factorization of a real M-by-N matrix A: // A = Q * R. // ~/git/lib_src/CLAPACK/SRC/sgeqrf.c lapack_int sgeqrf_(lapack_int* m, lapack_int* n, float* a, lapack_int* lda, float* tau, float* work, lapack_int* lwork, lapack_int* info); } #if defined(_MSC_VER) HH_REFERENCE_LIB("liblapack.lib"); HH_REFERENCE_LIB("libBLAS.lib"); #if 1 HH_REFERENCE_LIB("libf2c.lib"); // CLAPACK #else HH_REFERENCE_LIB("libF77.lib"); // liblapack HH_REFERENCE_LIB("libI77.lib"); #endif #endif // defined(_MSC_VER) #endif // !(defined(_WIN32) || defined(__CYGWIN__)) #endif // defined(HAVE_LAPACK) #endif // MESH_PROCESSING_LIBHH_MY_LAPACK_H_
{ "alphanum_fraction": 0.6783260462, "avg_line_length": 39.694214876, "ext": "h", "hexsha": "286488129ca6b90f84b336d583db62b05458fb8a", "lang": "C", "max_forks_count": 75, "max_forks_repo_forks_event_max_datetime": "2021-11-09T02:57:34.000Z", "max_forks_repo_forks_event_min_datetime": "2017-01-12T04:44:41.000Z", "max_forks_repo_head_hexsha": "194ce16b8b28bbab1263ca6bc26dedfa7a0eeea2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "wangxihao/Mesh-processing-library", "max_forks_repo_path": "libHh/my_lapack.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "194ce16b8b28bbab1263ca6bc26dedfa7a0eeea2", "max_issues_repo_issues_event_max_datetime": "2017-06-07T16:36:09.000Z", "max_issues_repo_issues_event_min_datetime": "2017-06-07T16:36:09.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "wangxihao/Mesh-processing-library", "max_issues_repo_path": "libHh/my_lapack.h", "max_line_length": 120, "max_stars_count": 422, "max_stars_repo_head_hexsha": "aa8c952fbbb00774008060767650b821bf72fa10", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hhoppe/Mesh-processing-library", "max_stars_repo_path": "libHh/my_lapack.h", "max_stars_repo_stars_event_max_datetime": "2022-03-21T14:38:49.000Z", "max_stars_repo_stars_event_min_datetime": "2017-01-12T04:44:39.000Z", "num_tokens": 1641, "size": 4803 }
#ifndef EXECUTION_CONTENT_INCLUDE #define EXECUTION_CONTENT_INCLUDE #include <atomic> #include <map> #include <string> #include <thread> #include <vector> #include <boost/asio.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/vector.hpp> #include <gsl/gsl> #include "base-utils/commandUtils.h" #include "base-utils/execution.h" #include "base-utils/tmpFile.h" namespace execHelper { namespace test { namespace baseUtils { class IoService { public: IoService() = default; IoService(const IoService& other) = delete; IoService(IoService&& other) = delete; ~IoService() noexcept; IoService& operator=(const IoService& other) = delete; IoService& operator=(IoService&& other) = delete; void start() noexcept; void stop() noexcept; void run() noexcept; boost::asio::io_service& get() noexcept; private: boost::asio::io_context m_service; std::atomic<bool> m_isRunning = {false}; std::thread m_thread; }; struct ExecutionContentData { std::vector<std::string> args; std::map<std::string, std::string> env; template <typename Archive> void serialize(Archive& ar, const unsigned int /*version*/) { ar& args& env; } }; struct ExecutionContentDataReply { ReturnCode returnCode; ExecutionContentDataReply(ReturnCode returnCode) noexcept : returnCode(returnCode) { ; } }; class ExecutionContentServer { public: using ConfigCommand = std::vector<std::string>; ExecutionContentServer(ReturnCode returnCode) noexcept; ~ExecutionContentServer() noexcept; ExecutionContentServer(const ExecutionContentServer& other) = delete; ExecutionContentServer(ExecutionContentServer&& other) noexcept; ExecutionContentServer& operator=(const ExecutionContentServer& other) = delete; ExecutionContentServer& operator=(ExecutionContentServer&& other) noexcept; void swap(ExecutionContentServer& other) noexcept; ConfigCommand getConfigCommand() const noexcept; unsigned int getNumberOfExecutions() const noexcept; const std::vector<ExecutionContentData>& getReceivedData() const noexcept; void clear() noexcept; static void registerIoService(gsl::not_null<IoService*> ioService) noexcept; private: /** * Opens the acceptor explicitly rather than using the appropriate constructor for it. This is to work around * the fact that the appropriate constructor will throw, causing an exception to leak out of the interface * * \throws boost::system::system_error If the acceptor can not be opened */ void openAcceptor(); void init() noexcept; void accept() noexcept; ExecutionContentDataReply addData(ExecutionContentData data) noexcept; std::vector<ExecutionContentData> m_receivedData; uint32_t m_numberOfExecutions = {0}; ReturnCode m_returnCode = {SUCCESS}; TmpFile m_file; boost::asio::local::stream_protocol::endpoint m_endpoint; boost::asio::local::stream_protocol::socket m_socket; boost::asio::local::stream_protocol::acceptor m_acceptor; static IoService* m_ioService; }; using ExecutionContent = ExecutionContentServer; class ExecutionContentClient { public: ExecutionContentClient(const Path& file); ReturnCode addExecution(const ExecutionContentData& data); private: boost::asio::local::stream_protocol::endpoint m_endpoint; }; } // namespace baseUtils } // namespace test } // namespace execHelper #endif /* EXECUTION_CONTENT_INCLUDE */
{ "alphanum_fraction": 0.729614949, "avg_line_length": 28.256, "ext": "h", "hexsha": "b1b13f07632ffda0542dea89e372d4a5688e68bc", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z", "max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "exec-helper/source", "max_forks_repo_path": "test/base-utils/include/base-utils/executionContent.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "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": "exec-helper/source", "max_issues_repo_path": "test/base-utils/include/base-utils/executionContent.h", "max_line_length": 113, "max_stars_count": 1, "max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "exec-helper/source", "max_stars_repo_path": "test/base-utils/include/base-utils/executionContent.h", "max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z", "num_tokens": 787, "size": 3532 }
#ifndef API_H_INCLUDED #define API_H_INCLUDED #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_complex.h> #include <plplot/plplot.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "stack.h" #include "utf8.h" #include "gdate.h" #include <setjmp.h> #if defined(_MSC_VER) || defined(_WIN32) #include <Windows.h> #endif #define RECORD_SEP '~' // Parse errors #define KEE_UNQU 0x01 // unmatched quotation marks #define KEE_UNLP 0x02 // unmatched left parentheses #define KEE_UNRP 0x04 // unmatched right parentheses #define KEE_UNOP 0x08 // unknown operators #define KEE_FUNC 0x10 // wrong function syntax #define KEE_ARG 0x20 #define KEE_NUM 0x40 // fail to parse a number //#define KEE_END 0x80 // fail to parse a number // Evaluation errors #define KEE_UNFUNC 0x40 // undefined function #define KEE_UNVAR 0x80 // unassigned variable // Return type #define KEV_REAL 1 #define KEV_INT 2 #define KEV_STR 3 #define KEV_VEC 4 #define KEV_MAT 5 #define KEV_COMPLEX 6 #define KEV_FNC 7 #define KEV_REC 8 #define KEV_VEC_INT 9 #define KEV_DEF 10 #define KEV_IMAGE 11 #define KEV_FILE 12 #define KEV_BUFFER 13 #define KEV_DATE 14 #define KEV_PTR 15 #define KEV_FPOS 16 #define KEV_REAL_S "REAL" #define KEV_INT_S "INT" #define KEV_STR_S "STR" #define KEV_VEC_S "VEC" #define KEV_MAT_S "MAT" #define KEV_COMPLEX_S "COMPLEX" #define KEV_CMD_S "CMD" #define KEV_FNC_S "FNC" #define KEV_REC_S "REC" #define KEV_VEC_INT_S "VEC_INT" #define KEV_DEF_S "DEF" #define KEV_IMAGE_S "IMAGE" #define KEV_FILE_S "FILE" #define KEV_BUFFER_S "BUFFER" #define KEV_DATE_S "DATE" #define KEV_PTR_S "PTR" #define KEV_FPOS_S "FPOS" extern char * kev_to_str[17]; #define KEO_NULL 0 #define KEO_POS 1 #define KEO_NEG 2 #define KEO_BNOT 3 #define KEO_LNOT 4 #define KEO_POW 5 #define KEO_MUL 6 #define KEO_DIV 7 #define KEO_IDIV 8 #define KEO_MOD 9 #define KEO_ADD 10 #define KEO_SUB 11 #define KEO_LSH 12 #define KEO_RSH 13 #define KEO_LT 14 #define KEO_LE 15 #define KEO_GT 16 #define KEO_GE 17 #define KEO_EQ 18 #define KEO_NE 19 #define KEO_BAND 20 #define KEO_BXOR 21 #define KEO_BOR 22 #define KEO_LAND 23 #define KEO_LOR 24 #define KEO_LET 25 #define KEO_NOP 26 #define KEO_MAX 27 #define KET_NULL 0 #define KET_DEFNAME 1 #define KET_CMD 2 #define KET_VCMD 3 #define KET_OP 4 #define KET_FUNC 5 #define KET_REC 6 #define KET_XPROP 7 #define KET_PROP 8 #define KET_VAL_SEP 10 #define KET_CONST 11 #define KET_VAL 12 #define KET_FILE 13 #define KET_XNAME 14 //already set when it's VNAME #define KET_VNAME 15 #define KEF_NULL 0 #define KEF_REAL 1 #define KEF_LET 2 #define KEF_GET 3 #include "kdq.h" #include "khash.h" struct token_s; struct kexpr_s; struct sml_s; typedef char* strptr; typedef struct token_s* ke1_p; typedef int(*cmdp)(struct sml_s * sml, int); typedef void(*fncp)(struct sml_s *); typedef int(*vcmdp)(struct sml_s * sml, int); typedef int(__cdecl *dllke_hash_add_t)(struct sml_s *, fncp, char *); typedef struct token_s *(__cdecl *dllke_get_out_t)(struct sml_s *); KHASH_MAP_INIT_STR(0, cmdp) KHASH_MAP_INIT_STR(1, vcmdp) KHASH_MAP_INIT_STR(2, int) KHASH_MAP_INIT_STR(3, int) KHASH_MAP_INIT_STR(5, fncp) KHASH_MAP_INIT_STR(6, int) KHASH_MAP_INIT_STR(7, int) #pragma warning( push ) #pragma warning( disable : 273) #pragma warning( disable : 4018) #pragma warning( disable : 4334) #pragma warning( disable : 4627) #pragma warning( disable : 4267) KDQ_INIT(int) #pragma warning( pop ) struct sml_s; typedef struct sml_s { int is_execute; int topGlobal; struct token_s *def_name; // current def name to put the stack ref struct token_s **stack; // stack for the evaluation of the program double *rstack; // stack for the evaluation of the program struct token_s *out; // pointer to the array of out parameter to put into the stack struct kexpr_s *kexpr; struct token_s ** fields; // array of all global fields of the program to exectue struct token_s ** tokens; // array of pointers of all program tokens int top; int localtop; // will be init with gfield_qte; int inittop; // will be init with gfield_qte; struct token_s * tokp; int out_qte; int tok_idx; int val; jmp_buf env_buffer; // GLOBAL VARIABLE USED BY ALL FUNCTIONS int field_qte; // number of local fields, reset for each def int gfield_qte; // number of global fields int mem_count; // current count of memory allocation // parser variables int isNextDefName; // flag to indicate that the next token is the def name char currentDefName[100]; // current name of the current function int sourceCodeLine; // use to keep the line number to show better error trapping int isFirstToken; // use to remove separators at the beginning of the program int isLastTokenNop; // use to manage the command seperator, the rule is to have one separator between each comand char lastErrorMessage[256]; // struct token_s * recp[100]; // local record fields struct token_s * grecp[100];// global record fields int rec_qte; // number of local record fields int grec_qte; // number of global record fields khash_t(5) *hfunction; khash_t(6) *hname; // function name = negative stack khash_t(7) *gname; // global name = positif stack #if defined(_MSC_VER) || defined(_WIN32) HMODULE libhandle[64]; int libhandle_qte; // number of global fields #endif kdq_t(int) *callstack; kdq_t(int) *hiforcommand; kdq_t(int) *hinextcommand; khash_t(3) *hidefcommand; khash_t(0) *hcommand; khash_t(1) *hvcommand; kstack_t *harg; int g_forstack[20]; int g_fortop; int lastDef; dllke_hash_add_t dllke_hash_add; dllke_get_out_t dllke_get_out; } sml_t; struct kexpr_s; typedef struct kexpr_s kexpr_t; typedef int * reclistt; struct token_s; typedef struct token_s { int64_t i; double r; union { // void(*builtin)(struct token_s *a, struct token_s *b, struct token_s *out); // execution function double(*real_func1)(double); double(*real_func2)(double, double); int(*defprop)(sml_t* sml, struct token_s* prop, int top); void(*deffunc)(sml_t* sml); int(*defcmd)(sml_t* sml, int itok); int(*defvcmd)(sml_t* sml, int itok); struct token_s * recp; } f; union { // void * ptr; struct token_s * tokp; char *s; char* image; char ** ms; fpos_t * fpos; FILE *file; void *buffer; GDate_t * date; gsl_vector_int * vector_int; gsl_vector * vector; gsl_matrix * matrix; gsl_complex tcomplex; reclistt reclist; PLGraphicsIn * plgrin; PLPointer * plptr; PLTRANSFORM_callback pltrcb; PLMAPFORM_callback plmpcb; PLDEFINED_callback pldefcb; PLLABEL_FUNC_callback pllblcb; PLFILL_callback plfillcb; } obj; char *name; // variable name or function name int32_t ijmp; int32_t sourceLine; // fast jmp uint16_t ttype; uint16_t vtype; int16_t ifield; int8_t icmd; int8_t assigned; int8_t propget; int8_t propset; int8_t tofree; int8_t islocal; int8_t op; int8_t n_args; int8_t realToken; int8_t isfor; } token_t; struct kexpr_s { int n; token_t *e; }; token_t * ke_get_out(sml_t *sml); void ke_hash_add(sml_t *sml, fncp key, char * name); void ke_inc_memory(sml_t *sml); void ke_dec_memory(sml_t *sml); void * ke_calloc_memory(sml_t *sml, size_t i, size_t x); void * ke_malloc_memory(sml_t *sml, size_t i); void ke_free_memory(sml_t *sml, void * m); void ke_print_one(sml_t *sml, token_t* t); gsl_matrix * sml_pop_set_matrix(sml_t * sml); gsl_vector * sml_pop_set_vector(sml_t * sml); gsl_vector_int * sml_pop_set_vector_int(sml_t * sml); gsl_matrix * sml_peek_set_matrix(sml_t * sml, int n); gsl_vector * sml_peek_set_vector(sml_t * sml, int n); gsl_vector_int * sml_peek_set_vector_int(sml_t * sml, int n); void * sml_peek_set_ptr(sml_t * sml, int n); #define __GLOBAL "g_" #define __GLOBAL_SEP "_" #define __GLOBAL_DSEP "__" #define sml_get_top(sml) sml->top #define sml_dec_top(sml) --sml->top #define sml_set_top(sml,top) sml->top=top #define sml_get_stack(sml) sml->stack #define sml_get_tokp(sml) sml->tokp #define sml_get_args(sml) sml->tokp->n_args #define sml_set_args(sml,a) sml->tokp->n_args = a #define sml_get_ttype(sml) sml->tokp->ttype #define sml_get_vtype(sml) sml->tokp->vtype #define sml_get_ijmp(sml) sml->tokp->ijmp #define sml_get_assigned(sml) sml->tokp->assigned #define sml_set_assigned(sml,a) sml->tokp->assigned = a #define sml_pop_token(sml) sml->stack[--sml->top] #define sml_pop_int(sml) sml->stack[--sml->top]->i #define sml_pop_real(sml) sml->stack[--sml->top]->r #define sml_pop_ptr(sml) sml->stack[--sml->top]->obj.ptr #define sml_pop_file(sml) sml->stack[--sml->top]->obj.file #define sml_pop_fpos(sml) sml->stack[--sml->top]->obj.fpos #define sml_pop_str(sml) sml->stack[--sml->top]->obj.s #define sml_pop_date(sml) sml->stack[--sml->top]->obj.date #define sml_pop_complex(sml) sml->stack[--sml->top]->obj.tcomplex #define sml_pop_complex_adr(sml) &sml->stack[--sml->top]->obj.tcomplex #define sml_pop_day(sml) sml->stack[--sml->top]->i #define sml_pop_month(sml) sml->stack[--sml->top]->i #define sml_pop_year(sml) sml->stack[--sml->top]->i #define sml_pop_matrix(sml) sml->stack[--sml->top]->obj.matrix #define sml_pop_vector(sml) sml->stack[--sml->top]->obj.vector #define sml_pop_vector_int(sml) sml->stack[--sml->top]->obj.vector_int #define sml_peek_token(sml,i) sml->stack[i] #define sml_peek_int(sml,ii) sml->stack[ii]->i #define sml_peek_real(sml,i) sml->stack[i]->r #define sml_peek_ptr(sml,i) sml->stack[i]->obj.ptr #define sml_peek_file(sml,i) sml->stack[i]->obj.file #define sml_peek_fpos(sml,i) sml->stack[i]->obj.fpos #define sml_peek_str(sml,i) sml->stack[i]->obj.s #define sml_peek_date(sml,i) sml->stack[i]->obj.date #define sml_peek_complex(sml,i) sml->stack[i]->obj.tcomplex #define sml_peek_complex_adr(sml,i) &sml->stack[i]->obj.tcomplex #define sml_peek_day(sml,i) (GDateDay)sml->stack[i]->i #define sml_peek_month(sml,i) (GDateMonth)sml->stack[i]->i #define sml_peek_year(sml,i) (GDateYear)sml->stack[i]->i #define sml_peek_matrix(sml,i) sml->stack[i]->obj.matrix #define sml_peek_vector(sml,i) sml->stack[i]->obj.vector #define sml_peek_vector_int(sml,i) sml->stack[i]->obj.vector_int #define sml_get_complex_adr &out->obj.tcomplex #define sml_get_type(t) t->vtype #define sml_get_str(t) t->obj.s #define sml_get_real(t) t->r #define sml_get_int(t) t->i #define sml_get_ifield(t) t->ifield #define sml_set_int(sml,t,ii) { int i = t->ifield; \ if (i < 0) { \ i += sml->localtop; \ } \ t = sml->fields[i]; \ t->i = ii; } #define sml_get_ptr(t) t->obj.ptr #define sml_get_file(t) t->obj.file #define sml_get_buffer(t) t->obj.buffer #define sml_get_fpos(t) t->obj.fpos #define sml_set_fpos(sml,t,fposp) { int i = t->ifield; \ if (i < 0) { \ i += sml->localtop; \ } \ t = sml->fields[i]; \ t->obj.fpos = fposp; } #define sml_set_ptr_null(sml,t) { int i = t->ifield; \ if (i < 0) { \ i += sml->localtop; \ } \ t = sml->fields[i]; \ t->obj.ptr = NULL; } #define sml_get_len(t) t->i #define sml_adr_str(t) &t->obj.s #define sml_adr_ptr(t) &t->obj #define sml_get_matrix(t) t->obj.matrix #define sml_get_vector(t) t->obj.vector #define sml_get_vector_int(t) t->obj.vector_int #define sml_get_complex(t) t->obj.complex #define sml_push_buffer(sml, b, ii) token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->obj.buffer = b; \ out->i = ii; \ out->r == (double)ii; \ out->ttype = KET_VAL; \ out->vtype = KEV_BUFFER; #define sml_push_file(sml, file) token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->obj.file = file; \ out->i = 1; \ out->r == 1.0; \ out->ttype = KET_VAL; \ out->vtype = KEV_FILE; #define sml_push_new_complex(sml) token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->ttype = KET_VAL; \ out->vtype = KEV_COMPLEX; #define sml_push_complex(sml, z) token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->obj.tcomplex = z; \ out->ttype = KET_VAL; \ out->vtype = KEV_COMPLEX; #define sml_push_real(sml, r) token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->r = r; \ out->i = (int64_t)r; \ out->ttype = KET_VAL; \ out->vtype = KEV_REAL; #define sml_push_date(sml, dt) token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->obj.date = dt; \ out->ttype = KET_VAL; \ out->vtype = KEV_DATE; #define sml_push_int(sml, ii) token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->i = ii; \ out->r = (double)ii; \ out->ttype = KET_VAL; \ out->vtype = KEV_INT; #define sml_push_ptr(sml, ptr) \ token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->obj.ptr = ptr; \ out->ttype = KET_VAL; \ out->vtype = KEV_PTR; #define sml_push_str(sml, str) \ token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->obj.s = str; \ out->ttype = KET_VAL; \ out->vtype = KEV_STR; #define sml_push_matrix(sml, m) \ token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->obj.matrix = m; \ out->ttype = KET_VAL; \ out->vtype = KEV_MAT; #define sml_push_vector(sml, v) \ token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->obj.vector = v; \ out->ttype = KET_VAL; \ out->vtype = KEV_VEC; #define sml_push_vector_int(sml, v) \ token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->obj.vector_int = v; \ out->ttype = KET_VAL; \ out->vtype = KEV_VEC_INT; #define sml_push_image(sml, image) \ token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->obj.image = image; \ out->ttype = KET_VAL; \ out->vtype = KEV_IMAGE; #define sml_push_fpos(sml, fposp) \ token_t* out; \ sml->stack[sml->top] = ke_get_out(sml); \ out = sml->stack[sml->top++]; \ out->obj.fpos = fposp; \ out->ttype = KET_VAL; \ out->vtype = KEV_FPOS; #define sml_out_date out->obj.date #define sml_free_ptr(sml,ptr) ke_free_memory(sml,ptr); ptr = NULL #define sml_new_ptr(sml,size) ke_calloc_memory(sml, size,1) #define sml_mem_inc ke_inc_memory #define sml_save_str(sml, tokp, tmp) \ int k = tokp->ifield; \ if (k < 0) \ k += sml->localtop; \ tokp = sml->fields[k]; \ if (tokp->vtype == KEV_STR && tokp->obj.s) { \ ke_free_memory(sml, tokp->obj.s); \ } \ tokp->obj.s = tmp; \ tokp->i = 0, tokp->r = 0 ; \ tokp->vtype = KEV_STR; #endif #ifdef _DEBUG #define sml_assert_args(sml,i,fnc) if (sml->tokp->n_args != i) { \ printf("ASSERT ERROR : Invalid number of parameters, expected <%d> got <%d> at line <%d> for function <%s>", i, sml->tokp->n_args, sml->tokp->sourceLine,fnc); \ longjmp(sml->env_buffer, 1); \ } #else #define sml_assert_args(sml,i,s) #endif #ifdef _DEBUG #define sml_assert_args_min(sml,i,fnc) if (sml->tokp->n_args < i) { \ printf("ASSERT ERROR : Invalid number of parameters, expected at least <%d> got <%d> at line <%d> for function <%s>", i, sml->tokp->n_args, sml->tokp->sourceLine,fnc); \ longjmp(sml->env_buffer, 1); \ } #else #define sml_assert_args_min(sml,i,fnc) #endif #ifdef _DEBUG #define sml_assert_type(sml,i,t,fnc) \ if (sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->vtype != t) { \ printf("ASSERT ERROR : Invalid type for parameter #%d, expected <%s> got <%s> at line <%d> for function <%s>", i, kev_to_str[t], kev_to_str[sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->vtype], sml->tokp->sourceLine,fnc); \ longjmp(sml->env_buffer, 1); \ } #else #define sml_assert_type(sml,i,t,s) #endif #ifdef _DEBUG #define sml_assert_type_int_or_real(sml,i,fnc) \ if (sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->vtype != KEV_INT && sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->vtype != KEV_REAL) { \ printf("ASSERT ERROR : Invalid type for parameter #%d, expected <INT OR REAL> got <%s> at line <%d> for function <%s>", i, kev_to_str[sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->vtype], sml->tokp->sourceLine,fnc); \ longjmp(sml->env_buffer, 1); \ } #else #define sml_assert_type_int_or_real(sml,i,s) #endif #ifdef _DEBUG #define sml_assert_str_in(sml,i,search,fnc) \ if (!strstr(search, sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->obj.s)) { \ printf("ASSERT ERROR : Invalid parameter value for parameter #%d, at line <%d> for function <%s>", i, sml->tokp->sourceLine,fnc); \ longjmp(sml->env_buffer, 1); \ } #else #define sml_assert_str_in(sml,i,f,s) #endif #ifdef _DEBUG #define sml_assert_str(sml,i,fnc) \ if (!strlen(sml->stack[sml->top - 1 - (sml->tokp->n_args - i)]->obj.s)) { \ printf("ASSERT ERROR : Invalid parameter value (empty) for parameter #%d, at line <%d> for function <%s>", i, sml->tokp->sourceLine,fnc); \ longjmp(sml->env_buffer, 1); \ } #else #define sml_assert_str(sml,i,fnc) #endif #ifdef _DEBUG #define sml_assert_size(sml,size,i,fnc) \ if (size <= 0) { \ printf("ASSERT ERROR : Invalid parameter value (<=0) for parameter #%d, at line <%d> for function <%s>", i, sml->tokp->sourceLine,fnc); \ longjmp(sml->env_buffer, 1); \ } #else #define sml_assert_size(sml,size,i,fnc) #endif #ifdef _DEBUG #define sml_assert_gz(sml,size,fnc) \ if (size < 0) { \ printf("ASSERT ERROR : Invalid parameters (size validation < 0) at line <%d> for function <%s>", sml->tokp->sourceLine,fnc); \ longjmp(sml->env_buffer, 1); \ } #else #define sml_assert_gz(sml,size,fnc) #endif #ifdef _DEBUG #define sml_assert_ptr(sml,p,i,fnc) \ if (p == NULL) { \ printf("ASSERT ERROR : Invalid parameter value (==NULL) for parameter #%d, at line <%d> for function <%s>", i, sml->tokp->sourceLine,fnc); \ longjmp(sml->env_buffer, 1); \ } #else #define sml_assert_ptr(sml,p,i,fnc) #endif #ifdef _DEBUG #define sml_assert_range(sml,i,v,from,to,fnc) \ if (v < from || v > to) { \ printf("ASSERT ERROR : Invalid parameter value <%d> expected (%d - %d) for parameter #%d, at line <%d> for function <%s>", v, from, to, i, sml->tokp->sourceLine,fnc); \ longjmp(sml->env_buffer, 1); \ } #else #define sml_assert_range(sml,i,v,from,to,fnc) #endif #define sml_fatal_error(sml,c,fnc) \ printf("ASSERT ERROR : Fatal error <%s> at line <%d> for function <%s>", c, sml->tokp->sourceLine , fnc); \ longjmp(sml->env_buffer, 1);
{ "alphanum_fraction": 0.6834813309, "avg_line_length": 29.9583333333, "ext": "h", "hexsha": "713b860a7b2c240e40bae6cefac347cbbdc1b908", "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": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "vinej/sml", "max_forks_repo_path": "api.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "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": "vinej/sml", "max_issues_repo_path": "api.h", "max_line_length": 231, "max_stars_count": null, "max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "vinej/sml", "max_stars_repo_path": "api.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6401, "size": 18694 }
/* fft/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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <string.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_dft_complex.h> #include <gsl/gsl_fft_complex.h> #include <gsl/gsl_fft_complex_float.h> #include <gsl/gsl_fft_real.h> #include <gsl/gsl_fft_real_float.h> #include <gsl/gsl_fft_halfcomplex.h> #include <gsl/gsl_fft_halfcomplex_float.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_test.h> void my_error_handler (const char *reason, const char *file, int line, int err); #include "complex_internal.h" /* Usage: test [n] Exercise the fft routines for length n. By default n runs from 1 to 100. The exit status indicates success or failure. */ #define BASE_DOUBLE #include "templates_on.h" #include "compare_source.c" #include "bitreverse.c" #include "test_complex_source.c" #include "test_real_source.c" #include "test_trap_source.c" #include "templates_off.h" #undef BASE_DOUBLE #define BASE_FLOAT #include "templates_on.h" #include "compare_source.c" #include "bitreverse.c" #include "test_complex_source.c" #include "test_real_source.c" #include "test_trap_source.c" #include "templates_off.h" #undef BASE_FLOAT int main (int argc, char *argv[]) { size_t i; size_t start = 1, end = 99; size_t stride ; size_t n = 0; gsl_ieee_env_setup (); if (argc == 2) n = strtol (argv[1], NULL, 0); if (n) { start = n ; end = n ; } for (i = 1 ; i <= end ; i *= 2) { if (i >= start) { for (stride = 1 ; stride < 4 ; stride++) { test_complex_bitreverse_order (stride, i) ; test_complex_radix2 (stride, i) ; test_real_bitreverse_order (stride, i) ; test_real_radix2 (stride, i) ; } } } for (i = start ; i <= end ; i++) { for (stride = 1 ; stride < 4 ; stride++) { test_complex_func (stride, i) ; test_complex_float_func (stride, i) ; test_real_func (stride, i) ; test_real_float_func (stride, i) ; } } gsl_set_error_handler (&my_error_handler); test_trap () ; test_float_trap () ; exit (gsl_test_summary ()); } void my_error_handler (const char *reason, const char *file, int line, int err) { if (0) printf ("(caught [%s:%d: %s (%d)])\n", file, line, reason, err) ; }
{ "alphanum_fraction": 0.6547181373, "avg_line_length": 25.7007874016, "ext": "c", "hexsha": "779a056f266e3eef777bfb06d3c16f37c07c25eb", "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/fft/test.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/fft/test.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/fft/test.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 882, "size": 3264 }
/** * * @file core_zpltmg_circul.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.8.0 * @author Mathieu Faverge * @date 2010-11-15 * @precisions normal z -> c d s * **/ #include <lapacke.h> #include <math.h> #include "common.h" /***************************************************************************//** * * @ingroup dplasma_cores_complex64 * * CORE_zpltmg_circul is a kernel used in circulant matrix generation * * See http://www.mathworks.fr/fr/help/matlab/ref/gallery.html#f84-999880 * * Circulant matrix * * A circulant matrix has the property that each row is obtained from the * previous one by cyclically permuting the entries one step forward. It is a * special Toeplitz matrix in which the diagonals "wrap around." * * The eigensystem of C (n-by-n) is known explicitly: If t is an nth root of * unity, then the inner product of v and w = [1 t t2 ... t(n – 1)] is an * eigenvalue of C and w(n:-1:1) is an eigenvector, where v is the first column of * C. * * ******************************************************************************* * * @param[in] M * The number of rows of the tile A to initialize. M >= 2. * * @param[in] N * The number of columns of the tile A to initialize. N >= 0. * * @param[out] A * On entry, the M-by-N tile to be initialized. * * @param[in] LDA * The leading dimension of the tile A. LDA >= max(1,M). * * @param[in] gM * The global number of rows of the full matrix, A is belonging to. gM >= (m0+gM). * * @param[in] m0 * The index of the first row of tile A in the full matrix. m0 >= 0. * * @param[in] n0 * The index of the first column of tile A in the full matrix. n0 >= 0. * * @param[in] V * Workspace of size gM, that contains the first clumn of the full matrix * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if INFO = -k, the k-th argument had an illegal value * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zpltmg_circul = PCORE_zpltmg_circul #define CORE_zpltmg_circul PCORE_zpltmg_circul #endif int CORE_zpltmg_circul( int M, int N, PLASMA_Complex64_t *A, int LDA, int gM, int m0, int n0, const PLASMA_Complex64_t *V ) { int i, j, ii, jj; /* Check input arguments */ if (M < 0) { coreblas_error(1, "Illegal value of M"); return -1; } if (N < 0) { coreblas_error(2, "Illegal value of N"); return -2; } if ((LDA < max(1,M)) && (M > 0)) { coreblas_error(4, "Illegal value of LDA"); return -4; } if (m0 < 0) { coreblas_error(6, "Illegal value of m0"); return -6; } if (n0 < 0) { coreblas_error(7, "Illegal value of n0"); return -7; } if (gM < m0+M) { coreblas_error(5, "Illegal value of gM"); return -5; } for (j=0, jj=n0; j<N; j++, jj++) { for (i=0, ii=m0; i<M; i++, ii++) { A[LDA*j + i] = V[ (jj-ii+gM)%gM ]; } } return PLASMA_SUCCESS; }
{ "alphanum_fraction": 0.5331564987, "avg_line_length": 29.25, "ext": "c", "hexsha": "64a8cebddfedf04c163f0a8fcf2d37052feb34e7", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z", "max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z", "max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "therault/dplasma", "max_forks_repo_path": "src/cores/core_zpltmg_circul.c", "max_issues_count": 5, "max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "therault/dplasma", "max_issues_repo_path": "src/cores/core_zpltmg_circul.c", "max_line_length": 90, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "therault/dplasma", "max_stars_repo_path": "src/cores/core_zpltmg_circul.c", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z", "num_tokens": 977, "size": 3393 }
/* * Copyright (c) 1997-1999 Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* This file was automatically generated --- DO NOT EDIT */ /* Generated on Sun Nov 7 20:44:52 EST 1999 */ #include <fftw-int.h> #include <fftw.h> /* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2hc-forward 32 */ /* * This function contains 764 FP additions, 340 FP multiplications, * (or, 618 additions, 194 multiplications, 146 fused multiply/add), * 91 stack variables, and 256 memory accesses */ static const fftw_real K145142338 = FFTW_KONST(+0.145142338627231183818096187908697637345738139); static const fftw_real K478470167 = FFTW_KONST(+0.478470167866104432467898943490134984741424603); static const fftw_real K235698368 = FFTW_KONST(+0.235698368412998824278193812952627188828730159); static const fftw_real K440960632 = FFTW_KONST(+0.440960632174177514856378431830194174754221310); static const fftw_real K317196642 = FFTW_KONST(+0.317196642081822749107585806612746685337843547); static const fftw_real K386505226 = FFTW_KONST(+0.386505226681368480405453304879234900485520646); static const fftw_real K497592363 = FFTW_KONST(+0.497592363336098443122418476554739960787737434); static const fftw_real K049008570 = FFTW_KONST(+0.049008570164780300997097781944320922930568337); static const fftw_real K277785116 = FFTW_KONST(+0.277785116509801112371415406974266437187468595); static const fftw_real K415734806 = FFTW_KONST(+0.415734806151272618539394188808952878369280406); static const fftw_real K097545161 = FFTW_KONST(+0.097545161008064133924142434238511120463845809); static const fftw_real K490392640 = FFTW_KONST(+0.490392640201615224563091118067119518486966865); static const fftw_real K765366864 = FFTW_KONST(+0.765366864730179543456919968060797733522689125); static const fftw_real K1_847759065 = FFTW_KONST(+1.847759065022573512256366378793576573644833252); static const fftw_real K1_414213562 = FFTW_KONST(+1.414213562373095048801688724209698078569671875); static const fftw_real K2_000000000 = FFTW_KONST(+2.000000000000000000000000000000000000000000000); static const fftw_real K195090322 = FFTW_KONST(+0.195090322016128267848284868477022240927691618); static const fftw_real K980785280 = FFTW_KONST(+0.980785280403230449126182236134239036973933731); static const fftw_real K555570233 = FFTW_KONST(+0.555570233019602224742830813948532874374937191); static const fftw_real K831469612 = FFTW_KONST(+0.831469612302545237078788377617905756738560812); static const fftw_real K382683432 = FFTW_KONST(+0.382683432365089771728459984030398866761344562); static const fftw_real K923879532 = FFTW_KONST(+0.923879532511286756128183189396788286822416626); static const fftw_real K707106781 = FFTW_KONST(+0.707106781186547524400844362104849039284835938); /* * Generator Id's : * $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $ * $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $ * $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $ */ void fftw_hc2hc_forward_32(fftw_real *A, const fftw_complex *W, int iostride, int m, int dist) { int i; fftw_real *X; fftw_real *Y; X = A; Y = A + (32 * iostride); { fftw_real tmp685; fftw_real tmp813; fftw_real tmp709; fftw_real tmp761; fftw_real tmp692; fftw_real tmp826; fftw_real tmp712; fftw_real tmp760; fftw_real tmp801; fftw_real tmp821; fftw_real tmp749; fftw_real tmp777; fftw_real tmp804; fftw_real tmp822; fftw_real tmp754; fftw_real tmp778; fftw_real tmp700; fftw_real tmp814; fftw_real tmp716; fftw_real tmp758; fftw_real tmp707; fftw_real tmp815; fftw_real tmp719; fftw_real tmp757; fftw_real tmp794; fftw_real tmp818; fftw_real tmp732; fftw_real tmp774; fftw_real tmp797; fftw_real tmp819; fftw_real tmp737; fftw_real tmp775; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp679; fftw_real tmp680; fftw_real tmp681; fftw_real tmp682; fftw_real tmp683; fftw_real tmp684; ASSERT_ALIGNED_DOUBLE; tmp679 = X[0]; tmp680 = X[16 * iostride]; tmp681 = tmp679 + tmp680; tmp682 = X[8 * iostride]; tmp683 = X[24 * iostride]; tmp684 = tmp682 + tmp683; tmp685 = tmp681 + tmp684; tmp813 = tmp681 - tmp684; tmp709 = tmp679 - tmp680; tmp761 = tmp682 - tmp683; } { fftw_real tmp688; fftw_real tmp710; fftw_real tmp691; fftw_real tmp711; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp686; fftw_real tmp687; fftw_real tmp689; fftw_real tmp690; ASSERT_ALIGNED_DOUBLE; tmp686 = X[4 * iostride]; tmp687 = X[20 * iostride]; tmp688 = tmp686 + tmp687; tmp710 = tmp686 - tmp687; tmp689 = X[28 * iostride]; tmp690 = X[12 * iostride]; tmp691 = tmp689 + tmp690; tmp711 = tmp689 - tmp690; } tmp692 = tmp688 + tmp691; tmp826 = tmp691 - tmp688; tmp712 = K707106781 * (tmp710 + tmp711); tmp760 = K707106781 * (tmp711 - tmp710); } { fftw_real tmp741; fftw_real tmp799; fftw_real tmp753; fftw_real tmp800; fftw_real tmp744; fftw_real tmp802; fftw_real tmp747; fftw_real tmp803; fftw_real tmp748; fftw_real tmp750; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp739; fftw_real tmp740; fftw_real tmp751; fftw_real tmp752; ASSERT_ALIGNED_DOUBLE; tmp739 = X[31 * iostride]; tmp740 = X[15 * iostride]; tmp741 = tmp739 - tmp740; tmp799 = tmp739 + tmp740; tmp751 = X[7 * iostride]; tmp752 = X[23 * iostride]; tmp753 = tmp751 - tmp752; tmp800 = tmp751 + tmp752; } { fftw_real tmp742; fftw_real tmp743; fftw_real tmp745; fftw_real tmp746; ASSERT_ALIGNED_DOUBLE; tmp742 = X[3 * iostride]; tmp743 = X[19 * iostride]; tmp744 = tmp742 - tmp743; tmp802 = tmp742 + tmp743; tmp745 = X[27 * iostride]; tmp746 = X[11 * iostride]; tmp747 = tmp745 - tmp746; tmp803 = tmp745 + tmp746; } tmp801 = tmp799 + tmp800; tmp821 = tmp799 - tmp800; tmp748 = K707106781 * (tmp744 + tmp747); tmp749 = tmp741 + tmp748; tmp777 = tmp741 - tmp748; tmp804 = tmp802 + tmp803; tmp822 = tmp803 - tmp802; tmp750 = K707106781 * (tmp747 - tmp744); tmp754 = tmp750 - tmp753; tmp778 = tmp753 + tmp750; } { fftw_real tmp696; fftw_real tmp714; fftw_real tmp699; fftw_real tmp715; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp694; fftw_real tmp695; fftw_real tmp697; fftw_real tmp698; ASSERT_ALIGNED_DOUBLE; tmp694 = X[2 * iostride]; tmp695 = X[18 * iostride]; tmp696 = tmp694 + tmp695; tmp714 = tmp694 - tmp695; tmp697 = X[10 * iostride]; tmp698 = X[26 * iostride]; tmp699 = tmp697 + tmp698; tmp715 = tmp697 - tmp698; } tmp700 = tmp696 + tmp699; tmp814 = tmp696 - tmp699; tmp716 = (K923879532 * tmp714) - (K382683432 * tmp715); tmp758 = (K382683432 * tmp714) + (K923879532 * tmp715); } { fftw_real tmp703; fftw_real tmp717; fftw_real tmp706; fftw_real tmp718; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp701; fftw_real tmp702; fftw_real tmp704; fftw_real tmp705; ASSERT_ALIGNED_DOUBLE; tmp701 = X[30 * iostride]; tmp702 = X[14 * iostride]; tmp703 = tmp701 + tmp702; tmp717 = tmp701 - tmp702; tmp704 = X[6 * iostride]; tmp705 = X[22 * iostride]; tmp706 = tmp704 + tmp705; tmp718 = tmp704 - tmp705; } tmp707 = tmp703 + tmp706; tmp815 = tmp703 - tmp706; tmp719 = (K923879532 * tmp717) + (K382683432 * tmp718); tmp757 = (K382683432 * tmp717) - (K923879532 * tmp718); } { fftw_real tmp724; fftw_real tmp792; fftw_real tmp736; fftw_real tmp793; fftw_real tmp727; fftw_real tmp795; fftw_real tmp730; fftw_real tmp796; fftw_real tmp731; fftw_real tmp733; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp722; fftw_real tmp723; fftw_real tmp734; fftw_real tmp735; ASSERT_ALIGNED_DOUBLE; tmp722 = X[iostride]; tmp723 = X[17 * iostride]; tmp724 = tmp722 - tmp723; tmp792 = tmp722 + tmp723; tmp734 = X[9 * iostride]; tmp735 = X[25 * iostride]; tmp736 = tmp734 - tmp735; tmp793 = tmp734 + tmp735; } { fftw_real tmp725; fftw_real tmp726; fftw_real tmp728; fftw_real tmp729; ASSERT_ALIGNED_DOUBLE; tmp725 = X[5 * iostride]; tmp726 = X[21 * iostride]; tmp727 = tmp725 - tmp726; tmp795 = tmp725 + tmp726; tmp728 = X[29 * iostride]; tmp729 = X[13 * iostride]; tmp730 = tmp728 - tmp729; tmp796 = tmp728 + tmp729; } tmp794 = tmp792 + tmp793; tmp818 = tmp792 - tmp793; tmp731 = K707106781 * (tmp727 + tmp730); tmp732 = tmp724 + tmp731; tmp774 = tmp724 - tmp731; tmp797 = tmp795 + tmp796; tmp819 = tmp796 - tmp795; tmp733 = K707106781 * (tmp730 - tmp727); tmp737 = tmp733 - tmp736; tmp775 = tmp736 + tmp733; } { fftw_real tmp693; fftw_real tmp708; fftw_real tmp809; fftw_real tmp810; fftw_real tmp811; fftw_real tmp812; ASSERT_ALIGNED_DOUBLE; tmp693 = tmp685 + tmp692; tmp708 = tmp700 + tmp707; tmp809 = tmp693 + tmp708; tmp810 = tmp794 + tmp797; tmp811 = tmp801 + tmp804; tmp812 = tmp810 + tmp811; X[8 * iostride] = tmp693 - tmp708; Y[-8 * iostride] = tmp811 - tmp810; X[16 * iostride] = tmp809 - tmp812; X[0] = tmp809 + tmp812; } { fftw_real tmp791; fftw_real tmp807; fftw_real tmp806; fftw_real tmp808; fftw_real tmp798; fftw_real tmp805; ASSERT_ALIGNED_DOUBLE; tmp791 = tmp685 - tmp692; tmp807 = tmp707 - tmp700; tmp798 = tmp794 - tmp797; tmp805 = tmp801 - tmp804; tmp806 = K707106781 * (tmp798 + tmp805); tmp808 = K707106781 * (tmp805 - tmp798); X[12 * iostride] = tmp791 - tmp806; X[4 * iostride] = tmp791 + tmp806; Y[-4 * iostride] = tmp807 + tmp808; Y[-12 * iostride] = tmp808 - tmp807; } { fftw_real tmp817; fftw_real tmp833; fftw_real tmp827; fftw_real tmp829; fftw_real tmp824; fftw_real tmp828; fftw_real tmp832; fftw_real tmp834; fftw_real tmp816; fftw_real tmp825; ASSERT_ALIGNED_DOUBLE; tmp816 = K707106781 * (tmp814 + tmp815); tmp817 = tmp813 + tmp816; tmp833 = tmp813 - tmp816; tmp825 = K707106781 * (tmp815 - tmp814); tmp827 = tmp825 - tmp826; tmp829 = tmp826 + tmp825; { fftw_real tmp820; fftw_real tmp823; fftw_real tmp830; fftw_real tmp831; ASSERT_ALIGNED_DOUBLE; tmp820 = (K923879532 * tmp818) + (K382683432 * tmp819); tmp823 = (K923879532 * tmp821) - (K382683432 * tmp822); tmp824 = tmp820 + tmp823; tmp828 = tmp823 - tmp820; tmp830 = (K923879532 * tmp819) - (K382683432 * tmp818); tmp831 = (K382683432 * tmp821) + (K923879532 * tmp822); tmp832 = tmp830 + tmp831; tmp834 = tmp831 - tmp830; } X[14 * iostride] = tmp817 - tmp824; X[2 * iostride] = tmp817 + tmp824; Y[-6 * iostride] = tmp827 + tmp828; Y[-10 * iostride] = tmp828 - tmp827; Y[-2 * iostride] = tmp829 + tmp832; Y[-14 * iostride] = tmp832 - tmp829; X[10 * iostride] = tmp833 - tmp834; X[6 * iostride] = tmp833 + tmp834; } { fftw_real tmp773; fftw_real tmp789; fftw_real tmp788; fftw_real tmp790; fftw_real tmp780; fftw_real tmp784; fftw_real tmp783; fftw_real tmp785; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp771; fftw_real tmp772; fftw_real tmp786; fftw_real tmp787; ASSERT_ALIGNED_DOUBLE; tmp771 = tmp709 - tmp712; tmp772 = tmp758 + tmp757; tmp773 = tmp771 + tmp772; tmp789 = tmp771 - tmp772; tmp786 = (K831469612 * tmp775) - (K555570233 * tmp774); tmp787 = (K555570233 * tmp777) + (K831469612 * tmp778); tmp788 = tmp786 + tmp787; tmp790 = tmp787 - tmp786; } { fftw_real tmp776; fftw_real tmp779; fftw_real tmp781; fftw_real tmp782; ASSERT_ALIGNED_DOUBLE; tmp776 = (K831469612 * tmp774) + (K555570233 * tmp775); tmp779 = (K831469612 * tmp777) - (K555570233 * tmp778); tmp780 = tmp776 + tmp779; tmp784 = tmp779 - tmp776; tmp781 = tmp719 - tmp716; tmp782 = tmp761 + tmp760; tmp783 = tmp781 - tmp782; tmp785 = tmp782 + tmp781; } X[13 * iostride] = tmp773 - tmp780; X[3 * iostride] = tmp773 + tmp780; Y[-5 * iostride] = tmp783 + tmp784; Y[-11 * iostride] = tmp784 - tmp783; Y[-3 * iostride] = tmp785 + tmp788; Y[-13 * iostride] = tmp788 - tmp785; X[11 * iostride] = tmp789 - tmp790; X[5 * iostride] = tmp789 + tmp790; } { fftw_real tmp721; fftw_real tmp769; fftw_real tmp768; fftw_real tmp770; fftw_real tmp756; fftw_real tmp764; fftw_real tmp763; fftw_real tmp765; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp713; fftw_real tmp720; fftw_real tmp766; fftw_real tmp767; ASSERT_ALIGNED_DOUBLE; tmp713 = tmp709 + tmp712; tmp720 = tmp716 + tmp719; tmp721 = tmp713 + tmp720; tmp769 = tmp713 - tmp720; tmp766 = (K980785280 * tmp737) - (K195090322 * tmp732); tmp767 = (K195090322 * tmp749) + (K980785280 * tmp754); tmp768 = tmp766 + tmp767; tmp770 = tmp767 - tmp766; } { fftw_real tmp738; fftw_real tmp755; fftw_real tmp759; fftw_real tmp762; ASSERT_ALIGNED_DOUBLE; tmp738 = (K980785280 * tmp732) + (K195090322 * tmp737); tmp755 = (K980785280 * tmp749) - (K195090322 * tmp754); tmp756 = tmp738 + tmp755; tmp764 = tmp755 - tmp738; tmp759 = tmp757 - tmp758; tmp762 = tmp760 - tmp761; tmp763 = tmp759 - tmp762; tmp765 = tmp762 + tmp759; } X[15 * iostride] = tmp721 - tmp756; X[iostride] = tmp721 + tmp756; Y[-7 * iostride] = tmp763 + tmp764; Y[-9 * iostride] = tmp764 - tmp763; Y[-iostride] = tmp765 + tmp768; Y[-15 * iostride] = tmp768 - tmp765; X[9 * iostride] = tmp769 - tmp770; X[7 * iostride] = tmp769 + tmp770; } } X = X + dist; Y = Y - dist; for (i = 2; i < m; i = i + 2, X = X + dist, Y = Y - dist, W = W + 31) { fftw_real tmp201; fftw_real tmp533; fftw_real tmp653; fftw_real tmp667; fftw_real tmp623; fftw_real tmp637; fftw_real tmp373; fftw_real tmp485; fftw_real tmp343; fftw_real tmp561; fftw_real tmp458; fftw_real tmp508; fftw_real tmp568; fftw_real tmp604; fftw_real tmp441; fftw_real tmp505; fftw_real tmp224; fftw_real tmp636; fftw_real tmp383; fftw_real tmp487; fftw_real tmp536; fftw_real tmp618; fftw_real tmp378; fftw_real tmp486; fftw_real tmp366; fftw_real tmp569; fftw_real tmp564; fftw_real tmp605; fftw_real tmp452; fftw_real tmp509; fftw_real tmp461; fftw_real tmp506; fftw_real tmp248; fftw_real tmp541; fftw_real tmp395; fftw_real tmp491; fftw_real tmp540; fftw_real tmp594; fftw_real tmp390; fftw_real tmp490; fftw_real tmp296; fftw_real tmp555; fftw_real tmp431; fftw_real tmp498; fftw_real tmp552; fftw_real tmp599; fftw_real tmp414; fftw_real tmp501; fftw_real tmp271; fftw_real tmp543; fftw_real tmp406; fftw_real tmp494; fftw_real tmp546; fftw_real tmp595; fftw_real tmp401; fftw_real tmp493; fftw_real tmp319; fftw_real tmp553; fftw_real tmp558; fftw_real tmp600; fftw_real tmp425; fftw_real tmp499; fftw_real tmp434; fftw_real tmp502; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp183; fftw_real tmp621; fftw_real tmp188; fftw_real tmp620; fftw_real tmp194; fftw_real tmp370; fftw_real tmp199; fftw_real tmp371; ASSERT_ALIGNED_DOUBLE; tmp183 = X[0]; tmp621 = Y[-31 * iostride]; { fftw_real tmp185; fftw_real tmp187; fftw_real tmp184; fftw_real tmp186; ASSERT_ALIGNED_DOUBLE; tmp185 = X[16 * iostride]; tmp187 = Y[-15 * iostride]; tmp184 = c_re(W[15]); tmp186 = c_im(W[15]); tmp188 = (tmp184 * tmp185) - (tmp186 * tmp187); tmp620 = (tmp186 * tmp185) + (tmp184 * tmp187); } { fftw_real tmp191; fftw_real tmp193; fftw_real tmp190; fftw_real tmp192; ASSERT_ALIGNED_DOUBLE; tmp191 = X[8 * iostride]; tmp193 = Y[-23 * iostride]; tmp190 = c_re(W[7]); tmp192 = c_im(W[7]); tmp194 = (tmp190 * tmp191) - (tmp192 * tmp193); tmp370 = (tmp192 * tmp191) + (tmp190 * tmp193); } { fftw_real tmp196; fftw_real tmp198; fftw_real tmp195; fftw_real tmp197; ASSERT_ALIGNED_DOUBLE; tmp196 = X[24 * iostride]; tmp198 = Y[-7 * iostride]; tmp195 = c_re(W[23]); tmp197 = c_im(W[23]); tmp199 = (tmp195 * tmp196) - (tmp197 * tmp198); tmp371 = (tmp197 * tmp196) + (tmp195 * tmp198); } { fftw_real tmp189; fftw_real tmp200; fftw_real tmp651; fftw_real tmp652; ASSERT_ALIGNED_DOUBLE; tmp189 = tmp183 + tmp188; tmp200 = tmp194 + tmp199; tmp201 = tmp189 + tmp200; tmp533 = tmp189 - tmp200; tmp651 = tmp621 - tmp620; tmp652 = tmp194 - tmp199; tmp653 = tmp651 - tmp652; tmp667 = tmp652 + tmp651; } { fftw_real tmp619; fftw_real tmp622; fftw_real tmp369; fftw_real tmp372; ASSERT_ALIGNED_DOUBLE; tmp619 = tmp370 + tmp371; tmp622 = tmp620 + tmp621; tmp623 = tmp619 + tmp622; tmp637 = tmp622 - tmp619; tmp369 = tmp183 - tmp188; tmp372 = tmp370 - tmp371; tmp373 = tmp369 - tmp372; tmp485 = tmp369 + tmp372; } } { fftw_real tmp325; fftw_real tmp454; fftw_real tmp341; fftw_real tmp439; fftw_real tmp330; fftw_real tmp455; fftw_real tmp336; fftw_real tmp438; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp322; fftw_real tmp324; fftw_real tmp321; fftw_real tmp323; ASSERT_ALIGNED_DOUBLE; tmp322 = X[31 * iostride]; tmp324 = Y[0]; tmp321 = c_re(W[30]); tmp323 = c_im(W[30]); tmp325 = (tmp321 * tmp322) - (tmp323 * tmp324); tmp454 = (tmp323 * tmp322) + (tmp321 * tmp324); } { fftw_real tmp338; fftw_real tmp340; fftw_real tmp337; fftw_real tmp339; ASSERT_ALIGNED_DOUBLE; tmp338 = X[23 * iostride]; tmp340 = Y[-8 * iostride]; tmp337 = c_re(W[22]); tmp339 = c_im(W[22]); tmp341 = (tmp337 * tmp338) - (tmp339 * tmp340); tmp439 = (tmp339 * tmp338) + (tmp337 * tmp340); } { fftw_real tmp327; fftw_real tmp329; fftw_real tmp326; fftw_real tmp328; ASSERT_ALIGNED_DOUBLE; tmp327 = X[15 * iostride]; tmp329 = Y[-16 * iostride]; tmp326 = c_re(W[14]); tmp328 = c_im(W[14]); tmp330 = (tmp326 * tmp327) - (tmp328 * tmp329); tmp455 = (tmp328 * tmp327) + (tmp326 * tmp329); } { fftw_real tmp333; fftw_real tmp335; fftw_real tmp332; fftw_real tmp334; ASSERT_ALIGNED_DOUBLE; tmp333 = X[7 * iostride]; tmp335 = Y[-24 * iostride]; tmp332 = c_re(W[6]); tmp334 = c_im(W[6]); tmp336 = (tmp332 * tmp333) - (tmp334 * tmp335); tmp438 = (tmp334 * tmp333) + (tmp332 * tmp335); } { fftw_real tmp331; fftw_real tmp342; fftw_real tmp456; fftw_real tmp457; ASSERT_ALIGNED_DOUBLE; tmp331 = tmp325 + tmp330; tmp342 = tmp336 + tmp341; tmp343 = tmp331 + tmp342; tmp561 = tmp331 - tmp342; tmp456 = tmp454 - tmp455; tmp457 = tmp336 - tmp341; tmp458 = tmp456 + tmp457; tmp508 = tmp456 - tmp457; } { fftw_real tmp566; fftw_real tmp567; fftw_real tmp437; fftw_real tmp440; ASSERT_ALIGNED_DOUBLE; tmp566 = tmp454 + tmp455; tmp567 = tmp438 + tmp439; tmp568 = tmp566 - tmp567; tmp604 = tmp566 + tmp567; tmp437 = tmp325 - tmp330; tmp440 = tmp438 - tmp439; tmp441 = tmp437 - tmp440; tmp505 = tmp437 + tmp440; } } { fftw_real tmp206; fftw_real tmp374; fftw_real tmp222; fftw_real tmp381; fftw_real tmp211; fftw_real tmp375; fftw_real tmp217; fftw_real tmp380; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp203; fftw_real tmp205; fftw_real tmp202; fftw_real tmp204; ASSERT_ALIGNED_DOUBLE; tmp203 = X[4 * iostride]; tmp205 = Y[-27 * iostride]; tmp202 = c_re(W[3]); tmp204 = c_im(W[3]); tmp206 = (tmp202 * tmp203) - (tmp204 * tmp205); tmp374 = (tmp204 * tmp203) + (tmp202 * tmp205); } { fftw_real tmp219; fftw_real tmp221; fftw_real tmp218; fftw_real tmp220; ASSERT_ALIGNED_DOUBLE; tmp219 = X[12 * iostride]; tmp221 = Y[-19 * iostride]; tmp218 = c_re(W[11]); tmp220 = c_im(W[11]); tmp222 = (tmp218 * tmp219) - (tmp220 * tmp221); tmp381 = (tmp220 * tmp219) + (tmp218 * tmp221); } { fftw_real tmp208; fftw_real tmp210; fftw_real tmp207; fftw_real tmp209; ASSERT_ALIGNED_DOUBLE; tmp208 = X[20 * iostride]; tmp210 = Y[-11 * iostride]; tmp207 = c_re(W[19]); tmp209 = c_im(W[19]); tmp211 = (tmp207 * tmp208) - (tmp209 * tmp210); tmp375 = (tmp209 * tmp208) + (tmp207 * tmp210); } { fftw_real tmp214; fftw_real tmp216; fftw_real tmp213; fftw_real tmp215; ASSERT_ALIGNED_DOUBLE; tmp214 = X[28 * iostride]; tmp216 = Y[-3 * iostride]; tmp213 = c_re(W[27]); tmp215 = c_im(W[27]); tmp217 = (tmp213 * tmp214) - (tmp215 * tmp216); tmp380 = (tmp215 * tmp214) + (tmp213 * tmp216); } { fftw_real tmp212; fftw_real tmp223; fftw_real tmp379; fftw_real tmp382; ASSERT_ALIGNED_DOUBLE; tmp212 = tmp206 + tmp211; tmp223 = tmp217 + tmp222; tmp224 = tmp212 + tmp223; tmp636 = tmp223 - tmp212; tmp379 = tmp217 - tmp222; tmp382 = tmp380 - tmp381; tmp383 = tmp379 + tmp382; tmp487 = tmp379 - tmp382; } { fftw_real tmp534; fftw_real tmp535; fftw_real tmp376; fftw_real tmp377; ASSERT_ALIGNED_DOUBLE; tmp534 = tmp374 + tmp375; tmp535 = tmp380 + tmp381; tmp536 = tmp534 - tmp535; tmp618 = tmp534 + tmp535; tmp376 = tmp374 - tmp375; tmp377 = tmp206 - tmp211; tmp378 = tmp376 - tmp377; tmp486 = tmp377 + tmp376; } } { fftw_real tmp348; fftw_real tmp442; fftw_real tmp353; fftw_real tmp443; fftw_real tmp444; fftw_real tmp445; fftw_real tmp359; fftw_real tmp448; fftw_real tmp364; fftw_real tmp449; fftw_real tmp447; fftw_real tmp450; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp345; fftw_real tmp347; fftw_real tmp344; fftw_real tmp346; ASSERT_ALIGNED_DOUBLE; tmp345 = X[3 * iostride]; tmp347 = Y[-28 * iostride]; tmp344 = c_re(W[2]); tmp346 = c_im(W[2]); tmp348 = (tmp344 * tmp345) - (tmp346 * tmp347); tmp442 = (tmp346 * tmp345) + (tmp344 * tmp347); } { fftw_real tmp350; fftw_real tmp352; fftw_real tmp349; fftw_real tmp351; ASSERT_ALIGNED_DOUBLE; tmp350 = X[19 * iostride]; tmp352 = Y[-12 * iostride]; tmp349 = c_re(W[18]); tmp351 = c_im(W[18]); tmp353 = (tmp349 * tmp350) - (tmp351 * tmp352); tmp443 = (tmp351 * tmp350) + (tmp349 * tmp352); } tmp444 = tmp442 - tmp443; tmp445 = tmp348 - tmp353; { fftw_real tmp356; fftw_real tmp358; fftw_real tmp355; fftw_real tmp357; ASSERT_ALIGNED_DOUBLE; tmp356 = X[27 * iostride]; tmp358 = Y[-4 * iostride]; tmp355 = c_re(W[26]); tmp357 = c_im(W[26]); tmp359 = (tmp355 * tmp356) - (tmp357 * tmp358); tmp448 = (tmp357 * tmp356) + (tmp355 * tmp358); } { fftw_real tmp361; fftw_real tmp363; fftw_real tmp360; fftw_real tmp362; ASSERT_ALIGNED_DOUBLE; tmp361 = X[11 * iostride]; tmp363 = Y[-20 * iostride]; tmp360 = c_re(W[10]); tmp362 = c_im(W[10]); tmp364 = (tmp360 * tmp361) - (tmp362 * tmp363); tmp449 = (tmp362 * tmp361) + (tmp360 * tmp363); } tmp447 = tmp359 - tmp364; tmp450 = tmp448 - tmp449; { fftw_real tmp354; fftw_real tmp365; fftw_real tmp562; fftw_real tmp563; ASSERT_ALIGNED_DOUBLE; tmp354 = tmp348 + tmp353; tmp365 = tmp359 + tmp364; tmp366 = tmp354 + tmp365; tmp569 = tmp365 - tmp354; tmp562 = tmp442 + tmp443; tmp563 = tmp448 + tmp449; tmp564 = tmp562 - tmp563; tmp605 = tmp562 + tmp563; } { fftw_real tmp446; fftw_real tmp451; fftw_real tmp459; fftw_real tmp460; ASSERT_ALIGNED_DOUBLE; tmp446 = tmp444 - tmp445; tmp451 = tmp447 + tmp450; tmp452 = K707106781 * (tmp446 - tmp451); tmp509 = K707106781 * (tmp446 + tmp451); tmp459 = tmp447 - tmp450; tmp460 = tmp445 + tmp444; tmp461 = K707106781 * (tmp459 - tmp460); tmp506 = K707106781 * (tmp460 + tmp459); } } { fftw_real tmp230; fftw_real tmp386; fftw_real tmp246; fftw_real tmp393; fftw_real tmp235; fftw_real tmp387; fftw_real tmp241; fftw_real tmp392; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp227; fftw_real tmp229; fftw_real tmp226; fftw_real tmp228; ASSERT_ALIGNED_DOUBLE; tmp227 = X[2 * iostride]; tmp229 = Y[-29 * iostride]; tmp226 = c_re(W[1]); tmp228 = c_im(W[1]); tmp230 = (tmp226 * tmp227) - (tmp228 * tmp229); tmp386 = (tmp228 * tmp227) + (tmp226 * tmp229); } { fftw_real tmp243; fftw_real tmp245; fftw_real tmp242; fftw_real tmp244; ASSERT_ALIGNED_DOUBLE; tmp243 = X[26 * iostride]; tmp245 = Y[-5 * iostride]; tmp242 = c_re(W[25]); tmp244 = c_im(W[25]); tmp246 = (tmp242 * tmp243) - (tmp244 * tmp245); tmp393 = (tmp244 * tmp243) + (tmp242 * tmp245); } { fftw_real tmp232; fftw_real tmp234; fftw_real tmp231; fftw_real tmp233; ASSERT_ALIGNED_DOUBLE; tmp232 = X[18 * iostride]; tmp234 = Y[-13 * iostride]; tmp231 = c_re(W[17]); tmp233 = c_im(W[17]); tmp235 = (tmp231 * tmp232) - (tmp233 * tmp234); tmp387 = (tmp233 * tmp232) + (tmp231 * tmp234); } { fftw_real tmp238; fftw_real tmp240; fftw_real tmp237; fftw_real tmp239; ASSERT_ALIGNED_DOUBLE; tmp238 = X[10 * iostride]; tmp240 = Y[-21 * iostride]; tmp237 = c_re(W[9]); tmp239 = c_im(W[9]); tmp241 = (tmp237 * tmp238) - (tmp239 * tmp240); tmp392 = (tmp239 * tmp238) + (tmp237 * tmp240); } { fftw_real tmp236; fftw_real tmp247; fftw_real tmp391; fftw_real tmp394; ASSERT_ALIGNED_DOUBLE; tmp236 = tmp230 + tmp235; tmp247 = tmp241 + tmp246; tmp248 = tmp236 + tmp247; tmp541 = tmp236 - tmp247; tmp391 = tmp230 - tmp235; tmp394 = tmp392 - tmp393; tmp395 = tmp391 - tmp394; tmp491 = tmp391 + tmp394; } { fftw_real tmp538; fftw_real tmp539; fftw_real tmp388; fftw_real tmp389; ASSERT_ALIGNED_DOUBLE; tmp538 = tmp386 + tmp387; tmp539 = tmp392 + tmp393; tmp540 = tmp538 - tmp539; tmp594 = tmp538 + tmp539; tmp388 = tmp386 - tmp387; tmp389 = tmp241 - tmp246; tmp390 = tmp388 + tmp389; tmp490 = tmp388 - tmp389; } } { fftw_real tmp278; fftw_real tmp410; fftw_real tmp294; fftw_real tmp429; fftw_real tmp283; fftw_real tmp411; fftw_real tmp289; fftw_real tmp428; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp275; fftw_real tmp277; fftw_real tmp274; fftw_real tmp276; ASSERT_ALIGNED_DOUBLE; tmp275 = X[iostride]; tmp277 = Y[-30 * iostride]; tmp274 = c_re(W[0]); tmp276 = c_im(W[0]); tmp278 = (tmp274 * tmp275) - (tmp276 * tmp277); tmp410 = (tmp276 * tmp275) + (tmp274 * tmp277); } { fftw_real tmp291; fftw_real tmp293; fftw_real tmp290; fftw_real tmp292; ASSERT_ALIGNED_DOUBLE; tmp291 = X[25 * iostride]; tmp293 = Y[-6 * iostride]; tmp290 = c_re(W[24]); tmp292 = c_im(W[24]); tmp294 = (tmp290 * tmp291) - (tmp292 * tmp293); tmp429 = (tmp292 * tmp291) + (tmp290 * tmp293); } { fftw_real tmp280; fftw_real tmp282; fftw_real tmp279; fftw_real tmp281; ASSERT_ALIGNED_DOUBLE; tmp280 = X[17 * iostride]; tmp282 = Y[-14 * iostride]; tmp279 = c_re(W[16]); tmp281 = c_im(W[16]); tmp283 = (tmp279 * tmp280) - (tmp281 * tmp282); tmp411 = (tmp281 * tmp280) + (tmp279 * tmp282); } { fftw_real tmp286; fftw_real tmp288; fftw_real tmp285; fftw_real tmp287; ASSERT_ALIGNED_DOUBLE; tmp286 = X[9 * iostride]; tmp288 = Y[-22 * iostride]; tmp285 = c_re(W[8]); tmp287 = c_im(W[8]); tmp289 = (tmp285 * tmp286) - (tmp287 * tmp288); tmp428 = (tmp287 * tmp286) + (tmp285 * tmp288); } { fftw_real tmp284; fftw_real tmp295; fftw_real tmp427; fftw_real tmp430; ASSERT_ALIGNED_DOUBLE; tmp284 = tmp278 + tmp283; tmp295 = tmp289 + tmp294; tmp296 = tmp284 + tmp295; tmp555 = tmp284 - tmp295; tmp427 = tmp278 - tmp283; tmp430 = tmp428 - tmp429; tmp431 = tmp427 - tmp430; tmp498 = tmp427 + tmp430; } { fftw_real tmp550; fftw_real tmp551; fftw_real tmp412; fftw_real tmp413; ASSERT_ALIGNED_DOUBLE; tmp550 = tmp410 + tmp411; tmp551 = tmp428 + tmp429; tmp552 = tmp550 - tmp551; tmp599 = tmp550 + tmp551; tmp412 = tmp410 - tmp411; tmp413 = tmp289 - tmp294; tmp414 = tmp412 + tmp413; tmp501 = tmp412 - tmp413; } } { fftw_real tmp253; fftw_real tmp397; fftw_real tmp269; fftw_real tmp404; fftw_real tmp258; fftw_real tmp398; fftw_real tmp264; fftw_real tmp403; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp250; fftw_real tmp252; fftw_real tmp249; fftw_real tmp251; ASSERT_ALIGNED_DOUBLE; tmp250 = X[30 * iostride]; tmp252 = Y[-iostride]; tmp249 = c_re(W[29]); tmp251 = c_im(W[29]); tmp253 = (tmp249 * tmp250) - (tmp251 * tmp252); tmp397 = (tmp251 * tmp250) + (tmp249 * tmp252); } { fftw_real tmp266; fftw_real tmp268; fftw_real tmp265; fftw_real tmp267; ASSERT_ALIGNED_DOUBLE; tmp266 = X[22 * iostride]; tmp268 = Y[-9 * iostride]; tmp265 = c_re(W[21]); tmp267 = c_im(W[21]); tmp269 = (tmp265 * tmp266) - (tmp267 * tmp268); tmp404 = (tmp267 * tmp266) + (tmp265 * tmp268); } { fftw_real tmp255; fftw_real tmp257; fftw_real tmp254; fftw_real tmp256; ASSERT_ALIGNED_DOUBLE; tmp255 = X[14 * iostride]; tmp257 = Y[-17 * iostride]; tmp254 = c_re(W[13]); tmp256 = c_im(W[13]); tmp258 = (tmp254 * tmp255) - (tmp256 * tmp257); tmp398 = (tmp256 * tmp255) + (tmp254 * tmp257); } { fftw_real tmp261; fftw_real tmp263; fftw_real tmp260; fftw_real tmp262; ASSERT_ALIGNED_DOUBLE; tmp261 = X[6 * iostride]; tmp263 = Y[-25 * iostride]; tmp260 = c_re(W[5]); tmp262 = c_im(W[5]); tmp264 = (tmp260 * tmp261) - (tmp262 * tmp263); tmp403 = (tmp262 * tmp261) + (tmp260 * tmp263); } { fftw_real tmp259; fftw_real tmp270; fftw_real tmp402; fftw_real tmp405; ASSERT_ALIGNED_DOUBLE; tmp259 = tmp253 + tmp258; tmp270 = tmp264 + tmp269; tmp271 = tmp259 + tmp270; tmp543 = tmp259 - tmp270; tmp402 = tmp253 - tmp258; tmp405 = tmp403 - tmp404; tmp406 = tmp402 - tmp405; tmp494 = tmp402 + tmp405; } { fftw_real tmp544; fftw_real tmp545; fftw_real tmp399; fftw_real tmp400; ASSERT_ALIGNED_DOUBLE; tmp544 = tmp397 + tmp398; tmp545 = tmp403 + tmp404; tmp546 = tmp544 - tmp545; tmp595 = tmp544 + tmp545; tmp399 = tmp397 - tmp398; tmp400 = tmp264 - tmp269; tmp401 = tmp399 + tmp400; tmp493 = tmp399 - tmp400; } } { fftw_real tmp301; fftw_real tmp421; fftw_real tmp306; fftw_real tmp422; fftw_real tmp420; fftw_real tmp423; fftw_real tmp312; fftw_real tmp416; fftw_real tmp317; fftw_real tmp417; fftw_real tmp415; fftw_real tmp418; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp298; fftw_real tmp300; fftw_real tmp297; fftw_real tmp299; ASSERT_ALIGNED_DOUBLE; tmp298 = X[5 * iostride]; tmp300 = Y[-26 * iostride]; tmp297 = c_re(W[4]); tmp299 = c_im(W[4]); tmp301 = (tmp297 * tmp298) - (tmp299 * tmp300); tmp421 = (tmp299 * tmp298) + (tmp297 * tmp300); } { fftw_real tmp303; fftw_real tmp305; fftw_real tmp302; fftw_real tmp304; ASSERT_ALIGNED_DOUBLE; tmp303 = X[21 * iostride]; tmp305 = Y[-10 * iostride]; tmp302 = c_re(W[20]); tmp304 = c_im(W[20]); tmp306 = (tmp302 * tmp303) - (tmp304 * tmp305); tmp422 = (tmp304 * tmp303) + (tmp302 * tmp305); } tmp420 = tmp301 - tmp306; tmp423 = tmp421 - tmp422; { fftw_real tmp309; fftw_real tmp311; fftw_real tmp308; fftw_real tmp310; ASSERT_ALIGNED_DOUBLE; tmp309 = X[29 * iostride]; tmp311 = Y[-2 * iostride]; tmp308 = c_re(W[28]); tmp310 = c_im(W[28]); tmp312 = (tmp308 * tmp309) - (tmp310 * tmp311); tmp416 = (tmp310 * tmp309) + (tmp308 * tmp311); } { fftw_real tmp314; fftw_real tmp316; fftw_real tmp313; fftw_real tmp315; ASSERT_ALIGNED_DOUBLE; tmp314 = X[13 * iostride]; tmp316 = Y[-18 * iostride]; tmp313 = c_re(W[12]); tmp315 = c_im(W[12]); tmp317 = (tmp313 * tmp314) - (tmp315 * tmp316); tmp417 = (tmp315 * tmp314) + (tmp313 * tmp316); } tmp415 = tmp312 - tmp317; tmp418 = tmp416 - tmp417; { fftw_real tmp307; fftw_real tmp318; fftw_real tmp556; fftw_real tmp557; ASSERT_ALIGNED_DOUBLE; tmp307 = tmp301 + tmp306; tmp318 = tmp312 + tmp317; tmp319 = tmp307 + tmp318; tmp553 = tmp318 - tmp307; tmp556 = tmp421 + tmp422; tmp557 = tmp416 + tmp417; tmp558 = tmp556 - tmp557; tmp600 = tmp556 + tmp557; } { fftw_real tmp419; fftw_real tmp424; fftw_real tmp432; fftw_real tmp433; ASSERT_ALIGNED_DOUBLE; tmp419 = tmp415 - tmp418; tmp424 = tmp420 + tmp423; tmp425 = K707106781 * (tmp419 - tmp424); tmp499 = K707106781 * (tmp424 + tmp419); tmp432 = tmp423 - tmp420; tmp433 = tmp415 + tmp418; tmp434 = K707106781 * (tmp432 - tmp433); tmp502 = K707106781 * (tmp432 + tmp433); } } { fftw_real tmp273; fftw_real tmp613; fftw_real tmp625; fftw_real tmp627; fftw_real tmp368; fftw_real tmp628; fftw_real tmp616; fftw_real tmp626; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp225; fftw_real tmp272; fftw_real tmp617; fftw_real tmp624; ASSERT_ALIGNED_DOUBLE; tmp225 = tmp201 + tmp224; tmp272 = tmp248 + tmp271; tmp273 = tmp225 + tmp272; tmp613 = tmp225 - tmp272; tmp617 = tmp594 + tmp595; tmp624 = tmp618 + tmp623; tmp625 = tmp617 + tmp624; tmp627 = tmp624 - tmp617; } { fftw_real tmp320; fftw_real tmp367; fftw_real tmp614; fftw_real tmp615; ASSERT_ALIGNED_DOUBLE; tmp320 = tmp296 + tmp319; tmp367 = tmp343 + tmp366; tmp368 = tmp320 + tmp367; tmp628 = tmp367 - tmp320; tmp614 = tmp599 + tmp600; tmp615 = tmp604 + tmp605; tmp616 = tmp614 - tmp615; tmp626 = tmp614 + tmp615; } Y[-16 * iostride] = tmp273 - tmp368; X[0] = tmp273 + tmp368; Y[-24 * iostride] = tmp613 - tmp616; X[8 * iostride] = tmp613 + tmp616; X[16 * iostride] = -(tmp625 - tmp626); Y[0] = tmp626 + tmp625; X[24 * iostride] = -(tmp627 - tmp628); Y[-8 * iostride] = tmp628 + tmp627; } { fftw_real tmp597; fftw_real tmp609; fftw_real tmp631; fftw_real tmp633; fftw_real tmp602; fftw_real tmp610; fftw_real tmp607; fftw_real tmp611; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp593; fftw_real tmp596; fftw_real tmp629; fftw_real tmp630; ASSERT_ALIGNED_DOUBLE; tmp593 = tmp201 - tmp224; tmp596 = tmp594 - tmp595; tmp597 = tmp593 + tmp596; tmp609 = tmp593 - tmp596; tmp629 = tmp271 - tmp248; tmp630 = tmp623 - tmp618; tmp631 = tmp629 + tmp630; tmp633 = tmp630 - tmp629; } { fftw_real tmp598; fftw_real tmp601; fftw_real tmp603; fftw_real tmp606; ASSERT_ALIGNED_DOUBLE; tmp598 = tmp296 - tmp319; tmp601 = tmp599 - tmp600; tmp602 = tmp598 + tmp601; tmp610 = tmp601 - tmp598; tmp603 = tmp343 - tmp366; tmp606 = tmp604 - tmp605; tmp607 = tmp603 - tmp606; tmp611 = tmp603 + tmp606; } { fftw_real tmp608; fftw_real tmp634; fftw_real tmp612; fftw_real tmp632; ASSERT_ALIGNED_DOUBLE; tmp608 = K707106781 * (tmp602 + tmp607); Y[-20 * iostride] = tmp597 - tmp608; X[4 * iostride] = tmp597 + tmp608; tmp634 = K707106781 * (tmp607 - tmp602); X[28 * iostride] = -(tmp633 - tmp634); Y[-12 * iostride] = tmp634 + tmp633; tmp612 = K707106781 * (tmp610 - tmp611); Y[-28 * iostride] = tmp609 - tmp612; X[12 * iostride] = tmp609 + tmp612; tmp632 = K707106781 * (tmp610 + tmp611); X[20 * iostride] = -(tmp631 - tmp632); Y[-4 * iostride] = tmp632 + tmp631; } } { fftw_real tmp537; fftw_real tmp577; fftw_real tmp548; fftw_real tmp635; fftw_real tmp580; fftw_real tmp643; fftw_real tmp560; fftw_real tmp574; fftw_real tmp638; fftw_real tmp644; fftw_real tmp584; fftw_real tmp590; fftw_real tmp571; fftw_real tmp575; fftw_real tmp587; fftw_real tmp591; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp542; fftw_real tmp547; fftw_real tmp582; fftw_real tmp583; ASSERT_ALIGNED_DOUBLE; tmp537 = tmp533 - tmp536; tmp577 = tmp533 + tmp536; tmp542 = tmp540 - tmp541; tmp547 = tmp543 + tmp546; tmp548 = K707106781 * (tmp542 - tmp547); tmp635 = K707106781 * (tmp542 + tmp547); { fftw_real tmp578; fftw_real tmp579; fftw_real tmp554; fftw_real tmp559; ASSERT_ALIGNED_DOUBLE; tmp578 = tmp541 + tmp540; tmp579 = tmp543 - tmp546; tmp580 = K707106781 * (tmp578 + tmp579); tmp643 = K707106781 * (tmp579 - tmp578); tmp554 = tmp552 - tmp553; tmp559 = tmp555 - tmp558; tmp560 = (K923879532 * tmp554) + (K382683432 * tmp559); tmp574 = (K382683432 * tmp554) - (K923879532 * tmp559); } tmp638 = tmp636 + tmp637; tmp644 = tmp637 - tmp636; tmp582 = tmp552 + tmp553; tmp583 = tmp555 + tmp558; tmp584 = (K382683432 * tmp582) + (K923879532 * tmp583); tmp590 = (K923879532 * tmp582) - (K382683432 * tmp583); { fftw_real tmp565; fftw_real tmp570; fftw_real tmp585; fftw_real tmp586; ASSERT_ALIGNED_DOUBLE; tmp565 = tmp561 - tmp564; tmp570 = tmp568 - tmp569; tmp571 = (K382683432 * tmp565) - (K923879532 * tmp570); tmp575 = (K382683432 * tmp570) + (K923879532 * tmp565); tmp585 = tmp561 + tmp564; tmp586 = tmp568 + tmp569; tmp587 = (K923879532 * tmp585) - (K382683432 * tmp586); tmp591 = (K923879532 * tmp586) + (K382683432 * tmp585); } } { fftw_real tmp549; fftw_real tmp572; fftw_real tmp573; fftw_real tmp576; ASSERT_ALIGNED_DOUBLE; tmp549 = tmp537 + tmp548; tmp572 = tmp560 + tmp571; Y[-22 * iostride] = tmp549 - tmp572; X[6 * iostride] = tmp549 + tmp572; tmp573 = tmp537 - tmp548; tmp576 = tmp574 - tmp575; Y[-30 * iostride] = tmp573 - tmp576; X[14 * iostride] = tmp573 + tmp576; } { fftw_real tmp645; fftw_real tmp646; fftw_real tmp647; fftw_real tmp648; ASSERT_ALIGNED_DOUBLE; tmp645 = tmp643 + tmp644; tmp646 = tmp574 + tmp575; X[22 * iostride] = -(tmp645 - tmp646); Y[-6 * iostride] = tmp646 + tmp645; tmp647 = tmp644 - tmp643; tmp648 = tmp571 - tmp560; X[30 * iostride] = -(tmp647 - tmp648); Y[-14 * iostride] = tmp648 + tmp647; } { fftw_real tmp581; fftw_real tmp588; fftw_real tmp589; fftw_real tmp592; ASSERT_ALIGNED_DOUBLE; tmp581 = tmp577 + tmp580; tmp588 = tmp584 + tmp587; Y[-18 * iostride] = tmp581 - tmp588; X[2 * iostride] = tmp581 + tmp588; tmp589 = tmp577 - tmp580; tmp592 = tmp590 - tmp591; Y[-26 * iostride] = tmp589 - tmp592; X[10 * iostride] = tmp589 + tmp592; } { fftw_real tmp639; fftw_real tmp640; fftw_real tmp641; fftw_real tmp642; ASSERT_ALIGNED_DOUBLE; tmp639 = tmp635 + tmp638; tmp640 = tmp590 + tmp591; X[18 * iostride] = -(tmp639 - tmp640); Y[-2 * iostride] = tmp640 + tmp639; tmp641 = tmp638 - tmp635; tmp642 = tmp587 - tmp584; X[26 * iostride] = -(tmp641 - tmp642); Y[-10 * iostride] = tmp642 + tmp641; } } { fftw_real tmp489; fftw_real tmp517; fftw_real tmp520; fftw_real tmp659; fftw_real tmp654; fftw_real tmp660; fftw_real tmp496; fftw_real tmp649; fftw_real tmp504; fftw_real tmp514; fftw_real tmp524; fftw_real tmp530; fftw_real tmp511; fftw_real tmp515; fftw_real tmp527; fftw_real tmp531; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp488; fftw_real tmp518; fftw_real tmp519; fftw_real tmp650; fftw_real tmp492; fftw_real tmp495; ASSERT_ALIGNED_DOUBLE; tmp488 = K707106781 * (tmp486 + tmp487); tmp489 = tmp485 - tmp488; tmp517 = tmp485 + tmp488; tmp518 = (K382683432 * tmp490) + (K923879532 * tmp491); tmp519 = (K923879532 * tmp494) - (K382683432 * tmp493); tmp520 = tmp518 + tmp519; tmp659 = tmp519 - tmp518; tmp650 = K707106781 * (tmp378 + tmp383); tmp654 = tmp650 + tmp653; tmp660 = tmp653 - tmp650; tmp492 = (K923879532 * tmp490) - (K382683432 * tmp491); tmp495 = (K923879532 * tmp493) + (K382683432 * tmp494); tmp496 = tmp492 - tmp495; tmp649 = tmp492 + tmp495; } { fftw_real tmp500; fftw_real tmp503; fftw_real tmp522; fftw_real tmp523; ASSERT_ALIGNED_DOUBLE; tmp500 = tmp498 - tmp499; tmp503 = tmp501 - tmp502; tmp504 = (K555570233 * tmp500) + (K831469612 * tmp503); tmp514 = (K555570233 * tmp503) - (K831469612 * tmp500); tmp522 = tmp498 + tmp499; tmp523 = tmp501 + tmp502; tmp524 = (K980785280 * tmp522) + (K195090322 * tmp523); tmp530 = (K980785280 * tmp523) - (K195090322 * tmp522); } { fftw_real tmp507; fftw_real tmp510; fftw_real tmp525; fftw_real tmp526; ASSERT_ALIGNED_DOUBLE; tmp507 = tmp505 - tmp506; tmp510 = tmp508 - tmp509; tmp511 = (K555570233 * tmp507) - (K831469612 * tmp510); tmp515 = (K831469612 * tmp507) + (K555570233 * tmp510); tmp525 = tmp505 + tmp506; tmp526 = tmp508 + tmp509; tmp527 = (K980785280 * tmp525) - (K195090322 * tmp526); tmp531 = (K195090322 * tmp525) + (K980785280 * tmp526); } { fftw_real tmp497; fftw_real tmp512; fftw_real tmp513; fftw_real tmp516; ASSERT_ALIGNED_DOUBLE; tmp497 = tmp489 + tmp496; tmp512 = tmp504 + tmp511; Y[-21 * iostride] = tmp497 - tmp512; X[5 * iostride] = tmp497 + tmp512; tmp513 = tmp489 - tmp496; tmp516 = tmp514 - tmp515; Y[-29 * iostride] = tmp513 - tmp516; X[13 * iostride] = tmp513 + tmp516; } { fftw_real tmp661; fftw_real tmp662; fftw_real tmp663; fftw_real tmp664; ASSERT_ALIGNED_DOUBLE; tmp661 = tmp659 + tmp660; tmp662 = tmp514 + tmp515; X[21 * iostride] = -(tmp661 - tmp662); Y[-5 * iostride] = tmp662 + tmp661; tmp663 = tmp660 - tmp659; tmp664 = tmp511 - tmp504; X[29 * iostride] = -(tmp663 - tmp664); Y[-13 * iostride] = tmp664 + tmp663; } { fftw_real tmp521; fftw_real tmp528; fftw_real tmp529; fftw_real tmp532; ASSERT_ALIGNED_DOUBLE; tmp521 = tmp517 + tmp520; tmp528 = tmp524 + tmp527; Y[-17 * iostride] = tmp521 - tmp528; X[iostride] = tmp521 + tmp528; tmp529 = tmp517 - tmp520; tmp532 = tmp530 - tmp531; Y[-25 * iostride] = tmp529 - tmp532; X[9 * iostride] = tmp529 + tmp532; } { fftw_real tmp655; fftw_real tmp656; fftw_real tmp657; fftw_real tmp658; ASSERT_ALIGNED_DOUBLE; tmp655 = tmp649 + tmp654; tmp656 = tmp530 + tmp531; X[17 * iostride] = -(tmp655 - tmp656); Y[-iostride] = tmp656 + tmp655; tmp657 = tmp654 - tmp649; tmp658 = tmp527 - tmp524; X[25 * iostride] = -(tmp657 - tmp658); Y[-9 * iostride] = tmp658 + tmp657; } } { fftw_real tmp385; fftw_real tmp469; fftw_real tmp472; fftw_real tmp673; fftw_real tmp668; fftw_real tmp674; fftw_real tmp408; fftw_real tmp665; fftw_real tmp436; fftw_real tmp466; fftw_real tmp476; fftw_real tmp482; fftw_real tmp463; fftw_real tmp467; fftw_real tmp479; fftw_real tmp483; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp384; fftw_real tmp470; fftw_real tmp471; fftw_real tmp666; fftw_real tmp396; fftw_real tmp407; ASSERT_ALIGNED_DOUBLE; tmp384 = K707106781 * (tmp378 - tmp383); tmp385 = tmp373 - tmp384; tmp469 = tmp373 + tmp384; tmp470 = (K923879532 * tmp390) + (K382683432 * tmp395); tmp471 = (K382683432 * tmp406) - (K923879532 * tmp401); tmp472 = tmp470 + tmp471; tmp673 = tmp471 - tmp470; tmp666 = K707106781 * (tmp487 - tmp486); tmp668 = tmp666 + tmp667; tmp674 = tmp667 - tmp666; tmp396 = (K382683432 * tmp390) - (K923879532 * tmp395); tmp407 = (K382683432 * tmp401) + (K923879532 * tmp406); tmp408 = tmp396 - tmp407; tmp665 = tmp396 + tmp407; } { fftw_real tmp426; fftw_real tmp435; fftw_real tmp474; fftw_real tmp475; ASSERT_ALIGNED_DOUBLE; tmp426 = tmp414 - tmp425; tmp435 = tmp431 - tmp434; tmp436 = (K980785280 * tmp426) + (K195090322 * tmp435); tmp466 = (K195090322 * tmp426) - (K980785280 * tmp435); tmp474 = tmp414 + tmp425; tmp475 = tmp431 + tmp434; tmp476 = (K555570233 * tmp474) + (K831469612 * tmp475); tmp482 = (K831469612 * tmp474) - (K555570233 * tmp475); } { fftw_real tmp453; fftw_real tmp462; fftw_real tmp477; fftw_real tmp478; ASSERT_ALIGNED_DOUBLE; tmp453 = tmp441 - tmp452; tmp462 = tmp458 - tmp461; tmp463 = (K195090322 * tmp453) - (K980785280 * tmp462); tmp467 = (K195090322 * tmp462) + (K980785280 * tmp453); tmp477 = tmp441 + tmp452; tmp478 = tmp458 + tmp461; tmp479 = (K831469612 * tmp477) - (K555570233 * tmp478); tmp483 = (K831469612 * tmp478) + (K555570233 * tmp477); } { fftw_real tmp409; fftw_real tmp464; fftw_real tmp465; fftw_real tmp468; ASSERT_ALIGNED_DOUBLE; tmp409 = tmp385 + tmp408; tmp464 = tmp436 + tmp463; Y[-23 * iostride] = tmp409 - tmp464; X[7 * iostride] = tmp409 + tmp464; tmp465 = tmp385 - tmp408; tmp468 = tmp466 - tmp467; Y[-31 * iostride] = tmp465 - tmp468; X[15 * iostride] = tmp465 + tmp468; } { fftw_real tmp675; fftw_real tmp676; fftw_real tmp677; fftw_real tmp678; ASSERT_ALIGNED_DOUBLE; tmp675 = tmp673 + tmp674; tmp676 = tmp466 + tmp467; X[23 * iostride] = -(tmp675 - tmp676); Y[-7 * iostride] = tmp676 + tmp675; tmp677 = tmp674 - tmp673; tmp678 = tmp463 - tmp436; X[31 * iostride] = -(tmp677 - tmp678); Y[-15 * iostride] = tmp678 + tmp677; } { fftw_real tmp473; fftw_real tmp480; fftw_real tmp481; fftw_real tmp484; ASSERT_ALIGNED_DOUBLE; tmp473 = tmp469 + tmp472; tmp480 = tmp476 + tmp479; Y[-19 * iostride] = tmp473 - tmp480; X[3 * iostride] = tmp473 + tmp480; tmp481 = tmp469 - tmp472; tmp484 = tmp482 - tmp483; Y[-27 * iostride] = tmp481 - tmp484; X[11 * iostride] = tmp481 + tmp484; } { fftw_real tmp669; fftw_real tmp670; fftw_real tmp671; fftw_real tmp672; ASSERT_ALIGNED_DOUBLE; tmp669 = tmp665 + tmp668; tmp670 = tmp482 + tmp483; X[19 * iostride] = -(tmp669 - tmp670); Y[-3 * iostride] = tmp670 + tmp669; tmp671 = tmp668 - tmp665; tmp672 = tmp479 - tmp476; X[27 * iostride] = -(tmp671 - tmp672); Y[-11 * iostride] = tmp672 + tmp671; } } } if (i == m) { fftw_real tmp5; fftw_real tmp105; fftw_real tmp158; fftw_real tmp171; fftw_real tmp12; fftw_real tmp170; fftw_real tmp108; fftw_real tmp155; fftw_real tmp74; fftw_real tmp97; fftw_real tmp130; fftw_real tmp146; fftw_real tmp82; fftw_real tmp98; fftw_real tmp127; fftw_real tmp145; fftw_real tmp24; fftw_real tmp90; fftw_real tmp115; fftw_real tmp138; fftw_real tmp35; fftw_real tmp91; fftw_real tmp112; fftw_real tmp139; fftw_real tmp51; fftw_real tmp94; fftw_real tmp123; fftw_real tmp143; fftw_real tmp59; fftw_real tmp95; fftw_real tmp120; fftw_real tmp142; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp1; fftw_real tmp157; fftw_real tmp4; fftw_real tmp156; fftw_real tmp2; fftw_real tmp3; ASSERT_ALIGNED_DOUBLE; tmp1 = X[0]; tmp157 = X[16 * iostride]; tmp2 = X[8 * iostride]; tmp3 = X[24 * iostride]; tmp4 = K707106781 * (tmp2 - tmp3); tmp156 = K707106781 * (tmp2 + tmp3); tmp5 = tmp1 + tmp4; tmp105 = tmp1 - tmp4; tmp158 = tmp156 + tmp157; tmp171 = tmp157 - tmp156; } { fftw_real tmp8; fftw_real tmp106; fftw_real tmp11; fftw_real tmp107; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp6; fftw_real tmp7; fftw_real tmp9; fftw_real tmp10; ASSERT_ALIGNED_DOUBLE; tmp6 = X[4 * iostride]; tmp7 = X[20 * iostride]; tmp8 = (K923879532 * tmp6) - (K382683432 * tmp7); tmp106 = (K382683432 * tmp6) + (K923879532 * tmp7); tmp9 = X[12 * iostride]; tmp10 = X[28 * iostride]; tmp11 = (K382683432 * tmp9) - (K923879532 * tmp10); tmp107 = (K923879532 * tmp9) + (K382683432 * tmp10); } tmp12 = tmp8 + tmp11; tmp170 = tmp11 - tmp8; tmp108 = tmp106 - tmp107; tmp155 = tmp106 + tmp107; } { fftw_real tmp65; fftw_real tmp80; fftw_real tmp63; fftw_real tmp78; fftw_real tmp69; fftw_real tmp75; fftw_real tmp72; fftw_real tmp76; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp64; fftw_real tmp79; fftw_real tmp61; fftw_real tmp62; ASSERT_ALIGNED_DOUBLE; tmp64 = X[31 * iostride]; tmp65 = K2_000000000 * tmp64; tmp79 = X[15 * iostride]; tmp80 = K2_000000000 * tmp79; tmp61 = X[7 * iostride]; tmp62 = X[23 * iostride]; tmp63 = K1_414213562 * (tmp61 - tmp62); tmp78 = K1_414213562 * (tmp61 + tmp62); { fftw_real tmp67; fftw_real tmp68; fftw_real tmp70; fftw_real tmp71; ASSERT_ALIGNED_DOUBLE; tmp67 = X[3 * iostride]; tmp68 = X[19 * iostride]; tmp69 = (K1_847759065 * tmp67) - (K765366864 * tmp68); tmp75 = (K765366864 * tmp67) + (K1_847759065 * tmp68); tmp70 = X[11 * iostride]; tmp71 = X[27 * iostride]; tmp72 = (K765366864 * tmp70) - (K1_847759065 * tmp71); tmp76 = (K1_847759065 * tmp70) + (K765366864 * tmp71); } } { fftw_real tmp66; fftw_real tmp73; fftw_real tmp128; fftw_real tmp129; ASSERT_ALIGNED_DOUBLE; tmp66 = tmp63 - tmp65; tmp73 = tmp69 + tmp72; tmp74 = tmp66 + tmp73; tmp97 = tmp66 - tmp73; tmp128 = tmp72 - tmp69; tmp129 = tmp80 - tmp78; tmp130 = tmp128 - tmp129; tmp146 = tmp128 + tmp129; } { fftw_real tmp77; fftw_real tmp81; fftw_real tmp125; fftw_real tmp126; ASSERT_ALIGNED_DOUBLE; tmp77 = tmp75 + tmp76; tmp81 = tmp78 + tmp80; tmp82 = tmp77 + tmp81; tmp98 = tmp81 - tmp77; tmp125 = tmp63 + tmp65; tmp126 = tmp75 - tmp76; tmp127 = tmp125 + tmp126; tmp145 = tmp126 - tmp125; } } { fftw_real tmp15; fftw_real tmp22; fftw_real tmp18; fftw_real tmp20; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp14; fftw_real tmp21; fftw_real tmp16; fftw_real tmp17; ASSERT_ALIGNED_DOUBLE; tmp14 = X[2 * iostride]; tmp15 = K2_000000000 * tmp14; tmp21 = X[18 * iostride]; tmp22 = K2_000000000 * tmp21; tmp16 = X[10 * iostride]; tmp17 = X[26 * iostride]; tmp18 = K1_414213562 * (tmp16 - tmp17); tmp20 = K1_414213562 * (tmp16 + tmp17); } { fftw_real tmp19; fftw_real tmp23; fftw_real tmp113; fftw_real tmp114; ASSERT_ALIGNED_DOUBLE; tmp19 = tmp15 + tmp18; tmp23 = tmp20 + tmp22; tmp24 = (K490392640 * tmp19) - (K097545161 * tmp23); tmp90 = (K097545161 * tmp19) + (K490392640 * tmp23); tmp113 = tmp22 - tmp20; tmp114 = tmp15 - tmp18; tmp115 = (K415734806 * tmp113) - (K277785116 * tmp114); tmp138 = (K415734806 * tmp114) + (K277785116 * tmp113); } } { fftw_real tmp29; fftw_real tmp33; fftw_real tmp27; fftw_real tmp31; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp28; fftw_real tmp32; fftw_real tmp25; fftw_real tmp26; ASSERT_ALIGNED_DOUBLE; tmp28 = X[30 * iostride]; tmp29 = K2_000000000 * tmp28; tmp32 = X[14 * iostride]; tmp33 = K2_000000000 * tmp32; tmp25 = X[6 * iostride]; tmp26 = X[22 * iostride]; tmp27 = K1_414213562 * (tmp25 - tmp26); tmp31 = K1_414213562 * (tmp25 + tmp26); } { fftw_real tmp30; fftw_real tmp34; fftw_real tmp110; fftw_real tmp111; ASSERT_ALIGNED_DOUBLE; tmp30 = tmp27 - tmp29; tmp34 = tmp31 + tmp33; tmp35 = (K490392640 * tmp30) + (K097545161 * tmp34); tmp91 = (K097545161 * tmp30) - (K490392640 * tmp34); tmp110 = tmp33 - tmp31; tmp111 = tmp27 + tmp29; tmp112 = (K415734806 * tmp110) - (K277785116 * tmp111); tmp139 = (K415734806 * tmp111) + (K277785116 * tmp110); } } { fftw_real tmp39; fftw_real tmp57; fftw_real tmp42; fftw_real tmp55; fftw_real tmp46; fftw_real tmp52; fftw_real tmp49; fftw_real tmp53; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp38; fftw_real tmp56; fftw_real tmp40; fftw_real tmp41; ASSERT_ALIGNED_DOUBLE; tmp38 = X[iostride]; tmp39 = K2_000000000 * tmp38; tmp56 = X[17 * iostride]; tmp57 = K2_000000000 * tmp56; tmp40 = X[9 * iostride]; tmp41 = X[25 * iostride]; tmp42 = K1_414213562 * (tmp40 - tmp41); tmp55 = K1_414213562 * (tmp40 + tmp41); { fftw_real tmp44; fftw_real tmp45; fftw_real tmp47; fftw_real tmp48; ASSERT_ALIGNED_DOUBLE; tmp44 = X[5 * iostride]; tmp45 = X[21 * iostride]; tmp46 = (K1_847759065 * tmp44) - (K765366864 * tmp45); tmp52 = (K765366864 * tmp44) + (K1_847759065 * tmp45); tmp47 = X[13 * iostride]; tmp48 = X[29 * iostride]; tmp49 = (K765366864 * tmp47) - (K1_847759065 * tmp48); tmp53 = (K1_847759065 * tmp47) + (K765366864 * tmp48); } } { fftw_real tmp43; fftw_real tmp50; fftw_real tmp121; fftw_real tmp122; ASSERT_ALIGNED_DOUBLE; tmp43 = tmp39 + tmp42; tmp50 = tmp46 + tmp49; tmp51 = tmp43 + tmp50; tmp94 = tmp43 - tmp50; tmp121 = tmp49 - tmp46; tmp122 = tmp57 - tmp55; tmp123 = tmp121 - tmp122; tmp143 = tmp121 + tmp122; } { fftw_real tmp54; fftw_real tmp58; fftw_real tmp118; fftw_real tmp119; ASSERT_ALIGNED_DOUBLE; tmp54 = tmp52 + tmp53; tmp58 = tmp55 + tmp57; tmp59 = tmp54 + tmp58; tmp95 = tmp58 - tmp54; tmp118 = tmp39 - tmp42; tmp119 = tmp52 - tmp53; tmp120 = tmp118 - tmp119; tmp142 = tmp118 + tmp119; } } { fftw_real tmp37; fftw_real tmp85; fftw_real tmp160; fftw_real tmp162; fftw_real tmp84; fftw_real tmp153; fftw_real tmp88; fftw_real tmp161; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp13; fftw_real tmp36; fftw_real tmp154; fftw_real tmp159; ASSERT_ALIGNED_DOUBLE; tmp13 = tmp5 + tmp12; tmp36 = tmp24 + tmp35; tmp37 = tmp13 - tmp36; tmp85 = tmp13 + tmp36; tmp154 = tmp91 - tmp90; tmp159 = tmp155 + tmp158; tmp160 = tmp154 - tmp159; tmp162 = tmp154 + tmp159; } { fftw_real tmp60; fftw_real tmp83; fftw_real tmp86; fftw_real tmp87; ASSERT_ALIGNED_DOUBLE; tmp60 = (K049008570 * tmp51) + (K497592363 * tmp59); tmp83 = (K049008570 * tmp74) - (K497592363 * tmp82); tmp84 = tmp60 + tmp83; tmp153 = tmp83 - tmp60; tmp86 = (K497592363 * tmp51) - (K049008570 * tmp59); tmp87 = (K497592363 * tmp74) + (K049008570 * tmp82); tmp88 = tmp86 + tmp87; tmp161 = tmp87 - tmp86; } X[8 * iostride] = tmp37 - tmp84; X[7 * iostride] = tmp37 + tmp84; X[15 * iostride] = tmp85 - tmp88; X[0] = tmp85 + tmp88; Y[-15 * iostride] = tmp153 - tmp160; Y[0] = tmp153 + tmp160; Y[-8 * iostride] = tmp161 - tmp162; Y[-7 * iostride] = tmp161 + tmp162; } { fftw_real tmp93; fftw_real tmp101; fftw_real tmp166; fftw_real tmp168; fftw_real tmp100; fftw_real tmp163; fftw_real tmp104; fftw_real tmp167; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp89; fftw_real tmp92; fftw_real tmp164; fftw_real tmp165; ASSERT_ALIGNED_DOUBLE; tmp89 = tmp5 - tmp12; tmp92 = tmp90 + tmp91; tmp93 = tmp89 + tmp92; tmp101 = tmp89 - tmp92; tmp164 = tmp35 - tmp24; tmp165 = tmp158 - tmp155; tmp166 = tmp164 - tmp165; tmp168 = tmp164 + tmp165; } { fftw_real tmp96; fftw_real tmp99; fftw_real tmp102; fftw_real tmp103; ASSERT_ALIGNED_DOUBLE; tmp96 = (K386505226 * tmp94) + (K317196642 * tmp95); tmp99 = (K386505226 * tmp97) - (K317196642 * tmp98); tmp100 = tmp96 + tmp99; tmp163 = tmp99 - tmp96; tmp102 = (K317196642 * tmp97) + (K386505226 * tmp98); tmp103 = (K386505226 * tmp95) - (K317196642 * tmp94); tmp104 = tmp102 - tmp103; tmp167 = tmp103 + tmp102; } X[12 * iostride] = tmp93 - tmp100; X[3 * iostride] = tmp93 + tmp100; X[11 * iostride] = tmp101 - tmp104; X[4 * iostride] = tmp101 + tmp104; Y[-11 * iostride] = tmp163 - tmp166; Y[-4 * iostride] = tmp163 + tmp166; Y[-12 * iostride] = tmp167 - tmp168; Y[-3 * iostride] = tmp167 + tmp168; } { fftw_real tmp117; fftw_real tmp133; fftw_real tmp174; fftw_real tmp176; fftw_real tmp132; fftw_real tmp175; fftw_real tmp136; fftw_real tmp169; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp109; fftw_real tmp116; fftw_real tmp172; fftw_real tmp173; ASSERT_ALIGNED_DOUBLE; tmp109 = tmp105 - tmp108; tmp116 = tmp112 - tmp115; tmp117 = tmp109 + tmp116; tmp133 = tmp109 - tmp116; tmp172 = tmp170 - tmp171; tmp173 = tmp138 + tmp139; tmp174 = tmp172 - tmp173; tmp176 = tmp173 + tmp172; } { fftw_real tmp124; fftw_real tmp131; fftw_real tmp134; fftw_real tmp135; ASSERT_ALIGNED_DOUBLE; tmp124 = (K440960632 * tmp120) + (K235698368 * tmp123); tmp131 = (K440960632 * tmp127) + (K235698368 * tmp130); tmp132 = tmp124 - tmp131; tmp175 = tmp124 + tmp131; tmp134 = (K440960632 * tmp130) - (K235698368 * tmp127); tmp135 = (K440960632 * tmp123) - (K235698368 * tmp120); tmp136 = tmp134 - tmp135; tmp169 = tmp135 + tmp134; } X[13 * iostride] = tmp117 - tmp132; X[2 * iostride] = tmp117 + tmp132; X[10 * iostride] = tmp133 - tmp136; X[5 * iostride] = tmp133 + tmp136; Y[-13 * iostride] = tmp169 - tmp174; Y[-2 * iostride] = tmp169 + tmp174; Y[-5 * iostride] = -(tmp175 + tmp176); Y[-10 * iostride] = tmp176 - tmp175; } { fftw_real tmp141; fftw_real tmp149; fftw_real tmp180; fftw_real tmp182; fftw_real tmp148; fftw_real tmp177; fftw_real tmp152; fftw_real tmp181; ASSERT_ALIGNED_DOUBLE; { fftw_real tmp137; fftw_real tmp140; fftw_real tmp178; fftw_real tmp179; ASSERT_ALIGNED_DOUBLE; tmp137 = tmp105 + tmp108; tmp140 = tmp138 - tmp139; tmp141 = tmp137 + tmp140; tmp149 = tmp137 - tmp140; tmp178 = tmp115 + tmp112; tmp179 = tmp170 + tmp171; tmp180 = tmp178 - tmp179; tmp182 = tmp178 + tmp179; } { fftw_real tmp144; fftw_real tmp147; fftw_real tmp150; fftw_real tmp151; ASSERT_ALIGNED_DOUBLE; tmp144 = (K478470167 * tmp142) + (K145142338 * tmp143); tmp147 = (K478470167 * tmp145) - (K145142338 * tmp146); tmp148 = tmp144 + tmp147; tmp177 = tmp147 - tmp144; tmp150 = (K145142338 * tmp145) + (K478470167 * tmp146); tmp151 = (K478470167 * tmp143) - (K145142338 * tmp142); tmp152 = tmp150 - tmp151; tmp181 = tmp151 + tmp150; } X[14 * iostride] = tmp141 - tmp148; X[iostride] = tmp141 + tmp148; X[9 * iostride] = tmp149 - tmp152; X[6 * iostride] = tmp149 + tmp152; Y[-9 * iostride] = tmp177 - tmp180; Y[-6 * iostride] = tmp177 + tmp180; Y[-14 * iostride] = tmp181 - tmp182; Y[-iostride] = tmp181 + tmp182; } } } static const int twiddle_order[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}; fftw_codelet_desc fftw_hc2hc_forward_32_desc = { "fftw_hc2hc_forward_32", (void (*)()) fftw_hc2hc_forward_32, 32, FFTW_FORWARD, FFTW_HC2HC, 707, 31, twiddle_order, };
{ "alphanum_fraction": 0.5738157017, "avg_line_length": 29.159100735, "ext": "c", "hexsha": "52404daff8ed8ebab80d51d71ffff70d4080df23", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z", "max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "albertsgrc/ftdock-opt", "max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_32.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "albertsgrc/ftdock-opt", "max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_32.c", "max_line_length": 125, "max_stars_count": 9, "max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "albertsgrc/ftdock-opt", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_32.c", "max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z", "num_tokens": 21074, "size": 67445 }
#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" #ifdef PERIODIC #define NEAREST(x) (((x)>boxhalf)?((x)-boxsize):(((x)<-boxhalf)?((x)+boxsize):(x))) #else #define NEAREST(x) (x) #endif /*! Structure for communication during the density computation. Holds data that is sent to other processors. */ static struct SOdens_in { MyDouble Pos[3]; double R200; int NodeList[NODELISTLENGTH]; } *SOdensIn, *SOdensGet; static struct SOdens_out { double Mass; #ifdef SO_VEL_DISPERSIONS double Vx200, Vy200, Vz200, Disp200; #endif } *SOdensResult, *SOdensOut; static double *R200, *M200; #ifdef SO_VEL_DISPERSIONS static double *Vx200, *Vy200, *Vz200, *Disp200; #endif void subfind_overdensity(void) { long long ntot; int i, j, ndone, ndone_flag, npleft, dummy, rep, iter; MyFloat *Left, *Right; char *Todo; int ngrp, sendTask, recvTask, place, nexport, nimport; double t0, t1, rguess, overdensity, Deltas[3], rhoback, z, omegaz, x, DeltaMean200, DeltaCrit200, DeltaTopHat; /* allocate buffers to arrange communication */ Ngblist = (int *) mymalloc(NumPart * sizeof(int)); All.BunchSize = (int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) + sizeof(struct SOdens_in) + sizeof(struct SOdens_out) + sizemax(sizeof(struct SOdens_in), sizeof(struct SOdens_out)))); DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index)); DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist)); Left = (MyFloat *) mymalloc(sizeof(MyFloat) * Ngroups); Right = (MyFloat *) mymalloc(sizeof(MyFloat) * Ngroups); R200 = (double *) mymalloc(sizeof(double) * Ngroups); M200 = (double *) mymalloc(sizeof(double) * Ngroups); #ifdef SO_VEL_DISPERSIONS Vx200 = (double *) mymalloc(sizeof(double) * Ngroups); Vy200 = (double *) mymalloc(sizeof(double) * Ngroups); Vz200 = (double *) mymalloc(sizeof(double) * Ngroups); Disp200 = (double *) mymalloc(sizeof(double) * Ngroups); #endif Todo = mymalloc(sizeof(char) * Ngroups); z = 1 / All.Time - 1; rhoback = 3 * All.Omega0 * All.Hubble * All.Hubble / (8 * M_PI * All.G); omegaz = All.Omega0 * pow(1 + z, 3) / (All.Omega0 * pow(1 + z, 3) + (1 - All.Omega0 - All.OmegaLambda) * pow(1 + z, 2) + All.OmegaLambda); DeltaMean200 = 200.0; DeltaCrit200 = 200.0 / omegaz; x = omegaz - 1; DeltaTopHat = 18 * M_PI * M_PI + 82 * x - 39 * x * x; DeltaTopHat /= omegaz; Deltas[0] = DeltaMean200; /* standard fixed overdensity with respect to background */ Deltas[1] = DeltaTopHat; /* tophat overdensity with respect to background */ Deltas[2] = DeltaCrit200; /* overdensity of 200 relative to critical, expressed relative to background density */ for(rep = 0; rep < 3; rep++) /* repeat for all three overdensity values */ { for(i = 0; i < Ngroups; i++) { if(Group[i].Nsubs > 0) { rguess = pow(All.G * Group[i].Mass / (100 * All.Hubble * All.Hubble), 1.0 / 3); Right[i] = 3 * rguess; Left[i] = 0; Todo[i] = 1; } else { Todo[i] = 0; } } iter = 0; /* we will repeat the whole thing for those groups where we didn't converge to a SO radius yet */ 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 < Ngroups; i++) { if(Todo[i]) { R200[i] = 0.5 * (Left[i] + Right[i]); if(subfind_overdensity_evaluate(i, 0, &nexport, Send_count) < 0) break; } } 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]; } } SOdensGet = (struct SOdens_in *) mymalloc(nimport * sizeof(struct SOdens_in)); SOdensIn = (struct SOdens_in *) mymalloc(nexport * sizeof(struct SOdens_in)); /* prepare particle data for export */ for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; SOdensIn[j].Pos[0] = Group[place].Pos[0]; SOdensIn[j].Pos[1] = Group[place].Pos[1]; SOdensIn[j].Pos[2] = Group[place].Pos[2]; SOdensIn[j].R200 = R200[place]; memcpy(SOdensIn[j].NodeList, DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int)); } /* exchange 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 data */ MPI_Sendrecv(&SOdensIn[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct SOdens_in), MPI_BYTE, recvTask, TAG_DENS_A, &SOdensGet[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct SOdens_in), MPI_BYTE, recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } myfree(SOdensIn); SOdensResult = (struct SOdens_out *) mymalloc(nimport * sizeof(struct SOdens_out)); SOdensOut = (struct SOdens_out *) mymalloc(nexport * sizeof(struct SOdens_out)); /* now do the locations that were sent to us */ for(j = 0; j < nimport; j++) subfind_overdensity_evaluate(j, 1, &dummy, &dummy); if(i >= Ngroups) 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(&SOdensResult[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct SOdens_out), MPI_BYTE, recvTask, TAG_DENS_B, &SOdensOut[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct SOdens_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; M200[place] += SOdensOut[j].Mass; } myfree(SOdensOut); myfree(SOdensResult); myfree(SOdensGet); } while(ndone < NTask); /* do final operations on results */ for(i = 0, npleft = 0; i < Ngroups; i++) { if(Todo[i]) { overdensity = M200[i] / (4.0 * M_PI / 3.0 * R200[i] * R200[i] * R200[i]) / rhoback; if((Right[i] - Left[i]) > 1.0e-4 * Left[i]) { /* need to redo this group */ npleft++; if(overdensity > Deltas[rep]) Left[i] = R200[i]; else Right[i] = R200[i]; if(iter >= MAXITER - 10) { printf ("gr=%d task=%d R200=%g Left=%g Right=%g Menclosed=%g Right-Left=%g\n pos=(%g|%g|%g)\n", i, ThisTask, R200[i], Left[i], Right[i], M200[i], Right[i] - Left[i], Group[i].Pos[0], Group[i].Pos[1], Group[i].Pos[2]); fflush(stdout); } } else Todo[i] = 0; } } sumup_large_ints(1, &npleft, &ntot); t1 = second(); if(ntot > 0) { iter++; if(iter > 0 && ThisTask == 0) { printf("SO 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); #ifdef SO_VEL_DISPERSIONS 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 < Ngroups; i++) { if(subfind_overdensity_evaluate_dispersion(i, 0, &nexport, Send_count) < 0) break; } 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]; } } SOdensGet = (struct SOdens_in *) mymalloc(nimport * sizeof(struct SOdens_in)); SOdensIn = (struct SOdens_in *) mymalloc(nexport * sizeof(struct SOdens_in)); /* prepare particle data for export */ for(j = 0; j < nexport; j++) { place = DataIndexTable[j].Index; SOdensIn[j].Pos[0] = Group[place].Pos[0]; SOdensIn[j].Pos[1] = Group[place].Pos[1]; SOdensIn[j].Pos[2] = Group[place].Pos[2]; SOdensIn[j].R200 = R200[place]; memcpy(SOdensIn[j].NodeList, DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int)); } /* exchange 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 data */ MPI_Sendrecv(&SOdensIn[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct SOdens_in), MPI_BYTE, recvTask, TAG_DENS_A, &SOdensGet[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct SOdens_in), MPI_BYTE, recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } myfree(SOdensIn); SOdensResult = (struct SOdens_out *) mymalloc(nimport * sizeof(struct SOdens_out)); SOdensOut = (struct SOdens_out *) mymalloc(nexport * sizeof(struct SOdens_out)); /* now do the locations that were sent to us */ for(j = 0; j < nimport; j++) subfind_overdensity_evaluate_dispersion(j, 1, &dummy, &dummy); if(i >= Ngroups) 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(&SOdensResult[Recv_offset[recvTask]], Recv_count[recvTask] * sizeof(struct SOdens_out), MPI_BYTE, recvTask, TAG_DENS_B, &SOdensOut[Send_offset[recvTask]], Send_count[recvTask] * sizeof(struct SOdens_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; Vx200[place] += SOdensOut[j].Vx200; Vy200[place] += SOdensOut[j].Vy200; Vz200[place] += SOdensOut[j].Vz200; Disp200[place] += SOdensOut[j].Disp200; } myfree(SOdensOut); myfree(SOdensResult); myfree(SOdensGet); } while(ndone < NTask); #endif for(i = 0; i < Ngroups; i++) { if(Group[i].Nsubs > 0) { overdensity = M200[i] / (4.0 * M_PI / 3.0 * R200[i] * R200[i] * R200[i]) / rhoback; if((overdensity - Deltas[rep]) > 0.1 * Deltas[rep]) { R200[i] = M200[i] = 0; } else if(M200[i] < 5 * Group[i].Mass / Group[i].Len) { R200[i] = M200[i] = 0; } } else R200[i] = M200[i] = 0; switch (rep) { case 0: Group[i].M_Mean200 = M200[i]; Group[i].R_Mean200 = R200[i]; break; case 1: Group[i].M_TopHat200 = M200[i]; Group[i].R_TopHat200 = R200[i]; break; case 2: Group[i].M_Crit200 = M200[i]; Group[i].R_Crit200 = R200[i]; break; } #ifdef SO_VEL_DISPERSIONS if(R200[i] > 0 && M200[i] > 0) { Vx200[i] /= M200[i]; Vy200[i] /= M200[i]; Vz200[i] /= M200[i]; Disp200[i] /= M200[i]; Disp200[i] -= (Vx200[i] * Vx200[i] + Vy200[i] * Vy200[i] + Vz200[i] * Vz200[i]); Disp200[i] = sqrt(Disp200[i] / 3); /* convert to 1D velocity dispersion */ } else { Disp200[i] = 0; } switch (rep) { case 0: Group[i].VelDisp_Mean200 = Disp200[i]; break; case 1: Group[i].VelDisp_TopHat200 = Disp200[i]; break; case 2: Group[i].VelDisp_Crit200 = Disp200[i]; break; } #endif } } myfree(Todo); #ifdef SO_VEL_DISPERSIONS myfree(Disp200); myfree(Vz200); myfree(Vy200); myfree(Vx200); #endif myfree(M200); myfree(R200); myfree(Right); myfree(Left); myfree(DataNodeList); myfree(DataIndexTable); 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. */ int subfind_overdensity_evaluate(int target, int mode, int *nexport, int *nsend_local) { int startnode, listindex = 0; double h, mass, massret; MyDouble *pos; if(mode == 0) { pos = Group[target].Pos; h = R200[target]; } else { pos = SOdensGet[target].Pos; h = SOdensGet[target].R200; } if(mode == 0) { startnode = All.MaxPart; /* root node */ } else { startnode = SOdensGet[target].NodeList[0]; startnode = Nodes[startnode].u.d.nextnode; /* open it */ } mass = 0; while(startnode >= 0) { while(startnode >= 0) { massret = subfind_ovderdens_treefind(pos, h, target, &startnode, mode, nexport, nsend_local); if(massret < 0) return -1; mass += massret; } if(mode == 1) { listindex++; if(listindex < NODELISTLENGTH) { startnode = SOdensGet[target].NodeList[listindex]; if(startnode >= 0) startnode = Nodes[startnode].u.d.nextnode; /* open it */ } } } if(mode == 0) M200[target] = mass; else SOdensResult[target].Mass = mass; return 0; } double subfind_ovderdens_treefind(MyDouble searchcenter[3], MyFloat hsml, int target, int *startnode, int mode, int *nexport, int *nsend_local) { int no, p, task, nexport_save; struct NODE *current; double mass; MyDouble dx, dy, dz, dist, r2; #define FACT2 0.86602540 #ifdef PERIODIC MyDouble xtmp; #endif nexport_save = *nexport; mass = 0; no = *startnode; while(no >= 0) { if(no < All.MaxPart) /* single particle */ { p = no; no = Nextnode[no]; dist = hsml; dx = NGB_PERIODIC_LONG_X(P[p].Pos[0] - searchcenter[0]); if(dx > dist) continue; dy = NGB_PERIODIC_LONG_Y(P[p].Pos[1] - searchcenter[1]); if(dy > dist) continue; dz = NGB_PERIODIC_LONG_Z(P[p].Pos[2] - searchcenter[2]); if(dz > dist) continue; if(dx * dx + dy * dy + dz * dz > dist * dist) continue; mass += P[p].Mass; } else { if(no >= All.MaxPart + MaxNodes) /* pseudo particle */ { if(mode == 1) endrun(12312); if(mode == 0) { if(Exportflag[task = DomainTask[no - (All.MaxPart + MaxNodes)]] != target) { Exportflag[task] = target; Exportnodecount[task] = NODELISTLENGTH; } if(Exportnodecount[task] == NODELISTLENGTH) { if(*nexport >= All.BunchSize) { *nexport = nexport_save; if(nexport_save == 0) endrun(13005); /* in this case, the buffer is too small to process even a single particle */ for(task = 0; task < NTask; task++) nsend_local[task] = 0; for(no = 0; no < nexport_save; no++) nsend_local[DataIndexTable[no].Task]++; return -1; } Exportnodecount[task] = 0; Exportindex[task] = *nexport; DataIndexTable[*nexport].Task = task; DataIndexTable[*nexport].Index = target; DataIndexTable[*nexport].IndexGet = *nexport; *nexport = *nexport + 1; nsend_local[task]++; } DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]++] = DomainNodeIndex[no - (All.MaxPart + MaxNodes)]; if(Exportnodecount[task] < NODELISTLENGTH) DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]] = -1; } no = Nextnode[no - MaxNodes]; continue; } current = &Nodes[no]; if(mode == 1) { if(current->u.d.bitflags & (1 << BITFLAG_TOPLEVEL)) /* we reached a top-level node again, which means that we are done with the branch */ { *startnode = -1; return mass; } } no = current->u.d.sibling; /* in case the node can be discarded */ dist = hsml + 0.5 * current->len; dx = NGB_PERIODIC_LONG_X(current->center[0] - searchcenter[0]); if(dx > dist) continue; dy = NGB_PERIODIC_LONG_Y(current->center[1] - searchcenter[1]); if(dy > dist) continue; dz = NGB_PERIODIC_LONG_Z(current->center[2] - searchcenter[2]); if(dz > dist) continue; /* now test against the minimal sphere enclosing everything */ dist += FACT1 * current->len; if((r2 = (dx * dx + dy * dy + dz * dz)) > dist * dist) continue; if((current->u.d.bitflags & ((1 << BITFLAG_TOPLEVEL) + (1 << BITFLAG_DEPENDS_ON_LOCAL_MASS))) == 0) /* only use fully local nodes */ { /* test whether the node is contained within the sphere */ dist = hsml - FACT2 * current->len; if(dist > 0) if(r2 < dist * dist) { mass += current->u.d.mass; continue; } } no = current->u.d.nextnode; /* ok, we need to open the node */ } } *startnode = -1; return mass; } #ifdef SO_VEL_DISPERSIONS int subfind_overdensity_evaluate_dispersion(int target, int mode, int *nexport, int *nsend_local) { int ngb, n, j, startnode, listindex = 0; double h, vx, vy, vz, v2, vvx, vvy, vvz; MyDouble *pos; double boxsize, boxhalf, vel_to_peculiar, H_of_a; boxsize = All.BoxSize; boxhalf = 0.5 * All.BoxSize; H_of_a = hubble_function(All.Time); vel_to_peculiar = 1.0 / All.Time; if(mode == 0) { pos = Group[target].Pos; h = R200[target]; } else { pos = SOdensGet[target].Pos; h = SOdensGet[target].R200; } if(mode == 0) { startnode = All.MaxPart; /* root node */ } else { startnode = SOdensGet[target].NodeList[0]; startnode = Nodes[startnode].u.d.nextnode; /* open it */ } vx = vy = vz = v2 = 0; while(startnode >= 0) { while(startnode >= 0) { ngb = subfind_ovderdens_treefind_dispersion(pos, h, target, &startnode, mode, nexport, nsend_local); if(ngb < 0) return -1; for(n = 0; n < ngb; n++) { j = Ngblist[n]; vvx = vel_to_peculiar * P[j].Vel[0] + H_of_a * All.Time * NEAREST(P[j].Pos[0] - pos[0]); vvy = vel_to_peculiar * P[j].Vel[1] + H_of_a * All.Time * NEAREST(P[j].Pos[1] - pos[1]); vvz = vel_to_peculiar * P[j].Vel[2] + H_of_a * All.Time * NEAREST(P[j].Pos[2] - pos[2]); vx += P[j].Mass * vvx; vy += P[j].Mass * vvy; vz += P[j].Mass * vvz; v2 += P[j].Mass * (vvx * vvx + vvy * vvy + vvz * vvz); } } if(mode == 1) { listindex++; if(listindex < NODELISTLENGTH) { startnode = SOdensGet[target].NodeList[listindex]; if(startnode >= 0) startnode = Nodes[startnode].u.d.nextnode; /* open it */ } } } if(mode == 0) { Disp200[target] = v2; Vx200[target] = vx; Vy200[target] = vy; Vz200[target] = vz; } else { SOdensResult[target].Disp200 = v2; SOdensResult[target].Vx200 = vx; SOdensResult[target].Vy200 = vy; SOdensResult[target].Vz200 = vz; } return 0; } int subfind_ovderdens_treefind_dispersion(MyDouble searchcenter[3], MyFloat hsml, int target, int *startnode, int mode, int *nexport, int *nsend_local) { int no, p, task, nexport_save, numngb; struct NODE *current; MyDouble dx, dy, dz, dist, r2; #define FACT2 0.86602540 #ifdef PERIODIC MyDouble xtmp; #endif nexport_save = *nexport; numngb = 0; no = *startnode; while(no >= 0) { if(no < All.MaxPart) /* single particle */ { p = no; no = Nextnode[no]; dist = hsml; dx = NGB_PERIODIC_LONG_X(P[p].Pos[0] - searchcenter[0]); if(dx > dist) continue; dy = NGB_PERIODIC_LONG_Y(P[p].Pos[1] - searchcenter[1]); if(dy > dist) continue; dz = NGB_PERIODIC_LONG_Z(P[p].Pos[2] - searchcenter[2]); if(dz > dist) continue; if(dx * dx + dy * dy + dz * dz > dist * dist) continue; Ngblist[numngb++] = p; } else { if(no >= All.MaxPart + MaxNodes) /* pseudo particle */ { if(mode == 1) endrun(12312); if(mode == 0) { if(Exportflag[task = DomainTask[no - (All.MaxPart + MaxNodes)]] != target) { Exportflag[task] = target; Exportnodecount[task] = NODELISTLENGTH; } if(Exportnodecount[task] == NODELISTLENGTH) { if(*nexport >= All.BunchSize) { *nexport = nexport_save; if(nexport_save == 0) endrun(13005); /* in this case, the buffer is too small to process even a single particle */ for(task = 0; task < NTask; task++) nsend_local[task] = 0; for(no = 0; no < nexport_save; no++) nsend_local[DataIndexTable[no].Task]++; return -1; } Exportnodecount[task] = 0; Exportindex[task] = *nexport; DataIndexTable[*nexport].Task = task; DataIndexTable[*nexport].Index = target; DataIndexTable[*nexport].IndexGet = *nexport; *nexport = *nexport + 1; nsend_local[task]++; } DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]++] = DomainNodeIndex[no - (All.MaxPart + MaxNodes)]; if(Exportnodecount[task] < NODELISTLENGTH) DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]] = -1; } no = Nextnode[no - MaxNodes]; continue; } current = &Nodes[no]; if(mode == 1) { if(current->u.d.bitflags & (1 << BITFLAG_TOPLEVEL)) /* we reached a top-level node again, which means that we are done with the branch */ { *startnode = -1; return numngb; } } no = current->u.d.sibling; /* in case the node can be discarded */ dist = hsml + 0.5 * current->len; dx = NGB_PERIODIC_LONG_X(current->center[0] - searchcenter[0]); if(dx > dist) continue; dy = NGB_PERIODIC_LONG_Y(current->center[1] - searchcenter[1]); if(dy > dist) continue; dz = NGB_PERIODIC_LONG_Z(current->center[2] - searchcenter[2]); if(dz > dist) continue; /* now test against the minimal sphere enclosing everything */ dist += FACT1 * current->len; if((r2 = (dx * dx + dy * dy + dz * dz)) > dist * dist) continue; no = current->u.d.nextnode; /* ok, we need to open the node */ } } *startnode = -1; return numngb; } #endif #endif
{ "alphanum_fraction": 0.5880455726, "avg_line_length": 25.1041009464, "ext": "c", "hexsha": "04db7eb203a982210b9d2a34ef9c5f54c9baab03", "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_so.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_so.c", "max_line_length": 144, "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_so.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7610, "size": 23874 }
/* * ----------------------------------------------------------------- * isat_lib.c * In Situ Adaptive Tabulation Library * Version: 2.0 * Last Update: Nov 3, 2019 * * Programmer: Americo Barbosa da Cunha Junior * americo.cunhajr@gmail.com * ----------------------------------------------------------------- * Copyright (c) 2010-2019, Americo Barbosa da Cunha Junior * All rights reserved. * ----------------------------------------------------------------- * This is the implementation file for ISAT_LIB module, a * computational library with In Situ Adaptive Tabulation (ISAT) * algorithm routines. * ----------------------------------------------------------------- */ #include <stdlib.h> #include <math.h> #include <time.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "../include/thrm_lib.h" #include "../include/ell_lib.h" #include "../include/ode_lib.h" #include "../include/isat_lib.h" /* *------------------------------------------------------------ * isat_alloc * * This function alocates memory for an ISAT workspace * structure and initialize its elements. * * Output: * isat_mem - pointer to ISAT workspace * * last update: Oct 9, 2019 *------------------------------------------------------------ */ isat_wrk *isat_alloc() { /* create ISAT workspace */ isat_wrk *isat_mem = NULL; /* memory allocation for ISAT workspace */ isat_mem = (isat_wrk *) malloc(sizeof(isat_wrk)); if ( isat_mem == NULL ) return NULL; /* initialize ISAT workspace elements */ isat_mem->root = NULL; isat_mem->lf = 0; isat_mem->nd = 0; isat_mem->add = 0; isat_mem->grw = 0; isat_mem->rtv = 0; isat_mem->dev = 0; isat_mem->hgt = 0; isat_mem->maxleaves = 0; isat_mem->time_add = 0.0; isat_mem->time_grw = 0.0; isat_mem->time_rtv = 0.0; isat_mem->time_dev = 0.0; return isat_mem; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * isat_free * * This function release the memory used by ISAT workspace. * * Input: * isat_bl - pointer to ISAT workspace * * last update: Oct 9, 2019 *------------------------------------------------------------ */ void isat_free(void **isat_bl) { /* create ISAT workspace */ isat_wrk *isat_mem = NULL; /* check if ISAT workspace memory block is NULL */ if ( *isat_bl == NULL ) return; isat_mem = (isat_wrk *) (*isat_bl); /* release the memory allocated for ISAT workspace elements */ if( isat_mem->root != NULL ) { bst_node_free((void **)&(isat_mem->root)); isat_mem->root = NULL; } /* release the memory allocated for ISAT workspace */ free(*isat_bl); *isat_bl = NULL; return; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * isat_bst_init * * This function initiates ISAT binary search tree. * * Input: * isat_mem - pointer to ISAT workspace * * last update: Oct 9, 2019 *------------------------------------------------------------ */ int isat_bst_init(isat_wrk *isat_mem) { /* check if ISAT workspece is allocated */ if ( isat_mem == NULL ) return GSL_EINVAL; /* memory allocation for ISAT binary search tree root */ if ( isat_mem->root == NULL ) { isat_mem->root = bst_node_alloc(); if ( isat_mem->root == NULL ) { free(isat_mem); isat_mem = NULL; return GSL_EINVAL; } } return GSL_SUCCESS; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * isat_statistics * * This function prints on screen ISAT workspace * statistics of usage. * * Input: * isat_mem - pointer to ISAT workspace * * last update: Oct 1, 2019 *------------------------------------------------------------ */ void isat_statistics(isat_wrk *isat_mem) { double time_add; double time_grw; double time_rtv; double time_dev; time_add = (double) (isat_mem->time_add / CLOCKS_PER_SEC) / isat_mem->add; time_grw = (double) (isat_mem->time_grw / CLOCKS_PER_SEC) / isat_mem->grw; time_rtv = (double) (isat_mem->time_rtv / CLOCKS_PER_SEC) / isat_mem->rtv; time_dev = (double) (isat_mem->time_dev / CLOCKS_PER_SEC) / isat_mem->dev; printf("\n ISAT statistics:"); printf("\n # of adds = %d", isat_mem->add); printf("\n # of grows = %d", isat_mem->grw); printf("\n # of retrieves = %d", isat_mem->rtv); printf("\n # of dir. eval. = %d", isat_mem->dev); printf("\n # of leaves = %d", isat_mem->lf); printf("\n # of nodes = %d", isat_mem->nd); printf("\n tree height = %d\n", isat_mem->hgt); printf("\n average values for CPU time (s):"); printf("\n add: %+.6e",time_add); printf("\n grw: %+.6e",time_grw); printf("\n rtv: %+.6e",time_rtv); printf("\n dev: %+.6e",time_dev); return; } /*------------------------------------------------------------*/ /* * ----------------------------------------------------------------- * isat_input * * This function receives ISAT input parameters from the user. * * Input: * maxleaves - maximum number of ISAT tree leaves * etol - ISAT error tolerance * * Output: * success or error * * last update: Nov 3, 2019 * ----------------------------------------------------------------- */ int isat_input(unsigned int *maxleaves,double *etol) { printf("\n Input ISAT parameters:\n"); printf("\n maximum of tree leaves:"); scanf("%d", maxleaves); printf("\n %d\n", *maxleaves); if( *maxleaves <= 0 ) GSL_ERROR(" maxleaves must be a positive integer",GSL_EINVAL); printf("\n ISAT error tolerance:"); scanf("%lf", etol); printf("\n %+.1e\n", *etol); if( *etol < 0.0 ) GSL_ERROR(" etol must be grather than zero",GSL_EINVAL); return GSL_SUCCESS; } /*----------------------------------------------------------------*/ /* *------------------------------------------------------------ * isat_eoa_matrix * * This function computes the EOA matrix in Cholesky form. * * Input: * A - gradient matrix * etol - error tolerance * * Output: * L - EOA Cholesky matrix * * last update: Oct 9, 2019 *------------------------------------------------------------ */ void isat_eoa_mtrx(gsl_matrix *A, double etol, gsl_matrix *L) { unsigned int i; double eps_max = 0.5; gsl_matrix *Aetol = NULL; gsl_matrix *V = NULL; gsl_vector *sigma = NULL; /* memory allocation */ Aetol = gsl_matrix_calloc(A->size2,A->size2); V = gsl_matrix_calloc(A->size2,A->size2); sigma = gsl_vector_calloc(A->size2); /* Aetol := A */ gsl_matrix_memcpy(Aetol,A); /* Aetol := (1/etol).A */ gsl_matrix_scale (Aetol,1.0/etol); /* Aetol = U*sigma*V^T */ ell_psd2eig(Aetol,V,sigma); /* eliminate small and large singular values */ for ( i = 0; i < sigma->size; i++ ) sigma->data[i] = GSL_MAX(sigma->data[i],eps_max); /* V*sigma^2*V^T = L*L^T */ ell_eig2chol(V,sigma,L); /* release allocated memory */ gsl_vector_free(sigma); gsl_matrix_free(V); gsl_matrix_free(Aetol); sigma = NULL; V = NULL; Aetol = NULL; return; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * isat_lerror * * This function computes the local error defined as * * eps = ||Rl(phi)- R(phi)||_2 where * * Rl(phi) = R(phi0) + A*(phi-phi0). * * Input: * Rphi - reaction mapping of phi * Rphi0 - reaction mapping of phi0 * A - mapping gradient matrix * phi - query composition * phi0 - initial composition * * Output: * eps - local error * * last update: Feb 19, 2010 *------------------------------------------------------------ */ double isat_lerror(gsl_vector *Rphi, gsl_vector *Rphi0, gsl_matrix *A, gsl_vector *phi, gsl_vector *phi0) { double eps; gsl_vector *Rlphi = NULL; /* memory allocation for Rlphi */ Rlphi = gsl_vector_calloc(phi->size); /* Rlphi := R(phi0) + A*(phi-phi0) */ linear_approx(phi,phi0,Rphi0,A,Rlphi); /* Rlphi := Rl(phi) - R(phi) */ gsl_vector_sub(Rlphi,Rphi); /* eps := 2-norm(Rl(phi) - R(phi)) */ eps = gsl_blas_dnrm2(Rlphi); /* releasing allocated memory */ gsl_vector_free(Rlphi); Rlphi = NULL; return eps; } /*------------------------------------------------------------*/ /* *------------------------------------------------------------ * isat4 * * This function executes the 4-th version of the * In Situ Adaptive Tabulation (ISAT) algorithm. * * * Input: * isat_mem - ISAT workspace * cvode_mem - ODE solver workspace * etol - error tolerance * t0 - initial time * delta_t - time step * phi - query composition * A - mapping gradient matrix * L - EOA Cholesky matrix * * Output: * Rphi - reaction mapping * success or error * * last update: Nov 3, 2019 *------------------------------------------------------------ */ int isat4(isat_wrk *isat_mem, void *cvode_mem, double etol, double t0, double delta_t, gsl_vector *phi, gsl_matrix *A, gsl_matrix *L, gsl_vector *Rphi) { /* CPU clock start counter */ clock_t cpu_start = clock(); int flag; unsigned int bst_side; bst_leaf *end_leaf = NULL; bst_node *end_node = NULL; /****** First call for ISAT algorithm ******/ /* check if there is no leaf in the binary search tree */ if( isat_mem->lf == 0 ) { int flag; bst_leaf *first_leaf = NULL; /* memory allocation for BST first leaf */ first_leaf = bst_leaf_alloc(); if ( first_leaf == NULL ) return GSL_ENOMEM; /* direct integration */ flag = odesolver_reinit(t0,phi,cvode_mem); if ( flag != GSL_SUCCESS ) return flag; flag = odesolver(cvode_mem, delta_t, Rphi); if ( flag != GSL_SUCCESS ) return flag; /* compute the mapping gradient matrix */ flag = gradient(cvode_mem,t0,delta_t,phi,Rphi,A); if ( flag != GSL_SUCCESS ) return flag; /* compute EOA Cholesky matrix */ isat_eoa_mtrx(A,etol,L); /* define first leaf elements */ bst_leaf_set(phi,Rphi,A,L,first_leaf); isat_mem->root->r_leaf = first_leaf; /* update ISAT workspace counters */ isat_mem->lf++; isat_mem->hgt = bst_height(isat_mem->root); return GSL_SUCCESS; } /****** Further calls for ISAT algorithm ******/ /* search for the near composition in binary search tree */ if( isat_mem->lf > 1 ) bst_side = bst_search(isat_mem->root, phi, &end_node, &end_leaf); else { end_node = isat_mem->root; end_leaf = isat_mem->root->r_leaf; bst_side = BST_RIGHT; } /* check if the near composition is inside the ellipsoid */ flag = ell_pt_in(phi,end_leaf->phi,end_leaf->L); if( flag == ELL_TRUE ) { /* compute the linear approximation */ linear_approx(phi,end_leaf->phi,end_leaf->Rphi,end_leaf->A,Rphi); /* update ISAT workspace counters */ isat_mem->rtv++; isat_mem->time_rtv += clock() - cpu_start; return GSL_SUCCESS; } else { double lerror = 0.0; /* performe direct integration */ flag = odesolver_reinit(t0,phi,cvode_mem); if ( flag != GSL_SUCCESS ) return flag; flag = odesolver(cvode_mem,delta_t,Rphi); if ( flag != GSL_SUCCESS ) return flag; /* compute ISAT local error */ lerror = isat_lerror(Rphi,end_leaf->Rphi, end_leaf->A,phi,end_leaf->phi); /* check if the local error is greater than etol */ if( lerror < etol ) { /* grow the ellipsoid */ ell_pt_modify(phi,end_leaf->phi,end_leaf->L); /* update ISAT workspace counters */ isat_mem->grw++; isat_mem->time_grw += clock() - cpu_start; return GSL_SUCCESS; } else { /* check if the maximum number of leaves is excced */ if( isat_mem->lf > isat_mem->maxleaves ) { /* update ISAT workspace counters */ isat_mem->dev++; isat_mem->time_dev += clock() - cpu_start; return GSL_SUCCESS; } bst_leaf *new_leaf = NULL; /* memory allocation */ new_leaf = bst_leaf_alloc(); if ( new_leaf == NULL ) return GSL_ENOMEM; /* compute the mapping gradient matrix */ flag = gradient(cvode_mem,t0,delta_t,phi,Rphi,A); if ( flag != GSL_SUCCESS ) return flag; /* compute ellipsoid matrix */ isat_eoa_mtrx(A,etol,L); /* define the new leaf elements */ bst_leaf_set(phi,Rphi,A,L,new_leaf); /* check if the binary search tree has more than one leaf */ if( isat_mem->lf > 1 ) { bst_node *new_node = NULL; /* memory allocation for the new node */ new_node = bst_node_alloc(); if ( new_node == NULL ) return GSL_ENOMEM; /* define the new node leaves */ bst_node_set(end_leaf,new_leaf,new_node); /* add the new node to the binary search tree */ bst_node_add(bst_side,end_node,new_node); } else bst_node_set(end_leaf,new_leaf,end_node); /* update ISAT workspace counters */ isat_mem->add++; isat_mem->lf++; isat_mem->nd++; isat_mem->hgt = bst_height(isat_mem->root); isat_mem->time_add += clock() - cpu_start; return GSL_SUCCESS; } } } /*------------------------------------------------------------*/
{ "alphanum_fraction": 0.4840900013, "avg_line_length": 26.0346620451, "ext": "c", "hexsha": "7114e18da121f5a8e494e7c54eeadcb0df60f4e6", "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-2.0/src/isat_lib.c", "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-2.0/src/isat_lib.c", "max_line_length": 78, "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-2.0/src/isat_lib.c", "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": 3742, "size": 15022 }
/* specfunc/hermite.c * * Copyright (C) 2011, 2012, 2013, 2014 Konrad Griessinger * (konradg(at)gmx.net) * * 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. */ /*----------------------------------------------------------------------* * "The purpose of computing is insight, not numbers." - R.W. Hamming * * Hermite polynomials, Hermite functions * * and their respective arbitrary derivatives * *----------------------------------------------------------------------*/ /* TODO: * - array functions for derivatives of Hermite functions * - asymptotic approximation for derivatives of Hermite functions * - refine existing asymptotic approximations, especially around x=sqrt(2*n+1) or x=sqrt(2*n+1)*sqrt(2), respectively */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_airy.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf_pow_int.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_hermite.h> #include "error.h" #include "eval.h" #define pow2(n) (gsl_sf_pow_int(2,n)) /* Evaluates the probabilists' Hermite polynomial of order n at position x using upward recurrence. */ static int gsl_sf_hermite_prob_iter_e(const int n, const double x, gsl_sf_result * result) { result->val = 0.; result->err = 0.; if(n < 0) { DOMAIN_ERROR(result); } else if(n == 0) { result->val = 1.; result->err = 0.; return GSL_SUCCESS; } else if(n == 1) { result->val = x; result->err = 0.; return GSL_SUCCESS; } else if(x == 0.){ if(GSL_IS_ODD(n)){ result->val = 0.; result->err = 0.; return GSL_SUCCESS; } else{ if(n < 301){ /* double f; int j; f = (GSL_IS_ODD(n/2)?-1.:1.); for(j=1; j < n; j+=2) { f*=j; } result->val = f; result->err = 0.; */ if(n < 297){ gsl_sf_doublefact_e(n-1, result); (GSL_IS_ODD(n/2)?result->val = -result->val:1.); } else if (n == 298){ result->val = (GSL_IS_ODD(n/2)?-1.:1.)*1.25527562259930633890922678431e304; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); } else{ result->val = (GSL_IS_ODD(n/2)?-1.:1.)*3.7532741115719259533385880851e306; result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val); } } else{ result->val = (GSL_IS_ODD(n/2)?GSL_NEGINF:GSL_POSINF); result->err = GSL_POSINF; } return GSL_SUCCESS; } } /* else if(x*x < 4.0*n && n > 100000) { // asymptotic formula double f = 1.0; int j; if(GSL_IS_ODD(n)) { f=gsl_sf_fact((n-1)/2)*gsl_sf_pow_int(2,n/2)*M_SQRT2/M_SQRTPI; } else { for(j=1; j < n; j+=2) { f*=j; } } return f*exp(x*x/4)*cos(x*sqrt(n)-(n%4)*M_PI_2)/sqrt(sqrt(1-x*x/4.0/n)); // return f*exp(x*x/4)*cos(x*sqrt(n)-n*M_PI_2)/sqrt(sqrt(1-x*x/4.0/n)); } */ else{ /* upward recurrence: He_{n+1} = x He_n - n He_{n-1} */ double p_n0 = 1.0; /* He_0(x) */ double p_n1 = x; /* He_1(x) */ double p_n = p_n1; double e_n0 = GSL_DBL_EPSILON; double e_n1 = fabs(x)*GSL_DBL_EPSILON; double e_n = e_n1; int j=0, c=0; for(j=1; j <= n-1; j++){ if (gsl_isnan(p_n) == 1){ break; } p_n = x*p_n1-j*p_n0; p_n0 = p_n1; p_n1 = p_n; e_n = (fabs(x)*e_n1+j*e_n0); e_n0 = e_n1; e_n1 = e_n; while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){ p_n0 *= 0.5; p_n1 *= 0.5; p_n = p_n1; e_n0 *= 0.5; e_n1 *= 0.5; e_n = e_n1; c++; } while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){ p_n0 *= 2.0; p_n1 *= 2.0; p_n = p_n1; e_n0 *= 2.0; e_n1 *= 2.0; e_n = e_n1; c--; } } /* // check to see that the correct values are computed, even when overflow strikes in the end; works, thus very large results are accessible by determining mantissa and exponent separately double lg2 = 0.30102999566398119521467838; double ln10 = 2.3025850929940456840179914546843642076011014886; printf("res= %g\n", p_n*pow(10.,((lg2*c)-((long)(lg2*c)))) ); printf("res= %g * 10^(%ld)\n", p_n*pow(10.,((lg2*c)-((long)(lg2*c))))/pow(10.,((long)(log(fabs(p_n*pow(10.,((lg2*c)-((long)(lg2*c))))))/ln10))), ((long)(log(fabs(p_n*pow(10.,((lg2*c)-((long)(lg2*c))))))/ln10))+((long)(lg2*c)) ); */ result->val = pow2(c)*p_n; result->err = pow2(c)*e_n + fabs(result->val)*GSL_DBL_EPSILON; /* result->err = e_n + n*fabs(p_n)*GSL_DBL_EPSILON; no idea, where the factor n came from => removed */ if (gsl_isnan(result->val) != 1){ return GSL_SUCCESS; } else{ return GSL_ERANGE; } } } /* Approximatively evaluates the probabilists' Hermite polynomial of order n at position x. * An approximation depending on the x-range (see Szego, Gabor (1939, 1958, 1967), Orthogonal Polynomials, American Mathematical Society) is used. */ static int gsl_sf_hermite_prob_appr_e(const int n, const double x, gsl_sf_result * result) { /* Plancherel-Rotach approximation (note: Szego defines the Airy function differently!) */ const double aizero1 = -2.3381074104597670384891972524467; /* first zero of the Airy function Ai */ double z = fabs(x)*M_SQRT1_2; double f = 1.; int j; for(j=1; j <= n; j++) { f*=sqrt(j); } if (z < sqrt(2*n+1.)+aizero1/M_SQRT2/pow(n,1/6.)){ double phi = acos(z/sqrt(2*n+1.)); result->val = f*(GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*pow(2./n,0.25)/sqrt(M_SQRTPI*sin(phi))*sin(M_PI*0.75+(0.5*n+0.25)*(sin(2*phi)-2*phi))*exp(0.5*z*z); result->err = 2. * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if (z > sqrt(2*n+1.)-aizero1/M_SQRT2/pow(n,1/6.)){ double phi = acosh(z/sqrt(2*n+1.)); result->val = f*(GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*pow(n,-0.25)/M_SQRT2/sqrt(M_SQRT2*M_SQRTPI*sinh(phi))*exp((0.5*n+0.25)*(2*phi-sinh(2*phi)))*exp(0.5*z*z); result->err = 2. * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else{ gsl_sf_result Ai; gsl_sf_airy_Ai_e((z-sqrt(2*n+1.))*M_SQRT2*pow(n,1/6.),0,&Ai); result->val = f*(GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*sqrt(M_SQRTPI*M_SQRT2)*pow(n,-1/12.)*Ai.val*exp(0.5*z*z); result->err = f*sqrt(M_SQRTPI*M_SQRT2)*pow(n,-1/12.)*Ai.err*exp(0.5*z*z) + GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } } /* Evaluates the probabilists' Hermite polynomial of order n at position x. * For small n upward recurrence is employed, while for large n and NaNs from the iteration an approximation depending on the x-range (see Szego, Gabor (1939, 1958, 1967), Orthogonal Polynomials, American Mathematical Society) is used. */ int gsl_sf_hermite_prob_e(const int n, const double x, gsl_sf_result * result) { if( (x==0. || n<=100000) && (gsl_sf_hermite_prob_iter_e(n,x,result)==GSL_SUCCESS) ){ return GSL_SUCCESS; } else{ return gsl_sf_hermite_prob_appr_e(n,x,result); } } double gsl_sf_hermite_prob(const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_prob_e(n, x, &result)); } /* Evaluates the m-th derivative of the probabilists' Hermite polynomial of order n at position x. * The direct formula He^{(m)}_n = n!/(n-m)!*He_{n-m}(x) (where He_j(x) is the j-th probabilists' Hermite polynomial and He^{(m)}_j(x) its m-th derivative) is employed. */ int gsl_sf_hermite_prob_der_e(const int m, const int n, const double x, gsl_sf_result * result) { if(n < 0 || m < 0) { DOMAIN_ERROR(result); } else if(n < m) { result->val = 0.; result->err = 0.; return GSL_SUCCESS; } else{ double f = gsl_sf_choose(n,m)*gsl_sf_fact(m); gsl_sf_result He; gsl_sf_hermite_prob_e(n-m,x,&He); result->val = He.val*f; result->err = He.err*f + GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } } double gsl_sf_hermite_prob_der(const int m, const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_prob_der_e(m, n, x, &result)); } /* Evaluates the physicists' Hermite polynomial of order n at position x. * For small n upward recurrence is employed, while for large n and NaNs from the iteration an approximation depending on the x-range (see Szego, Gabor (1939, 1958, 1967), Orthogonal Polynomials, American Mathematical Society) is used. */ int gsl_sf_hermite_phys_e(const int n, const double x, gsl_sf_result * result) { result->val = 0.; result->err = 0.; if(n < 0) { DOMAIN_ERROR(result); } else if(n == 0) { result->val = 1.; result->err = 0.; return GSL_SUCCESS; } else if(n == 1) { result->val = 2.0*x; result->err = 0.; return GSL_SUCCESS; } else if(x == 0.){ if(GSL_IS_ODD(n)){ result->val = 0.; result->err = 0.; return GSL_SUCCESS; } else{ if(n < 269){ double f = pow2(n/2); gsl_sf_doublefact_e(n-1, result); result->val *= f; result->err *= f; (GSL_IS_ODD(n/2)?result->val = -result->val:1.); /* double f; int j; f = (GSL_IS_ODD(n/2)?-1.:1.); for(j=1; j < n; j+=2) { f*=2*j; } result->val = f; result->err = 0.; */ } else{ result->val = (GSL_IS_ODD(n/2)?GSL_NEGINF:GSL_POSINF); result->err = GSL_POSINF; } return GSL_SUCCESS; } } /* else if(x*x < 2.0*n && n > 100000) { // asymptotic formula double f = 1.0; int j; if(GSL_IS_ODD(n)) { f=gsl_sf_fact((n-1)/2)*gsl_sf_pow_int(2,n)/M_SQRTPI; } else { for(j=1; j < n; j+=2) { f*=j; } f*=gsl_sf_pow_int(2,n/2); } return f*exp(x*x/2)*cos(x*sqrt(2.0*n)-(n%4)*M_PI_2)/sqrt(sqrt(1-x*x/2.0/n)); // return f*exp(x*x/2)*cos(x*sqrt(2.0*n)-n*M_PI_2)/sqrt(sqrt(1-x*x/2.0/n)); } */ else if (n <= 100000){ /* upward recurrence: H_{n+1} = 2x H_n - 2j H_{n-1} */ double p_n0 = 1.0; /* H_0(x) */ double p_n1 = 2.0*x; /* H_1(x) */ double p_n = p_n1; double e_n0 = GSL_DBL_EPSILON; double e_n1 = 2.*fabs(x)*GSL_DBL_EPSILON; double e_n = e_n1; int j=0, c=0; for(j=1; j <= n-1; j++){ if (gsl_isnan(p_n) == 1){ break; } p_n = 2.0*x*p_n1-2.0*j*p_n0; p_n0 = p_n1; p_n1 = p_n; e_n = 2.*(fabs(x)*e_n1+j*e_n0); e_n0 = e_n1; e_n1 = e_n; while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){ p_n0 *= 0.5; p_n1 *= 0.5; p_n = p_n1; e_n0 *= 0.5; e_n1 *= 0.5; e_n = e_n1; c++; } while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){ p_n0 *= 2.0; p_n1 *= 2.0; p_n = p_n1; e_n0 *= 2.0; e_n1 *= 2.0; e_n = e_n1; c--; } } result->val = pow2(c)*p_n; result->err = pow2(c)*e_n + fabs(result->val)*GSL_DBL_EPSILON; /* result->err = e_n + n*fabs(p_n)*GSL_DBL_EPSILON; no idea, where the factor n came from => removed */ if (gsl_isnan(result->val) != 1){ return GSL_SUCCESS; } } /* the following condition is implied by the logic above */ { /* Plancherel-Rotach approximation (note: Szego defines the Airy function differently!) */ const double aizero1 = -2.3381074104597670384891972524467; /* first zero of the Airy function Ai */ double z = fabs(x); double f = 1.; int j; for(j=1; j <= n; j++) { f*=sqrt(j); } if (z < sqrt(2*n+1.)+aizero1/M_SQRT2/pow(n,1/6.)){ double phi = acos(z/sqrt(2*n+1.)); result->val = f*(GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*(GSL_IS_ODD(n)?M_SQRT2:1.)*pow2(n/2)*pow(2./n,0.25)/sqrt(M_SQRTPI*sin(phi))*sin(M_PI*0.75+(0.5*n+0.25)*(sin(2*phi)-2*phi))*exp(0.5*z*z); result->err = 2. * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if (z > sqrt(2*n+1.)-aizero1/M_SQRT2/pow(n,1/6.)){ double phi = acosh(z/sqrt(2*n+1.)); result->val = f*(GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*(GSL_IS_ODD(n)?1.:M_SQRT1_2)*pow2(n/2)*pow(n,-0.25)/sqrt(M_SQRT2*M_SQRTPI*sinh(phi))*exp((0.5*n+0.25)*(2*phi-sinh(2*phi)))*exp(0.5*z*z); result->err = 2. * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else{ gsl_sf_result Ai; gsl_sf_airy_Ai_e((z-sqrt(2*n+1.))*M_SQRT2*pow(n,1/6.),0,&Ai); result->val = f*(GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*(GSL_IS_ODD(n)?M_SQRT2:1.)*sqrt(M_SQRTPI*M_SQRT2)*pow2(n/2)*pow(n,-1/12.)*Ai.val*exp(0.5*z*z); result->err = f*(GSL_IS_ODD(n)?M_SQRT2:1.)*pow2(n/2)*sqrt(M_SQRTPI*M_SQRT2)*pow(n,-1/12.)*Ai.err*exp(0.5*z*z) + GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } } } double gsl_sf_hermite_phys(const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_phys_e(n, x, &result)); } /* Evaluates the m-th derivative of the physicists' Hermite polynomial of order n at position x. * The direct formula H^{(m)}_n = 2**m*n!/(n-m)!*H_{n-m}(x) (where H_j(x) is the j-th physicists' Hermite polynomial and H^{(m)}_j(x) its m-th derivative) is employed. */ int gsl_sf_hermite_phys_der_e(const int m, const int n, const double x, gsl_sf_result * result) { if(n < 0 || m < 0) { DOMAIN_ERROR(result); } else if(n < m) { result->val = 0.; result->err = 0.; return GSL_SUCCESS; } else{ double f = gsl_sf_choose(n,m)*gsl_sf_fact(m)*pow2(m); gsl_sf_result H; gsl_sf_hermite_phys_e(n-m,x,&H); result->val = H.val*f; result->err = H.err*f + GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } } double gsl_sf_hermite_phys_der(const int m, const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_phys_der_e(m, n, x, &result)); } /* Evaluates the Hermite function of order n at position x. * For large n an approximation depending on the x-range (see Szego, Gabor (1939, 1958, 1967), Orthogonal Polynomials, American Mathematical Society) is used, while for small n the direct formula via the probabilists' Hermite polynomial is applied. */ int gsl_sf_hermite_func_e(const int n, const double x, gsl_sf_result * result) { /* if (x*x < 2.0*n && n > 100000){ // asymptotic formula double f = 1.0; int j; // return f*exp(x*x/4)*cos(x*sqrt(n)-n*M_PI_2)/sqrt(sqrt(1-x*x/4.0/n)); return cos(x*sqrt(2.0*n)-(n%4)*M_PI_2)/sqrt(sqrt(0.5*n/M_PI*(1-0.5*x*x/n)))/M_PI; } */ if (n < 0){ DOMAIN_ERROR(result); } else if(n == 0 && x != 0.) { result->val = exp(-0.5*x*x)/sqrt(M_SQRTPI); result->err = GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } else if(n == 1 && x != 0.) { result->val = M_SQRT2*x*exp(-0.5*x*x)/sqrt(M_SQRTPI); result->err = GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } else if (x == 0.){ if (GSL_IS_ODD(n)){ result->val = 0.; result->err = 0.; return GSL_SUCCESS; } else{ double f; int j; f = (GSL_IS_ODD(n/2)?-1.:1.); for(j=1; j < n; j+=2) { f*=sqrt(j/(j+1.)); } result->val = f/sqrt(M_SQRTPI); result->err = GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } } else if (n <= 100000){ double f = exp(-0.5*x*x)/sqrt(M_SQRTPI*gsl_sf_fact(n)); gsl_sf_result He; gsl_sf_hermite_prob_iter_e(n,M_SQRT2*x,&He); result->val = He.val*f; result->err = He.err*f + GSL_DBL_EPSILON*fabs(result->val); if (gsl_isnan(result->val) != 1 && f > GSL_DBL_MIN && gsl_finite(He.val) == 1){ return GSL_SUCCESS; } } /* upward recurrence: Psi_{n+1} = sqrt(2/(n+1))*x Psi_n - sqrt(n/(n+1)) Psi_{n-1} */ { double tw = exp(-x*x*0.5/n); /* "twiddle factor" (in the spirit of FFT) */ double p_n0 = tw/sqrt(M_SQRTPI); /* Psi_0(x) */ double p_n1 = p_n0*M_SQRT2*x; /* Psi_1(x) */ double p_n = p_n1; double e_n0 = p_n0*GSL_DBL_EPSILON; double e_n1 = p_n1*GSL_DBL_EPSILON; double e_n = e_n1; int j; int c = 0; for (j=1;j<n;j++) { if (gsl_isnan(p_n) == 1){ break; } p_n=tw*(M_SQRT2*x*p_n1-sqrt(j)*p_n0)/sqrt(j+1.); p_n0=tw*p_n1; p_n1=p_n; e_n=tw*(M_SQRT2*fabs(x)*e_n1+sqrt(j)*e_n0)/sqrt(j+1.); e_n0=tw*e_n1; e_n1=e_n; while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){ p_n0 *= 0.5; p_n1 *= 0.5; p_n = p_n1; e_n0 *= 0.5; e_n1 *= 0.5; e_n = e_n1; c++; } while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){ p_n0 = p_n0*2; p_n1 = p_n1*2; p_n = p_n1; e_n0 = e_n0*2; e_n1 = e_n1*2; e_n = e_n1; c--; } } result->val = p_n*pow2(c); result->err = n*fabs(result->val)*GSL_DBL_EPSILON; if (gsl_isnan(result->val) != 1){ return GSL_SUCCESS; } { /* Plancherel-Rotach approximation (note: Szego defines the Airy function differently!) */ const double aizero1 = -2.3381074104597670384891972524467; /* first zero of the Airy function Ai */ double z = fabs(x); if (z < sqrt(2*n+1.)+aizero1/M_SQRT2/pow(n,1/6.)){ double phi = acos(z/sqrt(2*n+1.)); result->val = (GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*pow(2./n,0.25)/M_SQRTPI/sqrt(sin(phi))*sin(M_PI*0.75+(0.5*n+0.25)*(sin(2*phi)-2*phi)); result->err = 2. * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else if (z > sqrt(2*n+1.)-aizero1/M_SQRT2/pow(n,1/6.)){ double phi = acosh(z/sqrt(2*n+1.)); result->val = (GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*pow(n,-0.25)/ 2/M_SQRTPI/sqrt(sinh(phi)/M_SQRT2)*exp((0.5*n+0.25)*(2*phi-sinh(2*phi))); result->err = 2. * GSL_DBL_EPSILON * fabs(result->val); return GSL_SUCCESS; } else{ gsl_sf_result Ai; gsl_sf_airy_Ai_e((z-sqrt(2*n+1.))*M_SQRT2*pow(n,1/6.),0,&Ai); result->val = (GSL_IS_ODD(n)&&(x<0.)?-1.:1.)*sqrt(M_SQRT2)*pow(n,-1/12.)*Ai.val; result->err = sqrt(M_SQRT2)*pow(n,-1/12.)*Ai.err + GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } } } } double gsl_sf_hermite_func(const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_func_e(n, x, &result)); } /* Evaluates all probabilists' Hermite polynomials up to order nmax at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_prob_array(const int nmax, const double x, double * result_array) { if(nmax < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if(nmax == 0) { result_array[0] = 1.0; return GSL_SUCCESS; } else if(nmax == 1) { result_array[0] = 1.0; result_array[1] = x; return GSL_SUCCESS; } else { /* upward recurrence: He_{n+1} = x He_n - n He_{n-1} */ double p_n0 = 1.0; /* He_0(x) */ double p_n1 = x; /* He_1(x) */ double p_n = p_n1; int j=0, c=0; result_array[0] = 1.0; result_array[1] = x; for(j=1; j <= nmax-1; j++){ p_n = x*p_n1-j*p_n0; p_n0 = p_n1; p_n1 = p_n; while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){ p_n0 *= 0.5; p_n1 *= 0.5; p_n = p_n1; c++; } while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){ p_n0 *= 2.0; p_n1 *= 2.0; p_n = p_n1; c--; } result_array[j+1] = pow2(c)*p_n; } return GSL_SUCCESS; } } /* Evaluates the m-th derivative of all probabilists' Hermite polynomials up to order nmax at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_prob_array_der(const int m, const int nmax, const double x, double * result_array) { if(nmax < 0 || m < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if(m == 0) { gsl_sf_hermite_prob_array(nmax, x, result_array); return GSL_SUCCESS; } else if(nmax < m) { int j; for(j=0; j <= nmax; j++){ result_array[j] = 0.0; } return GSL_SUCCESS; } else if(nmax == m) { int j; for(j=0; j < m; j++){ result_array[j] = 0.0; } result_array[nmax] = gsl_sf_fact(m); return GSL_SUCCESS; } else if(nmax == m+1) { int j; for(j=0; j < m; j++){ result_array[j] = 0.0; } result_array[nmax-1] = gsl_sf_fact(m); result_array[nmax] = result_array[nmax-1]*(m+1)*x; return GSL_SUCCESS; } else { /* upward recurrence: He^{(m)}_{n+1} = (n+1)/(n-m+1)*(x He^{(m)}_n - n He^{(m)}_{n-1}) */ double p_n0 = gsl_sf_fact(m); /* He^{(m)}_{m}(x) */ double p_n1 = p_n0*(m+1)*x; /* He^{(m)}_{m+1}(x) */ double p_n = p_n1; int j=0, c=0; for(j=0; j < m; j++){ result_array[j] = 0.0; } result_array[m] = p_n0; result_array[m+1] = p_n1; for(j=m+1; j <= nmax-1; j++){ p_n = (x*p_n1-j*p_n0)*(j+1)/(j-m+1); p_n0 = p_n1; p_n1 = p_n; while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){ p_n0 *= 0.5; p_n1 *= 0.5; p_n = p_n1; c++; } while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){ p_n0 *= 2.0; p_n1 *= 2.0; p_n = p_n1; c--; } result_array[j+1] = pow2(c)*p_n; } return GSL_SUCCESS; } } /* Evaluates all derivatives (starting from 0) up to the mmax-th derivative of the probabilists' Hermite polynomial of order n at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_prob_der_array(const int mmax, const int n, const double x, double * result_array) { if(n < 0 || mmax < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if(n == 0) { int j; result_array[0] = 1.0; for(j=1; j <= mmax; j++){ result_array[j] = 0.0; } return GSL_SUCCESS; } else if(n == 1 && mmax > 0) { int j; result_array[0] = x; result_array[1] = 1.0; for(j=2; j <= mmax; j++){ result_array[j] = 0.0; } return GSL_SUCCESS; } else if( mmax == 0) { result_array[0] = gsl_sf_hermite_prob(n,x); return GSL_SUCCESS; } else if( mmax == 1) { result_array[0] = gsl_sf_hermite_prob(n,x); result_array[1] = n*gsl_sf_hermite_prob(n-1,x); return GSL_SUCCESS; } else { /* upward recurrence */ int k = GSL_MAX_INT(0,n-mmax); /* Getting a bit lazy here... */ double p_n0 = gsl_sf_hermite_prob(k,x); /* He_k(x) */ double p_n1 = gsl_sf_hermite_prob(k+1,x); /* He_{k+1}(x) */ double p_n = p_n1; int j=0, c=0; for(j=n+1; j <= mmax; j++){ result_array[j] = 0.0; } result_array[GSL_MIN_INT(n,mmax)] = p_n0; result_array[GSL_MIN_INT(n,mmax)-1] = p_n1; for(j=GSL_MIN_INT(mmax,n)-1; j > 0; j--){ k++; p_n = x*p_n1-k*p_n0; p_n0 = p_n1; p_n1 = p_n; while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){ p_n0 *= 0.5; p_n1 *= 0.5; p_n = p_n1; c++; } while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){ p_n0 *= 2.0; p_n1 *= 2.0; p_n = p_n1; c--; } result_array[j-1] = pow2(c)*p_n; } p_n = 1.0; for(j=1; j <= GSL_MIN_INT(n,mmax); j++){ p_n = p_n*(n-j+1); result_array[j] = p_n*result_array[j]; } return GSL_SUCCESS; } } /* Evaluates the series sum_{j=0}^n a_j*He_j(x) with He_j being the j-th probabilists' Hermite polynomial. * For improved numerical stability the Clenshaw algorithm (Clenshaw, C. W. (July 1955). "A note on the summation of Chebyshev series". Mathematical Tables and other Aids to Computation 9 (51): 118–110.) adapted to probabilists' Hermite polynomials is used. */ int gsl_sf_hermite_prob_series_e(const int n, const double x, const double * a, gsl_sf_result * result) { if(n < 0) { DOMAIN_ERROR(result); } else if(n == 0) { result->val = a[0]; result->err = 0.; return GSL_SUCCESS; } else if(n == 1) { result->val = a[0]+a[1]*x; result->err = 2.*GSL_DBL_EPSILON * (fabs(a[0]) + fabs(a[1]*x)) ; return GSL_SUCCESS; } else { /* downward recurrence: b_n = a_n + x b_{n+1} - (n+1) b_{n+2} */ double b0 = 0.; double b1 = 0.; double btmp = 0.; double e0 = 0.; double e1 = 0.; double etmp = e1; int j; for(j=n; j >= 0; j--){ btmp = b0; b0 = a[j]+x*b0-(j+1)*b1; b1 = btmp; etmp = e0; e0 = (GSL_DBL_EPSILON*fabs(a[j])+fabs(x)*e0+(j+1)*e1); e1 = etmp; } result->val = b0; result->err = e0 + fabs(b0)*GSL_DBL_EPSILON; return GSL_SUCCESS; } } double gsl_sf_hermite_prob_series(const int n, const double x, const double * a) { EVAL_RESULT(gsl_sf_hermite_prob_series_e(n, x, a, &result)); } /* Evaluates all physicists' Hermite polynomials up to order nmax at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_phys_array(const int nmax, const double x, double * result_array) { if(nmax < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if(nmax == 0) { result_array[0] = 1.0; return GSL_SUCCESS; } else if(nmax == 1) { result_array[0] = 1.0; result_array[1] = 2.0*x; return GSL_SUCCESS; } else { /* upward recurrence: H_{n+1} = 2x H_n - 2n H_{n-1} */ double p_n0 = 1.0; /* H_0(x) */ double p_n1 = 2.0*x; /* H_1(x) */ double p_n = p_n1; int j=0, c=0; result_array[0] = 1.0; result_array[1] = 2.0*x; for(j=1; j <= nmax-1; j++){ p_n = 2.0*x*p_n1-2.0*j*p_n0; p_n0 = p_n1; p_n1 = p_n; while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){ p_n0 *= 0.5; p_n1 *= 0.5; p_n = p_n1; c++; } while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){ p_n0 *= 2.0; p_n1 *= 2.0; p_n = p_n1; c--; } result_array[j+1] = pow2(c)*p_n; } return GSL_SUCCESS; } } /* Evaluates the m-th derivative of all physicists' Hermite polynomials up to order nmax at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_phys_array_der(const int m, const int nmax, const double x, double * result_array) { if(nmax < 0 || m < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if(m == 0) { gsl_sf_hermite_phys_array(nmax, x, result_array); return GSL_SUCCESS; } else if(nmax < m) { int j; for(j=0; j <= nmax; j++){ result_array[j] = 0.0; } return GSL_SUCCESS; } else if(nmax == m) { int j; for(j=0; j < m; j++){ result_array[j] = 0.0; } result_array[nmax] = pow2(m)*gsl_sf_fact(m); return GSL_SUCCESS; } else if(nmax == m+1) { int j; for(j=0; j < m; j++){ result_array[j] = 0.0; } result_array[nmax-1] = pow2(m)*gsl_sf_fact(m); result_array[nmax] = result_array[nmax-1]*2*(m+1)*x; return GSL_SUCCESS; } else { /* upward recurrence: H^{(m)}_{n+1} = 2(n+1)/(n-m+1)*(x H^{(m)}_n - n H^{(m)}_{n-1}) */ double p_n0 = pow2(m)*gsl_sf_fact(m); /* H^{(m)}_{m}(x) */ double p_n1 = p_n0*2*(m+1)*x; /* H^{(m)}_{m+1}(x) */ double p_n = p_n1; int j=0, c=0; for(j=0; j < m; j++){ result_array[j] = 0.0; } result_array[m] = p_n0; result_array[m+1] = p_n1; for(j=m+1; j <= nmax-1; j++){ p_n = (x*p_n1-j*p_n0)*2*(j+1)/(j-m+1); p_n0 = p_n1; p_n1 = p_n; while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){ p_n0 *= 0.5; p_n1 *= 0.5; p_n = p_n1; c++; } while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){ p_n0 *= 2.0; p_n1 *= 2.0; p_n = p_n1; c--; } result_array[j+1] = pow2(c)*p_n; } return GSL_SUCCESS; } } /* Evaluates all derivatives (starting from 0) up to the mmax-th derivative of the physicists' Hermite polynomial of order n at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_phys_der_array(const int mmax, const int n, const double x, double * result_array) { if(n < 0 || mmax < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if(n == 0) { int j; result_array[0] = 1.0; for(j=1; j <= mmax; j++){ result_array[j] = 0.0; } return GSL_SUCCESS; } else if(n == 1 && mmax > 0) { int j; result_array[0] = 2*x; result_array[1] = 1.0; for(j=2; j <= mmax; j++){ result_array[j] = 0.0; } return GSL_SUCCESS; } else if( mmax == 0) { result_array[0] = gsl_sf_hermite_phys(n,x); return GSL_SUCCESS; } else if( mmax == 1) { result_array[0] = gsl_sf_hermite_phys(n,x); result_array[1] = 2*n*gsl_sf_hermite_phys(n-1,x); return GSL_SUCCESS; } else { /* upward recurrence */ int k = GSL_MAX_INT(0,n-mmax); /* Getting a bit lazy here... */ double p_n0 = gsl_sf_hermite_phys(k,x); /* H_k(x) */ double p_n1 = gsl_sf_hermite_phys(k+1,x); /* H_{k+1}(x) */ double p_n = p_n1; int j=0, c=0; for(j=n+1; j <= mmax; j++){ result_array[j] = 0.0; } result_array[GSL_MIN_INT(n,mmax)] = p_n0; result_array[GSL_MIN_INT(n,mmax)-1] = p_n1; for(j=GSL_MIN_INT(mmax,n)-1; j > 0; j--){ k++; p_n = 2*x*p_n1-2*k*p_n0; p_n0 = p_n1; p_n1 = p_n; while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){ p_n0 *= 0.5; p_n1 *= 0.5; p_n = p_n1; c++; } while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){ p_n0 *= 2.0; p_n1 *= 2.0; p_n = p_n1; c--; } result_array[j-1] = pow2(c)*p_n; } p_n = 1.0; for(j=1; j <= GSL_MIN_INT(n,mmax); j++){ p_n = p_n*(n-j+1)*2; result_array[j] = p_n*result_array[j]; } return GSL_SUCCESS; } } /* Evaluates the series sum_{j=0}^n a_j*H_j(x) with H_j being the j-th physicists' Hermite polynomial. * For improved numerical stability the Clenshaw algorithm (Clenshaw, C. W. (July 1955). "A note on the summation of Chebyshev series". Mathematical Tables and other Aids to Computation 9 (51): 118–110.) adapted to physicists' Hermite polynomials is used. */ int gsl_sf_hermite_phys_series_e(const int n, const double x, const double * a, gsl_sf_result * result) { if(n < 0) { DOMAIN_ERROR(result); } else if(n == 0) { result->val = a[0]; result->err = 0.; return GSL_SUCCESS; } else if(n == 1) { result->val = a[0]+a[1]*2.*x; result->err = 2.*GSL_DBL_EPSILON * (fabs(a[0]) + fabs(a[1]*2.*x)) ; return GSL_SUCCESS; } else { /* downward recurrence: b_n = a_n + 2x b_{n+1} - 2(n+1) b_{n+2} */ double b0 = 0.; double b1 = 0.; double btmp = 0.; double e0 = 0.; double e1 = 0.; double etmp = e1; int j; for(j=n; j >= 0; j--){ btmp = b0; b0 = a[j]+2.*x*b0-2.*(j+1)*b1; b1 = btmp; etmp = e0; e0 = (GSL_DBL_EPSILON*fabs(a[j])+fabs(2.*x)*e0+2.*(j+1)*e1); e1 = etmp; } result->val = b0; result->err = e0 + fabs(b0)*GSL_DBL_EPSILON; return GSL_SUCCESS; } } double gsl_sf_hermite_phys_series(const int n, const double x, const double * a) { EVAL_RESULT(gsl_sf_hermite_phys_series_e(n, x, a, &result)); } /* Evaluates all Hermite functions up to order nmax at position x. The results are stored in result_array. * Since all polynomial orders are needed, upward recurrence is employed. */ int gsl_sf_hermite_func_array(const int nmax, const double x, double * result_array) { if(nmax < 0) { GSL_ERROR ("domain error", GSL_EDOM); } else if(nmax == 0) { result_array[0] = exp(-0.5*x*x)/sqrt(M_SQRTPI); return GSL_SUCCESS; } else if(nmax == 1) { result_array[0] = exp(-0.5*x*x)/sqrt(M_SQRTPI); result_array[1] = result_array[0]*M_SQRT2*x; return GSL_SUCCESS; } else { /* upward recurrence: Psi_{n+1} = sqrt(2/(n+1))*x Psi_n - sqrt(n/(n+1)) Psi_{n-1} */ double p_n0 = exp(-0.5*x*x)/sqrt(M_SQRTPI); /* Psi_0(x) */ double p_n1 = p_n0*M_SQRT2*x; /* Psi_1(x) */ double p_n = p_n1; int j=0, c=0; result_array[0] = p_n0; result_array[1] = p_n1; for (j=1;j<=nmax-1;j++) { p_n=(M_SQRT2*x*p_n1-sqrt(j)*p_n0)/sqrt(j+1.); p_n0=p_n1; p_n1=p_n; while(( GSL_MIN(fabs(p_n0),fabs(p_n1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) > GSL_SQRT_DBL_MAX )){ p_n0 *= 0.5; p_n1 *= 0.5; p_n = p_n1; c++; } while(( ( ( fabs(p_n0) < GSL_SQRT_DBL_MIN ) && ( p_n0 != 0) ) || ( ( fabs(p_n1) < GSL_SQRT_DBL_MIN ) && ( p_n1 != 0) ) ) && ( GSL_MAX(fabs(p_n0),fabs(p_n1)) < 0.5*GSL_SQRT_DBL_MAX )){ p_n0 *= 2.0; p_n1 *= 2.0; p_n = p_n1; c--; } result_array[j+1] = pow2(c)*p_n; } return GSL_SUCCESS; } } /* Evaluates the series sum_{j=0}^n a_j*Psi_j(x) with Psi_j being the j-th Hermite function. * For improved numerical stability the Clenshaw algorithm (Clenshaw, C. W. (July 1955). "A note on the summation of Chebyshev series". Mathematical Tables and other Aids to Computation 9 (51): 118–110.) adapted to Hermite functions is used. */ int gsl_sf_hermite_func_series_e(const int n, const double x, const double * a, gsl_sf_result * result) { if(n < 0) { DOMAIN_ERROR(result); } else if(n == 0) { result->val = a[0]*exp(-0.5*x*x)/sqrt(M_SQRTPI); result->err = GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } else if(n == 1) { result->val = (a[0]+a[1]*M_SQRT2*x)*exp(-0.5*x*x)/sqrt(M_SQRTPI); result->err = 2.*GSL_DBL_EPSILON*(fabs(a[0])+fabs(a[1]*M_SQRT2*x))*exp(-0.5*x*x)/sqrt(M_SQRTPI); return GSL_SUCCESS; } else { /* downward recurrence: b_n = a_n + sqrt(2/(n+1))*x b_{n+1} - sqrt((n+1)/(n+2)) b_{n+2} */ double b0 = 0.; double b1 = 0.; double btmp = 0.; double e0 = 0.; double e1 = 0.; double etmp = e1; int j; for(j=n; j >= 0; j--){ btmp = b0; b0 = a[j]+sqrt(2./(j+1))*x*b0-sqrt((j+1.)/(j+2.))*b1; b1 = btmp; etmp = e0; e0 = (GSL_DBL_EPSILON*fabs(a[j])+sqrt(2./(j+1))*fabs(x)*e0+sqrt((j+1.)/(j+2.))*e1); e1 = etmp; } result->val = b0*exp(-0.5*x*x)/sqrt(M_SQRTPI); result->err = e0 + fabs(result->val)*GSL_DBL_EPSILON; return GSL_SUCCESS; } } double gsl_sf_hermite_func_series(const int n, const double x, const double * a) { EVAL_RESULT(gsl_sf_hermite_func_series_e(n, x, a, &result)); } /* Evaluates the m-th derivative of the Hermite function of order n at position x. * A summation including upward recurrences is used. */ int gsl_sf_hermite_func_der_e(const int m, const int n, const double x, gsl_sf_result * result) { /* FIXME: asymptotic formula! */ if(m < 0 || n < 0) { DOMAIN_ERROR(result); } else if(m == 0){ return gsl_sf_hermite_func_e(n,x,result); } else{ int j=0, c=0; double r,er,b; double h0 = 1.; double h1 = x; double eh0 = GSL_DBL_EPSILON; double eh1 = GSL_DBL_EPSILON; double p0 = 1.; double p1 = M_SQRT2*x; double ep0 = GSL_DBL_EPSILON; double ep1 = M_SQRT2*GSL_DBL_EPSILON; double f = 1.; for (j=GSL_MAX_INT(1,n-m+1);j<=n;j++) { f *= sqrt(2.*j); } if (m>n) { f = (GSL_IS_ODD(m-n)?-f:f); for (j=0;j<GSL_MIN_INT(n,m-n);j++) { f *= (m-j)/(j+1.); } } c = 0; for (j=1;j<=m-n;j++) { b = x*h1-j*h0; h0 = h1; h1 = b; b = (fabs(x)*eh1+j*eh0); eh0 = eh1; eh1 = b; while(( GSL_MIN(fabs(h0),fabs(h1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(h0),fabs(h1)) > GSL_SQRT_DBL_MAX )){ h0 *= 0.5; h1 *= 0.5; eh0 *= 0.5; eh1 *= 0.5; c++; } while(( ( (fabs(h0) < GSL_SQRT_DBL_MIN) && (h0 != 0) ) || ( (fabs(h1) < GSL_SQRT_DBL_MIN) && (h1 != 0) ) ) && ( GSL_MAX(fabs(h0),fabs(h1)) < 0.5*GSL_SQRT_DBL_MAX )){ h0 *= 2.0; h1 *= 2.0; eh0 *= 2.0; eh1 *= 2.0; c--; } } h0 *= pow2(c); h1 *= pow2(c); eh0 *= pow2(c); eh1 *= pow2(c); b = 0.; c = 0; for (j=1;j<=n-m;j++) { b = (M_SQRT2*x*p1-sqrt(j)*p0)/sqrt(j+1.); p0 = p1; p1 = b; b = (M_SQRT2*fabs(x)*ep1+sqrt(j)*ep0)/sqrt(j+1.); ep0 = ep1; ep1 = b; while(( GSL_MIN(fabs(p0),fabs(p1)) > 2.0*GSL_SQRT_DBL_MIN ) && ( GSL_MAX(fabs(p0),fabs(p1)) > GSL_SQRT_DBL_MAX )){ p0 *= 0.5; p1 *= 0.5; ep0 *= 0.5; ep1 *= 0.5; c++; } while(( ( (fabs(p0) < GSL_SQRT_DBL_MIN) && (p0 != 0) ) || ( (fabs(p1) < GSL_SQRT_DBL_MIN) && (p1 != 0) ) ) && ( GSL_MAX(fabs(p0),fabs(p1)) < 0.5*GSL_SQRT_DBL_MAX )){ p0 = p0*2; p1 = p1*2; ep0 = ep0*2; ep1 = ep1*2; c--; } } p0 *= pow2(c); p1 *= pow2(c); ep0 *= pow2(c); ep1 *= pow2(c); c = 0; b = 0.; r = 0.; er = 0.; for (j=GSL_MAX_INT(0,m-n);j<=m;j++) { r += f*h0*p0; er += eh0*fabs(f*p0)+ep0*fabs(f*h0)+GSL_DBL_EPSILON*fabs(f*h0*p0); b = x*h1-(j+1.)*h0; h0 = h1; h1 = b; b = 0.5*(fabs(x)*eh1+(j+1.)*eh0); eh0 = eh1; eh1 = b; b = (M_SQRT2*x*p1-sqrt(n-m+j+1.)*p0)/sqrt(n-m+j+2.); p0 = p1; p1 = b; b = 0.5*(M_SQRT2*fabs(x)*ep1+sqrt(n-m+j+1.)*ep0)/sqrt(n-m+j+2.); ep0 = ep1; ep1 = b; f *= -(m-j)/(j+1.)/sqrt(n-m+j+1.)*M_SQRT1_2; while(( (fabs(h0) > 2.0*GSL_SQRT_DBL_MIN) && (fabs(h1) > 2.0*GSL_SQRT_DBL_MIN) && (fabs(p0) > 2.0*GSL_SQRT_DBL_MIN) && (fabs(p1) > 2.0*GSL_SQRT_DBL_MIN) && (fabs(r) > 4.0*GSL_SQRT_DBL_MIN) ) && ( (fabs(h0) > GSL_SQRT_DBL_MAX) || (fabs(h1) > GSL_SQRT_DBL_MAX) || (fabs(p0) > GSL_SQRT_DBL_MAX) || (fabs(p1) > GSL_SQRT_DBL_MAX) || (fabs(r) > GSL_SQRT_DBL_MAX) )){ h0 *= 0.5; h1 *= 0.5; eh0 *= 0.5; eh1 *= 0.5; p0 *= 0.5; p1 *= 0.5; ep0 *= 0.5; ep1 *= 0.5; r *= 0.25; er *= 0.25; c++; } while(( ( (fabs(h0) < GSL_SQRT_DBL_MIN) && (h0 != 0) ) || ( (fabs(h1) < GSL_SQRT_DBL_MIN) && (h1 != 0) ) || ( (fabs(p0) < GSL_SQRT_DBL_MIN) && (p0 != 0) ) || ( (fabs(p1) < GSL_SQRT_DBL_MIN) && (p1 != 0) ) || ( (fabs(r) < GSL_SQRT_DBL_MIN) && (r != 0) ) ) && ( (fabs(h0) < 0.5*GSL_SQRT_DBL_MAX) && (fabs(h1) < 0.5*GSL_SQRT_DBL_MAX) && (fabs(p0) < 0.5*GSL_SQRT_DBL_MAX) && (fabs(p1) < 0.5*GSL_SQRT_DBL_MAX) && (fabs(r) < 0.25*GSL_SQRT_DBL_MAX) )){ p0 *= 2.0; p1 *= 2.0; ep0 *= 2.0; ep1 *= 2.0; h0 *= 2.0; h1 *= 2.0; eh0 *= 2.0; eh1 *= 2.0; r *= 4.0; er *= 4.0; c--; } } r *= pow2(2*c); er *= pow2(2*c); result->val = r*exp(-0.5*x*x)/sqrt(M_SQRTPI); result->err = er*fabs(exp(-0.5*x*x)/sqrt(M_SQRTPI)) + GSL_DBL_EPSILON*fabs(result->val); return GSL_SUCCESS; } } double gsl_sf_hermite_func_der(const int m, const int n, const double x) { EVAL_RESULT(gsl_sf_hermite_func_der_e(m, n, x, &result)); } static double H_zero_init(const int n, const int k) { double p = 1., x = 1., y = 1.; if (k == 1 && n > 50) { x = (GSL_IS_ODD(n)?1./sqrt((n-1)/6.):1./sqrt(0.5*n)); } else { p = -0.7937005259840997373758528196*gsl_sf_airy_zero_Ai(n/2-k+1); x = sqrt(2*n+1.); y = pow(2*n+1.,1/6.); x = x - p/y - 0.1*p*p/(x*y*y) + (9/280. - p*p*p*11/350.)/(x*x*x) + (p*277/12600. - gsl_sf_pow_int(p,4)*823/63000.)/gsl_sf_pow_int(x,4)/y; } p = acos(x/sqrt(2*n+1.)); y = M_PI*(-2*(n/2-k)-1.5)/(n+0.5); if(gsl_fcmp(y,sin(2.*p)-2*p,GSL_SQRT_DBL_EPSILON)==0) return x; /* initial approx sufficiently accurate */ if (y > -GSL_DBL_EPSILON) return sqrt(2*n+1.); if (p < GSL_DBL_EPSILON) p = GSL_DBL_EPSILON; if (p > M_PI_2) p = M_PI_2; if (sin(2.*p)-2*p > y){ x = GSL_MAX((sin(2.*p)-2*p-y)/4.,GSL_SQRT_DBL_EPSILON); do{ x *= 2.; p += x; } while (sin(2.*p)-2*p > y); } do { x = p; p -= (sin(2.*p)-2.*p-y)/(2.*cos(2.*p)-2.); if (p<0.||p>M_PI_2) p = M_PI_2; } while (gsl_fcmp(x,p,100*GSL_DBL_EPSILON)!=0); return sqrt(2*n+1.)*cos(p); } /* lookup table for the positive zeros of the probabilists' Hermite polynomials of order 3 through 20 */ static double He_zero_tab[99] = { 1.73205080756887729352744634151, 0.741963784302725857648513596726, 2.33441421833897723931751226721, 1.35562617997426586583052129087, 2.85697001387280565416230426401, 0.616706590192594152193686099399, 1.88917587775371067550566789858, 3.32425743355211895236183546247, 1.154405394739968127239597758838, 2.36675941073454128861885646856, 3.75043971772574225630392202571, 0.539079811351375108072461918694, 1.63651904243510799922544657297, 2.80248586128754169911301080618, 4.14454718612589433206019783917, 1.023255663789132524828148225810, 2.07684797867783010652215614374, 3.20542900285646994336567590292, 4.51274586339978266756667884317, 0.484935707515497653046233483105, 1.46598909439115818325066466416, 2.48432584163895458087625118368, 3.58182348355192692277623675546, 4.85946282833231215015516494660, 0.928868997381063940144111999584, 1.87603502015484584534137013967, 2.86512316064364499771968407254, 3.93616660712997692868589612142, 5.18800122437487094818666404539, 0.444403001944138945299732445510, 1.34037519715161672153112945211, 2.25946445100079912386492979448, 3.22370982877009747166319001956, 4.27182584793228172295999293076, 5.50090170446774760081221630899, 0.856679493519450033897376121795, 1.72541837958823916151095838741, 2.62068997343221478063807762201, 3.56344438028163409162493844661, 4.59139844893652062705231872720, 5.80016725238650030586450565322, 0.412590457954601838167454145167, 1.24268895548546417895063983219, 2.08834474570194417097139675101, 2.96303657983866750254927123447, 3.88692457505976938384755016476, 4.89693639734556468372449782879, 6.08740954690129132226890147034, 0.799129068324547999424888414207, 1.60671006902872973652322479373, 2.43243682700975804116311571682, 3.28908242439876638890856229770, 4.19620771126901565957404160583, 5.19009359130478119946445431715, 6.36394788882983831771116094427, 0.386760604500557347721047189801, 1.16382910055496477419336819907, 1.95198034571633346449212362880, 2.76024504763070161684598142269, 3.60087362417154828824902745506, 4.49295530252001124266582263095, 5.47222570594934308841242925805, 6.63087819839312848022981922233, 0.751842600703896170737870774614, 1.50988330779674075905491513417, 2.28101944025298889535537879396, 3.07379717532819355851658337833, 3.90006571719800990903311840097, 4.77853158962998382710540812497, 5.74446007865940618125547815768, 6.88912243989533223256205432938, 0.365245755507697595916901619097, 1.09839551809150122773848360538, 1.83977992150864548966395498992, 2.59583368891124032910545091458, 3.37473653577809099529779309480, 4.18802023162940370448450911428, 5.05407268544273984538327527397, 6.00774591135959752029303858752, 7.13946484914647887560975631213, 0.712085044042379940413609979021, 1.42887667607837287134157901452, 2.15550276131693514033871248449, 2.89805127651575312007902775275, 3.66441654745063847665304033851, 4.46587262683103133615452574019, 5.32053637733603803162823765939, 6.26289115651325170419416064557, 7.38257902403043186766326977122, 0.346964157081355927973322447164, 1.04294534880275103146136681143, 1.74524732081412671493067861704, 2.45866361117236775131735057433, 3.18901481655338941485371744116, 3.94396735065731626033176813604, 4.73458133404605534390170946748, 5.57873880589320115268040332802, 6.51059015701365448636289263918, 7.61904854167975829138128156060 }; /* Computes the s-th zero the probabilists' Hermite polynomial of order n. A Newton iteration using a continued fraction representation adapted from [E.T. Whittaker (1914), On the continued fractions which represent the functions of Hermite and other functions defined by differential equations, Proceedings of the Edinburgh Mathematical Society, 32, 65-74] is performed with the initial approximation from [Arpad Elbert and Martin E. Muldoon, Approximations for zeros of Hermite functions, pp. 117-126 in D. Dominici and R. S. Maier, eds, "Special Functions and Orthogonal Polynomials", Contemporary Mathematics, vol 471 (2008)] refined via the bisection method. */ int gsl_sf_hermite_prob_zero_e(const int n, const int s, gsl_sf_result * result) { if(n <= 0 || s < 0 || s > n/2) { DOMAIN_ERROR(result); } else if(s == 0) { if (GSL_IS_ODD(n) == 1) { result->val = 0.; result->err = 0.; return GSL_SUCCESS; } else { DOMAIN_ERROR(result); } } else if(n == 2) { result->val = 1.; result->err = 0.; return GSL_SUCCESS; } else if(n < 21) { result->val = He_zero_tab[(GSL_IS_ODD(n)?n/2:0)+((n/2)*(n/2-1))+s-2]; result->err = GSL_DBL_EPSILON*(result->val); return GSL_SUCCESS; } else { double d = 1., x = 1., x0 = 1.; int j; x = H_zero_init(n,s) * M_SQRT2; do { x0 = x; d = 0.; for (j=1; j<n; j++) d = j/(x-d); x -= (x-d)/n; /* gsl_fcmp can be used since the smallest zero approaches 1/sqrt(n) or 1/sqrt((n-1)/3.) for large n and thus all zeros are non-zero (except for the trivial case handled above) */ } while (gsl_fcmp(x,x0,10*GSL_DBL_EPSILON)!=0); result->val = x; result->err = 2*GSL_DBL_EPSILON*x + fabs(x-x0); return GSL_SUCCESS; } } double gsl_sf_hermite_prob_zero(const int n, const int s) { EVAL_RESULT(gsl_sf_hermite_prob_zero_e(n, s, &result)); } /* lookup table for the positive zeros of the physicists' Hermite polynomials of order 3 through 20 */ static double H_zero_tab[99] = { 1.22474487139158904909864203735, 0.524647623275290317884060253835, 1.65068012388578455588334111112, 0.958572464613818507112770593893, 2.02018287045608563292872408814, 0.436077411927616508679215948251, 1.335849074013696949714895282970, 2.35060497367449222283392198706, 0.816287882858964663038710959027, 1.67355162876747144503180139830, 2.65196135683523349244708200652, 0.381186990207322116854718885584, 1.157193712446780194720765779063, 1.98165675669584292585463063977, 2.93063742025724401922350270524, 0.723551018752837573322639864579, 1.46855328921666793166701573925, 2.26658058453184311180209693284, 3.19099320178152760723004779538, 0.342901327223704608789165025557, 1.03661082978951365417749191676, 1.75668364929988177345140122011, 2.53273167423278979640896079775, 3.43615911883773760332672549432, 0.656809566882099765024611575383, 1.32655708449493285594973473558, 2.02594801582575533516591283121, 2.78329009978165177083671870152, 3.66847084655958251845837146485, 0.314240376254359111276611634095, 0.947788391240163743704578131060, 1.59768263515260479670966277090, 2.27950708050105990018772856942, 3.02063702512088977171067937518, 3.88972489786978191927164274724, 0.605763879171060113080537108602, 1.22005503659074842622205526637, 1.85310765160151214200350644316, 2.51973568567823788343040913628, 3.24660897837240998812205115236, 4.10133759617863964117891508007, 0.291745510672562078446113075799, 0.878713787329399416114679311861, 1.47668273114114087058350654421, 2.09518325850771681573497272630, 2.74847072498540256862499852415, 3.46265693360227055020891736115, 4.30444857047363181262129810037, 0.565069583255575748526020337198, 1.13611558521092066631913490556, 1.71999257518648893241583152515, 2.32573248617385774545404479449, 2.96716692790560324848896036355, 3.66995037340445253472922383312, 4.49999070730939155366438053053, 0.273481046138152452158280401965, 0.822951449144655892582454496734, 1.38025853919888079637208966969, 1.95178799091625397743465541496, 2.54620215784748136215932870545, 3.17699916197995602681399455926, 3.86944790486012269871942409801, 4.68873893930581836468849864875, 0.531633001342654731349086553718, 1.06764872574345055363045773799, 1.61292431422123133311288254454, 2.17350282666662081927537907149, 2.75776291570388873092640349574, 3.37893209114149408338327069289, 4.06194667587547430689245559698, 4.87134519367440308834927655662, 0.258267750519096759258116098711, 0.776682919267411661316659462284, 1.30092085838961736566626555439, 1.83553160426162889225383944409, 2.38629908916668600026459301424, 2.96137750553160684477863254906, 3.57376906848626607950067599377, 4.24811787356812646302342016090, 5.04836400887446676837203757885, 0.503520163423888209373811765050, 1.01036838713431135136859873726, 1.52417061939353303183354859367, 2.04923170985061937575050838669, 2.59113378979454256492128084112, 3.15784881834760228184318034120, 3.76218735196402009751489394104, 4.42853280660377943723498532226, 5.22027169053748216460967142500, 0.245340708300901249903836530634, 0.737473728545394358705605144252, 1.23407621539532300788581834696, 1.73853771211658620678086566214, 2.25497400208927552308233334473, 2.78880605842813048052503375640, 3.34785456738321632691492452300, 3.94476404011562521037562880052, 4.60368244955074427307767524898, 5.38748089001123286201690041068 }; /* Computes the s-th zero the physicists' Hermite polynomial of order n, thus also the s-th zero of the Hermite function of order n. A Newton iteration using a continued fraction representation adapted from [E.T. Whittaker (1914), On the continued fractions which represent the functions of Hermite and other functions defined by differential equations, Proceedings of the Edinburgh Mathematical Society, 32, 65-74] is performed with the initial approximation from [Arpad Elbert and Martin E. Muldoon, Approximations for zeros of Hermite functions, pp. 117-126 in D. Dominici and R. S. Maier, eds, "Special Functions and Orthogonal Polynomials", Contemporary Mathematics, vol 471 (2008)] refined via the bisection method. */ int gsl_sf_hermite_phys_zero_e(const int n, const int s, gsl_sf_result * result) { if(n <= 0 || s < 0 || s > n/2) { DOMAIN_ERROR(result); } else if(s == 0) { if (GSL_IS_ODD(n) == 1) { result->val = 0.; result->err = 0.; return GSL_SUCCESS; } else { DOMAIN_ERROR(result); } } else if(n == 2) { result->val = M_SQRT1_2; result->err = 0.; return GSL_SUCCESS; } else if(n < 21) { result->val = H_zero_tab[(GSL_IS_ODD(n)?n/2:0)+((n/2)*(n/2-1))+s-2]; result->err = GSL_DBL_EPSILON*(result->val); return GSL_SUCCESS; } else { double d = 1., x = 1., x0 = 1.; int j; x = H_zero_init(n,s); do { x0 = x; d = 0.; for (j=1; j<n; j++) d = 2*j/(2.*x-d); x -= (2*x-d)*0.5/n; /* gsl_fcmp can be used since the smallest zero approaches 1/sqrt(n) or 1/sqrt((n-1)/3.) for large n and thus all zeros are non-zero (except for the trivial case handled above) */ } while (gsl_fcmp(x,x0,10*GSL_DBL_EPSILON)!=0); result->val = x; result->err = 2*GSL_DBL_EPSILON*x + fabs(x-x0); return GSL_SUCCESS; } } double gsl_sf_hermite_phys_zero(const int n, const int s) { EVAL_RESULT(gsl_sf_hermite_phys_zero_e(n, s, &result)); } int gsl_sf_hermite_func_zero_e(const int n, const int s, gsl_sf_result * result) { return gsl_sf_hermite_phys_zero_e(n, s, result); } double gsl_sf_hermite_func_zero(const int n, const int s) { EVAL_RESULT(gsl_sf_hermite_func_zero_e(n, s, &result)); }
{ "alphanum_fraction": 0.6215843641, "avg_line_length": 29.5837988827, "ext": "c", "hexsha": "cbf5503b7bf5aca6d45a7e24ffd32318cd7d2b75", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/hermite.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/hermite.c", "max_line_length": 591, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/specfunc/hermite.c", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "num_tokens": 20301, "size": 52955 }
#ifndef PROTO_H_ #define PROTO_H_ #define _DEFAULT_SOURCE 1 /** PROTO SETTINGS **/ #define PRECISION 2 #define MAX_LINE_LENGTH 9046 #define USE_CBLAS #define USE_LAPACK /* #define USE_CERES */ #define USE_STB_IMAGE #define WARN_UNUSED __attribute__((warn_unused_result)) #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <math.h> #include <time.h> #include <unistd.h> #include <dirent.h> #include <assert.h> #include <sys/time.h> #include <errno.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/poll.h> #ifdef USE_CBLAS #include <cblas.h> #endif #ifdef USE_LAPACK #include <lapacke.h> #endif #ifdef USE_CERES #include <ceres/c_api.h> #endif /****************************************************************************** * MACROS ******************************************************************************/ /** * Mark variable unused. * @param[in] expr Variable to mark as unused */ #define UNUSED(expr) \ do { \ (void) (expr); \ } while (0) /** * Check if condition is satisfied. * * If the condition is not satisfied a message M will be logged and a goto * error is called. * * @param[in] A Condition to be checked * @param[in] M Error message * @param[in] ... Varadic arguments for error message */ #define CHECK(A, M, ...) \ if (!(A)) { \ LOG_ERROR(M, ##__VA_ARGS__); \ goto error; \ } /****************************************************************************** * LOGGING ******************************************************************************/ /** Terminal ANSI colors */ #define KRED "\x1B[1;31m" #define KGRN "\x1B[1;32m" #define KYEL "\x1B[1;33m" #define KBLU "\x1B[1;34m" #define KMAG "\x1B[1;35m" #define KCYN "\x1B[1;36m" #define KWHT "\x1B[1;37m" #define KNRM "\x1B[1;0m" /** Macro function that returns the caller's filename */ #define __FILENAME__ \ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) /** * Debug * @param[in] M Message * @param[in] ... Varadic arguments */ #ifdef NDEBUG #define DEBUG(M, ...) #else #define DEBUG(M, ...) fprintf(stdout, "[DEBUG] " M "\n", ##__VA_ARGS__) #endif /** * Log info * @param[in] M Message * @param[in] ... Varadic arguments */ #define LOG_INFO(M, ...) \ fprintf(stderr, \ "[INFO] [%s:%d] " M "\n", \ __FILENAME__, \ __LINE__, \ ##__VA_ARGS__) /** * Log error * @param[in] M Message * @param[in] ... Varadic arguments */ #define LOG_ERROR(M, ...) \ fprintf(stderr, \ KRED "[ERROR] [%s:%d] " M KNRM "\n", \ __FILENAME__, \ __LINE__, \ ##__VA_ARGS__) /** * Log warn * @param[in] M Message * @param[in] ... Varadic arguments */ #define LOG_WARN(M, ...) \ fprintf(stderr, \ KYEL "[WARN] [%s:%d] " M KNRM "\n", \ __FILENAME__, \ __LINE__, \ ##__VA_ARGS__) /** * Fatal * * @param[in] M Message * @param[in] ... Varadic arguments */ #define FATAL(M, ...) \ fprintf(stdout, \ KRED "[FATAL] [%s:%d] " M KNRM "\n", \ __FILENAME__, \ __LINE__, \ ##__VA_ARGS__); \ exit(-1) /****************************************************************************** * FILESYSTEM ******************************************************************************/ void path_file_name(const char *path, char *fname); void path_file_ext(const char *path, char *fext); void path_dir_name(const char *path, char *dir_name); char *path_join(const char *x, const char *y); char **list_files(const char *path, int *nb_files); void list_files_free(char **data, const int n); char *file_read(const char *fp); void skip_line(FILE *fp); int file_exists(const char *fp); int file_rows(const char *fp); int file_copy(const char *src, const char *dest); /****************************************************************************** * DATA ******************************************************************************/ #if PRECISION == 1 typedef float real_t; #elif PRECISION == 2 typedef double real_t; #else #error "Precision not defined!" #endif size_t string_copy(char *dst, const char *src); void string_cat(char *dst, const char *src); char *string_malloc(const char *s); int **load_iarrays(const char *csv_path, int *nb_arrays); real_t **load_darrays(const char *csv_path, int *nb_arrays); int dsv_rows(const char *fp); int dsv_cols(const char *fp, const char delim); char **dsv_fields(const char *fp, const char delim, int *nb_fields); real_t **dsv_data(const char *fp, const char delim, int *nb_rows, int *nb_cols); void dsv_free(real_t **data, const int nb_rows); real_t **csv_data(const char *fp, int *nb_rows, int *nb_cols); void csv_free(real_t **data, const int nb_rows); /* real_t *load_matrix(const char *file_path); */ /* real_t *load_vector(const char *file_path); */ /****************************************************************************** * TIME ******************************************************************************/ /** Timestamp Type */ typedef uint64_t timestamp_t; struct timespec tic(); float toc(struct timespec *tic); float mtoc(struct timespec *tic); timestamp_t time_now(); real_t ts2sec(const timestamp_t ts); timestamp_t sec2ts(const real_t time_s); /****************************************************************************** * NETWORK ******************************************************************************/ /** * TCP server */ typedef struct tcp_server_t { int port; int sockfd; int conn; void *(*conn_handler)(void *); } tcp_server_t; /** * TCP client */ typedef struct tcp_client_t { char server_ip[1024]; int server_port; int sockfd; int (*loop_cb)(struct tcp_client_t *); } tcp_client_t; int ip_port_info(const int sockfd, char *ip, int *port); int tcp_server_setup(tcp_server_t *server, const int port); int tcp_server_loop(tcp_server_t *server); int tcp_client_setup(tcp_client_t *client, const char *server_ip, const int server_port); int tcp_client_loop(tcp_client_t *client); /****************************************************************************** * MATHS ******************************************************************************/ /** Mathematical Pi constant (i.e. 3.1415..) */ #ifndef M_PI #define M_PI (3.14159265358979323846) #endif /** Real number comparison tolerance */ #ifndef CMP_TOL #define CMP_TOL 1e-6 #endif /** Min of two numbers, X or Y. */ #define MIN(x, y) ((x) < (y) ? (x) : (y)) /** Max of two numbers, X or Y. */ #define MAX(x, y) ((x) > (y) ? (x) : (y)) /** Based on sign of b, return +ve or -ve a. */ #define SIGN2(a, b) ((b) >= 0.0 ? fabs(a) : -fabs(a)) float randf(float a, float b); real_t deg2rad(const real_t d); real_t rad2deg(const real_t r); int fltcmp(const real_t x, const real_t y); int fltcmp2(const void *x, const void *y); real_t pythag(const real_t a, const real_t b); real_t lerp(const real_t a, const real_t b, const real_t t); void lerp3(const real_t a[3], const real_t b[3], const real_t t, real_t x[3]); real_t sinc(const real_t x); real_t mean(const real_t *x, const size_t length); real_t median(const real_t *x, const size_t length); real_t var(const real_t *x, const size_t length); real_t stddev(const real_t *x, const size_t length); /****************************************************************************** * LINEAR ALGEBRA ******************************************************************************/ void print_matrix(const char *prefix, const real_t *A, const size_t m, const size_t n); void print_vector(const char *prefix, const real_t *v, const size_t n); void eye(real_t *A, const size_t m, const size_t n); void ones(real_t *A, const size_t m, const size_t n); void zeros(real_t *A, const size_t m, const size_t n); real_t *mat_malloc(const size_t m, const size_t n); int mat_cmp(const real_t *A, const real_t *B, const size_t m, const size_t n); int mat_equals(const real_t *A, const real_t *B, const size_t m, const size_t n, const real_t tol); int mat_save(const char *save_path, const real_t *A, const int m, const int n); real_t *mat_load(const char *save_path, int *nb_rows, int *nb_cols); void mat_set(real_t *A, const size_t stride, const size_t i, const size_t j, const real_t val); real_t mat_val(const real_t *A, const size_t stride, const size_t i, const size_t j); void mat_copy(const real_t *src, const int m, const int n, real_t *dest); void mat_row_set(real_t *A, const size_t stride, const int row_idx, const real_t *x); void mat_col_set(real_t *A, const size_t stride, const int nb_rows, const int col_idx, const real_t *x); void mat_block_get(const real_t *A, const size_t stride, const size_t rs, const size_t cs, const size_t re, const size_t ce, real_t *block); void mat_block_set(real_t *A, const size_t stride, const size_t rs, const size_t cs, const size_t re, const size_t ce, const real_t *block); void mat_diag_get(const real_t *A, const int m, const int n, real_t *d); void mat_diag_set(real_t *A, const int m, const int n, const real_t *d); void mat_triu(const real_t *A, const size_t n, real_t *U); void mat_tril(const real_t *A, const size_t n, real_t *L); real_t mat_trace(const real_t *A, const size_t m, const size_t n); void mat_transpose(const real_t *A, size_t m, size_t n, real_t *A_t); void mat_add(const real_t *A, const real_t *B, real_t *C, size_t m, size_t n); void mat_sub(const real_t *A, const real_t *B, real_t *C, size_t m, size_t n); void mat_scale(real_t *A, const size_t m, const size_t n, const real_t scale); real_t *vec_malloc(const size_t n); void vec_copy(const real_t *src, const size_t n, real_t *dest); int vec_equals(const real_t *x, const real_t *y, const size_t n); void vec_add(const real_t *x, const real_t *y, real_t *z, size_t n); void vec_sub(const real_t *x, const real_t *y, real_t *z, size_t n); void vec_scale(real_t *x, const size_t n, const real_t scale); real_t vec_norm(const real_t *x, const size_t n); void vec_normalize(real_t *x, const size_t n); void dot(const real_t *A, const size_t A_m, const size_t A_n, const real_t *B, const size_t B_m, const size_t B_n, real_t *C); void skew(const real_t x[3], real_t A[3 * 3]); void skew_inv(const real_t A[3 * 3], real_t x[3]); void fwdsubs(const real_t *L, const real_t *b, real_t *y, const size_t n); void bwdsubs(const real_t *U, const real_t *y, real_t *x, const size_t n); int check_jacobian(const char *jac_name, const real_t *fdiff, const real_t *jac, const size_t m, const size_t n, const real_t tol, const int verbose); #ifdef USE_CBLAS void cblas_dot(const real_t *A, const size_t A_m, const size_t A_n, const real_t *B, const size_t B_m, const size_t B_n, real_t *C); #endif /****************************************************************************** * SVD ******************************************************************************/ int svd(real_t *A, const int m, const int n, real_t *w, real_t *V); #ifdef USE_LAPACK void lapack_svd(real_t *A, int m, int n, real_t **S, real_t **U, real_t **V_t); #endif /****************************************************************************** * CHOL ******************************************************************************/ void chol(const real_t *A, const size_t n, real_t *L); void chol_solve(const real_t *A, const real_t *b, real_t *x, const size_t n); #ifdef USE_LAPACK void lapack_chol_solve(const real_t *A, const real_t *b, real_t *x, const size_t n); #endif /****************************************************************************** * TRANSFORMS ******************************************************************************/ void tf(const real_t params[7], real_t T[4 * 4]); void tf_vector(const real_t T[4 * 4], real_t params[7]); void tf_decompose(const real_t T[4 * 4], real_t C[3 * 3], real_t r[3]); void tf_rot_set(real_t T[4 * 4], const real_t C[3 * 3]); void tf_rot_get(const real_t T[4 * 4], real_t C[3 * 3]); void tf_quat_set(real_t T[4 * 4], const real_t q[4]); void tf_quat_get(const real_t T[4 * 4], real_t q[4]); void tf_euler_set(real_t T[4 * 4], const real_t ypr[3]); void tf_euler_get(const real_t T[4 * 4], real_t ypr[3]); void tf_trans_set(real_t T[4 * 4], const real_t r[3]); void tf_trans_get(const real_t T[4 * 4], real_t r[3]); void tf_inv(const real_t T[4 * 4], real_t T_inv[4 * 4]); void tf_point(const real_t T[4 * 4], const real_t p[3], real_t retval[3]); void tf_hpoint(const real_t T[4 * 4], const real_t p[4], real_t retval[4]); void tf_perturb_rot(real_t T[4 * 4], const real_t step_size, const int i); void tf_perturb_trans(real_t T[4 * 4], const real_t step_size, const int i); void print_pose_vector(const char *prefix, const real_t pose[7]); void rvec2rot(const real_t *rvec, const real_t eps, real_t *R); void euler321(const real_t ypr[3], real_t C[3 * 3]); void euler2quat(const real_t ypr[3], real_t q[4]); void rot2quat(const real_t C[3 * 3], real_t q[4]); void rot2euler(const real_t C[3 * 3], real_t ypr[3]); void quat2euler(const real_t q[4], real_t ypr[3]); void quat2rot(const real_t q[4], real_t C[3 * 3]); real_t quat_norm(const real_t q[4]); void quat_normalize(real_t q[4]); void quat_inv(const real_t q[4], real_t q_inv[4]); void quat_left(const real_t q[4], real_t left[4 * 4]); void quat_right(const real_t q[4], real_t right[4 * 4]); void quat_lmul(const real_t p[4], const real_t q[4], real_t r[4]); void quat_rmul(const real_t p[4], const real_t q[4], real_t r[4]); void quat_mul(const real_t p[4], const real_t q[4], real_t r[4]); void quat_delta(const real_t dalpha[3], real_t dq[4]); void quat_perturb(real_t q[4], const int i, const real_t h); /****************************************************************************** * Lie ******************************************************************************/ void lie_Exp(const real_t phi[3], real_t C[3 * 3]); void lie_Log(const real_t C[3 * 3], real_t rvec[3]); /****************************************************************************** * CV ******************************************************************************/ // IMAGE /////////////////////////////////////////////////////////////////////// typedef struct image_t { int width; int height; int channels; uint8_t *data; } image_t; void image_setup(image_t *img, const int width, const int height, uint8_t *data); image_t *image_load(const char *file_path); void image_print_properties(const image_t *img); void image_free(image_t *img); // GEOMETRY //////////////////////////////////////////////////////////////////// void linear_triangulation(const real_t P_i[3 * 4], const real_t P_j[3 * 4], const real_t z_i[2], const real_t z_j[2], real_t p[3]); // RADTAN ////////////////////////////////////////////////////////////////////// void radtan4_distort(const real_t params[4], const real_t p[2], real_t p_d[2]); void radtan4_point_jacobian(const real_t params[4], const real_t p[2], real_t J_point[2 * 2]); void radtan4_params_jacobian(const real_t params[4], const real_t p[2], real_t J_param[2 * 4]); // EQUI //////////////////////////////////////////////////////////////////////// void equi4_distort(const real_t params[4], const real_t p[2], real_t p_d[2]); void equi4_point_jacobian(const real_t params[4], const real_t p[2], real_t J_point[2 * 2]); void equi4_params_jacobian(const real_t params[4], const real_t p[2], real_t J_param[2 * 4]); // PINHOLE ///////////////////////////////////////////////////////////////////// real_t pinhole_focal(const int image_width, const real_t fov); void pinhole_K(const real_t params[4], real_t K[3 * 3]); void pinhole_projection_matrix(const real_t params[4], const real_t T[4 * 4], real_t P[3 * 4]); void pinhole_project(const real_t params[4], const real_t p_C[3], real_t z[2]); void pinhole_point_jacobian(const real_t params[4], real_t J_point[2 * 2]); void pinhole_params_jacobian(const real_t params[4], const real_t x[2], real_t J[2 * 4]); // PINHOLE-RADTAN4 ///////////////////////////////////////////////////////////// void pinhole_radtan4_project(const real_t params[8], const real_t p_C[3], real_t x[2]); void pinhole_radtan4_project_jacobian(const real_t params[8], const real_t p_C[3], real_t J[2 * 3]); void pinhole_radtan4_params_jacobian(const real_t params[8], const real_t p_C[3], real_t J[2 * 8]); // PINHOLE-EQUI4 /////////////////////////////////////////////////////////////// void pinhole_equi4_project(const real_t params[8], const real_t p_C[3], real_t x[2]); void pinhole_equi4_project_jacobian(const real_t params[8], const real_t p_C[3], real_t J[2 * 3]); void pinhole_equi4_params_jacobian(const real_t params[8], const real_t p_C[3], real_t J[2 * 8]); /****************************************************************************** * SENSOR FUSION ******************************************************************************/ #define POSE_PARAM 1 #define SB_PARAM 2 #define FEATURE_PARAM 3 #define EXTRINSICS_PARAM 4 #define CAM_PARAM 5 // POSE //////////////////////////////////////////////////////////////////////// typedef struct pose_t { timestamp_t ts; real_t pos[3]; real_t quat[4]; } pose_t; void pose_setup(pose_t *pose, const timestamp_t ts, const real_t *param); void pose_print(const char *prefix, const pose_t *pose); // SPEED AND BIASES //////////////////////////////////////////////////////////// typedef struct speed_biases_t { timestamp_t ts; real_t data[9]; } speed_biases_t; void speed_biases_setup(speed_biases_t *sb, const timestamp_t ts, const real_t *param); void speed_biases_print(const speed_biases_t *sb); // FEATURE ///////////////////////////////////////////////////////////////////// #define MAX_FEATURES 10000 typedef struct feature_t { real_t data[3]; } feature_t; void feature_setup(feature_t *p, const real_t *param); void feature_print(const feature_t *feature); typedef struct features_t { feature_t data[MAX_FEATURES]; int nb_features; int status[MAX_FEATURES]; } features_t; void features_setup(features_t *features); int features_exists(const features_t *features, const int feature_id); feature_t *features_get(features_t *features, const int feature_id); feature_t *features_add(features_t *features, const int feature_id, const real_t *param); void features_remove(features_t *features, const int feature_id); // EXTRINSICS ////////////////////////////////////////////////////////////////// typedef struct extrinsics_t { real_t pos[3]; real_t quat[4]; } extrinsics_t; void extrinsics_setup(extrinsics_t *extrinsics, const real_t *param); void extrinsics_print(const char *prefix, const extrinsics_t *exts); // CAMERA PARAMS /////////////////////////////////////////////////////////////// typedef struct camera_params_t { int cam_idx; int resolution[2]; char proj_model[20]; char dist_model[20]; real_t data[8]; } camera_params_t; void camera_params_setup(camera_params_t *camera, const int cam_idx, const int cam_res[2], const char *proj_model, const char *dist_model, const real_t *data); void camera_params_print(const camera_params_t *camera); // POSE FACTOR ///////////////////////////////////////////////////////////////// typedef struct pose_factor_t { real_t pos_meas[3]; real_t quat_meas[4]; pose_t *pose_est; int nb_params; real_t covar[6 * 6]; real_t sqrt_info[6 * 6]; } pose_factor_t; void pose_factor_setup(pose_factor_t *factor, pose_t *pose, const real_t var[6]); int pose_factor_eval(pose_factor_t *factor, real_t **params, real_t *residuals, real_t **jacobians); int pose_factor_ceres_eval(void *factor, double **params, double *residuals, double **jacobians); // BA FACTOR /////////////////////////////////////////////////////////////////// typedef struct ba_factor_t { const pose_t *pose; const camera_params_t *camera; const feature_t *feature; int nb_params; real_t covar[2 * 2]; real_t sqrt_info[2 * 2]; real_t z[2]; } ba_factor_t; void ba_factor_setup(ba_factor_t *factor, const pose_t *pose, const feature_t *feature, const camera_params_t *camera, const real_t z[2], const real_t var[2]); int ba_factor_eval(ba_factor_t *factor, real_t **params, real_t *residuals, real_t **jacobians); int ba_factor_ceres_eval(void *factor, double **params, double *residuals, double **jacobians); // CAMERA FACTOR /////////////////////////////////////////////////////////////// typedef struct cam_factor_t { const pose_t *pose; const extrinsics_t *extrinsics; const camera_params_t *camera; const feature_t *feature; int nb_params; real_t covar[2 * 2]; real_t sqrt_info[2 * 2]; real_t z[2]; } cam_factor_t; void cam_factor_setup(cam_factor_t *factor, const pose_t *pose, const extrinsics_t *extrinsics, const feature_t *feature, const camera_params_t *camera, const real_t z[2], const real_t var[2]); int cam_factor_eval(cam_factor_t *factor, real_t **params, real_t *residuals, real_t **jacobians); int cam_factor_ceres_eval(void *factor, double **params, double *residuals, double **jacobians); // IMU FACTOR ////////////////////////////////////////////////////////////////// #define MAX_IMU_BUF_SIZE 10000 typedef struct imu_params_t { uint64_t param_id; int imu_idx; real_t rate; real_t n_aw; real_t n_gw; real_t n_a; real_t n_g; real_t g; } imu_params_t; typedef struct imu_buf_t { timestamp_t ts[MAX_IMU_BUF_SIZE]; real_t acc[MAX_IMU_BUF_SIZE][3]; real_t gyr[MAX_IMU_BUF_SIZE][3]; int size; } imu_buf_t; typedef struct imu_factor_t { imu_params_t *imu_params; imu_buf_t imu_buf; pose_t *pose_i; pose_t *pose_j; speed_biases_t *sb_i; speed_biases_t *sb_j; real_t covar[15 * 15]; real_t r[15]; int r_size; real_t J0[2 * 6]; /* Jacobian w.r.t pose i */ real_t J1[2 * 9]; /* Jacobian w.r.t speed and biases i */ real_t J2[2 * 6]; /* Jacobian w.r.t pose j */ real_t J3[2 * 9]; /* Jacobian w.r.t speed and biases j */ real_t *jacs[4]; int nb_params; /* Preintegration variables */ real_t Dt; real_t F[15 * 15]; /* State jacobian */ real_t P[15 * 15]; /* State covariance */ real_t Q[15 * 15]; /* Noise matrix */ real_t dr[3]; /* Relative position */ real_t dv[3]; /* Relative velocity */ real_t dC[3 * 3]; /* Relative rotation */ real_t ba[3]; /* Accel biase */ real_t bg[3]; /* Gyro biase */ } imu_factor_t; void imu_buf_setup(imu_buf_t *imu_buf); void imu_buf_add(imu_buf_t *imu_buf, const timestamp_t ts, const real_t acc[3], const real_t gyr[3]); void imu_buf_clear(imu_buf_t *imu_buf); void imu_buf_copy(const imu_buf_t *from, imu_buf_t *to); void imu_buf_print(const imu_buf_t *imu_buf); /* void imu_factor_setup(imu_factor_t *factor, */ /* imu_params_t *imu_params, */ /* imu_buf_t *imu_buf, */ /* pose_t *pose_i, */ /* speed_biases_t *sb_i, */ /* pose_t *pose_j, */ /* speed_biases_t *sb_j); */ void imu_factor_reset(imu_factor_t *factor); // GRAPH /////////////////////////////////////////////////////////////////////// #define MAX_NB_FACTORS 1000 #define POSE_FACTOR 1 #define BA_FACTOR 2 #define CAM_FACTOR 3 #define IMU_FACTOR 4 typedef struct keyframe_t { cam_factor_t *cam_factors; int nb_cam_factors; imu_factor_t *imu_factors; int nb_imu_factors; pose_t *pose; } keyframe_t; typedef struct graph_t { void *factors[MAX_NB_FACTORS]; int nb_factors; int *factor_types; pose_t **poses; int nb_poses; const extrinsics_t *extrinsics; int nb_exts; camera_params_t **cam_params; int nb_cams; feature_t **features; int nb_features; real_t *H; real_t *g; real_t *x; int x_size; int r_size; } graph_t; void graph_setup(graph_t *graph); void graph_print(graph_t *graph); int graph_add_factor(graph_t *graph, void *factor, int factor_type); int graph_eval(graph_t *graph); void graph_optimize(graph_t *graph); /****************************************************************************** * DATASET ******************************************************************************/ pose_t *load_poses(const char *fp, int *nb_poses); int **assoc_pose_data(pose_t *gnd_poses, size_t nb_gnd_poses, pose_t *est_poses, size_t nb_est_poses, double threshold, size_t *nb_matches); /****************************************************************************** * SIM ******************************************************************************/ // SIM FEATURES //////////////////////////////////////////////////////////////// typedef struct sim_features_t { real_t **features; int nb_features; } sim_features_t; sim_features_t *load_sim_features(const char *csv_path); void free_sim_features(sim_features_t *features_data); // SIM IMU DATA //////////////////////////////////////////////////////////////// typedef struct sim_imu_data_t { real_t **data; int nb_measurements; } sim_imu_data_t; sim_imu_data_t *load_sim_imu_data(const char *csv_path); void free_sim_imu_data(sim_imu_data_t *imu_data); // SIM CAM DATA //////////////////////////////////////////////////////////////// typedef struct sim_cam_frame_t { timestamp_t ts; int *feature_ids; real_t **keypoints; int nb_measurements; } sim_cam_frame_t; typedef struct sim_cam_data_t { sim_cam_frame_t **frames; int nb_frames; timestamp_t *ts; real_t **poses; } sim_cam_data_t; sim_cam_frame_t *load_sim_cam_frame(const char *csv_path); void print_sim_cam_frame(sim_cam_frame_t *frame_data); void free_sim_cam_frame(sim_cam_frame_t *frame_data); sim_cam_data_t *load_sim_cam_data(const char *dir_path); void free_sim_cam_data(sim_cam_data_t *cam_data); #endif // _PROTO_H_
{ "alphanum_fraction": 0.5126150982, "avg_line_length": 33.5373467113, "ext": "h", "hexsha": "14c1e0646e48bf1d12cdd9ca84afc9dbc3fcd8b4", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-10-22T03:19:44.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-12T05:10:24.000Z", "max_forks_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "daoran/proto", "max_forks_repo_path": "proto/lib/proto.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_issues_repo_issues_event_max_datetime": "2021-12-21T01:10:10.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-21T01:08:52.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "daoran/proto", "max_issues_repo_path": "proto/lib/proto.h", "max_line_length": 80, "max_stars_count": 15, "max_stars_repo_head_hexsha": "c0f7bfc3acceac7872dfe9b510e2713f3e5efd90", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "daoran/proto", "max_stars_repo_path": "proto/lib/proto.h", "max_stars_repo_stars_event_max_datetime": "2021-12-20T12:25:04.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-27T21:37:47.000Z", "num_tokens": 6780, "size": 30083 }
/* randist/flat.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* This is the uniform distribution in the range [a, b) p(x) dx = 1/(b-a) dx if a <= x < b ..... = 0 otherwise */ double gsl_ran_flat (const gsl_rng * r, const double a, const double b) { double u = gsl_rng_uniform (r); /* A uniform distribution over [a,b) */ return a * (1 - u) + b * u; } double gsl_ran_flat_pdf (double x, const double a, const double b) { if (x < b && x >= a) { return 1 / (b - a); } else { return 0; } }
{ "alphanum_fraction": 0.6603107345, "avg_line_length": 26.2222222222, "ext": "c", "hexsha": "d81d41492e5ec5cdc8ce26d8ac67b121ba01295a", "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/randist/flat.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/flat.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/randist/flat.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": 405, "size": 1416 }
/* multifit/multiwlinear.c * * Copyright (C) 2015 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include "linear_common.c" /* General weighted case */ static int multifit_wlinear_svd (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, double tol, int balance, size_t * rank, gsl_vector * c, gsl_matrix * cov, double *chisq, gsl_multifit_linear_workspace * work) { if (X->size1 != y->size) { GSL_ERROR ("number of observations in y does not match rows of matrix X", GSL_EBADLEN); } else if (X->size2 != c->size) { GSL_ERROR ("number of parameters c does not match columns of matrix X", GSL_EBADLEN); } else if (w->size != y->size) { GSL_ERROR ("number of weights does not match number of observations", GSL_EBADLEN); } else if (cov->size1 != cov->size2) { GSL_ERROR ("covariance matrix is not square", GSL_ENOTSQR); } else if (c->size != cov->size1) { GSL_ERROR ("number of parameters does not match size of covariance matrix", GSL_EBADLEN); } else if (X->size1 != work->n || X->size2 != work->p) { GSL_ERROR ("size of workspace does not match size of observation matrix", GSL_EBADLEN); } else { const size_t n = X->size1; const size_t p = X->size2; size_t i, j, p_eff; gsl_matrix *A = work->A; gsl_matrix *Q = work->Q; gsl_matrix *QSI = work->QSI; gsl_vector *S = work->S; gsl_vector *t = work->t; gsl_vector *xt = work->xt; gsl_vector *D = work->D; /* Scale X, A = sqrt(w) X */ gsl_matrix_memcpy (A, X); for (i = 0; i < n; i++) { double wi = gsl_vector_get (w, i); if (wi < 0) wi = 0; { gsl_vector_view row = gsl_matrix_row (A, i); gsl_vector_scale (&row.vector, sqrt (wi)); } } /* Balance the columns of the matrix A if requested */ if (balance) { gsl_linalg_balance_columns (A, D); } else { gsl_vector_set_all (D, 1.0); } /* Decompose A into U S Q^T */ gsl_linalg_SV_decomp_mod (A, QSI, Q, S, xt); /* Solve sqrt(w) y = A c for c, by first computing t = sqrt(w) y */ for (i = 0; i < n; i++) { double wi = gsl_vector_get (w, i); double yi = gsl_vector_get (y, i); if (wi < 0) wi = 0; gsl_vector_set (t, i, sqrt (wi) * yi); } gsl_blas_dgemv (CblasTrans, 1.0, A, t, 0.0, xt); /* Scale the matrix Q, Q' = Q S^-1 */ gsl_matrix_memcpy (QSI, Q); { double s0 = gsl_vector_get (S, 0); p_eff = 0; for (j = 0; j < p; j++) { gsl_vector_view column = gsl_matrix_column (QSI, j); double sj = gsl_vector_get (S, j); double alpha; if (sj <= tol * s0) { alpha = 0.0; } else { alpha = 1.0 / sj; p_eff++; } gsl_vector_scale (&column.vector, alpha); } *rank = p_eff; } gsl_vector_set_zero (c); /* solution */ gsl_blas_dgemv (CblasNoTrans, 1.0, QSI, xt, 0.0, c); /* unscale the balancing factors */ gsl_vector_div (c, D); /* compute chisq, from residual r = y - X c */ { double r2 = 0; for (i = 0; i < n; i++) { double yi = gsl_vector_get (y, i); double wi = gsl_vector_get (w, i); gsl_vector_const_view row = gsl_matrix_const_row (X, i); double y_est, ri; gsl_blas_ddot (&row.vector, c, &y_est); ri = yi - y_est; r2 += wi * ri * ri; } *chisq = r2; /* Form covariance matrix cov = (X^T W X)^-1 = (Q S^-1) (Q S^-1)^T */ for (i = 0; i < p; i++) { gsl_vector_view row_i = gsl_matrix_row (QSI, i); double d_i = gsl_vector_get (D, i); for (j = i; j < p; j++) { gsl_vector_view row_j = gsl_matrix_row (QSI, j); double d_j = gsl_vector_get (D, j); double s; gsl_blas_ddot (&row_i.vector, &row_j.vector, &s); gsl_matrix_set (cov, i, j, s / (d_i * d_j)); gsl_matrix_set (cov, j, i, s / (d_i * d_j)); } } } return GSL_SUCCESS; } } int gsl_multifit_wlinear (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, gsl_vector * c, gsl_matrix * cov, double *chisq, gsl_multifit_linear_workspace * work) { size_t rank; int status = gsl_multifit_wlinear_tsvd(X, w, y, GSL_DBL_EPSILON, c, cov, chisq, &rank, work); return status; } int gsl_multifit_wlinear_tsvd (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, const double tol, gsl_vector * c, gsl_matrix * cov, double * chisq, size_t * rank, gsl_multifit_linear_workspace * work) { const size_t n = X->size1; const size_t p = X->size2; if (y->size != n) { GSL_ERROR("number of observations in y does not match matrix", GSL_EBADLEN); } else if (w->size != n) { GSL_ERROR("number of weights in w does not match matrix", GSL_EBADLEN); } else if (p != c->size) { GSL_ERROR ("number of parameters c does not match matrix", GSL_EBADLEN); } else if (tol <= 0) { GSL_ERROR ("tolerance must be positive", GSL_EINVAL); } else { int status; double rnorm, snorm; gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p); gsl_vector_view b = gsl_vector_subvector(work->t, 0, n); /* compute A = sqrt(W) X, b = sqrt(W) y */ status = gsl_multifit_linear_applyW(X, w, y, &A.matrix, &b.vector); if (status) return status; /* compute SVD of A */ status = gsl_multifit_linear_bsvd(&A.matrix, work); if (status) return status; status = multifit_linear_solve(X, &b.vector, tol, 0.0, rank, c, &rnorm, &snorm, work); if (status) return status; *chisq = rnorm * rnorm; /* variance-covariance matrix cov = s2 * (Q S^-1) (Q S^-1)^T */ { const size_t p = X->size2; size_t i, j; gsl_matrix_view QSI = gsl_matrix_submatrix(work->QSI, 0, 0, p, p); gsl_vector_view D = gsl_vector_subvector(work->D, 0, p); for (i = 0; i < p; i++) { gsl_vector_view row_i = gsl_matrix_row (&QSI.matrix, i); double d_i = gsl_vector_get (&D.vector, i); for (j = i; j < p; j++) { gsl_vector_view row_j = gsl_matrix_row (&QSI.matrix, j); double d_j = gsl_vector_get (&D.vector, j); double s; gsl_blas_ddot (&row_i.vector, &row_j.vector, &s); gsl_matrix_set (cov, i, j, s / (d_i * d_j)); gsl_matrix_set (cov, j, i, s / (d_i * d_j)); } } } } return GSL_SUCCESS; } int gsl_multifit_wlinear_svd (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, double tol, size_t * rank, gsl_vector * c, gsl_matrix * cov, double *chisq, gsl_multifit_linear_workspace * work) { int status = multifit_wlinear_svd (X, w, y, tol, 1, rank, c, cov, chisq, work); return status; } int gsl_multifit_wlinear_usvd (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, double tol, size_t * rank, gsl_vector * c, gsl_matrix * cov, double *chisq, gsl_multifit_linear_workspace * work) { int status = multifit_wlinear_svd (X, w, y, tol, 0, rank, c, cov, chisq, work); return status; }
{ "alphanum_fraction": 0.4964705882, "avg_line_length": 28.1700288184, "ext": "c", "hexsha": "eb86c21738c1c4bf07e991a7751b84b4bde0c963", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/multiwlinear.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/multiwlinear.c", "max_line_length": 95, "max_stars_count": 1, "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_path": "gsl-2.4/multifit/multiwlinear.c", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "num_tokens": 2559, "size": 9775 }
#ifndef EXAMPLE_GENERATOR_H #define EXAMPLE_GENERATOR_H #include <opencv/cv.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include "helper/bounding_box.h" #include "loader/loader_imagenet_det.h" #include "loader/video.h" #include "helper/Common.h" #include "helper/CommonCV.h" #include "helper/Constants.h" #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* GAUSSIAN*/ struct BBParams { double lambda_shift; double lambda_scale; double min_scale; double max_scale; }; // Generates additional training examples by taking random crops of the target object, // causing apparent translation and scale changes. class ExampleGenerator { public: ExampleGenerator(const double lambda_shift, const double lambda_scale, const double min_scale, const double max_scale); // Set up to train on the previous and current image, and the previous and current bounding boxes. void Reset(const BoundingBox& bbox_prev, const BoundingBox& bbox_curr, const cv::Mat& image_prev, const cv::Mat& image_curr); // Shift the whole bounding box for the current frame // (simulates camera motion) void MakeTrainingExampleBBShift(const bool visualize_example, cv::Mat* image_rand_focus, cv::Mat* target_pad, BoundingBox* bbox_gt_scaled) const; void MakeTrainingExampleBBShift(cv::Mat* image_rand_focus, cv::Mat* target_pad, BoundingBox* bbox_gt_scaled) const; // Focus the current image at the location of the previous frame's // bounding box (true motion). void MakeTrueExample(cv::Mat* image_focus, cv::Mat* target_pad, BoundingBox* bbox_gt_scaled) const; void MakeTrueExampleTight(cv::Mat* image_focus, cv::Mat* target_tight, BoundingBox* bbox_gt_scaled) const; // Make batch_size training examples according to the input parameters. void MakeTrainingExamples(const int num_examples, std::vector<cv::Mat>* images, std::vector<cv::Mat>* targets, std::vector<BoundingBox>* bboxes_gt_scaled); // Helper function to generate one moved box, non-gaussian version // trans_range, scale_range are defaults for uniform sampling of uniform samples static BoundingBox GenerateOneRandomCandidate(BoundingBox &bbox, gsl_rng* rng, int W, int H, const string method = "uniform", const double trans_range = POS_TRANS_RANGE, const double scale_range = POS_SCALE_RANGE, const double sd_x = SD_X, const double sd_y = SD_Y, const double sd_scale = SD_SCALE); // Make candidates given one frame // candidates: 200 neg and 50 pos candidates // labels: vector of scalar 1 means pos and 0 means neg // fixed number output, candidates and labels will have size == num_pos + num_neg void MakeCandidatesAndLabels(vector<Mat> *candidates, vector<double> *labels, const int num_pos = POS_CANDIDATES, const int num_neg = NEG_CANDIDATES); // Actual woker under MakeCandidatesAndLabels void MakeCandidatesAndLabelsBBox(vector<BoundingBox> *candidate_bboxes, vector<double> *labels, const int num_pos = POS_CANDIDATES, const int num_neg = NEG_CANDIDATES); void MakeCandidatesPos(vector<BoundingBox> *candidates, const int num = POS_CANDIDATES, const string method = "gaussian", const double trans_range = POS_TRANS_RANGE, const double scale_range = POS_SCALE_RANGE, const double sd_x = SD_X, const double sd_y = SD_Y, const double sd_scale = SD_SCALE, const double pos_iou_th = POS_IOU_TH ); void MakeCandidatesNeg(vector<BoundingBox> *candidates, const int num = NEG_CANDIDATES, const string method = "uniform", const double trans_range = 2 * SD_X, const double scale_range = POS_SCALE_RANGE, const double sd_x = SD_X, const double sd_y = SD_Y, const double sd_scale = SD_SCALE); void set_indices(const int video_index, const int frame_index) { video_index_ = video_index; frame_index_ = frame_index; } private: void MakeTrainingExampleBBShift(const bool visualize_example, const BBParams& bbparams, cv::Mat* image_rand_focus, cv::Mat* target_pad, BoundingBox* bbox_gt_scaled) const; void VisualizeExample(const cv::Mat& target_pad, const cv::Mat& image_rand_focus, const BoundingBox& bbox_gt_scaled) const; void get_default_bb_params(BBParams* default_params) const; // To generate synethic examples, shift the bounding box by an exponential with the given lambda parameter. double lambda_shift_; // To generate synethic examples, shift the bounding box by an exponential with the given lambda parameter. double lambda_scale_; // Do not scale the synthetic examples by more than max_scale_ shrink them by more than min_scale_. double min_scale_; double max_scale_; // Current training image. cv::Mat image_curr_; // Location of the target within the current and previous images. BoundingBox bbox_curr_gt_; BoundingBox bbox_prev_gt_; // Cropped and scaled image of the target object from the previous image. cv::Mat target_pad_; // tight previous target in previous image cv::Mat target_tight_; // Video and frame index from which the current example was generated. // These values are only used when saving images to a file, to assign them // a unique identifier. int video_index_; int frame_index_; gsl_rng* rng_; static std::mt19937 engine_; }; #endif // EXAMPLE_GENERATOR_H
{ "alphanum_fraction": 0.6640586797, "avg_line_length": 44.1366906475, "ext": "h", "hexsha": "176d878273d41f43489418e6720e529b2abb29e1", "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": "6c522b26f664c259bd371214e44c9c2cd32c51d0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Jim61C/GMD_Tracker", "max_forks_repo_path": "src/train/example_generator.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "6c522b26f664c259bd371214e44c9c2cd32c51d0", "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": "Jim61C/GMD_Tracker", "max_issues_repo_path": "src/train/example_generator.h", "max_line_length": 169, "max_stars_count": 2, "max_stars_repo_head_hexsha": "6c522b26f664c259bd371214e44c9c2cd32c51d0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Jim61C/GMD_Tracker", "max_stars_repo_path": "src/train/example_generator.h", "max_stars_repo_stars_event_max_datetime": "2018-06-19T21:49:19.000Z", "max_stars_repo_stars_event_min_datetime": "2018-04-14T14:33:30.000Z", "num_tokens": 1287, "size": 6135 }
#ifndef _FUNCTIONS_ #define _FUNCTIONS_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <limits.h> #include <cblas.h> #include <lapacke.h> #include "structs.c" #define PATH_LENGTH 32 #define LINE_LENGTH 50000 #define FRECHET 1 #define DTW 2 #define THRESHOLD 0.0000005 // Declare functions of functions.c file int is_centroid(int *, int , int ); double rand_gaussian(void); int centroids_transposition(segment **, int *, int *, int , double **); double **create_distances_array(segment **, int , int ); #endif
{ "alphanum_fraction": 0.6797385621, "avg_line_length": 17.4857142857, "ext": "h", "hexsha": "3c667007db404ba58b05bc1b4cc65e94f804d7fb", "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": "b5f7baf7d94eabdddd61f20232182bcce2f57a36", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "skanel94/Software-Development-for-Algorithmic-Problems", "max_forks_repo_path": "Part 3/Roads/src/functions.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b5f7baf7d94eabdddd61f20232182bcce2f57a36", "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": "skanel94/Software-Development-for-Algorithmic-Problems", "max_issues_repo_path": "Part 3/Roads/src/functions.h", "max_line_length": 72, "max_stars_count": null, "max_stars_repo_head_hexsha": "b5f7baf7d94eabdddd61f20232182bcce2f57a36", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "skanel94/Software-Development-for-Algorithmic-Problems", "max_stars_repo_path": "Part 3/Roads/src/functions.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 150, "size": 612 }
#pragma once #include "types/type_util.h" #include <expected.hpp> #include <gsl/gsl> #include <sstream> #include <variant> namespace util { template<typename... Args> std::string concat(const Args&... args) { std::stringstream ss; (ss << ... << args); return ss.str(); } namespace detail { template<typename T> T str_to(const std::string& str, std::size_t* pos, int base) { static_assert(AlwaysFalse<T>::value, "try_parse_number not defined for type T!"); } #define GEN_STR_TO_SPECIALIZATION(type, func) \ template<> \ inline type str_to(const std::string& str, std::size_t* pos, int base) \ { \ const auto parsed = func(str, pos, base); \ if (parsed > std::numeric_limits<type>::max()) { \ throw std::out_of_range{ "Value is out of range for type " #type }; \ } \ return gsl::narrow_cast<type>(parsed); \ } GEN_STR_TO_SPECIALIZATION(uint8_t, std::stoul) GEN_STR_TO_SPECIALIZATION(int8_t, std::stol) GEN_STR_TO_SPECIALIZATION(uint16_t, std::stoul) GEN_STR_TO_SPECIALIZATION(int16_t, std::stol) GEN_STR_TO_SPECIALIZATION(uint32_t, std::stoul) GEN_STR_TO_SPECIALIZATION(int32_t, std::stol) GEN_STR_TO_SPECIALIZATION(uint64_t, std::stoull) GEN_STR_TO_SPECIALIZATION(int64_t, std::stoll) template<> inline float str_to(const std::string& str, std::size_t* pos, int) { return std::stof(str, pos); } template<> inline double str_to(const std::string& str, std::size_t* pos, int) { return std::stod(str, pos); } template<> inline long double str_to(const std::string& str, std::size_t* pos, int) { return std::stold(str, pos); } } /** * Wrapper around the std::stoX functions. Tries to parse the given string as a number * of the given type and returns a tl::expected with the resulting number of the reason * for failure. The arguments are the same as for the std functions, with the exception that * base is only valid if T is an integer type */ template<typename T> tl::expected<T, std::variant<std::invalid_argument, std::out_of_range>> try_parse_number(const std::string& str, std::size_t* pos = nullptr, int base = 10) { try { const auto number = detail::str_to<T>(str, pos, base); return { number }; } catch (const std::invalid_argument& ex) { return tl::make_unexpected(std::variant<std::invalid_argument, std::out_of_range>{ ex }); } catch (const std::out_of_range& ex) { return tl::make_unexpected(std::variant<std::invalid_argument, std::out_of_range>{ ex }); } } } // namespace util
{ "alphanum_fraction": 0.5831669993, "avg_line_length": 32.6739130435, "ext": "h", "hexsha": "44263c55abcae12744170bf2fb2e4a358987bf7c", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2022-02-08T11:45:45.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:50:42.000Z", "max_forks_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "igd-geo/schwarzwald", "max_forks_repo_path": "schwarzwald/util/algorithms/Strings.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:28:06.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-25T08:37:30.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "igd-geo/schwarzwald", "max_issues_repo_path": "schwarzwald/util/algorithms/Strings.h", "max_line_length": 100, "max_stars_count": 10, "max_stars_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "igd-geo/schwarzwald", "max_stars_repo_path": "schwarzwald/util/algorithms/Strings.h", "max_stars_repo_stars_event_max_datetime": "2022-02-13T00:15:17.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-06T14:16:31.000Z", "num_tokens": 688, "size": 3006 }
#ifndef _SPC_RESP_H #define _SPC_RESP_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_nan.h> #include <gsl/gsl_sys.h> #include "fitsio.h" #include "aXe_grism.h" #include "spc_cfg.h" #include "spc_spc.h" #define RESPBUFFERSIZE 1024 // number of points used // for smoothing #define RESP_SMOOTH_LENGTH 50 // the number of sigmas // to smooth over #define RESP_SMOOTH_NSIG 3.0 #define MAX_ITER_TL 1000 /* * Struct: interpolator */ typedef struct { double xmin; double xmax; interpolator *resp_values; interpolator *resp_errors; } response_function; typedef struct { double wavelength; const calib_function *wl_calibration; } trlength_search; extern spectrum * get_response_function_from_FITS(char filename[], int hdunum); extern void apply_response_function(spectrum *spec, spectrum *resp, const int quant_cont); extern void apply_response_functionII(spectrum *spec, response_function *resp_func, const int quant_cont); extern d_point get_smooth_pars_for_beam(const aperture_conf *conf, const int smooth_conv, beam actbeam); extern int check_conf_for_smoothing(const aperture_conf *conf, const int smooth_conv); extern void apply_smoothed_response(const calib_function *wl_calibration, const int for_grism, const int quant_cont, response_function *resp_func, const d_point smooth_pars, spectrum *spec); extern double find_wavelength(double x, void *params); extern double get_tlength_prismwav(const double wavelength, const calib_function *wl_calibration); extern double get_central_tracelength(const double wavelength, const calib_function *wl_calibration, const int for_grism); extern void get_smoothed_response(const double wavelength, const d_point smooth_pars, const calib_function *wl_calibration, const int for_grism, const gsl_vector *weights, response_function *resp_func, double *resp_vals); //extern void //get_smoothed_response(const double wavelength, const double sigma_wav, const gsl_vector *weights, // response_function *resp_func, double *resp_vals); extern void get_weighted_sensitivity(const gsl_vector *pixvalues, const gsl_vector *errvalues, const gsl_vector *weights, const gsl_vector *pmask, double *resp_vals); extern void fill_weight(gsl_vector *weights); extern void get_troughput_table_name(char *filename, int beamID, char *table_name); extern double get_response_value_plus(const spectrum *resp, const double wavelength, int *nguess); extern void get_response_values(response_function *resp_func, double wavelength, double* resp_vals); extern response_function * create_response_function(char *filename); extern void free_response_function(response_function *resp_func); extern calib_function * get_calfunc_for_beam(const beam actbeam, const int for_grism, char CONF_file[], const aperture_conf * conf); #endif
{ "alphanum_fraction": 0.74910859, "avg_line_length": 26.5948275862, "ext": "h", "hexsha": "a2d0447264fdd1dd6eebfdf8142b4ec97772c37c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/spc_resp.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/spc_resp.h", "max_line_length": 109, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/spc_resp.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 686, "size": 3085 }
/* multifit/multiwlinear.c * * Copyright (C) 2015 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_linalg.h> #include "linear_common.c" int gsl_multifit_wlinear (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, gsl_vector * c, gsl_matrix * cov, double *chisq, gsl_multifit_linear_workspace * work) { size_t rank; int status = gsl_multifit_wlinear_tsvd(X, w, y, GSL_DBL_EPSILON, c, cov, chisq, &rank, work); return status; } int gsl_multifit_wlinear_tsvd (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, const double tol, gsl_vector * c, gsl_matrix * cov, double * chisq, size_t * rank, gsl_multifit_linear_workspace * work) { const size_t n = X->size1; const size_t p = X->size2; if (y->size != n) { GSL_ERROR("number of observations in y does not match matrix", GSL_EBADLEN); } else if (w->size != n) { GSL_ERROR("number of weights in w does not match matrix", GSL_EBADLEN); } else if (p != c->size) { GSL_ERROR ("number of parameters c does not match matrix", GSL_EBADLEN); } else if (tol <= 0) { GSL_ERROR ("tolerance must be positive", GSL_EINVAL); } else { int status; double rnorm, snorm; gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p); gsl_vector_view b = gsl_vector_subvector(work->t, 0, n); /* compute A = sqrt(W) X, b = sqrt(W) y */ status = gsl_multifit_linear_applyW(X, w, y, &A.matrix, &b.vector); if (status) return status; /* compute SVD of A */ status = gsl_multifit_linear_bsvd(&A.matrix, work); if (status) return status; status = multifit_linear_solve(X, &b.vector, tol, 0.0, rank, c, &rnorm, &snorm, work); if (status) return status; *chisq = rnorm * rnorm; /* variance-covariance matrix cov = s2 * (Q S^-1) (Q S^-1)^T */ { const size_t p = X->size2; size_t i, j; gsl_matrix_view QSI = gsl_matrix_submatrix(work->QSI, 0, 0, p, p); gsl_vector_view D = gsl_vector_subvector(work->D, 0, p); for (i = 0; i < p; i++) { gsl_vector_view row_i = gsl_matrix_row (&QSI.matrix, i); double d_i = gsl_vector_get (&D.vector, i); for (j = i; j < p; j++) { gsl_vector_view row_j = gsl_matrix_row (&QSI.matrix, j); double d_j = gsl_vector_get (&D.vector, j); double s; gsl_blas_ddot (&row_i.vector, &row_j.vector, &s); gsl_matrix_set (cov, i, j, s / (d_i * d_j)); gsl_matrix_set (cov, j, i, s / (d_i * d_j)); } } } } return GSL_SUCCESS; } int gsl_multifit_wlinear_svd (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, double tol, size_t * rank, gsl_vector * c, gsl_matrix * cov, double *chisq, gsl_multifit_linear_workspace * work) { int status = gsl_multifit_wlinear_tsvd(X, w, y, tol, c, cov, chisq, rank, work); return status; } int gsl_multifit_wlinear_usvd (const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, double tol, size_t * rank, gsl_vector * c, gsl_matrix * cov, double *chisq, gsl_multifit_linear_workspace * work) { /* FIXME: this call does actually perform balancing, but this function is deprecated anyway */ int status = gsl_multifit_wlinear_tsvd(X, w, y, tol, c, cov, chisq, rank, work); return status; }
{ "alphanum_fraction": 0.544353263, "avg_line_length": 32.1886792453, "ext": "c", "hexsha": "1f10684f203d90aac4ec57ed48519023d3b446d6", "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/multifit/multiwlinear.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/multifit/multiwlinear.c", "max_line_length": 96, "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/multifit/multiwlinear.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": 1287, "size": 5118 }
/* cdf/gsl_cdf.h * * Copyright (C) 2002 Jason H. Stover. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* Author: J. Stover */ #ifndef __GSL_CDF_H__ #define __GSL_CDF_H__ #include <gsl/gsl_types.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS GSL_EXPORT double gsl_cdf_ugaussian_P (const double x); GSL_EXPORT double gsl_cdf_ugaussian_Q (const double x); GSL_EXPORT double gsl_cdf_ugaussian_Pinv (const double P); GSL_EXPORT double gsl_cdf_ugaussian_Qinv (const double Q); GSL_EXPORT double gsl_cdf_gaussian_P (const double x, const double sigma); GSL_EXPORT double gsl_cdf_gaussian_Q (const double x, const double sigma); GSL_EXPORT double gsl_cdf_gaussian_Pinv (const double P, const double sigma); GSL_EXPORT double gsl_cdf_gaussian_Qinv (const double Q, const double sigma); GSL_EXPORT double gsl_cdf_gamma_P (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_gamma_Q (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_gamma_Pinv (const double P, const double a, const double b); GSL_EXPORT double gsl_cdf_gamma_Qinv (const double Q, const double a, const double b); GSL_EXPORT double gsl_cdf_cauchy_P (const double x, const double a); GSL_EXPORT double gsl_cdf_cauchy_Q (const double x, const double a); GSL_EXPORT double gsl_cdf_cauchy_Pinv (const double P, const double a); GSL_EXPORT double gsl_cdf_cauchy_Qinv (const double Q, const double a); GSL_EXPORT double gsl_cdf_laplace_P (const double x, const double a); GSL_EXPORT double gsl_cdf_laplace_Q (const double x, const double a); GSL_EXPORT double gsl_cdf_laplace_Pinv (const double P, const double a); GSL_EXPORT double gsl_cdf_laplace_Qinv (const double Q, const double a); GSL_EXPORT double gsl_cdf_rayleigh_P (const double x, const double sigma); GSL_EXPORT double gsl_cdf_rayleigh_Q (const double x, const double sigma); GSL_EXPORT double gsl_cdf_rayleigh_Pinv (const double P, const double sigma); GSL_EXPORT double gsl_cdf_rayleigh_Qinv (const double Q, const double sigma); GSL_EXPORT double gsl_cdf_chisq_P (const double x, const double nu); GSL_EXPORT double gsl_cdf_chisq_Q (const double x, const double nu); GSL_EXPORT double gsl_cdf_chisq_Pinv (const double P, const double nu); GSL_EXPORT double gsl_cdf_chisq_Qinv (const double Q, const double nu); GSL_EXPORT double gsl_cdf_exponential_P (const double x, const double mu); GSL_EXPORT double gsl_cdf_exponential_Q (const double x, const double mu); GSL_EXPORT double gsl_cdf_exponential_Pinv (const double P, const double mu); GSL_EXPORT double gsl_cdf_exponential_Qinv (const double Q, const double mu); GSL_EXPORT double gsl_cdf_exppow_P (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_exppow_Q (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_tdist_P (const double x, const double nu); GSL_EXPORT double gsl_cdf_tdist_Q (const double x, const double nu); GSL_EXPORT double gsl_cdf_tdist_Pinv (const double P, const double nu); GSL_EXPORT double gsl_cdf_tdist_Qinv (const double Q, const double nu); GSL_EXPORT double gsl_cdf_fdist_P (const double x, const double nu1, const double nu2); GSL_EXPORT double gsl_cdf_fdist_Q (const double x, const double nu1, const double nu2); GSL_EXPORT double gsl_cdf_fdist_Pinv (const double P, const double nu1, const double nu2); GSL_EXPORT double gsl_cdf_fdist_Qinv (const double Q, const double nu1, const double nu2); GSL_EXPORT double gsl_cdf_beta_P (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_beta_Q (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_beta_Pinv (const double P, const double a, const double b); GSL_EXPORT double gsl_cdf_beta_Qinv (const double Q, const double a, const double b); GSL_EXPORT double gsl_cdf_flat_P (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_flat_Q (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_flat_Pinv (const double P, const double a, const double b); GSL_EXPORT double gsl_cdf_flat_Qinv (const double Q, const double a, const double b); GSL_EXPORT double gsl_cdf_lognormal_P (const double x, const double zeta, const double sigma); GSL_EXPORT double gsl_cdf_lognormal_Q (const double x, const double zeta, const double sigma); GSL_EXPORT double gsl_cdf_lognormal_Pinv (const double P, const double zeta, const double sigma); GSL_EXPORT double gsl_cdf_lognormal_Qinv (const double Q, const double zeta, const double sigma); GSL_EXPORT double gsl_cdf_gumbel1_P (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_gumbel1_Q (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_gumbel1_Pinv (const double P, const double a, const double b); GSL_EXPORT double gsl_cdf_gumbel1_Qinv (const double Q, const double a, const double b); GSL_EXPORT double gsl_cdf_gumbel2_P (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_gumbel2_Q (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_gumbel2_Pinv (const double P, const double a, const double b); GSL_EXPORT double gsl_cdf_gumbel2_Qinv (const double Q, const double a, const double b); GSL_EXPORT double gsl_cdf_weibull_P (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_weibull_Q (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_weibull_Pinv (const double P, const double a, const double b); GSL_EXPORT double gsl_cdf_weibull_Qinv (const double Q, const double a, const double b); GSL_EXPORT double gsl_cdf_pareto_P (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_pareto_Q (const double x, const double a, const double b); GSL_EXPORT double gsl_cdf_pareto_Pinv (const double P, const double a, const double b); GSL_EXPORT double gsl_cdf_pareto_Qinv (const double Q, const double a, const double b); GSL_EXPORT double gsl_cdf_logistic_P (const double x, const double a); GSL_EXPORT double gsl_cdf_logistic_Q (const double x, const double a); GSL_EXPORT double gsl_cdf_logistic_Pinv (const double P, const double a); GSL_EXPORT double gsl_cdf_logistic_Qinv (const double Q, const double a); GSL_EXPORT double gsl_cdf_binomial_P (const unsigned int k, const double p, const unsigned int n); GSL_EXPORT double gsl_cdf_binomial_Q (const unsigned int k, const double p, const unsigned int n); GSL_EXPORT double gsl_cdf_poisson_P (const unsigned int k, const double mu); GSL_EXPORT double gsl_cdf_poisson_Q (const unsigned int k, const double mu); GSL_EXPORT double gsl_cdf_geometric_P (const unsigned int k, const double p); GSL_EXPORT double gsl_cdf_geometric_Q (const unsigned int k, const double p); GSL_EXPORT double gsl_cdf_negative_binomial_P (const unsigned int k, const double p, const double n); GSL_EXPORT double gsl_cdf_negative_binomial_Q (const unsigned int k, const double p, const double n); GSL_EXPORT double gsl_cdf_pascal_P (const unsigned int k, const double p, const unsigned int n); GSL_EXPORT double gsl_cdf_pascal_Q (const unsigned int k, const double p, const unsigned int n); GSL_EXPORT double gsl_cdf_hypergeometric_P (const unsigned int k, const unsigned int n1, const unsigned int n2, const unsigned int t); GSL_EXPORT double gsl_cdf_hypergeometric_Q (const unsigned int k, const unsigned int n1, const unsigned int n2, const unsigned int t); __END_DECLS #endif /* __GSL_CDF_H__ */
{ "alphanum_fraction": 0.7882845188, "avg_line_length": 48.3526011561, "ext": "h", "hexsha": "ec7be9e516b1ba7e8034ecf8b32e49c00bd8b8f3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_cdf.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_cdf.h", "max_line_length": 101, "max_stars_count": null, "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_cdf.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2220, "size": 8365 }
/* * Copyright (c) 2020 Microsoft. All rights reserved. */ #pragma once #include <array> #include <algorithm> #include <gsl/span> #include "common/common.h" #include "common/logger.h" // A wrapper around std::array that is specialized to uint8_t and enforces // initialization template <size_t TLength> class Blob : public CanBeSerialsed { using CArrayType = uint8_t[TLength]; using CppArrayType = std::array<uint8_t, TLength>; CppArrayType _data; public: static constexpr size_t array_size = TLength; using array_type = CppArrayType; constexpr Blob(const CArrayType &data) { std::copy(std::begin(data), std::end(data), _data.begin()); } constexpr Blob(const gsl::span<const uint8_t> &data) { const size_t size = std::min(_data.size(), data.size()); std::copy_n(data.begin(), size, _data.begin()); } constexpr Blob() noexcept : _data() { for (auto &b : _data) { b = 0; } } CppArrayType &array() { return _data; } const CppArrayType &array() const { return _data; } MemRef span() { return MakeMemRef(&_data); } CMemRef span() const { return MakeCMemRef(&_data); } uint8_t *data() noexcept { return _data.data(); } const uint8_t *data() const noexcept { return _data.data(); } uint8_t *end() { const MemRef span = gsl::make_span(data(), TLength + 1); const MemRef sub = span.subspan(TLength, 1); return sub.data(); } size_t length() const { return TLength; } bool operator==(const Blob<TLength> &d) const { return d.array() == array(); } bool operator!=(const Blob<TLength> &d) const { return d.array() != array(); } // we cannot check the whole object, but we can check the array. static_assert(OkAsParam<CppArrayType, TLength>::value); }; // A wrapper around std::array that is specialized to char and enforces // initialization template <size_t TLength> class CharBlob : public CannotBeSerialsed { using CArrayType = char[TLength]; using CppArrayType = std::array<char, TLength>; private: CppArrayType _data; size_t _length; // Danger! public: constexpr CharBlob(const gsl::span<const char> &data) { const size_t size = data.size(); if (size > TLength) { HW_LOG_FAIL("Blob not long enough"); while (1) ; } _data.fill(0); std::copy_n(data.begin(), size, _data.begin()); _length = size; } constexpr CharBlob(const char *data, size_t length) { if (length > TLength) { HW_LOG_FAIL("Blob not long enough"); while (1) ; } const CSignedMemRef aspan = MakeCSignedMemRef(data, length); _data.fill(0); std::copy_n(aspan.begin(), length, _data.begin()); _length = length; } constexpr CharBlob() noexcept : _data() { _data.fill(0); _length = 0; } CppArrayType &array() { return _data; } const CppArrayType &array() const { return _data; } SignedMemRef span() { return MakeSignedMemRef(&_data); } CSignedMemRef span() const { return MakeCSignedMemRef(&_data); } char *data() { return _data.data(); } const char *data() const { return _data.data(); } size_t maxlength() const { return TLength; } size_t length() const { return _length; } bool operator==(const CharBlob<TLength> &d) { if (d.length() != length()) { return false; } // not using the strcmp as these buffers may not have null-terminating // character const size_t len = length(); const CSignedMemRef _dspan = MakeCSignedMemRef(data(), len); const CSignedMemRef dspan = MakeCSignedMemRef(d.data(), len); return (_dspan == dspan); } bool operator!=(const CharBlob<TLength> &d) { if (d.length() != length()) { return true; } // not using the strcmp as these buffers may not have null-terminating // character const size_t len = length(); const CSignedMemRef _dspan = MakeCSignedMemRef(data(), len); const CSignedMemRef dspan = MakeCSignedMemRef(d.data(), len); return (_dspan != dspan); } };
{ "alphanum_fraction": 0.6545408931, "avg_line_length": 25.3885350318, "ext": "h", "hexsha": "73070feb5701d634d710294488eeabbffef7a826", "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": "703299f9ae5422cfd7161f80c32b5f3ad1bb6af6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "verified-HRoT/Verified-DICE-for-STM32H7", "max_forks_repo_path": "src/common/Blob.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "703299f9ae5422cfd7161f80c32b5f3ad1bb6af6", "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": "verified-HRoT/Verified-DICE-for-STM32H7", "max_issues_repo_path": "src/common/Blob.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "703299f9ae5422cfd7161f80c32b5f3ad1bb6af6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "verified-HRoT/Verified-DICE-for-STM32H7", "max_stars_repo_path": "src/common/Blob.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1082, "size": 3986 }
/*! \file getdata.h \brief rのメッシュと、そのメッシュにおける電子密度を与えるクラスの宣言 Copyright © 2015-2019 @dc1394 All Rights Reserved. This software is released under the BSD 2-Clause License. */ #ifndef _GETRMESHANDRHO_H_ #define _GETRMESHANDRHO_H_ #pragma once #include "../utility/property.h" #include <cstdint> // for std::int32_t, std::uint32_t #include <memory> // for std::unique_ptr #include <string> // for std::string #include <gsl/gsl_spline.h> // for gsl_interp_accel, gsl_interp_accel_free, gsl_spline, gsl_spline_free namespace getdata { using namespace utility; //! A class. /*! rのメッシュと、そのメッシュにおける動径波動関数を与えるクラス */ class GetData final { // #region 列挙型 public: //! A enumerated type /*! 密度か動径波動関数かを表す列挙型 */ enum class Rho_Wf_type { // 密度 RHO, // 動径波動関数 WF }; // #endregion 列挙型 // #region コンストラクタ・デストラクタ //! A constructor. /*! 唯一のコンストラクタ \param filename rのメッシュと、そのメッシュにおける電子密度が記録されたデータファイル名 */ GetData(std::string const & filename); //! A destructor. /*! デフォルトデストラクタ */ ~GetData() = default; // #endregion コンストラクタ・デストラクタ // #region メンバ関数 //! A public member function (const). /*! 関数の値を返す \param r rの値 \return 関数の値 */ double operator()(double r) const; //! A public member function (const). /*! 関数の微分の値を返す \param r rの値 \return 関数の微分の値 */ double dphidr(double r) const; // #endregion メンバ関数 // #region プロパティ //! A property. /*! 元素名 */ Property<std::string const&> Atomname; //! A property. /*! 方位量子数へのプロパティ */ Property<std::uint32_t> const L; //! A property. /*! 主量子数へのプロパティ */ Property<std::int32_t> const N; //! A property. /*! 軌道へのプロパティ */ Property<std::string> const Orbital; //! A property. /*! 波動関数の最大値のプロパティ */ Property<double> const Phimax; //! A property. /*! 波動関数が最大値を取るときのrへのプロパティ */ Property<double> const R2rhomaxr; //! A private member variable. /*! 解く方程式のタイプへのプロパティ */ Property<GetData::Rho_Wf_type> const Rho_wf_type; //! A property. /*! rのメッシュの最大値のプロパティ */ Property<double> const R_meshmax; //! A property. /*! rのメッシュの最小値のプロパティ */ Property<double> const R_meshmin; // #endregion プロパティ // #region メンバ変数 private: //! A private member variable. /*! gsl_interp_accelへのスマートポインタ */ std::unique_ptr<gsl_interp_accel, decltype(&gsl_interp_accel_free)> const acc_; //! A private member variable. /*! 元素名 */ std::string atomname_; //! A private member variable. /*! 方位量子数 */ std::uint32_t l_; //! A private member variable. /*! 主量子数 */ std::int32_t n_; //! A private member variable. /*! 軌道 */ std::string orbital_; //! A private member variable. /*! 波動関数φ */ std::vector<double> phi_; //! A private member variable. /*! 波動関数の最大値 */ double phimax_; //! A private member variable. /*! 波動関数が最大値を取るときのr */ double r2rhomaxr_; //! A private member variable. /*! 解く方程式のタイプ */ Rho_Wf_type rho_wf_type_; //! A private member variable. /*! rのメッシュの最大値 */ double r_meshmax_; //! A private member variable. /*! rのメッシュの最小値 */ double r_meshmin_; //! A private member variable. /*! rのメッシュ */ std::vector<double> r_mesh_; //! A private member variable. /*! gsl_interp_typeへのスマートポインタ */ std::unique_ptr<gsl_spline, decltype(&gsl_spline_free)> spline_; // #endregion メンバ変数 // #region 禁止されたコンストラクタ・メンバ関数 public: //! A public constructor (deleted). /*! デフォルトコンストラクタ(禁止) */ GetData() = delete; //! A public copy constructor (deleted). /*! コピーコンストラクタ(禁止) \param dummy コピー元のオブジェクト(未使用) */ GetData(GetData const & dummy) = delete; //! A public member function (deleted). /*! operator=()の宣言(禁止) \param dummy コピー元のオブジェクト(未使用) \return コピー元のオブジェクト */ GetData& operator=(GetData const & dummy) = delete; // #endregion 禁止されたコンストラクタ・メンバ関数 }; // #region メンバ関数 inline double GetData::operator()(double r) const { return gsl_spline_eval(spline_.get(), r, acc_.get()); } inline double GetData::dphidr(double r) const { return gsl_spline_eval_deriv(spline_.get(), r, acc_.get()); } // #endregion メンバ関数 } #endif // _GETRMESHANDRHO_H_
{ "alphanum_fraction": 0.4879539734, "avg_line_length": 20.9886792453, "ext": "h", "hexsha": "3c8f768254e31a2d47509e05a295cc141848d4df", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-07-04T11:44:57.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-04T11:44:57.000Z", "max_forks_repo_head_hexsha": "b1b8418efeab2ada1d38c86dd3205fcd2ef7cba2", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "dc1394/SchracVisualize2", "max_forks_repo_path": "SchracVisualize2/orbitaldensityrand/getdata/getdata.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "b1b8418efeab2ada1d38c86dd3205fcd2ef7cba2", "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": "dc1394/SchracVisualize2", "max_issues_repo_path": "SchracVisualize2/orbitaldensityrand/getdata/getdata.h", "max_line_length": 103, "max_stars_count": 10, "max_stars_repo_head_hexsha": "b1b8418efeab2ada1d38c86dd3205fcd2ef7cba2", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "dc1394/SchracVisualize_Direct3D_11", "max_stars_repo_path": "SchracVisualize2/orbitaldensityrand/getdata/getdata.h", "max_stars_repo_stars_event_max_datetime": "2021-07-12T12:20:33.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-04T10:53:29.000Z", "num_tokens": 1721, "size": 5562 }
/** * File: trace_conf.h */ #ifndef _TRACE_CONF_H #define _TRACE_CONF_H #include <string.h> #include <math.h> #include <gsl/gsl_vector.h> #include "aXe_grism.h" #include "aXe_errors.h" #include "spc_cfg.h" #include "disp_conf.h" /** A structure to contain the coefficient of a 2D polynomial that can be used to compute the given coefficient of the polynomial dispersion relation as at a particular i.j location in the image */ typedef struct { gsl_vector *pol; /* A vector containing the 2D polynomial coefficients */ d_point offset; /* X and Y offsets to apply to input coordinates */ d_point cpoint; /* The detector location at which this structure was computed */ int ID; /* The ID of the beam for which this coefficient is defined */ char file[MAXCHAR]; } tracestruct; extern int get_beam_trace_norder (char *filename, int beamID); extern gsl_vector * get_beam_trace_order (char *filename, int beamID, int order); extern float get_trace_coeff_at_pos (char *filename, int beamID, int order, d_point p); extern gsl_vector * get_trace_coeffs_at_pos (char *filename, int beamID, d_point p); extern gsl_vector * get_beam_trace_xoff (char *filename, int beamID); extern gsl_vector * get_beam_trace_yoff (char *filename, int beamID); extern float get_trace_xoff_at_pos (char *filename, int beamID, d_point p); extern float get_trace_yoff_at_pos (char *filename, int beamID, d_point p); extern float eval_trace_off_at_pos (gsl_vector *coeffs, d_point p, int beamID); extern tracestruct * get_tracestruct_at_pos (char *filename, int beamID, d_point p); extern void tracestruct_fprintf (FILE * file, tracestruct * trace); extern void free_tracestruct (tracestruct * trace); #endif
{ "alphanum_fraction": 0.7552083333, "avg_line_length": 24.6857142857, "ext": "h", "hexsha": "aac59024d40aeaa35938e0a4d6a66f4ae02ba525", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/trace_conf.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/trace_conf.h", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/trace_conf.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 444, "size": 1728 }
/* AUTORIGHTS Copyright (C) 2007 Princeton University This file is part of Ferret Toolkit. Ferret Toolkit 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, 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 <assert.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <fenv.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_vector.h> #include "LSH.h" #include "perturb.h" #define MISS_GAMMA 1 #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #define MAX_M 64 #define MAX_T 600 static inline double p_col_helper (double x) { double result; result = 2.0*gsl_cdf_ugaussian_P(x) - 1.0; result += sqrt(2.0/M_PI) * (exp(-x*x/2.0)-1.0)/x; return result; } static inline double p_col_p_helper (double x, double k) { return gsl_cdf_ugaussian_P((1.0 + k) * x) - gsl_cdf_ugaussian_P(k * x); } int LSH_recall_init (LSH_recall_t *recall, int d_step, float d_min, float d_max, int M, int L, int T, float W) { ptb_vec_t *ptb_score; ptb_vec_t *ptb_set; float **table; double dist, r, p; int i, j, k; int l; ptb_score = gen_score(M); assert(ptb_score != NULL); ptb_set = type_calloc(ptb_vec_t, T); assert(ptb_set != NULL); gen_perturb_set(ptb_score, ptb_set, M, T); recall->d_step = d_step; recall->d_min = d_min; recall->d_max = d_max; recall->T = T; recall->table = table = type_matrix_alloc(float, T + 1, d_step); for (i = 0; i < d_step; i++) { dist = d_min + (d_max - d_min) * i / d_step; dist = W / sqrt(dist); p = p_col_helper(dist); table[0][i] = log(1.0 - pow(p, M)); for (j = 1; j <= T; j++) { r = 1.0; l = 0; for (k = 0; k < 2 * M; k++) if (ptb_set[j-1].set & (1 << k)) { r *= p_col_p_helper(dist, ptb_score[k].key1); l++; } assert(l > 0); l = M - l; r *= pow(p, l); table[j][i] = table[j-1][i] + log(1.0-r); } for (j = 0; j <= T; j++) { table[j][i] = 1.0 - exp(L * table[j][i]); } } free(ptb_score); free(ptb_set); return 0; } int LSH_recall_dump (LSH_recall_t *recall, CASS_FILE *fout) { int ret; ret = cass_write_size(&recall->d_step, 1, fout); ret += cass_write_size(&recall->T, 1, fout); ret += cass_write_float(&recall->d_min, 1, fout); ret += cass_write_float(&recall->d_max, 1, fout); if (ret != 4) return CASS_ERR_IO; if (type_matrix_dump_stream(float, fout, recall->T + 1, recall->d_step, recall->table) != 0) return CASS_ERR_IO; return 0; } int LSH_recall_load (LSH_recall_t *recall, CASS_FILE *fin) { int ret; cass_size_t row, col; ret = cass_read_size(&recall->d_step, 1, fin); ret += cass_read_size(&recall->T, 1, fin); ret += cass_read_float(&recall->d_min, 1, fin); ret += cass_read_float(&recall->d_max, 1, fin); if (ret != 4) return CASS_ERR_IO; type_matrix_load_stream(float, fin, &row, &col, &recall->table); assert(row == recall->T +1); assert(col == recall->d_step); return 0; }
{ "alphanum_fraction": 0.666956774, "avg_line_length": 24.4468085106, "ext": "c", "hexsha": "3e1ff7d04342adfdcd0f8d0c0e4a13f15b0fbeb5", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-05-08T08:54:49.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-18T14:58:53.000Z", "max_forks_repo_head_hexsha": "f6f165310ecd760808580686fac2fa3f697440fc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "OleksiiOleksenko/fex", "max_forks_repo_path": "src/parsec/ferret/src/recall.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "f6f165310ecd760808580686fac2fa3f697440fc", "max_issues_repo_issues_event_max_datetime": "2018-05-24T11:03:07.000Z", "max_issues_repo_issues_event_min_datetime": "2018-05-24T11:03:07.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "OleksiiOleksenko/fex", "max_issues_repo_path": "src/parsec/ferret/src/recall.c", "max_line_length": 113, "max_stars_count": 15, "max_stars_repo_head_hexsha": "f6f165310ecd760808580686fac2fa3f697440fc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "OleksiiOleksenko/fex", "max_stars_repo_path": "src/parsec/ferret/src/recall.c", "max_stars_repo_stars_event_max_datetime": "2020-05-31T03:18:25.000Z", "max_stars_repo_stars_event_min_datetime": "2018-07-31T07:24:36.000Z", "num_tokens": 1132, "size": 3447 }
#include <Python.h> #include <numpy/arrayobject.h> #include <complex.h> #include <stdint.h> #include <stdlib.h> #include <math.h> #include <stdbool.h> #include <tgmath.h> #include <stdio.h> #include <time.h> #include "AG.h" #include "bitarray.h" #include "CH.h" #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> CHForm * python_tuple_to_CHForm(PyObject * tuple){ PyObject * py_n = PyTuple_GetItem(tuple, 0); PyArrayObject * py_F = (PyArrayObject *)PyTuple_GetItem(tuple, 1); PyArrayObject * py_G = (PyArrayObject *)PyTuple_GetItem(tuple, 2); PyArrayObject * py_M = (PyArrayObject *)PyTuple_GetItem(tuple, 3); PyArrayObject * py_g = (PyArrayObject *)PyTuple_GetItem(tuple, 4); PyArrayObject * py_v = (PyArrayObject *)PyTuple_GetItem(tuple, 5); PyArrayObject * py_s = (PyArrayObject *)PyTuple_GetItem(tuple, 6); PyObject * py_obj_phase = PyTuple_GetItem(tuple, 7); Py_complex py_phase = PyComplex_AsCComplex(py_obj_phase); int n = PyLong_AsLong(py_n); CHForm * state = calloc(1, sizeof(CHForm)); init_zero_CHForm(n, state); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ state->F[i] |= (((uint_bitarray_t)py_F->data[i*py_F->strides[0] + j*py_F->strides[1]]) & ONE) << j; state->G[i] |= (((uint_bitarray_t)py_G->data[i*py_G->strides[0] + j*py_G->strides[1]]) & ONE) << j; state->M[i] |= (((uint_bitarray_t)py_M->data[i*py_M->strides[0] + j*py_M->strides[1]]) & ONE) << j; } state->g1 |= (((uint_bitarray_t)py_g->data[i*py_g->strides[0]]) & ONE) << i; state->g2 |= ((((uint_bitarray_t)py_g->data[i*py_g->strides[0]]) >> 1u) & ONE) << i; state->v |= (((uint_bitarray_t)py_v->data[i*py_v->strides[0]]) & ONE) << i; state->s |= (((uint_bitarray_t)py_s->data[i*py_s->strides[0]]) & ONE) << i; } state->w = py_phase.real + I*py_phase.imag; return state; } PyObject * CHForm_to_python_tuple(CHForm * state){ const long int dimensions1[1] = {state->n}; const long int dimensions2[2] = {state->n, state->n}; PyArrayObject * F = (PyArrayObject*)PyArray_SimpleNew(2, dimensions2, PyArray_UBYTE); PyArrayObject * G = (PyArrayObject*)PyArray_SimpleNew(2, dimensions2, PyArray_UBYTE); PyArrayObject * M = (PyArrayObject*)PyArray_SimpleNew(2, dimensions2, PyArray_UBYTE); PyArrayObject * g = (PyArrayObject*)PyArray_SimpleNew(1, dimensions1, PyArray_UBYTE); PyArrayObject * v = (PyArrayObject*)PyArray_SimpleNew(1, dimensions1, PyArray_UBYTE); PyArrayObject * s = (PyArrayObject*)PyArray_SimpleNew(1, dimensions1, PyArray_UBYTE); for(int i = 0; i < state->n; i++){ for(int j = 0; j < state->n; j++){ //printf("(%d, %d)\n",i,j); F->data[i*F->strides[0] + j*F->strides[1]] = (unsigned char)((state->F[i] >> j) & ONE); G->data[i*G->strides[0] + j*G->strides[1]] = (unsigned char)((state->G[i] >> j) & ONE); M->data[i*M->strides[0] + j*M->strides[1]] = (unsigned char)((state->M[i] >> j) & ONE); } g->data[i*g->strides[0]] = 2*((state->g2 >> i) & ONE) + ((state->g1 >> i) & ONE); v->data[i*v->strides[0]] = ((state->v >> i) & ONE); s->data[i*s->strides[0]] = ((state->s >> i) & ONE); } //printf("%lf + %lf\n", creal(state->w), cimag(state->w)); Py_complex phase; phase.real = creal(state->w); phase.imag = cimag(state->w); return Py_BuildValue("iOOOOOOD", state->n, F, G, M, g, v, s, &phase); } CHForm * c_apply_gates_to_basis_state(int n, PyArrayObject * gates, PyArrayObject * controls, PyArrayObject * targets){ CHForm * state = calloc(1, sizeof(CHForm)); init_cb_CHForm(n, state); //printf("3\n"); for(int i = 0; i < gates->dimensions[0]; i++){ switch((char)gates->data[i*gates->strides[0]]) { case 'X': CXL(state, (unsigned int)controls->data[i*controls->strides[0]], (unsigned int)targets->data[i*targets->strides[0]]); break; case 'Z': CZL(state, (unsigned int)controls->data[i*controls->strides[0]], (unsigned int)targets->data[i*targets->strides[0]]); break; case 's': SL(state, (unsigned int)targets->data[i*targets->strides[0]]); break; case 'h': HL(state, (unsigned int)targets->data[i*targets->strides[0]]); break; } } return state; } /* * Given a product of the form appearing in (55) of Bravyi et al * work out the minus sign you get if you pull all the Zs to the left hand side and all the xs to the right */ unsigned int sort_pauli_string(uint n, uint_bitarray_t * x, uint_bitarray_t * z, uint_bitarray_t mask){ uint_bitarray_t t = 0; unsigned int sign = 0; for(int i = 0; i < n; i++){ if((mask >> i) & ONE){ t ^= z[i]; sign ^= parity(t & x[i]); } } return sign; } double complex measurement_overlap(CHForm * state, uint_bitarray_t x){ //compute the inner product <x | state> //where the bitstring x determines a computational basis state uint_fast64_t u = 0; // u = x F for(int i =0; i < state->n; i++){ for(int j=0; j <state->n;j++){ u ^= ((x>>j) & (state->F[j] >>i) & ONE) << i; } } if((u ^ state->s ) & (~state->v)){ return 0; } unsigned int signbit = sort_pauli_string(state->n, state->F, state->M, x); signbit ^= parity(u & state->s & state->v); unsigned int g = 0; for(int i = 0; i < state->n; i++){ if(( x >> i) &ONE ){ g += ((state->g1 >> i) & ONE) + 2*((state->g2 >> i) & ONE); } } if(signbit & ONE){ g += 2; } double complex phase = state->w; g %= 4; if(g == 1){ phase *= I; }else if(g == 2){ phase *= -1; }else if(g == 3){ phase *= -1*I; } double sqrt2 = sqrt(2.); for(int i = 0; i < state->n; i++){ if((state->v >> i) & ONE){ phase /= sqrt2; } } return phase; } void apply_z_projector(CHForm * state, int a, int q){ //apply the projector |a><a| to the qubit q where a is the least significant bit of a unsigned int k = a ^ parity(state->G[q] & (~state->v) & state->s); uint_bitarray_t t = (state->G[q] & state->v) ^ state->s; if(t == state->s){ if(k){ state->w = 0; }else{ desupersitionise(state, t, 2*k); state->w /= 2; // 2 since P = (I +- Z)/2 } } } void apply_z_projectors(CHForm * state, uint_bitarray_t a, uint_bitarray_t mask){ //for each qubit i //if mask mask_i == 1 //apply the projector |a_i><a_i| for(int i=0; i < state->n; i++){ if((mask >> i) & ONE){ unsigned int k = ((a>>i) ^ parity(state->G[i] & (~state->v) & state->s)) & ONE; uint_bitarray_t t = (state->G[i] & state->v) ^ state->s; if(t == state->s){ if(k){ state->w = 0; } }else{ desupersitionise(state, t, (2*k) % 4u); state->w /= 2; // 2 since P = (I +- Z)/2 } } } } CHForm * postselect_and_reduce(CHForm * state, uint_bitarray_t a, uint_bitarray_t mask){ //handle the case where we're actually doing a full inner product separately if(popcount(mask) == state->n){ state->w = measurement_overlap(state, a); if(state->n > 0){ free(state->F); free(state->G); free(state->M); state->F = NULL; state->G = NULL; state->M = NULL; } state->n = 0; return state; } for(unsigned int i = 0; i < state->n; i++){ if(((a & mask) >> i) & ONE){ XL(state, i); } } apply_z_projectors(state, 0u, mask); //now we arrange it so there is at most one qubit with s_i = 1, v_i = 0 //first try to find a qubit that isn't being deleted with s_i = 1, v_i = 0 if(((~state->v) & state->s) != 0){ //inside this block we know there are some qubits with s_i = 1, v_i = 0 int control_qubit = -1; for(int i = 0; i < state->n; i++){ if((((~mask) & state->s & (~state->v)) >> i) & ONE){ control_qubit = i; break; } } //we want to insert 4 cnots to swap an s_i = 1 onto a qubit with v_i = mask_i = 0 if(control_qubit < 0){ //first find a mask qubit with s_i = 1, v_i = 0 //and a non-mask qubit with s_i = 0, v_i = 0 int mask_qubit = -1; int non_mask = -1; for(int i = 0; i < state->n; i++){ if(((state->s & (~state->v)) >> i) & ONE){ mask_qubit = i; } if((((~mask) & (~state->s) & (~state->v)) >> i) & ONE){ non_mask = i; } } //insert this which is the identity //CX(mask_qubit, non_mask) CX(non_mask, mask_qubit) CX(non_mask, mask_qubit) CX(mask_qubit, non_mask) //multiply the left hand two onto U_C //and the right ones onto U_H |s> //where they will swap the which qubit has s = 0 and which has s = 1 CXR(state, mask_qubit, non_mask); CXR(state, non_mask, mask_qubit); state->s |= (ONE << non_mask); state->s &= (~(ONE << mask_qubit)); control_qubit = non_mask; } //so now we have a control qubit and (possibly) some others with s_i = 1, v_i = 0 //we go through and switch the s_i's to zero and insert cnots controlled on our control for(int i = 0; i < state->n; i++){ if(i != control_qubit){ if((((~state->v) & state->s) >> i) & ONE){ CXR(state, control_qubit, i); } } } state->s ^= (state->s & (~state->v)); state->s |= (ONE << control_qubit); } //at this point as many qubits are "free" as possible //i.e. there is at most one qubit with s_i = 1, v_i = 0 //and this control qubit is /not/ one of our mask qubits //we also want to ensure that all of our mask qubits have s_i = v_i = 0 //we know already at this point that if they have v_i = 0 they have s_i = 0 //so we just swap those of them which have v_i = 1 with a qubit that has v_i = s_i = 0 int swapCandidateIndex = 0; for(int i = 0; i < state->n; i++){ if(((mask & state->v) >> i) & ONE){ for(; ((mask | state->s | state->v)>>swapCandidateIndex) & ONE; swapCandidateIndex++){}; SWAPR(state, i, swapCandidateIndex); state->s |= ((state->s >> i) & ONE) << swapCandidateIndex; state->v |= ((state->v >> i) & ONE) << swapCandidateIndex; state->s &= (~(ONE << i)); state->v &= (~(ONE << i)); } } //printf("confirmation!\n"); //printBits(mask & state->s & state->v, state->n);printf("\n"); //at this point all our mask qubits have s_i = v_i = 0 //and there is at most one qubit with s_i=0, v_i = 1 //now we ensure that for each mask qubit q we have G[q][q] == 1 //and use that G is the inverse of F^T //to make each column we want to throw away "simple" //i.e. have a single 1 on the diagonal and zeros elsewhere uint_bitarray_t marked = 0; for(int q = 0; q < state->n; q++){ if((mask >> q) & ONE){ //q is a masked qubit if(((state->G[q] >> q) & ONE) == 0){ for(int i = 0; i < state->n; i++){ if(((state->G[q] & (~marked)) >> i) & ONE){ SWAPR(state,q,i); break; } } } for(int i=0; i < state->n; i++){ if((i != q) && ((state->G[q] >> i) & ONE)){ CXR(state, i, q); } } marked |= (ONE<<q); } } //now we want to delete the masked qubits int shift = 0; int i = 0; //uint_bitarray_t i_bit_mask = 0u; //printBits(mask, state->n); printf("\n"); /* printf("c mats\n"); */ /* for(int q = 0; q < state->n; q++){ */ /* printBits(state->F[q], state->n); */ /* printf(" "); */ /* printBits(state->G[q], state->n); */ /* printf(" "); */ /* printBits(state->M[q], state->n); */ /* printf(" "); */ /* printf("\n"); */ /* } */ //delete rows for(; i+shift < state->n; i++){ while(((mask>>(i+shift)) & ONE)){ shift += 1; } if(i+shift < state->n){ state->F[i] = state->F[i+shift]; state->G[i] = state->G[i+shift]; state->M[i] = state->M[i+shift]; for(int j = 0; j < state->n; j++){ state->F[j] = (state->F[j] ^ (state->F[j] & (ONE<<i))) | ((state->F[j] >> shift) & (ONE <<i)); state->G[j] = (state->G[j] ^ (state->G[j] & (ONE<<i))) | ((state->G[j] >> shift) & (ONE <<i)); state->M[j] = (state->M[j] ^ (state->M[j] & (ONE<<i))) | ((state->M[j] >> shift) & (ONE <<i)); } state->v = (state->v ^ (state->v & (ONE<<i))) | ((state->v >> shift) & (ONE <<i)); state->s = (state->s ^ (state->s & (ONE<<i))) | ((state->s >> shift) & (ONE <<i)); state->g1 = (state->g1 ^ (state->g1 & (ONE<<i))) | ((state->g1 >> shift) & (ONE <<i)); state->g2 = (state->g2 ^ (state->g2 & (ONE<<i))) | ((state->g2 >> shift) & (ONE <<i)); } } state->n = state->n-shift; state->F = realloc(state->F, state->n * sizeof(uint_bitarray_t)); state->G = realloc(state->G, state->n * sizeof(uint_bitarray_t)); state->M = realloc(state->M, state->n * sizeof(uint_bitarray_t)); uint_bitarray_t m = 0u; for(size_t i = 0; i < state->n; i++){ m |= (ONE << i); } for(size_t i = 0; i < state->n; i++){ state->F[i] &= m; state->G[i] &= m; state->M[i] &= m; } state->g1 &= m; state->g2 &= m; state->v &= m; state->s &= m; return state; } PyObject * apply_gates_to_basis_state_project_and_reduce(PyObject* self, PyObject* args){ PyArrayObject * gates; PyArrayObject * controls; PyArrayObject * targets; PyArrayObject * a; // project |a_i><a_i| onto qubit i iff mask_i == 1 PyArrayObject * mask; int n; //printf("1\n"); if (!PyArg_ParseTuple(args, "iO!O!O!O!O!", &n, &PyArray_Type, &gates, &PyArray_Type, &controls, &PyArray_Type, &targets, &PyArray_Type, &a, &PyArray_Type, &mask )){ return NULL; } CHForm * state = c_apply_gates_to_basis_state(n, gates, controls, targets); uint_bitarray_t bitA = 0; uint_bitarray_t bitMask = 0; for(int i = 0; i < n; i++){ if((char)a->data[i*a->strides[0]]){ bitA |= (ONE << i); } if((char)mask->data[i*mask->strides[0]]){ bitMask |= (ONE << i); } } postselect_and_reduce(state, bitA, bitMask); PyObject * tuple = CHForm_to_python_tuple(state); dealocate_state(state); return tuple; } //equatorial matrices define equatorial states //they are symmetric matrices with binary off diagonal elements //and mod 4 diagonal elements typedef struct equatorial_matrix{ int n; uint_bitarray_t * mat; uint_bitarray_t d1; uint_bitarray_t d2; } equatorial_matrix_t; void init_zero_equatorial_matrix(equatorial_matrix_t * matrix, int n){ matrix->n = n; matrix->mat = (uint_bitarray_t*)calloc(n, sizeof(uint_bitarray_t)); matrix->d1 = 0u; matrix->d2 = 0u; } void init_random_equatorial_matrix(equatorial_matrix_t * matrix, int n){ matrix->n = n; matrix->mat = (uint_bitarray_t*)calloc(n, sizeof(uint_bitarray_t)); uint_bitarray_t mask = 0u; for(int i = 0; i < n; i++){ mask |= (ONE<<i); } for(int i = 0; i < n; i++){ matrix->mat[i] = (bitarray_rand()) & mask; } for(int i = 0; i < n; i++){ for(int j = 0; j < i; j++){ matrix->mat[i] &= ~(ONE << j);//(((matrix->mat[j]>>i) &ONE) <<j); matrix->mat[i] |= (((matrix->mat[j] >> i) & ONE) <<j); } matrix->mat[i] &= ~(ONE << i); } matrix->d1 = bitarray_rand() & mask; matrix->d2 = bitarray_rand() & mask; } void dealocate_equatorial_matrix(equatorial_matrix_t * matrix){ matrix->n = 0; free(matrix->mat); } double complex equatorial_inner_product(CHForm* state, equatorial_matrix_t equatorial_state){ if(state->n == 0){ return conj(state->w); } //we store A+J in AJ uint_bitarray_t * AJ = calloc(state->n, sizeof(uint_bitarray_t)); for(size_t i = 0; i < state->n; i++){ for(size_t j = 0; j < i; j++){ uint_bitarray_t bit = parity(state->M[i] & state->F[j]) & ONE; AJ[i] |= (bit << j); AJ[j] |= (bit << i); } } //add A to J for(size_t i = 0; i < state->n; i++){ AJ[i] ^= equatorial_state.mat[i]; AJ[i] &= ~(ONE<<i); } //now we need to sort out the diagonal uint_bitarray_t AJd1 = equatorial_state.d1; uint_bitarray_t AJd2 = equatorial_state.d2; AJd2 ^= (AJd1 & state->g1); AJd1 ^= state->g1; AJd2 ^= state->g2; uint_bitarray_t * GT = calloc(state->n, sizeof(uint_bitarray_t)); // store transpose of G for(size_t i = 0; i < state->n; i++){ for(size_t j = 0; j < state->n; j++){ GT[j] |= ((state->G[i] >> j) & ONE) << i; } } //now we want to compute (A G)^T = G^T A^T //this is because doing X Y^T is generally faster than doing XY //since we can do the row / row dot products with popcount(x & y) //we need to know the value of G^T A^T mod-4 so we can work out what the diagonal of G^T A G should be //so we store it in two binary matrices X and Y such that G^T A^T = 2X + Y uint_bitarray_t * X = calloc(state->n, sizeof(uint_bitarray_t)); uint_bitarray_t * Y = calloc(state->n, sizeof(uint_bitarray_t)); for(size_t i = 0; i < state->n; i++){ for(size_t j = 0; j < state->n; j++){ uint_bitarray_t pc = (popcount(GT[i] & AJ[j]) % 4u); X[i] |= ((pc>>1) & ONE) << j; Y[i] |= ((pc) & ONE) << j; } } //add the contribution fron G^T D for(size_t i = 0; i < state->n; i++){ X[i] ^= (Y[i] & GT[i] & AJd1); // carry if both bits are 1 Y[i] ^= (GT[i] & AJd1); X[i] ^= (GT[i] & AJd2); } //now we compute K = G^T (A G) = G^T (G^T A^T)^T //we store K as a full symmetric matric of bits //we store the even part of the diagonal in bitarray bitKd2; //since the diagonal is the only bit we need mod-4 //in other words K = bitK + 2*diag(bitKd2) uint_bitarray_t * bitK = calloc(state->n, sizeof(uint_bitarray_t)); uint_bitarray_t bitKd2 = 0; for(size_t i = 0; i < state->n; i++){ for(size_t j = 0; j < i; j++){ //symmetric uint_bitarray_t pb = parity(GT[i] & Y[j]) & ONE; bitK[i] |= pb << j; bitK[j] |= pb << i; } //now we need to work out the diagonal //slightly more care is needed here as we care about the diagonal mod-4 uint_bitarray_t pc = popcount(GT[i] & Y[i]); bitK[i] |= (pc & ONE) << i; bitKd2 |= (((pc>>1) & ONE) ^ (parity(GT[i] & X[i]) & ONE)) << i; } free(X); free(Y); unsigned int n = popcount(state->v); uint_bitarray_t sK = 0; unsigned int sKs = 0; for(size_t a = 0; a < state->n; a++){ unsigned int pc = popcount(state->s & bitK[a]) % 4u; sK |= (pc & ONE) << a; sKs += pc * ((state->s >> a) & ONE); } sKs += 2*popcount(bitKd2 & state->s); //add 2*diag(s + sK) onto K bitKd2 ^= (state->s ^ sK); double complex prefactor = pow(0.5, (state->n+n)/2.); //printf("c sKs: %d, sKs2: %u\n", popcount(state->s & sK), sKs); unsigned int d = (sKs + 2 * popcount(state->s & state->v)) % 4u; if(d == 1){ prefactor *= I; }else if(d == 2){ prefactor *= -1.; }else if(d == 3){ prefactor *= -1.*I; } uint_bitarray_t k = 0; uint_bitarray_t L = 0; uint_bitarray_t * M = calloc(n+1, sizeof(uint_bitarray_t)); int fill_count_a = 0; for(int a = 0; (a<state->n); a++){ if((state->v >> a) & ONE){ k |= ((bitK[a] >> a) & ONE) << fill_count_a; L |= ((bitKd2 >> a) & ONE) << fill_count_a; fill_count_a += 1; } } fill_count_a = 0; int fill_count_b = 0; for(int a = 0; (a<state->n); a++){ if((state->v >> a) & ONE){ for(int b = 0; (b<a); b++){ if((state->v >> b) & ONE){ M[fill_count_b] |= (((bitK[b] >> a) & ONE) ^ ((k >> fill_count_a) & (k >> fill_count_b) & ONE)) << fill_count_a; fill_count_b += 1; } } fill_count_a += 1; fill_count_b = 0; } } M[n] = k; n +=1; //at this point we only need M and l //so free everything else free(bitK); free(AJ); free(GT); double re=0, im=0; int killed = 0; int exponent_of_2 = 0; bool exponent_of_minus_1 = false; bool last_element_asymetric = false; bool mu1_consts = false; bool mu2_consts = false; uint_fast64_t mask = 0; for(uint i = 0; i < n; i++){ mask |= (ONE << i); } //printf("eb\n"); while(true){ uint r=0, c=0; bool found = false; for(uint i = 0; i < n && !found; i++){ for(uint j = 0; j < i && !found; j++){ if(((M[i] >> j) & ONE) != ((M[j] >> i) & ONE)){ r=i; c=j; found = true; } } } if(!found){ //this is trivial apparently uint_bitarray_t diag = 0; for(uint i=0;i<n;i++){ diag ^= ((M[i] >> i) & ONE) << i; } if(last_element_asymetric){ if((diag & mask) == (L&mask)){ //printf("c1\n"); double signR = exponent_of_minus_1 ? (-1.) : 1.; bool new_exponent_of_minus_1 = (exponent_of_minus_1 ^ mu2_consts); double signI = new_exponent_of_minus_1 ? (-1.) : 1.; re = pow(2., exponent_of_2 + n - killed)*signR; im = pow(2., exponent_of_2 + n - killed)*signI; break; }else{ re = 0.; im = 0.; break; } }else{ if( ((diag & (~(ONE<<(n-1)))) & mask) == ((L & (~(ONE<<(n-1)))) & mask)){ if( ((diag & (ONE << (n-1)))&mask) == ((L & (ONE << (n-1)))&mask)){ double signR = exponent_of_minus_1 ? (-1.) : 1.; re = signR * pow(2., exponent_of_2+n-killed); im = 0; break; }else{ re = 0; double signI = exponent_of_minus_1 ? (-1.) : 1.; im = signI * pow(2., exponent_of_2+n-killed); break; } }else{ re = 0; im = 0; break; } } }else{ if(r+1 == n){ last_element_asymetric = true; } killed += 2; uint_fast64_t m1 = M[r]; uint_fast64_t m2 = M[c]; for(uint i=0; i<n;i++){ m1 ^= (((M[i] >> r) & ONE) << i); m2 ^= (((M[i] >> c) & ONE) << i); } m1 &= (~(ONE << r)); m1 &= (~(ONE << c)); m2 &= (~(ONE << r)); m2 &= (~(ONE << c)); mu1_consts = ((L>>r) & ONE) ^ ((M[r]>>r) & ONE); mu2_consts = ((L>>c) & ONE) ^ ((M[c]>>c) & ONE); M[r] = 0; M[c] = 0; for(uint i=0; i<n;i++){ M[i] &= ~(ONE << r); M[i] &= ~(ONE << c); } L &= (~(ONE << r)); L &= (~(ONE << c)); exponent_of_2 += 1; exponent_of_minus_1 ^= (mu1_consts & mu2_consts); for(uint i=0;i<n;i++){ if((m1>>i) & ONE){ M[i] ^= m2; } } if(mu1_consts){ L ^= m2; } if(mu2_consts){ L ^= m1; } } } free(M); //printf("en\n"); return conj(state->w) * prefactor * (re +im*I)/2; } double complex equatorial_inner_product_no_alloc(CHForm* state, equatorial_matrix_t equatorial_state, uint_bitarray_t * AJ, uint_bitarray_t * GT, uint_bitarray_t * X, uint_bitarray_t * Y, uint_bitarray_t * bitK, uint_bitarray_t * M){ if(state->n == 0){ return conj(state->w); } //we store A+J in AJ for(size_t i = 0; i < state->n; i++){ for(size_t j = 0; j < i; j++){ uint_bitarray_t bit = parity(state->M[i] & state->F[j]) & ONE; AJ[i] |= (bit << j); AJ[j] |= (bit << i); } } //add A to J for(size_t i = 0; i < state->n; i++){ AJ[i] ^= equatorial_state.mat[i]; AJ[i] &= ~(ONE<<i); } //now we need to sort out the diagonal uint_bitarray_t AJd1 = equatorial_state.d1; uint_bitarray_t AJd2 = equatorial_state.d2; AJd2 ^= (AJd1 & state->g1); AJd1 ^= state->g1; AJd2 ^= state->g2; //now we want to compute (A G)^T = G^T A^T //this is because doing X Y^T is generally faster than doing XY //since we can do the row / row dot products with popcount(x & y) //we need to know the value of G^T A^T mod-4 so we can work out what the diagonal of G^T A G should be //so we store it in two binary matrices X and Y such that G^T A^T = 2X + Y for(size_t i = 0; i < state->n; i++){ for(size_t j = 0; j < state->n; j++){ uint_bitarray_t pc = (popcount(GT[i] & AJ[j]) % 4u); X[i] |= ((pc>>1) & ONE) << j; Y[i] |= ((pc) & ONE) << j; } } //add the contribution fron G^T D for(size_t i = 0; i < state->n; i++){ X[i] ^= (Y[i] & GT[i] & AJd1); // carry if both bits are 1 Y[i] ^= (GT[i] & AJd1); X[i] ^= (GT[i] & AJd2); } //now we compute K = G^T (A G) = G^T (G^T A^T)^T //we store K as a full symmetric matric of bits //we store the even part of the diagonal in bitarray bitKd2; //since the diagonal is the only bit we need mod-4 //in other words K = bitK + 2*diag(bitKd2) uint_bitarray_t bitKd2 = 0; for(size_t i = 0; i < state->n; i++){ for(size_t j = 0; j < i; j++){ //symmetric uint_bitarray_t pb = parity(GT[i] & Y[j]) & ONE; bitK[i] |= pb << j; bitK[j] |= pb << i; } //now we need to work out the diagonal //slightly more care is needed here as we care about the diagonal mod-4 uint_bitarray_t pc = popcount(GT[i] & Y[i]); bitK[i] |= (pc & ONE) << i; bitKd2 |= (((pc>>1) & ONE) ^ (parity(GT[i] & X[i]) & ONE)) << i; } //free(X); //free(Y); memset(X, 0, sizeof(uint_bitarray_t)*state->n); memset(Y, 0, sizeof(uint_bitarray_t)*state->n); unsigned int n = popcount(state->v); uint_bitarray_t sK = 0; unsigned int sKs = 0; for(size_t a = 0; a < state->n; a++){ unsigned int pc = popcount(state->s & bitK[a]) % 4u; sK |= (pc & ONE) << a; sKs += pc * ((state->s >> a) & ONE); } sKs += 2*popcount(bitKd2 & state->s); //add 2*diag(s + sK) onto K bitKd2 ^= (state->s ^ sK); double complex prefactor = pow(0.5, (state->n+n)/2.); //printf("c sKs: %d, sKs2: %u\n", popcount(state->s & sK), sKs); unsigned int d = (sKs + 2 * popcount(state->s & state->v)) % 4u; if(d == 1){ prefactor *= I; }else if(d == 2){ prefactor *= -1.; }else if(d == 3){ prefactor *= -1.*I; } uint_bitarray_t k = 0; uint_bitarray_t L = 0; //uint_bitarray_t * M = calloc(n+1, sizeof(uint_bitarray_t)); int fill_count_a = 0; for(int a = 0; (a<state->n); a++){ if((state->v >> a) & ONE){ k |= ((bitK[a] >> a) & ONE) << fill_count_a; L |= ((bitKd2 >> a) & ONE) << fill_count_a; fill_count_a += 1; } } fill_count_a = 0; int fill_count_b = 0; for(int a = 0; (a<state->n); a++){ if((state->v >> a) & ONE){ for(int b = 0; (b<a); b++){ if((state->v >> b) & ONE){ M[fill_count_b] |= (((bitK[b] >> a) & ONE) ^ ((k >> fill_count_a) & (k >> fill_count_b) & ONE)) << fill_count_a; fill_count_b += 1; } } fill_count_a += 1; fill_count_b = 0; } } M[n] = k; n +=1; //at this point we only need M and l //so free everything else memset(bitK, 0, sizeof(uint_bitarray_t)*state->n); memset(AJ, 0, sizeof(uint_bitarray_t)*state->n); //memset(GT, 0, sizeof(uint_bitarray_t)*state->n); //free(bitK); //free(AJ); //free(GT); double re=0, im=0; int killed = 0; int exponent_of_2 = 0; bool exponent_of_minus_1 = false; bool last_element_asymetric = false; bool mu1_consts = false; bool mu2_consts = false; uint_bitarray_t mask = 0; for(uint i = 0; i < n; i++){ mask |= (ONE << i); } //printf("eb\n"); while(true){ uint r=0, c=0; bool found = false; for(uint i = 0; i < n && !found; i++){ for(uint j = 0; j < i && !found; j++){ if(((M[i] >> j) & ONE) != ((M[j] >> i) & ONE)){ r=i; c=j; found = true; } } } if(!found){ //this is trivial apparently uint_bitarray_t diag = 0; for(uint i=0;i<n;i++){ diag ^= ((M[i] >> i) & ONE) << i; } if(last_element_asymetric){ if((diag & mask) == (L&mask)){ //printf("c1\n"); double signR = exponent_of_minus_1 ? (-1.) : 1.; bool new_exponent_of_minus_1 = (exponent_of_minus_1 ^ mu2_consts); double signI = new_exponent_of_minus_1 ? (-1.) : 1.; re = pow(2., exponent_of_2 + n - killed)*signR; im = pow(2., exponent_of_2 + n - killed)*signI; break; }else{ re = 0.; im = 0.; break; } }else{ if( ((diag & (~(ONE<<(n-1)))) & mask) == ((L & (~(ONE<<(n-1)))) & mask)){ if( ((diag & (ONE << (n-1)))&mask) == ((L & (ONE << (n-1)))&mask)){ double signR = exponent_of_minus_1 ? (-1.) : 1.; re = signR * pow(2., exponent_of_2+n-killed); im = 0; break; }else{ re = 0; double signI = exponent_of_minus_1 ? (-1.) : 1.; im = signI * pow(2., exponent_of_2+n-killed); break; } }else{ re = 0; im = 0; break; } } }else{ //swap row r and column r to row killed and column killed //swap row c and column c to row killed+1 and column killed+1 uint_bitarray_t scratch_space = M[c]; if(c != killed){ M[c] = M[killed]; M[killed] = scratch_space; for(uint i=0; i < n;i++){ M[i] ^= (((M[i] >> c) & ONE) << killed); M[i] ^= (((M[i] >> killed) & ONE) << c); M[i] ^= (((M[i] >> c) & ONE) << killed); } } if(r != (killed+1)){ scratch_space = M[r]; M[r] = M[killed+1]; M[killed+1] = scratch_space; for(uint i=0; i < n;i++){ M[i] ^= (((M[i] >> r) & ONE) << (killed+1)); M[i] ^= (((M[i] >> (killed+1)) & ONE) << r); M[i] ^= (((M[i] >> r) & ONE) << (killed+1)); } } if(r+1 == n){ last_element_asymetric = true; } c = killed; r = killed+1; killed += 2; uint_bitarray_t m1 = M[r]; uint_bitarray_t m2 = M[c]; for(uint i=0; i<n;i++){ m1 ^= (((M[i] >> r) & ONE) << i); m2 ^= (((M[i] >> c) & ONE) << i); } m1 &= (~(ONE << r)); m1 &= (~(ONE << c)); m2 &= (~(ONE << r)); m2 &= (~(ONE << c)); mu1_consts = ((L>>r) & ONE) ^ ((M[r]>>r) & ONE); mu2_consts = ((L>>c) & ONE) ^ ((M[c]>>c) & ONE); L &= (~(ONE << r)); L &= (~(ONE << c)); exponent_of_2 += 1; exponent_of_minus_1 ^= (mu1_consts & mu2_consts); for(uint i=0;i<n;i++){ if((m1>>i) & ONE){ M[i] ^= m2; } } if(mu1_consts){ L ^= m2; } if(mu2_consts){ L ^= m1; } M[r] = 0; M[c] = 0; for(uint i=0; i<n;i++){ M[i] &= ~(ONE << r); M[i] &= ~(ONE << c); } } } memset(M, 0, sizeof(uint_bitarray_t)*(state->n+1)); //free(M); //printf("en\n"); return conj(state->w) * prefactor * (re +im*I)/2; } double complex equatorial_inner_product2(CHForm* state, uint_bitarray_t * A, uint_bitarray_t * GT, equatorial_matrix_t equatorial_state){ //we store A+J in AJ uint_bitarray_t * AJ = calloc(state->n, sizeof(uint_bitarray_t)); //add A to J for(size_t i = 0; i < state->n; i++){ AJ[i] |= (A[i] ^ equatorial_state.mat[i]); } //now we need to sort out the diagonal uint_bitarray_t AJd1 = equatorial_state.d1; uint_bitarray_t AJd2 = equatorial_state.d2; AJd2 ^= (AJd1 & state->g1); AJd1 ^= state->g1; AJd2 ^= state->g2; //now we want to compute (A G)^T = G^T A^T //this is because doing X Y^T is generally faster than doing XY //since we can do the row / row dot products with popcount(x & y) //we need to know the value of G^T A^T mod-4 so we can work out what the diagonal of G^T A G should be //so we store it in two binary matrices X and Y such that G^T A^T = 2X + Y uint_bitarray_t * X = calloc(state->n, sizeof(uint_bitarray_t)); uint_bitarray_t * Y = calloc(state->n, sizeof(uint_bitarray_t)); for(size_t i = 0; i < state->n; i++){ for(size_t j = 0; j < state->n; j++){ uint_bitarray_t pc = (popcount(GT[i] & AJ[j]) % 4u); X[i] |= ((pc>>1) & ONE) << j; Y[i] |= ((pc) & ONE) << j; } } //add the contribution fron G^T D for(size_t i = 0; i < state->n; i++){ X[i] ^= (Y[i] & GT[i] & AJd1); // carry if both bits are 1 Y[i] ^= (GT[i] & AJd1); X[i] ^= (GT[i] & AJd2); } //now we compute K = G^T (A G) = G^T (G^T A^T)^T //we store K as a full symmetric matric of bits //we store the even part of the diagonal in bitarray bitKd2; //since the diagonal is the only bit we need mod-4 //in other words K = bitK + 2*diag(bitKd2) uint_bitarray_t * bitK = calloc(state->n, sizeof(uint_bitarray_t)); uint_bitarray_t bitKd2 = 0; for(size_t i = 0; i < state->n; i++){ for(size_t j = 0; j < i; j++){ //symmetric uint_bitarray_t pb = parity(GT[i] & Y[j]) & ONE; bitK[i] |= pb << j; bitK[j] |= pb << i; } //now we need to work out the diagonal //slightly more care is needed here as we care about the diagonal mod-4 uint_bitarray_t pc = popcount(GT[i] & Y[i]); bitK[i] |= (pc & ONE) << i; bitKd2 |= (((pc>>1) & ONE) ^ (parity(GT[i] & X[i]) & ONE)) << i; } free(X); free(Y); unsigned int n = popcount(state->v); uint_bitarray_t sK = 0; unsigned int sKs = 0; for(size_t a = 0; a < state->n; a++){ unsigned int pc = popcount(state->s & bitK[a]) % 4u; sK |= (pc & ONE) << a; sKs += pc * ((state->s >> a) & ONE); } sKs += 2*popcount(bitKd2 & state->s); //add 2*diag(s + sK) onto K bitKd2 ^= (state->s ^ sK); double complex prefactor = pow(0.5, (state->n+n)/2.); //printf("c sKs: %d, sKs2: %u\n", popcount(state->s & sK), sKs); unsigned int d = (sKs + 2 * popcount(state->s & state->v)) % 4u; if(d == 1){ prefactor *= I; }else if(d == 2){ prefactor *= -1.; }else if(d == 3){ prefactor *= -1.*I; } uint_bitarray_t k = 0; uint_bitarray_t L = 0; uint_bitarray_t * M = calloc(n+1, sizeof(uint_bitarray_t)); int fill_count_a = 0; for(int a = 0; (a<state->n); a++){ if((state->v >> a) & ONE){ k |= ((bitK[a] >> a) & ONE) << fill_count_a; L |= ((bitKd2 >> a) & ONE) << fill_count_a; fill_count_a += 1; } } fill_count_a = 0; int fill_count_b = 0; for(int a = 0; (a<state->n); a++){ if((state->v >> a) & ONE){ for(int b = 0; (b<a); b++){ if((state->v >> b) & ONE){ M[fill_count_b] |= (((bitK[b] >> a) & ONE) ^ ((k >> fill_count_a) & (k >> fill_count_b) & ONE)) << fill_count_a; fill_count_b += 1; } } fill_count_a += 1; fill_count_b = 0; } } M[n] = k; n +=1; //at this point we only need M and l //so free everything else free(bitK); free(AJ); //free(GT); double re=0, im=0; int killed = 0; int exponent_of_2 = 0; bool exponent_of_minus_1 = false; bool last_element_asymetric = false; bool mu1_consts = false; bool mu2_consts = false; uint_fast64_t mask = 0; for(uint i = 0; i < n; i++){ mask |= (ONE << i); } //printf("eb\n"); while(true){ uint r=0, c=0; bool found = false; for(uint i = 0; i < n && !found; i++){ for(uint j = 0; j < i && !found; j++){ if(((M[i] >> j) & ONE) != ((M[j] >> i) & ONE)){ r=i; c=j; found = true; } } } if(!found){ //this is trivial apparently uint_bitarray_t diag = 0; for(uint i=0;i<n;i++){ diag ^= ((M[i] >> i) & ONE) << i; } if(last_element_asymetric){ if((diag & mask) == (L&mask)){ //printf("c1\n"); double signR = exponent_of_minus_1 ? (-1.) : 1.; bool new_exponent_of_minus_1 = (exponent_of_minus_1 ^ mu2_consts); double signI = new_exponent_of_minus_1 ? (-1.) : 1.; re = pow(2., exponent_of_2 + n - killed)*signR; im = pow(2., exponent_of_2 + n - killed)*signI; break; }else{ re = 0.; im = 0.; break; } }else{ if( ((diag & (~(ONE<<(n-1)))) & mask) == ((L & (~(ONE<<(n-1)))) & mask)){ if( ((diag & (ONE << (n-1)))&mask) == ((L & (ONE << (n-1)))&mask)){ double signR = exponent_of_minus_1 ? (-1.) : 1.; re = signR * pow(2., exponent_of_2+n-killed); im = 0; break; }else{ re = 0; double signI = exponent_of_minus_1 ? (-1.) : 1.; im = signI * pow(2., exponent_of_2+n-killed); break; } }else{ re = 0; im = 0; break; } } }else{ if(r+1 == n){ last_element_asymetric = true; } killed += 2; uint_fast64_t m1 = M[r]; uint_fast64_t m2 = M[c]; for(uint i=0; i<n;i++){ m1 ^= (((M[i] >> r) & ONE) << i); m2 ^= (((M[i] >> c) & ONE) << i); } m1 &= (~(ONE << r)); m1 &= (~(ONE << c)); m2 &= (~(ONE << r)); m2 &= (~(ONE << c)); mu1_consts = ((L>>r) & ONE) ^ ((M[r]>>r) & ONE); mu2_consts = ((L>>c) & ONE) ^ ((M[c]>>c) & ONE); M[r] = 0; M[c] = 0; for(uint i=0; i<n;i++){ M[i] &= ~(ONE << r); M[i] &= ~(ONE << c); } L &= (~(ONE << r)); L &= (~(ONE << c)); exponent_of_2 += 1; exponent_of_minus_1 ^= (mu1_consts & mu2_consts); for(uint i=0;i<n;i++){ if((m1>>i) & ONE){ M[i] ^= m2; } } if(mu1_consts){ L ^= m2; } if(mu2_consts){ L ^= m1; } } } free(M); //printf("en\n"); return conj(state->w) * prefactor * (re +im*I)/2; } static void partial_equatorial_inner_product(CHForm* state, equatorial_matrix_t equatorial_state, uint_bitarray_t mask){ int stateI = 0; int stateJ = 0; for(int i = 0; i < equatorial_state.n; i++){ while((((mask >> stateI) & ONE) == 0) && (stateI < state->n)){ stateI += 1; } //printf("%u, %u\n", (unsigned int)((equatorial_state.d1 >> i) & ONE) , (unsigned int)((equatorial_state.d2 >> i) & ONE)); if(stateI < state->n){ for(int k = 0; k < 4-((((equatorial_state.d1 >> i) & ONE) + 2*((equatorial_state.d2 >> i) & ONE))%4); k++){ SL(state, stateI); } for(int j=0; j < i; j++){ while((((mask >> stateJ) & ONE) == 0) && (stateJ < state->n)){ stateJ += 1; } if(stateJ < state->n){ if((equatorial_state.mat[i] >> j) & ONE){ CZL(state, stateI, stateJ); } stateJ += 1; } } stateI += 1; } stateJ = 0; } stateI = 0; for(int i = 0; i < equatorial_state.n; i++){ while((((mask >> stateI) & ONE) == 0) && (stateI < state->n)){ stateI += 1; } if(stateI < state->n){ HL(state, stateI); stateI += 1; } } postselect_and_reduce(state, 0u, mask); } double complex equatorial_inner_product3(CHForm* state, equatorial_matrix_t equatorial_state){ CHForm copy = copy_CHForm(state); uint_bitarray_t mask = 0u; for(int i = 0; i < equatorial_state.n; i++){ mask |= (ONE << i); for(int j = 0; j < i; j++){ if((equatorial_state.mat[i] >> j) & ONE){ CZL(&copy, i, j); } } if((equatorial_state.d1 >> i) & ONE){ SL(&copy, i); } if((equatorial_state.d2 >> i) & ONE){ SL(&copy, i); SL(&copy, i); } HL(&copy, i); } //now we are attempting to compute w <0| UC UH |s> = w<0|UH|s> //int v0s0 = popcount(mask & (~copy.v) & (~copy.s)); int v0s1 = popcount(mask & (~copy.v) & ( copy.s)); int v1s0 = popcount(mask & ( copy.v) & (~copy.s)); int v1s1 = popcount(mask & ( copy.v) & ( copy.s)); if(v0s1 > 0){ dealocate_state(&copy); return 0.; } if(v1s1 % 2 == 1){ copy.w *= -1; } double complex val = copy.w * cpowl(1./sqrt(2), v1s0 + v1s1); dealocate_state(&copy); return val; } static PyObject * magic_sample_1(PyObject* self, PyObject* args){ PyArrayObject * gates; PyArrayObject * controls; PyArrayObject * targets; PyArrayObject * a; // project |a_i><a_i| onto qubit i iff mask_i == 1 PyArrayObject * mask; int n; int magic_samples; int equatorial_samples; unsigned int seed; //printf("1\n"); if (!PyArg_ParseTuple(args, "iiiiO!O!O!O!O!", &n, &magic_samples, &equatorial_samples, &seed, &PyArray_Type, &gates, &PyArray_Type, &controls, &PyArray_Type, &targets, &PyArray_Type, &a, &PyArray_Type, &mask )){ return NULL; } srand(seed); //gatetize all the t gates int t = 0; for(int i = 0; i < gates->dimensions[0]; i++){ if(((char)gates->data[i*gates->strides[0]]) == 't'){ gates->data[i*gates->strides[0]] = 'X'; controls->data[i*controls->strides[0]] = (unsigned char)targets->data[i*targets->strides[0]]; targets->data[i*targets->strides[0]] = (unsigned char)(n + t); t += 1; } } //printf("c1 t = %d\n", t); //now we do the Clifford evolution "precomputation" CHForm * evolved_state = c_apply_gates_to_basis_state(n+t, gates, controls, targets); //now we project onto the measurement outcomes for the w qubits //and throw away those qubits //leaving us with an n+t-w qubit state uint_bitarray_t bitA = 0; uint_bitarray_t bitMask = 0; for(int i = 0; i < n; i++){ if((char)a->data[i*a->strides[0]]){ bitA |= (ONE << i); } if((char)mask->data[i*mask->strides[0]]){ bitMask |= (ONE << i); } } postselect_and_reduce(evolved_state, bitA, bitMask); //printf("c1 after postselection\n"); //print_CHForm(evolved_state); //at this point we want to generate a list of length equatorial_samples //containing n - w - qubit equatorial states //ie. (n-w) x (n-w) binary symmetric matrices equatorial_matrix_t * equatorial_matrices = calloc(equatorial_samples, sizeof(equatorial_matrix_t)); for(int i = 0; i < equatorial_samples; i++){ init_random_equatorial_matrix(&(equatorial_matrices[i]), evolved_state->n - t); } uint_bitarray_t magic_mask = 0u; int w = evolved_state->n - t; //printf("w = %d\n", w); for(int i = evolved_state->n - t; i < evolved_state->n; i++){ magic_mask |= (ONE<<i); } uint_bitarray_t * ys = calloc(magic_samples, sizeof(uint_bitarray_t)); for(int i = 0; i < magic_samples; i++){ ys[i] = bitarray_rand() & magic_mask; } double complex * inner_prods = calloc(equatorial_samples, sizeof(double complex)); double complex alpha = (1. - I*(sqrt(2.) - 1.))/2.; double beta = log2(4. - 2.*sqrt(2.)); double complex alpha_phase = alpha / sqrt(1.-1./sqrt(2.)); double complex alpha_c_phase = conj(alpha_phase); //uint_bitarray_t * A = calloc(evolved_state->n - t, sizeof(uint_bitarray_t)); //uint_bitarray_t * GT = calloc(evolved_state->n - t, sizeof(uint_bitarray_t)); for(int i = 0; i < magic_samples; i++){ //sample a bitstring y of length t //printf("y: ");printBits(y, evolved_state->n); int hamming_weight = popcount(ys[i]); //printf("c1 copy 1\n"); //print_CHForm(evolved_state); CHForm copy = copy_CHForm(evolved_state); for(int k = evolved_state->n - t; k < evolved_state->n; k++){ if((ys[i] >> k ) & ONE){ SL(&copy, k); } HL(&copy, k); } postselect_and_reduce(&copy, (uint_bitarray_t)0, magic_mask); /* for(size_t i = 0; i < copy.n; i++){ */ /* A[i] = 0u; */ /* GT[i] = 0u; */ /* } */ /* for(size_t i = 0; i < copy.n; i++){ */ /* for(size_t j = 0; j < i; j++){ */ /* uint_bitarray_t bit = parity(copy.M[i] & copy.F[j]) & ONE; */ /* A[i] |= (bit << j); */ /* A[j] |= (bit << i); */ /* GT[i] |= ((copy.G[j] >> i) & ONE) << j; */ /* GT[j] |= ((copy.G[i] >> j) & ONE) << i; */ /* } */ /* } */ //now copy is a state of n-w qubits double complex prefactor = powl(2., (t+ beta*t)/2.)*cpowl(alpha_c_phase, t-hamming_weight)*cpowl(alpha_phase, hamming_weight); for(int j = 0; j < equatorial_samples; j++){ CHForm copy2 = copy_CHForm(&copy); double complex d = conj(equatorial_inner_product(&copy2, equatorial_matrices[j]))/(double)(magic_samples); inner_prods[j] += prefactor*d; dealocate_state(&copy2); //printf("1[%d,%d]: %d, (%lf, %lf), (%lf, %lf)\n",i, j, hamming_weight, creal(prefactor), cimag(prefactor), creal(d), cimag(d)); } dealocate_state(&copy); } free(ys); //free(A); //free(GT); double acc = 0; for(int j = 0; j < equatorial_samples; j++){ acc += powl(2,w)* creal(inner_prods[j]*conj(inner_prods[j]))/(double)equatorial_samples; } free(inner_prods); for(int j = 0; j < equatorial_samples; j++){ dealocate_equatorial_matrix(&equatorial_matrices[j]); } free(equatorial_matrices); dealocate_state(evolved_state); free(evolved_state); return PyComplex_FromDoubles(creal(acc), cimag(acc)); } static PyObject * magic_sample_2(PyObject* self, PyObject* args){ PyArrayObject * gates; PyArrayObject * controls; PyArrayObject * targets; PyArrayObject * a; // project |a_i><a_i| onto qubit i iff mask_i == 1 PyArrayObject * mask; int n; int magic_samples; int equatorial_samples; unsigned int seed; //printf("1\n"); if (!PyArg_ParseTuple(args, "iiiiO!O!O!O!O!", &n, &magic_samples, &equatorial_samples, &seed, &PyArray_Type, &gates, &PyArray_Type, &controls, &PyArray_Type, &targets, &PyArray_Type, &a, &PyArray_Type, &mask )){ return NULL; } srand(seed); //gatetize all the t gates int t = 0; for(int i = 0; i < gates->dimensions[0]; i++){ if(((char)gates->data[i*gates->strides[0]]) == 't'){ gates->data[i*gates->strides[0]] = 'X'; controls->data[i*controls->strides[0]] = targets->data[i*targets->strides[0]]; targets->data[i*targets->strides[0]] = (unsigned char)(n + t); t += 1; } } //printf("c2 t = %d\n", t); //now we do the Clifford evolution "precomputation" CHForm * evolved_state = c_apply_gates_to_basis_state(n+t, gates, controls, targets); //now we project onto the measurement outcomes for the w qubits //and throw away those qubits //leaving us with an n+t-w qubit state uint_bitarray_t bitA = 0; uint_bitarray_t bitMask = 0; for(int i = 0; i < n; i++){ if((a->data[i*a->strides[0]]) & ONE){ bitA |= (ONE << i); } if((mask->data[i*mask->strides[0]]) & ONE){ bitMask |= (ONE << i); } } postselect_and_reduce(evolved_state, bitA, bitMask); //printf("c2 after postselection\n"); //print_CHForm(evolved_state); //at this point we want to generate a list of length equatorial_samples //containing n - w - qubit equatorial states //ie. (n-w) x (n-w) binary symmetric matrices equatorial_matrix_t * equatorial_matrices = calloc(equatorial_samples, sizeof(equatorial_matrix_t)); for(int i = 0; i < equatorial_samples; i++){ init_random_equatorial_matrix(&(equatorial_matrices[i]), evolved_state->n - t); } uint_bitarray_t magic_mask = 0; int w = evolved_state->n - t; for(int i = evolved_state->n - t; i < evolved_state->n; i++){ magic_mask |= (ONE<<i); } uint_bitarray_t * ys = calloc(magic_samples, sizeof(uint_bitarray_t)); for(int i = 0; i < magic_samples; i++){ ys[i] = (bitarray_rand() & magic_mask) >> (evolved_state->n - t); } uint_bitarray_t equatorial_mask = 0; for(int i = 0; i < evolved_state->n - t; i++){ equatorial_mask |= (ONE << i); } /* printf("magic 2:\n"); */ /* printf("equatorial mask\n"); */ /* printBits(equatorial_mask, evolved_state->n);printf("\n"); */ /* printf("magic mask\n"); */ /* printBits(magic_mask, evolved_state->n);printf("\n"); */ /* printf("ys[0]\n"); */ /* printBits(ys[0], evolved_state->n);printf("\n"); */ /* printf("\n"); */ /* printf("c2 equatorial matrix\n"); */ /* for(int i = 0; i < equatorial_matrices[0].n; i++){ */ /* printBits(equatorial_matrices[0].mat[i], equatorial_matrices[0].n);printf("\n"); */ /* } */ /* printBits(equatorial_matrices[0].d1, equatorial_matrices[0].n);printf("\n"); */ /* printBits(equatorial_matrices[0].d2, equatorial_matrices[0].n);printf("\n"); */ double complex alpha = (1. - I*(sqrt(2.) - 1.))/2.; double beta = log2(4. - 2.*sqrt(2.)); double complex acc = 0; double complex alpha_phase = alpha / sqrt(1.-1./sqrt(2.)); double complex alpha_c_phase = conj(alpha_phase); for(int j = 0; j < equatorial_samples; j++){ CHForm copy = copy_CHForm(evolved_state); partial_equatorial_inner_product(&copy, equatorial_matrices[j], equatorial_mask); //printf("c2 copy after equatorial partial product\n"); //print_CHForm(&copy); //at this point we have a t qubit state and we take the inner product with each magic sample double complex overlaps = 0; for(int i = 0; i < magic_samples; i++){ CHForm inner_copy = copy_CHForm(&copy); //uint_bitarray_t y = bitarray_rand() & magic_mask; int hamming_weight = popcount(ys[i]); double complex prefactor = powl(2., (t+ beta*t)/2)*cpowl(alpha_c_phase, t-hamming_weight)*cpowl(alpha_phase, hamming_weight); //printf("c2 prefactor(%lf, %lf)\n", creal(prefactor), cimag(prefactor)); for(int k = 0; k < inner_copy.n; k++){ if((ys[i] >> k) & ONE){ SL(&inner_copy, k); //SL(&inner_copy, k); //SL(&inner_copy, k); } HL(&inner_copy, k); } double complex d = measurement_overlap(&inner_copy, (uint_bitarray_t)0)/magic_samples; //printf("2[%d,%d]: %d, (%lf, %lf), (%lf, %lf)\n",i, j, hamming_weight, creal(prefactor), cimag(prefactor), creal(d), cimag(d)); overlaps += prefactor*d; dealocate_state(&inner_copy); } acc += powl(2.,w)*creal(overlaps*conj(overlaps))/(double)equatorial_samples; dealocate_state(&copy); } for(int i = 0; i < equatorial_samples; i++){ dealocate_equatorial_matrix(&equatorial_matrices[i]); } free(equatorial_matrices); dealocate_state(evolved_state); //printf("c2(%lf, %lf)\n", creal(acc), cimag(acc)); return PyComplex_FromDoubles(creal(acc), cimag(acc)); } static PyObject * main_simulation_algorithm(PyObject* self, PyObject* args){ PyArrayObject * gates; PyArrayObject * controls; PyArrayObject * targets; PyArrayObject * a; // project |a_i><a_i| on qubit i on the first w qubits (a is length w array) int n; int measured_qubits; int magic_samples; int equatorial_samples; unsigned int seed; //printf("1\n"); if (!PyArg_ParseTuple(args, "iiiiiO!O!O!O!", &n, &magic_samples, &equatorial_samples, &seed, &measured_qubits, &PyArray_Type, &gates, &PyArray_Type, &controls, &PyArray_Type, &targets, &PyArray_Type, &a )){ return NULL; } srand(seed); //gatetize all the t gates int t = 0; for(int i = 0; i < gates->dimensions[0]; i++){ if(((char)gates->data[i*gates->strides[0]]) == T){ gates->data[i*gates->strides[0]] = CX; //controls->data[i*controls->strides[0]] = (unsigned int)targets->data[i*targets->strides[0]]; unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i); *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i); ptr = (unsigned int *)PyArray_GETPTR1(targets, i); *ptr = (unsigned int)(n + t); t += 1; } } //now we do the stabiliser evolution //to compute W StabTable * state = StabTable_new(n+t, n+t); /* printf("0:\n"); */ /* StabTable_print(state); */ /* printf("\n"); */ for(int i = 0; i < gates->dimensions[0]; i++){ //printf("%d, %c, %d, %d\n", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]); switch((char)gates->data[i*gates->strides[0]]) { case CX: StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case CZ: StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case S: StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case H: StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; } } //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0> //we "fix" this by applying a bunch of X gates to the measured qubits here for(int i = 0; i < measured_qubits; i++){ if((unsigned char)a->data[i*a->strides[0]]){ StabTable_X(state, i); } } int log_v = StabTable_apply_constraints(state, measured_qubits, t); if(log_v < 0){ return PyComplex_FromDoubles(0., 0.); } //now delete the first (n) = table->n - t (since table->n = n + t at this point) qubits //at this point we should just be left with t qubits int q_to_delete = state->n - t; int new_size = t; for(int s = 0; s < state->k; s++){ for(int q = q_to_delete; q < state->n; q++){ state->table[s][q-q_to_delete] = state->table[s][q]; } for(int q = q_to_delete; q < state->n; q++){ state->table[s][q-2*q_to_delete+state->n] = state->table[s][q+state->n]; } state->table[s] = realloc(state->table[s], sizeof(unsigned char) * 2 * new_size); } state->n = new_size; QCircuit * W = StabTable_simplifying_unitary(state); //printf("after computing W\n"); state->circ = NULL; //now we have to work out what we need to do magic sampling with this W circuit //we need the CH-form for W|\tilde{0}> //and the AG tableau for W|0> (no tilde!) CHForm chState; init_cb_CHForm(t,&chState); //Hadamard everything because we want to know the evolution of |\tilde{0}> = |+> for(int i = 0; i < t; i++){ HL(&chState, i); } //printf("before computing chState & agState\n"); StabTable * agState = StabTable_new(t,t); for(int i = 0; i < W->length; i++){ //printf("%d, %c, %d, %d\n", i, W->tape[i].tag, W->tape[i].control, W->tape[i].target); switch(W->tape[i].tag) { case CX: CXL(&chState, W->tape[i].control, W->tape[i].target); StabTable_CX(agState, W->tape[i].control, W->tape[i].target); //StabTable_CX(stateCopy, W->tape[i].control, W->tape[i].target); break; case CZ: CZL(&chState, W->tape[i].control, W->tape[i].target); StabTable_CZ(agState, W->tape[i].control, W->tape[i].target); //StabTable_CZ(stateCopy, W->tape[i].control, W->tape[i].target); break; case S: SL(&chState, W->tape[i].target); StabTable_S(agState, W->tape[i].target); //StabTable_S(stateCopy, W->tape[i].target); break; case H: HL(&chState, W->tape[i].target); StabTable_H(agState, W->tape[i].target); //StabTable_H(stateCopy, W->tape[i].target); break; } } /* printf("Action of W\n"); */ /* StabTable_print(stateCopy); */ /* StabTable_free(stateCopy); */ /* return PyComplex_FromDoubles(0, 0); */ //printf("after computing chState & agState\n"); //now S_k^3 = e^{-i\pi/4} (1/sqrt(2)) (I + i Z_k) //W S_k^3 W^\dagger = e^{-i\pi/4} (1/sqrt(2)) (I + i W Z_k W^\dagger) //W Z_k W^\dagger is exactly the k^th row of agState //Now we have to apply e^{-i\pi/4} (1/sqrt(2)) (I + i W Z_k W^\dagger) to w UC UH |s> //e^{-i\pi/4} (1/sqrt(2)) w (I + i W Z_k W^\dagger)UC UH |s> = e^{-i\pi/4} (1/sqrt(2)) w UC (UC^\dagger(I + i W Z_k W^\dagger)UC) UH |s> // = e^{-i\pi/4} (1/sqrt(2)) w UC (I + i UC^\dagger W Z_k W^\dagger UC) UH |s> //printf("before freeing W\n"); //QCircuit_free(W); //printf("after freeing W\n"); //at this point we want to generate a list of length equatorial_samples //containing t - r - qubit equatorial states //ie. (t-r) x (t-r) binary symmetric matrices equatorial_matrix_t * equatorial_matrices = calloc(equatorial_samples, sizeof(equatorial_matrix_t)); for(int i = 0; i < equatorial_samples; i++){ init_random_equatorial_matrix(&(equatorial_matrices[i]), state->n-state->k); } //printf("a\n"); uint_bitarray_t magic_mask = 0; for(int i = 0; i < t; i++){ magic_mask |= (ONE<<i); } //printf("b\n"); uint_bitarray_t * ys = calloc(magic_samples, sizeof(uint_bitarray_t)); for(int i = 0; i < magic_samples; i++){ ys[i] = bitarray_rand() & magic_mask; } //printf("c\n"); uint_bitarray_t equatorial_mask = 0; for(int i = 0; i < state->n-state->k; i++){ equatorial_mask |= (ONE << i); } //printf("d\n"); //we project onto 0 and throw away the first t-r qubits //leaving us with an r qubit state uint_bitarray_t bitA = 0; uint_bitarray_t bitMask = 0; for(int i = 0; i < state->k; i++){ bitMask |= (ONE << i); } //printf("e\n"); double complex * inner_prods = calloc(equatorial_samples, sizeof(double complex)); double complex alpha = (1. - I*(sqrt(2.) - 1.))/2.; double beta = log2(4. - 2.*sqrt(2.)); double complex alpha_phase = alpha / cabs(alpha); double complex alpha_c_phase = conj(alpha_phase); double sampling_time = 0.; double norm_est_time = 0.; clock_t start; clock_t end; for(int i = 0; i < magic_samples; i++){ start = clock(); //printf("%d\n", i); //generate our state CHForm copy = copy_CHForm(&chState); for(int bit = 0; bit < t; bit++){ if((ys[i] >> bit) & ONE){ //apply W S^3_bit W^\dagger to chState uint_bitarray_t * z_mat = calloc(t, sizeof(uint_bitarray_t)); uint_bitarray_t * x_mat = calloc(t, sizeof(uint_bitarray_t)); uint_bitarray_t mask = (uint_bitarray_t)0; uint_bitarray_t t_mask = (uint_bitarray_t)0; unsigned int g = 2*agState->phases[bit] ; for(int j = 0; j < t; j++){ if(agState->table[bit][j]){ x_mat[j] = copy.F[j]; z_mat[j] = copy.M[j]; mask |= (ONE << j); } if(agState->table[bit][j+agState->n]){ z_mat[j] ^= copy.G[j]; } t_mask |= (ONE << j); //if x and z are both 1 we get a factor of i because iXZ == Y if((agState->table[bit][j] == 1) && (agState->table[bit][j+agState->n] == 1)){ g += 1; } } g += popcount(copy.g1 & mask) + 2*popcount(copy.g2 & mask); g += 2*sort_pauli_string(t, x_mat, z_mat, mask); uint_bitarray_t u = 0u; // u_m is exponent of X_m uint_bitarray_t h = 0u; // h_m is exponent of Z_m for(int k = 0; k < t; k++){ if(agState->table[bit][k]){ u ^= (copy.F[k] & t_mask); h ^= (copy.M[k] & t_mask); } if(agState->table[bit][k+agState->n]){ h ^= (copy.G[k] & t_mask); } } //at this point the state we want is w U_c [I + i^g \prod_m Z_m^{h_m}X_m^{u_m}] U_H |s> //we need to commute the product through U_H //and then desuperpositionise //we pull the same trick again // (\prod_m X_m^{u_m}Z_m^{h_m} ) U_H = U_H (U_H^\dagger (\prod_m Z_m^{h_m}X_m^{u_m}) U_H) //n.b. Hadamard is self-adjoint //what happens - if V_k is zero then nothing happens //if V_k is 1 then we swap X and Z //if V_k is 1 and X and Z are both 1 we get a minus sign uint_bitarray_t u2 = (u & (~copy.v)) ^ (h & (copy.v)); uint_bitarray_t h2 = (h & (~copy.v)) ^ (u & (copy.v)); g += 2*parity(u & h & copy.v & t_mask); //at this point the state we want is w U_c [I + i^g U_H \prod_m Z_m^{h2_m} X_m^{u2_m}] |s> //we apply the paulis to |s> //every x flips a bit of s //every time a z hits a |1> we get a -1 //xs happen first uint_bitarray_t y = (copy.s ^ u2) & t_mask; g += 2*parity(y & h2 & t_mask); g += 1; //an i appears in the expression for S^3 in terms of Z and I g %= 4; //at this point the state we want is w e^{-i\pi/4}/sqrt{2} U_c U_h( |s> + i^(g) |y>) //extra factors from the formula for S^3 if((y & t_mask) == (copy.s & t_mask)){ double complex a = 1.; if(g == 0){ a += 1.; } if(g == 1){ a += (1.)*I; } if(g == 2){ a += (-1.); } if(g == 3){ a += (-1.*I); } copy.w *= (a*(1 - 1.*I)/2.); }else{ desupersitionise(&copy, y, g); copy.w *= (1.-1.*I)/2.; } free(x_mat); free(z_mat); } } end = clock(); sampling_time += ((double)(end - start)) / (double)CLOCKS_PER_SEC; start = clock(); //at this point copy contains our magic sample //we want to project it and do fastnorm estimation //printf("before: %d %lu\n", i, ys[i]); //print_CHForm(&copy); //printf("\n"); //now we project onto the measurement outcomes for the w qubits postselect_and_reduce(&copy, bitA, bitMask); //printf("after: %d %lu\n", i, ys[i]); //print_CHForm(&copy); //printf("\n"); int hamming_weight = popcount(ys[i]); //printf("%d\n", hamming_weight); //powl(2., log_v+t+beta*t+(agState->k-w)/2.)*cpowl(alpha, t-hamming_weight)*cpowl(alpha_c, hamming_weight); //printf("%lf, %d, %d, %d, %d\n", beta, t,log_v, measured_qubits, hamming_weight); //printf("%lf + %lf I\n", creal(alpha_phase), cimag(alpha_phase)); //printf("%lf + %lf I\n", creal(alpha_c_phase), cimag(alpha_c_phase)); double complex prefactor = powl(2., ((beta + 1)*t + log_v - measured_qubits)/2.)*cpowl(alpha_phase, t-hamming_weight)*cpowl(alpha_c_phase, hamming_weight); //printf("%lf + %lf I\n", creal(prefactor), cimag(prefactor)); //equatorial_samples = 10; for(int j = 0; j < equatorial_samples; j++){ //CHForm copy2 = copy_CHForm(&copy); double complex d = conj(equatorial_inner_product(&copy, equatorial_matrices[j]))/(double)(magic_samples); //printf("%lf + %lf*I\n", creal(d), cimag(d)); inner_prods[j] += prefactor*d; //dealocate_state(&copy2); } end = clock(); norm_est_time += ((double)(end - start)) / (double)CLOCKS_PER_SEC; dealocate_state(&copy); } free(ys); //printf("sampling_time: %lf\nnorm_est_time: %lf\n", sampling_time, norm_est_time); double acc = 0; for(int j = 0; j < equatorial_samples; j++){ acc += creal(inner_prods[j]*conj(inner_prods[j]))/(double)equatorial_samples; } free(inner_prods); for(int j = 0; j < equatorial_samples; j++){ dealocate_equatorial_matrix(&equatorial_matrices[j]); } free(equatorial_matrices); StabTable_free(agState); dealocate_state(&chState); StabTable_free(state); //printf("c1(%lf, %lf)\n", creal(acc), cimag(acc)); return PyComplex_FromDoubles(creal(acc), cimag(acc)); } static PyObject * main_simulation_algorithm2(PyObject* self, PyObject* args){ PyArrayObject * gates; PyArrayObject * controls; PyArrayObject * targets; PyArrayObject * a; // project |a_i><a_i| on qubit i on the first w qubits (a is length w array) int n; int measured_qubits; int magic_samples; int equatorial_samples; unsigned int seed; //printf("1\n"); if (!PyArg_ParseTuple(args, "iiiiiO!O!O!O!", &n, &magic_samples, &equatorial_samples, &seed, &measured_qubits, &PyArray_Type, &gates, &PyArray_Type, &controls, &PyArray_Type, &targets, &PyArray_Type, &a )){ return NULL; } //printf("%d, %d, %d\n", n, magic_samples, equatorial_samples); srand(seed); //gatetize all the t gates int t = 0; for(int i = 0; i < gates->dimensions[0]; i++){ if(((char)gates->data[i*gates->strides[0]]) == T){ gates->data[i*gates->strides[0]] = CX; controls->data[i*controls->strides[0]] = targets->data[i*targets->strides[0]]; targets->data[i*targets->strides[0]] = (unsigned char)(n + t); t += 1; } } //now we do the stabiliser evolution //to compute W StabTable * state = StabTable_new(n+t, n+t); for(int i = 0; i < gates->dimensions[0]; i++){ switch((char)gates->data[i*gates->strides[0]]) { case CX: StabTable_CX(state, (unsigned int)controls->data[i*controls->strides[0]], (unsigned int)targets->data[i*targets->strides[0]]); break; case CZ: StabTable_CZ(state, (unsigned int)controls->data[i*controls->strides[0]], (unsigned int)targets->data[i*targets->strides[0]]); break; case S: StabTable_S(state, (unsigned int)targets->data[i*targets->strides[0]]); break; case H: StabTable_H(state, (unsigned int)targets->data[i*targets->strides[0]]); break; } } //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0> //we "fix" this by applying a bunch of X gates to the measured qubits here for(int i = 0; i < measured_qubits; i++){ if((unsigned char)a->data[i*a->strides[0]]){ StabTable_X(state, i); } } int log_v = StabTable_apply_constraints(state, measured_qubits, t); //printf("log_v = %d\n", log_v); if(log_v < 0){ return PyComplex_FromDoubles(0., 0.); } /* //at this point state is a stab table with fewer stabs than qubits */ /* //representing a mixed state */ /* //it is still on n+t qubits */ /* //but the first n qubits are trivial (the stabs are all the identity there) */ /* //we can just delete them */ //now delete the first (n) = table->n - t (since table->n = n + t at this point) qubits //at this point we should just be left with t qubits int q_to_delete = state->n - t; int new_size = t; for(int s = 0; s < state->k; s++){ for(int q = q_to_delete; q < state->n; q++){ state->table[s][q-q_to_delete] = state->table[s][q]; } for(int q = q_to_delete; q < state->n; q++){ state->table[s][q-2*q_to_delete+state->n] = state->table[s][q+state->n]; } state->table[s] = realloc(state->table[s], sizeof(unsigned char) * 2 * new_size); } state->n = new_size; //printf("before computing W\n"); QCircuit * W = StabTable_simplifying_unitary(state); //printf("after computing W\n"); state->circ = NULL; //now we have to work out what we need to do magic sampling with this W circuit //we need the CH-form for W|\tilde{0}> //and the AG tableau for W|0> (no tilde!) CHForm chState; init_cb_CHForm(t,&chState); //Hadamard everything because we want to know the evolution of |\tilde{0}> = |+> for(int i = 0; i < t; i++){ HL(&chState, i); } //printf("before computing chState & agState\n"); StabTable * agState = StabTable_new(t,t); for(int i = 0; i < W->length; i++){ switch(W->tape[i].tag) { case CX: CXL(&chState, W->tape[i].control, W->tape[i].target); StabTable_CX(agState, W->tape[i].control, W->tape[i].target); break; case CZ: CZL(&chState, W->tape[i].control, W->tape[i].target); StabTable_CZ(agState, W->tape[i].control, W->tape[i].target); break; case S: SL(&chState, W->tape[i].target); StabTable_S(agState, W->tape[i].target); break; case H: HL(&chState, W->tape[i].target); StabTable_H(agState, W->tape[i].target); break; } } //printf("after computing chState & agState\n"); //now S_k^3 = e^{i\pi/4} (1/sqrt(2)) (I + i Z_k) //W S_k^3 W^\dagger = e^{i\pi/4} (1/sqrt(2)) (I + i W Z_k W^\dagger) //W Z_k W^\dagger is exactly the k^th row of agState //Now we have to apply e^{i\pi/4} (1/sqrt(2)) (I + i W Z_k W^\dagger) to w UC UH |s> //e^{i\pi/4} (1/sqrt(2)) w (I + i W Z_k W^\dagger)UC UH |s> = e^{i\pi/4} (1/sqrt(2)) w UC (UC^\dagger(I + i W Z_k W^\dagger)UC) UH |s> // = e^{i\pi/4} (1/sqrt(2)) w UC (I + i UC^\dagger W Z_k W^\dagger UC) UH |s> //printf("before freeing W\n"); //QCircuit_free(W); //printf("after freeing W\n"); //at this point we want to generate a list of length equatorial_samples //containing t - r - qubit equatorial states //ie. (t-r) x (t-r) binary symmetric matrices equatorial_matrix_t * equatorial_matrices = calloc(equatorial_samples, sizeof(equatorial_matrix_t)); for(int i = 0; i < equatorial_samples; i++){ init_random_equatorial_matrix(&(equatorial_matrices[i]), state->n-state->k); } //printf("a\n"); uint_bitarray_t magic_mask = 0; for(int i = 0; i < t; i++){ magic_mask |= (ONE<<i); } //printf("b\n"); uint_bitarray_t * ys = calloc(magic_samples, sizeof(uint_bitarray_t)); for(int i = 0; i < magic_samples; i++){ ys[i] = bitarray_rand() & magic_mask; } //printf("c\n"); uint_bitarray_t equatorial_mask = 0; for(int i = 0; i < state->n-state->k; i++){ equatorial_mask |= (ONE << i); } //printf("d\n"); //we project onto 0 and throw away the first t-r qubits //leaving us with an r qubit state uint_bitarray_t bitA = 0; uint_bitarray_t bitMask = 0; for(int i = 0; i < state->k; i++){ bitMask |= (ONE << i); } //printf("e\n"); double complex * inner_prods = calloc(equatorial_samples, sizeof(double complex)); double complex alpha = (1. - I*(sqrt(2.) - 1.))/2.; double beta = log2(4. - 2.*sqrt(2.)); double complex alpha_phase = alpha / cabs(alpha); double complex alpha_c_phase = conj(alpha_phase); double sampling_time = 0.; double norm_est_time = 0.; clock_t start; clock_t end; for(int i = 0; i < magic_samples; i++){ start = clock(); //printf("%d\n", i); //generate our state //CHForm copy = copy_CHForm(&chState); CHForm copy; init_cb_CHForm(t, &copy); for(int bit = 0; bit < t; bit++){ HL(&copy, bit); if((ys[i] >> bit) & ONE){ SL(&copy, bit); SL(&copy, bit); SL(&copy, bit); } } for(int j = 0; j < W->length; j++){ switch(W->tape[j].tag) { case CX: CXL(&copy, W->tape[j].control, W->tape[j].target); break; case CZ: CZL(&copy, W->tape[j].control, W->tape[j].target); break; case S: SL(&copy, W->tape[j].target); break; case H: HL(&copy, W->tape[j].target); break; } } end = clock(); sampling_time += ((double)(end - start)) / (double)CLOCKS_PER_SEC; start = clock(); //at this point copy contains our magic sample //we want to project it and do fastnorm estimation //now we project onto the measurement outcomes for the w qubits postselect_and_reduce(&copy, bitA, bitMask); int hamming_weight = popcount(ys[i]); //powl(2., log_v+t+beta*t+(agState->k-w)/2.)*cpowl(alpha, t-hamming_weight)*cpowl(alpha_c, hamming_weight); //printf("%lf, %d, %d, %d, %d\n", beta, t,log_v, measured_qubits, hamming_weight); //printf("%lf + %lf I\n", creal(alpha_phase), cimag(alpha_phase)); //printf("%lf + %lf I\n", creal(alpha_c_phase), cimag(alpha_c_phase)); double complex prefactor = powl(2., ((beta + 1)*t + log_v - measured_qubits)/2.)*cpowl(alpha_phase, t-hamming_weight)*cpowl(alpha_c_phase, hamming_weight); //printf("%lf + %lf I\n", creal(prefactor), cimag(prefactor)); for(int j = 0; j < equatorial_samples; j++){ CHForm copy2 = copy_CHForm(&copy); double complex d = conj(equatorial_inner_product(&copy2, equatorial_matrices[j]))/(double)(magic_samples); inner_prods[j] += prefactor*d; dealocate_state(&copy2); } end = clock(); norm_est_time += ((double)(end - start)) / (double)CLOCKS_PER_SEC; dealocate_state(&copy); } free(ys); //printf("sampling_time2: %lf\nnorm_est_time2: %lf\n", sampling_time, norm_est_time); double complex acc = 0; for(int j = 0; j < equatorial_samples; j++){ acc += creal(inner_prods[j]*conj(inner_prods[j]))/(double)equatorial_samples; } free(inner_prods); for(int j = 0; j < equatorial_samples; j++){ dealocate_equatorial_matrix(&equatorial_matrices[j]); } free(equatorial_matrices); StabTable_free(agState); dealocate_state(&chState); StabTable_free(state); //printf("c1(%lf, %lf)\n", creal(acc), cimag(acc)); return PyComplex_FromDoubles(creal(acc), cimag(acc)); } static PyObject * v_r_info(PyObject* self, PyObject* args){ PyArrayObject * gates; PyArrayObject * controls; PyArrayObject * targets; PyArrayObject * a; // project |a_i><a_i| on qubit i on the first w qubits (a is length w array) int n; int measured_qubits; //printf("1\n"); if (!PyArg_ParseTuple(args, "iiO!O!O!O!", &n, &measured_qubits, &PyArray_Type, &gates, &PyArray_Type, &controls, &PyArray_Type, &targets, &PyArray_Type, &a )){ return NULL; } //gatetize all the t gates int t = 0; for(int i = 0; i < gates->dimensions[0]; i++){ if(((char)gates->data[i*gates->strides[0]]) == T){ gates->data[i*gates->strides[0]] = CX; //controls->data[i*controls->strides[0]] = (unsigned int)targets->data[i*targets->strides[0]]; unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i); *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i); ptr = (unsigned int *)PyArray_GETPTR1(targets, i); *ptr = (unsigned int)(n + t); //printf("%d, %d, %u, %u\n", t, n, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); t += 1; } } //now we do the stabiliser evolution //to compute W StabTable * state = StabTable_new(n+t, n+t); /* printf("0:\n"); */ /* StabTable_print(state); */ /* printf("\n"); */ for(int i = 0; i < gates->dimensions[0]; i++){ //printf("%d, %c, %d, %d\n", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]); switch((char)gates->data[i*gates->strides[0]]) { case CX: StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case CZ: StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case S: StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case H: StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; } } //StabTable_print(state); //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0> //we "fix" this by applying a bunch of X gates to the measured qubits here //for(int i = 0; i < measured_qubits; i++){ // if((unsigned char)a->data[i*a->strides[0]]){ // StabTable_X(state, i); // } //} int log_v = StabTable_apply_constraints(state, measured_qubits, t); return Py_BuildValue("ii", log_v, t-state->k); //StabTable_free(state); //Py_RETURN_NONE; } static PyObject * lhs_rank_info(PyObject* self, PyObject* args){ PyArrayObject * gates; PyArrayObject * controls; PyArrayObject * targets; PyArrayObject * a; // project |a_i><a_i| on qubit i on the first w qubits (a is length w array) int n; int measured_qubits; if (!PyArg_ParseTuple(args, "iiO!O!O!O!", &n, &measured_qubits, &PyArray_Type, &gates, &PyArray_Type, &controls, &PyArray_Type, &targets, &PyArray_Type, &a )){ return NULL; } //gatetize all the t gates int t = 0; for(int i = 0; i < gates->dimensions[0]; i++){ if(((char)gates->data[i*gates->strides[0]]) == T){ gates->data[i*gates->strides[0]] = CX; //controls->data[i*controls->strides[0]] = (unsigned int)targets->data[i*targets->strides[0]]; unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i); *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i); ptr = (unsigned int *)PyArray_GETPTR1(targets, i); *ptr = (unsigned int)(n + t); t += 1; } } //now we do the stabiliser evolution //to compute W StabTable * state = StabTable_new(n+t, n+t); /* printf("0:\n"); */ /* StabTable_print(state); */ /* printf("\n"); */ for(int i = 0; i < gates->dimensions[0]; i++){ //printf("%d, %c, %d, %d\n", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]); switch((char)gates->data[i*gates->strides[0]]) { case CX: StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case CZ: StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case S: StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case H: StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; } } //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0> //we "fix" this by applying a bunch of X gates to the measured qubits here //for(int i = 0; i < measured_qubits; i++){ // if((unsigned char)a->data[i*a->strides[0]]){ // StabTable_X(state, i); // } //} //printf("\n");StabTable_print(state);printf("\n"); int log_v = StabTable_apply_constraints(state, measured_qubits, t); //printf("\n");StabTable_print(state);printf("\n"); int first_k = state->k; if(log_v < 0){ return PyComplex_FromDoubles(0., 0.); } //StabTable * before_T_copy = StabTable_copy(state); //printf("state->k = %d\n", state->k); StabTable_apply_T_constraints(state, t); //printf("state->k = %d\n", state->k); //at this point the variable state contains the long G guys StabTable * longG = StabTable_copy(state); //now we evolve these back in time with V for(int i = gates->dimensions[0]-1; i >= 0 ; i--){ //printf("%d, %c, %d, %d\n", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]); switch((char)gates->data[i*gates->strides[0]]) { case CX: StabTable_CX(longG, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case CZ: StabTable_CZ(longG, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case S: StabTable_S(longG, (*(unsigned int *)PyArray_GETPTR1(targets,i))); StabTable_S(longG, (*(unsigned int *)PyArray_GETPTR1(targets,i))); StabTable_S(longG, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case H: StabTable_H(longG, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; } } //StabTable_print(longG); longG->n = longG->n - t; for(int i = 0; i < longG->k; i++){ for(int j = 0; j < longG->n; j++){ longG->table[i][j+longG->n] = longG->table[i][j+longG->n + t]; } longG->table[i] = realloc(longG->table[i], 2*(longG->n)*sizeof(unsigned char)); } //StabTable_print(longG); //now we have to do row echelon form on longG to work out the rank int h = 0; int k = longG->n; int rank = 0; while(h < longG->k && k < 2*longG->n){ int poss_pivot = StabTable_first_non_zero_in_col(longG, k, h); if(poss_pivot < 0){ k += 1; }else{ int pivot = poss_pivot; //now known to be non-negative if(pivot != h){ //swap rows h and pivot of the table StabTable_swap_rows(longG,h,pivot); } for(int j = 0; j < longG->k; j++){ if((j != h) && (longG->table[j][k] != 0)){ StabTable_rowsum(longG,j,h); } } h += 1; k += 1; rank += 1; } } //printf("idenits = %d\n", identity_qubits); //printf("Rank = %d\n", rank); //printf("lonG->k = %d\n", longG->k); //StabTable_print(longG);printf("\n"); //StabTable_free(longG); return Py_BuildValue("iiii", first_k, longG->n, longG->k, rank); } static PyObject * compute_algorithm(PyObject* self, PyObject* args){ PyArrayObject * gates; PyArrayObject * controls; PyArrayObject * targets; PyArrayObject * a; // project |a_i><a_i| on qubit i on the first w qubits (a is length w array) int n; int measured_qubits; if (!PyArg_ParseTuple(args, "iiO!O!O!O!", &n, &measured_qubits, &PyArray_Type, &gates, &PyArray_Type, &controls, &PyArray_Type, &targets, &PyArray_Type, &a )){ return NULL; } //clock_t start = clock(); //gatetize all the t gates int t = 0; for(int i = 0; i < gates->dimensions[0]; i++){ if(((char)gates->data[i*gates->strides[0]]) == T){ gates->data[i*gates->strides[0]] = CX; unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i); *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i); ptr = (unsigned int *)PyArray_GETPTR1(targets, i); *ptr = (unsigned int)(n + t); t += 1; } } //printf("\n"); //now we do the stabiliser evolution //to compute W //printf("t = %d\n", t); //printf("w = %d\n", measured_qubits); StabTable * state = StabTable_new(n+t, n+t); /* printf("0:\n"); */ /* StabTable_print(state); */ /* printf("\n"); */ for(int i = 0; i < gates->dimensions[0]; i++){ //printf("%d, %c, %d, %d\n", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]); switch((*(unsigned char *)PyArray_GETPTR1(gates,i))) { case CX: StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case CZ: StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case S: StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case H: StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; } } //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0> //we "fix" this by applying a bunch of X gates to the measured qubits here for(int i = 0; i < measured_qubits; i++){ if((*(unsigned char *)PyArray_GETPTR1(a,i)) == 1){ //printf("flipping %d\n",i); StabTable_X(state, i); } } //printf("Entering constraints code\n"); //StabTable_print(state);printf("\n"); int log_v = StabTable_apply_constraints(state, measured_qubits, t); //printf("constraints code returned log_v = %d\n",log_v); //StabTable_print(state);printf("\n"); if(log_v < 0){ return Py_BuildValue("d", 0); //PyComplex_FromDoubles(0., 0.); } //now delete the first (n) = table->n - t (since table->n = n + t at this point) qubits // at this point we should just be left with t qubits int q_to_delete = state->n - t; int new_size = t; for(int s = 0; s < state->k; s++){ for(int q = q_to_delete; q < state->n; q++){ state->table[s][q-q_to_delete] = state->table[s][q]; } for(int q = q_to_delete; q < state->n; q++){ state->table[s][q-2*q_to_delete+state->n] = state->table[s][q+state->n]; } state->table[s] = realloc(state->table[s], sizeof(unsigned char) * 2 * new_size); } state->n = new_size; //int d = state->k; //int r = state->n - state->k; StabTable_delete_all_identity_qubits(state, NULL); StabTable_apply_T_constraints(state,t); StabTable_delete_all_identity_qubits(state, NULL); //printf("final state:\n"); //StabTable_print(state); //we explicitly compute the sum appearing in 10 uint_bitarray_t full_mask = 0u; for(int i = 0; i < state->k; i++){ full_mask |= (ONE << i); } double complex acc = 0.; //printf("final k = %d\n", state->k); //printBits(full_mask,5);printf("\n"); for(uint_bitarray_t mask = 0u; mask <= full_mask; mask++){ //printf("mask = ");printBits(mask,5);printf("\n"); unsigned char * row = calloc(2*state->n, sizeof(unsigned char)); unsigned char phase = 0; //we do the element of the sum corresponding to the bits of mask being 1 for(int j = 0; j < state->k; j++){ if((mask >> j) & ONE){ //printf("%d, ", j); phase = StabTable_rowsum2(state, row, phase, j); } } //printf("\n"); //so now (row, phase) indicate a particular length t string of pauli matrices //and we want to compute <T|^t (row,phase |T>^t int ICount = 0; int XCount = 0; int YCount = 0; int ZCount = 0; for(int j = 0; j < state->n; j++){ if((row[j] == 0) && (row[j+state->n] == 0)){ ICount += 1; } if((row[j] == 1) && (row[j+state->n] == 0)){ XCount += 1; } if((row[j] == 0) && (row[j+state->n] == 1)){ ZCount += 1; } if((row[j] == 1) && (row[j+state->n] == 1)){ YCount += 1; } } double val = powl(1./2., (XCount + YCount)/2.); //printf("val=%lf\n", creal(val)); //printf("I = %d, X = %d, Y = %d, Z = %d, total = %d\n", ICount, XCount, YCount, ZCount, ICount+ XCount+ YCount+ ZCount); if(ZCount == 0){ if(((phase + YCount) % 2) == 0){ acc += val; }else{ acc -= val; } } free(row); } if(full_mask == 0u){ acc = 1; } //printf("%lf\n",creal(acc)); acc *= powl(2., log_v - measured_qubits); //printf("%lf\n",creal(acc)); //end = clock(); //double calc_time = ((double)(end - start)) / (double)CLOCKS_PER_SEC; StabTable_free(state); return Py_BuildValue("d", acc); } static PyObject * StabTable_to_python_tuple(StabTable * table){ const long int dimensions1[1] = {table->k}; const long int dimensions2[2] = {table->k, 2*table->n}; PyArrayObject * py_table = (PyArrayObject*)PyArray_SimpleNew(2, dimensions2, PyArray_UBYTE); PyArrayObject * py_phases = (PyArrayObject*)PyArray_SimpleNew(1, dimensions1, PyArray_UBYTE); for(int s = 0; s < table->k; s++){ for(int q = 0; q < 2*table->n; q++){ py_table->data[s*py_table->strides[0] + q*py_table->strides[1]] = (unsigned char)table->table[s][q]; } py_phases->data[s*py_phases->strides[0]] = table->phases[s]; } return Py_BuildValue("iiOO", table->n, table->k, (PyObject*)py_table, (PyObject*)py_phases); } static StabTable * python_tuple_to_StabTable(PyObject * tuple){ PyObject * py_n = PyTuple_GetItem(tuple, 0); PyObject * py_k = PyTuple_GetItem(tuple, 1); PyObject * py_table = PyTuple_GetItem(tuple, 2); PyObject * py_phases = PyTuple_GetItem(tuple, 3); int n = PyLong_AsLong(py_n); int k = PyLong_AsLong(py_k); StabTable * table = StabTable_new(n, k); for(int s = 0; s < table->k; s++){ for(int q = 0; q < 2*table->n; q++){ table->table[s][q] = *((unsigned char*)PyArray_GETPTR2(py_table, s, q)); } table->phases[s]= *((unsigned char*)PyArray_GETPTR1(py_phases, s)); } return table; } static PyObject * compress_algorithm(PyObject* self, PyObject* args){ PyArrayObject * gates; PyArrayObject * controls; PyArrayObject * targets; PyArrayObject * a; // project |a_i><a_i| on qubit i on the first w qubits (a is length w array) int n; int measured_qubits; if (!PyArg_ParseTuple(args, "iiO!O!O!O!", &n, &measured_qubits, &PyArray_Type, &gates, &PyArray_Type, &controls, &PyArray_Type, &targets, &PyArray_Type, &a )){ return NULL; } //clock_t start = clock(); //gatetize all the t gates int t = 0; for(int i = 0; i < gates->dimensions[0]; i++){ if(((char)gates->data[i*gates->strides[0]]) == T){ gates->data[i*gates->strides[0]] = CX; unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i); *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i); ptr = (unsigned int *)PyArray_GETPTR1(targets, i); *ptr = (unsigned int)(n + t); t += 1; } } //printf("\n"); //now we do the stabiliser evolution //to compute W //printf("t = %d\n", t); //printf("w = %d\n", measured_qubits); StabTable * state = StabTable_new(n+t, n+t); /* printf("0:\n"); */ /* StabTable_print(state); */ /* printf("\n"); */ for(int i = 0; i < gates->dimensions[0]; i++){ //printf("%d, %c, %d, %d\n", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]); switch((*(unsigned char *)PyArray_GETPTR1(gates,i))) { case CX: StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case CZ: StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case S: StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case H: StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; } } //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0> //we "fix" this by applying a bunch of X gates to the measured qubits here for(int i = 0; i < measured_qubits; i++){ if((*(unsigned char *)PyArray_GETPTR1(a,i)) == 1){ //printf("flipping %d\n",i); StabTable_X(state, i); } } //printf("Entering constraints code\n"); //StabTable_print(state);printf("\n"); int log_v = StabTable_apply_constraints(state, measured_qubits, t); //printf("constraints code returned log_v = %d\n",log_v); //StabTable_print(state);printf("\n"); if(log_v < 0){ return Py_BuildValue("d", 0); //PyComplex_FromDoubles(0., 0.); } //now delete the first (n) = table->n - t (since table->n = n + t at this point) qubits // at this point we should just be left with t qubits int q_to_delete = state->n - t; int new_size = t; for(int s = 0; s < state->k; s++){ for(int q = q_to_delete; q < state->n; q++){ state->table[s][q-q_to_delete] = state->table[s][q]; } for(int q = q_to_delete; q < state->n; q++){ state->table[s][q-2*q_to_delete+state->n] = state->table[s][q+state->n]; } state->table[s] = realloc(state->table[s], sizeof(unsigned char) * 2 * new_size); } state->n = new_size; int d = state->k; int r = state->n - state->k; int * magic_qubit_numbers = calloc(state->n, sizeof(int)); for(int i = 0; i < state->n; i++){ magic_qubit_numbers[i] = i; } int delta_t = StabTable_delete_all_identity_qubits(state, magic_qubit_numbers); int delta_d = StabTable_apply_T_constraints(state,t); int delta_t_prime = StabTable_delete_all_identity_qubits(state, magic_qubit_numbers); int final_d = state->k; int final_t = state->n; QCircuit * W = StabTable_simplifying_unitary(state); //printf("after computing W\n"); state->circ = NULL; //now we have to work out what we need to do magic sampling with this W circuit //we need the CH-form for W|\tilde{0}> //and the AG tableau for W|0> (no tilde!) CHForm chState; init_cb_CHForm(t,&chState); //Hadamard everything because we want to know the evolution of |\tilde{0}> = |+> for(int i = 0; i < t; i++){ HL(&chState, i); } //printf("before computing chState & agState\n"); StabTable * agState = StabTable_new(t,t); for(int i = 0; i < W->length; i++){ switch(W->tape[i].tag) { case CX: CXL(&chState, W->tape[i].control, W->tape[i].target); StabTable_CX(agState, W->tape[i].control, W->tape[i].target); break; case CZ: CZL(&chState, W->tape[i].control, W->tape[i].target); StabTable_CZ(agState, W->tape[i].control, W->tape[i].target); break; case S: SL(&chState, W->tape[i].target); StabTable_S(agState, W->tape[i].target); break; case H: HL(&chState, W->tape[i].target); StabTable_H(agState, W->tape[i].target); break; } } npy_intp dims[] = {state->n}; PyObject * magic_arr = PyArray_SimpleNewFromData(1, dims, NPY_INT, (void*) magic_qubit_numbers); PyArray_ENABLEFLAGS((PyArrayObject *)magic_arr, NPY_ARRAY_OWNDATA); //tell the array it owns its data so the array gets free'd QCircuit_free(W); StabTable_free(state); PyObject * pyChState = CHForm_to_python_tuple(&chState); PyObject * pyAGState = StabTable_to_python_tuple(agState); dealocate_state(&chState); StabTable_free(agState); //printf("hi\n"); //Py_DECREF(gates); //Py_DECREF(controls); //Py_DECREF(targets); //Py_DECREF(a); //printf("hi2\n"); return Py_BuildValue("iiiiiiiiiOOO", d, r, t, delta_d, delta_t, delta_t_prime, final_d, final_t, log_v, pyChState, pyAGState, magic_arr); } static PyObject * compress_algorithm_no_state_output(PyObject* self, PyObject* args){ PyArrayObject * gates; PyArrayObject * controls; PyArrayObject * targets; PyArrayObject * a; // project |a_i><a_i| on qubit i on the first w qubits (a is length w array) int n; int measured_qubits; if (!PyArg_ParseTuple(args, "iiO!O!O!O!", &n, &measured_qubits, &PyArray_Type, &gates, &PyArray_Type, &controls, &PyArray_Type, &targets, &PyArray_Type, &a )){ return NULL; } //clock_t start = clock(); //gatetize all the t gates int t = 0; for(int i = 0; i < gates->dimensions[0]; i++){ if(((char)gates->data[i*gates->strides[0]]) == T){ gates->data[i*gates->strides[0]] = CX; unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i); *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i); ptr = (unsigned int *)PyArray_GETPTR1(targets, i); *ptr = (unsigned int)(n + t); t += 1; } } //printf("\n"); //now we do the stabiliser evolution //to compute W //printf("t = %d\n", t); //printf("w = %d\n", measured_qubits); StabTable * state = StabTable_new(n+t, n+t); /* printf("0:\n"); */ /* StabTable_print(state); */ /* printf("\n"); */ for(int i = 0; i < gates->dimensions[0]; i++){ //printf("%d, %c, %d, %d\n", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]); switch((*(unsigned char *)PyArray_GETPTR1(gates,i))) { case CX: StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case CZ: StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case S: StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case H: StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; } } //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0> //we "fix" this by applying a bunch of X gates to the measured qubits here for(int i = 0; i < measured_qubits; i++){ if((*(unsigned char *)PyArray_GETPTR1(a,i)) == 1){ //printf("flipping %d\n",i); StabTable_X(state, i); } } //printf("Entering constraints code\n"); //StabTable_print(state);printf("\n"); int log_v = StabTable_apply_constraints(state, measured_qubits, t); //printf("constraints code returned log_v = %d\n",log_v); //StabTable_print(state);printf("\n"); if(log_v < 0){ return Py_BuildValue("d", 0); //PyComplex_FromDoubles(0., 0.); } //now delete the first (n) = table->n - t (since table->n = n + t at this point) qubits // at this point we should just be left with t qubits int q_to_delete = state->n - t; int new_size = t; for(int s = 0; s < state->k; s++){ for(int q = q_to_delete; q < state->n; q++){ state->table[s][q-q_to_delete] = state->table[s][q]; } for(int q = q_to_delete; q < state->n; q++){ state->table[s][q-2*q_to_delete+state->n] = state->table[s][q+state->n]; } state->table[s] = realloc(state->table[s], sizeof(unsigned char) * 2 * new_size); } state->n = new_size; int d = state->k; int r = state->n - state->k; //int * magic_qubit_numbers = calloc(state->n, sizeof(int)); //for(int i = 0; i < state->n; i++){ //magic_qubit_numbers[i] = i; //} int delta_t = StabTable_delete_all_identity_qubits(state, NULL); int delta_d = StabTable_apply_T_constraints(state,t); int delta_t_prime = StabTable_delete_all_identity_qubits(state, NULL); int final_d = state->k; int final_t = state->n; //QCircuit * W = StabTable_simplifying_unitary(state); //printf("after computing W\n"); //state->circ = NULL; //now we have to work out what we need to do magic sampling with this W circuit //we need the CH-form for W|\tilde{0}> //and the AG tableau for W|0> (no tilde!) //CHForm chState; //init_cb_CHForm(t,&chState); //Hadamard everything because we want to know the evolution of |\tilde{0}> = |+> //for(int i = 0; i < t; i++){ // HL(&chState, i); //} //printf("before computing chState & agState\n"); /* StabTable * agState = StabTable_new(t,t); */ /* for(int i = 0; i < W->length; i++){ */ /* switch(W->tape[i].tag) { */ /* case CX: */ /* CXL(&chState, W->tape[i].control, W->tape[i].target); */ /* StabTable_CX(agState, W->tape[i].control, W->tape[i].target); */ /* break; */ /* case CZ: */ /* CZL(&chState, W->tape[i].control, W->tape[i].target); */ /* StabTable_CZ(agState, W->tape[i].control, W->tape[i].target); */ /* break; */ /* case S: */ /* SL(&chState, W->tape[i].target); */ /* StabTable_S(agState, W->tape[i].target); */ /* break; */ /* case H: */ /* HL(&chState, W->tape[i].target); */ /* StabTable_H(agState, W->tape[i].target); */ /* break; */ /* } */ /* } */ /* npy_intp dims[] = {state->n}; */ /* PyObject * magic_arr = PyArray_SimpleNewFromData(1, dims, NPY_INT, (void*) magic_qubit_numbers); */ /* PyArray_ENABLEFLAGS((PyArrayObject *)magic_arr, NPY_ARRAY_OWNDATA); //tell the array it owns its data so the array gets free'd */ //QCircuit_free(W); StabTable_free(state); //PyObject * pyChState = CHForm_to_python_tuple(&chState); //PyObject * pyAGState = StabTable_to_python_tuple(agState); //dealocate_state(&chState); //StabTable_free(agState); //printf("hi\n"); //Py_DECREF(gates); //Py_DECREF(controls); //Py_DECREF(targets); //Py_DECREF(a); //printf("hi2\n"); return Py_BuildValue("iiiiiiiii", d, r, t, delta_d, delta_t, delta_t_prime, final_d, final_t, log_v); } static PyObject * compress_algorithm_no_region_c_constraints(PyObject* self, PyObject* args){ PyArrayObject * gates; PyArrayObject * controls; PyArrayObject * targets; PyArrayObject * a; // project |a_i><a_i| on qubit i on the first w qubits (a is length w array) int n; int measured_qubits; if (!PyArg_ParseTuple(args, "iiO!O!O!O!", &n, &measured_qubits, &PyArray_Type, &gates, &PyArray_Type, &controls, &PyArray_Type, &targets, &PyArray_Type, &a )){ return NULL; } //clock_t start = clock(); //gatetize all the t gates int t = 0; for(int i = 0; i < gates->dimensions[0]; i++){ if(((char)gates->data[i*gates->strides[0]]) == T){ gates->data[i*gates->strides[0]] = CX; unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i); *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i); ptr = (unsigned int *)PyArray_GETPTR1(targets, i); *ptr = (unsigned int)(n + t); t += 1; } } //printf("\n"); //now we do the stabiliser evolution //to compute W //printf("t = %d\n", t); //printf("w = %d\n", measured_qubits); StabTable * state = StabTable_new(n+t, n+t); /* printf("0:\n"); */ /* StabTable_print(state); */ /* printf("\n"); */ for(int i = 0; i < gates->dimensions[0]; i++){ //printf("%d, %c, %d, %d\n", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]); switch((*(unsigned char *)PyArray_GETPTR1(gates,i))) { case CX: StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case CZ: StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case S: StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; case H: StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i))); break; } } //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0> //we "fix" this by applying a bunch of X gates to the measured qubits here for(int i = 0; i < measured_qubits; i++){ if((*(unsigned char *)PyArray_GETPTR1(a,i)) == 1){ //printf("flipping %d\n",i); StabTable_X(state, i); } } //printf("Entering constraints code\n"); //StabTable_print(state);printf("\n"); int log_v = StabTable_apply_constraints(state, measured_qubits, t); //printf("constraints code returned log_v = %d\n",log_v); //StabTable_print(state);printf("\n"); if(log_v < 0){ StabTable_free(state); return Py_BuildValue("d", 0); //PyComplex_FromDoubles(0., 0.); } //now delete the first (n) = table->n - t (since table->n = n + t at this point) qubits // at this point we should just be left with t qubits int q_to_delete = state->n - t; int new_size = t; for(int s = 0; s < state->k; s++){ for(int q = q_to_delete; q < state->n; q++){ state->table[s][q-q_to_delete] = state->table[s][q]; } for(int q = q_to_delete; q < state->n; q++){ state->table[s][q-2*q_to_delete+state->n] = state->table[s][q+state->n]; } state->table[s] = realloc(state->table[s], sizeof(unsigned char) * 2 * new_size); } state->n = new_size; int d = state->k; int r = state->n - state->k; //int * magic_qubit_numbers = calloc(state->n, sizeof(int)); //for(int i = 0; i < state->n; i++){ //magic_qubit_numbers[i] = i; //} int delta_t = -1; int delta_d = -1; int delta_t_prime = -1; int final_d = state->k; int final_t = state->n; QCircuit * W = StabTable_simplifying_unitary(state); state->circ = NULL; //now we have to work out what we need to do magic sampling with this W circuit //we need the CH-form for W|\tilde{0}> //and the AG tableau for W|0> (no tilde!) CHForm chState; init_cb_CHForm(t,&chState); //Hadamard everything because we want to know the evolution of |\tilde{0}> = |+> for(int i = 0; i < t; i++){ HL(&chState, i); } //printf("before computing chState & agState\n"); StabTable * agState = StabTable_new(t,t); for(int i = 0; i < W->length; i++){ switch(W->tape[i].tag) { case CX: CXL(&chState, W->tape[i].control, W->tape[i].target); StabTable_CX(agState, W->tape[i].control, W->tape[i].target); break; case CZ: CZL(&chState, W->tape[i].control, W->tape[i].target); StabTable_CZ(agState, W->tape[i].control, W->tape[i].target); break; case S: SL(&chState, W->tape[i].target); StabTable_S(agState, W->tape[i].target); break; case H: HL(&chState, W->tape[i].target); StabTable_H(agState, W->tape[i].target); break; } } //npy_intp dims[] = {state->n}; //PyObject * magic_arr = PyArray_SimpleNewFromData(1, dims, NPY_INT, (void*) magic_qubit_numbers); //PyArray_ENABLEFLAGS((PyArrayObject *)magic_arr, NPY_ARRAY_OWNDATA); //tell the array it owns its data so the array gets free'd QCircuit_free(W); StabTable_free(state); PyObject * pyChState = CHForm_to_python_tuple(&chState); PyObject * pyAGState = StabTable_to_python_tuple(agState); dealocate_state(&chState); StabTable_free(agState); //d, r, t, delta_d, delta_t, delta_t_prime, final_d, final_t, log_v return Py_BuildValue("iiiiiiiiiOO", d, r, t, delta_d, delta_t, delta_t_prime, final_d, final_t, log_v, pyChState, pyAGState); } static PyObject * estimate_algorithm(PyObject* self, PyObject* args){ int magic_samples, equatorial_samples, r, log_v, measured_qubits, seed; PyObject * CHTuple; PyObject * AGTuple; if (!PyArg_ParseTuple(args, "iiiiiiO!O!", &magic_samples, &equatorial_samples, &measured_qubits, &log_v, &r, &seed, &PyTuple_Type, &CHTuple, &PyTuple_Type, &AGTuple )){ return NULL; } srand(seed); CHForm * chState = python_tuple_to_CHForm(CHTuple); StabTable * agState = python_tuple_to_StabTable(AGTuple); //at this point we want to generate a list of length equatorial_samples //containing r - qubit equatorial states //ie. r x r binary symmetric matrices equatorial_matrix_t * equatorial_matrices = calloc(equatorial_samples, sizeof(equatorial_matrix_t)); for(int i = 0; i < equatorial_samples; i++){ init_random_equatorial_matrix(&(equatorial_matrices[i]), r); } //printf("a\n"); uint_bitarray_t magic_mask = 0; for(int i = 0; i < agState->n; i++){ magic_mask |= (ONE<<i); } //printf("b\n"); uint_bitarray_t * ys = calloc(magic_samples, sizeof(uint_bitarray_t)); for(int i = 0; i < magic_samples; i++){ ys[i] = bitarray_rand() & magic_mask; } //printf("c\n"); uint_bitarray_t equatorial_mask = 0; for(int i = 0; i < r; i++){ equatorial_mask |= (ONE << i); } //printf("d\n"); //we project onto 0 and throw away the first t-r qubits //leaving us with an r qubit state uint_bitarray_t bitA = 0; uint_bitarray_t bitMask = 0; for(int i = 0; i < chState->n-r; i++){ bitMask |= (ONE << i); } //printf("e\n"); double complex * inner_prods = calloc(equatorial_samples, sizeof(double complex)); double complex alpha = (1. - I*(sqrt(2.) - 1.))/2.; double beta = log2(4. - 2.*sqrt(2.)); double complex alpha_phase = alpha / cabs(alpha); double complex alpha_c_phase = conj(alpha_phase); for(int i = 0; i < magic_samples; i++){ //printf("%d\n", i); //generate our state CHForm copy = copy_CHForm(chState); for(int bit = 0; bit < chState->n; bit++){ if((ys[i] >> bit) & ONE){ //apply W S^3_bit W^\dagger to chState uint_bitarray_t * z_mat = calloc(chState->n, sizeof(uint_bitarray_t)); uint_bitarray_t * x_mat = calloc(chState->n, sizeof(uint_bitarray_t)); uint_bitarray_t mask = (uint_bitarray_t)0; uint_bitarray_t t_mask = (uint_bitarray_t)0; unsigned int g = 2*agState->phases[bit] ; for(int j = 0; j < chState->n; j++){ if(agState->table[bit][j]){ x_mat[j] = copy.F[j]; z_mat[j] = copy.M[j]; mask |= (ONE << j); } if(agState->table[bit][j+agState->n]){ z_mat[j] ^= copy.G[j]; } t_mask |= (ONE << j); //if x and z are both 1 we get a factor of i because iXZ == Y if((agState->table[bit][j] == 1) && (agState->table[bit][j+agState->n] == 1)){ g += 1; } } g += popcount(copy.g1 & mask) + 2*popcount(copy.g2 & mask); g += 2*sort_pauli_string(chState->n, x_mat, z_mat, mask); uint_bitarray_t u = 0u; // u_m is exponent of X_m uint_bitarray_t h = 0u; // h_m is exponent of Z_m for(int k = 0; k < chState->n; k++){ if(agState->table[bit][k]){ u ^= (copy.F[k] & t_mask); h ^= (copy.M[k] & t_mask); } if(agState->table[bit][k+agState->n]){ h ^= (copy.G[k] & t_mask); } } //at this point the state we want is w U_c [I + i^g \prod_m Z_m^{h_m}X_m^{u_m}] U_H |s> //we need to commute the product through U_H //and then desuperpositionise //we pull the same trick again // (\prod_m X_m^{u_m}Z_m^{h_m} ) U_H = U_H (U_H^\dagger (\prod_m Z_m^{h_m}X_m^{u_m}) U_H) //n.b. Hadamard is self-adjoint //what happens - if V_k is zero then nothing happens //if V_k is 1 then we swap X and Z //if V_k is 1 and X and Z are both 1 we get a minus sign uint_bitarray_t u2 = (u & (~copy.v)) ^ (h & (copy.v)); uint_bitarray_t h2 = (h & (~copy.v)) ^ (u & (copy.v)); g += 2*parity(u & h & copy.v & t_mask); //at this point the state we want is w U_c [I + i^g U_H \prod_m Z_m^{h2_m} X_m^{u2_m}] |s> //we apply the paulis to |s> //every x flips a bit of s //every time a z hits a |1> we get a -1 //xs happen first uint_bitarray_t y = (copy.s ^ u2) & t_mask; g += 2*parity(y & h2 & t_mask); g += 1; //an i appears in the expression for S^3 in terms of Z and I g %= 4; //at this point the state we want is w e^{-i\pi/4}/sqrt{2} U_c U_h( |s> + i^(g) |y>) //extra factors from the formula for S^3 if((y & t_mask) == (copy.s & t_mask)){ double complex a = 1.; if(g == 0){ a += 1.; } if(g == 1){ a += (1.)*I; } if(g == 2){ a += (-1.); } if(g == 3){ a += (-1.*I); } copy.w *= (a*(1 - 1.*I)/2.); }else{ desupersitionise(&copy, y, g); copy.w *= (1.-1.*I)/2.; } free(x_mat); free(z_mat); } } //at this point copy contains our magic sample //we want to project it and do fastnorm estimation //now we project onto the measurement outcomes for the w qubits postselect_and_reduce(&copy, bitA, bitMask); int hamming_weight = popcount(ys[i]); double complex prefactor = powl(2., ((beta + 1)*chState->n + log_v - measured_qubits)/2.)*cpowl(alpha_phase, chState->n-hamming_weight)*cpowl(alpha_c_phase, hamming_weight); for(int j = 0; j < equatorial_samples; j++){ //CHForm copy2 = copy_CHForm(&copy); double complex d = conj(equatorial_inner_product(&copy, equatorial_matrices[j]))/(double)(magic_samples); inner_prods[j] += prefactor*d; } dealocate_state(&copy); } free(ys); double acc = 0; for(int j = 0; j < equatorial_samples; j++){ acc += creal(inner_prods[j]*conj(inner_prods[j]))/(double)equatorial_samples; } free(inner_prods); for(int j = 0; j < equatorial_samples; j++){ dealocate_equatorial_matrix(&equatorial_matrices[j]); } free(equatorial_matrices); StabTable_free(agState); dealocate_state(chState); free(chState); return PyComplex_FromDoubles(creal(acc), cimag(acc)); } static PyObject * estimate_algorithm_r_equals_0(PyObject* self, PyObject* args){ int magic_samples, log_v, seed; PyObject * CHTuple; PyObject * AGTuple; if (!PyArg_ParseTuple(args, "iiiO!O!", &magic_samples, &log_v, &seed, &PyTuple_Type, &CHTuple, &PyTuple_Type, &AGTuple )){ return NULL; } srand(seed); CHForm * chState = python_tuple_to_CHForm(CHTuple); StabTable * agState = python_tuple_to_StabTable(AGTuple); uint_bitarray_t magic_mask = 0; for(int i = 0; i < agState->n; i++){ magic_mask |= (ONE<<i); } //printf("b\n"); uint_bitarray_t * ys = calloc(magic_samples, sizeof(uint_bitarray_t)); for(int i = 0; i < magic_samples; i++){ ys[i] = bitarray_rand() & magic_mask; } double complex alpha = (1. - I*(sqrt(2.) - 1.))/2.; double beta = log2(4. - 2.*sqrt(2.)); double complex alpha_phase = alpha / cabs(alpha); double complex alpha_c_phase = conj(alpha_phase); double complex acc = 0; for(int i = 0; i < magic_samples; i++){ //printf("%d\n", i); //generate our state CHForm copy = copy_CHForm(chState); for(int bit = 0; bit < chState->n; bit++){ if((ys[i] >> bit) & ONE){ //apply W S^3_bit W^\dagger to chState uint_bitarray_t * z_mat = calloc(chState->n, sizeof(uint_bitarray_t)); uint_bitarray_t * x_mat = calloc(chState->n, sizeof(uint_bitarray_t)); uint_bitarray_t mask = (uint_bitarray_t)0; uint_bitarray_t t_mask = (uint_bitarray_t)0; unsigned int g = 2*agState->phases[bit] ; for(int j = 0; j < chState->n; j++){ if(agState->table[bit][j]){ x_mat[j] = copy.F[j]; z_mat[j] = copy.M[j]; mask |= (ONE << j); } if(agState->table[bit][j+agState->n]){ z_mat[j] ^= copy.G[j]; } t_mask |= (ONE << j); //if x and z are both 1 we get a factor of i because iXZ == Y if((agState->table[bit][j] == 1) && (agState->table[bit][j+agState->n] == 1)){ g += 1; } } g += popcount(copy.g1 & mask) + 2*popcount(copy.g2 & mask); g += 2*sort_pauli_string(chState->n, x_mat, z_mat, mask); uint_bitarray_t u = 0u; // u_m is exponent of X_m uint_bitarray_t h = 0u; // h_m is exponent of Z_m for(int k = 0; k < chState->n; k++){ if(agState->table[bit][k]){ u ^= (copy.F[k] & t_mask); h ^= (copy.M[k] & t_mask); } if(agState->table[bit][k+agState->n]){ h ^= (copy.G[k] & t_mask); } } //at this point the state we want is w U_c [I + i^g \prod_m Z_m^{h_m}X_m^{u_m}] U_H |s> //we need to commute the product through U_H //and then desuperpositionise //we pull the same trick again // (\prod_m X_m^{u_m}Z_m^{h_m} ) U_H = U_H (U_H^\dagger (\prod_m Z_m^{h_m}X_m^{u_m}) U_H) //n.b. Hadamard is self-adjoint //what happens - if V_k is zero then nothing happens //if V_k is 1 then we swap X and Z //if V_k is 1 and X and Z are both 1 we get a minus sign uint_bitarray_t u2 = (u & (~copy.v)) ^ (h & (copy.v)); uint_bitarray_t h2 = (h & (~copy.v)) ^ (u & (copy.v)); g += 2*parity(u & h & copy.v & t_mask); //at this point the state we want is w U_c [I + i^g U_H \prod_m Z_m^{h2_m} X_m^{u2_m}] |s> //we apply the paulis to |s> //every x flips a bit of s //every time a z hits a |1> we get a -1 //xs happen first uint_bitarray_t y = (copy.s ^ u2) & t_mask; g += 2*parity(y & h2 & t_mask); g += 1; //an i appears in the expression for S^3 in terms of Z and I g %= 4; //at this point the state we want is w e^{-i\pi/4}/sqrt{2} U_c U_h( |s> + i^(g) |y>) //extra factors from the formula for S^3 if((y & t_mask) == (copy.s & t_mask)){ double complex a = 1.; if(g == 0){ a += 1.; } if(g == 1){ a += (1.)*I; } if(g == 2){ a += (-1.); } if(g == 3){ a += (-1.*I); } copy.w *= (a*(1 - 1.*I)/2.); }else{ desupersitionise(&copy, y, g); copy.w *= (1.-1.*I)/2.; } free(x_mat); free(z_mat); } } //at this point copy contains our magic sample //we want to project it - no fast norm needed as r = 0 int hamming_weight = popcount(ys[i]); double complex prefactor = powl(2., ((beta)*chState->n + log_v)/2.)*cpowl(alpha_phase, chState->n-hamming_weight)*cpowl(alpha_c_phase, hamming_weight); double complex overlap = measurement_overlap(&copy, (uint_bitarray_t)0); acc += prefactor*overlap/magic_samples; dealocate_state(&copy); } double complex prob = creal(acc*conj(acc)); free(ys); StabTable_free(agState); dealocate_state(chState); free(chState); return PyComplex_FromDoubles(creal(prob), cimag(prob)); } //if inverse == 1 apply H S^3 H, otherwise apply H S H static void applyHSH_to_CHForm(CHForm * chState, StabTable * agState, int bit, unsigned char inverse, uint_bitarray_t * x_mat, uint_bitarray_t * z_mat){ uint_bitarray_t mask = (uint_bitarray_t)0; uint_bitarray_t t_mask = (uint_bitarray_t)0; unsigned int g = 2*agState->phases[bit]; for(int j = 0; j < chState->n; j++){ if(agState->table[bit][j]){ x_mat[j] = chState->F[j]; z_mat[j] = chState->M[j]; mask |= (ONE << j); } if(agState->table[bit][j+agState->n]){ z_mat[j] ^= chState->G[j]; } t_mask |= (ONE << j); //if x and z are both 1 we get a factor of i because iXZ == Y if((agState->table[bit][j] == 1) && (agState->table[bit][j+agState->n] == 1)){ g += 1; } } g += popcount(chState->g1 & mask) + 2*popcount(chState->g2 & mask); g += 2*sort_pauli_string(chState->n, x_mat, z_mat, mask); uint_bitarray_t u = 0u; // u_m is exponent of X_m uint_bitarray_t h = 0u; // h_m is exponent of Z_m for(int k = 0; k < chState->n; k++){ if(agState->table[bit][k]){ u ^= (chState->F[k] & t_mask); h ^= (chState->M[k] & t_mask); } if(agState->table[bit][k+agState->n]){ h ^= (chState->G[k] & t_mask); } } //at this point the state we want is w U_c [I + i^g \prod_m Z_m^{h_m}X_m^{u_m}] U_H |s> //we need to commute the product through U_H //and then desuperpositionise //we pull the same trick again // (\prod_m X_m^{u_m}Z_m^{h_m} ) U_H = U_H (U_H^\dagger (\prod_m Z_m^{h_m}X_m^{u_m}) U_H) //n.b. Hadamard is self-adjoint //what happens - if V_k is zero then nothing happens //if V_k is 1 then we swap X and Z //if V_k is 1 and X and Z are both 1 we get a minus sign uint_bitarray_t u2 = (u & (~chState->v)) ^ (h & (chState->v)); uint_bitarray_t h2 = (h & (~chState->v)) ^ (u & (chState->v)); g += 2*parity(u & h & chState->v & t_mask); //at this point the state we want is w U_c [I + i^g U_H \prod_m Z_m^{h2_m} X_m^{u2_m}] |s> //we apply the paulis to |s> //every x flips a bit of s //every time a z hits a |1> we get a -1 //xs happen first uint_bitarray_t y = (chState->s ^ u2) & t_mask; g += 2*parity(y & h2 & t_mask); g += (3 + 2*inverse); //an i appears in the expression for S^3 in terms of Z and I, and a -i appears in the expression for S g %= 4; //at this point the state we want is w e^{\pm i\pi/4}/sqrt{2} U_c U_h( |s> + i^(g) |y>) //extra factors from the formula for S^3 //if we're doing S^3 it should be e^{-i\pi/4} and if we're doing S it should be e^{i\pi/4} if((y & t_mask) == (chState->s & t_mask)){ double complex a = 1.; if(g == 0){ a += 1.; } if(g == 1){ a += (1.)*I; } if(g == 2){ a += (-1.); } if(g == 3){ a += (-1.*I); } chState->w *= a; //(a*(1 - 1.*I)/2.); }else{ desupersitionise(chState, y, g); } chState->w *= (1.+1.*I)/2.; if(inverse == 1){ chState->w *= (-1.)*I; } memset(x_mat, 0, sizeof(uint_bitarray_t)*chState->n); memset(z_mat, 0, sizeof(uint_bitarray_t)*chState->n); } static PyObject * estimate_algorithm_with_arbitrary_phases(PyObject* self, PyObject* args){ int magic_samples, equatorial_samples, r, log_v, measured_qubits, seed; PyObject * CHTuple; PyObject * AGTuple; PyArrayObject * phases; if (!PyArg_ParseTuple(args, "iiiiiiO!O!O!", &magic_samples, &equatorial_samples, &measured_qubits, &log_v, &r, &seed, &PyTuple_Type, &CHTuple, &PyTuple_Type, &AGTuple, &PyArray_Type, &phases )){ return NULL; } srand(seed); gsl_rng * RNG = gsl_rng_alloc(gsl_rng_mt19937); gsl_rng_set(RNG, seed); CHForm * chState = python_tuple_to_CHForm(CHTuple); StabTable * agState = python_tuple_to_StabTable(AGTuple); double complex * alpha_phases = calloc(chState->n, sizeof(double complex)); //now we allow arbitrary phase gates different gates need different alphas double complex * alpha_prime_phases = calloc(chState->n, sizeof(double complex)); double stab_extent_sqrt = 1.; //printf("chState->n = %d\n", chState->n); double * probs = calloc(chState->n, sizeof(double)); for(int i = 0; i < chState->n; i++){ double phase; phase = *(double *)PyArray_GETPTR1(phases, i); //printf("phase[%d] = %lf\n", i, phase); alpha_phases[i] = (I + cexpl(-1.*I*phase))/((1. + I)*sqrt(1. - sinl(phase))); alpha_prime_phases[i] = (1. - cexpl(-1.*I*phase))/((1. + I)*sqrt(1. - cosl(phase))); stab_extent_sqrt *= (sqrt(1. - sinl(phase)) + sqrt(1. - cosl(phase))); probs[i] = sqrt(1.-sin(phase))/(sqrt(1.-sin(phase)) + sqrt(1.-cos(phase))); //printf("%d: (%lf, %lf), (%lf, %lf)\n", i, creal(alpha_phases[i]), cimag(alpha_phases[i]), creal(alpha_prime_phases[i]), cimag(alpha_prime_phases[i])); } //printf("stab_extent_sqrt = %lf\n", stab_extent_sqrt); //at this point we want to generate a list of length equatorial_samples //containing r - qubit equatorial states //ie. r x r binary symmetric matrices equatorial_matrix_t * equatorial_matrices = calloc(equatorial_samples, sizeof(equatorial_matrix_t)); for(int i = 0; i < equatorial_samples; i++){ init_random_equatorial_matrix(&(equatorial_matrices[i]), r); } //printf("a\n"); uint_bitarray_t magic_mask = 0; for(int i = 0; i < agState->n; i++){ magic_mask |= (ONE<<i); } //printf("b\n"); uint_bitarray_t * ys = calloc(magic_samples, sizeof(uint_bitarray_t)); for(int i = 0; i < magic_samples; i++){ ys[i] = (uint_bitarray_t)0; for(int bit = 0; bit < agState->n; bit++){ if(!gsl_ran_bernoulli(RNG, probs[bit])){ ys[i] |= (ONE << bit); } } } //printf("c\n"); uint_bitarray_t equatorial_mask = 0; for(int i = 0; i < r; i++){ equatorial_mask |= (ONE << i); } //printf("d\n"); //we project onto 0 and throw away the first t-r qubits //leaving us with an r qubit state uint_bitarray_t bitA = 0; uint_bitarray_t bitMask = 0; for(int i = 0; i < ((int)chState->n)-((int)r); i++){ bitMask |= (ONE << i); } double complex * inner_prods = calloc(equatorial_samples, sizeof(double complex)); //we will use this memory when doing the magic sampling uint_bitarray_t * z_mat = calloc(chState->n, sizeof(uint_bitarray_t)); uint_bitarray_t * x_mat = calloc(chState->n, sizeof(uint_bitarray_t)); //we will use this memory when doing fastnorm uint_bitarray_t * AJ = calloc(chState->n, sizeof(uint_bitarray_t)); uint_bitarray_t * GT = calloc(chState->n, sizeof(uint_bitarray_t)); uint_bitarray_t * bitK = calloc(chState->n, sizeof(uint_bitarray_t)); uint_bitarray_t * X = calloc(chState->n, sizeof(uint_bitarray_t)); uint_bitarray_t * Y = calloc(chState->n, sizeof(uint_bitarray_t)); uint_bitarray_t * M = calloc(chState->n+1, sizeof(uint_bitarray_t)); CHForm allOnesState = copy_CHForm(chState); for(int bit = 0; bit < chState->n; bit++){ applyHSH_to_CHForm(&allOnesState, agState, bit, (unsigned char)1, x_mat, z_mat); } for(int i = 0; i < magic_samples; i++){ double complex prefactor = stab_extent_sqrt * cpowl(2., (((int)chState->n) /*- ((int)r)*/ + ((int)log_v) - ((int)measured_qubits))/2.); /* printf("stab_extent_sqrt = %lf\n", stab_extent_sqrt); */ /* printf("%d\n", chState->n); */ /* printf("%d\n", r); */ /* printf("%d\n", log_v); */ /* printf("%d\n", measured_qubits); */ /* printf("%lf\n", (((int)chState->n) - ((int)r) + ((int)log_v) - ((int)measured_qubits))/2.); */ //printf("prefactor = %lf + %lf*I\n", creal(prefactor), cimag(prefactor)); //printf("%d\n", i); //generate our state CHForm * state_to_copy = NULL; int hamming_weight = popcount(ys[i]); unsigned char inverse = 1; if(2*hamming_weight > chState->n){ //if the Hamming weight is big we're better starting with the all ones state state_to_copy = &allOnesState; inverse = 0; //apply H S H to flip bits from 1 to 0 }else{ //if the Hamming weight is small we're better starting with the all zeros state state_to_copy = chState; inverse = 1; // apply H S^3 H to flip bits from 0 to 1 } CHForm copy = copy_CHForm(state_to_copy); for(int bit = 0; bit < chState->n; bit++){ if((ys[i] >> bit) & ONE){ prefactor *= alpha_prime_phases[bit]; }else{ prefactor *= alpha_phases[bit]; } if(((ys[i] >> bit) & ONE) == inverse){ //apply W S^3_bit W^\dagger to chState applyHSH_to_CHForm(&copy, agState, bit, inverse, x_mat, z_mat); } } //printf("prefactor = %lf + %lf *I\n", creal(prefactor), cimag(prefactor)); //at this point copy contains our magic sample //we want to project it and do fastnorm estimation //now we project onto the measurement outcomes for the w qubits postselect_and_reduce(&copy, bitA, bitMask); //int hamming_weight = popcount(ys[i]); //double complex prefactor = powl(2., ((beta + 1)*chState->n + log_v - measured_qubits)/2.)*cpowl(alpha_phase, chState->n-hamming_weight)*cpowl(alpha_c_phase, hamming_weight); for(size_t i = 0; i < copy.n; i++){ for(size_t j = 0; j < copy.n; j++){ GT[j] |= ((copy.G[i] >> j) & ONE) << i; } } for(int j = 0; j < equatorial_samples; j++){ //CHForm copy2 = copy_CHForm(&copy); double complex d = conj(equatorial_inner_product_no_alloc(&copy, equatorial_matrices[j], AJ, GT, X,Y, bitK,M))/(double)(magic_samples); //printf("(%lf, %lf), (%lf, %lf)\n", creal(prefactor), cimag(prefactor), creal(d), cimag(d)); inner_prods[j] += prefactor*d; } memset(GT, 0, sizeof(uint_bitarray_t)*agState->n); dealocate_state(&copy); } free(x_mat); free(z_mat); free(AJ); free(GT); free(X); free(Y); free(bitK); free(M); free(probs); free(ys); free(alpha_phases); free(alpha_prime_phases); double acc = 0; for(int j = 0; j < equatorial_samples; j++){ acc += creal(inner_prods[j]*conj(inner_prods[j]))/(double)equatorial_samples; } free(inner_prods); for(int j = 0; j < equatorial_samples; j++){ dealocate_equatorial_matrix(&equatorial_matrices[j]); } gsl_rng_free(RNG); free(equatorial_matrices); StabTable_free(agState); dealocate_state(chState); free(chState); //dealocate_state(&allOnesState); return PyComplex_FromDoubles(creal(acc), cimag(acc)); } static PyMethodDef myMethods[] = { { "apply_gates_to_basis_state_project_and_reduce", apply_gates_to_basis_state_project_and_reduce, METH_VARARGS, "Applies a bunch of gates to an initial computational-basis state, then applies a bunch of z projectors and removes the (now product state) qubits we projected"}, { "magic_sample_1", magic_sample_1, METH_VARARGS, "do the sampling algorithm with magic sampling first"}, { "magic_sample_2", magic_sample_2, METH_VARARGS, "do the sampling algorithm with fastnorm first"}, { "main_simulation_algorithm", main_simulation_algorithm, METH_VARARGS, "compute a computational basis measurement outcome overlap"}, { "main_simulation_algorithm2", main_simulation_algorithm2, METH_VARARGS, "compute a computational basis measurement outcome overlap dumb sampling method"}, { "v_r_info", v_r_info, METH_VARARGS, "stuff"}, { "lhs_rank_info", lhs_rank_info, METH_VARARGS, "stuff"}, { "compute_algorithm", compute_algorithm, METH_VARARGS, "stuff"}, { "compress_algorithm", compress_algorithm, METH_VARARGS, "Run the compress algorithm precomputation"}, { "compress_algorithm_no_region_c_constraints", compress_algorithm_no_region_c_constraints, METH_VARARGS, "Run the compress algorithm precomputation without region c constraints"}, { "compress_algorithm_no_state_output", compress_algorithm_no_state_output, METH_VARARGS, "Run the compress algorithm precomputation without computing AG state and CH state"}, { "estimate_algorithm", estimate_algorithm, METH_VARARGS, "Run the estimate algorithm"}, { "estimate_algorithm_r_equals_0", estimate_algorithm_r_equals_0, METH_VARARGS, "Run the estimate algorithm when r = 0"}, { "estimate_algorithm_with_arbitrary_phases", estimate_algorithm_with_arbitrary_phases, METH_VARARGS, "Run the estimate algorithm"}, { NULL, NULL, 0, NULL } }; // Our Module Definition struct static struct PyModuleDef clifford_t_estim = { PyModuleDef_HEAD_INIT, "clifford_t_estim", "Interface with c Cliffor+T estimation code", -1, myMethods }; // Initializes our module using our above struct PyMODINIT_FUNC PyInit_clifford_t_estim(void) { import_array(); //double x = 5.0; //double y = gsl_sf_bessel_J0 (x); //printf ("J0(%g) = %.18e\n", x, y); //printf("Hello!\n"); return PyModule_Create(&clifford_t_estim); }
{ "alphanum_fraction": 0.5203667561, "avg_line_length": 36.4384753134, "ext": "c", "hexsha": "42c813ed310056b3b6174413151962796f01ab26", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-02-02T11:13:11.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-02T11:13:11.000Z", "max_forks_repo_head_hexsha": "c460c143f25fc637aa18c2907e01afeea46112e0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "or1426/Cliford-T-estimator", "max_forks_repo_path": "cmodule.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "c460c143f25fc637aa18c2907e01afeea46112e0", "max_issues_repo_issues_event_max_datetime": "2021-02-02T11:18:49.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-02T11:18:00.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "or1426/Cliford-T-estimator", "max_issues_repo_path": "cmodule.c", "max_line_length": 278, "max_stars_count": 8, "max_stars_repo_head_hexsha": "c460c143f25fc637aa18c2907e01afeea46112e0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "or1426/Cliford-T-estimator", "max_stars_repo_path": "cmodule.c", "max_stars_repo_stars_event_max_datetime": "2021-09-15T04:01:29.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-01T13:17:22.000Z", "num_tokens": 41486, "size": 142438 }
// MIT License // // Copyright (c) 2020 SunnyCase // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <board.h> #include <chino/ddk/list.h> #include <chino/ddk/object.h> #include <chino/threading.h> #include <gsl/gsl-lite.hpp> namespace chino::threading { namespace details { struct kthread_checker; } struct kprocess; struct kthread : public ob::object { static constexpr ptrdiff_t PROCESS_THREAD_ENTRY_OFFSET = 0; static constexpr ptrdiff_t SCHED_ENTRY_OFFSET = PROCESS_THREAD_ENTRY_OFFSET + VOID_LIST_NODE_SIZE; kthread() = default; void init_stack(gsl::span<uintptr_t> stack, thread_start_t start, void *arg) noexcept; friend struct details::kthread_checker; // BEGIN LIST NODES, BE CAREFUL ABOUT THE OFFSETS !!! list_node<kthread, void, PROCESS_THREAD_ENTRY_OFFSET> process_threads_entry_; list_node<kthread, void, SCHED_ENTRY_OFFSET> sched_entry_; // END LIST NODES kprocess *owner_ = nullptr; tid_t tid_; thread_priority priority_; std::atomic<uint32_t> exit_code_; gsl::span<uintptr_t> stack_; arch::thread_context_t context_; }; namespace details { struct kthread_checker { static_assert(offsetof(kthread, process_threads_entry_) == kthread::PROCESS_THREAD_ENTRY_OFFSET); }; } }
{ "alphanum_fraction": 0.7502149613, "avg_line_length": 33.2285714286, "ext": "h", "hexsha": "aa294b415b0a8fa842201dfc57223b6b7ebdc9fe", "lang": "C", "max_forks_count": 20, "max_forks_repo_forks_event_max_datetime": "2021-09-13T10:14:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-05-18T03:54:08.000Z", "max_forks_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dotnetGame/chino-os", "max_forks_repo_path": "src/kernel/include/chino/threading/thread.h", "max_issues_count": 7, "max_issues_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_issues_repo_issues_event_max_datetime": "2020-04-30T14:46:51.000Z", "max_issues_repo_issues_event_min_datetime": "2018-05-15T02:15:33.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dotnetGame/chino-os", "max_issues_repo_path": "src/kernel/include/chino/threading/thread.h", "max_line_length": 105, "max_stars_count": 137, "max_stars_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "chino-os/chino-os", "max_stars_repo_path": "src/kernel/include/chino/threading/thread.h", "max_stars_repo_stars_event_max_datetime": "2022-03-10T11:42:23.000Z", "max_stars_repo_stars_event_min_datetime": "2018-04-28T09:50:17.000Z", "num_tokens": 530, "size": 2326 }
/* interpolation/spline.c * * Copyright (C) 2001, 2007 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <string.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> gsl_spline * gsl_spline_alloc (const gsl_interp_type * T, size_t size) { gsl_spline * spline = (gsl_spline *) malloc (sizeof(gsl_spline)); if (spline == NULL) { GSL_ERROR_NULL ("failed to allocate space for spline struct", GSL_ENOMEM); } spline->interp = gsl_interp_alloc (T, size); if (spline->interp == NULL) { free (spline); GSL_ERROR_NULL ("failed to allocate space for interp", GSL_ENOMEM); }; spline->x = (double *) malloc (size * sizeof(double)); if (spline->x == NULL) { gsl_interp_free(spline->interp); free(spline); GSL_ERROR_NULL ("failed to allocate space for x", GSL_ENOMEM); } spline->y = (double *) malloc (size * sizeof(double)); if (spline->y == NULL) { free(spline->x); gsl_interp_free(spline->interp); free(spline); GSL_ERROR_NULL ("failed to allocate space for y", GSL_ENOMEM); } spline->size = size; return spline; } int gsl_spline_init (gsl_spline * spline, const double x_array[], const double y_array[], size_t size) { if (size != spline->size) { GSL_ERROR ("data must match size of spline object", GSL_EINVAL); } memcpy (spline->x, x_array, size * sizeof(double)); memcpy (spline->y, y_array, size * sizeof(double)); { int status = gsl_interp_init (spline->interp, x_array, y_array, size); return status; } } const char * gsl_spline_name(const gsl_spline * spline) { return gsl_interp_name(spline->interp); } unsigned int gsl_spline_min_size(const gsl_spline * spline) { return gsl_interp_min_size(spline->interp); } void gsl_spline_free (gsl_spline * spline) { RETURN_IF_NULL (spline); gsl_interp_free (spline->interp); free (spline->x); free (spline->y); free (spline); } int gsl_spline_eval_e (const gsl_spline * spline, double x, gsl_interp_accel * a, double *y) { return gsl_interp_eval_e (spline->interp, spline->x, spline->y, x, a, y); } double gsl_spline_eval (const gsl_spline * spline, double x, gsl_interp_accel * a) { return gsl_interp_eval (spline->interp, spline->x, spline->y, x, a); } int gsl_spline_eval_deriv_e (const gsl_spline * spline, double x, gsl_interp_accel * a, double *dydx) { return gsl_interp_eval_deriv_e (spline->interp, spline->x, spline->y, x, a, dydx); } double gsl_spline_eval_deriv (const gsl_spline * spline, double x, gsl_interp_accel * a) { return gsl_interp_eval_deriv (spline->interp, spline->x, spline->y, x, a); } int gsl_spline_eval_deriv2_e (const gsl_spline * spline, double x, gsl_interp_accel * a, double * d2) { return gsl_interp_eval_deriv2_e (spline->interp, spline->x, spline->y, x, a, d2); } double gsl_spline_eval_deriv2 (const gsl_spline * spline, double x, gsl_interp_accel * a) { return gsl_interp_eval_deriv2 (spline->interp, spline->x, spline->y, x, a); } int gsl_spline_eval_integ_e (const gsl_spline * spline, double a, double b, gsl_interp_accel * acc, double * result) { return gsl_interp_eval_integ_e (spline->interp, spline->x, spline->y, a, b, acc, result); } double gsl_spline_eval_integ (const gsl_spline * spline, double a, double b, gsl_interp_accel * acc) { return gsl_interp_eval_integ (spline->interp, spline->x, spline->y, a, b, acc); }
{ "alphanum_fraction": 0.5644599303, "avg_line_length": 26.4923076923, "ext": "c", "hexsha": "3d8605d89fc6482f59f58b5661e5e55e7fefc9e2", "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/interpolation/spline.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/interpolation/spline.c", "max_line_length": 98, "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/interpolation/spline.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": 1233, "size": 5166 }
/** * * Copyright 2018, Planet Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_multifit.h> #include <math.h> void wrap_gsl_multifit_robust(double *x, double *y, double *c, double *adj_Rsqrd, int *numIter, double *rmse, int method, int perPixelX, int numRows, int numCols, int numImages, int numParams, int numRowsX, int numColsX, double nullVal);
{ "alphanum_fraction": 0.7202072539, "avg_line_length": 35.7407407407, "ext": "h", "hexsha": "ffadadf96b434eaf5405120cae2a5c63db3de139", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2021-09-28T02:08:24.000Z", "max_forks_repo_forks_event_min_datetime": "2019-03-20T10:39:55.000Z", "max_forks_repo_head_hexsha": "f1f46e07c7ee45c3d11e066795e110a0019518e5", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "planetlabs/planet-tmask", "max_forks_repo_path": "tmask/robreg.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f1f46e07c7ee45c3d11e066795e110a0019518e5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "planetlabs/planet-tmask", "max_issues_repo_path": "tmask/robreg.h", "max_line_length": 81, "max_stars_count": 8, "max_stars_repo_head_hexsha": "f1f46e07c7ee45c3d11e066795e110a0019518e5", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "planetlabs/planet-tmask", "max_stars_repo_path": "tmask/robreg.h", "max_stars_repo_stars_event_max_datetime": "2021-12-09T08:49:02.000Z", "max_stars_repo_stars_event_min_datetime": "2018-08-14T04:53:26.000Z", "num_tokens": 242, "size": 965 }
#include <stdlib.h> #include <complex.h> #include <float.h> #include <math.h> #include <string.h> #ifdef _MACOSX #include <Accelerate/Accelerate.h> #else #include <cblas.h> #endif #include "fastsphere.h" #include "spreflect.h" #include "translator.h" #include "scatmat.h" #include "fsht.h" #include "farfield.h" #include "util.h" /* Reflect incoming plane waves from the surfaces of all spheres. */ int sprflpw (complex double *rhs, spscat *spl, int nsph, shdata *shtr) { int i, nterm; complex double *vptr; spscat *sp; nterm = shtr->ntheta * shtr->nphi; #pragma omp parallel for private(i,vptr,sp) default(shared) for (i = 0; i < nsph; ++i) { sp = spl + i; vptr = rhs + i * nterm; /* Multiply by the reflection coefficient in SH space. */ ffsht (vptr, shtr, sp->spdesc->deg); spreflect (vptr, vptr, (spl + i)->spdesc->reflect, sp->spdesc->deg, shtr->nphi, 0, 1); ifsht (vptr, shtr, sp->spdesc->deg); } return nsph; } /* Compute translations between all spheres. Augments the output vector, does * not overwrite it. */ int sptrans (complex double *vout, complex double *vin, int nsph, trdesc *trans, shdata *shtr) { int nterm, nsq; nterm = shtr->ntheta * shtr->nphi; nsq = nsph * nsph; /* Perform the translations. */ #pragma omp parallel default(shared) { complex double *voptr, *viptr; int i, j, off, k; #pragma omp for for (off = 0; off < nsq; ++off) { j = off / nsph; /* Source sphere. */ i = off % nsph; /* Destination sphere. */ /* Don't bother with self-translations. Also ignore dense * translations for the moment. */ if (i == j || trans[off].type != TRPLANE) continue; /* Do the diagonal, plane-wave translation. */ voptr = vout + i * nterm; viptr = vin + j * nterm; /* Copy to output, but only one thread at a time. */ #pragma omp critical(outplane) for (k = 0; k < nterm; ++k) voptr[k] += trans[off].trdata[k] * viptr[k]; } } return nsph; } /* Compute the MVP between the scattering matrix and a specified vector. */ int scatmat (complex double *vout, complex double *vin, spscat *spl, int nsph, trdesc *trans, shdata *shtr) { int nterm, n, i; nterm = shtr->ntheta * shtr->nphi; n = nterm * nsph; /* Initialize the output bufer. */ memset (vout, 0, n * sizeof(complex double)); /* Compute the spherical translations. */ sptrans (vout, vin, nsph, trans, shtr); /* Compute the reflections of plane waves at sphere surfaces. */ sprflpw (vout, spl, nsph, shtr); /* Subtract the incoming field from the outgoing field. */ #pragma omp parallel for private(i) default(shared) for (i = 0; i < n; ++i) vout[i] = vin[i] - vout[i]; return nsph; } int bicgstab (complex double *sol, complex double *rhs, int guess, spscat *spl, int nsph, trdesc *trans, shdata *shtr, itconf *itc) { int i, j, n, nterm; complex double *r, *rhat, *v, *p, *t; complex double rho, alpha, omega, beta; double err, rhn; nterm = shtr->ntheta * shtr->nphi; n = nterm * nsph; rho = alpha = omega = 1.; /* Allocate and zero the work arrays. */ r = calloc (5 * n, sizeof(complex double)); rhat = r + n; v = rhat + n; p = v + n; t = p + n; /* Compute the norm of the right-hand side for residual scaling. */ rhn = cblas_dznrm2 (n, rhs, 1); /* Compute the inital matrix-vector product for the input guess. */ if (guess) scatmat (r, sol, spl, nsph, trans, shtr); /* Subtract from the RHS to form the residual. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) r[j] = rhs[j] - r[j]; if (!guess) memset (sol, 0, n * sizeof(complex double)); /* Copy the initial residual as the test vector. */ memcpy (rhat, r, n * sizeof(complex double)); /* Find the norm of the initial residual. */ err = cblas_dznrm2(n, r, 1) / rhn; printf ("True residual: %g\n", err); /* Run iterations until convergence or the maximum is reached. */ for (i = 0; i < itc->iter && err > itc->eps; ++i) { /* Pre-compute portion of beta from previous iteration. */ beta = alpha / (rho * omega); /* Compute rho for this iteration. */ rho = pardot (rhat, r, n); /* Include the missing factor in beta. */ beta *= rho; /* Update the search vector. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) p[j] = r[j] + beta * (p[j] - omega * v[j]); /* Compute the first search step, v = A * p. */ scatmat (v, p, spl, nsph, trans, shtr); /* Compute the next alpha. */ alpha = rho / pardot (rhat, v, n); #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) { /* Update the solution vector. */ sol[j] += alpha * p[j]; /* Update the residual vector. */ r[j] -= alpha * v[j]; } /* Compute the scaled residual norm and stop if convergence * has been achieved. */ err = cblas_dznrm2 (n, r, 1) / rhn; printf ("BiCG-STAB(%0.1f): %g\n", 0.5 + i, err); if (err < itc->eps) break; /* Compute the next search step, t = A * r. */ scatmat (t, r, spl, nsph, trans, shtr); /* Compute the update direction. */ omega = pardot (t, r, n) / pardot (t, t, n); /* Update both the residual and the solution guess. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) { /* Update the solution vector. */ sol[j] += omega * r[j]; /* Update the residual vector. */ r[j] -= omega * t[j]; } /* Compute the scaled residual norm. */ err = cblas_dznrm2 (n, r, 1) / rhn; printf ("BiCG-STAB(%d): %g\n", i + 1, err); } free (r); return i; } int gmres (complex double *sol, complex double *rhs, int guess, spscat *spl, int nsph, trdesc *trans, shdata *shtr, itconf *itc) { int nterm = shtr->ntheta * shtr->nphi, n = nterm * nsph; long lwork; int i, j, one = 1, mit = itc->iter; complex double *h, *v, *beta, *y; complex double *vp, *hp, *s, cr, cone = 1.; double rhn, err, *c; /* Allocate space for all required complex vectors. */ lwork = (mit + 1) * (mit + n + 1) + mit; v = calloc (lwork, sizeof(complex double)); /* The Krylov subspace. */ beta = v + n * (mit + 1); /* The least-squares RHS. */ h = beta + mit + 1; /* The upper Hessenberg matrix. */ s = h + (mit + 1) * mit; /* Givens rotation sines. */ /* Allocate space for the Givens rotation cosines. */ c = malloc (mit * sizeof(double)); /* Compute the norm of the RHS for residual scaling. */ rhn = cblas_dznrm2 (n, rhs, 1); /* Compute the initial matrix-vector product for the input guess. */ if (guess) scatmat (v, sol, spl, nsph, trans, shtr); /* Subtract from the RHS to form the residual. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) v[j] = rhs[j] - v[j]; /* Zero the initial guess if one wasn't provided. */ if (!guess) memset (sol, 0, n * sizeof(complex double)); /* Find the norm of the initial residual. */ err = cblas_dznrm2(n, v, 1); /* Construct the initial Arnoldi vector by normalizing the residual. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) v[j] /= err; /* Construct the vector beta for the minimization problem. */ beta[0] = err; /* Report the RRE. */ err /= rhn; printf ("True residual: %g\n", err); for (i = 0; i < mit && err > itc->eps; ++i) { /* Point to the working space for this iteration. */ vp = v + i * n; hp = h + i * (mit + 1); /* Compute the next expansion of the Krylov space. */ scatmat (vp + n, vp, spl, nsph, trans, shtr); /* Perform modified Gram-Schmidt to orthogonalize the basis. */ /* This also builds the Hessenberg matrix column. */ cmgs (vp + n, hp, v, n, i + 1); /* Compute the norm of the next basis vector. */ hp[i + 1] = cblas_dznrm2(n, vp + n, 1); /* Avoid breakdown. */ if (cabs(hp[i + 1]) < DBL_EPSILON) { ++i; break; } /* Normalize the basis vector. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) vp[n + j] /= creal(hp[i + 1]); /* Apply previous Givens rotations to the Hessenberg column. */ for (j = 0; j < i; ++j) zrot_ (&one, (void *)(hp + j), &one, (void *)(hp + j + 1), &one, (void *)(c + j), (void *)(s + j)); /* Compute the Givens rotation for the current iteration. */ zlartg_ ((void *)(hp + i), (void *)(hp + i + 1), (void *)(c + i), (void *)(s + i), (void *)(&cr)); /* Apply the current Givens rotation to the Hessenberg column. */ hp[i] = cr; hp[i + 1] = 0; /* Perform the rotation on the vector beta. */ zrot_ (&one, (void *)(beta + i), &one, (void *)(beta + i + 1), &one, (void *)(c + i), (void *)(s + i)); /* Estimate the RRE for this iteration. */ err = cabs(beta[i + 1]) / rhn; printf ("GMRES(%d): %g\n", i, err); } /* If there were any GMRES iterations, update the solution. */ if (i > 0) { /* Compute the minimizer of the least-squares problem. */ cblas_ztrsv (CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, i, h, mit + 1, beta, 1); /* Compute the update to the solution. */ cblas_zgemv (CblasColMajor, CblasNoTrans, n, i, &cone, v, n, beta, 1, &cone, sol, 1); } free (v); free (c); return i; }
{ "alphanum_fraction": 0.6120823191, "avg_line_length": 29.3441558442, "ext": "c", "hexsha": "a4d1cc2ff184a5c9f7202e7f3461f4fd6d3789e0", "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": "18d8bd2d73aaabeafe4ead48955c8d8190eddbf2", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "ahesford/fastsphere", "max_forks_repo_path": "scatmat.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "18d8bd2d73aaabeafe4ead48955c8d8190eddbf2", "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": "ahesford/fastsphere", "max_issues_repo_path": "scatmat.c", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "18d8bd2d73aaabeafe4ead48955c8d8190eddbf2", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "ahesford/fastsphere", "max_stars_repo_path": "scatmat.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3033, "size": 9038 }
#include "ccv.h" #include "ccv_internal.h" #if defined(HAVE_SSE2) #include <xmmintrin.h> #elif defined(HAVE_NEON) #include <arm_neon.h> #endif #ifdef HAVE_GSL #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #endif #ifdef USE_DISPATCH #include <dispatch/dispatch.h> #endif #ifdef HAVE_CUDA #include "cuda/cwc.h" #endif #include "3rdparty/sqlite3/sqlite3.h" #include "inl/ccv_convnet_inl.h" #ifndef CASE_TESTS ccv_convnet_t* ccv_convnet_new(int use_cwc_accel, ccv_size_t input, ccv_convnet_layer_param_t params[], int count) { ccv_convnet_t* convnet = (ccv_convnet_t*)ccmalloc(sizeof(ccv_convnet_t) + sizeof(ccv_convnet_layer_t) * count + sizeof(ccv_dense_matrix_t*) * count * 2); convnet->use_cwc_accel = use_cwc_accel; #ifdef HAVE_GSL gsl_rng_env_setup(); gsl_rng* rng = gsl_rng_alloc(gsl_rng_default); gsl_rng_set(rng, (unsigned long int)convnet); #endif convnet->reserved = 0; convnet->layers = (ccv_convnet_layer_t*)(convnet + 1); convnet->acts = (ccv_dense_matrix_t**)(convnet->layers + count); memset(convnet->acts, 0, sizeof(ccv_dense_matrix_t*) * count); convnet->denoms = (ccv_dense_matrix_t**)(convnet->acts + count); memset(convnet->denoms, 0, sizeof(ccv_dense_matrix_t*) * count); convnet->count = count; convnet->input = input; convnet->rows = params[0].input.matrix.rows; convnet->cols = params[0].input.matrix.cols; convnet->channels = params[0].input.matrix.channels; convnet->mean_activity = ccv_dense_matrix_new(convnet->input.height, convnet->input.width, convnet->channels | CCV_32F, 0, 0); ccv_zero(convnet->mean_activity); ccv_convnet_layer_t* layers = convnet->layers; int i, j; for (i = 0; i < count; i++) { layers[i].type = params[i].type; layers[i].input = params[i].input; layers[i].net = params[i].output; layers[i].reserved = 0; switch (params[i].type) { case CCV_CONVNET_CONVOLUTIONAL: assert(params[i].input.matrix.channels % params[i].input.matrix.partition == 0); assert(params[i].output.convolutional.count % params[i].output.convolutional.partition == 0); assert(params[i].output.convolutional.partition % params[i].input.matrix.partition == 0); assert(params[i].output.convolutional.partition >= params[i].input.matrix.partition); layers[i].wnum = params[i].output.convolutional.rows * params[i].output.convolutional.cols * params[i].output.convolutional.channels / params[i].input.matrix.partition * params[i].output.convolutional.count; layers[i].w = (float*)ccmalloc(sizeof(float) * (layers[i].wnum + params[i].output.convolutional.count)); layers[i].bias = layers[i].w + layers[i].wnum; #ifdef HAVE_GSL for (j = 0; j < layers[i].wnum; j++) layers[i].w[j] = (gsl_rng_uniform_pos(rng) * 2 - 1) * params[i].glorot / sqrtf(params[i].output.convolutional.rows * params[i].output.convolutional.cols * params[i].output.convolutional.channels / params[i].input.matrix.partition + params[i].output.convolutional.count); #else for (j = 0; j < layers[i].wnum; j++) layers[i].w[j] = 0; #endif for (j = 0; j < params[i].output.convolutional.count; j++) layers[i].bias[j] = params[i].bias; break; case CCV_CONVNET_FULL_CONNECT: layers[i].wnum = params[i].input.node.count * params[i].output.full_connect.count; layers[i].w = (float*)ccmalloc(sizeof(float) * (layers[i].wnum + params[i].output.full_connect.count)); layers[i].bias = layers[i].w + layers[i].wnum; #ifdef HAVE_GSL for (j = 0; j < layers[i].wnum; j++) layers[i].w[j] = (gsl_rng_uniform_pos(rng) * 2 - 1) * params[i].glorot / sqrtf(params[i].input.node.count + params[i].output.full_connect.count); #else for (j = 0; j < layers[i].wnum; j++) layers[i].w[j] = 0; #endif for (j = 0; j < params[i].output.full_connect.count; j++) layers[i].bias[j] = params[i].bias; break; default: layers[i].wnum = 0; layers[i].w = 0; layers[i].bias = 0; break; } } #ifdef HAVE_GSL gsl_rng_free(rng); #endif return convnet; } int ccv_convnet_verify(ccv_convnet_t* convnet, int output) { int i, out_rows, out_cols, out_partition; if (convnet->count < 1) return -1; // the last layer has to be full connect if (convnet->layers[convnet->count - 1].type != CCV_CONVNET_FULL_CONNECT) return -1; // you cannot enable relu on the last layer if (convnet->layers[convnet->count - 1].net.full_connect.relu) return -1; for (i = 0; i < convnet->count; i++) { ccv_convnet_layer_t* layer = convnet->layers + i; if (i > 0 && (out_rows != layer->input.matrix.rows || out_cols != layer->input.matrix.cols)) return -1; ccv_convnet_make_output(layer, layer->input.matrix.rows, layer->input.matrix.cols, &out_rows, &out_cols, &out_partition); } if (out_rows * out_cols != output) return -1; int count = 0; for (i = 0; i < convnet->count; i++) { ccv_convnet_layer_t* layer = convnet->layers + i; if (layer->type == CCV_CONVNET_FULL_CONNECT) { count = i; break; } } // all the layers after the first full connect layer should only be full connect layer for (i = count; i < convnet->count; i++) if (convnet->layers[i].type != CCV_CONVNET_FULL_CONNECT || convnet->layers[i].input.matrix.rows * convnet->layers[i].input.matrix.cols * convnet->layers[i].input.matrix.channels != convnet->layers[i].input.node.count) return -1; return 0; } #endif #if defined(HAVE_SSE2) || defined(HAVE_NEON) static void _ccv_convnet_layer_simd_alloc_reserved(ccv_convnet_layer_t* layer) { if (layer->reserved) return; int partition = layer->input.matrix.partition; int ch = layer->net.convolutional.channels; int count = layer->net.convolutional.count; int kernel_rows = layer->net.convolutional.rows; int kernel_cols = layer->net.convolutional.cols; int ch_per_partition = ch / partition; int count_per_4 = count / 4; float* simd_w = (float*)ccmalloc(sizeof(float) * layer->wnum); int i, j, k, c; for (k = 0; k < count_per_4; k++) for (i = 0; i < kernel_rows * kernel_cols; i++) for (j = 0; j < ch_per_partition; j++) for (c = 0; c < 4; c++) simd_w[(k * kernel_rows * kernel_cols * ch_per_partition + i * ch_per_partition + j) * 4 + c] = layer->w[(k * 4 + c) * kernel_rows * kernel_cols * ch_per_partition + i * ch_per_partition + j]; layer->reserved = simd_w; } #endif #define SIMD(x) ((float*)((x)->reserved)) #if defined(HAVE_SSE2) static inline void _ccv_convnet_convolutional_forward_propagate_sse2(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* db, int rows, int cols, int ch, int count, int strides, int border, int kernel_rows, int kernel_cols, int ch_per_partition, int count_per_partition) { assert(SIMD(layer)); #define main_for(block) \ parallel_for(k, (count >> 2)) { \ int i, j, x, y, c; \ int p = k * 4 / count_per_partition; \ float* ap = a->data.f32 + p * ch_per_partition; \ float* bp = db->data.f32 + k * 4; \ float* layer_w = SIMD(layer) + k * 4 * kernel_rows * kernel_cols * ch_per_partition; \ float bias[4] __attribute__ ((__aligned__(16))); \ memcpy(bias, layer->bias + k * 4, sizeof(float) * 4); \ /* 4 accumulators */ \ __m128 z4 = _mm_setzero_ps(); \ for (i = 0; i < db->rows; i++) \ { \ int comy = ccv_max(i * strides - border, 0) - (i * strides - border); \ int maxy = kernel_rows - comy - (i * strides + kernel_rows - ccv_min(a->rows + border, i * strides + kernel_rows)); \ comy *= ch_per_partition * kernel_cols; \ for (j = 0; j < db->cols; j++) \ { \ __m128 v40 = _mm_load_ps(bias); \ __m128 v41 = _mm_setzero_ps(); \ __m128 v42 = _mm_setzero_ps(); \ __m128 v43 = _mm_setzero_ps(); \ int comx = ccv_max(j * strides - border, 0) - (j * strides - border); \ int maxx = kernel_cols - comx - (j * strides + kernel_cols - ccv_min(a->cols + border, j * strides + kernel_cols)); \ float* w = layer_w + (comx * ch_per_partition + comy) * 4; \ float* apz = ap + ccv_max(j * strides - border, 0) * ch; \ /* when we have border, we simply do zero padding */ \ for (y = 0; y < maxy; y++) \ { \ /* special casing for these cases to speed up SIMD computation */ \ for (x = 0; x < maxx; x++) \ { \ c = 0; \ for (; c < ch_per_partition - 3; c += 4) \ { \ __m128 apz4 = _mm_loadu_ps(apz + x * ch + c); \ __m128 w40 = _mm_loadu_ps(w + (x * ch_per_partition + c) * 4); \ __m128 w41 = _mm_loadu_ps(w + (x * ch_per_partition + c + 1) * 4); \ __m128 w42 = _mm_loadu_ps(w + (x * ch_per_partition + c + 2) * 4); \ __m128 w43 = _mm_loadu_ps(w + (x * ch_per_partition + c + 3) * 4); \ __m128 apz40 = _mm_shuffle_ps(apz4, apz4, 0x00); \ __m128 apz41 = _mm_shuffle_ps(apz4, apz4, 0x55); \ __m128 apz42 = _mm_shuffle_ps(apz4, apz4, 0xAA); \ __m128 apz43 = _mm_shuffle_ps(apz4, apz4, 0xFF); \ v40 =_mm_add_ps(_mm_mul_ps(w40, apz40), v40); \ v41 =_mm_add_ps(_mm_mul_ps(w41, apz41), v41); \ v42 =_mm_add_ps(_mm_mul_ps(w42, apz42), v42); \ v43 =_mm_add_ps(_mm_mul_ps(w43, apz43), v43); \ } \ block /* insert executions for tail partition */ \ } \ w += kernel_cols * ch_per_partition * 4; \ apz += a->cols * ch; \ } \ __m128 v4 = _mm_max_ps(z4, _mm_add_ps(_mm_add_ps(v40, v41), _mm_add_ps(v42, v43))); \ _mm_storeu_ps(bp + j * count, v4); /* ReLU */ \ } \ bp += db->cols * count; \ ap += a->cols * ch * (ccv_max((i + 1) * strides - border, 0) - ccv_max(i * strides - border, 0)); \ } \ } parallel_endfor if (ch_per_partition % 4 == 0) { main_for(); } else if (ch_per_partition % 4 == 3) { // unroll the last for-loops #define block \ __m128 apz40 = _mm_load1_ps(apz + x * ch + c); \ __m128 apz41 = _mm_load1_ps(apz + x * ch + c + 1); \ __m128 apz42 = _mm_load1_ps(apz + x * ch + c + 2); \ __m128 w40 = _mm_loadu_ps(w + (x * ch_per_partition + c) * 4); \ __m128 w41 = _mm_loadu_ps(w + (x * ch_per_partition + c + 1) * 4); \ __m128 w42 = _mm_loadu_ps(w + (x * ch_per_partition + c + 2) * 4); \ v40 = _mm_add_ps(_mm_mul_ps(w40, apz40), v40); \ v41 = _mm_add_ps(_mm_mul_ps(w41, apz41), v41); \ v42 = _mm_add_ps(_mm_mul_ps(w42, apz42), v42); main_for(block); #undef block } else if (ch_per_partition % 4 == 2) { // unroll the last for-loops #define block \ __m128 apz40 = _mm_load1_ps(apz + x * ch + c); \ __m128 apz41 = _mm_load1_ps(apz + x * ch + c + 1); \ __m128 w40 = _mm_loadu_ps(w + (x * ch_per_partition + c) * 4); \ __m128 w41 = _mm_loadu_ps(w + (x * ch_per_partition + c + 1) * 4); \ v40 = _mm_add_ps(_mm_mul_ps(w40, apz40), v40); \ v41 = _mm_add_ps(_mm_mul_ps(w41, apz41), v41); main_for(block); #undef block } else { #define block \ __m128 apz4 = _mm_load1_ps(apz + x * ch + c); \ __m128 w4 = _mm_loadu_ps(w + (x * ch_per_partition + c) * 4); \ v40 = _mm_add_ps(_mm_mul_ps(w4, apz4), v40); main_for(block); #undef block } #undef main_for } #elif defined(HAVE_NEON) static inline void _ccv_convnet_convolutional_forward_propagate_neon(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* db, int rows, int cols, int ch, int count, int strides, int border, int kernel_rows, int kernel_cols, int ch_per_partition, int count_per_partition) { assert(SIMD(layer)); #define main_for(block) \ parallel_for(k, (count >> 2)) { \ int i, j, x, y, c; \ int p = k * 4 / count_per_partition; \ float* ap = a->data.f32 + p * ch_per_partition; \ float* bp = db->data.f32 + k * 4; \ float* layer_w = SIMD(layer) + k * 4 * kernel_rows * kernel_cols * ch_per_partition; \ float bias[4] __attribute__ ((__aligned__(16))); \ memcpy(bias, layer->bias + k * 4, sizeof(float) * 4); \ float32x4_t z4 = vmovq_n_f32(0); \ for (i = 0; i < db->rows; i++) \ { \ int comy = ccv_max(i * strides - border, 0) - (i * strides - border); \ int maxy = kernel_rows - comy - (i * strides + kernel_rows - ccv_min(a->rows + border, i * strides + kernel_rows)); \ comy *= ch_per_partition * kernel_cols; \ for (j = 0; j < db->cols; j++) \ { \ float32x4_t v40 = vld1q_f32(bias); \ float32x4_t v41 = vmovq_n_f32(0); \ int comx = ccv_max(j * strides - border, 0) - (j * strides - border); \ int maxx = kernel_cols - comx - (j * strides + kernel_cols - ccv_min(a->cols + border, j * strides + kernel_cols)); \ float* w = layer_w + (comx * ch_per_partition + comy) * 4; \ float* apz = ap + ccv_max(j * strides - border, 0) * ch; \ /* when we have border, we simply do zero padding */ \ for (y = 0; y < maxy; y++) \ { \ for (x = 0; x < maxx; x++) \ { \ c = 0; \ for (; c < ch_per_partition - 1; c += 2) \ { \ float32x2_t apz4 = vld1_f32(apz + x * ch + c); \ float32x4_t apz40 = vdupq_lane_f32(apz4, 0); \ float32x4_t apz41 = vdupq_lane_f32(apz4, 1); \ float32x4_t w40 = vld1q_f32(w + (x * ch_per_partition + c) * 4); \ float32x4_t w41 = vld1q_f32(w + (x * ch_per_partition + c + 1) * 4); \ v40 = vmlaq_f32(v40, w40, apz40); \ v41 = vmlaq_f32(v41, w41, apz41); \ } \ block /* insert executions for tail partition */ \ } \ w += kernel_cols * ch_per_partition * 4; \ apz += a->cols * ch; \ } \ float32x4_t v4 = vmaxq_f32(z4, vaddq_f32(v40, v41)); \ vst1q_f32(bp + j * count, v4); /* ReLU */ \ } \ bp += db->cols * count; \ ap += a->cols * ch * (ccv_max((i + 1) * strides - border, 0) - ccv_max(i * strides - border, 0)); \ } \ } parallel_endfor if (ch_per_partition % 2 == 0) { main_for(); } else { // unroll the last for-loops #define block \ float32x4_t apz4 = vmovq_n_f32(apz[x * ch + c]); \ float32x4_t w4 = vld1q_f32(w + (x * ch_per_partition + c) * 4); \ v40 = vmlaq_f32(v40, w4, apz4); main_for(block); #undef block } #undef main_for } #else static inline void _ccv_convnet_convolutional_forward_propagate_fallback(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* db, int rows, int cols, int ch, int count, int strides, int border, int kernel_rows, int kernel_cols, int ch_per_partition, int count_per_partition) { parallel_for(k, count) { int i, j, x, y, c; int p = k / count_per_partition; float* ap = a->data.f32 + p * ch_per_partition; float* bp = db->data.f32 + k; float* layer_w = layer->w + k * kernel_rows * kernel_cols * ch_per_partition; float bias = layer->bias[k]; for (i = 0; i < db->rows; i++) { int comy = ccv_max(i * strides - border, 0) - (i * strides - border); int maxy = kernel_rows - comy - (i * strides + kernel_rows - ccv_min(a->rows + border, i * strides + kernel_rows)); comy *= ch_per_partition * kernel_cols; for (j = 0; j < db->cols; j++) { float v = bias; int comx = ccv_max(j * strides - border, 0) - (j * strides - border); int maxx = kernel_cols - comx - (j * strides + kernel_cols - ccv_min(a->cols + border, j * strides + kernel_cols)); float* w = layer_w + comx * ch_per_partition + comy; float* apz = ap + ccv_max(j * strides - border, 0) * ch; // when we have border, we simply do zero padding for (y = 0; y < maxy; y++) { for (x = 0; x < maxx; x++) for (c = 0; c < ch_per_partition; c++) v += w[x * ch_per_partition + c] * apz[x * ch + c]; w += kernel_cols * ch_per_partition; apz += a->cols * ch; } bp[j * count] = ccv_max(0, v); // ReLU } bp += db->cols * count; ap += a->cols * ch * (ccv_max((i + 1) * strides - border, 0) - ccv_max(i * strides - border, 0)); } } parallel_endfor } #endif static void _ccv_convnet_convolutional_forward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b) { int rows, cols, partition; ccv_convnet_make_output(layer, a->rows, a->cols, &rows, &cols, &partition); int ch = layer->net.convolutional.channels; int count = layer->net.convolutional.count; int strides = layer->net.convolutional.strides; int border = layer->net.convolutional.border; int kernel_rows = layer->net.convolutional.rows; int kernel_cols = layer->net.convolutional.cols; int type = CCV_32F | count; assert(CCV_GET_CHANNEL(a->type) == ch); assert(CCV_GET_DATA_TYPE(a->type) == CCV_32F); ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, rows, cols, type, type, 0); int ch_per_partition = ch / partition; int count_per_partition = count / partition; assert(count_per_partition % 4 == 0); #if defined(HAVE_SSE2) || defined(HAVE_NEON) _ccv_convnet_layer_simd_alloc_reserved(layer); #endif #if defined(HAVE_SSE2) _ccv_convnet_convolutional_forward_propagate_sse2(layer, a, db, rows, cols, ch, count, strides, border, kernel_rows, kernel_cols, ch_per_partition, count_per_partition); #elif defined(HAVE_NEON) _ccv_convnet_convolutional_forward_propagate_neon(layer, a, db, rows, cols, ch, count, strides, border, kernel_rows, kernel_cols, ch_per_partition, count_per_partition); #else _ccv_convnet_convolutional_forward_propagate_fallback(layer, a, db, rows, cols, ch, count, strides, border, kernel_rows, kernel_cols, ch_per_partition, count_per_partition); #endif } static void _ccv_convnet_full_connect_forward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b) { assert(CCV_GET_DATA_TYPE(a->type) == CCV_32F); ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, layer->net.full_connect.count, 1, CCV_32F | CCV_C1, CCV_32F | CCV_C1, 0); int ch = CCV_GET_CHANNEL(a->type); int rows = a->rows, cols = a->cols; // reshape a for gemm assert(a->step == a->cols * CCV_GET_DATA_TYPE_SIZE(a->type) * ch); a->rows = rows * cols * ch, a->cols = 1, a->type = (a->type - ch) | CCV_C1; assert(a->rows * db->rows == layer->wnum); a->step = a->cols * CCV_GET_DATA_TYPE_SIZE(a->type); int i; float* bptr = db->data.f32; for (i = 0; i < db->rows; i++) bptr[i] = layer->bias[i]; ccv_dense_matrix_t dw = ccv_dense_matrix(db->rows, a->rows, CCV_32F | CCV_C1, layer->w, 0); ccv_gemm(&dw, a, 1, db, 1, 0, (ccv_matrix_t**)&db, 0); // supply db as matrix C is allowed if (layer->net.full_connect.relu) for (i = 0; i < db->rows; i++) bptr[i] = ccv_max(0, bptr[i]); // relu a->rows = rows, a->cols = cols, a->type = (a->type - CCV_GET_CHANNEL(a->type)) | ch; a->step = a->cols * CCV_GET_DATA_TYPE_SIZE(a->type) * CCV_GET_CHANNEL(a->type); } static void _ccv_convnet_rnorm_forward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, ccv_dense_matrix_t** denoms) { int rows, cols, partition; ccv_convnet_make_output(layer, a->rows, a->cols, &rows, &cols, &partition); int size = layer->net.rnorm.size; float kappa = layer->net.rnorm.kappa; float alpha = layer->net.rnorm.alpha; float beta = layer->net.rnorm.beta; int way = size / 2; assert(CCV_GET_DATA_TYPE(a->type) == CCV_32F); int ch = CCV_GET_CHANNEL(a->type); int type = CCV_32F | ch; ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, rows, cols, type, type, 0); int i, j, k, x, p; float* ap = a->data.f32; float* bp = db->data.f32; int ch_per_partition = ch / partition; if (denoms) { ccv_dense_matrix_t* ddenoms = *denoms = ccv_dense_matrix_renew(*denoms, rows, cols, type, type, 0); float* dp = ddenoms->data.f32; for (i = 0; i < db->rows; i++) { for (j = 0; j < db->cols; j++) for (p = 0; p < partition; p++) for (k = 0; k < ch_per_partition; k++) { float v = ap[j * ch + p * ch_per_partition + k]; float denom = 0; for (x = ccv_max(k - way, 0); x <= ccv_min(k + way, ch_per_partition - 1); x++) denom += ap[j * ch + p * ch_per_partition + x] * ap[j * ch + p * ch_per_partition + x]; denom = kappa + alpha * denom; dp[j * ch + p * ch_per_partition + k] = denom; bp[j * ch + p * ch_per_partition + k] = v * powf(denom, -beta); } ap += a->cols * ch; dp += ddenoms->cols * ch; bp += db->cols * ch; } } else { for (i = 0; i < db->rows; i++) { for (j = 0; j < db->cols; j++) for (p = 0; p < partition; p++) for (k = 0; k < ch_per_partition; k++) { float v = ap[j * ch + p * ch_per_partition + k]; float denom = 0; for (x = ccv_max(k - way, 0); x <= ccv_min(k + way, ch_per_partition - 1); x++) denom += ap[j * ch + p * ch_per_partition + x] * ap[j * ch + p * ch_per_partition + x]; denom = kappa + alpha * denom; bp[j * ch + p * ch_per_partition + k] = v * powf(denom, -beta); } ap += a->cols * ch; bp += db->cols * ch; } } } static void _ccv_convnet_max_pool_forward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b) { int rows, cols, partition; ccv_convnet_make_output(layer, a->rows, a->cols, &rows, &cols, &partition); int size = layer->net.pool.size; int strides = layer->net.pool.strides; int border = layer->net.pool.border; assert(CCV_GET_DATA_TYPE(a->type) == CCV_32F); int ch = CCV_GET_CHANNEL(a->type); int type = CCV_32F | ch; ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, rows, cols, type, type, 0); int i, j, k, x, y; float* ap = a->data.f32; float* bp = db->data.f32; for (i = 0; i < db->rows; i++) { const int start_y = ccv_max(i * strides - border, 0) - (i * strides - border); const int end_y = size + ccv_min(i * strides + size - border, a->rows) - (i * strides + size - border); for (j = 0; j < db->cols; j++) { const int start_x = ccv_max(j * strides - border, 0) - (j * strides - border); const int end_x = size + ccv_min(j * strides + size - border, a->cols) - (j * strides + size - border); for (k = 0; k < ch; k++) { float v = 0; for (y = start_y; y < end_y; y++) for (x = start_x; x < end_x; x++) if (x == start_x && y == start_y) v = ap[(j * strides - border + x + (y - border) * a->cols) * ch + k]; else if (ap[(j * strides - border + x + (y - border) * a->cols) * ch + k] > v) v = ap[(j * strides - border + x + (y - border) * a->cols) * ch + k]; bp[j * ch + k] = v; } } ap += a->cols * ch * strides; bp += db->cols * ch; } } static void _ccv_convnet_average_pool_forward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b) { int rows, cols, partition; ccv_convnet_make_output(layer, a->rows, a->cols, &rows, &cols, &partition); int size = layer->net.pool.size; int strides = layer->net.pool.strides; int border = layer->net.pool.border; assert(CCV_GET_DATA_TYPE(a->type) == CCV_32F); int ch = CCV_GET_CHANNEL(a->type); int type = CCV_32F | ch; ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, rows, cols, type, type, 0); int i, j, k, x, y; float* ap = a->data.f32; float* bp = db->data.f32; for (i = 0; i < db->rows; i++) { const int start_y = ccv_max(i * strides - border, 0) - (i * strides - border); const int end_y = size + ccv_min(i * strides + size - border, a->rows) - (i * strides + size - border); for (j = 0; j < db->cols; j++) { const int start_x = ccv_max(j * strides - border, 0) - (j * strides - border); const int end_x = size + ccv_min(j * strides + size - border, a->cols) - (j * strides + size - border); for (k = 0; k < ch; k++) { float v = 0; for (y = start_y; y < end_y; y++) for (x = start_x; x < end_x; x++) v += ap[(j * strides - border + x + (y - border) * a->cols) * ch + k]; bp[j * ch + k] = v / ((end_x - start_x) * (end_y - start_y)); } } ap += a->cols * ch * strides; bp += db->cols * ch; } } static void _ccv_convnet_layer_forward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, ccv_dense_matrix_t** denoms) { switch(layer->type) { case CCV_CONVNET_CONVOLUTIONAL: _ccv_convnet_convolutional_forward_propagate(layer, a, b); break; case CCV_CONVNET_FULL_CONNECT: _ccv_convnet_full_connect_forward_propagate(layer, a, b); break; case CCV_CONVNET_LOCAL_RESPONSE_NORM: _ccv_convnet_rnorm_forward_propagate(layer, a, b, denoms); break; case CCV_CONVNET_MAX_POOL: _ccv_convnet_max_pool_forward_propagate(layer, a, b); break; case CCV_CONVNET_AVERAGE_POOL: _ccv_convnet_average_pool_forward_propagate(layer, a, b); break; } } static void _ccv_convnet_full_connect_forward_propagate_parallel(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b) { assert(CCV_GET_DATA_TYPE(a->type) == CCV_32F); ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, a->rows, layer->net.full_connect.count, CCV_32F | CCV_C1, CCV_32F | CCV_C1, 0); // reshape a for gemm int i, j; float* bptr = db->data.f32; for (i = 0; i < db->rows; i++) { for (j = 0; j < db->cols; j++) bptr[j] = layer->bias[j]; bptr += db->cols; } ccv_dense_matrix_t dw = ccv_dense_matrix(db->cols, a->cols, CCV_32F | CCV_C1, layer->w, 0); ccv_gemm(a, &dw, 1, db, 1, CCV_B_TRANSPOSE, (ccv_matrix_t**)&db, 0); // supply db as matrix C is allowed bptr = db->data.f32; if (layer->net.full_connect.relu) for (i = 0; i < db->rows; i++) { for (j = 0; j < db->cols; j++) bptr[j] = ccv_max(0, bptr[j]); // relu bptr += db->cols; } } static void _ccv_convnet_compute_softmax_parallel(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type) { assert(CCV_GET_CHANNEL(a->type) == CCV_C1); assert(CCV_GET_DATA_TYPE(a->type) == CCV_32F); ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, 1, a->cols, CCV_32F | CCV_C1, CCV_32F | CCV_C1, 0); ccv_zero(db); int i, j; float* aptr = a->data.f32; float* bptr = db->data.f32; float* cptr = (float*)ccmalloc(sizeof(float) * a->cols); for (i = 0; i < a->rows; i++) { double max = aptr[0]; for (j = 1; j < a->cols; j++) if (aptr[j] > max) max = aptr[j]; double tt = 0; for (j = 0; j < a->cols; j++) tt += (cptr[j] = expf(aptr[j] - max)); tt = 1.0 / tt; for (j = 0; j < a->cols; j++) bptr[j] += cptr[j] * tt; aptr += a->cols; } ccfree(cptr); } #ifndef CASE_TESTS void ccv_convnet_encode(ccv_convnet_t* convnet, ccv_dense_matrix_t** a, ccv_dense_matrix_t** b, int batch) { #ifdef HAVE_CUDA if (convnet->use_cwc_accel) cwc_convnet_encode(convnet, a, b, batch); else { #endif assert(batch == 1); assert(CCV_GET_CHANNEL((*a)->type) == convnet->channels); assert((*a)->rows == convnet->rows); assert((*a)->cols == convnet->cols); int i; // save the last layer of neuron cache in case that we encode to a different matrix ccv_dense_matrix_t* out_neuron = convnet->acts[convnet->count - 1]; convnet->acts[convnet->count - 1] = *b; _ccv_convnet_layer_forward_propagate(convnet->layers, *a, convnet->acts, convnet->denoms); for (i = 1; i < convnet->count; i++) _ccv_convnet_layer_forward_propagate(convnet->layers + i, convnet->acts[i - 1], convnet->acts + i, convnet->denoms + i); if (convnet->acts + convnet->count - 1 != b) { *b = convnet->acts[convnet->count - 1]; // restore the last layer of neuron cache convnet->acts[convnet->count - 1] = out_neuron; } #ifdef HAVE_CUDA } #endif } // find the layer for scanning (it is the last convolutional layer) static int _ccv_convnet_find_scan(ccv_convnet_t* convnet) { int i; ccv_convnet_layer_t* layers = convnet->layers; for (i = convnet->count - 1; i >= 0; i--) if (layers[i].type == CCV_CONVNET_CONVOLUTIONAL) return i; return -1; } static int _ccv_convnet_derive_scale(ccv_convnet_t* convnet, int scan) { int i, scale = 1; for (i = scan; i >= 0; i--) { ccv_convnet_layer_t* layer = convnet->layers + i; switch (layer->type) { case CCV_CONVNET_CONVOLUTIONAL: scale *= layer->net.convolutional.strides; break; case CCV_CONVNET_MAX_POOL: case CCV_CONVNET_AVERAGE_POOL: scale *= layer->net.pool.strides; break; } } return scale; } static int _ccv_convnet_find_full_connect(ccv_convnet_t* convnet) { int i; for (i = 0; i < convnet->count; i++) if (convnet->layers[i].type == CCV_CONVNET_FULL_CONNECT) return i; return -1; } void ccv_convnet_classify(ccv_convnet_t* convnet, ccv_dense_matrix_t** a, int symmetric, ccv_array_t** ranks, int tops, int batch) { #ifdef HAVE_CUDA if (convnet->use_cwc_accel) cwc_convnet_classify(convnet, a, symmetric, ranks, tops, batch); else { #endif int i, j, k, t; ccv_dense_matrix_t** b = (ccv_dense_matrix_t**)alloca(sizeof(ccv_dense_matrix_t*) * (convnet->count + 1)); int scan = _ccv_convnet_find_scan(convnet); int scale = _ccv_convnet_derive_scale(convnet, scan); int full_connect = _ccv_convnet_find_full_connect(convnet); assert(scan >= 0 && scan < convnet->count); assert(full_connect >= 0 && full_connect < convnet->count); memset(b, 0, sizeof(ccv_dense_matrix_t*) * (convnet->count + 1)); for (i = 0; i < batch; i++) { assert(CCV_GET_CHANNEL(a[i]->type) == convnet->channels); assert(a[i]->rows == convnet->input.height || a[i]->cols == convnet->input.width); assert(a[i]->rows >= convnet->input.height && a[i]->cols >= convnet->input.width); // find optimal rows and cols to slice to int rows = convnet->rows + ((a[i]->rows - convnet->rows) / scale) * scale; int cols = convnet->cols + ((a[i]->cols - convnet->cols) / scale) * scale; assert(rows == convnet->input.height || cols == convnet->input.width); assert(rows <= a[i]->rows && cols <= a[i]->cols); ccv_dense_matrix_t* slice = 0; ccv_slice(a[i], (ccv_matrix_t**)&slice, CCV_32F, (a[i]->rows - rows) / 2, (a[i]->cols - cols) / 2, rows, cols); ccv_dense_matrix_t* mean_activity = 0; // scale mean activity up to be substractable (from this one, the CPU implementation is an approximation of GPU implementation) ccv_resample(convnet->mean_activity, &mean_activity, 0, rows, cols, CCV_INTER_CUBIC); ccv_subtract(slice, mean_activity, (ccv_matrix_t**)b, CCV_32F); ccv_matrix_free(mean_activity); ccv_matrix_free(slice); // doing the first few layers until the first scan layer int out_rows, out_cols, out_partition; ccv_dense_matrix_t* c = ccv_dense_matrix_new(5 * (!!symmetric + 1), convnet->layers[full_connect].input.node.count, CCV_32F | CCV_C1, 0, 0); for (t = 0; t <= !!symmetric; t++) { rows = b[0]->rows, cols = b[0]->cols; for (j = 0; j < scan + 1; j++) { ccv_convnet_layer_t* layer = convnet->layers + j; ccv_convnet_make_output(layer, rows, cols, &out_rows, &out_cols, &out_partition); _ccv_convnet_layer_forward_propagate(layer, b[j], b + j + 1, 0); assert(b[j + 1]->rows == out_rows && b[j + 1]->cols == out_cols); if (j > 0) ccv_matrix_free(b[j]); rows = out_rows, cols = out_cols; } int offsets[5][2] = { {0, 0}, {cols - convnet->layers[scan + 1].input.matrix.cols, 0}, {(cols - convnet->layers[scan + 1].input.matrix.cols) / 2, (rows - convnet->layers[scan + 1].input.matrix.rows) / 2}, {0, rows - convnet->layers[scan + 1].input.matrix.rows}, {cols - convnet->layers[scan + 1].input.matrix.cols, rows - convnet->layers[scan + 1].input.matrix.rows}, }; for (k = 0; k < 5; k++) { ccv_dense_matrix_t* input = 0; ccv_convnet_layer_t* layer = convnet->layers + scan + 1; ccv_slice(b[scan + 1], (ccv_matrix_t**)&input, CCV_32F, offsets[k][1], offsets[k][0], layer->input.matrix.rows, layer->input.matrix.cols); // copy the last layer for full connect compute b[full_connect] = ccv_dense_matrix_new(convnet->layers[full_connect].input.matrix.rows, convnet->layers[full_connect].input.matrix.cols, CCV_NO_DATA_ALLOC | CCV_32F | convnet->layers[full_connect].input.matrix.channels, c->data.f32 + (t * 5 + k) * convnet->layers[full_connect].input.node.count, 0); for (j = scan + 1; j < full_connect; j++) { layer = convnet->layers + j; _ccv_convnet_layer_forward_propagate(layer, j > scan + 1 ? b[j] : input, b + j + 1, 0); if (j > scan + 1) ccv_matrix_free(b[j]); else ccv_matrix_free(input); } ccv_matrix_free(b[full_connect]); // set it to 0 memset(b + scan + 2, 0, sizeof(ccv_dense_matrix_t*) * (full_connect - scan - 1)); } ccv_matrix_free(b[scan + 1]); memset(b + 1, 0, sizeof(ccv_dense_matrix_t*) * (scan + 1)); ccv_flip(b[0], &b[0], 0, CCV_FLIP_X); } ccv_matrix_free(b[0]); // now have everything in c, do the last full connect propagate b[full_connect] = c; for (j = full_connect; j < convnet->count; j++) { ccv_convnet_layer_t* layer = convnet->layers + j; assert(layer->type == CCV_CONVNET_FULL_CONNECT); _ccv_convnet_full_connect_forward_propagate_parallel(layer, b[j], b + j + 1); ccv_matrix_free(b[j]); } ccv_dense_matrix_t* softmax = 0; _ccv_convnet_compute_softmax_parallel(b[convnet->count], &softmax, 0); ccv_matrix_free(b[convnet->count]); ranks[i] = ccv_array_new(sizeof(ccv_classification_t), tops, 0); float* r = softmax->data.f32; assert(tops <= softmax->cols); for (j = 0; j < tops; j++) { float max_val = -1; int max_idx = -1; for (k = 0; k < softmax->cols; k++) if (r[k] >= 0 && r[k] > max_val) max_val = r[k], max_idx = k; assert(max_idx >= 0); r[max_idx] = -1; ccv_classification_t classification = { .id = max_idx, .confidence = max_val / ((!!symmetric + 1) * 5), }; ccv_array_push(ranks[i], &classification); } ccv_matrix_free(softmax); memset(b, 0, sizeof(ccv_dense_matrix_t*) * (convnet->count + 1)); } #ifdef HAVE_CUDA } #endif } #endif #ifdef HAVE_GSL // compute back propagated gradient & weight update delta static void _ccv_convnet_convolutional_backward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* n, ccv_dense_matrix_t* m, ccv_dense_matrix_t** b, ccv_convnet_layer_t* update_params) { // a is the input gradient (for back prop). // x is the input (for forward prop), b is the output gradient (gradient, or known as propagated error) // note that y (the output from forward prop) is not included because the full connect net is simple enough that we don't need it int rows, cols, partition; ccv_convnet_make_output(layer, layer->input.matrix.rows, layer->input.matrix.cols, &rows, &cols, &partition); int ch = layer->net.convolutional.channels; int count = layer->net.convolutional.count; int strides = layer->net.convolutional.strides; int border = layer->net.convolutional.border; int kernel_rows = layer->net.convolutional.rows; int kernel_cols = layer->net.convolutional.cols; assert(a->rows == rows); assert(a->cols == cols); assert(CCV_GET_CHANNEL(a->type) == count); int a_rows = a->rows, a_cols = a->cols, a_ch = CCV_GET_CHANNEL(a->type); a->rows = rows, a->cols = cols, a->type = (a->type - a_ch) | count; assert(CCV_GET_CHANNEL(m->type) == ch); assert(CCV_GET_DATA_TYPE(m->type) == CCV_32F); int count_per_partition = count / partition; int ch_per_partition = ch / partition; // update weight gradient parallel_for(k, count) { int i, j, x, y, c; int p = k / count_per_partition; float* mp = m->data.f32 + p * ch_per_partition; float* ap = a->data.f32 + k; float* np = n->data.f32 + k; float* update_w = update_params->w + k * kernel_rows * kernel_cols * ch_per_partition; float bias = 0; for (i = 0; i < rows; i++) { int comy = ccv_max(i * strides - border, 0) - (i * strides - border); int maxy = kernel_rows - comy - (i * strides + kernel_rows - ccv_min(m->rows + border, i * strides + kernel_rows)); comy *= ch_per_partition * kernel_cols; for (j = 0; j < cols; j++) { if (np[j * count] > 0) { /* when np is bigger than 0, relu continues to update the weight, otherwise it stops */ float v = ap[j * count]; bias += v; int comx = ccv_max(j * strides - border, 0) - (j * strides - border); int maxx = kernel_cols - comx - (j * strides + kernel_cols - ccv_min(m->cols + border, j * strides + kernel_cols)); float* w = update_w + comx * ch_per_partition + comy; float* mpz = mp + ccv_max(j * strides - border, 0) * ch; /* when we have border, we simply do zero padding */ for (y = 0; y < maxy; y++) { for (x = 0; x < maxx; x++) for (c = 0; c < ch_per_partition; c++) w[x * ch_per_partition + c] += v * mpz[x * ch + c]; w += kernel_cols * ch_per_partition; mpz += m->cols * ch; } } } ap += a->cols * count; np += n->cols * count; mp += m->cols * ch * (ccv_max((i + 1) * strides - border, 0) - ccv_max(i * strides - border, 0)); } update_params->bias[k] += bias; } parallel_endfor if (b) { ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, m->rows, m->cols, CCV_32F | CCV_GET_CHANNEL(m->type), CCV_32F | CCV_GET_CHANNEL(m->type), 0); // clear it up before propagate result ccv_zero(db); int k; for (k = 0; k < count; k++) { int i, j, x, y, c; int p = k / count_per_partition; float* bp = db->data.f32 + p * ch_per_partition; float* ap = a->data.f32 + k; float* np = n->data.f32 + k; float* layer_w = layer->w + k * kernel_rows * kernel_cols * ch_per_partition; for (i = 0; i < rows; i++) { int comy = ccv_max(i * strides - border, 0) - (i * strides - border); int maxy = kernel_rows - comy - (i * strides + kernel_rows - ccv_min(db->rows + border, i * strides + kernel_rows)); comy *= ch_per_partition * kernel_cols; for (j = 0; j < cols; j++) { if (np[j * count] > 0) { /* when np is bigger than 0, relu continues to update the weight, otherwise it stops */ float v = ap[j * count]; int comx = ccv_max(j * strides - border, 0) - (j * strides - border); int maxx = kernel_cols - comx - (j * strides + kernel_cols - ccv_min(db->cols + border, j * strides + kernel_cols)); float* w = layer_w + comx * ch_per_partition + comy; float* bpz = bp + ccv_max(j * strides - border, 0) * ch; /* when we have border, we simply do zero padding */ for (y = 0; y < maxy; y++) { for (x = 0; x < maxx; x++) for (c = 0; c < ch_per_partition; c++) bpz[x * ch + c] += v * w[x * ch_per_partition + c]; w += kernel_cols * ch_per_partition; bpz += db->cols * ch; } } } ap += a->cols * count; np += n->cols * count; bp += db->cols * ch * (ccv_max((i + 1) * strides - border, 0) - ccv_max(i * strides - border, 0)); } } } a->rows = a_rows, a->cols = a_cols, a->type = (a->type - CCV_GET_CHANNEL(a->type)) | a_ch; } static void _ccv_convnet_full_connect_backward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* y, ccv_dense_matrix_t* x, ccv_dense_matrix_t** b, ccv_convnet_layer_t* update_params) { // a is the input gradient (for back prop), y is the output (for forward prop) // x is the input (for forward prop), b is the output gradient (gradient, or known as propagated error) ccv_dense_matrix_t* db = 0; if (b) db = *b = ccv_dense_matrix_renew(*b, x->rows, x->cols, CCV_32F | CCV_GET_CHANNEL(x->type), CCV_32F | CCV_GET_CHANNEL(x->type), 0); int x_rows = x->rows, x_cols = x->cols, x_ch = CCV_GET_CHANNEL(x->type); x->rows = x_rows * x_cols * x_ch, x->cols = 1, x->type = (x->type - x_ch) | CCV_C1; x->step = x->cols * CCV_GET_DATA_TYPE_SIZE(x->type); int i; if (layer->net.full_connect.relu) for (i = 0; i < y->rows; i++) if (y->data.f32[i] <= 0) a->data.f32[i] = 0; ccv_dense_matrix_t w = ccv_dense_matrix(a->rows, x->rows, CCV_32F | CCV_C1, update_params->w, 0); ccv_dense_matrix_t* dw = &w; // compute bias gradient ccv_dense_matrix_t bias = ccv_dense_matrix(a->rows, 1, CCV_32F | CCV_C1, update_params->bias, 0); ccv_dense_matrix_t* dbias = &bias; ccv_add(a, dbias, (ccv_matrix_t**)&dbias, 0); // compute weight gradient ccv_gemm(a, x, 1, dw, 1, CCV_B_TRANSPOSE, (ccv_matrix_t**)&dw, 0); w = ccv_dense_matrix(a->rows, x->rows, CCV_32F | CCV_C1, layer->w, 0); // propagate error if (db) { db->rows = x->rows, db->cols = x->cols, db->type = (db->type - x_ch) | CCV_C1; db->step = db->cols * CCV_GET_DATA_TYPE_SIZE(db->type); ccv_gemm(&w, a, 1, 0, 0, CCV_A_TRANSPOSE, (ccv_matrix_t**)&db, 0); db->rows = x_rows, db->cols = x_cols, db->type = (db->type - CCV_GET_CHANNEL(db->type)) | x_ch; db->step = db->cols * CCV_GET_DATA_TYPE_SIZE(db->type) * CCV_GET_CHANNEL(db->type); } x->rows = x_rows, x->cols = x_cols, x->type = (x->type - CCV_GET_CHANNEL(x->type)) | x_ch; x->step = x->cols * CCV_GET_DATA_TYPE_SIZE(x->type) * CCV_GET_CHANNEL(x->type); } static void _ccv_convnet_rnorm_backward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* n, ccv_dense_matrix_t* m, ccv_dense_matrix_t* denoms, ccv_dense_matrix_t** b) { int rows, cols, partition; ccv_convnet_make_output(layer, layer->input.matrix.rows, layer->input.matrix.cols, &rows, &cols, &partition); int size = layer->net.rnorm.size; float alpha = layer->net.rnorm.alpha; float beta = layer->net.rnorm.beta; int way = size / 2; assert(CCV_GET_DATA_TYPE(a->type) == CCV_32F); int ch = CCV_GET_CHANNEL(a->type); int type = CCV_32F | ch; ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, rows, cols, type, type, 0); int i, j, k, x, p; float* ap = a->data.f32; float* np = n->data.f32; float* mp = m->data.f32; float* dp = denoms->data.f32; float* bp = db->data.f32; int ch_per_partition = ch / partition; for (i = 0; i < db->rows; i++) { for (j = 0; j < db->cols; j++) for (p = 0; p < partition; p++) for (k = 0; k < ch_per_partition; k++) { float nom = 0; for (x = ccv_max(k - way, 0); x <= ccv_min(k + way, ch_per_partition - 1); x++) nom += -2 * alpha * beta * ap[j * ch + x + p * ch_per_partition] * np[j * ch + x + p * ch_per_partition] / dp[j * ch + x + p * ch_per_partition]; bp[j * ch + k + p * ch_per_partition] = mp[j * ch + k + p * ch_per_partition] * nom + ap[j * ch + k + p * ch_per_partition] * powf(dp[j * ch + k + p * ch_per_partition], -beta); } ap += a->cols * ch; np += n->cols * ch; mp += m->cols * ch; dp += denoms->cols * ch; bp += db->cols * ch; } } static void _ccv_convnet_max_pool_backward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* n, ccv_dense_matrix_t* m, ccv_dense_matrix_t** b) { // a is the input gradient (for back prop), y is the output (from forward prop), // x is the input (for forward prop), b is the output gradient (gradient, or known as propagated error) // pooling layer doesn't need the dropout if (b) { assert(CCV_GET_CHANNEL(a->type) == CCV_GET_CHANNEL(n->type)); assert(CCV_GET_CHANNEL(a->type) == CCV_GET_CHANNEL(m->type)); int ch = CCV_GET_CHANNEL(a->type); ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, m->rows, m->cols, CCV_32F | ch, CCV_32F | ch, 0); ccv_zero(db); int size = layer->net.pool.size; int strides = layer->net.pool.strides; int border = layer->net.pool.border; int i, j, k, x, y; float* ap = a->data.f32; float* bp = db->data.f32; float* np = n->data.f32; float* mp = m->data.f32; for (i = 0; i < a->rows; i++) { const int start_y = ccv_max(i * strides - border, 0) - (i * strides - border); const int end_y = size + ccv_min(i * strides + size - border, db->rows) - (i * strides + size - border); for (j = 0; j < a->cols; j++) { const int start_x = ccv_max(j * strides - border, 0) - (j * strides - border); const int end_x = size + ccv_min(j * strides + size - border, db->cols) - (j * strides + size - border); for (k = 0; k < ch; k++) { float v = np[j * ch + k]; float u = ap[j * ch + k]; for (y = start_y; y < end_y; y++) for (x = start_x; x < end_x; x++) // we have to do direct comparison otherwise it will contribute to too many cells // and the propagation won't work. But CPU will have different result comparing with GPU if (mp[(j * strides - border + x + (y - border) * m->cols) * ch + k] == v) bp[(j * strides - border + x + (y - border) * db->cols) * ch + k] += u; } } ap += a->cols * ch; np += n->cols * ch; bp += db->cols * ch * strides; mp += m->cols * ch * strides; } } } static void _ccv_convnet_average_pool_backward_propagate(ccv_convnet_layer_t* layer, ccv_dense_matrix_t* a, ccv_dense_matrix_t* m, ccv_dense_matrix_t** b) { // a is the input gradient (for back prop), y is the output (from forward prop), // x is the input (for forward prop), b is the output gradient (gradient, or known as propagated error) // pooling layer doesn't need the dropout if (b) { assert(CCV_GET_CHANNEL(a->type) == CCV_GET_CHANNEL(m->type)); int ch = CCV_GET_CHANNEL(a->type); ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, m->rows, m->cols, CCV_32F | ch, CCV_32F | ch, 0); ccv_zero(db); int size = layer->net.pool.size; int strides = layer->net.pool.strides; int border = layer->net.pool.border; int i, j, k, x, y; float* ap = a->data.f32; float* bp = db->data.f32; for (i = 0; i < a->rows; i++) { const int start_y = ccv_max(i * strides - border, 0) - (i * strides - border); const int end_y = size + ccv_min(i * strides + size - border, db->rows) - (i * strides + size - border); for (j = 0; j < a->cols; j++) { const int start_x = ccv_max(j * strides - border, 0) - (j * strides - border); const int end_x = size + ccv_min(j * strides + size - border, db->cols) - (j * strides + size - border); for (k = 0; k < ch; k++) { float u = ap[j * ch + k] / ((end_x - start_x) * (end_y - start_y)); for (y = start_y; y < end_y; y++) for (x = start_x; x < end_x; x++) bp[(j * strides - border + x + (y - border) * db->cols) * ch + k] += u; } } ap += a->cols * ch; bp += db->cols * ch * strides; } } } static void _ccv_convnet_propagate_loss(ccv_convnet_t* convnet, ccv_dense_matrix_t* a, ccv_dense_matrix_t* dloss, ccv_convnet_t* update_params) { int i; ccv_convnet_layer_t* layer = convnet->layers + convnet->count - 1; assert(layer->type == CCV_CONVNET_FULL_CONNECT); // the last layer has too be a full connect one to generate softmax result _ccv_convnet_full_connect_backward_propagate(layer, dloss, convnet->acts[convnet->count - 1], convnet->acts[convnet->count - 2], convnet->count - 1 > 0 ? update_params->acts + convnet->count - 2 : 0, update_params->layers + convnet->count - 1); for (i = convnet->count - 2; i >= 0; i--) { layer = convnet->layers + i; switch (layer->type) { case CCV_CONVNET_CONVOLUTIONAL: _ccv_convnet_convolutional_backward_propagate(layer, update_params->acts[i], convnet->acts[i], i > 0 ? convnet->acts[i - 1] : a, i > 0 ? update_params->acts + i - 1 : 0, update_params->layers + i); break; case CCV_CONVNET_FULL_CONNECT: _ccv_convnet_full_connect_backward_propagate(layer, update_params->acts[i], convnet->acts[i], i > 0 ? convnet->acts[i - 1] : a, i > 0 ? update_params->acts + i - 1 : 0, update_params->layers + i); break; case CCV_CONVNET_LOCAL_RESPONSE_NORM: _ccv_convnet_rnorm_backward_propagate(layer, update_params->acts[i], convnet->acts[i], i > 0 ? convnet->acts[i - 1] : a, convnet->denoms[i], i > 0 ? update_params->acts + i - 1 : 0); break; case CCV_CONVNET_MAX_POOL: _ccv_convnet_max_pool_backward_propagate(layer, update_params->acts[i], convnet->acts[i], i > 0 ? convnet->acts[i - 1] : a, i > 0 ? update_params->acts + i - 1 : 0); break; case CCV_CONVNET_AVERAGE_POOL: _ccv_convnet_average_pool_backward_propagate(layer, update_params->acts[i], i > 0 ? convnet->acts[i - 1] : a, i > 0 ? update_params->acts + i - 1 : 0); break; } } } static void _ccv_convnet_update(ccv_convnet_t* convnet, int batch, ccv_convnet_t* momentum, ccv_convnet_t* update_params, ccv_convnet_layer_train_param_t* layer_params) { int i, j; float learn_rate; for (i = 0; i < convnet->count; i++) switch (update_params->layers[i].type) { case CCV_CONVNET_CONVOLUTIONAL: { float* w = convnet->layers[i].w; float* vw = momentum->layers[i].w; float* dw = update_params->layers[i].w; learn_rate = layer_params[i].w.learn_rate / batch; for (j = 0; j < convnet->layers[i].wnum; j++) { vw[j] = layer_params[i].w.momentum * vw[j] - layer_params[i].w.decay * layer_params[i].w.learn_rate * w[j] + learn_rate * dw[j]; w[j] += vw[j]; } float* bias = convnet->layers[i].bias; float* vbias = momentum->layers[i].bias; float* dbias = update_params->layers[i].bias; learn_rate = layer_params[i].bias.learn_rate / batch; for (j = 0; j < convnet->layers[i].net.convolutional.count; j++) { vbias[j] = layer_params[i].bias.momentum * vbias[j] - layer_params[i].bias.decay * layer_params[i].bias.learn_rate * bias[j] + learn_rate * dbias[j]; bias[j] += vbias[j]; } break; } case CCV_CONVNET_FULL_CONNECT: { float* w = convnet->layers[i].w; float* vw = momentum->layers[i].w; float* dw = update_params->layers[i].w; learn_rate = layer_params[i].w.learn_rate / batch; for (j = 0; j < convnet->layers[i].wnum; j++) { vw[j] = layer_params[i].w.momentum * vw[j] - layer_params[i].w.decay * layer_params[i].w.learn_rate * w[j] + learn_rate * dw[j]; w[j] += vw[j]; } float* bias = convnet->layers[i].bias; float* vbias = momentum->layers[i].bias; float* dbias = update_params->layers[i].bias; learn_rate = layer_params[i].bias.learn_rate / batch; for (j = 0; j < convnet->layers[i].net.full_connect.count; j++) { vbias[j] = layer_params[i].bias.momentum * vbias[j] - layer_params[i].bias.decay * layer_params[i].bias.learn_rate * bias[j] + learn_rate * dbias[j]; bias[j] += vbias[j]; } break; } } } static void _ccv_convnet_update_zero(ccv_convnet_t* update_params) { int i; for (i = 0; i < update_params->count; i++) switch (update_params->layers[i].type) { case CCV_CONVNET_CONVOLUTIONAL: memset(update_params->layers[i].w, 0, sizeof(float) * update_params->layers[i].wnum); memset(update_params->layers[i].bias, 0, sizeof(float) * update_params->layers[i].net.convolutional.count); break; case CCV_CONVNET_FULL_CONNECT: assert(update_params->layers[i].wnum % update_params->layers[i].net.full_connect.count == 0); memset(update_params->layers[i].w, 0, sizeof(float) * update_params->layers[i].wnum); memset(update_params->layers[i].bias, 0, sizeof(float) * update_params->layers[i].net.full_connect.count); break; } } static ccv_convnet_t* _ccv_convnet_update_new(ccv_convnet_t* convnet) { ccv_convnet_t* update_params = (ccv_convnet_t*)ccmalloc(sizeof(ccv_convnet_t) + sizeof(ccv_convnet_layer_t) * convnet->count + sizeof(ccv_dense_matrix_t*) * convnet->count); update_params->reserved = 0; update_params->layers = (ccv_convnet_layer_t*)(update_params + 1); update_params->acts = (ccv_dense_matrix_t**)(update_params->layers + convnet->count); memset(update_params->acts, 0, sizeof(ccv_dense_matrix_t*) * convnet->count); update_params->denoms = 0; update_params->input = convnet->input; update_params->rows = convnet->rows; update_params->cols = convnet->cols; update_params->count = convnet->count; update_params->channels = convnet->channels; update_params->mean_activity = 0; int i; for (i = 0; i < convnet->count; i++) { update_params->layers[i].type = convnet->layers[i].type; update_params->layers[i].input = convnet->layers[i].input; update_params->layers[i].net = convnet->layers[i].net; update_params->layers[i].wnum = convnet->layers[i].wnum; update_params->layers[i].reserved = 0; switch (update_params->layers[i].type) { case CCV_CONVNET_CONVOLUTIONAL: update_params->layers[i].w = (float*)cccalloc(update_params->layers[i].wnum + update_params->layers[i].net.convolutional.count, sizeof(float)); update_params->layers[i].bias = update_params->layers[i].w + update_params->layers[i].wnum; break; case CCV_CONVNET_FULL_CONNECT: assert(update_params->layers[i].wnum % update_params->layers[i].net.full_connect.count == 0); update_params->layers[i].w = (float*)cccalloc(update_params->layers[i].wnum + update_params->layers[i].net.full_connect.count, sizeof(float)); update_params->layers[i].bias = update_params->layers[i].w + update_params->layers[i].wnum; break; case CCV_CONVNET_LOCAL_RESPONSE_NORM: case CCV_CONVNET_MAX_POOL: case CCV_CONVNET_AVERAGE_POOL: update_params->layers[i].w = 0; update_params->layers[i].bias = 0; break; } } return update_params; } static void _ccv_convnet_compute_softmax(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type) { int ch = CCV_GET_CHANNEL(a->type); assert(CCV_GET_DATA_TYPE(a->type) == CCV_32F); ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, a->rows, a->cols, CCV_32F | ch, CCV_32F | ch, 0); int i; float* aptr = a->data.f32; float* bptr = db->data.f32; double max = aptr[0]; for (i = 1; i < a->rows * a->cols * ch; i++) if (aptr[i] > max) max = aptr[i]; double tt = 0; for (i = 0; i < a->rows * a->cols * ch; i++) tt += (bptr[i] = expf(aptr[i] - max)); tt = 1.0 / tt; for (i = 0; i < a->rows * a->cols * ch; i++) bptr[i] *= tt; } static void _ccv_convnet_classify(ccv_convnet_t* convnet, ccv_dense_matrix_t** a, int* labels, int batch) { assert(batch == 1); ccv_convnet_encode(convnet, a, convnet->acts + convnet->count - 1, 1); int i, c = 0; ccv_dense_matrix_t* b = convnet->acts[convnet->count - 1]; float maxc = b->data.f32[0]; for (i = 1; i < b->rows; i++) if (b->data.f32[i] > maxc) maxc = b->data.f32[i], c = i; labels[0] = c; } #endif #ifndef CASE_TESTS void ccv_convnet_supervised_train(ccv_convnet_t* convnet, ccv_array_t* categorizeds, ccv_array_t* tests, const char* filename, ccv_convnet_train_param_t params) { #ifdef HAVE_GSL #ifdef HAVE_CUDA if (convnet->use_cwc_accel) cwc_convnet_supervised_train(convnet, categorizeds, tests, filename, params); else { #endif int i, j, t; gsl_rng_env_setup(); gsl_rng* rng = gsl_rng_alloc(gsl_rng_default); int aligned_padding = categorizeds->rnum % params.mini_batch; int aligned_rnum = categorizeds->rnum - aligned_padding; int* idx = (int*)ccmalloc(sizeof(int) * (categorizeds->rnum + aligned_padding)); for (i = 0; i < categorizeds->rnum; i++) idx[i] = i; gsl_ran_shuffle(rng, idx, categorizeds->rnum, sizeof(int)); // the last layer has to be full connect, thus we can use it as softmax layer assert(convnet->layers[convnet->count - 1].type == CCV_CONVNET_FULL_CONNECT); int category_count = convnet->layers[convnet->count - 1].net.full_connect.count; ccv_convnet_t* update_params = _ccv_convnet_update_new(convnet); ccv_convnet_t* momentum = _ccv_convnet_update_new(convnet); for (t = 0; t < params.max_epoch; t++) { for (i = 0; i < aligned_rnum; i++) { // dropout the first hidden layer ccv_categorized_t* categorized = (ccv_categorized_t*)ccv_array_get(categorizeds, idx[i]); ccv_convnet_encode(convnet, &categorized->matrix, convnet->acts + convnet->count - 1, 1); ccv_dense_matrix_t* softmax = convnet->acts[convnet->count - 1]; float* dloss = softmax->data.f32; _ccv_convnet_compute_softmax(softmax, &softmax, 0); assert(softmax->rows == category_count && softmax->cols == 1); // this mashes softmax and logistic regression together // also, it gives you -D[loss w.r.t. to x_i] (note the negative sign) for (j = 0; j < category_count; j++) dloss[j] = (j == categorized->c) - dloss[j]; _ccv_convnet_propagate_loss(convnet, categorized->matrix, softmax, update_params); if ((i + 1) % params.mini_batch == 0) { FLUSH(CCV_CLI_INFO, " - at epoch %03d / %d => stochastic gradient descent at %d / %d", t + 1, params.max_epoch, (i + 1) / params.mini_batch, aligned_rnum / params.mini_batch); // update weights _ccv_convnet_update(convnet, params.mini_batch, momentum, update_params, params.layer_params); _ccv_convnet_update_zero(update_params); // compact the convnet to avoid any staled temporary resource ccv_convnet_compact(convnet); } } int miss = 0; for (i = 0; i < tests->rnum; i++) { FLUSH(CCV_CLI_INFO, " - at epoch %03d / %d => going through %d / %d for tests", t + 1, params.max_epoch, i + 1, tests->rnum); ccv_categorized_t* test = (ccv_categorized_t*)ccv_array_get(tests, i); int c = 0; _ccv_convnet_classify(convnet, &test->matrix, &c, 1); if (c != test->c) ++miss; } FLUSH(CCV_CLI_INFO, " - at epoch %03d / %d => with miss rate %.2f%%\n", t + 1, params.max_epoch, miss * 100.0f / tests->rnum); if (t + 1 < params.max_epoch) { // reshuffle the parts we visited and move the rest to the beginning memcpy(idx + categorizeds->rnum, idx + aligned_rnum, sizeof(int) * aligned_padding); memmove(idx + aligned_padding, idx, sizeof(int) * aligned_rnum); memcpy(idx, idx + categorizeds->rnum, sizeof(int) * aligned_padding); gsl_ran_shuffle(rng, idx + aligned_padding, aligned_rnum, sizeof(int)); } } ccfree(idx); ccv_convnet_free(momentum); ccv_convnet_free(update_params); gsl_rng_free(rng); #ifdef HAVE_CUDA } #endif #else assert(0 && "ccv_convnet_supervised_train requires GSL library support"); #endif } void ccv_convnet_compact(ccv_convnet_t* convnet) { #ifdef HAVE_CUDA cwc_convnet_compact(convnet); #endif int i; for (i = 0; i < convnet->count; i++) { if (convnet->acts[i]) ccv_matrix_free(convnet->acts[i]); convnet->acts[i] = 0; if (convnet->denoms) { if (convnet->denoms[i]) ccv_matrix_free(convnet->denoms[i]); convnet->denoms[i] = 0; } if (SIMD(convnet->layers + i)) { ccfree(convnet->layers[i].reserved); convnet->layers[i].reserved = 0; } } } void ccv_convnet_write(ccv_convnet_t* convnet, const char* filename, ccv_convnet_write_param_t params) { sqlite3* db = 0; if (SQLITE_OK == sqlite3_open(filename, &db)) { const char layer_create_table_qs[] = "CREATE TABLE IF NOT EXISTS layer_params " "(layer INTEGER PRIMARY KEY ASC, type INTEGER, " "input_matrix_rows INTEGER, input_matrix_cols INTEGER, input_matrix_channels INTEGER, input_matrix_partition INTEGER, input_node_count INTEGER, " "output_rows INTEGER, output_cols INTEGER, output_channels INTEGER, output_partition INTEGER, output_count INTEGER, output_strides INTEGER, output_border INTEGER, " "output_size INTEGER, output_kappa REAL, output_alpha REAL, output_beta REAL, output_relu INTEGER);" "CREATE TABLE IF NOT EXISTS convnet_params " "(convnet INTEGER PRIMARY KEY ASC, input_height INTEGER, input_width INTEGER, mean_activity BLOB);" "CREATE TABLE IF NOT EXISTS layer_data " "(layer INTEGER PRIMARY KEY ASC, weight BLOB, bias BLOB, half_precision INTEGER);"; assert(SQLITE_OK == sqlite3_exec(db, layer_create_table_qs, 0, 0, 0)); const char layer_params_insert_qs[] = "REPLACE INTO layer_params " "(layer, type, " "input_matrix_rows, input_matrix_cols, input_matrix_channels, input_matrix_partition, input_node_count, " "output_rows, output_cols, output_channels, output_partition, output_count, output_strides, output_border, " "output_size, output_kappa, output_alpha, output_beta, output_relu) VALUES " "($layer, $type, " // 1 "$input_matrix_rows, $input_matrix_cols, $input_matrix_channels, $input_matrix_partition, $input_node_count, " // 6 "$output_rows, $output_cols, $output_channels, $output_partition, $output_count, $output_strides, $output_border, " // 13 "$output_size, $output_kappa, $output_alpha, $output_beta, $output_relu);"; // 18 sqlite3_stmt* layer_params_insert_stmt = 0; assert(SQLITE_OK == sqlite3_prepare_v2(db, layer_params_insert_qs, sizeof(layer_params_insert_qs), &layer_params_insert_stmt, 0)); const char layer_data_insert_qs[] = "REPLACE INTO layer_data " "(layer, weight, bias, half_precision) VALUES ($layer, $weight, $bias, $half_precision);"; sqlite3_stmt* layer_data_insert_stmt = 0; assert(SQLITE_OK == sqlite3_prepare_v2(db, layer_data_insert_qs, sizeof(layer_data_insert_qs), &layer_data_insert_stmt, 0)); int i; for (i = 0; i < convnet->count; i++) { ccv_convnet_layer_t* layer = convnet->layers + i; // insert layer params sqlite3_bind_int(layer_params_insert_stmt, 1, i); sqlite3_bind_int(layer_params_insert_stmt, 2, layer->type); sqlite3_bind_int(layer_params_insert_stmt, 3, layer->input.matrix.rows); sqlite3_bind_int(layer_params_insert_stmt, 4, layer->input.matrix.cols); sqlite3_bind_int(layer_params_insert_stmt, 5, layer->input.matrix.channels); sqlite3_bind_int(layer_params_insert_stmt, 6, layer->input.matrix.partition); sqlite3_bind_int(layer_params_insert_stmt, 7, layer->input.node.count); switch (layer->type) { case CCV_CONVNET_CONVOLUTIONAL: sqlite3_bind_int(layer_params_insert_stmt, 8, layer->net.convolutional.rows); sqlite3_bind_int(layer_params_insert_stmt, 9, layer->net.convolutional.cols); sqlite3_bind_int(layer_params_insert_stmt, 10, layer->net.convolutional.channels); sqlite3_bind_int(layer_params_insert_stmt, 11, layer->net.convolutional.partition); sqlite3_bind_int(layer_params_insert_stmt, 12, layer->net.convolutional.count); sqlite3_bind_int(layer_params_insert_stmt, 13, layer->net.convolutional.strides); sqlite3_bind_int(layer_params_insert_stmt, 14, layer->net.convolutional.border); break; case CCV_CONVNET_FULL_CONNECT: sqlite3_bind_int(layer_params_insert_stmt, 12, layer->net.full_connect.count); sqlite3_bind_int(layer_params_insert_stmt, 19, layer->net.full_connect.relu); break; case CCV_CONVNET_MAX_POOL: case CCV_CONVNET_AVERAGE_POOL: sqlite3_bind_int(layer_params_insert_stmt, 13, layer->net.pool.strides); sqlite3_bind_int(layer_params_insert_stmt, 14, layer->net.pool.border); sqlite3_bind_int(layer_params_insert_stmt, 15, layer->net.pool.size); break; case CCV_CONVNET_LOCAL_RESPONSE_NORM: sqlite3_bind_int(layer_params_insert_stmt, 15, layer->net.rnorm.size); sqlite3_bind_double(layer_params_insert_stmt, 16, layer->net.rnorm.kappa); sqlite3_bind_double(layer_params_insert_stmt, 17, layer->net.rnorm.alpha); sqlite3_bind_double(layer_params_insert_stmt, 18, layer->net.rnorm.beta); break; } assert(SQLITE_DONE == sqlite3_step(layer_params_insert_stmt)); sqlite3_reset(layer_params_insert_stmt); sqlite3_clear_bindings(layer_params_insert_stmt); // insert layer data if (layer->type == CCV_CONVNET_CONVOLUTIONAL || layer->type == CCV_CONVNET_FULL_CONNECT) { sqlite3_bind_int(layer_data_insert_stmt, 1, i); if (params.half_precision) { uint16_t* w = (uint16_t*)ccmalloc(sizeof(uint16_t) * layer->wnum); ccv_float_to_half_precision(layer->w, w, layer->wnum); uint16_t* bias = (uint16_t*)ccmalloc(sizeof(uint16_t) * (layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count)); ccv_float_to_half_precision(layer->bias, bias, layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count); sqlite3_bind_blob(layer_data_insert_stmt, 2, w, sizeof(uint16_t) * layer->wnum, ccfree); sqlite3_bind_blob(layer_data_insert_stmt, 3, bias, sizeof(uint16_t) * (layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count), ccfree); } else { sqlite3_bind_blob(layer_data_insert_stmt, 2, layer->w, sizeof(float) * layer->wnum, SQLITE_STATIC); sqlite3_bind_blob(layer_data_insert_stmt, 3, layer->bias, sizeof(float) * (layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count), SQLITE_STATIC); } sqlite3_bind_int(layer_data_insert_stmt, 4, params.half_precision); assert(SQLITE_DONE == sqlite3_step(layer_data_insert_stmt)); sqlite3_reset(layer_data_insert_stmt); sqlite3_clear_bindings(layer_data_insert_stmt); } } // insert convnet related params const char convnet_params_insert_qs[] = "REPLACE INTO convnet_params " "(convnet, mean_activity, input_height, input_width) VALUES (0, $mean_activity, $input_height, $input_width);"; sqlite3_stmt* convnet_params_insert_stmt = 0; assert(SQLITE_OK == sqlite3_prepare_v2(db, convnet_params_insert_qs, sizeof(convnet_params_insert_qs), &convnet_params_insert_stmt, 0)); assert(convnet->mean_activity->rows == convnet->input.height); assert(convnet->mean_activity->cols == convnet->input.width); assert(CCV_GET_CHANNEL(convnet->mean_activity->type) == convnet->channels); assert(CCV_GET_DATA_TYPE(convnet->mean_activity->type) == CCV_32F); sqlite3_bind_blob(convnet_params_insert_stmt, 1, convnet->mean_activity->data.f32, sizeof(float) * convnet->input.height * convnet->input.width * convnet->channels, SQLITE_STATIC); sqlite3_bind_int(convnet_params_insert_stmt, 2, convnet->input.height); sqlite3_bind_int(convnet_params_insert_stmt, 3, convnet->input.width); assert(SQLITE_DONE == sqlite3_step(convnet_params_insert_stmt)); sqlite3_reset(convnet_params_insert_stmt); sqlite3_clear_bindings(convnet_params_insert_stmt); sqlite3_finalize(layer_params_insert_stmt); sqlite3_finalize(layer_data_insert_stmt); sqlite3_finalize(convnet_params_insert_stmt); sqlite3_close(db); } } ccv_convnet_t* ccv_convnet_read(int use_cwc_accel, const char* filename) { sqlite3* db = 0; if (SQLITE_OK == sqlite3_open(filename, &db)) { ccv_convnet_t* convnet = 0; sqlite3_stmt* layer_params_stmt = 0; // load layer params const char layer_params_qs[] = "SELECT type, " // 1 "input_matrix_rows, input_matrix_cols, input_matrix_channels, input_matrix_partition, input_node_count, " // 6 "output_rows, output_cols, output_channels, output_partition, output_count, output_strides, output_border, " // 13 "output_size, output_kappa, output_alpha, output_beta, output_relu FROM layer_params ORDER BY layer ASC;"; // 18 if (SQLITE_OK == sqlite3_prepare_v2(db, layer_params_qs, sizeof(layer_params_qs), &layer_params_stmt, 0)) { ccv_array_t* layer_params = ccv_array_new(sizeof(ccv_convnet_layer_param_t), 3, 0); while (sqlite3_step(layer_params_stmt) == SQLITE_ROW) { ccv_convnet_layer_param_t layer_param; layer_param.type = sqlite3_column_int(layer_params_stmt, 0); layer_param.input.matrix.rows = sqlite3_column_int(layer_params_stmt, 1); layer_param.input.matrix.cols = sqlite3_column_int(layer_params_stmt, 2); layer_param.input.matrix.channels = sqlite3_column_int(layer_params_stmt, 3); layer_param.input.matrix.partition = sqlite3_column_int(layer_params_stmt, 4); layer_param.input.node.count = sqlite3_column_int(layer_params_stmt, 5); layer_param.bias = layer_param.glorot = 0; // this is irrelevant to read convnet switch (layer_param.type) { case CCV_CONVNET_CONVOLUTIONAL: layer_param.output.convolutional.rows = sqlite3_column_int(layer_params_stmt, 6); layer_param.output.convolutional.cols = sqlite3_column_int(layer_params_stmt, 7); layer_param.output.convolutional.channels = sqlite3_column_int(layer_params_stmt, 8); layer_param.output.convolutional.partition = sqlite3_column_int(layer_params_stmt, 9); layer_param.output.convolutional.count = sqlite3_column_int(layer_params_stmt, 10); layer_param.output.convolutional.strides = sqlite3_column_int(layer_params_stmt, 11); layer_param.output.convolutional.border = sqlite3_column_int(layer_params_stmt, 12); break; case CCV_CONVNET_FULL_CONNECT: layer_param.output.full_connect.count = sqlite3_column_int(layer_params_stmt, 10); layer_param.output.full_connect.relu = sqlite3_column_int(layer_params_stmt, 17); break; case CCV_CONVNET_MAX_POOL: case CCV_CONVNET_AVERAGE_POOL: layer_param.output.pool.strides = sqlite3_column_int(layer_params_stmt, 11); layer_param.output.pool.border = sqlite3_column_int(layer_params_stmt, 12); layer_param.output.pool.size = sqlite3_column_int(layer_params_stmt, 13); break; case CCV_CONVNET_LOCAL_RESPONSE_NORM: layer_param.output.rnorm.size = sqlite3_column_int(layer_params_stmt, 13); layer_param.output.rnorm.kappa = sqlite3_column_double(layer_params_stmt, 14); layer_param.output.rnorm.alpha = sqlite3_column_double(layer_params_stmt, 15); layer_param.output.rnorm.beta = sqlite3_column_double(layer_params_stmt, 16); break; } ccv_array_push(layer_params, &layer_param); } sqlite3_finalize(layer_params_stmt); sqlite3_stmt* convnet_params_input_stmt = 0; // load convnet params for input const char convnet_params_input_qs[] = "SELECT input_height, input_width FROM convnet_params WHERE convnet = 0;"; ccv_size_t input = ccv_size(0, 0); if (SQLITE_OK == sqlite3_prepare_v2(db, convnet_params_input_qs, sizeof(convnet_params_input_qs), &convnet_params_input_stmt, 0)) { if (sqlite3_step(convnet_params_input_stmt) == SQLITE_ROW) { input.height = sqlite3_column_int(convnet_params_input_stmt, 0); input.width = sqlite3_column_int(convnet_params_input_stmt, 1); } sqlite3_finalize(convnet_params_input_stmt); } assert(input.height != 0 && input.width != 0); convnet = ccv_convnet_new(use_cwc_accel, input, (ccv_convnet_layer_param_t*)ccv_array_get(layer_params, 0), layer_params->rnum); ccv_array_free(layer_params); // load layer data sqlite3_stmt* layer_data_stmt = 0; const char layer_data_qs[] = "SELECT layer, weight, bias, half_precision FROM layer_data;"; if (SQLITE_OK == sqlite3_prepare_v2(db, layer_data_qs, sizeof(layer_data_qs), &layer_data_stmt, 0)) { while (sqlite3_step(layer_data_stmt) == SQLITE_ROW) { ccv_convnet_layer_t* layer = convnet->layers + sqlite3_column_int(layer_data_stmt, 0); int half_precision = sqlite3_column_int(layer_data_stmt, 3); int wnum = sqlite3_column_bytes(layer_data_stmt, 1) / (half_precision ? sizeof(uint16_t) : sizeof(float)); // if weights available, load weights if (wnum == layer->wnum) { const void* w = sqlite3_column_blob(layer_data_stmt, 1); if (half_precision) { float* f = (float*)ccmalloc(sizeof(float) * layer->wnum); ccv_half_precision_to_float((uint16_t*)w, f, layer->wnum); w = f; } switch (layer->type) { case CCV_CONVNET_CONVOLUTIONAL: memcpy(layer->w, w, sizeof(float) * layer->wnum); break; case CCV_CONVNET_FULL_CONNECT: memcpy(layer->w, w, sizeof(float) * layer->wnum); break; } if (half_precision) ccfree((void*)w); } int bnum = sqlite3_column_bytes(layer_data_stmt, 2) / (half_precision ? sizeof(uint16_t) : sizeof(float)); // if bias available, load bias if (bnum == (layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count)) { const void* bias = sqlite3_column_blob(layer_data_stmt, 2); if (half_precision) { float* f = (float*)ccmalloc(sizeof(float) * (layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count)); ccv_half_precision_to_float((uint16_t*)bias, f, layer->type == CCV_CONVNET_CONVOLUTIONAL ? layer->net.convolutional.count : layer->net.full_connect.count); bias = f; } switch (layer->type) { case CCV_CONVNET_CONVOLUTIONAL: memcpy(layer->bias, bias, sizeof(float) * layer->net.convolutional.count); break; case CCV_CONVNET_FULL_CONNECT: memcpy(layer->bias, bias, sizeof(float) * layer->net.full_connect.count); break; } if (half_precision) ccfree((void*)bias); } } sqlite3_finalize(layer_data_stmt); } sqlite3_stmt* convnet_params_mean_activity_stmt = 0; // load convnet params for mean activity const char convnet_params_mean_activity_qs[] = "SELECT mean_activity FROM convnet_params WHERE convnet = 0;"; if (SQLITE_OK == sqlite3_prepare_v2(db, convnet_params_mean_activity_qs, sizeof(convnet_params_mean_activity_qs), &convnet_params_mean_activity_stmt, 0)) { if (sqlite3_step(convnet_params_mean_activity_stmt) == SQLITE_ROW) { int elems = sqlite3_column_bytes(convnet_params_mean_activity_stmt, 0) / sizeof(float); if (elems == convnet->input.height * convnet->input.width * convnet->channels) memcpy(convnet->mean_activity->data.f32, sqlite3_column_blob(convnet_params_mean_activity_stmt, 0), sizeof(float) * elems); } sqlite3_finalize(convnet_params_mean_activity_stmt); } } sqlite3_close(db); return convnet; } return 0; } void ccv_convnet_input_formation(ccv_size_t input, ccv_dense_matrix_t* a, ccv_dense_matrix_t** b) { if (a->rows > input.height && a->cols > input.width) ccv_resample(a, b, CCV_32F, ccv_max(input.height, (int)(a->rows * (float)input.height / a->cols + 0.5)), ccv_max(input.width, (int)(a->cols * (float)input.width / a->rows + 0.5)), CCV_INTER_AREA); else if (a->rows < input.height || a->cols < input.width) ccv_resample(a, b, CCV_32F, ccv_max(input.height, (int)(a->rows * (float)input.height / a->cols + 0.5)), ccv_max(input.width, (int)(a->cols * (float)input.width / a->rows + 0.5)), CCV_INTER_CUBIC); else ccv_shift(a, (ccv_matrix_t**)b, CCV_32F, 0, 0); // converting to 32f } void ccv_convnet_free(ccv_convnet_t* convnet) { ccv_convnet_compact(convnet); int i; for (i = 0; i < convnet->count; i++) if (convnet->layers[i].w) ccfree(convnet->layers[i].w); if (convnet->mean_activity) ccv_matrix_free(convnet->mean_activity); ccfree(convnet); } #endif
{ "alphanum_fraction": 0.6704238421, "avg_line_length": 43.3108747045, "ext": "c", "hexsha": "ca79e27857d1050327c25552812aebb906134c0c", "lang": "C", "max_forks_count": 18, "max_forks_repo_forks_event_max_datetime": "2021-07-11T17:57:28.000Z", "max_forks_repo_forks_event_min_datetime": "2016-02-18T08:34:17.000Z", "max_forks_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "sunkaianna/ccv", "max_forks_repo_path": "lib/ccv_convnet.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0", "max_issues_repo_issues_event_max_datetime": "2021-02-23T16:48:05.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-24T03:41:53.000Z", "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "sunkaianna/ccv", "max_issues_repo_path": "lib/ccv_convnet.c", "max_line_length": 303, "max_stars_count": 38, "max_stars_repo_head_hexsha": "3a8cc247c1f4c36cb910c94fad0abeafe3e029b0", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "sunkaianna/ccv", "max_stars_repo_path": "lib/ccv_convnet.c", "max_stars_repo_stars_event_max_datetime": "2021-07-02T15:14:13.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-08T19:47:43.000Z", "num_tokens": 23542, "size": 73282 }
#pragma once //! \file This file defines some C APIs to trigger CBLAS methods. #include "cinn/runtime/cinn_runtime.h" #ifdef CINN_WITH_MKL_CBLAS #include <mkl_cblas.h> #else #include <cblas.h> #endif // define some C APIs extern "C" { /** * \brief Do GEMM on buffer A and B and write result to buffer C. * We pass the \param M, \param N, \param K although the shape can retrieve from cinn_buffer_t because the size of a * matrix not equals the shape of a buffer it is stored. * @param alpha The scaling factor of the product of A and B * @param M Number of the rows of A * @param N the number of the columns in both B and C * @param K the number of columns of A * @param ta whether to transpose A * @param tb whether to transpose B * @param lda The size of the first dimension of A * @param ldb The size of the first dimension of B * @param ldc The size of the first dimension of C * @param beta The scaling factor of C * @param A The matrix A * @param B The matrix B * @param C The output matrix */ void cinn_cpu_mkl_gemm_fp32(float alpha, int M, int N, int K, bool ta, bool tb, int lda, int ldb, int ldc, float beta, cinn_buffer_t* A, cinn_buffer_t* B, cinn_buffer_t* C); } // extern "C"
{ "alphanum_fraction": 0.559793148, "avg_line_length": 33.6304347826, "ext": "h", "hexsha": "c8ddb5dbdc11702c8b430cb8e055b60e16bf89be", "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": "bed13f4752d80d01a3e1d96a4cc4f5aa56b1e292", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "edithgogo/CINN", "max_forks_repo_path": "cinn/runtime/cpu/cblas.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "bed13f4752d80d01a3e1d96a4cc4f5aa56b1e292", "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": "edithgogo/CINN", "max_issues_repo_path": "cinn/runtime/cpu/cblas.h", "max_line_length": 116, "max_stars_count": 1, "max_stars_repo_head_hexsha": "bed13f4752d80d01a3e1d96a4cc4f5aa56b1e292", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "edithgogo/CINN", "max_stars_repo_path": "cinn/runtime/cpu/cblas.h", "max_stars_repo_stars_event_max_datetime": "2019-10-23T09:16:23.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-23T09:16:23.000Z", "num_tokens": 357, "size": 1547 }
/* linalg/qr_band.c * * 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. */ #include <config.h> #include <stdlib.h> #include <string.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 (p,q) banded M x N matrix A into * * A = Q R * * where Q is orthogonal (M x M) and R is upper triangular (M x N). * * Example with M = 7, N = 6, (p,q) = (2,1) * * A = [ A11 A12 0 0 0 0 ] * [ A21 A22 A23 0 0 0 ] * [ A31 A32 A33 A34 0 0 ] * [ 0 A42 A43 A44 A45 0 ] * [ 0 0 A53 A54 A55 A56 ] * [ 0 0 0 A64 A65 A66 ] * [ 0 0 0 0 A75 A76 ] * * AB has dimensions N-by-(2p + q + 1) * * INPUT: OUTPUT: * * AB = [ * * * A11 A21 A31 ] AB = [ * * * R11 V21 V31 ] * [ * * A12 A22 A32 A42 ] [ * * R12 R22 V32 V42 ] * [ * 0 A23 A33 A43 A53 ] [ * R13 R23 R33 V43 V53 ] * [ 0 0 A34 A44 A54 A64 ] [ R14 R24 R34 R44 V54 V64 ] * [ 0 0 A45 A55 A65 A75 ] [ R25 R35 R45 R55 V65 V75 ] * [ 0 0 A56 A66 A76 * ] [ R36 R46 R56 R66 V76 * ] * -p-- -q- -1- ---p--- ---p--- -q- -1- ---p--- * * 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 */ int gsl_linalg_QR_band_decomp_L2 (const size_t M, const size_t p, const size_t q, gsl_matrix * AB, gsl_vector * tau) { const size_t N = AB->size1; if (tau->size != N) { GSL_ERROR ("tau must have length N", GSL_EBADLEN); } else if (AB->size2 != 2*p + q + 1) { GSL_ERROR ("dimensions of AB are inconsistent with (p,q)", GSL_EBADLEN); } else { const size_t minMN = GSL_MIN(M, N); size_t j; /* set AB(:,1:p) to zero */ if (p > 0) { gsl_matrix_view m = gsl_matrix_submatrix(AB, 0, 0, N, p); gsl_matrix_set_zero(&m.matrix); } for (j = 0; j < minMN; ++j) { /* Compute the Householder transformation to reduce the j-th column of the matrix to a multiple of the j-th unit vector */ size_t k1 = GSL_MIN(p + 1, M - j); /* number of non-zero elements of this column, including diagonal element */ size_t k2 = GSL_MIN(p + q, N - j - 1); /* number of columns to update */ gsl_vector_view c = gsl_matrix_subrow(AB, j, p + q, k1); double tau_j = gsl_linalg_householder_transform (&(c.vector)); double * ptr = gsl_vector_ptr(&(c.vector), 0); gsl_vector_set (tau, j, tau_j); /* apply the transformation to the remaining columns */ if (k2 > 0) { gsl_matrix_view m = gsl_matrix_submatrix (AB, j + 1, p + q - 1, k2, k1); gsl_vector_view work = gsl_vector_subvector(tau, j + 1, k2); double tmp = *ptr; m.matrix.tda -= 1; /* unskew matrix */ /* we want to compute H*A(j:j+k1-1,j+1:j+k2), but due to our using row-major order, the * matrix m contains A(j:j+k1-1,j+1:j+k2)^T. So therefore we apply H from the right, * * [H*A]^T = A^T H^T = A^T H */ *ptr = 1.0; gsl_linalg_householder_right(tau_j, &(c.vector), &(m.matrix), &(work.vector)); *ptr = tmp; } } return GSL_SUCCESS; } } int gsl_linalg_QR_band_unpack_L2 (const size_t p, const size_t q, const gsl_matrix * QRB, const gsl_vector * tau, gsl_matrix * Q, gsl_matrix * R) { const size_t M = Q->size1; const size_t N = QRB->size1; if (Q->size2 != M) { GSL_ERROR ("Q matrix must be square", 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 < GSL_MIN (M, N)) { GSL_ERROR ("size of tau must be at least MIN(M,N)", GSL_EBADLEN); } else if (QRB->size2 != 2*p + q + 1) { GSL_ERROR ("dimensions of QRB are inconsistent with (p,q)", GSL_EBADLEN); } else { size_t i; /* form matrix Q */ gsl_matrix_set_identity (Q); for (i = GSL_MIN (M, N); i-- > 0;) { size_t k1 = GSL_MIN(p + 1, M - i); /* number of non-zero elements of this column, including diagonal element */ gsl_vector_const_view h = gsl_matrix_const_subrow(QRB, i, p + q, k1); gsl_matrix_view m = gsl_matrix_submatrix (Q, i, i, k1, M - i); double ti = gsl_vector_get (tau, i); gsl_vector_view work = gsl_matrix_subcolumn(R, 0, 0, M - i); double * ptr = gsl_vector_ptr((gsl_vector *) &h.vector, 0); double tmp = *ptr; *ptr = 1.0; gsl_linalg_householder_left (ti, &h.vector, &m.matrix, &work.vector); *ptr = tmp; } /* form matrix R */ gsl_matrix_set_zero(R); for (i = 0; i <= GSL_MIN(p + q, N - 1); ++i) { gsl_vector_const_view src = gsl_matrix_const_subcolumn(QRB, p + q - i, i, GSL_MIN(M, N - i)); gsl_vector_view dest = gsl_matrix_superdiagonal(R, i); gsl_vector_memcpy(&dest.vector, &src.vector); } return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.5485129205, "avg_line_length": 32.5555555556, "ext": "c", "hexsha": "968c14fb4ad23025d33f53bf390aa5f492958f2b", "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/qr_band.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/qr_band.c", "max_line_length": 125, "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/qr_band.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": 1933, "size": 6153 }
/* Code for the article 'Landscape heterogeneity buffers biodiversity of meta-food-webs under global change through rescue and drainage effects' Copyright (C) 2016 Christian Guill & Florian D. Schneider Copyright (C) 2020 Remo Ryser 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, see <http://www.gnu.org/licenses/>. last edit: 01.03.2020 by RR */ /* // ************** Local foodweb code extended into space *************************** Remo Ryser, Johanna Häussler, Markus Stark */ #include <stdio.h> #include <math.h> #include <string.h> #include <fstream> // for input/output from or to files //#include <stdlib.h> #include <iostream> // for input/output on terminal #include <sstream> #include <vector> #include <cstdlib> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_rng.h> // random number generator #include <gsl/gsl_randist.h> // random number distributions #include <gsl/gsl_blas.h> // linear algebra routines #include <gsl/gsl_linalg.h> // linear algebra #include <gsl/gsl_sort_vector.h> // vector operations #include <gsl/gsl_odeiv.h> // ODE solver #include <cvode/cvode.h> /* prototypes for CVODE fcts., consts. */ #include <nvector/nvector_serial.h> /* serial N_Vector types, fcts., macros */ #include <cvode/cvode_dense.h> /* prototype for CVDense */ double *web_calc(gsl_rng *r); static void dynamics(double B[], double Bdot[], void *params, double t); static void pdef_structure(gsl_rng *r,gsl_matrix *Ap, gsl_vector *mass, gsl_matrix *Up, gsl_vector *DmaxPlant); static void output(gsl_matrix *SW, gsl_vector *mass, gsl_vector *con, double iniB[], double meanB[], double meanB_tot[], double CV[], double CV_tot[], double params[], int paramslength, double Biomass_Temp[], double RGG_params[], double net_growth_Temp[]); static void getInputSpp(); static void getInputRicker(); static void getInputMass(gsl_vector *mass, gsl_matrix *Up,gsl_vector *DmaxPlant); static void getInputLandscape(); static void getInputCoords(gsl_vector *coords_in_v); static void getInputSW(gsl_matrix *SW_input); static void getInputNutrient(gsl_vector *NS_input); double get_random_parameter(double mean, double sigma, double low_cutoff, double high_cutoff ,gsl_rng *r); static void mean_body_mass(double meanB[], gsl_vector *mass, double mean_body_masses[]); static void set_parameters(gsl_rng *r, gsl_matrix *Ap, gsl_vector *mass, double params[], gsl_matrix *Up); static void set_spatial_parameters(gsl_rng *r, gsl_matrix *SW, gsl_vector *Loc, gsl_vector *NS, double params[]); static void initialise_biomass_densities(double B[], double iniB[], double params[], gsl_rng *r); static void solve_ode(double B[], double meanB[], double meanB_tot[], double CV[], double CV_tot[], double params[], gsl_matrix *CovM, double Biomass_Temp[], double net_growth_Temp[]); static void Extinction(double B[], int Num); static void Extinct_Species(double B[], int Num, int Pat); static int Cvode_rates(realtype t, N_Vector y, N_Vector ydot, void *params); static void net_rates(gsl_vector *TBvec, gsl_vector *Ivec, gsl_vector *Dvec, gsl_vector *Xvec, gsl_vector *Emvec, gsl_vector *N_in, gsl_vector *N_out, gsl_vector *N_up, void *params, double t); static void Prepare_timeseries_file(FILE *timeseries); static void Write_timeseries_to_file(double B[], double t, FILE *timeseries); static void Prepare_netrates_file(FILE *netrates); static void Write_netrates_to_file(int p, gsl_vector *netvec, gsl_vector *Emvec_p, FILE *netrates); static void Prepare_disprates_file(FILE *disprates); static void Write_disprates_to_file(int i, int j, gsl_vector *Imvec_i, FILE *disprates); static void Write_params_to_file(double params[], int paramslength); static void Write_landscape_to_file(double params[]); static void Write_SW_matrix_to_file(gsl_matrix *SW); static void Generate_RGG_structure(gsl_rng *ran, gsl_vector *mass, gsl_vector *Loc, gsl_matrix *SW, gsl_matrix *SW_input, gsl_vector *con, double params[], double RGG_params[], gsl_vector *DmaxPlant); static void calc_patch_distances(gsl_matrix *P_Dist, gsl_vector *Loc, double RGG_params[]); static void calc_spatial_connectance(gsl_matrix *SW, gsl_vector *con, double RGG_params[]); static void show_matrix(gsl_matrix *A, int Num, int N2); static void show_vector(gsl_vector *A, int Num); double calc_sd(gsl_vector *con, int START, int P, int div); double calc_mean(gsl_vector *con, int START, int P, int div);
{ "alphanum_fraction": 0.7510917031, "avg_line_length": 48.9126213592, "ext": "h", "hexsha": "dc834cc6e75a159f3f82f61059aac547822687c4", "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": "524d0a5362d914cafb7cca5efd08ad20f437a57e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "RemoRyser/Metafoodweb", "max_forks_repo_path": "Code-Metafoodweb/Code/FullWeb/pdef_dynamics_1.1_space.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "524d0a5362d914cafb7cca5efd08ad20f437a57e", "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": "RemoRyser/Metafoodweb", "max_issues_repo_path": "Code-Metafoodweb/Code/FullWeb/pdef_dynamics_1.1_space.h", "max_line_length": 256, "max_stars_count": 1, "max_stars_repo_head_hexsha": "524d0a5362d914cafb7cca5efd08ad20f437a57e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "RemoRyser/Metafoodweb", "max_stars_repo_path": "Code-Metafoodweb/Code/FullWeb/pdef_dynamics_1.1_space.h", "max_stars_repo_stars_event_max_datetime": "2022-03-25T21:49:06.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-25T21:49:06.000Z", "num_tokens": 1268, "size": 5038 }
#include "readArray_MPI.h" #include "../include/paralleltt.h" #include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <lapacke.h> #include <time.h> #include <math.h> void* p_hilbert_init(int d, int* n){ p_hilbert* parameters = (p_hilbert*) malloc(sizeof(p_hilbert)); parameters->d = d; parameters->n = (int*) malloc(d*sizeof(int)); for (int ii = 0; ii < d; ++ii){ parameters->n[ii] = n[ii]; } parameters->n_stream = (int*) calloc(d, sizeof(int)); parameters->n_prod = (long*) malloc(d * sizeof(long)); return (void*) parameters; } void p_hilbert_free(void* parameters){ p_hilbert* p_casted = (p_hilbert*) parameters; free(p_casted->n); p_casted->n = NULL; free(p_casted->n_stream); p_casted->n_stream = NULL; free(p_casted->n_prod); p_casted->n_prod = NULL; free(p_casted); } void f_hilbert(double* restrict X, int* ind1, int* ind2, const void* parameters) { p_hilbert* p_casted = (p_hilbert*) parameters; int d = p_casted->d; int* n = p_casted->n; int* n_stream = p_casted->n_stream; long* n_prod = p_casted->n_prod; long N_stream = 1; for (int ii = 0; ii < d; ++ii){ n_stream[ii] = ind2[ii] - ind1[ii]; N_stream = N_stream*n_stream[ii]; } n_prod[0] = 1; for (int ii = 1; ii < d; ++ii){ n_prod[ii] = (long) n_prod[ii-1] * n_stream[ii-1]; } int bias = 1; for (int jj = 0; jj < d; ++jj){ bias = bias + ind1[jj]; } for (long ii = 0; ii < N_stream; ++ii){ int xinv = bias; long tmp = ii; for (int jj = d-1; jj >= 0; jj--){ xinv += tmp/n_prod[jj]; tmp = tmp % n_prod[jj]; } X[ii] = (double) 1/xinv; } } void* p_gaussian_bumps_init(int d, int* n, int M, double gamma, double* region, double* centers) { p_gaussian_bumps* parameters = (p_gaussian_bumps*) malloc(sizeof(p_gaussian_bumps)); parameters->d = d; parameters->n = (int*) calloc(d, sizeof(int)); for (int ii = 0; ii < d; ++ii){ parameters->n[ii] = n[ii]; } parameters->M = M; parameters->gamma = gamma; parameters->region = (double*) calloc(2*d, sizeof(double)); for (int ii = 0; ii < 2*d; ++ii){ parameters->region[ii] = region[ii]; } parameters->centers = (double*) calloc(d*M, sizeof(double)); for (int ii = 0; ii < d*M; ++ii){ parameters->centers[ii] = centers[ii]; } // parameters->ten_ind_ii = (int*) calloc(d, sizeof(int)); parameters->x_ii = (double*) calloc(d, sizeof(double)); parameters->n_stream = (int*) calloc(d, sizeof(double)); parameters->n_prod = (long*) calloc(d, sizeof(long)); return (void*) parameters; } void* unit_random_p_gaussian_bumps_init(int d, int* n, int M, double gamma, int seed) { p_gaussian_bumps* parameters = (p_gaussian_bumps*) malloc(sizeof(p_gaussian_bumps)); parameters->d = d; parameters->n = (int*) calloc(d, sizeof(int)); for (int ii = 0; ii < d; ++ii){ parameters->n[ii] = n[ii]; } parameters->M = M; parameters->gamma = gamma; parameters->region = (double*) calloc(2*d, sizeof(double)); for (int ii = 0; ii < d; ++ii){ parameters->region[2*ii] = -1.0; parameters->region[2*ii+1] = 1.0; } parameters->centers = (double*) calloc(d*M, sizeof(double)); srand(seed); int r1 = rand()%4096, r2 = rand()%4096, r3 = rand()%4096, r4 = rand()%4096; int iseed[4] = {r1, r2, r3, r4+(r4%2 == 0?1:0)}; LAPACKE_dlarnv(2, iseed, d*M, parameters->centers); parameters->x_ii = (double*) calloc(d, sizeof(double)); parameters->n_stream = (int*) calloc(d, sizeof(double)); parameters->n_prod = (long*) calloc(d, sizeof(long)); return (void*) parameters; } void p_gaussian_bumps_free(void* parameters) { p_gaussian_bumps* p_casted = (p_gaussian_bumps*) parameters; free(p_casted->n); p_casted->n = NULL; free(p_casted->region); p_casted->region = NULL; free(p_casted->centers); p_casted->centers = NULL; free(p_casted->x_ii); p_casted->x_ii = NULL; free(p_casted->n_stream); p_casted->n_stream = NULL; free(p_casted->n_prod); p_casted->n_prod = NULL; free(p_casted); } void f_gaussian_bumps(double* restrict X, int* ind1, int* ind2, const void* parameters) { p_gaussian_bumps* p_casted = (p_gaussian_bumps*) parameters; int d = p_casted->d; int* n = p_casted->n; int M = p_casted->M; double gamma = p_casted->gamma; double* region = p_casted->region; double* centers = p_casted->centers; double* x_ii = p_casted->x_ii; int* n_stream = p_casted->n_stream; long* n_prod = p_casted->n_prod; long N_stream = 1; for (int ii = 0; ii < d; ++ii){ n_stream[ii] = ind2[ii] - ind1[ii]; N_stream = N_stream*n_stream[ii]; } n_prod[0] = 1; for (int ii = 1; ii < d; ++ii){ n_prod[ii] = (long) n_prod[ii-1] * n_stream[ii-1]; } for (long ii = 0; ii < N_stream; ++ii){ long tmp = ii; for (int jj = d-1; jj >= 0; jj--){ int ind_jj = tmp/n_prod[jj]; x_ii[jj] = region[2*jj] + (ind_jj + ind1[jj]) * (region[2*jj + 1] - region[2*jj]) / (n[jj] - 1); tmp = tmp % n_prod[jj]; } X[ii] = 0; for (int kk = 0; kk < M; ++kk){ double exponent = 0; for (int jj = 0; jj < d; ++jj){ exponent += (x_ii[jj] - centers[kk*d + jj]) * (x_ii[jj] - centers[kk*d + jj]); } X[ii] += exp(-gamma * exponent); } } } void* p_arithmetic_init(int d, int* n) { p_arithmetic* parameters = (p_arithmetic*) malloc(sizeof(p_arithmetic)); parameters->d = d; parameters->n = (int*) malloc(d*sizeof(int)); for (int ii = 0; ii < d; ++ii){ parameters->n[ii] = n[ii]; } return (void*) parameters; } void p_arithmetic_free(void* parameters) { p_arithmetic* p_casted = (p_arithmetic*) parameters; free(p_casted->n); p_casted->n = NULL; free(p_casted); } void f_arithmetic(double* restrict X, int* ind1, int* ind2, const void* parameters) { p_arithmetic* p_casted = (p_arithmetic*) parameters; int d = p_casted->d; int* n = p_casted->n; int* n_stream = (int*) calloc(d, sizeof(int)); long N_stream = 1; for (int ii = 0; ii < d; ++ii){ n_stream[ii] = ind2[ii] - ind1[ii]; N_stream = N_stream*n_stream[ii]; } int* ind_ii = (int*) calloc(d, sizeof(int)); for (int ii = 0; ii < N_stream; ++ii){ to_tensor_ind(ind_ii, ii, n_stream, d); for (int jj = 0; jj < d; ++jj){ ind_ii[jj] = ind_ii[jj] + ind1[jj]; } X[ii] = 1 + to_vec_ind(ind_ii, n, d); // X[ii] = X[ii] + (0.000000001 / X[ii]); } free(n_stream); free(ind_ii); } void* p_tt_init(tensor_train* tt) { p_tt* parameters = (p_tt*) malloc(sizeof(p_tt)); parameters->tt = tt; return (void*) parameters; } // Doesn't actually free the tensor train. You gotta do that yourself void p_tt_free(void* parameters) { p_tt* p_casted = (p_tt*) parameters; p_casted->tt = NULL; free(p_casted); } void f_tt(double* restrict X, int* ind1, int* ind2, const void* parameters) { p_tt* p_casted = (p_tt*) parameters; tensor_train* tt = p_casted->tt; int d = tt->d; int* n = tt->n; int* r = tt->r; matrix_tt** train_submats = (matrix_tt**) calloc(d, sizeof(matrix_tt*)); for (int ii = 0; ii < d; ++ii){ matrix_tt* train_mat_ii = matrix_tt_wrap(r[ii]*n[ii], r[ii+1], tt->trains[ii]); train_submats[ii] = submatrix(train_mat_ii, ind1[ii]*r[ii], ind2[ii]*r[ii], 0, r[ii+1]); free(train_mat_ii); } matrix_tt* mult = submatrix_copy(train_submats[d-1]); matrix_tt_reshape(r[d-1], ind2[d-1] - ind1[d-1], mult); for (int jj = d-2; jj >= 1; --jj){ matrix_tt* new_mult = matrix_tt_init(train_submats[jj]->m, mult->n); matrix_tt_dgemm(train_submats[jj], mult, new_mult, 1.0, 0.0); matrix_tt_reshape(r[jj], (new_mult->n) * (new_mult->m) / r[jj], new_mult); matrix_tt_free(mult); mult = new_mult; } long X_m = 1; for (int ii = 1; ii < d; ++ii){ X_m = X_m*(ind2[ii] - ind1[ii]); } matrix_tt* X_mat = matrix_tt_wrap(ind2[0] - ind1[0], X_m, X); matrix_tt_dgemm(train_submats[0], mult, X_mat, 1.0, 0.0); for (int ii = 0; ii < d; ++ii){ free(train_submats[ii]); train_submats[ii] = NULL; } free(train_submats); train_submats = NULL; matrix_tt_free(mult); mult = NULL; free(X_mat); X_mat = NULL; } double tt_error(tensor_train* tt, MPI_tensor* ten) { MPI_Comm comm = ten->comm; tt_broadcast(comm, tt); void* parameters_tt = p_tt_init(tt); MPI_tensor* ten_tt = MPI_tensor_init(ten->d, ten->n, ten->nps, ten->comm, &f_tt, parameters_tt); int rank = ten_tt->rank; int* schedule_rank = ten_tt->schedule[rank]; double true_norm_squared = 0; double diff_norm_squared = 0; flattening_info* fi = flattening_info_init(ten, 0, 1, 0); for (int ii = 0; ii < ten->n_schedule; ++ii){ int block = schedule_rank[ii]; if (block != -1){ stream(ten, block); stream(ten_tt, block); flattening_info_update(fi, ten, block); long N = fi->t_N; for (int jj = 0; jj < N; ++jj){ ten_tt->X[jj] = ten_tt->X[jj] - ten->X[jj]; } matrix_tt* mat_true = matrix_tt_wrap(N, 1, ten->X); double tmp = frobenius_norm(mat_true); true_norm_squared = true_norm_squared + tmp*tmp; matrix_tt* mat_diff = matrix_tt_wrap(N, 1, ten_tt->X); tmp = frobenius_norm(mat_diff); diff_norm_squared = diff_norm_squared + tmp*tmp; // printf("r%d ii%d true_norm_squared = %e, diff_norm_squared = %e\n", rank, ii, true_norm_squared, diff_norm_squared); free(mat_true); mat_true = NULL; free(mat_diff); mat_diff = NULL; } } int head = 0; double true_norm_reduced; double diff_norm_reduced; MPI_Reduce(&true_norm_squared, &true_norm_reduced, 1, MPI_DOUBLE, MPI_SUM, head, comm); true_norm_reduced = sqrt(true_norm_reduced); MPI_Reduce(&diff_norm_squared, &diff_norm_reduced, 1, MPI_DOUBLE, MPI_SUM, head, comm); diff_norm_reduced = sqrt(diff_norm_reduced); double rel_err = diff_norm_reduced/true_norm_reduced; p_tt_free(parameters_tt); parameters_tt = NULL; flattening_info_free(fi); fi = NULL; MPI_tensor_free(ten_tt); ten_tt = NULL; return rel_err; }
{ "alphanum_fraction": 0.5875929587, "avg_line_length": 30.0934844193, "ext": "c", "hexsha": "1d913068b63aaa2461d80cc31daa4883dcee991e", "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": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "SidShi/Parallel_TT_sketching", "max_forks_repo_path": "test/readArray_MPI.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "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": "SidShi/Parallel_TT_sketching", "max_issues_repo_path": "test/readArray_MPI.c", "max_line_length": 130, "max_stars_count": null, "max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "SidShi/Parallel_TT_sketching", "max_stars_repo_path": "test/readArray_MPI.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3350, "size": 10623 }
#include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <dc1394/dc1394.h> #include <math.h> #include <fitsio.h> #include <gsl/gsl_statistics.h> #include <xpa.h> #include <time.h> #include <sys/time.h> #include <string.h> #include <inttypes.h> #define NXPA 10 typedef struct _Box { double x; double y; double fwhm; double cenx; double ceny; double counts; double background; double noise; double sigmaxythresh; double snr; double sigmaxy; double sigmafwhmthresh; double sigmafwhm; double strehl; double max; int r; } Box; typedef struct _Back { double x; double y; double background; double sigma; int r; int width; } Back; Box box[3]; Back back; long nelements, naxes[2], fpixel; int boxsize = 17; /* MASSDIMM values */ /* 20101228: determined DIMM pixel scale to be 1.78"/pixel using HR1866 and HR8895 as astrometric double stars */ double pixel_scale = 1.78; double d = 0.080; double r = 0.170; double lambda = 0.6e-6; double stardist(int i, int j) { return( sqrt( (box[i].cenx-box[j].cenx)*(box[i].cenx-box[j].cenx) + (box[i].ceny-box[j].ceny)*(box[i].ceny-box[j].ceny) ) ); } /* this routine uses a. tokovinin's modified equation given in 2002, PASP, 114, 1156 */ double seeing(double var) { double b, K, seeing; b = r/d; /* pixel scale in "/pixel, convert to rad */ var = var * pow(pixel_scale/206265.0, 2); K = 0.364 * (1.0 - 0.532 * pow(b, -1/3) - 0.024 * pow(b, -7/3)); seeing = 206265.0 * 0.98 * pow(d/lambda, 0.2) * pow(var/K, 0.6); return seeing; } /* this routine uses the classic DIMM equation */ double old_seeing(double var) { double r0; /* pixel scale in "/pixel, convert to rad */ var = var * pow(pixel_scale/206265.0, 2); r0 = pow(2.0 * (lambda * lambda) * ( ( 0.1790 * pow(d, -1.0/3.0) - 0.0968 * pow(r, -1.0/3.0) ) / var ), 0.6); // return 206265.0*0.98*lambda/r0; return r0; } /* measure the background in an annulus around the spot pattern */ int background(unsigned char *image, int imwidth, int imheight) { int i, j, backpix; int low_y, up_y, low_x, up_x; double dist, sum, sumsq; backpix = 0; sum = 0.0; sumsq = 0.0; low_y = back.y - back.r - back.width; up_y = back.y + back.r + back.width; low_x = back.x - back.r - back.width; up_x = back.x + back.r + back.width; if (low_y < 0) { low_y = 0; } if (up_y >= imheight) { up_y = imheight; } if (low_x < 0) { low_x = 0; } if (up_x >= imwidth) { up_x = imwidth; } for (i=low_y; i<up_y; i++) { for (j=low_x; j<up_x; j++) { dist = sqrt(pow(back.x-j, 2) + pow(back.y-i, 2)); if (dist >= back.r && dist <= back.r+back.width) { sum += image[i*naxes[0]+j]; backpix++; } } } back.background = sum/backpix; //back.background = 0.0; for (i=low_y; i<up_y; i++) { for (j=low_x; j<up_x; j++) { dist = sqrt(pow(back.x-j, 2) + pow(back.y-i, 2)); if (dist >= back.r && dist <= back.r+back.width) { sumsq += (image[i*naxes[0]+j]-back.background)* (image[i*naxes[0]+j]-back.background); } } } back.sigma = sqrt(sumsq/backpix); //back.sigma = 1.0; return 1; } /* measure centroid using center-of-mass algorithm */ int centroid(unsigned char *image, int imwidth, int imheight, int num) { int i, j; double max = 0.0; double sum = 0.0; double sumx = 0.0; double sumxx = 0.0; double sumy = 0.0; double sumyy = 0.0; double val = 0.0; double gain = 0.9; double rmom; double dist, dx; double nsigma = 3.0; int low_y, up_y, low_x, up_x; int sourcepix = 0; dx = pixel_scale/206265.0; low_y = box[num].y - box[num].r; up_y = box[num].y + box[num].r; low_x = box[num].x - box[num].r; up_x = box[num].x + box[num].r; if (low_y < 0) { low_y = 0; } if (up_y >= imheight) { up_y = imheight; } if (low_x < 0) { low_x = 0; } if (up_x >= imwidth) { up_x = imwidth; } for (i=low_y; i<up_y; i++) { for (j=low_x; j<up_x; j++) { dist = sqrt(pow(box[num].x-j, 2) + pow(box[num].y-i, 2)); if (dist <= box[num].r) { val = image[i*naxes[0]+j] - back.background; if (val >= nsigma*back.sigma) { if (val > max) { max = val; } sum += val; sumx += val*j; sumxx += val*j*j; sumy += val*i; sumyy += val*i*i; sourcepix++; } } } } if ( sum <= 0.0 ) { box[num].sigmaxy = -1.0; box[num].sigmafwhm = -1.0; box[num].snr = 0.0; box[num].fwhm = -1.0; box[num].counts = 1.0; box[num].strehl = 0.0; } else { box[num].max = max; box[num].strehl = (max/sum)*(4.0/3.14159)*pow( lambda/(d*dx), 2); rmom = ( sumxx - sumx * sumx / sum + sumyy - sumy * sumy / sum ) / sum; if ( rmom <= 0 ) { box[num].fwhm = -1.0; } else { box[num].fwhm = sqrt(rmom) * 2.354 / sqrt(2.0); } box[num].counts = sum; box[num].cenx = sumx / sum; box[num].ceny = sumy / sum; box[num].noise = back.sigma*sourcepix; box[num].x += gain*(box[num].cenx - box[num].x); box[num].y += gain*(box[num].ceny - box[num].y); box[num].snr = sum/sqrt(box[num].noise*box[num].noise + sum); box[num].sigmaxy = 1.0 / box[num].snr / sqrt(6.0); box[num].sigmafwhm = back.sigma * pow(sourcepix,1.5) / 10. / box[num].fwhm / box[num].counts * 2.354 * 2.354 / 2.0; } return 1; } int grab_frame(dc1394camera_t *c, unsigned char *buf, int nbytes) { dc1394video_frame_t *frame=NULL; dc1394error_t err; err = dc1394_capture_dequeue(c, DC1394_CAPTURE_POLICY_WAIT, &frame); if (err != DC1394_SUCCESS) { dc1394_log_error("Unable to capture."); dc1394_capture_stop(c); dc1394_camera_free(c); exit(1); } memcpy(buf, frame->image, nbytes); dc1394_capture_enqueue(c, frame); return 1; } int add_gaussian(unsigned char *buffer, float cenx, float ceny, float a, float sigma) { float gauss, rsq; int i, j, low_x, up_x, low_y, up_y, size; double xoff, yoff; xoff = 2.0*drand48() - 1.0; yoff = 2.0*drand48() - 1.0; cenx += 0.5*xoff; ceny += 0.5*yoff; size = 30; low_x = (int)(cenx-size); up_x = (int)(cenx+size); low_y = (int)(ceny-size); up_y = (int)(ceny+size); for (i=low_y; i<up_y; i++) { for (j=low_x; j<up_x; j++) { rsq = (cenx - j)*(cenx - j) + (ceny - i)*(ceny - i); gauss = a*expf(-1.0*rsq/(sigma*sigma)); if (gauss > 255) gauss = 255; buffer[i*naxes[0]+j] += (unsigned char)gauss; } } return 1; } int main(int argc, char *argv[]) { dc1394_t * dc; dc1394camera_t * camera; dc1394camera_list_t * list; dc1394error_t err; dc1394video_mode_t mode; unsigned int max_height, max_width, winleft, wintop; uint64_t total_bytes = 0; unsigned char *buffer, *buffer2, *average; char *names[NXPA]; char *messages[NXPA]; char filename[256], xpastr[256]; char *froot; fitsfile *fptr; int i, j, f, fstatus, status, nimages, nboxes, test, xsize, ysize; int nbad = 0, nbad_l = 0; FILE *init, *out, *cenfile; float xx = 0.0, yy = 0.0, xsum = 0.0, ysum = 0.0; float elapsed_time, fps, avemax; double *dist, *sig, *dist_l, *sig_l, *weight, *weight_l; double mean, var, var_l, avesig, airmass, exptime; double r0, seeing_short, seeing_long, seeing_ave; struct timeval start_time, end_time; struct tm ut; time_t start_sec, end_sec; suseconds_t start_usec, end_usec; srand48((unsigned)time(NULL)); XPA xpa; xpa = XPAOpen(NULL); stderr = freopen("measure_seeing.log", "w", stderr); if (argc <= 3) { printf("Usage: measure_seeing <n> <airmass> <exptime>\n"); exit(-1); } nimages = atoi(argv[1]); airmass = atof(argv[2]); exptime = atof(argv[3]); fstatus = 0; status = 0; xsize = 320; ysize = 240; naxes[0] = xsize; naxes[1] = ysize; fpixel = 1; fps = 1.0/exptime; if (fps > 330.0) { fps = 330.0; } nelements = naxes[0]*naxes[1]; mode = DC1394_VIDEO_MODE_FORMAT7_1; dc = dc1394_new(); if (!dc) return -1; err = dc1394_camera_enumerate(dc, &list); DC1394_ERR_RTN(err, "Failed to enumerate cameras."); if (list->num == 0) { dc1394_log_error("No cameras found."); return -1; } camera = dc1394_camera_new(dc, list->ids[0].guid); if (!camera) { dc1394_log_error("Failed to initialize camera with guid %"PRIx64".", list->ids[0].guid); return -1; } dc1394_camera_free_list(list); printf("Using camera with GUID %"PRIx64"\n", camera->guid); // need to use legacy firewire400 mode for now. 800 not quite reliable. dc1394_video_set_iso_speed(camera, DC1394_ISO_SPEED_400); // configure camera for format7 err = dc1394_video_set_mode(camera, mode); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "Can't choose video mode."); err = dc1394_format7_get_max_image_size(camera, mode, &max_width, &max_height); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "cannot get max image size."); winleft = 0; wintop = 0; err = dc1394_format7_set_roi(camera, mode, DC1394_COLOR_CODING_MONO8, DC1394_USE_MAX_AVAIL, winleft, wintop, // left, top xsize, ysize); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "Can't set ROI."); // set the frame rate to absolute value in frames/sec err = dc1394_feature_set_mode(camera, DC1394_FEATURE_FRAME_RATE, DC1394_FEATURE_MODE_MANUAL); DC1394_ERR_CLN_RTN(err, dc1394_camera_free (camera), "cannot set framerate to manual"); err = dc1394_feature_set_absolute_control(camera, DC1394_FEATURE_FRAME_RATE, DC1394_TRUE); DC1394_ERR_CLN_RTN(err, dc1394_camera_free (camera), "cannot set framerate to absolute mode"); err = dc1394_feature_set_absolute_value(camera, DC1394_FEATURE_FRAME_RATE, fps); DC1394_ERR_CLN_RTN(err,dc1394_camera_free (camera),"cannot set framerate"); printf("I: framerate is %f fps\n", fps); // set the shutter speed to absolute value in seconds err = dc1394_feature_set_mode(camera, DC1394_FEATURE_SHUTTER, DC1394_FEATURE_MODE_MANUAL); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "cannot set shutter to manual"); err = dc1394_feature_set_absolute_control(camera, DC1394_FEATURE_SHUTTER, DC1394_TRUE); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "cannot set shutter to absolute mode"); err = dc1394_feature_set_absolute_value(camera, DC1394_FEATURE_SHUTTER, exptime); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "cannot set shutter"); printf("I: exptime is %f s\n", exptime); // set gain manually. use relative value here in range 48 to 730. err = dc1394_feature_set_mode(camera, DC1394_FEATURE_GAIN, DC1394_FEATURE_MODE_MANUAL); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "cannot set gain to manual"); err = dc1394_feature_set_value(camera, DC1394_FEATURE_GAIN, 400); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "cannot set gain"); // set brightness manually. use relative value in range 0 to 1023. err = dc1394_feature_set_mode(camera, DC1394_FEATURE_BRIGHTNESS, DC1394_FEATURE_MODE_MANUAL); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "cannot set brightness to manual"); err = dc1394_feature_set_value(camera, DC1394_FEATURE_BRIGHTNESS, 100); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "cannot set brightness"); err = dc1394_format7_get_total_bytes(camera, DC1394_VIDEO_MODE_FORMAT7_1, &total_bytes); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "Can't get total bytes."); err = dc1394_capture_setup(camera, 16, DC1394_CAPTURE_FLAGS_DEFAULT); DC1394_ERR_CLN_RTN(err, dc1394_camera_free(camera), "Error capturing."); // start the camera up err = dc1394_video_set_transmission(camera, DC1394_ON); if (err != DC1394_SUCCESS) { dc1394_log_error("Unable to start camera iso transmission."); dc1394_capture_stop(camera); dc1394_camera_free(camera); return -1; } printf("Camera successfully initialized.\n"); out = fopen("seeing.dat", "a"); cenfile = fopen("centroids.dat", "w"); init = fopen("init_cen_all", "r"); i = 0; while (fscanf(init, "%f %f\n", &xx, &yy) != EOF) { box[i].x = xx; box[i].cenx = xx; box[i].y = yy; box[i].ceny = yy; box[i].r = boxsize/2.0; i++; } nboxes = i; fclose(init); back.r = 60; back.width = 10; /* allocate the buffers */ if (!(dist = calloc(nimages, sizeof(double)))) { printf("Couldn't allocate dist array.\n"); exit(-1); } if (!(sig = calloc(nimages, sizeof(double)))) { printf("Couldn't allocate sig array.\n"); exit(-1); } if (!(weight = calloc(nimages, sizeof(double)))) { printf("Couldn't allocate sig array.\n"); exit(-1); } if (!(weight_l = calloc(nimages, sizeof(double)))) { printf("Couldn't allocate sig array.\n"); exit(-1); } if (!(dist_l = calloc(nimages, sizeof(double)))) { printf("Couldn't allocate dist_l array.\n"); exit(-1); } if (!(sig_l = calloc(nimages, sizeof(double)))) { printf("Couldn't allocate sig_l array.\n"); exit(-1); } if (!(buffer = malloc(nelements*sizeof(char)))) { printf("Couldn't Allocate Image Buffer\n"); exit(-1); } if (!(buffer2 = malloc(nelements*sizeof(char)))) { printf("Couldn't Allocate 2nd Image Buffer\n"); exit(-1); } if (!(average = malloc(nelements*sizeof(char)))) { printf("Couldn't Allocate Average Image Buffer\n"); exit(-1); } froot = "seeing.fits"; avemax = 0.0; /* get initial frame */ grab_frame(camera, buffer2, nelements*sizeof(char)); grab_frame(camera, buffer2, nelements*sizeof(char)); grab_frame(camera, buffer2, nelements*sizeof(char)); grab_frame(camera, buffer2, nelements*sizeof(char)); // add_gaussian(buffer2, 195.0, 130.0, 140.0, 1.5); // add_gaussian(buffer2, 140.0, 115.0, 140.0, 1.5); gettimeofday(&start_time, NULL); for (f=0; f<nimages; f++) { grab_frame(camera, buffer, nelements*sizeof(char)); // add_gaussian(buffer, 195.0, 130.0, 140.0, 1.5); // add_gaussian(buffer, 140.0, 115.0, 140.0, 1.5); // find center of star images and calculate background xsum = 0.0; ysum = 0.0; for (i=0; i<nboxes; i++) { xsum += box[i].cenx; ysum += box[i].ceny; } back.x = xsum/nboxes; back.y = ysum/nboxes; background(buffer, naxes[0], naxes[1]); for (i=0; i<nboxes; i++) { box[i].r = boxsize/2.0; centroid(buffer, naxes[0], naxes[1], i); } /* fix both boxes to the same Y */ ysum = (box[0].y + box[1].y)/2.0; box[0].y = ysum; box[1].y = ysum; if (box[0].snr < box[1].snr) { weight[f] = (box[0].snr/box[0].counts)*(box[0].snr/box[0].counts); } else { weight[f] = (box[1].snr/box[1].counts)*(box[1].snr/box[1].counts); } if (weight[f] == 0.0) { nbad++; } dist[f] = stardist(0, 1); if (dist[f] > 55.0 || dist[f] < 15.0) { weight[f] = 0.0; } if (box[0].fwhm > 0.0 && box[1].fwhm > 0.0) { for (i=0; i<nboxes; i++) { fprintf(cenfile, "%6.2f %6.2f %5.2f %9.4f %8.4f %7.4f %7.4f %8.4f %5.3f\t ", box[i].cenx, box[i].ceny, box[i].fwhm, box[i].counts, back.background, box[i].noise, box[i].sigmaxy, box[i].snr, box[i].strehl ); } sig[f] = sqrt(box[0].sigmaxy*box[0].sigmaxy + box[1].sigmaxy*box[1].sigmaxy); fprintf(cenfile, "%6.2f %6.2f %.1e\n", dist[f], sig[f], exptime); if (box[0].max > box[1].max) { avemax += box[0].max; } else { avemax += box[1].max; } } /* now average two exposures */ for (j=0; j<nelements; j++) { test = (int)buffer[j] + (int)buffer2[j]; if (test <= 254) { average[j] = buffer[j]+buffer2[j]; } else { average[j] = 254; } } memcpy(buffer2, buffer, nelements*sizeof(char)); xsum = 0.0; ysum = 0.0; for (i=0; i<nboxes; i++) { xsum += box[i].cenx; ysum += box[i].ceny; } back.x = xsum/nboxes; back.y = ysum/nboxes; background(average, naxes[0], naxes[1]); for (i=0; i<nboxes; i++) { box[i].r = boxsize/2.0; //centroid(average, i); //box[i].r = boxsize/3.0; //centroid(average, i); //box[i].r = boxsize/4.0; centroid(average, naxes[0], naxes[1], i); } if (box[0].snr < box[1].snr) { weight_l[f] = (box[0].snr/box[0].counts)*(box[0].snr/box[0].counts); } else { weight_l[f] = (box[1].snr/box[1].counts)*(box[1].snr/box[1].counts); } if (weight_l[f] == 0.0) { nbad_l++; } dist_l[f] = stardist(0, 1); sig_l[f] = sqrt(box[0].sigmaxy*box[0].sigmaxy + box[1].sigmaxy*box[1].sigmaxy); if (f % 160 == 0) { sprintf(filename, "!%s", froot); fits_create_file(&fptr, "!seeing.fits", &fstatus); fits_create_img(fptr, BYTE_IMG, 2, naxes, &fstatus); fits_write_img(fptr, TBYTE, fpixel, nelements, buffer, &fstatus); fits_close_file(fptr, &fstatus); fits_report_error(stdout, fstatus); status = XPASet(xpa, "timDIMM", "array [xdim=320,ydim=240,bitpix=8]", "ack=false", (char *)buffer, nelements, names, messages, NXPA); sprintf(xpastr, "image; box %f %f %d %d 0.0", box[0].x, box[0].y, boxsize, boxsize); status = XPASet(xpa, "timDIMM", "regions", "ack=false", xpastr, strlen(xpastr), names, messages, NXPA); sprintf(xpastr, "image; box %f %f %d %d 0.0", box[1].x, box[1].y, boxsize, boxsize); status = XPASet(xpa, "timDIMM", "regions", "ack=false", xpastr, strlen(xpastr), names, messages, NXPA); } } gettimeofday(&end_time, NULL); printf("End capture.\n"); /*----------------------------------------------------------------------- * stop data transmission *-----------------------------------------------------------------------*/ err = dc1394_video_set_transmission(camera, DC1394_OFF); DC1394_ERR_RTN(err,"couldn't stop the camera?"); start_sec = start_time.tv_sec; start_usec = start_time.tv_usec; end_sec = end_time.tv_sec; end_usec = end_time.tv_usec; elapsed_time = (float)((end_sec + 1.0e-6*end_usec) - (start_sec + 1.0e-6*start_usec)); fps = nimages/elapsed_time; printf("Elapsed time = %g seconds.\n", elapsed_time); printf("Framerate = %g fps.\n", fps); avemax /= nimages; printf("Avemax is %.3f\n", avemax); /* analyze short exposure */ printf("\t SHORT EXPOSURE\n"); mean = gsl_stats_wmean(weight, 1, dist, 1, nimages); avesig = gsl_stats_wmean(weight, 1, sig, 1, nimages); printf("mean = %f, avesig = %f\n", mean, avesig); printf("\n"); var = gsl_stats_wvariance_m(weight, 1, dist, 1, nimages, mean); var = var - avesig*avesig; if (var < 0.0) { var = 0.0; } seeing_short = seeing(var)/pow(airmass,0.6); r0 = old_seeing(var); printf("sigma = %f, seeing = %f\n", sqrt(var), seeing_short); /* analyze long exposure */ printf("\t LONG EXPOSURE\n"); mean = gsl_stats_wmean(weight_l, 1, dist_l, 1, nimages); avesig = gsl_stats_wmean(weight_l, 1, sig_l, 1, nimages); printf("mean_l = %f, avesig_l = %f\n", mean, avesig); printf("\n"); var_l = gsl_stats_wvariance_m(weight_l, 1, dist_l, 1, nimages, mean); var_l = var_l - avesig*avesig; if (var_l < 0.0) { var_l = 0.0; } seeing_long = seeing(var_l)/pow(airmass,0.6); printf("sigma_l = %f, seeing_l = %f\n", sqrt(var_l), seeing_long); printf("Bad samples: %d for short, %d for long.\n", nbad, nbad_l); /* reduce exposure when too bright */ if (avemax > 100.0) { if (exptime > 1.0e-3) { exptime -= 1.0e-3; } else { exptime /= 2.0; } printf("\033[0;33mStar too bright, reducing exposure time to %.1e seconds.\033[0;39m\n", exptime); } /* increase if too faint, but max out at 8 ms */ if (avemax < 25.0) { if (exptime >= 1.0e-3) { exptime += 1.0e-3; } else { exptime *= 2.0; } if (exptime > 8.0e-3) { exptime = 8.0e-3; printf("\033[0;33mStar too faint, but exposure time max'ed out at %.1e seconds.\033[0;39m\n", exptime); } else { printf("\033[0;33mStar too faint, exposure time increased to %.1e seconds.\033[0;39m\n", exptime); } } init = fopen("exptime", "w"); fprintf(init, "%.2e\n", exptime); fclose(init); if (nbad < 30) { seeing_ave = pow(seeing_short, 1.75)*pow(seeing_long,-0.75); printf("\033[0;32mAirmass corrected seeing = %4.2f\"\033[0;39m\n\n", seeing_short); printf("\033[0;32mFried Parameter, R0 = %.2f cm\033[0;39m\n\n", 100*r0); gmtime_r(&end_sec, &ut); fprintf(out, "%d-%02d-%02d %02d:%02d:%02d %f %f %f %f %f %f\n", ut.tm_year+1900, ut.tm_mon+1, ut.tm_mday, ut.tm_hour, ut.tm_min, ut.tm_sec, var, var_l, seeing_short, seeing_long, seeing_ave, airmass); init = fopen("init_cen_all", "w"); for (i=0; i<nboxes; i++) { fprintf(init, "%f %f\n", box[i].cenx, box[i].ceny); } fclose(init); init = fopen("seeing.out", "w"); fprintf(init, "%.2f\n", seeing_short); fclose(init); init = fopen("r0.out", "w"); fprintf(init, "%.1f\n", 100*r0); fclose(init); } else { printf("\n\n\033[0;31mABORTING measurement! Lost at least one box.\033[0;39m\n\n"); } fclose(cenfile); fclose(out); return (status); }
{ "alphanum_fraction": 0.5961760495, "avg_line_length": 28.1940104167, "ext": "c", "hexsha": "74717299cfcca474a862b84c076a0eb0049fe611", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2017-12-01T13:02:36.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-29T15:16:35.000Z", "max_forks_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "marissakotze/timDIMM", "max_forks_repo_path": "src/measure_seeing.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "marissakotze/timDIMM", "max_issues_repo_path": "src/measure_seeing.c", "max_line_length": 104, "max_stars_count": 1, "max_stars_repo_head_hexsha": "dde00a3bb6ca7c3d9b71e24f9363350a0e2a323f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "marissakotze/timDIMM", "max_stars_repo_path": "src/measure_seeing.c", "max_stars_repo_stars_event_max_datetime": "2021-06-06T15:26:36.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-06T15:26:36.000Z", "num_tokens": 7440, "size": 21653 }
#pragma once #include "Utils.h" #include <algorithm> #include <array> #include <atomic> #include <deque> #include <functional> #include <initializer_list> #include <limits> #include <memory> #include <mutex> #include <set> #include <vector> #include <gsl/gsl> namespace indexes::utils { template <typename epoch_t, typename ReclaimedType, int ReclamationThreshold = 1000, typename Enable = void> class EpochManager; // Provides support for epoch based reclaimation. template <typename epoch_t, typename ReclaimedType, int ReclamationThreshold> class EpochManager< epoch_t, ReclaimedType, ReclamationThreshold, typename std::enable_if_t< (ReclamationThreshold > 0) && std::is_integral_v<epoch_t> && !std::is_same_v<epoch_t, bool> && !std::is_same_v<epoch_t, char>>> { // Calling thread must be registered by calling `RegisterThread` before using // epoch based safe memory reclamation. using ReclaimedPtrType = ReclaimedType *; public: // It is undefined behaviour to use epoch manager, without registering the // thread. Returns false, if active registered thread count is more than // `MAX_THREADS`. If returned false, thread is not registered. // enter_epoch guarantees that all shared objects, accessed by the calling // thread, after enter_epoch is called are safe. // Recursive calls are allowed inline void enter_epoch() { auto &pd = m_local_epoch[ThreadRegistry::ThreadID()]; if (pd.nested_level == 0) { pd.epoch.store(now(), std::memory_order_release); std::atomic_thread_fence(std::memory_order_acquire); } pd.nested_level++; } // exit_epoch marks quiescent state of the calling thread, when nesting // becomes 0. // Enables reclaimation of objects retired before calling thread's epoch. inline void exit_epoch() { auto &pd = m_local_epoch[ThreadRegistry::ThreadID()]; pd.nested_level--; if (pd.nested_level == 0) pd.epoch.store(QUIESCENT_STATE, std::memory_order_release); } // Switch to new epoch and return old epoch inline epoch_t switch_epoch() { return m_global_epoch++; } // Returns current threads epoch inline epoch_t my_epoch() { return m_local_epoch[ThreadRegistry::ThreadID()].epoch.load( std::memory_order_relaxed); } // Return current epoch inline epoch_t now() const { return m_global_epoch; } // retire objects and start a new epoch. // Objects will be reclaimed at a suitable and safe epoch. // When reclaimed `reclaimer` will be called for each reclaimed object. void retire_in_new_epoch(std::function<void(ReclaimedPtrType object)> reclaimer, gsl::span<ReclaimedPtrType> objects) { retire(reclaimer, objects, switch_epoch()); } inline void retire_in_new_epoch(std::function<void(ReclaimedPtrType object)> reclaimer, ReclaimedPtrType object) { retire_in_new_epoch(reclaimer, {&object, 1}); } // retire objects in current (without starting new epoch) epoch. // Objects will be reclaimed at a suitable and safe epoch. // When reclaimed `reclaimer` will be called for each reclaimed object. void retire_in_current_epoch( std::function<void(ReclaimedPtrType object)> reclaimer, gsl::span<ReclaimedPtrType> objects) { retire(reclaimer, objects, now()); } inline void retire_in_current_epoch( std::function<void(ReclaimedPtrType object)> reclaimer, ReclaimedPtrType object) { retire_in_current_epoch(reclaimer, {&object, 1}); } // Reclaim objects which are safe to reclaim. // Returns # objects still not reclaimed (but retired). // A long running thread using an epoch could prevent // reclaimation of objects visible to that thread. size_t do_reclaim() { return reclaim_in_retire_list(m_retire_list[ThreadRegistry::ThreadID()], get_min_used_epoch()); } void reclaim_all() { epoch_t min_used_epoch = get_min_used_epoch(); for (auto &retire_list : m_retire_list) { reclaim_in_retire_list(retire_list, min_used_epoch); } } // Getter/Setter for reclaimation threshold. // # objects to collect before triggering reclaimation. // A low value means possibly reduced peak memory consumption, but would less // performance, because of frequent calls to `DoReclaim`. void set_reclamation_threshold(int threshold) { if (threshold > 0) m_reclaimation_threshold = threshold; } int get_reclamation_threshold(int threshold) { return m_reclaimation_threshold; } EpochManager() : m_reclaimation_threshold{ReclamationThreshold}, m_global_epoch{0}, m_local_epoch(ThreadRegistry::MAX_THREADS), m_retire_list(ThreadRegistry::MAX_THREADS) {} EpochManager(const EpochManager &) = delete; EpochManager(EpochManager &&) = delete; private: class Retiree { public: Retiree(ReclaimedPtrType object, std::function<void(ReclaimedPtrType object)> reclaimer, epoch_t retired_epoch) : m_object(object), m_retired_epoch(retired_epoch), m_reclaimer(reclaimer) {} // Can reclaim this object after the given `epoch` bool can_reclaim(epoch_t epoch) const { return epoch > m_retired_epoch; } void reclaim() { return m_reclaimer(m_object); } private: // Object to reclaim safely. ReclaimedPtrType m_object; // Epoch on which the object was retired. epoch_t m_retired_epoch; // Callback to call during reclaimation. std::function<void(ReclaimedPtrType object)> m_reclaimer; }; static size_t reclaim_in_retire_list(std::deque<Retiree> &retire_list, epoch_t min_used_epoch) { auto begin = std::begin(retire_list); auto reclaim_upto = begin; for (auto &retiree : retire_list) { if (!retiree.can_reclaim(min_used_epoch)) break; retiree.reclaim(); reclaim_upto++; } size_t num_reclaimed = reclaim_upto - begin; if (num_reclaimed) { retire_list.erase(begin, reclaim_upto); retire_list.shrink_to_fit(); } return retire_list.size(); } epoch_t get_min_used_epoch() { return std::min_element(std::begin(m_local_epoch), std::begin(m_local_epoch) + ThreadRegistry::MaxThreadID() + 1, [](const auto &a, const auto &b) { return a.epoch.load() < b.epoch.load(); }) ->epoch; } void retire(std::function<void(ReclaimedPtrType object)> reclaimer, gsl::span<ReclaimedPtrType> objects, epoch_t retired_epoch) { auto &retire_list = m_retire_list[ThreadRegistry::ThreadID()]; for (auto object : objects) retire_list.emplace_back(object, reclaimer, retired_epoch); if (static_cast<int>(retire_list.size()) >= m_reclaimation_threshold) do_reclaim(); } // Reclaimation threshold. Default 1000 objects std::atomic<int> m_reclaimation_threshold; // Global epoch std::atomic<epoch_t> m_global_epoch; // Quiescent state static constexpr epoch_t QUIESCENT_STATE = std::numeric_limits<epoch_t>::max(); struct alignas(128) PrivateData { std::atomic<epoch_t> epoch = QUIESCENT_STATE; int nested_level = 0; }; // Thread local epoch, denotes the epoch of each thread. // Accessed using `slot` by each thread. std::vector<PrivateData> m_local_epoch; // Thread local retire list. Accessed using `slot` by each thread. std::vector<std::deque<Retiree>> m_retire_list; }; } // namespace indexes::utils
{ "alphanum_fraction": 0.6902887139, "avg_line_length": 32.4255319149, "ext": "h", "hexsha": "352397aa938d1d93e76d907acee4ec5552b24b08", "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": "e4027ba2151be57a59034d04dba7d0f2a8e75fef", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "harikrishnan94/bwtree", "max_forks_repo_path": "include/indexes/utils/EpochManager.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "e4027ba2151be57a59034d04dba7d0f2a8e75fef", "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": "harikrishnan94/bwtree", "max_issues_repo_path": "include/indexes/utils/EpochManager.h", "max_line_length": 79, "max_stars_count": 7, "max_stars_repo_head_hexsha": "e4027ba2151be57a59034d04dba7d0f2a8e75fef", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "harikrishnan94/InMemIndexes", "max_stars_repo_path": "include/indexes/utils/EpochManager.h", "max_stars_repo_stars_event_max_datetime": "2021-12-27T20:03:10.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-31T04:06:14.000Z", "num_tokens": 1798, "size": 7620 }
/* * Kaczmarz down-up sweep on diagonally banded matrix. The essential loop is: * * for each row i * x = x + w*(b(i) - A(i,:)*x)*A(i,:)' * end * * The matrix is given in band storage format, where each row (stored * contiguously in memory) of the array R stores a diagonal of the matrix with * offset idx(j), such that * * A(i,i+idx(j)) = R(i,j) * * use (from MATLAB): * y = sweepR_mex(R,idx,x,b,w,dir) * * R - matrix of diagonals of matrix A * idx - offsets of diagonals * x - initial guess * b - right hand side (source) * w - relaxation parameter (0 <= w <= 2) * ns - number of RHS * n_threads - OPTIONAL argument to control the number of execution * threads solving CARP blocks in parallel. The number of threads can also * be defined via an environment variable (OMP_NUM_THREADS), but this * optional argument takes precedence. The default number of threads is * one. Take care if using more than one MATLAB worker per node: each * MATLAB worker will use OMP_NUM_THREADS, so if there are four workers on * a node, there will be 4 x OMP_NUM_THREADS parallel CARP sweeps. * compile : * mex -largeArrayDims sweep_MT_mex.c -DDEFINEUNIX -lmwblas CFLAGS="\$CFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp" * * Author: Mathias Louboutin from Art Petrenko sweepR_mex.c * Seismic Laboratory for Imaging and Modeling * Department of Earth, Ocean, and Atmosperic Sciences * The University of British Columbia * * Date: March, 2015 * You may use this code only under the conditions and terms of the * license contained in the file LICENSE provided with this source * code. If you do not agree to these terms you may not use this * software. */ #include <stdlib.h> /* for getenv */ #include <stddef.h> /* for size_t type */ #include <string.h> /* for memcpy */ #include <pthread.h> /* for threading */ #include <omp.h> /* The following section allows this file to compile on Mac OS X 10.8.5. Pass * the flag -DARCH_MACI64 to the compiler to activate it. */ #ifdef ARCH_MACI64 #include <mach/error.h> typedef wchar_t char16_t; #else /* not ARCH_MACI64 */ #include <error.h> #endif /* ARCH_MACI64 */ #include <math.h> #include <mex.h> #include <matrix.h> #include <blas.h> struct copy_init_guess_data_t { double *copy_src_real, *copy_dst_real; double *copy_src_imag, *copy_dst_imag; long n_to_copy; }; struct sweep_data_t { long start_row, end_row, ncol, ny, nx, haloWidth, main_diagonal_offset; double *Rr, *Ri, *yr, *yi, *br, *bi; long *idx; double w; int dir, n_threads, ns; }; struct average_data_t { double *copy_src_real, *copy_dst_real; double *copy_src_imag, *copy_dst_imag; double *halo_1_real, *halo_2_real; double *halo_1_imag, *halo_2_imag; double *halo_dst_real, *halo_dst_imag; long n_to_copy, n_in_halo; }; struct thread_data_t { struct copy_init_guess_data_t copy_init_guess_data; struct sweep_data_t sweep_data; struct average_data_t average_data; pthread_barrier_t *barrier; }; void *do_sweep(void *thread_args_void) { struct sweep_data_t *thread_args; /* Variables contained in thread_args_void struct */ long start_row, end_row, ncol, ny, nx; /* Rr and Ri are pointers to short fat ncol-by-N matrices */ double *Rr, *Ri, *yr, *yi, *br, *bi; long *idx; double w; int n_threads,ns; /* Temporary storage variables */ double cr = 0, ci = 0; long offset, main_diagonal_offset; /* Assign local pointers to data locations in shared memory */ thread_args = (struct sweep_data_t *) thread_args_void; start_row = thread_args->start_row; end_row = thread_args->end_row; ncol = thread_args->ncol; ny = thread_args->ny; nx = thread_args->nx; main_diagonal_offset = thread_args->main_diagonal_offset; Rr = thread_args->Rr; Ri = thread_args->Ri; idx = thread_args->idx; yr = thread_args->yr; yi = thread_args->yi; br = thread_args->br; bi = thread_args->bi; w = thread_args->w; n_threads = thread_args->n_threads; ns = thread_args->ns; offset = (start_row == 0 ? 0 : - main_diagonal_offset); long i; int s; long j; long k; long indj; long toto; #pragma omp parallel for schedule(static,1) private(k,indj,i,j,cr,ci) num_threads(n_threads) for(s=0 ; s<ns; s++) { /* Kaczmarz sweep on one row block */ for(i = start_row ; i<end_row ;i++ ) { if (0 <= i + main_diagonal_offset && i + main_diagonal_offset < nx){ cr = br[i + main_diagonal_offset+s*nx]; ci = bi[i + main_diagonal_offset+nx*s]; } else{ error(1,0,"Discovery of whether the iterate vector is haloed failed."); } /* First loop over non-zero row elements calculates inner product * of matrix row and CARP iterate */ long diff = i - start_row + offset; long icol=i*ncol; for(j=0 ; j<ncol;j++) { /* i + idx[j] is the column index for the full Helmholtz matrix. * k is the index into the vector representing the CARP iterate * of the given block. */ k = diff + idx[j]; indj=icol + j; if(0<=k && k<ny) { cr -= Rr[indj]*yr[k+s*nx] - Ri[indj]*yi[k+s*nx]; ci -= Rr[indj]*yi[k+s*nx] + Ri[indj]*yr[k+s*nx]; } } cr*=w; ci*=w; /* Second loop over non-zero row elements updates Karkzmarz iterate */ for(j=0 ; j<ncol;j++) { k = diff + idx[j]; indj=icol + j; if(0<=k && k<ny) { yr[k+s*nx] += cr*Rr[indj] + ci*Ri[indj]; yi[k+s*nx] += -cr*Ri[indj] + ci*Rr[indj]; } } } cr = 0; ci = 0; for(i = end_row-1 ; i>start_row-1 ;i-- ) { if (0 <= i + main_diagonal_offset && i + main_diagonal_offset < nx){ cr = br[i + main_diagonal_offset+s*nx]; ci = bi[i + main_diagonal_offset+nx*s]; } else{ error(1,0,"Discovery of whether the iterate vector is haloed failed."); } /* First loop over non-zero row elements calculates inner product * of matrix row and CARP iterate */ long diff = i - start_row + offset; long icol=i*ncol; for(j=0 ; j<ncol;j++) { /* i + idx[j] is the column index for the full Helmholtz matrix. * k is the index into the vector representing the CARP iterate * of the given block. */ k = diff + idx[j]; indj=icol + j; if(0<=k && k<ny) { cr -= Rr[indj]*yr[k+s*nx] - Ri[indj]*yi[k+s*nx]; ci -= Rr[indj]*yi[k+s*nx] + Ri[indj]*yr[k+s*nx]; } } cr*=w; ci*=w; /* Second loop over non-zero row elements updates Karkzmarz iterate */ for(j=0 ; j<ncol;j++) { k = diff + idx[j]; indj=icol + j; if(0<=k && k<ny) { yr[k+s*nx] += cr*Rr[indj] + ci*Ri[indj]; yi[k+s*nx] += -cr*Ri[indj] + ci*Rr[indj]; } } } } return NULL; } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* structs to hold all arguments to each thread in one variable */ struct sweep_data_t **thread_args_sweep = NULL; struct copy_init_guess_data_t **copy_init_guess_data = NULL; mwSize ncol, nx; ptrdiff_t ncolBlas, idxIncBlas = 1, maxIdxLoc = 0; double *Rr,*Ri,*idxd = NULL,*xr,*xi,*br,*bi,*yr,*yi; long *idx = NULL; double w = 0; int ns; mwSize n_threads = 1; char *n_threads_str = NULL; mwSize N=1, numGridPointsPerBlock, main_diagonal_offset; /* Flags that are set if memory is allocated within the MEX file */ int Ri_alloc=0, xi_alloc=0, bi_alloc=0; mwSize *seg_bounds_hi, *seg_bounds_mid, *seg_bounds_row, *seg_bounds_lo; /* Read input arguments; initialize complex part to zero if input is real. */ ns = lrint(mxGetScalar(prhs[5])); N = mxGetN(prhs[0]); ncol = mxGetM(prhs[0]); ncolBlas = (ptrdiff_t)ncol; Rr = mxGetPr(prhs[0]); if(mxIsComplex(prhs[0])){ Ri = mxGetPi(prhs[0]); } else{ Ri = mxCalloc(N*ncol,sizeof(double)); Ri_alloc = 1; } idxd = mxGetPr(prhs[1]); nx = mxGetM(prhs[2]); xr = mxGetPr(prhs[2]); if(mxIsComplex(prhs[2])){ xi = mxGetPi(prhs[2]); } else{ xi = mxCalloc(nx*ns,sizeof(double)); xi_alloc = 1; } br = mxGetPr(prhs[3]); if(mxIsComplex(prhs[3])){ bi = mxGetPi(prhs[3]); } else{ bi = mxCalloc(nx*ns,sizeof(double)); bi_alloc = 1; } if (mxGetM(prhs[3]) != nx){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:NumElements", "The number of elements in the iterate and right hand side vectors must be equal."); } /* Allocate the final output vector */ plhs[0] = mxCreateDoubleMatrix(nx,ns, mxCOMPLEX); yr = mxGetPr(plhs[0]); yi = mxGetPi(plhs[0]); /* Check to make sure memory was allocated correctly */ if (Rr==NULL || Ri==NULL || idxd==NULL || xr==NULL || xi==NULL || br==NULL || bi==NULL || yr==NULL || yi==NULL){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:OutOfMemory", "Could not allocate memory for main computational variables."); } if ((idx = (long *) mxCalloc(ncol, sizeof(long))) == NULL){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:OutOfMemory", "Could not allocate memory for main computational variables."); } mwSize i; for (i=0; i < ncol; i++){ idx[i] = lrint(idxd[i]); } /* The default value for the number of threads can be overridden by an * environment variable. */ n_threads_str = getenv("OMP_NUM_THREADS"); if (n_threads_str == NULL){ n_threads = 1; } else{ n_threads = strtol(n_threads_str, NULL, 10); if(n_threads < 1){ n_threads = 1; } } /* The environment variable can in turn be overridden by an optional * argument to the mexFunction. */ if (nrhs >= 7){ if(1 <= lrint(mxGetScalar(prhs[6]))){ n_threads = lrint(mxGetScalar(prhs[6])); } } /* printf("Using %d threads \n",n_threads); /* Partition the iterate vector into blocks. Note that the below * partitioning scheme is slighlty different from that in pCARPCG.m in this * directory. The partitioning scheme of pCARPCG corresponds to * distributing a three dimensional array with dimensions given by n * according to Matlab's codistributor1d.defaultPartition(n(3)), and then * vectorizing it. The partition scheme of the present file instead uses * Matlab's codistributor1d.defaultPartion(prod(n)). In other words, * pCARPCG divides the iterate into blocks along the slow dimension, * whereas sweepR_mex.c does not take dimensionality into account, only the * total number of gridpoints. This is done to avoid needing an extra input * parameter with the the system dimensions. The seg_bounds_hi, _lo and * _mid arrays contain indices into non-haloed vectors, while the * seg_bounds_row array contains indices to the rows of the system matrix. * * yr_seg[i_thread-1] overlap yr_seg[i_thread] * ------------------------|-----|-----|------------------------------- * .----------------^ | ^-------------------. * seg_bounds_lo[i_thread], seg_bounds_mid[i_thread], seg_bounds_hi[i_thread] */ numGridPointsPerBlock = N; seg_bounds_hi = (mwSize *)mxCalloc(2,sizeof(mwSize)); seg_bounds_mid = (mwSize *)mxCalloc(2,sizeof(mwSize)); seg_bounds_lo = (mwSize *)mxCalloc(2,sizeof(mwSize)); seg_bounds_row = (mwSize *)mxCalloc(2,sizeof(mwSize)); if (N == nx){ main_diagonal_offset = 0; } else{ /* The vector is haloed. We are only able to correctly process matrices * with a non-zero main diagonal and symmetric off-main diagonal offsets. */ if (ncol % 2 != 1){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:EvenNumberOfDiags", "Input iterate vector appears to be haloed but there is an even number of non-zero diagonals in the system matrix."); } main_diagonal_offset = idx[ncol/2]; mwSize i; for (i = 1; i <= ncol/2; i++){ if (idx[ncol/2 + i] - main_diagonal_offset != -(idx[ncol/2 - i] - main_diagonal_offset)){ mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:DiagsNotSymmetric", "Input iterate vector appears to be haloed but the pattern of non-zero diagonals in the system matrix is not symmetric."); } } } seg_bounds_hi[0] = 0; seg_bounds_mid[0] = 0; seg_bounds_row[0] = 0; seg_bounds_lo[0] = 0; seg_bounds_lo[1] = nx; seg_bounds_hi[1] = nx; seg_bounds_mid[1] = nx; seg_bounds_row[1] = N; thread_args_sweep = (struct sweep_data_t **)mxCalloc(1, sizeof(struct sweep_data_t *)); /* Set thread arguments */ thread_args_sweep[0] = (struct sweep_data_t *)mxCalloc(1,sizeof(struct sweep_data_t)); thread_args_sweep[0]->start_row = seg_bounds_row[0]; thread_args_sweep[0]->end_row = seg_bounds_row[1]; thread_args_sweep[0]->ncol = ncol; thread_args_sweep[0]->ny = seg_bounds_hi[1]-seg_bounds_lo[0]; thread_args_sweep[0]->nx = nx; thread_args_sweep[0]->main_diagonal_offset = main_diagonal_offset; thread_args_sweep[0]->Rr = Rr; thread_args_sweep[0]->Ri = Ri; thread_args_sweep[0]->idx = idx; thread_args_sweep[0]->yr = yr; thread_args_sweep[0]->yi = yi; thread_args_sweep[0]->br = br; thread_args_sweep[0]->bi = bi; thread_args_sweep[0]->w = w; thread_args_sweep[0]->n_threads = n_threads; thread_args_sweep[0]->ns = ns; /* Set the initial guess directly in the output array too */ memcpy((void *)yr, (void *)xr, sizeof(double)*nx*ns); memcpy((void *)yi, (void *)xi, sizeof(double)*nx*ns); do_sweep((void *)thread_args_sweep[0]); /* Free memory if it was allocated within the MEX file. */ if (Ri_alloc){ mxFree(Ri); } if (xi_alloc){ mxFree(xi); } if (bi_alloc){ mxFree(bi); } mxFree(idx); mxFree(thread_args_sweep); /* Don't think I need pthread_exit() here, because pthread_join is called above */ return; }
{ "alphanum_fraction": 0.6589124746, "avg_line_length": 30.774049217, "ext": "c", "hexsha": "2da869d95b20b21fb67d9af48500141927932b45", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-04-27T08:46:39.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-15T02:34:32.000Z", "max_forks_repo_head_hexsha": "3fb78e7338b9f1702dfcc0a94748ce5e86562739", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "yuanyuxin0077/SLIM-release-apps-public", "max_forks_repo_path": "tools/deprecated/solvers/Krylov/sweep_MT_mex_old.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3fb78e7338b9f1702dfcc0a94748ce5e86562739", "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": "yuanyuxin0077/SLIM-release-apps-public", "max_issues_repo_path": "tools/deprecated/solvers/Krylov/sweep_MT_mex_old.c", "max_line_length": 128, "max_stars_count": 2, "max_stars_repo_head_hexsha": "4db4043a38c5a4b7ccfee87be3e43992a38e8054", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "liaman/SLIM-release-apps-public", "max_stars_repo_path": "tools/deprecated/solvers/Krylov/sweep_MT_mex_old.c", "max_stars_repo_stars_event_max_datetime": "2021-09-03T13:36:49.000Z", "max_stars_repo_stars_event_min_datetime": "2021-07-26T02:42:22.000Z", "num_tokens": 4271, "size": 13756 }
#ifndef GBPINTERPOLATE_AWAKE #define GBPINTERPOLATE_AWAKE #include <gbpLib.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_integration.h> typedef struct interp_struct interp_info; struct interp_struct { gsl_interp * interp; gsl_interp_accel * accel; size_t n; const gsl_interp_type *T; double * x; double * y; }; void free_interpolate(void **interp, void *params); void init_interpolate(double *x, double *y, size_t n, const gsl_interp_type *T, interp_info **interp); void ADaPS_store_interp(ADaPS **list, void *data, const char *name, ...); double interpolate(interp_info *interp, double x); double interpolate_derivative(interp_info *interp, double x); double interpolate_integral(interp_info *interp, double x_lo, double x_hi); double interpolate_maximum_function(double x, void *params); void interpolate_maximum(interp_info *interp, double x_lo_in, double x_guess_in, double x_hi_in, double threshold, double * x_maxima, double * y_maxima); double interpolate_minimum_function(double x, void *params); void interpolate_minimum(interp_info *interp, double x_lo_in, double x_guess_in, double x_hi_in, double threshold, double * x_minima, double * y_minima); #endif
{ "alphanum_fraction": 0.5641646489, "avg_line_length": 40.2926829268, "ext": "h", "hexsha": "af4223b1427e87be054e6ff6cee5689cb5db0e50", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpMath/gbpInterpolate/gbpInterpolate.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpMath/gbpInterpolate/gbpInterpolate.h", "max_line_length": 104, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpMath/gbpInterpolate/gbpInterpolate.h", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "num_tokens": 326, "size": 1652 }
/** * @file LoadFromBST.h * * @brief Definition of function to load voxel volume from BST files * * @author Stefan Reinhold * @copyright Copyright (C) 2018 Stefan Reinhold -- All Rights Reserved. * You may use, distribute and modify this code under the terms of * the AFL 3.0 license; see LICENSE for full license details. */ #pragma once #include "VolumeSize.h" #include "VoxelSize.h" #include <Eigen/Core> #include <ImageStack/ImageStack.h> #include <ImageStack/ImageStackLoaderBST.h> #include <ImageStack/ResolutionDecorator.h> #include <gsl/gsl> namespace CortidQCT { namespace IO { /** * @brief Loads a BST file and calles the given functional with the loaded * data. * * The functional is called with a pointer to the raw data as the first * argument, the 3d size of the loaded data as the second argument a with the * 3d resolution (i.e. voxel size) as the third argument. * * @tparam F functional to be called by the function * @param filename Path to the file to be loaded * @param f functional that is beeing called * @throw std::runtime_error if the loading failed */ template <class F> void loadFromBST(std::string const &filename, F &&f) { using Decorator = ImageStack::ResolutionDecorator; using Img = ImageStack::ImageStack<float, ImageStack::HostStorage, Decorator>; using Loader = ImageStack::ImageStackLoaderBST<Img>; auto const img = Img(Loader(filename)); auto const mapping = img.map(); auto const size = img.size().template cast<std::size_t>().eval(); auto const resol = img.resolution.template cast<float>().eval(); VoxelSize voxelSize{resol.x(), resol.y(), resol.z()}; VolumeSize volumeSize{size.x(), size.y(), size.z()}; f(mapping.data(), volumeSize, voxelSize); } } // namespace IO } // namespace CortidQCT
{ "alphanum_fraction": 0.7082417582, "avg_line_length": 30.8474576271, "ext": "h", "hexsha": "77765689838593768b86372fc3c95141352bc35b", "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": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_forks_repo_licenses": [ "AFL-3.0" ], "max_forks_repo_name": "ithron/CortidQCT", "max_forks_repo_path": "lib/optional/LoadFromBST.h", "max_issues_count": 28, "max_issues_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_issues_repo_issues_event_max_datetime": "2021-04-22T08:11:33.000Z", "max_issues_repo_issues_event_min_datetime": "2018-10-23T10:51:36.000Z", "max_issues_repo_licenses": [ "AFL-3.0" ], "max_issues_repo_name": "ithron/CortidQCT", "max_issues_repo_path": "lib/optional/LoadFromBST.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59", "max_stars_repo_licenses": [ "AFL-3.0" ], "max_stars_repo_name": "ithron/CortidQCT", "max_stars_repo_path": "lib/optional/LoadFromBST.h", "max_stars_repo_stars_event_max_datetime": "2021-08-21T17:30:23.000Z", "max_stars_repo_stars_event_min_datetime": "2021-08-21T17:30:23.000Z", "num_tokens": 451, "size": 1820 }
/** * \author Sylvain Marsat, University of Maryland - NASA GSFC * * \brief C code for the geometric coefficients entering the response for LISA-like detectors. * */ #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 "waveform.h" #include "LISAgeometry.h" #include <time.h> /* for testing */ //Named LISA-like constellation struct examples /* struct tagLISAconstellation { double OrbitOmega,OrbitPhi0,OrbitR; double ConstOmega,ConstPhi0,ConstL; } */ LISAconstellation LISAProposal = { EarthOrbitOmega_SI, 0, AU_SI, EarthOrbitOmega_SI, 0, 2.5e9, LISAProposalnoise }; LISAconstellation LISA2017 = { EarthOrbitOmega_SI, 0, AU_SI, EarthOrbitOmega_SI, 0, 2.5e9, LISA2017noise }; LISAconstellation LISA2010 = { EarthOrbitOmega_SI, 0, AU_SI, EarthOrbitOmega_SI, 0, 5e9, LISA2010noise }; LISAconstellation slowOrbitLISA = { EarthOrbitOmega_SI/100.0, 0, AU_SI, EarthOrbitOmega_SI/100.0, 0, 2.5e9, LISA2017noise }; LISAconstellation tinyOrbitLISA = { EarthOrbitOmega_SI, 0, AU_SI/100, EarthOrbitOmega_SI, 0, 2.5e9, LISA2017noise }; LISAconstellation fastOrbitLISA = { EarthOrbitOmega_SI*10.0, 0, AU_SI, EarthOrbitOmega_SI*10.0, 0, 2.5e9, LISA2017noise }; LISAconstellation bigOrbitLISA = { EarthOrbitOmega_SI/10.0, 0, AU_SI, EarthOrbitOmega_SI/10.0, 0, 2.5e9, LISA2017noise }; /****************************************************************/ /********* Coefficients for the geometric response **************/ /* External storage for cos, sin and coefficients */ static double coeffn1Hn1crossconst, coeffn1Hn1plusconst, coeffn2Hn2crossconst, coeffn2Hn2plusconst, coeffn3Hn3crossconst, coeffn3Hn3plusconst; static double coeffn1Hn1pluscos[4]; static double coeffn1Hn1plussin[4]; static double coeffn2Hn2pluscos[4]; static double coeffn2Hn2plussin[4]; static double coeffn3Hn3pluscos[4]; static double coeffn3Hn3plussin[4]; static double coeffn1Hn1crosscos[4]; static double coeffn1Hn1crosssin[4]; static double coeffn2Hn2crosscos[4]; static double coeffn2Hn2crosssin[4]; static double coeffn3Hn3crosscos[4]; static double coeffn3Hn3crosssin[4]; static double coeffkn1const, coeffkn2const, coeffkn3const, coeffkp1plusp2const, coeffkp2plusp3const, coeffkp3plusp1const, coeffkp1const, coeffkp2const, coeffkp3const, coeffkRconst; static double coeffkn1cos[2]; static double coeffkn1sin[2]; static double coeffkn2cos[2]; static double coeffkn2sin[2]; static double coeffkn3cos[2]; static double coeffkn3sin[2]; static double coeffkp1plusp2cos[2]; static double coeffkp1plusp2sin[2]; static double coeffkp2plusp3cos[2]; static double coeffkp2plusp3sin[2]; static double coeffkp3plusp1cos[2]; static double coeffkp3plusp1sin[2]; static double coeffkp1cos[2]; static double coeffkp1sin[2]; static double coeffkp2cos[2]; static double coeffkp2sin[2]; static double coeffkp3cos[2]; static double coeffkp3sin[2]; static double coeffkRcos[2]; static double coeffkRsin[2]; static double cosarray[4]; static double sinarray[4]; #pragma omp threadprivate(coeffn1Hn1crossconst, coeffn1Hn1plusconst, coeffn2Hn2crossconst, coeffn2Hn2plusconst, coeffn3Hn3crossconst, coeffn3Hn3plusconst) #pragma omp threadprivate(coeffn1Hn1pluscos,coeffn1Hn1plussin,coeffn2Hn2pluscos,coeffn2Hn2plussin,coeffn3Hn3pluscos,coeffn3Hn3plussin) #pragma omp threadprivate(coeffn1Hn1crosscos,coeffn1Hn1crosssin,coeffn2Hn2crosscos,coeffn2Hn2crosssin,coeffn3Hn3crosscos,coeffn3Hn3crosssin) #pragma omp threadprivate(coeffkn1const, coeffkn2const, coeffkn3const, coeffkp1plusp2const, coeffkp2plusp3const, coeffkp3plusp1const, coeffkp1const, coeffkp2const, coeffkp3const, coeffkRconst) #pragma omp threadprivate(coeffkn1cos,coeffkn1sin,coeffkn2cos,coeffkn2sin,coeffkn3cos,coeffkn3sin) #pragma omp threadprivate(coeffkp1cos,coeffkp1sin,coeffkp2cos,coeffkp2sin,coeffkp3cos,coeffkp3sin) #pragma omp threadprivate(coeffkp1plusp2cos,coeffkp1plusp2sin,coeffkp2plusp3cos,coeffkp2plusp3sin,coeffkp3plusp1cos,coeffkp3plusp1sin) #pragma omp threadprivate(coeffkRcos,coeffkRsin,cosarray,sinarray) /*************************************************************/ /********* Functions for the geometric response **************/ /* Function to convert string input TDI string to TDItag */ TDItag ParseTDItag(char* string) { TDItag tag; if(strcmp(string, "delayO")==0) tag = delayO; else if(strcmp(string, "y12L")==0) tag = y12L; else if(strcmp(string, "y12")==0) tag = y12; else if(strcmp(string, "TDIXYZ")==0) tag = TDIXYZ; else if(strcmp(string, "TDIalphabetagamma")==0) tag = TDIalphabetagamma; else if(strcmp(string, "TDIAETXYZ")==0) tag = TDIAETXYZ; else if(strcmp(string, "TDIAETalphabetagamma")==0) tag = TDIAETalphabetagamma; else if(strcmp(string, "TDIX")==0) tag = TDIX; else if(strcmp(string, "TDIalpha")==0) tag = TDIalpha; else if(strcmp(string, "TDIAXYZ")==0) tag = TDIAXYZ; else if(strcmp(string, "TDIEXYZ")==0) tag = TDIEXYZ; else if(strcmp(string, "TDITXYZ")==0) tag = TDITXYZ; else if(strcmp(string, "TDIAalphabetagamma")==0) tag = TDIAalphabetagamma; else if(strcmp(string, "TDIEalphabetagamma")==0) tag = TDIEalphabetagamma; else if(strcmp(string, "TDITalphabetagamma")==0) tag = TDITalphabetagamma; else { printf("Error in ParseTDItag: string not recognized.\n"); exit(1); } return tag; } /* Function to convert string input ResponseApprox to tag */ ResponseApproxtag ParseResponseApproxtag(char* string) { ResponseApproxtag tag; if(strcmp(string, "full")==0) tag = full; else if(strcmp(string, "lowfL")==0) tag = lowfL; else if(strcmp(string, "lowf")==0) tag = lowf; else { printf("Error in ParseResponseApproxtag: string not recognized.\n"); exit(1); } return tag; } /* Compute Solar System Barycenter time tSSB from retarded time at the center of the LISA constellation tL */ /* NOTE: depends on the sky position given in SSB parameters */ double tSSBfromLframe(const LISAconstellation *variant, const double tL, const double lambdaSSB, const double betaSSB) { double phase = variant->ConstOmega*tL + variant->ConstPhi0 - lambdaSSB; double RoC = variant->OrbitR/C_SI; return tL + RoC*cos(betaSSB)*cos(phase) - 1./2*variant->ConstOmega*pow(RoC*cos(betaSSB), 2)*sin(2.*phase); } /* Compute retarded time at the center of the LISA constellation tL from Solar System Barycenter time tSSB */ double tLfromSSBframe(const LISAconstellation *variant, const double tSSB, const double lambdaSSB, const double betaSSB) { double phase = variant->ConstOmega*tSSB + variant->ConstPhi0 - lambdaSSB; double RoC = variant->OrbitR/C_SI; return tSSB - RoC*cos(betaSSB)*cos(phase); } /* Convert L-frame params to SSB-frame params */ /* NOTE: no transformation of the phase -- approximant-dependence with e.g. EOBNRv2HMROM setting phiRef at fRef, and freedom in definition */ int ConvertLframeParamsToSSBframe( double* tSSB, double* lambdaSSB, double* betaSSB, double* psiSSB, const double tL, const double lambdaL, const double betaL, const double psiL, const LISAconstellation *variant) { double alpha = 0., cosalpha = 0, sinalpha = 0., coslambdaL = 0, sinlambdaL = 0., cosbetaL = 0., sinbetaL = 0., cospsiL = 0., sinpsiL = 0.; double coszeta = cos(PI/3.); double sinzeta = sin(PI/3.); coslambdaL = cos(lambdaL); sinlambdaL = sin(lambdaL); cosbetaL = cos(betaL); sinbetaL = sin(betaL); cospsiL = cos(psiL); sinpsiL = sin(psiL); double lambdaSSB_approx = 0.; double betaSSB_approx = 0.; /* Initially, approximate alpha using tL instead of tSSB - then iterate */ double tSSB_approx = tL; for(int k=0; k<3; k++) { alpha = variant->ConstOmega * (tSSB_approx) + variant->ConstPhi0; cosalpha = cos(alpha); sinalpha = sin(alpha); lambdaSSB_approx = atan2(cosalpha*cosalpha*cosbetaL*sinlambdaL -sinalpha*sinbetaL*sinzeta + cosbetaL*coszeta*sinalpha*sinalpha*sinlambdaL -cosalpha*cosbetaL*coslambdaL*sinalpha + cosalpha*cosbetaL*coszeta*coslambdaL*sinalpha, cosbetaL*coslambdaL*sinalpha*sinalpha -cosalpha*sinbetaL*sinzeta + cosalpha*cosalpha*cosbetaL*coszeta*coslambdaL -cosalpha*cosbetaL*sinalpha*sinlambdaL + cosalpha*cosbetaL*coszeta*sinalpha*sinlambdaL); betaSSB_approx = asin(coszeta*sinbetaL + cosalpha*cosbetaL*coslambdaL*sinzeta + cosbetaL*sinalpha*sinzeta*sinlambdaL); tSSB_approx = tSSBfromLframe(variant, tL, lambdaSSB_approx, betaSSB_approx); } *tSSB = tSSB_approx; *lambdaSSB = lambdaSSB_approx; *betaSSB = betaSSB_approx; /* Polarization */ *psiSSB = modpi(psiL + atan2(cosalpha*sinzeta*sinlambdaL -coslambdaL*sinalpha*sinzeta, cosbetaL*coszeta -cosalpha*coslambdaL*sinbetaL*sinzeta -sinalpha*sinbetaL*sinzeta*sinlambdaL)); return SUCCESS; } /* Convert SSB-frame params to L-frame params */ /* NOTE: no transformation of the phase -- approximant-dependence with e.g. EOBNRv2HMROM setting phiRef at fRef, and freedom in definition */ int ConvertSSBframeParamsToLframe( double* tL, double* lambdaL, double* betaL, double* psiL, const double tSSB, const double lambdaSSB, const double betaSSB, const double psiSSB, const LISAconstellation *variant) { double alpha = 0., cosalpha = 0, sinalpha = 0., coslambda = 0, sinlambda = 0., cosbeta = 0., sinbeta = 0., cospsi = 0., sinpsi = 0.; double coszeta = cos(PI/3.); double sinzeta = sin(PI/3.); coslambda = cos(lambdaSSB); sinlambda = sin(lambdaSSB); cosbeta = cos(betaSSB); sinbeta = sin(betaSSB); cospsi = cos(psiSSB); sinpsi = sin(psiSSB); alpha = variant->ConstOmega * (tSSB) + variant->ConstPhi0; cosalpha = cos(alpha); sinalpha = sin(alpha); *tL = tLfromSSBframe(variant, tSSB, lambdaSSB, betaSSB); *lambdaL = atan2(cosalpha*cosalpha*cosbeta*sinlambda + sinalpha*sinbeta*sinzeta + cosbeta*coszeta*sinalpha*sinalpha*sinlambda -cosalpha*cosbeta*coslambda*sinalpha + cosalpha*cosbeta*coszeta*coslambda*sinalpha, cosalpha*sinbeta*sinzeta + cosbeta*coslambda*sinalpha*sinalpha + cosalpha*cosalpha*cosbeta*coszeta*coslambda -cosalpha*cosbeta*sinalpha*sinlambda + cosalpha*cosbeta*coszeta*sinalpha*sinlambda); *betaL = asin(coszeta*sinbeta -cosalpha*cosbeta*coslambda*sinzeta -cosbeta*sinalpha*sinzeta*sinlambda); *psiL = modpi(psiSSB + atan2(coslambda*sinalpha*sinzeta -cosalpha*sinzeta*sinlambda, cosbeta*coszeta + cosalpha*coslambda*sinbeta*sinzeta + sinalpha*sinbeta*sinzeta*sinlambda)); return SUCCESS; } /* Function cardinal sine */ double sinc(const double x) { if (x==0) return 1; else return sin(x)/x; } /* Function to compute, given a value of a sky position and polarization, all the complicated time-independent trigonometric coefficients entering the response */ void SetCoeffsG(const double lambda, const double beta, const double psi) { /* Precomputing cosines and sines */ double coslambda = cos(lambda); double sinlambda = sin(lambda); double cosbeta = cos(beta); double sinbeta = sin(beta); double cospsi = cos(psi); double sinpsi = sin(psi); /* Projection coefficients for hplus in n3.H.n3 */ /**/ coeffn3Hn3plusconst = 1./128 * (-4*cospsi*cospsi + 4*sinpsi*sinpsi -27*coslambda*coslambda*cospsi*cospsi -27*sinlambda*sinlambda*sinpsi*sinpsi -4*cosbeta*cosbeta*cospsi*cospsi -4*sinbeta*sinbeta*sinpsi*sinpsi + 4*cosbeta*cosbeta*sinpsi*sinpsi + 4*cospsi*cospsi*sinbeta*sinbeta + 27*coslambda*coslambda*sinpsi*sinpsi + 27*cospsi*cospsi*sinlambda*sinlambda -9*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -9*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -9*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -9*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 9*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + 9*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + 9*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + 9*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -54*sqrt3*coslambda*sinlambda*sinpsi*sinpsi + 54*sqrt3*coslambda*cospsi*cospsi*sinlambda -144*coslambda*cospsi*sinbeta*sinlambda*sinpsi -72*sqrt3*coslambda*coslambda*cospsi*sinbeta*sinpsi -18*sqrt3*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi -18*sqrt3*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 18*sqrt3*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda + 18*sqrt3*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 72*sqrt3*cospsi*sinbeta*sinlambda*sinlambda*sinpsi); /**/ coeffn3Hn3pluscos[0] = 1./16*cosbeta * (-9*cospsi*cospsi*sinbeta*sinlambda + 9*sinbeta*sinlambda*sinpsi*sinpsi + 18*coslambda*cospsi*sinpsi -7*sqrt3*coslambda*sinbeta*sinpsi*sinpsi + 7*sqrt3*coslambda*cospsi*cospsi*sinbeta + 14*sqrt3*cospsi*sinlambda*sinpsi); /**/ coeffn3Hn3pluscos[1] = -3./64 * (-3*sinpsi*sinpsi + 3*cospsi*cospsi -6*coslambda*coslambda*cospsi*cospsi -6*sinlambda*sinlambda*sinpsi*sinpsi -3*cosbeta*cosbeta*sinpsi*sinpsi -3*cospsi*cospsi*sinbeta*sinbeta + 3*cosbeta*cosbeta*cospsi*cospsi + 3*sinbeta*sinbeta*sinpsi*sinpsi + 6*coslambda*coslambda*sinpsi*sinpsi + 6*cospsi*cospsi*sinlambda*sinlambda -2*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -2*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -2*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -2*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 2*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + 2*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + 2*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + 2*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -32*coslambda*cospsi*sinbeta*sinlambda*sinpsi); /**/ coeffn3Hn3pluscos[2] = -1./16*cosbeta * (-6*coslambda*cospsi*sinpsi -3*sinbeta*sinlambda*sinpsi*sinpsi + 3*cospsi*cospsi*sinbeta*sinlambda + sqrt3*coslambda*cospsi*cospsi*sinbeta -sqrt3*coslambda*sinbeta*sinpsi*sinpsi + 2*sqrt3*cospsi*sinlambda*sinpsi); /**/ coeffn3Hn3pluscos[3] = 1./128 * (-3*coslambda*coslambda*cospsi*cospsi -3*sinlambda*sinlambda*sinpsi*sinpsi + 3*coslambda*coslambda*sinpsi*sinpsi + 3*cospsi*cospsi*sinlambda*sinlambda + cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -6*sqrt3*coslambda*cospsi*cospsi*sinlambda + 6*sqrt3*coslambda*sinlambda*sinpsi*sinpsi -16*coslambda*cospsi*sinbeta*sinlambda*sinpsi -8*sqrt3*cospsi*sinbeta*sinlambda*sinlambda*sinpsi -2*sqrt3*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda -2*sqrt3*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 2*sqrt3*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi + 2*sqrt3*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 8*sqrt3*coslambda*coslambda*cospsi*sinbeta*sinpsi); /**/ coeffn3Hn3plussin[0] = -1./16*cosbeta * (-9*coslambda*sinbeta*sinpsi*sinpsi + 9*coslambda*cospsi*cospsi*sinbeta + 18*cospsi*sinlambda*sinpsi + sqrt3*sinbeta*sinlambda*sinpsi*sinpsi -sqrt3*cospsi*cospsi*sinbeta*sinlambda + 2*sqrt3*coslambda*cospsi*sinpsi); /**/ coeffn3Hn3plussin[1] = 3./64 * (-3*sqrt3*sinpsi*sinpsi + 3*sqrt3*cospsi*cospsi -12*coslambda*sinlambda*sinpsi*sinpsi -3*sqrt3*cosbeta*cosbeta*sinpsi*sinpsi -3*sqrt3*cospsi*cospsi*sinbeta*sinbeta + 3*sqrt3*cosbeta*cosbeta*cospsi*cospsi + 3*sqrt3*sinbeta*sinbeta*sinpsi*sinpsi + 12*coslambda*cospsi*cospsi*sinlambda -16*coslambda*coslambda*cospsi*sinbeta*sinpsi -4*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi -4*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 4*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda + 4*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 16*cospsi*sinbeta*sinlambda*sinlambda*sinpsi); /**/ coeffn3Hn3plussin[2] = 1./16*cosbeta * (-3*coslambda*sinbeta*sinpsi*sinpsi + 3*coslambda*cospsi*cospsi*sinbeta + 6*cospsi*sinlambda*sinpsi + sqrt3*sinbeta*sinlambda*sinpsi*sinpsi -sqrt3*cospsi*cospsi*sinbeta*sinlambda + 2*sqrt3*coslambda*cospsi*sinpsi); /**/ coeffn3Hn3plussin[3] = 1./128 * (-6*coslambda*cospsi*cospsi*sinlambda -3*sqrt3*coslambda*coslambda*sinpsi*sinpsi -3*sqrt3*cospsi*cospsi*sinlambda*sinlambda + 3*sqrt3*coslambda*coslambda*cospsi*cospsi + 3*sqrt3*sinlambda*sinlambda*sinpsi*sinpsi + 6*coslambda*sinlambda*sinpsi*sinpsi + sqrt3*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi + sqrt3*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda + sqrt3*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta + sqrt3*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -8*cospsi*sinbeta*sinlambda*sinlambda*sinpsi -2*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda -2*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi -sqrt3*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi -sqrt3*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi -sqrt3*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi -sqrt3*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda + 2*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi + 2*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 8*coslambda*coslambda*cospsi*sinbeta*sinpsi + 16*sqrt3*coslambda*cospsi*sinbeta*sinlambda*sinpsi); /* Projection coefficients for hcross in n3.H.n3 */ /**/ coeffn3Hn3crossconst = 1./64 * (4*cospsi*sinpsi -27*cospsi*sinlambda*sinlambda*sinpsi -4*cospsi*sinbeta*sinbeta*sinpsi + 4*cosbeta*cosbeta*cospsi*sinpsi + 27*coslambda*coslambda*cospsi*sinpsi -36*coslambda*cospsi*cospsi*sinbeta*sinlambda -18*sqrt3*coslambda*coslambda*cospsi*cospsi*sinbeta -18*sqrt3*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -9*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -9*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 9*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + 9*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 18*sqrt3*coslambda*coslambda*sinbeta*sinpsi*sinpsi + 18*sqrt3*cospsi*cospsi*sinbeta*sinlambda*sinlambda + 36*coslambda*sinbeta*sinlambda*sinpsi*sinpsi -54*sqrt3*coslambda*cospsi*sinlambda*sinpsi -18*sqrt3*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi + 18*sqrt3*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi); /**/ coeffn3Hn3crosscos[0] = 1./16*cosbeta * (-9*coslambda*sinpsi*sinpsi + 9*coslambda*cospsi*cospsi -7*sqrt3*sinlambda*sinpsi*sinpsi + 7*sqrt3*cospsi*cospsi*sinlambda + 18*cospsi*sinbeta*sinlambda*sinpsi -14*sqrt3*coslambda*cospsi*sinbeta*sinpsi); /**/ coeffn3Hn3crosscos[1] = -3./32 * (-3*cospsi*sinpsi -6*cospsi*sinlambda*sinlambda*sinpsi -3*cosbeta*cosbeta*cospsi*sinpsi + 3*cospsi*sinbeta*sinbeta*sinpsi + 6*coslambda*coslambda*cospsi*sinpsi -8*coslambda*cospsi*cospsi*sinbeta*sinlambda -2*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -2*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 2*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + 2*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 8*coslambda*sinbeta*sinlambda*sinpsi*sinpsi); /**/ coeffn3Hn3crosscos[2] = 1./16*cosbeta * (-3*coslambda*sinpsi*sinpsi + 3*coslambda*cospsi*cospsi + sqrt3*sinlambda*sinpsi*sinpsi -sqrt3*cospsi*cospsi*sinlambda + 6*cospsi*sinbeta*sinlambda*sinpsi + 2*sqrt3*coslambda*cospsi*sinbeta*sinpsi); /**/ coeffn3Hn3crosscos[3] = 1./64 * (-3*cospsi*sinlambda*sinlambda*sinpsi + 3*coslambda*coslambda*cospsi*sinpsi + cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi -4*coslambda*cospsi*cospsi*sinbeta*sinlambda -2*sqrt3*coslambda*coslambda*sinbeta*sinpsi*sinpsi -2*sqrt3*cospsi*cospsi*sinbeta*sinlambda*sinlambda -cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 2*sqrt3*coslambda*coslambda*cospsi*cospsi*sinbeta + 2*sqrt3*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 4*coslambda*sinbeta*sinlambda*sinpsi*sinpsi + 6*sqrt3*coslambda*cospsi*sinlambda*sinpsi -2*sqrt3*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi + 2*sqrt3*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi); /**/ coeffn3Hn3crosssin[0] = -1./16*cosbeta * (-9*sinlambda*sinpsi*sinpsi + 9*cospsi*cospsi*sinlambda + sqrt3*coslambda*cospsi*cospsi -sqrt3*coslambda*sinpsi*sinpsi -18*coslambda*cospsi*sinbeta*sinpsi + 2*sqrt3*cospsi*sinbeta*sinlambda*sinpsi); /**/ coeffn3Hn3crosssin[1] = -3./32 * (-4*coslambda*coslambda*sinbeta*sinpsi*sinpsi -4*cospsi*cospsi*sinbeta*sinlambda*sinlambda + 3*sqrt3*cospsi*sinpsi + 4*coslambda*coslambda*cospsi*cospsi*sinbeta + 4*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -3*sqrt3*cospsi*sinbeta*sinbeta*sinpsi + 3*sqrt3*cosbeta*cosbeta*cospsi*sinpsi + 12*coslambda*cospsi*sinlambda*sinpsi -4*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi + 4*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi); /**/ coeffn3Hn3crosssin[2] = 1./16*cosbeta * (-3*sinlambda*sinpsi*sinpsi + 3*cospsi*cospsi*sinlambda + sqrt3*coslambda*cospsi*cospsi -sqrt3*coslambda*sinpsi*sinpsi -6*coslambda*cospsi*sinbeta*sinpsi + 2*sqrt3*cospsi*sinbeta*sinlambda*sinpsi); /**/ coeffn3Hn3crosssin[3] = 1./64 * (-2*coslambda*coslambda*sinbeta*sinpsi*sinpsi -2*cospsi*cospsi*sinbeta*sinlambda*sinlambda + 2*coslambda*coslambda*cospsi*cospsi*sinbeta + 2*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -3*sqrt3*coslambda*coslambda*cospsi*sinpsi + 3*sqrt3*cospsi*sinlambda*sinlambda*sinpsi + 6*coslambda*cospsi*sinlambda*sinpsi + sqrt3*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi + sqrt3*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi -4*sqrt3*coslambda*sinbeta*sinlambda*sinpsi*sinpsi -2*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi -sqrt3*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi -sqrt3*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 2*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi + 4*sqrt3*coslambda*cospsi*cospsi*sinbeta*sinlambda); /* Projection coefficients for hplus in n2.H.n2 */ /**/ coeffn2Hn2plusconst = 1./128 * (-4*cospsi*cospsi + 4*sinpsi*sinpsi -27*coslambda*coslambda*cospsi*cospsi -27*sinlambda*sinlambda*sinpsi*sinpsi -4*cosbeta*cosbeta*cospsi*cospsi -4*sinbeta*sinbeta*sinpsi*sinpsi + 4*cosbeta*cosbeta*sinpsi*sinpsi + 4*cospsi*cospsi*sinbeta*sinbeta + 27*coslambda*coslambda*sinpsi*sinpsi + 27*cospsi*cospsi*sinlambda*sinlambda -9*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -9*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -9*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -9*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 9*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + 9*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + 9*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + 9*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -54*sqrt3*coslambda*cospsi*cospsi*sinlambda + 54*sqrt3*coslambda*sinlambda*sinpsi*sinpsi -144*coslambda*cospsi*sinbeta*sinlambda*sinpsi -72*sqrt3*cospsi*sinbeta*sinlambda*sinlambda*sinpsi -18*sqrt3*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda -18*sqrt3*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 18*sqrt3*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi + 18*sqrt3*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 72*sqrt3*coslambda*coslambda*cospsi*sinbeta*sinpsi); /**/ coeffn2Hn2pluscos[0] = 1./16*cosbeta * (-18*coslambda*cospsi*sinpsi -9*sinbeta*sinlambda*sinpsi*sinpsi + 9*cospsi*cospsi*sinbeta*sinlambda -7*sqrt3*coslambda*sinbeta*sinpsi*sinpsi + 7*sqrt3*coslambda*cospsi*cospsi*sinbeta + 14*sqrt3*cospsi*sinlambda*sinpsi); /**/ coeffn2Hn2pluscos[1] = -3./64 * (-3*sinpsi*sinpsi + 3*cospsi*cospsi -6*coslambda*coslambda*cospsi*cospsi -6*sinlambda*sinlambda*sinpsi*sinpsi -3*cosbeta*cosbeta*sinpsi*sinpsi -3*cospsi*cospsi*sinbeta*sinbeta + 3*cosbeta*cosbeta*cospsi*cospsi + 3*sinbeta*sinbeta*sinpsi*sinpsi + 6*coslambda*coslambda*sinpsi*sinpsi + 6*cospsi*cospsi*sinlambda*sinlambda -2*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -2*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -2*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -2*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 2*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + 2*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + 2*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + 2*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -32*coslambda*cospsi*sinbeta*sinlambda*sinpsi); /**/ coeffn2Hn2pluscos[2] = -1./16*cosbeta * (-3*cospsi*cospsi*sinbeta*sinlambda + 3*sinbeta*sinlambda*sinpsi*sinpsi + 6*coslambda*cospsi*sinpsi + sqrt3*coslambda*cospsi*cospsi*sinbeta -sqrt3*coslambda*sinbeta*sinpsi*sinpsi + 2*sqrt3*cospsi*sinlambda*sinpsi); /**/ coeffn2Hn2pluscos[3] = 1./128 * (-3*coslambda*coslambda*cospsi*cospsi -3*sinlambda*sinlambda*sinpsi*sinpsi + 3*coslambda*coslambda*sinpsi*sinpsi + 3*cospsi*cospsi*sinlambda*sinlambda + cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -6*sqrt3*coslambda*sinlambda*sinpsi*sinpsi + 6*sqrt3*coslambda*cospsi*cospsi*sinlambda -16*coslambda*cospsi*sinbeta*sinlambda*sinpsi -8*sqrt3*coslambda*coslambda*cospsi*sinbeta*sinpsi -2*sqrt3*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi -2*sqrt3*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 2*sqrt3*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda + 2*sqrt3*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 8*sqrt3*cospsi*sinbeta*sinlambda*sinlambda*sinpsi); /**/ coeffn2Hn2plussin[0] = 1./16*cosbeta * (-9*coslambda*sinbeta*sinpsi*sinpsi + 9*coslambda*cospsi*cospsi*sinbeta + 18*cospsi*sinlambda*sinpsi + sqrt3*cospsi*cospsi*sinbeta*sinlambda -2*sqrt3*coslambda*cospsi*sinpsi -sqrt3*sinbeta*sinlambda*sinpsi*sinpsi); /**/ coeffn2Hn2plussin[1] = -3./64 * (-3*sqrt3*sinpsi*sinpsi + 3*sqrt3*cospsi*cospsi -12*coslambda*cospsi*cospsi*sinlambda -3*sqrt3*cosbeta*cosbeta*sinpsi*sinpsi -3*sqrt3*cospsi*cospsi*sinbeta*sinbeta + 3*sqrt3*cosbeta*cosbeta*cospsi*cospsi + 3*sqrt3*sinbeta*sinbeta*sinpsi*sinpsi + 12*coslambda*sinlambda*sinpsi*sinpsi -16*cospsi*sinbeta*sinlambda*sinlambda*sinpsi -4*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda -4*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 4*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi + 4*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 16*coslambda*coslambda*cospsi*sinbeta*sinpsi); /**/ coeffn2Hn2plussin[2] = -1./16*cosbeta * (-3*coslambda*sinbeta*sinpsi*sinpsi + 3*coslambda*cospsi*cospsi*sinbeta + 6*cospsi*sinlambda*sinpsi + sqrt3*cospsi*cospsi*sinbeta*sinlambda -2*sqrt3*coslambda*cospsi*sinpsi -sqrt3*sinbeta*sinlambda*sinpsi*sinpsi); /**/ coeffn2Hn2plussin[3] = 1./128 * (-6*coslambda*cospsi*cospsi*sinlambda -3*sqrt3*coslambda*coslambda*cospsi*cospsi -3*sqrt3*sinlambda*sinlambda*sinpsi*sinpsi + 3*sqrt3*coslambda*coslambda*sinpsi*sinpsi + 3*sqrt3*cospsi*cospsi*sinlambda*sinlambda + 6*coslambda*sinlambda*sinpsi*sinpsi + sqrt3*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + sqrt3*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + sqrt3*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + sqrt3*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -8*cospsi*sinbeta*sinlambda*sinlambda*sinpsi -2*coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda -2*cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi -sqrt3*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -sqrt3*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -sqrt3*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -sqrt3*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 2*coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi + 2*cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 8*coslambda*coslambda*cospsi*sinbeta*sinpsi -16*sqrt3*coslambda*cospsi*sinbeta*sinlambda*sinpsi); /* Projection coefficients for hcross in n2.H.n2 */ /**/ coeffn2Hn2crossconst = 1./64 * (4*cospsi*sinpsi -27*cospsi*sinlambda*sinlambda*sinpsi -4*cospsi*sinbeta*sinbeta*sinpsi + 4*cosbeta*cosbeta*cospsi*sinpsi + 27*coslambda*coslambda*cospsi*sinpsi -36*coslambda*cospsi*cospsi*sinbeta*sinlambda -18*sqrt3*coslambda*coslambda*sinbeta*sinpsi*sinpsi -18*sqrt3*cospsi*cospsi*sinbeta*sinlambda*sinlambda -9*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -9*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 9*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + 9*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 18*sqrt3*coslambda*coslambda*cospsi*cospsi*sinbeta + 18*sqrt3*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 36*coslambda*sinbeta*sinlambda*sinpsi*sinpsi + 54*sqrt3*coslambda*cospsi*sinlambda*sinpsi -18*sqrt3*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi + 18*sqrt3*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi); /**/ coeffn2Hn2crosscos[0] = -1./16*cosbeta * (-9*coslambda*sinpsi*sinpsi + 9*coslambda*cospsi*cospsi -7*sqrt3*cospsi*cospsi*sinlambda + 7*sqrt3*sinlambda*sinpsi*sinpsi + 18*cospsi*sinbeta*sinlambda*sinpsi + 14*sqrt3*coslambda*cospsi*sinbeta*sinpsi); /**/ coeffn2Hn2crosscos[1] = -3./32 * (-3*cospsi*sinpsi -6*cospsi*sinlambda*sinlambda*sinpsi -3*cosbeta*cosbeta*cospsi*sinpsi + 3*cospsi*sinbeta*sinbeta*sinpsi + 6*coslambda*coslambda*cospsi*sinpsi -8*coslambda*cospsi*cospsi*sinbeta*sinlambda -2*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -2*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 2*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + 2*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 8*coslambda*sinbeta*sinlambda*sinpsi*sinpsi); /**/ coeffn2Hn2crosscos[2] = -1./16*cosbeta * (-3*coslambda*sinpsi*sinpsi + 3*coslambda*cospsi*cospsi + sqrt3*cospsi*cospsi*sinlambda -sqrt3*sinlambda*sinpsi*sinpsi + 6*cospsi*sinbeta*sinlambda*sinpsi -2*sqrt3*coslambda*cospsi*sinbeta*sinpsi); /**/ coeffn2Hn2crosscos[3] = 1./64 * (-3*cospsi*sinlambda*sinlambda*sinpsi + 3*coslambda*coslambda*cospsi*sinpsi + cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi -4*coslambda*cospsi*cospsi*sinbeta*sinlambda -2*sqrt3*coslambda*coslambda*cospsi*cospsi*sinbeta -2*sqrt3*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 2*sqrt3*coslambda*coslambda*sinbeta*sinpsi*sinpsi + 2*sqrt3*cospsi*cospsi*sinbeta*sinlambda*sinlambda + 4*coslambda*sinbeta*sinlambda*sinpsi*sinpsi -6*sqrt3*coslambda*cospsi*sinlambda*sinpsi -2*sqrt3*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi + 2*sqrt3*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi); /**/ coeffn2Hn2crosssin[0] = -1./16*cosbeta * (-9*cospsi*cospsi*sinlambda + 9*sinlambda*sinpsi*sinpsi + sqrt3*coslambda*cospsi*cospsi -sqrt3*coslambda*sinpsi*sinpsi + 18*coslambda*cospsi*sinbeta*sinpsi + 2*sqrt3*cospsi*sinbeta*sinlambda*sinpsi); /**/ coeffn2Hn2crosssin[1] = -3./32 * (-4*coslambda*coslambda*sinbeta*sinpsi*sinpsi -4*cospsi*cospsi*sinbeta*sinlambda*sinlambda -3*sqrt3*cospsi*sinpsi + 4*coslambda*coslambda*cospsi*cospsi*sinbeta + 4*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -3*sqrt3*cosbeta*cosbeta*cospsi*sinpsi + 3*sqrt3*cospsi*sinbeta*sinbeta*sinpsi + 12*coslambda*cospsi*sinlambda*sinpsi -4*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi + 4*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi); /**/ coeffn2Hn2crosssin[2] = 1./16*cosbeta * (-3*cospsi*cospsi*sinlambda + 3*sinlambda*sinpsi*sinpsi + sqrt3*coslambda*cospsi*cospsi -sqrt3*coslambda*sinpsi*sinpsi + 6*coslambda*cospsi*sinbeta*sinpsi + 2*sqrt3*cospsi*sinbeta*sinlambda*sinpsi); /**/ coeffn2Hn2crosssin[3] = 1./64 * (-2*coslambda*coslambda*sinbeta*sinpsi*sinpsi -2*cospsi*cospsi*sinbeta*sinlambda*sinlambda + 2*coslambda*coslambda*cospsi*cospsi*sinbeta + 2*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -3*sqrt3*cospsi*sinlambda*sinlambda*sinpsi + 3*sqrt3*coslambda*coslambda*cospsi*sinpsi + 6*coslambda*cospsi*sinlambda*sinpsi + sqrt3*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + sqrt3*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi -4*sqrt3*coslambda*cospsi*cospsi*sinbeta*sinlambda -2*cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi -sqrt3*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -sqrt3*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 2*coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi + 4*sqrt3*coslambda*sinbeta*sinlambda*sinpsi*sinpsi); /* Projection coefficients for hplus in n1.H.n1 */ /**/ coeffn1Hn1plusconst = 1./64 * (-2*cospsi*cospsi + 2*sinpsi*sinpsi -27*coslambda*coslambda*sinpsi*sinpsi -27*cospsi*cospsi*sinlambda*sinlambda -2*cosbeta*cosbeta*cospsi*cospsi -2*sinbeta*sinbeta*sinpsi*sinpsi + 2*cosbeta*cosbeta*sinpsi*sinpsi + 2*cospsi*cospsi*sinbeta*sinbeta + 27*coslambda*coslambda*cospsi*cospsi + 27*sinlambda*sinlambda*sinpsi*sinpsi -9*cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi -9*cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi -9*coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi -9*cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda + 9*cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi + 9*cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda + 9*coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta + 9*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi + 144*coslambda*cospsi*sinbeta*sinlambda*sinpsi); /**/ coeffn1Hn1pluscos[0] = -1./8*sqrt3*cosbeta * (coslambda*cospsi*cospsi*sinbeta -coslambda*sinbeta*sinpsi*sinpsi + 2*cospsi*sinlambda*sinpsi); /**/ coeffn1Hn1pluscos[1] = -3./32 * (-3*cospsi*cospsi + 3*sinpsi*sinpsi -3*cosbeta*cosbeta*cospsi*cospsi -3*coslambda*coslambda*cospsi*cospsi -3*sinbeta*sinbeta*sinpsi*sinpsi -3*sinlambda*sinlambda*sinpsi*sinpsi + 3*cosbeta*cosbeta*sinpsi*sinpsi + 3*coslambda*coslambda*sinpsi*sinpsi + 3*cospsi*cospsi*sinbeta*sinbeta + 3*cospsi*cospsi*sinlambda*sinlambda + cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi + cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi + coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi + cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda -cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi -cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda -coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta -sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -16*coslambda*cospsi*sinbeta*sinlambda*sinpsi); /**/ coeffn1Hn1pluscos[2] = 1./8*sqrt3*cosbeta * (coslambda*cospsi*cospsi*sinbeta -coslambda*sinbeta*sinpsi*sinpsi + 2*cospsi*sinlambda*sinpsi); /**/ coeffn1Hn1pluscos[3] = 1./64 * (-3*coslambda*coslambda*sinpsi*sinpsi -3*cospsi*cospsi*sinlambda*sinlambda + 3*coslambda*coslambda*cospsi*cospsi + 3*sinlambda*sinlambda*sinpsi*sinpsi + cosbeta*cosbeta*coslambda*coslambda*sinpsi*sinpsi + cosbeta*cosbeta*cospsi*cospsi*sinlambda*sinlambda + coslambda*coslambda*cospsi*cospsi*sinbeta*sinbeta + sinbeta*sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -cosbeta*cosbeta*coslambda*coslambda*cospsi*cospsi -cosbeta*cosbeta*sinlambda*sinlambda*sinpsi*sinpsi -coslambda*coslambda*sinbeta*sinbeta*sinpsi*sinpsi -cospsi*cospsi*sinbeta*sinbeta*sinlambda*sinlambda + 16*coslambda*cospsi*sinbeta*sinlambda*sinpsi); /**/ coeffn1Hn1plussin[0] = 5./8*sqrt3*cosbeta * (cospsi*cospsi*sinbeta*sinlambda -2*coslambda*cospsi*sinpsi -sinbeta*sinlambda*sinpsi*sinpsi); /**/ coeffn1Hn1plussin[1] = -3./16 * (-3*coslambda*cospsi*cospsi*sinlambda + 3*coslambda*sinlambda*sinpsi*sinpsi + coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi + cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda -4*cospsi*sinbeta*sinlambda*sinlambda*sinpsi -coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda -cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi + 4*coslambda*coslambda*cospsi*sinbeta*sinpsi); /**/ coeffn1Hn1plussin[2] = 1./8*sqrt3*cosbeta * (cospsi*cospsi*sinbeta*sinlambda -2*coslambda*cospsi*sinpsi -sinbeta*sinlambda*sinpsi*sinpsi); /**/ coeffn1Hn1plussin[3] = 1./32 * (-3*coslambda*sinlambda*sinpsi*sinpsi + 3*coslambda*cospsi*cospsi*sinlambda + coslambda*cospsi*cospsi*sinbeta*sinbeta*sinlambda + cosbeta*cosbeta*coslambda*sinlambda*sinpsi*sinpsi -4*coslambda*coslambda*cospsi*sinbeta*sinpsi -coslambda*sinbeta*sinbeta*sinlambda*sinpsi*sinpsi -cosbeta*cosbeta*coslambda*cospsi*cospsi*sinlambda + 4*cospsi*sinbeta*sinlambda*sinlambda*sinpsi); /* Projection coefficients for hcross in n1.H.n1 */ /**/ coeffn1Hn1crossconst = 1./32 * (2*cospsi*sinpsi -27*coslambda*coslambda*cospsi*sinpsi -2*cospsi*sinbeta*sinbeta*sinpsi + 2*cosbeta*cosbeta*cospsi*sinpsi + 27*cospsi*sinlambda*sinlambda*sinpsi -36*coslambda*sinbeta*sinlambda*sinpsi*sinpsi -9*cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi -9*coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 9*cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi + 9*cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 36*coslambda*cospsi*cospsi*sinbeta*sinlambda); /**/ coeffn1Hn1crosscos[0] = -1./8*sqrt3*cosbeta * (cospsi*cospsi*sinlambda -sinlambda*sinpsi*sinpsi -2*coslambda*cospsi*sinbeta*sinpsi); /**/ coeffn1Hn1crosscos[1] = -3./16 * (3*cospsi*sinpsi -3*cospsi*sinbeta*sinbeta*sinpsi -3*cospsi*sinlambda*sinlambda*sinpsi + 3*cosbeta*cosbeta*cospsi*sinpsi + 3*coslambda*coslambda*cospsi*sinpsi + cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi + coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi -4*coslambda*cospsi*cospsi*sinbeta*sinlambda -cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi -cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi + 4*coslambda*sinbeta*sinlambda*sinpsi*sinpsi); /**/ coeffn1Hn1crosscos[2] = 1./8*sqrt3*cosbeta * (cospsi*cospsi*sinlambda -sinlambda*sinpsi*sinpsi -2*coslambda*cospsi*sinbeta*sinpsi); /**/ coeffn1Hn1crosscos[3] = 1./32 * (-3*coslambda*coslambda*cospsi*sinpsi + 3*cospsi*sinlambda*sinlambda*sinpsi + cospsi*sinbeta*sinbeta*sinlambda*sinlambda*sinpsi + cosbeta*cosbeta*coslambda*coslambda*cospsi*sinpsi -4*coslambda*sinbeta*sinlambda*sinpsi*sinpsi -cosbeta*cosbeta*cospsi*sinlambda*sinlambda*sinpsi -coslambda*coslambda*cospsi*sinbeta*sinbeta*sinpsi + 4*coslambda*cospsi*cospsi*sinbeta*sinlambda); /**/ coeffn1Hn1crosssin[0] = -5./8*sqrt3*cosbeta * (coslambda*cospsi*cospsi -coslambda*sinpsi*sinpsi + 2*cospsi*sinbeta*sinlambda*sinpsi); /**/ coeffn1Hn1crosssin[1] = -3./8 * (coslambda*coslambda*cospsi*cospsi*sinbeta + sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -coslambda*coslambda*sinbeta*sinpsi*sinpsi -cospsi*cospsi*sinbeta*sinlambda*sinlambda + 3*coslambda*cospsi*sinlambda*sinpsi + coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi -cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi); /**/ coeffn1Hn1crosssin[2] = -1./8*sqrt3*cosbeta * (coslambda*cospsi*cospsi -coslambda*sinpsi*sinpsi + 2*cospsi*sinbeta*sinlambda*sinpsi); /**/ coeffn1Hn1crosssin[3] = 1./16 * (coslambda*coslambda*sinbeta*sinpsi*sinpsi + cospsi*cospsi*sinbeta*sinlambda*sinlambda -coslambda*coslambda*cospsi*cospsi*sinbeta -sinbeta*sinlambda*sinlambda*sinpsi*sinpsi -3*coslambda*cospsi*sinlambda*sinpsi + cosbeta*cosbeta*coslambda*cospsi*sinlambda*sinpsi -coslambda*cospsi*sinbeta*sinbeta*sinlambda*sinpsi); /* Coefficients in k.n3 */ /**/ coeffkn3const = 3./8*cosbeta * (sinlambda -sqrt3*coslambda); /**/ coeffkn3cos[0] = 3./4 * (-sinbeta); /**/ coeffkn3cos[1] = -1./8*cosbeta * (-sinlambda -sqrt3*coslambda); /**/ coeffkn3sin[0] = -1./4*sqrt3 * (-sinbeta); /**/ coeffkn3sin[1] = 1./8*cosbeta * (-coslambda + sqrt3*sinlambda); /* Coefficients in k.n2 */ /**/ coeffkn2const = -3./8*cosbeta * (-sinlambda -sqrt3*coslambda); /**/ coeffkn2cos[0] = -3./4 * (-sinbeta); /**/ coeffkn2cos[1] = 1./8*cosbeta * (sinlambda -sqrt3*coslambda); /**/ coeffkn2sin[0] = -1./4*sqrt3 * (-sinbeta); /**/ coeffkn2sin[1] = 1./8*cosbeta * (-coslambda -sqrt3*sinlambda); /* Coefficients in k.n1 */ /**/ coeffkn1const = 3./4*cosbeta * (-sinlambda); /**/ coeffkn1cos[0] = 0. ; /**/ coeffkn1cos[1] = 1./4*cosbeta * (-sinlambda); /**/ coeffkn1sin[0] = 1./2*sqrt3 * (-sinbeta); /**/ coeffkn1sin[1] = -1./4*cosbeta * (-coslambda); /* Coefficients in k.(p1+p2) */ /**/ coeffkp1plusp2const = -1./8*cosbeta * (-3*sinlambda -sqrt3*coslambda); /**/ coeffkp1plusp2cos[0] = -1./4 * (-sinbeta); /**/ coeffkp1plusp2cos[1] = 1./24*cosbeta * (3*sinlambda -sqrt3*coslambda); /**/ coeffkp1plusp2sin[0] = -1./4*sqrt3 * (-sinbeta); /**/ coeffkp1plusp2sin[1] = 1./24*cosbeta * (-3*coslambda -sqrt3*sinlambda); /* Coefficients in k.(p2+p3) */ /**/ coeffkp2plusp3const = 1./4*sqrt3*cosbeta * (-coslambda); /**/ coeffkp2plusp3cos[0] = 1./2 * (-sinbeta); /**/ coeffkp2plusp3cos[1] = -1./4/sqrt3 * (-cosbeta*coslambda); /**/ coeffkp2plusp3sin[0] = 0. ; /**/ coeffkp2plusp3sin[1] = -1./4/sqrt3 * (-cosbeta*sinlambda); /* Coefficients in k.(p3+p1) */ /**/ coeffkp3plusp1const = -1./8*cosbeta * (3*sinlambda -sqrt3*coslambda); /**/ coeffkp3plusp1cos[0] = -1./4 * (-sinbeta); /**/ coeffkp3plusp1cos[1] = 1./24*cosbeta * (-3*sinlambda -sqrt3*coslambda); /**/ coeffkp3plusp1sin[0] = 1./4*sqrt3 * (-sinbeta); /**/ coeffkp3plusp1sin[1] = -1./24*cosbeta * (-3*coslambda + sqrt3*sinlambda); /* Coefficients in k.p1 */ /**/ coeffkp1const = -1./4*sqrt3 * (-cosbeta*coslambda); /**/ coeffkp1cos[0] = -1./2 * (-sinbeta); /**/ coeffkp1cos[1] = 1./(4*sqrt3) * (-cosbeta*coslambda); /**/ coeffkp1sin[0] = 0. ; /**/ coeffkp1sin[1] = 1./(4*sqrt3) * (-cosbeta*sinlambda); /* Coefficients in k.p2 */ /**/ coeffkp2const = 1./8*cosbeta * (3*sinlambda -sqrt3*coslambda); /**/ coeffkp2cos[0] = 1./4 * (-sinbeta); /**/ coeffkp2cos[1] = -1./24*cosbeta * (-3*sinlambda -sqrt3*coslambda); /**/ coeffkp2sin[0] = -1./4*sqrt3 * (-sinbeta); /**/ coeffkp2sin[1] = 1./24*cosbeta * (-3*coslambda + sqrt3*sinlambda); /* Coefficients in k.p3 */ /**/ coeffkp3const = 1./8*cosbeta * (-3*sinlambda -sqrt3*coslambda); /**/ coeffkp3cos[0] = 1./4 * (-sinbeta); /**/ coeffkp3cos[1] = -1./24*cosbeta * (3*sinlambda -sqrt3*coslambda); /**/ coeffkp3sin[0] = 1./4*sqrt3 * (-sinbeta); /**/ coeffkp3sin[1] = -1./24*cosbeta * (-3*coslambda -sqrt3*sinlambda); /* Coefficients in k.R */ /**/ coeffkRconst = 0.; coeffkRcos[0] = 1. * (-cosbeta*coslambda); coeffkRsin[0] = 1. * (-cosbeta*sinlambda); coeffkRcos[1] = 0.; coeffkRsin[1] = 0.; } /*********************** Fourier-domain response ************************/ /* Individual functions GABmode: older version, does not include the orbital delay (was treated separately as Bessel phase) */ /* Collective function EvaluateGABmode: orbital delay included */ /* Conventions changed: now MLDC conventions */ /* Function evaluating G21, combining the two polarization with the spherical harmonics factors */ double complex G21mode(const LISAconstellation *variant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross) { double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } double n3Pn3plus = coeffn3Hn3plusconst; double n3Pn3cross = coeffn3Hn3crossconst; for(int j=0; j<4; j++) { n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j]; n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j]; } double kn3 = coeffkn3const; double kp1plusp2 = coeffkp1plusp2const; for(int j=0; j<2; j++) { kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j]; kp1plusp2 += cosarray[j] * coeffkp1plusp2cos[j] + sinarray[j] * coeffkp1plusp2sin[j]; } return I*PI*f*variant->ConstL/C_SI * (n3Pn3plus*Yfactorplus + n3Pn3cross*Yfactorcross) * sinc( PI*f*variant->ConstL/C_SI * (1.+kn3)) * cexp( I*PI*f*variant->ConstL/C_SI * (1.+kp1plusp2) ); } /* Function evaluating G12, combining the two polarization with the spherical harmonics factors */ double complex G12mode(const LISAconstellation *variant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross) { double phase = variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } double n3Pn3plus = coeffn3Hn3plusconst; double n3Pn3cross = coeffn3Hn3crossconst; for(int j=0; j<4; j++) { n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j]; n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j]; } double kn3 = coeffkn3const; double kp1plusp2 = coeffkp1plusp2const; for(int j=0; j<2; j++) { kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j]; kp1plusp2 += cosarray[j] * coeffkp1plusp2cos[j] + sinarray[j] * coeffkp1plusp2sin[j]; } return I*PI*f*variant->ConstL/C_SI * (n3Pn3plus*Yfactorplus + n3Pn3cross*Yfactorcross) * sinc( PI*f*variant->ConstL/C_SI * (1.-kn3)) * cexp( I*PI*f*variant->ConstL/C_SI * (1.+kp1plusp2) ); } /* Function evaluating G32, combining the two polarization with the spherical harmonics factors */ double complex G32mode(const LISAconstellation *variant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross) { double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } double n1Pn1plus = coeffn1Hn1plusconst; double n1Pn1cross = coeffn1Hn1crossconst; for(int j=0; j<4; j++) { n1Pn1plus += cosarray[j] * coeffn1Hn1pluscos[j] + sinarray[j] * coeffn1Hn1plussin[j]; n1Pn1cross += cosarray[j] * coeffn1Hn1crosscos[j] + sinarray[j] * coeffn1Hn1crosssin[j]; } double kn1 = coeffkn1const; double kp2plusp3 = coeffkp2plusp3const; for(int j=0; j<2; j++) { kn1 += cosarray[j] * coeffkn1cos[j] + sinarray[j] * coeffkn1sin[j]; kp2plusp3 += cosarray[j] * coeffkp2plusp3cos[j] + sinarray[j] * coeffkp2plusp3sin[j]; } return I*PI*f*variant->ConstL/C_SI * (n1Pn1plus*Yfactorplus + n1Pn1cross*Yfactorcross) * sinc( PI*f*variant->ConstL/C_SI * (1.+kn1)) * cexp( I*PI*f*variant->ConstL/C_SI * (1.+kp2plusp3) ); } /* Function evaluating G23, combining the two polarization with the spherical harmonics factors */ double complex G23mode(const LISAconstellation *variant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross) { double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1)* phase); sinarray[j] = sin((j+1)* phase); } double n1Pn1plus = coeffn1Hn1plusconst; double n1Pn1cross = coeffn1Hn1crossconst; for(int j=0; j<4; j++) { n1Pn1plus += cosarray[j] * coeffn1Hn1pluscos[j] + sinarray[j] * coeffn1Hn1plussin[j]; n1Pn1cross += cosarray[j] * coeffn1Hn1crosscos[j] + sinarray[j] * coeffn1Hn1crosssin[j]; } double kn1 = coeffkn1const; double kp2plusp3 = coeffkp2plusp3const; for(int j=0; j<2; j++) { kn1 += cosarray[j] * coeffkn1cos[j] + sinarray[j] * coeffkn1sin[j]; kp2plusp3 += cosarray[j] * coeffkp2plusp3cos[j] + sinarray[j] * coeffkp2plusp3sin[j]; } return I*PI*f*variant->ConstL/C_SI * (n1Pn1plus*Yfactorplus + n1Pn1cross*Yfactorcross) * sinc( PI*f*variant->ConstL/C_SI * (1.-kn1)) * cexp( I*PI*f*variant->ConstL/C_SI * (1.+kp2plusp3) ); } /* Function evaluating G13, combining the two polarization with the spherical harmonics factors */ double complex G13mode(const LISAconstellation *variant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross) { double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } double n2Pn2plus = coeffn2Hn2plusconst; double n2Pn2cross = coeffn2Hn2crossconst; for(int j=0; j<4; j++) { n2Pn2plus += cosarray[j] * coeffn2Hn2pluscos[j] + sinarray[j] * coeffn2Hn2plussin[j]; n2Pn2cross += cosarray[j] * coeffn2Hn2crosscos[j] + sinarray[j] * coeffn2Hn2crosssin[j]; } double kn2 = coeffkn2const; double kp3plusp1 = coeffkp3plusp1const; for(int j=0; j<2; j++) { kn2 += cosarray[j] * coeffkn2cos[j] + sinarray[j] * coeffkn2sin[j]; kp3plusp1 += cosarray[j] * coeffkp3plusp1cos[j] + sinarray[j] * coeffkp3plusp1sin[j]; } return I*PI*f*variant->ConstL/C_SI * (n2Pn2plus*Yfactorplus + n2Pn2cross*Yfactorcross) * sinc( PI*f*variant->ConstL/C_SI * (1.+kn2)) * cexp( I*PI*f*variant->ConstL/C_SI * (1.+kp3plusp1) ); } /* Function evaluating G31, combining the two polarization with the spherical harmonics factors */ double complex G31mode(const LISAconstellation *variant, const double f, const double t, const double complex Yfactorplus, const double complex Yfactorcross) { double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } double n2Pn2plus = coeffn2Hn2plusconst; double n2Pn2cross = coeffn2Hn2crossconst; for(int j=0; j<4; j++) { n2Pn2plus += cosarray[j] * coeffn2Hn2pluscos[j] + sinarray[j] * coeffn2Hn2plussin[j]; n2Pn2cross += cosarray[j] * coeffn2Hn2crosscos[j] + sinarray[j] * coeffn2Hn2crosssin[j]; } double kn2 = coeffkn2const; double kp3plusp1 = coeffkp3plusp1const; for(int j=0; j<2; j++) { kn2 += cosarray[j] * coeffkn2cos[j] + sinarray[j] * coeffkn2sin[j]; kp3plusp1 += cosarray[j] * coeffkp3plusp1cos[j] + sinarray[j] * coeffkp3plusp1sin[j]; } return I*PI*f*variant->ConstL/C_SI * (n2Pn2plus*Yfactorplus + n2Pn2cross*Yfactorcross) * sinc( PI*f*variant->ConstL/C_SI * (1.-kn2)) * cexp( I*PI*f*variant->ConstL/C_SI * (1.+kp3plusp1) ); } /* Function evaluating all coefficients G12, G21, G23, G32, G31, G13, combining the two polarization with the spherical harmonics factors */ /* Note: includes orbital delay */ int EvaluateGABmode( const LISAconstellation *variant, /* Description of LISA variant */ double complex* G12, /* Output for G12 */ double complex* G21, /* Output for G21 */ double complex* G23, /* Output for G23 */ double complex* G32, /* Output for G32 */ double complex* G31, /* Output for G31 */ double complex* G13, /* Output for G13 */ const double f, /* Frequency */ const double t, /* Time */ const double complex Yfactorplus, /* Spin-weighted spherical harmonic factor for plus */ const double complex Yfactorcross, /* Spin-weighted spherical harmonic factor for cross */ const int tagdelayR, /* Tag: when 1, include the phase term of the R-delay */ const ResponseApproxtag responseapprox) /* Tag to select possible low-f approximation level in FD response */ { double phase = variant->ConstOmega*t + variant->ConstPhi0; /* Precompute array of sine/cosine */ for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } /* Scalar products with k */ double n1Pn1plus = coeffn1Hn1plusconst; double n1Pn1cross = coeffn1Hn1crossconst; double n2Pn2plus = coeffn2Hn2plusconst; double n2Pn2cross = coeffn2Hn2crossconst; double n3Pn3plus = coeffn3Hn3plusconst; double n3Pn3cross = coeffn3Hn3crossconst; for(int j=0; j<4; j++) { n1Pn1plus += cosarray[j] * coeffn1Hn1pluscos[j] + sinarray[j] * coeffn1Hn1plussin[j]; n1Pn1cross += cosarray[j] * coeffn1Hn1crosscos[j] + sinarray[j] * coeffn1Hn1crosssin[j]; n2Pn2plus += cosarray[j] * coeffn2Hn2pluscos[j] + sinarray[j] * coeffn2Hn2plussin[j]; n2Pn2cross += cosarray[j] * coeffn2Hn2crosscos[j] + sinarray[j] * coeffn2Hn2crosssin[j]; n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j]; n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j]; } /* Scalar products with k */ double kn1 = coeffkn1const; double kn2 = coeffkn2const; double kn3 = coeffkn3const; double kp1plusp2 = coeffkp1plusp2const; double kp2plusp3 = coeffkp2plusp3const; double kp3plusp1 = coeffkp3plusp1const; double kR = coeffkRconst; for(int j=0; j<2; j++) { kn1 += cosarray[j] * coeffkn1cos[j] + sinarray[j] * coeffkn1sin[j]; kn2 += cosarray[j] * coeffkn2cos[j] + sinarray[j] * coeffkn2sin[j]; kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j]; kp1plusp2 += cosarray[j] * coeffkp1plusp2cos[j] + sinarray[j] * coeffkp1plusp2sin[j]; kp2plusp3 += cosarray[j] * coeffkp2plusp3cos[j] + sinarray[j] * coeffkp2plusp3sin[j]; kp3plusp1 += cosarray[j] * coeffkp3plusp1cos[j] + sinarray[j] * coeffkp3plusp1sin[j]; kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j]; } /* Common factors */ double complex factn1Pn1 = n1Pn1plus*Yfactorplus + n1Pn1cross*Yfactorcross; double complex factn2Pn2 = n2Pn2plus*Yfactorplus + n2Pn2cross*Yfactorcross; double complex factn3Pn3 = n3Pn3plus*Yfactorplus + n3Pn3cross*Yfactorcross; double prefactor = PI*f*variant->ConstL/C_SI; double prefactorR = 2*PI*f*variant->OrbitR/C_SI; double complex factorcexp12 = cexp(I*prefactor * (1.+kp1plusp2)); double complex factorcexp23 = cexp(I*prefactor * (1.+kp2plusp3)); double complex factorcexp31 = cexp(I*prefactor * (1.+kp3plusp1)); double factorsinc12 = sinc( prefactor * (1.-kn3)); double factorsinc21 = sinc( prefactor * (1.+kn3)); double factorsinc23 = sinc( prefactor * (1.-kn1)); double factorsinc32 = sinc( prefactor * (1.+kn1)); double factorsinc31 = sinc( prefactor * (1.-kn2)); double factorsinc13 = sinc( prefactor * (1.+kn2)); /* The tag tagdelayR allows to choose to include or not the R-delay phase term (here leading order) */ double complex factorcexpkR; if(tagdelayR) factorcexpkR = cexp(I*prefactorR * kR); else factorcexpkR = 1.; /* Take into account level of approximation in for low-f response - choices are full, lowfL or lowf */ if(responseapprox==lowf) { factorcexpkR = 1.; } if((responseapprox==lowfL)||(responseapprox==lowf)) { factorsinc12 = 1.; factorsinc21 = 1.; factorsinc23 = 1.; factorsinc32 = 1.; factorsinc31 = 1.; factorsinc13 = 1.; factorcexp12 = 1.; factorcexp23 = 1.; factorcexp31 = 1.; } /* Output result */ *G12 = I*prefactor * factorcexpkR * factn3Pn3 * factorsinc12 * factorcexp12; *G21 = I*prefactor * factorcexpkR * factn3Pn3 * factorsinc21 * factorcexp12; *G23 = I*prefactor * factorcexpkR * factn1Pn1 * factorsinc23 * factorcexp23; *G32 = I*prefactor * factorcexpkR * factn1Pn1 * factorsinc32 * factorcexp23; *G31 = I*prefactor * factorcexpkR * factn2Pn2 * factorsinc31 * factorcexp31; *G13 = I*prefactor * factorcexpkR * factn2Pn2 * factorsinc13 * factorcexp31; return SUCCESS; } /*********************** Fourier-domain TDI factors ************************/ /* Functions evaluating the Fourier-domain factors (combinations of the GAB's) for TDI observables */ /* NOTE: factors have been scaled out, in parallel of what is done for the noise function */ /* Note: in case only one channel is considered, amplitudes for channels 2 and 3 are simply set to 0 */ /* (allows minimal changes from the old structure that assumed KTV A,E,T - but probably not optimal) */ int EvaluateTDIfactor3Chan( const LISAconstellation *variant, /* Description of LISA variant */ double complex* factor1, /* Output for factor for TDI channel 1 */ double complex* factor2, /* Output for factor for TDI channel 2 */ double complex* factor3, /* Output for factor for TDI channel 3 */ const double complex G12, /* Input for G12 */ const double complex G21, /* Input for G21 */ const double complex G23, /* Input for G23 */ const double complex G32, /* Input for G32 */ const double complex G31, /* Input for G31 */ const double complex G13, /* Input for G13 */ const double f, /* Frequency */ const TDItag tditag, /* Selector for the TDI observables */ const ResponseApproxtag responseapprox) /* Tag to select possible low-f approximation level in FD response */ { /* Notation: x=pifL, z=e^2ix*/ double x = PI*f*variant->ConstL/C_SI; double complex z = cexp(2*I*x); /* In both lowf and lowf-L approximations, ignore z factors - consitently ignore all TDI delays */ if((responseapprox==lowf)||(responseapprox==lowfL)) { x = 0.; z = 1.; } switch(tditag) { /* For testing purposes: basic yAB observable - no factor */ case y12: *factor1 = G12; *factor2 = 0.; *factor3 = 0.; break; /* For testing purposes: basic yABL observable - no factor, same as for yAB */ case y12L: *factor1 = G12; *factor2 = 0.; *factor3 = 0.; break; /* First-generation rescaled TDI aet from X,Y,Z */ /* With x=pifL, factors scaled out: A,E I*sqrt2*sin2x*e2ix - T 2*sqrt2*sin2x*sinx*e3ix */ case TDIAETXYZ: *factor1 = 0.5 * ( (1.+z)*(G31+G13) - G23 - z*G32 - G21 - z*G12 ); *factor2 = 0.5*invsqrt3 * ( (1.-z)*(G13-G31) + (2.+z)*(G12-G32) + (1.+2*z)*(G21-G23) ); *factor3 = invsqrt6 * ( G21-G12 + G32-G23 + G13-G31); break; /* First-generation rescaled TDI aet from alpha, beta, gamma */ /* With x=pifL, factors scaled out: A,E -I*2sqrt2*sinx*eix - T sinx/(sin3x*eix) */ case TDIAETalphabetagamma: *factor1 = 0.5 * (G13+G31 + z*(G12+G32) - (1.+z)*(G21+G13)); *factor2 = 0.5*invsqrt3 * ((2.+z)*(G12-G32) + (1.+z)*(G21-G23) + (1.+2*z)*(G13-G31)); *factor3 = invsqrt3 * (G21-G12 + G32-G23 + G13-G31); break; /* First-generation TDI XYZ */ /* With x=pifL, factor scaled out: 2I*sin2x*e2ix */ case TDIXYZ: *factor1 = G21 + z*G12 - G31 - z*G13; *factor2 = G32 + z*G23 - G12 - z*G21; *factor3 = G13 + z*G31 - G23 - z*G32; break; /* First-generation TDI alpha beta gamma */ case TDIalphabetagamma: *factor1 = G21-G31 + z*(G13-G12) + z*z*(G32-G23); *factor2 = G32-G12 + z*(G21-G23) + z*z*(G13-G31); *factor3 = G13-G23 + z*(G32-G31) + z*z*(G21-G12); break; /* First-generation TDI XYZ */ case TDIX: *factor1 = G21 + z*G12 - G31 - z*G13; *factor2 = 0.; *factor3 = 0.; break; /* First-generation TDI alpha beta gamma */ case TDIalpha: *factor1 = G21-G31 + z*(G13-G12) + z*z*(G32-G23); *factor2 = 0.; *factor3 = 0.; break; /* First-generation rescaled TDI aet from X,Y,Z */ /* With x=pifL, factors scaled out: A,E I*sqrt2*sin2x*eix - T 2*sqrt2*sin2x*sinx*e2ix */ case TDIAXYZ: *factor1 = 0.5 * ( (1.+z)*(G31+G13) - G23 - z*G32 - G21 - z*G12 ); *factor2 = 0.; *factor3 = 0.; break; case TDIEXYZ: *factor1 = 0.5*invsqrt3 * ( (1.-z)*(G13-G31) + (2.+z)*(G12-G32) + (1.+2*z)*(G12-G23) ); *factor2 = 0.; *factor3 = 0.; break; case TDITXYZ: *factor1 = invsqrt6 * ( G21-G12 + G32-G23 + G13-G31); *factor2 = 0.; *factor3 = 0.; break; /* First-generation rescaled TDI aet from alpha, beta, gamma */ /* With x=pifL, factors scaled out: A,E -I*2sqrt2*sinx*eix - T sinx/(sin3x*eix) */ case TDIAalphabetagamma: *factor1 = 0.5 * (G13+G31 + z*(G12+G32) - (1.+z)*(G21+G13)); *factor2 = 0.; *factor3 = 0.; break; case TDIEalphabetagamma: *factor1 = 0.5*invsqrt3 * ((2.+z)*(G12-G32) + (1.+z)*(G21-G23) + (1.+2*z)*(G13-G31)); *factor2 = 0.; *factor3 = 0.; break; case TDITalphabetagamma: *factor1 = invsqrt3 * (G21-G12 + G32-G23 + G13-G31); *factor2 = 0.; *factor3 = 0.; break; default: printf("Error in EvaluateTDIfactor3Chan: tditag not recognized.\n"); exit(1); } return SUCCESS; } /* Function evaluating the Fourier-domain factors that have been scaled out of TDI observables */ /* The factors scaled out, parallel what is done for the noise functions */ /* Note: in case only one channel is considered, factors for channels 2 and 3 are simply set to 0 */ int ScaledTDIfactor3Chan( const LISAconstellation *variant, /* Description of LISA variant */ double complex* factor1, /* Output for factor for TDI factor 1 */ double complex* factor2, /* Output for factor for TDI factor 2 */ double complex* factor3, /* Output for factor for TDI factor 3 */ const double f, /* Frequency */ const TDItag tditag) /* Selector for the TDI observables */ { /* Notation: x=pifL */ double x = PI*f*variant->ConstL/C_SI; switch(tditag) { /* First-generation rescaled TDI aet from X,Y,Z */ case TDIAETXYZ: *factor1 = I*sqrt(2)*sin(2*x)*cexp(2*I*x); *factor2 = I*sqrt(2)*sin(2*x)*cexp(2*I*x); *factor3 = 2*sqrt(2)*sin(x)*sin(2*x)*cexp(3*I*x); break; /* First-generation rescaled TDI aet from alpha, beta, gamma */ case TDIAETalphabetagamma: *factor1 = -I*2*sqrt(2)*sin(x)*cexp(I*x); *factor2 = -I*2*sqrt(2)*sin(x)*cexp(I*x); *factor3 = sin(3*x)/sin(x)*cexp(I*x); break; /* First-generation TDI XYZ */ case TDIXYZ: *factor1 = 2*I*sin(2*x)*cexp(2*I*x); *factor2 = 2*I*sin(2*x)*cexp(2*I*x); *factor3 = 2*I*sin(2*x)*cexp(2*I*x); break; /* First-generation TDI alpha beta gamma */ case TDIalphabetagamma: *factor1 = 1.; *factor2 = 1.; *factor3 = 1.; break; /* First-generation TDI XYZ */ case TDIX: *factor1 = 2*I*sin(2*x)*cexp(2*I*x); *factor2 = 0.; *factor3 = 0.; break; /* First-generation TDI alpha beta gamma */ case TDIalpha: *factor1 = 1.; *factor2 = 0.; *factor3 = 0.; break; /* First-generation rescaled TDI aet from X,Y,Z */ /* With x=pifL, factors scaled out: A,E I*sqrt2*sin2x*eix - T 2*sqrt2*sin2x*sinx*e2ix */ case TDIAXYZ: *factor1 = I*sqrt(2)*sin(2*x)*cexp(2*I*x); *factor2 = 0.; *factor3 = 0.; break; case TDIEXYZ: *factor1 = I*sqrt(2)*sin(2*x)*cexp(2*I*x); *factor2 = 0.; *factor3 = 0.; break; case TDITXYZ: *factor1 = 2*sqrt(2)*sin(x)*sin(2*x)*cexp(3*I*x); *factor2 = 0.; *factor3 = 0.; break; /* First-generation rescaled TDI aet from alpha, beta, gamma */ /* With x=pifL, factors scaled out: A,E -I*2sqrt2*sinx*eix - T sinx/(sin3x*eix) */ case TDIAalphabetagamma: *factor1 = -I*2*sqrt(2)*sin(x)*cexp(I*x); *factor2 = 0.; *factor3 = 0.; break; case TDIEalphabetagamma: *factor1 = -I*2*sqrt(2)*sin(x)*cexp(I*x); *factor2 = 0.; *factor3 = 0.; break; case TDITalphabetagamma: *factor1 = sin(3*x)/sin(x)*cexp(I*x); *factor2 = 0.; *factor3 = 0.; break; default: printf("Error in EvaluateTDIfactor3Chan: tditag not recognized.\n"); exit(1); } return SUCCESS; } /* Function restoring the factor that have been scaled out of the TDI observables */ /* NOTE: the operation is made in-place, and the input is overwritten */ int RestoreInPlaceScaledFactorTDI( const LISAconstellation *variant, /* Description of LISA variant */ ListmodesCAmpPhaseFrequencySeries* listtdi, /* Output/Input: list of mode contributions to TDI observable */ TDItag tditag, /* Tag selecting the TDI observable */ int nchannel) /* TDI channel number */ { double complex factor1 = 0; double complex factor2 = 0; double complex factor3 = 0; double complex factor; double complex camp; ListmodesCAmpPhaseFrequencySeries* listelement = listtdi; /* Going throug the list of modes */ while(listelement) { gsl_vector* freq = listelement->freqseries->freq; gsl_vector* ampreal = listelement->freqseries->amp_real; gsl_vector* ampimag = listelement->freqseries->amp_imag; for(int i=0; i<freq->size; i++) { ScaledTDIfactor3Chan(variant,&factor1, &factor2, &factor3, gsl_vector_get(freq, i), tditag); switch(nchannel) { case 1: factor = factor1; break; case 2: factor = factor2; break; case 3: factor = factor3; break; } camp = factor * (gsl_vector_get(ampreal, i) + I*gsl_vector_get(ampimag, i)); gsl_vector_set(ampreal, i, creal(camp)); gsl_vector_set(ampimag, i, cimag(camp)); } listelement = listelement->next; } return SUCCESS; } /* Functions evaluating the Fourier-domain factors (combinations of the GAB's) for TDI observables */ /* int EvaluateTDIfactor1Chan( */ /* double complex* factor, /\* Output for factor for TDI channel *\/ */ /* const double complex G12, /\* Input for G12 *\/ */ /* const double complex G21, /\* Input for G21 *\/ */ /* const double complex G23, /\* Input for G23 *\/ */ /* const double complex G32, /\* Input for G32 *\/ */ /* const double complex G31, /\* Input for G31 *\/ */ /* const double complex G13, /\* Input for G13 *\/ */ /* const double f, /\* Frequency *\/ */ /* const TDItag tditag) /\* Selector for the TDI observables *\/ */ /* { */ /* /\* Notation: x=pifL, z = e^2ix*\/ */ /* double x = PI*f*variant->ConstL/C_SI; */ /* double complex z = cexp(2*I*x); */ /* double sin2x = sin(2*x); */ /* double complex commonfac; */ /* switch(tditag) { */ /* /\* First-generation TDI XYZ *\/ */ /* case TDIX: { */ /* commonfac = 2*I*z*sin2x; */ /* *factor = commonfac * (G21 + z*G12 - G31 - z*G13); } */ /* case TDIY: { */ /* commonfac = 2*I*z*sin2x; */ /* *factor = commonfac * (G32 + z*G23 - G12 - z*G21); } */ /* case TDIZ: { */ /* commonfac = 2*I*z*sin2x; */ /* *factor = commonfac * (G13 + z*G31 - G23 - z*G32); } */ /* /\* First-generation TDI alpha beta gamma *\/ */ /* case TDIalpha: { */ /* *factor = G21-G31 + z*(G13-G12) + z*z*(G32-G23); } */ /* case TDIbeta: { */ /* *factor = G32-G12 + z*(G21-G23) + z*z*(G13-G31); } */ /* case TDIgamma: { */ /* *factor = G13-G23 + z*(G32-G31) + z*z*(G21-G12); } */ /* /\* First-generation rescaled TDI aet from X,Y,Z *\/ */ /* /\* With x=pifL, factors scaled out: A,E I*sqrt2*sin2x*eix - T 2*sqrt2*sin2x*sinx*e2ix *\/ */ /* case TDIAXYZ: { */ /* *factor = 0.5 * ( (1.+z)*(G31+G13) - G23 - z*G32 - G21 - z*G12 ); } */ /* case TDIEXYZ: { */ /* *factor = 0.5*invsqrt3 * ( (1.-z)*(G13-G31) + (2.+z)*(G12-G32) + (1.+2*z)*(G12-G23) ); } */ /* case TDITXYZ: { */ /* *factor = invsqrt6 * ( G21-G12 + G32-G23 + G13-G31); } */ /* /\* First-generation rescaled TDI aet from alpha, beta, gamma *\/ */ /* /\* With x=pifL, factors scaled out: A,E -I*2sqrt2*sinx*eix - T sinx/(sin3x*eix) *\/ */ /* case TDIAalphabetagamma: { */ /* *factor = 0.5 * (G13+G31 + z*(G12+G32) - (1.+z)*(G21+G13)); } */ /* case TDIEalphabetagamma: { */ /* *factor = 0.5*invsqrt3 * ((2+z)*(G12-G32) + (1+z)*(G21-G23) + (1.+2*z)*(G13-G31)); } */ /* case TDITalphabetagamma: { */ /* *factor = invsqrt3 * (G21-G12 + G32-G23 + G13-G31); } */ /* default: { */ /* printf("Error in EvaluateTDIfactor3Chan: tditag not recognized."); */ /* exit(1); } */ /* } */ /* } */ /*********************** Time-domain response ************************/ /* Processing single mode in amp/phase form through orbital time delay */ static double hOTDAmpPhase( const LISAconstellation *variant, /* Description of LISA variant */ double* amp, /* Output: amplitude */ double* phase, /* Output: phase */ gsl_spline* splineamp, /* Input spline for TD mode amplitude */ gsl_spline* splinephase, /* Input spline for TD mode phase */ gsl_interp_accel* accelamp, /* Accelerator for amp spline */ gsl_interp_accel* accelphase, /* Accelerator for phase spline */ const double t) /* Time */ { double tphase=variant->ConstOmega*t + variant->ConstPhi0; /* Precompute array of sine/cosine */ for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * tphase); sinarray[j] = sin((j+1) * tphase); } /* Scalar product k.R */ double kR = coeffkRconst; for(int j=0; j<2; j++) { kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j]; } /* Common factor and delay */ double delay = -(kR*variant->OrbitR)/C_SI; /* Output result */ *amp = gsl_spline_eval(splineamp, t+delay, accelamp); *phase = gsl_spline_eval(splinephase, t+delay, accelphase); } /* Functions evaluating yAB observables in time domain - constellation response only */ /* Note: includes both h22 and h2m2 contributions, assuming planar orbits so that h2-2 = h22* */ static double y12LTDfromh22AmpPhase( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splineamp, /* Input spline for h22 TD amp */ gsl_spline* splinephase, /* Input spline for h22 TD phase */ gsl_interp_accel* accelamp, /* Accelerator for amp spline */ gsl_interp_accel* accelphase, /* Accelerator for phase spline */ double complex Y22, /* Y22 factor needed to convert h22 to hplus, hcross */ double complex Y2m2, /* Y2-2 factor needed to convert h2-2 to hplus, hcross */ const double t) /* Time */ { /* Precompute array of sine/cosine */ double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } /* Scalar products with k */ double n3Pn3plus = coeffn3Hn3plusconst; double n3Pn3cross = coeffn3Hn3crossconst; for(int j=0; j<4; j++) { n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j]; n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j]; } /* Scalar products with k */ double kn3 = coeffkn3const; double kp1 = coeffkp1const; double kp2 = coeffkp2const; for(int j=0; j<2; j++) { kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j]; kp1 += cosarray[j] * coeffkp1cos[j] + sinarray[j] * coeffkp1sin[j]; kp2 += cosarray[j] * coeffkp2cos[j] + sinarray[j] * coeffkp2sin[j]; } /* Common factor and delay */ double factorp = (1./(1.-kn3)) * 0.5*n3Pn3plus; double factorc = (1./(1.-kn3)) * 0.5*n3Pn3cross; double firstdelay = -((kp1 + 1)*variant->ConstL)/C_SI; double seconddelay = -(kp2*variant->ConstL)/C_SI; /* Values of Y22*h22 + Y2-2*h2-2 at 1 and 2 with delays, and hplus, hcross */ /* Note: includes both h22 and h2m2 contributions, assuming planar orbits so that h2-2 = h22* */ double A22at1 = gsl_spline_eval(splineamp, t+firstdelay, accelamp); double phi22at1 = gsl_spline_eval(splinephase, t+firstdelay, accelphase); double A22at2 = gsl_spline_eval(splineamp, t+seconddelay, accelamp); double phi22at2 = gsl_spline_eval(splinephase, t+seconddelay, accelphase); double complex Y22h22at1 = Y22 * A22at1 * cexp(I*phi22at1); double complex Y22h22at2 = Y22 * A22at2 * cexp(I*phi22at2); double complex Y2m2h2m2at1 = Y2m2 * A22at1 * cexp(-I*phi22at1); double complex Y2m2h2m2at2 = Y2m2 * A22at2 * cexp(-I*phi22at2); double hp1 = creal(Y22h22at1 + Y2m2h2m2at1); double hc1 = -cimag(Y22h22at1 + Y2m2h2m2at1); double hp2 = creal(Y22h22at2 + Y2m2h2m2at2); double hc2 = -cimag(Y22h22at2 + Y2m2h2m2at2); /* Result */ double y12 = factorp*(hp1 - hp2) + factorc*(hc1 - hc2); return y12; } /* Functions evaluating yAB observables in time domain - orbital and constellation response */ /* Note: includes both h22 and h2m2 contributions, assuming planar orbits so that h2-2 = h22* */ static double y12TDfromh22AmpPhase( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splineamp, /* Input spline for h22 TD amp */ gsl_spline* splinephase, /* Input spline for h22 TD phase */ gsl_interp_accel* accelamp, /* Accelerator for amp spline */ gsl_interp_accel* accelphase, /* Accelerator for phase spline */ double complex Y22, /* Y22 factor needed to convert h22 to hplus, hcross */ double complex Y2m2, /* Y2-2 factor needed to convert h2-2 to hplus, hcross */ const double t) /* Time */ { /* Precompute array of sine/cosine */ double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } /* Scalar product k.R */ double kR = coeffkRconst; for(int j=0; j<2; j++) { kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j]; } /* Common factor and delay */ double delay0 = -(kR*variant->OrbitR)/C_SI; /* Scalar products with k */ double n3Pn3plus = coeffn3Hn3plusconst; double n3Pn3cross = coeffn3Hn3crossconst; for(int j=0; j<4; j++) { n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j]; n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j]; } /* Scalar products with k */ double kn3 = coeffkn3const; double kp1 = coeffkp1const; double kp2 = coeffkp2const; for(int j=0; j<2; j++) { kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j]; kp1 += cosarray[j] * coeffkp1cos[j] + sinarray[j] * coeffkp1sin[j]; kp2 += cosarray[j] * coeffkp2cos[j] + sinarray[j] * coeffkp2sin[j]; } /* Common factor and delay */ double factorp = (1./(1.-kn3)) * 0.5*n3Pn3plus; double factorc = (1./(1.-kn3)) * 0.5*n3Pn3cross; double firstdelay = delay0 - ((kp1 + 1)*variant->ConstL)/C_SI; double seconddelay = delay0 - (kp2*variant->ConstL)/C_SI; /* Values of Y22*h22 + Y2-2*h2-2 at 1 and 2 with delays, and hplus, hcross */ /* Note: includes both h22 and h2m2 contributions, assuming planar orbits so that h2-2 = h22* */ double A22at1 = gsl_spline_eval(splineamp, t+firstdelay, accelamp); double phi22at1 = gsl_spline_eval(splinephase, t+firstdelay, accelphase); double A22at2 = gsl_spline_eval(splineamp, t+seconddelay, accelamp); double phi22at2 = gsl_spline_eval(splinephase, t+seconddelay, accelphase); double complex Y22h22at1 = Y22 * A22at1 * cexp(I*phi22at1); double complex Y22h22at2 = Y22 * A22at2 * cexp(I*phi22at2); double complex Y2m2h2m2at1 = Y2m2 * A22at1 * cexp(-I*phi22at1); double complex Y2m2h2m2at2 = Y2m2 * A22at2 * cexp(-I*phi22at2); double hp1 = creal(Y22h22at1 + Y2m2h2m2at1); double hc1 = -cimag(Y22h22at1 + Y2m2h2m2at1); double hp2 = creal(Y22h22at2 + Y2m2h2m2at2); double hc2 = -cimag(Y22h22at2 + Y2m2h2m2at2); /* Result */ double y12 = factorp*(hp1 - hp2) + factorc*(hc1 - hc2); return y12; } /* Functions evaluating yAB observables in time domain */ double y12TD( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t) /* Time */ { /* Precompute array of sine/cosine */ double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } /* Scalar products with k */ double n3Pn3plus = coeffn3Hn3plusconst; double n3Pn3cross = coeffn3Hn3crossconst; for(int j=0; j<4; j++) { n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j]; n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j]; } /* Scalar products with k */ double kn3 = coeffkn3const; double kp1 = coeffkp1const; double kp2 = coeffkp2const; double kR = coeffkRconst; for(int j=0; j<2; j++) { kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j]; kp1 += cosarray[j] * coeffkp1cos[j] + sinarray[j] * coeffkp1sin[j]; kp2 += cosarray[j] * coeffkp2cos[j] + sinarray[j] * coeffkp2sin[j]; kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j]; } /* Common factor and delay */ double factorp = (1./(1.-kn3)) * 0.5*n3Pn3plus; double factorc = (1./(1.-kn3)) * 0.5*n3Pn3cross; double firstdelay = -(kR*variant->OrbitR + (kp1 + 1)*variant->ConstL)/C_SI; double seconddelay = -(kR*variant->OrbitR + kp2*variant->ConstL)/C_SI; /* Result */ double y12 = factorp*(gsl_spline_eval(splinehp, t+firstdelay, accelhp) - gsl_spline_eval(splinehp, t+seconddelay, accelhp)) + factorc*(gsl_spline_eval(splinehc, t+firstdelay, accelhc) - gsl_spline_eval(splinehc, t+seconddelay, accelhc)); return y12; } double y21TD( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t) /* Time */ { /* Precompute array of sine/cosine */ double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } /* Scalar products with k */ double n3Pn3plus = coeffn3Hn3plusconst; double n3Pn3cross = coeffn3Hn3crossconst; for(int j=0; j<4; j++) { n3Pn3plus += cosarray[j] * coeffn3Hn3pluscos[j] + sinarray[j] * coeffn3Hn3plussin[j]; n3Pn3cross += cosarray[j] * coeffn3Hn3crosscos[j] + sinarray[j] * coeffn3Hn3crosssin[j]; } /* Scalar products with k */ double kn3 = coeffkn3const; double kp1 = coeffkp1const; double kp2 = coeffkp2const; double kR = coeffkRconst; for(int j=0; j<2; j++) { kn3 += cosarray[j] * coeffkn3cos[j] + sinarray[j] * coeffkn3sin[j]; kp1 += cosarray[j] * coeffkp1cos[j] + sinarray[j] * coeffkp1sin[j]; kp2 += cosarray[j] * coeffkp2cos[j] + sinarray[j] * coeffkp2sin[j]; kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j]; } /* Common factor and delay */ double factorp = (1./(1.+kn3)) * 0.5*n3Pn3plus; double factorc = (1./(1.+kn3)) * 0.5*n3Pn3cross; double firstdelay = -(kR*variant->OrbitR + (kp2 + 1)*variant->ConstL)/C_SI; double seconddelay = -(kR*variant->OrbitR + kp1*variant->ConstL)/C_SI; /* Result */ double y21 = factorp*(gsl_spline_eval(splinehp, t+firstdelay, accelhp) - gsl_spline_eval(splinehp, t+seconddelay, accelhp)) + factorc*(gsl_spline_eval(splinehc, t+firstdelay, accelhc) - gsl_spline_eval(splinehc, t+seconddelay, accelhc)); return y21; } double y23TD( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t) /* Time */ { /* Precompute array of sine/cosine */ double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } /* Scalar products with k */ double n1Pn1plus = coeffn1Hn1plusconst; double n1Pn1cross = coeffn1Hn1crossconst; for(int j=0; j<4; j++) { n1Pn1plus += cosarray[j] * coeffn1Hn1pluscos[j] + sinarray[j] * coeffn1Hn1plussin[j]; n1Pn1cross += cosarray[j] * coeffn1Hn1crosscos[j] + sinarray[j] * coeffn1Hn1crosssin[j]; } /* Scalar products with k */ double kn1 = coeffkn1const; double kp2 = coeffkp2const; double kp3 = coeffkp3const; double kR = coeffkRconst; for(int j=0; j<2; j++) { kn1 += cosarray[j] * coeffkn1cos[j] + sinarray[j] * coeffkn1sin[j]; kp2 += cosarray[j] * coeffkp2cos[j] + sinarray[j] * coeffkp2sin[j]; kp3 += cosarray[j] * coeffkp3cos[j] + sinarray[j] * coeffkp3sin[j]; kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j]; } /* Common factor and delay */ double factorp = (1./(1.-kn1)) * 0.5*n1Pn1plus; double factorc = (1./(1.-kn1)) * 0.5*n1Pn1cross; double firstdelay = -(kR*variant->OrbitR + (kp2 + 1)*variant->ConstL)/C_SI; double seconddelay = -(kR*variant->OrbitR + kp3*variant->ConstL)/C_SI; /* Result */ double y23 = factorp*(gsl_spline_eval(splinehp, t+firstdelay, accelhp) - gsl_spline_eval(splinehp, t+seconddelay, accelhp)) + factorc*(gsl_spline_eval(splinehc, t+firstdelay, accelhc) - gsl_spline_eval(splinehc, t+seconddelay, accelhc)); return y23; } double y32TD( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t) /* Time */ { /* Precompute array of sine/cosine */ double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } /* Scalar products with k */ double n1Pn1plus = coeffn1Hn1plusconst; double n1Pn1cross = coeffn1Hn1crossconst; for(int j=0; j<4; j++) { n1Pn1plus += cosarray[j] * coeffn1Hn1pluscos[j] + sinarray[j] * coeffn1Hn1plussin[j]; n1Pn1cross += cosarray[j] * coeffn1Hn1crosscos[j] + sinarray[j] * coeffn1Hn1crosssin[j]; } /* Scalar products with k */ double kn1 = coeffkn1const; double kp2 = coeffkp2const; double kp3 = coeffkp3const; double kR = coeffkRconst; for(int j=0; j<2; j++) { kn1 += cosarray[j] * coeffkn1cos[j] + sinarray[j] * coeffkn1sin[j]; kp2 += cosarray[j] * coeffkp2cos[j] + sinarray[j] * coeffkp2sin[j]; kp3 += cosarray[j] * coeffkp3cos[j] + sinarray[j] * coeffkp3sin[j]; kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j]; } /* Common factor and delay */ double factorp = (1./(1.+kn1)) * 0.5*n1Pn1plus; double factorc = (1./(1.+kn1)) * 0.5*n1Pn1cross; double firstdelay = -(kR*variant->OrbitR + (kp3 + 1)*variant->ConstL)/C_SI; double seconddelay = -(kR*variant->OrbitR + kp2*variant->ConstL)/C_SI; /* Result */ double y32 = factorp*(gsl_spline_eval(splinehp, t+firstdelay, accelhp) - gsl_spline_eval(splinehp, t+seconddelay, accelhp)) + factorc*(gsl_spline_eval(splinehc, t+firstdelay, accelhc) - gsl_spline_eval(splinehc, t+seconddelay, accelhc)); return y32; } double y31TD( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t) /* Time */ { /* Precompute array of sine/cosine */ double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } /* Scalar products with k */ double n2Pn2plus = coeffn2Hn2plusconst; double n2Pn2cross = coeffn2Hn2crossconst; for(int j=0; j<4; j++) { n2Pn2plus += cosarray[j] * coeffn2Hn2pluscos[j] + sinarray[j] * coeffn2Hn2plussin[j]; n2Pn2cross += cosarray[j] * coeffn2Hn2crosscos[j] + sinarray[j] * coeffn2Hn2crosssin[j]; } /* Scalar products with k */ double kn2 = coeffkn2const; double kp3 = coeffkp3const; double kp1 = coeffkp1const; double kR = coeffkRconst; for(int j=0; j<2; j++) { kn2 += cosarray[j] * coeffkn2cos[j] + sinarray[j] * coeffkn2sin[j]; kp3 += cosarray[j] * coeffkp3cos[j] + sinarray[j] * coeffkp3sin[j]; kp1 += cosarray[j] * coeffkp1cos[j] + sinarray[j] * coeffkp1sin[j]; kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j]; } /* Common factor and delay */ double factorp = (1./(1.-kn2)) * 0.5*n2Pn2plus; double factorc = (1./(1.-kn2)) * 0.5*n2Pn2cross; double firstdelay = -(kR*variant->OrbitR + (kp3 + 1)*variant->ConstL)/C_SI; double seconddelay = -(kR*variant->OrbitR + kp1*variant->ConstL)/C_SI; /* Result */ double y31 = factorp*(gsl_spline_eval(splinehp, t+firstdelay, accelhp) - gsl_spline_eval(splinehp, t+seconddelay, accelhp)) + factorc*(gsl_spline_eval(splinehc, t+firstdelay, accelhc) - gsl_spline_eval(splinehc, t+seconddelay, accelhc)); return y31; } double y13TD( const LISAconstellation *variant, /* Description of LISA variant */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t) /* Time */ { /* Precompute array of sine/cosine */ double phase=variant->ConstOmega*t + variant->ConstPhi0; for(int j=0; j<4; j++) { cosarray[j] = cos((j+1) * phase); sinarray[j] = sin((j+1) * phase); } /* Scalar products with k */ double n2Pn2plus = coeffn2Hn2plusconst; double n2Pn2cross = coeffn2Hn2crossconst; for(int j=0; j<4; j++) { n2Pn2plus += cosarray[j] * coeffn2Hn2pluscos[j] + sinarray[j] * coeffn2Hn2plussin[j]; n2Pn2cross += cosarray[j] * coeffn2Hn2crosscos[j] + sinarray[j] * coeffn2Hn2crosssin[j]; } /* Scalar products with k */ double kn2 = coeffkn2const; double kp3 = coeffkp3const; double kp1 = coeffkp1const; double kR = coeffkRconst; for(int j=0; j<2; j++) { kn2 += cosarray[j] * coeffkn2cos[j] + sinarray[j] * coeffkn2sin[j]; kp3 += cosarray[j] * coeffkp3cos[j] + sinarray[j] * coeffkp3sin[j]; kp1 += cosarray[j] * coeffkp1cos[j] + sinarray[j] * coeffkp1sin[j]; kR += cosarray[j] * coeffkRcos[j] + sinarray[j] * coeffkRsin[j]; } /* Common factor and delay */ double factorp = (1./(1.+kn2)) * 0.5*n2Pn2plus; double factorc = (1./(1.+kn2)) * 0.5*n2Pn2cross; double firstdelay = -(kR*variant->OrbitR + (kp1 + 1)*variant->ConstL)/C_SI; double seconddelay = -(kR*variant->OrbitR + kp3*variant->ConstL)/C_SI; /* Result */ double y13 = factorp*(gsl_spline_eval(splinehp, t+firstdelay, accelhp) - gsl_spline_eval(splinehp, t+seconddelay, accelhp)) + factorc*(gsl_spline_eval(splinehc, t+firstdelay, accelhc) - gsl_spline_eval(splinehc, t+seconddelay, accelhc)); return y13; } /**/ int EvaluateTDIXYZTD( const LISAconstellation *variant, /* Description of LISA variant */ double* TDIX, /* Output: value of TDI observable X */ double* TDIY, /* Output: value of TDI observable Y */ double* TDIZ, /* Output: value of TDI observable Z */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t) /* Time */ { double armdelay = variant->ConstL/C_SI; double X = (y31TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y13TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) + (y21TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y12TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)) - (y21TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y12TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) - (y31TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y13TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)); double Y = (y12TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y21TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) + (y32TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y23TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)) - (y32TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y23TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) - (y12TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y21TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)); double Z = (y23TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y32TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) + (y13TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y31TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)) - (y13TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y31TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) - (y23TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y32TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)); /* Output */ *TDIX = X; *TDIY = Y; *TDIZ = Z; return SUCCESS; } /**/ int EvaluateTDIAETXYZTD( const LISAconstellation *variant, /* Description of LISA variant */ double* TDIA, /* Output: value of TDI observable X */ double* TDIE, /* Output: value of TDI observable Y */ double* TDIT, /* Output: value of TDI observable Z */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ const double t) /* Time */ { double armdelay = variant->ConstL/C_SI; double X = (y31TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y13TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) + (y21TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y12TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)) - (y21TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y12TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) - (y31TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y13TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)); double Y = (y12TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y21TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) + (y32TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y23TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)) - (y32TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y23TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) - (y12TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y21TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)); double Z = (y23TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y32TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) + (y13TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y31TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)) - (y13TD(variant, splinehp, splinehc, accelhp, accelhc, t) + y31TD(variant, splinehp, splinehc, accelhp, accelhc, t - armdelay)) - (y23TD(variant, splinehp, splinehc, accelhp, accelhc, t - 2*armdelay) + y32TD(variant, splinehp, splinehc, accelhp, accelhc, t - 3*armdelay)); /* Output */ *TDIA = 1./(2*sqrt(2)) * (Z-X); *TDIE = 1./(2*sqrt(6)) * (X-2*Y+Z); *TDIT = 1./(2*sqrt(3)) * (X+Y+Z); return SUCCESS; } /**/ int GenerateTDITD3Chanhphc( const LISAconstellation *variant, /* Description of LISA variant */ RealTimeSeries** TDI1, /* Output: real time series for TDI channel 1 */ RealTimeSeries** TDI2, /* Output: real time series for TDI channel 2 */ RealTimeSeries** TDI3, /* Output: real time series for TDI channel 3 */ gsl_spline* splinehp, /* Input spline for TD hplus */ gsl_spline* splinehc, /* Input spline for TD hcross */ gsl_interp_accel* accelhp, /* Accelerator for hp spline */ gsl_interp_accel* accelhc, /* Accelerator for hc spline */ gsl_vector* times, /* Vector of times to evaluate */ int nbptmargin, /* Margin set to 0 on both side to avoid problems with delays out of the domain */ TDItag tditag) /* Tag selecting the TDI observables */ { /* Initialize output */ int nbpt = times->size; RealTimeSeries_Init(TDI1, nbpt); RealTimeSeries_Init(TDI2, nbpt); RealTimeSeries_Init(TDI3, nbpt); gsl_vector_memcpy((*TDI1)->times, times); gsl_vector_memcpy((*TDI2)->times, times); gsl_vector_memcpy((*TDI3)->times, times); gsl_vector_set_zero((*TDI1)->h); gsl_vector_set_zero((*TDI2)->h); gsl_vector_set_zero((*TDI3)->h); /* Loop over time samples - we take a margin to avoid problems with the domain */ double t; double* tval = times->data; double* tdi1 = (*TDI1)->h->data; double* tdi2 = (*TDI2)->h->data; double* tdi3 = (*TDI3)->h->data; double tdi1val = 0, tdi2val = 0, tdi3val = 0; /* For testing purposes: basic observable yAB */ if(tditag==y12) { for(int i=nbptmargin; i<nbpt-nbptmargin; i++) { t = tval[i]; tdi1[i] = y12TD(variant, splinehp, splinehc, accelhp, accelhc, t); tdi2[i] = 0.; tdi3[i] = 0.; } } else if(tditag==TDIXYZ) { for(int i=nbptmargin; i<nbpt-nbptmargin; i++) { t = tval[i]; EvaluateTDIXYZTD(variant, &tdi1val, &tdi2val, &tdi3val, splinehp, splinehc, accelhp, accelhc, t); tdi1[i] = tdi1val; tdi2[i] = tdi2val; tdi3[i] = tdi3val; } } else if(tditag==TDIAETXYZ) { for(int i=nbptmargin; i<nbpt-nbptmargin; i++) { t = tval[i]; EvaluateTDIAETXYZTD(variant, &tdi1val, &tdi2val, &tdi3val, splinehp, splinehc, accelhp, accelhc, t); tdi1[i] = tdi1val; tdi2[i] = tdi2val; tdi3[i] = tdi3val; } } else { printf("Error: in GenerateTDITD3Chan, TDI tag not recognized.\n"); } return SUCCESS; } /* Generate hO orbital-delayed for one mode contribution from amp, phase */ int Generateh22TDO( const LISAconstellation *variant, /* Description of LISA variant */ AmpPhaseTimeSeries** h22tdO, /* Output: amp/phase time series for h22TDO */ gsl_spline* splineamp, /* Input spline for TD mode amplitude */ gsl_spline* splinephase, /* Input spline for TD mode phase */ gsl_interp_accel* accelamp, /* Accelerator for amp spline */ gsl_interp_accel* accelphase, /* Accelerator for phase spline */ gsl_vector* times, /* Vector of times to evaluate */ int nbptmargin) /* Margin set to 0 on both side to avoid problems with delays out of the domain */ { /* Initialize output */ int nbpt = times->size; AmpPhaseTimeSeries_Init(h22tdO, nbpt); gsl_vector_memcpy((*h22tdO)->times, times); gsl_vector_set_zero((*h22tdO)->h_amp); gsl_vector_set_zero((*h22tdO)->h_phase); /* Loop over time samples - we take a margin to avoid problems with the domain */ double t; double* tval = times->data; double* amp = (*h22tdO)->h_amp->data; double* phase = (*h22tdO)->h_phase->data; /* Loop over time samples */ for(int i=nbptmargin; i<nbpt-nbptmargin; i++) { t = tval[i]; hOTDAmpPhase(variant,&(amp[i]), &(phase[i]), splineamp, splinephase, accelamp, accelphase, t); } return SUCCESS; } /* Generate y12L from orbital-delayed h22 in amp/phase form */ /* Note: includes both h22 and h2m2 contributions, assuming planar orbits so that h2-2 = h22* */ /* BEWARE: this ignores the fact that processing through orbital delay breaks the h2-2 = h22* symmetry */ int Generatey12LTD( const LISAconstellation *variant, /* Description of LISA variant */ RealTimeSeries** y12Ltd, /* Output: real time series for y12L */ gsl_spline* splineamp, /* Input spline for h22 TD amplitude */ gsl_spline* splinephase, /* Input spline for h22 TD phase */ gsl_interp_accel* accelamp, /* Accelerator for h22 amp spline */ gsl_interp_accel* accelphase, /* Accelerator for h22 phase spline */ gsl_vector* times, /* Vector of times to evaluate */ double Theta, /* Inclination */ double Phi, /* Phase */ int nbptmargin) /* Margin set to 0 on both side to avoid problems with delays out of the domain */ { /* Initialize output */ int nbpt = times->size; RealTimeSeries_Init(y12Ltd, nbpt); gsl_vector_memcpy((*y12Ltd)->times, times); gsl_vector_set_zero((*y12Ltd)->h); /* Spin-weighted spherical harmonic Y22 and Y2-2 */ double complex Y22 = SpinWeightedSphericalHarmonic(Theta, Phi, -2, 2, 2); double complex Y2m2 = SpinWeightedSphericalHarmonic(Theta, Phi, -2, 2, -2); /* Loop over time samples - we take a margin to avoid problems with the domain */ double t; double* tval = times->data; double* y12val = (*y12Ltd)->h->data; /* Loop over time samples */ for(int i=nbptmargin; i<nbpt-nbptmargin; i++) { t = tval[i]; y12val[i] = y12LTDfromh22AmpPhase(variant, splineamp, splinephase, accelamp, accelphase, Y22, Y2m2, t); } return SUCCESS; } /* Generate y12 from original h22 in amp/phase form, including both */ /* Here no approximation made as to the decomposition of the response in two steps, all the response is evaluated at once */ /* Note: includes both h22 and h2m2 contributions, assuming planar orbits so that h2-2 = h22* */ int Generatey12TD( const LISAconstellation *variant, /* Description of LISA variant */ RealTimeSeries** y12td, /* Output: real time series for y12L */ gsl_spline* splineamp, /* Input spline for h22 TD amplitude */ gsl_spline* splinephase, /* Input spline for h22 TD phase */ gsl_interp_accel* accelamp, /* Accelerator for h22 amp spline */ gsl_interp_accel* accelphase, /* Accelerator for h22 phase spline */ gsl_vector* times, /* Vector of times to evaluate */ double Theta, /* Inclination */ double Phi, /* Phase */ int nbptmargin) /* Margin set to 0 on both side to avoid problems with delays out of the domain */ { /* Initialize output */ int nbpt = times->size; RealTimeSeries_Init(y12td, nbpt); gsl_vector_memcpy((*y12td)->times, times); gsl_vector_set_zero((*y12td)->h); /* Spin-weighted spherical harmonic Y22 and Y2-2 */ double complex Y22 = SpinWeightedSphericalHarmonic(Theta, Phi, -2, 2, 2); double complex Y2m2 = SpinWeightedSphericalHarmonic(Theta, Phi, -2, 2, -2); /* Loop over time samples - we take a margin to avoid problems with the domain */ double t; double* tval = times->data; double* y12val = (*y12td)->h->data; /* Loop over time samples */ for(int i=nbptmargin; i<nbpt-nbptmargin; i++) { t = tval[i]; y12val[i] = y12TDfromh22AmpPhase(variant, splineamp, splinephase, accelamp, accelphase, Y22, Y2m2, t); } return SUCCESS; }
{ "alphanum_fraction": 0.6913396225, "avg_line_length": 56.7315550511, "ext": "c", "hexsha": "ae1a058cf546f69e8af0e422d187284bc5f32ab1", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z", "max_forks_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "JohnGBaker/flare", "max_forks_repo_path": "LISAsim/LISAgeometry.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "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": "JohnGBaker/flare", "max_issues_repo_path": "LISAsim/LISAgeometry.c", "max_line_length": 1269, "max_stars_count": 3, "max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "JohnGBaker/flare", "max_stars_repo_path": "LISAsim/LISAgeometry.c", "max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z", "max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z", "num_tokens": 32496, "size": 99961 }
#ifndef __SIMQ_H #define __SIMQ_H #include "Queue.h" #include "statistics.h" #include "input.h" #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* Defining non-queue function prototypes */ Customer* createCustomer(gsl_rng **); gsl_rng * randomGenerator(); void validateArgs(int, char **); #endif
{ "alphanum_fraction": 0.7265625, "avg_line_length": 18.2857142857, "ext": "h", "hexsha": "91ce5489edf0000f9d9125252f3e8b1d7d2dbf8c", "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": "9f1dfaa6b97049ddeb508e692865f7ed442062e7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "b4ba/Postoffice_Queue_Simulation", "max_forks_repo_path": "simQ.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "9f1dfaa6b97049ddeb508e692865f7ed442062e7", "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": "b4ba/Postoffice_Queue_Simulation", "max_issues_repo_path": "simQ.h", "max_line_length": 44, "max_stars_count": null, "max_stars_repo_head_hexsha": "9f1dfaa6b97049ddeb508e692865f7ed442062e7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "b4ba/Postoffice_Queue_Simulation", "max_stars_repo_path": "simQ.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 102, "size": 384 }
#include <pygsl/solver.h> #include <gsl/gsl_multifit_nlin.h> const char * filename = __FILE__; PyObject *module = NULL; static const char multifit_f_type_name[] = "F-MultiFitSolver"; static const char multifit_fdf_type_name[] = "FdF-MultiFitSolver"; static int PyGSL_multifit_function_wrap(const gsl_vector *x, void *params, gsl_vector *f) { PyGSL_solver *self = (PyGSL_solver *) params; return PyGSL_function_wrap_Op_On(x, f, self->cbs[0], self->args, x->size, f->size, __FUNCTION__); } static int PyGSL_multifit_function_wrap_df(const gsl_vector *x, void *params, gsl_matrix *df) { PyGSL_solver *self = (PyGSL_solver *) params; /* size 1 or size 2 from matrix ? */ return PyGSL_function_wrap_Op_Opn(x, df, self->cbs[1], self->args, df->size1, x->size, __FUNCTION__); } static int PyGSL_multifit_function_wrap_fdf(const gsl_vector *x, void *params, gsl_vector *f, gsl_matrix *df) { PyGSL_solver *self = (PyGSL_solver *) params; /* size 1 or size 2 from matrix ? */ return PyGSL_function_wrap_Op_On_Opn(x, f, df, self->cbs[2], self->args, f->size, x->size, __FUNCTION__); } static PyObject * PyGSL_multifit_fdfsolver_set(PyGSL_solver *self, PyObject *pyargs, PyObject *kw) { gsl_multifit_function_fdf * c_sys; struct pygsl_solver_n_set info = {1, NULL, (set_m_t)gsl_multifit_fdfsolver_set}; PyObject * tmp; FUNC_MESS_BEGIN(); if(self->c_sys == NULL){ if((c_sys = calloc(1, sizeof(gsl_multifit_function_fdf))) == NULL){ PyGSL_ERROR_NULL("Could not allocate the memory for the c_sys", GSL_ENOMEM); } c_sys->n=self->problem_dimensions[1]; c_sys->p=self->problem_dimensions[0]; c_sys->f = PyGSL_multifit_function_wrap; c_sys->df = PyGSL_multifit_function_wrap_df; c_sys->fdf = PyGSL_multifit_function_wrap_fdf; c_sys->params=(void*)self; info.c_sys = c_sys; }else{ info.c_sys = self->c_sys; } tmp = PyGSL_solver_n_set(self, pyargs, kw, &info); if(tmp == NULL){ PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__ - 2); } FUNC_MESS_END(); return tmp; } static PyObject* PyGSL_multifit_fdfsolver_position(PyGSL_solver *self, PyObject *args) { return PyGSL_solver_ret_vec(self, args, (ret_vec)gsl_multifit_fdfsolver_position); } static gsl_multifit_fdfsolver * PyGSL_get_multifit_solver(PyGSL_solver *self) { FUNC_MESS_BEGIN(); assert(PyGSL_solver_check(self)); FUNC_MESS_END(); return (gsl_multifit_fdfsolver *) (self->solver); } static PyObject* PyGSL_multifit_fdfsolver_x(PyGSL_solver *self, PyObject *args) { return (PyObject *) PyGSL_copy_gslvector_to_pyarray(PyGSL_get_multifit_solver(self)->x); } static PyObject* PyGSL_multifit_fdfsolver_dx(PyGSL_solver *self, PyObject *args) { return (PyObject *) PyGSL_copy_gslvector_to_pyarray(PyGSL_get_multifit_solver(self)->dx); } static PyObject* PyGSL_multifit_fdfsolver_f(PyGSL_solver *self, PyObject *args) { return (PyObject *) PyGSL_copy_gslvector_to_pyarray(PyGSL_get_multifit_solver(self)->f); } static PyObject* PyGSL_multifit_fdfsolver_J(PyGSL_solver *self, PyObject *args) { return (PyObject *) PyGSL_copy_gslmatrix_to_pyarray(PyGSL_get_multifit_solver(self)->J); } static PyObject* PyGSL_multifit_fdfsolver_test_delta(PyGSL_solver *self, PyObject *args) { int flag; double epsabs, epsrel; gsl_multifit_fdfsolver *s = self->solver; if(!PyArg_ParseTuple(args, "dd", &epsabs, &epsrel)) return NULL; flag = gsl_multifit_test_delta(s->dx, s->x, epsabs, epsrel); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } static PyObject* PyGSL_multifit_fdfsolver_test_gradient(PyGSL_solver *self, PyObject *args) { int flag; double epsabs; gsl_vector *g = NULL; gsl_multifit_fdfsolver *s = self->solver; if(!PyArg_ParseTuple(args, "d", &epsabs)) return NULL; flag = gsl_multifit_gradient(s->J, s->f, g); if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS) return NULL; flag = gsl_multifit_test_gradient(g, epsabs); return PyGSL_ERROR_FLAG_TO_PYINT(flag); } static PyMethodDef PyGSL_multifit_fmethods[] = { {NULL, NULL, 0, NULL} }; static PyMethodDef PyGSL_multifit_fdfmethods[] = { {"J", (PyCFunction)PyGSL_multifit_fdfsolver_J, METH_NOARGS, NULL}, {"dx", (PyCFunction)PyGSL_multifit_fdfsolver_dx, METH_NOARGS, NULL}, {"x", (PyCFunction)PyGSL_multifit_fdfsolver_x, METH_NOARGS, NULL}, {"position", (PyCFunction)PyGSL_multifit_fdfsolver_position, METH_NOARGS, NULL}, {"f", (PyCFunction)PyGSL_multifit_fdfsolver_f, METH_NOARGS, NULL}, {"set", (PyCFunction)PyGSL_multifit_fdfsolver_set, METH_VARARGS|METH_KEYWORDS, NULL}, {"test_delta", (PyCFunction)PyGSL_multifit_fdfsolver_test_delta, METH_VARARGS, NULL}, {"test_gradient", (PyCFunction)PyGSL_multifit_fdfsolver_test_gradient, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} }; const struct _SolverStatic multifit_solver_f = {{ (void_m_t) gsl_multifit_fsolver_free, /* gsl_multifit_fsolver_restart */ (void_m_t) NULL, (name_m_t) gsl_multifit_fsolver_name, (int_m_t) gsl_multifit_fsolver_iterate}, 1, PyGSL_multifit_fmethods, multifit_f_type_name}, multifit_solver_fdf = {{(void_m_t) gsl_multifit_fdfsolver_free, /* gsl_multifit_fdfsolver_restart (void_m_t) */ NULL, (name_m_t) gsl_multifit_fdfsolver_name, (int_m_t) gsl_multifit_fdfsolver_iterate}, 3, PyGSL_multifit_fdfmethods, multifit_fdf_type_name}; static PyObject* PyGSL_multifit_f_init(PyObject *self, PyObject *args, const gsl_multifit_fsolver_type * type) { PyObject *tmp=NULL; solver_alloc_struct s = {type, (void_an_t) gsl_multifit_fsolver_alloc, &multifit_solver_f}; FUNC_MESS_BEGIN(); tmp = PyGSL_solver_dn_init(self, args, &s, 2); FUNC_MESS_END(); return tmp; } static PyObject* PyGSL_multifit_fdf_init(PyObject *self, PyObject *args, const gsl_multifit_fdfsolver_type * type) { PyObject *tmp=NULL; solver_alloc_struct s = {type, (void_an_t) gsl_multifit_fdfsolver_alloc, &multifit_solver_fdf}; FUNC_MESS_BEGIN(); tmp = PyGSL_solver_dn_init(self, args, &s, 2); FUNC_MESS_END(); return tmp; } #define AMFIT_FDF(name) \ static PyObject* PyGSL_multifit_init_ ## name (PyObject *self, PyObject *args)\ { \ PyObject *tmp = NULL; \ FUNC_MESS_BEGIN(); \ tmp = PyGSL_multifit_fdf_init(self, args, gsl_multifit_fdfsolver_ ## name); \ if (tmp == NULL){ \ PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \ } \ FUNC_MESS_END(); \ return tmp; \ } AMFIT_FDF(lmsder) AMFIT_FDF(lmder) PyObject * PyGSL_multifit_gradient(PyObject *self, PyObject *args) { PyArrayObject *J_a = NULL, *f_a = NULL, *g_a = NULL; PyObject *J_o = NULL, *f_o = NULL; gsl_vector_view f; gsl_vector_view g; gsl_matrix_view J; PyGSL_array_index_t stride_recalc, dimension; int flag; if(!PyArg_ParseTuple(args, "OO:gsl_multifit_gradient", &J_o, &f_o)){ return NULL; } J_a = PyGSL_matrix_check(J_o, -1, -1, PyGSL_DARRAY_CINPUT(1), NULL, NULL, NULL); if(J_a == NULL) goto fail; dimension = J_a->dimensions[0]; /* Numpy calculates strides in bytes, gsl in basis type */ f_a = PyGSL_vector_check(f_o, dimension, PyGSL_DARRAY_INPUT(2), &stride_recalc, NULL); if(f_a == NULL) goto fail; dimension = J_a->dimensions[1]; g_a = (PyArrayObject *) PyGSL_New_Array(1, &dimension, PyArray_DOUBLE); if(g_a == NULL) goto fail; J = gsl_matrix_view_array((double *) J_a->data, J_a->dimensions[0], J_a->dimensions[1]); f = gsl_vector_view_array_with_stride((double *) f_a->data, stride_recalc, f_a->dimensions[0]); g = gsl_vector_view_array((double *) g_a->data, dimension); flag = gsl_multifit_gradient(&J.matrix, &f.vector, &g.vector); Py_DECREF(J_a); Py_DECREF(f_a); if((PyGSL_ERROR_FLAG(flag)) != GSL_SUCCESS) goto fail; return (PyObject * )g_a; fail : Py_XDECREF(J_a); Py_XDECREF(f_a); Py_XDECREF(g_a); return NULL; } PyObject * PyGSL_multifit_covar(PyObject *self, PyObject *args) { PyArrayObject *J_a = NULL, *C_a = NULL; PyObject *J_o = NULL; gsl_matrix_view J, C; PyGSL_array_index_t dimensions[2]; int flag; double epsrel; if(!PyArg_ParseTuple(args, "Od:gsl_multifit_covar", &J_o, &epsrel)){ return NULL; } J_a = PyGSL_matrix_check(J_o, -1, -1, PyGSL_DARRAY_CINPUT(1), NULL, NULL, NULL); if(J_a == NULL) goto fail; dimensions[0] = J_a->dimensions[1]; dimensions[1] = J_a->dimensions[1]; C_a = (PyArrayObject *) PyGSL_New_Array(2, dimensions, PyArray_DOUBLE); if(C_a == NULL) goto fail; J = gsl_matrix_view_array((double *) J_a->data, J_a->dimensions[0], J_a->dimensions[1]); C = gsl_matrix_view_array((double *) C_a->data, C_a->dimensions[0], C_a->dimensions[1]); flag = gsl_multifit_covar(&J.matrix, epsrel, &C.matrix); Py_DECREF(J_a); if((PyGSL_ERROR_FLAG(flag)) != GSL_SUCCESS) goto fail; return (PyObject * )C_a; fail : Py_XDECREF(J_a); Py_XDECREF(C_a); return NULL; } static PyObject * PyGSL_multifit_test_delta(PyObject * self, PyObject * args) { return PyGSL_solver_vvdd_i(self, args, gsl_multifit_test_delta); } static PyObject * PyGSL_multifit_test_gradient(PyObject * self, PyObject * args) { return PyGSL_solver_vd_i(self, args, gsl_multifit_test_gradient); } static PyMethodDef mMethods[] = { /* multifit solvers */ {"lmder", PyGSL_multifit_init_lmder, METH_VARARGS, NULL}, {"lmsder", PyGSL_multifit_init_lmsder, METH_VARARGS, NULL}, /* multifit funcs */ {"fit_test_delta", PyGSL_multifit_test_delta, METH_VARARGS, NULL}, {"fit_test_gradient", PyGSL_multifit_test_gradient, METH_VARARGS, NULL}, {"gradient", PyGSL_multifit_gradient, METH_VARARGS, NULL}, {"covar", PyGSL_multifit_covar, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} }; static const char PyGSL_multifit_nlin_module_doc[] = "XXX Missing \n"; void initmultifit_nlin(void) { PyObject* m, *dict, *item; FUNC_MESS_BEGIN(); m=Py_InitModule("multifit_nlin", mMethods); module = m; assert(m); dict = PyModule_GetDict(m); if(!dict) goto fail; init_pygsl() import_pygsl_solver(); assert(PyGSL_API); if (!(item = PyString_FromString((char*)PyGSL_multifit_nlin_module_doc))){ PyErr_SetString(PyExc_ImportError, "I could not generate module doc string!"); goto fail; } if (PyDict_SetItemString(dict, "__doc__", item) != 0){ PyErr_SetString(PyExc_ImportError, "I could not init doc string!"); goto fail; } FUNC_MESS_END(); return; fail: FUNC_MESS("FAIL"); return; }
{ "alphanum_fraction": 0.663079615, "avg_line_length": 32.0168067227, "ext": "c", "hexsha": "02357debe69250b124a0864727338f025b823d56", "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/testing/src/solvers/multifit_nlin.c", "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/testing/src/solvers/multifit_nlin.c", "max_line_length": 98, "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/testing/src/solvers/multifit_nlin.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3369, "size": 11430 }
/* movstat/fill.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 <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_movstat.h> /* gsl_movstat_fill() Fill window for sample 'idx' from x using given end conditions Inputs: endtype - how to handle end points x - input vector, length n idx - index of center sample in window in [0,n-1] H - number of samples left of center to include J - number of samples right of center to include window - (output) window of samples centered on x_{idx}, W_{idx}^{H,J}, length H + J + 1 Return: size of filled window (<= H + J + 1) */ size_t gsl_movstat_fill(const gsl_movstat_end_t endtype, const gsl_vector * x, const size_t idx, const size_t H, const size_t J, double * window) { if (idx >= x->size) { GSL_ERROR_VAL ("window center index must be between 0 and n - 1", GSL_EDOM, 0); } else { const int n = (int) x->size; const int iidx = (int) idx; const int iH = (int) H; const int iJ = (int) J; int idx1, idx2, j; size_t window_size; if (endtype == GSL_MOVSTAT_END_TRUNCATE) { idx1 = GSL_MAX(iidx - iH, 0); idx2 = GSL_MIN(iidx + iJ, n - 1); } else { idx1 = iidx - iH; idx2 = iidx + iJ; } window_size = (size_t) (idx2 - idx1 + 1); /* fill sliding window */ for (j = idx1; j <= idx2; ++j) { int widx = j - idx1; if (j < 0) { /* initial condition */ if (endtype == GSL_MOVSTAT_END_PADZERO) window[widx] = 0.0; else if (endtype == GSL_MOVSTAT_END_PADVALUE) window[widx] = gsl_vector_get(x, 0); } else if (j >= n) { if (endtype == GSL_MOVSTAT_END_PADZERO) window[widx] = 0.0; else if (endtype == GSL_MOVSTAT_END_PADVALUE) window[widx] = gsl_vector_get(x, n - 1); } else { window[widx] = gsl_vector_get(x, j); } } return window_size; } }
{ "alphanum_fraction": 0.5683663527, "avg_line_length": 30.1862745098, "ext": "c", "hexsha": "7989c3998273a6d6eb9346608d49113fdb135567", "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/fill.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/fill.c", "max_line_length": 89, "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/fill.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": 819, "size": 3079 }
/* PETSC_DEPTRECATED causes parse erros in bindgen */ #define PETSC_DEPRECATED(arg) /* Not sure how this is generated... */ #define PETSC_BITS_PER_BYTE 8 #include <petsc.h>
{ "alphanum_fraction": 0.7572254335, "avg_line_length": 28.8333333333, "ext": "h", "hexsha": "4d2e4489ce93668a1e804bc4ae9e7b5934c12b67", "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": "ec7d92db067964e36e1319619c8773ec210d66f8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tkonolige/petsc-bindgen-rust", "max_forks_repo_path": "wrapper.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "ec7d92db067964e36e1319619c8773ec210d66f8", "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": "tkonolige/petsc-bindgen-rust", "max_issues_repo_path": "wrapper.h", "max_line_length": 53, "max_stars_count": null, "max_stars_repo_head_hexsha": "ec7d92db067964e36e1319619c8773ec210d66f8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tkonolige/petsc-bindgen-rust", "max_stars_repo_path": "wrapper.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 45, "size": 173 }
/* * CosmoCalcs.c * Library for computing physical parameters in lambda CDM cosmologies * FRLW universes. * * Created by Sean Lake on 5/24/14. */ #include "CosmoCalcs.h" #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_poly.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #define MAX(a, b) \ ({ __typeof__ (a) x = (a); \ __typeof__ (b) y = (b); \ x > y ? x : y; }) #define MIN(a, b) \ ({ __typeof__ (a) x = (a); \ __typeof__ (b) y = (b); \ x <= y ? x : y; }) #define CLAMP(a, min, max) \ ({ __typeof__ (a) hilim = (max); \ __typeof__ (a) lolim = (min); \ __typeof__ (a) x = (a); \ x = x <= hilim ? x : hilim; \ x > lolim ? x : lolim; }) #define EXPEL(a, leftbound, rightbound) \ ({ __typeof__ (a) l = (leftbound); \ __typeof__ (a) r = (rightbound); \ __typeof__ (a) x = (a); \ __typeof__ (a) Two = 2; \ x >= r || x <= l ? x : ((Two * (x - leftbound) >= \ rightbound - leftbound) ? rightbound : leftbound); }) #ifdef FP_FAST_FMA #define FMA_m(a, b, c) fma(a, b, c) #else #define FMA_m(a, b, c) ( (a) * (b) + (c) ) #endif //Function prototypes (because we don't export everything) static double NotImplementedFunc(struct UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr); static double NotImplementedInvFunc(struct UniverseLCDM *uni, double Dc, unsigned int branchNum, double epsrel, unsigned int maxiter); //interpolation functions static void LtEdgeBases(double, double, double *restrict); static inline void RtEdgeBases(double, double, double *restrict); static void centerBases(double, double, double *restrict); static void Dc0Derivatives(UniverseLCDM *, double, double *); static void tL0Derivatives(UniverseLCDM *, double, double *); static double MeanValueInterval(double, double *, double *, double *); //integration functions static inline double Einv(UniverseLCDM *, double); static inline double dDc0_dz_gsl(double, void *); static inline double dtL0_dz_gsl(double, void *); //Cosmology functions static inline double DcT0Flat(struct UniverseLCDM *, double, bool, double, double, size_t, double *); static double DcT0NegK(struct UniverseLCDM *, double, bool, double, double, size_t, double *); static double DcT0PosK(struct UniverseLCDM *, double, bool, double, double, size_t, double *); static inline double Vc0Flat(struct UniverseLCDM *, double, bool, double, double, size_t, double *); static double Vc0NegK(struct UniverseLCDM *, double, bool, double, double, size_t, double *); static double Vc0PosK(struct UniverseLCDM *, double, bool, double, double, size_t, double *); //Inverse cosmology functions static double FindDa0Max(UniverseLCDM *, double, unsigned int); static double DcT0InvFlat(struct UniverseLCDM *, double, unsigned int, double, unsigned int); static double DcT0InvNegK(struct UniverseLCDM *, double, unsigned int, double, unsigned int); static double DcT0InvPosK(struct UniverseLCDM *, double, unsigned int, double, unsigned int); static double Da0InvFlat(struct UniverseLCDM *, double, unsigned int, double, unsigned int); static double Da0InvNegK(struct UniverseLCDM *, double, unsigned int, double, unsigned int); static double Da0InvPosK(struct UniverseLCDM *, double, unsigned int, double, unsigned int); static double Dl0InvFlat(struct UniverseLCDM *, double, unsigned int, double, unsigned int); static double Dl0InvNegK(struct UniverseLCDM *, double, unsigned int, double, unsigned int); static double Dl0InvPosK(struct UniverseLCDM *, double, unsigned int, double, unsigned int); static double Vc0InvFlat(struct UniverseLCDM *, double, unsigned int, double, unsigned int); static double Vc0InvNegK(struct UniverseLCDM *, double, unsigned int, double, unsigned int); static double Vc0InvPosK(struct UniverseLCDM *, double, unsigned int, double, unsigned int); //Constants const double clight = 299792458.0; const double MeterPerAu = 0.149598e12; const double AuPerMeter = 0x1.d662b65385936p-38; //1.0 / MeterPerAu; const double MeterPerParsec = 0x1.b68064bc05bf1p+54; //MeterPerAu / tan( pi / (3600.0 * 180.0) ); const double ParsecPerMeter = 0x1.2ae8abdcb93c6p-55; //1.0 / MeterPerParsec; const double MeterPerMpc = 0x1.a2300a115feaep+74; //1e6 * MeterPerParsec; const double MpcPerMeter = 0x1.396dbd4dbf44bp-75; //1.0 / MpcPerMeter; const double SecPerYear = 31557600.0; //365.25 * 24.0 * 3600.0; const double YearPerSec = 0x1.1032d78f1540bp-25; //1.0 / SecPerYear; const double SecPerGyear = 31557600.0e9; //1e9 * SecPerYear; const double GyearPerSec = 0x1.244561c42c152p-55; //1.0 / SecPerGyear; const double Pi = 0x1.921fb54442d18p+1; static double NotImplementedFunc(struct UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { fprintf(stderr, "Error: calling a function that isn't implemented yet."); exit(EXIT_FAILURE); return NAN; } static double NotImplementedInvFunc(struct UniverseLCDM *uni, double Dc, unsigned int branchNum, double epsrel, unsigned int maxiter) { fprintf(stderr, "Error: calling an inverse function that isn't implemented yet."); exit(EXIT_FAILURE); return NAN; } /* Define the Hermite interpolation basis functions, with x the distance from * the central point in units of h, the distance between points. * Assumes equidistance points. results written to yvals, which must have length 4.*/ static void LtEdgeBases(double x, double h, double *restrict yvals) { double *res = yvals; double scale = x*x; scale *= scale; //zeroth derivative basis polynomial *res = FMA_m(FMA_m(FMA_m(105.0/32.0, x, -2.0), x, -385.0/32.0), x, 15.0/2.0); *res = FMA_m(FMA_m(FMA_m(*res, x, 495/32.0), x, -10.0), x, -231.0/32.0); *res = FMA_m(*res, x, 5.0) * scale; //first derivative basis polynomial ++res; scale *= h; *res = FMA_m(FMA_m(FMA_m(41.0/32.0, x, -29.0/32.0), x, -145.0/32.0), x, 105.0/32.0); *res = FMA_m(FMA_m(FMA_m(*res, x, 175.0/32.0), x, -131.0/32.0), x, -71.0/32.0); *res = FMA_m(*res, x, 55.0/32.0) * scale; //second derivative basis polynomial ++res; scale *= h; *res = FMA_m(FMA_m(FMA_m(3.0/16.0, x, -5.0/32.0), x, -5.0/8.0), x, 17.0/32.0); *res = FMA_m(FMA_m(FMA_m(*res, x, 11.0/16.0), x, -19.0/32.0), x, -1.0/4.0); *res = FMA_m(*res, x, 7.0/32.0) * scale; //third derivative basis polynomial ++res; scale *= h; *res = FMA_m(FMA_m(FMA_m(1.0/96.0, x, -1.0/96.0), x, -1.0/32.0), x, 1.0/32.0); *res = FMA_m(FMA_m(FMA_m(*res, x, 1.0/32.0), x, -1.0/32.0), x, -1.0/96.0); *res = FMA_m(*res, x, 1.0/96.0) * scale; return; } static inline void RtEdgeBases(double x, double h, double *restrict yvals) { LtEdgeBases(-x, h, yvals); yvals[1] *= -1.0; yvals[3] *= -1.0; return; } static void centerBases(double x, double h, double *restrict yvals) { double *res = yvals; double x2 = x*x; double scale = h; //zeroth derivative basis polynomial *res = FMA_m(FMA_m(FMA_m(4.0, x2, -15.0), x2, 20.0), x2, -10.0); *res = FMA_m(*res, x2*x2, 1.0); //first derivative basis polynomial ++res; *res = (*(res-1)) * x * h; //second derivative basis polynomial ++res; scale *= h; *res = FMA_m(FMA_m(FMA_m(0.5, x2, -2.0), x2, 3.0), x2, -2.0); *res = FMA_m(*res, x2, 0.5) * x2 * scale; //third derivative basis polynomial ++res; *res = (*(res-1)) * x * h / 3.0; return; } //Computes Einverse and its first two derivatives static void Dc0Derivatives(UniverseLCDM *uni, double invscale, double *results) { double rootarg, E, scale; double *res, *coeff; if ( uni->flat ) { rootarg = FMA_m(uni->OmegaRelativistic, invscale, uni->OmegaMatter); rootarg = FMA_m(rootarg, invscale * invscale * invscale, uni->OmegaLambda ); } else { rootarg = FMA_m(uni->OmegaRelativistic, invscale, uni->OmegaMatter); rootarg = FMA_m(rootarg, invscale, uni->OmegaCurvature); rootarg = FMA_m(rootarg, invscale * invscale, uni->OmegaLambda ); } E = sqrt(rootarg); res = results; //First order derivative scale = E / rootarg; *res = scale; //Second order derivative ++res; coeff = uni->Dc0_2ndDerCoeffs; *res = FMA_m(FMA_m(coeff[2], invscale, coeff[1]), invscale, coeff[0]) * invscale; scale /= rootarg; *res *= scale; //Third order derivative ++res; coeff = uni->Dc0_3rdDerCoeffs; *res = FMA_m(FMA_m(FMA_m(coeff[6], invscale, coeff[5]), invscale, coeff[4]), invscale, coeff[3]); *res = FMA_m(FMA_m(FMA_m(*res, invscale, coeff[2]), invscale, coeff[1]), invscale, coeff[0]); scale /= rootarg; *res *= scale; return; } //Computes the first four derivatives of tL0 static void tL0Derivatives(UniverseLCDM *uni, double invscale, double *results) { double rootarg, E, scale, scalestep; double *res, *coeffs; if ( uni->flat ) { rootarg = FMA_m(uni->OmegaRelativistic, invscale, uni->OmegaMatter); rootarg = FMA_m(rootarg, invscale * invscale * invscale, uni->OmegaLambda ); } else { rootarg = FMA_m(uni->OmegaRelativistic, invscale, uni->OmegaMatter); rootarg = FMA_m(rootarg, invscale, uni->OmegaCurvature); rootarg = FMA_m(rootarg, invscale * invscale, uni->OmegaLambda ); } E = sqrt(rootarg); res = results; //First order derivative scalestep = invscale * rootarg; scale = E / scalestep; *res = scale; //Second order derivative ++res; coeffs = uni->tL0_2ndDerCoeffs; *res = FMA_m(FMA_m(coeffs[4], invscale, coeffs[3]), invscale, coeffs[2]); *res = FMA_m(FMA_m(*res, invscale, coeffs[1]), invscale, coeffs[0]); scale /= scalestep; *res *= scale; //Third order derivative ++res; coeffs = uni->tL0_3rdDerCoeffs; *res = FMA_m(FMA_m(FMA_m(coeffs[8], invscale, coeffs[7]), invscale, coeffs[6]), invscale, coeffs[5]); *res = FMA_m(FMA_m(FMA_m(*res, invscale, coeffs[4]), invscale, coeffs[3]), invscale, coeffs[2]); *res = FMA_m(FMA_m(*res, invscale, coeffs[1]), invscale, coeffs[0]); scale /= scalestep; *res *= scale; return; } //Used for computing the cached integral values static double MeanValueInterval(double sampleSpacing, double *leftFuncDirs, double *centerFuncDirs, double *rightFuncDirs) { double result; double x = sampleSpacing * sampleSpacing; result = (-FMA_m(-32.0, centerFuncDirs[2], leftFuncDirs[2] + rightFuncDirs[2] ) \ * (1.0/630.0)); result = FMA_m(result, x, \ FMA_m(32.0, centerFuncDirs[0], 5.0*(leftFuncDirs[0] + rightFuncDirs[0])) \ * (1.0/42.0)); return result; } static double Einv(UniverseLCDM *uni, double invscale) { double rootarg; if ( uni->flat ) { rootarg = FMA_m(uni->OmegaRelativistic, invscale, uni->OmegaMatter); rootarg = FMA_m(rootarg, invscale * invscale * invscale, uni->OmegaLambda ); } else { rootarg = FMA_m(uni->OmegaRelativistic, invscale, uni->OmegaMatter); rootarg = FMA_m(rootarg, invscale, uni->OmegaCurvature); rootarg = FMA_m(rootarg, invscale * invscale, uni->OmegaLambda ); } return sqrt(rootarg) / rootarg; } static double dDc0_dz_gsl(double ainv, void *p) { return Einv((UniverseLCDM *)p, ainv); } double dDc0_dz_Cosmic(UniverseLCDM *uni, double z) { return Einv(uni, 1.0 + z); } double dDc_dz_Cosmic(UniverseLCDM *uni, double z) { return Einv(uni, 1.0 + z) * uni->DH; } double dtL0_dz_Cosmic(UniverseLCDM *uni, double z) { double invscale = 1.0 + z; return Einv(uni, invscale) / invscale; } static double dtL0_dz_gsl(double ainv, void *p) { return Einv((UniverseLCDM *)p, ainv) / ainv; } double dtL_dz_Cosmic(UniverseLCDM *uni, double z) { double invscale = 1.0 + z; return Einv(uni, invscale) / invscale * uni->tH; } bool InitUniverse(UniverseLCDM *uni, double H0, double OmegaL, double OmegaM, double OmegaR, bool flat, bool GSLcache ) { double OmegaK; uni->F_DcT0 = &NotImplementedFunc; uni->F_Vc0 = &NotImplementedFunc; uni->F_DcT0Inv = &NotImplementedInvFunc; uni->F_Vc0Inv = &NotImplementedInvFunc; if ( H0 < 0.0 || OmegaM < 0.0 || OmegaR < 0.0 ) { double *f; fprintf(stderr, "InitUniverse: unphysical universe.%s", " All of the following must be positive:\n"); fprintf(stderr, "H0 = %.4g, OmegaM=%.4g, OmegaR=%.4g\n", H0, OmegaM, OmegaR); uni->OmegaLambda = NAN; uni->OmegaMatter = NAN; uni->OmegaRelativistic = NAN; uni->OmegaCurvature = NAN; uni->H0 = NAN; uni->h = NAN; uni->tH = NAN; uni->DH = NAN; uni->VH = NAN; uni->age0 = NAN; uni->zLastTurn = NAN; uni->zNextTurn = NAN; uni->CacheValid = false; for (f = uni->Dc0_2ndDerCoeffs; f < uni->Dc0_2ndDerCoeffs+3; ++f) { *f = NAN; } for (f = uni->Dc0_3rdDerCoeffs; f < uni->Dc0_3rdDerCoeffs+7; ++f) { *f = NAN; } for (f = uni->tL0_2ndDerCoeffs; f < uni->tL0_2ndDerCoeffs+5; ++f) { *f = NAN; } for (f = uni->tL0_3rdDerCoeffs; f < uni->tL0_3rdDerCoeffs+9; ++f) { *f = NAN; } for (f = uni->Dc0_TaylorCoeffs; f < uni->Dc0_TaylorCoeffs+5; ++f) { *f = NAN; } for (f = uni->tL0_TaylorCoeffs; f < uni->tL0_TaylorCoeffs+5; ++f) { *f = NAN; } return false; } uni->H0 = H0; uni->OmegaMatter = OmegaM; uni->OmegaRelativistic = OmegaR; uni->flat = flat; if ( flat == true ) { OmegaL = 1.0 - OmegaM - OmegaR; OmegaK = 0.0; } else { OmegaK = 1.0 - ( OmegaM + OmegaL + OmegaR ); } uni->OmegaCurvature = OmegaK; uni->OmegaLambda = OmegaL; uni->h = H0 * 0.01 * 1e-3 * MeterPerMpc; uni->tH = 1.0 / H0; uni->DH = clight / H0; uni->VH = uni->DH * uni->DH * uni->DH; { //Find the turning points (if they exist) int polyorder; gsl_poly_complex_workspace *scratch; const double poly[5] = { OmegaL, 0.0, uni->OmegaCurvature, OmegaM, OmegaR }; double roots[8]; int err; double *iPart, *rPart; if (OmegaR > 0.0) { polyorder = 4; } else if (OmegaM > 0.0) { polyorder = 3; } else if (fabs(OmegaK) > NumericallyFlat) { polyorder = 2; } else { polyorder = 0; } if (polyorder > 0) { scratch = gsl_poly_complex_workspace_alloc( polyorder + 1 ); err = gsl_poly_complex_solve( poly, polyorder + 1, scratch, roots ); if ( err == GSL_EFAILED ) { fprintf(stderr, "GSL failed to find all of the candidate turning points%s", "for this cosmology:\n"); fprintf(stderr, "OmegaL = %.4f, OmegaK = %.4f, OmegaM = %.4f, OmegaR = %.4f\n", OmegaL, uni->OmegaCurvature, OmegaM, OmegaR); return false; } } uni->zLastTurn = INFINITY; uni->zNextTurn = -1.0; for (rPart = roots; rPart < roots + 2*polyorder-1; rPart += 2) { iPart = rPart + 1; if (fabs(*iPart) < IMAGINARYTOL && *rPart > 0.0) { *rPart -= 1.0; //convert inverse scale to z if (*rPart < uni->zLastTurn && *rPart > 0.0) { uni->zLastTurn = *rPart; } else if (*rPart > uni->zNextTurn && *rPart <= 0.0) { uni->zNextTurn = *rPart; } } } } { //Init the derivative parameters double *f; double OmegaK = uni->OmegaCurvature; //Dc0 Second derivative parameters f = &(uni->Dc0_2ndDerCoeffs[0]); f[0] = - OmegaK; f[1] = - 1.5 * OmegaM; f[2] = -2.0 * OmegaR; //Dc0 Third derivative parameters f = uni->Dc0_3rdDerCoeffs; f[0] = - OmegaK * OmegaL; f[1] = -3.0 * OmegaL * OmegaM; f[2] = 2.0 * OmegaK * OmegaK - 6.0 * OmegaL * OmegaR; f[3] = 5.0 * OmegaK * OmegaM; f[4] = 5.0 * OmegaK * OmegaR + 3.75 * OmegaM * OmegaM; f[5] = 9.0 * OmegaM * OmegaR; f[6] = 6.0 * OmegaR * OmegaR; //tL0 Second derivative parameters f = uni->tL0_2ndDerCoeffs; f[0] = -OmegaL; f[1] = 0.0; f[2] = -2.0 * OmegaK; f[3] = -2.5 * OmegaM; f[4] = -3.0 * OmegaR; //tL0 Third derivative parameters f = uni->tL0_3rdDerCoeffs; f[0] = 2.0 * OmegaL * OmegaL; f[1] = 0.0; f[2] = 5.0 * OmegaK * OmegaL; f[3] = 4.0 * OmegaL * OmegaM; f[4] = 2.0 * OmegaL * OmegaR + 6.0 * OmegaK * OmegaK; f[5] = 14.0 * OmegaK * OmegaM; f[6] = 15.0 * OmegaK * OmegaR + 8.75 * OmegaM * OmegaM; f[7] = 20.0 * OmegaM * OmegaR; f[8] = 12.0 * OmegaR * OmegaR; //Dc0 Low redshift Taylor expansion parameters f = uni->Dc0_TaylorCoeffs; f[0] = 1.0; f[1] = (- OmegaR \ - 0.5 * OmegaM \ + OmegaL \ - 1.0) * 0.5; f[2] = (1.5 * OmegaR * OmegaR \ + 1.5 * OmegaR * OmegaM \ - 3.0 * OmegaL * OmegaR \ + 0.5 * OmegaR \ + 0.375 * OmegaM * OmegaM \ - 1.5 * OmegaL * OmegaM \ + 0.5 * OmegaM \ + 1.5 * OmegaL * OmegaL \ - 2.5 * OmegaL \ + 1.0 ) / 3.0; f[3] = ( - 2.5 * OmegaR * OmegaR * OmegaR \ - 3.75 * OmegaR * OmegaR * OmegaM \ + 7.5 * OmegaR * OmegaR * OmegaL \ - 1.875 * OmegaR * OmegaM * OmegaM \ + 7.5 * OmegaR * OmegaM * OmegaL \ - 0.75 * OmegaR * OmegaM \ - 7.5 * OmegaR * OmegaL * OmegaL \ + 6.0 * OmegaR * OmegaL \ - 0.5 * OmegaR \ - 0.3125 * OmegaM * OmegaM * OmegaM \ + 1.875 * OmegaM * OmegaM * OmegaL \ - 0.375 * OmegaM * OmegaM \ - 3.75 * OmegaM * OmegaL * OmegaL \ + 3.75 * OmegaM * OmegaL \ - 0.5 * OmegaM \ + 2.5 * OmegaL * OmegaL * OmegaL \ - 6.0 * OmegaL * OmegaL \ + 4.5 * OmegaL \ - 1.0 ) * 0.25; f[4] = ( 4.375 * OmegaR * OmegaR * OmegaR * OmegaR \ + 8.75 * OmegaM * OmegaR * OmegaR * OmegaR \ - 17.5 * OmegaL * OmegaR * OmegaR * OmegaR \ - 1.25 * OmegaR * OmegaR * OmegaR \ + 6.5625 * OmegaM * OmegaM * OmegaR * OmegaR \ - 26.25 * OmegaM * OmegaL * OmegaR * OmegaR \ + 26.25 * OmegaL * OmegaL * OmegaR * OmegaR \ - 11.25 * OmegaL * OmegaR * OmegaR \ + 0.375 * OmegaR * OmegaR \ + 2.1875 * OmegaM * OmegaM * OmegaM * OmegaR \ - 13.125 * OmegaL * OmegaM * OmegaM * OmegaR \ + 0.9375 * OmegaM * OmegaM * OmegaR \ + 26.25 * OmegaL * OmegaL * OmegaM * OmegaR \ - 15.0 * OmegaL * OmegaM * OmegaR \ + 0.75 * OmegaM * OmegaR \ - 17.5 * OmegaL * OmegaL * OmegaL * OmegaR \ + 26.25 * OmegaL * OmegaL * OmegaR \ - 9.75 * OmegaL * OmegaR \ + 0.5 * OmegaR \ + 0.2734375 * OmegaM * OmegaM * OmegaM * OmegaM \ - 2.1875 * OmegaL * OmegaM * OmegaM * OmegaM \ + 0.3125 * OmegaM * OmegaM * OmegaM \ + 6.5625 * OmegaL * OmegaL * OmegaM * OmegaM \ - 4.6875 * OmegaL * OmegaM * OmegaM \ + 0.375 * OmegaM * OmegaM \ - 8.75 * OmegaL * OmegaL * OmegaL * OmegaM \ + 15.0 * OmegaL * OmegaL * OmegaM \ - 6.75 * OmegaL * OmegaM \ + 0.5 * OmegaM \ + 4.375 * OmegaL * OmegaL * OmegaL * OmegaL \ - 13.75 * OmegaL * OmegaL * OmegaL \ + 15.375 * OmegaL * OmegaL \ - 7.0 * OmegaL \ + 1.0 ) / 5.0; //tL0 Low redshift Taylor expansion parameters f = uni->tL0_TaylorCoeffs; f[0] = 1.0; f[1] = ( - OmegaR \ - 0.5 * OmegaM \ + OmegaL \ - 2.0 ) * 0.5; f[2] = ( 0.5 * OmegaR * OmegaR \ + 0.5 * OmegaM * OmegaR \ - OmegaL * OmegaR \ + 0.5 * OmegaR \ + 0.125 * OmegaM * OmegaM \ - 0.5 * OmegaL * OmegaM \ + OmegaM / 3.0 \ + 0.5 * OmegaL * OmegaL \ - 7.0 * OmegaL / 6.0 \ + 1.0 ); f[3] = ( - 2.5 * OmegaR * OmegaR * OmegaR \ - 3.75 * OmegaM * OmegaR * OmegaR \ + 7.5 * OmegaL * OmegaR * OmegaR \ - 1.5 * OmegaR * OmegaR \ - 1.875 * OmegaM * OmegaM * OmegaR \ + 7.5 * OmegaL * OmegaM * OmegaR \ + 2.25 * OmegaM * OmegaR \ - 7.5 * OmegaL * OmegaL * OmegaR \ + 9.0 * OmegaL * OmegaR \ - 2.0 * OmegaR \ - 0.3125 * OmegaM * OmegaM * OmegaM \ + 1.875 * OmegaL * OmegaM * OmegaM \ - 0.75 * OmegaM * OmegaM \ - 3.75 * OmegaL * OmegaL * OmegaM \ + 5.25 * OmegaL * OmegaM \ - 1.5 * OmegaM \ + 2.5 * OmegaL * OmegaL * OmegaL \ - 7.5 * OmegaL * OmegaL \ + 8.0 * OmegaL \ - 4.0 ) * 0.25; f[4] = ( 4.375 * OmegaR * OmegaR * OmegaR * OmegaR \ + 8.75 * OmegaM * OmegaR * OmegaR * OmegaR \ - 17.5 * OmegaL * OmegaR * OmegaR * OmegaR \ + 1.25 * OmegaR * OmegaR * OmegaR \ + 6.5625 * OmegaM * OmegaM * OmegaR * OmegaR \ - 26.25 * OmegaL * OmegaM * OmegaR * OmegaR \ + 3.75 * OmegaM * OmegaR * OmegaR \ + 26.25 * OmegaL * OmegaL * OmegaR * OmegaR \ - 18.75 * OmegaL * OmegaR * OmegaR \ + 1.875 * OmegaR * OmegaR \ + 2.1875 * OmegaM * OmegaM * OmegaM * OmegaR \ - 13.125 * OmegaL * OmegaM * OmegaM * OmegaR \ + 2.8125 * OmegaM * OmegaM * OmegaR \ + 26.25 * OmegaL * OmegaL * OmegaM * OmegaR \ - 22.5 * OmegaL * OmegaM * OmegaR \ + 3.0 * OmegaM * OmegaR \ - 17.5 * OmegaL * OmegaL * OmegaL * OmegaR \ + 33.75 * OmegaL * OmegaL * OmegaR \ - 18.75 * OmegaL * OmegaR \ + 2.5 * OmegaR \ + 0.2734375 * OmegaM * OmegaM * OmegaM * OmegaM \ - 2.1875 * OmegaL * OmegaM * OmegaM * OmegaM \ + 0.625 * OmegaM * OmegaM * OmegaM \ + 6.5625 * OmegaL * OmegaL * OmegaM * OmegaM \ - 6.5625 * OmegaL * OmegaM * OmegaM \ + 1.125 * OmegaM * OmegaM \ - 8.75 * OmegaL * OmegaL * OmegaL * OmegaM \ + 18.75 * OmegaL * OmegaL * OmegaM \ - 12.0 * OmegaL * OmegaM \ + 2.0 * OmegaM \ + 4.375 * OmegaL * OmegaL * OmegaL * OmegaL \ - 16.25 * OmegaL * OmegaL * OmegaL \ + 22.875 * OmegaL * OmegaL \ - 15.0 * OmegaL \ + 5.0 ) / 5.0; } //Cache only works if there are no turning points in the cache interval if (uni->zLastTurn > zMaxInterp && uni->zLastTurn > zMinInterp && \ uni->zNextTurn < zMaxInterp && uni->zNextTurn < zMinInterp ) { double errest; double cur_Dc0, cur_tL0; CachePoint *curPt_Dc0, *curPt_tL0; double curAinv = 1.0 + zMinInterp; int idx; int DcintegratorStatus, tLintegratorStatus; gsl_integration_workspace *scratch; gsl_function Dintegrand, tLintegrand; //Integrate to the left side of the cache using GSL scratch = gsl_integration_workspace_alloc( MaxGSLlevel ); Dintegrand.function = &dDc0_dz_gsl; Dintegrand.params = (void *)uni; DcintegratorStatus = gsl_integration_qag( &Dintegrand, \ 1.0, curAinv, \ GSLCacheEpsabs, GSLCacheEpsrel, MaxGSLlevel, GSL_INTEG_GAUSS51, \ scratch, &cur_Dc0, &errest); tLintegrand.function = &dtL0_dz_gsl; tLintegrand.params = (void *)uni; tLintegratorStatus = gsl_integration_qag( &tLintegrand, \ 1.0, curAinv, \ GSLCacheEpsabs, GSLCacheEpsrel, MaxGSLlevel, GSL_INTEG_GAUSS51, \ scratch, &cur_tL0, &errest); if (DcintegratorStatus == GSL_EFAILED || tLintegratorStatus==GSL_EFAILED){ uni->CacheValid = false; } else if (GSLcache) { double Dc0ders[3], tL0ders[3]; uni->CacheValid = true; curPt_Dc0 = uni->Dc0Cache; curPt_tL0 = uni->tL0Cache; curPt_Dc0->ders[0] = cur_Dc0; curPt_tL0->ders[0] = cur_tL0; for (idx = 1; idx < InterpIntervals + 1; ++idx) { ++curPt_Dc0; ++curPt_tL0; curAinv = 1.0 + zMinInterp + zInterpCellWidth * (double) idx; DcintegratorStatus = gsl_integration_qag( &Dintegrand, \ 1.0, curAinv, \ GSLCacheEpsabs, GSLCacheEpsrel, MaxGSLlevel, GSL_INTEG_GAUSS51, \ scratch, &cur_Dc0, &errest); tLintegratorStatus = gsl_integration_qag( &tLintegrand, \ 1.0, curAinv, \ GSLCacheEpsabs, GSLCacheEpsrel, MaxGSLlevel, GSL_INTEG_GAUSS51, \ scratch, &cur_tL0, &errest); if (DcintegratorStatus == GSL_EFAILED || \ tLintegratorStatus == GSL_EFAILED) { uni->CacheValid = false; break; } curPt_Dc0->ders[0] = cur_Dc0; curPt_tL0->ders[0] = cur_tL0; Dc0Derivatives(uni, curAinv, Dc0ders); tL0Derivatives(uni, curAinv, tL0ders); memcpy( &(curPt_Dc0->ders[1]), Dc0ders, 3 * sizeof(double) ); memcpy( &(curPt_tL0->ders[1]), tL0ders, 3 * sizeof(double) ); } } else { double deltaDc0, deltatL0; int intervalsPerCell = 4; double deltazinteg = zInterpCellWidth / (double) (intervalsPerCell << 1); double deltazinteg2 = 2.0 * deltazinteg; double Diffs_Dc0[9], Diffs_tL0[9]; double *leftDiffs_Dc0, *centDiffs_Dc0, *rightDiffs_Dc0; double *leftDiffs_tL0, *centDiffs_tL0, *rightDiffs_tL0; double *temp; int cacheInt = 0; //Do a rolling integral using a 3 point 0-3 derivative rule to accumulate //the cache. leftDiffs_Dc0 = Diffs_Dc0; centDiffs_Dc0 = leftDiffs_Dc0 + 3; rightDiffs_Dc0 = centDiffs_Dc0 + 3; leftDiffs_tL0 = Diffs_tL0; centDiffs_tL0 = leftDiffs_tL0 + 3; rightDiffs_tL0 = centDiffs_tL0 + 3; Dc0Derivatives(uni, curAinv, rightDiffs_Dc0); tL0Derivatives(uni, curAinv, rightDiffs_tL0); curPt_Dc0 = uni->Dc0Cache; curPt_tL0 = uni->tL0Cache; curPt_Dc0->ders[0] = cur_Dc0; curPt_tL0->ders[0] = cur_tL0; memcpy( &(curPt_Dc0->ders[1]), rightDiffs_Dc0, 3 * sizeof(double) ); memcpy( &(curPt_tL0->ders[1]), rightDiffs_tL0, 3 * sizeof(double) ); deltaDc0 = 0.0; deltatL0 = 0.0; for (idx = 0; idx < InterpIntervals * intervalsPerCell; ++idx) { //swap left and right diffs pointers temp = leftDiffs_Dc0; leftDiffs_Dc0 = rightDiffs_Dc0; rightDiffs_Dc0 = temp; temp = leftDiffs_tL0; leftDiffs_tL0 = rightDiffs_tL0; rightDiffs_tL0 = temp; //Fill in the center and right Diffs pointers curAinv += deltazinteg; Dc0Derivatives(uni, curAinv, centDiffs_Dc0); tL0Derivatives(uni, curAinv, centDiffs_tL0); curAinv += deltazinteg; Dc0Derivatives(uni, curAinv, rightDiffs_Dc0); tL0Derivatives(uni, curAinv, rightDiffs_tL0); deltaDc0 = FMA_m(deltazinteg2, \ MeanValueInterval(deltazinteg, \ leftDiffs_Dc0, centDiffs_Dc0, rightDiffs_Dc0), deltaDc0); deltatL0 = FMA_m(deltazinteg2, \ MeanValueInterval(deltazinteg, \ leftDiffs_tL0, centDiffs_tL0, rightDiffs_tL0), deltatL0); cacheInt += 1; if (cacheInt == intervalsPerCell) { //Cache the right hand side. cacheInt = 0; cur_Dc0 += deltaDc0; cur_tL0 += deltatL0; deltaDc0 = 0.0; deltatL0 = 0.0; ++curPt_Dc0; ++curPt_tL0; curPt_Dc0->ders[0] = cur_Dc0; curPt_tL0->ders[0] = cur_tL0; memcpy( &(curPt_Dc0->ders[1]), rightDiffs_Dc0, 3 * sizeof(double) ); memcpy( &(curPt_tL0->ders[1]), rightDiffs_tL0, 3 * sizeof(double) ); } } uni->CacheValid = true; } gsl_integration_workspace_free( scratch ); } else { fprintf(stderr, "Warning: InitUniverse cannot produce an integration cache\n%s", "if the cosmology has a turning point in the cache interval.\n"); uni->CacheValid = false; } { //Assign function pointers if (uni->flat || fabs(OmegaK) <= NumericallyFlat) { uni->F_DcT0 = &DcT0Flat; uni->F_Vc0 = &Vc0Flat; uni->F_DcT0Inv = &DcT0InvFlat; uni->F_Da0Inv = &Da0InvFlat; uni->F_Dl0Inv = &Dl0InvFlat; uni->F_Vc0Inv = &Vc0InvFlat; } else if (OmegaK < 0.0) { uni->F_DcT0 = &DcT0NegK; uni->F_Vc0 = &Vc0NegK; uni->F_DcT0Inv = &DcT0InvNegK; uni->F_Da0Inv = &Da0InvNegK; uni->F_Dl0Inv = &Dl0InvNegK; uni->F_Vc0Inv = &Vc0InvNegK; } else { uni->F_DcT0 = &DcT0PosK; uni->F_Vc0 = &Vc0PosK; uni->F_DcT0Inv = &DcT0InvPosK; uni->F_Da0Inv = &Da0InvPosK; uni->F_Dl0Inv = &Dl0InvPosK; uni->F_Vc0Inv = &Vc0InvPosK; } } {//Calculate vital statistics double dummy; if (isinf(uni->zLastTurn)) { uni->age0 = tL0_Cosmic(uni, INFINITY, true, 1e-6, 1e-6, MaxGSLlevel, &dummy); uni->Dc0Max = Dc0_Cosmic(uni, INFINITY, true, 1e-6, 1e-6, MaxGSLlevel, &dummy); uni->tL0LastTurn = NAN; uni->Dc0LastTurn = NAN; uni->Dc0InvD0max = uni->Dc0Max; } else { uni->age0 = INFINITY; uni->Dc0Max = INFINITY; uni->tL0LastTurn = tL0_Cosmic(uni, uni->zLastTurn, true, 1e-6, 1e-6, MaxGSLlevel, &dummy); uni->Dc0LastTurn = Dc0_Cosmic(uni, uni->zLastTurn, true, 1e-6, 1e-6, MaxGSLlevel, &dummy); uni->Dc0InvD0max = uni->Dc0LastTurn; } if (uni->zNextTurn <= -1.0) { uni->tL0NextTurn = INFINITY; } else { uni->tL0NextTurn = tL0_Cosmic(uni, uni->zNextTurn, true, 1e-6, 1e-6, MaxGSLlevel, &dummy); } uni->z_DaMax = FindDa0Max(uni, 0x1.0p-20, 1024); if (uni->flat || fabs(OmegaK) <= NumericallyFlat) { uni->DcT0Max = uni->Dc0Max; uni->Vc0Universe = Vc0Flat(uni, uni->zLastTurn, true, \ 1e-6, 1e-6, MaxGSLlevel, &dummy ); uni->Da0Max = Dc0_Cosmic(uni, uni->z_DaMax, true, \ 1e-6, 1e-6, 128, &dummy) / (1.0 + uni->z_DaMax); } else if (OmegaK < 0.0) { double N = sqrt(-OmegaK); uni->DcT0Max = uni->DH * N / (-OmegaK); uni->DcT0Max = MIN( uni->DcT0Max, sin( N * uni->DcT0Max ) * N / (-OmegaK) ); uni->Vc0Universe = Vc0NegK(uni, uni->zLastTurn, true, \ 1e-6, 1e-6, MaxGSLlevel, &dummy ); uni->Da0Max = DcT0NegK(uni, uni->z_DaMax, true, \ 1e-6, 1e-6, 128, &dummy) / (1.0 + uni->z_DaMax); } else { //OmegaK > 0.0 double N = sqrt(OmegaK); uni->DcT0Max = sinh( N * uni->Dc0Max ) * N / OmegaK; uni->Vc0Universe = Vc0PosK(uni, uni->zLastTurn, true, \ 1e-6, 1e-6, MaxGSLlevel, &dummy ); uni->Da0Max = DcT0PosK(uni, uni->z_DaMax, true, \ 1e-6, 1e-6, 128, &dummy) / (1.0 + uni->z_DaMax); } } return true; } UniverseLCDM *MakeUniverse(double H0, double OmegaL, double OmegaM, double OmegaR, bool flat, bool GSLcache) { UniverseLCDM *uni; bool unigood; if ( H0 < 0.0 || OmegaM < 0.0 || OmegaR < 0.0 ) { uni = NULL; } else { uni = (UniverseLCDM *) malloc( sizeof (UniverseLCDM) ); unigood = InitUniverse(uni, H0, OmegaL, OmegaM, OmegaR, flat,\ GSLcache); if (unigood == false) { free(uni); uni = NULL; } } return uni; } void FreeUniverse(UniverseLCDM *uni) { /*if (uni != NULL) { free(uni); }*/ return; } double Dc0_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { double result, weight, zpos; if (z < -1.0) { fprintf(stderr, "Dc0_Cosmic: invalid redshift. Redshifts must be >= -1.0\n"); fprintf(stderr, "z = %.16e\n", z); return NAN; } else if (z > uni->zLastTurn || z < uni->zNextTurn) { fprintf(stderr, "Dc0_Cosmic: invalid redshift. Cannot integrate past turning points.\n"); fprintf(stderr, "z = %.16e, zNextTurn = %.16e, zLastTurn = %.16e\n", z, uni->zNextTurn, uni->zLastTurn ); return NAN; } zpos = fabs(z); result = 0.0; weight = 1.0; if (zpos <= TaylorMaxZ) { //Perform the taylor series calculation double *coeffs = uni->Dc0_TaylorCoeffs; if (zpos > TaylorInterpMinZ) { weight = (TaylorMaxZ - zpos) * TaylorInterpInterval; } else { weight = 1.0; } result = FMA_m(FMA_m(coeffs[4], z, coeffs[3]), z, coeffs[2]); result = FMA_m(FMA_m(result, z, coeffs[1]), z, coeffs[0]) * z * weight; weight = 1.0 - weight; } *abserr = 0.0; if (fast && uni->CacheValid && z >= zMinInterp && z <= zMaxInterp \ && zpos > TaylorInterpMinZ) { double tempres, zCenter, x; double bases[4], *ders; int centeridx; CachePoint *curPt; //Use the interpolation cache centeridx = round((z - zMinInterp) / zInterpCellWidth); centeridx = CLAMP(centeridx, 1, InterpIntervals); zCenter = ((double) centeridx) * zInterpCellWidth + zMinInterp; x = (z - zCenter) / zInterpCellWidth; tempres = 0.0; curPt = uni->Dc0Cache + (centeridx - 1); ders = curPt->ders; LtEdgeBases(x, zInterpCellWidth, bases); tempres = FMA_m(bases[2], ders[2], FMA_m(bases[3], ders[3], tempres)); tempres = FMA_m(bases[0], ders[0], FMA_m(bases[1], ders[1], tempres)); ++curPt; ders = curPt->ders; centerBases(x, zInterpCellWidth, bases); tempres = FMA_m(bases[2], ders[2], FMA_m(bases[3], ders[3], tempres)); tempres = FMA_m(bases[0], ders[0], FMA_m(bases[1], ders[1], tempres)); ++curPt; ders = curPt->ders; RtEdgeBases(x, zInterpCellWidth, bases); tempres = FMA_m(bases[2], ders[2], FMA_m(bases[3], ders[3], tempres)); tempres = FMA_m(bases[0], ders[0], FMA_m(bases[1], ders[1], tempres)); result = FMA_m(weight, tempres, result); *abserr = tempres * pow(x, 12.0); } else if ( ((zpos > TaylorInterpMinZ && (!fast || !uni->CacheValid)) || z > zMaxInterp || z < zMinInterp) ) { gsl_integration_workspace *scratch; gsl_function integrand; int DcintegratorStatus; double tempres, temperr; scratch = gsl_integration_workspace_alloc( limit ); integrand.function = &dDc0_dz_gsl; integrand.params = (void *)uni; if (!isinf(z) && \ (z >= uni->zLastTurn * 0x1.fffffff8p-1 || \ z <= uni->zNextTurn * 0x1.fffffff8p-1 || \ z <= -1.0 * 0x1.fffffff8p-1)) { DcintegratorStatus = gsl_integration_qags(&integrand, \ 1.0, 1.0 + z, \ epsabs, epsrel, limit, \ scratch, &tempres, &temperr); } else if (isinf(z)) { DcintegratorStatus = gsl_integration_qagiu(&integrand, \ 1.0, \ epsabs, epsrel, limit, \ scratch, &tempres, &temperr); } else { double z0 = 0.0; double Dc0_z0 = 0.0; if ( uni->CacheValid ) { if ( z > zMaxInterp ) { z0 = zMaxInterp; Dc0_z0 = uni->Dc0Cache[InterpIntervals - 1].ders[0]; } else if ( z < zMinInterp ) { z0 = zMinInterp; Dc0_z0 = uni->Dc0Cache[0].ders[0]; } } DcintegratorStatus = gsl_integration_qag(&integrand, \ 1.0 + z0, 1.0 + z, \ epsabs, epsrel, limit, GSL_INTEG_GAUSS41, \ scratch, &tempres, &temperr); tempres += Dc0_z0; } gsl_integration_workspace_free( scratch ); if (DcintegratorStatus == GSL_EFAILED) { fprintf(stderr, "Dc0_Cosmic: gsl integrator failed.\n"); *abserr = NAN; return NAN; } result = FMA_m(weight, tempres, result); *abserr = FMA_m(weight, temperr, *abserr); } return result; } double Dc_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { return Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr) * uni->DH; } double tL0_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { double result, weight, zpos; if (z < -1.0) { fprintf(stderr, "tL0_Cosmic: invalid redshift. Redshifts must be >= -1.0\n"); fprintf(stderr, "z = %.16e\n", z); return NAN; } else if (z > uni->zLastTurn || z < uni->zNextTurn) { fprintf(stderr, "tL0_Cosmic: invalid redshift. Cannot integrate past turning points.\n"); fprintf(stderr, "z = %.16e, zNextTurn = %.16e, zLastTurn = %.16e\n", z, uni->zNextTurn, uni->zLastTurn ); return NAN; } zpos = fabs(z); result = 0.0; weight = 1.0; if (zpos <= TaylorMaxZ) { //Perform the taylor series calculation double *coeffs = uni->tL0_TaylorCoeffs; if (zpos > TaylorInterpMinZ) { weight = (TaylorMaxZ - zpos) * TaylorInterpInterval; } else { weight = 1.0; } result = FMA_m(FMA_m(coeffs[4], z, coeffs[3]), z, coeffs[2]); result = FMA_m(FMA_m(result, z, coeffs[1]), z, coeffs[0]) * z * weight; weight = 1.0 - weight; } *abserr = 0.0; if (fast && uni->CacheValid && z >= zMinInterp && z <= zMaxInterp \ && zpos > TaylorInterpMinZ) { double tempres, zCenter, x; double bases[4], *ders; int centeridx; CachePoint *curPt; //Use the interpolation cache centeridx = round((z - zMinInterp) / zInterpCellWidth); if (centeridx < 1) { centeridx = 1; } else if (centeridx >= InterpIntervals + 1) { centeridx = InterpIntervals; } zCenter = ((double) centeridx) * zInterpCellWidth + zMinInterp; x = (z - zCenter) / zInterpCellWidth; tempres = 0.0; curPt = uni->tL0Cache + centeridx - 1; ders = curPt->ders; LtEdgeBases(x, zInterpCellWidth, bases); tempres = FMA_m(bases[2], ders[2], FMA_m(bases[3], ders[3], tempres)); tempres = FMA_m(bases[0], ders[0], FMA_m(bases[1], ders[1], tempres)); ++curPt; ders = curPt->ders; centerBases(x, zInterpCellWidth, bases); tempres = FMA_m(bases[2], ders[2], FMA_m(bases[3], ders[3], tempres)); tempres = FMA_m(bases[0], ders[0], FMA_m(bases[1], ders[1], tempres)); ++curPt; ders = curPt->ders; RtEdgeBases(x, zInterpCellWidth, bases); tempres = FMA_m(bases[2], ders[2], FMA_m(bases[3], ders[3], tempres)); tempres = FMA_m(bases[0], ders[0], FMA_m(bases[1], ders[1], tempres)); result = FMA_m(weight, tempres, result); *abserr = tempres * pow(x, 12.0); } else if ( ((zpos > TaylorInterpMinZ && !fast) || z > zMaxInterp || z < zMinInterp) ) { gsl_integration_workspace *scratch; gsl_function integrand; int tLintegratorStatus; double tempres, temperr; scratch = gsl_integration_workspace_alloc( limit ); integrand.function = &dtL0_dz_gsl; integrand.params = (void *)uni; if (!isinf(z) && \ (z >= uni->zLastTurn * 0x1.fffffff8p-1 || \ z <= uni->zNextTurn * 0x1.fffffff8p-1 || \ z <= -1.0 * 0x1.fffffff8p-1)) { tLintegratorStatus = gsl_integration_qags(&integrand, \ 1.0, 1.0 + z, \ epsabs, epsrel, limit, \ scratch, &tempres, &temperr); } else if (isinf(z)) { tLintegratorStatus = gsl_integration_qagiu(&integrand, \ 1.0, \ epsabs, epsrel, limit, \ scratch, &tempres, &temperr); } else { double z0 = 0.0; double tL0_z0 = 0.0; if ( uni->CacheValid ) { if ( z > zMaxInterp ) { z0 = zMaxInterp; tL0_z0 = uni->tL0Cache[InterpIntervals - 1].ders[0]; } else if ( z < zMinInterp ) { z0 = zMinInterp; tL0_z0 = uni->tL0Cache[0].ders[0]; } } tLintegratorStatus = gsl_integration_qag(&integrand, \ 1.0 + z0, 1.0 + z, \ epsabs, epsrel, limit, GSL_INTEG_GAUSS41, \ scratch, &tempres, &temperr); tempres += tL0_z0; } gsl_integration_workspace_free( scratch ); if (tLintegratorStatus == GSL_EFAILED) { fprintf(stderr, "tL0_Cosmic: gsl integrator failed.\n"); *abserr = NAN; return NAN; } result = FMA_m(weight, tempres, result); *abserr = FMA_m(weight, temperr, *abserr); } return result; } double tL_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { return tL0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr) * uni->tH; } double DcT_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { double result; result = (*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr); result *= uni->DH; *abserr *= uni->DH; return result; } double DcT0_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { return (*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr); } static inline double DcT0Flat(struct UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { return Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr); } static double DcT0NegK(struct UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { double result, nrm; double OmegaKpos = -uni->OmegaCurvature; result = Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr); nrm = sqrt(OmegaKpos); result = sin(nrm * result) * nrm / OmegaKpos; return result; } static double DcT0PosK(struct UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { double result, nrm; double OmegaKpos = uni->OmegaCurvature; result = Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr); nrm = sqrt(uni->OmegaCurvature); result = sinh(nrm * result) * nrm / uni->OmegaCurvature; return result; } double Da0_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { return ((*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr) \ / (1.0 + z)); } double Da_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { return ((*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr) \ * uni->DH / (1.0 + z)); } double Dl0_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { return ((*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr) \ * (1.0 + z)); } double Dl_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { return ((*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr) \ * (1.0 + z) * uni->DH); } double dVc_dzdOmega0_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { double D = (*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr); return D * D * Einv(uni, 1.0 + z); } double dVc_dzdOmega_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { double D = (*(uni->F_DcT0))(uni, z, fast, epsabs, epsrel, limit, abserr); return D * D * Einv(uni, 1.0 + z) * uni->VH; } double Vc_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { return ((*(uni->F_Vc0))(uni, z, fast, epsabs, epsrel, limit, abserr) \ * uni->VH); } double Vc0_Cosmic(UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { return (*(uni->F_Vc0))(uni, z, fast, epsabs, epsrel, limit, abserr); } static double Vc0Flat(struct UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { double DcT = Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr); double result, scale; scale = 4.0*Pi * DcT * DcT; result = DcT * scale / 3.0; *abserr *= scale; return result; } static double Vc0NegK(struct UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { double Dc = Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr); double OmegaKpos = -uni->OmegaCurvature; double x, nrm, result, scale; nrm = sqrt(OmegaKpos); x = 2.0 * Dc * nrm; if ( fabs(x) < 0x1.cp-2 ) { //Use Taylor expansion where more accurate double x2 = x*x; double errscale; //Taylor expansion for sin(x) - x result = FMA_m(0x1.6124613a86d09p-33, x2, -0x1.ae64567f544e4p-26); result = FMA_m(FMA_m(result, x2, 0x1.71de3a556c734p-19), x2, -0x1.a01a01a01a01ap-13); result = FMA_m(FMA_m(result, x2, 0x1.1111111111111p-7), x2, -0x1.5555555555555p-3); result *= x2 * x; } else { result = sin(x) - x; } //First scaling of the abserr scale = sin(0.5 * x); scale *= 4.0 * Pi * scale / OmegaKpos; *abserr *= scale; //Final scaling of results result *= -Pi * nrm / (OmegaKpos * OmegaKpos); return result; } static double Vc0PosK(struct UniverseLCDM *uni, double z, bool fast, double epsabs, double epsrel, size_t limit, double *abserr) { double Dc = Dc0_Cosmic(uni, z, fast, epsabs, epsrel, limit, abserr); double OmegaKpos = uni->OmegaCurvature; double x, nrm, result, scale; nrm = sqrt(OmegaKpos); x = 2.0 * Dc * nrm; if ( fabs(x) < 0.5 ) { //Use Taylor expansion where more accurate double x2 = x*x; //Taylor expansion for sinh(x) - x result = FMA_m(0x1.6124613a86d09p-33, x2, 0x1.ae64567f544e4p-26); result = FMA_m(FMA_m(result, x2, 0x1.71de3a556c734p-19), x2, 0x1.a01a01a01a01ap-13); result = FMA_m(FMA_m(result, x2, 0x1.1111111111111p-7), x2, 0x1.5555555555555p-3); result *= x2 * x; } else { result = sinh(x) - x; } //First scaling of the abserr scale = sinh(0.5 * x); scale *= 4.0 * Pi * scale / OmegaKpos; *abserr *= scale; //Final scaling of results result *= Pi * nrm / (OmegaKpos * OmegaKpos); return result; } double Dc0Inv_Cosmic(UniverseLCDM *uni, double Dc0, unsigned int branchNum, double epsrel, unsigned int maxiter) { double zCur, zLast, f, fp, fppoverfp, foverfp, delta, ainv, dummy; double c3, c2, c1; double epsrelDc0 = 0.0625 * epsrel; double epsabsDc0 = epsrelDc0 * Dc0; unsigned int iter; bool converged = false; if (isnan(Dc0) || isnan(epsrel)) { return NAN; } else if (Dc0 < uni->Dc0InvD0max) { //do nothing } else if (!isnan(uni->Dc0LastTurn) && Dc0 == uni->Dc0LastTurn) { return uni->zLastTurn; } else if (Dc0 == uni->Dc0Max) { return INFINITY; } else { fprintf(stderr, "Dc0Inv_Cosmic: Dc0 outside the invertable region.\n"); return NAN; } //Approximation for Dc0 = z / (1 + OmegaM * z ) zCur = Dc0 / (1.0 - uni->OmegaMatter * Dc0); c3 = -2.0 * uni->OmegaRelativistic; c2 = -1.5 * uni->OmegaMatter; c1 = -uni->OmegaCurvature; //Iterate using modified Halley's method for (iter = 0; iter < maxiter; ++iter) { zLast = zCur; f = (Dc0_Cosmic(uni, zCur, true, epsabsDc0, epsrelDc0, MaxGSLlevel, &dummy) \ - Dc0); ainv = 1.0 + zCur; fp = Einv(uni, ainv); fppoverfp = FMA_m(FMA_m(c3, ainv, c2), ainv, c1) * ainv * fp * fp; foverfp = f / fp; delta = -foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4); zCur += delta; //Prevent the current estimate from becoming invalid if (zCur <= -1.0) { if (zCur < -1.0) { zCur = fabs(zCur + 1.0) - 1.0; } else { zCur = -0.5; } delta = zCur - zLast; } if (fabs(delta) <= epsrel * fabs(zCur)) { converged = true; break; } } if (!converged) { zCur = NAN; } return zCur; } double DcInv_Cosmic(UniverseLCDM *uni, double Dc, unsigned int branchNum, double epsrel, unsigned int maxiter) { double Dc0 = Dc / uni->DH; return Dc0Inv_Cosmic(uni, Dc0, branchNum, epsrel, maxiter); } double DcT0Inv_Cosmic(UniverseLCDM *uni, double DcT0, unsigned int branchNum, double epsrel, unsigned int maxiter) { return (*(uni->F_DcT0Inv))(uni, DcT0, branchNum, epsrel, maxiter); } static double DcT0InvFlat(struct UniverseLCDM *uni, double DcT0, unsigned int branchNum, double epsrel, unsigned int maxiter){ return Dc0Inv_Cosmic(uni, DcT0, branchNum, epsrel, maxiter); } static double DcT0InvNegK(struct UniverseLCDM *uni, double DcT0, unsigned int branchNum, double epsrel, unsigned int maxiter){ double x, nrm, Dc0; double OmegaKpos = -uni->OmegaCurvature; nrm = sqrt(OmegaKpos); x = asin(DcT0 * nrm); if (branchNum == 0) { //common case, do nothing } else if ((branchNum & 1) == 0) { //branchNum even x += copysign(2.0 * Pi * (double) branchNum, x); } else { //branchNum odd //Reflect across Pi/2 x += 2.0 * copysign( 0.5 * Pi - fabs(x), x); //Add the remaining branch shifts x += copysign(2.0 * Pi * (double) (branchNum - 1), x); } Dc0 = x * nrm / OmegaKpos; return Dc0Inv_Cosmic(uni, Dc0, 0, epsrel, maxiter); } static double DcT0InvPosK(struct UniverseLCDM *uni, double DcT0, unsigned int branchNum, double epsrel, unsigned int maxiter){ double x, nrm, Dc0; double OmegaKpos = uni->OmegaCurvature; nrm = sqrt(OmegaKpos); x = asinh(DcT0 * nrm); Dc0 = x * nrm / OmegaKpos; return Dc0Inv_Cosmic(uni, Dc0, 0, epsrel, maxiter); } double DcTInv_Cosmic(UniverseLCDM *uni, double DcT, unsigned int branchNum, double epsrel, unsigned int maxiter) { return DcT0Inv_Cosmic(uni, DcT / uni->DH, branchNum, epsrel, maxiter); } double Da0Inv_Cosmic(UniverseLCDM *uni, double Da0, unsigned int branchNum, double epsrel, unsigned int maxiter) { return (*(uni->F_Da0Inv))(uni, Da0, branchNum, epsrel, maxiter); } double Da0InvFlat(struct UniverseLCDM *uni, double Da0, unsigned int branchNum, double epsrel, unsigned int maxiter) { double zCur, zLast, f, ainv, a, Einv_, dummy; double fp, fppoverfp, foverfp, delta; double Dc0; double zMin, zMax; double c1, c2, c3; double epsrelDa0 = 0.0625 * epsrel; double epsabsDa0 = Da0 * epsrelDa0; unsigned int iter; bool converged = false; if (isnan(Da0) || isnan(epsrel)) { return NAN; } else if (Da0 < uni->Da0Max) { if (branchNum == 0) { zMin = -1.0; zMax = uni->z_DaMax; } else { double z = uni->zLastTurn; double dummy; double Da0LastTurn = (DcT0Flat(uni, z, true, 1e-6, epsrel, 128, &dummy) \ / (1.0 + z)); if (Da0 < Da0LastTurn) { return NAN; } else if (Da0 == Da0LastTurn) { return uni->zLastTurn; } zMin = uni->z_DaMax; zMax = uni->zLastTurn; } } else if (Da0 == uni->Da0Max) { return uni->z_DaMax; } else { fprintf(stderr, "Da0InvFlat: Da0 outside the invertable region.\n"); printf("%.16e\n", uni->Da0Max); return NAN; } if (branchNum == 0) { zCur = 0.5 * (zMin + zMax); } else { zCur = 2.0 * zMin; } f = Da0; c3 = -2.0 * uni->OmegaRelativistic; c2 = -1.5 * uni->OmegaMatter; c1 = -uni->OmegaCurvature; //Because Da often has a maximum, we proceed using Halley's iteration instead of Newtons. for (iter = 0; iter < maxiter; ++iter) { zLast = zCur; ainv = 1.0 + zCur; a = 1.0 / ainv; Dc0 = Dc0_Cosmic(uni, zCur, true, epsabsDa0, epsrelDa0, 128, &dummy); Einv_ = Einv(uni, ainv); f = FMA_m(Dc0, a, - Da0); fp = FMA_m(-Dc0, a, Einv_) * a; foverfp = f / fp; fppoverfp = FMA_m(FMA_m(c3, ainv, c2), ainv, c1) * ainv / fp; fppoverfp = FMA_m(fppoverfp, Einv_ * Einv_ * Einv_, -2.0) * a; delta = - foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4); zCur += delta; //Prevent the current estimate from becoming invalid if (zCur <= zMin){ if (zCur < zMin) { zCur = fabs(zCur - zMin) + zMin; } else { zCur = zMin + MIN(0.5, 0.125 * (zMax - zMin)); } delta = zCur - zLast; } else if (zCur >= zMax) { if (zCur > zMax) { zCur = zMax - fabs(zMax - zCur); } else { zCur = zMax - MIN(0.5, 0.125 * (zMax - zMin)); } delta = zCur - zLast; } if (fabs(delta) <= epsrel * fabs(zCur)) { converged = true; break; } } if (!converged) { zCur = NAN; } return zCur; } double Da0InvNegK(struct UniverseLCDM *uni, double Da0, unsigned int branchNum, double epsrel, unsigned int maxiter) { double zCur, zLast, f, ainv, a, Einv_, dummy; double fp, fppoverfp, foverfp, delta; double tanReduced, sinReduced, cosReduced, Dc0; double Wkpos = -uni->OmegaCurvature; double rootWk = sqrt(Wkpos); double zMin, zMax; double c1, c2, c3; double epsrelDa0 = 0.0625 * epsrel; double epsabsDa0 = Da0 * epsrelDa0; unsigned int iter; bool converged = false; if (isnan(Da0) || isnan(epsrel)) { return NAN; } else if (Da0 < uni->Da0Max) { if (branchNum == 0) { zMin = -1.0; zMax = uni->z_DaMax; } else { double z = uni->zLastTurn; double dummy; double Da0LastTurn = (DcT0Flat(uni, z, true, 1e-6, epsrel, 128, &dummy) \ / (1.0 + z)); if (Da0 < Da0LastTurn) { return NAN; } else if (Da0 == Da0LastTurn) { return uni->zLastTurn; } zMin = uni->z_DaMax; zMax = uni->zLastTurn; } } else if (Da0 == uni->Da0Max) { return uni->z_DaMax; } else { fprintf(stderr, "Da0Inv_Cosmic: Da0 outside the invertable region.\n"); return NAN; } if (branchNum == 0) { zCur = 0.5 * (zMin + zMax); } else { zCur = 2.0 * zMin; } c3 = -2.0 * uni->OmegaRelativistic; c2 = -1.5 * uni->OmegaMatter; c1 = -uni->OmegaCurvature; //Because Da often has a maximum, we proceed using Halley's iteration instead of Newtons. for (iter = 0; iter < maxiter; ++iter) { zLast = zCur; ainv = 1.0 + zCur; a = 1.0 / ainv; Dc0 = Dc0_Cosmic(uni, zCur, true, epsabsDa0, epsrelDa0, 128, &dummy); Einv_ = Einv(uni, ainv); sinReduced = sin(Dc0 * rootWk)/rootWk; cosReduced = cos(Dc0 * rootWk); tanReduced = sinReduced / cosReduced; f = FMA_m(sinReduced, a, -Da0); fp = FMA_m(-sinReduced, a, cosReduced * Einv_) * a; foverfp = f / fp; fppoverfp = FMA_m(FMA_m(c3, ainv, c2), ainv, c1) / fp; fppoverfp = FMA_m(fppoverfp, Einv_ * Einv_ * Einv_, FMA_m(Einv_ * Einv_, -Wkpos, 2.0 * a) * tanReduced); delta = - foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4); zCur += delta; //Prevent the current estimate from becoming invalid if (zCur <= zMin){ if (zCur < zMin) { zCur = fabs(zCur - zMin) + zMin; } else { zCur = zMin + MIN(0.5, 0.125 * (zMax - zMin)); } delta = zCur - zLast; } else if (zCur >= zMax) { if (zCur > zMax) { zCur = zMax - fabs(zMax - zCur); } else { zCur = zMax - MIN(0.5, 0.125 * (zMax - zMin)); } delta = zCur - zLast; } if (fabs(delta) <= epsrel * fabs(zCur)) { converged = true; break; } } if (!converged) { zCur = NAN; } return zCur; } double Da0InvPosK(struct UniverseLCDM *uni, double Da0, unsigned int branchNum, double epsrel, unsigned int maxiter) { double zCur, zLast, f, ainv, a, Einv_, dummy; double fp, fppoverfp, foverfp, delta; double tanhReduced, sinhReduced, coshReduced, Dc0; double Wkpos = uni->OmegaCurvature; double rootWk = sqrt(Wkpos); double zMin, zMax; double c1, c2, c3; double epsrelDa0 = 0.0625 * epsrel; double epsabsDa0 = Da0 * epsrelDa0; unsigned int iter; bool converged = false; if (isnan(Da0) || isnan(epsrel)) { return NAN; } else if (Da0 < uni->Da0Max) { if (branchNum == 0) { zMin = -1.0; zMax = uni->z_DaMax; } else { double z = uni->zLastTurn; double dummy; double Da0LastTurn = (DcT0Flat(uni, z, true, 1e-6, epsrel, 128, &dummy) \ / (1.0 + z)); if (Da0 < Da0LastTurn) { return NAN; } else if (Da0 == Da0LastTurn) { return uni->zLastTurn; } zMin = uni->z_DaMax; zMax = uni->zLastTurn; } } else if (Da0 == uni->Da0Max) { return uni->z_DaMax; } else { fprintf(stderr, "Da0Inv_Cosmic: Da0 outside the invertable region.\n"); return NAN; } if (branchNum == 0) { zCur = 0.5 * (zMin + zMax); } else { zCur = 2.0 * zMin; } c3 = -2.0 * uni->OmegaRelativistic; c2 = -1.5 * uni->OmegaMatter; c1 = -uni->OmegaCurvature; //Because Da often has a maximum, we proceed using Halley's iteration instead of Newtons. for (iter = 0; iter < maxiter; ++iter) { zLast = zCur; ainv = 1.0 + zCur; a = 1.0 / ainv; Dc0 = Dc0_Cosmic(uni, zCur, true, epsabsDa0, epsrelDa0, 128, &dummy); Einv_ = Einv(uni, ainv); sinhReduced = sinh(Dc0 * rootWk)/rootWk; coshReduced = cosh(Dc0 * rootWk); tanhReduced = tanh(Dc0 * rootWk)/rootWk; f = FMA_m(sinhReduced, a, -Da0); fp = FMA_m(-sinhReduced, a, coshReduced * Einv_) * a; foverfp = f / fp; fppoverfp = FMA_m(FMA_m(c3, ainv, c2), ainv, c1) / fp; fppoverfp = FMA_m(fppoverfp, Einv_ * Einv_ * Einv_, FMA_m(Einv_ * Einv_, Wkpos, 2.0 * a) * tanhReduced); delta = - foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4); zCur += delta; //Prevent the current estimate from becoming invalid if (zCur <= zMin){ if (zCur < zMin) { zCur = fabs(zCur - zMin) + zMin; } else { zCur = zMin + MIN(0.5, 0.125 * (zMax - zMin)); } delta = zCur - zLast; } else if (zCur >= zMax) { if (zCur > zMax) { zCur = zMax - fabs(zMax - zCur); } else { zCur = zMax - MIN(0.5, 0.125 * (zMax - zMin)); } delta = zCur - zLast; } if (fabs(delta) <= epsrel * fabs(zCur)) { converged = true; break; } } if (!converged) { zCur = NAN; } return zCur; } double DaInv_Cosmic(UniverseLCDM *uni, double Da, unsigned int branchNum, double epsrel, unsigned int maxiter) { return Da0Inv_Cosmic(uni, Da / uni->DH, branchNum, epsrel, maxiter); } double Dl0Inv_Cosmic(UniverseLCDM *uni, double Dl0, unsigned int branchNum, double epsrel, unsigned int maxiter) { return (*(uni->F_Dl0Inv))(uni, Dl0, branchNum, epsrel, maxiter); } double Dl0InvFlat(struct UniverseLCDM *uni, double Dl0, unsigned int branchNum, double epsrel, unsigned int maxiter) { double zCur, zLast, branchsign, f, ainv, Einv_, dummy; double fp, fppoverfp, foverfp, delta; double Dc0; double zMin, zMax; double c1, c2, c3; double epsrelDl0 = 0.0625 * epsrel; double epsabsDl0 = Dl0 * epsrelDl0; unsigned int iter; bool converged = false; if (isnan(Dl0) || isnan(epsrel)) { return NAN; } else if (isinf(Dl0)) { return INFINITY; } else if ((!isnan(uni->Dc0LastTurn) && \ Dl0 < uni->Dc0LastTurn * (1.0 + uni->zLastTurn)) || \ isnan(uni->Dc0LastTurn)) { //do nothing } else { fprintf(stderr, "Dl0InvFlat: Unhandled case.\n"); return NAN; } //Approximation for Dc0 = z * (1+z) / ( 1 + OmegaM * z ) zCur = 0.5 * (1.0 - Dc0 * uni->OmegaMatter); zCur = sqrt(FMA_m(zCur, zCur, Dc0)) - zCur; c3 = -2.0 * uni->OmegaRelativistic; c2 = -1.5 * uni->OmegaMatter; c1 = -uni->OmegaCurvature; //Iterate using modified Halley's method for (iter = 0; iter < maxiter; ++iter) { zLast = zCur; ainv = 1.0 + zCur; Dc0 = Dc0_Cosmic(uni, zCur, true, epsabsDl0, epsrelDl0, 128, &dummy); Einv_ = Einv(uni, ainv); f = FMA_m(Dc0, ainv, -Dl0); fp = FMA_m(Einv_, ainv, Dc0); foverfp = f / fp; fppoverfp = FMA_m(FMA_m(FMA_m(c3, ainv, c2), ainv, c1), ainv * ainv * Einv_ * Einv_, 2.0) * Einv_; fppoverfp /= fp; delta = -foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4); zCur += delta; //Prevent the current estimate from becoming invalid if (zCur <= -1.0) { if (zCur < -1.0) { zCur = fabs(zCur + 1.0) - 1.0; } else { zCur = -0.5; } delta = zCur - zLast; } if (fabs(delta) < epsrel * fabs(zCur)) { converged = true; break; } } if (!converged) { zCur = NAN; } return zCur; } double Dl0InvNegK(struct UniverseLCDM *uni, double Dl0, unsigned int branchNum, double epsrel, unsigned int maxiter) { double zCur, zLast, branchsign, f, ainv, Einv_, dummy; double fp, fppoverfp, foverfp, delta; double tanReduced, sinReduced, cosReduced, Dc0; double Wkpos = -uni->OmegaCurvature; double rootWk = sqrt(Wkpos); double zMin, zMax; double c1, c2, c3; double epsrelDl0 = 0.0625 * epsrel; double epsabsDl0 = Dl0 * epsrelDl0; unsigned int iter; bool converged = false; if (isnan(Dl0) || isnan(epsrel)) { return NAN; } else if (isinf(Dl0)) { return INFINITY; } else if ((!isnan(uni->Dc0LastTurn) && \ Dl0 < uni->Dc0LastTurn * (1.0 + uni->zLastTurn)) || \ isnan(uni->Dc0LastTurn)) { //do nothing } else { fprintf(stderr, "Dl0InvNegK: Unhandled case.\n"); return NAN; } //Approximation for Dc0 = z * (1+z) / ( 1 + OmegaM * z ) zCur = 0.5 * (1.0 - Dc0 * uni->OmegaMatter); zCur = sqrt(FMA_m(zCur, zCur, Dc0)) - zCur; c3 = -2.0 * uni->OmegaRelativistic; c2 = -1.5 * uni->OmegaMatter; c1 = -uni->OmegaCurvature; //Iterate using modified Halley's method for (iter = 0; iter < maxiter; ++iter) { zLast = zCur; ainv = 1.0 + zCur; Dc0 = Dc0_Cosmic(uni, zCur, true, epsabsDl0, epsrelDl0, 128, &dummy); Einv_ = Einv(uni, ainv); sinReduced = sin(Dc0 * rootWk)/rootWk; cosReduced = cos(Dc0 * rootWk); tanReduced = tan(Dc0 * rootWk)/rootWk; f = FMA_m(sinReduced, ainv, -Dl0); fp = FMA_m(Einv_ * cosReduced, ainv, sinReduced); foverfp = f / fp; fppoverfp = (FMA_m(FMA_m(c3, ainv, c2), ainv, c1) * \ ainv * Einv_ * Einv_); fppoverfp /= FMA_m(Einv_, ainv, tanReduced); fppoverfp += FMA_m(tanReduced, ainv * Einv_ / -Wkpos, 2.0); fppoverfp *= Einv_; delta = -foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4); zCur += delta; //Prevent the current estimate from becoming invalid if (zCur <= -1.0) { if (zCur < -1.0) { zCur = fabs(zCur + 1.0) - 1.0; } else { zCur = -0.5; } delta = zCur - zLast; } if (fabs(delta) < epsrel * fabs(zCur)) { converged = true; break; } } if (!converged) { zCur = NAN; } return zCur; } double Dl0InvPosK(struct UniverseLCDM *uni, double Dl0, unsigned int branchNum, double epsrel, unsigned int maxiter) { double zCur, zLast, branchsign, f, ainv, Einv_, dummy; double fp, fppoverfp, foverfp, delta; double tanhReduced, sinhReduced, coshReduced, Dc0; double Wkpos = uni->OmegaCurvature; double rootWk = sqrt(Wkpos); double zMin, zMax; double c1, c2, c3; double epsrelDl0 = 0.0625 * epsrel; double epsabsDl0 = Dl0 * epsrelDl0; unsigned int iter; bool converged = false; if (isnan(Dl0) || isnan(epsrel)) { return NAN; } else if (isinf(Dl0)) { return INFINITY; } else if ((!isnan(uni->Dc0LastTurn) && \ Dl0 < uni->Dc0LastTurn * (1.0 + uni->zLastTurn)) || \ isnan(uni->Dc0LastTurn)) { //do nothing } else { fprintf(stderr, "Dl0InvPosK: Unhandled case.\n"); return NAN; } //Approximation for Dc0 = z * (1+z) / ( 1 + OmegaM * z ) zCur = 0.5 * (1.0 - Dc0 * uni->OmegaMatter); zCur = sqrt(FMA_m(zCur, zCur, Dc0)) - zCur; c3 = -2.0 * uni->OmegaRelativistic; c2 = -1.5 * uni->OmegaMatter; c1 = -uni->OmegaCurvature; //Iterate using modified Halley's method for (iter = 0; iter < maxiter; ++iter) { zLast = zCur; ainv = 1.0 + zCur; Dc0 = Dc0_Cosmic(uni, zCur, true, epsabsDl0, epsrelDl0, 128, &dummy); Einv_ = Einv(uni, ainv); sinhReduced = sinh(Dc0 * rootWk)/rootWk; coshReduced = cosh(Dc0 * rootWk); tanhReduced = tanh(Dc0 * rootWk)/rootWk; f = FMA_m(sinhReduced, ainv, -Dl0); fp = FMA_m(Einv_ * coshReduced, ainv, sinhReduced); foverfp = f / fp; fppoverfp = (FMA_m(FMA_m(c3, ainv, c2), ainv, c1) * \ ainv * Einv_ * Einv_); fppoverfp /= FMA_m(Einv_, ainv, tanhReduced); fppoverfp += FMA_m(tanhReduced, ainv * Einv_ / Wkpos, 2.0); fppoverfp *= Einv_; delta = -foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-4); zCur += delta; //Prevent the current estimate from becoming invalid if (zCur <= -1.0) { if (zCur < -1.0) { zCur = fabs(zCur + 1.0) - 1.0; } else { zCur = -0.5; } delta = zCur - zLast; } if (fabs(delta) < epsrel * fabs(zCur)) { converged = true; break; } } if (!converged) { zCur = NAN; } return zCur; } double DlInv_Cosmic(UniverseLCDM *uni, double Dl, unsigned int branchNum, double epsrel, unsigned int maxiter) { return Dl0Inv_Cosmic(uni, Dl / uni->DH, branchNum, epsrel, maxiter); } double Vc0Inv_Cosmic(UniverseLCDM *uni, double Vc0, unsigned int branchNum, double epsrel, unsigned int maxiter) { return (*(uni->F_Vc0Inv))(uni, Vc0, branchNum, epsrel, maxiter); } double VcInv_Cosmic(UniverseLCDM *uni, double Vc, unsigned int branchNum, double epsrel, unsigned int maxiter) { double Vc0 = Vc / uni->VH; return Vc0Inv_Cosmic(uni, Vc0, branchNum, epsrel, maxiter); } static double Vc0InvFlat(struct UniverseLCDM *uni, double Vc0, unsigned int branchNum, double epsrel, unsigned int maxiter) { return Dc0Inv_Cosmic(uni, pow(Vc0 * 3.0 / (4.0 * Pi), 1.0/3.0), branchNum, epsrel, maxiter); } static double Vc0InvNegK(struct UniverseLCDM *uni, double Vc0, unsigned int branchNum, double epsrel, unsigned int maxiter) { double OmegaKpos = -uni->OmegaCurvature; double nrm = sqrt(OmegaKpos); double x, f, fp, delta; unsigned int iter; bool converged = false; double xCur, xLast, y, sx; double y0, dy; double epsrelx = epsrel * 0.25; y = -OmegaKpos * nrm * Vc0 / Pi; //This is sin(x) - x y0 = -2.0 * Pi * round(y / (2*Pi)); dy = y - y0; xCur = -y0 - copysign(pow(6.0 * fabs(dy), 1.0/3.0), dy) ; //Iterate using Newton's method for (iter = 0; iter < maxiter; ++iter) { xLast = xCur; sx = sin(xCur); f = sx - xCur - y; fp = sin(0.5*xCur); fp *= -2.0 * fp; delta = -f/fp; xCur += delta; if (fabs(delta) <= epsrelx * fabs(xCur)) { converged = true; break; } } if (converged) { return Dc0Inv_Cosmic(uni, xCur * 0.5 * nrm / OmegaKpos, branchNum, epsrel, maxiter); } return NAN; } static double Vc0InvPosK(struct UniverseLCDM *uni, double Vc0, unsigned int branchNum, double epsrel, unsigned int maxiter) { double OmegaKpos = uni->OmegaCurvature; double nrm = sqrt(OmegaKpos); double x, f, fp, delta; unsigned int iter; bool converged = false; double xCur, xLast, y, ypos, sx; double epsrelx = epsrel * 0.25; y = OmegaKpos * nrm * Vc0 / Pi; //This is sinh(x) - x ypos = fabs(y); if (ypos < 4.5) { xCur = copysign(pow(6.0 * ypos, 1.0/3.0), y); } else { xCur = copysign(y, log(0.5*ypos)); } //Iterate using Newton's method for (iter = 0; iter < maxiter; ++iter) { xLast = xCur; sx = sinh(xCur); f = sx - xCur - y; fp = sinh(0.5*xCur); fp *= 2.0 * fp; delta = -f/fp; xCur += delta; if (fabs(delta) <= epsrelx * fabs(xCur)) { converged = true; break; } } if (converged) { return Dc0Inv_Cosmic(uni, xCur * 0.5 * nrm / OmegaKpos, branchNum, epsrel, maxiter); } return NAN; } double tL0Inv_Cosmic(UniverseLCDM *uni, double tL0, unsigned int branchNum, double epsrel, unsigned int maxiter) { double zCur, zLast, f, fp, dummy; double ainv, foverfp, fppoverfp, delta, c4, c3, c2, c0; double epsreltL0 = 0.0625 * epsrel; double epsabstL0 = tL0 * epsreltL0; unsigned int iter; bool converged = false; if (isnan(tL0) || isnan(epsrel)) { return NAN; } else if (tL0 < uni->age0) { //do nothing } else if (!isnan(uni->tL0LastTurn) && tL0 == uni->tL0LastTurn) { return uni->zLastTurn; } else if (tL0 == uni->age0) { return INFINITY; } else if (isnan(tL0) || isnan(epsrel)) { return NAN; } else { fprintf(stderr, "tL0Inv_Cosmic: tL0 outside the invertable region.\n"); return NAN; } c4 = -3.0 * uni->OmegaRelativistic; c3 = -2.5 * uni->OmegaMatter; c2 = -2.0 * uni->OmegaCurvature; c0 = -uni->OmegaLambda; //Approximation for tL= tAge * ( 1 - 1/pow(1+z, 1.5) ) zCur = pow(1.0 - tL0 / uni->age0, -2.0/3.0); //Iterate using Halley's method for (iter = 0; iter < maxiter; ++iter) { zLast = zCur; f = (tL0_Cosmic(uni, zCur, true, epsabstL0, epsreltL0, MaxGSLlevel, &dummy) - tL0); ainv = 1.0 + zCur; fp = Einv(uni, ainv) / ainv; fppoverfp = FMA_m(FMA_m(FMA_m(c4, ainv, c3), ainv, c2), ainv * ainv, c0) * ainv; fppoverfp *= fp * fp; foverfp = f / fp; delta = -foverfp / MAX(FMA_m(-0.5 * fppoverfp, foverfp, 1.0), 0x1.0p-1); zCur += delta; //Prevent the current estimate from becoming invalid if (zCur <= -1.0){ if (zCur < -1.0) { zCur = fabs(zCur + 1.0) - 1.0; } else { zCur = -0.5; } delta = zCur - zLast; } if (fabs(delta) <= epsrel * fabs(zCur)) { converged = true; break; } } if (!converged) { zCur = NAN; } return zCur; } double tLInv_Cosmic(UniverseLCDM *uni, double tL, unsigned int branchNum, double epsrel, unsigned int maxiter) { double tL0 = tL / uni->tH; return tL0Inv_Cosmic(uni, tL0, branchNum, epsrel, maxiter); } //Function to find the redshift at which Da has a maximum static double FindDa0Max(UniverseLCDM *uni, double epsrel, unsigned int maxiter) { double Einv_, ainv, a, zCur, zLast, dummy; double epsrelDa0 = 0.0625 * epsrel; unsigned int iter; bool converged = false; if (uni->flat || fabs(uni->OmegaCurvature) <= NumericallyFlat) { //Iterate using Newton's method double f, fp, delta, Dc0, dummy; double c3, c2, c1; zCur = 0.0; f = (DcT0Flat(uni, 1.0, true, epsrelDa0, epsrel, 128, &dummy) \ / ainv); c3 = -2.0 * uni->OmegaRelativistic; c2 = -1.5 * uni->OmegaMatter; c1 = -uni->OmegaCurvature; for (iter = 0; iter < maxiter; ++iter) { zLast = zCur; ainv = 1.0 + zCur; a = 1.0 / ainv; Dc0 = DcT0Flat(uni, zCur, \ true, f * epsrelDa0, epsrel, 128, &dummy); Einv_ = Einv(uni, ainv); f = FMA_m(-Dc0, a, Einv_); fp = FMA_m(FMA_m(c3, ainv, c2), ainv, c1); fp = FMA_m(fp, ainv * Einv_ * Einv_ * Einv_, \ FMA_m(Dc0, a, -Einv_) * a * 2.0); delta = -f / fp; zCur += delta; //Prevent the current estimate from becoming invalid if (zCur <= -1.0){ if (zCur < -1.0) { zCur = fabs(zCur + 1.0) - 1.0; } else { zCur = -0.5; } } if (fabs(delta) <= epsrel * fabs(zCur) || isinf(zCur)) { converged = true; break; } } } else if (uni->OmegaCurvature < 0.0) { //Iterate using Newton's method double f, fp, delta, Dc0, dummy; double c3, c2, c1; double tanReduced, Einv_, ainv, a; double Wkpos = -uni->OmegaCurvature; double rootWk = sqrt(Wkpos); zCur = 0.0; Dc0 = (Dc0_Cosmic(uni, 1.0, true, epsrelDa0, epsrel, 128, &dummy) \ / ainv); c3 = -2.0 * uni->OmegaRelativistic; c2 = -1.5 * uni->OmegaMatter; c1 = -uni->OmegaCurvature; for (iter = 0; iter < maxiter; ++iter) { zLast = zCur; ainv = 1.0 + zCur; a = 1.0 / ainv; Dc0 = Dc0_Cosmic(uni, zCur, true, epsrelDa0 * Dc0, epsrelDa0, 128, &dummy); tanReduced = tan(Dc0 * rootWk) / rootWk; Einv_ = Einv(uni, ainv); f = FMA_m(-tanReduced, a, Einv_); fp = FMA_m(2.0*tanReduced, a, -2.0 * Einv_); fp = FMA_m(fp, a, Einv_*Einv_ * \ FMA_m(FMA_m(FMA_m(c3, ainv, c2), ainv, c1), \ ainv * Einv_, Wkpos * tanReduced)); delta = -f / fp; zCur += delta; //Prevent the current estimate from becoming invalid if (zCur <= -1.0){ if (zCur < -1.0) { zCur = fabs(zCur + 1.0) - 1.0; } else { zCur = -0.5; } } if (fabs(delta) <= epsrel * fabs(zCur) || isinf(zCur)) { converged = true; break; } } } else { //uni->OmegaCurvature > 0.0 //Iterate using Newton's method double f, fp, delta, Dc0, dummy; double c3, c2, c1; double tanhReduced, Einv_, ainv, a; double Wkpos = uni->OmegaCurvature; double rootWk = sqrt(Wkpos); zCur = 0.0; Dc0 = (Dc0_Cosmic(uni, 1.0, true, epsrelDa0, epsrel, 128, &dummy) \ / ainv); c3 = -2.0 * uni->OmegaRelativistic; c2 = -1.5 * uni->OmegaMatter; c1 = -uni->OmegaCurvature; for (iter = 0; iter < maxiter; ++iter) { zLast = zCur; ainv = 1.0 + zCur; a = 1.0 / ainv; Dc0 = Dc0_Cosmic(uni, zCur, true, epsrelDa0 * Dc0, epsrelDa0, 128, &dummy); tanhReduced = tanh(Dc0 * rootWk) / rootWk; Einv_ = Einv(uni, ainv); f = FMA_m(-tanhReduced, a, Einv_); fp = FMA_m(2.0*tanhReduced, a, -2.0 * Einv_); fp = FMA_m(fp, a, Einv_*Einv_ * \ FMA_m(FMA_m(FMA_m(c3, ainv, c2), ainv, c1), \ ainv * Einv_, Wkpos * tanhReduced)); delta = -f / fp; zCur += delta; //Prevent the current estimate from becoming invalid if (zCur <= -1.0){ if (zCur < -1.0) { zCur = fabs(zCur + 1.0) - 1.0; } else { zCur = -0.5; } } if (fabs(delta) <= epsrel * fabs(zCur) || isinf(zCur)) { converged = true; break; } } } if (!converged) { zCur = NAN; } return zCur; }
{ "alphanum_fraction": 0.6330563893, "avg_line_length": 26.9718420023, "ext": "c", "hexsha": "4e41f6463e6f3767561b97439557d94485f4f3e9", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2019-11-27T09:04:25.000Z", "max_forks_repo_forks_event_min_datetime": "2017-08-22T05:19:03.000Z", "max_forks_repo_head_hexsha": "95f4f1b4d87e54e3e469598b70d09c70c657d59e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "odysseus9672/SELPythonLibs", "max_forks_repo_path": "CosmoCalcs/CosmoCalcs.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "95f4f1b4d87e54e3e469598b70d09c70c657d59e", "max_issues_repo_issues_event_max_datetime": "2017-08-25T04:44:56.000Z", "max_issues_repo_issues_event_min_datetime": "2017-08-22T05:27:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "odysseus9672/SELPythonLibs", "max_issues_repo_path": "CosmoCalcs/CosmoCalcs.c", "max_line_length": 102, "max_stars_count": 2, "max_stars_repo_head_hexsha": "95f4f1b4d87e54e3e469598b70d09c70c657d59e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "odysseus9672/SELPythonLibs", "max_stars_repo_path": "CosmoCalcs/CosmoCalcs.c", "max_stars_repo_stars_event_max_datetime": "2020-06-12T11:44:08.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-15T18:06:50.000Z", "num_tokens": 26903, "size": 68967 }
/* filter/gaussian.c * * Gaussian smoothing filters * * 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 <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_filter.h> #include <gsl/gsl_poly.h> /* maximum derivative order allowed for Gaussian filter */ #define GSL_FILTER_GAUSSIAN_MAX_ORDER 10 typedef double gaussian_type_t; typedef double ringbuf_type_t; #include "ringbuf.c" typedef struct { size_t n; /* window size */ double * window; /* linear array with current window */ ringbuf * rbuf; /* ring buffer storing current window */ } gaussian_state_t; static size_t gaussian_size(const size_t n); static int gaussian_init(const size_t n, void * vstate); static int gaussian_insert(const gaussian_type_t x, void * vstate); static int gaussian_delete(void * vstate); static int gaussian_get(void * params, gaussian_type_t * result, const void * vstate); static const gsl_movstat_accum gaussian_accum_type; /* gsl_filter_gaussian_alloc() Allocate a workspace for Gaussian filtering. Inputs: K - number of samples in window; if even, it is rounded up to the next odd, to have a symmetric window Return: pointer to workspace */ gsl_filter_gaussian_workspace * gsl_filter_gaussian_alloc(const size_t K) { const size_t H = K / 2; gsl_filter_gaussian_workspace *w; size_t state_size; w = calloc(1, sizeof(gsl_filter_gaussian_workspace)); if (w == 0) { GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM); } w->K = 2 * H + 1; w->kernel = malloc(w->K * sizeof(double)); if (w->kernel == 0) { gsl_filter_gaussian_free(w); GSL_ERROR_NULL ("failed to allocate space for kernel", GSL_ENOMEM); return NULL; } state_size = gaussian_size(w->K); w->movstat_workspace_p = gsl_movstat_alloc_with_size(state_size, H, H); if (!w->movstat_workspace_p) { gsl_filter_gaussian_free(w); GSL_ERROR_NULL ("failed to allocate space for movstat workspace", GSL_ENOMEM); } return w; } void gsl_filter_gaussian_free(gsl_filter_gaussian_workspace * w) { if (w->kernel) free(w->kernel); if (w->movstat_workspace_p) gsl_movstat_free(w->movstat_workspace_p); free(w); } /* gsl_filter_gaussian() Apply a Gaussian filter to an input vector: G_{sigma}(x) = exp [ -x^2 / (2 sigma^2) ] Inputs: alpha - number of standard deviations to include in Gaussian kernel order - derivative order of Gaussian x - input vector, size n y - (output) filtered vector, size n w - workspace Notes: 1) If alpha = 3, then the Gaussian kernel will be a Gaussian of +/- 3 standard deviations */ int gsl_filter_gaussian(const gsl_filter_end_t endtype, const double alpha, const size_t order, const gsl_vector * x, gsl_vector * y, gsl_filter_gaussian_workspace * w) { if (x->size != y->size) { GSL_ERROR("input and output vectors must have same length", GSL_EBADLEN); } else if (alpha <= 0.0) { GSL_ERROR("alpha must be positive", GSL_EDOM); } else { int status; gsl_vector_view kernel = gsl_vector_view_array(w->kernel, w->K); /* construct Gaussian kernel of length K */ gsl_filter_gaussian_kernel(alpha, order, 1, &kernel.vector); status = gsl_movstat_apply_accum(endtype, x, &gaussian_accum_type, (void *) w->kernel, y, NULL, w->movstat_workspace_p); return status; } } /* gsl_filter_gaussian_kernel() Construct Gaussian kernel with given sigma and order Inputs: alpha - number of standard deviations to include in window order - kernel order (0 = gaussian, 1 = first derivative, ...) normalize - normalize so sum(G) = 1 kernel - (output) Gaussian kernel Return: success/error Notes: 1) If alpha = 3, then the output kernel will contain a Gaussian with +/- 3 standard deviations */ int gsl_filter_gaussian_kernel(const double alpha, const size_t order, const int normalize, gsl_vector * kernel) { const size_t N = kernel->size; if (alpha <= 0.0) { GSL_ERROR("alpha must be positive", GSL_EDOM); } else if (order > GSL_FILTER_GAUSSIAN_MAX_ORDER) { GSL_ERROR("derivative order is too large", GSL_EDOM); } else { const double half = 0.5 * (N - 1.0); /* (N - 1) / 2 */ double sum = 0.0; size_t i; /* check for quick return */ if (N == 1) { if (order == 0) gsl_vector_set(kernel, 0, 1.0); else gsl_vector_set(kernel, 0, 0.0); return GSL_SUCCESS; } for (i = 0; i < N; ++i) { double xi = ((double)i - half) / half; double yi = alpha * xi; double gi = exp(-0.5 * yi * yi); gsl_vector_set(kernel, i, gi); sum += gi; } /* normalize so sum(kernel) = 1 */ if (normalize) gsl_vector_scale(kernel, 1.0 / sum); if (order > 0) { const double beta = -0.5 * alpha * alpha; double q[GSL_FILTER_GAUSSIAN_MAX_ORDER + 1]; size_t k; /* * Need to calculate derivatives of the Gaussian window; define * * w(n) = C * exp [ p(n) ] * * p(n) = beta * n^2 * beta = -1/2 * ( alpha / ((N-1)/2) )^2 * * Then: * * d^k/dn^k w(n) = q_k(n) * w(n) * * where q_k(n) is a degree-k polynomial in n, which satisfies: * * q_k(n) = d/dn q_{k-1}(n) + q_{k-1}(n) * dp(n)/dn * q_0(n) = 1 / half^{order} */ /* initialize q_0(n) = 1 / half^{order} */ q[0] = 1.0 / gsl_pow_uint(half, order); for (i = 1; i <= GSL_FILTER_GAUSSIAN_MAX_ORDER; ++i) q[i] = 0.0; /* loop through derivative orders and calculate q_k(n) for k = 1,...,order */ for (k = 1; k <= order; ++k) { double qm1 = q[0]; q[0] = q[1]; for (i = 1; i <= k; ++i) { double tmp = q[i]; q[i] = (i + 1.0) * q[i + 1] + /* d/dn q_{k-1} */ 2.0 * beta * qm1; /* q_{k-1}(n) p'(n) */ qm1 = tmp; } } /* now set w(n) := q(n) * w(n) */ for (i = 0; i < N; ++i) { double xi = ((double)i - half) / half; double qn = gsl_poly_eval(q, order + 1, xi); double *wn = gsl_vector_ptr(kernel, i); *wn *= qn; } } return GSL_SUCCESS; } } static size_t gaussian_size(const size_t n) { size_t size = 0; size += sizeof(gaussian_state_t); size += n * sizeof(gaussian_type_t); size += ringbuf_size(n); return size; } static int gaussian_init(const size_t n, void * vstate) { gaussian_state_t * state = (gaussian_state_t *) vstate; state->n = n; state->window = (gaussian_type_t *) ((unsigned char *) vstate + sizeof(gaussian_state_t)); state->rbuf = (ringbuf *) ((unsigned char *) state->window + n * sizeof(gaussian_type_t)); ringbuf_init(n, state->rbuf); return GSL_SUCCESS; } static int gaussian_insert(const gaussian_type_t x, void * vstate) { gaussian_state_t * state = (gaussian_state_t *) vstate; /* add new element to ring buffer */ ringbuf_insert(x, state->rbuf); return GSL_SUCCESS; } static int gaussian_delete(void * vstate) { gaussian_state_t * state = (gaussian_state_t *) vstate; if (!ringbuf_is_empty(state->rbuf)) ringbuf_pop_back(state->rbuf); return GSL_SUCCESS; } static int gaussian_get(void * params, gaussian_type_t * result, const void * vstate) { const gaussian_state_t * state = (const gaussian_state_t *) vstate; const double * kernel = (const double *) params; size_t n = ringbuf_copy(state->window, state->rbuf); double sum = 0.0; size_t i; for (i = 0; i < n; ++i) sum += state->window[i] * kernel[n - i - 1]; *result = sum; return GSL_SUCCESS; } static const gsl_movstat_accum gaussian_accum_type = { gaussian_size, gaussian_init, gaussian_insert, gaussian_delete, gaussian_get };
{ "alphanum_fraction": 0.6073321555, "avg_line_length": 26.2492753623, "ext": "c", "hexsha": "d83c90e2c0bd2e284335e9c50251f21b80608f1f", "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/filter/gaussian.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/filter/gaussian.c", "max_line_length": 113, "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/filter/gaussian.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": 2446, "size": 9056 }
#include <stdlib.h> #include <limits.h> #include <stdio.h> #include <errno.h> #include <time.h> #include <sys/resource.h> #include <string.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> double drand() { return (double) rand() / RAND_MAX; } void ptime(struct rusage *ru0, struct rusage *ru1) { double utime = 0, stime = 0, ttime = 0; utime = (double) ru1->ru_utime.tv_sec + 1.e-6 * (double) ru1->ru_utime.tv_usec - ru0->ru_utime.tv_sec - 1.e-6 * (double) ru0->ru_utime.tv_usec; stime = (double) ru1->ru_stime.tv_sec + 1.e-6 * (double) ru1->ru_stime.tv_usec - ru0->ru_stime.tv_sec - 1.e-6 * (double) ru0->ru_stime.tv_usec; ttime = stime + utime; printf("%3f\n", ttime); } int main(int argc, char *argv[]) { if (argc < 2) { errno = EINVAL; perror(""); return errno; } int n = strtol(argv[1], NULL, 10); if (0 != errno) { perror(""); return errno; } srand(time(NULL)); int els = n * n; double *A_data = (double *) malloc(els * sizeof(double)); for (int i = 0; i < els; i++) { A_data[i] = drand(); } double *b_data = (double *) malloc(n * sizeof(double)); for (int i = 0; i < n; i++) { b_data[i] = drand(); } gsl_matrix_view A = gsl_matrix_view_array(A_data, n, n); gsl_matrix *A_copy = gsl_matrix_alloc(n, n); gsl_matrix_memcpy(A_copy, &A.matrix); fprintf(stderr, "A = [\n"); gsl_matrix_fprintf(stderr, &A.matrix, "%g"); fprintf(stderr, "]\n"); gsl_vector_view b = gsl_vector_view_array(b_data, n); fprintf(stderr, "b = [\n"); gsl_vector_fprintf(stderr, &b.vector, "%g"); fprintf(stderr, "]\n"); gsl_vector *x = gsl_vector_alloc(n); struct rusage t0, t1, t2; int s; gsl_permutation *p = gsl_permutation_alloc(n); getrusage(RUSAGE_SELF, &t0); gsl_linalg_LU_decomp(&A.matrix, p, &s); getrusage(RUSAGE_SELF, &t1); gsl_linalg_LU_solve(&A.matrix, p, &b.vector, x); getrusage(RUSAGE_SELF, &t2); fprintf(stderr, "x = [\n"); gsl_vector_fprintf(stderr, x, "%g"); fprintf(stderr, "]\n"); fprintf(stderr, "%s \n", "decomposition time:"); ptime(&t0, &t1); fprintf(stderr, "%s \n", "solve time:"); ptime(&t1, &t2); fprintf(stderr, "%s \n", "together time:"); ptime(&t0, &t2); gsl_vector *y = gsl_vector_alloc(n); gsl_blas_dgemv(CblasNoTrans, 1.0, A_copy, x, 0, y); fprintf(stderr, "y = [\n"); gsl_vector_fprintf(stderr, y, "%g"); fprintf(stderr, "]\n"); gsl_permutation_free(p); gsl_vector_free(x); return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5707425194, "avg_line_length": 25.5377358491, "ext": "c", "hexsha": "4532e8c4d5bf41b864531dbd7a6aa15c1f6b38b5", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mistyfiky/agh-mownit", "max_forks_repo_path": "lab6/zad.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mistyfiky/agh-mownit", "max_issues_repo_path": "lab6/zad.c", "max_line_length": 61, "max_stars_count": null, "max_stars_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mistyfiky/agh-mownit", "max_stars_repo_path": "lab6/zad.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 857, "size": 2707 }
#pragma once #include <typeinfo> #include <gsl/gsl_assert> #include <algorithm> #include "halleystring.h" #include <halley/support/exception.h> namespace Halley { template <typename T> struct EnumNames { }; struct UserConverter { template<typename T, typename std::enable_if<std::is_enum<T>::value, int>::type = 0> static String toString(const T& v) { return EnumNames<T>()()[int(v)]; } template<typename T, typename std::enable_if<!std::is_enum<T>::value, int>::type = 0> static String toString(const T& v) { return v.toString(); } template<typename T, typename std::enable_if<std::is_enum<T>::value, int>::type = 0> static T fromString(const String& str) { EnumNames<T> n; auto names = n(); auto res = std::find_if(std::begin(names), std::end(names), [&](const char* v) { return str == v; }); if (res == std::end(names)) { throw Exception("String \"" + str + "\" does not exist in enum \"" + typeid(T).name() + "\".", HalleyExceptions::Utils); } return T(res - std::begin(names)); } template<typename T, typename std::enable_if<!std::is_enum<T>::value, int>::type = 0> static T fromString(const String& str) { return T(str); } }; template <typename T> struct ToStringConverter { String operator()(const T& s) const { return UserConverter::toString(s); } }; template <typename T> struct FromStringConverter { T operator()(const String& s) const { return UserConverter::fromString<T>(s); } }; template<size_t N> struct ToStringConverter<char[N]> { String operator()(const char s[N]) const { return String(s); } }; template<> struct ToStringConverter<const char*> { String operator()(const char* s) const { return String(s); } }; template<> struct ToStringConverter<char*> { String operator()(const char* s) const { return String(s); } }; template<size_t N> struct ToStringConverter<wchar_t[N]> { String operator()(const wchar_t s[N]) const { return String(s); } }; template<> struct ToStringConverter<const wchar_t*> { String operator()(const wchar_t* s) const { return String(s); } }; template<> struct ToStringConverter<wchar_t*> { String operator()(const wchar_t* s) const { return String(s); } }; template<> struct ToStringConverter<std::string> { String operator()(const std::string& s) const { return String(s); } }; template<> struct ToStringConverter<bool> { String operator()(bool s) const { return String(s ? "true" : "false"); } }; template<> struct FromStringConverter<bool> { bool operator()(const String& s) const { return s == "true"; } }; template <typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0> String toString(T src, int precisionDigits = -1, char decimalSeparator = '.') { Expects(precisionDigits >= -1 && precisionDigits <= 20); std::stringstream str; if (precisionDigits != -1) { str << std::fixed << std::setprecision(precisionDigits); } str << src; String result; if (precisionDigits == -1) { result = String::prettyFloat(str.str()); } else { result = str.str(); } if (decimalSeparator != '.') { result = result.replaceAll(String("."), String(decimalSeparator)); } return result; } template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0> String toString(T value, int base = 10, int width = 1) { Expects(base == 10 || base == 16 || base == 8); std::stringstream ss; if (base == 16) { ss.setf(std::ios::hex, std::ios::basefield); } else if (base == 8) { ss.setf(std::ios::oct, std::ios::basefield); } if (width > 1) { ss << std::setfill('0') << std::setw(width); } ss << value; return ss.str(); } template <typename T, typename std::enable_if<!std::is_integral<T>::value && !std::is_floating_point<T>::value, int>::type = 0> String toString(const T& value) { return ToStringConverter<typename std::remove_cv<T>::type>()(value); } template <typename T> T fromString(const String& value) { return FromStringConverter<T>()(value); } template <typename T, typename std::enable_if<!std::is_same<T, String>::value, int>::type = 0> String operator+ (const String& lhp, const T& rhp) { return lhp + toString<typename std::remove_cv<T>::type>(rhp); } template <typename T, typename std::enable_if<!std::is_same<T, String>::value, int>::type = 0> String operator+ (const T& lhp, const String& rhp) { return toString<typename std::remove_cv<T>::type>(lhp) + rhp; } }
{ "alphanum_fraction": 0.6409753973, "avg_line_length": 20.9726027397, "ext": "h", "hexsha": "9ae41f4f222203a6fed17cc10e7268468b6babbe", "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": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "sunhay/halley", "max_forks_repo_path": "src/engine/utils/include/halley/text/string_converter.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "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": "sunhay/halley", "max_issues_repo_path": "src/engine/utils/include/halley/text/string_converter.h", "max_line_length": 128, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "sunhay/halley", "max_stars_repo_path": "src/engine/utils/include/halley/text/string_converter.h", "max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z", "num_tokens": 1316, "size": 4593 }
/* sum/levin_utrunc.c * * 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. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_test.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sum.h> int gsl_sum_levin_utrunc_accel (const double *array, const size_t array_size, gsl_sum_levin_utrunc_workspace * w, double *sum_accel, double *abserr_trunc) { return gsl_sum_levin_utrunc_minmax (array, array_size, 0, array_size - 1, w, sum_accel, abserr_trunc); } int gsl_sum_levin_utrunc_minmax (const double *array, const size_t array_size, const size_t min_terms, const size_t max_terms, gsl_sum_levin_utrunc_workspace * w, double *sum_accel, double *abserr_trunc) { if (array_size == 0) { *sum_accel = 0.0; *abserr_trunc = 0.0; w->sum_plain = 0.0; w->terms_used = 0; return GSL_SUCCESS; } else if (array_size == 1) { *sum_accel = array[0]; *abserr_trunc = GSL_POSINF; w->sum_plain = array[0]; w->terms_used = 1; return GSL_SUCCESS; } else { const double SMALL = 0.01; const size_t nmax = GSL_MAX (max_terms, array_size) - 1; double trunc_n = 0.0, trunc_nm1 = 0.0; double actual_trunc_n = 0.0, actual_trunc_nm1 = 0.0; double result_n = 0.0, result_nm1 = 0.0; size_t n; int better = 0; int before = 0; int converging = 0; double least_trunc = GSL_DBL_MAX; double result_least_trunc; /* Calculate specified minimum number of terms. No convergence tests are made, and no truncation information is stored. */ for (n = 0; n < min_terms; n++) { const double t = array[n]; result_nm1 = result_n; gsl_sum_levin_utrunc_step (t, n, w, &result_n); } /* Assume the result after the minimum calculation is the best. */ result_least_trunc = result_n; /* Calculate up to maximum number of terms. Check truncation condition. */ for (; n <= nmax; n++) { const double t = array[n]; result_nm1 = result_n; gsl_sum_levin_utrunc_step (t, n, w, &result_n); /* Compute the truncation error directly */ actual_trunc_nm1 = actual_trunc_n; actual_trunc_n = fabs (result_n - result_nm1); /* Average results to make a more reliable estimate of the real truncation error */ trunc_nm1 = trunc_n; trunc_n = 0.5 * (actual_trunc_n + actual_trunc_nm1); /* Determine if we are in the convergence region. */ better = (trunc_n < trunc_nm1 || trunc_n < SMALL * fabs (result_n)); converging = converging || (better && before); before = better; if (converging) { if (trunc_n < least_trunc) { /* Found a low truncation point in the convergence region. Save it. */ least_trunc = trunc_n; result_least_trunc = result_n; } if (fabs (trunc_n / result_n) < 10.0 * GSL_MACH_EPS) break; } } if (converging) { /* Stopped in the convergence region. Return result and error estimate. */ *sum_accel = result_least_trunc; *abserr_trunc = least_trunc; w->terms_used = n; return GSL_SUCCESS; } else { /* Never reached the convergence region. Use the last calculated values. */ *sum_accel = result_n; *abserr_trunc = trunc_n; w->terms_used = n; return GSL_SUCCESS; } } } int gsl_sum_levin_utrunc_step (const double term, const size_t n, gsl_sum_levin_utrunc_workspace * w, double *sum_accel) { if (term == 0.0) { /* This is actually harmless when treated in this way. A term which is exactly zero is simply ignored; the state is not changed. We return GSL_EZERODIV as an indicator that this occured. */ return GSL_EZERODIV; } else if (n == 0) { *sum_accel = term; w->sum_plain = term; w->q_den[0] = 1.0 / term; w->q_num[0] = 1.0; return GSL_SUCCESS; } else { double factor = 1.0; double ratio = (double) n / (n + 1.0); int j; w->sum_plain += term; w->q_den[n] = 1.0 / (term * (n + 1.0) * (n + 1.0)); w->q_num[n] = w->sum_plain * w->q_den[n]; for (j = n - 1; j >= 0; j--) { double c = factor * (j + 1) / (n + 1); factor *= ratio; w->q_den[j] = w->q_den[j + 1] - c * w->q_den[j]; w->q_num[j] = w->q_num[j + 1] - c * w->q_num[j]; } *sum_accel = w->q_num[0] / w->q_den[0]; return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.5498998665, "avg_line_length": 29.5172413793, "ext": "c", "hexsha": "03bf8bc041006b4262f3b52c61bf4a8d8e5a8f55", "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/sum/levin_utrunc.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/sum/levin_utrunc.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/sum/levin_utrunc.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": 1599, "size": 5992 }
/* GENETIC - A simple genetic algorithm. Copyright 2014, Javier Burguete Tolosa. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``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 Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file entity.c * \brief Source file to define the entity functions. * \author Javier Burguete Tolosa. * \copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved. */ #define _GNU_SOURCE #include <gsl/gsl_rng.h> #include <glib.h> #include "entity.h" /** * Function to create an entity. */ void entity_new (Entity * entity, ///< Entity struct. unsigned int genome_nbytes, ///< Number of bytes of the entity genome. unsigned int id) ///< Identifier number. { entity->id = id; // Aligning in 4 bytes entity->nbytes = ((genome_nbytes + 3) / 4) * 4; entity->genome = (char *) g_slice_alloc (entity->nbytes); } /** * Function to init randomly the genome of an entity. */ void entity_init (Entity * entity, ///< Entity struct. gsl_rng * rng) ///< GSL random numbers generator. { unsigned int i; for (i = 0; i < entity->nbytes; ++i) entity->genome[i] = (char) gsl_rng_uniform_int (rng, 256); } /** * Function to free the memory used by an entity. */ void entity_free (Entity * entity) ///< Entity struct. { g_slice_free1 (entity->nbytes, entity->genome); }
{ "alphanum_fraction": 0.7277867528, "avg_line_length": 33.4594594595, "ext": "c", "hexsha": "c13ba5d9ab51c5da03764e72d8ba14c4922c8ea3", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_forks_event_min_datetime": "2017-05-22T08:54:08.000Z", "max_forks_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "jburguete/genetic", "max_forks_repo_path": "3.0.0/entity.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "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": "jburguete/genetic", "max_issues_repo_path": "3.0.0/entity.c", "max_line_length": 79, "max_stars_count": 3, "max_stars_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "jburguete/genetic", "max_stars_repo_path": "3.0.0/entity.c", "max_stars_repo_stars_event_max_datetime": "2017-05-02T02:31:16.000Z", "max_stars_repo_stars_event_min_datetime": "2016-04-07T07:31:25.000Z", "num_tokens": 571, "size": 2476 }
/* bspline/test.c * * Copyright (C) 2006 Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <gsl/gsl_test.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_ieee_utils.h> void test_bspline (gsl_bspline_workspace * bw) { gsl_vector *B; size_t i, j; size_t n = 100; size_t ncoeffs = gsl_bspline_ncoeffs (bw); size_t order = gsl_bspline_order (bw); size_t nbreak = gsl_bspline_nbreak (bw); double a = gsl_bspline_breakpoint (0, bw); double b = gsl_bspline_breakpoint (nbreak - 1, bw); B = gsl_vector_alloc (ncoeffs); for (i = 0; i < n; i++) { double xi = a + (b - a) * (i / (n - 1.0)); double sum = 0; gsl_bspline_eval (xi, B, bw); for (j = 0; j < ncoeffs; j++) { double Bj = gsl_vector_get (B, j); int s = (Bj < 0 || Bj > 1); gsl_test (s, "basis-spline coefficient %u is in range [0,1] for x=%g", j, xi); sum += Bj; } gsl_test_rel (sum, 1.0, order * GSL_DBL_EPSILON, "basis-spline order %u is normalized for x=%g", order, xi); } gsl_vector_free (B); } int main (int argc, char **argv) { int status = 0; size_t order, breakpoints, i; gsl_ieee_env_setup (); argc = 0; /* prevent warnings about unused parameters */ argv = 0; for (order = 1; order < 10; order++) { for (breakpoints = 2; breakpoints < 100; breakpoints++) { double a = -1.23 * order, b = 45.6 * order; gsl_bspline_workspace *bw = gsl_bspline_alloc (order, breakpoints); gsl_bspline_knots_uniform (a, b, bw); test_bspline (bw); gsl_bspline_free (bw); } } for (order = 1; order < 10; order++) { for (breakpoints = 2; breakpoints < 100; breakpoints++) { double a = -1.23 * order, b = 45.6 * order; gsl_bspline_workspace *bw = gsl_bspline_alloc (order, breakpoints); gsl_vector *k = gsl_vector_alloc (breakpoints); for (i = 0; i < breakpoints; i++) { double f, x; f = sqrt (i / (breakpoints - 1.0)); x = (1 - f) * a + f * b; gsl_vector_set (k, i, x); }; gsl_bspline_knots (k, bw); test_bspline (bw); gsl_vector_free (k); gsl_bspline_free (bw); } } exit (gsl_test_summary ()); }
{ "alphanum_fraction": 0.5767427321, "avg_line_length": 28.3097345133, "ext": "c", "hexsha": "e05dde047b436d8d3d358be45700f3e0692585f5", "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/bspline/test.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/bspline/test.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/bspline/test.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 904, "size": 3199 }