Search is not available for this dataset
text string | meta dict |
|---|---|
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
/************************************************************************************************************************************************************************/
/************************************************************************************************************************************************************************/
//VARIABLE GLOBALE
int size = 100;
int limit = 100;
gsl_interp_accel *acc[25];
gsl_spline *spline[25];
double fg, // growth factor
b, //Bias factor
smin, // Minimum of s range
smax, // Maximum of s range
sigv, // Value of Sigma_v (define in sigma_v function)
sig8, // Value of sigma 8 (define in main function)
kmin, // minimum k in the power spectrum file (define in main function)
kmax, // minimum k in the power spectrum file (define in main function)
lk, // lk = kmax-kmin lenth for the integral calculation (define in main function)
f1, //Bias factor CLPT
f2, //Bias factor CLPT
sig_shift;
const int val=160; // Nb of lines in the files Xi_r_CLPT, Sigma_CLPT and V12_CLPT
struct my_f_params { double a; double b; };
/*********************************************************************************************************************************************************************/
/*******************\\ Gauss-Legendre integral quadrature\\***********************************************************************************************************/
static const double x[] = {
1.56289844215430828714e-02, 4.68716824215916316162e-02,
7.80685828134366366918e-02, 1.09189203580061115002e-01,
1.40203137236113973212e-01, 1.71080080538603274883e-01,
2.01789864095735997236e-01, 2.32302481844973969643e-01,
2.62588120371503479163e-01, 2.92617188038471964730e-01,
3.22360343900529151720e-01, 3.51788526372421720979e-01,
3.80872981624629956772e-01, 4.09585291678301542532e-01,
4.37897402172031513100e-01, 4.65781649773358042251e-01,
4.93210789208190933576e-01, 5.20158019881763056670e-01,
5.46597012065094167460e-01, 5.72501932621381191292e-01,
5.97847470247178721259e-01, 6.22608860203707771585e-01,
6.46761908514129279840e-01, 6.70283015603141015784e-01,
6.93149199355801965946e-01, 7.15338117573056446485e-01,
7.36828089802020705530e-01, 7.57598118519707176062e-01,
7.77627909649495475605e-01, 7.96897892390314476375e-01,
8.15389238339176254384e-01, 8.33083879888400823522e-01,
8.49964527879591284320e-01, 8.66014688497164623416e-01,
8.81218679385018415547e-01, 8.95561644970726986709e-01,
9.09029570982529690453e-01, 9.21609298145333952679e-01,
9.33288535043079545942e-01, 9.44055870136255977955e-01,
9.53900782925491742847e-01, 9.62813654255815527284e-01,
9.70785775763706331929e-01, 9.77809358486918288561e-01,
9.83877540706057015509e-01, 9.88984395242991747997e-01,
9.93124937037443459632e-01, 9.96295134733125149166e-01,
9.98491950639595818382e-01, 9.99713726773441233703e-01
};
static const double A[] = {
3.12554234538633569472e-02, 3.12248842548493577326e-02,
3.11638356962099067834e-02, 3.10723374275665165874e-02,
3.09504788504909882337e-02, 3.07983790311525904274e-02,
3.06161865839804484966e-02, 3.04040795264548200160e-02,
3.01622651051691449196e-02, 2.98909795933328309169e-02,
2.95904880599126425122e-02, 2.92610841106382766198e-02,
2.89030896011252031353e-02, 2.85168543223950979908e-02,
2.81027556591011733175e-02, 2.76611982207923882944e-02,
2.71926134465768801373e-02, 2.66974591835709626611e-02,
2.61762192395456763420e-02, 2.56294029102081160751e-02,
2.50575444815795897034e-02, 2.44612027079570527207e-02,
2.38409602659682059633e-02, 2.31974231852541216230e-02,
2.25312202563362727021e-02, 2.18430024162473863146e-02,
2.11334421125276415432e-02, 2.04032326462094327666e-02,
1.96530874944353058650e-02, 1.88837396133749045537e-02,
1.80959407221281166640e-02, 1.72904605683235824399e-02,
1.64680861761452126430e-02, 1.56296210775460027242e-02,
1.47758845274413017686e-02, 1.39077107037187726882e-02,
1.30259478929715422855e-02, 1.21314576629794974079e-02,
1.12251140231859771176e-02, 1.03078025748689695861e-02,
9.38041965369445795116e-03, 8.44387146966897140266e-03,
7.49907325546471157895e-03, 6.54694845084532276405e-03,
5.58842800386551515727e-03, 4.62445006342211935096e-03,
3.65596120132637518238e-03, 2.68392537155348241939e-03,
1.70939265351810523958e-03, 7.34634490505671730396e-04
};
#define NUM_OF_POSITIVE_ZEROS sizeof(x) / sizeof(double)
#define NUM_OF_ZEROS NUM_OF_POSITIVE_ZEROS+NUM_OF_POSITIVE_ZEROS
double
Gauss_Legendre_Integration2_100pts(double a, double b, double (*f)(double, void *), void *prms)
{
double integral = 0.0;
double c = 0.5 * (b - a);
double d = 0.5 * (b + a);
double dum;
const double *px = &x[NUM_OF_POSITIVE_ZEROS - 1];
const double *pA = &A[NUM_OF_POSITIVE_ZEROS - 1];
for (; px >= x; pA--, px--) {
dum = c * *px;
integral += *pA * ( (*f)(d - dum,prms) + (*f)(d + dum,prms) );
}
return c * integral;
}
void Gauss_Legendre_Zeros_100pts( double zeros[] ) {
const double *px = &x[NUM_OF_POSITIVE_ZEROS - 1];
double *pz = &zeros[NUM_OF_ZEROS - 1];
for (; px >= x; px--) {
*(zeros++) = - *px;
*(pz--) = *px;
}
}
void Gauss_Legendre_Coefs_100pts( double coefs[] ) {
const double *pA = &A[NUM_OF_POSITIVE_ZEROS - 1];
double *pc = &coefs[NUM_OF_ZEROS - 1];
for (; pA >= A; pA--) {
*(coefs++) = *pA;
*(pc--) = *pA;
}
}
/***********************************************************************************************************************************************************************/
/********************************\\ Interpolation Function \\***********************************************************************************************************/
double Pm(double k)
{
if (k>=kmin && k<=kmax) return gsl_spline_eval (spline[1], k, acc[1]);
else return 0;
}
double Xim_interp(double s)
{
if (s>=smin && s<=smax-1) return gsl_spline_eval (spline[2], s, acc[2]);
else return 0;
}
double V12_interp(double s)
{
if (s>=smin && s<=smax-1) return gsl_spline_eval (spline[3], s, acc[3]);
else return 0;
}
double Psiper_interp(double s)
{
if (s>=smin && s<=smax-1) return gsl_spline_eval (spline[4], s, acc[4]);
else return 0;
}
double Psipar_interp(double s)
{
if (s>=smin && s<=smax-1) return gsl_spline_eval (spline[5], s, acc[5]);
else return 0;
}
double Xi_R_CLPT(double s)
{
if (s>=smin && s<=smax) return gsl_spline_eval (spline[6], s, acc[6])
+ f1*gsl_spline_eval (spline[7], s, acc[7])
+ f2*gsl_spline_eval (spline[8], s, acc[8])
+ f1*f1*gsl_spline_eval (spline[9], s, acc[9])
+ f1*f2*gsl_spline_eval (spline[10], s, acc[10])
+ f2*f2*gsl_spline_eval (spline[11], s, acc[11]);
else return 0;
}
double V12_CLPT(double s)
{
if (s>=smin && s<=smax) return gsl_spline_eval (spline[12], s, acc[12])
+ f1*gsl_spline_eval (spline[13], s, acc[13])
+ f2*gsl_spline_eval (spline[14], s, acc[14])
+ f1*f1*gsl_spline_eval (spline[15], s, acc[15])
+ f1*f2*gsl_spline_eval (spline[16], s, acc[16]);
else return 0;
}
double Sig_par_CLPT(double s)
{
if (s>=smin && s<= smax) return gsl_spline_eval (spline[17], s, acc[17])
+ f1*gsl_spline_eval (spline[18], s, acc[18])
+ f2*gsl_spline_eval (spline[19], s, acc[19])
+ f1*f1*gsl_spline_eval (spline[20], s, acc[20]);
else return 0;
}
double Sig_per_CLPT(double s)
{
if (s>=smin && s<=smax) return gsl_spline_eval (spline[21], s, acc[21])
+ f1*gsl_spline_eval (spline[22], s, acc[22])
+ f2*gsl_spline_eval (spline[23], s, acc[23])
+ f1*f1*gsl_spline_eval (spline[24], s, acc[24]);
else return 0;
}
/**********************************************************************************************************************************************************************/
/*************\\ Gaussian Function\\***********************************************************************************************************************************/
double gaus (double x, double moy, double var2)
{
return 1./(sqrt(2.*M_PI*var2))*exp(-pow((x-moy),2)/(2.*var2));
}
/**********************************************************************************************************************************************************************/
/*************\\Decomposition of s and r\\*****************************************************************************************************************************/
double spar (double s, double mu_s)
{
return s*mu_s;
}
double rperp (double s, double spar) // rp = sp (perp)
{
return sqrt(s*s-spar*spar);
}
double r_real(double rp, double rpar)
{
return sqrt(rp*rp+rpar*rpar);
}
double mu_r(double rpar, double r)
{
return rpar/r;
}
/***********************************************************************************************************************************************************************/
/***************\\ Sigma_8\\********************************************************************************************************************************************/
double fS8 (double k, void * params)
{
double x = k*8;
return Pm(k)*k*k*(sin(x)-x*cos(x))*(sin(x)-x*cos(x))/pow(x,6);
}
double S8 (void)
{
double result, error;
gsl_function F;
F.function = &fS8;
gsl_integration_cquad_workspace *w = gsl_integration_cquad_workspace_alloc(size);
gsl_integration_cquad(&F, smin, smax, 0, 1e-12, w, &result, &error, NULL);
gsl_integration_cquad_workspace_free(w);
return 9./(2.*M_PI*M_PI)*result;
}
/*********************************************************************************************************************************************************************/
/****************\\Normalisation of P_m\\*****************************************************************************************************************************/
double Pm_norm (double s)
{
return Pm(s)/sig8;
}
/***********************************************************************************************************************************************************************/
/*****************\\ V_12(r) Function\\*********************************************************************************************************************************/
//Decomposition of bessel function j1
double vsin (double k, void * params)
{
double alpha = *(double *) params;
return Pm_norm(k)*alpha/k;
}
double vcos (double k, void * params)
{
double alpha = *(double *) params;
return Pm_norm(k)*alpha;
}
double V12(double r)
{
if(r>=.1){
double result1, error1, result2, error2, alpha, alpha1, err;
if(r<1) err = 0.1;
else err= 0.1;
// Vsin calculation
alpha = 1./(r*r);
gsl_function F1;
F1.function = &vsin;
F1.params = α
gsl_integration_workspace *w1 = gsl_integration_workspace_alloc(size);
gsl_integration_workspace *w2 = gsl_integration_workspace_alloc(size);
gsl_integration_qawo_table *t1 = gsl_integration_qawo_table_alloc(r, lk, GSL_INTEG_SINE, size);
gsl_integration_qawf(&F1, kmin, err, limit, w1, w2, t1, &result1, &error1);
// Vcos calculation
alpha1 = 1./r;
gsl_function F2;
F2.function = &vcos;
F2.params = &alpha1;
gsl_integration_workspace *w3 = gsl_integration_workspace_alloc(size);
gsl_integration_workspace *w4 = gsl_integration_workspace_alloc(size);
gsl_integration_qawo_table *t2 = gsl_integration_qawo_table_alloc(r, lk, GSL_INTEG_COSINE, size);
gsl_integration_qawf(&F2, kmin, err, limit, w3, w4, t2, &result2, &error2);
gsl_integration_workspace_free(w1);
gsl_integration_workspace_free(w2);
gsl_integration_qawo_table_free(t1);
gsl_integration_workspace_free(w3);
gsl_integration_workspace_free(w4);
gsl_integration_qawo_table_free(t2);
return result2-result1;
}
else return 0;
}
/************************************************************************************************************************************************************************/
/*************\\Sigma_12(mu,r) functions\\*******************************************************************************************************************************/
// Sigma_v
double fsigmav(double k, void * params)
{
double alpha = *(double *) params;
return alpha*Pm_norm(k);
}
double Sigmav(void)
{
double result,error;
double alpha = 1./3.;
gsl_function F;
F.function = &fsigmav;
F.params = α
gsl_integration_workspace *w = gsl_integration_workspace_alloc(size);
gsl_integration_qag(&F, kmin, kmax, 0, 1e-5, limit, 6, w, &result, &error);
gsl_integration_workspace_free(w);
return result;
}
// Psiper(r)
//Decomposition of bessel function j1
double Psipersin(double k, void * params)
{
double alpha = *(double *) params;
return alpha*Pm_norm(k)/(pow(k,3));
}
double Psipercos(double k, void * params)
{
double alpha = *(double *) params;
return alpha*Pm_norm(k)/(k*k);
}
double Psiper(double r) // We adapt the error at lower scale to compute the integral
{
if (r>=0.8){
double err;
// for sin part
double result1,error1;
double alpha = 1./pow(r,3);
// for cos part
double result2,error2;
double alpha1 = 1./(r*r);
if(r<10) {
if (r<2.1) err = 10;
else err= 1;}
else err=0.5;
// Psipersin calculation
gsl_function F1;
F1.function = &Psipersin;
F1.params = α
gsl_integration_workspace *w1 = gsl_integration_workspace_alloc(size);
gsl_integration_workspace *w2 = gsl_integration_workspace_alloc(size);
gsl_integration_qawo_table *t1 = gsl_integration_qawo_table_alloc(r, lk, GSL_INTEG_SINE, size);
gsl_integration_qawf(&F1, kmin, err, limit, w1, w2, t1, &result1, &error1);
// Psipercos calculation
gsl_function F2;
F2.function = &Psipercos;
F2.params = &alpha1;
gsl_integration_workspace *w3 = gsl_integration_workspace_alloc(size);
gsl_integration_workspace *w4 = gsl_integration_workspace_alloc(size);
gsl_integration_qawo_table *t2 = gsl_integration_qawo_table_alloc(r, lk, GSL_INTEG_COSINE, size);
gsl_integration_qawf(&F2, kmin, err, limit, w3, w4, t2, &result2, &error2);
gsl_integration_workspace_free(w1);
gsl_integration_workspace_free(w2);
gsl_integration_qawo_table_free(t1);
gsl_integration_workspace_free(w3);
gsl_integration_workspace_free(w4);
gsl_integration_qawo_table_free(t2);
return (result1-result2);}
else return 0;
}
// Psipar(r)
double psiparf(double k, void * params)
{
double alpha = *(double *) params;
return alpha*Pm_norm(k)/k;
}
double Psipar(double r)
{
double result,error;
double alpha = 1./r;
gsl_function F;
F.function = &psiparf;
F.params = α
gsl_integration_workspace *w1 = gsl_integration_workspace_alloc(size);
gsl_integration_workspace *w2 = gsl_integration_workspace_alloc(size);
gsl_integration_qawo_table *t1 = gsl_integration_qawo_table_alloc(r, lk, GSL_INTEG_SINE, size);
gsl_integration_qawf(&F, kmin, 1e-1, limit, w1, w2, t1, &result, &error);
gsl_integration_workspace_free(w1);
gsl_integration_workspace_free(w2);
gsl_integration_qawo_table_free(t1);
return (result-2.*Psiper(r));
}
/********Sigma_12(mu,r)***************************************************************************************************************************************************/
double Sigma12 (double mu, double r, double sigv) // from linear (Gaussian streaming) model
{
return 2.*(sigv-mu*mu*Psipar_interp(r)-(1.-(mu*mu))*Psiper_interp(r));
}
double Sigma12_CLPT (double mu, double r) // from CLPT prediction
{
return (mu*mu*Sig_par_CLPT(r)+(1.-mu*mu)*Sig_per_CLPT(r))/(1.+Xi_R_CLPT(r))-27.;
}
/***********************************************************************************************************************************************************************/
/************\\Correlation function in real space\\*********************************************************************************************************************/
double fXim(double k, void * params)
{
double alpha = *(double *) params;
double f = alpha*Pm_norm(k)*k;
return f;
}
double Xim (double r)
{
double result, error;
double alpha = 1./(2.*M_PI*M_PI*r);
gsl_function F;
F.function = &fXim;
F.params = α
gsl_integration_workspace *w1 = gsl_integration_workspace_alloc(200);
gsl_integration_workspace *w2 = gsl_integration_workspace_alloc(200);
gsl_integration_qawo_table *t = gsl_integration_qawo_table_alloc(r, lk, GSL_INTEG_SINE, size);
gsl_integration_qawf(&F, kmin, 1e-3, 200, w1, w2, t, &result, &error);
gsl_integration_workspace_free(w1);
gsl_integration_workspace_free(w2);
gsl_integration_qawo_table_free(t);
return result;
}
/***********************************************************************************************************************************************************************/
/*************\\Correlation function in z-space\\***********************************************************************************************************************/
double fXis (double y, void *p)
{
struct my_f_params * params = (struct my_f_params *)p;
double spp = (params->a); // parallel component of s
double rp = (params->b); // perpendicular componant of s
double r = r_real(rp, y); // norm of r
double v = fg*b/(M_PI*M_PI)*V12_interp(r); // V_12(r)
double mu_r = y/r;
double x = spp-y;
double moy = mu_r*v; // average of the gaussian distribution
double var = pow(fg,2)/(2.*M_PI*M_PI)*Sigma12(mu_r,r,sigv); // Variance Sigma_12
if (var>0) return (1.+Xim_interp(r))*gaus(x, moy, var);
else return 0;
}
double Xis (double sp, double spi) //Compute in sperp, spar
{
struct my_f_params params = {spi, sp};
double result = Gauss_Legendre_Integration2_100pts(-200, 200, &fXis, ¶ms);
return result -1.;
}
/*********************************************************************************************************************************************************************/
/****************\\Correlation function in z-space for CLPT prediction\\**********************************************************************************************/
double fXis_CLPT (double y, void *p)
{
struct my_f_params * params = (struct my_f_params *)p;
double spp = (params->a);
double rp = (params->b);
double r = r_real(rp, y);
double v = fg*V12_CLPT(r)/(1.+Xi_R_CLPT(r));
double mu_r = y/r;
double x = spp-y;
double moy = mu_r*v;
double var = pow(fg,2)*Sigma12_CLPT(mu_r,r);
if (var>0) return (1.+Xi_R_CLPT(r))*gaus(x, moy, var);
else return 0;
}
double Xis_CLPT (double sp, double spi)
{
struct my_f_params params = {spi, sp};
double result = Gauss_Legendre_Integration2_100pts(-200, 200, &fXis_CLPT, ¶ms);
return result -1.;
}
/**********************************************************************************************************************************************************************/
/*********\\Legendre Multipole\\***************************************************************************************************************************************/
double fmultipole(double mu, void * p)
{
struct my_f_params * params = (struct my_f_params *)p;
double s = (params->a);
double l = (params->b);
double rp = s*sqrt(1-mu*mu); // Decomposition of S in spar (=spi) and sp=rp
double spi = s*mu;
double Xi_s= Xis(rp,spi);
return Xi_s*gsl_sf_legendre_Pl(l,mu);
}
double multipole(double s, double l)
{
double result;
struct my_f_params params = {s, l};
result = Gauss_Legendre_Integration2_100pts(-1, 1, &fmultipole, ¶ms);
return (2.*l+1.)/2.*result;
}
/********************************************************************************************************************************************************************/
/****************\\Legendre Multipole with CLPT prediction\\*********************************************************************************************************/
double fmultipole_CLPT(double mu, void * p)
{
struct my_f_params * params = (struct my_f_params *)p;
double s = (params->a);
double l = (params->b);
double rp = s*sqrt(1.-mu*mu);
double spi = s*mu; // Decomposition of S in spar (=spi) and sp=rp
double Xi_s= Xis_CLPT(rp,spi);
return Xi_s*gsl_sf_legendre_Pl(l,mu);
}
double multipole_CLPT(double s, double l)
{
double result;
struct my_f_params params = {s, l};
result = Gauss_Legendre_Integration2_100pts(-1, 1, &fmultipole_CLPT, ¶ms);
return (2.*l+1.)/2.*result;
}
/************************************************************************************************************************************************************************/
/***********\\ Interpolation \\*****************************************************************************************************************************/
void interpole(int n, char ficher[100],int vmax)
{
double T_x[vmax];
double T_y[vmax];
FILE* f;
int i = 0;
f =fopen(ficher, "r");
for(i=0; i < vmax; i++) fscanf(f, "%lf %lf\n", &T_x[i], &T_y[i]);
acc[n] = gsl_interp_accel_alloc ();
spline[n] = gsl_spline_alloc(gsl_interp_cspline, vmax);
gsl_spline_init (spline[n], T_x, T_y, vmax);
fclose(f);
}
void interpole_Xi()
{
FILE *fxi;
int i;
double Xi_x[val], Xi_f0[val], Xi_f1[val], Xi_f2[val], Xi_f1_2[val], Xi_f1_f2[val], Xi_f2_2[val];
fxi = fopen("data/Xi_r_CLPT.dat", "r");
for(i=0; i < val; i++) fscanf(fxi, "%lf %lf %lf %lf %lf %lf %lf\n",&Xi_x[i], &Xi_f0[i], &Xi_f1[i], &Xi_f2[i], &Xi_f1_2[i], &Xi_f1_f2[i], &Xi_f2_2[i]);
acc[6] = gsl_interp_accel_alloc ();
spline[6] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[6], Xi_x, Xi_f0, val);
acc[7] = gsl_interp_accel_alloc ();
spline[7] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[7], Xi_x, Xi_f1, val);
acc[8] = gsl_interp_accel_alloc ();
spline[8] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[8], Xi_x, Xi_f2, val);
acc[9] = gsl_interp_accel_alloc ();
spline[9] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[9], Xi_x, Xi_f1_2, val);
acc[10] = gsl_interp_accel_alloc ();
spline[10] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[10], Xi_x, Xi_f1_f2, val);
acc[11] = gsl_interp_accel_alloc ();
spline[11] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[11], Xi_x, Xi_f2_2, val);
fclose(fxi);
}
void interpole_V12()
{
FILE *fv12;
int i;
double V12_x[val], V12_f0[val], V12_f1[val], V12_f2[val], V12_f1_2[val], V12_f1_f2[val];
fv12 = fopen("data/V_12_CLPT.dat", "r");
for(i=0; i < val; i++) fscanf(fv12, "%lf %lf %lf %lf %lf %lf\n",&V12_x[i], &V12_f0[i], &V12_f1[i], &V12_f2[i], &V12_f1_2[i], &V12_f1_f2[i]);
acc[12] = gsl_interp_accel_alloc ();
spline[12] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[12], V12_x, V12_f0, val);
acc[13] = gsl_interp_accel_alloc ();
spline[13] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[13], V12_x, V12_f1, val);
acc[14] = gsl_interp_accel_alloc ();
spline[14] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[14], V12_x, V12_f2, val);
acc[15] = gsl_interp_accel_alloc ();
spline[15] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[15], V12_x, V12_f1_2, val);
acc[16] = gsl_interp_accel_alloc ();
spline[16] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[16], V12_x, V12_f1_f2, val);
fclose(fv12);
}
/*
void interpole_sigma()
{
int i, val =150;
double S_x[val], S_par[val], S_per[val];
FILE* fx;
fx = fopen("../../CLPT/Sigma.dat", "r");
for(i=0; i < val; i++) fscanf(fx, "%lf %lf %lf\n", &S_x[i], &S_par[i], &S_per[i]);
acc[8] = gsl_interp_accel_alloc ();
spline[8] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[8], S_x, S_par, val);
acc[9] = gsl_interp_accel_alloc ();
spline[9] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[9], S_x, S_per, val);
fclose(fx);
}*/
void interpole_sigma()
{
int i;
double S_x[val], S_par_f0[val], S_par_f1[val], S_par_f2[val], S_par_f1_2[val], S_per_f0[val], S_per_f1[val], S_per_f2[val], S_per_f1_2[val];
FILE* fsig;
fsig = fopen("data/Sigma_12_CLPT.dat", "r");
for(i=0; i<val; i++) fscanf(fsig, "%lf %lf %lf %lf %lf %lf %lf %lf %lf\n", &S_x[i], &S_par_f0[i], &S_par_f1[i], &S_par_f2[i], &S_par_f1_2[i], &S_per_f0[i], &S_per_f1[i], &S_per_f2[i], &S_per_f1_2[i]);
acc[17] = gsl_interp_accel_alloc ();
spline[17] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[17], S_x, S_par_f0, val);
acc[18] = gsl_interp_accel_alloc ();
spline[18] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[18], S_x, S_par_f1, val);
acc[19] = gsl_interp_accel_alloc ();
spline[19] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[19], S_x, S_par_f2, val);
acc[20] = gsl_interp_accel_alloc ();
spline[20] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[20], S_x, S_par_f1_2, val);
acc[21] = gsl_interp_accel_alloc ();
spline[21] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[21], S_x, S_per_f0, val);
acc[22] = gsl_interp_accel_alloc ();
spline[22] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[22], S_x, S_per_f1, val);
acc[23] = gsl_interp_accel_alloc ();
spline[23] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[23], S_x, S_per_f2, val);
acc[24] = gsl_interp_accel_alloc ();
spline[24] = gsl_spline_alloc(gsl_interp_cspline, val);
gsl_spline_init (spline[24], S_x, S_per_f1_2, val);
fclose(fsig);
}
/***********************************************************************************************************************************************************************/
/************\\Count the number of ligne in a file\\********************************************************************************************************************/
int compte(FILE *fichier)
{
int c;
int nLignes = 0;
int c2 = '\0';
while((c=fgetc(fichier)) != EOF){ if(c=='\n') nLignes++; c2 = c;}
if(c2 != '\n') nLignes++;
return nLignes;
}
/************************************************************************************************************************************************************************/
/******\\Write in a file\\***********************************************************************************************************************************************/
void write(char f[], double func(double))
{
double spi;
FILE* fi;
fi = fopen(f,"w+");
for(spi=smin; spi<smax; spi+=0.5) fprintf(fi,"%le %le\n", spi, func(spi));
fclose(fi);
}
/******************************************************************************************************************************************************************/
/***************\\MAIN FUNCTION\\**********************************************************************************************************************************/
int main (int argc, char *argv[])
{
double spi,sp,li;
int i, nLignes;
FILE *fi, *par, *ps, *f;
char file[BUFSIZ];
/*
sig_shift = 0;
b = 1;
fg = 0.820165;
f1 = atof(argv[1]);
f2 = atof(argv[2]);
smin=2.5;
smax=158;
val=160;
// printf("f1=%lf f2=%lf\n",f1,f2);
// char* file = "power_spec_EBOSS.txt";*/
par = fopen(argv[1],"r");
// Check parameter file
if (argc ==2 && par!=0) EXIT_SUCCESS;
else {
printf("Wrong parameter file\n");
return EXIT_FAILURE;
}
// Read parameter file
fscanf(par,"%*s %lf\n", &smin);
fscanf(par,"%*s %lf\n", &smax);
fscanf(par,"%*s %lf\n", &b);
fscanf(par,"%*s %lf\n", &fg);
fscanf(par,"%*s %lf\n", &f1);
fscanf(par,"%*s %lf\n", &f2);
fscanf(par,"%*s %lf\n", &sig_shift);
fscanf(par,"%*s %s\n",file);
//Check smin and smax
li = (smax-smin)/0.5;
if (li<0){
printf("wrong parameters smin/smax");
return EXIT_FAILURE;
}
// Count number of lines
ps = fopen(file, "r");
if (ps!=0){
nLignes = compte(ps);
}
else {
printf("Error openning power spectrum file.\n");
return 1;
}
// Read kmin and kmax
rewind(ps);
kmin=1e30;
kmax=0;
for(i=0; i < nLignes; i++) {
double va;
fscanf(ps, "%lf %*f\n", &va);
if (va<kmin) kmin=va;
if (va>kmax) kmax=va;
}
fclose(ps);
lk = kmax-kmin;
// Interpolation of power spectrum file
interpole(1,file, nLignes);
sig8=1.;
sigv = Sigmav();
// printf("s8=%lf\n",sig8);
// Compute and save functions in text files
write("data/Xim.dat",Xim);
write("data/V12.dat",V12);
write("data/Psiper.dat",Psiper);
write("data/Psipar.dat",Psipar);
interpole(2,"data/Xim.dat", li);
interpole(3,"data/V12.dat", li);
interpole(4,"data/Psiper.dat", li);
interpole(5,"data/Psipar.dat", li);
interpole_Xi();
interpole_V12();
interpole_sigma();
// Multipoles calculation
fi = fopen("data/multipole.dat","w+"); ;
printf("Calcul des multipoles\n");
for(spi=smin; spi<smax; spi+=1){
double xi0=sig8*multipole(spi,0);
double xi2=sig8*multipole(spi,2);
double xi4=sig8*multipole(spi,4);
fprintf(fi,"%le %le %le %le\n", spi, xi0, xi2, xi4);
}
fclose(fi);
fi = fopen("data/multipole_CLPT.dat","w+");
printf("Calcul des multipoles CLPT\n");
for(spi=smin; spi<smax; spi+=1){
double xi0=multipole_CLPT(spi,0);
double xi2=multipole_CLPT(spi,2);
double xi4=multipole_CLPT(spi,4);
//printf("%lf %lf %lf ", spi, xi0, xi2);
fprintf(fi,"%lf %lf %lf %lf\n", spi, xi0, xi2,xi4);
}
fclose(fi);
//Correlation function Xi_s(spar,sper)
f = fopen("data/Xi_s.dat","w+");
printf("Calcul de Xis\n");
for(spi=smin; spi<smax; spi+=0.1){
for(sp=smin; sp<smax; sp+=0.1){
double V=Xis(sp,spi);
fprintf(f,"%le %le %le\n",sp, spi, V);
}
}
fclose(f);
f = fopen("data/Xi_s_CLPT.dat","w+");
printf("Calcul de Xis_CLPT\n");
for(spi=smin; spi<smax; spi+=0.1){
for(sp=smin; sp<smax; sp+=0.1){
double V=Xis_CLPT(sp,spi);
fprintf(f,"%le %le %le\n",sp, spi, V);
}
}
fclose(f);
for (i=0; i<25; i++){
gsl_spline_free (spline[i]);
gsl_interp_accel_free (acc[i]);
}
return 0;
}
| {
"alphanum_fraction": 0.524865987,
"avg_line_length": 37.180875576,
"ext": "c",
"hexsha": "b1378da78315290cc1aa23d2b77ca0698c3fbb52",
"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": "39f2422f922b007351ba94ba69d05b87cc6ec9a0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "antoine-rocher/Master-2-internship",
"max_forks_repo_path": "Code_RSD_GS.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "39f2422f922b007351ba94ba69d05b87cc6ec9a0",
"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": "antoine-rocher/Master-2-internship",
"max_issues_repo_path": "Code_RSD_GS.c",
"max_line_length": 201,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "39f2422f922b007351ba94ba69d05b87cc6ec9a0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "antoine-rocher/Master-2-internship",
"max_stars_repo_path": "Code_RSD_GS.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-10T10:33:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-16T14:04:45.000Z",
"num_tokens": 9379,
"size": 32273
} |
/*
* parameters.h
* Spike
*
* Created by Ben Evans on 18/08/2008.
* Copyright 2008 University of Oxford. All rights reserved.
*
*/
#ifndef _PARAMETERS_H
#define _PARAMETERS_H
#include <stdbool.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_version.h>
typedef int tstep; // Signed to allow spikeTimes[0] = -BIG //long long
typedef unsigned char uchar;
struct SIMULATION{
bool Xgrid;
tstep tally;
tstep ptTS;
tstep trainTS;
tstep testTS;
tstep totTS;
float minTau;
double start;
double elapsed;
double realSecPerSimSec;
} SIM;
typedef struct DIMENSIONS {
int nRows;
int nCols;
int nFilt;
} DIM;
//extern SIMULATION SIM;
/*typedef enum {
Off,
//Uniform,
Gaussian
} NOISE;*/
typedef enum {
MinD,
ConstD,
UniformD,
GaussD,
SOMD
} DELAY;
typedef enum {
//Zero,
Constant, // Zero set using appropriate Dg modifier
Uniform,
Gaussian,
SOM
} INITIALISATION;
typedef enum {
None,
MaintainLength,
MaintainSum
} NORMALISATION;
/********************** Main Network Parmeters *************************/
// Update read_parameters and defaults.m when a new parameter is added
typedef struct {
// Simulation
float DT;
bool initialised; // Internal
int loops;
bool pretrain;// = true;
bool train;// = true;
bool priorPhases;
bool isolateEfE;
bool trainPause;
bool noise; // int
float noiseScale;
float SigmaE;
float SigmaI;
NORMALISATION normalise;
int nRecordsPL;// = 0;
int nRecords;
int * vRecords;
//float TotalTime;
float MaxTime;
float EpochTime;
float TestTime;
int EpochMS;
int TestMS;
int TotalMS;
int RecordMS;
//tstep TotalTS;
int TSperMS;
int spkBuffer;
//int inpSpkBuff;
bool printConnections;
bool saveInputSpikes;
bool probConnect;
bool loadWeights;
// Stimuli
char * imgDir;
char * imgList;
bool randStimOrder;// = true;
bool randTransOrder;
bool randTransDirection;
bool interleaveTrans;
bool localRep;// = true;
float current;// = 1.25e-9;
float currentSpread;
bool loadStimuli;
bool stimGroups;
int nBG; // # shared between groups
int nWG; // # specific within each group
int nGroups;
int nStimuli;
int nTransPS;
bool newTestSet;
int M; // Degree of training i.e. train with M of the NCK
int K; // Number of stimuli presented simultaneously
//int nTestGroups;
int nTestStimuli;
int nTestTransPS;
float transP_Train;
float transP_Test;
int shift;
int nFiringNeurons;
float a; // Sparseness of stimuli
bool useFilteredImages;
bool gabor;
int nScales;
int * vScales;
int nOrients;
int * vOrients;
int nPhases;
int * vPhases;
int sInputs;
int nRows;
int nCols;
// Network
int nLayers;// = 2;
int nWLayers;
bool inputInhib;
int nExcit;// = 120;
int * vExcit;
int LvExcit;
int nSynEfE;
float * pCnxEfE;
int LpEfE;
int nSynElE;
float * pCnxElE;
int LpElE;
int nSynIE;
float * pCnxIE;
int LpIE;
int nInhib;// = 40;
float rInhib;
int * vInhib;
int LvInhib;
int nSynEI;
float * pCnxEI;
int LpEI;
int nSynII;
float * pCnxII;
int LpII;
INITIALISATION initEfE;
float iEfE;
bool axonDelay; //DELAY axonDelay;
DELAY delayEfE;
DELAY delayElE;
DELAY delayEI;
float d_const;
float d_min;
float d_max;
float d_mean;
float d_sd;
float spatialScale;
float condSpeed;
float maxDelay;
bool SOM;
bool SOMinput;
float SOMsigE;
float SOMsigI;
float SOMclip;
//float SOMstrE;
//float SOMstrI;
bool trainEfE; // Internal var modified through isolateEfE
bool trainElE;
INITIALISATION initElE;
float iElE;
DIM * layDim;
int * vSquare;
// Cell bodies
float capE;// = 2.0e-10;
float capI;// = 10.0e-12;
float gLeakE;// = 10.0e-9;
float gLeakI;// = 5.0e-9;
float VrestE;
float VrestI;
float VhyperE;
float VhyperI;
float ThreshE;
float ThreshI;
float VrevE;
float VrevI;
float refract;// = 0.002
bool adaptation;
float alphaCa;
float tauCa;
float gAHP;
float VK;
// Synapses (afferent axons)
bool noSTDPdelay;
float alphaC;// = 0.5;
float tauC;// = 0.005;
float alphaD;// = 0.5;
float tauD;// = 0.009;
float learnR;// = 0.1;
float DgEfE; //modEf; // alter the strength of Excit f-f synapses
//float tauEfE;// tauEE = 0.01;
float DgElE;//Dg_ElE
//float tauElE;
float tauEE;
float DgIE;//Dg_IE = 0.5;
float tauIE;// = 0.001
float DgEI;//Dg_EI = 0.5;
float tauEI;// = 0.001;
float DgII;//Dg_II = 0.5;
float tauII;// = 0.001;
float gMax;// = 48.0e-10;
} PARAMS;
//PARAMS * mp;
extern PARAMS * mp;
extern gsl_rng * mSeed;
extern gsl_rng ** states;
#endif
| {
"alphanum_fraction": 0.6884332516,
"avg_line_length": 18.0200803213,
"ext": "h",
"hexsha": "0e55ed07cead0141abf816bf42b6f5527a2ce5ba",
"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": "23f537bfa3605a5d1100b51eea7160d92d43be58",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "wincle626/SpikingNeuralNetworkSimulatorXOS",
"max_forks_repo_path": "_Spike/parameters.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "23f537bfa3605a5d1100b51eea7160d92d43be58",
"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": "wincle626/SpikingNeuralNetworkSimulatorXOS",
"max_issues_repo_path": "_Spike/parameters.h",
"max_line_length": 73,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "23f537bfa3605a5d1100b51eea7160d92d43be58",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "wincle626/SpikingNeuralNetworkSimulatorXOS",
"max_stars_repo_path": "_Spike/parameters.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1423,
"size": 4487
} |
#pragma once
#ifndef _NOGSL
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#else
#include "FakeGSL.h"
#endif
#include <limits>
#include <math.h>
#include <vector>
#include "BasicError.h"
using namespace std;
class GradUtil {
public:
static int counter;
static constexpr double MAXVAL = 1e30;
static constexpr double MINVAL = -1e30;
static constexpr double PI = 3.1415926535897;
static double ALPHA;
static double BETA;
static gsl_vector* tmp;
static gsl_vector* tmp1;
static gsl_vector* tmp2;
static gsl_vector* tmp3;
static gsl_vector* tmpT; // used for internal computations in mult, div - don't use it anywhere else
static void allocateTempVectors(int size);
static void clearTempVectors();
static double findMin(double val1, double val2, gsl_vector* grad1, gsl_vector* grad2, gsl_vector* l);
static double findMin(const vector<double>& vals, const vector<gsl_vector*>& grads, gsl_vector* l);
static double findMax(double val1, double val2, gsl_vector* grad1, gsl_vector* grad2, gsl_vector* h);
static double findMax(const vector<double>& vals, const vector<gsl_vector*>& grads, gsl_vector* h);
static double findMax(const vector<double>& vals);
static double sigmoid(double d, gsl_vector* grads, gsl_vector* out);
static double sigmoid(double d);
static void default_grad(gsl_vector* out);
static double softMinMax(const vector<double>& vals, const vector<gsl_vector*>& grads, gsl_vector* l, double alpha, double t);
static double softMinMax(const vector<double>& vals, double alpha, double t);
static void compute_plus_grad(gsl_vector* mgrads, gsl_vector* fgrads, gsl_vector* out);
static void compute_mult_grad(double mval, double fval, gsl_vector* mgrads, gsl_vector* fgrads, gsl_vector* out);
static void compute_div_grad(double mval, double fval, gsl_vector* mgrads, gsl_vector* fgrads, gsl_vector* out);
static void compute_neg_grad(gsl_vector* mgrads, gsl_vector* out);
static void compute_square_grad(double mval, gsl_vector* mgrads, gsl_vector* out);
static void compute_arctan_grad(double mval, gsl_vector* mgrads, gsl_vector* out);
static void compute_sin_grad(double mval, gsl_vector* mgrads, gsl_vector* out);
static void compute_cos_grad(double mval, gsl_vector* mgrads, gsl_vector* out);
static void compute_tan_grad(double mval, gsl_vector* mgrads, gsl_vector* out);
static void compute_sqrt_grad(double mval, gsl_vector* mgrads, gsl_vector* out);
static void compute_exp_grad(double mval, gsl_vector* mgrads, gsl_vector* out);
static bool inLimit(double v) {
if (!isfinite(v)) return false;
if (v > MAXVAL || v < MINVAL) return false;
return true;
}
static inline double bound(double v) {
if (v < MAXVAL) {
if (v > MINVAL) {
return v;
}
else {
return MINVAL;
}
}
else {
return MAXVAL;
}
/*
if (!inLimit(v)) {
//cout << "Bound reached" << endl;
return v > 0 ? MAXVAL : MINVAL;
} else {
return v;
}
*/
}
};
| {
"alphanum_fraction": 0.7345491388,
"avg_line_length": 31.8387096774,
"ext": "h",
"hexsha": "ab4f2f6e7fad02e8f607b9a3b151f669cf292182",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z",
"max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_forks_repo_licenses": [
"X11"
],
"max_forks_repo_name": "natebragg/sketch-backend",
"max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/Utils/GradUtil.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z",
"max_issues_repo_licenses": [
"X11"
],
"max_issues_repo_name": "natebragg/sketch-backend",
"max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/Utils/GradUtil.h",
"max_line_length": 127,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_stars_repo_licenses": [
"X11"
],
"max_stars_repo_name": "natebragg/sketch-backend",
"max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/Utils/GradUtil.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z",
"num_tokens": 791,
"size": 2961
} |
/*
Copyright (c) 2015, Patrick Weltevrede
All rights reserved.
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.
3. Neither the name of the copyright holder nor the names of its contributors may 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_sort.h>
#include "psrsalsa.h"
typedef struct {
datafile_definition datafile;
double f2_min, f2_max;
double f3_min, f3_max;
double P3IntegrateLow, P3IntegrateHigh;
int SelectP3Integrate;
double oversaturize;
}twodfs_def;
typedef struct {
char *textside;
double fl_min, fl_max;
double dl;
double LRegionLow, LRegionHigh;
int SelectLRegion;
int doFlip;
int ExtraVerticalMaximaSkip;
int noside;
int overlaypp;
int inside;
int noylabels;
int noxlabels;
int notop;
int autooversaturizel, autooversaturize2, autozoomP2;
float labelscale, titlescale;
double oversaturizel;
double Imin, Imax;
double scaleFig_x, scaleFig_y;
int plot_xlabel, plot_ylabel, plot_ylabeltop;
int nomain;
int showwedge;
int showwedge_max;
int normaliseSide;
int nointegrateNumbers;
int intflip;
int usephase;
int lineColour;
int normalise_spectra;
int SelectP3Region;
}plotoptions_def;
int loadLRFS(datafile_definition *lrfs, int extprefix, int longsnap, int argc, char **argv, plotoptions_def *plotoptions, verbose_definition verbose);
int load2dfs(twodfs_def *twodfs_allinfo, datafile_definition AverageProfile, int file_number, int extprefix, int altname, int argc, char **argv, plotoptions_def plotoptions, verbose_definition verbose);
void Plot2dfs(twodfs_def twodfs_allinfo, twodfs_def twodfs2_allinfo, datafile_definition AverageProfile, int twodfsonly, int Number, char *title, plotoptions_def plotoptions, verbose_definition verbose);
void PlotLRFS(datafile_definition lrfs, datafile_definition AverageProfile, twodfs_def twodfs_allinfo, char *title, plotoptions_def plotoptions, verbose_definition verbose);
int loadHeaderPulseStack(datafile_definition *AverageProfile, datafile_definition lrfs, double *period, int type_of_plots, int argc, char **argv, verbose_definition verbose);
void autozoomP2(twodfs_def *twodfs_allinfo, datafile_definition AverageProfile, plotoptions_def plotoptions, verbose_definition verbose);
int main(int argc, char **argv)
{
int i, j, xi, SelectP2Region, LoadTwo, NrSelectedOverSaturize;
int file_number, ImaxSet, IminSet, type_of_plots, maxSubpulsePhaseSet, minSubpulsePhaseSet, do_phase_slope, extprefix;
char PlotDevice[100], filename[1000], txt[1000];
int title_index, Load2dfs, LoadLRFS, plotvariance, plotmodindex, ok_flag, altProf, lineStyle, ret, longsnap;
double P3RegionLow, P3RegionHigh, maxSubpulsePhase, minSubpulsePhase;
float I, x, profilescale;
float maxvalue_mod, maxvalue_stddev, maxsigma_stddev, maxsigma_mod, ImaxValue, IminValue, phase_slope_g, phase_slope_o;
FILE *fout_ascii;
long k;
datafile_definition subpulseTrackProfile, subpulseTrackProfileErr, subpulseAmpProfile;
datafile_definition AverageProfile, VarianceProfile, ModProfile, VarianceProfileErr, ModProfileErr, lrfs;
verbose_definition noverbose;
psrsalsaApplication application;
plotoptions_def plotoptions;
twodfs_def twodfs_allinfo, twodfs2_allinfo;
initApplication(&application, "pspecFig", "");
type_of_plots = 0;
file_number = 1;
plotoptions.scaleFig_x = 1;
plotoptions.scaleFig_y = 1;
do_phase_slope = 0;
plotoptions.autooversaturizel = 0;
plotoptions.autooversaturize2 = 0;
plotoptions.autozoomP2 = 0;
extprefix = 0;
longsnap = 0;
if(argc < 2) {
printf("Program to plot some of the pspec output\n\nUsage: pspecFig [options] stack_file (i.e. the name of the pulse stack that has been processed by pspec). By default the profile/modulation index/standard deviation profile/lrfs/2dfs are combined in a single plot (mode A). When -phaseplot is specified, a plot of the profile/subpulse amplitude and subpulse phase is produced (mode B).\n\n");
printf("Where optional options are:\n\n");
printf("General options:\n");
printf("-headerlist Show options of the -header option.\n");
printf("-header Change this header parameter.\n");
printf(" Example -header 'name J0123+4567'\n");
printf("-v Verbose mode (to get a better idea what is happening)\n");
printf("-debug Enable more output (where implemented)\n");
printf("-nocounters Don't show counters etc (useful when generating log files)\n");
printf("-phaseplot Enable mode B operation, see above.\n");
printf("\nGeneral file/panel options:\n");
printf("-altProf Load this alternative .profile file (generated by pspec).\n");
printf(" Useful if profile/modindex/stddev curves are calculated from\n");
printf(" a different file than the spectra.\n");
printf("-notop Don't show top plot\n");
printf("\nMode A specific file/panel options:\n");
printf("-2 Load two 2dfs's corresponding to two pulse longitude ranges\n");
printf("-2dfsnr Override 2dfs file number of first 2dfs. Default is %d.\n", file_number);
printf("-nolrfs Do not load lrfs\n");
printf("-no2dfs Do not load 2dfs's\n");
printf("-noside Don't show side panels\n");
printf("-normspectra Normalise the spectra (peak value=1)\n");
printf("-normside Normalise the side panels (peak value=1)\n");
printf("\nGeneral range options:\n");
printf("-Imax Set maximum value of the y-range of the top plot\n");
printf("-Imin Set minimum value of the y-range of the top plot\n");
printf("-long \"low high\" Set horizontal range shown lrfs/profile.\n");
printf("-phase Use pulse longitude in phase rather than degrees.\n");
printf("-dlong Shift lrfs/profile by this amount of degrees or phase.\n");
printf("\nMode A specific range options:\n");
printf("-p3 \"low high\" Set vertical range shown in lrfs/2dfs in cpp.\n");
printf("-p2 \"low high\" Set horizontal range as shown in 2dfs (can use this option\n");
printf(" twice if -2 is used) in cpp.\n");
printf("-int \"low high\" Select vertical integration range in 2dfs in cpp\n");
printf(" (affects the side panels, can be use twice if -2 is used).\n");
printf("-modsigma Set minimum significance for the modulation index (def. is 3).\n");
printf("-stddevsigma Same for the stddev values (default is 3).\n");
printf("-modmax Set the max allowed value for the modulation index\n");
printf(" (other values are ignored).\n");
printf("-stddevmax Same for the stddev values\n");
printf("\nMode B specific range options:\n");
printf("-spmax Set maximum value of the y-range of the subpulse phase plot\n");
printf("-spmin Set minimum value of the y-range of the subpulse phase plot\n");
printf("\nOther graphics options:\n");
printf("-device \"...\" Plot device\n");
printf("-inside Place tick marks inside\n");
printf("-labelscale Set size of labels (default is 1)\n");
printf("-titlescale Set size of title (default is 1), but -labalscale affects size as well.\n");
printf("-noylabels Don't show ylabels\n");
printf("-linestyle Set the PGPLOT line style of the pulse profile\n");
printf("-linecolor Set the PGPLOT line color of the pulse profile\n");
printf("-scalefig \"x y\" Scale size of panel with factors x and y\n");
printf("-title Set the title\n");
printf("-ytop Show y-label of top plot\n");
printf("\nMode A specific graphics options:\n");
printf("-intflip Add a flipped version of the vertical integration of the 2dfs\n");
printf("-intnrs Show nrs along side panels axis, instead of just a tick\n");
printf("-scalel scale The values in the lrfs are boosted by factor scale, resulting\n");
printf(" in clipping, which can highlight weaker features.\n");
printf("-scale2 scale As -scalel, but for 2dfs instead of lrfs.\n");
printf(" When this option is used twice, the 2nd time the\n");
printf(" option is used applies to the second 2dfs shown.\n");
printf("-scalep Scale profile by this factor\n");
printf("-noflip Do not flip 2DFS horizontally. If specified positive drift\n");
printf(" corresponds to power in the negative side of the diagram.\n");
printf("-overlay Overlay pulse profile over LRFS\n");
printf("-noxlabels Don't show xlabels on 2dfs bottom integration panel.\n");
printf("-nomod Do not plot a modulation index profile\n");
printf("-nostddev Do not plot a standard deviation profile\n");
printf("-showwedge Plot an annotated wedge to show color scale\n");
printf("-showwedge_showmax Plot a label indicating the maximum value in the data.\n");
printf(" With the -scalel or -scale2 option this is not necessarily\n");
printf(" the maximum of the colour scale.\n");
printf("-textside Set the text printed in top left corner of the graph\n");
printf("-xlabel Show x-label of LRFS and 2DFS in cpp\n");
printf("-xlabel2 Show x-label of LRFS and 2DFS in P0/P2\n");
printf("-xlabel3 Show x-label of LRFS and 2DFS in P/P2\n");
printf("-ylabel Show y-label of LRFS in cpp\n");
printf("-ylabel2 Show y-label of LRFS in P0/P3\n");
printf("-ylabel3 Show y-label of LRFS in P/P3\n");
printf("-s Skip the specified number of P3 bins when determining\n");
printf(" the range in left-hand side integrations panels. By default\n");
printf(" the first bin is skipped.\n");
printf("\nMode B specific graphics options:\n");
printf("-noflip Do not change sign of subpulse phase. If specified positive\n");
printf(" drift corresponds to a decrease subpulse phase as function of\n");
printf(" pulse longitude.\n");
printf("-xlabel Show x-label in pulse longitude\n");
printf("-ylabel Show y-label in subpulse phase\n");
printf("-phaseslope \"g o\" In the subpulse phase plot, add a line with gradient g (in deg\n");
printf(" per deg) and offset o in deg.\n");
printf("\n");
printf("Please use the appropriate citation when using results of this software in your publications:\n\n");
printf("More information about the lrfs/2dfs/modulation index can be found in:\n");
printf(" - Weltevrede et al. 2006, A&A, 445, 243\n");
printf(" - Weltevrede et al. 2007, A&A, 469, 607\n");
printf("More information about bootstrap/subpulse phase track & amplitude can be found in:\n");
printf(" - Weltevrede et al. 2012, MNRAS, 424, 843\n\n");
printCitationInfo();
terminateApplication(&application);
return 0;
}
plotoptions.plot_ylabeltop = 0;
plotoptions.nomain = 0;
plotoptions.SelectP3Region = 0;
SelectP2Region = 0;
plotoptions.SelectLRegion = 0;
twodfs_allinfo.SelectP3Integrate = 0;
twodfs2_allinfo.SelectP3Integrate = 0;
LoadTwo = 0;
strcpy(PlotDevice, "?");
twodfs_allinfo.oversaturize = 1;
twodfs2_allinfo.oversaturize = 1;
plotoptions.oversaturizel = 1;
NrSelectedOverSaturize = 0;
maxvalue_mod = -1;
maxsigma_mod = 3;
maxvalue_stddev = -1;
maxsigma_stddev = 3;
title_index = -1;
plotoptions.textside = NULL;
plotoptions.doFlip = 1;
plotoptions.ExtraVerticalMaximaSkip = 1;
Load2dfs = 1;
LoadLRFS = 1;
plotvariance = 1;
plotmodindex = 1;
profilescale = 1;
plotoptions.plot_xlabel = 0;
plotoptions.plot_ylabel = 0;
plotoptions.notop = 0;
plotoptions.noside = 0;
plotoptions.overlaypp = 0;
plotoptions.inside = 0;
plotoptions.labelscale = 1.0;
plotoptions.titlescale = 1.0;
plotoptions.noylabels = 0;
plotoptions.noxlabels = 0;
altProf = 0;
plotoptions.dl = 0;
ImaxSet = 0;
IminSet = 0;
lineStyle = 1;
plotoptions.lineColour = 1;
maxSubpulsePhaseSet = 0;
minSubpulsePhaseSet = 0;
maxSubpulsePhase = 0;
minSubpulsePhase = 0;
plotoptions.showwedge = 0;
plotoptions.showwedge_max = 0;
plotoptions.normalise_spectra = 0;
plotoptions.normaliseSide = 0;
plotoptions.nointegrateNumbers = 1;
plotoptions.intflip = 0;
plotoptions.usephase = 0;
twodfs_allinfo.f2_min = 0.0;
twodfs_allinfo.f2_max = 0.0;
twodfs2_allinfo.f2_min = 0.0;
twodfs2_allinfo.f2_max = 0.0;
for(i = 1; i < argc; i++) {
if(strcmp(argv[i], "-headerlist") == 0) {
printHeaderCommandlineOptions(stdout);
terminateApplication(&application);
return 0;
}
}
int argclast;
argclast = argc-1;
if(argv[argc-1][0] == '-')
argclast += 1;
for(i = 1; i < argclast; i++) {
if(strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "-D") == 0 || strcmp(argv[i], "-device") == 0 || strcmp(argv[i], "-dev") == 0) {
strcpy(PlotDevice, argv[i+1]);
i++;
}else if(strcmp(argv[i], "-v") == 0) {
application.verbose_state.verbose = 1;
}else if(strcmp(argv[i], "-phaseplot") == 0) {
type_of_plots = 1;
}else if(strcmp(argv[i], "-debug") == 0) {
application.verbose_state.debug = 1;
}else if(strcmp(argv[i], "-nocounters") == 0) {
application.verbose_state.nocounters = 1;
}else if(strcmp(argv[i], "-xlabel") == 0
) {
plotoptions.plot_xlabel = 1;
}else if(strcmp(argv[i], "-xlabel2") == 0
) {
plotoptions.plot_xlabel = 2;
}else if(strcmp(argv[i], "-xlabel3") == 0
) {
plotoptions.plot_xlabel = 3;
}else if(strcmp(argv[i], "-ylabel") == 0
) {
plotoptions.plot_ylabel = 1;
}else if(strcmp(argv[i], "-ylabel2") == 0
) {
plotoptions.plot_ylabel = 2;
}else if(strcmp(argv[i], "-ylabel3") == 0
) {
plotoptions.plot_ylabel = 3;
}else if(strcmp(argv[i], "-nolrfs") == 0
) {
LoadLRFS = 0;
}else if(strcmp(argv[i], "-2") == 0) {
LoadTwo = 1;
}else if(strcmp(argv[i], "-no2dfs") == 0
) {
Load2dfs = 0;
}else if(strcmp(argv[i], "-inside") == 0) {
plotoptions.inside = 1;
}else if(strcmp(argv[i], "-nostddev") == 0
) {
plotvariance = 0;
}else if(strcmp(argv[i], "-nomod") == 0
) {
plotmodindex = 0;
}else if(strcmp(argv[i], "-f") == 0 || strcmp(argv[i], "-noflip") == 0) {
plotoptions.doFlip = 0;
}else if(strcmp(argv[i], "-notop") == 0) {
plotoptions.notop = 1;
}else if(strcmp(argv[i], "-noside") == 0) {
plotoptions.noside = 1;
}else if(strcmp(argv[i], "-nomain") == 0) {
plotoptions.nomain = 1;
}else if(strcmp(argv[i], "-overlay") == 0) {
plotoptions.overlaypp = 1;
}else if(strcmp(argv[i], "-noylabels") == 0) {
plotoptions.noylabels = 1;
}else if(strcmp(argv[i], "-noxlabels") == 0) {
plotoptions.noxlabels = 1;
}else if(strcmp(argv[i], "-showwedge") == 0) {
plotoptions.showwedge = 1;
}else if(strcmp(argv[i], "-showwedge_showmax") == 0) {
plotoptions.showwedge_max = 1;
}else if(strcmp(argv[i], "-normspectra") == 0) {
plotoptions.normalise_spectra = 1;
}else if(strcmp(argv[i], "-normside") == 0) {
plotoptions.normaliseSide = 1;
}else if(strcmp(argv[i], "-intnrs") == 0) {
plotoptions.nointegrateNumbers = 0;
}else if(strcmp(argv[i], "-intflip") == 0) {
plotoptions.intflip = 1;
}else if(strcmp(argv[i], "-phase") == 0) {
plotoptions.usephase = 1;
}else if(strcmp(argv[i], "-linestyle") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%d", &lineStyle, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-linecolor") == 0 || strcmp(argv[i], "-linecolour") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%d", &(plotoptions.lineColour), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-scalep") == 0
) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%f", &profilescale, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-dlong") == 0 || strcmp(argv[i], "-dl") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf", &(plotoptions.dl), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-labelscale") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%f", &(plotoptions.labelscale), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-titlescale") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%f", &(plotoptions.titlescale), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-Imax") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%f", &ImaxValue, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
ImaxSet = 1;
i++;
}else if(strcmp(argv[i], "-Imin") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%f", &IminValue, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
IminSet = 1;
i++;
}else if(strcmp(argv[i], "-spmax") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf", &maxSubpulsePhase, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
maxSubpulsePhaseSet = 1;
i++;
}else if(strcmp(argv[i], "-spmin") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf", &minSubpulsePhase, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
minSubpulsePhaseSet = 1;
i++;
}else if(strcmp(argv[i], "-header") == 0) {
i++;
}else if(strcmp(argv[i], "-altProf") == 0) {
altProf = i+1;
i++;
}else if(strcmp(argv[i], "-p3") == 0) {
plotoptions.SelectP3Region = 1;
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf %lf", &P3RegionLow, &P3RegionHigh, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-p2") == 0) {
if(SelectP2Region == 0) {
SelectP2Region = 1;
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf %lf", &(twodfs_allinfo.f2_min), &(twodfs_allinfo.f2_max), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
twodfs2_allinfo.f2_min = twodfs_allinfo.f2_min;
twodfs2_allinfo.f2_max = twodfs_allinfo.f2_max;
}else {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf %lf", &(twodfs2_allinfo.f2_min), &(twodfs2_allinfo.f2_max), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
}
i++;
}else if(strcmp(argv[i], "-long") == 0 || strcmp(argv[i], "-l") == 0) {
plotoptions.SelectLRegion = 1;
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf %lf", &(plotoptions.LRegionLow), &(plotoptions.LRegionHigh), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-phaseslope") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%f %f", &phase_slope_g, &phase_slope_o, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
do_phase_slope = 1;
i++;
}else if(strcmp(argv[i], "-scalel") == 0
) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf", &(plotoptions.oversaturizel), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-scale2") == 0
) {
if(NrSelectedOverSaturize == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf", &(twodfs_allinfo.oversaturize), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
twodfs2_allinfo.oversaturize = twodfs_allinfo.oversaturize;
NrSelectedOverSaturize = 1;
}else {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf", &(twodfs2_allinfo.oversaturize), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
}
i++;
}else if(strcmp(argv[i], "-modsigma") == 0
) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0,-1, "%f", &maxsigma_mod, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-stddevsigma") == 0
) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%f", &maxsigma_stddev, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-modmax") == 0
) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%f", &maxvalue_mod, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-stddevmax") == 0
) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%f", &maxvalue_stddev, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-s") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%d", &(plotoptions.ExtraVerticalMaximaSkip), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-title") == 0
) {
title_index = i+1;
i++;
}else if(strcmp(argv[i], "-textside") == 0
) {
plotoptions.textside = argv[i+1];
i++;
}else if(strcmp(argv[i], "-2dfsnr") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%d", &file_number, NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-int") == 0
) {
if(twodfs_allinfo.SelectP3Integrate == 0) {
twodfs_allinfo.SelectP3Integrate = 1;
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf %lf", &(twodfs_allinfo.P3IntegrateLow), &(twodfs_allinfo.P3IntegrateHigh), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
twodfs2_allinfo.SelectP3Integrate = 1;
twodfs2_allinfo.P3IntegrateLow = twodfs_allinfo.P3IntegrateLow;
twodfs2_allinfo.P3IntegrateHigh = twodfs_allinfo.P3IntegrateHigh;
}else {
twodfs2_allinfo.SelectP3Integrate = 1;
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf %lf", &(twodfs2_allinfo.P3IntegrateLow), &(twodfs2_allinfo.P3IntegrateHigh), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
}
i++;
}else if(strcmp(argv[i], "-ytop") == 0
) {
plotoptions.plot_ylabeltop = 1;
}else if(strcmp(argv[i], "-scalefig") == 0) {
if(parse_command_string(application.verbose_state, argc, argv, i+1, 0, -1, "%lf %lf", &(plotoptions.scaleFig_x), &(plotoptions.scaleFig_y), NULL) == 0) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Cannot parse '%s' option.", argv[i]);
return 0;
}
i++;
}else {
printerror(application.verbose_state.debug, "Unknown option: %s\nRun pspecFig without command line options for a help", argv[i]);
terminateApplication(&application);
return 0;
}
}
copyVerboseState(application.verbose_state, &noverbose);
noverbose.verbose = 0;
cleanPSRData(&(twodfs_allinfo.datafile), application.verbose_state);
cleanPSRData(&(twodfs2_allinfo.datafile), application.verbose_state);
cleanPSRData(&lrfs, application.verbose_state);
cleanPSRData(&AverageProfile, application.verbose_state);
cleanPSRData(&VarianceProfile, application.verbose_state);
cleanPSRData(&VarianceProfileErr, application.verbose_state);
cleanPSRData(&ModProfile, application.verbose_state);
cleanPSRData(&ModProfileErr, application.verbose_state);
cleanPSRData(&subpulseTrackProfile, application.verbose_state);
cleanPSRData(&subpulseTrackProfileErr, application.verbose_state);
cleanPSRData(&subpulseAmpProfile, application.verbose_state);
if(type_of_plots == 0) {
if(loadLRFS(&lrfs, extprefix, longsnap, argc, argv, &plotoptions, application.verbose_state) == 0) {
return 0;
}
}
double period;
if(loadHeaderPulseStack(&AverageProfile, lrfs, &period, type_of_plots, argc, argv, application.verbose_state) == 0) {
return 0;
}
if(extprefix == 0) {
sprintf(txt, "profile");
}
if(change_filename_extension(argv[argc-1], filename, txt, 1000, application.verbose_state) == 0)
return 0;
if(altProf > 0) {
strncpy(filename, argv[altProf], 1000);
}
if(set_filename_PSRData(&AverageProfile, filename, application.verbose_state) == 0) {
fflush(stdout);
printerror(application.verbose_state.debug, "ERROR psecFig: Setting file name failed.");
return 0;
}
if(type_of_plots == 0) {
copy_params_PSRData(AverageProfile, &VarianceProfile, application.verbose_state);
copy_params_PSRData(AverageProfile, &ModProfile, application.verbose_state);
copy_params_PSRData(AverageProfile, &VarianceProfileErr, application.verbose_state);
copy_params_PSRData(AverageProfile, &ModProfileErr, application.verbose_state);
VarianceProfile.data = malloc(AverageProfile.NrBins*sizeof(float));
ModProfile.data = malloc(AverageProfile.NrBins*sizeof(float));
VarianceProfileErr.data = malloc(AverageProfile.NrBins*sizeof(float));
ModProfileErr.data = malloc(AverageProfile.NrBins*sizeof(float));
if(VarianceProfile.data == NULL || ModProfile.data == NULL || VarianceProfileErr.data == NULL || ModProfileErr.data == NULL) {
printerror(application.verbose_state.debug, "Memory allocation error");
return 0;
}
}else {
copy_params_PSRData(AverageProfile, &subpulseTrackProfile, application.verbose_state);
copy_params_PSRData(AverageProfile, &subpulseTrackProfileErr, application.verbose_state);
copy_params_PSRData(AverageProfile, &subpulseAmpProfile, application.verbose_state);
subpulseTrackProfile.data = malloc(AverageProfile.NrBins*sizeof(float));
subpulseTrackProfileErr.data = malloc(AverageProfile.NrBins*sizeof(float));
subpulseAmpProfile.data = malloc(AverageProfile.NrBins*sizeof(float));
if(subpulseTrackProfile.data == NULL || subpulseTrackProfileErr.data == NULL || subpulseAmpProfile.data == NULL) {
printerror(application.verbose_state.debug, "Memory allocation error");
return 0;
}
}
if(application.verbose_state.verbose)
printf("Reading %s\n", filename);
fout_ascii = fopen(filename, "r");
if(fout_ascii == NULL) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Unable to open %s.", filename);
return 0;
}
for(i = 0; i < AverageProfile.NrBins; i++) {
if(type_of_plots == 0) {
j = fscanf(fout_ascii, "%ld %f %f %f %f %f", &k, &AverageProfile.data[i], &VarianceProfile.data[i], &VarianceProfileErr.data[i], &ModProfile.data[i], &ModProfileErr.data[i]);
}else {
float junk;
j = fscanf(fout_ascii, "%ld %f %f %f %f %f", &k, &AverageProfile.data[i], &junk, &junk, &junk, &junk);
}
if(j != 6) {
printwarning(application.verbose_state.debug, "WARNING: It looks like profile data is rebinned? Check the units.");
AverageProfile.fixedtsamp *= AverageProfile.NrBins/(double)(i);
AverageProfile.tsampMode = TSAMPMODE_FIXEDTSAMP;
AverageProfile.NrBins = i;
printwarning(application.verbose_state.debug, "WARNING: Assuming the number of bins = %ld and the sampling time = %lf s.", AverageProfile.NrBins, AverageProfile.fixedtsamp);
if(type_of_plots == 0) {
copy_params_PSRData(AverageProfile, &VarianceProfile, application.verbose_state);
copy_params_PSRData(AverageProfile, &ModProfile, application.verbose_state);
copy_params_PSRData(AverageProfile, &VarianceProfileErr, application.verbose_state);
copy_params_PSRData(AverageProfile, &ModProfileErr, application.verbose_state);
}else {
copy_params_PSRData(AverageProfile, &subpulseTrackProfile, application.verbose_state);
copy_params_PSRData(AverageProfile, &subpulseTrackProfileErr, application.verbose_state);
copy_params_PSRData(AverageProfile, &subpulseAmpProfile, application.verbose_state);
}
break;
}
if(k != i) {
printerror(application.verbose_state.debug, "Unexpected bin number");
return 0;
}
}
fclose(fout_ascii);
if(application.verbose_state.verbose)
printf("%ld points read from %s\n", AverageProfile.NrBins, filename);
ret = get_period(AverageProfile, 0, &period, application.verbose_state);
if(ret == 2) {
printerror(application.verbose_state.debug, "ERROR pspecFig (%s): Cannot obtain period", AverageProfile.filename);
return 0;
}
plotoptions.fl_min = 0 + plotoptions.dl;
plotoptions.fl_max = 360*(AverageProfile.NrBins-1)*get_tsamp(AverageProfile, 0, application.verbose_state)/period + plotoptions.dl;
if(plotoptions.usephase) {
plotoptions.fl_min /= 360.0;
plotoptions.fl_max /= 360.0;
}
if(type_of_plots == 1) {
if(extprefix == 0) {
sprintf(txt, "amplitude");
}
if(change_filename_extension(argv[argc-1], filename, txt, 1000, application.verbose_state) == 0)
return 0;
if(application.verbose_state.verbose)
printf("Reading %s\n", filename);
fout_ascii = fopen(filename, "r");
if(fout_ascii == NULL) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Unable to open %s.", filename);
return 0;
}
for(i = 0; i < AverageProfile.NrBins; i++) {
j = fscanf(fout_ascii, "%ld %f", &k, &subpulseAmpProfile.data[i]);
if(j != 2) {
printerror(application.verbose_state.debug, "Unexpected end of file (bin %d). Resolution in subpulse phase track doesn't match resolution in profile file?", i+1);
return 0;
}
if(k != i) {
printerror(application.verbose_state.debug, "Unexpected bin number");
return 0;
}
}
fclose(fout_ascii);
if(application.verbose_state.verbose)
printf("%ld points read from %s\n", AverageProfile.NrBins, filename);
}
if(type_of_plots == 1) {
if(extprefix == 0) {
sprintf(txt, "track");
}
if(change_filename_extension(argv[argc-1], filename, txt, 1000, application.verbose_state) == 0)
return 0;
if(application.verbose_state.verbose)
printf("Reading %s\n", filename);
fout_ascii = fopen(filename, "r");
if(fout_ascii == NULL) {
printerror(application.verbose_state.debug, "ERROR pspecFig: Unable to open %s.", filename);
return 0;
}
for(i = 0; i < AverageProfile.NrBins; i++) {
j = fscanf(fout_ascii, "%ld %f %f", &k, &subpulseTrackProfile.data[i], &subpulseTrackProfileErr.data[i]);
if(j != 3) {
printerror(application.verbose_state.debug, "Unexpected end of file (bin %d). Resolution in subpulse phase track doesn't match resolution in profile file?", i+1);
return 0;
}
if(k != i) {
printerror(application.verbose_state.debug, "Unexpected bin number");
return 0;
}
}
fclose(fout_ascii);
if(application.verbose_state.verbose)
printf("%ld points read from %s\n", AverageProfile.NrBins, filename);
}
twodfs_allinfo.f3_min = 0;
twodfs_allinfo.f3_max = 0.5;
if(type_of_plots == 0 && Load2dfs != 0) {
if(load2dfs(&twodfs_allinfo, AverageProfile, file_number, extprefix, 0, argc, argv, plotoptions, application.verbose_state) == 0) {
return 0;
}
if(LoadTwo != 0) {
file_number++;
if(load2dfs(&twodfs2_allinfo, AverageProfile, file_number, extprefix, 0, argc, argv, plotoptions, application.verbose_state) == 0) {
return 0;
}
}
if(plotoptions.SelectP3Region != 0) {
twodfs_allinfo.f3_min = P3RegionLow;
twodfs_allinfo.f3_max = P3RegionHigh;
twodfs2_allinfo.f3_min = P3RegionLow;
twodfs2_allinfo.f3_max = P3RegionHigh;
}
if(twodfs_allinfo.SelectP3Integrate == 0) {
twodfs_allinfo.P3IntegrateLow = twodfs_allinfo.f3_min;
twodfs_allinfo.P3IntegrateHigh = twodfs_allinfo.f3_max;
twodfs2_allinfo.P3IntegrateLow = twodfs_allinfo.f3_min;
twodfs2_allinfo.P3IntegrateHigh = twodfs_allinfo.f3_max;
}
}
ppgopen(PlotDevice);
ppgask(0);
ppgslw(1);
ppgpage();
ppgslw(1);
ppgscf(1);
ppgsch(0.38*plotoptions.labelscale);
if(plotoptions.notop == 0) {
ppgsch(0.55*plotoptions.labelscale*plotoptions.titlescale);
ppgscf(2);
ppgslw(2);
ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.15*plotoptions.scaleFig_y, 0.95);
if(title_index > 0) {
ppgmtxt("t",1,0.5,0.5,argv[title_index]);
}
ppgslw(1);
ppgscf(1);
ppgsch(0.38*plotoptions.labelscale);
plotoptions.Imin = 0;
plotoptions.Imax = 0;
ret = get_period(AverageProfile, 0, &period, application.verbose_state);
if(ret == 2) {
printerror(application.verbose_state.debug, "ERROR pspecFig (%s): Cannot obtain period", AverageProfile.filename);
return 0;
}
for(xi=0; xi < AverageProfile.NrBins; xi++) {
double xpos;
xpos = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;
if(plotoptions.usephase)
xpos /= 360.0;
if(xpos >= plotoptions.fl_min && xpos <= plotoptions.fl_max) {
I = AverageProfile.data[xi];
if(I > plotoptions.Imax)
plotoptions.Imax = I;
if(I < plotoptions.Imin)
plotoptions.Imin = I;
}
}
if(plotoptions.SelectLRegion != 0) {
plotoptions.fl_min = plotoptions.LRegionLow;
plotoptions.fl_max = plotoptions.LRegionHigh;
}
if(type_of_plots == 0) {
for(xi=0; xi < ModProfile.NrBins; xi++) {
double xpos;
xpos = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;
if(plotoptions.usephase)
xpos /= 360.0;
if(xpos+plotoptions.dl >= plotoptions.fl_min && xpos+plotoptions.dl <= plotoptions.fl_max) {
ok_flag = 1;
if(maxsigma_mod > 0 && ModProfile.data[xi]/ModProfileErr.data[xi] < maxsigma_mod)
ok_flag = 0;
if(maxvalue_mod > 0 && ModProfile.data[xi] > maxvalue_mod)
ok_flag = 0;
if(ok_flag) {
I = ModProfile.data[xi];
if(I+ModProfileErr.data[xi] > plotoptions.Imax)
plotoptions.Imax = I+ModProfileErr.data[xi];
if(I-ModProfileErr.data[xi] < plotoptions.Imin)
plotoptions.Imin = I-ModProfileErr.data[xi];
}
}
}
for(xi=0; xi < VarianceProfile.NrBins; xi++) {
double xpos;
xpos = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;
if(plotoptions.usephase)
xpos /= 360.0;
if(xpos + plotoptions.dl >= plotoptions.fl_min && xpos + plotoptions.dl <= plotoptions.fl_max) {
I = VarianceProfile.data[xi];
if(I > plotoptions.Imax)
plotoptions.Imax = I;
if(I < plotoptions.Imin)
plotoptions.Imin = I;
}
}
}else {
for(xi=0; xi < subpulseAmpProfile.NrBins; xi++) {
double xpos;
xpos = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;
if(plotoptions.usephase)
xpos /= 360.0;
if(xpos + plotoptions.dl >= plotoptions.fl_min && xpos + plotoptions.dl <= plotoptions.fl_max) {
I = subpulseAmpProfile.data[xi];
if(I > plotoptions.Imax)
plotoptions.Imax = I;
if(I < plotoptions.Imin)
plotoptions.Imin = I;
}
}
}
if(-0.05*plotoptions.Imax < plotoptions.Imin)
plotoptions.Imin = -0.05*plotoptions.Imax;
if(ImaxSet)
plotoptions.Imax = ImaxValue/1.05;
if(IminSet)
plotoptions.Imin = IminValue/1.05;
ppgswin(plotoptions.fl_min, plotoptions.fl_max, plotoptions.Imin, 1.05*plotoptions.Imax);
if(LoadLRFS == 0) {
if(plotoptions.inside) {
if(plotoptions.noylabels) {
ppgbox("bcnst",0.0,0,"bcst",0.0,0);
}else {
ppgbox("bcnst",0.0,0,"bcnst",0.0,0);
}
}else {
if(plotoptions.noylabels) {
ppgbox("bcnst",0.0,0,"bcsti",0.0,0);
}else {
ppgbox("bcnst",0.0,0,"bcnsti",0.0,0);
}
}
}else {
if(plotoptions.inside) {
if(plotoptions.noylabels) {
ppgbox("cst",0.0,0,"bcst",0.0,0);
}else {
ppgbox("cst",0.0,0,"bcnst",0.0,0);
}
}else {
if(plotoptions.noylabels) {
ppgbox("cst",0.0,0,"bcsti",0.0,0);
}else {
ppgbox("cst",0.0,0,"bcnsti",0.0,0);
}
}
}
if(plotoptions.plot_xlabel != 0 && LoadLRFS == 0) {
ppgsch(0.3*plotoptions.labelscale);
if(plotoptions.usephase)
ppgmtxt("b",3.0,0.5,0.5,"Pulse longitude (phase)");
else
ppgmtxt("b",3.0,0.5,0.5,"Pulse longitude (deg)");
ppgsch(0.38*plotoptions.labelscale);
}
ppgsls(lineStyle);
ppgslw(2);
ppgsci(plotoptions.lineColour);
i = 0;
double deg_per_sample;
deg_per_sample = get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;
for(xi=0; xi < AverageProfile.NrBins; xi++) {
double xpos;
xpos = xi*deg_per_sample;
if(plotoptions.usephase)
xpos /= 360.0;
if(xpos+plotoptions.dl >= plotoptions.fl_min-deg_per_sample && xpos+plotoptions.dl <= plotoptions.fl_max+deg_per_sample) {
I = AverageProfile.data[xi]*profilescale;
if(i == 0) {
ppgmove(xpos+plotoptions.dl,I);
i = 1;
}else {
ppgdraw(xpos+plotoptions.dl,I);
}
}
}
ppgsci(1);
if(type_of_plots == 0) {
if(plotvariance) {
i = 0;
ppgsls(1);
ppgslw(1);
ppgscr(20, 0.5, 0.5, 0.5);
ppgsci(20);
for(xi=0; xi < AverageProfile.NrBins; xi++) {
x = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;
if(plotoptions.usephase)
x /= 360.0;
x += plotoptions.dl;
if(x >= plotoptions.fl_min-deg_per_sample && x <= plotoptions.fl_max+deg_per_sample) {
I = VarianceProfile.data[xi];
ok_flag = 1;
if(maxsigma_stddev > 0 && VarianceProfile.data[xi]/VarianceProfileErr.data[xi] < maxsigma_stddev)
ok_flag = 0;
if(maxvalue_stddev > 0 && VarianceProfile.data[xi] > maxvalue_stddev)
ok_flag = 0;
if(ok_flag == 0) {
I = 0;
i = 0;
}else {
if(i == 0) {
ppgmove(x,I);
i = 1;
}else {
ppgsci(20);
ppgdraw(x,I);
}
ppgsci(1);
ppgpt1(x, I, 4);
}
}
}
ppgsci(1);
}
if(plotmodindex) {
i = 0;
ppgsls(1);
ppgslw(1);
for(xi=0; xi < ModProfile.NrBins; xi++) {
x = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;
if(plotoptions.usephase)
x /= 360.0;
x += plotoptions.dl;
if(x >= plotoptions.fl_min-deg_per_sample && x <= plotoptions.fl_max+deg_per_sample) {
I = ModProfile.data[xi];
ok_flag = 1;
if(maxsigma_mod > 0 && ModProfile.data[xi]/ModProfileErr.data[xi] < maxsigma_mod)
ok_flag = 0;
if(maxvalue_mod > 0 && ModProfile.data[xi] > maxvalue_mod)
ok_flag = 0;
if(ok_flag == 0) {
I = 0;
i = 0;
}else {
if(i == 0) {
ppgmove(x,I);
i = 1;
}else {
ppgdraw(x,I);
}
}
}
}
ppgsls(1);
ppgslw(1);
for(xi=0; xi < ModProfile.NrBins; xi++) {
x = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;
if(plotoptions.usephase)
x /= 360.0;
x += plotoptions.dl;
if(x >= plotoptions.fl_min-deg_per_sample && x <= plotoptions.fl_max+deg_per_sample) {
I = ModProfile.data[xi];
ok_flag = 1;
if(maxsigma_mod > 0 && ModProfile.data[xi]/ModProfileErr.data[xi] < maxsigma_mod)
ok_flag = 0;
if(maxvalue_mod > 0 && ModProfile.data[xi] > maxvalue_mod)
ok_flag = 0;
if(ok_flag != 0) {
ppgpt1(x, I, -1);
ppgerr1(6,x,I,ModProfileErr.data[xi], 1);
}
}
}
}
}else {
i = 0;
ppgsls(4);
ppgslw(1);
for(xi=0; xi < AverageProfile.NrBins; xi++) {
x = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;
if(plotoptions.usephase)
x /= 360.0;
x += plotoptions.dl;
if(x >= plotoptions.fl_min-deg_per_sample && x <= plotoptions.fl_max+deg_per_sample) {
I = subpulseAmpProfile.data[xi];
if(i == 0) {
ppgmove(x, I);
i = 1;
}else {
ppgdraw(x, I);
}
}
}
ppgsls(1);
}
if(plotoptions.plot_ylabel != 0) {
ppgsch(0.3*plotoptions.labelscale);
if(plotoptions.plot_ylabeltop) {
if(type_of_plots == 0) {
ppgmtxt("l",2.8,0.5,0.5,"Intensity/Modulation index");
}else {
ppgmtxt("l",2.8,0.5,0.5,"Intensity");
}
}
ppgsch(0.38*plotoptions.labelscale);
}
}
if(type_of_plots == 0) {
if(Load2dfs != 0 && LoadLRFS == 0) {
char *title;
title = NULL;
if(title_index > 0 && plotoptions.notop && LoadLRFS == 0) {
title = argv[title_index];
}
Plot2dfs(twodfs_allinfo, twodfs2_allinfo, AverageProfile, 1, 0, title, plotoptions, application.verbose_state);
if (LoadTwo != 0) {
Plot2dfs(twodfs_allinfo, twodfs2_allinfo, AverageProfile, 1, 1, NULL, plotoptions, application.verbose_state);
}
}else {
if(LoadLRFS != 0) {
char *title;
title = NULL;
if(title_index > 0 && plotoptions.notop) {
title = argv[title_index];
}
PlotLRFS(lrfs, AverageProfile, twodfs_allinfo, title, plotoptions, application.verbose_state);
}
if(Load2dfs != 0) {
Plot2dfs(twodfs_allinfo, twodfs2_allinfo, AverageProfile, 0, 0, NULL, plotoptions, application.verbose_state);
}
if(LoadTwo != 0) {
Plot2dfs(twodfs_allinfo, twodfs2_allinfo, AverageProfile, 0, 1, NULL, plotoptions, application.verbose_state);
}
}
}else {
ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.3*plotoptions.scaleFig_y, 0.95-0.15*plotoptions.scaleFig_y);
ppgslw(1);
ppgscf(1);
ppgsch(0.38*plotoptions.labelscale);
plotoptions.Imin = 0;
plotoptions.Imax = 0;
for(xi=0; xi < subpulseTrackProfile.NrBins; xi++) {
double xpos;
xpos = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;
if(plotoptions.usephase)
xpos /= 360.0;
if(xpos+plotoptions.dl >= plotoptions.fl_min && xpos+plotoptions.dl <= plotoptions.fl_max) {
I = subpulseTrackProfile.data[xi];
if(plotoptions.doFlip)
I *= -1;
if(I+subpulseTrackProfileErr.data[xi] > plotoptions.Imax)
plotoptions.Imax = I+subpulseTrackProfileErr.data[xi];
if(I-subpulseTrackProfileErr.data[xi] < plotoptions.Imin)
plotoptions.Imin = I-subpulseTrackProfileErr.data[xi];
}
}
if(plotoptions.SelectLRegion != 0) {
plotoptions.fl_min = plotoptions.LRegionLow;
plotoptions.fl_max = plotoptions.LRegionHigh;
}
if(maxSubpulsePhaseSet)
plotoptions.Imax = maxSubpulsePhase/1.05;
if(minSubpulsePhaseSet)
plotoptions.Imin = minSubpulsePhase/1.05;
ppgswin(plotoptions.fl_min, plotoptions.fl_max, plotoptions.Imin, 1.05*plotoptions.Imax);
if(plotoptions.inside) {
if(plotoptions.noylabels) {
ppgbox("bcnst",0.0,0,"bcst",0.0,0);
}else {
ppgbox("bcnst",0.0,0,"bcnst",0.0,0);
}
}else {
if(plotoptions.noylabels) {
ppgbox("bcnst",0.0,0,"bcsti",0.0,0);
}else {
ppgbox("bcnst",0.0,0,"bcnsti",0.0,0);
}
}
if(plotoptions.plot_xlabel != 0 && LoadLRFS == 0) {
ppgsch(0.3*plotoptions.labelscale);
if(plotoptions.usephase)
ppgmtxt("b",3.0,0.5,0.5,"Pulse longitude (phase)");
else
ppgmtxt("b",3.0,0.5,0.5,"Pulse longitude (deg)");
ppgsch(0.38*plotoptions.labelscale);
}
if(do_phase_slope) {
ppgsls(4);
if(plotoptions.usephase == 0) {
x = plotoptions.dl;
I = x*phase_slope_g + phase_slope_o;
I = derotate_deg(I);
ppgmove(x, I);
ppgdraw(x+360, I+phase_slope_g*360);
ppgmove(x, I-360);
ppgdraw(x+360, I-360+phase_slope_g*360);
ppgmove(x, I-2*360);
ppgdraw(x+360, I-2*360+phase_slope_g*360);
ppgmove(x, I+360);
ppgdraw(x+360, I+360+phase_slope_g*360);
ppgmove(x, I+2*360);
ppgdraw(x+360, I+2*360+phase_slope_g*360);
}else {
x = plotoptions.dl;
I = x*360.0*phase_slope_g + phase_slope_o;
I = derotate_deg(I);
ppgmove(x, I);
ppgdraw(x+1.0, I+phase_slope_g*360);
ppgmove(x, I-360);
ppgdraw(x+1.0, I-360+phase_slope_g*360);
ppgmove(x, I-2*360);
ppgdraw(x+1.0, I-2*360+phase_slope_g*360);
ppgmove(x, I+360);
ppgdraw(x+1.0, I+360+phase_slope_g*360);
ppgmove(x, I+2*360);
ppgdraw(x+1.0, I+2*360+phase_slope_g*360);
}
ppgsls(1);
}
ppgscr(20, 0.5, 0.5, 0.5);
ppgsci(20);
ppgsls(1);
ppgslw(1);
for(xi=0; xi < subpulseTrackProfile.NrBins; xi++) {
x = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;
if(plotoptions.usephase)
x /= 360.0;
x += plotoptions.dl;
if(x >= plotoptions.fl_min && x <= plotoptions.fl_max) {
I = subpulseTrackProfile.data[xi];
if(plotoptions.doFlip)
I *= -1;
ppgerr1(6,x,I,subpulseTrackProfileErr.data[xi], 1);
ppgerr1(6,x,I+360,subpulseTrackProfileErr.data[xi], 1);
ppgerr1(6,x,I-360,subpulseTrackProfileErr.data[xi], 1);
}
}
ppgsci(1);
ppgslw(3);
for(xi=0; xi < subpulseTrackProfile.NrBins; xi++) {
x = xi*get_tsamp(AverageProfile, 0, application.verbose_state)*360.0/period;
if(plotoptions.usephase)
x /= 360.0;
x += plotoptions.dl;
if(x >= plotoptions.fl_min && x <= plotoptions.fl_max) {
I = subpulseTrackProfile.data[xi];
if(plotoptions.doFlip)
I *= -1;
ppgpt1(x, I, -1);
ppgpt1(x, I+360, -1);
ppgpt1(x, I-360, -1);
}
}
ppgslw(1);
if(plotoptions.plot_xlabel != 0) {
ppgsch(0.3*plotoptions.labelscale);
if(plotoptions.usephase)
ppgmtxt("b",3.0,0.5,0.5,"Pulse longitude (phase)");
else
ppgmtxt("b",3.0,0.5,0.5,"Pulse longitude (deg)");
ppgsch(0.38*plotoptions.labelscale);
}
if(plotoptions.plot_ylabel != 0) {
ppgsch(0.3*plotoptions.labelscale);
if(plotoptions.usephase)
ppgmtxt("l",2.8,0.5,0.5,"Subpulse phase (phase)");
else
ppgmtxt("l",2.8,0.5,0.5,"Subpulse phase (deg)");
ppgsch(0.38*plotoptions.labelscale);
}
}
if(preprocess_checknan(AverageProfile, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checkinf(AverageProfile, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.");
}
if(type_of_plots == 0) {
if(preprocess_checknan(VarianceProfile, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checkinf(VarianceProfile, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checknan(ModProfile, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checkinf(ModProfile, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checknan(VarianceProfileErr, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checkinf(VarianceProfileErr, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checknan(ModProfileErr, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checkinf(ModProfileErr, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.");
}
}else {
if(preprocess_checknan(subpulseTrackProfile, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checkinf(subpulseTrackProfile, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checknan(subpulseTrackProfileErr, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checkinf(subpulseTrackProfileErr, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checknan(subpulseAmpProfile, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have NAN's in them. Artifacts can be expected in the plot.");
}
if(preprocess_checkinf(subpulseAmpProfile, 1, noverbose)) {
printwarning(application.verbose_state.debug, "WARNING: The profile data appears to have INF's in them. Artifacts can be expected in the plot.");
}
}
ppgend();
closePSRData(&AverageProfile, 0, application.verbose_state);
closePSRData(&(twodfs_allinfo.datafile), 0, application.verbose_state);
closePSRData(&(twodfs2_allinfo.datafile), 0, application.verbose_state);
closePSRData(&lrfs, 0, application.verbose_state);
closePSRData(&VarianceProfile, 0, application.verbose_state);
closePSRData(&ModProfile, 0, application.verbose_state);
closePSRData(&VarianceProfileErr, 0, application.verbose_state);
closePSRData(&ModProfileErr, 0, application.verbose_state);
closePSRData(&subpulseTrackProfile, 0, application.verbose_state);
closePSRData(&subpulseTrackProfileErr, 0, application.verbose_state);
closePSRData(&subpulseAmpProfile, 0, application.verbose_state);
terminateApplication(&application);
return 0;
}
void GetExtremesSubsetVertical(twodfs_def twodfs_allinfo, float *Imin, float *Imax)
{
float I, x, y;
int xi, yi;
*Imin = 0;
*Imax = 0;
for(xi = 0; xi < twodfs_allinfo.datafile.NrBins; xi++) {
I = 0;
for(yi = 0; yi < twodfs_allinfo.datafile.NrSubints; yi++) {
pgplotMapCoordinateInverse(&x, &y, xi, yi);
if(y >= twodfs_allinfo.P3IntegrateLow && y <= twodfs_allinfo.P3IntegrateHigh) {
if(x >= twodfs_allinfo.f2_min && x <= twodfs_allinfo.f2_max) {
I += twodfs_allinfo.datafile.data[yi*twodfs_allinfo.datafile.NrBins+xi];
}
}
}
if(I < *Imin)
*Imin = I;
if(I > *Imax)
*Imax = I;
}
*Imin *= 2.0;
*Imax *= 2.0;
}
void GetExtremesSubsetHorizontal(datafile_definition spectrum, int istwodfs, double f2_min, double f2_max, double f3_min, double f3_max, float *Imin, float *Imax, plotoptions_def plotoptions)
{
float I, x, y;
int xi, yi, ok;
*Imin = 0;
*Imax = 0;
for(yi = plotoptions.ExtraVerticalMaximaSkip; yi < spectrum.NrSubints; yi++) {
I = 0;
for(xi = 0; xi < spectrum.NrBins; xi++) {
pgplotMapCoordinateInverse(&x, &y, xi, yi);
ok = 0;
if(istwodfs == 0) {
if(x >= plotoptions.fl_min && x <= plotoptions.fl_max && y >= f3_min && y <= f3_max) {
ok = 1;
}
}else {
if(x >= f2_min && x <= f2_max && y >= f3_min && y <= f3_max) {
ok = 1;
}
}
if(ok) {
I += spectrum.data[yi*spectrum.NrBins+xi];
}
}
if(I < *Imin)
*Imin = I;
if(I > *Imax)
*Imax = I;
}
*Imin *= 2.0;
*Imax *= 2.0;
}
void IntegrateSubsetHorizontal(datafile_definition lrfs, twodfs_def twodfs_allinfo, twodfs_def twodfs2_allinfo, int twodfsonly, int Number, int normalise, plotoptions_def plotoptions)
{
float I, Imin, Imax, x, y;
int xi, yi;
float offset;
offset = 0+0.03*(plotoptions.labelscale-1.0)*((float)Number+1.0);
if(Number == -1) {
ppgsvp(0.2-0.04*plotoptions.scaleFig_x, 0.2, 0.95-0.3*plotoptions.scaleFig_y, 0.95-0.15*plotoptions.scaleFig_y);
}else {
if(twodfsonly == 0) {
ppgsvp(0.2-0.04*plotoptions.scaleFig_x, 0.2, 0.95-0.48*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y, 0.95-0.33*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y);
}else {
ppgsvp(0.2-0.04*plotoptions.scaleFig_x, 0.2, 0.95-0.33*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y, 0.95-0.18*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y);
}
}
if(Number == -1) {
GetExtremesSubsetHorizontal(lrfs, 0, 0.0, 0.0, twodfs_allinfo.f3_min, twodfs_allinfo.f3_max, &Imin, &Imax, plotoptions);
}else if(Number == 0) {
GetExtremesSubsetHorizontal(twodfs_allinfo.datafile, 1, twodfs_allinfo.f2_min, twodfs_allinfo.f2_max, twodfs_allinfo.f3_min, twodfs_allinfo.f3_max, &Imin, &Imax, plotoptions);
}else {
GetExtremesSubsetHorizontal(twodfs2_allinfo.datafile, 1, twodfs2_allinfo.f2_min, twodfs2_allinfo.f2_max, twodfs2_allinfo.f3_min, twodfs2_allinfo.f3_max, &Imin, &Imax, plotoptions);
}
double scale;
scale = fabs(Imax);
if(fabs(Imin) > scale)
scale = fabs(Imin);
if(normalise == 0)
scale = 1.0;
ppgswin(Imin/scale,1.05*Imax/scale, twodfs_allinfo.f3_min,twodfs_allinfo.f3_max);
ppgbox("bcv",0.0,0,"bnsti",0.0,0);
ppgbox("",0.0,0,"c",0.0,0);
if(plotoptions.textside != NULL) {
if(twodfsonly == 0) {
if(Number == -1) {
ppgsch(0.55*plotoptions.labelscale*plotoptions.titlescale);
ppgscf(2);
ppgslw(2);
if (plotoptions.notop == 1) {
ppgtext(Imin, (twodfs_allinfo.f3_max-twodfs_allinfo.f3_min)*1.15, plotoptions.textside);
} else {
ppgtext(Imin, (twodfs_allinfo.f3_max-twodfs_allinfo.f3_min)*2.095, plotoptions.textside);
}
ppgslw(1);
ppgscf(1);
ppgsch(0.38*plotoptions.labelscale);
}
}else {
if(strlen(plotoptions.textside) != 0 && plotoptions.notop == 0) {
ppgsch(0.55*plotoptions.labelscale*plotoptions.titlescale);
ppgscf(2);
ppgslw(2);
ppgtext(Imin, (twodfs_allinfo.f3_max-twodfs_allinfo.f3_min)+0.65, plotoptions.textside);
ppgslw(1);
ppgscf(1);
ppgsch(0.38*plotoptions.labelscale);
}else if (strlen(plotoptions.textside) != 0 && plotoptions.notop == 1) {
ppgsch(0.55*plotoptions.labelscale*plotoptions.titlescale);
ppgscf(2);
ppgslw(2);
ppgtext(Imin, (twodfs_allinfo.f3_max-twodfs_allinfo.f3_min)+0.1, plotoptions.textside);
ppgslw(1);
ppgscf(1);
ppgsch(0.38*plotoptions.labelscale);
}
}
}
y = floor(log10(Imax*0.33/scale));
x = floor(Imax*0.33/(pow(10,y)*scale));
x = x*pow(10,y);
char labelnumbers[3];
if(plotoptions.nointegrateNumbers == 0) {
strcpy(labelnumbers, "n");
}else {
strcpy(labelnumbers, "");
}
ppgsch(0.38*plotoptions.labelscale*0.66);
ppgaxis(labelnumbers,0,twodfs_allinfo.f3_max,Imax*0.33/scale,twodfs_allinfo.f3_max,0,Imax*0.33/scale,x,1,0.3,0,0,-0.5,90);
ppgsch(0.38*plotoptions.labelscale);
datafile_definition *spectrum;
double xmin, xmax, ymin, ymax;
if(Number == -1) {
spectrum = &lrfs;
xmin = plotoptions.fl_min;
xmax = plotoptions.fl_max;
ymin = twodfs_allinfo.f3_min;
ymax = twodfs_allinfo.f3_max;
}else if(Number == 0) {
spectrum = &(twodfs_allinfo.datafile);
xmin = twodfs_allinfo.f2_min;
xmax = twodfs_allinfo.f2_max;
ymin = twodfs_allinfo.f3_min;
ymax = twodfs_allinfo.f3_max;
}else if(Number == 1) {
spectrum = &(twodfs2_allinfo.datafile);
xmin = twodfs2_allinfo.f2_min;
xmax = twodfs2_allinfo.f2_max;
ymin = twodfs2_allinfo.f3_min;
ymax = twodfs2_allinfo.f3_max;
}
for(yi = 0; yi < spectrum->NrSubints; yi++) {
I = 0;
for(xi = 0; xi < spectrum->NrBins; xi++) {
pgplotMapCoordinateInverse(&x, &y, xi, yi);
if(x >= xmin && x <= xmax && y >= ymin && y <= ymax) {
I += spectrum->data[yi*spectrum->NrBins+xi];
}
}
if(yi == 0) {
ppgmove(2.0*I/scale, y);
}else {
ppgdraw(2.0*I/scale, y);
}
}
}
void PlotLRFS(datafile_definition lrfs, datafile_definition AverageProfile, twodfs_def twodfs_allinfo, char *title, plotoptions_def plotoptions, verbose_definition verbose)
{
float I;
int xi, i;
ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.3*plotoptions.scaleFig_y, 0.95-0.15*plotoptions.scaleFig_y);
if(title != NULL) {
ppgsch(0.55*plotoptions.labelscale*plotoptions.titlescale);
ppgscf(2);
ppgslw(2);
ppgmtxt("t",1,0.5,0.5,title);
ppgslw(1);
ppgscf(1);
ppgsch(0.38*plotoptions.labelscale);
}
if(plotoptions.SelectLRegion != 0) {
plotoptions.fl_min = plotoptions.LRegionLow;
plotoptions.fl_max = plotoptions.LRegionHigh;
}
ppgswin(plotoptions.fl_min,plotoptions.fl_max,twodfs_allinfo.f3_min,twodfs_allinfo.f3_max);
if(plotoptions.plot_xlabel != 0) {
ppgsch(0.3*plotoptions.labelscale);
if(plotoptions.usephase)
ppgmtxt("b",3.0,0.5,0.5,"Pulse longitude (phase)");
else
ppgmtxt("b",3.0,0.5,0.5,"Pulse longitude (deg)");
ppgsch(0.38*plotoptions.labelscale);
}
if(plotoptions.plot_ylabel != 0) {
ppgsch(0.3*plotoptions.labelscale);
if(plotoptions.noside) {
if(plotoptions.plot_ylabel == 1)
ppgmtxt("l",2.8,0.5,0.5,"Fluctuation frequency (cpp)");
else if(plotoptions.plot_ylabel == 2)
ppgmtxt("l",2.8,0.5,0.5,"Fluctuation frequency (P\\d0\\u/P\\d3\\u)");
else if(plotoptions.plot_ylabel == 3)
ppgmtxt("l",2.8,0.5,0.5,"Fluctuation frequency (P/P\\d3\\u)");
}else {
float offset;
offset = 10 - (plotoptions.labelscale-1.0)*(7-2.8);
offset += 7*(plotoptions.scaleFig_x-1.0);
if(plotoptions.plot_ylabel == 1)
ppgmtxt("l",offset,0.5,0.5,"Fluctuation frequency (cpp)");
else if(plotoptions.plot_ylabel == 2)
ppgmtxt("l",offset,0.5,0.5,"Fluctuation frequency (P\\d0\\u/P\\d3\\u)");
else if(plotoptions.plot_ylabel == 3)
ppgmtxt("l",offset,0.5,0.5,"Fluctuation frequency (P/P\\d3\\u)");
}
ppgsch(0.38*plotoptions.labelscale);
}
pgplot_options_definition pgplot_options;
pgplot_clear_options(&pgplot_options);
pgplot_options.box.box_labelsize = 0.3*plotoptions.labelscale;
pgplot_options.viewport.dontopen = 1;
pgplot_options.viewport.dontclose = 1;
pgplot_options.viewport.noclear = 1;
double period;
int ret;
ret = get_period(lrfs, 0, &period, verbose);
if(ret == 2) {
printerror(verbose.debug, "ERROR pspecFig (%s): Cannot obtain period", lrfs.filename);
exit(0);
}
double xright;
xright = 360*(lrfs.NrBins-1)*get_tsamp(lrfs, 0, verbose)/period;
if(plotoptions.usephase)
xright /= 360.0;
pgplotMap(&pgplot_options, lrfs.data, lrfs.NrBins, lrfs.NrSubints, 0+plotoptions.dl, xright+plotoptions.dl, plotoptions.fl_min, plotoptions.fl_max, 0, 0.5, twodfs_allinfo.f3_min, twodfs_allinfo.f3_max, PPGPLOT_GRAYSCALE, 0, 0, 0, NULL, 0, 0, plotoptions.oversaturizel, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, plotoptions.showwedge, plotoptions.showwedge_max, 0, 0, verbose);
ret = get_period(AverageProfile, 0, &period, verbose);
if(ret == 2) {
printerror(verbose.debug, "ERROR pspecFig (%s): Cannot obtain period", AverageProfile.filename);
exit(0);
}
if(plotoptions.overlaypp) {
ppgsci(plotoptions.lineColour);
ppgsls(1);
ppgslw(1);
i = 0;
for(xi=0; xi < AverageProfile.NrBins; xi++) {
double xpos;
xpos = xi*get_tsamp(AverageProfile, 0, verbose)*360.0/period;
if(plotoptions.usephase)
xpos /= 360.0;
if(xpos+plotoptions.dl >= plotoptions.fl_min && xpos+plotoptions.dl <= plotoptions.fl_max) {
I = AverageProfile.data[xi]*0.5;
if(i == 0) {
ppgmove(xpos+plotoptions.dl,I);
i = 1;
}else {
ppgdraw(xpos+plotoptions.dl,I);
}
}
}
ppgsci(1);
}
ppgswin(plotoptions.fl_min,plotoptions.fl_max,twodfs_allinfo.f3_min,twodfs_allinfo.f3_max);
ppgsch(0.38*plotoptions.labelscale);
if(plotoptions.noside) {
if(plotoptions.inside) {
if(plotoptions.noylabels)
ppgbox("bcnst",0.0,0,"bcst",0.0,0);
else
ppgbox("bcnst",0.0,0,"bcnst",0.0,0);
}else {
if(plotoptions.noylabels)
ppgbox("bcnsti",0.0,0,"bcsti",0.0,0);
else
ppgbox("bcnsti",0.0,0,"bcnsti",0.0,0);
}
}else {
if(plotoptions.inside) {
ppgbox("bcnst",0.0,0,"cst",0.0,0);
}else {
ppgbox("bcnsti",0.0,0,"csti",0.0,0);
}
}
if(plotoptions.noside == 0) {
IntegrateSubsetHorizontal(lrfs, twodfs_allinfo, twodfs_allinfo, 0, -1, plotoptions.normaliseSide, plotoptions);
}
ppgsch(0.38*plotoptions.labelscale);
}
void IntegrateSubsetVertical(twodfs_def twodfs_allinfo, int twodfsonly, int Number, int normalise, int nointegrateNumbers, plotoptions_def plotoptions)
{
float I, Imin, Imax, x, y, offset;
int xi, yi;
offset = 0+0.03*(plotoptions.labelscale-1.0)*((float)Number+1.0);
if(twodfsonly == 0) {
ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.52*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y, 0.95-0.48*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y);
}else {
ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.37*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y, 0.95-0.33*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y);
}
GetExtremesSubsetVertical(twodfs_allinfo, &Imin, &Imax);
double scale;
scale = fabs(Imax);
if(fabs(Imin) > scale)
scale = fabs(Imin);
if(normalise == 0)
scale = 1.0;
ppgswin(twodfs_allinfo.f2_min,twodfs_allinfo.f2_max,Imin/scale,1.05*Imax/scale);
if(plotoptions.noxlabels == 0)
ppgbox("bnst",0.0,0,"bcvi",0.0,0);
else
ppgbox("bst",0.0,0,"bcvi",0.0,0);
ppgbox("c",0.0,0,"",0.0,0);
y = floor(log10(Imax*0.7/scale));
x = floor(Imax*0.7/(pow(10,y)*scale));
x = x*pow(10,y);
char labelnumbers[3];
if(plotoptions.nointegrateNumbers == 0) {
strcpy(labelnumbers, "n");
}else {
strcpy(labelnumbers, "");
}
ppgsch(0.38*plotoptions.labelscale*0.66);
ppgaxis(labelnumbers,twodfs_allinfo.f2_min, 0,twodfs_allinfo.f2_min, Imax*.7/scale,0,Imax*.7/scale,x,1,0.3,0,0,-0.8,90);
ppgsch(0.38*plotoptions.labelscale);
int direction;
for(direction = 1-plotoptions.intflip; direction < 2; direction++) {
if(direction == 0) {
ppgsci(8);
ppgsls(2);
}else {
ppgsci(1);
ppgsls(1);
}
for(xi = 0; xi < twodfs_allinfo.datafile.NrBins; xi++) {
I = 0;
for(yi = 0; yi < twodfs_allinfo.datafile.NrSubints; yi++) {
pgplotMapCoordinateInverse(&x, &y, xi, yi);
if(y >= twodfs_allinfo.P3IntegrateLow && y <= twodfs_allinfo.P3IntegrateHigh)
I += twodfs_allinfo.datafile.data[yi*twodfs_allinfo.datafile.NrBins+xi];
}
if(direction == 0)
x *= -1.0;
if(xi == 0) {
ppgmove(x,2.0*I/scale);
}else {
ppgdraw(x,2.0*I/scale);
}
}
}
}
void Plot2dfs(twodfs_def twodfs_allinfo, twodfs_def twodfs2_allinfo, datafile_definition AverageProfile, int twodfsonly, int Number, char *title, plotoptions_def plotoptions, verbose_definition verbose)
{
float offset;
offset = 0+0.03*(plotoptions.labelscale-1.0)*((float)Number+1.0);
if(twodfsonly == 0) {
ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.48*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y, 0.95-0.33*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y);
}else {
ppgsvp(0.2, 0.2+0.11*plotoptions.scaleFig_x, 0.95-0.33*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y, 0.95-0.18*plotoptions.scaleFig_y-0.22*Number*plotoptions.scaleFig_y-offset*plotoptions.scaleFig_y);
}
if(twodfsonly && title != NULL) {
ppgsch(0.55*plotoptions.labelscale*plotoptions.titlescale);
ppgscf(2);
ppgslw(2);
ppgmtxt("t",1,0.5,0.5,title);
ppgslw(1);
ppgscf(1);
ppgsch(0.38*plotoptions.labelscale);
}
ppgswin(twodfs_allinfo.f2_min,twodfs_allinfo.f2_max,twodfs_allinfo.f3_min,twodfs_allinfo.f3_max);
if(plotoptions.plot_ylabel != 0) {
ppgsch(0.3*plotoptions.labelscale);
if(plotoptions.noside) {
if(plotoptions.plot_ylabel == 1)
ppgmtxt("l",2.8,0.5,0.5,"Fluctuation frequency (cpp)");
else if(plotoptions.plot_ylabel == 2)
ppgmtxt("l",2.8,0.5,0.5,"Fluctuation frequency (P\\d0\\u/P\\d3\\u)");
else if(plotoptions.plot_ylabel == 3)
ppgmtxt("l",2.8,0.5,0.5,"Fluctuation frequency (P/P\\d3\\u)");
}else {
float offset;
offset = 10 - (plotoptions.labelscale-1.0)*(7-2.8);
offset += 7*(plotoptions.scaleFig_x-1.0);
if(plotoptions.plot_ylabel == 1)
ppgmtxt("l",offset,0.5,0.5,"Fluctuation frequency (cpp)");
else if(plotoptions.plot_ylabel == 2)
ppgmtxt("l",offset,0.5,0.5,"Fluctuation frequency (P\\d0\\u/P\\d3\\u)");
else if(plotoptions.plot_ylabel == 3)
ppgmtxt("l",offset,0.5,0.5,"Fluctuation frequency (P/P\\d3\\u)");
}
ppgsch(0.38*plotoptions.labelscale);
}
pgplot_options_definition pgplot_options;
pgplot_clear_options(&pgplot_options);
pgplot_options.box.box_labelsize = 0.3*plotoptions.labelscale;
pgplot_options.viewport.noclear = 1;
pgplot_options.viewport.dontopen = 1;
pgplot_options.viewport.dontclose = 1;
if(!plotoptions.nomain) {
datafile_definition *curtwodfs;
float cur_f2_min, cur_f2_max;
float cur_f3_min, cur_f3_max;
float cur_oversaturize;
if(Number == 0) {
curtwodfs = &(twodfs_allinfo.datafile);
cur_f2_min = twodfs_allinfo.f2_min;
cur_f2_max = twodfs_allinfo.f2_max;
cur_f3_min = twodfs_allinfo.f3_min;
cur_f3_max = twodfs_allinfo.f3_max;
cur_oversaturize = twodfs_allinfo.oversaturize;
}else {
curtwodfs = &(twodfs2_allinfo.datafile);
cur_f2_min = twodfs2_allinfo.f2_min;
cur_f2_max = twodfs2_allinfo.f2_max;
cur_f3_min = twodfs2_allinfo.f3_min;
cur_f3_max = twodfs2_allinfo.f3_max;
cur_oversaturize = twodfs2_allinfo.oversaturize;
}
float cpp_min;
float cpp_max;
if(curtwodfs->xrangeset) {
cpp_min = curtwodfs->xrange[0];
cpp_max = curtwodfs->xrange[1];
}else {
cpp_min = -AverageProfile.NrBins/2.0-0.5*AverageProfile.NrBins/(float)curtwodfs->NrBins;
cpp_max = +AverageProfile.NrBins/2.0-0.5*AverageProfile.NrBins/(float)curtwodfs->NrBins;
}
if(plotoptions.doFlip) {
cpp_min *= -1.0;
cpp_max *= -1.0;
}
pgplotMap(&pgplot_options, curtwodfs->data, curtwodfs->NrBins, curtwodfs->NrSubints, cpp_min, cpp_max, cur_f2_min, cur_f2_max, 0, 0.5, cur_f3_min, cur_f3_max, PPGPLOT_GRAYSCALE, 0, 0, 0, NULL, 0, 0, cur_oversaturize, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, plotoptions.showwedge, plotoptions.showwedge_max, 0, 0, verbose);
ppgsch(0.38*plotoptions.labelscale);
if(plotoptions.noside) {
if(plotoptions.inside) {
if(plotoptions.noylabels)
ppgbox("cst",0.0,0,"bcst",0.0,0);
else
ppgbox("cst",0.0,0,"bcnst",0.0,0);
}else {
if(plotoptions.noylabels)
ppgbox("csti",0.0,0,"bcsti",0.0,0);
else
ppgbox("csti",0.0,0,"bcnsti",0.0,0);
}
}else {
if(plotoptions.inside) {
ppgbox("cst",0.0,0,"cst",0.0,0);
}else {
ppgbox("csti",0.0,0,"csti",0.0,0);
}
}
ppgbox("c",0.0,0,"c",0.0,0);
if(twodfs_allinfo.SelectP3Integrate != 0) {
ppgsls(2);
ppgslw(1);
if(Number == 0) {
ppgmove(twodfs_allinfo.f2_min, twodfs_allinfo.P3IntegrateLow);
ppgdraw(twodfs_allinfo.f2_max, twodfs_allinfo.P3IntegrateLow);
}else {
ppgmove(twodfs_allinfo.f2_min, twodfs2_allinfo.P3IntegrateLow);
ppgdraw(twodfs_allinfo.f2_max, twodfs2_allinfo.P3IntegrateLow);
}
ppgsls(2);
if(Number == 0) {
ppgmove(twodfs_allinfo.f2_min, twodfs_allinfo.P3IntegrateHigh);
ppgdraw(twodfs_allinfo.f2_max, twodfs_allinfo.P3IntegrateHigh);
}else {
ppgmove(twodfs_allinfo.f2_min, twodfs2_allinfo.P3IntegrateHigh);
ppgdraw(twodfs_allinfo.f2_max, twodfs2_allinfo.P3IntegrateHigh);
}
ppgsls(1);
ppgslw(1);
}
}
if(Number == 0) {
IntegrateSubsetVertical(twodfs_allinfo, twodfsonly, Number, plotoptions.normaliseSide, plotoptions.nointegrateNumbers, plotoptions);
}else {
IntegrateSubsetVertical(twodfs2_allinfo, twodfsonly, Number, plotoptions.normaliseSide, plotoptions.nointegrateNumbers, plotoptions);
}
if(plotoptions.plot_xlabel == 1) {
ppgsch(0.3*plotoptions.labelscale);
ppgmtxt("b",3.0,0.5,0.5,"Fluctuation frequency (cpp)");
ppgsch(0.38*plotoptions.labelscale);
}else if(plotoptions.plot_xlabel == 2) {
ppgsch(0.3*plotoptions.labelscale);
ppgmtxt("b",3.0,0.5,0.5,"Fluctuation frequency (P\\d0\\u/P\\d2\\u)");
ppgsch(0.38*plotoptions.labelscale);
}else if(plotoptions.plot_xlabel == 3) {
ppgsch(0.3*plotoptions.labelscale);
ppgmtxt("b",3.0,0.5,0.5,"Fluctuation frequency (P/P\\d2\\u)");
ppgsch(0.38*plotoptions.labelscale);
}
if(!(plotoptions.noside)) {
IntegrateSubsetHorizontal(twodfs_allinfo.datafile, twodfs_allinfo, twodfs2_allinfo, twodfsonly, Number, plotoptions.normaliseSide, plotoptions);
}
}
int loadLRFS(datafile_definition *lrfs, int extprefix, int longsnap, int argc, char **argv, plotoptions_def *plotoptions, verbose_definition verbose)
{
char filename[MaxFilenameLength], txt[MaxFilenameLength];
datafile_definition clone;
if(extprefix == 0) {
sprintf(txt, "lrfs");
}
if(change_filename_extension(argv[argc-1], filename, txt, MaxFilenameLength, verbose) == 0) {
return 0;
}
if(verbose.verbose) {
printf("Reading %s\n", filename);
}
closePSRData(lrfs, 0, verbose);
if(!openPSRData(lrfs, filename, 0, 0, 1, 0, verbose)) {
return 0;
}
if(PSRDataHeader_parse_commandline(lrfs, argc, argv, verbose) == 0) {
return 0;
}
double period;
int ret;
ret = get_period(*lrfs, 0, &period, verbose);
if(ret == 2) {
printerror(verbose.debug, "ERROR pspecFig (%s): Cannot obtain period", lrfs->filename);
return 0;
}
if(period < 0.001) {
printerror(verbose.debug, "ERROR pspecFig (%s): The period does not appear to be set in the header. Consider using the -header option.", lrfs->filename);
return 0;
}
if(get_tsamp(*lrfs, 0, verbose) < 0.0000001) {
printerror(verbose.debug, "ERROR pspecFig (%s): The sampling time does not appear to be set in the header. Consider using the -header option.", lrfs->filename);
return 0;
}
if(verbose.verbose) {
printf("%ldx%ld points read from lrfs\n", lrfs->NrBins, lrfs->NrSubints);
}
if(lrfs->NrPols > 1) {
if(preprocess_polselect(*lrfs, &clone, 0, verbose) == 0) {
printerror(verbose.debug, "ERROR pspecFig (%s): Error selecting polarization channel 0.", lrfs->filename);
return 0;
}
swap_orig_clone(lrfs, &clone, verbose);
}
long i;
double max;
if(plotoptions->normalise_spectra) {
for(i = 0; i < lrfs->NrSubints * lrfs->NrBins; i++) {
if(i == 0 || fabs(lrfs->data[i]) > max) {
max = fabs(lrfs->data[i]);
}
}
for(i = 0; i < lrfs->NrSubints * lrfs->NrBins; i++) {
lrfs->data[i] /= 0.999*max;
}
}
return 1;
}
int loadHeaderPulseStack(datafile_definition *AverageProfile, datafile_definition lrfs, double *period, int type_of_plots, int argc, char **argv, verbose_definition verbose)
{
if(verbose.verbose)
printf("Reading %s\n", argv[argc-1]);
closePSRData(AverageProfile, 0, verbose);
if(!openPSRData(AverageProfile, argv[argc-1], 0, 0, 0, 0, verbose))
return 0;
if(!readHeaderPSRData(AverageProfile, 0, 0, verbose))
return 0;
if(PSRDataHeader_parse_commandline(AverageProfile, argc, argv, verbose) == 0)
return 0;
if(type_of_plots == 0) {
if(AverageProfile->NrBins != lrfs.NrBins) {
printwarning(verbose.debug, "WARNING: Nr of bins in pulse stack and LRFS do not match. It looks like data is rebinned? Check the units.");
}
}
int ret_prd;
ret_prd = get_period(*AverageProfile, 0, period, verbose);
if(ret_prd == 2) {
printerror(verbose.debug, "ERROR pspecFig (%s): Cannot obtain period", AverageProfile->filename);
return 0;
}
if(*period < 0.001) {
printerror(verbose.debug, "ERROR pspecFig (%s): The period does not appear to be set in the header. Consider using the -header option.", AverageProfile->filename);
return 0;
}
if(get_tsamp(*AverageProfile, 0, verbose) < 0.0000001) {
printerror(verbose.debug, "ERROR pspecFig (%s): The sampling time does not appear to be set in the header. Consider using the -header option.", AverageProfile->filename);
return 0;
}
closePSRData(AverageProfile, 1, verbose);
AverageProfile->format = MEMORY_format;
AverageProfile->NrSubints = 1;
AverageProfile->NrFreqChan = 1;
AverageProfile->NrPols = 1;
AverageProfile->data = malloc(AverageProfile->NrBins*sizeof(float));
if(AverageProfile->data == NULL) {
printerror(verbose.debug, "ERROR pspecFig (%s): Memory allocation error", AverageProfile->filename);
return 0;
}
return 1;
}
int load2dfs(twodfs_def *twodfs_allinfo, datafile_definition AverageProfile, int file_number, int extprefix, int altname, int argc, char **argv, plotoptions_def plotoptions, verbose_definition verbose)
{
char filename[MaxFilenameLength], txt[MaxFilenameLength];
datafile_definition clone;
if(altname) {
strcpy(filename, argv[altname]);
}else {
if(extprefix == 0) {
sprintf(txt, "%d.2dfs", file_number);
}
if(change_filename_extension(argv[argc-1], filename, txt, MaxFilenameLength, verbose) == 0) {
return 0;
}
}
if(verbose.verbose) {
printf("Reading %s\n", filename);
}
closePSRData(&(twodfs_allinfo->datafile), 0, verbose);
if(!openPSRData(&(twodfs_allinfo->datafile), filename, 0, 0, 1, 0, verbose)) {
return 0;
}
if(PSRDataHeader_parse_commandline(&(twodfs_allinfo->datafile), argc, argv, verbose) == 0) {
return 0;
}
if(verbose.verbose) {
printf("%ldx%ld points read from 2dfs\n", twodfs_allinfo->datafile.NrBins, twodfs_allinfo->datafile.NrSubints);
}
if(twodfs_allinfo->datafile.NrPols > 1) {
if(preprocess_polselect(twodfs_allinfo->datafile, &clone, 0, verbose) == 0) {
printerror(verbose.debug, "ERROR pspecFig: Error selecting polarization channel 0.");
return 0;
}
swap_orig_clone(&(twodfs_allinfo->datafile), &clone, verbose);
}
long i;
double max;
if(plotoptions.normalise_spectra) {
for(i = 0; i < twodfs_allinfo->datafile.NrSubints * twodfs_allinfo->datafile.NrBins; i++) {
if(i == 0 || fabs(twodfs_allinfo->datafile.data[i]) > max) {
max = fabs(twodfs_allinfo->datafile.data[i]);
}
}
for(i = 0; i < twodfs_allinfo->datafile.NrSubints * twodfs_allinfo->datafile.NrBins; i++) {
twodfs_allinfo->datafile.data[i] /= 0.999*max;
}
}
if(twodfs_allinfo->f2_min == 0.0 && twodfs_allinfo->f2_min == 0.0) {
if(twodfs_allinfo->datafile.xrangeset) {
twodfs_allinfo->f2_min = twodfs_allinfo->datafile.xrange[0];
twodfs_allinfo->f2_max = twodfs_allinfo->datafile.xrange[1];
}else {
twodfs_allinfo->f2_min = -AverageProfile.NrBins/2.0;
twodfs_allinfo->f2_max = -AverageProfile.NrBins/2.0 + AverageProfile.NrBins*(twodfs_allinfo->datafile.NrBins-1.0)/(float)twodfs_allinfo->datafile.NrBins;
}
float f2_resolution;
f2_resolution = (twodfs_allinfo->f2_max - twodfs_allinfo->f2_min)/(float)(twodfs_allinfo->datafile.NrBins-1);
twodfs_allinfo->f2_min -= 0.5*f2_resolution;
twodfs_allinfo->f2_max += 0.5*f2_resolution;
if(plotoptions.doFlip) {
float swap;
swap = twodfs_allinfo->f2_min;
twodfs_allinfo->f2_min = -twodfs_allinfo->f2_max;
twodfs_allinfo->f2_max = -swap;
}
}
twodfs_allinfo->f3_min = 0;
twodfs_allinfo->f3_max = 0.5;
if(twodfs_allinfo->SelectP3Integrate) {
if(twodfs_allinfo->P3IntegrateHigh > twodfs_allinfo->f3_max) {
twodfs_allinfo->P3IntegrateHigh = twodfs_allinfo->f3_max;
}
}
if(twodfs_allinfo->f3_min < 0) {
twodfs_allinfo->f3_min = 0;
}
return 1;
}
| {
"alphanum_fraction": 0.6692399423,
"avg_line_length": 41.3844155844,
"ext": "c",
"hexsha": "29647052f566fb812a8a3ebaceb1f43850d33aa8",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z",
"max_forks_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "weltevrede/psrsalsa",
"max_forks_repo_path": "src/prog/pspecFig.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008",
"max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "weltevrede/psrsalsa",
"max_issues_repo_path": "src/prog/pspecFig.c",
"max_line_length": 755,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "4c5b1b32513174ec1f6929905e67c8b9ca44e008",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "weltevrede/psrsalsa",
"max_stars_repo_path": "src/prog/pspecFig.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z",
"num_tokens": 25425,
"size": 79665
} |
/*! \file deleter.h
\brief gsl_interp_accelとgsl_splineのデリータを宣言・定義したヘッダファイル
Copyright © 2015 @dc1394 All Rights Reserved.
This software is released under the BSD 2-Clause License.
*/
#ifndef _DELETER_H_
#define _DELETER_H_
#pragma once
#include <gsl/gsl_spline.h> // for gsl_interp_accel, gsl_interp_accel_free, gsl_spline, gsl_spline_free
namespace freefallsolveeom {
//! A lambda expression.
/*!
gsl_interp_accelへのポインタを解放するラムダ式
\param acc gsl_interp_accelへのポインタ
*/
static auto const gsl_interp_accel_deleter = [](auto acc) {
gsl_interp_accel_free(acc);
};
//! A lambda expression.
/*!
gsl_splineへのポインタを解放するラムダ式
\param spline gsl_splineへのポインタ
*/
static auto const gsl_spline_deleter = [](auto spline) {
gsl_spline_free(spline);
};
}
#endif // _DELETER_H_
| {
"alphanum_fraction": 0.6889400922,
"avg_line_length": 24.1111111111,
"ext": "h",
"hexsha": "d399c0127c4710f9e669438748a12fc35f01fa51",
"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": "a44993c1f2c08bedac84af158c75933e89cc6318",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "dc1394/Freefall",
"max_forks_repo_path": "Freefall/freefallsolveeom/utility/deleter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a44993c1f2c08bedac84af158c75933e89cc6318",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "dc1394/Freefall",
"max_issues_repo_path": "Freefall/freefallsolveeom/utility/deleter.h",
"max_line_length": 107,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a44993c1f2c08bedac84af158c75933e89cc6318",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "dc1394/Freefall",
"max_stars_repo_path": "Freefall/freefallsolveeom/utility/deleter.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 272,
"size": 868
} |
/*
* BSD 3-Clause License
*
* Copyright (c) 2018, mtezych
* 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.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may 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 HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CL_CONTEXT
#define CL_CONTEXT
#ifdef __APPLE__
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif
#include <cl/Device.h>
#include <util/util.h>
#include <gsl/span>
#include <vector>
#include <cstddef>
namespace cl
{
struct Platform;
struct Context
{
cl_context clContext;
//
// @note: The NotifyCallback must be thread-safe.
//
using NotifyCallback = void (CL_CALLBACK *)
(
const char* errorInfo,
const void* privateInfo, size_t cb,
void* userData
);
Context
(
const Platform& platform,
gsl::span<const Device> devices
);
Context
(
const Platform& platform,
cl_device_type deviceType
);
~Context ();
Context (Context&& context);
Context (const Context& context) = delete;
Context& operator = (Context&& context);
Context& operator = (const Context& context) = delete;
enum class Info : cl_context_info
{
NumDevices = CL_CONTEXT_NUM_DEVICES,
ReferenceCount = CL_CONTEXT_REFERENCE_COUNT,
};
template <Info info>
auto GetInfo() const
{
auto infoSize = std::size_t { 0 };
auto result = clGetContextInfo
(
clContext, util::enum_cast(info),
0, nullptr, &infoSize
);
assert(result == CL_SUCCESS);
auto infoBytes = std::vector<std::byte>
{
infoSize, std::byte { 0x00 }
};
result = clGetContextInfo
(
clContext, util::enum_cast(info),
infoBytes.size(), infoBytes.data(), nullptr
);
assert(result == CL_SUCCESS);
return InfoResult<info>::FromBytes(infoBytes);
}
private:
template <Info info>
struct InfoResult;
};
template <>
struct Context::InfoResult<Context::Info::NumDevices>
{
static cl_uint
FromBytes (const std::vector<std::byte>& infoBytes);
};
template <>
struct Context::InfoResult<Context::Info::ReferenceCount>
{
static cl_uint
FromBytes (const std::vector<std::byte>& infoBytes);
};
}
#endif
| {
"alphanum_fraction": 0.7095577746,
"avg_line_length": 24.3402777778,
"ext": "h",
"hexsha": "bffb961727691ab5dcf4beadb54ac7303bb28613",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-07-14T23:16:23.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-12-21T00:31:17.000Z",
"max_forks_repo_head_hexsha": "05c1b85eb89117a9b406f3f32470367937331614",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "mtezych/cpp",
"max_forks_repo_path": "cl/include/cl/Context.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "05c1b85eb89117a9b406f3f32470367937331614",
"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": "mtezych/cpp",
"max_issues_repo_path": "cl/include/cl/Context.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "05c1b85eb89117a9b406f3f32470367937331614",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mtezych/cpp",
"max_stars_repo_path": "cl/include/cl/Context.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 843,
"size": 3505
} |
/* min/bracketing.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi
*
* 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.
*/
/* bracketing.c -- find an initial bracketing interval for a function to minimize */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_machine.h>
#include "min.h"
int
gsl_min_find_bracket(gsl_function *f,double *minimum,double * f_minimum,
double * x_lower, double * f_lower,
double * x_upper, double * f_upper,
size_t eval_max)
{
/* The three following variables must be declared volatile to avoid storage
in extended precision registers available on some architecture. The code
relies on the ability to compare double values. As the values will be
store in regular memory, the extended precision will then be lost and
values that are different in extended precision might have equal
representation in double precision. This behavior might break the
algorithm.
*/
volatile double f_left = *f_lower;
volatile double f_right = *f_upper;
volatile double f_center;
double x_left = *x_lower;
double x_right= *x_upper;
double x_center;
const double golden = 0.3819660; /* golden = (3 - sqrt(5))/2 */
size_t nb_eval = 0;
if (f_right >= f_left)
{
x_center = (x_right - x_left) * golden + x_left;
nb_eval++;
SAFE_FUNC_CALL (f, x_center, &f_center);
}
else
{
x_center = x_right ;
f_center = f_right ;
x_right = (x_center - x_left) / golden + x_left;
nb_eval++;
SAFE_FUNC_CALL (f, x_right, &f_right);
}
do
{
if (f_center < f_left )
{
if (f_center < f_right)
{
*x_lower = x_left;
*x_upper = x_right;
*minimum = x_center;
*f_lower = f_left;
*f_upper = f_right;
*f_minimum = f_center;
/* gsl_ieee_printf_double (&f_left);
printf(" ");
gsl_ieee_printf_double (&f_center);
printf("\n");*/
return GSL_SUCCESS;
}
else if (f_center > f_right)
{
x_left = x_center;
f_left = f_center;
x_center = x_right;
f_center = f_right;
x_right = (x_center - x_left) / golden + x_left;
nb_eval++;
SAFE_FUNC_CALL (f, x_right, &f_right);
}
else /* f_center == f_right */
{
x_right = x_center;
f_right = f_center;
x_center = (x_right - x_left) * golden + x_left;
nb_eval++;
SAFE_FUNC_CALL (f, x_center, &f_center);
}
}
else /* f_center >= f_left */
{
x_right = x_center;
f_right = f_center;
x_center = (x_right - x_left) * golden + x_left;
nb_eval++;
SAFE_FUNC_CALL (f, x_center, &f_center);
}
}
while (nb_eval < eval_max
&& (x_right - x_left) > GSL_SQRT_DBL_EPSILON * ( (x_right + x_left) * 0.5 ) + GSL_SQRT_DBL_EPSILON);
*x_lower = x_left;
*x_upper = x_right;
*minimum = x_center;
*f_lower = f_left;
*f_upper = f_right;
*f_minimum = f_center;
return GSL_FAILURE;
}
| {
"alphanum_fraction": 0.6436441817,
"avg_line_length": 29.5317460317,
"ext": "c",
"hexsha": "de869d4b94d3a159f2818f2d03fc7d8d474852cc",
"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/min/bracketing.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/min/bracketing.c",
"max_line_length": 102,
"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/min/bracketing.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": 1014,
"size": 3721
} |
/*
* C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer
*
* Yan-Rong Li, liyanrong@mail.ihep.ac.cn
* Jun 30, 2016
*
*/
#ifndef _MODEL1_H
#define _MODEL1_H
#include <stdbool.h>
#include <gsl/gsl_rng.h>
/* number of model parameters */
extern int num_params;
extern int which_level_update;
extern double *limits; // limits from dnest
extern int thistask, totaltask;
extern DNestFptrSet *fptrset_thismodel;
/* functions */
void from_prior_thismodel(void *model);
void print_particle_thismodel(FILE *fp, const void *model);
double log_likelihoods_cal_thismodel(const void *model);
double perturb_thismodel(void *model);
void restart_action_model1(int iflag);
#endif
| {
"alphanum_fraction": 0.7589670014,
"avg_line_length": 21.78125,
"ext": "h",
"hexsha": "f8f7ddbb75b44112288b74b27b882b4b0c902ee2",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/DNest_C",
"max_forks_repo_path": "src/model1.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e",
"max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "LiyrAstroph/DNest_C",
"max_issues_repo_path": "src/model1.h",
"max_line_length": 71,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/CDNest",
"max_stars_repo_path": "src/model1.h",
"max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z",
"num_tokens": 184,
"size": 697
} |
/**
*
* @file testing_ssygst.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 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_transformation(int, int, int, float*, float*, int, float*, int, float);
static int check_factorization(int, float*, float*, int, int , float);
int testing_ssygst(int argc, char **argv)
{
/* Check for number of arguments*/
if (argc != 3) {
USAGE("HEGST", "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');
int N = atoi(argv[0]);
int LDA = atoi(argv[1]);
int LDB = atoi(argv[2]);
int info_transformation, info_factorization;
int i, u;
int LDAxN = LDA*N;
int LDBxN = LDB*N;
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 *Ainit = (float *)malloc(LDAxN*sizeof(float));
float *Binit = (float *)malloc(LDBxN*sizeof(float));
/* Check if unable to allocate memory */
if ((!A1)||(!A2)||(!B1)||(!B2)||(!Ainit)||(!Binit)){
printf("Out of Memory \n ");
return -2;
}
/*----------------------------------------------------------
* TESTING SSYGST
*/
/* Initialize A1 and A2 */
PLASMA_splgsy(0., N, A1, LDA, 5198);
LAPACKE_slacpy_work(LAPACK_COL_MAJOR, 'A', N, N, A1, LDA, Ainit, LDA);
/* Initialize B1 and B2 */
PLASMA_splgsy((float)N, N, B1, LDB, 4231);
LAPACKE_slacpy_work(LAPACK_COL_MAJOR, 'A', N, N, B1, LDB, Binit, LDB);
printf("\n");
printf("------ TESTS FOR PLASMA SSYGST ROUTINE ------- \n");
printf(" Size of the Matrix %d by %d\n", N, N);
printf("\n");
printf(" The matrices A and B are 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 SSYGST
*/
for (i=0; i<3; i++) {
for (u=0; u<2; u++) {
memcpy(A2, Ainit, LDAxN*sizeof(float));
memcpy(B2, Binit, LDBxN*sizeof(float));
PLASMA_spotrf(uplo[u], N, B2, LDB);
PLASMA_ssygst(itype[i], uplo[u], N, A2, LDA, B2, LDB);
/* Check the Cholesky factorization and the transformation */
info_factorization = check_factorization(N, B1, B2, LDB, uplo[u], eps);
info_transformation = check_transformation(itype[i], uplo[u], N, A1, A2, LDA, B2, LDB, eps);
if ( (info_transformation == 0) && (info_factorization == 0) ) {
printf("***************************************************\n");
printf(" ---- TESTING SSYGST (%s, %s) ....... PASSED !\n", itypestr[i], uplostr[u]);
printf("***************************************************\n");
}
else {
printf("************************************************\n");
printf(" - TESTING SSYGST (%s, %s) ... FAILED !\n", itypestr[i], uplostr[u]);
printf("************************************************\n");
}
}
}
free(A1);
free(A2);
free(B1);
free(B2);
free(Ainit);
free(Binit);
return 0;
}
/*------------------------------------------------------------------------
* Check the factorization of the matrix A2
*/
static int check_factorization(int N, float *A1, float *A2, int LDA, int uplo, float eps)
{
float alpha = 1.0;
float Anorm, Rnorm, result;
int info_factorization;
int i,j;
float *Residual = (float *)malloc(N*N*sizeof(float));
float *L1 = (float *)malloc(N*N*sizeof(float));
float *L2 = (float *)malloc(N*N*sizeof(float));
float *work = (float *)malloc(N*sizeof(float));
memset((void*)L1, 0, N*N*sizeof(float));
memset((void*)L2, 0, N*N*sizeof(float));
LAPACKE_slacpy_work(LAPACK_COL_MAJOR,' ', N, N, A1, LDA, Residual, N);
/* Dealing with L'L or U'U */
LAPACKE_slacpy_work(LAPACK_COL_MAJOR, lapack_const(uplo), N, N, A2, LDA, L1, N);
LAPACKE_slacpy_work(LAPACK_COL_MAJOR, lapack_const(uplo), N, N, A2, LDA, L2, N);
if (uplo == PlasmaUpper)
cblas_strmm(CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo, CblasTrans, CblasNonUnit, N, N, (alpha), L1, N, L2, N);
else
cblas_strmm(CblasColMajor, CblasRight, (CBLAS_UPLO)uplo, CblasTrans, CblasNonUnit, N, N, (alpha), L1, N, L2, N);
/* Compute the Residual || A - L'L|| */
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
Residual[j*N+i] = L2[j*N+i] - Residual[j*N+i];
Rnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, N, Residual, N, work);
Anorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, N, A1, LDA, work);
result = Rnorm / ( Anorm * N * eps );
printf("============\n");
printf("Checking the Cholesky Factorization \n");
printf("-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \n", result);
if ( isnan(result) || isinf(result) || (result > 60.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 Transformation to standard eigenvalue problem
*/
static int check_transformation(int itype, int uplo, int N, float *A1, float *A2, int LDA, float *B2, int LDB, float eps)
{
float alpha = 1.0;
float Anorm, Rnorm, result;
int info_transformation;
int i, j;
char *str;
float *Residual = (float *)malloc(N*N*sizeof(float));
float *Aorig = (float *)malloc(N*N*sizeof(float));
float *work = (float *)malloc(N*sizeof(float));
LAPACKE_slacpy_work(LAPACK_COL_MAJOR, 'a', N, N, A1, LDA, Residual, N);
LAPACKE_slacpy_work(LAPACK_COL_MAJOR, lapack_const(uplo), N, N, A2, LDA, Aorig, N);
/* Rebuild the symmetry of A2 */
if (uplo == PlasmaLower) {
for (j = 0; j < N; j++)
for (i = j+1; i < N; i++)
Aorig[j+i*N] = (Aorig[i+j*N]);
} else {
for (i = 0; i < N; i++)
for (j = i+1; j < N; j++)
Aorig[j+i*N] = (Aorig[i+j*N]);
}
if (itype == 1) {
if (uplo == PlasmaLower) {
str = "L*A2*L'";
cblas_strmm(CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasNonUnit, N, N, (alpha), B2, LDB, Aorig, N);
cblas_strmm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit, N, N, (alpha), B2, LDB, Aorig, N);
}
else{
str = "U'*A2*U";
cblas_strmm(CblasColMajor, CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, N, N, (alpha), B2, LDB, Aorig, N);
cblas_strmm(CblasColMajor, CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, N, N, (alpha), B2, LDB, Aorig, N);
}
}
else {
if (uplo == PlasmaLower) {
str = "inv(L')*A2*inv(L)";
cblas_strsm(CblasColMajor, CblasLeft, CblasLower, CblasTrans, CblasNonUnit, N, N, (alpha), B2, LDB, Aorig, N);
cblas_strsm(CblasColMajor, CblasRight, CblasLower, CblasNoTrans, CblasNonUnit, N, N, (alpha), B2, LDB, Aorig, N);
}
else{
str = "inv(U)*A2*inv(U')";
cblas_strsm(CblasColMajor, CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, N, N, (alpha), B2, LDB, Aorig, N);
cblas_strsm(CblasColMajor, CblasRight, CblasUpper, CblasTrans, CblasNonUnit, N, N, (alpha), B2, LDB, Aorig, N);
}
}
/* Compute the Residual ( A1 - W ) */
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
Residual[j*N+i] = Aorig[j*N+i] - Residual[j*N+i];
Rnorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, N, Residual, N, work);
Anorm = LAPACKE_slange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), N, N, A1, LDA, work);
result = Rnorm / (Anorm * N *eps);
printf("============\n");
printf("Checking the global transformation \n");
printf("-- ||A1-%s||_oo/(||A1||_oo.N.eps) = %e \n", str, result );
if (isnan(result) || isinf(result) || (result > 60.0) ) {
printf("-- Transformation is suspicious ! \n");
info_transformation = 1;
}
else {
printf("-- Transformation is CORRECT ! \n");
info_transformation = 0;
}
free(Residual); free(Aorig); free(work);
return info_transformation;
}
| {
"alphanum_fraction": 0.5336271115,
"avg_line_length": 36.5172413793,
"ext": "c",
"hexsha": "a0528339ced2c9280fe32417433b00c25b3c4902",
"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_ssygst.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_ssygst.c",
"max_line_length": 130,
"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_ssygst.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2940,
"size": 9531
} |
/*
cp ../../../../native_ref/<target binary> libnetlib.so
gcc-mp-4.8 -O3 ddottest.c common.c -o ddottest -L. -lnetlib -I../../../../netlib/CBLAS
./ddottest > ../../../results/mac_os_x-x86_64-ddot-CBLAS.csv
gcc-mp-4.8 -O3 ddottest.c common.c -o ddottest -I/System/Library/Frameworks/vecLib.framework/Headers -framework veclib
./ddottest > ../../../results/mac_os_x-x86_64-ddot-veclib.csv
gcc-mp-4.8 -O3 ddottest.c common.c -o ddottest -I/opt/local/include /opt/local/lib/libatlas.a /opt/local/lib/libcblas.a /opt/local/lib/liblapack.a /opt/local/lib/libf77blas.a -lgfortran
./ddottest > ../../../results/mac_os_x-x86_64-ddot-atlas.csv
gcc-mp-4.8 -O3 ddottest.c common.c -o ddottest -I../../../../netlib/CBLAS -L/opt/intel/composerxe/mkl/lib -lmkl_rt
export DYLD_LIBRARY_PATH=/opt/intel/composerxe/mkl/lib:/opt/intel/composerxe/lib/
./ddottest > ../../../results/mac_os_x-x86_64-ddot-mkl.csv
gcc-mp-4.8 -O3 ddottest.c cudawrapper.c common.c -o ddottest -I../../../../netlib/CBLAS -I/usr/local/cuda/include/ -L/usr/local/cuda/lib -lcublas
export DYLD_LIBRARY_PATH=/usr/local/cuda/lib
./ddottest > ../../../results/mac_os_x-x86_64-ddot-cuda.csv
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cblas.h>
#include "common.h"
long benchmark(int size) {
long requestStart, requestEnd;
double* a = random_array(size);
double* b = random_array(size);
requestStart = currentTimeNanos();
cblas_ddot(size, a, 1, b, 1);
requestEnd = currentTimeNanos();
free(a);
free(b);
return (requestEnd - requestStart);
}
main()
{
srand(time(NULL));
double factor = 6.0 / 100.0;
int i, j;
for (i = 0 ; i < 10 ; i++) {
for (j = 1 ; j <= 100 ; j++) {
int size = (int) pow(10.0, factor * j);
if (size < 10) continue;
long took = benchmark(size);
printf("\"%d\",\"%lu\"\n", size, took);
}
}
} | {
"alphanum_fraction": 0.6362212944,
"avg_line_length": 29.9375,
"ext": "c",
"hexsha": "b30efc3901a29d1754894d8ceb6c76f3ae47e45c",
"lang": "C",
"max_forks_count": 154,
"max_forks_repo_forks_event_max_datetime": "2021-09-07T04:58:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-03T22:48:26.000Z",
"max_forks_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "debasish83/netlib-java",
"max_forks_repo_path": "perf/src/main/c/ddottest.c",
"max_issues_count": 59,
"max_issues_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3",
"max_issues_repo_issues_event_max_datetime": "2017-07-24T14:20:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-01T10:34:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "debasish83/netlib-java",
"max_issues_repo_path": "perf/src/main/c/ddottest.c",
"max_line_length": 185,
"max_stars_count": 624,
"max_stars_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "debasish83/netlib-java",
"max_stars_repo_path": "perf/src/main/c/ddottest.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-26T22:06:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-10T02:29:22.000Z",
"num_tokens": 619,
"size": 1916
} |
#include <stdio.h>
#include <gsl/gsl_sf_bessel.h>
int
main (void)
{
double x = 5.0;
double y = gsl_sf_bessel_J0 (x);
printf ("J0(%g) = %.18e\n", x, y);
return 0;
}
| {
"alphanum_fraction": 0.5953757225,
"avg_line_length": 14.4166666667,
"ext": "c",
"hexsha": "bd2848271477d2a12511abc2bebaa3897438b51e",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/intro.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/intro.c",
"max_line_length": 36,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/intro.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": 69,
"size": 173
} |
/*! \file allvars.h
* \brief declares global variables.
*
* This file declares all global variables. Further variables should be added here, and declared as
* 'extern'. The actual existence of these variables is provided by the file 'allvars.c'. To produce
* 'allvars.c' from 'allvars.h', do the following:
*
* - Erase all #define's, typedef's, and enum's
* - add #include "allvars.h", delete the #ifndef ALLVARS_H conditional
* - delete all keywords 'extern'
* - delete all struct definitions enclosed in {...}, e.g.
* "extern struct global_data_all_processes {....} All;"
* becomes "struct global_data_all_processes All;"
*/
#ifndef ALLVARS_H
#define ALLVARS_H
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include "tags.h"
#define GADGETVERSION "2.0" /*!< code version string */
#define TIMEBASE (1<<28) /*!< The simulated timespan is mapped onto the integer interval [0,TIMESPAN],
* where TIMESPAN needs to be a power of 2. Note that (1<<28) corresponds to 2^29
*/
#define MAXTOPNODES 200000 /*!< Maximum number of nodes in the top-level tree used for domain decomposition */
typedef long long peanokey; /*!< defines the variable type used for Peano-Hilbert keys */
#define BITS_PER_DIMENSION 18 /*!< Bits per dimension available for Peano-Hilbert order.
Note: If peanokey is defined as type int, the allowed maximum is 10.
If 64-bit integers are used, the maximum is 21 */
#define PEANOCELLS (((peanokey)1)<<(3*BITS_PER_DIMENSION)) /*!< The number of different Peano-Hilbert cells */
#define RNDTABLE 3000 /*!< gives the length of a table with random numbers, refreshed at every timestep.
This is used to allow application of random numbers to a specific particle
in a way that is independent of the number of processors used. */
#define MAX_REAL_NUMBER 1e37
#define MIN_REAL_NUMBER 1e-37
#define MAXLEN_FILENAME 4096 /*!< Maximum number of characters for filenames (including the full path) */
#ifdef ISOTHERM_EQS
#define GAMMA (1.0) /*!< index for isothermal gas */
#else
#define GAMMA (5.0/3) /*!< adiabatic index of simulated gas */
#endif
#define GAMMA_MINUS1 (GAMMA-1)
#define HYDROGEN_MASSFRAC 0.76 /*!< mass fraction of hydrogen, relevant only for radiative cooling */
/* Some physical constants in cgs units */
#define GRAVITY 6.672e-8 /*!< Gravitational constant (in cgs units) */
#define SOLAR_MASS 1.989e33
#define SOLAR_LUM 3.826e33
#define RAD_CONST 7.565e-15
#define AVOGADRO 6.0222e23
#define BOLTZMANN 1.3806e-16
#define GAS_CONST 8.31425e7
#define C 2.9979e10
#define PLANCK 6.6262e-27
#define CM_PER_MPC 3.085678e24
#define PROTONMASS 1.6726e-24
#define ELECTRONMASS 9.10953e-28
#define THOMPSON 6.65245e-25
#define ELECTRONCHARGE 4.8032e-10
#define HUBBLE 3.2407789e-18 /* in h/sec */
/* Some conversion factors */
#define SEC_PER_MEGAYEAR 3.155e13
#define SEC_PER_YEAR 3.155e7
#ifndef ASMTH
#define ASMTH 1.25 /*!< ASMTH gives the scale of the short-range/long-range force split in units of FFT-mesh cells */
#endif
#ifndef RCUT
#define RCUT 4.5 /*!< RCUT gives the maximum distance (in units of the scale used for the force split) out to
which short-range forces are evaluated in the short-range tree walk. */
#endif
#define MAX_NGB 20000 /*!< defines maximum length of neighbour list */
#define MAXLEN_OUTPUTLIST 500 /*!< maxmimum number of entries in list of snapshot output times */
#define DRIFT_TABLE_LENGTH 1000 /*!< length of the lookup table used to hold the drift and kick factors */
#define MAXITER 150 /*!< maxmimum number of steps for SPH neighbour iteration */
#ifdef DOUBLEPRECISION /*!< If defined, the variable type FLOAT is set to "double", otherwise to FLOAT */
#define FLOAT double
#else
#define FLOAT float
#endif
#ifndef TWODIMS
#define NUMDIMS 3 /*!< For 3D-normalized kernel */
#define KERNEL_COEFF_1 2.546479089470 /*!< Coefficients for SPH spline kernel and its derivative */
#define KERNEL_COEFF_2 15.278874536822
#define KERNEL_COEFF_3 45.836623610466
#define KERNEL_COEFF_4 30.557749073644
#define KERNEL_COEFF_5 5.092958178941
#define KERNEL_COEFF_6 (-15.278874536822)
#define NORM_COEFF 4.188790204786 /*!< Coefficient for kernel normalization. Note: 4.0/3 * PI = 4.188790204786 */
#else
#define NUMDIMS 2 /*!< For 2D-normalized kernel */
#define KERNEL_COEFF_1 (5.0/7*2.546479089470) /*!< Coefficients for SPH spline kernel and its derivative */
#define KERNEL_COEFF_2 (5.0/7*15.278874536822)
#define KERNEL_COEFF_3 (5.0/7*45.836623610466)
#define KERNEL_COEFF_4 (5.0/7*30.557749073644)
#define KERNEL_COEFF_5 (5.0/7*5.092958178941)
#define KERNEL_COEFF_6 (5.0/7*(-15.278874536822))
#define NORM_COEFF M_PI /*!< Coefficient for kernel normalization. */
#endif
extern int ThisTask; /*!< the rank of the local processor */
extern int NTask; /*!< number of processors */
extern int PTask; /*!< smallest integer such that NTask <= 2^PTask */
extern int NumPart; /*!< number of particles on the LOCAL processor */
extern int N_gas; /*!< number of gas particles on the LOCAL processor */
extern long long Ntype[6]; /*!< total number of particles of each type */
extern int NtypeLocal[6]; /*!< local number of particles of each type */
extern int NumForceUpdate; /*!< number of active particles on local processor in current timestep */
extern int NumSphUpdate; /*!< number of active SPH particles on local processor in current timestep */
extern double CPUThisRun; /*!< Sums the CPU time for the process (current submission only) */
extern int RestartFlag; /*!< taken from command line used to start code. 0 is normal start-up from
initial conditions, 1 is resuming a run from a set of restart files, while 2
marks a restart from a snapshot file. */
extern char *Exportflag; /*!< Buffer used for flagging whether a particle needs to be exported to another process */
extern int *Ngblist; /*!< Buffer to hold indices of neighbours retrieved by the neighbour search routines */
extern int TreeReconstructFlag; /*!< Signals that a new tree needs to be constructed */
extern int Flag_FullStep; /*!< This flag signals that the current step involves all particles */
extern int ZeroTimestepEncountered; /*!< Flag used by AMUSE. When a particle is assigned a timestep of zero, an
exception is raised instead of forcing the application to exit. */
extern gsl_rng *random_generator; /*!< the employed random number generator of the GSL library */
extern double RndTable[RNDTABLE]; /*!< Hold a table with random numbers, refreshed every timestep */
extern double DomainCorner[3]; /*!< gives the lower left corner of simulation volume */
extern double DomainCenter[3]; /*!< gives the center of simulation volume */
extern double DomainLen; /*!< gives the (maximum) side-length of simulation volume */
extern double DomainFac; /*!< factor used for converting particle coordinates to a Peano-Hilbert mesh covering the simulation volume */
extern int DomainMyStart; /*!< first domain mesh cell that resides on the local processor */
extern int DomainMyLast; /*!< last domain mesh cell that resides on the local processor */
extern int *DomainStartList; /*!< a table that lists the first domain mesh cell for all processors */
extern int *DomainEndList; /*!< a table that lists the last domain mesh cell for all processors */
extern double *DomainWork; /*!< a table that gives the total "work" due to the particles stored by each processor */
extern int *DomainCount; /*!< a table that gives the total number of particles held by each processor */
extern int *DomainCountSph; /*!< a table that gives the total number of SPH particles held by each processor */
extern int *DomainTask; /*!< this table gives for each leaf of the top-level tree the processor it was assigned to */
extern int *DomainNodeIndex; /*!< this table gives for each leaf of the top-level tree the corresponding node of the gravitational tree */
extern FLOAT *DomainTreeNodeLen; /*!< this table gives for each leaf of the top-level tree the side-length of the corresponding node of the gravitational tree */
extern FLOAT *DomainHmax; /*!< this table gives for each leaf of the top-level tree the maximum SPH smoothing length among the particles of the corresponding node of the gravitational tree */
extern struct DomainNODE
{
FLOAT s[3]; /*!< center-of-mass coordinates */
FLOAT vs[3]; /*!< center-of-mass velocities */
FLOAT mass; /*!< mass of node */
#ifdef UNEQUALSOFTENINGS
#ifndef ADAPTIVE_GRAVSOFT_FORGAS
int bitflags; /*!< this bit-field encodes the particle type with the largest softening among the particles of the nodes, and whether there are particles with different softening in the node */
#else
FLOAT maxsoft; /*!< hold the maximum gravitational softening of particles in the
node if the ADAPTIVE_GRAVSOFT_FORGAS option is selected */
#endif
#endif
}
*DomainMoment; /*!< this table stores for each node of the top-level tree corresponding node data from the gravitational tree */
extern peanokey *DomainKeyBuf; /*!< this points to a buffer used during the exchange of particle data */
extern peanokey *Key; /*!< a table used for storing Peano-Hilbert keys for particles */
extern peanokey *KeySorted; /*!< holds a sorted table of Peano-Hilbert keys for all particles, used to construct top-level tree */
extern int NTopnodes; /*!< total number of nodes in top-level tree */
extern int NTopleaves; /*!< number of leaves in top-level tree. Each leaf can be assigned to a different processor */
extern struct topnode_data
{
int Daughter; /*!< index of first daughter cell (out of 8) of top-level node */
int Pstart; /*!< for the present top-level node, this gives the index of the first node in the concatenated list of topnodes collected from all processors */
int Blocks; /*!< for the present top-level node, this gives the number of corresponding nodes in the concatenated list of topnodes collected from all processors */
int Leaf; /*!< if the node is a leaf, this gives its number when all leaves are traversed in Peano-Hilbert order */
peanokey Size; /*!< number of Peano-Hilbert mesh-cells represented by top-level node */
peanokey StartKey; /*!< first Peano-Hilbert key in top-level node */
long long Count; /*!< counts the number of particles in this top-level node */
}
*TopNodes; /*!< points to the root node of the top-level tree */
extern double TimeOfLastTreeConstruction; /*!< holds what it says, only used in connection with FORCETEST */
/* variables for input/output, usually only used on process 0 */
extern char ParameterFile[MAXLEN_FILENAME]; /*!< file name of parameterfile used for starting the simulation */
extern FILE *FdInfo; /*!< file handle for info.txt log-file. */
extern FILE *FdEnergy; /*!< file handle for energy.txt log-file. */
extern FILE *FdTimings; /*!< file handle for timings.txt log-file. */
extern FILE *FdCPU; /*!< file handle for cpu.txt log-file. */
#ifdef FORCETEST
extern FILE *FdForceTest; /*!< file handle for forcetest.txt log-file. */
#endif
extern double DriftTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological drift factors */
extern double GravKickTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological kick factor for gravitational forces */
extern double HydroKickTable[DRIFT_TABLE_LENGTH]; /*!< table for the cosmological kick factor for hydrodynmical forces */
extern void *CommBuffer; /*!< points to communication buffer, which is used in the domain decomposition, the
parallel tree-force computation, the SPH routines, etc. */
/*! This structure contains data which is the SAME for all tasks (mostly code parameters read from the
* parameter file). Holding this data in a structure is convenient for writing/reading the restart file, and
* it allows the introduction of new global variables in a simple way. The only thing to do is to introduce
* them into this structure.
*/
extern struct global_data_all_processes
{
long long TotNumPart; /*!< total particle numbers (global value) */
long long TotN_gas; /*!< total gas particle number (global value) */
int MaxPart; /*!< This gives the maxmimum number of particles that can be stored on one processor. */
int MaxPartSph; /*!< This gives the maxmimum number of SPH particles that can be stored on one processor. */
double BoxSize; /*!< Boxsize in case periodic boundary conditions are used */
int ICFormat; /*!< selects different versions of IC file-format */
int SnapFormat; /*!< selects different versions of snapshot file-formats */
int NumFilesPerSnapshot; /*!< number of files in multi-file snapshot dumps */
int NumFilesWrittenInParallel;/*!< maximum number of files that may be written simultaneously when
writing/reading restart-files, or when writing snapshot files */
int BufferSize; /*!< size of communication buffer in MB */
int BunchSizeForce; /*!< number of particles fitting into the buffer in the parallel tree-force algorithm */
int BunchSizeDensity; /*!< number of particles fitting into the communication buffer in the density computation */
int BunchSizeHydro; /*!< number of particles fitting into the communication buffer in the SPH hydrodynamical force computation */
int BunchSizeDomain; /*!< number of particles fitting into the communication buffer in the domain decomposition */
double PartAllocFactor; /*!< in order to maintain work-load balance, the particle load will usually
NOT be balanced. Each processor allocates memory for PartAllocFactor times
the average number of particles to allow for that */
double TreeAllocFactor; /*!< Each processor allocates a number of nodes which is TreeAllocFactor times
the maximum(!) number of particles. Note: A typical local tree for N
particles needs usually about ~0.65*N nodes. */
/* some SPH parameters */
double DesNumNgb; /*!< Desired number of SPH neighbours */
double MaxNumNgbDeviation; /*!< Maximum allowed deviation neighbour number */
double ArtBulkViscConst; /*!< Sets the parameter \f$\alpha\f$ of the artificial viscosity */
double ArtBulkViscBeta; /*!< Sets the parameter \f$\beta\f$ of the artificial viscosity */
double InitGasTemp; /*!< may be used to set the temperature in the IC's */
double MinGasTemp; /*!< may be used to set a floor for the gas temperature */
double MinEgySpec; /*!< the minimum allowed temperature expressed as energy per unit mass */
/* some force counters */
long long TotNumOfForces; /*!< counts total number of force computations */
long long NumForcesSinceLastDomainDecomp; /*!< count particle updates since last domain decomposition */
/* system of units */
double G; /*!< Gravity-constant in internal units */
double UnitTime_in_s; /*!< factor to convert internal time unit to seconds/h */
double UnitMass_in_g; /*!< factor to convert internal mass unit to grams/h */
double UnitVelocity_in_cm_per_s; /*!< factor to convert intqernal velocity unit to cm/sec */
double UnitLength_in_cm; /*!< factor to convert internal length unit to cm/h */
double UnitPressure_in_cgs; /*!< factor to convert internal pressure unit to cgs units (little 'h' still around!) */
double UnitDensity_in_cgs; /*!< factor to convert internal length unit to g/cm^3*h^2 */
double UnitCoolingRate_in_cgs; /*!< factor to convert internal cooling rate to cgs units */
double UnitEnergy_in_cgs; /*!< factor to convert internal energy to cgs units */
double UnitTime_in_Megayears; /*!< factor to convert internal time to megayears/h */
double GravityConstantInternal; /*!< If set to zero in the parameterfile, the internal value of the
gravitational constant is set to the Newtonian value based on the system of
units specified. Otherwise the value provided is taken as internal gravity constant G. */
/* Cosmological parameters */
double Hubble; /*!< Hubble-constant in internal units */
double Omega0; /*!< matter density in units of the critical density (at z=0)*/
double OmegaLambda; /*!< vaccum energy density relative to crictical density (at z=0) */
double OmegaBaryon; /*!< baryon density in units of the critical density (at z=0)*/
double HubbleParam; /*!< little `h', i.e. Hubble constant in units of 100 km/s/Mpc. Only needed to get absolute physical values for cooling physics */
/* Code options */
int ComovingIntegrationOn; /*!< flags that comoving integration is enabled */
int PeriodicBoundariesOn; /*!< flags that periodic boundaries are enabled */
int ResubmitOn; /*!< flags that automatic resubmission of job to queue system is enabled */
int TypeOfOpeningCriterion; /*!< determines tree cell-opening criterion: 0 for Barnes-Hut, 1 for relative criterion */
int TypeOfTimestepCriterion; /*!< gives type of timestep criterion (only 0 supported right now - unlike gadget-1.1) */
int OutputListOn; /*!< flags that output times are listed in a specified file */
/* Parameters determining output frequency */
int SnapshotFileCount; /*!< number of snapshot that is written next */
double TimeBetSnapshot; /*!< simulation time interval between snapshot files */
double TimeOfFirstSnapshot; /*!< simulation time of first snapshot files */
double CpuTimeBetRestartFile; /*!< cpu-time between regularly generated restart files */
double TimeLastRestartFile; /*!< cpu-time when last restart-file was written */
double TimeBetStatistics; /*!< simulation time interval between computations of energy statistics */
double TimeLastStatistics; /*!< simulation time when the energy statistics was computed the last time */
int NumCurrentTiStep; /*!< counts the number of system steps taken up to this point */
/* Current time of the simulation, global step, and end of simulation */
double Time; /*!< current time of the simulation */
double TimeBegin; /*!< time of initial conditions of the simulation */
double TimeStep; /*!< difference between current times of previous and current timestep */
double TimeMax; /*!< marks the point of time until the simulation is to be evolved */
/* variables for organizing discrete timeline */
double Timebase_interval; /*!< factor to convert from floating point time interval to integer timeline */
int Ti_Current; /*!< current time on integer timeline */
int Ti_nextoutput; /*!< next output time on integer timeline */
#ifdef FLEXSTEPS
int PresentMinStep; /*!< If FLEXSTEPS is used, particle timesteps are chosen as multiples of the present minimum timestep. */
int PresentMaxStep; /*!< If FLEXSTEPS is used, this is the maximum timestep in timeline units, rounded down to the next power 2 division */
#endif
#ifdef PMGRID
int PM_Ti_endstep; /*!< begin of present long-range timestep */
int PM_Ti_begstep; /*!< end of present long-range timestep */
#endif
/* Placement of PM grids */
#ifdef PMGRID
double Asmth[2]; /*!< Gives the scale of the long-range/short-range split (in mesh-cells), both for the coarse and the high-res mesh */
double Rcut[2]; /*!< Gives the maximum radius for which the short-range force is evaluated with the tree (in mesh-cells), both for the coarse and the high-res mesh */
double Corner[2][3]; /*!< lower left corner of coarse and high-res PM-mesh */
double UpperCorner[2][3]; /*!< upper right corner of coarse and high-res PM-mesh */
double Xmintot[2][3]; /*!< minimum particle coordinates both for coarse and high-res PM-mesh */
double Xmaxtot[2][3]; /*!< maximum particle coordinates both for coarse and high-res PM-mesh */
double TotalMeshSize[2]; /*!< total extension of coarse and high-res PM-mesh */
#endif
/* Variables that keep track of cumulative CPU consumption */
double TimeLimitCPU; /*!< CPU time limit as defined in parameterfile */
double CPU_TreeConstruction; /*!< time spent for constructing the gravitational tree */
double CPU_TreeWalk; /*!< actual time spent for pure tree-walks */
double CPU_Gravity; /*!< cumulative time used for gravity computation (tree-algorithm only) */
double CPU_Potential; /*!< time used for computing gravitational potentials */
double CPU_Domain; /*!< cumulative time spent for domain decomposition */
double CPU_Snapshot; /*!< time used for writing snapshot files */
double CPU_Total; /*!< cumulative time spent for domain decomposition */
double CPU_CommSum; /*!< accumulated time used for communication, and for collecting partial results, in tree-gravity */
double CPU_Imbalance; /*!< cumulative time lost accross all processors as work-load imbalance in gravitational tree */
double CPU_HydCompWalk; /*!< time used for actual SPH computations, including neighbour search */
double CPU_HydCommSumm; /*!< cumulative time used for communication in SPH, and for collecting partial results */
double CPU_HydImbalance; /*!< cumulative time lost due to work-load imbalance in SPH */
double CPU_Hydro; /*!< cumulative time spent for SPH related computations */
double CPU_EnsureNgb; /*!< time needed to iterate on correct neighbour numbers */
double CPU_Predict; /*!< cumulative time to drift the system forward in time, including dynamic tree updates */
double CPU_TimeLine; /*!< time used for determining new timesteps, and for organizing the timestepping, including kicks of active particles */
double CPU_PM; /*!< time used for long-range gravitational force */
double CPU_Peano; /*!< time required to establish Peano-Hilbert order */
/* tree code opening criterion */
double ErrTolTheta; /*!< BH tree opening angle */
double ErrTolForceAcc; /*!< parameter for relative opening criterion in tree walk */
/* adjusts accuracy of time-integration */
double ErrTolIntAccuracy; /*!< accuracy tolerance parameter \f$ \eta \f$ for timestep criterion. The
timestep is \f$ \Delta t = \sqrt{\frac{2 \eta eps}{a}} \f$ */
double MinSizeTimestep; /*!< minimum allowed timestep. Normally, the simulation terminates if the
timestep determined by the timestep criteria falls below this limit. */
double MaxSizeTimestep; /*!< maximum allowed timestep */
double MaxRMSDisplacementFac; /*!< this determines a global timestep criterion for cosmological simulations
in comoving coordinates. To this end, the code computes the rms velocity
of all particles, and limits the timestep such that the rms displacement
is a fraction of the mean particle separation (determined from the
particle mass and the cosmological parameters). This parameter specifies
this fraction. */
double CourantFac; /*!< SPH-Courant factor */
int BunchSizeTime; /*!< number of particles fitting into the communication buffer in the timestep communication */
/* frequency of tree reconstruction/domain decomposition */
double TreeDomainUpdateFrequency; /*!< controls frequency of domain decompositions */
/* Gravitational and hydrodynamical softening lengths (given in terms of an `equivalent' Plummer softening length).
* Five groups of particles are supported 0="gas", 1="halo", 2="disk", 3="bulge", 4="stars", 5="bndry"
*/
double MinGasHsmlFractional; /*!< minimum allowed SPH smoothing length in units of SPH gravitational softening length */
double MinGasHsml; /*!< minimum allowed SPH smoothing length */
double SofteningGas; /*!< comoving gravitational softening lengths for type 0 */
double SofteningHalo; /*!< comoving gravitational softening lengths for type 1 */
double SofteningDisk; /*!< comoving gravitational softening lengths for type 2 */
double SofteningBulge; /*!< comoving gravitational softening lengths for type 3 */
double SofteningStars; /*!< comoving gravitational softening lengths for type 4 */
double SofteningBndry; /*!< comoving gravitational softening lengths for type 5 */
double SofteningGasMaxPhys; /*!< maximum physical softening length for type 0 */
double SofteningHaloMaxPhys; /*!< maximum physical softening length for type 1 */
double SofteningDiskMaxPhys; /*!< maximum physical softening length for type 2 */
double SofteningBulgeMaxPhys; /*!< maximum physical softening length for type 3 */
double SofteningStarsMaxPhys; /*!< maximum physical softening length for type 4 */
double SofteningBndryMaxPhys; /*!< maximum physical softening length for type 5 */
double SofteningTable[6]; /*!< current (comoving) gravitational softening lengths for each particle type */
double ForceSoftening[6]; /*!< the same, but multiplied by a factor 2.8 - at that scale the force is Newtonian */
double MassTable[6]; /*!< Table with particle masses for particle types with equal mass.
If particle masses are all equal for one type, the corresponding entry in MassTable
is set to this value, allowing the size of the snapshot files to be reduced. */
/* some filenames */
char InitCondFile[MAXLEN_FILENAME]; /*!< filename of initial conditions */
char OutputDir[MAXLEN_FILENAME]; /*!< output directory of the code */
char SnapshotFileBase[MAXLEN_FILENAME]; /*!< basename to construct the names of snapshotf files */
char EnergyFile[MAXLEN_FILENAME]; /*!< name of file with energy statistics */
char CpuFile[MAXLEN_FILENAME]; /*!< name of file with cpu-time statistics */
char InfoFile[MAXLEN_FILENAME]; /*!< name of log-file with a list of the timesteps taken */
char TimingsFile[MAXLEN_FILENAME]; /*!< name of file with performance metrics of gravitational tree algorithm */
char RestartFile[MAXLEN_FILENAME]; /*!< basename of restart-files */
char ResubmitCommand[MAXLEN_FILENAME]; /*!< name of script-file that will be executed for automatic restart */
char OutputListFilename[MAXLEN_FILENAME]; /*!< name of file with list of desired output times */
double OutputListTimes[MAXLEN_OUTPUTLIST]; /*!< table with desired output times */
int OutputListLength; /*!< number of output times stored in the table of desired output times */
}
All; /*!< a container variable for global variables that are equal on all processors */
/*! This structure holds all the information that is
* stored for each particle of the simulation.
*/
extern struct particle_data
{
FLOAT Pos[3]; /*!< particle position at its current time */
FLOAT Mass; /*!< particle mass */
FLOAT Vel[3]; /*!< particle velocity at its current time */
FLOAT GravAccel[3]; /*!< particle acceleration due to gravity */
#ifdef PMGRID
FLOAT GravPM[3]; /*!< particle acceleration due to long-range PM gravity force*/
#endif
#ifdef FORCETEST
FLOAT GravAccelDirect[3]; /*!< particle acceleration when computed with direct summation */
#endif
FLOAT Potential; /*!< gravitational potential */
FLOAT OldAcc; /*!< magnitude of old gravitational force. Used in relative opening criterion */
#ifndef LONGIDS
unsigned int ID; /*!< particle identifier */
#else
unsigned long long ID; /*!< particle identifier */
#endif
int Type; /*!< flags particle type. 0=gas, 1=halo, 2=disk, 3=bulge, 4=stars, 5=bndry */
int Ti_endstep; /*!< marks start of current timestep of particle on integer timeline */
int Ti_begstep; /*!< marks end of current timestep of particle on integer timeline */
#ifdef TIMESTEP_LIMITER
int Ti_sizestep;
#endif
#ifdef FLEXSTEPS
int FlexStepGrp; /*!< a random 'offset' on the timeline to create a smooth groouping of particles */
#endif
float GravCost; /*!< weight factor used for balancing the work-load */
#ifdef PSEUDOSYMMETRIC
float AphysOld; /*!< magnitude of acceleration in last timestep. Used to make a first order
prediction of the change of acceleration expected in the future, thereby
allowing to guess whether a decrease/increase of the timestep should occur
in the timestep that is started. */
#endif
}
*P, /*!< holds particle data on local processor */
*DomainPartBuf; /*!< buffer for particle data used in domain decomposition */
/* the following struture holds data that is stored for each SPH particle in addition to the collisionless
* variables.
*/
extern struct sph_particle_data
{
FLOAT Entropy; /*!< current value of entropy (actually entropic function) of particle */
FLOAT Density; /*!< current baryonic mass density of particle */
FLOAT Hsml; /*!< current smoothing length */
FLOAT Left; /*!< lower bound in iterative smoothing length search */
FLOAT Right; /*!< upper bound in iterative smoothing length search */
FLOAT NumNgb; /*!< weighted number of neighbours found */
FLOAT Pressure; /*!< current pressure */
FLOAT DtEntropy; /*!< rate of change of entropy */
FLOAT HydroAccel[3]; /*!< acceleration due to hydrodynamical force */
FLOAT VelPred[3]; /*!< predicted SPH particle velocity at the current time */
FLOAT DivVel; /*!< local velocity divergence */
FLOAT CurlVel; /*!< local velocity curl */
FLOAT Rot[3]; /*!< local velocity curl */
FLOAT DhsmlDensityFactor; /*!< correction factor needed in the equation of motion of the conservative entropy formulation of SPH */
FLOAT MaxSignalVel; /*!< maximum "signal velocity" occuring for this particle */
#ifdef TIMESTEP_UPDATE
int FeedbackFlag;
FLOAT FeedAccel[3]; /*!< acceleration due to feedback force */
#endif
#ifdef MORRIS97VISC
FLOAT Alpha; /*!< viscosity coefficient */
FLOAT DAlphaDt; /*!< time rate of change of viscosity coefficient */
#endif
}
*SphP, /*!< holds SPH particle data on local processor */
*DomainSphBuf; /*!< buffer for SPH particle data in domain decomposition */
/* Variables for Tree
*/
extern int MaxNodes; /*!< maximum allowed number of internal nodes */
extern int Numnodestree; /*!< number of (internal) nodes in each tree */
extern struct NODE
{
FLOAT len; /*!< sidelength of treenode */
FLOAT center[3]; /*!< geometrical center of node */
#ifdef ADAPTIVE_GRAVSOFT_FORGAS
FLOAT maxsoft; /*!< hold the maximum gravitational softening of particles in the
node if the ADAPTIVE_GRAVSOFT_FORGAS option is selected */
#endif
union
{
int suns[8]; /*!< temporary pointers to daughter nodes */
struct
{
FLOAT s[3]; /*!< center of mass of node */
FLOAT mass; /*!< mass of node */
int bitflags; /*!< a bit-field with various information on the node */
int sibling; /*!< this gives the next node in the walk in case the current node can be used */
int nextnode; /*!< this gives the next node in case the current node needs to be opened */
int father; /*!< this gives the parent node of each node (or -1 if we have the root node) */
}
d;
}
u;
}
*Nodes_base, /*!< points to the actual memory allocted for the nodes */
*Nodes; /*!< this is a pointer used to access the nodes which is shifted such that Nodes[All.MaxPart]
gives the first allocated node */
extern int *Nextnode; /*!< gives next node in tree walk */
extern int *Father; /*!< gives parent node in tree */
extern struct extNODE /*!< this structure holds additional tree-node information which is not needed in the actual gravity computation */
{
FLOAT hmax; /*!< maximum SPH smoothing length in node. Only used for gas particles */
FLOAT vs[3]; /*!< center-of-mass velocity */
}
*Extnodes_base, /*!< points to the actual memory allocted for the extended node information */
*Extnodes; /*!< provides shifted access to extended node information, parallel to Nodes/Nodes_base */
/*! Header for the standard file format.
*/
extern struct io_header
{
int npart[6]; /*!< number of particles of each type in this file */
double mass[6]; /*!< mass of particles of each type. If 0, then the masses are explicitly
stored in the mass-block of the snapshot file, otherwise they are omitted */
double time; /*!< time of snapshot file */
double redshift; /*!< redshift of snapshot file */
int flag_sfr; /*!< flags whether the simulation was including star formation */
int flag_feedback; /*!< flags whether feedback was included (obsolete) */
unsigned int npartTotal[6]; /*!< total number of particles of each type in this snapshot. This can be
different from npart if one is dealing with a multi-file snapshot. */
int flag_cooling; /*!< flags whether cooling was included */
int num_files; /*!< number of files in multi-file snapshot */
double BoxSize; /*!< box-size of simulation in case periodic boundaries were used */
double Omega0; /*!< matter density in units of critical density */
double OmegaLambda; /*!< cosmological constant parameter */
double HubbleParam; /*!< Hubble parameter in units of 100 km/sec/Mpc */
int flag_stellarage; /*!< flags whether the file contains formation times of star particles */
int flag_metals; /*!< flags whether the file contains metallicity values for gas and star particles */
unsigned int npartTotalHighWord[6]; /*!< High word of the total number of particles of each type */
int flag_entropy_instead_u; /*!< flags that IC-file contains entropy instead of u */
char fill[60]; /*!< fills to 256 Bytes */
}
header; /*!< holds header for snapshot files */
#define IO_NBLOCKS 11 /*!< total number of defined information blocks for snapshot files.
Must be equal to the number of entries in "enum iofields" */
enum iofields /*!< this enumeration lists the defined output blocks in snapshot files. Not all of them need to be present. */
{
IO_POS,
IO_VEL,
IO_ID,
IO_MASS,
IO_U,
IO_RHO,
IO_HSML,
IO_POT,
IO_ACCEL,
IO_DTENTR,
IO_TSTP,
};
extern char Tab_IO_Labels[IO_NBLOCKS][4]; /*<! This table holds four-byte character tags used for fileformat 2 */
/* global state of system, used for global statistics
*/
extern struct state_of_system
{
double Mass;
double EnergyKin;
double EnergyPot;
double EnergyInt;
double EnergyTot;
double Momentum[4];
double AngMomentum[4];
double CenterOfMass[4];
double MassComp[6];
double EnergyKinComp[6];
double EnergyPotComp[6];
double EnergyIntComp[6];
double EnergyTotComp[6];
double MomentumComp[6][4];
double AngMomentumComp[6][4];
double CenterOfMassComp[6][4];
}
SysState; /*<! Structure for storing some global statistics about the simulation. */
/* Various structures for communication
*/
extern struct gravdata_in
{
union
{
FLOAT Pos[3];
FLOAT Acc[3];
FLOAT Potential;
}
u;
#ifdef UNEQUALSOFTENINGS
int Type;
#ifdef ADAPTIVE_GRAVSOFT_FORGAS
FLOAT Soft;
#endif
#endif
union
{
FLOAT OldAcc;
int Ninteractions;
}
w;
}
*GravDataIn, /*!< holds particle data to be exported to other processors */
*GravDataGet, /*!< holds particle data imported from other processors */
*GravDataResult, /*!< holds the partial results computed for imported particles. Note: We use GravDataResult = GravDataGet, such that the result replaces the imported data */
*GravDataOut; /*!< holds partial results received from other processors. This will overwrite the GravDataIn array */
extern struct gravdata_index
{
int Task;
int Index;
int SortIndex;
}
*GravDataIndexTable; /*!< the particles to be exported are grouped by task-number. This table allows the results to be disentangled again and to be assigned to the correct particle */
extern struct densdata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
FLOAT Hsml;
int Index;
int Task;
}
*DensDataIn, /*!< holds particle data for SPH density computation to be exported to other processors */
*DensDataGet; /*!< holds imported particle data for SPH density computation */
extern struct densdata_out
{
FLOAT Rho;
FLOAT Div, Rot[3];
FLOAT DhsmlDensity;
FLOAT Ngb;
}
*DensDataResult, /*!< stores the locally computed SPH density results for imported particles */
*DensDataPartialResult; /*!< imported partial SPH density results from other processors */
extern struct hydrodata_in
{
FLOAT Pos[3];
FLOAT Vel[3];
FLOAT Hsml;
FLOAT Mass;
FLOAT Density;
FLOAT Pressure;
FLOAT F1;
FLOAT DhsmlDensityFactor;
int Timestep;
int Task;
int Index;
#ifdef MORRIS97VISC
FLOAT Alpha;
#endif
}
*HydroDataIn, /*!< holds particle data for SPH hydro-force computation to be exported to other processors */
*HydroDataGet; /*!< holds imported particle data for SPH hydro-force computation */
extern struct hydrodata_out
{
FLOAT Acc[3];
FLOAT DtEntropy;
FLOAT MaxSignalVel;
}
*HydroDataResult, /*!< stores the locally computed SPH hydro results for imported particles */
*HydroDataPartialResult; /*!< imported partial SPH hydro-force results from other processors */
#ifdef TIMESTEP_LIMITER
extern struct timedata_in
{
FLOAT Pos[3];
FLOAT Hsml;
int Size;
int Begin;
int Index;
int Task;
}
*TimeDataIn,
*TimeDataGet;
#endif
#ifndef NOMPI
#ifdef MPI_VERSION
extern MPI_Comm GADGET_WORLD;
#endif
#endif
#endif
| {
"alphanum_fraction": 0.664437178,
"avg_line_length": 49.7142857143,
"ext": "h",
"hexsha": "c26f5a68f721c3c8af331ea5504c85837e372bb8",
"lang": "C",
"max_forks_count": 102,
"max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z",
"max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "rieder/amuse",
"max_forks_repo_path": "src/amuse/community/gadget2/src/allvars.h",
"max_issues_count": 690,
"max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "rknop/amuse",
"max_issues_repo_path": "src/amuse/community/gadget2/src/allvars.h",
"max_line_length": 212,
"max_stars_count": 131,
"max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "rknop/amuse",
"max_stars_repo_path": "src/amuse/community/gadget2/src/allvars.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z",
"num_tokens": 8997,
"size": 40368
} |
/*
* Copyright (c) 2016 Kengo Tateishi (@tkengo)
* Licensed under MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* MxRuby is really inspired by numpy.
*
* This file is implementation of extended array functions for ruby. The MX class is defined on ruby
* interpreter by compiling it.
*/
#include <ruby.h>
/* #include <cblas.h> */
#include "mx.h"
/*
* MX class object in C. This is initialized in Init_mxruby function.
*/
VALUE rb_cMx;
VALUE rb_eDataTypeError;
MX *mxx_initialize(VALUE shape, DTYPE dtype)
{
MX *mx = MX_ALLOC(MX);
mxx_setup(mx, dtype);
mxx_initialize_shape(mx, shape);
if (mx->size > 0) {
mx->elptr = MX_ALLOC_N(char, DTYPE_SIZES[mx->dtype] * mx->size);
}
return mx;
}
void mxx_setup(MX *mx, DTYPE dtype)
{
mx->dim = 0;
mx->size = 0;
mx->dtype = dtype;
mx->shape = NULL;
mx->elptr = NULL;
}
void mxx_initialize_shape(MX *mx, VALUE shape)
{
char shape_is_array = TYPE(shape) == T_ARRAY;
mx->size = 1;
mx->dim = shape_is_array ? RARRAY_LEN(shape) : 1;
mx->shape = MX_ALLOC_N(size_t, mx->dim);
for (int i = 0; i < mx->dim; i++) {
mx->shape[i] = FIX2INT(shape_is_array ? RARRAY_AREF(shape, i) : shape);
mx->size *= mx->shape[i];
}
}
void mxx_free(MX *mx)
{
if (mx->shape != NULL) {
MX_FREE(mx->shape);
}
if (mx->elptr != NULL) {
MX_FREE(mx->elptr);
}
MX_FREE(mx);
}
static VALUE mx_alloc(VALUE klass)
{
MX *mx = MX_ALLOC(MX);
mxx_setup(mx, DTYPE_FLOAT64);
return Data_Wrap_Struct(klass, 0, mxx_free, mx);
}
static VALUE mx_initialize(VALUE self, VALUE shape, VALUE initial_value, VALUE opt)
{
MX *mx;
Data_Get_Struct(self, MX, mx);
if (!NIL_P(opt)) {
VALUE rb_dtype = rb_hash_aref(opt, ID2SYM(rb_intern("dtype")));
if (!NIL_P(rb_dtype)) {
mx->dtype = mxx_dtype_from_symbol(rb_dtype);
}
}
mxx_initialize_shape(mx, shape);
if (mx->size > 0) {
mx->elptr = MX_ALLOC_N(char, DTYPE_SIZES[mx->dtype] * mx->size);
if (TYPE(initial_value) == T_ARRAY) {
for (int i = 0; i < mx->size; i++) {
VALUE v = RARRAY_AREF(initial_value, i);
mxx_rb_to_c(mx->elptr + i * DTYPE_SIZES[mx->dtype], mx->dtype, v);
}
} else if (!NIL_P(initial_value)) {
for (int i = 0; i < mx->size; i++) {
mxx_rb_to_c(mx->elptr + i * DTYPE_SIZES[mx->dtype], mx->dtype, initial_value);
}
}
}
return self;
}
static VALUE mx_shape(VALUE self)
{
MX *mx = MX_DATA_PTR(self);
VALUE *shape = MX_ALLOC_N(VALUE, mx->dim);
for (int i = 0; i < mx->dim; i++) {
shape[i] = INT2FIX(mx->shape[i]);
}
return rb_ary_new4(mx->dim, shape);
}
static VALUE mx_dim(VALUE self)
{
return INT2FIX(MX_DATA_DIM(self));
}
static VALUE mx_size(VALUE self)
{
return INT2FIX(MX_DATA_SIZE(self));
}
static VALUE mx_dtype(VALUE self)
{
return ID2SYM(rb_intern(DTYPE_NAMES[MX_DATA_PTR(self)->dtype]));
}
static VALUE mx_dot(VALUE self, VALUE target)
{
int N = 2;
MX *mx = MX_DATA_PTR(self);
void *c = MX_ALLOC_N(char, mx->shape[0] * mx->shape[1] * DTYPE_SIZES[mx->dtype]);
/* cblas_sgemm( */
/* CblasRowMajor, CblasNoTrans, CblasNoTrans, */
/* N, N, N, */
/* 1, mx->elptr, N, */
/* MX_DATA_ELPTR(target), N, */
/* 0, c, N */
/* ); */
MX_FREE(mx->elptr);
mx->elptr = c;
return self;
}
static VALUE mx_astype(int argc, VALUE *argv, VALUE self)
{
VALUE rb_new_dtype, rb_opt;
rb_scan_args(argc, argv, "1:", &rb_new_dtype, &rb_opt);
DTYPE new_dtype = mxx_dtype_from_symbol(rb_new_dtype);
MX *dest = MX_ALLOC(MX);
mxx_copy_cast(MX_DATA_PTR(self), dest, new_dtype);
return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, dest);
}
static void mxs_to_a(VALUE *ary, size_t shape_index, size_t array_index, MX *mx)
{
if (shape_index == mx->dim - 1) {
for (int i = 0; i < mx->shape[shape_index]; i++) {
void *p = (char *)mx->elptr + (i + array_index) * DTYPE_SIZES[mx->dtype];
ary[i] = mxx_c_to_rb(p, mx->dtype);
}
} else {
size_t skip = 1;
for (int i = shape_index + 1; i < mx->dim; i++) {
skip *= mx->shape[i];
}
for (int i = 0; i < mx->shape[shape_index]; i++) {
VALUE *v = MX_ALLOC_N(VALUE, mx->shape[shape_index + 1]);
mxs_to_a(v, shape_index + 1, skip * i + array_index, mx);
ary[i] = rb_ary_new4(mx->shape[shape_index + 1], v);
}
}
}
static VALUE mx_to_a(VALUE self)
{
MX *mx = MX_DATA_PTR(self);
VALUE *ary = MX_ALLOC_N(VALUE, mx->shape[0]);
mxs_to_a(ary, 0, 0, mx);
return rb_ary_new4(mx->shape[0], ary);
}
static VALUE mx_flatten(VALUE self)
{
MX *mx = MX_DATA_PTR(self);
VALUE *el = MX_ALLOC_N(VALUE, mx->size);
size_t dsize = DTYPE_SIZES[mx->dtype];
for (int i = 0; i < mx->size; i++) {
el[i] = mxx_c_to_rb((char *)mx->elptr + i * dsize, mx->dtype);
}
return rb_ary_new4(mx->size, el);
}
static VALUE mx_first(VALUE self)
{
MX *mx = MX_DATA_PTR(self);
if (mx->size > 0) {
return mxx_c_to_rb(mx->elptr, mx->dtype);
}
return Qnil;
}
static VALUE mx_second(VALUE self)
{
MX *mx = MX_DATA_PTR(self);
if (mx->size > 1) {
return mxx_c_to_rb(mx->elptr + DTYPE_SIZES[mx->dtype], mx->dtype);
}
return Qnil;
}
static VALUE mx_last(VALUE self)
{
MX *mx = MX_DATA_PTR(self);
if (mx->size > 0) {
return mxx_c_to_rb(mx->elptr + (mx->size - 1) * DTYPE_SIZES[mx->dtype], mx->dtype);
}
return Qnil;
}
static VALUE mx_reshape(VALUE self, VALUE shape)
{
MX *mx = MX_DATA_PTR(self);
MX *reshaped_mx = MX_ALLOC(MX);
mxx_initialize_shape(reshaped_mx, shape);
if (mx->size != reshaped_mx->size) {
rb_raise(rb_eArgError, "Cannot do reshape operation between shape size of [ %ld ] and [ %ld ]. Total size of new array must be unchanged.", mx->size, reshaped_mx->size);
}
reshaped_mx->dtype = mx->dtype;
reshaped_mx->elptr = MX_ALLOC_N(char, reshaped_mx->size * DTYPE_SIZES[reshaped_mx->dtype]);
mxx_copy_elptr(mx, reshaped_mx);
return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, reshaped_mx);
}
static VALUE mx_sum(int argc, VALUE *argv, VALUE self)
{
MX *mx = MX_DATA_PTR(self);
if (DTYPE_IS_INT(mx->dtype)) {
long sum = (long)mxx_sum(mx);
return INT2FIX(sum);
} else {
return rb_float_new(mxx_sum(mx));
}
}
static VALUE mx_is_empty(VALUE self)
{
MX *mx = MX_DATA_PTR(self);
return mx->size == 0 ? Qtrue : Qfalse;
}
static VALUE mx_set(int argc, VALUE *argv, VALUE self)
{
return self;
}
/**
* Slice the `src` matrix, then the sliced matrix will be stored into the dest matrix.
* @params src Source matrix to be sliced
* @params dest Destination matrix
* @params src_pos Copy start position in the source matrix
* @params count Copy element count
* @params depth ?
* @params idx
* @params idx_len
*/
static void _mxs_slice(MX *src, MX *dest, VALUE idx, size_t idx_len, int depth, size_t size,
size_t src_pos, size_t *dest_pos)
{
if (depth == idx_len) {
mxx_copy_by_size(
MX_DATA_POS(src, src_pos),
MX_DATA_POS(dest, *dest_pos),
size,
dest->dtype
);
*dest_pos += size;
} else {
size_t skip = 1;
for (int i = depth + 1; i < src->dim; i++) {
skip *= src->shape[i];
}
long beg, len;
VALUE v = RARRAY_AREF(idx, depth);
if (FIXNUM_P(v)) {
_mxs_slice(src, dest, idx, idx_len, depth + 1, skip, src_pos + FIX2INT(v) * skip, dest_pos);
} else if (rb_range_beg_len(v, &beg, &len, src->shape[depth], 0) == Qtrue) {
for (long i = 0; i < len; i++) {
_mxs_slice(src, dest, idx, idx_len, depth + 1, skip, src_pos + (beg + i) * skip, dest_pos);
}
}
}
}
static MX *mxs_slice(MX *src, VALUE idx, size_t idx_len)
{
/**
* mx = [ [ [1,1], [2,2], [3,3], [4,4] ],
* [ [0,0], [0,0], [0,0], [0,0] ],
* [ [5,5], [6,6], [7,7], [8,8] ] ], shape = [3, 4, 2]
*
* mx[0] = [ [1,1], [2,2], [3,3], [4,4] ], shape = [4, 2]
* mx[0..1] = [ [ [1,1], [2,2], [3,3], [4,4] ],
* [ [0,0], [0,0], [0,0], [0,0] ] ], shape = [2, 4, 2]
*
* mx[0, 0..1] = [ [1,1], [2,2] ], shape = [2, 2]
*
* mx[0..1, 0] = [ [1,1],
* [0,0] ], shape = [2, 2]
* mx[0..1, 0..1] = [ [ [1,1], [2,2] ],
* [ [0,0], [0,0] ] ], shape = [2, 2, 2]
*
* mx[0..1, 0..1, 0] = [ [ 1, 2 ],
* [ 0, 0 ] ], shape = [2, 2]
*
* mx = [ [1, 2, 3],
* [4, 5, 6],
* [7, 8, 9] ], shape = [3, 3]
*
* mx[0] = [1, 2, 3], shape = [3]
* mx[0..1] = [ [1, 2, 3]
* [4, 5, 6] ], shape = [2, 3]
* mx[0..1, 0] = [ 1
* 4 ], shape = [2, 1]
* mx[0..1, [0]] = [ [1]
* [4] ], shape = [2, 1]
*
* mx[0, 0] = 1, shape = nil
* mx[0, 0..1] = [1, 2], shape = [2]
*
* mx[[0]] = [ [1, 2, 3] ], shape = [1, 3]
* mx[0..0] = [ [1, 2, 3]
* [4, 5, 6] ], shape = [2, 3]
* mx[[0, 1]] = [ [1, 2, 3]
* [4, 5, 6] ], shape = [2, 3]
*
* 引数がFIXNUMだったらdimが1個減る
* 引数がrangeまたはarrayだったら次元は減らずにshapeがその長さになる
*/
long beg, len;
size_t new_dim = 0;
size_t *tmp = MX_ALLOC_N(size_t, src->dim);
for (int i = 0; i < src->dim; i++) {
if (i < idx_len) {
VALUE v = RARRAY_AREF(idx, i);
if (rb_range_beg_len(v, &beg, &len, src->shape[i], 0) == Qtrue) {
tmp[new_dim++] = len;
}
} else {
tmp[new_dim++] = src->shape[i];
}
}
VALUE *new_shape = MX_ALLOC_N(VALUE, new_dim);
for (int i = 0; i < new_dim; i++) {
new_shape[i] = INT2FIX(tmp[i]);
}
MX *new_mx = MX_ALLOC(MX);
mxx_initialize_shape(new_mx, rb_ary_new4(new_dim, new_shape));
new_mx->dtype = src->dtype;
new_mx->elptr = MX_ALLOC_N(char, new_mx->size * DTYPE_SIZES[new_mx->dtype]);
MX_FREE(tmp);
size_t dest_pos = 0;
_mxs_slice(src, new_mx, idx, idx_len, 0, 0, 0, &dest_pos);
}
static VALUE mx_get(int argc, VALUE *argv, VALUE self)
{
VALUE idx;
rb_scan_args(argc, argv, "0*", &idx);
MX *mx = MX_DATA_PTR(self);
size_t idx_len = RARRAY_LEN(idx);
if (idx_len > mx->dim) {
return Qnil;
}
MX *new_mx = mxs_slice(mx, idx, idx_len);
return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, new_mx);
return self;
}
static VALUE mx_ewadd(VALUE self, VALUE other)
{
MX *mx = MX_DATA_PTR(self);
MX *new_mx = MX_ALLOC(MX);
if (IS_MX(other)) {
MX *other_mx = MX_DATA_PTR(other);
if (!mxx_is_same_shape(mx, other_mx)) {
rb_raise(rb_eDataTypeError, "Cannot do addition operation between different shapes");
}
mxx_ewadd_array(mx, other_mx, new_mx);
} else {
if (TYPE(other) == T_FLOAT) {
mxx_ewadd_dblscalar(mx, NUM2DBL(other), new_mx);
} else {
mxx_ewadd_intscalar(mx, FIX2INT(other), new_mx);
}
}
return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, new_mx);
}
static VALUE mx_ewsub(VALUE self, VALUE other)
{
MX *mx = MX_DATA_PTR(self);
MX *new_mx = MX_ALLOC(MX);
if (IS_MX(other)) {
MX *other_mx = MX_DATA_PTR(other);
if (!mxx_is_same_shape(mx, other_mx)) {
rb_raise(rb_eDataTypeError, "Cannot do subtraction operation between different shapes");
}
mxx_ewsub_array(mx, other_mx, new_mx);
} else {
if (TYPE(other) == T_FLOAT) {
mxx_ewsub_dblscalar(mx, NUM2DBL(other), new_mx);
} else {
mxx_ewsub_intscalar(mx, FIX2INT(other), new_mx);
}
}
return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, new_mx);
}
static VALUE mx_ewmul(VALUE self, VALUE other)
{
MX *mx = MX_DATA_PTR(self);
MX *new_mx = MX_ALLOC(MX);
if (IS_MX(other)) {
MX *other_mx = MX_DATA_PTR(other);
if (!mxx_is_same_shape(mx, other_mx)) {
rb_raise(rb_eDataTypeError, "Cannot do multiplication operation between different shapes");
}
mxx_ewmul_array(mx, other_mx, new_mx);
} else {
if (TYPE(other) == T_FLOAT) {
mxx_ewmul_dblscalar(mx, NUM2DBL(other), new_mx);
} else {
mxx_ewmul_intscalar(mx, FIX2INT(other), new_mx);
}
}
return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, new_mx);
}
static VALUE mx_ewpow(VALUE self, VALUE other)
{
MX *mx = MX_DATA_PTR(self);
MX *new_mx = MX_ALLOC(MX);
if (IS_MX(other)) {
MX *other_mx = MX_DATA_PTR(other);
if (!mxx_is_same_shape(mx, other_mx)) {
rb_raise(rb_eDataTypeError, "Cannot do power operation between different shapes");
}
if (DTYPE_IS_INT(other_mx->dtype)) {
mxx_ewintpow_array(mx, other_mx, new_mx);
} else {
mxx_ewpow_array(mx, other_mx, new_mx);
}
} else {
if (TYPE(other) == T_FIXNUM) {
mxx_ewpow_intscalar(mx, FIX2INT(other), new_mx);
} else {
mxx_ewpow_dblscalar(mx, NUM2DBL(other), new_mx);
}
}
return Data_Wrap_Struct(CLASS_OF(self), 0, mxx_free, new_mx);
}
static VALUE mx_sing_eye(int argc, VALUE *argv, VALUE klass)
{
int row, col, dim = 2;
VALUE rb_row, rb_col, rb_opt;
rb_scan_args(argc, argv, "11:", &rb_row, &rb_col, &rb_opt);
DTYPE dtype = mxx_dtype_from_opt(rb_opt, DTYPE_FLOAT64);
VALUE *shape = MX_ALLOC_N(VALUE, dim);
shape[0] = rb_row;
if (NIL_P(rb_col)) {
shape[1] = rb_row;
} else {
shape[1] = rb_col;
}
int count = MX_MIN(FIX2INT(shape[0]), FIX2INT(shape[1]));
if (count < 0) {
MX_FREE(shape);
rb_raise(rb_eArgError, "Negative dimensions are not allowed");
}
MX *mx = mxx_initialize(rb_ary_new4(dim, shape), dtype);
memset(mx->elptr, 0x00, mx->size * DTYPE_SIZES[mx->dtype]);
mxx_eye(mx, count);
MX_FREE(shape);
return Data_Wrap_Struct(klass, 0, mxx_free, mx);;
}
static VALUE mx_sing_arange(int argc, VALUE *argv, VALUE klass)
{
double start, stop, step;
int start_type, stop_type, step_type;
VALUE rb_start, rb_stop, rb_step, rb_opt;
DTYPE dtype;
rb_scan_args(argc, argv, "12:", &rb_start, &rb_stop, &rb_step, &rb_opt);
if (NIL_P(rb_stop)) {
start = 0;
stop = NUM2DBL(rb_start);
start_type = T_FIXNUM;
stop_type = TYPE(rb_start);
} else {
start = NUM2DBL(rb_start);
stop = NUM2DBL(rb_stop);
start_type = TYPE(rb_start);
stop_type = TYPE(rb_stop);
}
step = NIL_P(rb_step) ? 1 : NUM2DBL(rb_step);
step_type = NIL_P(rb_step) ? T_FIXNUM : TYPE(rb_step);
if (step == 0) {
rb_raise(rb_eArgError, "Cannot specify 0 to the step argument");
} else if (step > 0 && start > stop) {
rb_raise(rb_eArgError, "Confuse arguments order. start > stop.");
} else if (step < 0 && start < stop) {
rb_raise(rb_eArgError, "Confuse arguments order. start < stop.");
} else if (start == stop) {
MX *mx = mxx_initialize(INT2FIX(0), DTYPE_INT64);
return Data_Wrap_Struct(klass, 0, mxx_free, mx);
}
// T_FIXNUM => FIXNUM_P
if (step_type == T_FIXNUM && start_type == T_FIXNUM && stop_type == T_FIXNUM) {
dtype = DTYPE_INT64;
} else {
dtype = DTYPE_FLOAT64;
}
size_t shape = (size_t)fabs(ceil((stop - start) / step));
MX *mx = mxx_initialize(INT2FIX(shape), mxx_dtype_from_opt(rb_opt, dtype));
mxx_linspace(mx, start, step);
return Data_Wrap_Struct(klass, 0, mxx_free, mx);
}
static VALUE mx_sing_linspace(int argc, VALUE *argv, VALUE klass)
{
VALUE rb_start, rb_stop, rb_num, rb_opt;
rb_scan_args(argc, argv, "21:", &rb_start, &rb_stop, &rb_num, &rb_opt);
if (NIL_P(rb_num)) {
rb_num = INT2FIX(100);
}
if (FIX2INT(rb_num) < 0) {
rb_raise(rb_eArgError, "Cannot specify negative number to the shape argument");
}
DTYPE dtype = mxx_dtype_from_opt(rb_opt, DTYPE_FLOAT64);
MX *mx = mxx_initialize(rb_num, dtype);
double start = NUM2DBL(rb_start);
double stop = NUM2DBL(rb_stop);
double step = (stop - start) * (1.0 / (double)(mx->size - 1));
mxx_linspace(mx, start, step);
return Data_Wrap_Struct(klass, 0, mxx_free, mx);
}
void Init_mxruby()
{
rb_cMx = rb_define_class("MX", rb_cObject);
rb_eDataTypeError = rb_define_class("DataTypeError", rb_eStandardError);
rb_define_alloc_func(rb_cMx, mx_alloc);
rb_define_protected_method(rb_cMx, "__set__", mx_initialize, 3);
rb_define_method(rb_cMx, "shape", mx_shape, 0);
rb_define_method(rb_cMx, "dim", mx_dim, 0);
rb_define_method(rb_cMx, "size", mx_size, 0);
rb_define_method(rb_cMx, "dtype", mx_dtype, 0);
rb_define_method(rb_cMx, "dot", mx_dot, 1);
rb_define_method(rb_cMx, "astype", mx_astype, -1);
rb_define_method(rb_cMx, "to_a", mx_to_a, 0);
rb_define_method(rb_cMx, "flatten", mx_flatten, 0);
rb_define_method(rb_cMx, "first", mx_first, 0);
rb_define_method(rb_cMx, "second", mx_second, 0);
rb_define_method(rb_cMx, "last", mx_last, 0);
rb_define_method(rb_cMx, "reshape", mx_reshape, 1);
rb_define_method(rb_cMx, "sum", mx_sum, -1);
rb_define_method(rb_cMx, "empty?", mx_is_empty, 0);
rb_define_method(rb_cMx, "[]=", mx_set, -1);
rb_define_method(rb_cMx, "[]", mx_get, -1);
rb_define_method(rb_cMx, "+", mx_ewadd, 1);
rb_define_method(rb_cMx, "-", mx_ewsub, 1);
rb_define_method(rb_cMx, "*", mx_ewmul, 1);
rb_define_method(rb_cMx, "**", mx_ewpow, 1);
rb_define_singleton_method(rb_cMx, "eye", mx_sing_eye, -1);
rb_define_singleton_method(rb_cMx, "arange", mx_sing_arange, -1);
rb_define_singleton_method(rb_cMx, "linspace", mx_sing_linspace, -1);
Init_random();
}
| {
"alphanum_fraction": 0.5708471265,
"avg_line_length": 28.9732704403,
"ext": "c",
"hexsha": "ffc988be040af9ed7884c299ab6e731a1091ab26",
"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": "f828c829dc556fbad34047272875d7af1406bff5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tkengo/mxruby",
"max_forks_repo_path": "ext/mxruby/mx.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f828c829dc556fbad34047272875d7af1406bff5",
"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": "tkengo/mxruby",
"max_issues_repo_path": "ext/mxruby/mx.c",
"max_line_length": 177,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f828c829dc556fbad34047272875d7af1406bff5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tkengo/mxruby",
"max_stars_repo_path": "ext/mxruby/mx.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5889,
"size": 18427
} |
#ifndef __GSL_SORT_VECTOR_H__
#define __GSL_SORT_VECTOR_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 <gsl/gsl_sort_vector_long_double.h>
#include <gsl/gsl_sort_vector_double.h>
#include <gsl/gsl_sort_vector_float.h>
#include <gsl/gsl_sort_vector_ulong.h>
#include <gsl/gsl_sort_vector_long.h>
#include <gsl/gsl_sort_vector_uint.h>
#include <gsl/gsl_sort_vector_int.h>
#include <gsl/gsl_sort_vector_ushort.h>
#include <gsl/gsl_sort_vector_short.h>
#include <gsl/gsl_sort_vector_uchar.h>
#include <gsl/gsl_sort_vector_char.h>
#endif /* __GSL_SORT_VECTOR_H__ */
| {
"alphanum_fraction": 0.7537688442,
"avg_line_length": 25.6774193548,
"ext": "h",
"hexsha": "47bae77e16fe32b5516624f35bcd2ec8f9ee5984",
"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": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "deps/include/gsl/gsl_sort_vector.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "berkus/music-cs",
"max_issues_repo_path": "deps/include/gsl/gsl_sort_vector.h",
"max_line_length": 49,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "berkus/music-cs",
"max_stars_repo_path": "deps/include/gsl/gsl_sort_vector.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z",
"num_tokens": 216,
"size": 796
} |
#include <sstream>
#include <iostream>
#include <string>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_rng.h>
#include <iomanip>
#include <complex>
#include <cmath>
#include <random>
using namespace std::complex_literals;
// pretty print a gsl vector.
std::string ppVector(const gsl_vector *v) {
std::ostringstream str;
int r;
str << "(";
for (r = 0; r < (int) v->size; r++) {
str << gsl_vector_get(v, r);
if (r < v->size - 1) {
str << ",";
}
}
str << ")";
return str.str();
}
void
vectorOpsCheck() {
fprintf(stdout, "\n Vector Operations ..............................................\n");
int N = 3;
gsl_vector *v1 = gsl_vector_alloc(N);
gsl_vector *v2 = gsl_vector_alloc(N);
gsl_vector *v3 = gsl_vector_alloc(N);
gsl_vector *v4 = gsl_vector_alloc(N);
gsl_vector *v5 = gsl_vector_alloc(N);
gsl_vector_set_all(v1, 1.0);
gsl_vector_set_zero(v2);
gsl_vector_set(v2, 1, 1.0);
gsl_vector_set(v3, 0, 0.1);
gsl_vector_set(v3, 1, 0.6);
gsl_vector_set(v3, 2, 0.3);
gsl_vector_set(v4, 0, 1.3);
gsl_vector_set(v4, 1, 0.0);
gsl_vector_set(v4, 2, 0.9);
gsl_vector_set(v5, 0, 0.8);
gsl_vector_set(v5, 1, 1.2);
gsl_vector_set(v5, 2, 1.6);
fprintf(stdout, "v1 = %s\n", ppVector(v1).c_str());
fprintf(stdout, "v2 = %s\n", ppVector(v2).c_str());
gsl_vector_add(v1, v2);
fprintf(stdout, "v1 + v2 = %s\n", ppVector(v1).c_str());
fprintf(stdout, "\n");
fprintf(stdout, "v1 = %s\n", ppVector(v3).c_str());
fprintf(stdout, "v2 = %s\n", ppVector(v5).c_str());
gsl_vector_sub(v3, v5);
fprintf(stdout, "v1 - v2 = %s\n", ppVector(v3).c_str());
fprintf(stdout, "\n");
fprintf(stdout, "v1 = %s\n", ppVector(v2).c_str());
fprintf(stdout, "v2 = %s\n", ppVector(v4).c_str());
gsl_vector_mul(v2, v4);
fprintf(stdout, "v1 dot v2 = %s\n", ppVector(v2).c_str());
fprintf(stdout, "\n");
fprintf(stdout, "v1 = %s\n", ppVector(v5).c_str());
fprintf(stdout, "norm(v1) = %f\n", gsl_blas_dnrm2(v5));
fprintf(stdout, "\n");
gsl_vector_free(v1);
gsl_vector_free(v2);
gsl_vector_free(v3);
gsl_vector_free(v4);
gsl_vector_free(v5);
fprintf(stdout, "\n");
}
void
complexNumOpsCheck() {
fprintf(stdout, "\n Complex Number Operations ..............................................\n");
std::complex<double> c1 = 1.1 + 2.0i;
std::complex<double> c2 = 2.3 - 0.4i;
fprintf(stdout, "let c1 = Complex(real: %1.1f, imag: %1.1f)\n", real(c1), imag(c1));
fprintf(stdout, "let c2 = Complex(real: %1.1f, imag: %1.1f)\n", real(c2), imag(c2));
fprintf(stdout, "XCTAssertEqual(c1+c2, c2+c1)\n");
fprintf(stdout, "XCTAssertEqual(c2*c1, c2*c1)\n");
fprintf(stdout, "XCTAssertEqual(c1+c2, Complex(real:%1.1f, imag: %1.1f))\n", real(c1+c2), imag(c1+c2));
fprintf(stdout, "XCTAssertEqual(c1-c2, Complex(real:%1.1f, imag: %1.1f))\n", real(c1-c2), imag(c1-c2));
fprintf(stdout, "XCTAssertEqual(c1*c2, Complex(real:%1.1f, imag: %1.1f))\n", real(c1*c2), imag(c1*c2));
fprintf(stdout, "XCTAssertEqual(c1/c2, Complex(real:%1.6f, imag: %1.6f))\n", real(c1/c2), imag(c1/c2));
fprintf(stdout, "XCTAssertEqual(c2/c1, Complex(real:%1.6f, imag: %1.5f))\n", real(c2/c1), imag(c2/c1));
fprintf(stdout, "XCTAssertEqual(c1.conjugate(), Complex(real:%1.1f, imag: %1.1f))\n", real(conj(c1)), imag(conj(c1)));
fprintf(stdout, "XCTAssertEqual(c1.modulus(), %1.14f\n", norm(c1));
fprintf(stdout, "XCTAssertEqual(c1.norm(), %1.14f\n", norm(c1));
fprintf(stdout, "XCTAssertEqualWithAccuracy(c1.arg(), %1.15f, accuracy:0.0001)\n", arg(c1));
fprintf(stdout, "XCTAssertEqual(c2.conjugate(), Complex(real:%1.1f, imag: %1.1f))\n", real(conj(c2)), imag(conj(c2)));
fprintf(stdout, "XCTAssertEqual(c2.modulus(), %1.14f\n", norm(c2));
fprintf(stdout, "XCTAssertEqual(c2.norm(), %1.14f\n", norm(c2));
fprintf(stdout, "XCTAssertEqualWithAccuracy(c2.arg(), %1.15f, accuracy:0.0001)\n", arg(c2));
fprintf(stdout, "\n");
}
void
printComplexMathChecks(std::complex<double> c1) {
fprintf(stdout, "var c1 = Complex(real: %1.1f, imag: %1.1f)\n", real(c1), imag(c1));
fprintf(stdout, "let cosc1 = cos(value: c1)\n");
fprintf(stdout, "let sinc1 = sin(value: c1)\n");
fprintf(stdout, "let tanc1 = tan(value: c1)\n");
fprintf(stdout, "XCTAssertEqual(cosc1.real(), %1.15f)\n", real(cos(c1)));
fprintf(stdout, "XCTAssertEqual(cosc1.imag(), %1.15f)\n", imag(cos(c1)));
fprintf(stdout, "XCTAssertEqual(sinc1.real(), %1.15f)\n", real(sin(c1)));
fprintf(stdout, "XCTAssertEqual(sinc1.imag(), %1.15f)\n", imag(sin(c1)));
fprintf(stdout, "XCTAssertEqual(tanc1.real(), %1.15f)\n", real(tan(c1)));
fprintf(stdout, "XCTAssertEqual(tanc1.imag(), %1.15f)\n", imag(tan(c1)));
fprintf(stdout, "let coshc1 = cosh(value: c1)\n");
fprintf(stdout, "let sinhc1 = sinh(value: c1)\n");
fprintf(stdout, "let tanhc1 = tanh(value: c1)\n");
fprintf(stdout, "XCTAssertEqual(coshc1.real(), %1.15f)\n", real(cosh(c1)));
fprintf(stdout, "XCTAssertEqual(coshc1.imag(), %1.15f)\n", imag(cosh(c1)));
fprintf(stdout, "XCTAssertEqual(sinhc1.real(), %1.15f)\n", real(sinh(c1)));
fprintf(stdout, "XCTAssertEqual(sinhc1.imag(), %1.15f)\n", imag(sinh(c1)));
fprintf(stdout, "XCTAssertEqual(tanhc1.real(), %1.15f)\n", real(tanh(c1)));
fprintf(stdout, "XCTAssertEqual(tanhc1.imag(), %1.15f)\n", imag(tanh(c1)));
fprintf(stdout, "let acosc1 = acos(value: c1)\n");
fprintf(stdout, "let asinc1 = asin(value: c1)\n");
fprintf(stdout, "let atanc1 = atan(value: c1)\n");
fprintf(stdout, "XCTAssertEqual(acosc1.real(), %1.15f)\n", real(acos(c1)));
fprintf(stdout, "XCTAssertEqual(acosc1.imag(), %1.15f)\n", imag(acos(c1)));
fprintf(stdout, "XCTAssertEqual(asinc1.real(), %1.15f)\n", real(asin(c1)));
fprintf(stdout, "XCTAssertEqual(asinc1.imag(), %1.15f)\n", imag(asin(c1)));
fprintf(stdout, "XCTAssertEqual(atanc1.real(), %1.15f)\n", real(atan(c1)));
fprintf(stdout, "XCTAssertEqual(atanc1.imag(), %1.15f)\n", imag(atan(c1)));
fprintf(stdout, "let acoshc1 = acosh(value: c1)\n");
fprintf(stdout, "let asinhc1 = asinh(value: c1)\n");
fprintf(stdout, "let atanhc1 = atanh(value: c1)\n");
fprintf(stdout, "XCTAssertEqual(acoshc1.real(), %1.15f)\n", real(acosh(c1)));
fprintf(stdout, "XCTAssertEqual(acoshc1.imag(), %1.15f)\n", imag(acosh(c1)));
fprintf(stdout, "XCTAssertEqual(asinhc1.real(), %1.15f)\n", real(asinh(c1)));
fprintf(stdout, "XCTAssertEqual(asinhc1.imag(), %1.15f)\n", imag(asinh(c1)));
fprintf(stdout, "XCTAssertEqual(atanhc1.real(), %1.15f)\n", real(atanh(c1)));
fprintf(stdout, "XCTAssertEqual(atanhc1.imag(), %1.15f)\n", imag(atanh(c1)));
fprintf(stdout, "let expc1 = exp(value: c1)\n");
fprintf(stdout, "let logc1 = log(value: c1)\n");
fprintf(stdout, "let log10c1 = log10(value: c1)\n");
fprintf(stdout, "let sqrtc1 = sqrt(value: c1)\n");
fprintf(stdout, "XCTAssertEqual(expc1.real(), %1.15f)\n", real(exp(c1)));
fprintf(stdout, "XCTAssertEqual(expc1.imag(), %1.15f)\n", imag(exp(c1)));
fprintf(stdout, "XCTAssertEqual(logc1.real(), %1.15f)\n", real(log(c1)));
fprintf(stdout, "XCTAssertEqual(logc1.imag(), %1.15f)\n", imag(log(c1)));
fprintf(stdout, "XCTAssertEqual(log10c1.real(), %1.15f)\n", real(log10(c1)));
fprintf(stdout, "XCTAssertEqual(log10c1.imag(), %1.15f)\n", imag(log10(c1)));
fprintf(stdout, "XCTAssertEqual(sqrtc1.real(), %1.15f)\n", real(sqrt(c1)));
fprintf(stdout, "XCTAssertEqual(sqrtc1.imag(), %1.15f)\n", imag(sqrt(c1)));
}
void
complexMathCheck() {
fprintf(stdout, "\n Complex Number Trig Operations ..............................................\n");
std::complex<double> c1 = 1.1 + 2.0i;
printComplexMathChecks(c1);
c1 = 2.3 - 0.4i;
printComplexMathChecks(c1);
fprintf(stdout, "\n");
}
void
rngCheck() {
fprintf(stdout, "\n Random Number Generator Tests ..............................................\n");
fprintf(stdout, "\n Mersenne Twister 64 bit ..............................................\n");
int n = 10;
std::mt19937_64 generator (12345678);
std::uniform_real_distribution<double> dis(0.0, 1.0);
fprintf(stdout, "[%f", dis(generator));
for (int i = 1; i < n; i++) {
fprintf(stdout, ", %f", dis(generator));
}
fprintf(stdout, "]");
fprintf(stdout, "\n");
}
int
main(void) {
complexNumOpsCheck();
vectorOpsCheck();
rngCheck();
complexMathCheck();
return 0;
}
| {
"alphanum_fraction": 0.6052328262,
"avg_line_length": 38.56,
"ext": "c",
"hexsha": "d15837754c0a757c0fd2aec07ebc90a217b1980b",
"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": "eb61e93de15a98c34239a938d49459080e324ba9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "anthonyohare/SwiftScientificLibrary",
"max_forks_repo_path": "ValidationTests/gsl_tests.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "eb61e93de15a98c34239a938d49459080e324ba9",
"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": "anthonyohare/SwiftScientificLibrary",
"max_issues_repo_path": "ValidationTests/gsl_tests.c",
"max_line_length": 122,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "eb61e93de15a98c34239a938d49459080e324ba9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "anthonyohare/SwiftScientificLibrary",
"max_stars_repo_path": "ValidationTests/gsl_tests.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2937,
"size": 8676
} |
/*
/
/ adkGSL.h
/
/ homebrewed addons to gsl */
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#include <math.h>
#include <assert.h>
int gsl_vector_includes(gsl_vector *aVec, double aValue);
double gsl_vector_sum(gsl_vector *aVec, int aVecSize);
double gsl_matrix_row_sum(gsl_matrix *mat, int row, int rowSize);
double log_sum(gsl_vector *vec);
double *gsl_matrix_2_lapack(gsl_matrix *m);
double gsl_vector_dot_product(gsl_vector *vec1, gsl_vector *vec2);
void gsl_vector_outer_product(gsl_vector *vec1, gsl_vector *vec2, gsl_matrix *result);
gsl_matrix *gsl_matrix_power(gsl_matrix *A, int k);
gsl_matrix *gsl_matrix_power_logs(gsl_matrix *A, int k);
void gsl_matrix_lower_tri_copy(gsl_matrix *src, gsl_matrix *dest);
void gsl_matrix_upper_tri_copy(gsl_matrix *src, gsl_matrix *dest);
void gsl_matrix_lower_tri(gsl_matrix *x);
void gsl_matrix_upper_tri(gsl_matrix *x);
double gsl_matrix_trace(gsl_matrix *x);
void gsl_matrix_covariance(gsl_matrix *data, gsl_matrix *cov);
void fillMatrixFromArray(double *numbers, gsl_matrix *dest, int nrow, int ncol);
void fillMatrixFromVector(gsl_vector *numbers, gsl_matrix *dest, int nrow, int ncol);
void fillArrayFromMatrix(gsl_matrix *src, gsl_vector *dest);
void fillCholArrayFromMatrix(gsl_matrix *src, gsl_vector *dest);
void fillMatrixFromCholArray(double *numbers, gsl_matrix *dest, int nrow, int ncol);
//lapack wrappers
int dgeev(char jobvl, char jobvr, int n, double *a, int lda, double *wr, double *wi, double *vl,
int ldvl,double *vr, int ldvr, double *work, int lwork);
int dhseqr(char job, char compz, int n, int ilo, int ihi,double *h, int ldh, double *wr, double *wi, double *z, int ldz, double *work, int lwork);
| {
"alphanum_fraction": 0.7755568247,
"avg_line_length": 40.7209302326,
"ext": "h",
"hexsha": "f2b929888a71fd69e7740f40b7f50fa9285eac9c",
"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": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "andrewkern/segSiteHMM",
"max_forks_repo_path": "hmm/adkGSL.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"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": "andrewkern/segSiteHMM",
"max_issues_repo_path": "hmm/adkGSL.h",
"max_line_length": 146,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "andrewkern/segSiteHMM",
"max_stars_repo_path": "hmm/adkGSL.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 515,
"size": 1751
} |
// Copyright 2021 atframework
// Created by owent on
#pragma once
#include <stdint.h>
#include <cstddef>
#include <cstring>
#include <memory>
#include <string>
#include <type_traits>
#include <config/compiler/protobuf_prefix.h>
#include <rapidjson/document.h>
#include <config/compiler/protobuf_suffix.h>
#include <gsl/select-gsl.h>
#include <log/log_wrapper.h>
#include <libatbus.h>
#include "atframe/atapp_config.h"
namespace google {
namespace protobuf {
class Message;
class Timestamp;
class Duration;
} // namespace protobuf
} // namespace google
namespace atapp {
struct LIBATAPP_MACRO_API_HEAD_ONLY rapidsjon_loader_string_mode {
enum type {
RAW = 0,
URI,
URI_COMPONENT,
};
};
struct LIBATAPP_MACRO_API_HEAD_ONLY rapidsjon_loader_load_options {
bool reserve_empty;
bool convert_large_number_to_string; // it's friendly to JSON.parse(...) in javascript
rapidsjon_loader_string_mode::type string_mode;
inline rapidsjon_loader_load_options()
: reserve_empty(false), convert_large_number_to_string(false), string_mode(rapidsjon_loader_string_mode::RAW) {}
};
struct LIBATAPP_MACRO_API_HEAD_ONLY rapidsjon_loader_dump_options {
rapidsjon_loader_string_mode::type string_mode;
bool convert_number_from_string; // it's friendly to JSON.parse(...) in javascript
inline rapidsjon_loader_dump_options()
: string_mode(rapidsjon_loader_string_mode::RAW), convert_number_from_string(true) {}
};
LIBATAPP_MACRO_API std::string rapidsjon_loader_stringify(const rapidjson::Document &doc, size_t more_reserve_size = 0);
LIBATAPP_MACRO_API bool rapidsjon_loader_unstringify(rapidjson::Document &doc, const std::string &json);
LIBATAPP_MACRO_API const char *rapidsjon_loader_get_type_name(rapidjson::Type t);
LIBATAPP_MACRO_API std::string rapidsjon_loader_stringify(
const ATBUS_MACRO_PROTOBUF_NAMESPACE_ID::Message &src,
const rapidsjon_loader_load_options &options = rapidsjon_loader_load_options());
LIBATAPP_MACRO_API bool rapidsjon_loader_parse(
ATBUS_MACRO_PROTOBUF_NAMESPACE_ID::Message &dst, const std::string &src,
const rapidsjon_loader_dump_options &options = rapidsjon_loader_dump_options());
LIBATAPP_MACRO_API void rapidsjon_loader_mutable_set_member(rapidjson::Value &parent, gsl::string_view key,
rapidjson::Value &&val, rapidjson::Document &doc);
LIBATAPP_MACRO_API void rapidsjon_loader_mutable_set_member(rapidjson::Value &parent, gsl::string_view key,
const rapidjson::Value &val, rapidjson::Document &doc);
LIBATAPP_MACRO_API void rapidsjon_loader_mutable_set_member(rapidjson::Value &parent, gsl::string_view key,
gsl::string_view val, rapidjson::Document &doc);
LIBATAPP_MACRO_API void rapidsjon_loader_append_to_list(rapidjson::Value &list_parent, gsl::string_view val,
rapidjson::Document &doc);
LIBATAPP_MACRO_API void rapidsjon_loader_dump_to(
const rapidjson::Document &src, ATBUS_MACRO_PROTOBUF_NAMESPACE_ID::Message &dst,
const rapidsjon_loader_dump_options &options = rapidsjon_loader_dump_options());
LIBATAPP_MACRO_API void rapidsjon_loader_load_from(
rapidjson::Document &dst, const ATBUS_MACRO_PROTOBUF_NAMESPACE_ID::Message &src,
const rapidsjon_loader_load_options &options = rapidsjon_loader_load_options());
LIBATAPP_MACRO_API void rapidsjon_loader_dump_to(
const rapidjson::Value &src, ATBUS_MACRO_PROTOBUF_NAMESPACE_ID::Message &dst,
const rapidsjon_loader_dump_options &options = rapidsjon_loader_dump_options());
LIBATAPP_MACRO_API void rapidsjon_loader_load_from(
rapidjson::Value &dst, rapidjson::Document &doc, const ATBUS_MACRO_PROTOBUF_NAMESPACE_ID::Message &src,
const rapidsjon_loader_load_options &options = rapidsjon_loader_load_options());
// ============ template implement ============
template <class TVAL, bool>
struct rapidsjon_loader_mutable_member_helper;
template <class TVAL>
struct rapidsjon_loader_mutable_member_helper<TVAL, true> {
static LIBATAPP_MACRO_API_HEAD_ONLY inline void set(rapidjson::Value &parent, gsl::string_view key, TVAL &&val,
rapidjson::Document &doc) {
rapidsjon_loader_mutable_set_member(parent, key, gsl::string_view(std::forward<TVAL>(val)), doc);
}
static LIBATAPP_MACRO_API_HEAD_ONLY inline void append(rapidjson::Value &parent, TVAL &&val,
rapidjson::Document &doc) {
rapidsjon_loader_append_to_list(parent, gsl::string_view(std::forward<TVAL>(val)), doc);
}
};
template <class TVAL>
struct rapidsjon_loader_mutable_member_helper<TVAL, false> {
static LIBATAPP_MACRO_API_HEAD_ONLY inline void set(rapidjson::Value &parent, gsl::string_view key, TVAL &&val,
rapidjson::Document &doc) {
if (parent.IsNull()) {
parent.SetObject();
}
if (!parent.IsObject()) {
FWLOGERROR("parent should be a object, but we got {}.", rapidsjon_loader_get_type_name(parent.GetType()));
return;
}
rapidjson::Value jkey;
jkey.SetString(rapidjson::StringRef(key.data(), static_cast<rapidjson::SizeType>(key.size())));
rapidjson::Value::MemberIterator iter = parent.FindMember(jkey);
if (iter != parent.MemberEnd()) {
iter->value.Set(std::forward<TVAL>(val), doc.GetAllocator());
} else {
rapidjson::Value k;
k.SetString(key.data(), static_cast<rapidjson::SizeType>(key.size()), doc.GetAllocator());
parent.AddMember(k, std::forward<TVAL>(val), doc.GetAllocator());
}
}
static LIBATAPP_MACRO_API_HEAD_ONLY inline void append(rapidjson::Value &parent, TVAL &&val,
rapidjson::Document &doc) {
if (parent.IsNull()) {
parent.SetArray();
}
if (!parent.IsArray()) {
FWLOGERROR("parent should be a array, but we got {}.", rapidsjon_loader_get_type_name(parent.GetType()));
return;
}
parent.PushBack(std::forward<TVAL>(val), doc.GetAllocator());
}
};
template <class TVAL, class = typename std::enable_if<
!std::is_same<typename std::decay<TVAL>::type, gsl::string_view>::value>::type>
LIBATAPP_MACRO_API_HEAD_ONLY void rapidsjon_loader_mutable_set_member(rapidjson::Value &parent, gsl::string_view key,
TVAL &&val, rapidjson::Document &doc) {
rapidsjon_loader_mutable_member_helper<TVAL, std::is_convertible<TVAL, gsl::string_view>::value>::set(
parent, key, std::forward<TVAL>(val), doc);
}
template <class TVAL, class = typename std::enable_if<
!std::is_same<typename std::decay<TVAL>::type, gsl::string_view>::value>::type>
LIBATAPP_MACRO_API_HEAD_ONLY void rapidsjon_loader_append_to_list(rapidjson::Value &parent, TVAL &&val,
rapidjson::Document &doc) {
rapidsjon_loader_mutable_member_helper<TVAL, std::is_convertible<TVAL, gsl::string_view>::value>::append(
parent, std::forward<TVAL>(val), doc);
}
} // namespace atapp
| {
"alphanum_fraction": 0.6999589547,
"avg_line_length": 42.4941860465,
"ext": "h",
"hexsha": "6383981df07f33f8495d8dfae601f99539d89522",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2020-04-19T10:06:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-04T06:14:12.000Z",
"max_forks_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "atframework/libatapp",
"max_forks_repo_path": "include/atframe/atapp_conf_rapidjson.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80",
"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": "atframework/libatapp",
"max_issues_repo_path": "include/atframe/atapp_conf_rapidjson.h",
"max_line_length": 120,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "atframework/libatapp",
"max_stars_repo_path": "include/atframe/atapp_conf_rapidjson.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-29T01:22:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-23T04:38:33.000Z",
"num_tokens": 1670,
"size": 7309
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_errno.h>
#include "ccl.h"
#include "ccl_params.h"
#include "ccl_redshifts.h"
// ---- LSST redshift distributions & current specs -----
// ---- Consider spline for input dN/dz - pending
/*------ ROUTINE: ccl_create_photoz_info ------
INPUT: void * params, (double *) pz_func (double, double, void *)
TASK: create a structure amalgamating the user-input information on the photo-z model.
The structure holds a pointer to the function which returns the probability of getting a certain z_ph (first double)
given a z_spec (second double), and a pointer to the parameters which get passed to that function (other than z_ph and z_sp); */
pz_info* ccl_create_photoz_info(void * params,
double (*pz_func)(double, double,void*, int*))
{
pz_info * this_info = malloc(sizeof(pz_info));
this_info ->your_pz_params = params;
this_info -> your_pz_func = pz_func;
return this_info;
}
/*------ ROUTINE: ccl_photoz -----
INPUT: double z_ph, void *params
TASK: Returns the value of p(z_photo, z). Change this function to
change the way true-z and photo-z's are related.
This has to be in a form that gsl can integrate.
*/
// struct of parameters to pass to photo_z
struct pz_params{
double z_true; // Gives the true redshift at which to evaluate
pz_info * pz_information; //Calls the photo-z scatter model
int *status;
};
static double ccl_photoz(double z_ph, void * params)
{
struct pz_params * p = (struct pz_params *) params;
pz_info * user_stuff = (pz_info*) p->pz_information;
double z_s = p->z_true;
return (user_stuff->your_pz_func)(z_ph, z_s, user_stuff->your_pz_params,p->status);
}
// Gaussian photo-z function
double gaussian_pz(double z_ph, double z_s, void* params, int *status){
double sigma_z0 = *((double*) params);
double sigma_z = sigma_z0 * (1. + z_s);
return exp(- (z_ph - z_s)*(z_ph - z_s) / (2.*sigma_z*sigma_z)) \
/ (sqrt(2.*M_PI) *sigma_z);
}
/*------ ROUTINE: ccl_specs_create_gaussian_photoz_info ------
INPUT: void * user_pz_params, (double *) user_pz_func (double, double, void *)
TASK: Convenience function for creating a Gaussian photo-z model with error
sigma(z) = sigma_z0 (1 + z). */
pz_info* ccl_create_gaussian_photoz_info(double sigma_z0){
// Allocate memory so that this value persists
double* sigma_z0_copy = malloc(sizeof(double));
*sigma_z0_copy = sigma_z0;
// Construct pz_info struct
pz_info * this_info = malloc(sizeof(pz_info));
this_info->your_pz_params = sigma_z0_copy;
this_info->your_pz_func = &gaussian_pz;
return this_info;
}
/* ------ ROUTINE: ccl_free_photoz_info -------
INPUT: pz_info my_photoz_info
TASK: free memory holding the structure containing user-input photoz information */
void ccl_free_photoz_info(pz_info *my_photoz_info)
{
free(my_photoz_info);
}
/*------ ROUTINE: ccl_create_dNdz_info ------
INPUT: void * params, (double *) dNdz_func (double, void *, int*)
TASK: create a structure amalgamating the information on an analytic true dNdz model.
The structure holds a pointer to the function which returns the analytic dNdz
* and a pointer to the parameters which get passed to that function (other than z); */
dNdz_info* ccl_create_dNdz_info(void * params, double(*dNdz_func)(double,void*,int*))
{
dNdz_info * this_info = malloc(sizeof(dNdz_info));
this_info ->your_dN_params = params;
this_info -> your_dN_func = dNdz_func;
return this_info;
}
/*------ ROUTINE: dNdz_smail ----------
* INPUT: z, params (containing: alpha, beta, z0), status
* OUTPUT: Analytic Smail et al. type dNdz (NOT normalized) */
double dNdz_smail(double z, void* params, int *status){
double alpha = ((smail_params*) params)->alpha;
double beta = ((smail_params*) params)->beta;
double z0 = ((smail_params*) params)->z0;
return pow(z, alpha) * exp(- pow(z/z0, beta) );
}
/*------ ROUTINE: ccl_create_smail_dNdz_info ------
INPUT: alpha, beta, z0
TASK: Convenience function for creating an analytic dNdz wrt true z
* of the 'smail' form: dNdz ~ z^alpha exp(- (z/z0)^beta) */
dNdz_info* ccl_create_Smail_dNdz_info(double alpha, double beta, double z0){
// Allocate a smail type parmaeter structure
smail_params * smail_par = malloc(sizeof(smail_params));
smail_par->alpha = alpha;
smail_par->beta = beta;
smail_par->z0 = z0;
// Construct dNdz_info struct
dNdz_info * this_info = malloc(sizeof(dNdz_info));
this_info->your_dN_params = smail_par;
this_info->your_dN_func = &dNdz_smail;
return this_info;
}
/*------ ROUTINE: ccl_dNdz -----
INPUT: double z, void *params
TASK: Returns the value of dNdz(z). Change this function to
change the way true-z and photo-z's are related.
This has to be in a form that gsl can integrate.
*/
static double ccl_dNdz(double z, dNdz_info* params, int* status)
{
return (params->your_dN_func)(z, params->your_dN_params, status);
}
/* ------ ROUTINE: ccl_free_dNdz_info -------
INPUT: dNdz_info my_dNdz_info
TASK: free memory holding the structure containing dNdz information */
void ccl_free_dNdz_info(dNdz_info *my_dNdz_info)
{
free(my_dNdz_info);
}
/*------ ROUTINE: ccl_specs_norm_integrand -----
INPUT: double z_ph, void *params
TASK: Returns the integrand which is integrated to get the normalization of
dNdz in a given photometric redshift bin (the denominator from dNdz_sources_tomog).
This has to be an separate function that gsl can integrate.
*/
// struct of parameters to pass to norm_integrand
struct norm_params {
double bin_zmin_;
double bin_zmax_;
pz_info * pz_information;
dNdz_info * dN_information;
int *status;
};
static double ccl_norm_integrand(double z, void* params)
{
// This is a struct that contains a true redshift and a pointer to the information about the photo_z model
struct pz_params pz_val_p; // parameters for the photoz pdf wrt true-z
double pz_int=0; // pointer to the value of the integral over the photoz model
struct norm_params *p = (struct norm_params *) params; // parameters of the current function (because of form required for gsl integration)
double z_min = p->bin_zmin_;
double z_max = p->bin_zmax_;
// Check whether ccl_splines and ccl_gsl exist; exit gracefully if they
// can't be loaded
if(ccl_splines==NULL || ccl_gsl==NULL) ccl_cosmology_read_config();
if(ccl_splines==NULL || ccl_gsl==NULL) {
ccl_raise_exception(CCL_ERROR_MISSING_CONFIG_FILE,
"ccl_redshift.c: Failed to read config file.");
return NAN;
}
// Set up parameters for the pz part of the intermediary integral.
pz_val_p.z_true = z;
pz_val_p.status = p->status;
pz_val_p.pz_information = p-> pz_information;
// Do the intermediary integral over the model relating photo-z to true-z
gsl_integration_cquad_workspace * workspace = gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION);
gsl_function F;
F.function = ccl_photoz;
F.params = &pz_val_p;
int gslstatus = gsl_integration_cquad(&F, z_min, z_max, 0.0,ccl_gsl->INTEGRATION_DNDZ_EPSREL,workspace,&pz_int, NULL, NULL);
if(gslstatus != GSL_SUCCESS) {
ccl_raise_gsl_warning(gslstatus, "ccl_redshifts.c: ccl_specs_norm_integrand():");
*p->status|= gslstatus;
}
gsl_integration_cquad_workspace_free(workspace);
return ccl_dNdz(z, p->dN_information, p->status) * pz_int ;
}
/*------ ROUTINE: ccl_specs_dNdz_tomog -----
INPUT: double z, , double bin_zmin, double bin_zmax, dNdz function pointer, sigma_z function pointer
tomographic boundaries are [bin_zmin,bin_zmax]
TASK: dNdz in a particular tomographic bin,
convolved with a photo-z model (defined by the user), and normalized.
returns a status integer 0 if called with an allowable type of dNdz, non-zero otherwise
(this is different from the regular status handling procedure because we don't pass a cosmology to this function)
*/
void ccl_dNdz_tomog(double z, double bin_zmin, double bin_zmax,
pz_info * photo_info, dNdz_info * dN_info, double *tomoout, int *status)
{
// This uses equation 33 of Joachimi & Schneider 2009, arxiv:0905.0393
double numerator_integrand=0, denom_integrand=0, dNdz_t;
// This struct contains a spec redshift and a pointer to a photoz information struct.
struct pz_params pz_p_val; //parameters for the integral over the photoz's
struct norm_params norm_p_val;
// Check whether ccl_splines and ccl_gsl exist; exit gracefully if they
// can't be loaded
if(ccl_splines==NULL || ccl_gsl==NULL) ccl_cosmology_read_config();
if(ccl_splines==NULL || ccl_gsl==NULL) {
ccl_raise_exception(CCL_ERROR_MISSING_CONFIG_FILE,
"ccl_redshifts.c: Failed to read config file.");
*status = CCL_ERROR_MISSING_CONFIG_FILE;
return;
}
// Set up the parameters to pass to the normalising integral (of type struct norm_params
norm_p_val.bin_zmin_=bin_zmin;
norm_p_val.bin_zmax_=bin_zmax;
norm_p_val.pz_information = photo_info;
norm_p_val.status = status;
norm_p_val.dN_information = dN_info;
dNdz_t = ccl_dNdz(z, dN_info, status);
// Set up the parameters for the integral over the photo z function in the numerator (of type struct pz_params)
pz_p_val.z_true = z;
pz_p_val.status = status;
pz_p_val.pz_information = photo_info; // pointer to user information
// Integrate over the assumed pdf of photo-z wrt true-z in this bin (this goes in the numerator of the result):
gsl_integration_cquad_workspace * workspace = gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION);
gsl_function F;
F.function = ccl_photoz;
F.params = &pz_p_val;
int gslstatus = gsl_integration_cquad(&F, bin_zmin, bin_zmax, 0.0,ccl_gsl->INTEGRATION_DNDZ_EPSREL,workspace,&numerator_integrand, NULL, NULL);
if(gslstatus != GSL_SUCCESS) {
ccl_raise_gsl_warning(gslstatus, "ccl_redshifts.c: ccl_norm_integrand():");
*status |= gslstatus;
}
gsl_integration_cquad_workspace_free(workspace);
// Now get the denominator, which normalizes dNdz over the photometric bin
workspace = gsl_integration_cquad_workspace_alloc(ccl_gsl->N_ITERATION);
F.function = ccl_norm_integrand;
F.params = &norm_p_val;
gslstatus = gsl_integration_cquad(&F, Z_MIN_SOURCES, Z_MAX_SOURCES, 0.0,ccl_gsl->INTEGRATION_DNDZ_EPSREL,workspace,&denom_integrand, NULL, NULL);
if(gslstatus != GSL_SUCCESS) {
ccl_raise_gsl_warning(gslstatus, "ccl_redshifts.c: ccl_norm_integrand():");
*status |= gslstatus;
}
gsl_integration_cquad_workspace_free(workspace);
if (*status) {
*status = CCL_ERROR_INTEG;
return;
}
*tomoout = dNdz_t * numerator_integrand / denom_integrand;
}
| {
"alphanum_fraction": 0.7208229541,
"avg_line_length": 38.0315789474,
"ext": "c",
"hexsha": "e606751253fa10ded06683c9487fd3846209cf69",
"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": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "vrastil/CCL",
"max_forks_repo_path": "src/ccl_redshifts.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3",
"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": "vrastil/CCL",
"max_issues_repo_path": "src/ccl_redshifts.c",
"max_line_length": 147,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "vrastil/CCL",
"max_stars_repo_path": "src/ccl_redshifts.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3022,
"size": 10839
} |
// NIT_inspiral - code to rapidly compute extreme mass-ratio inspirals using self-force results
// Copyright (C) 2017 Niels Warburton
//
// 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 <https://www.gnu.org/licenses/>.
#ifndef __INTERPOLANT_H__
#define __INTERPOLANT_H__
#include <vector>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
using namespace std;
typedef vector<double> Vector;
class Interpolant{
public:
// 1D interpolation
Interpolant(Vector x, Vector f);
double eval(double x);
// 2D interpolation
Interpolant(Vector x, Vector y, Vector f);
double eval(double x, double y);
// Destructor
~Interpolant();
private:
int interp_type; // Set to 1 for 1D interpolation and 2 for 2D interpolation
gsl_spline *spline;
gsl_spline2d *spline2d;
gsl_interp_accel *xacc;
gsl_interp_accel *yacc;
};
#endif // __INTERPOLANT_H__
| {
"alphanum_fraction": 0.7457511897,
"avg_line_length": 28.2884615385,
"ext": "h",
"hexsha": "c0e2aa92ad897312e17e8b0432b1274966cd563c",
"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": "ebabce680fc87e90ff1de30246dcda9beb384bb4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "basuparth/ICERM_Workshop",
"max_forks_repo_path": "FastEMRIWaveforms/include/Interpolant.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ebabce680fc87e90ff1de30246dcda9beb384bb4",
"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": "basuparth/ICERM_Workshop",
"max_issues_repo_path": "FastEMRIWaveforms/include/Interpolant.h",
"max_line_length": 95,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ebabce680fc87e90ff1de30246dcda9beb384bb4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "basuparth/ICERM_Workshop",
"max_stars_repo_path": "FastEMRIWaveforms/include/Interpolant.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 390,
"size": 1471
} |
/*
* 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:57 EST 1999 */
#include <fftw-int.h>
#include <fftw.h>
/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -twiddleinv 2 */
/*
* This function contains 6 FP additions, 4 FP multiplications,
* (or, 4 additions, 2 multiplications, 2 fused multiply/add),
* 10 stack variables, and 8 memory accesses
*/
/*
* 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 fftwi_twiddle_2(fftw_complex *A, const fftw_complex *W, int iostride, int m, int dist)
{
int i;
fftw_complex *inout;
inout = A;
for (i = m; i > 0; i = i - 1, inout = inout + dist, W = W + 1) {
fftw_real tmp1;
fftw_real tmp8;
fftw_real tmp6;
fftw_real tmp7;
ASSERT_ALIGNED_DOUBLE;
tmp1 = c_re(inout[0]);
tmp8 = c_im(inout[0]);
{
fftw_real tmp3;
fftw_real tmp5;
fftw_real tmp2;
fftw_real tmp4;
ASSERT_ALIGNED_DOUBLE;
tmp3 = c_re(inout[iostride]);
tmp5 = c_im(inout[iostride]);
tmp2 = c_re(W[0]);
tmp4 = c_im(W[0]);
tmp6 = (tmp2 * tmp3) + (tmp4 * tmp5);
tmp7 = (tmp2 * tmp5) - (tmp4 * tmp3);
}
c_re(inout[iostride]) = tmp1 - tmp6;
c_re(inout[0]) = tmp1 + tmp6;
c_im(inout[0]) = tmp7 + tmp8;
c_im(inout[iostride]) = tmp8 - tmp7;
}
}
static const int twiddle_order[] =
{1};
fftw_codelet_desc fftwi_twiddle_2_desc =
{
"fftwi_twiddle_2",
(void (*)()) fftwi_twiddle_2,
2,
FFTW_BACKWARD,
FFTW_TWIDDLE,
55,
1,
twiddle_order,
};
| {
"alphanum_fraction": 0.6472428627,
"avg_line_length": 29.3908045977,
"ext": "c",
"hexsha": "e25d8c818695491dceb58d704a6408f523d1bfac",
"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/fftw/ftwi_2.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/fftw/ftwi_2.c",
"max_line_length": 121,
"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/fftw/ftwi_2.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": 803,
"size": 2557
} |
/* linalg/gsl_linalg.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2006, 2007 Gerard Jungman, Brian Gough, 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.
*/
#ifndef __GSL_LINALG_H__
#define __GSL_LINALG_H__
#include <gsl/gsl_mode.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.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 enum
{
GSL_LINALG_MOD_NONE = 0,
GSL_LINALG_MOD_TRANSPOSE = 1,
GSL_LINALG_MOD_CONJUGATE = 2
}
gsl_linalg_matrix_mod_t;
/* Note: You can now use the gsl_blas_dgemm function instead of matmult */
/* Simple implementation of matrix multiply.
* Calculates C = A.B
*
* exceptions: GSL_EBADLEN
*/
int gsl_linalg_matmult (const gsl_matrix * A,
const gsl_matrix * B,
gsl_matrix * C);
/* Simple implementation of matrix multiply.
* Allows transposition of either matrix, so it
* can compute A.B or Trans(A).B or A.Trans(B) or Trans(A).Trans(B)
*
* exceptions: GSL_EBADLEN
*/
int gsl_linalg_matmult_mod (const gsl_matrix * A,
gsl_linalg_matrix_mod_t modA,
const gsl_matrix * B,
gsl_linalg_matrix_mod_t modB,
gsl_matrix * C);
/* Calculate the matrix exponential by the scaling and
* squaring method described in Moler + Van Loan,
* SIAM Rev 20, 801 (1978). The mode argument allows
* choosing an optimal strategy, from the table
* given in the paper, for a given precision.
*
* exceptions: GSL_ENOTSQR, GSL_EBADLEN
*/
int gsl_linalg_exponential_ss(
const gsl_matrix * A,
gsl_matrix * eA,
gsl_mode_t mode
);
/* Householder Transformations */
double gsl_linalg_householder_transform (gsl_vector * v);
gsl_complex gsl_linalg_complex_householder_transform (gsl_vector_complex * v);
int gsl_linalg_householder_hm (double tau,
const gsl_vector * v,
gsl_matrix * A);
int gsl_linalg_householder_mh (double tau,
const gsl_vector * v,
gsl_matrix * A);
int gsl_linalg_householder_hv (double tau,
const gsl_vector * v,
gsl_vector * w);
int gsl_linalg_householder_hm1 (double tau,
gsl_matrix * A);
int gsl_linalg_complex_householder_hm (gsl_complex tau,
const gsl_vector_complex * v,
gsl_matrix_complex * A);
int gsl_linalg_complex_householder_mh (gsl_complex tau,
const gsl_vector_complex * v,
gsl_matrix_complex * A);
int gsl_linalg_complex_householder_hv (gsl_complex tau,
const gsl_vector_complex * v,
gsl_vector_complex * w);
/* Hessenberg reduction */
int gsl_linalg_hessenberg_decomp(gsl_matrix *A, gsl_vector *tau);
int gsl_linalg_hessenberg_unpack(gsl_matrix * H, gsl_vector * tau,
gsl_matrix * U);
int gsl_linalg_hessenberg_unpack_accum(gsl_matrix * H, gsl_vector * tau,
gsl_matrix * U);
int gsl_linalg_hessenberg_set_zero(gsl_matrix * H);
int gsl_linalg_hessenberg_submatrix(gsl_matrix *M, gsl_matrix *A,
size_t top, gsl_vector *tau);
/* To support gsl-1.9 interface: DEPRECATED */
int gsl_linalg_hessenberg(gsl_matrix *A, gsl_vector *tau);
/* Hessenberg-Triangular reduction */
int gsl_linalg_hesstri_decomp(gsl_matrix * A, gsl_matrix * B,
gsl_matrix * U, gsl_matrix * V,
gsl_vector * work);
/* Singular Value Decomposition
* exceptions:
*/
int
gsl_linalg_SV_decomp (gsl_matrix * A,
gsl_matrix * V,
gsl_vector * S,
gsl_vector * work);
int
gsl_linalg_SV_decomp_mod (gsl_matrix * A,
gsl_matrix * X,
gsl_matrix * V,
gsl_vector * S,
gsl_vector * work);
int gsl_linalg_SV_decomp_jacobi (gsl_matrix * A,
gsl_matrix * Q,
gsl_vector * S);
int
gsl_linalg_SV_solve (const gsl_matrix * U,
const gsl_matrix * Q,
const gsl_vector * S,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_SV_leverage(const gsl_matrix *U, gsl_vector *h);
/* LU Decomposition, Gaussian elimination with partial pivoting
*/
int gsl_linalg_LU_decomp (gsl_matrix * A, gsl_permutation * p, int *signum);
int gsl_linalg_LU_solve (const gsl_matrix * LU,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_LU_svx (const gsl_matrix * LU,
const gsl_permutation * p,
gsl_vector * x);
int gsl_linalg_LU_refine (const gsl_matrix * A,
const gsl_matrix * LU,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x,
gsl_vector * residual);
int gsl_linalg_LU_invert (const gsl_matrix * LU,
const gsl_permutation * p,
gsl_matrix * inverse);
double gsl_linalg_LU_det (gsl_matrix * LU, int signum);
double gsl_linalg_LU_lndet (gsl_matrix * LU);
int gsl_linalg_LU_sgndet (gsl_matrix * lu, int signum);
/* Complex LU Decomposition */
int gsl_linalg_complex_LU_decomp (gsl_matrix_complex * A,
gsl_permutation * p,
int *signum);
int gsl_linalg_complex_LU_solve (const gsl_matrix_complex * LU,
const gsl_permutation * p,
const gsl_vector_complex * b,
gsl_vector_complex * x);
int gsl_linalg_complex_LU_svx (const gsl_matrix_complex * LU,
const gsl_permutation * p,
gsl_vector_complex * x);
int gsl_linalg_complex_LU_refine (const gsl_matrix_complex * A,
const gsl_matrix_complex * LU,
const gsl_permutation * p,
const gsl_vector_complex * b,
gsl_vector_complex * x,
gsl_vector_complex * residual);
int gsl_linalg_complex_LU_invert (const gsl_matrix_complex * LU,
const gsl_permutation * p,
gsl_matrix_complex * inverse);
gsl_complex gsl_linalg_complex_LU_det (gsl_matrix_complex * LU,
int signum);
double gsl_linalg_complex_LU_lndet (gsl_matrix_complex * LU);
gsl_complex gsl_linalg_complex_LU_sgndet (gsl_matrix_complex * LU,
int signum);
/* QR decomposition */
int gsl_linalg_QR_decomp (gsl_matrix * A,
gsl_vector * tau);
int gsl_linalg_QR_solve (const gsl_matrix * QR,
const gsl_vector * tau,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_QR_svx (const gsl_matrix * QR,
const gsl_vector * tau,
gsl_vector * x);
int gsl_linalg_QR_lssolve (const gsl_matrix * QR,
const gsl_vector * tau,
const gsl_vector * b,
gsl_vector * x,
gsl_vector * residual);
int gsl_linalg_QR_QRsolve (gsl_matrix * Q,
gsl_matrix * R,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_QR_Rsolve (const gsl_matrix * QR,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_QR_Rsvx (const gsl_matrix * QR,
gsl_vector * x);
int gsl_linalg_QR_update (gsl_matrix * Q,
gsl_matrix * R,
gsl_vector * w,
const gsl_vector * v);
int gsl_linalg_QR_QTvec (const gsl_matrix * QR,
const gsl_vector * tau,
gsl_vector * v);
int gsl_linalg_QR_Qvec (const gsl_matrix * QR,
const gsl_vector * tau,
gsl_vector * v);
int gsl_linalg_QR_QTmat (const gsl_matrix * QR,
const gsl_vector * tau,
gsl_matrix * A);
int gsl_linalg_QR_unpack (const gsl_matrix * QR,
const gsl_vector * tau,
gsl_matrix * Q,
gsl_matrix * R);
int gsl_linalg_R_solve (const gsl_matrix * R,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_R_svx (const gsl_matrix * R,
gsl_vector * x);
/* Q R P^T decomposition */
int gsl_linalg_QRPT_decomp (gsl_matrix * A,
gsl_vector * tau,
gsl_permutation * p,
int *signum,
gsl_vector * norm);
int gsl_linalg_QRPT_decomp2 (const gsl_matrix * A,
gsl_matrix * q, gsl_matrix * r,
gsl_vector * tau,
gsl_permutation * p,
int *signum,
gsl_vector * norm);
int gsl_linalg_QRPT_solve (const gsl_matrix * QR,
const gsl_vector * tau,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_QRPT_svx (const gsl_matrix * QR,
const gsl_vector * tau,
const gsl_permutation * p,
gsl_vector * x);
int gsl_linalg_QRPT_QRsolve (const gsl_matrix * Q,
const gsl_matrix * R,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_QRPT_Rsolve (const gsl_matrix * QR,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_QRPT_Rsvx (const gsl_matrix * QR,
const gsl_permutation * p,
gsl_vector * x);
int gsl_linalg_QRPT_update (gsl_matrix * Q,
gsl_matrix * R,
const gsl_permutation * p,
gsl_vector * u,
const gsl_vector * v);
/* LQ decomposition */
int gsl_linalg_LQ_decomp (gsl_matrix * A, gsl_vector * tau);
int gsl_linalg_LQ_solve_T (const gsl_matrix * LQ, const gsl_vector * tau,
const gsl_vector * b, gsl_vector * x);
int gsl_linalg_LQ_svx_T (const gsl_matrix * LQ, const gsl_vector * tau,
gsl_vector * x);
int gsl_linalg_LQ_lssolve_T (const gsl_matrix * LQ, const gsl_vector * tau,
const gsl_vector * b, gsl_vector * x,
gsl_vector * residual);
int gsl_linalg_LQ_Lsolve_T (const gsl_matrix * LQ, const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_LQ_Lsvx_T (const gsl_matrix * LQ, gsl_vector * x);
int gsl_linalg_L_solve_T (const gsl_matrix * L, const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_LQ_vecQ (const gsl_matrix * LQ, const gsl_vector * tau,
gsl_vector * v);
int gsl_linalg_LQ_vecQT (const gsl_matrix * LQ, const gsl_vector * tau,
gsl_vector * v);
int gsl_linalg_LQ_unpack (const gsl_matrix * LQ, const gsl_vector * tau,
gsl_matrix * Q, gsl_matrix * L);
int gsl_linalg_LQ_update (gsl_matrix * Q, gsl_matrix * R,
const gsl_vector * v, gsl_vector * w);
int gsl_linalg_LQ_LQsolve (gsl_matrix * Q, gsl_matrix * L,
const gsl_vector * b, gsl_vector * x);
/* P^T L Q decomposition */
int gsl_linalg_PTLQ_decomp (gsl_matrix * A, gsl_vector * tau,
gsl_permutation * p, int *signum,
gsl_vector * norm);
int gsl_linalg_PTLQ_decomp2 (const gsl_matrix * A, gsl_matrix * q,
gsl_matrix * r, gsl_vector * tau,
gsl_permutation * p, int *signum,
gsl_vector * norm);
int gsl_linalg_PTLQ_solve_T (const gsl_matrix * QR,
const gsl_vector * tau,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_PTLQ_svx_T (const gsl_matrix * LQ,
const gsl_vector * tau,
const gsl_permutation * p,
gsl_vector * x);
int gsl_linalg_PTLQ_LQsolve_T (const gsl_matrix * Q, const gsl_matrix * L,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_PTLQ_Lsolve_T (const gsl_matrix * LQ,
const gsl_permutation * p,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_PTLQ_Lsvx_T (const gsl_matrix * LQ,
const gsl_permutation * p,
gsl_vector * x);
int gsl_linalg_PTLQ_update (gsl_matrix * Q, gsl_matrix * L,
const gsl_permutation * p,
const gsl_vector * v, gsl_vector * w);
/* Cholesky Decomposition */
int gsl_linalg_cholesky_decomp (gsl_matrix * A);
int gsl_linalg_cholesky_solve (const gsl_matrix * cholesky,
const gsl_vector * b,
gsl_vector * x);
int gsl_linalg_cholesky_svx (const gsl_matrix * cholesky,
gsl_vector * x);
int gsl_linalg_cholesky_invert(gsl_matrix * cholesky);
/* Cholesky decomposition with unit-diagonal triangular parts.
* A = L D L^T, where diag(L) = (1,1,...,1).
* Upon exit, A contains L and L^T as for Cholesky, and
* the diagonal of A is (1,1,...,1). The vector Dis set
* to the diagonal elements of the diagonal matrix D.
*/
int gsl_linalg_cholesky_decomp_unit(gsl_matrix * A, gsl_vector * D);
/* Complex Cholesky Decomposition */
int gsl_linalg_complex_cholesky_decomp (gsl_matrix_complex * A);
int gsl_linalg_complex_cholesky_solve (const gsl_matrix_complex * cholesky,
const gsl_vector_complex * b,
gsl_vector_complex * x);
int gsl_linalg_complex_cholesky_svx (const gsl_matrix_complex * cholesky,
gsl_vector_complex * x);
int gsl_linalg_complex_cholesky_invert(gsl_matrix_complex * cholesky);
/* Symmetric to symmetric tridiagonal decomposition */
int gsl_linalg_symmtd_decomp (gsl_matrix * A,
gsl_vector * tau);
int gsl_linalg_symmtd_unpack (const gsl_matrix * A,
const gsl_vector * tau,
gsl_matrix * Q,
gsl_vector * diag,
gsl_vector * subdiag);
int gsl_linalg_symmtd_unpack_T (const gsl_matrix * A,
gsl_vector * diag,
gsl_vector * subdiag);
/* Hermitian to symmetric tridiagonal decomposition */
int gsl_linalg_hermtd_decomp (gsl_matrix_complex * A,
gsl_vector_complex * tau);
int gsl_linalg_hermtd_unpack (const gsl_matrix_complex * A,
const gsl_vector_complex * tau,
gsl_matrix_complex * U,
gsl_vector * diag,
gsl_vector * sudiag);
int gsl_linalg_hermtd_unpack_T (const gsl_matrix_complex * A,
gsl_vector * diag,
gsl_vector * subdiag);
/* Linear Solve Using Householder Transformations
* exceptions:
*/
int gsl_linalg_HH_solve (gsl_matrix * A, const gsl_vector * b, gsl_vector * x);
int gsl_linalg_HH_svx (gsl_matrix * A, gsl_vector * x);
/* Linear solve for a symmetric tridiagonal system.
* The input vectors represent the NxN matrix as follows:
*
* diag[0] offdiag[0] 0 ...
* offdiag[0] diag[1] offdiag[1] ...
* 0 offdiag[1] diag[2] ...
* 0 0 offdiag[2] ...
* ... ... ... ...
*/
int gsl_linalg_solve_symm_tridiag (const gsl_vector * diag,
const gsl_vector * offdiag,
const gsl_vector * b,
gsl_vector * x);
/* Linear solve for a nonsymmetric tridiagonal system.
* The input vectors represent the NxN matrix as follows:
*
* diag[0] abovediag[0] 0 ...
* belowdiag[0] diag[1] abovediag[1] ...
* 0 belowdiag[1] diag[2] ...
* 0 0 belowdiag[2] ...
* ... ... ... ...
*/
int gsl_linalg_solve_tridiag (const gsl_vector * diag,
const gsl_vector * abovediag,
const gsl_vector * belowdiag,
const gsl_vector * b,
gsl_vector * x);
/* Linear solve for a symmetric cyclic tridiagonal system.
* The input vectors represent the NxN matrix as follows:
*
* diag[0] offdiag[0] 0 ..... offdiag[N-1]
* offdiag[0] diag[1] offdiag[1] .....
* 0 offdiag[1] diag[2] .....
* 0 0 offdiag[2] .....
* ... ...
* offdiag[N-1] ...
*/
int gsl_linalg_solve_symm_cyc_tridiag (const gsl_vector * diag,
const gsl_vector * offdiag,
const gsl_vector * b,
gsl_vector * x);
/* Linear solve for a nonsymmetric cyclic tridiagonal system.
* The input vectors represent the NxN matrix as follows:
*
* diag[0] abovediag[0] 0 ..... belowdiag[N-1]
* belowdiag[0] diag[1] abovediag[1] .....
* 0 belowdiag[1] diag[2]
* 0 0 belowdiag[2] .....
* ... ...
* abovediag[N-1] ...
*/
int gsl_linalg_solve_cyc_tridiag (const gsl_vector * diag,
const gsl_vector * abovediag,
const gsl_vector * belowdiag,
const gsl_vector * b,
gsl_vector * x);
/* Bidiagonal decomposition */
int gsl_linalg_bidiag_decomp (gsl_matrix * A,
gsl_vector * tau_U,
gsl_vector * tau_V);
int gsl_linalg_bidiag_unpack (const gsl_matrix * A,
const gsl_vector * tau_U,
gsl_matrix * U,
const gsl_vector * tau_V,
gsl_matrix * V,
gsl_vector * diag,
gsl_vector * superdiag);
int gsl_linalg_bidiag_unpack2 (gsl_matrix * A,
gsl_vector * tau_U,
gsl_vector * tau_V,
gsl_matrix * V);
int gsl_linalg_bidiag_unpack_B (const gsl_matrix * A,
gsl_vector * diag,
gsl_vector * superdiag);
/* Balancing */
int gsl_linalg_balance_matrix (gsl_matrix * A, gsl_vector * D);
int gsl_linalg_balance_accum (gsl_matrix * A, gsl_vector * D);
int gsl_linalg_balance_columns (gsl_matrix * A, gsl_vector * D);
__END_DECLS
#endif /* __GSL_LINALG_H__ */
| {
"alphanum_fraction": 0.5412155745,
"avg_line_length": 35.3949579832,
"ext": "h",
"hexsha": "9e2710d7658a75d2ff07f9c7b4efc493fb99c7c7",
"lang": "C",
"max_forks_count": 173,
"max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z",
"max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_forks_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_forks_repo_name": "juandesant/astrometry.net",
"max_forks_repo_path": "gsl-an/gsl/gsl_linalg.h",
"max_issues_count": 208,
"max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z",
"max_issues_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_issues_repo_name": "juandesant/astrometry.net",
"max_issues_repo_path": "gsl-an/gsl/gsl_linalg.h",
"max_line_length": 100,
"max_stars_count": 460,
"max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_stars_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_stars_repo_name": "juandesant/astrometry.net",
"max_stars_repo_path": "gsl-an/gsl/gsl_linalg.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z",
"num_tokens": 4700,
"size": 21060
} |
/**
* Interface to flatfielding
*/
#ifndef _SPC_FLATFIELD_H
#define _SPC_FLATFIELD_H 1
#include <stdlib.h>
#include <stdarg.h>
#include <math.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
typedef struct
{
int poly_order; /* order of the polynomial */
gsl_matrix **coeffs; /* the list of gsl_matrix'es containing */
/* the polynomial coefficients of the FF */
double wmin; /* Minumum wavelength value for the coeff. normalization */
double wmax; /* Maximum wavelength value for the coeff. normalization */
}
poly_cube_flatfield;
/**
Descriptor of flatfield with a single flatfield image and a
polynomial flatfield dependence.
*/
typedef struct
{
gsl_matrix *flatfield; /* The flatfield image, giving the relative
efficiency for each pixel in the aperture */
gsl_matrix *errors; /* relative errors for flatfield */
int poly_order; /* order of the polynomial */
double *poly_coeffs; /* coefficients for the polynom */
}
polynom_flatfield;
/**
Descriptor of flatfield with multiple flatfields at different
wave lengths
*/
typedef struct
{
int num_flats; /* number of (lambda,flatfield) pairs */
gsl_matrix **flatfields; /* flatfield images, giving the relative
efficiency for each pixel in the aperture */
gsl_matrix **errors; /* relative errors for flatfields */
double *lambdas; /* wave lengths for entries in flatfields */
}
multi_flatfield;
/**
Descriptor of a flatfielding function, including the function
to compute the flat field value of a given pixel, the bounding box
we handle, and auxillary data (usually a flatfield image)
*/
typedef struct s_flatfield
{
void (*func) (const double lambda, const int x, const int y,
PIXEL_T * const val, PIXEL_T * const err,
const struct s_flatfield * const self);
int ll_x, ll_y, w, h; /* bounding box we handle */
union
{
polynom_flatfield *poly;
multi_flatfield *multi;
}
data;
}
flatfield_d;
poly_cube_flatfield * load_flat_poly_cube(char *fname);
void free_flat_poly_cube(poly_cube_flatfield *poly_cube);
flatfield_d *make_poly_flatfield (const beam * const curbeam,
const char *const flat_name,
const int order,
const double *const coeffs);
void free_poly_flatfield (flatfield_d * const flat);
flatfield_d *make_multi_flatfield (const beam * const curbeam,
const int num_flats, const double lambda,
const char *const flat_name, ...);
void free_multi_flatfield (flatfield_d * const flat);
void apply_flatfield (ap_pixel * const ap_p, const flatfield_d * const flat);
double poly_cube_flatfield_lambda (const double lambda, const int x, const int y,
poly_cube_flatfield *poly_cube);
#endif
| {
"alphanum_fraction": 0.7042204395,
"avg_line_length": 28.3861386139,
"ext": "h",
"hexsha": "93dea00d890ea96d85f757be1b7d2fd569db223a",
"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_flatfield.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_flatfield.h",
"max_line_length": 82,
"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_flatfield.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 691,
"size": 2867
} |
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <gsl/gsl_sf.h>
#define HBARC 197.3269804 // MeV•fm
#define MASS_TRITON 2808.92113298 // MeV
#define MASS_DEUTERON 1875.61294257 // MeV
#define MASS_NEUTRON 939.565420 // MeV
#define MASS_ALPHA 3727.37940 // MeV
const double MU_D = MASS_TRITON*MASS_DEUTERON/(MASS_TRITON + MASS_DEUTERON);
const double MU_N = MASS_ALPHA*MASS_NEUTRON/(MASS_ALPHA + MASS_NEUTRON);
const double ALPHA = 1.0/137.035999084;
const double Q = 17.6;
const double J = 1.5;
const double J1 = 0.5;
const double J2 = 1.0;
double relative_momentum(double e, double mu)
{
return sqrt(2*mu*e)/HBARC;
}
double sommerfeld(double e, double mu)
{
return ALPHA * sqrt(mu/(2*e));
}
void coulomb_functions(double* F, double* Fp, double* G, double* Gp, int l, double eta,
double x)
{
int info;
double exp_f, exp_g;
gsl_sf_result f, fp, g, gp;
info = gsl_sf_coulomb_wave_FG_e(eta, x, l, 0, &f, &fp, &g, &gp, &exp_f, &exp_g);
// printf("%.4f %.4f\n", exp_f, exp_g);
if (info == GSL_EOVRFLW) printf("overflow or underflow encountered\n");
*F = f.val*exp(exp_f);
*Fp = fp.val*exp(exp_f);
*G = g.val*exp(exp_g);
*Gp = gp.val*exp(exp_g);
}
double penetration_factor(int l, double eta, double x)
{
double F, Fp, G, Gp;
coulomb_functions(&F, &Fp, &G, &Gp, l, eta, x);
return x / (F*F + G*G);
}
double shift_factor(int l, double eta, double x)
{
double F, Fp, G, Gp;
coulomb_functions(&F, &Fp, &G, &Gp, l, eta, x);
return x * (F*Fp + G*Gp) / (F*F + G*G);
}
double Gamma_c(double gamma_c_sq, int l, double eta, double x)
{
return 2 * gamma_c_sq * penetration_factor(l, eta, x);
}
double Delta_c(double gamma_c_2, double k, double r, double Bc, int l, double eta)
{
return -gamma_c_2 * (shift_factor(l, eta, k*r)-Bc);
}
double Sdn2(double energy, double e0, double Bd, double Bn, double gamma_d_2,
double gamma_n_2, double kd, double ad, double kn, double an, double eta,
double A)
{
double Gamma_d = Gamma_c(gamma_d_2, 0, eta, kd*ad);
double Gamma_n = Gamma_c(gamma_n_2, 2, 0, kn*an);
double Gamma = Gamma_d + Gamma_n;
double Delta_d = Delta_c(gamma_d_2, kd, ad, Bd, 0, eta);
double Delta_n = Delta_c(gamma_n_2, kn, an, Bn, 2, 0);
double Delta = Delta_d + Delta_n;
// printf("Sdn2: %.2e %.2e %.2e\n", Gamma_d, Gamma_n, Delta);
return Gamma_d*Gamma_n / ((e0+Delta-energy)*(e0+Delta-energy) + Gamma*Gamma/4) +
2.0/M_PI*A * penetration_factor(0, eta, kd*ad) * penetration_factor(0, 0.0, kn*an);
}
/*
Evaluates the cross section (barn = 100fm^2) at energy en (MeV) with R-matrix parameters:
eB (MeV) where Bc = shift_factor(eB),
gamma_d_2 (MeV) is the reduced deuteron width,
gamma_n_2 (MeV) is the reduced neutron width,
ad (fm) is the deuteron channel radius,
an (fm) is the neutron channel radius,
and ue (MeV) is the electron screening potential.
*/
double cross_section(double en, double e0, double eB, double gamma_d_2,
double gamma_n_2, double ad, double an, double ue, double A)
{
if (en < 0.0 || e0 < 0.0 || eB < 0.0 || gamma_d_2 < 0.0 ||
gamma_n_2 < 0.0 || ad < 0.0 || an < 0.0 || ue < 0.0) {
return INFINITY;
}
double kd = relative_momentum(en, MU_D); // 1/fm
double kn = relative_momentum(en+Q, MU_N); // 1/fm
double kdB = relative_momentum(eB, MU_D); // 1/fm
double knB = relative_momentum(eB+Q, MU_N); // 1/fm
double eta = sommerfeld(en, MU_D); // dimensionless
double etaB = sommerfeld(eB, MU_D); // dimensionless
// printf("kdB = %.2e\n", kdB);
double Bd = shift_factor(0, etaB, kdB*ad); // dimensionless
double Bn = shift_factor(2, 0, knB*an); // dimensionless
// printf("Bd = %.2e kdB = %.2e ad = %.2e\n", Bd, kdB, ad);
return exp(M_PI*eta*ue/en) *
M_PI/(kd*kd) * (2.0*J+1.0)/((2.0*J1+1.0)*(2.0*J2+1.0)) *
Sdn2(en, e0, Bd, Bn, gamma_d_2, gamma_n_2, kd, ad, kn, an, eta, A) / 100;
}
/*
Evaluates the S-factor (MeV•barn = MeV•100fm^2) at energy en (MeV) with R-matrix parameters:
eB (MeV) where Bc = shift_factor(eB),
gamma_d_2 (MeV) is the reduced deuteron width,
gamma_n_2 (MeV) is the reduced neutron width,
ad (fm) is the deuteron channel radius,
an (fm) is the neutron channel radius,
and ue (MeV) is the electron screening potential.
*/
double S_factor(double en, double e0, double eB, double gamma_d_2,
double gamma_n_2, double ad, double an, double ue, double A)
{
if (en < 0.0 || e0 < 0.0 || eB < 0.0 || gamma_d_2 < 0.0 ||
gamma_n_2 < 0.0 || ad < 0.0 || an < 0.0 || ue < 0.0) {
return INFINITY;
}
double kd = relative_momentum(en, MU_D); // 1/fm
double kn = relative_momentum(en+Q, MU_N); // 1/fm
double kdB = relative_momentum(eB, MU_D); // 1/fm
double knB = relative_momentum(eB+Q, MU_N); // 1/fm
double eta = sommerfeld(en, MU_D); // dimensionless
double etaB = sommerfeld(eB, MU_D); // dimensionless
// printf("kdB = %.2e\n", kdB);
double Bd = shift_factor(0, etaB, kdB*ad); // dimensionless
double Bn = shift_factor(2, 0, knB*an); // dimensionless
// printf("Bd = %.2e kdB = %.2e ad = %.2e\n", Bd, kdB, ad);
return exp(M_PI*eta*ue/en) * en * exp(2*M_PI*eta) *\
M_PI/(kd*kd) * (2.0*J+1.0)/((2.0*J1+1.0)*(2.0*J2+1.0)) *\
Sdn2(en, e0, Bd, Bn, gamma_d_2, gamma_n_2, kd, ad, kn, an, eta, A) / 100;
}
double S_factor_unitary_limit(double en, double ue)
{
if (en < 0.0 || ue < 0.0) {
return INFINITY;
}
double kd = relative_momentum(en, MU_D); // 1/fm
double eta = sommerfeld(en, MU_D); // dimensionless
return exp(M_PI*eta*ue/en) * en * exp(2*M_PI*eta) *\
M_PI/(kd*kd) * (2.0*J+1.0)/((2.0*J1+1.0)*(2.0*J2+1.0)) * 1.0 / 100;
}
| {
"alphanum_fraction": 0.652173913,
"avg_line_length": 35.5320512821,
"ext": "c",
"hexsha": "c0bde800afc1ca1942108e0e50ab0d445a87ad85",
"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": "fa02a3631d8798d7f85b68064ae98ab2e1ede88d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "odell/r-matrix-emulation",
"max_forks_repo_path": "r-matrix-simple.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fa02a3631d8798d7f85b68064ae98ab2e1ede88d",
"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": "odell/r-matrix-emulation",
"max_issues_repo_path": "r-matrix-simple.c",
"max_line_length": 92,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fa02a3631d8798d7f85b68064ae98ab2e1ede88d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "odell/r-matrix-emulation",
"max_stars_repo_path": "r-matrix-simple.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-25T19:25:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-02-25T19:25:06.000Z",
"num_tokens": 2126,
"size": 5543
} |
/* integration/cquad.c
*
* Copyright (C) 2010 Pedro Gonnet
*
* 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_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include "cquad_const.c"
/* Allocates a workspace for the given maximum number of intervals.
Note that if the workspace gets filled, the intervals with the
lowest error estimates are dropped. The maximum number of
intervals is therefore not the maximum number of intervals
that will be computed, but merely the size of the buffer.
*/
gsl_integration_cquad_workspace *
gsl_integration_cquad_workspace_alloc (const size_t n)
{
gsl_integration_cquad_workspace *w;
/* Check inputs */
if (n < 3)
GSL_ERROR_VAL ("workspace size n must be at least 3", GSL_EDOM, 0);
/* Allocate first the workspace struct */
if ((w =
(gsl_integration_cquad_workspace *)
malloc (sizeof (gsl_integration_cquad_workspace))) == NULL)
GSL_ERROR_VAL ("failed to allocate space for workspace struct",
GSL_ENOMEM, 0);
/* Allocate the intervals */
if ((w->ivals =
(gsl_integration_cquad_ival *)
malloc (sizeof (gsl_integration_cquad_ival) * n)) == NULL)
{
free (w);
GSL_ERROR_VAL ("failed to allocate space for the intervals", GSL_ENOMEM,
0);
}
/* Allocate the max-heap indices */
if ((w->heap = (size_t *) malloc (sizeof (size_t) * n)) == NULL)
{
free (w->ivals);
free (w);
GSL_ERROR_VAL ("failed to allocate space for the heap", GSL_ENOMEM, 0);
}
/* Remember the size of the workspace */
w->size = n;
/* Return the result */
return w;
}
/* Liberates the workspace memory.
*/
void
gsl_integration_cquad_workspace_free (gsl_integration_cquad_workspace * w)
{
/* Nothing to be done? */
if (w == NULL)
return;
/* Free the intervals first */
if (w->ivals != NULL)
free (w->ivals);
/* Free the heap */
if (w->heap != NULL)
free (w->heap);
/* Free the structure */
free (w);
}
/* Compute the product of the fx with one of the inverse
Vandermonde-like matrices. */
static void
Vinvfx (const double *fx, double *c, const int d)
{
int i, j;
switch (d)
{
case 0:
for (i = 0; i <= 4; i++)
{
c[i] = 0.0;
for (j = 0; j <= 4; j++)
c[i] += V1inv[i * 5 + j] * fx[j * 8];
}
break;
case 1:
for (i = 0; i <= 8; i++)
{
c[i] = 0.0;
for (j = 0; j <= 8; j++)
c[i] += V2inv[i * 9 + j] * fx[j * 4];
}
break;
case 2:
for (i = 0; i <= 16; i++)
{
c[i] = 0.0;
for (j = 0; j <= 16; j++)
c[i] += V3inv[i * 17 + j] * fx[j * 2];
}
break;
case 3:
for (i = 0; i <= 32; i++)
{
c[i] = 0.0;
for (j = 0; j <= 32; j++)
c[i] += V4inv[i * 33 + j] * fx[j];
}
break;
}
}
/* Downdate the interpolation given by the n coefficients c
by removing the nodes with indices in nans. */
static void
downdate (double *c, int n, int d, int *nans, int nnans)
{
static const int bidx[4] = { 0, 6, 16, 34 };
double b_new[34], alpha;
int i, j;
for (i = 0; i <= n + 1; i++)
b_new[i] = bee[bidx[d] + i];
for (i = 0; i < nnans; i++)
{
b_new[n + 1] = b_new[n + 1] / Lalpha[n];
b_new[n] = (b_new[n] + xi[nans[i]] * b_new[n + 1]) / Lalpha[n - 1];
for (j = n - 1; j > 0; j--)
b_new[j] =
(b_new[j] + xi[nans[i]] * b_new[j + 1] -
Lgamma[j + 1] * b_new[j + 2]) / Lalpha[j - 1];
for (j = 0; j <= n; j++)
b_new[j] = b_new[j + 1];
alpha = c[n] / b_new[n];
for (j = 0; j < n; j++)
c[j] -= alpha * b_new[j];
c[n] = 0;
n--;
}
}
/* The actual integration routine.
*/
int
gsl_integration_cquad (const gsl_function * f, double a, double b,
double epsabs, double epsrel,
gsl_integration_cquad_workspace * ws,
double *result, double *abserr, size_t * nevals)
{
/* Some constants that we will need. */
static const int n[4] = { 4, 8, 16, 32 };
static const int skip[4] = { 8, 4, 2, 1 };
static const int idx[4] = { 0, 5, 14, 31 };
static const double w = M_SQRT2 / 2;
static const int ndiv_max = 20;
/* Actual variables (as opposed to constants above). */
double m, h, temp;
double igral, err, igral_final, err_final, err_excess;
int nivals, neval = 0;
int i, j, d, split, t;
int nnans, nans[32];
gsl_integration_cquad_ival *iv, *ivl, *ivr;
double nc, ncdiff;
/* Check the input arguments. */
if (f == NULL)
GSL_ERROR ("function pointer shouldn't be NULL", GSL_EINVAL);
if (result == NULL)
GSL_ERROR ("result pointer shouldn't be NULL", GSL_EINVAL);
if (ws == NULL)
GSL_ERROR ("workspace pointer shouldn't be NULL", GSL_EINVAL);
/* Check for unreasonable accuracy demands */
if (epsabs < 0.0 || epsrel < 0.0)
GSL_ERROR ("tolerances may not be negative", GSL_EBADTOL);
if (epsabs <= 0 && epsrel < GSL_DBL_EPSILON)
GSL_ERROR ("unreasonable accuracy requirement", GSL_EBADTOL);
/* Create the first interval. */
iv = &(ws->ivals[0]);
m = (a + b) / 2;
h = (b - a) / 2;
nnans = 0;
for (i = 0; i <= n[3]; i++)
{
iv->fx[i] = GSL_FN_EVAL (f, m + xi[i] * h);
neval++;
if (!finite (iv->fx[i]))
{
nans[nnans++] = i;
iv->fx[i] = 0.0;
}
}
Vinvfx (iv->fx, &(iv->c[idx[0]]), 0);
Vinvfx (iv->fx, &(iv->c[idx[3]]), 3);
Vinvfx (iv->fx, &(iv->c[idx[2]]), 2);
for (i = 0; i < nnans; i++)
iv->fx[nans[i]] = GSL_NAN;
iv->a = a;
iv->b = b;
iv->depth = 3;
iv->rdepth = 1;
iv->ndiv = 0;
iv->igral = 2 * h * iv->c[idx[3]] * w;
nc = 0.0;
for (i = n[2] + 1; i <= n[3]; i++)
{
temp = iv->c[idx[3] + i];
nc += temp * temp;
}
ncdiff = nc;
for (i = 0; i <= n[2]; i++)
{
temp = iv->c[idx[2] + i] - iv->c[idx[3] + i];
ncdiff += temp * temp;
nc += iv->c[idx[3] + i] * iv->c[idx[3] + i];
}
ncdiff = sqrt (ncdiff);
nc = sqrt (nc);
iv->err = ncdiff * 2 * h;
if (ncdiff / nc > 0.1 && iv->err < 2 * h * nc)
iv->err = 2 * h * nc;
/* Initialize the heaps. */
for (i = 0; i < ws->size; i++)
ws->heap[i] = i;
/* Initialize some global values. */
igral = iv->igral;
err = iv->err;
nivals = 1;
igral_final = 0.0;
err_final = 0.0;
err_excess = 0.0;
/* Main loop. */
while (nivals > 0 && err > 0.0 &&
!(err <= fabs (igral) * epsrel || err <= epsabs)
&& !(err_final > fabs (igral) * epsrel
&& err - err_final < fabs (igral) * epsrel)
&& !(err_final > epsabs && err - err_final < epsabs))
{
/* Put our finger on the interval with the largest error. */
iv = &(ws->ivals[ws->heap[0]]);
m = (iv->a + iv->b) / 2;
h = (iv->b - iv->a) / 2;
/* printf
("cquad: processing ival %i (of %i) with [%e,%e] int=%e, err=%e, depth=%i\n",
ws->heap[0], nivals, iv->a, iv->b, iv->igral, iv->err, iv->depth);
*/
/* Should we try to increase the degree? */
if (iv->depth < 3)
{
/* Keep tabs on some variables. */
d = ++iv->depth;
/* Get the new (missing) function values */
for (i = skip[d]; i <= 32; i += 2 * skip[d])
{
iv->fx[i] = GSL_FN_EVAL (f, m + xi[i] * h);
neval++;
}
nnans = 0;
for (i = 0; i <= 32; i += skip[d])
{
if (!finite (iv->fx[i]))
{
nans[nnans++] = i;
iv->fx[i] = 0.0;
}
}
/* Compute the new coefficients. */
Vinvfx (iv->fx, &(iv->c[idx[d]]), d);
/* Downdate any NaNs. */
if (nnans > 0)
{
downdate (&(iv->c[idx[d]]), n[d], d, nans, nnans);
for (i = 0; i < nnans; i++)
iv->fx[nans[i]] = GSL_NAN;
}
/* Compute the error estimate. */
nc = 0.0;
for (i = n[d - 1] + 1; i <= n[d]; i++)
{
temp = iv->c[idx[d] + i];
nc += temp * temp;
}
ncdiff = nc;
for (i = 0; i <= n[d - 1]; i++)
{
temp = iv->c[idx[d - 1] + i] - iv->c[idx[d] + i];
ncdiff += temp * temp;
nc += iv->c[idx[d] + i] * iv->c[idx[d] + i];
}
ncdiff = sqrt (ncdiff);
nc = sqrt (nc);
iv->err = ncdiff * 2 * h;
/* Compute the local integral. */
iv->igral = 2 * h * w * iv->c[idx[d]];
/* Split the interval prematurely? */
split = (nc > 0 && ncdiff / nc > 0.1);
}
/* Maximum degree reached, just split. */
else
{
split = 1;
}
/* Should we drop this interval? */
if ((m + h * xi[0]) >= (m + h * xi[1])
|| (m + h * xi[31]) >= (m + h * xi[32])
|| iv->err < fabs (iv->igral) * GSL_DBL_EPSILON * 10)
{
/* printf
("cquad: dumping ival %i (of %i) with [%e,%e] int=%e, err=%e, depth=%i\n",
ws->heap[0], nivals, iv->a, iv->b, iv->igral, iv->err,
iv->depth);
*/
/* Keep this interval's contribution */
err_final += iv->err;
igral_final += iv->igral;
/* Swap with the last element on the heap */
t = ws->heap[nivals - 1];
ws->heap[nivals - 1] = ws->heap[0];
ws->heap[0] = t;
nivals--;
/* Fix up the heap */
i = 0;
while (2 * i + 1 < nivals)
{
/* Get the kids */
j = 2 * i + 1;
/* If the j+1st entry exists and is larger than the jth,
use it instead. */
if (j + 1 < nivals
&& ws->ivals[ws->heap[j + 1]].err >=
ws->ivals[ws->heap[j]].err)
j++;
/* Do we need to move the ith entry up? */
if (ws->ivals[ws->heap[j]].err <= ws->ivals[ws->heap[i]].err)
break;
else
{
t = ws->heap[j];
ws->heap[j] = ws->heap[i];
ws->heap[i] = t;
i = j;
}
}
}
/* Do we need to split this interval? */
else if (split)
{
/* Some values we will need often... */
d = iv->depth;
/* Generate the interval on the left */
ivl = &(ws->ivals[ws->heap[nivals++]]);
ivl->a = iv->a;
ivl->b = m;
ivl->depth = 0;
ivl->rdepth = iv->rdepth + 1;
ivl->fx[0] = iv->fx[0];
ivl->fx[32] = iv->fx[16];
for (i = skip[0]; i < 32; i += skip[0])
{
ivl->fx[i] =
GSL_FN_EVAL (f, (ivl->a + ivl->b) / 2 + xi[i] * h / 2);
neval++;
}
nnans = 0;
for (i = 0; i <= 32; i += skip[0])
{
if (!finite (ivl->fx[i]))
{
nans[nnans++] = i;
ivl->fx[i] = 0.0;
}
}
Vinvfx (ivl->fx, ivl->c, 0);
if (nnans > 0)
{
downdate (ivl->c, n[0], 0, nans, nnans);
for (i = 0; i < nnans; i++)
ivl->fx[nans[i]] = GSL_NAN;
}
for (i = 0; i <= n[d]; i++)
{
ivl->c[idx[d] + i] = 0.0;
for (j = i; j <= n[d]; j++)
ivl->c[idx[d] + i] += Tleft[i * 33 + j] * iv->c[idx[d] + j];
}
ncdiff = 0.0;
for (i = 0; i <= n[0]; i++)
{
temp = ivl->c[i] - ivl->c[idx[d] + i];
ncdiff += temp * temp;
}
for (i = n[0] + 1; i <= n[d]; i++)
{
temp = ivl->c[idx[d] + i];
ncdiff += temp * temp;
}
ncdiff = sqrt (ncdiff);
ivl->err = ncdiff * h;
/* Check for divergence. */
ivl->ndiv = iv->ndiv + (fabs (iv->c[0]) > 0
&& ivl->c[0] / iv->c[0] > 2);
if (ivl->ndiv > ndiv_max && 2 * ivl->ndiv > ivl->rdepth)
{
/* need copysign(INFINITY, igral) */
*result = (igral >= 0) ? GSL_POSINF : GSL_NEGINF;
if (nevals != NULL)
*nevals = neval;
return GSL_EDIVERGE;
}
/* Compute the local integral. */
ivl->igral = h * w * ivl->c[0];
/* Generate the interval on the right */
ivr = &(ws->ivals[ws->heap[nivals++]]);
ivr->a = m;
ivr->b = iv->b;
ivr->depth = 0;
ivr->rdepth = iv->rdepth + 1;
ivr->fx[0] = iv->fx[16];
ivr->fx[32] = iv->fx[32];
for (i = skip[0]; i < 32; i += skip[0])
{
ivr->fx[i] =
GSL_FN_EVAL (f, (ivr->a + ivr->b) / 2 + xi[i] * h / 2);
neval++;
}
nnans = 0;
for (i = 0; i <= 32; i += skip[0])
{
if (!finite (ivr->fx[i]))
{
nans[nnans++] = i;
ivr->fx[i] = 0.0;
}
}
Vinvfx (ivr->fx, ivr->c, 0);
if (nnans > 0)
{
downdate (ivr->c, n[0], 0, nans, nnans);
for (i = 0; i < nnans; i++)
ivr->fx[nans[i]] = GSL_NAN;
}
for (i = 0; i <= n[d]; i++)
{
ivr->c[idx[d] + i] = 0.0;
for (j = i; j <= n[d]; j++)
ivr->c[idx[d] + i] += Tright[i * 33 + j] * iv->c[idx[d] + j];
}
ncdiff = 0.0;
for (i = 0; i <= n[0]; i++)
{
temp = ivr->c[i] - ivr->c[idx[d] + i];
ncdiff += temp * temp;
}
for (i = n[0] + 1; i <= n[d]; i++)
{
temp = ivr->c[idx[d] + i];
ncdiff += temp * temp;
}
ncdiff = sqrt (ncdiff);
ivr->err = ncdiff * h;
/* Check for divergence. */
ivr->ndiv = iv->ndiv + (fabs (iv->c[0]) > 0
&& ivr->c[0] / iv->c[0] > 2);
if (ivr->ndiv > ndiv_max && 2 * ivr->ndiv > ivr->rdepth)
{
/* need copysign(INFINITY, igral) */
*result = (igral >= 0) ? GSL_POSINF : GSL_NEGINF;
if (nevals != NULL)
*nevals = neval;
return GSL_EDIVERGE;
}
/* Compute the local integral. */
ivr->igral = h * w * ivr->c[0];
/* Fix-up the heap: we now have one interval on top
that we don't need any more and two new, unsorted
ones at the bottom. */
/* Flip the last interval to the top of the heap and
sift down. */
t = ws->heap[nivals - 1];
ws->heap[nivals - 1] = ws->heap[0];
ws->heap[0] = t;
nivals--;
/* Sift this interval back down the heap. */
i = 0;
while (2 * i + 1 < nivals - 1)
{
j = 2 * i + 1;
if (j + 1 < nivals - 1
&& ws->ivals[ws->heap[j + 1]].err >=
ws->ivals[ws->heap[j]].err)
j++;
if (ws->ivals[ws->heap[j]].err <= ws->ivals[ws->heap[i]].err)
break;
else
{
t = ws->heap[j];
ws->heap[j] = ws->heap[i];
ws->heap[i] = t;
i = j;
}
}
/* Now grab the last interval and sift it up the heap. */
i = nivals - 1;
while (i > 0)
{
j = (i - 1) / 2;
if (ws->ivals[ws->heap[j]].err < ws->ivals[ws->heap[i]].err)
{
t = ws->heap[j];
ws->heap[j] = ws->heap[i];
ws->heap[i] = t;
i = j;
}
else
break;
}
}
/* Otherwise, just fix-up the heap. */
else
{
i = 0;
while (2 * i + 1 < nivals)
{
j = 2 * i + 1;
if (j + 1 < nivals
&& ws->ivals[ws->heap[j + 1]].err >=
ws->ivals[ws->heap[j]].err)
j++;
if (ws->ivals[ws->heap[j]].err <= ws->ivals[ws->heap[i]].err)
break;
else
{
t = ws->heap[j];
ws->heap[j] = ws->heap[i];
ws->heap[i] = t;
i = j;
}
}
}
/* If the heap is about to overflow, remove the last two
intervals. */
while (nivals > ws->size - 2)
{
iv = &(ws->ivals[ws->heap[nivals - 1]]);
/* printf
("cquad: dumping ival %i (of %i) with [%e,%e] int=%e, err=%e, depth=%i\n",
ws->heap[0], nivals, iv->a, iv->b, iv->igral, iv->err,
iv->depth);
*/
err_final += iv->err;
igral_final += iv->igral;
nivals--;
}
/* Collect the value of the integral and error. */
igral = igral_final;
err = err_final;
for (i = 0; i < nivals; i++)
{
igral += ws->ivals[ws->heap[i]].igral;
err += ws->ivals[ws->heap[i]].err;
}
}
/* Dump the contents of the heap. */
/* for (i = 0; i < nivals; i++)
{
iv = &(ws->ivals[ws->heap[i]]);
printf
("cquad: ival %i (%i) with [%e,%e], int=%e, err=%e, depth=%i, rdepth=%i\n",
i, ws->heap[i], iv->a, iv->b, iv->igral, iv->err, iv->depth,
iv->rdepth);
}
*/
/* Clean up and present the results. */
*result = igral;
if (abserr != NULL)
*abserr = err;
if (nevals != NULL)
*nevals = neval;
/* All is well that ends well. */
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.4995414246,
"avg_line_length": 23.9108187135,
"ext": "c",
"hexsha": "da96b93879b42eb655f67520d93d89e1639d0bb1",
"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": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ruslankuzmin/julia",
"max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/integration/cquad.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"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": "ruslankuzmin/julia",
"max_issues_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/integration/cquad.c",
"max_line_length": 86,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/integration/cquad.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": 5931,
"size": 16355
} |
#ifndef MATMUL_CMAT_MUL_H
#define MATMUL_CMAT_MUL_H
#include <cblas.h>
#include <pthread.h>
#include "cmatrix.h"
#define _AVX512
//#define _AVX2
//#define _NEON
#if defined(_NEON)
#include "arm_neon.h"
#elif defined(_AVX512) || defined(_AVX2)
#include <immintrin.h>
#endif
#define BLOCKSIZE 1
#define UNROLL 4
typedef enum {
Naive,
Blas,
Order,
Simd,
OpenCv,
Threads,
OpenMp,
Unroll,
Block,
// UnrollMp,
} kMatMulMode;
CMatrix *MatMul(ReadOnlyMat mat1, ReadOnlyMat mat2, kMatMulMode mode, int times);
CMatrix *MatMulO3(ReadOnlyMat mat1, ReadOnlyMat mat2);
void MatMulChangeOrd(ReadOnlyMat mat1, ReadOnlyMat mat2, int times);
CMatrix *MatMulBlas(ReadOnlyMat mat1, ReadOnlyMat mat2);
//CMatrix *MatMulStrassen(ReadOnlyMat mat1, ReadOnlyMat mat2, int edge);
CMatrix *MatMulCV(ReadOnlyMat mat1, ReadOnlyMat mat2);
CMatrix *MatMulMP(ReadOnlyMat mat1, ReadOnlyMat mat2);
CMatrix *MatMulSimd(ReadOnlyMat mat1, ReadOnlyMat mat2);
CMatrix *MatMulUnroll(ReadOnlyMat mat1, ReadOnlyMat mat2);
CMatrix *MatMulBlock(ReadOnlyMat mat1, ReadOnlyMat mat2);
CMatrix *MatMulThreads(ReadOnlyMat mat1, ReadOnlyMat mat2);
//CMatrix *MatMulUnrollMp(ReadOnlyMat mat1, ReadOnlyMat mat2);
#endif //MATMUL_CMAT_MUL_H
| {
"alphanum_fraction": 0.7550040032,
"avg_line_length": 20.1451612903,
"ext": "h",
"hexsha": "006dc452a0544b7ee078fab0c52839886ffc0ea3",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-01-03T07:49:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-01-03T07:49:07.000Z",
"max_forks_repo_head_hexsha": "c15e4055b3e260e84e94c8db46b4180448c3619f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "YZL24/SUSTech-CS205",
"max_forks_repo_path": "Project 3/src/cmat_mul.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c15e4055b3e260e84e94c8db46b4180448c3619f",
"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": "YZL24/SUSTech-CS205",
"max_issues_repo_path": "Project 3/src/cmat_mul.h",
"max_line_length": 81,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "c15e4055b3e260e84e94c8db46b4180448c3619f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "YZL24/SUSTech-CS205",
"max_stars_repo_path": "Project 3/src/cmat_mul.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-23T14:18:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-29T06:13:08.000Z",
"num_tokens": 388,
"size": 1249
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <getopt.h>
#include <iniparser.h>
#include "parmt_utils.h"
#include "iscl/array/array.h"
#include "iscl/memory/memory.h"
#include "iscl/os/os.h"
#ifdef PARMT_USE_INTEL
#include <mkl_cblas.h>
#else
#include <cblas.h>
#endif
#define PROGRAM_NAME "mergemt"
static void printUsage(void);
static int parseArguments(int argc, char *argv[],
char iniFile[PATH_MAX]);
struct mergemtParms_struct
{
char **files;
double *wts;
char archiveFile[PATH_MAX];
int nfiles;
};
int mergemt_readIni(const char *iniFile, struct mergemtParms_struct *parms);
int main(int argc, char *argv[])
{
struct mergemtParms_struct parms;
char iniFile[PATH_MAX], programNameIn[256];
double *beta0, *beta1, *betaLoc, *dep0, *dep1, *depLoc,
*gamma0, *gamma1, *gammaLoc, *kappa0, *kappa1, *kappaLoc,
*M0, *M1, *M0loc, *phi0, *phi1,
*phiLoc, *sigma0, *sigma1, *sigmaLoc, *theta0, *theta1,
*thetaLoc, xsum;
int i, ierr, il, im, indx, jndx, nb, nb0, nb1, ncopy, ng, ng0, ng1,
nk, nk0, nk1, nlocs, nlocs0, nlocs1, nm, nm0, nm1, nmt, nmt0, nmt1,
ns, ns0, ns1, nt, nt0, nt1;
const int jm = 0;
ierr = parseArguments(argc, argv, iniFile);
if (ierr != 0)
{
if (ierr ==-2){return EXIT_SUCCESS;}
printf("%s: Error parsing arguments\n", PROGRAM_NAME);
return EXIT_FAILURE;
}
if (!os_path_isfile(iniFile))
{
printf("%s: Error ini file doesn't exist\n", PROGRAM_NAME);
return EXIT_FAILURE;
}
ierr = mergemt_readIni(iniFile, &parms);
if (ierr != 0)
{
printf("%s: Error reading ini file\n", PROGRAM_NAME);
return EXIT_FAILURE;
}
xsum = array_sum64f(parms.nfiles, parms.wts, &ierr);
if (fabs(xsum) < 1.e-14)
{
printf("%s: Division by zero - setting to 1\n", PROGRAM_NAME);
xsum = 1.0;
}
cblas_dscal(parms.nfiles, 1.0/xsum, parms.wts, 1);
// Load the files
nlocs0 =-1;
nlocs1 =-1;
nm0 =-1;
nm1 =-1;
nb0 =-1;
nb1 =-1;
ng0 =-1;
ng1 =-1;
nk0 =-1;
nk1 =-1;
ns0 =-1;
ns1 =-1;
nt0 =-1;
nt1 =-1;
nmt0 =-1;
nmt1 =-1;
dep0 = NULL;
dep1 = NULL;
M0 = NULL;
M1 = NULL;
beta0 = NULL;
beta1 = NULL;
gamma0 = NULL;
gamma1 = NULL;
kappa0 = NULL;
kappa1 = NULL;
sigma0 = NULL;
sigma1 = NULL;
theta0 = NULL;
theta1 = NULL;
phi0 = NULL;
phi1 = NULL;
for (i=0; i<parms.nfiles; i++)
{
if (!os_path_isfile(parms.files[i])){continue;}
printf("%s: Loading archive: %s\n", PROGRAM_NAME, parms.files[i]);
ierr = parmt_io_readObjfnArchive64f(parms.files[i],
programNameIn,
&nlocs, &depLoc,
&nm, &M0loc,
&nb, &betaLoc,
&ng, &gammaLoc,
&nk, &kappaLoc,
&ns, &sigmaLoc,
&nt, &thetaLoc,
&nmt, &phiLoc);
if (ierr != 0)
{
printf("%s: Error loading %s; skipping...\n",
PROGRAM_NAME, parms.files[i]);
continue;
}
if (strcasecmp("parmt", programNameIn) == 0)
{
if (nm0 ==-1)
{
nlocs0 = nlocs;
nm0 = nm;
nb0 = nb;
ng0 = ng;
nk0 = nk;
ns0 = ns;
nt0 = nt;
nmt0 = nmt;
phi0 = array_zeros64f(nmt, &ierr);
dep0 = array_copy64f(nlocs, depLoc, &ierr);
M0 = array_copy64f(nm, M0loc, &ierr);
beta0 = array_copy64f(nb, betaLoc, &ierr);
gamma0 = array_copy64f(ng, gammaLoc, &ierr);
kappa0 = array_copy64f(nk, kappaLoc, &ierr);
sigma0 = array_copy64f(ns, sigmaLoc, &ierr);
theta0 = array_copy64f(nt, thetaLoc, &ierr);
}
if (nm0 != nm || nb0 != nb || ng0 != ng || nk0 != nk ||
ns0 != ns || nt0 != nt || nmt0 != nmt || nlocs0 != nlocs)
{
printf("%s: Size mismatch in parmt\n", PROGRAM_NAME);
continue;
}
cblas_daxpy(nmt, parms.wts[i], phiLoc, 1, phi0, 1);
}
else if (strcasecmp("polarmt", programNameIn) == 0)
{
if (nm1 ==-1)
{
nlocs1 = nlocs;
nm1 = nm;
nb1 = nb;
ng1 = ng;
nk1 = nk;
ns1 = ns;
nt1 = nt;
nmt1 = nmt;
phi1 = array_zeros64f(nmt, &ierr);
dep1 = array_copy64f(nlocs, depLoc, &ierr);
M1 = array_copy64f(nm, M0loc, &ierr);
beta1 = array_copy64f(nb, betaLoc, &ierr);
gamma1 = array_copy64f(ng, gammaLoc, &ierr);
kappa1 = array_copy64f(nk, kappaLoc, &ierr);
sigma1 = array_copy64f(ns, sigmaLoc, &ierr);
theta1 = array_copy64f(nt, thetaLoc, &ierr);
}
printf("%f\n",parms.wts[i]);
cblas_daxpy(nmt, parms.wts[i], phiLoc, 1, phi1, 1);
}
else
{
printf("%s: Unkown origin: %s\n", PROGRAM_NAME, programNameIn);
goto NEXT;
}
NEXT:;
memory_free64f(&M0loc);
memory_free64f(&betaLoc);
memory_free64f(&gammaLoc);
memory_free64f(&kappaLoc);
memory_free64f(&sigmaLoc);
memory_free64f(&thetaLoc);
memory_free64f(&phiLoc);
}
if (phi0 != NULL && phi1 != NULL)
{
if (nb0 != nb1 || ng0 != ng1 || nk0 != nk1 ||
ns0 != ns1 || nt0 != nt1 || nlocs0 != nlocs)
{
printf("%s: Inconsistent grid search sizes\n", PROGRAM_NAME);
return -1;
}
printf("%f\n", array_max64f(nmt0, phi0, &ierr));
printf("%f\n", array_max64f(nmt1, phi1, &ierr));
printf("%s: Stacking polarities into waveforms...\n", PROGRAM_NAME);
/*
for (i=0; i<nm0; i++)
{
//printf("%d %d\n", nmt, nmt0);
cblas_daxpy(nmt1, 1.0, phi1, 1, &phi0[nmt1*i], 1);
}
*/
for (il=0; il<nlocs0; il++)
{
for (im=0; im<nm0; im++)
{
indx = il*nm0*nb0*ng0*nk0*ns0*nt0
+ im*nb0*ng0*nk0*ns0*nt0;
jndx = il*nm1*nb1*ng1*nk1*ns1*nt1
+ jm*nb1*ng1*nk1*ns1*nt1;
ncopy = nb0*ng0*nk0*ns0*nt0;
cblas_daxpy(ncopy, 1.0, &phi1[jndx], 1, &phi0[indx], 1);
}
}
printf("%f\n", array_max64f(nmt0, phi0, &ierr));
printf("%s: Writing joint archive\n", PROGRAM_NAME);
ierr = parmt_io_createObjfnArchive64f(PROGRAM_NAME, parms.archiveFile,
1, //data.nobs, TODO - read and fix
nlocs0, dep0,
nm0, M0,
nb0, beta0,
ng0, gamma0,
nk0, kappa0,
ns0, sigma0,
nt0, theta0);
ierr = parmt_io_writeObjectiveFunction64f(parms.archiveFile,
nmt0, phi0);
}
else
{
if (phi0 != NULL)
{
printf("%s: Writing joint waveform archive\n", PROGRAM_NAME);
ierr = parmt_io_createObjfnArchive64f(PROGRAM_NAME, parms.archiveFile,
1, //data.nobs, TODO - read and fix
nlocs0, dep0,
nm0, M0,
nb0, beta0,
ng0, gamma0,
nk0, kappa0,
ns0, sigma0,
nt0, theta0);
ierr = parmt_io_writeObjectiveFunction64f(parms.archiveFile,
nmt0, phi0);
}
else if (phi1 != NULL)
{
printf("%s: Writing joint waveform archive\n", PROGRAM_NAME);
ierr = parmt_io_createObjfnArchive64f(PROGRAM_NAME, parms.archiveFile,
1, //data.nobs, TODO - read and fix
nlocs1, dep1,
nm1, M1,
nb1, beta1,
ng1, gamma1,
nk1, kappa1,
ns1, sigma1,
nt1, theta1);
}
}
memory_free64f(&dep0);
memory_free64f(&dep1);
memory_free64f(&M0);
memory_free64f(&M1);
memory_free64f(&beta0);
memory_free64f(&beta1);
memory_free64f(&gamma0);
memory_free64f(&gamma1);
memory_free64f(&kappa0);
memory_free64f(&kappa1);
memory_free64f(&sigma0);
memory_free64f(&sigma1);
memory_free64f(&theta0);
memory_free64f(&theta1);
memory_free64f(&phi0);
memory_free64f(&phi1);
return EXIT_SUCCESS;
}
//============================================================================//
int mergemt_readIni(const char *iniFile,
struct mergemtParms_struct *parms)
{
const char *fcnm = "mergemt_readIni\0";
const char *s;
char vname[256];
dictionary *ini;
int i, ierr;
memset(parms, 0, sizeof(struct mergemtParms_struct));
if (!os_path_isfile(iniFile))
{
printf("%s: Error ini file doesn't exist\n", fcnm);
return -1;
}
ini = iniparser_load(iniFile);
parms->nfiles = iniparser_getint(ini, "general:nmerge\0", 0);
if (parms->nfiles < 1)
{
printf("%s: No files to merge\n", fcnm);
return -1;
}
parms->files = (char **) calloc((size_t) parms->nfiles, sizeof(char *));
parms->wts = array_set64f(parms->nfiles, 1.0, &ierr);
for (i=0; i<parms->nfiles; i++)
{
parms->files[i] = (char *) calloc(PATH_MAX, sizeof(char));
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "general:mergeFile_%d", i+1);
s = iniparser_getstring(ini, vname, NULL);
if (!os_path_isfile(s))
{
printf("%s: File %s doesn't exist\n", fcnm, s);
continue;
}
strcpy(parms->files[i], s);
memset(vname, 0, 256*sizeof(char));
sprintf(vname, "general:wtFile_%d", i+1);
parms->wts[i] = iniparser_getdouble(ini, vname, 1.0);
if (parms->wts[i] < 0.0)
{
printf("%s: Weight can't be negative: %f\n", fcnm, parms->wts[i]);
return -1;
}
}
memset(vname, 0, 256*sizeof(char));
strcpy(vname, "general:mergeArchive");
s = iniparser_getstring(ini, vname, "mergemt.h5");
strcpy(parms->archiveFile, s);
iniparser_freedict(ini);
return 0;
}
//============================================================================//
static int parseArguments(int argc, char *argv[],
char iniFile[PATH_MAX])
{
bool linFile;
int prod;
linFile = false;
memset(iniFile, 0, PATH_MAX*sizeof(char));
while (true)
{
static struct option longOptions[] =
{
{"help", no_argument, 0, '?'},
{"help", no_argument, 0, 'h'},
{"ini_file", required_argument, 0, 'i'},
{0, 0, 0, 0}
};
int c, optionIndex;
c = getopt_long(argc, argv, "?hi:m:l:",
longOptions, &optionIndex);
if (c ==-1){break;}
if (c == 'i')
{
strcpy(iniFile, (const char *) optarg);
linFile = true;
}
else if (c == 'h' || c == '?')
{
printUsage();
return -2;
}
else
{
printf("%s: Unknown options: %s\n",
PROGRAM_NAME, argv[optionIndex]);
}
}
if (!linFile)
{
printf("%s: Error must specify ini file\n\n", PROGRAM_NAME);
printUsage();
return -1;
}
return 0;
}
//============================================================================//
static void printUsage(void)
{
printf("Usage:\n mergemt -i input_file\n\n");
printf("Required arguments:\n");
printf(" -i input_file specifies the initialization file\n");
printf("\n");
printf("Optional arguments:\n");
printf(" -h displays this message\n");
return;
}
| {
"alphanum_fraction": 0.4529624604,
"avg_line_length": 33.2481203008,
"ext": "c",
"hexsha": "dcd0433e3bf00446afd55ae7c832020a648f8d52",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_forks_repo_licenses": [
"Intel"
],
"max_forks_repo_name": "bakerb845/parmt",
"max_forks_repo_path": "src/mergemt.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Intel"
],
"max_issues_repo_name": "bakerb845/parmt",
"max_issues_repo_path": "src/mergemt.c",
"max_line_length": 82,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_stars_repo_licenses": [
"Intel"
],
"max_stars_repo_name": "bakerb845/parmt",
"max_stars_repo_path": "src/mergemt.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3582,
"size": 13266
} |
#include <math.h>
#include <stdio.h>
#include <stdarg.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_statistics_double.h>
#include "../include/type.h"
#include "../include/util.h"
#include "../include/myfunc.h"
#include "../include/global.h"
#include "../include/cthreadpool.h"
extern double rho;
extern double cutoff;
extern clock_t dur;
#define ITER_CUTOFF 0.01
/**
* @brief invoke this function before return from
* MLE_marginal_iteration and MLE_marginal_iteration_constrain.
*
* @param mle
* @param sum
* @param psi1
* @param psi2
* @param beta0
* @param beta1
* @param var1
* @param var2
*/
void mle_result_set(mle_result* mle, double sum, gsl_vector* psi1, gsl_vector* psi2,
double beta0, double beta1, double var1, double var2) {
mle->sum = sum;
mle->params.psi1 = psi1;
mle->params.psi2 = psi2;
mle->params.beta0 = beta0;
mle->params.beta1 = beta1;
mle->params.var1 = var1;
mle->params.var2 = var2;
return;
}
double myfunc_multivar(const double x[], va_list argv) {
gsl_vector *psi1 = va_arg(argv, gsl_vector*);
gsl_vector *psi2 = va_arg(argv, gsl_vector*);
double var1 = va_arg(argv, double), var2 = va_arg(argv, double);
double sum1, sum2;
// TODO memcpy replaced.
sum1 = cuscumsum(psi1, sum_for_multivar, 1, x[0]);
sum2 = cuscumsum(psi2, sum_for_multivar, 1, x[1]);
sum1 = sum1/(var1*2), sum2 = sum2/(var2*2);
return sum1 + sum2 + 0.05 * pow(rho, 2) / (1 - pow(rho, 2)) * \
(pow(gsl_cdf_gaussian_Pinv(x[0], 1), 2) + pow(gsl_cdf_gaussian_Pinv(x[1], 1), 2) - \
2 * rho * gsl_cdf_gaussian_Pinv(x[0], 1) * gsl_cdf_gaussian_Pinv(x[1], 1));
}
void myfunc_multivar_der(const double x[], double res[], va_list argv) {
gsl_vector *psi1 = va_arg(argv, gsl_vector*);
gsl_vector *psi2 = va_arg(argv, gsl_vector*);
double var1 = va_arg(argv, double), var2 = va_arg(argv, double);
double sum1, sum2, tmp = pow(rho,2)/(1-pow(rho,2));
double ppfx0 = gsl_cdf_gaussian_Pinv(x[0], 1);
double ppfx1 = gsl_cdf_gaussian_Pinv(x[1], 1);
sum1 = cuscumsum(psi1, sum_for_multivar_der, 1, x[0]);
sum2 = cuscumsum(psi2, sum_for_multivar_der, 1, x[1]);
sum1 = sum1/(var1*2), sum2 = sum2/(var2*2);
// TODO are there any better way to convert cdf to pdf?
res[0] = sum1 + tmp * 0.1*(ppfx0-rho*ppfx1)/gsl_ran_gaussian_pdf(ppfx0, 1);
res[1] = sum2 + tmp * 0.1*(ppfx1-rho*ppfx0)/gsl_ran_gaussian_pdf(ppfx1, 1);
return;
}
double myfunc_1_2(const double x[], va_list argv) {
int flag = va_arg(argv, int);
gsl_vector *psi1 = va_arg(argv, gsl_vector*);
gsl_vector *psi2 = va_arg(argv, gsl_vector*);
double var1 = va_arg(argv, double), var2 = va_arg(argv, double);
double sum1, sum2;
if (flag == 1) {
sum1 = cuscumsum(psi1, sum_for_multivar, 1, x[0]+cutoff);
sum2 = cuscumsum(psi2, sum_for_multivar, 1, x[0]);
} else {
sum1 = cuscumsum(psi1, sum_for_multivar, 1, x[0]);
sum2 = cuscumsum(psi2, sum_for_multivar, 1, x[0]+cutoff);
}
sum1 = sum1/(var1*2), sum2 = sum2/(var2*2);
return sum1 + sum2 + 0.05 * pow(rho, 2) / (1 - pow(rho, 2)) * \
(pow(gsl_cdf_gaussian_Pinv(x[0]+cutoff, 1), 2) + pow(gsl_cdf_gaussian_Pinv(x[0], 1), 2) - \
2 * rho * gsl_cdf_gaussian_Pinv(x[0]+cutoff, 1) * gsl_cdf_gaussian_Pinv(x[0], 1));
}
void myfunc_der_1_2(const double x[], double res[], va_list argv) {
int flag = va_arg(argv, int);
gsl_vector *psi1 = va_arg(argv, gsl_vector*);
gsl_vector *psi2 = va_arg(argv, gsl_vector*);
double var1 = va_arg(argv, double), var2 = va_arg(argv, double);
double sum1, sum2, tmp = pow(rho,2)/(1-pow(rho,2));
double ppfx0 = gsl_cdf_gaussian_Pinv(x[0], 1);
double ppfxc = gsl_cdf_gaussian_Pinv(x[0]+cutoff, 1);
if (flag == 1) {
sum1 = cuscumsum(psi1, sum_for_multivar_der, 1, x[0]+cutoff);
sum2 = cuscumsum(psi2, sum_for_multivar_der, 1, x[0]);
} else {
sum1 = cuscumsum(psi1, sum_for_multivar_der, 1, x[0]);
sum2 = cuscumsum(psi2, sum_for_multivar_der, 1, x[0]+cutoff);
}
sum1 = sum1/(var1*2), sum2 = sum2/(var2*2);
// TODO are there any better way to convert cdf to pdf?
res[0] = sum1 + tmp * 0.1*(ppfxc-rho*ppfx0)/gsl_ran_gaussian_pdf(ppfxc, 1);
res[1] = sum2 + tmp * 0.1*(ppfx0-rho*ppfxc)/gsl_ran_gaussian_pdf(ppfx0, 1);
res[0] += res[1];
return;
}
double myfunc_marginal(const double x[], va_list argv) {
gsl_vector* I = va_arg(argv, gsl_vector*), *S = va_arg(argv, gsl_vector*);
gsl_vector* psi = va_arg(argv, gsl_vector*);
double var = va_arg(argv, double), sum = 0;
int inclu_len = va_arg(argv, int), skip_len = va_arg(argv, int), idx = 0;
sum = cuscumsum(psi, sum_for_marginal, 7, &idx, x[0], I, S, var, inclu_len, skip_len);
return sum;
}
void myfunc_marginal_der(const double x[], double res[], va_list argv) {
gsl_vector* I = va_arg(argv, gsl_vector*), *S = va_arg(argv, gsl_vector*);
gsl_vector* psi = va_arg(argv, gsl_vector*);
double var = va_arg(argv, double), sum;
int inclu_len = va_arg(argv, int), skip_len = va_arg(argv, int), idx = 0;
sum = cuscumsum(psi, sum_for_marginal_der, 7, &idx, x[0], I, S, var, inclu_len, skip_len);
res[0] = sum;
return;
}
double myfunc_marginal_1_2(const double x[], va_list argv) {
int flag = va_arg(argv, int);
double beta1, beta2;
if (flag == 1) {
beta1 = x[0] + cutoff, beta2 = x[0];
} else {
beta1 = x[0], beta2 = x[0] + cutoff;
}
// TODO parameter ordering
return myfunc_marginal(&beta1, argv) + myfunc_marginal(&beta2, argv);
}
void myfunc_marginal_1_2_der(const double x[], double res[], va_list argv) {
int flag = va_arg(argv, int);
double beta1, beta2;
double tmp1, tmp2;
if (flag == 1) {
beta1 = x[0] + cutoff, beta2 = x[0];
} else {
beta1 = x[0], beta2 = x[0] + cutoff;
}
// TODO parameter ordering
myfunc_marginal_der(&beta1, &tmp1, argv);
myfunc_marginal_der(&beta2, &tmp2, argv);
res[0] = tmp1 + tmp2;
return;
}
double myfunc_individual(const double x[], va_list argv) {
double I = va_arg(argv, double), S = va_arg(argv, double);
double beta = va_arg(argv, double), var = va_arg(argv, double);
int inclu_len = va_arg(argv, int), skip_len = va_arg(argv, int);
double new_psi = inclu_len * x[0]/(inclu_len * x[0] + skip_len * (1 - x[0]));
// TODO This change the result.
return pow((logit(x[0]) - logit(beta)), 2)/(2 * var) -
(I * log(new_psi) + S * log(1 - new_psi) - log(x[0]) - log(1-x[0]));
// return -(I * log(new_psi) + S * log(1 - new_psi) -
// pow((logit(x[0]) - logit(beta)), 2)/(2 * var) + log(x[0] - x[0]*x[0]));
// return -(I * log(new_psi) + S * log(1 - new_psi) -
// pow((logit(x[0]) - logit(beta)), 2)/(2 * var) + log(x[0]) + log(1-x[0]));
}
void myfunc_individual_der(const double x[], double res[], va_list argv) {
double I = va_arg(argv, double), S = va_arg(argv, double);
double beta = va_arg(argv, double), var = va_arg(argv, double);
int inclu_len = va_arg(argv, int), skip_len = va_arg(argv, int);
double new_psi = inclu_len * x[0]/(inclu_len * x[0] + skip_len * (1 - x[0]));
double new_psi_der = inclu_len * skip_len/pow(inclu_len * x[0] + skip_len * (1 - x[0]), 2);
res[0] = 1/x[0] + S/(1 - new_psi) * new_psi_der + \
(logit(x[0]) - logit(beta))/(var * x[0] * (1 - x[0])) - (1/(1-x[0]) + I/new_psi * new_psi_der);
return;
}
#define individual_for_loop() \
for (idx = 0; idx < psi1->size; ++idx) { \
x[0] = gsl_vector_get(psi1, idx); \
cur_sum += l_bfgs_b_wrapper(n, m, x, l, u, nbd, \
myfunc_individual, myfunc_individual_der, \
factr, pgtol, iprint, 15000, 15000, \
6, gsl_vector_get(i1, idx), gsl_vector_get(s1, idx), \
beta0, var1, inclu_len, skip_len); \
gsl_vector_set(psi1, idx, x[0]); \
} \
for (idx = 0; idx < psi2->size; ++idx) { \
x[0] = gsl_vector_get(psi2, idx); \
cur_sum += l_bfgs_b_wrapper(n, m, x, l, u, nbd, \
myfunc_individual, myfunc_individual_der, \
factr, pgtol, iprint, 15000, 15000, \
6, gsl_vector_get(i2, idx), gsl_vector_get(s2, idx), \
beta1, var2, inclu_len, skip_len); \
gsl_vector_set(psi2, idx, x[0]); \
} \
int MLE_marginal_iteration(gsl_vector* i1, gsl_vector* i2,
gsl_vector* s1, gsl_vector* s2,
const int inclu_len, const int skip_len,
mle_result* mle) {
gsl_vector* psi1 = gsl_vector_alloc(i1->size); // TODO deallocation.
gsl_vector* psi2 = gsl_vector_alloc(i2->size);
vec2psi(psi1, i1, s1, inclu_len, skip_len);
vec2psi(psi2, i2, s2, inclu_len, skip_len);
int iter_max = 100, count = 0, i = 0;
size_t idx = 0;
double prev_sum = 0, cur_sum = 0;
double var1 = 10 * gsl_stats_variance(psi1->data, 1, psi1->size) * (psi1->size-1)/(psi1->size);
double var2 = 10 * gsl_stats_variance(psi2->data, 1, psi2->size) * (psi2->size-1)/(psi2->size);
double beta0, beta1, iter_cutoff = 1;
integer n, m = 10, nbd[nmax];
doublereal x[nmax], l[nmax], u[nmax], factr=1.0e7, pgtol=1.0e-5, iprint=-1;
if (var1 <= 0.01 || psi1->size == 1) {
var1 = 0.01;
}
if (var2 <= 0.01 || psi2->size == 1) {
var2 = 0.01;
}
// TODO & or && ?
// According to original python code 'while((iter_cutoff>0.01)&(count<=iter_maxrun)):',
// it's a bit arithmetic '&'. However, it should be a logical 'and' in such senario.
while((iter_cutoff > ITER_CUTOFF) && (count <= iter_max)) {
++count, n = 2;
x[0] = gsl_stats_mean(psi1->data, 1, psi1->size);
x[1] = gsl_stats_mean(psi2->data, 1, psi2->size);
for (i = 0; i < n; ++i) {
nbd[i] = 2;
l[i] = 0.01;
u[i] = 0.99;
}
l_bfgs_b_wrapper(n, m, x, l, u, nbd,
myfunc_multivar, myfunc_multivar_der, factr, pgtol,
iprint, 15000, 15000, 4, psi1, psi2, var1, var2);
beta0 = x[0], beta1 = x[1];
n = 1, cur_sum = 0;
individual_for_loop();
if (count > 1) {
iter_cutoff = fabs(prev_sum - cur_sum);
}
prev_sum = cur_sum;
}
if (count > iter_max) {
mle_result_set(mle, cur_sum, psi1, psi2, 0, 0, var1, var2);
return 0;
}
iter_cutoff = 1, iter_max = 100, count = 0, prev_sum = 0;
while((iter_cutoff > ITER_CUTOFF) && (count <= iter_max)) {
++count, n = 1;
x[0] = beta0;
l_bfgs_b_wrapper(n, m, x, l, u, nbd,
myfunc_marginal, myfunc_marginal_der,
factr, pgtol, iprint, 15000, 15000,
6, i1, s1, psi1, var1, inclu_len, skip_len);
beta0 = x[0];
x[0] = beta1;
l_bfgs_b_wrapper(n, m, x, l, u, nbd,
myfunc_marginal, myfunc_marginal_der,
factr, pgtol, iprint, 15000, 15000,
6, i2, s2, psi2, var2, inclu_len, skip_len);
beta1 = x[0];
cur_sum = 0;
individual_for_loop();
if (count > 1) {
iter_cutoff = fabs(prev_sum - cur_sum);
}
prev_sum = cur_sum;
}
gsl_vector_free(psi1);
gsl_vector_free(psi2);
if (count > iter_max) {
mle_result_set(mle, cur_sum, psi1, psi2, 0, 0, var1, var2);
return 0;
}
mle_result_set(mle, cur_sum, psi1, psi2, beta0, beta1, var1, var2);
return 0;
}
int MLE_marginal_iteration_constrain(gsl_vector* i1, gsl_vector* i2,
gsl_vector* s1, gsl_vector* s2,
const int inclu_len, const int skip_len,
mle_result* mle) {
gsl_vector* psi1 = gsl_vector_alloc(i1->size); // TODO deallocation.
gsl_vector* psi2 = gsl_vector_alloc(i2->size);
vec2psi(psi1, i1, s1, inclu_len, skip_len);
vec2psi(psi2, i2, s2, inclu_len, skip_len);
int iter_max = 100, count = 0, i = 0;
size_t idx = 0;
double prev_sum = 0, cur_sum = 0, iter_cutoff = 1;
double var1 = 10 * gsl_stats_variance(psi1->data, 1, psi1->size) * (psi1->size-1)/(psi1->size);
double var2 = 10 * gsl_stats_variance(psi2->data, 1, psi2->size) * (psi2->size-1)/(psi2->size);
double beta0, beta1;
integer n = 1, m = 10, nbd[nmax];
doublereal x[nmax], l[nmax], u[nmax], factr=1.0e7, pgtol=1.0e-5, iprint=-1;
if (var1 <= 0.01 || psi1->size == 1) {
var1 = 0.01;
}
if (var2 <= 0.01 || psi2->size == 1) {
var2 = 0.01;
}
// TODO & or && ?
// According to original python code 'while((iter_cutoff>0.01)&(count<=iter_maxrun)):',
// it's a bit arithmetic '&'. However, it should be a logical 'and' in such senario.
while((iter_cutoff > ITER_CUTOFF) && (count <= iter_max)) {
++count;
x[0] = gsl_stats_mean(psi1->data, 1, psi1->size);
x[1] = gsl_stats_mean(psi2->data, 1, psi2->size);
for (i = 0; i < n; ++i) {
nbd[i] = 2;
l[i] = 0.001;
u[i] = 0.999-cutoff;
}
if (x[0] > x[1]) {
l_bfgs_b_wrapper(n, m, x+1, l, u, nbd,
myfunc_1_2, myfunc_der_1_2, factr, pgtol,
iprint, 15000, 15000, 5, 1, psi1, psi2, var1, var2);
beta1 = fmax(fmin(x[1], 1-cutoff), 0);
beta0 = beta1 + cutoff;
} else {
l_bfgs_b_wrapper(n, m, x, l, u, nbd,
myfunc_1_2, myfunc_der_1_2, factr, pgtol,
iprint, 15000, 15000, 5, 2, psi1, psi2, var1, var2);
beta0 = fmax(fmin(x[0], 1-cutoff), 0);
beta1 = beta0 + cutoff;
}
cur_sum = 0;
for (i = 0; i < n; ++i) {
nbd[i] = 2;
l[i] = 0.01;
u[i] = 0.99;
}
individual_for_loop();
if (count > 1) {
iter_cutoff = fabs(prev_sum - cur_sum);
}
prev_sum = cur_sum;
}
if (count > iter_max) {
mle_result_set(mle, cur_sum, psi1, psi2, 0, 0, var1, var2);
return 0;
}
iter_cutoff = 1, iter_max = 100, count = 0, prev_sum = 0;
while((iter_cutoff > ITER_CUTOFF) && (count <= iter_max)) {
++count;
for (i = 0; i < n; ++i) {
nbd[i] = 2;
l[i] = 0.001;
u[i] = 0.999-cutoff;
}
x[0] = beta0;
x[1] = beta1;
if (gsl_stats_mean(psi1->data, 1, psi1->size) > gsl_stats_mean(psi2->data, 1, psi2->size)) {
l_bfgs_b_wrapper(n, m, x+1, l, u, nbd,
myfunc_marginal_1_2, myfunc_marginal_1_2_der, factr, pgtol,
iprint, 15000, 15000, 13, 1, i1, s1, psi1, var1, inclu_len, skip_len,
i2, s2, psi2, var2, inclu_len, skip_len);
beta1 = fmax(fmin(x[1], 1-cutoff), 0);
beta0 = beta1 + cutoff;
} else {
l_bfgs_b_wrapper(n, m, x, l, u, nbd,
myfunc_marginal_1_2, myfunc_marginal_1_2_der, factr, pgtol,
iprint, 15000, 15000, 13, 2, i1, s1, psi1, var1, inclu_len, skip_len,
i2, s2, psi2, var2, inclu_len, skip_len);
beta0 = fmax(fmin(x[0], 1-cutoff), 0);
beta1 = beta0 + cutoff;
}
cur_sum = 0;
for (i = 0; i < n; ++i) {
nbd[i] = 2;
l[i] = 0.01;
u[i] = 0.99;
}
individual_for_loop();
if (count > 1) {
iter_cutoff = fabs(prev_sum - cur_sum);
}
prev_sum = cur_sum;
// printf("%.12f, %.12f, %.12f, %.12f\n", beta0, beta1, iter_cutoff, prev_sum);
}
gsl_vector_free(psi1);
gsl_vector_free(psi2);
if (count > iter_max) {
mle_result_set(mle, cur_sum, psi1, psi2, 0, 0, var1, var2);
return 0;
}
mle_result_set(mle, cur_sum, psi1, psi2, beta0, beta1, var1, var2);
return 0;
}
void* thread_wrapper_for_LT(void* arg) {
double *ret = (double*)malloc(sizeof(double));
odiff *data = (odiff*)arg;
*ret = likelihood_test(data->inc1, data->inc2,
data->skp1, data->skp2,
data->inclu_len, data->skip_len,
data->flag, data->id);
return (void*)ret;
}
void* batch_wrapper_for_LT(void* arg) {
batch_datum *args = (batch_datum*)arg;
int batch_size = args->batch_size, i;
double *ret = (double*)malloc(sizeof(double)*batch_size);
odiff *datum = (odiff*)*args->datum;
odiff data;
for (i = 0; i < batch_size; ++i) {
data = datum[i];
ret[i] = likelihood_test(data.inc1, data.inc2,
data.skp1, data.skp2,
data.inclu_len, data.skip_len,
data.flag, data.id);
}
return (void*)ret;
}
double likelihood_test(gsl_vector *i1, gsl_vector *i2, gsl_vector *s1, gsl_vector *s2,
int inclu_len, int skip_len, int flag, char* id) {
printf("Testing %s\n", id);
if (!flag) {
printf("1 return from: %s\n", id);
return 1;
} else {
mle_result mle;
MLE_marginal_iteration(i1, i2, s1, s2, inclu_len, skip_len, &mle);
if (fabs(mle.params.beta0 - mle.params.beta1) <= cutoff) {
printf("2 return from: %s\n", id);
return 1;
} else {
mle_result mle_constrain;
MLE_marginal_iteration_constrain(i1, i2, s1, s2, inclu_len, skip_len, &mle_constrain);
printf("3 return from: %s\n", id);
return 1 - gsl_cdf_chisq_P(2 * (fabs(mle_constrain.sum - mle.sum)), 1);
}
}
}
int vec2psi(gsl_vector* psi, gsl_vector *inc, gsl_vector *skp,
int inclu_len, int skip_len) {
size_t idx;
for(idx = 0; idx < inc->size; ++idx) {
if (gsl_vector_get(inc, idx) + gsl_vector_get(skp, idx) == 0) {
gsl_vector_set(psi, idx, 0.5);
} else {
gsl_vector_set(psi, idx, gsl_vector_get(inc, idx)/
(gsl_vector_get(inc, idx) + inclu_len * gsl_vector_get(skp, idx)/skip_len));
}
}
return 0;
}
| {
"alphanum_fraction": 0.5503595206,
"avg_line_length": 36.0364683301,
"ext": "c",
"hexsha": "fd648a6bf8316b5f24008e19cc5a4fb3caf9f819",
"lang": "C",
"max_forks_count": 39,
"max_forks_repo_forks_event_max_datetime": "2022-03-19T09:14:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-01T20:25:44.000Z",
"max_forks_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621",
"max_forks_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_forks_repo_name": "chunjie-sam-liu/rmats-turbo",
"max_forks_repo_path": "rMATS_C/src/myfunc.c",
"max_issues_count": 163,
"max_issues_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T19:39:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-03T06:54:27.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_issues_repo_name": "chunjie-sam-liu/rmats-turbo",
"max_issues_repo_path": "rMATS_C/src/myfunc.c",
"max_line_length": 108,
"max_stars_count": 88,
"max_stars_repo_head_hexsha": "8a2ad659717a1ccd6dbecd593dc1370ba7c30621",
"max_stars_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_stars_repo_name": "chunjie-sam-liu/rmats-turbo",
"max_stars_repo_path": "rMATS_C/src/myfunc.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T17:34:39.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-01T20:20:01.000Z",
"num_tokens": 6321,
"size": 18775
} |
/* altProbes.c - Match probes to splicing events and do anaylysis.
This program origianlly was written to calculate which probe
sets were being expressed and matching up the probe sets with
the correct splice junctions. Since then it has expanded to fill
a number of roles as it is one of the few times where the probe
sets, data, and splicing information are all accesible at the
same time. Now the program is almost run in an iterative fashion,
the first time it generates a number of matrices that are used
in R to do calculations. The pvalues and scores that come out
of R can then be fed back in to be used as pre-calculated
p-vals and scores for outputting new stats.
Currently altProbes actually:
- Matches probe sets to splicing paths.
- Calculates average intensities and pvalues for a given path.
- Looks for known binding sites of splicing factors.
- Lifts splicing factors to current assembly and looks for overlaps
with conserved elements.
- Compiles and outputs matrices for R.
- Outputs a number of cassette exon specific sequence files.
*/
#include "common.h"
#include "bed.h"
#include "hash.h"
#include "options.h"
#include "chromKeeper.h"
#include "binRange.h"
#include "obscure.h"
#include "linefile.h"
#include "dystring.h"
#include "altGraphX.h"
#include "splice.h"
#include "hdb.h"
#include "dMatrix.h"
#include "liftOver.h"
#include "dnautil.h"
#include <gsl/gsl_math.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_statistics_double.h>
struct altPath
/* Information about a path and associated bed probes. */
{
struct altPath *next; /* Next in list. */
int probeCount; /* Number of probes on this path. */
struct bed **beds; /* Array of beds that are unique to this path. */
int *bedTypes; /* Are beds exons or splice junction probes. */
double **expVals; /* Expression values. */
double **pVals; /* Probability of expression. */
double *avgExpVals; /* Average value for each exp. */
struct path *path; /* Path that this altPath represents. */
double score; /* Score of being expressed overall. */
double exonCorr; /* Correlation of exon probe set with include junction if appropriate. */
double exonSkipCorr; /* Correlation of exon probe set with skip junction if appropriate. */
double probCorr; /* Correlation of exon probe set prob and include probs. */
double probSkipCorr; /* Correlation of exon probe set prob skip junction if appropriate. */
double exonSjPercent; /* Percentage of includes confirmed by exon probe set. */
double sjExonPercent; /* Percentage of exons confirmed by sj probe set. */
int exonAgree; /* Number of times exon agrees with matched splice junction */
int exonDisagree; /* Number of times exon disagrees with matched splice junction. */
int sjAgree; /* Number of times sj agrees with matched exon */
int sjDisagree; /* Number of times sj disagrees with matched exon. */
int sjExp; /* Number of times sj expressed. */
int exonExp; /* Number of times exon expressed. */
int *motifUpCounts; /* Number of motifs counted upstream for each motif. */
int *motifDownCounts; /* Number of motifs counted downstream for each motif. */
int *motifInsideCounts; /* Number of motifs counted inside for each motif. */
};
struct valuesMat
/* Matrix of slNames. */
{
struct valuesMat *next; /* Next in list. */
struct hash *rowIndex; /* Hash of row names idexes. */
int colCount; /* Number of columns. */
int maxCols; /* Number of columns we have memory for. */
char **colNames; /* Column Names. */
int rowCount; /* Number of rows. */
int maxRows; /* Number of rows we have memory for. */
char **rowNames; /* Names of rows. */
char ***vals; /* Values. */
};
struct altEvent
/* Information about a particular alt-splicing event. Specifically a
* collection of paths and the associated data. */
{
struct altEvent *next; /* Next in list. */
struct splice *splice; /* Splice event. */
struct altPath *altPathList; /* Matching of paths to probe sets. */
int altPathProbeCount; /* Paths with associated probes. */
int geneProbeCount; /* Number of probes on this gene. */
struct bed **geneBeds; /* Array of beds that are unique to this gene. */
double **geneExpVals; /* Expression values. */
double **genePVals; /* Probability of expression. */
double *avgExpVals; /* Average value for each exp. */
double flipScore; /* Number of times on version - number of times other / sum of both. */
double percentUltra; /* Percentage of bases that overlap very conserved elements. */
double pVal; /* PVal of being differentially expressed. */
boolean isExpressed; /* Is this altEvent Expressed. */
boolean isAltExpressed; /* Is this altEvent alt-expressed? */
};
struct bindSite
/* Binding sites for a protein. */
{
struct bindSite *next; /* Next in list. */
char **motifs; /* List of valid motifs. */
int motifCount; /* Number of moitfs to look for. */
char *rnaBinder; /* Rna binding protein associated with these sites. */
};
struct unitTest
{
struct unitTest *next; /* Next in list. */
boolean (*test)(struct unitTest *test); /* Function to call for test. */
char *description; /* Description of tests. */
char *errorMsg; /* Error message returned by test. */
};
/* Create a funtion pointer. */
typedef boolean (*testFunction)(struct unitTest *test);
struct unitTest *tests = NULL;
static struct optionSpec optionSpecs[] =
/* Our acceptable options to be called with. */
{
{"help", OPTION_BOOLEAN},
{"junctionProbes", OPTION_STRING},
{"spliceFile", OPTION_STRING},
{"probFile", OPTION_STRING},
{"intensityFile", OPTION_STRING},
{"db", OPTION_STRING},
{"doPathRatios", OPTION_STRING},
{"brainSpecific", OPTION_STRING},
{"tissueExpThresh", OPTION_INT},
{"otherTissExpThresh", OPTION_INT},
{"useMaxProbeSet", OPTION_BOOLEAN},
{"browser", OPTION_STRING},
{"brainSpecificStrict", OPTION_BOOLEAN},
{"tissueSpecific", OPTION_STRING},
{"brainTissues", OPTION_STRING},
{"combinePSets", OPTION_BOOLEAN},
{"useExonBeds", OPTION_BOOLEAN},
{"skipMotifControls", OPTION_BOOLEAN},
{"selectedPValues", OPTION_STRING},
{"selectedPValFile", OPTION_STRING},
{"outputProbeMatch", OPTION_STRING},
{"outputProbePvals", OPTION_STRING},
{"outputRatioStats", OPTION_STRING},
{"psToRefGene", OPTION_STRING},
{"psToKnownGene", OPTION_STRING},
{"splicePVals", OPTION_STRING},
{"cassetteBeds", OPTION_STRING},
{"newDb", OPTION_STRING},
{"flipScoreSort", OPTION_BOOLEAN},
{"conservedCassettes", OPTION_STRING},
{"notHumanCassettes", OPTION_STRING},
{"pValThresh", OPTION_FLOAT},
{"controlStats", OPTION_STRING},
{"sortScore", OPTION_STRING},
{"plotDir", OPTION_STRING},
{"minFlip", OPTION_FLOAT},
{"maxFlip", OPTION_FLOAT},
{"minIntCons", OPTION_FLOAT},
{"phastConsScores", OPTION_STRING},
{"muscleOn", OPTION_BOOLEAN},
{"presThresh", OPTION_FLOAT},
{"doTests", OPTION_BOOLEAN},
{NULL, 0}
};
static char *optionDescripts[] =
/* Description of our options for usage summary. */
{
"Display this message.",
"Bed format junction probe sets.",
"Splice format file containing alternative splicing events.",
"Data matrix with probability of transcription for each probe set.",
"Data matrix with intensity estimates for each probe set.",
"Database freeze of splices.",
"Generate ratios of probe sets of splice events to each other.",
"Output brain specific isoforms and dna.",
"How many tissues have to be seen before called expressed [default=1].",
"How many other tissues have to be seen before called expressed [default=1].",
"Instead of using best correlated probe set use all probe sets.",
"Browser to point at when creating web page.",
"Require each non-brain tissue to be below absThresh.",
"Output tissue specific counts for various events to this file.",
"Comma separated list of tissues to consider brain.",
"Combine the p-values for a path using Fisher's method.",
"Use exon beds, not just splice junction beds.",
"Skip looking at the motifs in the controls, can be quite slow.",
"File containing list of AFFY G###### ids and gene names.",
"File containing list of AFFY G###### ids and known gene ids.",
"File to output pvalue vectors for selected genes to.",
"Output the splicing events and the probes that were used.",
"Output the probe level pvals for each alternative event.",
"Output the ratio for altCassette, alt5, alt3, and altMutExclusive to file.",
"File with mapping from probe set to gene name.",
"File with pvalues for specific splices of interest.",
"Prefix for files to output not-expressed, expressed not alt, and alt cassette beds.",
"Genome to try and lift coordinates to.",
"Sort brain specific genes by flip score.",
"Cassettes that are conserved (in new genome).",
"Cassettes that are not in human (in new genome).",
"Threshold to filter pvalue at, default .001",
"Output some stats for control exons to this file.",
"Score to replace flipScore for sorting, etc.",
"Directory plots are in.",
"Minimum Flip Score to output fasta record for.",
"Maximum Flip Score to output fasta record for.",
"Minimum intron conservation percent to output fasta records for.",
"Conservation scores table where first column is skipping probeset.",
"Do muscle rather than brain, currently only effects some urls.",
"Threshold to be declared expressed.",
"Do some unit tests."
};
int isBrainTissue[256]; /* Global brain identifier. */
struct hash *liftOverHash = NULL; /* Hash holding chains for lifting. */
struct hash *bedHash = NULL; /* Access bed probe sets by hash. */
double presThresh = .9; /* Threshold for being called present. */
int tissueExpThresh = 1; /* Number of tissues something must be seen in to
be considered expressed. */
double absThresh = .1; /* Threshold for being called not present. */
boolean brainSpecificStrict = FALSE; /* Do we require that all non-brain tissues be below absThresh? */
char *browserName = NULL; /* Name of browser that we are going to html link to. */
char *db = NULL; /* Database version used here. */
char *newDb = NULL; /* Database version lifting to. */
boolean useMaxProbeSet; /* Instead of using the best correlated probe set, use any
probe set. */
boolean useComboProbes = FALSE; /* Combine probe sets on a given path using fisher's method. */
boolean useExonBedsToo = FALSE; /* Use exon beds too, not just splice junction beds. */
int intronsConserved = 0;
int intronsConsCounted = 0;
struct slRef *brainSpEvents = NULL; /* List of brain specific events. */
FILE *constMotifCounts = NULL; /* Counts for each motif in constitutive exons. */
FILE *probeMappingsOut = NULL;
FILE *ratioStatOut = NULL; /* File to output a matrix of ratios of skip/includes. */
FILE *ratioSkipIntenOut = NULL; /* Intensity file for skip paths. */
FILE *ratioIncIntenOut = NULL; /* Intensity file for skip paths. */
FILE *ratioGeneIntenOut = NULL; /* Intensity file for gene probe set. */
FILE *ratioProbOut = NULL; /* Probability gene is expressed. */
FILE *incProbOut = NULL; /* Include maximium probability values. */
FILE *skipProbOut = NULL; /* Skip maximum probability values. */
FILE *incProbCombOut = NULL; /* Include combined probability values. */
FILE *skipProbCombOut = NULL; /* Skip combined probability values. */
FILE *pathProbabilitiesOut = NULL; /* File to print out path probability vectors. */
FILE *pathExpressionOut = NULL; /* File to print out path probability vectors. */
FILE *pathProbabilitiesBedOut = NULL; /* File to print out corresponding beds for paths. */
double pvalThresh = 2; //.05 / 1263; /* Threshold at which we believe pval is real. */
struct hash *notHumanHash = NULL; /* Hash of exons that are not even aligned to human. */
struct hash *conservedHash = NULL; /* Hash of conserved exon events. */
struct hash *splicePValsHash = NULL; /* Hash of pvals of interest. */
struct hash *phastConsHash = NULL; /* Hash of conservation scores of interest. */
struct hash *sortScoreHash = NULL; /* Hash of scores of interest. */
struct hash *outputPValHash = NULL; /* Hash of selected names. */
struct hash *psToRefGeneHash = NULL; /* Hash of probe set to affy genes. */
struct hash *psToKnownGeneHash = NULL; /* Hash of probe set to known genes. */
int otherTissueExpThres = 1; /* Number of other tissues something must be seen in to
be considered expressed, used */
struct bindSite *bindSiteList = NULL; /* List of rna binding sites to look for. */
struct bindSite **bindSiteArray = NULL; /* array of rna binding sites to look for. */
int bindSiteCount = 0; /* Number of binding sites to loop through. */
int cassetteExonCount = 0; /* Number of cassette exons examined. */
int cassetteExonSkipCount = 0; /* Number of cassette exons examined. */
int *cassetteUpMotifs = NULL; /* Counts of motifs upstream cassette exons. */
int *cassetteDownMotifs = NULL; /* Counts of moitfs downstream cassette exons. */
int *cassetteInsideMotifs = NULL; /* Counts of moitfs downstream cassette exons. */
int *cassetteSkipUpMotifs = NULL; /* Counts of motifs upstream cassette exons for skipping exons. */
int *cassetteSkipDownMotifs = NULL; /* Counts of moitfs downstream cassette exon for skipping exons. */
int *cassetteSkipInsideMotifs = NULL; /* Counts of moitfs downstream cassette exons for skipping exons. */
int cassetteSkipInsideBpCount = 0; /* Counts of base pairs cassette exons for skipping exons. */
int controlExonCount = 0; /* Number of control exons examined. */
int *controlUpMotifs = NULL; /* Counts of motifs upstream cassette exons. */
int *controlDownMotifs = NULL; /* Counts of moitfs downstream cassette exons. */
int *controlInsideMotifs = NULL; /* Counts of moitfs inside cassette exons. */
int controlInsideBpCount = 0; /* Counts of moitfs inside cassette exons. */
boolean skipMotifControls = FALSE; /* Skip looking for motifs in controls. */
FILE *controlValuesOut = NULL; /* File to output control values to. */
struct valuesMat *controlValuesVm = NULL; /* ValuesMat to keep track of various stats. */
struct valuesMat *brainSpecificValues = NULL; /* Values to keep track of for values. */
int brainSpecificEventCount = 0; /* How many brain specific events are there. */
int brainSpecificEventCassCount = 0; /* How many brain specific events are there. */
int brainSpecificEventMutExCount = 0; /* How many brain specific events are there. */
int brainSpecificPathCount = 0; /* How many brain specific paths are there. */
FILE *brainSpValuesOut = NULL; /* Value matrix outputted here. */
FILE *brainSpDnaUpOut = NULL; /* File for dna around first exon on
* brain specific isoforms. */
FILE *brainSpConsDnaOut = NULL;
FILE *brainSpConsBedOut = NULL;
FILE *brainSpDnaUpDownOut = NULL;
FILE *brainSpDnaDownOut = NULL;
FILE *brainSpDnaMergedOut = NULL;
FILE *brainSpBedUpOut = NULL; /* File for paths (in bed format) that
* are brain specific. */
FILE *brainSpBedDownOut = NULL;
FILE *brainSpPathBedOut = NULL;
FILE *brainSpPathEndsBedOut = NULL;
FILE *brainSpPSetOut = NULL;
FILE *brainSpPathBedExonUpOut = NULL;
FILE *brainSpPathBedExonDownOut = NULL;
FILE *brainSpTableHtmlOut = NULL; /* Html table for visualizing brain specific events. */
FILE *brainSpFrameHtmlOut = NULL; /* Html frame for visualizing brain specific events. */
static int *brainSpecificCounts;
FILE *tissueSpecificOut = NULL; /* File to output tissue specific results to. */
boolean tissueSpecificStrict = FALSE; /* Do we require that all other tissues be below absThresh? */
static int **tissueSpecificCounts; /* Array of counts for different tissue specific splice
types per tissue. */
int *brainSpecificMotifUpCounts = NULL;
int *brainSpecificMotifDownCounts = NULL;
int *brainSpecificMotifInsideCounts = NULL;
int brainSpecificMotifInsideBpCount = 0;
FILE *expressedCassetteBedOut = NULL; /* Output beds for casssette exons that are expressed. */
FILE *altCassetteBedOut = NULL; /* Output beds for cassettte exons that are alt. expressed. */
FILE *notExpressedCassetteBedOut = NULL; /* Output beds for cassette exons that don't look expressed. */
/* Keep track of how many of each event are occuring. */
static int alt5PrimeCount = 0;
static int alt3PrimeCount = 0;
static int altCassetteCount = 0;
static int altRetIntCount = 0;
static int altOtherCount = 0;
static int alt3PrimeSoftCount = 0;
static int alt5PrimeSoftCount = 0;
static int altMutExclusiveCount = 0;
static int altControlCount = 0;
/* Keep track of how many of each event with probes */
static int alt5PrimeWProbeCount = 0;
static int alt3PrimeWProbeCount = 0;
static int altCassetteWProbeCount = 0;
static int altRetIntWProbeCount = 0;
static int altOtherWProbeCount = 0;
static int alt3PrimeSoftWProbeCount = 0;
static int alt5PrimeSoftWProbeCount = 0;
static int altMutExclusiveWProbeCount = 0;
static int altControlWProbeCount = 0;
/* Keep track of how many of each event expressed. */
static int alt5PrimeExpCount = 0;
static int alt3PrimeExpCount = 0;
static int altCassetteExpCount = 0;
static int altRetIntExpCount = 0;
static int altOtherExpCount = 0;
static int alt3PrimeSoftExpCount = 0;
static int alt5PrimeSoftExpCount = 0;
static int altMutExclusiveExpCount = 0;
static int altControlExpCount = 0;
/* Keep track of how many of each event alt-expressed */
static int alt5PrimeAltExpCount = 0;
static int alt3PrimeAltExpCount = 0;
static int altCassetteAltExpCount = 0;
static int altRetIntAltExpCount = 0;
static int altOtherAltExpCount = 0;
static int alt3PrimeSoftAltExpCount = 0;
static int alt5PrimeSoftAltExpCount = 0;
static int altMutExclusiveAltExpCount = 0;
static int altControlAltExpCount = 0;
void usage()
/** Print usage and quit. */
{
int i=0;
warn("altProbes - Match probes to splicing paths and analyze.\n"
"options are:");
for(i=0; i<ArraySize(optionSpecs) -1; i++)
fprintf(stderr, " -%s -- %s\n", optionSpecs[i].name, optionDescripts[i]);
errAbort("\nusage:\n ");
}
struct splice *ndr2CassTest()
/* Create a splice for use in testsing. */
{
char *string = cloneString("chr14 43771400 43772080 chr14.7822-8.26 2 - 9319 38 43765895,43766921,43767127,43767179,43767304,43767340,43767563,43767611,43767860,43767912,43768199,43768244,43768682,43768786,43768944,43769001,43769182,43769269,43769488,43769549,43770672,43770735,43770929,43771050,43771294,43771356,43771400,43771404,43771700,43771742,43772080,43772161,43773937,43774090,43774093,43774180,43774538,43774609, 0,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,1,3,2,1,3,1,3,1,1,2,2,1,2, 2 {\"chr14\",43771400,43772080,0,2,2,{26,30,},24,31,0,},{\"chr14\",43771400,43772080,0,4,4,{26,28,29,30,},24,31,42,},");
struct splice *splice = NULL;
char *words[100];
chopByWhite(string, words, sizeof(words));
splice = spliceLoad(words);
}
struct bed *ndr2BedTest()
/* Create beds used in testing. */
{
char *inc1 = "chr14 43771385 43771715 G6912708@J918653_RC@j_at 0 - 43771385 43771715 0 2 15,15, 0,315,";
char *skip = "chr14 43771385 43772095 G6912708@J918654_RC@j_at 0 - 43771385 43772095 0 2 15,15, 0,695,";
char *inc2 = "chr14 43771727 43772095 G6912708@J918655_RC@j_at 0 - 43771727 43772095 0 2 15,15, 0,353,";
char *gene = "chr14 43765981 43772151 G6912708_RC_a_at 0 - 43765981 43772151 0 9 25,25,25,25,25,25,25,25,43, 0,149,1602,3222,3262,3516,5000,5392,6127,";
struct bed *bedList = NULL, *bed = NULL;
char *words[12];
chopByWhite(cloneString(inc1), words, ArraySize(words));
bed = bedLoadN(words,12);
slAddHead(&bedList, bed);
chopByWhite(cloneString(skip), words, ArraySize(words));
bed = bedLoadN(words,12);
slAddHead(&bedList, bed);
chopByWhite(cloneString(inc2), words, ArraySize(words));
bed = bedLoadN(words,12);
slAddHead(&bedList, bed);
chopByWhite(cloneString(gene), words, ArraySize(words));
bed = bedLoadN(words,12);
slAddHead(&bedList, bed);
slReverse(&bedList);
return bedList;
}
struct dMatrix *ndr2BedTestMat(boolean probability)
/* Create a fake matrix of probabilities. If probability is TRUE fill
in a probability matrix, otherwise fill in an intensity matrix. */
{
struct dMatrix *probs = NULL;
static char *colNames[] = {"cerebellum", "cortex", "heart", "skeletal"};
static char *rowNames[] = {"G6912708@J918653_RC@j_at", "G6912708@J918654_RC@j_at",
"G6912708@J918655_RC@j_at", "G6912708_RC_a_at"};
double probM[4][4] = {{.8, 1, 0, .5},{0, 0, 0, 1}, {.8, 0, 0, .5}, {1, 0, .5, 1}};
double intenM[4][4] = {{1, 1, 1, 2.5}, {1, 1, 1, 1}, {1, 1, 0, 1.5}, {1, 1, 1, .5}};
double **matrix = NULL;
int count = 0;
AllocVar(probs);
AllocArray(matrix, ArraySize(rowNames));
probs->nameIndex = newHash(3);
for(count = 0; count < ArraySize(colNames); count++)
{
if(probability)
matrix[count] = CloneArray(probM[count], ArraySize(probM[count]));
else
matrix[count] = CloneArray(intenM[count], ArraySize(intenM[count]));
hashAddInt(probs->nameIndex, rowNames[count], count);
}
probs->colNames = colNames;
probs->colCount = ArraySize(colNames);
probs->rowNames = rowNames;
probs->rowCount = ArraySize(rowNames);
probs->matrix = matrix;
return probs;
}
struct valuesMat *newValuesMat(int numCol, int numRow)
/* Create a new values matrix. */
{
struct valuesMat *vm = NULL;
int i = 0;
AllocVar(vm);
vm->maxCols = numCol;
vm->maxRows = numRow;
AllocArray(vm->colNames, vm->maxCols);
AllocArray(vm->rowNames, vm->maxRows);
AllocArray(vm->vals, vm->maxRows);
for(i = 0; i < vm->maxRows; i++)
AllocArray(vm->vals[i], vm->maxCols);
vm->rowIndex = newHash(round(logBase2(vm->maxCols) + .5));
return vm;
}
void vmAddVal(struct valuesMat *vm, char *rowName, char *colName, char *val)
/* Add item val to rowName in correct column. */
{
int i = 0;
int colIx = -1;
int rowIx = -1;
assert(vm);
assert(vm->rowIndex);
assert(rowName);
assert(val);
assert(colName);
for( i = 0; i < vm->colCount; i++)
if(sameString(vm->colNames[i], colName))
{
colIx = i;
break;
}
/* If column not existent add it. */
if(colIx == -1)
{
if(vm->colCount + 1 >= vm->maxCols)
{
ExpandArray(vm->colNames, vm->maxCols, vm->maxCols+1);
for(i = 0; i < vm->rowCount; i++)
ExpandArray(vm->vals[i], vm->maxCols, vm->maxCols+1);
vm->maxCols++;
}
colIx = vm->colCount;
vm->colNames[colIx] = cloneString(colName);
vm->colCount++;
}
/* Get the row for that identifier. */
rowIx = hashIntValDefault(vm->rowIndex, rowName, -1);
if(rowIx == -1)
{
if(vm->rowCount + 1 >= vm->maxRows)
{
ExpandArray(vm->rowNames, vm->maxRows, vm->maxRows+1);
ExpandArray(vm->vals, vm->maxRows, vm->maxRows+1);
AllocArray(vm->vals[vm->maxRows], vm->maxCols);
vm->maxRows++;
}
rowIx = vm->rowCount;
vm->rowNames[rowIx] = cloneString(rowName);
hashAddInt(vm->rowIndex, rowName, rowIx);
vm->rowCount++;
}
vm->vals[rowIx][colIx] = cloneString(val);
}
void vmWriteVals(struct valuesMat *vm, FILE *out)
/* Writ out the vm. */
{
int colIx = 0, rowIx = 0;
for(colIx = 0; colIx < vm->colCount - 1; colIx++)
fprintf(out, "%s\t", vm->colNames[colIx]);
fprintf(out, "%s\n", vm->colNames[colIx]);
for(rowIx = 0; rowIx < vm->rowCount; rowIx++)
{
fprintf(out, "%s\t", vm->rowNames[rowIx]);
for(colIx = 0; colIx < vm->colCount -1; colIx++)
fprintf(out, "%s\t", vm->vals[rowIx][colIx]);
fprintf(out, "%s\n", vm->vals[rowIx][colIx]);
}
}
void logSpliceType(enum altSpliceType type)
/* Log the different types of splicing. */
{
switch (type)
{
case alt5Prime:
alt5PrimeCount++;
break;
case alt3Prime:
alt3PrimeCount++;
break;
case altCassette:
altCassetteCount++;
break;
case altRetInt:
altRetIntCount++;
break;
case altOther:
altOtherCount++;
break;
case alt5PrimeSoft:
alt5PrimeSoftCount++;
break;
case alt3PrimeSoft:
alt3PrimeSoftCount++;
break;
case altMutExclusive:
altMutExclusiveCount++;
break;
case altControl:
altControlCount++;
break;
default:
errAbort("logSpliceType() - Don't recognize type %d", type);
}
}
void logSpliceTypeWProbe(enum altSpliceType type)
/* Log the different types of splicing. */
{
switch (type)
{
case alt5Prime:
alt5PrimeWProbeCount++;
break;
case alt3Prime:
alt3PrimeWProbeCount++;
break;
case altCassette:
altCassetteWProbeCount++;
break;
case altRetInt:
altRetIntWProbeCount++;
break;
case altOther:
altOtherWProbeCount++;
break;
case alt5PrimeSoft:
alt5PrimeSoftWProbeCount++;
break;
case alt3PrimeSoft:
alt3PrimeSoftWProbeCount++;
break;
case altMutExclusive:
altMutExclusiveWProbeCount++;
break;
case altControl:
altControlWProbeCount++;
break;
default:
errAbort("logSpliceType() - Don't recognize type %d", type);
}
}
void logSpliceTypeExp(enum altSpliceType type)
/* Log the different types of splicing. */
{
switch (type)
{
case alt5Prime:
alt5PrimeExpCount++;
break;
case alt3Prime:
alt3PrimeExpCount++;
break;
case altCassette:
altCassetteExpCount++;
break;
case altRetInt:
altRetIntExpCount++;
break;
case altOther:
altOtherExpCount++;
break;
case alt5PrimeSoft:
alt5PrimeSoftExpCount++;
break;
case alt3PrimeSoft:
alt3PrimeSoftExpCount++;
break;
case altMutExclusive:
altMutExclusiveExpCount++;
break;
case altControl:
altControlExpCount++;
break;
default:
errAbort("logSpliceType() - Don't recognize type %d", type);
}
}
void logSpliceTypeAltExp(enum altSpliceType type)
/* Log the different types of splicing. */
{
switch (type)
{
case alt5Prime:
alt5PrimeAltExpCount++;
break;
case alt3Prime:
alt3PrimeAltExpCount++;
break;
case altCassette:
altCassetteAltExpCount++;
break;
case altRetInt:
altRetIntAltExpCount++;
break;
case altOther:
altOtherAltExpCount++;
break;
case alt5PrimeSoft:
alt5PrimeSoftAltExpCount++;
break;
case alt3PrimeSoft:
alt3PrimeSoftAltExpCount++;
break;
case altMutExclusive:
altMutExclusiveAltExpCount++;
break;
case altControl:
altControlAltExpCount++;
break;
default:
errAbort("logSpliceType() - Don't recognize type %d", type);
}
}
void initSplicePVals()
/* Load up the pvals of interest generated in a separate file. */
{
struct lineFile *lf = NULL;
char *fileName = optionVal("splicePVals", NULL);
char *words[2];
struct slDouble *sd = NULL;
assert(fileName);
splicePValsHash = newHash(10);
lf = lineFileOpen(fileName, TRUE);
while(lineFileNextRow(lf, words, ArraySize(words)))
{
char *mark = NULL;
hashAdd(splicePValsHash, words[0], slDoubleNew(sqlDouble((words[1]))));
}
lineFileClose(&lf);
}
double pvalForSplice(char *name)
/* Return a pval as specified in the splicePVal file or 2 if not there. */
{
struct slDouble *d = NULL;
if(splicePValsHash == NULL)
errAbort("Need to specify -splicePVal file if using pvalForSplice");
assert(name);
d = hashFindVal(splicePValsHash, name);
if(d == NULL)
return 2.0;
return d->val;
}
void initPhastConsScores()
/* Load up the conservation scores of interest generated in a separate file. */
{
struct lineFile *lf = NULL;
char *fileName = optionVal("phastConsScores", NULL);
char *words[2];
struct slDouble *sd = NULL;
assert(fileName);
phastConsHash = newHash(10);
lf = lineFileOpen(fileName, TRUE);
while(lineFileNextRow(lf, words, ArraySize(words)))
{
hashAdd(phastConsHash, words[0], slDoubleNew(sqlDouble((words[1]))));
}
lineFileClose(&lf);
}
double phastConsForSplice(char *name)
/* Return a phast cons score associated with the splicing event. */
{
struct slDouble *d = NULL;
if(phastConsHash == NULL)
errAbort("Need to specify -phastConsScores file if using phastConsForSplice");
assert(name);
d = hashFindVal(phastConsHash, name);
if(d == NULL)
return -1;
return d->val;
}
void initSortScore()
/* Load up the pvals of interest generated in a separate file. */
{
struct lineFile *lf = NULL;
char *fileName = optionVal("sortScore", NULL);
char *words[2];
struct slDouble *sd = NULL;
assert(fileName);
sortScoreHash = newHash(10);
lf = lineFileOpen(fileName, TRUE);
while(lineFileNextRow(lf, words, ArraySize(words)))
{
char *mark = NULL;
double d = 0;
d = sqlDouble(words[1]);
sd = slDoubleNew(d);
hashAddUnique(sortScoreHash, words[0], sd);
}
lineFileClose(&lf);
}
double sortScoreForSplice(char *name)
/* Return a pval as specified in the splicePVal file or 2 if not there. */
{
struct slDouble *d = NULL;
if(sortScoreHash == NULL)
errAbort("Need to specify -sortScore file if using sortScoreForSplice");
assert(name);
d = hashFindVal(sortScoreHash, name);
if(d == NULL)
return 0;
return d->val;
}
void initPsToRefGene()
/* Load up a file that converts from affy psName to gene names. */
{
struct lineFile *lf = NULL;
char *fileName = optionVal("psToRefGene", NULL);
char *words[2];
assert(fileName);
psToRefGeneHash = newHash(10);
lf = lineFileOpen(fileName, TRUE);
while(lineFileNextRow(lf, words, ArraySize(words)))
{
hashAdd(psToRefGeneHash, words[1], cloneString(words[0]));
}
lineFileClose(&lf);
}
char *refSeqForPSet(char *pSet)
/* Look up the refseq name for a probe set. */
{
static boolean warned = FALSE;
char *gene = NULL;
if(psToRefGeneHash == NULL)
{
if(warned != TRUE)
warn("Can't convert psName to refSeq name, have to specify psToRefGene flag.");
warned = TRUE;
return pSet;
}
gene = hashFindVal(psToRefGeneHash, pSet);
if(gene == NULL)
return pSet;
return gene;
}
void initPsToKnownGene()
/* Load up a file that converts from affy psName to gene names. */
{
struct lineFile *lf = NULL;
char *fileName = optionVal("psToKnownGene", NULL);
char *words[2];
assert(fileName);
psToKnownGeneHash = newHash(10);
lf = lineFileOpen(fileName, TRUE);
while(lineFileNextRow(lf, words, ArraySize(words)))
{
hashAdd(psToKnownGeneHash, words[1], cloneString(words[0]));
}
lineFileClose(&lf);
}
char *knownGeneForPSet(char *pSet)
/* Look up the refseq name for a probe set. */
{
static boolean warned = FALSE;
char *gene = NULL;
if(psToKnownGeneHash == NULL)
{
if(warned != TRUE)
errAbort("Can't convert psName to known name, have to specify psToKnowngene flag.");
warned = TRUE;
return pSet;
}
gene = hashFindVal(psToKnownGeneHash, pSet);
if(gene == NULL)
return pSet;
return gene;
}
void initBindSiteList()
/* Create a little hand curated knowledge about binding sites. */
{
struct bindSite *bsList = NULL, *bs = NULL;
int i = 0;
/* Nova-1 */
AllocVar(bs);
bs->motifCount = 2;
AllocArray(bs->motifs, bs->motifCount);
/* Expand TCATY */
bs->motifs[i++] = cloneString("TCATT");
bs->motifs[i++] = cloneString("TCATC");
bs->rnaBinder = cloneString("Nova-1");
slAddHead(&bsList, bs);
/* Fox-1 */
AllocVar(bs);
bs->motifCount = 1;
AllocArray(bs->motifs, bs->motifCount);
bs->motifs[0] = cloneString("GCATG");
bs->rnaBinder = cloneString("Fox-1");
slAddHead(&bsList, bs);
/* PTB */
AllocVar(bs);
bs->motifCount = 1;
AllocArray(bs->motifs, bs->motifCount);
bs->motifs[0] = cloneString("CTCTCT");
bs->rnaBinder = cloneString("PTB/nPTB");
slAddHead(&bsList, bs);
/* hnRNPs */
AllocVar(bs);
bs->motifCount = 1;
AllocArray(bs->motifs, bs->motifCount);
bs->motifs[0] = cloneString("GGGG");
bs->rnaBinder = cloneString("hnRNP-H/F");
slAddHead(&bsList, bs);
/* /\* First motif... *\/ */
/* i = 0; */
/* AllocVar(bs); */
/* bs->motifCount = 16; */
/* AllocArray(bs->motifs, bs->motifCount); */
/* /\* (YNCURY; Y, pyrimidine; R, purine; N, any nucleotide; the branch point adenosine is underlined*\/ */
/* bs->motifs[i++] = cloneString("TACTAAT"); */
/* bs->motifs[i++] = cloneString("TGCTAAT"); */
/* bs->motifs[i++] = cloneString("TTCTAAT"); */
/* bs->motifs[i++] = cloneString("TCCTAAT"); */
/* bs->motifs[i++] = cloneString("TACTAAC"); */
/* bs->motifs[i++] = cloneString("TGCTAAC"); */
/* bs->motifs[i++] = cloneString("TTCTAAC"); */
/* bs->motifs[i++] = cloneString("TCCTAAC"); */
/* bs->motifs[i++] = cloneString("TATTAAT"); */
/* bs->motifs[i++] = cloneString("TGTTAAT"); */
/* bs->motifs[i++] = cloneString("TTTTAAT"); */
/* bs->motifs[i++] = cloneString("TCTTAAT"); */
/* bs->motifs[i++] = cloneString("TATTAAC"); */
/* bs->motifs[i++] = cloneString("TGTTAAC"); */
/* bs->motifs[i++] = cloneString("TTTTAAC"); */
/* bs->motifs[i++] = cloneString("TCTTAAC"); */
/* bs->rnaBinder = cloneString("TNCTAAC/T"); */
/* slAddHead(&bsList, bs); */
i = 0;
AllocVar(bs);
bs->motifCount = 1;
AllocArray(bs->motifs, bs->motifCount);
bs->motifs[i++] = cloneString("CTAAC");
bs->rnaBinder = cloneString("CTAAC");
slAddHead(&bsList, bs);
i = 0;
AllocVar(bs);
bs->motifCount = 2;
AllocArray(bs->motifs, bs->motifCount);
bs->motifs[i++] = cloneString("TGCTTTC");
bs->motifs[i++] = cloneString("TGTTTTC");
bs->rnaBinder = cloneString("TGYTTTC");
slAddHead(&bsList, bs);
i = 0;
AllocVar(bs);
bs->motifCount = 1;
AllocArray(bs->motifs, bs->motifCount);
bs->motifs[i++] = cloneString("TAGGG");
bs->rnaBinder = cloneString("hnRNP-A1");
slAddHead(&bsList, bs);
i = 0;
AllocVar(bs);
bs->motifCount = 2;
AllocArray(bs->motifs, bs->motifCount);
bs->motifs[i++] = cloneString("TCCTTT");
bs->motifs[i++] = cloneString("TGCTTT");
bs->rnaBinder = cloneString("TG/CCTTT");
slAddHead(&bsList, bs);
/* i = 0; */
/* AllocVar(bs); */
/* bs->motifCount = 2; */
/* AllocArray(bs->motifs, bs->motifCount); */
/* bs->motifs[i++] = cloneString("TGCTTTCC"); */
/* bs->motifs[i++] = cloneString("TGTTTTCC"); */
/* bs->rnaBinder = cloneString("TGC/TTTTCC"); */
/* slAddHead(&bsList, bs); */
/* First discovered motif... */
AllocVar(bs);
bs->motifCount = 1;
AllocArray(bs->motifs, bs->motifCount);
bs->motifs[0] = cloneString("TCCTT");
bs->rnaBinder = cloneString("TCCTT");
slAddHead(&bsList, bs);
slReverse(&bsList);
bindSiteList = bsList;
AllocArray(bindSiteArray, slCount(bsList));
for(bs = bsList; bs != NULL; bs = bs->next)
bindSiteArray[bindSiteCount++] = bs;
AllocArray(cassetteUpMotifs, bindSiteCount);
AllocArray(cassetteDownMotifs, bindSiteCount);
AllocArray(cassetteInsideMotifs, bindSiteCount);
AllocArray(cassetteSkipUpMotifs, bindSiteCount);
AllocArray(cassetteSkipDownMotifs, bindSiteCount);
AllocArray(cassetteSkipInsideMotifs, bindSiteCount);
AllocArray(controlUpMotifs, bindSiteCount);
AllocArray(controlDownMotifs, bindSiteCount);
AllocArray(controlInsideMotifs, bindSiteCount);
}
boolean isJunctionBed(struct bed *bed)
/* Return TRUE if bed looks like a junction probe. Specifically
two blocks, each 15bp. FALSE otherwise. */
{
if(bed->blockCount == 2 && bed->blockSizes[0] == 15 && bed->blockSizes[1] == 15)
return TRUE;
return FALSE;
}
boolean validVertex(struct splice *splice, int v1, int v2)
/* Check to see if a given vertex is the sink or source of the
graph and should be ignored. */
{
return (v1 >= 0 && v1 < splice->vCount && v2 >= 0 && v2 < splice->vCount);
}
enum ggEdgeType pathEdgeTypeValid(struct splice *s, int v1, int v2)
{
assert(validVertex(s, v1,v2));
return pathEdgeType(s->vTypes, v1, v2);
}
boolean pathContainsIntron(struct splice *splice, struct path *path, char *chrom,
int chromStart, int chromEnd, char *strand)
/* Return TRUE if this path contains an intron (splice junction) that
starts at chromStart and ends at chromEnd. */
{
int i = 0;
int *vPos = splice->vPositions;
int *verts = path->vertices;
if (differentString(splice->tName, chrom) ||
differentString(splice->strand, strand))
return FALSE;
/* Check the edges on the path. */
for(i = 0; i < path->vCount - 1; i++)
{
if(validVertex(splice, verts[i], verts[i+1]) &&
pathEdgeTypeValid(splice, verts[i], verts[i+1]) == ggSJ)
{
if(chromStart == vPos[verts[i]] && chromEnd == vPos[verts[i+1]])
return TRUE;
}
}
return FALSE;
}
boolean pathContainsBlock(struct splice *splice, struct path *path, char *chrom,
int chromStart, int chromEnd, char *strand,
boolean allBases)
/* Return TRUE if this block is contained in the path, FALSE otherwise.
If allBases then every base in chromStart-chromEnd must be covered
by path. */
{
int i = 0;
int *vPos = splice->vPositions;
int *verts = path->vertices;
if (differentString(splice->tName, chrom) ||
differentString(splice->strand, strand))
return FALSE;
/* Check the first edge. */
if(validVertex(splice, path->upV, verts[0]) &&
pathEdgeTypeValid(splice, path->upV,verts[0]) == ggExon)
{
if(chromStart >= vPos[path->upV] && chromEnd <= vPos[verts[0]])
return TRUE;
else if (!allBases && rangeIntersection(chromStart, chromEnd,
vPos[path->upV], vPos[verts[0]]) > 0)
return TRUE;
}
/* Check the last edge. */
if(validVertex(splice, verts[path->vCount -1], path->downV) &&
pathEdgeTypeValid(splice, verts[path->vCount - 1], path->downV) == ggExon)
{
if (chromStart >= vPos[verts[path->vCount - 1]] &&
chromEnd <= vPos[path->downV])
return TRUE;
else if (!allBases &&
rangeIntersection(chromStart, chromEnd,
vPos[verts[path->vCount - 1]], vPos[path->downV]) > 0)
return TRUE;
}
/* Check the edges on the path. */
for(i = 0; i < path->vCount - 1; i++)
{
if(validVertex(splice, verts[i], verts[i+1]) &&
pathEdgeTypeValid(splice, verts[i], verts[i+1]) == ggExon)
{
if (chromStart >= vPos[verts[i]] && chromEnd <= vPos[verts[i+1]])
return TRUE;
else if (!allBases && rangeIntersection(chromStart, chromEnd,
vPos[verts[i]], vPos[verts[i+1]]) > 0)
return TRUE;
}
}
return FALSE;
}
boolean pathContainsBed(struct splice *splice, struct path *path,
struct bed *bed, boolean intronsToo)
/* Return TRUE if this path contains this bed, FALSE otherwise. If
allBases, the bed must be completely subsumed by the path. */
{
boolean containsBed = TRUE;
int i = 0;
assert(bed);
for(i = 0; i < bed->blockCount; i++)
{
int chromStart = bed->chromStart + bed->chromStarts[i];
int chromEnd = bed->chromStart + bed->chromStarts[i] + bed->blockSizes[i];
/* Check the exon. */
containsBed &= pathContainsBlock(splice, path, bed->chrom, chromStart,
chromEnd, bed->strand, TRUE);
if(containsBed == FALSE)
break;
/* Check the next intron. */
if (intronsToo && i+1 != bed->blockCount)
containsBed &= pathContainsIntron(splice, path, bed->chrom, chromEnd,
bed->chromStarts[i+1]+chromStart, bed->strand);
}
return containsBed;
}
void insertBedIntoPath(struct altEvent *altEvent, struct altPath *altPath,
struct bed *bed)
/* Add the cbed to this path. */
{
int pCount = 0;
assert(altPath);
pCount = altPath->probeCount;
ExpandArray(altPath->beds, pCount, pCount+1);
ExpandArray(altPath->bedTypes, pCount, pCount+1);
altPath->beds[altPath->probeCount++] = bed;
}
int findProbeSetsForEvents(struct altEvent *altEvent)
/* Look for all of the beds that overlap a splice and match
them the ones that are uniq to a path. Returns the number
of probes that map to this splice. */
{
struct binElement *be = NULL, *beList = NULL;
struct altPath *altPath = NULL, *altMatchPath = NULL;
struct bed *bed = NULL;
assert(altEvent);
struct splice *splice = altEvent->splice;
/* Load all the beds that span this range. */
beList = chromKeeperFind(splice->tName, splice->tStart, splice->tEnd);
for(be = beList; be != NULL; be = be->next)
{
bed = be->val;
if(isJunctionBed(bed) || (useExonBedsToo && strchr(bed->name, '@') != NULL))
{
altMatchPath = NULL; /* Indicates that we haven't found a match for this bed. */
for(altPath = altEvent->altPathList; altPath != NULL; altPath = altPath->next)
{
/* If it is a junction pass the intronsToo flag == TRUE, otherwise
set to false. */
if((isJunctionBed(bed) && pathContainsBed(splice, altPath->path, bed, TRUE)) ||
(!isJunctionBed(bed) && pathContainsBed(splice, altPath->path, bed, FALSE)))
{
if(altMatchPath == NULL)
altMatchPath = altPath; /* So far unique match. */
else
{ /* Not a unique match. */
altMatchPath = NULL;
break;
}
}
}
}
else
continue;
/* If we've uniquely found a path for a bed insert it. */
if(altMatchPath != NULL)
insertBedIntoPath(altEvent, altMatchPath, bed);
}
/* Count up how many paths have probes. */
for(altPath = altEvent->altPathList; altPath != NULL; altPath = altPath->next)
if(altPath->probeCount > 0)
altEvent->altPathProbeCount++;
}
void bedLoadChromKeeper()
/* Load the beds's in the file into the chromKeeper. */
{
char *db = optionVal("db", NULL);
char *bedFile = optionVal("junctionProbes", NULL);
struct bed *bed = NULL, *bedList = NULL;
bedHash = newHash(12);
if(db == NULL)
errAbort("Must specify a database when loading beds.");
if(bedFile == NULL)
errAbort("Must specify a file for loading beds.");
chromKeeperInit(db);
bedList = bedLoadAll(bedFile);
for(bed = bedList; bed != NULL; bed = bed->next)
{
chromKeeperAdd(bed->chrom, bed->chromStart, bed->chromEnd, bed);
hashAdd(bedHash, bed->name, bed);
}
}
struct altEvent *altEventsFromSplices(struct splice *spliceList)
/* Create the altEvents and altPaths from the spliceList. */
{
struct splice *splice = NULL;
struct path *path = NULL;
struct altEvent *event = NULL, *eventList = NULL;
struct altPath *altPath = NULL, *altPathList = NULL;
for(splice = spliceList; splice != NULL; splice = splice->next)
{
AllocVar(event);
event->splice = splice;
for(path = splice->paths; path != NULL; path = path->next)
{
AllocVar(altPath);
altPath->score = 1;
altPath->path = path;
slAddHead(&event->altPathList, altPath);
}
slReverse(&event->altPathList);
slAddHead(&eventList, event);
}
slReverse(&eventList);
return eventList;
}
void fillInAltPathData(struct altPath *altPath, struct dMatrix *intenM,
struct dMatrix *probM)
/* Fill in the data for the probes that map to this
altPath. */
{
int i = 0;
int pCount = altPath->probeCount;
if(pCount == 0)
return;
AllocArray(altPath->expVals, pCount);
AllocArray(altPath->pVals, pCount);
AllocArray(altPath->avgExpVals, pCount);
for(i = 0; i < pCount; i++)
{
int index = hashIntValDefault(intenM->nameIndex, altPath->beds[i]->name, -1);
if(index != -1)
altPath->expVals[i] = intenM->matrix[index];
index = hashIntValDefault(probM->nameIndex, altPath->beds[i]->name, -1);
if(index != -1)
altPath->pVals[i] = probM->matrix[index];
}
}
char *altGeneNameForPSet(struct bed *bed)
/* Do some parsing of the bed name and assemble
a gene name. */
{
static char altGeneName[256]; /* static so memory char * can be returned. */
char buff[256];
char *mark = NULL;
char *extra = "EX";
*altGeneName = '\0';
safef(buff, sizeof(buff), "%s", bed->name);
mark = strchr(buff, '@');
if(mark != NULL)
{
*mark = '\0';
/* If not looking for altSet skip the extra string. */
if(stringIn("RC", bed->name))
safef(altGeneName, sizeof(altGeneName), "%s%s_RC_a_at", buff, extra);
else
safef(altGeneName, sizeof(altGeneName), "%s%s_a_at", buff, extra);
return altGeneName;
}
return NULL;
}
char *geneNameForPSet(struct bed *bed)
/* Do some parsing of the bed name and assemble
a gene name. */
{
static char geneName[256]; /* static so memory char * can be returned. */
char buff[256];
char *mark = NULL;
char *extra = "EX";
*geneName = '\0';
safef(buff, sizeof(buff), "%s", bed->name);
mark = strchr(buff, '@');
if(mark != NULL)
{
*mark = '\0';
/* If not looking for altSet skip the extra string. */
extra = "";
if(stringIn("RC", bed->name))
safef(geneName, sizeof(geneName), "%s%s_RC_a_at", buff, extra);
else
safef(geneName, sizeof(geneName), "%s%s_a_at", buff, extra);
return geneName;
}
return NULL;
}
void fillInGeneData(struct altEvent *altEvent, struct dMatrix *intenM,
struct dMatrix *probM)
/* Fill in the gene probe set data for this event. */
{
int i = 0;
struct altPath *altPath = NULL;
for(altPath = altEvent->altPathList; altPath != NULL; altPath = altPath->next)
{
if(altPath->probeCount > 0)
{
int index = -1;
int altIndex = -1;
char *geneName = NULL, *altGeneName = NULL;
int geneCount = 0;
/* Find the indexes of the possible gene sets. */
geneName = geneNameForPSet(altPath->beds[0]);
index = hashIntValDefault(intenM->nameIndex, geneName, -1);
altGeneName = altGeneNameForPSet(altPath->beds[0]);
altIndex = hashIntValDefault(intenM->nameIndex, altGeneName, -1);
/* Count how many probes we found. */
if(index != -1)
geneCount++;
if(altIndex != -1)
geneCount++;
if(geneCount > 0)
{
/* Allocate some memory. */
AllocArray(altEvent->geneBeds, geneCount);
AllocArray(altEvent->geneExpVals, geneCount);
AllocArray(altEvent->genePVals, geneCount);
AllocArray(altEvent->avgExpVals, geneCount);
altEvent->geneProbeCount = geneCount;
/* If we found the main name look it up. */
if(index != -1)
{
altEvent->geneBeds[0] = hashFindVal(bedHash, geneName);
altEvent->geneExpVals[0] = intenM->matrix[index];
index = hashIntValDefault(probM->nameIndex, geneName, -1);
if(index != -1)
altEvent->genePVals[0] = probM->matrix[index];
}
/* Try the alternative gene probe set. */
if(altIndex != -1)
{
int offSet = geneCount - 1;
altEvent->geneBeds[offSet] = hashFindVal(bedHash, altGeneName);
altEvent->geneExpVals[offSet] = intenM->matrix[altIndex];
index = hashIntValDefault(probM->nameIndex, altGeneName, -1);
if(index != -1)
altEvent->genePVals[offSet] = probM->matrix[index];
}
}
}
}
}
void fillInEventData(struct altEvent *eventList, struct dMatrix *intenM,
struct dMatrix *probM)
/* Loop through the eventList and fill in the altPaths with
data in intenM and probM. */
{
struct altEvent *event = NULL;
struct altPath *altPath = NULL;
for(event = eventList; event != NULL; event = event->next)
{
for(altPath = event->altPathList; altPath != NULL; altPath = altPath->next)
{
fillInAltPathData(altPath, intenM, probM);
}
fillInGeneData(event, intenM, probM);
}
}
double geneExpression(struct altEvent *event, int tissueIx)
/* Return maximum pval for all the gene sets. */
{
double maxInten = -1;
int geneIx = 0;
for(geneIx = 0; geneIx < event->geneProbeCount; geneIx++)
{
if(event->geneExpVals[geneIx] != NULL &&
(event->geneExpVals[geneIx][tissueIx] >= maxInten))
maxInten = event->geneExpVals[geneIx][tissueIx];
}
return maxInten;
}
double genePVal(struct altEvent *event, int tissueIx)
/* Return maximum pval for all the gene sets. */
{
double maxPval = -1;
int geneIx = 0;
for(geneIx = 0; geneIx < event->geneProbeCount; geneIx++)
{
if(event->genePVals[geneIx] != NULL &&
(event->genePVals[geneIx][tissueIx] >= maxPval))
maxPval = event->genePVals[geneIx][tissueIx];
}
return maxPval;
}
boolean geneExpressed(struct altEvent *event, int tissueIx)
/* Return TRUE if any of the gene probe sets are expressed in
this tissue. */
{
if(genePVal(event, tissueIx) >= presThresh)
return TRUE;
return FALSE;
}
void printVars(double *preLog, double *log)
{
printf("Pre-Log %.20f, Log() %.20f\n", preLog, log);
}
double pvalAltPathMaxExpressed(struct altPath *altPath, int tissueIx)
/* Return the maximum pval attained for this path. */
{
double max = 0;
int i = 0;
for(i = 0; i < altPath->probeCount; i++)
{
if(altPath->pVals[i] && altPath->pVals[i][tissueIx] >= max)
{
max = altPath->pVals[i][tissueIx];
}
}
return max;
}
double pvalAltPathCombExpressed(struct altPath *altPath, int tissueIx)
/* Combine pvals that path expressed using fisher's method and return
overall prob that expressed. */
{
double probProduct = 0;
int probCount = 0;
int i = 0;
double combination = 0;
double x = 0;
for(i = 0; i < altPath->probeCount; i++)
{
if(altPath->pVals[i])
{
/* Check for log 0, make it just log very small number. */
if(altPath->pVals[i][tissueIx] == 0)
x = log(.00000001);
else
x = log(altPath->pVals[i][tissueIx]);
probProduct += x;
probCount++;
}
}
/* If no probes return 0. */
if (probCount == 0)
return 0;
combination = gsl_cdf_chisq_P(-2.0*probProduct,2.0*probCount);
return combination;
}
boolean altPathProbesCombExpressed(struct altEvent *event, struct altPath *altPath,
int probeIx, int tissueIx)
/* Return TRUE if the path is expressed, FALSE otherwise. */
{
double combination = 1;
assert(altPath);
combination = pvalAltPathCombExpressed(altPath, tissueIx);
if(combination <= altPath->score && event->genePVals && geneExpressed(event, tissueIx))
altPath->score = combination;
if(combination <= 1 - presThresh)
return TRUE;
return FALSE;
}
boolean altPathProbesExpressed(struct altEvent *event, struct altPath *altPath,
int probeIx, int tissueIx, double *expression)
/* Return TRUE if the path is expressed, FALSE otherwise. */
{
int i = 0;
int probeCount = 0;
double **expVals = altPath->expVals;
boolean expressed = FALSE;
if (useMaxProbeSet)
{
for(i = 0; i < altPath->probeCount; i++)
{
if(altPath->pVals[i] && altPath->pVals[i][tissueIx] >= presThresh)
{
expressed = TRUE;
*expression = max(*expression, expVals[i][tissueIx]);
}
}
}
else if(useComboProbes)
{
if(altPathProbesCombExpressed(event, altPath, probeIx, tissueIx))
expressed = TRUE;
if(expVals[i] != NULL)
{
for(i = 0; i < altPath->probeCount; i++)
{
*expression += expVals[i][tissueIx];
probeCount++;
}
}
if(probeCount > 0)
*expression = *expression / probeCount;
}
else
{
if(altPath->pVals[probeIx] && altPath->pVals[probeIx][tissueIx] >= presThresh)
{
expressed = TRUE;
*expression = altPath->expVals[probeIx][tissueIx];
}
}
return expressed;
}
boolean tissueExpressed(struct altEvent *event, struct altPath *altPath,
int probeIx, int tissueIx, double *expression)
/* Return TRUE if the probeIx in tissueIx is above minimum
pVal, FALSE otherwise. */
{
int geneIx = 0;
if(!altPathProbesExpressed(event, altPath, probeIx, tissueIx, expression))
return FALSE;
if(event->genePVals && geneExpressed(event, tissueIx))
return TRUE;
return FALSE;
}
boolean altPathProbesNotExpressed(struct altEvent *event, struct altPath *altPath,
int probeIx, int tissueIx)
/* Return TRUE if the path is notExpressed, FALSE otherwise. */
{
boolean notExpressed = FALSE;
int i = 0;
if (useMaxProbeSet)
{
for(i = 0; i < altPath->probeCount; i++)
{
if(altPath->pVals[i] && altPath->pVals[i][tissueIx] <= absThresh)
notExpressed = TRUE;
}
}
else
{
if(altPath->pVals[probeIx] && altPath->pVals[probeIx][tissueIx] <= absThresh)
notExpressed = TRUE;
}
return notExpressed;
}
boolean tissueNotExpressed(struct altEvent *event, struct altPath *altPath,
int probeIx, int tissueIx)
/* Return TRUE if the probeIx in tissueIx is above minimum
pVal, FALSE otherwise. */
{
int geneIx = 0;
if(!altPathProbesNotExpressed(event, altPath, probeIx, tissueIx))
return FALSE;
return TRUE;
}
double covariance(double *X, double *Y, int count)
/* Compute the covariance for two vectors.
cov(X,Y) = E[XY] - E[X]E[Y]
page 326 Sheldon Ross "A First Course in Probability" 1998
*/
{
double cov = gsl_stats_covariance(X, 1, Y, 1, count);
return cov;
}
double correlation(double *X, double *Y, int count)
/* Compute the correlation between X and Y
correlation(X,Y) = cov(X,Y)/ squareRt(var(X)var(Y))
page 332 Sheldon Ross "A First Course in Probability" 1998
*/
{
double varX = gsl_stats_variance(X, 1, count);
double varY = gsl_stats_variance(Y, 1, count);
double covXY = gsl_stats_covariance(X, 1, Y, 1, count);
double correlation = covXY / sqrt(varX *varY);
return correlation;
}
int determineBestProbe(struct altEvent *event, struct altPath *altPath,
struct dMatrix *intenM, struct dMatrix *probM,
int pathIx)
/* Find the probe with the best correlation to the gene probe sets. */
{
double corr = 0, bestCorr = -2;
int bestIx = -1;
int bedIx = 0, geneIx = 0;
/* Check the easy case. */
if(altPath->probeCount == 1)
return 0;
/* Loop through and find the probe set with the best
correlation to the gene sets. */
for(bedIx = 0; bedIx < altPath->probeCount; bedIx++)
{
if(altPath->expVals[bedIx] == NULL)
continue;
for(geneIx = 0; geneIx < event->geneProbeCount; geneIx++)
{
if(event->geneExpVals[geneIx] == NULL)
continue;
corr = correlation(altPath->expVals[bedIx],
event->geneExpVals[geneIx], intenM->colCount);
if(corr >= bestCorr)
{
bestIx = bedIx;
bestCorr = corr;
}
}
}
return bestIx;
}
void readSelectedList(char *fileName)
/* Read in a list of gene identifiers that we want to
output. */
{
struct lineFile *lf = NULL;
struct hash *hash = newHash(12);
char *words[2];
int wordCount = ArraySize(words);
assert(fileName);
lf = lineFileOpen(fileName, TRUE);
while (lineFileChopNext(lf, words, wordCount))
{
hashAdd(hash, words[0], cloneString(words[1]));
}
lineFileClose(&lf);
outputPValHash = hash;
}
char *isSelectedProbeSet(struct altEvent *event, struct altPath *altPath)
/* Return gene name if this probe set is select for outputing
probability vector else return NULL. */
{
char *mark;
char buff[256];
struct altPath *path = NULL;
int i = 0;
for(i = 0; i < altPath->probeCount; i++)
{
if(altPath->beds[i] != NULL)
{
char *mark = strchr(altPath->beds[i]->name, '@');
if(mark != NULL)
{
char *geneName = NULL;
*mark = '\0';
if((geneName = hashFindVal(outputPValHash, altPath->beds[i]->name)) != NULL)
{
*mark = '@';
return geneName;
}
}
}
}
return NULL;
}
char * nameForType(int type)
/* Log the different types of splicing. */
{
switch (type)
{
case alt5Prime:
return "alt5Prime";
break;
case alt3Prime:
return "alt3Prime";
break;
case altCassette:
return "altCassette";
break;
case altRetInt:
return "altRetInt";
break;
case altOther:
return "altOther";
break;
case altControl:
return "altControl";
break;
case altMutExclusive:
return "altMutEx";
break;
case alt5PrimeSoft:
return "altTxStart";
break;
case alt3PrimeSoft:
return "altTxEnd";
break;
case altIdentity:
return "altIdentity";
break;
default:
errAbort("nameForType() - Don't recognize type %d", type);
}
return "error";
}
void outputPathProbabilities(struct altEvent* event, struct altPath *altPath,
struct dMatrix *intenM, struct dMatrix *probM,
int** expressed, int **notExpressed, double **expression,
int pathIx)
/* Print out a thresholded probablilty vector for clustering and visualization
in treeview. */
{
int i = 0;
FILE *out = pathProbabilitiesOut;
FILE *eOut = pathExpressionOut;
struct splice *splice = event->splice;
struct path *path = altPath->path;
char *geneName = NULL;
assert(out);
if((geneName = isSelectedProbeSet(event, altPath)) != NULL)
{
char *psName = "Error";
assert(altPath->beds[0] != NULL);
psName = altPath->beds[0]->name;
fprintf(out, "%s\t%s.%s.%s.%d", psName, geneName, nameForType(splice->type), psName, path->bpCount);
fprintf(eOut, "%s\t%s.%s.%s.%d", psName, geneName, nameForType(splice->type), psName, path->bpCount);
for(i = 0; i < probM->colCount; i++)
{
fprintf(eOut, "\t%f", expression[pathIx][i]);
if(expressed[pathIx][i])
fprintf(out, "\t2");
else if(notExpressed[pathIx][i])
fprintf(out, "\t-2");
else
fprintf(out, "\t0");
}
fprintf(out, "\n");
fprintf(eOut, "\n");
}
}
boolean altPathExpressed(struct altEvent *event, struct altPath *altPath,
struct dMatrix *intenM, struct dMatrix *probM,
int **expressed, int **notExpressed, double **expression,
int pathIx)
/* Fill in the expression matrix for this path. */
{
int bestProbeIx = 0;
int tissueIx = 0;
int total = 0;
/* Quick check to see if there are any
probes at all. */
if(altPath->probeCount == 0)
return FALSE;
bestProbeIx = determineBestProbe(event, altPath, intenM, probM, pathIx);
/* Loop through the tissues to see if they are expressed. */
if(bestProbeIx == -1)
return FALSE;
for(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)
{
double e = -1;
if(tissueExpressed(event, altPath, bestProbeIx, tissueIx, &e))
{
expressed[pathIx][tissueIx]++;
total++;
}
else if(tissueNotExpressed(event, altPath, bestProbeIx, tissueIx))
{
notExpressed[pathIx][tissueIx]++;
}
expression[pathIx][tissueIx] = e;
}
return total > 0;
}
double expressionAverage(struct altPath *altPath, int tissueIx)
/* Return the average expression for all probe sets matched
to this path in this tissue. */
{
double pathExp = 0.0;
int pCount = 0.0;
int probeIx = 0;
for(probeIx = 0; probeIx < altPath->probeCount; probeIx++)
{
if(altPath->expVals[probeIx])
{
pathExp += altPath->expVals[probeIx][tissueIx];
pCount++;
}
}
if(pCount == 0)
return -1;
pathExp = pathExp / pCount;
return pathExp;
}
char *nameForSplice(struct splice *splice, struct altPath *namePath)
/* Return a unique name for this splicing event. Memory is owned by
this function and will be overwritten each time this function is
called. */
{
static char buff[256];
safef(buff, sizeof(buff), "%s:%s:%s:%s:%s:%s:%d:%d",
splice->name, refSeqForPSet(namePath->beds[0]->name), nameForType(splice->type), namePath->beds[0]->name,
splice->strand, splice->tName, splice->tStart, splice->tEnd);
return buff;
}
double calculateFlipScore(struct altEvent *event, struct altPath *altPath,
char *name, struct dMatrix *probM,
boolean *isBrain, boolean doAll, int *incBrain, int *skipBrain)
/* Calculate |(#times skip > include) - (#times skip < include)|/totalTissues */
{
struct altPath *skip = NULL, *include = NULL;
int tissueIx = 0;
int brainCount = 0;
int notBrainCount = 0;
int tissueCount = 0;
*incBrain = 0;
*skipBrain = 0;
assert(event);
skip = event->altPathList;
include = event->altPathList->next;
assert(probM);
assert(probM->colCount > 0);
/* Use the sortScore hash if it is setup. */
if(sortScoreHash != NULL)
{
double result = sortScoreForSplice(nameForSplice(event->splice, altPath));
if (result > 0)
*incBrain = 1;
else if(result < 0)
*skipBrain = 1;
return result;
}
/* Else do some calculations. */
for(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)
{
if(geneExpressed(event, tissueIx) || doAll)
{
double skipI = expressionAverage(skip, tissueIx);
double incI = expressionAverage(include, tissueIx);
if(incI >= skipI && skipI >= 0 && incI >= 0)
{
if(isBrain[tissueIx])
{
brainCount++;
(*incBrain)++;
}
else
notBrainCount++;
tissueCount++;
}
else if(skipI >= 0 && incI >= 0)
{
if(isBrain[tissueIx])
{
brainCount--;
(*skipBrain)++;
}
else
notBrainCount--;
tissueCount++;
}
}
}
/* If no data, then set score to worst val: 0 */
if(tissueCount == 0)
return 0;
else
{
double brainScore = 0;
double nonBrainScore = 0;
brainScore = (double) brainCount / tissueCount;
nonBrainScore = (double) notBrainCount / tissueCount;
return fabs(brainScore - nonBrainScore);
}
return 0;
}
boolean brainSpecific(struct altEvent *event, struct altPath *path, int pathIx,
int **expressed, int **notExpressed,
int pathCount, struct dMatrix *probM)
/* Output the event if it is alt-expressed and brain
specific. */
{
int tissueIx = 0;
int brainTissues = 0;
int otherTissues = 0;
int geneBrainTissues = 0;
int geneOtherTissues = 0;
int brainIx = 0;
int incBrain = 0, skipBrain =0;
static int tissueCount = 0;
static char *brainTissuesToChop = NULL;
static char *brainTissuesStrings[256];
static boolean initDone = FALSE;
/* Setup array of what is brain and what isn't. */
if (!initDone)
{
brainTissuesToChop = cloneString(optionVal("brainTissues","cerebellum,cerebral_hemisphere,cortex,hind_brain,medial_eminence,olfactory_bulb,pinealgland,thalamus"));
if(ArraySize(isBrainTissue) < probM->colCount)
errAbort("Can only handle up to %d columns, %d is too many",
ArraySize(isBrainTissue), probM->colCount);
/* Set everthing to FALSE. */
for(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)
isBrainTissue[tissueIx] = FALSE;
/* Set brain tissue to TRUE. */
tissueCount = chopByChar(brainTissuesToChop, ',', brainTissuesStrings, ArraySize(brainTissuesStrings));
for(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)
for(brainIx = 0; brainIx < tissueCount; brainIx++)
if(stringIn(brainTissuesStrings[brainIx], probM->colNames[tissueIx]))
isBrainTissue[tissueIx] = TRUE;
initDone = TRUE;
}
/* If we have pvals specified by the user use them instead. */
if(splicePValsHash != NULL)
{
double d = 0;
if (path->probeCount > 0)
d = pvalForSplice(nameForSplice(event->splice, path));
else
return FALSE;
if(d <= pvalThresh)
return TRUE;
else
return FALSE;
}
/* Otherwise use the routines here. */
for(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)
{
if(expressed[pathIx] != NULL &&
expressed[pathIx][tissueIx])
{
if(isBrainTissue[tissueIx])
brainTissues++;
else
otherTissues++;
}
else if(brainSpecificStrict &&
notExpressed[pathIx] != NULL &&
!notExpressed[pathIx][tissueIx])
{
if(!isBrainTissue[tissueIx])
otherTissues++;
}
if(geneExpressed(event, tissueIx))
{
if(isBrainTissue[tissueIx])
geneBrainTissues++;
else
geneOtherTissues++;
}
}
if (otherTissues == 0 && rainTissues >= tissueExpThresh && geneOtherTissues >= tissueExpThresh)
return TRUE;
return FALSE;
}
boolean tissueSpecific(struct altEvent *event, int pathIx, int targetTissue,
int **expressed, int **notExpressed,
int pathCount, struct dMatrix *probM)
/* Output the event if it is alt-expressed and brain
specific. */
{
int tissueIx = 0;
int specificTissues = 0;
int otherTissues = 0;
int geneSpecificTissues = 0;
int geneOtherTissues = 0;
for(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)
{
if(expressed[pathIx] != NULL &&
expressed[pathIx][tissueIx])
{
if(tissueIx == targetTissue)
specificTissues++;
else
otherTissues++;
}
else if(tissueSpecificStrict &&
notExpressed[pathIx] != NULL &&
!notExpressed[pathIx][tissueIx])
{
if(tissueIx != targetTissue)
otherTissues++;
}
if(geneExpressed(event, tissueIx))
{
if(tissueIx == targetTissue)
geneSpecificTissues++;
else
geneOtherTissues++;
}
}
if (otherTissues == 0 && specificTissues >= tissueExpThresh && geneOtherTissues >= tissueExpThresh)
return TRUE;
return FALSE;
}
void fillInSequences(struct altEvent *event, struct path *path,
struct dnaSeq **upSeq, struct dnaSeq **downSeq, struct dnaSeq **exonSeq,
struct bed **upSeqBed, struct bed **downSeqBed)
/* Fill in the sequences from the path. 200 from intron, 5bp from
exon. */
{
int firstSplice = -1;
int secondSplice = -1;
int i = 0;
struct splice *splice = event->splice;
int *vPos = splice->vPositions;
unsigned char*vTypes = splice->vTypes;
int vC = path->vCount;
int *verts = path->vertices;
int exonOffset = 0;
int intronOffset = 100;
/* Want first exon in order of transcription. */
if(sameString(splice->strand,"+"))
{
for(i = 0; i < vC -1; i++)
if(validVertex(splice, verts[i], verts[i+1]) &&
pathEdgeTypeValid(splice, verts[i], verts[i+1]) == ggExon)
{
firstSplice = vPos[verts[i]];
secondSplice = vPos[verts[i+1]];
break;
}
}
else
{
for(i = vC-1; i > 0; i--)
if(validVertex(splice, verts[i-1], verts[i]) &&
pathEdgeTypeValid(splice, verts[i-1], verts[i]) == ggExon)
{
firstSplice = vPos[verts[i-1]];
secondSplice = vPos[verts[i]];
break;
}
}
if(firstSplice < 0 || secondSplice < 0)
errAbort("Problem with event %s at %s:%d-%d doesn't have an exon",
splice->name, splice->tName, splice->tStart, splice->tEnd);
AllocVar(*upSeqBed);
AllocVar(*downSeqBed);
/* Construct the beds. */
(*upSeqBed)->name = cloneString(splice->name);
(*upSeqBed)->chrom = cloneString(splice->tName);
safef((*upSeqBed)->strand, sizeof((*upSeqBed)->strand), "%s", splice->strand);
(*upSeqBed)->chromStart = firstSplice - intronOffset;
(*upSeqBed)->chromEnd = firstSplice + exonOffset;
(*upSeqBed)->score = splice->type;
(*downSeqBed)->name = cloneString(splice->name);
(*downSeqBed)->chrom = cloneString(splice->tName);
safef((*downSeqBed)->strand, sizeof((*downSeqBed)->strand), "%s", splice->strand);
(*downSeqBed)->chromStart = secondSplice - exonOffset;
(*downSeqBed)->chromEnd = secondSplice + intronOffset;
(*downSeqBed)->score = splice->type;
/* Get the sequences. */
*upSeq = hSeqForBed((*upSeqBed));
*downSeq = hSeqForBed((*downSeqBed));
*exonSeq = hChromSeq(splice->tName , firstSplice, secondSplice);
if (sameString(splice->strand, "-"))
reverseComplement((*exonSeq)->dna, (*exonSeq)->size);
/* If on negative strand swap up and down. */
if(sameString(splice->strand, "-"))
{
struct dnaSeq *tmpSeq = NULL;
struct bed *tmpBed = NULL;
/* Swap beds. */
tmpBed = *upSeqBed;
*upSeqBed = *downSeqBed;
*downSeqBed = tmpBed;
/* Swap sequences. */
tmpSeq = *upSeq;
*upSeq = *downSeq;
*downSeq = tmpSeq;
}
}
void makeJunctMdbGenericLink(struct splice *js, struct dyString *buff, char *name)
{
int offSet = 100;
int i = 0;
dyStringClear(buff);
dyStringPrintf(buff,"<a target=\"plots\" href=\"http://mdb1-sugnet.gi.ucsc.edu/cgi-bin/"
"mdbSpliceGraph?mdbsg.calledSelf=on&coordString=%s:%c:%s:%d-%d&mdbsg.cs=%d"
"&mdbsg.ce=%d&mdbsg.expName=%s&mdbsg.probeSummary=on&mdbsg.toScale=on\">",
"mm2", js->strand[0], js->tName, js->tStart, js->tEnd,
js->tStart - offSet, js->tEnd + offSet, "AffyMouseSplice1-02-2004");
dyStringPrintf(buff, "%s", name);
dyStringPrintf(buff, "</a> ");
}
struct bed *phastConForRegion(char *table, char *chrom, int chromStart, int chromEnd)
/* Load the beds for the region specified in the table specified. */
{
struct sqlConnection *conn = hAllocConn2();
struct sqlResult *sr = NULL;
struct bed *conBed = NULL, *conBedList = NULL;
int rowOffset = 0;
char **row = NULL;
sr = hRangeQuery(conn, table, chrom, chromStart, chromEnd,
NULL, &rowOffset);
while((row = sqlNextRow(sr)) != NULL)
{
conBed = bedLoad5(row+rowOffset);
slAddHead(&conBedList, conBed);
}
sqlFreeResult(&sr);
hFreeConn2(&conn);
slReverse(&conBedList);
return conBedList;
}
struct bed *bed12ForRegion(char *table, char *chrom, int chromStart, int chromEnd, char strand)
/* Load the beds for the region specified in the table specified. */
{
struct sqlConnection *conn = hAllocConn2();
struct sqlResult *sr = NULL;
struct bed *bed = NULL, *bedList = NULL;
int rowOffset = 0;
char **row = NULL;
sr = hRangeQuery(conn, table, chrom, chromStart, chromEnd,
NULL, &rowOffset);
while((row = sqlNextRow(sr)) != NULL)
{
bed = bedLoad12(row+rowOffset);
if(bed->strand[0] == strand)
slAddHead(&bedList, bed);
else
bedFree(&bed);
}
sqlFreeResult(&sr);
hFreeConn2(&conn);
slReverse(&bedList);
return bedList;
}
double gcPercentForRegion(char *chrom, int chromStart, int chromEnd, char *db)
/* Return gcPercent for region. */
{
struct dnaSeq *seq = NULL;
int hist[4];
double percent = 0;
if(newDb != NULL && sameString(db, newDb))
seq = hChromSeq2(chrom, chromStart, chromEnd);
else
seq = hChromSeq(chrom, chromStart, chromEnd);
dnaBaseHistogram(seq->dna, seq->size, hist);
percent = (1.0 *hist[G_BASE_VAL]+hist[C_BASE_VAL])/seq->size;
dnaSeqFree(&seq);
return percent;
}
void findExonNumForRegion(char *chrom, int chromStart, int chromEnd, char strand,
int *exonNum, int *exonCount)
/* Find out which exon this region overlaps and fill in the exonNum and exonCount. */
{
struct bed *bed = NULL, *bedList = NULL, *goodBed = NULL;
int blockIx = 0;
int *starts = NULL, *sizes = NULL;
int cs = 0, ce = 0;
*exonNum = -1;
*exonCount = -1;
bedList = bed12ForRegion("agxBed", chrom, chromStart, chromEnd, strand);
for(bed = bedList; bed != NULL; bed = bed->next)
{
if(bed->strand[0] != strand)
continue;
cs = bed->chromStart;
ce = bed->chromEnd;
starts = bed->chromStarts;
sizes = bed->blockSizes;
for(blockIx = 0; blockIx < bed->blockCount; blockIx++)
{
int bStart = cs+starts[blockIx];
int bEnd = cs+starts[blockIx]+sizes[blockIx];
if(rangeIntersection(chromStart, chromEnd, bStart, bEnd ) > 0)
{
if(goodBed == NULL)
{
goodBed = bed;
*exonNum = blockIx;
*exonCount = bed->blockCount;
}
break;
}
}
}
if(strand == '-' && *exonNum != -1)
{
*exonNum = *exonCount - *exonNum;
}
bedFreeList(&bedList);
}
double percentIntronBasesOverlappingConsSide(char *table, char *chrom, int chromStart, int chromEnd, boolean upStream)
/* Percentage of intron bases that overlap a phastCons element. */
{
int intronOffset = 100, overlap = 0;
double percent = 0;
if(newDb != NULL && hTableExists2(table))
{
struct bed *upstream = NULL;
struct bed *bed = NULL;
if(upStream == TRUE)
upstream = phastConForRegion(table, chrom, chromStart-intronOffset, chromStart);
else
upstream = phastConForRegion(table, chrom, chromEnd, chromEnd + intronOffset);
for(bed = upstream; bed != NULL; bed = bed->next)
{
if(upStream == TRUE)
{
overlap += positiveRangeIntersection(chromStart-intronOffset, chromStart,
bed->chromStart, bed->chromEnd);
}
else
{
overlap += positiveRangeIntersection(chromEnd, chromEnd+intronOffset,
bed->chromStart, bed->chromEnd);
}
}
percent = (double)overlap / (intronOffset);
bedFreeList(&upstream);
}
return percent;
}
double percentIntronBasesOverlappingCons(char *table, char *chrom, int chromStart, int chromEnd)
/* Percentage of intron bases that overlap a phastCons element. */
{
int intronOffset = 100, overlap = 0;
double percent = 0;
if(newDb != NULL && hTableExists2(table))
{
struct bed *upstream = phastConForRegion(table, chrom, chromStart-intronOffset, chromStart);
struct bed *downstream = phastConForRegion(table, chrom, chromEnd, chromEnd + intronOffset);
struct bed *bed = NULL;
for(bed = upstream; bed != NULL; bed = bed->next)
{
overlap += positiveRangeIntersection(chromStart-intronOffset, chromStart,
bed->chromStart, bed->chromEnd);
}
for(bed = downstream; bed != NULL; bed = bed->next)
{
overlap += positiveRangeIntersection(chromEnd, chromEnd+intronOffset,
bed->chromStart, bed->chromEnd);
}
percent = (double)overlap / (2 * intronOffset);
bedFreeList(&upstream);
bedFreeList(&downstream);
}
return percent;
}
void printLinks(struct altEvent *event)
/* Loop through and print each splicing event to web page. */
{
struct splice *s = NULL;
struct path *lastPath = NULL;
struct splice *splice = event->splice;
struct altPath *altPath = NULL, *namePath = NULL;
char *brainDiffDir = optionVal("plotDir","brainDiffPlots.9");
char *fileSuffix = optionVal("fileSuffix", "png");
char *chrom = NULL;
char strand;
int chromStart = 0, chromEnd = 0;
int diff = -1;
char *useDb = db;
char *newDb = optionVal("newDb", NULL);
boolean overlapsPhasCons = FALSE;
double overlapPercent = 0;
struct dyString *buff = NULL;
char *skipPSet = NULL;
int i = 0;
boolean muscleOn = optionExists("muscleOn");
/* struct altPath *incPath = NULL, *skipPath = NULL; */
if(splice->paths == NULL || splice->type == altControl)
return;
for (altPath = event->altPathList; altPath != NULL; altPath = altPath->next)
{
struct bed *bed = NULL;
double score = event->flipScore;
char upPos[256];
char downPos[256];
/* If we're dealing with a cassette or other limit to 2 paths
use skip/include path model. */
if (onlyTwoPaths(event))
{
namePath = event->altPathList;
altPath = event->altPathList->next;
diff = abs(splice->paths->bpCount - splice->paths->next->bpCount);
}
else
{
diff = altPath->path->bpCount;
namePath = altPath;
}
/* Check to make sure that we have probes and that this
path is brain specific. */
if (namePath->probeCount < 1 || event->geneProbeCount < 1)
continue;
if(splicePValsHash != NULL)
{
double d = 0;
d = pvalForSplice(nameForSplice(event->splice,namePath));
if(d > pvalThresh)
continue;
event->pVal = d;
}
if(sortScoreHash != NULL)
score = sortScoreForSplice(nameForSplice(event->splice, namePath));
bed = pathToBed(altPath->path, event->splice, -1, -1, FALSE);
chrom = cloneString(bed->chrom);
chromStart = bed->chromStart;
chromEnd = bed->chromEnd;
strand = bed->strand[0];
if(newDb != NULL)
{
if(liftOverCoords(&chrom, &chromStart, &chromEnd, &strand))
useDb = newDb;
}
/* overlapPercent = percentIntronBasesOverlappingCons(chrom, chromStart,chromEnd); */
buff = newDyString(256);
/* if(brainSpPSetOut != NULL) */
/* { */
/* skipPath = namePath; */
/* skipPSet = skipPath->beds[0]->name; */
/* if(onlyTwoPaths(event)) */
/* incPath = event->altPathList->next; */
/* else */
/* incPath = NULL; */
/* fprintf(brainSpPSetOut, "%s\t", refSeqForPSet(skipPSet)); */
/* fprintf(brainSpPSetOut, "%s\t", skipPSet); */
/* if(incPath != NULL) */
/* { */
/* fprintf(brainSpPSetOut, "%d\t", incPath->probeCount); */
/* for(i = 0; i < incPath->probeCount; i++) */
/* { */
/* fprintf(brainSpPSetOut, "%s,", incPath->beds[i]->name); */
/* } */
/* } */
/* else */
/* { */
/* fprintf(brainSpPSetOut, "%d\t", event->geneProbeCount); */
/* for(i = 0; i < event->geneProbeCount; i++) */
/* { */
/* fprintf(brainSpPSetOut, "%s,", event->geneBeds[i]->name); */
/* } */
/* } */
/* fprintf(brainSpPSetOut, "\t%d\t", event->geneProbeCount); */
/* for(i = 0; i < event->geneProbeCount; i++) */
/* { */
/* fprintf(brainSpPSetOut, "%s,", event->geneBeds[i]->name); */
/* } */
/* fprintf(brainSpPSetOut, "\n"); */
/* } */
fprintf(brainSpTableHtmlOut, "<tr><td>");
if(overlapsPhasCons)
fprintf(brainSpTableHtmlOut, "<span style='color:red;'> * </span>");
fprintf(brainSpTableHtmlOut, "<a target=\"browser\" "
"href=\"http://%s/cgi-bin/hgTracks?db=%s&position=%s:%d-%d&hgt.motifs=TCATT%%2CTCATC%%2CGGGGG%%2CCTCTCT%%2CGCATG%%2CTCCTT\",>", browserName,
useDb, chrom, chromStart-100, chromEnd+100);
fprintf(brainSpTableHtmlOut,"%s </a><font size=-1>%s</font>\n",
refSeqForPSet(event->geneBeds[0]->name), useDb);
safef(upPos, sizeof(upPos), "%s:%d-%d", chrom, chromStart-95, chromStart+5);
safef(downPos, sizeof(downPos), "%s:%d-%d", chrom, chromEnd-5, chromEnd+95);
fprintf(brainSpTableHtmlOut, "<a target=\"browser\" "
"href=\"http://%s/cgi-bin/hgTracks?db=%s&position=%s&complement=%d&hgt.motifs=TCATT%%2CTCATC%%2CGGGGG%%2CCTCTCT%%2CGCATG%%2CTCCTT\">[u]</a>",
browserName, useDb, strand == '+' ? upPos : downPos,
strand == '-' ? 1 : 0);
fprintf(brainSpTableHtmlOut, "<a target=\"browser\" "
"href=\"http://%s/cgi-bin/hgTracks?db=%s&position=%s&complement=%d&hgt.motifs=TCATT%%2CTCATC%%2CGGGGG%%2CCTCTCT%%2CGCATG%%2CTCCTT\">[d]</a>",
browserName, useDb, strand == '+' ? downPos : upPos,
strand == '-' ? 1 : 0);
fprintf(brainSpTableHtmlOut,
"<a target=\"plots\" href=\"http://%s/cgi-bin/spliceProbeVis?skipPName=%s%s\">[p]</a>",
browserName, namePath->beds[0]->name, muscleOn ? "&muscle=on" : "");
fprintf(brainSpTableHtmlOut,
"<a target=\"plots\" href=\"http://%s/cgi-bin/spliceProbeVis?skipPName=%s&pdf=on%s\">[pdf]</a>",
browserName, namePath->beds[0]->name, muscleOn ? "&muscle=on" : "");
fprintf(brainSpTableHtmlOut,
"<a target=\"plots\" href=\"./%s/%s:%s:%s:%s:%s:%s:%d:%d.%s\">[f]</a>",
brainDiffDir,
splice->name, refSeqForPSet(namePath->beds[0]->name),
nameForType(splice->type), namePath->beds[0]->name,
splice->strand, splice->tName, splice->tStart, splice->tEnd, fileSuffix);
/* makeJunctMdbGenericLink(splice, buff, "[p]"); */
/* fprintf(brainSpTableHtmlOut, "%s", buff->string); */
fprintf(brainSpTableHtmlOut, "<font size=-1>(%5.2f, %s, %d, %d)</font>", event->percentUltra, nameForType(splice->type), diff, diff % 3);
fprintf(brainSpTableHtmlOut, "<font size=-2>");
if (altPath->motifUpCounts != NULL)
{
fprintf(brainSpTableHtmlOut, "[");
for (i = 0; i < bindSiteCount; i++)
fprintf(brainSpTableHtmlOut, " %d", altPath->motifUpCounts[i]);
fprintf(brainSpTableHtmlOut, "] ");
fprintf(brainSpTableHtmlOut, "[");
for (i = 0; i < bindSiteCount; i++)
fprintf(brainSpTableHtmlOut, " %d", altPath->motifInsideCounts[i]);
fprintf(brainSpTableHtmlOut, "] ");
fprintf(brainSpTableHtmlOut, "[");
for (i = 0; i < bindSiteCount; i++)
fprintf(brainSpTableHtmlOut, " %d", altPath->motifDownCounts[i]);
fprintf(brainSpTableHtmlOut, "] ");
}
fprintf(brainSpTableHtmlOut, "</font>\n");
fprintf(brainSpTableHtmlOut, " </td>");
fprintf(brainSpTableHtmlOut,"<td>%.4f</td></tr>\n", score);
dyStringFree(&buff);
}
}
double consForIntCoords(char *chrom, int intStart, int intEnd, boolean doLift)
/* Return the conservation for the intron specified by intStart, intEnd. */
{
char strand = '+';
char *startChrom = cloneString(chrom);
char *endChrom = cloneString(chrom);
double cons = 0;
int overlap = 0;
int chromStart = intStart - 10, chromEnd = intEnd + 10;
struct bed *bedList = NULL, *bed = NULL;
if(doLift && newDb != NULL)
{
/* Lift over each end seperately so as to ignore changes
in assembly in the middle. */
liftOverCoords(&startChrom, &chromStart, &intStart, &strand);
liftOverCoords(&endChrom, &intEnd, &chromEnd, &strand);
}
if(intStart < intEnd && newDb != NULL)
{
bedList = phastConForRegion("phastConsOrig90", startChrom, intStart, intEnd);
for(bed = bedList; bed != NULL; bed = bed->next)
{
overlap += positiveRangeIntersection(intStart, intEnd,
bed->chromStart, bed->chromEnd);
}
cons = (double)overlap / (intEnd - intStart);
bedFreeList(&bedList);
}
else
cons = 0;
return cons;
}
void fillInStatsForEvent(struct valuesMat *vm, char *name, char *chrom, int intStart,
int exonStart, int exonEnd, int intEnd, char strand,
enum altSpliceType type)
/* Fill in stats for the exon specified by intStart->exonStart->exonEnd->intEnd. */
{
char *skipPSet = NULL;
char buff[256];
double percentPhastCons = 0;
double upIntCons = 0;
double downIntCons = 0;
double ultraCons = 0;
int exonCount = -1, exonNum = -1;
double cons = 0;
/* Add event to our list for later sorting, etc. */
ultraCons = cons = percentIntronBasesOverlappingConsSide("phastConsOrig90", chrom, exonStart,exonEnd, TRUE);
/* Percent ultra. */
safef(buff, sizeof(buff), "%.4f", cons);
vmAddVal(vm, name, "intronUltraConsUpStream", buff);
cons = percentIntronBasesOverlappingConsSide("phastConsOrig90", chrom, exonStart,exonEnd, FALSE);
ultraCons += cons;
/* Percent ultra. */
safef(buff, sizeof(buff), "%.4f", cons);
vmAddVal(vm, name, "intronUltraConsDownStream", buff);
ultraCons = ultraCons / 2;
/* Percent ultra. */
safef(buff, sizeof(buff), "%.4f", ultraCons);
vmAddVal(vm, name, "intronUltraCons", buff);
/* Percent conserved. */
percentPhastCons = percentIntronBasesOverlappingCons("phastConsElements", chrom, exonStart, exonEnd);
safef(buff, sizeof(buff), "%.4f", percentPhastCons);
vmAddVal(vm, name, "intronCons", buff);
/* Name of splicing event. */
vmAddVal(vm, name, "type", nameForType(type));
/* Size in bp of splicing event. */
safef(buff, sizeof(buff), "%d", exonEnd - exonStart);
vmAddVal(vm, name, "bpDiff", buff);
/* Intron size. */
safef(buff, sizeof(buff), "%d", intEnd - intStart);
vmAddVal(vm, name, "intronSize", buff);
/* Genome Position. */
safef(buff, sizeof(buff), "%s:%d-%d", chrom, intStart, intEnd);
vmAddVal(vm, name, "mm2.genomePos", buff);
/* Genome Position. */
safef(buff, sizeof(buff), "%s:%d-%d", chrom, exonStart, exonEnd);
vmAddVal(vm, name, "mm5.exonPos", buff);
/* Strand. */
safef(buff, sizeof(buff), "%c", strand);
vmAddVal(vm, name, "strand", buff);
/* GC Percent. */
safef(buff, sizeof(buff), "%.4f", gcPercentForRegion(chrom, exonStart, exonEnd, newDb));
vmAddVal(vm, name, "gcPercent", buff);
/* Upstream intron conservation. */
upIntCons = consForIntCoords(chrom, intStart, exonStart, FALSE );
downIntCons = consForIntCoords(chrom, exonEnd, intEnd, FALSE);
if(strand == '-')
{
double dTmp = upIntCons;
upIntCons = downIntCons;
downIntCons = dTmp;
}
safef(buff, sizeof(buff), "%g", upIntCons);
vmAddVal(vm, name, "upFullIntronCons", buff);
safef(buff, sizeof(buff), "%g", downIntCons);
vmAddVal(vm, name, "downFullIntronCons", buff);
/* Add some values about expresion. */
findExonNumForRegion(chrom, exonStart, exonEnd, strand, &exonNum, &exonCount);
safef(buff, sizeof(buff), "%d", exonNum);
vmAddVal(vm, name, "exonNum", buff);
safef(buff, sizeof(buff), "%d", exonCount);
vmAddVal(vm, name, "exonCount", buff);
}
void writeOutOverlappingUltra(FILE *out, FILE *bedOut, char *chrom,
int chromStart, int chromEnd, char strand)
/* Write out the sequences for phastCons elements that overlap the region. */
{
struct bed *bedList = NULL, *bed = NULL;
struct dnaSeq *seq = NULL;
char buff[256];
bedList = phastConForRegion("phastConsOrig90", chrom, chromStart, chromEnd);
for(bed = bedList; bed != NULL; bed = bed->next)
{
seq = hChromSeq2(bed->chrom, bed->chromStart, bed->chromEnd);
if(strand == '-')
reverseComplement(seq->dna, seq->size);
safef(buff, sizeof(buff), "%s.%s:%d-%d", bed->name, chrom, chromStart, chromEnd);
safef(bed->strand, sizeof(bed->strand), "%c", strand);
faWriteNext(out, buff, seq->dna, seq->size);
dnaSeqFree(&seq);
bedTabOutN(bed, 6, bedOut);
}
bedFreeList(&bedList);
}
void outputBrainSpecificEvents(struct altEvent *event, int **expressed, int **notExpressed,
int pathCount, struct dMatrix *probM)
/* Output the event if it is alt-expressed and brain
specific. */
{
struct dnaSeq *upSeq = NULL;
struct dnaSeq *downSeq = NULL;
struct dnaSeq *exonSeq = NULL;
struct bed *pathBed = NULL;
struct bed *upSeqBed = NULL;
struct bed *downSeqBed = NULL;
struct slRef *brainEvent = NULL;
boolean lifted = FALSE;
int i = 0;
int pathIx = 0;
struct altPath *altPath = NULL;
boolean brainSpecificEvent = FALSE;
struct splice *splice = event->splice;
boolean eventAdded = FALSE;
for(altPath = event->altPathList; altPath != NULL; altPath = altPath->next, pathIx++)
{
char *chrom = NULL;
int chromStart = 0;
int chromEnd = 0;
int intronEnd = 0;
int intronStart = 0;
int intronDummy = 0;
char strand;
char *skipPSet = NULL;
struct altPath *skipPath = NULL;
struct altPath *incPath = NULL;
struct altPath *namePath = NULL;
char buff[256];
double percentPhastCons = 0;
double upIntCons = 0;
double downIntCons = 0;
double cons = 0, ultraCons = 0;
double flipScore = 0;
double maxProb = 0;
int incBrain = 0, skipBrain =0;
int exonCount = -1, exonNum = -1;
if(onlyTwoPaths(event) && altPath == event->altPathList->next)
namePath = event->altPathList;
else
namePath = altPath;
if(!brainSpecific(event, namePath, pathIx, expressed, notExpressed, pathCount, probM) ||
splice->type == altOther)
{
continue;
}
/* check to make sure this path includes some sequence. */
pathBed = pathToBed(altPath->path, event->splice, -1, -1, FALSE);
if(pathBed == NULL && splice->type != alt5PrimeSoft && splice->type != alt3PrimeSoft)
continue;
if (!eventAdded)
{
/* Add event to our list for later sorting, etc. */
AllocVar(brainEvent);
brainEvent->val = event;
slAddHead(&brainSpEvents, brainEvent);
eventAdded = TRUE;
}
if(sortScoreHash != NULL && namePath->probeCount > 0)
event->flipScore = sortScoreForSplice(nameForSplice(event->splice, namePath));
/* Rest of the logging functions are only for cassettes with probes. */
if(splice->type != altCassette || event->altPathProbeCount < 2)
{
continue;
}
/* Print out the cassette connected to the proximal exons. */
if(brainSpPathEndsBedOut)
{
struct bed *longBed = pathToBed(altPath->path, event->splice, -1, -1, TRUE);
assert(longBed);
bedTabOutN(longBed, 12, brainSpPathEndsBedOut);
bedFree(&longBed);
}
/* Lets do some stat recording. */
skipPath = event->altPathList;
skipPSet = skipPath->beds[0]->name;
incPath = event->altPathList->next;
/* if(brainSpPSetOut != NULL) */
/* { */
/* fprintf(brainSpPSetOut, "%s\t", refSeqForPSet(skipPSet)); */
/* fprintf(brainSpPSetOut, "%s\t", skipPSet); */
/* fprintf(brainSpPSetOut, "%d\t", incPath->probeCount); */
/* for(i = 0; i < incPath->probeCount; i++) */
/* { */
/* fprintf(brainSpPSetOut, "%s,", incPath->beds[i]->name); */
/* } */
/* fprintf(brainSpPSetOut, "\t%d\t", event->geneProbeCount); */
/* for(i = 0; i < event->geneProbeCount; i++) */
/* { */
/* fprintf(brainSpPSetOut, "%s,", event->geneBeds[i]->name); */
/* } */
/* fprintf(brainSpPSetOut, "\n"); */
/* } */
chrom = cloneString(pathBed->chrom);
chromStart = pathBed->chromStart;
chromEnd = pathBed->chromEnd;
intronStart = splice->tStart;
intronEnd = splice->tEnd;
strand = pathBed->strand[0];
if(newDb != NULL)
{
lifted = liftOverCoords(&chrom, &chromStart, &chromEnd, &strand);
}
/* Add event to our list for later sorting, etc. */
ultraCons = cons = percentIntronBasesOverlappingConsSide("phastConsOrig90", chrom, chromStart,chromEnd, TRUE);
/* Percent ultra. */
safef(buff, sizeof(buff), "%.4f", cons);
vmAddVal(brainSpecificValues, skipPSet, "intronUltraConsUpStream", buff);
cons = percentIntronBasesOverlappingConsSide("phastConsOrig90", chrom, chromStart,chromEnd, FALSE);
ultraCons += cons;
/* Percent ultra. */
safef(buff, sizeof(buff), "%.4f", cons);
vmAddVal(brainSpecificValues, skipPSet, "intronUltraConsDownStream", buff);
ultraCons = ultraCons / 2;
event->percentUltra = ultraCons;
/* event->percentUltra = percentIntronBasesOverlappingCons("phastConsOrig90", chrom, chromStart,chromEnd); */
if(event->percentUltra >= .20)
intronsConserved++;
intronsConsCounted++;
/* Percent ultra. */
safef(buff, sizeof(buff), "%.4f", event->percentUltra);
vmAddVal(brainSpecificValues, skipPSet, "intronUltraCons", buff);
/* If we have phastCons data we want it to end up being printed. */
if (phastConsHash != NULL)
event->percentUltra = phastConsForSplice(skipPSet);
/* Percent conserved. */
percentPhastCons = percentIntronBasesOverlappingCons("phastConsElements", chrom, chromStart,chromEnd);
safef(buff, sizeof(buff), "%.4f", percentPhastCons);
vmAddVal(brainSpecificValues, skipPSet, "intronCons", buff);
/* Name of splicing event. */
vmAddVal(brainSpecificValues, skipPSet, "type", nameForType(splice->type));
/* Size in bp of splicing event. */
safef(buff, sizeof(buff), "%d", incPath->path->bpCount - skipPath->path->bpCount);
vmAddVal(brainSpecificValues, skipPSet, "bpDiff", buff);
/* Modulous 3. */
safef(buff, sizeof(buff), "%d", (incPath->path->bpCount - skipPath->path->bpCount) % 3);
vmAddVal(brainSpecificValues, skipPSet, "mod3", buff);
/* Intron size. */
safef(buff, sizeof(buff), "%d", splice->tEnd - splice->tStart);
vmAddVal(brainSpecificValues, skipPSet, "intronSize", buff);
/* Gene Name. */
if(psToRefGeneHash != NULL)
vmAddVal(brainSpecificValues, skipPSet, "geneName", refSeqForPSet(skipPSet));
/* Known Gene. */
if(psToKnownGeneHash != NULL)
vmAddVal(brainSpecificValues, skipPSet, "knownGene", knownGeneForPSet(skipPSet));
/* Chrom. */
safef(buff, sizeof(buff), "%s", splice->tName);
vmAddVal(brainSpecificValues, skipPSet, "mm2.chrom", buff);
/* ChromStart */
safef(buff, sizeof(buff), "%d",pathBed->chromStart);
vmAddVal(brainSpecificValues, skipPSet, "mm2.exonChromStart", buff);
/* ChromEnd */
safef(buff, sizeof(buff), "%d",pathBed->chromEnd);
vmAddVal(brainSpecificValues, skipPSet, "mm2.exonChromEnd", buff);
/* Strand. */
vmAddVal(brainSpecificValues, skipPSet, "strand", splice->strand);
/* Genome Position. */
safef(buff, sizeof(buff), "%s:%d-%d", splice->tName, splice->tStart, splice->tEnd);
vmAddVal(brainSpecificValues, skipPSet, "mm2.genomePos", buff);
/* Genome Position. */
safef(buff, sizeof(buff), "%s:%d-%d", chrom, chromStart, chromEnd);
vmAddVal(brainSpecificValues, skipPSet, "mm5.exonPos", buff);
/* Pvalue. */
if(splicePValsHash != NULL)
{
safef(buff, sizeof(buff), "%g", pvalForSplice(nameForSplice(event->splice, skipPath)));
vmAddVal(brainSpecificValues, skipPSet, "bsPVal", buff);
event->pVal = atof(buff);
}
/* GC Percent. */
safef(buff, sizeof(buff), "%.4f", gcPercentForRegion(pathBed->chrom, pathBed->chromStart, pathBed->chromEnd, db));
vmAddVal(brainSpecificValues, skipPSet, "gcPercent", buff);
/* Upstream intron conservation. */
upIntCons = consForIntCoords(splice->tName, splice->tStart, pathBed->chromStart, TRUE);
downIntCons = consForIntCoords(splice->tName, pathBed->chromEnd, splice->tEnd, TRUE);
if(pathBed->strand[0] == '-')
{
double dTmp = upIntCons;
upIntCons = downIntCons;
downIntCons = dTmp;
}
safef(buff, sizeof(buff), "%g", upIntCons);
vmAddVal(brainSpecificValues, skipPSet, "upFullIntronCons", buff);
safef(buff, sizeof(buff), "%g", downIntCons);
vmAddVal(brainSpecificValues, skipPSet, "downFullIntronCons", buff);
/* Calculate a flip score using all tissues even if they
aren't expressed. */
event->flipScore = flipScore = calculateFlipScore(event, skipPath, skipPSet, probM, isBrainTissue, TRUE, &incBrain, &skipBrain);
safef(buff, sizeof(buff), "%.4f", flipScore);
vmAddVal(brainSpecificValues, skipPSet, "flipScoreAllTissues", buff);
/* flip. */
safef(buff, sizeof(buff), "%.4f", event->flipScore);
vmAddVal(brainSpecificValues, skipPSet, "flipScore", buff);
/* Calculate times brain includes and brain excludes. */
flipScore = calculateFlipScore(event, skipPath, skipPSet, probM, isBrainTissue, FALSE, &incBrain, &skipBrain);
safef(buff, sizeof(buff), "%d", incBrain);
vmAddVal(brainSpecificValues, skipPSet, "incBrain", buff);
safef(buff, sizeof(buff), "%d", skipBrain);
vmAddVal(brainSpecificValues, skipPSet, "skipBrain", buff);
/* Conserved in human transcriptome? */
safef(buff, sizeof(buff), "%s:%d-%d:%c", chrom,
chromStart, chromEnd, strand);
if(!lifted || conservedHash == NULL)
vmAddVal(brainSpecificValues, skipPSet, "humanAltToo", "UNKNOWN");
else if(hashFindVal(conservedHash, buff) != NULL)
vmAddVal(brainSpecificValues, skipPSet, "humanAltToo", "TRUE");
else
vmAddVal(brainSpecificValues, skipPSet, "humanAltToo", "FALSE");
/* Add some values about expresion. */
if(lifted)
findExonNumForRegion(chrom, chromStart, chromEnd, strand, &exonNum, &exonCount);
safef(buff, sizeof(buff), "%d", exonNum);
vmAddVal(brainSpecificValues, skipPSet, "exonNum", buff);
safef(buff, sizeof(buff), "%d", exonCount);
vmAddVal(brainSpecificValues, skipPSet, "exonCount", buff);
if(event->altPathProbeCount >= 2)
vmAddVal(brainSpecificValues, skipPSet, "wProbes", "TRUE");
else
vmAddVal(brainSpecificValues, skipPSet, "wProbes", "FALSE");
if(event->isExpressed)
vmAddVal(brainSpecificValues, skipPSet, "expressed", "TRUE");
else
vmAddVal(brainSpecificValues, skipPSet, "expressed", "FALSE");
if(event->isAltExpressed)
vmAddVal(brainSpecificValues, skipPSet, "altExpressed", "TRUE");
else
vmAddVal(brainSpecificValues, skipPSet, "altExpressed", "FALSE");
maxProb = max(skipPath->score, incPath->score);
safef(buff, sizeof(buff), "%.10f", maxProb);
vmAddVal(brainSpecificValues, skipPSet, "pExpressed", buff);
/* Splice event name. */
safef(buff, sizeof(buff), "%s", event->splice->name);
vmAddVal(brainSpecificValues, skipPSet, "spliceName", buff);
/* Count up some motifs. */
if(splice->type == altCassette && altPath->path->bpCount > 0)
{
if(event->flipScore >= 0)
cassetteSkipInsideBpCount += incPath->path->bpCount - skipPath->path->bpCount;
else
brainSpecificMotifInsideBpCount += incPath->path->bpCount - skipPath->path->bpCount;
for(i = 0; i < bindSiteCount; i++)
{
int total = altPath->motifUpCounts[i] + altPath->motifDownCounts[i] + altPath->motifInsideCounts[i];
char colName[256];
/* Add the total up. */
safef(buff, sizeof(buff), "%d", total);
vmAddVal(brainSpecificValues, skipPSet, bindSiteArray[i]->rnaBinder, buff);
/* Add the upstream counts */
safef(colName, sizeof(colName), "%s-up", bindSiteArray[i]->rnaBinder);
safef(buff, sizeof(buff), "%d", altPath->motifUpCounts[i]);
vmAddVal(brainSpecificValues, skipPSet, colName, buff);
/* Add the downstream counts. */
safef(colName, sizeof(colName), "%s-down", bindSiteArray[i]->rnaBinder);
safef(buff, sizeof(colName), "%d", altPath->motifDownCounts[i]);
vmAddVal(brainSpecificValues, skipPSet, colName, buff);
if(event->flipScore >=0)
{
cassetteSkipUpMotifs[i] += event->altPathList->next->motifUpCounts[i];
cassetteSkipDownMotifs[i] += event->altPathList->next->motifDownCounts[i];
cassetteSkipInsideMotifs[i] += event->altPathList->next->motifInsideCounts[i];
}
else
{
brainSpecificMotifUpCounts[i] += altPath->motifUpCounts[i];
brainSpecificMotifDownCounts[i] += altPath->motifDownCounts[i];
brainSpecificMotifInsideCounts[i] += altPath->motifInsideCounts[i];
}
}
if(event->flipScore >=0)
cassetteExonSkipCount++;
}
brainSpecificPathCount++;
brainSpecificEvent = TRUE;
fillInSequences(event, slLastEl(event->splice->paths),
&upSeq, &downSeq, &exonSeq, &upSeqBed, &downSeqBed);
/* Write out the data. */
if (event->flipScore >= optionFloat("minFlip", -200000)
&& event->flipScore <= optionFloat("maxFlip", 200000)
&& event->percentUltra >= optionFloat("minIntCons", 0.0))
{
struct bed *endsBed = NULL;
struct bed *upExonBed = NULL, *downExonBed = NULL;
struct dyString *dna = newDyString(2*upSeq->size+5);
char *tmp = NULL;
dyStringPrintf(dna, "%sNNN%s", upSeq->dna, downSeq->dna);
if(lifted)
{
writeOutOverlappingUltra(brainSpConsDnaOut, brainSpConsBedOut,
chrom, chromStart, chromEnd, strand);
}
faWriteNext(brainSpDnaUpOut, upSeq->name, upSeq->dna, upSeq->size);
bedTabOutN(upSeqBed, 6, brainSpBedUpOut);
vmAddVal(brainSpecificValues, skipPSet, "upSeq", upSeq->dna);
faWriteNext(brainSpDnaDownOut, downSeq->name, downSeq->dna, downSeq->size);
bedTabOutN(downSeqBed, 6, brainSpBedDownOut);
vmAddVal(brainSpecificValues, skipPSet, "downSeq", downSeq->dna);
vmAddVal(brainSpecificValues, skipPSet, "exonSeq", exonSeq->dna);
faWriteNext(brainSpDnaMergedOut, upSeqBed->name, dna->string, dna->stringSize);
pathBed->score = 100*event->flipScore;
tmp = pathBed->name;
pathBed->name = skipPSet;
bedTabOutN(pathBed, 6, brainSpPathBedOut);
pathBed->name = tmp;
/* Find the ends of the intron and make beds for the
portions of the upstream and downstream exons that connect
to this exon bed. */
endsBed = pathToBed(altPath->path, event->splice, -1, -1, TRUE);
assert(endsBed);
AllocVar(upExonBed);
AllocVar(downExonBed);
upExonBed->strand[0] = downExonBed->strand[0] = endsBed->strand[0];
upExonBed->score = downExonBed->score = pathBed->score;
upExonBed->chrom = cloneString(endsBed->chrom);
downExonBed->chrom = cloneString(endsBed->chrom);
upExonBed->name = cloneString(endsBed->name);
downExonBed->name = cloneString(endsBed->name);
downExonBed->chromStart = endsBed->chromEnd;
downExonBed->chromEnd = downExonBed->chromStart + 10;
upExonBed->chromEnd = endsBed->chromStart;
upExonBed->chromStart = upExonBed->chromEnd - 10;
if (endsBed->strand[0] == '-')
{
struct bed *tmp = upExonBed;
upExonBed = downExonBed;
downExonBed = tmp;
}
bedTabOutN(upExonBed, 6, brainSpPathBedExonUpOut);
bedTabOutN(downExonBed, 6, brainSpPathBedExonDownOut);
bedFree(&upExonBed);
bedFree(&downExonBed);
bedFree(&endsBed);
}
bedFree(&upSeqBed);
bedFree(&downSeqBed);
dnaSeqFree(&upSeq);
dnaSeqFree(&downSeq);
dnaSeqFree(&exonSeq);
}
if(brainSpecificEvent == TRUE)
{
brainSpecificEventCount++;
switch(splice->type)
{
case altCassette :
brainSpecificCounts[altCassette]++;
break;
case altMutExclusive :
brainSpecificCounts[altMutExclusive]++;
break;
case alt5Prime :
brainSpecificCounts[alt5Prime]++;
break;
case alt3Prime :
brainSpecificCounts[alt3Prime]++;
break;
case alt3PrimeSoft :
brainSpecificCounts[alt3PrimeSoft]++;
break;
case altOther :
brainSpecificCounts[altOther]++;
break;
}
}
}
void incrementCountByType(int *array, int type)
{
switch(type)
{
case altCassette :
array[altCassette]++;
break;
case altMutExclusive :
array[altMutExclusive]++;
break;
case alt5Prime :
array[alt5Prime]++;
break;
case alt3Prime :
array[alt3Prime]++;
break;
case alt3PrimeSoft :
array[alt3PrimeSoft]++;
break;
case altOther :
array[altOther]++;
break;
}
}
void outputTissueSpecificEvents(struct altEvent *event, int **expressed, int **notExpressed,
int pathCount, struct dMatrix *probM)
/* Output the event if it is tissue specific
specific. */
{
int tissueIx = 0;
struct altPath *altPath = NULL;
struct splice *splice = event->splice;
for(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)
{
boolean tissueSpecificEvent = FALSE;
int pathIx = 0;
for(altPath = event->altPathList; altPath != NULL; altPath = altPath->next, pathIx++)
{
if (altPath->path->bpCount > 0
&& tissueSpecific(event, pathIx, tissueIx, expressed, notExpressed, pathCount, probM))
{
incrementCountByType(tissueSpecificCounts[tissueIx], splice->type);
break;
}
}
}
}
boolean onlyTwoPaths(struct altEvent *event)
/* Return TRUE if event is altCassette, alt3Prime, alt5Prime,
* altMutEx. FALSE otherwise. */
{
int type = event->splice->type;
if(type == altCassette || type == alt3Prime || type == alt5Prime || type == altMutExclusive)
return TRUE;
return FALSE;
}
double expressionRatio(struct altEvent *event, struct altPath *skipPath,
struct altPath *incPath, int tissueIx)
/* Calculate the expression ratio between the two paths.*/
{
double skipExp = 0.0, incExp = 0.0;
int probeIx = 0;
double ratio = 0.0;
/* Calculate average expression for inc and skip paths. */
skipExp = expressionAverage(skipPath, tissueIx);
incExp = expressionAverage(incPath, tissueIx);
if(skipExp == -1 || incExp == -1)
return -1;
/* Caclulate the ratio. */
if(incExp == 0)
incExp = .00001;
ratio = skipExp / incExp;
return ratio;
}
struct altPath *altPathStubForGeneSet(struct altEvent *event, int geneIx)
/* Create a "fake" path from data for gene probe set. Return NULL if no
probeSets for a given event. */
{
struct altPath *ap = NULL;
if(event->geneProbeCount < 1)
return NULL;
AllocVar(ap);
ap->probeCount = 1;
ap->beds = &event->geneBeds[geneIx];
ap->expVals = &event->geneExpVals[geneIx];
ap->pVals = &event->genePVals[geneIx];
ap->avgExpVals = event->geneExpVals[geneIx];
return ap;
}
void outputRatioStatsForPaths(struct altEvent *event, struct altPath *incPath,
struct altPath *skipPath, struct altPath *namePath,
struct dMatrix *probM, struct dMatrix *intenM)
/* Write the stats for a pair of particular paths. */
{
struct splice *splice = event->splice;
int tissueIx = 0;
char *eventName = nameForSplice(splice, namePath);
int i = 0;
char *skipPSet = NULL;
assert(ratioStatOut != NULL);
assert(intenM->colCount = probM->colCount);
/* If there is no data don't output anything. */
if(skipPath->probeCount == 0 || incPath->probeCount == 0)
return;
if(brainSpPSetOut != NULL)
{
skipPSet = namePath->beds[0]->name;
fprintf(brainSpPSetOut, "%s\t", refSeqForPSet(skipPSet));
fprintf(brainSpPSetOut, "%s\t", skipPSet);
fprintf(brainSpPSetOut, "%d\t", incPath->probeCount);
for (i = 0; i < incPath->probeCount; i++)
{
fprintf(brainSpPSetOut, "%s,", incPath->beds[i]->name);
}
fprintf(brainSpPSetOut, "\t%d\t", event->geneProbeCount);
for (i = 0; i < event->geneProbeCount; i++)
{
fprintf(brainSpPSetOut, "%s,", event->geneBeds[i]->name);
}
fprintf(brainSpPSetOut, "\n");
}
fprintf(ratioStatOut, "%s", eventName);
fprintf(ratioSkipIntenOut, "%s", eventName);
fprintf(ratioIncIntenOut, "%s", eventName);
fprintf(ratioGeneIntenOut, "%s", eventName);
fprintf(ratioProbOut, "%s", eventName);
fprintf(incProbOut, "%s", eventName);
fprintf(skipProbOut, "%s", eventName);
fprintf(incProbCombOut, "%s", eventName);
fprintf(skipProbCombOut, "%s", eventName);
/* Loop through tissues caclulating ratio. */
for(tissueIx = 0; tissueIx < probM->colCount; tissueIx++)
{
double ratio = expressionRatio(event, skipPath, incPath, tissueIx);
int bestProbeIx = determineBestProbe(event, incPath, intenM, probM, BIGNUM);
fprintf(ratioStatOut, "\t%.6f", ratio);
fprintf(ratioSkipIntenOut, "\t%.6f", expressionAverage(skipPath, tissueIx));
fprintf(ratioIncIntenOut, "\t%.6f", expressionAverage(incPath, tissueIx));
fprintf(ratioGeneIntenOut, "\t%.6f", geneExpression(event, tissueIx));
fprintf(ratioProbOut, "\t%.6f", genePVal(event, tissueIx));
fprintf(skipProbOut, "\t%.6f", pvalAltPathMaxExpressed(skipPath, tissueIx));
fprintf(incProbOut, "\t%.6f", pvalAltPathMaxExpressed(incPath, tissueIx));
fprintf(skipProbCombOut, "\t%.6f", 1-pvalAltPathCombExpressed(skipPath, tissueIx));
/* fprintf(incProbCombOut, "\t%.6f", incPath->pVals[bestProbeIx][tissueIx]); */
fprintf(incProbCombOut, "\t%.6f", 1-pvalAltPathCombExpressed(incPath, tissueIx));
}
fprintf(ratioStatOut, "\n");
fprintf(ratioSkipIntenOut, "\n");
fprintf(ratioIncIntenOut, "\n");
fprintf(ratioGeneIntenOut, "\n");
fprintf(ratioProbOut, "\n");
fprintf(incProbOut, "\n");
fprintf(skipProbOut, "\n");
fprintf(incProbCombOut, "\n");
fprintf(skipProbCombOut, "\n");
}
void outputRatioStats(struct altEvent *event, struct dMatrix *probM,
struct dMatrix *intenM, boolean doVsGeneSets)
/* Calculate the ratio of skip to include for tissues that are
considered expressed. For tissues where event isn't expressed
output -1 as all ratios will be positive this makes a good empty
data place holder. */
{
struct altPath *skipPath = NULL, *incPath = NULL, *namePath = NULL;
double tmpThresh = presThresh;
/* Few sanity checks. */
assert(ratioStatOut != NULL);
assert(intenM->colCount = probM->colCount);
/* Going to include everything that we think might
have a chance of being expressed. */
if (!doVsGeneSets)
{
assert(slCount(event->altPathList) == 2);
skipPath = event->altPathList;
incPath = event->altPathList->next;
namePath = skipPath;
/* If there is no data don't output anything. */
if(skipPath->probeCount == 0 || incPath->probeCount == 0)
return;
presThresh = absThresh;
outputRatioStatsForPaths(event, incPath, skipPath, namePath, probM, intenM);
presThresh = tmpThresh;
}
else if(event->geneProbeCount > 0)
{
struct altPath *gene1Path = NULL, *gene2Path = NULL;
presThresh = absThresh;
gene1Path = altPathStubForGeneSet(event, 0);
for (incPath = event->altPathList; incPath != NULL; incPath = incPath->next)
{
if (incPath->probeCount == 0)
continue;
skipPath = gene1Path;
namePath = incPath;
outputRatioStatsForPaths(event, incPath, skipPath, namePath, probM, intenM);
}
freez(&gene1Path);
presThresh = tmpThresh;
}
}
void doEventAnalysis(struct altEvent *event, struct dMatrix *intenM,
struct dMatrix *probM)
/* Analyze a given event. */
{
int i = 0;
struct splice *splice = event->splice;
int **expressed = NULL;
int **notExpressed = NULL;
double **expression = NULL;
struct altPath *altPath = NULL;
int pathCount = slCount(event->altPathList);
int pathExpCount = 0;
int pathIx = 0;
int withProbes = 0;
/* Allocate a 2D array for expression. */
AllocArray(expressed, pathCount);
AllocArray(notExpressed, pathCount);
AllocArray(expression, pathCount);
for(i = 0; i < pathCount; i++)
{
AllocArray(expressed[i], probM->colCount);
AllocArray(notExpressed[i], probM->colCount);
AllocArray(expression[i], intenM->colCount);
}
/* Fill in the array. */
for(altPath = event->altPathList; altPath != NULL; altPath = altPath->next)
{
if(altPath->probeCount > 0)
withProbes++;
if (altPathExpressed(event, altPath, intenM, probM,
expressed, notExpressed, expression, pathIx))
pathExpCount++;
/* Output the probabilities. */
if(pathProbabilitiesOut != NULL && event->splice->type != altOther)
{
outputPathProbabilities(event, altPath, intenM, probM,
expressed, notExpressed, expression, pathIx);
}
pathIx++;
}
/* Determine our expression, alternate or otherwise. */
if(pathExpCount >= tissueExpThresh && withProbes > 1)
event->isExpressed = TRUE;
if(pathExpCount >= tissueExpThresh * 2 && withProbes > 1)
event->isAltExpressed = TRUE;
/* If we are outputting the beds for cassettes do it now. */
if(altCassetteBedOut && event->splice->type == altCassette && event->altPathProbeCount >= 2)
{
struct bed *outBed = pathToBed(event->altPathList->next->path, event->splice, -1, -1, TRUE);
if(event->isAltExpressed)
bedTabOutN(outBed, 12, altCassetteBedOut);
else if(event->isExpressed)
bedTabOutN(outBed, 12, expressedCassetteBedOut);
else
bedTabOutN(outBed, 12, notExpressedCassetteBedOut);
bedFree(&outBed);
}
/* If we are outputting a ratio statistic do it now. */
if(onlyTwoPaths(event) && ratioStatOut)
{
outputRatioStats(event, probM, intenM, FALSE);
}
else if(( splice->type == altMutExclusive ||
splice->type == alt3PrimeSoft ||
splice->type == alt5PrimeSoft) &&
ratioStatOut)
{
outputRatioStats(event, probM, intenM, TRUE);
}
/* Get a background count of motifs in the cassettes. */
if(brainSpBedUpOut != NULL)
outputBrainSpecificEvents(event, expressed, notExpressed, pathCount, probM);
if(tissueSpecificOut != NULL && event->isExpressed == TRUE)
outputTissueSpecificEvents(event, expressed, notExpressed, pathCount, probM);
if(event->isAltExpressed && event->splice->type == altCassette && event->pVal < pvalThresh)
{
for(i = 0; i < bindSiteCount; i++)
{
cassetteUpMotifs[i] += event->altPathList->next->motifUpCounts[i];
cassetteDownMotifs[i] += event->altPathList->next->motifDownCounts[i];
cassetteInsideMotifs[i] += event->altPathList->next->motifInsideCounts[i];
}
cassetteExonCount++;
}
/* Cleanup some memory. */
for(i = 0; i < pathCount; i++)
{
freez(&expressed[i]);
freez(¬Expressed[i]);
freez(&expression[i]);
}
freez(¬Expressed);
freez(&expressed);
freez(&expression);
}
int stringOccurance(char *needle, char *haystack)
/* How many times is needle in haystack? */
{
int count = 0;
char *rest = haystack;
touppers(needle);
touppers(haystack);
while((rest = stringIn(needle, rest)) != NULL)
{
count++;
rest++;
}
return count;
}
int countMotifs(char *seq, struct bindSite *bs)
/* Count how many times this binding site appears in this
sequence. */
{
int i = 0, j = 0;
int count = 0;
touppers(seq);
for(i = 0; i < bs->motifCount; i++)
{
count += stringOccurance(bs->motifs[i],seq);
}
return count;
}
void doMotifCassetteAnalysis(struct altEvent *event)
/* Look to see how many motifs are found around this event. */
{
struct dnaSeq *upStream = NULL, *downStream = NULL, *tmp = NULL, *inside = NULL;
struct altPath *altPath = event->altPathList->next;
struct path *path = altPath->path;
int *vPos = event->splice->vPositions;
int *v = path->vertices;
int chromStart = vPos[v[1]];
int chromEnd = vPos[v[2]];
int motifWin = optionInt("motifWin", 200);
int i = 0;
if(event->splice->strand[0] == '-')
{
upStream = hChromSeq(path->tName, chromEnd, chromEnd+motifWin);
reverseComplement(upStream->dna, upStream->size);
downStream = hChromSeq(path->tName, chromStart-motifWin, chromStart);
reverseComplement(downStream->dna, downStream->size);
inside = hChromSeq(path->tName, chromStart, chromEnd);
reverseComplement(inside->dna, inside->size);
}
else
{
upStream = hChromSeq(path->tName, chromStart-motifWin, chromStart);
downStream = hChromSeq(path->tName, chromEnd, chromEnd+motifWin);
inside = hChromSeq(path->tName, chromStart, chromEnd);
}
AllocArray(altPath->motifUpCounts, bindSiteCount);
AllocArray(altPath->motifDownCounts, bindSiteCount);
AllocArray(altPath->motifInsideCounts, bindSiteCount);
for(i = 0; i < bindSiteCount; i++)
{
altPath->motifUpCounts[i] += countMotifs(upStream->dna, bindSiteArray[i]);
altPath->motifDownCounts[i] += countMotifs(downStream->dna, bindSiteArray[i]);
altPath->motifInsideCounts[i] += countMotifs(inside->dna, bindSiteArray[i]);
}
dnaSeqFree(&upStream);
dnaSeqFree(&downStream);
dnaSeqFree(&inside);
}
void doMotifControlAnalysis(struct altEvent *event)
/* Look to see how many motifs are found around this event. */
{
struct dnaSeq *upStream = NULL, *downStream = NULL, *tmp = NULL, *inside = NULL;
struct altPath *altPath = event->altPathList;
struct splice *splice = event->splice;
struct path *path = altPath->path;
struct bed *bed = NULL;
int *vPos = event->splice->vPositions;
int *v = path->vertices;
int chromStart = 0;
int chromEnd = 0;
int motifWin = optionInt("motifWin", 200);
int i = 0;
int blockIx;
bed = pathToBed(path, splice, -1, -1, FALSE);
if(bed == NULL)
return;
/* Only do internal exons. */
for(blockIx = 1; blockIx < bed->blockCount - 1; blockIx++)
{
struct bed *outBed = NULL;
/* Print out a bed of this exon. */
AllocVar(outBed);
outBed->chromStart = chromStart = bed->chromStart + bed->chromStarts[blockIx];
outBed->chromEnd = chromEnd = chromStart + bed->blockSizes[blockIx];
safef(outBed->strand,sizeof(outBed->strand),"%s", bed->strand);
outBed->score = bed->score;
outBed->chrom = cloneString(bed->chrom);
outBed->name = cloneString(bed->name);
subChar(outBed->name, '-', '\0');
bedTabOutN(outBed, 6, brainSpPathBedOut);
if(!skipMotifControls)
{
assert(constMotifCounts);
fprintf(constMotifCounts, "%s:%s:%d-%d",
outBed->name, outBed->chrom, outBed->chromStart, outBed->chromEnd);
/* Get the sequences and do motif analysis. */
if(event->splice->strand[0] == '-')
{
upStream = hChromSeq(path->tName, chromEnd, chromEnd+motifWin);
reverseComplement(upStream->dna, upStream->size);
downStream = hChromSeq(path->tName, chromStart-motifWin, chromStart);
reverseComplement(downStream->dna, downStream->size);
inside = hChromSeq(path->tName, chromStart, chromEnd);
reverseComplement(inside->dna, inside->size);
}
else
{
upStream = hChromSeq(path->tName, chromStart-motifWin, chromStart);
downStream = hChromSeq(path->tName, chromEnd, chromEnd+motifWin);
inside = hChromSeq(path->tName, chromStart, chromEnd);
}
touppers(upStream->dna);
touppers(downStream->dna);
touppers(inside->dna);
controlInsideBpCount += inside->size;
if(altPath->motifUpCounts == NULL)
{
AllocArray(altPath->motifUpCounts, bindSiteCount);
AllocArray(altPath->motifDownCounts, bindSiteCount);
AllocArray(altPath->motifInsideCounts, bindSiteCount);
}
for(i = 0; i < bindSiteCount; i++)
{
int upStreamCount = countMotifs(upStream->dna, bindSiteArray[i]);
int downStreamCount = countMotifs(downStream->dna, bindSiteArray[i]);
int insideCount = countMotifs(inside->dna, bindSiteArray[i]);
/* Report our counts. */
fprintf(constMotifCounts, "\t%d\t%d", upStreamCount, downStreamCount);
altPath->motifUpCounts[i] += upStreamCount;
controlUpMotifs[i] += upStreamCount;
altPath->motifDownCounts[i] += downStreamCount;
controlDownMotifs[i] += downStreamCount;
altPath->motifInsideCounts[i] += insideCount;
controlInsideMotifs[i] += insideCount;
}
bedFree(&outBed);
/* Finish control line. */
fprintf(constMotifCounts, "\n");
controlExonCount++;
}
}
dnaSeqFree(&upStream);
dnaSeqFree(&downStream);
dnaSeqFree(&inside);
}
int flipScoreCmp(const void *va, const void *vb)
/* Compare to sort based on chrom,chromStart. */
{
const struct slRef *a = *((struct slRef**)va);
const struct slRef *b = *((struct slRef **)vb);
struct altEvent *aE = a->val;
struct altEvent *bE = b->val;
if(fabs(aE->flipScore) > fabs(bE->flipScore))
return -1;
else if(fabs(aE->flipScore) < fabs(bE->flipScore))
return 1;
return 0;
}
int percentUltraCmp(const void *va, const void *vb)
/* Compare to sort based on chrom,chromStart. */
{
const struct slRef *a = *((struct slRef**)va);
const struct slRef *b = *((struct slRef **)vb);
struct altEvent *aE = a->val;
struct altEvent *bE = b->val;
if(aE->percentUltra < bE->percentUltra)
return 1;
else if(aE->percentUltra > bE->percentUltra)
return -1;
return 0;
}
boolean isHardExon(unsigned char *vTypes, int v1, int v2)
/* Return TRUE if this is a hard exon. */
{
if(ggExon == pathEdgeType(vTypes, v1, v2) &&
(vTypes[v1] == ggHardStart || vTypes[v1] == ggHardEnd) &&
(vTypes[v2] == ggHardStart || vTypes[v2] == ggHardEnd))
return TRUE;
return FALSE;
}
void doControlStats(struct altEvent *event)
/* Calculate control stats for control events. */
{
struct splice *splice = event->splice;
struct path *path = event->altPathList->path;
int chromStart = 0, chromEnd = 0;
char strand;
char *chrom;
int vertIx = 0;
int *verts = NULL;
int vC = path->vCount;
int *vPos = splice->vPositions;
unsigned char *vTypes = splice->vTypes;
struct dyString *name = newDyString(128);
for(vertIx = 0; vertIx < vC - 1; vertIx++)
{
if(isHardExon(vTypes, vertIx, vertIx+1))
{
char *startChrom = cloneString(path->tName);
char *endChrom = cloneString(path->tName);
char *cassChrom = cloneString(path->tName);
int intStart = vPos[vertIx == 0 ? path->upV : vertIx-1];
int dummy = 0;
int chromStart = vPos[vertIx];
int chromEnd = vPos[vertIx+1];
int intEnd = vPos[vertIx+1 == vC - 1 ? path->downV : vertIx+2];
char strand = splice->strand[0];
boolean lifted = TRUE;
dyStringClear(name);
/* Lift over each end seperately so as to ignore changes
in assembly in the middle. */
dummy = intStart-10;
lifted &= liftOverCoords(&startChrom, &dummy, &intStart, &strand);
strand = splice->strand[0];
dummy = intEnd+10;
lifted &= liftOverCoords(&endChrom, &intEnd, &dummy, &strand);
strand = splice->strand[0];
lifted &= liftOverCoords(&cassChrom, &chromStart, &chromEnd, &strand);
if(lifted && sameString(endChrom, cassChrom) && sameString (startChrom, cassChrom))
{
dyStringPrintf(name, "%s.%s:%d-%d", splice->name, startChrom, chromStart, chromEnd);
fillInStatsForEvent(controlValuesVm, name->string, startChrom,
intStart, chromStart, chromEnd, intEnd, strand,
altControl);
}
}
}
dyStringFree(&name);
}
void doAnalysis(struct altEvent *eventList, struct dMatrix *intenM,
struct dMatrix *probM)
/* How many of the alt events are expressed. */
{
struct altEvent *event = NULL;
int i = 0;
struct altPath *altPath = NULL;
int expressed = 0, altExpressed = 0;
struct slRef *ref = NULL;
int contCount = 0;
char *prefix = optionVal("brainSpecific", NULL);
char *useDb = newDb;
for(event = eventList; event != NULL; event = event->next)
{
if(event->splice->type == altCassette && bindSiteCount > 0)
doMotifCassetteAnalysis(event);
else if(event->splice->type == altControl && bindSiteCount > 0)
doMotifControlAnalysis(event);
if(controlValuesVm != NULL && event->splice->type == altControl)
{
if(++contCount % 100 == 0)
{
fputc('*',stderr);
fflush(stderr);
contCount = 0;
}
doControlStats(event);
}
doEventAnalysis(event, intenM, probM);
if(event->isExpressed)
logSpliceTypeExp(event->splice->type);
if(event->isAltExpressed)
logSpliceTypeAltExp(event->splice->type);
}
if(brainSpBedUpOut != NULL)
{
char *chrom = NULL;
int chromStart = 0, chromEnd = 0;
struct bed *bed = NULL;
if(optionExists("flipScoreSort"))
slSort(&brainSpEvents, flipScoreCmp);
else
slSort(&brainSpEvents, percentUltraCmp);
vmWriteVals(brainSpecificValues, brainSpValuesOut);
event = brainSpEvents->val;
altPath = event->altPathList->next;
bed = pathToBed(altPath->path, event->splice, -1, -1, FALSE);
chrom = cloneString(bed->chrom);
chromStart = bed->chromStart;
chromEnd = bed->chromEnd;
fprintf(brainSpFrameHtmlOut, "<html><head><title>%s Specific Events.</title></head>\n"
"<frameset cols=\"30%,70%\">\n"
" <frame name=\"_list\" src=\"./%s%s\">\n"
" <frameset rows=\"50%,50%\">\n"
" <frame name=\"browser\" src=\"http://%s/cgi-bin/hgTracks?db=%s&hgt.motifs=GCATG,CTCTCT,GGGG&position=%s:%d-%d\">\n"
" <frame name=\"plots\" src=\"http://%s/cgi-bin/hgTracks?db=%s&position=%s:%d-%d\">\n"
" </frameset>\n"
"</frameset>\n"
"</html>\n", optionVal("brainTissues","Brain"), prefix, ".table.html",
browserName, useDb,
chrom, chromStart, chromEnd,
browserName, useDb,
chrom, chromStart, chromEnd
);
carefulClose(&brainSpFrameHtmlOut);
for(ref = brainSpEvents; ref != NULL; ref = ref->next)
{
struct altEvent *bEvent = ref->val;
printLinks(bEvent);
}
}
}
double calcPercent(double numerator, double denominator)
/* Calculate a percent checking for zero. */
{
if(denominator != 0)
return (100.0 * numerator / denominator);
return 0;
}
double cph(double numerator, double denominator)
/* Calculate a ratio checking for zero. */
{
if(denominator != 0)
return (numerator / denominator);
return 0;
}
void reportTissueSpecificCounts(char **tissueNames, int tissueCount)
/* Writ out a matrix of tissues and their counts. */
{
int i = 0, j = 0;
assert(tissueSpecificOut);
fprintf(tissueSpecificOut, "\taltCassette\taltMutExclusive\talt5Prime\talt3Prime\taltOther\n");
for(i = 0; i < tissueCount; i++)
{
fprintf(tissueSpecificOut, "%-22s\t%4d\t%4d\t%4d\t%4d\t%4d\n", tissueNames[i],
tissueSpecificCounts[i][altCassette], tissueSpecificCounts[i][altMutExclusive],
tissueSpecificCounts[i][alt5Prime],tissueSpecificCounts[i][alt3Prime],
tissueSpecificCounts[i][altOther]);
}
}
void reportMotifCounts(int *up, int *down, int *in, int total, int bpTotal)
{
int *u = up;
int *d = down;
int *i = in;
int t = total;
int bt = bpTotal;
struct bindSite **b = bindSiteArray;
assert(up);
assert(down);
fprintf(stderr, "+----------+--------------+----------------+----------------+-----------------+----------------+----------------+\n");
fprintf(stderr, "| Position | %12s | %14s | %14s | %15s | %14s | %14s |\n",
b[0]->rnaBinder, b[1]->rnaBinder, b[2]->rnaBinder, b[3]->rnaBinder, b[4]->rnaBinder, b[5]->rnaBinder);
fprintf(stderr, "+----------+--------------+----------------+----------------+-----------------+----------------+----------------+\n");
//fprintf(stderr, "+----------+------------+--------------+--------------+---------------+--------------+--------------+\n");
fprintf(stderr, "| %-8s | %3d (%4.4f) | %5d (%4.4f) | %5d (%4.4f) | %6d (%4.4f) | %5d (%4.4f) | %5d (%4.4f) |\n",
"UpStream", u[0], cph(u[0],t), u[1], cph(u[1],t), u[2], cph(u[2],t), u[3], cph(u[3],t), u[4],cph(u[4],t), u[5],cph(u[5],t));
fprintf(stderr, "| %-8s | %3d (%4.4f) | %5d (%4.4f) | %5d (%4.4f) | %6d (%4.4f) | %5d (%4.4f) | %5d (%4.4f) |\n",
"DnStream", d[0], cph(d[0],t), d[1], cph(d[1],t), d[2], cph(d[2],t), d[3], cph(d[3],t), d[4],cph(d[4],t), d[5],cph(d[5],t));
fprintf(stderr, "| %-8s | %3d (%1.4f) | %5d (%1.4f) | %5d (%1.4f) | %6d (%1.4f) | %5d (%1.4f) | %5d (%1.4f) |\n",
"Inside ", i[0], cph(i[0],bt), i[1], cph(i[1],bt), i[2], cph(i[2],bt), i[3], cph(i[3],bt), i[4],cph(i[4],bt), i[5],cph(i[5],bt));
fprintf(stderr, "+----------+--------------+----------------+----------------+-----------------+----------------+----------------+\n");
}
void reportBrainSpCounts()
/* Print brain specific results. */
{
if(brainSpDnaUpOut != NULL)
{
int *bC = brainSpecificCounts;
char *tissue = optionVal("brainTissues","Brain");
fprintf(stderr, "%d %s Specific Events. %d %s Specific paths\n",
brainSpecificEventCount, tissue, brainSpecificPathCount, tissue);
fprintf(stderr, "+----------+---------+-------+-------+-------+-------+\n");
fprintf(stderr, "| Cassette | MutExcl | Alt3' | Alt5' | TxEnd | Other |\n");
fprintf(stderr, "+----------+---------+-------+-------+-------+-------+\n");
fprintf(stderr, "| %8d | %7d | %5d | %5d | %5d | %5d |\n",
bC[altCassette], bC[altMutExclusive], bC[alt3Prime], bC[alt5Prime],
bC[alt3PrimeSoft], bC[altOther]);
fprintf(stderr, "+----------+---------+-------+-------+-------+-------+\n");
if(bindSiteCount != 0)
{
int *u = brainSpecificMotifUpCounts;
int *d = brainSpecificMotifDownCounts;
int *i = brainSpecificMotifInsideCounts;
int bp = brainSpecificMotifInsideBpCount;
struct bindSite **b = bindSiteArray;
fprintf(stderr,"Cassette binding sites in %d include exons:\n", bC[altCassette]-cassetteExonSkipCount);
reportMotifCounts(u,d,i,bC[altCassette] - cassetteExonSkipCount, bp);
u = cassetteSkipUpMotifs;
d = cassetteSkipDownMotifs;
i = cassetteSkipInsideMotifs;
bp = cassetteSkipInsideBpCount;
fprintf(stderr,"Cassette binding sites in %d skip exons:\n", cassetteExonSkipCount);
reportMotifCounts(u,d,i,cassetteExonSkipCount, bp);
}
}
}
void reportEventCounts()
/* Print some stats about splices and probe with counts. */
{
fprintf(stderr, "+----------------------+-------+-----------+-----------+------+---------+\n");
fprintf(stderr, "| Alt Event. | Count | w/ Probes | Expressed | Alt. | Percent |\n");
fprintf(stderr, "+----------------------+-------+-----------+-----------+------+---------+\n");
fprintf(stderr, "| alt 5' | %5d | %4d | %4d | %3d | %5.1f%% |\n",
alt5PrimeCount, alt5PrimeWProbeCount, alt5PrimeExpCount, alt5PrimeAltExpCount,
calcPercent(alt5PrimeAltExpCount, alt5PrimeExpCount));
fprintf(stderr, "| alt 3' | %5d | %4d | %4d | %3d | %5.1f%% |\n",
alt3PrimeCount, alt3PrimeWProbeCount, alt3PrimeExpCount, alt3PrimeAltExpCount,
calcPercent(alt3PrimeAltExpCount, alt3PrimeExpCount));
fprintf(stderr, "| alt Cass | %5d | %4d | %4d | %3d | %5.1f%% |\n",
altCassetteCount, altCassetteWProbeCount, altCassetteExpCount, altCassetteAltExpCount,
calcPercent(altCassetteAltExpCount, altCassetteExpCount));
fprintf(stderr, "| alt Ret. Int. | %5d | %4d | %4d | %3d | %5.1f%% |\n",
altRetIntCount, altRetIntWProbeCount, altRetIntExpCount, altRetIntAltExpCount,
calcPercent(altRetIntAltExpCount, altRetIntExpCount));
fprintf(stderr, "| alt Mutual Exclusive | %5d | %4d | %4d | %3d | %5.1f%% |\n",
altMutExclusiveCount, altMutExclusiveWProbeCount, altMutExclusiveExpCount, altMutExclusiveAltExpCount,
calcPercent(altMutExclusiveAltExpCount, altMutExclusiveExpCount));
fprintf(stderr, "| alt Txn Start | %5d | %4d | %4d | %3d | %5.1f%% |\n",
alt5PrimeSoftCount, alt5PrimeSoftWProbeCount, alt5PrimeSoftExpCount, alt5PrimeSoftAltExpCount,
calcPercent(alt5PrimeSoftAltExpCount, alt5PrimeSoftExpCount));
fprintf(stderr, "| alt Txn End | %5d | %4d | %4d | %3d | %5.1f%% |\n",
alt3PrimeSoftCount, alt3PrimeSoftWProbeCount, alt3PrimeSoftExpCount, alt3PrimeSoftAltExpCount,
calcPercent(alt3PrimeSoftAltExpCount, alt3PrimeSoftExpCount));
fprintf(stderr, "| alt Other | %5d | %4d | %4d | %3d | %5.1f%% |\n",
altOtherCount, altOtherWProbeCount, altOtherExpCount, altOtherAltExpCount,
calcPercent(altOtherAltExpCount, altOtherExpCount));
fprintf(stderr, "| alt Control | %5d | %4d | %4d | %3d | %5.1f%% |\n",
altControlCount, altControlWProbeCount, altControlExpCount, altControlAltExpCount,
calcPercent(altControlAltExpCount, altControlExpCount));
fprintf(stderr, "+----------------------+-------+-----------+-----------+------+---------+\n");
/* if(bindSiteCount != 0) */
/* { */
/* int *u = cassetteUpMotifs; */
/* int *d = cassetteDownMotifs; */
/* int *i = cassetteInsideMotifs; */
/* struct bindSite **b = bindSiteArray; */
/* fprintf(stderr,"Cassette binding sites in included %d include exons:\n", cassetteExonCount); */
/* reportMotifCounts(u,d,i,cassetteExonCount); */
/* } */
if(bindSiteCount != 0)
{
int *u = controlUpMotifs;
int *d = controlDownMotifs;
int *i = controlInsideMotifs;
struct bindSite **b = bindSiteArray;
fprintf(stderr,"Control binding sites in %d exons:\n", controlExonCount);
reportMotifCounts(u,d,i,controlExonCount, controlInsideBpCount);
}
}
void initLiftOver()
/* Initialize the liftOver process. */
{
char *from = optionVal("db", NULL);
char *to = optionVal("newDb", NULL);
char *chainFile = NULL;
assert(from);
hSetDb2(to);
if(to == NULL)
errAbort("Must specify a -newDb to do a lift.");
chainFile = liftOverChainFile(from, to);
if(chainFile == NULL)
errAbort("Couldn't load a lift chainFile for %s->%s", from, to);
liftOverHash = newHash(12);
readLiftOverMap(chainFile, liftOverHash);
}
boolean liftOverCoords(char **chrom, int *chromStart, int *chromEnd, char *strand)
/* Return TRUE and new values if values passed in can be lifted. */
{
char *newChrom = NULL;
int newStart = 0, newEnd = 0;
char newStrand;
char *msg = NULL;
boolean success = FALSE;
if(liftOverHash != NULL)
msg = liftOverRemapRange(liftOverHash, .95, *chrom, *chromStart, *chromEnd, *strand,
1.0, &newChrom, &newStart, &newEnd, &newStrand);
if(msg == NULL)
{
freez(chrom);
*chrom = newChrom;
*chromStart = newStart;
*chromEnd = newEnd;
*strand = newStrand;
success = TRUE;
}
return success;
}
void initTissueSpecific(int tissueCount)
/* Open up the files for tissue specific isoforms and dna. */
{
char *name = optionVal("tissueSpecific", NULL);
int i = 0;
AllocArray(tissueSpecificCounts, tissueCount);
for(i = 0; i < tissueCount; i++)
{
AllocArray(tissueSpecificCounts[i], 20);
}
tissueSpecificOut = mustOpen(name, "w");
}
void initBrainSpecific()
/* Open up the files for brain specific isoforms and dna. */
{
struct bindSite *bs = NULL;
char *prefix = optionVal("brainSpecific", NULL);
struct dyString *file = newDyString(strlen(prefix)+10);
char *useDb = newDb;
brainSpecificStrict = optionExists("brainSpecificStrict");
brainSpecificValues = newValuesMat(400,15);
AllocArray(brainSpecificCounts, altMutExclusive + 1);
if(bindSiteCount > 0)
{
AllocArray(brainSpecificMotifUpCounts, bindSiteCount);
AllocArray(brainSpecificMotifDownCounts, bindSiteCount);
AllocArray(brainSpecificMotifInsideCounts, bindSiteCount);
}
dyStringClear(file);
dyStringPrintf(file, "%s.path.bed", prefix);
brainSpPathBedOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.probeSets.tab", prefix);
brainSpPSetOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.path.ends.bed", prefix);
brainSpPathEndsBedOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.path.exonUp.bed", prefix);
brainSpPathBedExonUpOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.path.exonDown.bed", prefix);
brainSpPathBedExonDownOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.up.fa", prefix);
brainSpDnaUpOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.merged.fa", prefix);
brainSpDnaMergedOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.cons.fa", prefix);
brainSpConsDnaOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.cons.bed", prefix);
brainSpConsBedOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.down.fa", prefix);
brainSpDnaDownOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.up.bed", prefix);
brainSpBedUpOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.down.bed", prefix);
brainSpBedDownOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.values.tab", prefix);
brainSpValuesOut = mustOpen(file->string, "w");
dyStringClear(file);
dyStringPrintf(file, "%s.table.html", prefix);
brainSpTableHtmlOut = mustOpen(file->string, "w");
fprintf(brainSpTableHtmlOut, "<html>\n<body bgcolor=\"#FFF9D2\"><b>Alt-Splice List</b>\n");
fprintf(brainSpTableHtmlOut, "<tr><td><b>Motif Order:</b>");
for(bs = bindSiteList; bs != NULL; bs = bs->next)
fprintf(brainSpTableHtmlOut, "%s, ", bs->rnaBinder);
fprintf(brainSpTableHtmlOut, "</td></tr>");
fprintf(brainSpTableHtmlOut, "<table border=1><tr><th>Name</th><th>Sep</th></tr>\n");
dyStringClear(file);
dyStringPrintf(file, "%s.frame.html", prefix);
brainSpFrameHtmlOut = mustOpen(file->string, "w");
dyStringFree(&file);
}
void printCdtHeader(FILE *out, struct dMatrix *dM)
{
int i = 0;
fprintf(out, "YORF\tNAME");
for(i = 0; i < dM->colCount; i++)
{
fprintf(out, "\t%s", dM->colNames[i]);
}
fprintf(out, "\n");
}
void initRatioStats(struct dMatrix *intenM)
/* Setupt a file to output ratio statistics to. */
{
int i = 0;
char *outputRatioStats = optionVal("outputRatioStats", NULL);
struct dyString *buff = NULL;
assert(outputRatioStats);
assert(intenM);
buff = newDyString(strlen(outputRatioStats)+30);
ratioStatOut = mustOpen(outputRatioStats, "w");
dyStringClear(buff);
dyStringPrintf(buff, "%s.skip.intensity", outputRatioStats);
ratioSkipIntenOut = mustOpen(buff->string, "w");
dyStringClear(buff);
dyStringPrintf(buff, "%s.inc.intensity", outputRatioStats);
ratioIncIntenOut = mustOpen(buff->string, "w");
dyStringClear(buff);
dyStringPrintf(buff, "%s.gene.prob", outputRatioStats);
ratioProbOut = mustOpen(buff->string, "w");
dyStringClear(buff);
dyStringPrintf(buff, "%s.gene.intensity", outputRatioStats);
ratioGeneIntenOut = mustOpen(buff->string, "w");
dyStringClear(buff);
dyStringPrintf(buff, "%s.inc.prob", outputRatioStats);
incProbOut = mustOpen(buff->string, "w");
dyStringClear(buff);
dyStringPrintf(buff, "%s.skip.prob", outputRatioStats);
skipProbOut = mustOpen(buff->string, "w");
dyStringClear(buff);
dyStringPrintf(buff, "%s.inc.comb.prob", outputRatioStats);
incProbCombOut = mustOpen(buff->string, "w");
dyStringClear(buff);
dyStringPrintf(buff, "%s.skip.comb.prob", outputRatioStats);
skipProbCombOut = mustOpen(buff->string, "w");
for(i = 0; i < intenM->colCount - 1; i++)
{
fprintf(ratioStatOut, "%s\t", intenM->colNames[i]);
fprintf(ratioSkipIntenOut, "%s\t", intenM->colNames[i]);
fprintf(ratioIncIntenOut, "%s\t", intenM->colNames[i]);
fprintf(ratioGeneIntenOut, "%s\t", intenM->colNames[i]);
fprintf(ratioProbOut, "%s\t", intenM->colNames[i]);
fprintf(skipProbOut, "%s\t", intenM->colNames[i]);
fprintf(incProbOut, "%s\t", intenM->colNames[i]);
fprintf(skipProbCombOut, "%s\t", intenM->colNames[i]);
fprintf(incProbCombOut, "%s\t", intenM->colNames[i]);
}
fprintf(ratioStatOut, "%s\n", intenM->colNames[i]);
fprintf(ratioSkipIntenOut, "%s\n", intenM->colNames[i]);
fprintf(ratioIncIntenOut, "%s\n", intenM->colNames[i]);
fprintf(ratioGeneIntenOut, "%s\n", intenM->colNames[i]);
fprintf(ratioProbOut, "%s\n", intenM->colNames[i]);
fprintf(skipProbOut, "%s\n", intenM->colNames[i]);
fprintf(incProbOut, "%s\n", intenM->colNames[i]);
fprintf(skipProbCombOut, "%s\n", intenM->colNames[i]);
fprintf(incProbCombOut, "%s\n", intenM->colNames[i]);
}
void outputProbeMatches(struct altEvent *eventList)
/* Loop through the event list and output the different probes for
each path. Only do events that have two paths. */
{
struct altEvent *event = NULL;
FILE *out = NULL;
char *fileName = optionVal("outputProbeMatch", NULL);
struct altPath *altPath = NULL;
int i = 0;
assert(fileName);
out = mustOpen(fileName, "w");
for(event = eventList; event != NULL; event = event->next)
{
if(slCount(event->altPathList) != 2 || event->altPathProbeCount != 2)
continue;
fprintf(out, "%s", event->splice->name);
/* Loop through the alternative isoforms and print comma separated probes for each path. */
for(altPath = event->altPathList; altPath != NULL; altPath = altPath->next)
{
fputc('\t', out);
for(i = 0; i < altPath->probeCount; i++)
{
struct bed *bed = altPath->beds[i];
fprintf(out, "%s,", bed->name);
}
}
fputc('\n', out);
}
carefulClose(&out);
}
void outputProbePvals(struct altEvent *eventList, struct dMatrix *probM)
/* Loop through the events and output the probe probabilities. Only do events
that have two paths. */
{
struct altEvent *event = NULL;
struct altPath *altPath = NULL;
char *fileName = optionVal("outputProbePvals", NULL);
int probeIx = 0;
int expIx = 0;
int expCount = 0;
FILE *out = NULL;
assert(fileName);
assert(probM);
out = mustOpen(fileName, "w");
expCount = probM->colCount;
/* Output the header of column names. */
for(expIx = 0; expIx < expCount-1; expIx++)
fprintf(out, "%s\t", probM->colNames[expIx]);
fprintf(out, "%s\n", probM->colNames[expIx]);
for(event = eventList; event != NULL; event = event->next)
{
if(slCount(event->altPathList) != 2 || event->altPathProbeCount != 2)
continue;
for(altPath = event->altPathList; altPath != NULL; altPath = altPath->next)
{
for(probeIx = 0; probeIx < altPath->probeCount; probeIx++)
{
fprintf(out, "%s", altPath->beds[probeIx]->name);
for(expIx = 0; expIx < expCount; expIx++)
{
fprintf(out, "\t%.5f", altPath->pVals[probeIx][expIx]);
}
fputc('\n',out);
}
}
}
carefulClose(&out);
}
void altProbes()
/* Top level function to map probes to paths and analyze. */
{
struct splice *spliceList = NULL;
struct altEvent *eventList = NULL, *event = NULL;
struct dMatrix *intenM = NULL, *probM = NULL;
char *intenIn = optionVal("intensityFile", NULL);
char *probIn = optionVal("probFile", NULL);
char *splicesIn = optionVal("spliceFile", NULL);
if(splicesIn == NULL)
errAbort("Must specify a apliceFile");
warn("Loading splices from %s", splicesIn);
spliceList = spliceLoadAll(splicesIn);
eventList = altEventsFromSplices(spliceList);
warn("Loading beds.");
bedLoadChromKeeper();
dotForUserInit(max(slCount(eventList)/20, 1));
for(event = eventList; event != NULL; event = event->next)
{
dotForUser();
findProbeSetsForEvents(event);
logSpliceType(event->splice->type);
if(event->altPathProbeCount >= 2)
{
logSpliceTypeWProbe(event->splice->type);
}
}
warn("");
if(optionExists("outputProbeMatch"))
outputProbeMatches(eventList);
warn("Reading Data Matrixes.");
if(probIn == NULL || intenIn == NULL)
errAbort("Must specify intensityFile and probeFile");
intenM = dMatrixLoad(intenIn);
probM = dMatrixLoad(probIn);
/* If we're doing path probabilities print some headers. */
if(pathProbabilitiesOut != NULL)
{
printCdtHeader(pathProbabilitiesOut, probM);
printCdtHeader(pathExpressionOut, intenM);
}
if(optionExists("tissueSpecific"))
initTissueSpecific(probM->colCount);
if(optionExists("outputRatioStats"))
initRatioStats(intenM);
warn("Filling in event data.");
fillInEventData(eventList, intenM, probM);
warn("Doing analysis");
if(optionExists("outputProbePvals"))
outputProbePvals(eventList, probM);
doAnalysis(eventList, intenM, probM);
reportEventCounts();
reportBrainSpCounts();
if(intronsConsCounted > 0)
warn("%d of %d introns are heavily conserved %.2f%%",
intronsConserved, intronsConsCounted, (100.0 * intronsConserved)/intronsConsCounted);
if(tissueSpecificOut)
reportTissueSpecificCounts(probM->colNames, probM->colCount);
if(brainSpTableHtmlOut)
fprintf(brainSpTableHtmlOut, "</table></body></html>\n");
if(controlValuesVm != NULL)
vmWriteVals(controlValuesVm, controlValuesOut);
carefulClose(&brainSpTableHtmlOut);
carefulClose(&brainSpDnaUpOut);
carefulClose(&brainSpDnaDownOut);
carefulClose(&brainSpBedUpOut);
carefulClose(&brainSpBedDownOut);
carefulClose(&brainSpPathBedOut);
}
boolean unitTestFunct(struct unitTest *test, boolean passed,
struct dyString *error, char *errorMsg)
/* Wrapper around printing things to the error. */
{
assert(error);
if(!passed)
dyStringPrintf(error, "%s, ", errorMsg);
return passed;
}
boolean testStringOccurance(struct unitTest *test)
/* Test how many times a motif is counted. */
{
int count = 0;
if(stringOccurance(cloneString("ggGG"), cloneString("nnnnnggggg")) != 2)
return FALSE;
if(stringOccurance(cloneString("ggGG"), cloneString("nnnnngggggnnnn")) != 2)
return FALSE;
if(stringOccurance(cloneString("ggGG"), cloneString("gggggnnnn")) != 2)
return FALSE;
if(stringOccurance(cloneString("gcATG"), cloneString("GcatGcattg")) != 1)
return FALSE;
return TRUE;
}
boolean testCdfChiSqP(struct unitTest *test)
/* Test the gsl results for the chisq function. Gold values from R.*/
{
double result = 0;
char buff[256];
/* Run the function for som test values, print to
a buffer to get the precision / rounding right. */
result = gsl_cdf_chisq_P(-2*log(.9),2);
safef(buff, sizeof(buff), "%.7f", result);
if(differentString(buff, "0.1000000"))
return FALSE;
result = gsl_cdf_chisq_P(-2*log(.1),2);
safef(buff, sizeof(buff), "%.7f", result);
if(differentString(buff, "0.9000000"))
return FALSE;
result = gsl_cdf_chisq_P(-2*(log(.1)+log(.9)+log(.5)),6);
safef(buff, sizeof(buff), "%.7f", result);
if(differentString(buff, "0.5990734"))
return FALSE;
result = gsl_cdf_chisq_P(-2*(log(.8)+log(.8)),4);
safef(buff, sizeof(buff), "%.8f", result);
if(differentString(buff, "0.07437625"))
return FALSE;
return TRUE;
}
boolean testPathContains(struct unitTest *test)
/* Test the path contains block functionality. */
{
struct splice *ndr2 = ndr2CassTest();
struct path *skipPath = NULL, *incPath = NULL;
struct dyString *error = newDyString(128);
boolean result = TRUE, currentResult = TRUE;
skipPath = ndr2->paths;
incPath = ndr2->paths->next;
if(pathContainsIntron(ndr2, skipPath, "chr14", 43771385+15, 43772095-15, "-") != TRUE)
currentResult = FALSE;
if(pathContainsIntron(ndr2, skipPath, "chr14", 43771385+15, 43771715-15, "-") != FALSE)
currentResult = FALSE;
if(pathContainsIntron(ndr2, skipPath, "chr14", 43771727+15, 43772095-15, "-") != FALSE)
currentResult = FALSE;
if(currentResult == FALSE)
{
dyStringPrintf(error, "Problem with placing introns on skip path, ");
result = FALSE;
}
currentResult = TRUE;
if(pathContainsIntron(ndr2, incPath, "chr14", 43771385+15, 43772095-15, "-") != FALSE)
currentResult = FALSE;
if(pathContainsIntron(ndr2, incPath, "chr14", 43771385+15, 43771715-15, "-") != TRUE)
currentResult = FALSE;
if(pathContainsIntron(ndr2, incPath, "chr14", 43771727+15, 43772095-15, "-") != TRUE)
currentResult = FALSE;
if(currentResult == FALSE)
{
dyStringPrintf(error, "Problem with placing introns on skip path, ");
result = FALSE;
}
currentResult = TRUE;
if(pathContainsBlock(ndr2, incPath, "chr14", 43771727, 43771727+15, "-", TRUE) != TRUE)
currentResult = FALSE;
if(pathContainsBlock(ndr2, incPath, "chr14", 43771703, 43771735, "-", TRUE) != TRUE)
currentResult = FALSE;
if(pathContainsBlock(ndr2, skipPath, "chr14", 43771703, 43771735, "-", TRUE) != FALSE)
currentResult = FALSE;
if(currentResult == FALSE)
{
dyStringPrintf(error, "Problem placing blocks with all bases, ");
result = FALSE;
}
currentResult = TRUE;
if(pathContainsBlock(ndr2, incPath, "chr14", 43771727, 43771727+16, "-", TRUE) != FALSE)
currentResult = FALSE;
if(pathContainsBlock(ndr2, incPath, "chr14", 43771727, 43771727+16, "-", FALSE) != TRUE)
currentResult = FALSE;
if(currentResult == FALSE)
{
dyStringPrintf(error, "Problem placing blocks with not all bases, ");
result = FALSE;
}
test->errorMsg = cloneString(error->string);
dyStringFree(&error);
return result;
}
boolean testPathContainsBed(struct unitTest *test)
/* Test to see if a path contains the right stuff. */
{
struct splice *ndr2 = ndr2CassTest();
struct bed *bedList = ndr2BedTest(), *bed = NULL;
/* 1 include, 2 skip, 3 include, 4 gene. */
struct path *skipPath = NULL, *incPath = NULL;
boolean result = TRUE;
struct dyString *error = newDyString(128);
skipPath = ndr2->paths;
incPath = ndr2->paths->next;
/* First include. */
bed = bedList;
if(pathContainsBed(ndr2, skipPath, bed, TRUE) != FALSE)
{
result = FALSE;
dyStringPrintf(error, "Matching include bed to skip, ");
}
if(pathContainsBed(ndr2, incPath, bed, TRUE) != TRUE)
{
result = FALSE;
dyStringPrintf(error, "Not matching include bed to include, ");
}
/* Skip probe set. */
bed = bed->next;
if(pathContainsBed(ndr2, skipPath, bed, TRUE) != TRUE)
{
result = FALSE;
dyStringPrintf(error, "Not matching skip bed to skip, ");
}
if(pathContainsBed(ndr2, incPath, bed, TRUE) != FALSE)
{
result = FALSE;
dyStringPrintf(error, "Matching skip bed to include, ");
}
/* Second include. */
bed = bed->next;
if(pathContainsBed(ndr2, skipPath, bed, TRUE) != FALSE)
{
result = FALSE;
dyStringPrintf(error, "Matching 2nd include bed to skip, ");
}
if(pathContainsBed(ndr2, incPath, bed, TRUE) != TRUE)
{
result = FALSE;
dyStringPrintf(error, "Not matching 2nd include bed to include, ");
}
/* Gene probe set. */
bed = bed->next;
if(pathContainsBed(ndr2, skipPath, bed, FALSE) != FALSE)
{
result = FALSE;
dyStringPrintf(error, "Matching gene set to skip path, ");
}
if(pathContainsBed(ndr2, incPath, bed, FALSE) != FALSE)
{
result = FALSE;
dyStringPrintf(error, "Matching gene set to include path, ");
}
test->errorMsg = cloneString(error->string);
dyStringFree(&error);
return result;
}
struct altEvent *setupNdr2AltEvent()
/* Setup an ndr2 fake event for testing. */
{
struct splice *splice = ndr2CassTest();
struct altEvent *event = NULL;
struct path *path = NULL;
struct altPath *altPath = NULL;
struct dMatrix *probM = ndr2BedTestMat(TRUE);
struct dMatrix *intenM = ndr2BedTestMat(FALSE);
double expression = 0;
AllocVar(event);
event->splice = splice;
AllocArray(event->geneExpVals, 1);
AllocArray(event->genePVals, 1);
event->geneProbeCount = 1;
event->altPathProbeCount = 2;
event->geneExpVals[0] = intenM->matrix[3];
event->genePVals[0] = probM->matrix[3];
AllocVar(altPath);
altPath->path = splice->paths;
altPath->probeCount = 1;
AllocArray(altPath->expVals, altPath->probeCount);
altPath->expVals[0] = intenM->matrix[1];
AllocArray(altPath->pVals, altPath->probeCount);
altPath->pVals[0] = probM->matrix[1];
slAddHead(&event->altPathList, altPath);
AllocVar(altPath);
altPath->path = splice->paths->next;
altPath->probeCount = 2;
AllocArray(altPath->expVals, altPath->probeCount);
altPath->expVals[0] = intenM->matrix[0];
altPath->expVals[1] = intenM->matrix[2];
AllocArray(altPath->pVals, altPath->probeCount);
altPath->pVals[0] = probM->matrix[0];
altPath->pVals[1] = probM->matrix[2];
slAddHead(&event->altPathList, altPath);
slReverse(&event->altPathList);
return event;
}
boolean testAltPathProbesExpressed(struct unitTest *test)
/* Test to see if presense abs software is calling. */
{
struct altEvent *event = setupNdr2AltEvent();
struct dyString *error = newDyString(128);
double expression = 0;
boolean result = TRUE;
useMaxProbeSet = TRUE;
if(altPathProbesExpressed(event, event->altPathList->next, 1, 0, &expression) != FALSE)
{
result = FALSE;
dyStringPrintf(error, "Max probe set calling false positive, ");
}
if(altPathProbesExpressed(event, event->altPathList, 0, 3, &expression) != TRUE)
{
result = FALSE;
dyStringPrintf(error, "Max probe set calling positive false, ");
}
useMaxProbeSet = FALSE;
useComboProbes = TRUE;
if(altPathProbesExpressed(event, event->altPathList->next, 1, 0, &expression) != TRUE)
{
result = FALSE;
dyStringPrintf(error, "Combo probes not combining correctly, ");
}
test->errorMsg = cloneString(error->string);
dyStringFree(&error);
return result;
}
boolean sameDouble(double d1, double d2)
/* Check to see if these are the same doubles to 6 sig digits. */
{
char buff1[128], buff2[128];
safef(buff1, sizeof(buff1), "%.6f", d1);
safef(buff2, sizeof(buff2), "%.6f", d2);
return sameString(buff1, buff2);
}
boolean testExpressionRatio(struct unitTest *test)
/* Test to see if the ratios are calculated properly for expresionRatio() */
{
struct altEvent *event = setupNdr2AltEvent();
struct dyString *error = newDyString(128);
double expression = 0;
boolean result = TRUE;
boolean current = FALSE;
struct altPath *skipPath = event->altPathList;
struct altPath *incPath = event->altPathList->next;
double tmpThresh = presThresh;
presThresh = absThresh;
current = sameDouble(expressionRatio(event, skipPath, incPath, 0), 1);
result &= unitTestFunct(test, current, error, "Averaging");
current = sameDouble(expressionRatio(event, skipPath, incPath, 2), 2);
result &= unitTestFunct(test, current, error, "Low expressed");
current = sameDouble(expressionRatio(event, skipPath, incPath, 3), .5);
result &= unitTestFunct(test, current, error, "Averaging");
presThresh = tmpThresh;
return result;
}
boolean testBrainSpecific(struct unitTest *test)
/* Test to see if ndr2 is brain specific (which it should be). */
{
struct altEvent *event = setupNdr2AltEvent();
boolean result = FALSE;
int **expressed = NULL;
int **notExpressed = NULL;
double **expression = NULL;
struct altPath *altPath = NULL;
int pathCount = slCount(event->altPathList);
int pathIx = 0;
int pathExpCount = 0;
int i = 0;
struct dMatrix *probM = ndr2BedTestMat(TRUE);
struct dMatrix *intenM = ndr2BedTestMat(FALSE);
/* Allocate a 2D array for expression. */
AllocArray(expressed, pathCount);
AllocArray(notExpressed, pathCount);
AllocArray(expression, pathCount);
for(i = 0; i < pathCount; i++)
{
AllocArray(expressed[i], probM->colCount);
AllocArray(notExpressed[i], probM->colCount);
AllocArray(expression[i], intenM->colCount);
}
for(altPath = event->altPathList; altPath != NULL; altPath = altPath->next)
{
if (altPathExpressed(event, altPath, intenM, probM,
expressed, notExpressed, expression, pathIx))
pathExpCount++;
pathIx++;
}
result = brainSpecific(event, altPath, 1, expressed, notExpressed, 2, probM);
if(result != TRUE)
test->errorMsg = cloneString("Not showing brain expressed.");
/* Cleanup some memory. */
for(i = 0; i < pathCount; i++)
{
freez(&expressed[i]);
freez(¬Expressed[i]);
freez(&expression[i]);
}
freez(¬Expressed);
freez(&expressed);
freez(&expression);
return result;
}
void initTests()
{
struct unitTest *test = NULL;
/* Testing stat routines. */
AllocVar(test);
test->test = testCdfChiSqP;
test->description = "GSL ChiSq function";
slAddHead(&tests, test);
/* Testing motif matching. */
AllocVar(test);
test->test = testStringOccurance;
test->description = "Motif searching";
slAddHead(&tests, test);
/* Testing finding blocks on paths. */
AllocVar(test);
test->test = testPathContains;
test->description = "Match introns and exon blocks to paths";
slAddHead(&tests, test);
/* Testing finding blocks on paths. */
AllocVar(test);
test->test = testPathContainsBed;
test->description = "Match beds to paths";
slAddHead(&tests, test);
/* Testing finding blocks on paths. */
AllocVar(test);
test->test = testAltPathProbesExpressed;
test->description = "Call paths as expressed or not.";
slAddHead(&tests, test);
/* Testing expression ratio generation. */
AllocVar(test);
test->test = testExpressionRatio;
test->description = "Generate expression ratios.";
slAddHead(&tests, test);
/* Testing brain specificity. */
AllocVar(test);
test->test = testBrainSpecific;
test->description = "Brain Specific detection.";
slAddHead(&tests, test);
slReverse(&tests);
}
void runTests()
{
struct unitTest *test, *testNext, *passed = NULL, *failed = NULL;
boolean passedAll = TRUE;
int passCount = 0, *failCount = 0;
for(test = tests; test != NULL; test = testNext)
{
testNext = test->next;
if(test->test(test) != FALSE)
{
passCount++;
slAddHead(&passed, test);
}
else
{
slAddHead(&failed, test);
passedAll = FALSE;
failCount++;
}
}
if(passedAll)
{
fprintf(stdout, "Passed all %d tests.\n", passCount);
exit(0);
}
else
{
fprintf(stdout, "Failed tests:\n");
for(test = failed; test != NULL; test = test->next)
{
fprintf(stdout, "%-40s\tFAILED\t%s\n", test->description,
test->errorMsg == NULL ? "" : test->errorMsg);
}
exit(1);
}
}
void initCassetteBedsOut()
{
struct dyString *buff = NULL;
char *prefix = optionVal("cassetteBeds", NULL);
assert(prefix);
buff = newDyString(strlen(prefix)+20);
dyStringClear(buff);
dyStringPrintf(buff, "%s.altExpressed.bed", prefix);
altCassetteBedOut = mustOpen(buff->string, "w");
dyStringClear(buff);
dyStringPrintf(buff, "%s.expressed.bed", prefix);
expressedCassetteBedOut = mustOpen(buff->string, "w");
dyStringClear(buff);
dyStringPrintf(buff, "%s.notExpressed.bed", prefix);
notExpressedCassetteBedOut = mustOpen(buff->string, "w");
}
void initNotHumanCassettes()
/* Load up cassettes that we think are notHuman. */
{
char *file = optionVal("notHumanCassettes", NULL);
struct bed *bed = NULL, *bedList = NULL;
char buff[256];
notHumanHash = newHash(10);
assert(file);
bedList = bedLoadAll(file);
for(bed = bedList; bed != NULL; bed = bed->next)
{
safef(buff, sizeof(buff), "%s:%d-%d:%s", bed->chrom, bed->chromStart,bed->chromEnd, bed->strand);
hashAdd(notHumanHash, buff, bed);
}
}
void initConservedCassettes()
/* Load up cassettes that we think are conserved. */
{
char *file = optionVal("conservedCassettes", NULL);
struct bed *bed = NULL, *bedList = NULL;
char buff[256];
conservedHash = newHash(10);
assert(file);
bedList = bedLoadAll(file);
for(bed = bedList; bed != NULL; bed = bed->next)
{
safef(buff, sizeof(buff), "%s:%d-%d:%s", bed->chrom, bed->chromStart,bed->chromEnd, bed->strand);
hashAdd(conservedHash, buff, bed);
}
}
void initConstMotifCounts()
/* Initialize file for reporting motif counts in constitutive exons. */
{
int i = 0;
constMotifCounts = mustOpen("constitutiveMotifCounts.tab", "w");
/* Do the first n-1 with tabs. */
for(i=0; i<bindSiteCount-1; i++)
{
fprintf(constMotifCounts, "%s-up\t%s-down\t",
bindSiteArray[i]->rnaBinder, bindSiteArray[i]->rnaBinder);
}
/* Last one with newline. */
fprintf(constMotifCounts, "%s-up\t%s-down\n",
bindSiteArray[i]->rnaBinder, bindSiteArray[i]->rnaBinder);
}
void setOptions()
/* Set up some options. */
{
char *selectedPValues = optionVal("selectedPValues", NULL);
if(optionExists("doTests"))
{
initTests();
runTests();
}
presThresh = optionFloat("presThresh", .9);
pvalThresh = optionFloat("pValThresh", .001);
tissueExpThresh = optionInt("tissueExpThresh", 1);
otherTissueExpThres = optionInt("otherTissueExpThres", 1);
useMaxProbeSet = optionExists("useMaxProbeSet");
db = optionVal("db", NULL);
browserName = optionVal("browser", "hgwdev-sugnet.gi.ucsc.edu");
useComboProbes = optionExists("combinePSets");
useExonBedsToo = optionExists("useExonBeds");
skipMotifControls = optionExists("skipMotifControls");
newDb = optionVal("newDb", NULL);
if(optionExists("newDb"))
initLiftOver();
if(optionExists("psToRefGene"))
initPsToRefGene();
if(optionExists("psToKnownGene"))
initPsToKnownGene();
if(optionExists("phastConsScores"))
initPhastConsScores();
if(optionExists("splicePVals"))
initSplicePVals();
if(optionExists("cassetteBeds"))
initCassetteBedsOut();
if(optionExists("conservedCassettes"))
initConservedCassettes();
if(optionExists("notHumanCassettes"))
initNotHumanCassettes();
if(optionExists("controlStats"))
{
controlValuesVm = newValuesMat(1000, 15);
controlValuesOut = mustOpen(optionVal("controlStats", NULL), "w");
}
if(optionExists("sortScore"))
{
initSortScore();
}
if(selectedPValues != NULL)
{
char *selectedPValFile = optionVal("selectedPValFile", NULL);
char buff[2048];
if(selectedPValFile == NULL)
errAbort("Must specify a selectedPValFile when enabling selectedPValues");
readSelectedList(selectedPValues);
pathProbabilitiesOut = mustOpen(selectedPValFile, "w");
safef(buff, sizeof(buff), "%s.bed", selectedPValFile);
pathProbabilitiesBedOut = mustOpen(buff, "w");
safef(buff, sizeof(buff), "%s.intensity", selectedPValFile);
pathExpressionOut = mustOpen(buff, "w");
}
if(useMaxProbeSet)
warn("Using max value from all probe sets in a path.");
/* Set up the datbase. */
db = optionVal("db", NULL);
if(db != NULL)
hSetDb(db);
else
errAbort("Must specify database.");
initBindSiteList();
if (!skipMotifControls)
initConstMotifCounts();
if(optionVal("brainSpecific", NULL) != NULL)
initBrainSpecific();
}
int main(int argc, char *argv[])
/* Everybody's favorite function... */
{
if(argc == 1)
usage();
optionInit(&argc, argv, optionSpecs);
if(optionExists("help"))
usage();
setOptions();
altProbes();
return 0;
}
| {
"alphanum_fraction": 0.670377991,
"avg_line_length": 32.3334715026,
"ext": "c",
"hexsha": "a29928fbae7a53cc656fa14e8b1b903b9de53f7a",
"lang": "C",
"max_forks_count": 80,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T16:36:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-04-16T10:39:48.000Z",
"max_forks_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "andypohl/kent",
"max_forks_repo_path": "src/hg/altSplice/affySplice/altProbes.c",
"max_issues_count": 60,
"max_issues_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1",
"max_issues_repo_issues_event_max_datetime": "2022-03-30T15:21:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-03T15:15:06.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "andypohl/kent",
"max_issues_repo_path": "src/hg/altSplice/affySplice/altProbes.c",
"max_line_length": 620,
"max_stars_count": 171,
"max_stars_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "andypohl/kent",
"max_stars_repo_path": "src/hg/altSplice/affySplice/altProbes.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T20:21:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-22T15:16:02.000Z",
"num_tokens": 45889,
"size": 156009
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_sf_bessel.h>
#include "utility.h"
#include "constants.h"
#include <gsl/gsl_cblas.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <omp.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_pow_int.h>
#ifdef EXTERN_VARIABLES
#define EXTERN
#else
#define EXTERN extern
#endif
#define OSSZI 14000
#define SIMULATIONEN 10
#define KUPF_BINARY 1 // set to 1 for Kupferman/ fully mobile bath
#define VIRTUAL_FLAG 0 // set to 1 to transfer force one way onto virtual particle, no bath recouoling
#define SIMPSON_BINARY 1
#define REFLECTALL_FLAG 0
#define OMMEGA_READ_BINARY 0 // if true, don't regenerate ommega. use ommega.dat
#define DIM 1
#define ORDER ((2 * OSSZI + 2) * DIM)
#define LABELPREFIX "GIT_HUB" //a string to add to your result folder
#define T_POWERS 0 // no function, just compiler needs to know
#define T_MULT 1.0 // same
#define LOGSCALE_BINARY 0 // leave at 0, toggles time setup. WIP
#define TIME_STEPS 0.05 // snapshot intervall for saved values
#define LENGTH_T 1000 + 9 // Number N of saved steps (format must be N +9)
#define TIME_SHIFT 500
#define TIME_END (double)((double) (LENGTH_T-9) * TIME_STEPS) //leave macro as is
//#endif
#define THREADSNR 1 // most efficient at dimension
#define KBOLTZ 1.380641e-8
#define TEMP 100.0
#define GAMMA 1.0 // drag
#define LOWER_CUTOFF_FLAG 0 // 1 for lower cutoff frequency when settinh up the ommega
#define ALPHA 0.8 // exponent free random walk msqdplcmnt t^alpha
#define mass 1.0 // mass tracer particle
#define TIME_ARRIVAL 3000.0 // Diffusion time over lattice cell
#define MAXSTEPSIZE_BINARY 0 // set to 1 to decouple from smallest period to fixed N * DT = MAXSTEPSIEMULT
#define MAXSTEPSIZEMULT 5.0e-4 // stepsize in terms of shortest period scale
#define NUMBER_TO_INF (500) // muss gerade sein, hindernisse die Symetrisch um null verteilt sind in 1-D
#define VOL_FRAC 0.0
#define LABEL "ZWANZIG_THERMALIZED" // "ZWANZIG" or "ZWANZIG_THERMALISED"
#define SUMMATION_METHOD Neumaier_Sum // Sign_, Kahan oder Neumaier_ gefolgt von sum
#define STEPPER_METHOD VVerlet_Step_deriv_Box //bis jetzt VVerlet_Step_Target_Square oder VVerlet_Step_deriv oder VVerlet_Step_Yukawa Verlet_Step_Target_Pore_Rectangle
#define POTI_HANDLE deriv_parallel
#define NORM_INT 0 // für Norm_Diff die art der p-norm, 0 für infty
#define MAX_NR_PLOTS 50
#define ESCAPE_CELLS 0 // anzahl der gitterzellen ohne hinderniss -1
#define REFLEC_BINARY 1 // toggle bewteewn reflecting new(1) or old(0) velocity, or no velcotiy adjust (2)
#define FLAG_RAND_BATH 0 // set 1 for unifrom random bath, 0 for uniform deteriministic
#define DENSITY_SAMPLING_LENGTH 10
#define DENSITY_SAMPLING_POINTS 10
#define DIFF_COEFF_MODIFY 0.01 // modify for VVerlet_Step_drag_sphere
#define DENSITY_SNAPSHOTS 5
#define TARGET_METHOD Get_Lattice_Targets_Corner_Square // method to determine free cells
#define PARALLEL //nicht definieren falls ohne -fopenmp compiliert!
#ifdef PARALLEL
#define THREADS THREADSNR
#define SETNUMTHREADS omp_set_num_threads(THREADSNR);
#else
#define SETNUMTHREADS
#define THREADS 1 //wichtig zur zeitberechnung dass dann THREADS auf 1 gesetzt wird, wenn nicht parallel operiert
#endif
//#define OCL
#ifdef OCL
#define VVERLET Opencl_VVerlet
#else
#define VVERLET VVerlet_parallel
#endif
EXTERN int FLAG_DUMP_VALUE; // if error occurs set 1, dump calculation, start fresh
EXTERN int NUMBER_PORE_OBSTACLES; //number of spheres in Yukawa pore wall per side
EXTERN double LATTICE_SPACING;
EXTERN double DIFF_COEFF;
EXTERN double TARGET_LENGTH;
EXTERN double VIRTUAL_X[DIM];
EXTERN double VIRTUAL_V[DIM];
EXTERN int OUTPUT_FLAG; //set 1 before first output, after that 0 to hide messages
// from Setuo functions for ommega and gamma
EXTERN int TARGET_CONTACT; // counts number of hits on lattice
EXTERN int TARGET_FLAG; // Toggles after first hit per run
EXTERN int lattice_position[DIM]; // aktuelle Gitterzelle
EXTERN double massq[OSSZI];
EXTERN double time_first_contact;
EXTERN double coupling[OSSZI]; //Koppl. Konst. Gamma im Zwanzig
EXTERN double ommega[OSSZI]; // Osszi Kreisfreq
EXTERN double y[ORDER]; // Startvec
EXTERN double MAXSTEPSIZE; //Schrittweite Integrator
EXTERN double LASTSTEPSIZE;
EXTERN int **POSITIONS; //enthält Koordinated der Gitterpunkte
EXTERN double L_BALL; // ballistische Länge der Diffusion
EXTERN int (*Sum_Method)(int N, double input[], double *ans);
EXTERN void (*Poti_Handle)(const double *y, double *ans, double t,int N); // externe oder Hindernisskraft
EXTERN void (*Stepper_Method)(int N, double x[N/2] , double v[N/2], double a[N/2], double *t,
void (*deriv) (double *y, double *ans, double t,int N));
// Methode mit oder ohne Hindernisse für Verlet_schritt
EXTERN gsl_rng * RAND_GLOBAL; // globally accessible random variable
| {
"alphanum_fraction": 0.7518334985,
"avg_line_length": 44.6460176991,
"ext": "h",
"hexsha": "11f51cd1a76082ccbd1c468785dde741ebdb6891",
"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": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_forks_repo_path": "global.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"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": "nowottnm/KAC_ZWANZIG_SIM",
"max_issues_repo_path": "global.h",
"max_line_length": 167,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_stars_repo_path": "global.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1516,
"size": 5045
} |
#ifndef UTILITIES_H
#define UTILITIES_H
#include <gsl/gsl_rng.h>
#include <gsl/gsl_histogram.h>
#include <fftw3.h>
gsl_rng * init_rng(void);
void allocate_arrays(double ** signal, double ** spectrum,
const size_t length);
gsl_histogram * init_histogram(const double r_min, const double r_max,
const size_t bin_n);
gsl_histogram * init_histogram_uniform(const double r_min, const double r_max,
const size_t bin_n);
void load_wisdom(const char * filename);
fftw_plan make_plan(double * signal, const size_t length);
void make_fft(fftw_plan plan);
void remove_mean(double * signal, const size_t length);
void compute_spectrum(const double * signal, double * spectrum,
const size_t length);
void smooth(const unsigned neighbors, double *spectrum, const size_t length);
void final_spectrum(double *spectrum, const size_t length,
const unsigned count, const double delta, const unsigned neighbors);
double frequency(const size_t i, const size_t length, const double delta);
void output_spectrum(const char * filename, const double * spectrum,
const size_t length, const double delta, const size_t n_points);
void output_signal(const char * filename, const double * signal,
const size_t length, const double delta, const size_t n_points);
void output_signal_full(const char * filename, const double * signal,
const size_t length, const double delta);
void output_distribution(const char * filename, const gsl_histogram * hist);
void cleanup(double * signal, double * spectrum, fftw_plan plan, gsl_rng * r,
gsl_histogram * hist);
#endif
| {
"alphanum_fraction": 0.7657828283,
"avg_line_length": 30.4615384615,
"ext": "h",
"hexsha": "b7d82778d9409d5db306bff1bbfc8f3adf526d96",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "JuliusRuseckas/numerical-sde-variable-step",
"max_forks_repo_path": "utilities.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "JuliusRuseckas/numerical-sde-variable-step",
"max_issues_repo_path": "utilities.h",
"max_line_length": 78,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "6204ac9d212fd6c73751d215c49e95373b573430",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "JuliusRuseckas/numerical-sde-variable-step",
"max_stars_repo_path": "utilities.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-25T07:04:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-28T09:12:48.000Z",
"num_tokens": 351,
"size": 1584
} |
#ifndef _CHAIN_H_
#define _CHAIN_H_
/* ---------------------------------------------------------
headers
--------------------------------------------------------- */
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <iostream>
#include <vector>
// my headers
#include <md.h>
#include <debug.h>
#include "dcdio.h"
// headers 3rd
/* #include <armadillo> */
/* #include <gsl/gsl_math.h> */
/* #include <gsl/gsl_eigen.h> */
/* #include "boost/multi_array.hpp" */
#include <cassert>
/* SYMLINK: Eigen /usr/local/include/. */
/* [dale~/sop_dev/contacts/segment]$lt /usr/local/include/eigen */
/* lrwxrwxrwx 1 root root 25 09.25.2015 21:04 /usr/local/include/eigen -> /usr/include/eigen3/Eigen/ */
/* #include<Eigen/Eigenvalues> */
/* #include <Eigen/Dense> */
#ifdef INERTIA
#include <Eigen/Core>
#include <Eigen/Eigenvalues>
using namespace Eigen;
#endif // INERTIA
/* using namespace Eigen; */
// namespaces
/* using namespace arma; */
/* ---------------------------------------------------------
definitions
--------------------------------------------------------- */
/* 2000, 100; 700,20; 500,50 */
#if defined ONEMOL || defined ALLATOM
#define MOLECULE_INITIAL_SIZE 6900
#define MOLECULE_INITIAL_SIZE_MT 6900
#else
#define MOLECULE_INITIAL_SIZE 700
#define MOLECULE_INITIAL_SIZE_MT 700
#endif // ONEMOL
#define MAX_CONTACTS 24 /* per atom */
class Contact {
public:
/* int resid; */
int cresid;
int total;
int index; // index
int cindex; // contacted index
double eh; // energy scaling (well depth)
double distance;
// Constructor
Contact (); // Constructor declared.
// Destructors:
~Contact() {
/* delete [] pos; */
};
};
inline Contact::Contact() {
cresid = -1;
index = -1;
cindex = -1;
total = -1;
eh = 0.0; // keep at 0.0, used in assign_contact_eh as default
distance = 0.0;
}
typedef struct Chain Molecule;
class Chain {
public:
char filename[46];
int chainid;
int num_atoms;
int num_atoms_ca;
int index;
int findex;
int pf_pos_low; // for selecting index near midpoint of centroids, curvature of PF
int pf_pos_high;
int file_line_begin;
int file_line_end;
char atomtype[MOLECULE_INITIAL_SIZE][4];
char resname[MOLECULE_INITIAL_SIZE][4];
int resid[MOLECULE_INITIAL_SIZE];
int indices[MOLECULE_INITIAL_SIZE]; // not used yet.
Vector pos[MOLECULE_INITIAL_SIZE];
Contact contacts[MOLECULE_INITIAL_SIZE][MAX_CONTACTS];
int total_num_contacts_2x;
int tally_num_contacts_2x[MOLECULE_INITIAL_SIZE];
int num_contacts_2x_persist_ref[MOLECULE_INITIAL_SIZE];
Vector centroid;
int nearest_targets[32];
double nearest_targets_dist[32];
int nearestneighbors_chainid[8];
double nearestneighbors_dist[8];
int LonN; // contacted monomer
int LatE;
int LonS;
int LatW;
int LonN_total2x; // total
int LatE_total2x;
int LonS_total2x;
int LatW_total2x;
// general inter
Contact intercontacts[MOLECULE_INITIAL_SIZE][MAX_CONTACTS];
// latlon contacts
Contact contactsLonN[MOLECULE_INITIAL_SIZE][MAX_CONTACTS];
Contact contactsLatE[MOLECULE_INITIAL_SIZE][MAX_CONTACTS];
Contact contactsLonS[MOLECULE_INITIAL_SIZE][MAX_CONTACTS];
Contact contactsLatW[MOLECULE_INITIAL_SIZE][MAX_CONTACTS];
// Constructors:
Chain(int a=-1, int b = 0, double p = 0.0, double q = -1.0) {
chainid = a;
num_atoms = a;
num_atoms_ca = a;
index = a;
findex = a;
pf_pos_low = a;
pf_pos_high = a;
file_line_begin = a;
file_line_end = a;
total_num_contacts_2x = a;
centroid.x = p;
centroid.y = p;
centroid.z = p;
LonN = a;
LonS = a;
LatW = a;
LatE = a;
// initialize to 0.0 p
for (int i=0; i < MOLECULE_INITIAL_SIZE; i++ ) {
pos[i].x = p;
pos[i].y = p;
pos[i].z = p;
// initialize to 0 b
tally_num_contacts_2x[i] = b;
num_contacts_2x_persist_ref[i] = b;
for ( int j=0; j < MAX_CONTACTS; j++ ) {
contacts[i][j].cresid = a;
contacts[i][j].distance = p;
}
for ( int j=0; j < 8; j++ ) {
nearestneighbors_chainid[j] = -1;
nearestneighbors_dist[j] = p;
}
for ( int j=0; j < 32; j++ ) {
nearest_targets[j] = a;
}
}
}
// Destructors:
~Chain() {
/* delete [] pos; */
/* std::cout << "Object is being deleted" << std::endl; */
};
// Declarations:
void print_prop();
void assign_indices();
void fprintf_indices();
void GetMomentofInertiaTensor();
void ComputeCentroid();
void print_centroid();
int countcontacts(Contact (*map)[MAX_CONTACTS]);
};
inline void Chain::ComputeCentroid() {
int i;
double xtot = 0.0, ytot = 0.0, ztot = 0.0;
/* printf("computing centroid ca: %d\n",num_atoms_ca); */
for ( int i=0; i < num_atoms_ca; i++ ) {
/* printf("%d\n",i); */
xtot += pos[i].x;
ytot += pos[i].y;
ztot += pos[i].z;
}
centroid.x = xtot / num_atoms_ca;
centroid.y = ytot / num_atoms_ca;
centroid.z = ztot / num_atoms_ca;
// PRINT HERE
/* debug("c(%d): %f %f %f\n",chainid,centroid.x,centroid.y,centroid.z); */
}
// amazing!!
/* By declared that method with inline keyword, compiler will either inline */
/* the whole method or, if it decides not to, it will generate anonymous */
/* method (same method but with some unique name for a given object file), */
/* so there will be no conflicts in object files. For example: */
/* class foo { */
/* public: */
/* void bar (); */
/* }; */
/* inline void foo::bar () */
/* { */
/* } */
inline void Chain::print_prop() {
/* printf("id: %d ",chainid); */
/* printf(" filename: %s\n",filename); */
/* printf("CA: %d ",num_atoms_ca); */
/* printf(" index(%d) ",index); */
/* printf(" final_index(%d)\n",findex); */
/* printf("begin_end: [ %d %d ]\n\n",file_line_begin,file_line_end); */
/* debug("id: %d CA: %d\n",chainid,num_atoms_ca); */
/* debug(" filename: %s\n",filename); */
/* debug("CA: %d \n",num_atoms_ca); */
/* debug(" index(%d) \n",index); */
/* debug(" final_index(%d)\n",findex); */
/* debug("begin_end: [ %d %d ]\n",file_line_begin,file_line_end); */
printf("centroid: %f %f %f\n",centroid.x,centroid.y,centroid.z);
}
inline void Chain::print_centroid() {
printf("centroid: %f %f %f\n",centroid.x,centroid.y,centroid.z);
}
inline void Chain::assign_indices() {
/* printf("id: %d ",chainid); */
/* printf(" filename: %s\n",filename); */
/* printf("CA: %d ",num_atoms_ca); */
/* printf(" index(%d) ",index); */
/* printf(" final_index(%d)\n",findex); */
/* printf("begin_end: [ %d %d ]\n\n",file_line_begin,file_line_end); */
debug("id: %d atoms:%d CA:%d\n",chainid,num_atoms,num_atoms_ca);
/* debug(" filename: %s\n",filename); */
/* debug("CA: %d \n",num_atoms_ca); */
/* debug(" index(%d) \n",index); */
/* debug(" final_index(%d)\n",findex); */
debug("begin_end: [ %d %d ]\n",file_line_begin,file_line_end);
for( int i=0; i < num_atoms_ca; i++ ) {
indices[i] = index + i;
}
}
inline void Chain::fprintf_indices() {
/* printf(" index(%d) ",index); */
/* printf(" final_index(%d)\n",findex); */
printf(" %d__[%d|%d]\n",chainid,index,findex);
FILE * fp_indices;
fp_indices = fopen("indices_foreach_segments.dat","a+");
for ( int i=0; i < num_atoms_ca; i++ ) {
fprintf(fp_indices,"%6d %6d %6d\n",chainid,index,findex);
}
fclose(fp_indices);
/* for( int i=0; i < num_atoms_ca; i++ ) { */
/* /\* indices[i] = index + i; *\/ */
/* printf(" %d",indices[i]); */
/* printf(" ") */
/* } */
/* printf("\n"); */
}
inline int Chain::countcontacts(Contact (*map)[MAX_CONTACTS]) {
/* printf("declare countcontacts!\n"); */
int count = 0;
// using 0,3 indices. 1,4, 2,5, ... 430,433
for(int i=0; i<MOLECULE_INITIAL_SIZE; i++){
// for(int j=0; j<MAX_CONTACTS; j++){
for(int k=0; k<MAX_CONTACTS; k++){
if(map[i][k].cresid == -1){
break;
} else {
count ++;
// printf("%d-%d (%d) %d/50\n",i,map[i][k].cresid,count,k);
}
// printf(" %d",map[i][k].index);
// map[num1][k].cindex = chain[num1].indices[j];
// double eh; // energy scaling (well depth)
// map[num1][k].distance = dist;
// if(map[i][k].cresid != -1){
// count ++;
// } // if
// } // for 3
// } // if
} // for 2
} // for 1
if(count != 0){
debug("declare total contacts in this map are: %d\n",count);
} else {
debug("empty map.\n");
}
// // map[chain_num].total = count;
return count;
}
#ifdef INERTIA
inline void Chain::GetMomentofInertiaTensor() {
/* printf("chain: %d; atoms: %d;\n",chainid,num_atoms_ca); */
double x2=0.0,y2=0.0,z2=0.0;
double xy=0.0,xz=0.0,yz=0.0;
double Ixx=0.0,Iyy=0.0,Izz=0.0;
double Ixy=0.0,Ixz=0.0,Iyz=0.0;
/* http://farside.ph.utexas.edu/teaching/336k/Newtonhtml/node64.html moment of Inertia Tensor */
/* http://farside.ph.utexas.edu/teaching/336k/Newtonhtml/node67.html get eigenvectors */
for(int a=0; a<num_atoms_ca; a++) {
/* for(int a=0; a<5; a++) { */
/* printf("%d",a); */
/* printf("%f %f %f\n",pos[a].x,pos[a].y,pos[a].z); */
x2 += pos[a].x * pos[a].x;
y2 += pos[a].y * pos[a].y;
z2 += pos[a].z * pos[a].z;
xy += pos[a].x * pos[a].y;
xz += pos[a].x * pos[a].z;
yz += pos[a].y * pos[a].z;
Ixx += y2 + z2;
Iyy += x2 + z2;
Izz += x2 + y2;
Ixy += pos[a].x * pos[a].y;
Ixz += pos[a].x * pos[a].z;
Iyz += pos[a].y * pos[a].z;
}
Ixy = Ixy * -1.0;
Ixz = Ixz * -1.0;
Iyz = Iyz * -1.0;
printf("xx_yy_zz: %f %f %f\n",Ixx,Iyy,Izz);
printf("xy_xz_yz: %f %f %f\n",Ixy,Ixz,Iyz);
// begin eigen library
Matrix3d A(3,3);
A(0,0) = Ixx;
A(0,1) = Ixy;
A(0,2) = Ixz;
A(1,0) = Ixy;
A(1,1) = Iyy;
A(1,2) = Iyz;
A(2,0) = Ixz;
A(2,1) = Iyz;
A(2,2) = Izz;
/* std::cout << "Here is the matrix A:\n" << A << std::endl; */
// build matrix
double InertiaTensor[3][3] = {
{Ixx, Ixy, Ixz},
{Ixy, Iyy, Iyz},
{Ixz, Iyz, Izz},
};
// Ixy xz yz are altered beyond this point.
double lowest_value_diag = Ixx;
if ( Iyy < Ixx ) {
if ( Izz < Iyy ) {
lowest_value_diag = Izz;
} else {
lowest_value_diag = Iyy;
}
} else if ( Izz < Ixx ) {
lowest_value_diag = Izz;
}
double lowest_value_offdiag;
if ( Ixy < 0.0 ) {
Ixy = -1.0 * Ixy;
}
if ( Ixz < 0.0 ) {
Ixz = -1.0 * Ixz;
}
if ( Iyz < 0.0 ) {
Iyz = -1.0 * Iyz;
}
lowest_value_offdiag = Ixy;
if ( Ixz < Ixy ) {
if ( Iyz < Ixz ) {
lowest_value_offdiag = Iyz;
} else {
lowest_value_offdiag = Ixz;
}
} else if ( Iyz < Ixy ) {
lowest_value_offdiag = Iyz;
}
double lowest_value;
if ( lowest_value_offdiag < lowest_value_diag ) {
lowest_value = lowest_value_offdiag;
} else {
lowest_value = lowest_value_offdiag;
}
printf("lv: %f\n",lowest_value);
lowest_value = lowest_value * 0.95;
/* printf("lv: %f\n",lowest_value); */
// Matrix entries * lowest_value;
/* // ORIGINAL EXAMPLE */
/* // Create a 3D array that is 3 x 4 x 2 */
/* typedef boost::multi_array<double, 3> array_type; */
/* typedef array_type::index index; */
/* array_type A(boost::extents[3][4][2]); */
/* // Assign values to the elements */
/* int values = 0; */
/* for(index i = 0; i != 3; ++i) */
/* for(index j = 0; j != 4; ++j) */
/* for(index k = 0; k != 2; ++k) */
/* A[i][j][k] = values++; */
/* // Verify values */
/* int verify = 0; */
/* for(index i = 0; i != 3; ++i) */
/* for(index j = 0; j != 4; ++j) */
/* for(index k = 0; k != 2; ++k) */
/* assert(A[i][j][k] == verify++); */
/* /\* return 0; *\/ */
/* ---------------------------------------------------------
boost! no eigenvalue/eigenvector
--------------------------------------------------------- */
/* // Create a 3D array that is 3 x 4 x 2 */
/* typedef boost::multi_array<double, 2> array_type; */
/* typedef array_type::index index; */
/* array_type A(boost::extents[3][3]); */
/* array_type B(boost::extents[3][3]); */
/* // x row */
/* A[0][0] = Ixx; */
/* A[0][1] = Ixy; */
/* A[0][2] = Ixz; */
/* // y row */
/* A[1][0] = Ixy; */
/* A[1][1] = Iyy; */
/* A[1][2] = Iyz; */
/* // y row */
/* A[2][0] = Ixz; */
/* A[2][1] = Iyz; */
/* A[2][2] = Izz; */
/* /\* // Verify values *\/ */
/* /\* int verify = 0; *\/ */
/* /\* for(index i = 0; i != 3; i++) { *\/ */
/* /\* for(index j = 0; j != 3; j++) { *\/ */
/* /\* /\\* assert(A[i][j] == verify++); *\\/ *\/ */
/* /\* // reassign by lowest_value scaling *\/ */
/* /\* printf("A: %f\n",A[i][j]); *\/ */
/* /\* } *\/ */
/* /\* } *\/ */
/* // Verify values A */
/* for(index i = 0; i != 3; i++) { */
/* for(index j = 0; j != 3; j++) { */
/* // reassign by lowest_value scaling */
/* A[i][j] = A[i][j] / lowest_value; */
/* printf("A/d: %f\n",A[i][j]); */
/* } */
/* } */
/* ---------------------------------------------------------
boost! no eigenvalue/eigenvector - END
--------------------------------------------------------- */
/* gsl_matrix_view m = gsl_matrix_view_array (InertiaTensor, 3, 3); */
/* gsl_vector *eval = gsl_vector_alloc (3); */
/* gsl_matrix *evec = gsl_matrix_alloc (3, 3); */
/* gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (3); */
/* gsl_eigen_symmv (&m.matrix, eval, evec, w); */
/* gsl_eigen_symmv_free (w); */
/* gsl_eigen_symmv_sort (eval,evec,GSL_EIGEN_SORT_ABS_ASC); */
/* { */
/* int i; */
/* for (i = 0; i < 4; i++) */
/* { */
/* double eval_i */
/* = gsl_vector_get (eval, i); */
/* gsl_vector_view evec_i */
/* = gsl_matrix_column (evec, i); */
/* printf ("eigenvalue = %g\n", eval_i); */
/* printf ("eigenvector = \n"); */
/* gsl_vector_fprintf (stdout, */
/* &evec_i.vector, "%g"); */
/* } */
/* } */
/* gsl_vector_free (eval); */
/* gsl_matrix_free (evec); */
/* return 0; */
// eigen continued
A = A / lowest_value;
std::cout << "Here is the matrix A:\n" << A << std::endl;
VectorXcd eivals = A.eigenvalues();
std::cout << "The eigenvalues of the 3x3 matrix of ones are:" << std::endl << eivals << std::endl;
/* VectorXcd eivecs = A.eigenvectors(); */
/* std::cout << "The eigenvalues of the 3x3 matrix of ones are:" << std::endl << eivecs << std::endl; */
EigenSolver<MatrixXd> es(A);
std::cout << "The first eigenvector of the 3x3 matrix of ones is:"
<< std::endl << es.eigenvectors().col(0) << std::endl;
std::cout << "The second eigenvector of the 3x3 matrix of ones is:"
<< std::endl << es.eigenvectors().col(1) << std::endl;
std::cout << "The third eigenvector of the 3x3 matrix of ones is:"
<< std::endl << es.eigenvectors().col(2) << std::endl;
/* Matrix3d m = Matrix3d::(3,3); */
/* cout << "m =" << endl << m << endl; */
}
#endif // INERTIA
/* class Map { */
/* /\* int num_atoms,max_contacts_per_atom; *\/ */
/* public: */
/* /\* std::vector< std::vector< std::vector<int>>> map; *\/ */
/* std::vector< std::vector<int> > map; */
/* /\* std::vector *\/ */
/* std::vector<Contact> contacts; */
/* // Constructor */
/* /\* Map(); *\/ */
/* /\* declarations: *\/ */
/* /\* void extend_map(int); *\/ */
/* void build_map_default(Chain *chain, int cid); // use chain_ref */
/* }; */
/* /\* inline Map::extend_map(int ca){ *\/ */
/* /\* for (int i=0; i<ca; i++) { *\/ */
/* /\* map.push_back(i); // ADD the ROW. *\/ */
/* /\* } *\/ */
/* /\* } *\/ */
/* inline void Map::build_map_default(Chain *chain,int cid){ */
/* // default: 8A */
/* /\* int count; *\/ */
/* double dist; */
/* Contact x; */
/* /\* ,y; *\/ */
/* for (int i=0; i<chain[cid].num_atoms_ca; i++) { */
/* /\* printf("%d\n",i); *\/ */
/* for(int j=i; j<chain[cid].num_atoms_ca; j++) { */
/* if ( i >= j-2 && i <= j+2) { */
/* // exclude j = i +/- 2 */
/* /\* printf("%d\t no --> %d j: %d %d\n",i,j,j-2,j+2); *\/ */
/* } else { */
/* /\* printf("%d\n",j); *\/ */
/* dist = distance(chain[cid].pos[i],chain[cid].pos[j]); */
/* /\* printf("%8.4f\n",dist); *\/ */
/* if ( dist <= 8.0 ) { */
/* x.cresid = j; */
/* x.distance = dist; */
/* x.index = i + chain[cid].index; */
/* x.cindex = j + chain[cid].index; */
/* contacts.insert(contacts.end(),x); */
/* } /\* END 8.0 *\/ */
/* } // else/if */
/* } // j */
/* /\* map.push_back(contacts); *\/ */
/* /\* contacts.clear(); *\/ */
/* } // i */
/* /\* std::vector<int>::iterator it; *\/ */
/* /\* for (it=contacts.begin(); it<contacts.end(); it++) { *\/ */
/* /\* // std::cout << *it << ' ' << std::endl; *\/ */
/* /\* printf("%d ",*it); *\/ */
/* /\* } *\/ */
/* /\* std::vector<int>::iterator iter; // declare a general iterator *\/ */
/* for ( int k = contacts.begin(); k < contacts.end(); k++){ */
/* printf("%d\n",contacts[k].index); */
/* } */
/* } */
/* inline Map::Map() { */
/* // constructor */
/* for (int i=0; i<num_atoms; i++ ) { */
/* /\* printf("%d\n",i); *\/ */
/* for (int j=0; j<max_contacts_per_atom; j++){ */
/* /\* if ( mol->contacts[i][j].cresid != 0 || mol->contacts[i][j].distance != 0.0) { *\/ */
/* /\* printf("%d %f\n",mol->contacts[i][j].cresid,mol->contacts[i][j].distance); *\/ */
/* contacts[i][j].cresid = -1; */
/* contacts[i][j].distance = 0.0; */
/* } */
/* } */
/* } */
/* inline void Map::get_contacts() { */
/* } */
/* inline void Map::set_values (int natoms, int max_contacts) { */
/* num_atoms = natoms; */
/* max_contacts_per_atom = max_contacts; */
/* } */
/* ---------------------------------------------------------
Molecule preparations:
--------------------------------------------------------- */
void build_contact_map(Molecule *mol);
void build_latlon_contact_map(Chain *chain, int num_chains, int start, int stop,\
Contact (*map)[MAX_CONTACTS],int sel);
void build_contact_map_inter_monomer(Chain *chain,int cid, Contact (*map)[MAX_CONTACTS], int sel);
void build_contact_map_inter(Chain *chain,int cid1,int cid2,Contact (*map)[MAX_CONTACTS]);
void compare_contacts(Chain *chref,Chain *chain,int cid, int sel);
void evaluate_original_contacts_now(Chain *chref,Chain *chain,int cid, int sel);
void print_contact_map(Contact (*map)[MAX_CONTACTS]);
void fprintf_count_of_contacts_2x_persist_from_reference( Molecule *m1, Molecule *m2);
void fprintf_bond_vector_angle_with_tension_vector( Molecule *m1, Molecule *m2 );
void fprintf_contacts_for_one_monomer_face(Chain *chain, int num_chains, int sel);
void fprintf_contact_map_gsop(Contact (*map)[MAX_CONTACTS]);
void fprintf_all_indices(Chain *chref,int num_chains);
void tubulin_monomers_angles( Molecule *m1, Molecule *m2, int r1, int r2, FILE *fp);
void get_tubulin_centroid( Molecule *m1, Vector *com);
void get_centroid_from_array( Vector arr_centroid[],int i, int j, Vector *centroid);
Vector get_centroid_from_centroids(Chain *chain,int start_chain,int stop_chain);
void get_centroid_movement(Chain *chain_ref,Chain *chain_later,int num_chains);
void get_centroid_xyzposition_movement(Chain *chain_later,int chains_to_use,FILE *fp_xyzpos);
/* void get_centroid_xyzposition_movement(chain_later,chains_to_use,fp_xyzpos); */
/* void get_latangle_from35centroids(Chain *chain_ref,Chain *chain_later,int m,int sel); */
void get_latangle_from35centroids(Chain *chain_ref,Chain *chain_later,int m,FILE *fp,int sel);
std::vector<double> get_3angles_dimerbyalpha(Chain *chain_ref,Chain *chain_later,int cid);
/* void get_latangle_from35centroids(Chain *chain_ref,Chain *chain_later,int m,int sel,FILE *fp_ang); */
void get_midpoint_reference_indices(Chain *chain,int i,int *index_ref_i,int *index_ref_c,int sel);
/* get_midpoint_reference_indices(chain_ref,i,&index_ref_i,&index_ref_c,1); */
void compute_nearest_neighbors(Chain *chain, int num_chains);
void determine_latlon_neighbors(Chain *chains, int num_chains, Vector axis);
void get_monomer_monomer_info( Molecule *m1, Molecule *m2,\
Vector ref_norm, Vector m1centroid,\
Vector m2centroid );
/* void load_dcd_coords_to_chain(dcdhandle *dcd,Chain *chain,int num_chains); */
/* void load_chain_coords_to_timestep(Chain *chain,int num_chains,\ */
/* const molfile_timestep_t *ts); */
void print_chain_coords(Chain *chain,int num_chains);
// overloaded.
void assign_contact_eh(Contact (*map)[MAX_CONTACTS],float eh,int low_resid,\
int high_resid,int low_cresid,int high_cresid);
void assign_contact_eh(Contact (*map)[MAX_CONTACTS],float eh);
/* void dcd_to_chain(ddc,chain_0); */
/* void dcd_to_chain(dcdhandle *v,Chain *chain); */
/* void load_chain_coords_to_timestep(dcdhandle *dcd,Chain *chain,int num_chains,\ */
/* void *v, const molfile_timestep_t *ts,int natoms); */
/* load_chain_coords_to_timestep(dcdw,chain_later,chains_to_use,vw,×tep_w,natoms_w); */
/* static int read_next_timestep(void *v, int natoms, molfile_timestep_t *ts) { */
/* static int write_timestep(void *v, const molfile_timestep_t *ts) { */
#endif
| {
"alphanum_fraction": 0.5216160913,
"avg_line_length": 29.3346104725,
"ext": "h",
"hexsha": "f3fbf603c60069b67c0967058a6ebdc233c85063",
"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": "c4f014100bd7e0fc1af27f44febc8eccef35d829",
"max_forks_repo_licenses": [
"Zed"
],
"max_forks_repo_name": "dmerz75/segment_analysis_md",
"max_forks_repo_path": "include/chain.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c4f014100bd7e0fc1af27f44febc8eccef35d829",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Zed"
],
"max_issues_repo_name": "dmerz75/segment_analysis_md",
"max_issues_repo_path": "include/chain.h",
"max_line_length": 108,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c4f014100bd7e0fc1af27f44febc8eccef35d829",
"max_stars_repo_licenses": [
"Zed"
],
"max_stars_repo_name": "dmerz75/segment_analysis_md",
"max_stars_repo_path": "include/chain.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6829,
"size": 22969
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_result.h>
#include <fftw3.h>
#include "cosmocalc.h"
double get_k0_fftlog(int N, double mu, double q, double r0, double L, double k0guess);
void um_fftlog(int m, double mu, double q, double k0, double r0, double L, double *realpart, double *imagpart);
void compute_discrete_spherical_fft(double *data, int N, double r0, double L, double q, double *result, double *k0)
{
double mu,rn,kn,tmp[2],um[2],k0guess;
int i,m;
static int initFlag = 1;
static double *rin;
static fftw_complex *out;
static fftw_plan pf,pb;
if(initFlag)
{
initFlag = 0;
rin = (double*)fftw_malloc(sizeof(double)*N);
out = (fftw_complex*)fftw_malloc(sizeof(fftw_complex)*(N/2+1));
pf = fftw_plan_dft_r2c_1d(N,rin,out,FFTW_MEASURE);
pb = fftw_plan_dft_c2r_1d(N,out,rin,FFTW_MEASURE);
}
for(i=0;i<N;++i)
{
rn = r0*exp(L/((double) N)*((double) (i-N/2)));
rin[i] = data[i]*4.0*M_PI*pow(rn,1.5)*sqrt(M_PI/2.0);
}
fftw_execute(pf);
q = 0.0;
mu = 0.5;
k0guess = *k0;
*k0 = get_k0_fftlog(N,mu,q,r0,L,k0guess);
for(i=0;i<N/2+1;++i)
{
if(i >= N/2)
m = i-N;
else
m = i;
um_fftlog(m,mu,q,*k0,r0,L,&(um[0]),&(um[1]));
if(m == N/2 || m == -N/2)
um[1] = 0.0;
tmp[0] = out[i][0]*um[0] - out[i][1]*um[1];
tmp[1] = out[i][1]*um[0] + out[i][0]*um[1];
out[i][0] = tmp[0];
out[i][1] = tmp[1];
}
fftw_execute(pb);
for(i=0;i<N;++i)
{
kn = (*k0)*exp(L/((double) N)*((double) (N/2-i)));
result[N-i-1] = rin[i]/((double) N)/pow(kn,1.5)*exp(L/((double) N)*3.0/2.0);
}
/* not needed
fftw_destroy_plan(pf);
fftw_destroy_plan(pb);
fftw_free(rin);
fftw_free(out);
*/
}
double get_k0_fftlog(int N, double mu, double q, double r0, double L, double k0guess)
{
double zr,zi,arg;
gsl_sf_result lnr_top,lnr_bot;
gsl_sf_result arg_top,arg_bot;
double twox[2];
double grat[2];
double tmp[2];
double lnkr;
int intval;
//do top part of gamma function ratio
zr = (mu + 1.0 + q)/2.0;
zi = M_PI*((double) N)/L/2.0;
gsl_sf_lngamma_complex_e(zr,zi,&lnr_top,&arg_top);
//do bottom
zr = (mu + 1.0 - q)/2.0;
zi = -1.0*M_PI*((double) N)/L/2.0;
gsl_sf_lngamma_complex_e(zr,zi,&lnr_bot,&arg_bot);
//get real and imag parts of 2^(q+i*2*pi*m/L)
zr = pow(2.0,q);
twox[0] = zr*cos(M_PI*((double) N)/L*log(2.0));
twox[1] = zr*sin(M_PI*((double) N)/L*log(2.0));
//now do computation of real and imag parts of result
zr = exp(lnr_top.val-lnr_bot.val);
grat[0] = zr*cos(arg_top.val-arg_bot.val);
grat[1] = zr*sin(arg_top.val-arg_bot.val);
//do product
tmp[0] = grat[0]*twox[0] - grat[1]*twox[1];
tmp[1] = grat[0]*twox[1] + grat[1]*twox[0];
//find k0
lnkr = log(k0guess*r0);
arg = atan2(tmp[1],tmp[0])/M_PI*L/((double) N);
intval = (int) ((lnkr-arg)/(L/((double) N)));
return exp(arg + ((double) intval)*L/((double) N))/r0;
}
void um_fftlog(int m, double mu, double q, double k0, double r0, double L, double *realpart, double *imagpart)
{
double zr,zi;
gsl_sf_result lnr_top,lnr_bot;
gsl_sf_result arg_top,arg_bot;
double kr[2];
double twox[2];
double grat[2];
double tmp[2];
//do top part of gamma function ratio
zr = (mu + 1.0 + q)/2.0;
zi = M_PI*((double) m)/L;
gsl_sf_lngamma_complex_e(zr,zi,&lnr_top,&arg_top);
//do bottom
zr = (mu + 1.0 - q)/2.0;
zi = -1.0*M_PI*((double) m)/L;
gsl_sf_lngamma_complex_e(zr,zi,&lnr_bot,&arg_bot);
//get real and imag parts of (k0*r0)^(i*2*pi*m/L)
zr = -1.0*log(k0*r0)*2.0*M_PI*((double) m)/L;
kr[0] = cos(zr);
kr[1] = sin(zr);
//get real and imag parts of 2^(q+i*2*pi*m/L)
zr = pow(2.0,q);
twox[0] = zr*cos(2.0*M_PI*m/L*log(2.0));
twox[1] = zr*sin(2.0*M_PI*m/L*log(2.0));
//now do computation of real and imag parts of result
zr = exp(lnr_top.val-lnr_bot.val);
grat[0] = zr*cos(arg_top.val-arg_bot.val);
grat[1] = zr*sin(arg_top.val-arg_bot.val);
tmp[0] = kr[0]*twox[0] - kr[1]*twox[1];
tmp[1] = kr[0]*twox[1] + kr[1]*twox[0];
*realpart = tmp[0]*grat[0] - tmp[1]*grat[1];
*imagpart = tmp[0]*grat[1] + tmp[1]*grat[0];
}
| {
"alphanum_fraction": 0.5962980319,
"avg_line_length": 26.0243902439,
"ext": "c",
"hexsha": "4c4efde26555807cd0b40d0cef168c0d01a3e6d2",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z",
"max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "beckermr/cosmocalc",
"max_forks_repo_path": "src/fftlog.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "beckermr/cosmocalc",
"max_issues_repo_path": "src/fftlog.c",
"max_line_length": 115,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "beckermr/cosmocalc",
"max_stars_repo_path": "src/fftlog.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1707,
"size": 4268
} |
#ifndef KGS_NULLSPACESVD_H
#define KGS_NULLSPACESVD_H
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <string>
#include "math/SVD.h"
#include "math/Nullspace.h"
/**
* An implementation of Nullspace backed by SVD
*/
class NullspaceSVD: public Nullspace {
public:
/** Will construct a nullspace of `matrix` using the SVD decomposition */
NullspaceSVD(SVD* svd);
/** Update the Nullspace (and underlying SVD) to reflect an updated state of the matrix */
void updateFromMatrix() override;
/** Return the SVD of the nullspace as columns of a matrix */
SVD *getSVD() const;
static void setSingularValueTolerance(double val);
private:
SVD* m_svd; ///< SVD underlying this nullspace
/// These values have to be chosen according to the numerical analysis
static double SINGVAL_TOL;
// static constexpr double RIGID_TOL = 1.0e-10; //0.0000000001; //depends on molecule, but 10^-10 seems a good fit!
friend class Configuration;
};
#endif //KGS_nullptrSPACE_H
| {
"alphanum_fraction": 0.7201565558,
"avg_line_length": 25.55,
"ext": "h",
"hexsha": "68c25a710518afde6e20461c1ecdb1a2ae6461ff",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_forks_repo_path": "src/math/NullspaceSVD.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_issues_repo_path": "src/math/NullspaceSVD.h",
"max_line_length": 118,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_stars_repo_path": "src/math/NullspaceSVD.h",
"max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z",
"num_tokens": 276,
"size": 1022
} |
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include <cconfigspace.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#define NUM_AREAS 4
#define NUM_SAMPLES 10000
void test_create_roulette_distribution() {
ccs_distribution_t distrib = NULL;
ccs_result_t err = CCS_SUCCESS;
int32_t refcount;
ccs_object_type_t otype;
ccs_distribution_type_t dtype;
ccs_numeric_type_t data_type;
ccs_interval_t interval;
const size_t num_areas = NUM_AREAS;
ccs_float_t areas[NUM_AREAS];
size_t num_areas_ret;
ccs_float_t areas_ret[NUM_AREAS];
const ccs_float_t epsilon = 1e-15;
for(size_t i = 0; i < num_areas; i++) {
areas[i] = (double)(i+1);
}
err = ccs_create_roulette_distribution(
num_areas,
areas,
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_object_get_type(distrib, &otype);
assert( err == CCS_SUCCESS );
assert( otype == CCS_DISTRIBUTION );
err = ccs_distribution_get_type(distrib, &dtype);
assert( err == CCS_SUCCESS );
assert( dtype == CCS_ROULETTE );
err = ccs_distribution_get_data_types(distrib, &data_type);
assert( err == CCS_SUCCESS );
assert( data_type == CCS_NUM_INTEGER );
err = ccs_distribution_get_bounds(distrib, &interval);
assert( err == CCS_SUCCESS );
assert( interval.type == CCS_NUM_INTEGER );
assert( interval.lower.i == 0 );
assert( interval.lower_included == CCS_TRUE );
assert( interval.upper.i == 4 );
assert( interval.upper_included == CCS_FALSE );
err = ccs_roulette_distribution_get_num_areas(distrib, &num_areas_ret);
assert( err == CCS_SUCCESS );
assert( num_areas_ret == num_areas );
err = ccs_roulette_distribution_get_areas(distrib, num_areas, areas_ret, &num_areas_ret);
assert( err == CCS_SUCCESS );
assert( num_areas_ret == num_areas );
ccs_float_t inv_sum = 2.0 / (num_areas * (num_areas + 1));
for (size_t i = 0; i < num_areas; i++) {
assert( areas_ret[i] <= areas[i] * inv_sum + epsilon &&
areas_ret[i] >= areas[i] * inv_sum - epsilon );
}
err = ccs_object_get_refcount(distrib, &refcount);
assert( err == CCS_SUCCESS );
assert( refcount == 1 );
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
}
void test_create_roulette_distribution_errors() {
ccs_distribution_t distrib = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_areas = NUM_AREAS;
ccs_float_t areas[NUM_AREAS];
for(size_t i = 0; i < num_areas; i++) {
areas[i] = (double)(i+1);
}
err = ccs_create_roulette_distribution(
0,
areas,
&distrib);
assert( err == -CCS_INVALID_VALUE );
err = ccs_create_roulette_distribution(
SIZE_MAX,
areas,
&distrib);
assert( err == -CCS_INVALID_VALUE );
err = ccs_create_roulette_distribution(
num_areas,
NULL,
&distrib);
assert( err == -CCS_INVALID_VALUE );
err = ccs_create_roulette_distribution(
num_areas,
areas,
NULL);
assert( err == -CCS_INVALID_VALUE );
areas[1] = -2;
err = ccs_create_roulette_distribution(
num_areas,
areas,
&distrib);
assert( err == -CCS_INVALID_VALUE );
}
void test_roulette_distribution() {
ccs_distribution_t distrib = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
ccs_numeric_t samples[NUM_SAMPLES];
const size_t num_areas = NUM_AREAS;
ccs_float_t areas[NUM_AREAS];
int counts[NUM_AREAS];
for(size_t i = 0; i < num_areas; i++) {
areas[i] = (double)(i+1);
counts[i] = 0;
}
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_roulette_distribution(
num_areas,
areas,
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_samples(distrib, rng, num_samples, samples);
assert( err == CCS_SUCCESS );
ccs_float_t sum = 0.0;
ccs_float_t inv_sum = 0.0;
for(size_t i = 0; i < num_areas; i++) {
sum += areas[i];
}
inv_sum = 1.0 / sum;
for(size_t i = 0; i < num_samples; i++) {
assert( samples[i].i >=0 && samples[i].i < 4 );
counts[samples[i].i]++;
}
for(size_t i = 0; i < num_areas; i++) {
ccs_float_t target = num_samples * areas[i] * inv_sum;
assert( counts[i] >= target * 0.95 && counts[i] <= target * 1.05 );
}
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
void test_roulette_distribution_zero() {
ccs_distribution_t distrib = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
ccs_numeric_t samples[NUM_SAMPLES];
const size_t num_areas = NUM_AREAS;
ccs_float_t areas[NUM_AREAS];
int counts[NUM_AREAS];
for(size_t i = 0; i < num_areas; i++) {
areas[i] = (double)(i+1);
counts[i] = 0;
}
areas[1] = 0.0;
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_roulette_distribution(
num_areas,
areas,
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_samples(distrib, rng, num_samples, samples);
assert( err == CCS_SUCCESS );
ccs_float_t sum = 0.0;
ccs_float_t inv_sum = 0.0;
for(size_t i = 0; i < num_areas; i++) {
sum += areas[i];
}
inv_sum = 1.0 / sum;
for(size_t i = 0; i < num_samples; i++) {
assert( samples[i].i >=0 && samples[i].i < 4 );
counts[samples[i].i]++;
}
for(size_t i = 0; i < num_areas; i++) {
ccs_float_t target = num_samples * areas[i] * inv_sum;
assert( counts[i] >= target * 0.95 && counts[i] <= target * 1.05 );
}
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
void test_roulette_distribution_strided_samples() {
ccs_distribution_t distrib1 = NULL;
ccs_distribution_t distrib2 = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
ccs_numeric_t samples[NUM_SAMPLES*2];
const size_t num_areas = NUM_AREAS;
ccs_float_t areas1[NUM_AREAS];
ccs_float_t areas2[NUM_AREAS];
int counts1[NUM_AREAS];
int counts2[NUM_AREAS];
for(size_t i = 0; i < num_areas; i++) {
areas1[i] = (double)(i+1);
counts1[i] = 0;
areas2[i] = (double)(i+2);
counts2[i] = 0;
}
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_roulette_distribution(
num_areas,
areas1,
&distrib1);
assert( err == CCS_SUCCESS );
err = ccs_create_roulette_distribution(
num_areas,
areas2,
&distrib2);
assert( err == CCS_SUCCESS );
err = ccs_distribution_strided_samples(distrib1, rng, num_samples, 2, samples);
assert( err == CCS_SUCCESS );
err = ccs_distribution_strided_samples(distrib2, rng, num_samples, 2, &(samples[0]) + 1);
assert( err == CCS_SUCCESS );
ccs_float_t sum = 0.0;
ccs_float_t inv_sum = 0.0;
for(size_t i = 0; i < num_areas; i++) {
sum += areas1[i];
}
inv_sum = 1.0 / sum;
for(size_t i = 0; i < num_samples; i++) {
assert( samples[2*i].i >=0 && samples[2*i].i < 4 );
counts1[samples[2*i].i]++;
}
for(size_t i = 0; i < num_areas; i++) {
ccs_float_t target = num_samples * areas1[i] * inv_sum;
assert( counts1[i] >= target * 0.95 && counts1[i] <= target * 1.05 );
}
sum = 0.0;
inv_sum = 0.0;
for(size_t i = 0; i < num_areas; i++) {
sum += areas2[i];
}
inv_sum = 1.0 / sum;
for(size_t i = 0; i < num_samples; i++) {
assert( samples[2*i+1].i >=0 && samples[2*i+1].i < 4 );
counts2[samples[2*i+1].i]++;
}
for(size_t i = 0; i < num_areas; i++) {
ccs_float_t target = num_samples * areas2[i] * inv_sum;
assert( counts2[i] >= target * 0.95 && counts2[i] <= target * 1.05 );
}
err = ccs_release_object(distrib1);
assert( err == CCS_SUCCESS );
err = ccs_release_object(distrib2);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
void test_roulette_distribution_soa_samples() {
ccs_distribution_t distrib = NULL;
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
ccs_numeric_t samples[NUM_SAMPLES];
const size_t num_areas = NUM_AREAS;
ccs_float_t areas[NUM_AREAS];
int counts[NUM_AREAS];
ccs_numeric_t *p_samples;
for(size_t i = 0; i < num_areas; i++) {
areas[i] = (double)(i+1);
counts[i] = 0;
}
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_roulette_distribution(
num_areas,
areas,
&distrib);
assert( err == CCS_SUCCESS );
p_samples = &(samples[0]);
err = ccs_distribution_soa_samples(distrib, rng, num_samples, &p_samples);
assert( err == CCS_SUCCESS );
ccs_float_t sum = 0.0;
ccs_float_t inv_sum = 0.0;
for(size_t i = 0; i < num_areas; i++) {
sum += areas[i];
}
inv_sum = 1.0 / sum;
for(size_t i = 0; i < num_samples; i++) {
assert( samples[i].i >=0 && samples[i].i < 4 );
counts[samples[i].i]++;
}
for(size_t i = 0; i < num_areas; i++) {
ccs_float_t target = num_samples * areas[i] * inv_sum;
assert( counts[i] >= target * 0.95 && counts[i] <= target * 1.05 );
}
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
int main() {
ccs_init();
test_create_roulette_distribution();
test_create_roulette_distribution_errors();
test_roulette_distribution();
test_roulette_distribution_zero();
test_roulette_distribution_strided_samples();
test_roulette_distribution_soa_samples();
ccs_fini();
return 0;
}
| {
"alphanum_fraction": 0.6532918611,
"avg_line_length": 27.2457627119,
"ext": "c",
"hexsha": "1c65038ee6dee358fec6579035394839f1933ccf",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-07T17:54:11.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-16T18:20:47.000Z",
"max_forks_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "deephyper/CCS",
"max_forks_repo_path": "tests/test_roulette_distribution.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_issues_repo_issues_event_max_datetime": "2021-12-15T10:48:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-15T10:37:41.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "deephyper/CCS",
"max_issues_repo_path": "tests/test_roulette_distribution.c",
"max_line_length": 90,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "deephyper/CCS",
"max_stars_repo_path": "tests/test_roulette_distribution.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-29T16:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-29T16:31:28.000Z",
"num_tokens": 2839,
"size": 9645
} |
/*
* -----------------------------------------------------------------
* Thermochemistry Library --- thrm_lib.c
* Version: 1.6180
* Date: Mar 15, 2010
* -----------------------------------------------------------------
* Programmer: Americo Barbosa da Cunha Junior
* americo.cunhajr@gmail.com
* -----------------------------------------------------------------
* Copyright (c) 2010 by Americo Barbosa da Cunha Junior
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* A copy of the GNU General Public License is available in
* LICENSE.txt or http://www.gnu.org/licenses/.
* -----------------------------------------------------------------
* This is the implementation file of a library
* with thermochemistry routines.
* -----------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include "../include/cklib.h"
#include "../include/ckthrm.h"
#include "../include/thrm_lib.h"
/*
*------------------------------------------------------------
* thrm_title
*
* This function prints the program title on the screen
*
* last update: Oct 20, 2009
* -----------------------------------------------------------------
*/
void thrm_title()
{
time_t curtime = time (NULL);
struct tm *loctime = localtime (&curtime);
printf("\n");
printf("=============================================");
printf("\n Themochemistry Direct Simulation\n");
printf("\n Author:");
printf("\n Americo Barbosa da Cunha Junior --- PUC-Rio");
printf("\n americo.cunhajr@gmail.com\n");
printf("\n Date:");
printf("\n %s", asctime(loctime) );
printf("=============================================");
printf("\n");
return;
}
/*
*------------------------------------------------------------
* thrm_mech
*
* This function prints on the screen informations about the
* chemical kinetics mechanism
*
* Input:
* n_e - # of elements
* n_s - # of species
* n_r - # of reactions
* mech - mechanism name
*
* last update: Jul 22, 2009
*------------------------------------------------------------
*/
void thrm_mech(int n_e,int n_s,int n_r,char *mech)
{
printf("\n");
printf("\n Thermochemistry Mechanism: %s", mech);
printf("\n # of elements = %d", n_e);
printf("\n # of species = %d", n_s);
printf("\n # of reactions = %d", n_r);
printf("\n");
printf("\n");
return;
}
/*------------------------------------------------------------*/
/*
* -----------------------------------------------------------------
* thrm_input
*
* This function receives the pmsr parameters
* and returns GSL_SUCCESS if there is no error.
*
* Input:
* Np - # of particles
* k - # of discrete time steps
* delta_t - time step
* tau_res - residence time
* tau_mix - mixture time
* tau_pair - pairwize time
*
* Output:
* success or error
*
* last update: Feb 5, 2009
* -----------------------------------------------------------------
*/
int thrm_input(int *steps,double *t0,double *delta_t,
double *Tmax,double *Tmin,double *tol)
{
printf("\n Input simulation parameters:\n");
printf("\n # of integration steps:");
scanf("%d", steps);
printf("\n %d\n", *steps);
if( *steps <= 0 )
return GSL_EINVAL;
printf("\n initial time:");
scanf("%lf", t0);
printf("\n %+.1e\n", *t0);
if( *t0 < 0.0 )
return GSL_EINVAL;
printf("\n time step:");
scanf("%lf", delta_t);
printf("\n %+.1e\n", *delta_t);
if( *delta_t <= 0.0 )
return GSL_EINVAL;
printf("\n temperature upper bound:");
scanf("%lf", Tmax);
printf("\n %+.1e\n", *Tmax);
if( *Tmax < 0.0 )
return GSL_EINVAL;
printf("\n temperature lower bound:");
scanf("%lf", Tmin);
printf("\n %+.1e\n", *Tmin);
if( *Tmin < 0.0 || *Tmin > *Tmax )
return GSL_EINVAL;
printf("\n tolerance:");
scanf("%lf", tol);
printf("\n %+.1e\n", *tol);
if( *tol <= 0.0 )
return GSL_EINVAL;
return GSL_SUCCESS;
}
/*----------------------------------------------------------------*/
/*
*------------------------------------------------------------
* thrm_alloc
*
* This function allocates a struct thermochemistry.
*
* Output:
* thrm - pointer to a struct thermochemistry
*
* last update: May 10, 2009
*------------------------------------------------------------
*/
thrm_wrk* thrm_alloc()
{
thrm_wrk *thrm = NULL;
/* memory allocation for ck_wrk struct */
thrm = (thrm_wrk *) malloc(sizeof(thrm_wrk));
if ( thrm == NULL )
return NULL;
/* setting ck_wrk elements equal NULL and 0.0 */
thrm->iwk = NULL;
thrm->rwk = NULL;
thrm->cwk = NULL;
thrm->leniwk = 0;
thrm->lenrwk = 0;
thrm->lencwk = 0;
thrm->n_e = 0;
thrm->n_s = 0;
thrm->n_r = 0;
return thrm;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* thrm_free
*
* This function frees the memory used by CK work vectors
*
* Input:
* thrm - pointer to a struct chemkin
*
* Output:
* void
*
* last update: Jul 21, 2009
*------------------------------------------------------------
*/
void thrm_free(void **thrm_bl)
{
thrm_wrk* thrm = NULL;
/* checking if thrm_bl is NULL */
if ( *thrm_bl == NULL )
return;
thrm = (thrm_wrk *) (*thrm_bl);
/* releasing ck work vectors */
if( thrm->iwk != NULL )
{
free(thrm->iwk);
thrm->iwk = NULL;
}
if( thrm->rwk != NULL )
{
free(thrm->rwk);
thrm->rwk = NULL;
}
if( thrm->cwk != NULL )
{
free(thrm->cwk);
thrm->cwk = NULL;
}
/* releasing thrm struct */
free(*thrm_bl);
*thrm_bl = NULL;
return;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* thrm_init
*
* This function initiates chemkin work vectors and the
* mechanism parameters.
*
* Input:
* thrm - pointer to a struct thermochemistry
*
* Output:
* success or error
*
* last update: Feb 19, 2010
*------------------------------------------------------------
*/
int thrm_init(thrm_wrk *thrm)
{
if ( thrm == NULL )
return GSL_EINVAL;
/* calling ck_wrk_len subroutine */
ck_wrk_len(&(thrm->leniwk),&(thrm->lenrwk),&(thrm->lencwk));
/* memory allocation for ck work vectors */
thrm->iwk = (int *) malloc( (thrm->leniwk)*sizeof(int));
thrm->rwk = (double *) malloc( (thrm->lenrwk)*sizeof(double));
thrm->cwk = (char *) malloc(16*(thrm->lencwk)*sizeof(char));
if ( thrm->iwk == NULL || thrm->rwk == NULL || thrm->cwk == NULL )
{
thrm_free((void **)&thrm);
return GSL_ENOMEM;
}
/* calling ck_wrk_init subroutine */
ck_wrk_init(&(thrm->leniwk),&(thrm->lenrwk),&(thrm->lencwk),
thrm->iwk,thrm->rwk,thrm->cwk);
/* calling ck_wrk_indx subroutine */
ck_wrk_indx(thrm->iwk,thrm->rwk,&(thrm->n_e),&(thrm->n_s),&(thrm->n_r));
return GSL_SUCCESS;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* thrm_composition
*
* This function sets composition vector with values.
*
* Input:
* thrm - pointer to a struct thermochemistry
*
* Output:
* phi - composition vector
* success or error
*
* last update: Mar 2, 2010
*------------------------------------------------------------
*/
void thrm_composition(thrm_wrk *thrm,gsl_vector *phi)
{
/* calling ck_wrk_comp subroutine */
ck_composition(&(thrm->n_s),thrm->iwk,thrm->rwk,thrm->cwk,phi->data);
return;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* thrm_page_heading0
*
* This function prints the properties names on the screen.
*
* Input:
* thrm - pointer to a struct thermochemistry
*
* last update: Nov 6, 2009
*------------------------------------------------------------
*/
void thrm_page_heading0(FILE *file)
{
fprintf(file," t(s) ");
fprintf(file," T(K) ");
fprintf(file," h ");
fprintf(file," p ");
fprintf(file," CO2 ");
fprintf(file," O2 ");
fprintf(file," CO ");
fprintf(file," O ");
return;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* thrm_h2T
*
* This function computes the mixture temperature for a
* given enthalpy, pressure and species mass fraction.
*
* Input:
* ck - pointer to a struct chemkin
* phi - composition vector
*
* Output:
* T - mixture temperature
*
* last update: Mar 2, 2010
*------------------------------------------------------------
*/
double thrm_h2T(thrm_wrk *thrm,double *phi,double Tmax,double Tmin,double tol)
{
double T = 0.0;
ck_h2t_bisec(&(thrm->n_s),phi,&Tmax,&Tmin,&tol,thrm->iwk,thrm->rwk,&T);
/*ck_h2t_newt(&(thrm->n_s),phi,&tol,thrm->iwk,thrm->rwk,&T,&T);*/
return T;
}
/*------------------------------------------------------------*/
/*
* -----------------------------------------------------------------
* thrm_temp_meanvar
*
* This function computes the temperature mean and variance
* using the algorithm of Knuth/Welford.
*
* Ref.:
* D. E. Knuth (1998)
* The Art of Computer Programming,
* volume 2: Seminumerical Algorithms
* 3rd ed., Addison-Wesley.
*
* B. P. Welford (1962).
* "Note on a method for calculating corrected sums
* of squares and products". Technometrics 4(3):419–420
*
* Input:
* Np - # of particles
* ps - system of particle
* thrm - pointer to a struct thermochemistry
* Tmax - temperature upper bound
* Tmin - temperature lower bound
* tol - tolerance
* mean - temperature mean
* var - temperature variance
*
* Output:
* success or error
*
* last update: Mar 4, 2010
* -----------------------------------------------------------------
*/
void thrm_temp_meanvar(int Np,gsl_vector **ps,thrm_wrk *thrm,
double Tmax,double Tmin,double tol,double *mean,double *var)
{
int i;
double T = 0.0;
double S = 0.0;
double M = 0.0;
double delta = 0.0;
for ( i = 0; i < Np; i++ )
{
T = thrm_h2T(thrm,ps[i]->data,Tmax,Tmin,tol);
delta = T - M;
M += delta/(double) (i+1);
S += delta*(T - M);
}
/* mean */
*mean = M;
/* variance */
*var = S/(double) (i-1);
return;
}
/*----------------------------------------------------------------*/
/*
*------------------------------------------------------------
* thrm_rrsum
*
* This function computes the reaction rates sum given the
* reaction rate vector.
*
* Input:
* phi - composition vector
*
* Output:
* sum - reaction rates sum
*
* last update: Sep 28, 2009
*------------------------------------------------------------
*/
double thrm_rrsum(gsl_vector *phi)
{
unsigned int i;
double sum = 0.0;
for (i = 2; i < phi->size; i++)
sum += phi->data[i];
return sum;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* thrm_mfsum
*
* This function computes the mass fraction sum given a
* composition vector.
*
* Input:
* phi - composition vector
*
* Output:
* sum - mass fraction sum
*
* last update: Sep 24, 2009
*------------------------------------------------------------
*/
double thrm_mfsum(gsl_vector *phi)
{
unsigned int i;
double sum = 0.0;
for (i = 2; i < phi->size; i++)
sum += phi->data[i];
return sum;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* thrm_mfsign
*
* This function checks if the mass fraction
* components are all positive in a composition vector.
*
* Input:
* phi - composition vector
*
* Output:
* flag - success or fail
*
* last update: Sep 28, 2009
*------------------------------------------------------------
*/
int thrm_mfsign(gsl_vector *phi)
{
unsigned int i;
int flag = GSL_SUCCESS;
for (i = 2; i < phi->size; i++)
if ( phi->data[i] < 0.0 )
flag = GSL_EFAILED;
return flag;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* thrm_eqs
*
* This function defines the set of governing diferential
* equations, one for enthalpy, one for pressure and ns
* for species mass fractions.
*
* Input:
* t - instant time
* phi - composition vector
* Sphi - reaction rate vector
* thrm_data - pointer to external data
*
* Output:
* success or error
*
* last update: Feb 19, 2010
*------------------------------------------------------------
*/
int thrm_eqs(double t,N_Vector phi,N_Vector Sphi,void *thrm_data)
{
int i, Neq;
double tol = 1.0e-4;
double Tmax = 5000.0, Tmin = 100.0;
double p, T, rho;
double *phi_data = NULL;
double *Sphi_data = NULL;
double *wdot = NULL;
double *wt = NULL;
thrm_wrk *thrm = NULL;
/* initiating ck workspace */
thrm = (thrm_wrk *)thrm_data;
if ( thrm == NULL )
return GSL_EINVAL;
/* obtaining phi and Rphi length and components */
Neq = NV_LENGTH_S(phi);
phi_data = NV_DATA_S(phi);
Sphi_data = NV_DATA_S(Sphi);
/* memory allocation for species molar mass and reaction rate vectors */
wt = (double *) malloc((Neq-2)*sizeof(double));
wdot = (double *) malloc((Neq-2)*sizeof(double));
if( wt == NULL || wdot == NULL )
{
free(wt);
free(wdot);
return GSL_ENOMEM;
}
/* pressure (dynes/cm^2) */
p = phi_data[1];
/* mixture temperature (K) */
T = thrm_h2T(thrm,phi_data,Tmax,Tmin,tol);
if( T < tol )
return GSL_EFAILED;
/* mixture density (g/cm^3)*/
ckrhoy(&p,&T,&(phi_data[2]),thrm->iwk,thrm->rwk,&rho);
/* species molar weight (g/mol) */
ckwt(thrm->iwk,thrm->rwk,wt);
/* species molar production rates (mol/(cm^3.s)) */
ckwyp(&p,&T,&(phi_data[2]),thrm->iwk,thrm->rwk,wdot);
/* dh/dt = 0 (isoenthalpic) */
Sphi_data[0] = 0.0;
/* dp/dt = 0 (isobaric) */
Sphi_data[1] = 0.0;
/* dY[i]/dt = wdot[i-2].wt[i-2]/rho */
for ( i = 2; i < Neq; i++ )
Sphi_data[i] = wdot[i-2]*wt[i-2]/rho;
/* releasing allocated memory */
free(wdot);
free(wt);
phi_data = NULL;
Sphi_data = NULL;
wdot = NULL;
wt = NULL;
thrm = NULL;
return GSL_SUCCESS;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* thrm_eqs2
*
* This function defines the set of governing diferential
* equations, one for temperature and ns
* for species mass fractions.
*
* Input:
* t - instant time
* phi - state vector
* Sphi - reaction rate vector
* thrm_data - pointer to external data
*
* Output:
* success or error
*
* last update: Dec 28, 2010
*------------------------------------------------------------
*/
int thrm_eqs2(double t,N_Vector phi,N_Vector Sphi,void *thrm_data)
{
int i, Neq;
double T, p, rho, cpb, sum = 0.0;
double *phi_data = NULL;
double *Sphi_data = NULL;
double *wdot = NULL;
double *wt = NULL;
double *h = NULL;
thrm_wrk *thrm = NULL;
/* initiating ck workspace */
thrm = (thrm_wrk *)thrm_data;
if ( thrm == NULL )
return GSL_EINVAL;
/* obtaining phi and Rphi length and components */
Neq = NV_LENGTH_S(phi);
phi_data = NV_DATA_S(phi);
Sphi_data = NV_DATA_S(Sphi);
/* memory allocation for species molar mass and reaction rate vectors */
wt = (double *) malloc((Neq-2)*sizeof(double));
wdot = (double *) malloc((Neq-2)*sizeof(double));
h = (double *) malloc((Neq-2)*sizeof(double));
if( wt == NULL || wdot == NULL || h == NULL)
{
free(wt);
free(wdot);
free(h);
return GSL_ENOMEM;
}
/* mixture temperature (K) */
T = phi_data[0];
/* pressure (dynes/cm^2) */
p = phi_data[1];
/* mixture density (g/cm^3)*/
ckrhoy(&p,&T,&(phi_data[2]),thrm->iwk,thrm->rwk,&rho);
/* mean specific heat at constant pressure (ergs/g.K) */
ckcpbs(&T,&(phi_data[2]),thrm->iwk,thrm->rwk,&cpb);
/* species molar weight (g/mol) */
ckwt(thrm->iwk,thrm->rwk,wt);
/* species molar production rates (mol/(cm^3.s)) */
ckwyp(&p,&T,&(phi_data[2]),thrm->iwk,thrm->rwk,wdot);
/* species specific enthalpy (ergs/g) */
ckhms(&T,thrm->iwk,thrm->rwk,h);
/* dY[i+2]/dt = wdot[i].wt[i]/rho */
for ( i = 0; i < thrm->n_s; i++ )
{
Sphi_data[i+2] = wdot[i]*wt[i]/rho;
sum += h[i]*wdot[i]*wt[i];
}
/* dT/dt = -1/(rho.cpb) . sum_i=1^ns h[i].wdot[i].wt[i] */
Sphi_data[0] = -sum/(rho*cpb);
/* dp/dt = 0 (isobaric) */
Sphi_data[1] = 0.0;
/* releasing allocated memory */
free(wdot);
free(wt);
free(h);
phi_data = NULL;
Sphi_data = NULL;
wdot = NULL;
wt = NULL;
h = NULL;
thrm = NULL;
return GSL_SUCCESS;
}
/*------------------------------------------------------------*/
| {
"alphanum_fraction": 0.469866435,
"avg_line_length": 23.6128205128,
"ext": "c",
"hexsha": "44e73a1b02c37b40385c7dd06cef3919d7774346",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z",
"max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "americocunhajr/CRFlowLib",
"max_forks_repo_path": "CRFlowLib-1.0/src/thrm_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-1.0/src/thrm_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/thrm_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": 4977,
"size": 18418
} |
// randomizer.h
// (C) 2013-2020 Nicholas G Davies
#ifndef RANDOMIZER_H
#define RANDOMIZER_H
#include <vector>
#include <limits>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <cmath>
#include <stdexcept>
#include <string>
class Randomizer
{
public:
Randomizer(unsigned long int seed = 0);
Randomizer(const Randomizer& R);
~Randomizer();
void Reset();
double Uniform(double min = 0.0, double max = 1.0);
double RoundedUniform(double min = 0.0, double max = 1.0, double shoulder = 0.01);
double Normal(double mean = 0.0, double sd = 1.0);
double Normal(double mean, double sd, double clamp);
double Cauchy(double x0 = 0.0, double gamma = 1.0);
double LogNormal(double zeta = 0.0, double sd = 1.0);
double Exponential(double rate = 1.0);
double Gamma(double shape, double scale);
double Beta(double alpha, double beta);
unsigned int Discrete(unsigned int size);
int Discrete(int min, int max);
void Multinomial(unsigned int N, std::vector<double>& p, std::vector<unsigned int>& n);
bool Bernoulli(double p);
unsigned int Binomial(unsigned int n, double p);
unsigned int BetaBinomial(unsigned int n, double p, double a_plus_b);
int Poisson(double mean);
int Geometric(double p);
int Round(double x);
template <typename T>
void Shuffle(std::vector<T>& vec);
inline gsl_rng* GSL_RNG() const { return r; }
inline unsigned long int Seed() const { return seed; }
private:
unsigned long int seed;
gsl_rng* r;
};
template <typename T>
void Randomizer::Shuffle(std::vector<T>& vec)
{
gsl_ran_shuffle(r, &vec[0], vec.size(), sizeof(vec[0]));
}
#endif | {
"alphanum_fraction": 0.6763831053,
"avg_line_length": 27.5573770492,
"ext": "h",
"hexsha": "77c74d388dc8f21ff46c1515fcb83e5b3fe5c72d",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-07-15T00:11:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-15T00:11:25.000Z",
"max_forks_repo_head_hexsha": "149997f77dddfe48906e15c1e4c0dcda976c0a6f",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "yangclaraliu/covid_europe_vac_app",
"max_forks_repo_path": "deprecated_4_speed/covidm_for_fitting/model_v2/randomizer.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "149997f77dddfe48906e15c1e4c0dcda976c0a6f",
"max_issues_repo_issues_event_max_datetime": "2020-10-31T10:56:44.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-10-31T08:41:20.000Z",
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "yangclaraliu/covid_europe_vac_app",
"max_issues_repo_path": "deprecated_4_speed/covidm_for_fitting/model_v2/randomizer.h",
"max_line_length": 91,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "1119331676dcf397242610a4b1da08582c3e7faf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nicholasdavies/covid-tiers",
"max_stars_repo_path": "fitting/covidm_for_fitting/model_v2/randomizer.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-22T07:33:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-31T22:18:20.000Z",
"num_tokens": 456,
"size": 1681
} |
// Copyright (c) 2005 - 2010 Marc de Kamps
// 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.
// * Neither the name of the copyright holder nor the names of its contributors may 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.
//
// If you use this software in work leading to a scientific publication, you should cite
// the 'currently valid reference', which can be found at http://miind.sourceforge.net
#ifndef _CODE_LIBS_NUMTOOLSLIB_NODE_EXSTATEDVINTEGRATOR_INCLUDE_GUARD
#define _CODE_LIBS_NUMTOOLSLIB_NODE_EXSTATEDVINTEGRATOR_INCLUDE_GUARD
#include <limits>
#include <vector>
#include <gsl/gsl_odeiv.h>
#include <gsl/gsl_errno.h>
#include "AbstractDVIntegratorCode.h"
#include "BasicDefinitions.h"
#include "DVIntegratorException.h"
#include "DVIntegratorStateParameter.h"
using std::vector;
using std::istream;
using std::ostream;
using std::string;
using std::numeric_limits;
namespace NumtoolsLib
{
//! This is a wrapper class for the GSL numerical ODE solvers. Examples of its usage can be
//! found in DynamicLib, for example in the Wilson-Cowan Algorithm. Unlike DVIntegrator it operates on a
//! state vector that is maintained by another class.
//!
//! The ExStateDVIntegrator is typically member of a class which requires the solution of a system
//! of ODEs. In the source file of that class a function must be defined whose return type is int
//! and whose arguments are given in the typedef for Function. A pointer to this function, (i.e the
//! function name must be given in the constructor. If the GSL
//! solver requires a Jacobian, then Derivative must also be defined, but for simple solvers,
//! such as 4-th order Runge-Kutta this is not required and the derivative argument can be left out.
//! Often, the ODE system requires parameters that need to be updated during the evolution of the system.
//! This parameter can be a single number, a vector or anything else. The type of the parameter must
//! be provided using the template argument. The class of the parameter must have a default constructor.
template <class ParameterObject=double>
class ExStateDVIntegrator : public AbstractDVIntegrator<ParameterObject>
{
public:
//! Constructor
ExStateDVIntegrator
(
Number, //<! maximum number of integrations
double*, //<! initial state
Number, //<! state size
TimeStep, //<! initial time step
Time, //<! initial time
const Precision&, //<! absolute and relative precision
Function, //<! dydt
Derivative deravative = 0, //<! Jacobian, if available
const gsl_odeiv_step_type* p_step_algorithm = gsl_odeiv_step_rkf45 //<! gsl integrator object
);
//! copy constructor must be defined, because the state of the integrator
//! must be handled correctly
ExStateDVIntegrator(const ExStateDVIntegrator&);
//! Ditto for copy operator
ExStateDVIntegrator& operator=(const ExStateDVIntegrator&);
//! virtual destructor
virtual ~ExStateDVIntegrator();
//! Set a new state
bool Reconfigure
(
const DVIntegratorStateParameter<ParameterObject>&
);
//! Current time
Time CurrentTime() const;
//! Only use if for efficiency reasons, acces to internal state is necessary
const double* BeginState() const;
//! Ditto
const double* EndState () const;
//! streaming tag
virtual string Tag () const;
//! Direct access to the parameter object for performance reasons
ParameterObject& Parameter();
private:
}; // end of NodeIntegrator
} // end of namespace
#endif // include guard
| {
"alphanum_fraction": 0.7511785202,
"avg_line_length": 42.798245614,
"ext": "h",
"hexsha": "3e59e2a1227718255cc55e08b8ac7417542bf84f",
"lang": "C",
"max_forks_count": 9,
"max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z",
"max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dekamps/miind",
"max_forks_repo_path": "libs/NumtoolsLib/ExStateDVIntegrator.h",
"max_issues_count": 41,
"max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856",
"max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dekamps/miind",
"max_issues_repo_path": "libs/NumtoolsLib/ExStateDVIntegrator.h",
"max_line_length": 163,
"max_stars_count": 13,
"max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dekamps/miind",
"max_stars_repo_path": "libs/NumtoolsLib/ExStateDVIntegrator.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z",
"num_tokens": 1127,
"size": 4879
} |
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2013.
//
// This software is released under a three-clause BSD license:
// * 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.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Steffen Sass, Holger Plattfaut, Bastian Blank $
// --------------------------------------------------------------------------
#ifndef OPENMS_FILTERING_DATAREDUCTION_SILACFILTERING_H
#define OPENMS_FILTERING_DATAREDUCTION_SILACFILTERING_H
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DRange.h>
#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/PeakWidthEstimator.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
#include <list>
#include <map>
#include <vector>
namespace OpenMS
{
class SILACFilter;
/**
@brief Filtering for SILAC data.
This filtering can be used to extract SILAC features from an MS experiment.
Several SILACFilters can be added to the filtering to search for specific SILAC patterns.
@see SILACFilter
*/
class OPENMS_DLLAPI SILACFiltering :
public ProgressLogger
{
public:
typedef std::vector<SILACFilter> Filters;
/**
* @brief holds all filters used in the filtering
*/
Filters filters_;
/**
* @brief Wrapper class for spectrum interpolation
*/
class OPENMS_DLLAPI SpectrumInterpolation
{
private:
gsl_interp_accel * current_;
gsl_spline * spline_;
public:
SpectrumInterpolation(const MSSpectrum<> &, const SILACFiltering &);
~SpectrumInterpolation();
DoubleReal operator()(DoubleReal mz) const
{
return gsl_spline_eval(spline_, mz, current_);
}
};
private:
/**
* @brief minimal intensity of SILAC features
*/
DoubleReal intensity_cutoff_;
/**
* @brief raw data
*/
MSExperiment<Peak1D> & exp_;
/**
* @brief picked data
*/
MSExperiment<Peak1D> picked_exp_;
/**
* @brief picked data seeds
*/
MSExperiment<Peak1D> picked_exp_seeds_;
/**
* Filename base for debugging output
*/
const String debug_filebase_;
/**
* @brief pick data seeds
*/
void pickSeeds_();
/**
* @brief apply filtering to picked data seeds
*/
void filterSeeds_();
public:
/// peak-width equation
const PeakWidthEstimator::Result peak_width;
/**
* @brief detailed constructor
* @param exp raw data
* @param intensity_cutoff minimal intensity of SILAC features
*/
SILACFiltering(MSExperiment<Peak1D> & exp, const PeakWidthEstimator::Result &, const DoubleReal intensity_cutoff, const String debug_filebase_ = "");
/**
* @brief adds a new filter to the filtering
* @param filter filter to add
*/
void addFilter(SILACFilter & filter);
/**
* @brief starts the filtering based on the added filters
*/
void filterDataPoints();
/**
* @brief structure for blacklist
* @param range m/z and RT interval to be blacklisted
* @param charge charge of the generating filter
* @param mass_separations mass separations of the generating filter
* @param relative_peak_position m/z position of the blacklisted area relative to the mono-isotopic peak of the unlabelled peptide
*/
struct BlacklistEntry
{
DRange<2> range;
Int charge;
std::vector<DoubleReal> mass_separations;
DoubleReal relative_peak_position;
};
/**
* @brief holds the range that is blacklisted for other filters and the filter that generated the blacklist entry
*/
std::multimap<DoubleReal, BlacklistEntry> blacklist;
};
}
#endif /* SILACFILTERING_H_ */
| {
"alphanum_fraction": 0.6548259778,
"avg_line_length": 31.8514285714,
"ext": "h",
"hexsha": "586f7868706a92d4fb06b7ca76706b8453b6bca7",
"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": "45455356482ce5ab35e32e445609b291ec78a6d6",
"max_forks_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_forks_repo_name": "kreinert/OpenMS",
"max_forks_repo_path": "src/openms/include/OpenMS/FILTERING/DATAREDUCTION/SILACFiltering.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_issues_repo_name": "kreinert/OpenMS",
"max_issues_repo_path": "src/openms/include/OpenMS/FILTERING/DATAREDUCTION/SILACFiltering.h",
"max_line_length": 153,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3",
"max_stars_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_stars_repo_name": "open-ms/all-svn-branches",
"max_stars_repo_path": "include/OpenMS/FILTERING/DATAREDUCTION/SILACFiltering.h",
"max_stars_repo_stars_event_max_datetime": "2018-05-23T03:43:10.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-05-23T03:43:10.000Z",
"num_tokens": 1200,
"size": 5574
} |
/*
** Implementation of LISA algorithm
** for statistical inference of fMRI images
**
** generic plug-in.
** A file containing a list of all 3D permutation images must be supplied.
**
** G.Lohmann, April 2017
*/
#include <viaio/Vlib.h>
#include <viaio/file.h>
#include <viaio/mu.h>
#include <viaio/option.h>
#include <viaio/os.h>
#include <viaio/VImage.h>
#include <via/via.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_histogram.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#ifdef _OPENMP
#include <omp.h>
#endif /*_OPENMP*/
#define ABS(x) ((x) > 0 ? (x) : -(x))
extern void VIsolatedVoxels(VImage src,float threshold);
extern void VHistogram(gsl_histogram *histogram,VString filename);
extern void VCheckImage(VImage src);
extern void FDR(VImage src,VImage dest,gsl_histogram *nullhist,gsl_histogram *realhist,double alpha);
extern void ImageStats(VImage src,double *,double *,double *hmin,double *hmax);
extern void VBilateralFilter(VImage src,VImage dest,int radius,double var1,double var2,int);
extern double VImageVar(VImage src);
extern void VImageCount(VImage src);
extern void VGetHistRange(VImage src,double *hmin,double *hmax);
extern float VGetMode(VImage src);
extern void VZScale(VImage src,float mode,float stddev);
extern void HistoUpdate(VImage,gsl_histogram *);
/* make sure all input images are in float and have the same number of pixels */
void CheckImageTypes(VImage zmap,VImage *permimages,int numperm)
{
size_t npixels = VImageNPixels(zmap);
int i;
for (i=0; i<numperm; i++) {
if (npixels != VImageNPixels(permimages[i]))
VError(" inconsistent number of pixels in permutation image %d",i);
if (VPixelRepn(permimages[i]) != VFloatRepn) VError(" perm image %d is not in float repn");
}
}
int main (int argc, char *argv[])
{
static VString filename = "";
static VFloat alpha = 0.05;
static VShort radius = 2;
static VFloat rvar = 2.0;
static VFloat svar = 2.0;
static VShort numiter = 2;
static VBoolean centering = FALSE;
static VBoolean cleanup = TRUE;
static VShort nproc = 0;
static VOptionDescRec options[] = {
{"permutations",VStringRepn,1,(VPointer) &filename,VRequiredOpt,NULL,"List of all permutation images"},
{"alpha",VFloatRepn,1,(VPointer) &alpha,VOptionalOpt,NULL,"FDR significance level"},
{"radius",VShortRepn,1,(VPointer) &radius,VOptionalOpt,NULL,"Bilateral parameter (radius in voxels)"},
{"rvar",VFloatRepn,1,(VPointer) &rvar,VOptionalOpt,NULL,"Bilateral parameter (radiometric)"},
{"svar",VFloatRepn,1,(VPointer) &svar,VOptionalOpt,NULL,"Bilateral parameter (spatial)"},
{"filteriterations",VShortRepn,1,(VPointer) &numiter,VOptionalOpt,NULL,"Bilateral parameter (number of iterations)"},
{"cleanup",VBooleanRepn,1,(VPointer) &cleanup,VOptionalOpt,NULL,"Whether to remove isolated voxels"},
{"j",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,"Number of processors to use, '0' to use all"},
};
FILE *out_file=NULL,*in_file=NULL;
VString in_filename=NULL;
char *prg_name=GetLipsiaName("vlisa_generic");
fprintf (stderr, "%s\n", prg_name);
gsl_set_error_handler_off ();
/* Parse command line arguments and identify files: */
VParseFilterCmdZ (VNumber (options), options, argc, argv,&in_file,&out_file,&in_filename);
/* Read the input zmap file: */
VAttrList list = VReadAttrListZ(in_file,in_filename,0L,TRUE,FALSE);
VImage zmap1 = VReadImage(list);
if (zmap1 == NULL) VError(" no input zmap image found");
if (VPixelRepn(zmap1) != VFloatRepn) VError(" input pixel repn must be float");
VAttrList geolist = VGetGeoInfo(list);
/* Read permutation file containing a list of 3D images */
VAttrList listperm = VReadAttrList(filename,0L,FALSE,FALSE);
int numperm = VAttrListNumImages(listperm);
VImage *zmap = VAttrListGetImages(listperm,numperm);
CheckImageTypes(zmap1,zmap,numperm);
fprintf(stderr," Number of permutation images: %d\n",(int)numperm);
/* estimate null variance to adjust radiometric parameter, use first 30 permutations */
double zvar=0,hmin=0,hmax=0;
float stddev=1.0;
int nperm=0;
if (numperm > 0) {
int tstperm = 30;
if (tstperm > numperm) tstperm = numperm;
double varsum=0,nx=0;
for (nperm = 0; nperm < tstperm; nperm++) {
zvar = VImageVar(zmap[nperm]);
varsum += zvar;
nx++;
}
double meanvar = varsum/nx;
stddev = sqrt(meanvar);
}
/* get non-permuted hotspot map */
float mode=0;
if (centering) mode = VGetMode(zmap1);
if (numperm > 0) VZScale(zmap1,mode,stddev);
VImage dst1 = VCreateImageLike(zmap1);
VBilateralFilter(zmap1,dst1,(int)radius,(double)rvar,(double)svar,(int)numiter);
/* ini histograms */
VGetHistRange(dst1,&hmin,&hmax);
size_t nbins = 20000;
gsl_histogram *hist0 = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (hist0,hmin,hmax);
gsl_histogram *histz = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (histz,hmin,hmax);
HistoUpdate(dst1,histz);
/* omp-stuff */
#ifdef _OPENMP
int num_procs=omp_get_num_procs();
if (nproc > 0 && nproc < num_procs) num_procs = nproc;
fprintf(stderr," using %d cores\n",(int)num_procs);
omp_set_num_threads(num_procs);
#endif /* _OPENMP */
/* do random permutations */
#pragma omp parallel for shared(zmap) schedule(dynamic)
for (nperm = 0; nperm < numperm; nperm++) {
if (nperm%20 == 0) fprintf(stderr," perm %4d of %d\r",nperm,(int)numperm);
float mode=0;
if (centering) mode = VGetMode(zmap[nperm]);
VZScale(zmap[nperm],mode,stddev);
VImage dst = VCreateImageLike (zmap1);
VBilateralFilter(zmap[nperm],dst,(int)radius,(double)rvar,(double)svar,(int)numiter);
#pragma omp critical
{
HistoUpdate(dst,hist0);
}
VDestroyImage(dst);
}
/* apply fdr */
VImage fdrimage = VCopyImage (dst1,NULL,VAllBands);
if (numperm > 0) {
FDR(dst1,fdrimage,hist0,histz,(double)alpha);
if (cleanup && alpha < 1.0) {
VIsolatedVoxels(fdrimage,(float)(1.0-alpha));
}
}
/* output */
VAttrList out_list = VCreateAttrList ();
VHistory(VNumber(options),options,prg_name,&list,&out_list);
VSetGeoInfo(geolist,out_list);
VAppendAttr (out_list,"image",NULL,VImageRepn,fdrimage);
if (! VWriteFile (out_file, out_list)) exit (1);
fprintf (stderr, "\n%s: done.\n", argv[0]);
exit(0);
}
| {
"alphanum_fraction": 0.7032118592,
"avg_line_length": 32.5427135678,
"ext": "c",
"hexsha": "fbd22e3c8cdd006d52daa5987a7ada1c2434c3ba",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/stats/vlisa_generic/vlisa_generic.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/stats/vlisa_generic/vlisa_generic.c",
"max_line_length": 121,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/stats/vlisa_generic/vlisa_generic.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z",
"num_tokens": 1950,
"size": 6476
} |
#include <stdio.h>
#include <cblas.h>
int
main ()
{
int i;
double x[] = { 1, 1, 1 };
cblas_dscal(3, 4.323, x, 1);
for (i = 0; i < 3; ++i)
printf ("%f\n", x[i]);
return 0;
} | {
"alphanum_fraction": 0.4591836735,
"avg_line_length": 11.5294117647,
"ext": "c",
"hexsha": "9fd3aae05a5aaeb3a9419b3d548265371932975f",
"lang": "C",
"max_forks_count": 11,
"max_forks_repo_forks_event_max_datetime": "2020-07-29T15:37:39.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-11-19T14:22:38.000Z",
"max_forks_repo_head_hexsha": "02484cb732f5fc5801dde4e16f71fe93a88fecbd",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "gkiar/fuzzy-python",
"max_forks_repo_path": "test/testblas.c",
"max_issues_count": 20,
"max_issues_repo_head_hexsha": "02484cb732f5fc5801dde4e16f71fe93a88fecbd",
"max_issues_repo_issues_event_max_datetime": "2020-02-20T16:15:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-13T19:12:02.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "gkiar/fuzzy-python",
"max_issues_repo_path": "test/testblas.c",
"max_line_length": 30,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "02484cb732f5fc5801dde4e16f71fe93a88fecbd",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "gkiar/fuzzy-python",
"max_stars_repo_path": "test/testblas.c",
"max_stars_repo_stars_event_max_datetime": "2020-10-27T08:14:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-01-31T18:43:28.000Z",
"num_tokens": 88,
"size": 196
} |
#ifndef _RNG_INTERNAL_H
#define _RNG_INTERNAL_H
#include <gsl/gsl_rng.h>
struct _ccs_rng_data_s {
const gsl_rng_type *rng_type;
gsl_rng *rng;
};
typedef struct _ccs_rng_data_s _ccs_rng_data_t;
struct _ccs_rng_ops_s {
_ccs_object_ops_t obj_ops;
};
typedef struct _ccs_rng_ops_s _ccs_rng_ops_t;
struct _ccs_rng_s {
_ccs_object_internal_t obj;
_ccs_rng_data_t *data;
};
#endif //_RNG_INTERNAL_H
| {
"alphanum_fraction": 0.7826086957,
"avg_line_length": 17.25,
"ext": "h",
"hexsha": "c847e62cb17a5cf5c471b4fd4635e5579d55d49b",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-07T17:54:11.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-16T18:20:47.000Z",
"max_forks_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "deephyper/CCS",
"max_forks_repo_path": "src/rng_internal.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_issues_repo_issues_event_max_datetime": "2021-12-15T10:48:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-15T10:37:41.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "deephyper/CCS",
"max_issues_repo_path": "src/rng_internal.h",
"max_line_length": 47,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "deephyper/CCS",
"max_stars_repo_path": "src/rng_internal.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-29T16:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-29T16:31:28.000Z",
"num_tokens": 127,
"size": 414
} |
// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
// reserved. See files LICENSE and NOTICE for details.
//
// This file is part of CEED, a collection of benchmarks, miniapps, software
// libraries and APIs for efficient high-order finite element and spectral
// element discretizations for exascale applications. For more information and
// source code availability see http://github.com/ceed.
//
// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,
// a collaborative effort of two U.S. Department of Energy organizations (Office
// of Science and the National Nuclear Security Administration) responsible for
// the planning and preparation of a capable exascale ecosystem, including
// software, applications, hardware, advanced system engineering and early
// testbed platforms, in support of the nation's exascale computing imperative.
#ifndef setup_h
#define setup_h
#include <stdbool.h>
#include <string.h>
#include <petsc.h>
#include <petscdmplex.h>
#include <petscfe.h>
#include <ceed.h>
#include "qfunctions/bps/common.h"
#include "qfunctions/bps/bp1.h"
#include "qfunctions/bps/bp2.h"
#include "qfunctions/bps/bp3.h"
#include "qfunctions/bps/bp4.h"
// -----------------------------------------------------------------------------
// PETSc Operator Structs
// -----------------------------------------------------------------------------
// Data for PETSc Matshell
typedef struct UserO_ *UserO;
struct UserO_ {
MPI_Comm comm;
DM dm;
Vec Xloc, Yloc, diag;
CeedVector xceed, yceed;
CeedOperator op;
Ceed ceed;
};
// Data for PETSc Interp/Restrict Matshells
typedef struct UserIR_ *UserIR;
struct UserIR_ {
MPI_Comm comm;
DM dmc, dmf;
Vec Xloc, Yloc, mult;
CeedVector ceedvecc, ceedvecf;
CeedOperator op;
Ceed ceed;
};
// -----------------------------------------------------------------------------
// libCEED Data Struct
// -----------------------------------------------------------------------------
// libCEED data struct for level
typedef struct CeedData_ *CeedData;
struct CeedData_ {
Ceed ceed;
CeedBasis basisx, basisu, basisctof;
CeedElemRestriction Erestrictx, Erestrictu, Erestrictxi, Erestrictui,
Erestrictqdi;
CeedQFunction qf_apply;
CeedOperator op_apply, op_restrict, op_interp;
CeedVector qdata, xceed, yceed;
};
// -----------------------------------------------------------------------------
// Command Line Options
// -----------------------------------------------------------------------------
// Coarsening options
typedef enum {
COARSEN_UNIFORM = 0, COARSEN_LOGARITHMIC = 1
} coarsenType;
static const char *const coarsenTypes [] = {"uniform","logarithmic",
"coarsenType","COARSEN",0
};
// -----------------------------------------------------------------------------
// Boundary Conditions
// -----------------------------------------------------------------------------
// Diff boundary condition function
PetscErrorCode BCsDiff(PetscInt dim, PetscReal time, const PetscReal x[],
PetscInt ncompu, PetscScalar *u, void *ctx) {
// *INDENT-OFF*
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
// *INDENT-ON*
const CeedScalar c[3] = { 0, 1., 2. };
const CeedScalar k[3] = { 1., 2., 3. };
PetscFunctionBeginUser;
for (PetscInt i = 0; i < ncompu; i++)
u[i] = sin(M_PI*(c[0] + k[0]*x[0])) *
sin(M_PI*(c[1] + k[1]*x[1])) *
sin(M_PI*(c[2] + k[2]*x[2]));
PetscFunctionReturn(0);
}
// Mass boundary condition function
PetscErrorCode BCsMass(PetscInt dim, PetscReal time, const PetscReal x[],
PetscInt ncompu, PetscScalar *u, void *ctx) {
PetscFunctionBeginUser;
for (PetscInt i = 0; i < ncompu; i++)
u[i] = PetscSqrtScalar(PetscSqr(x[0]) + PetscSqr(x[1]) +
PetscSqr(x[2]));
PetscFunctionReturn(0);
}
// Create BC label
static PetscErrorCode CreateBCLabel(DM dm, const char name[]) {
int ierr;
DMLabel label;
PetscFunctionBeginUser;
ierr = DMCreateLabel(dm, name); CHKERRQ(ierr);
ierr = DMGetLabel(dm, name, &label); CHKERRQ(ierr);
ierr = DMPlexMarkBoundaryFaces(dm, 1, label); CHKERRQ(ierr);
ierr = DMPlexLabelComplete(dm, label); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// -----------------------------------------------------------------------------
// BP Option Data
// -----------------------------------------------------------------------------
// BP options
typedef enum {
CEED_BP1 = 0, CEED_BP2 = 1, CEED_BP3 = 2,
CEED_BP4 = 3, CEED_BP5 = 4, CEED_BP6 = 5
} bpType;
static const char *const bpTypes[] = {"bp1","bp2","bp3","bp4","bp5","bp6",
"bpType","CEED_BP",0
};
// BP specific data
typedef struct {
CeedInt ncompu, qdatasize, qextra;
CeedQFunctionUser setupgeo, setuprhs, apply, error;
const char *setupgeofname, *setuprhsfname, *applyfname, *errorfname;
CeedEvalMode inmode, outmode;
CeedQuadMode qmode;
PetscBool enforce_bc;
PetscErrorCode (*bcs_func)(PetscInt, PetscReal, const PetscReal *,
PetscInt, PetscScalar *, void *);
} bpData;
bpData bpOptions[6] = {
[CEED_BP1] = {
.ncompu = 1,
.qdatasize = 1,
.qextra = 1,
.setupgeo = SetupMassGeo,
.setuprhs = SetupMassRhs,
.apply = Mass,
.error = Error,
.setupgeofname = SetupMassGeo_loc,
.setuprhsfname = SetupMassRhs_loc,
.applyfname = Mass_loc,
.errorfname = Error_loc,
.inmode = CEED_EVAL_INTERP,
.outmode = CEED_EVAL_INTERP,
.qmode = CEED_GAUSS,
.enforce_bc = false,
.bcs_func = BCsMass
},
[CEED_BP2] = {
.ncompu = 3,
.qdatasize = 1,
.qextra = 1,
.setupgeo = SetupMassGeo,
.setuprhs = SetupMassRhs3,
.apply = Mass3,
.error = Error3,
.setupgeofname = SetupMassGeo_loc,
.setuprhsfname = SetupMassRhs3_loc,
.applyfname = Mass3_loc,
.errorfname = Error3_loc,
.inmode = CEED_EVAL_INTERP,
.outmode = CEED_EVAL_INTERP,
.qmode = CEED_GAUSS,
.enforce_bc = false,
.bcs_func = BCsMass
},
[CEED_BP3] = {
.ncompu = 1,
.qdatasize = 6,
.qextra = 1,
.setupgeo = SetupDiffGeo,
.setuprhs = SetupDiffRhs,
.apply = Diff,
.error = Error,
.setupgeofname = SetupDiffGeo_loc,
.setuprhsfname = SetupDiffRhs_loc,
.applyfname = Diff_loc,
.errorfname = Error_loc,
.inmode = CEED_EVAL_GRAD,
.outmode = CEED_EVAL_GRAD,
.qmode = CEED_GAUSS,
.enforce_bc = true,
.bcs_func = BCsDiff
},
[CEED_BP4] = {
.ncompu = 3,
.qdatasize = 6,
.qextra = 1,
.setupgeo = SetupDiffGeo,
.setuprhs = SetupDiffRhs3,
.apply = Diff3,
.error = Error3,
.setupgeofname = SetupDiffGeo_loc,
.setuprhsfname = SetupDiffRhs3_loc,
.applyfname = Diff_loc,
.errorfname = Error3_loc,
.inmode = CEED_EVAL_GRAD,
.outmode = CEED_EVAL_GRAD,
.qmode = CEED_GAUSS,
.enforce_bc = true,
.bcs_func = BCsDiff
},
[CEED_BP5] = {
.ncompu = 1,
.qdatasize = 6,
.qextra = 0,
.setupgeo = SetupDiffGeo,
.setuprhs = SetupDiffRhs,
.apply = Diff,
.error = Error,
.setupgeofname = SetupDiffGeo_loc,
.setuprhsfname = SetupDiffRhs_loc,
.applyfname = Diff_loc,
.errorfname = Error_loc,
.inmode = CEED_EVAL_GRAD,
.outmode = CEED_EVAL_GRAD,
.qmode = CEED_GAUSS_LOBATTO,
.enforce_bc = true,
.bcs_func = BCsDiff
},
[CEED_BP6] = {
.ncompu = 3,
.qdatasize = 6,
.qextra = 0,
.setupgeo = SetupDiffGeo,
.setuprhs = SetupDiffRhs3,
.apply = Diff3,
.error = Error3,
.setupgeofname = SetupDiffGeo_loc,
.setuprhsfname = SetupDiffRhs3_loc,
.applyfname = Diff_loc,
.errorfname = Error3_loc,
.inmode = CEED_EVAL_GRAD,
.outmode = CEED_EVAL_GRAD,
.qmode = CEED_GAUSS_LOBATTO,
.enforce_bc = true,
.bcs_func = BCsDiff
}
};
// -----------------------------------------------------------------------------
// PETSc FE Boilerplate
// -----------------------------------------------------------------------------
// Create FE by degree
static int PetscFECreateByDegree(DM dm, PetscInt dim, PetscInt Nc,
PetscBool isSimplex, const char prefix[],
PetscInt order, PetscFE *fem) {
PetscQuadrature q, fq;
DM K;
PetscSpace P;
PetscDualSpace Q;
PetscInt quadPointsPerEdge;
PetscBool tensor = isSimplex ? PETSC_FALSE : PETSC_TRUE;
PetscErrorCode ierr;
PetscFunctionBeginUser;
/* Create space */
ierr = PetscSpaceCreate(PetscObjectComm((PetscObject) dm), &P); CHKERRQ(ierr);
ierr = PetscObjectSetOptionsPrefix((PetscObject) P, prefix); CHKERRQ(ierr);
ierr = PetscSpacePolynomialSetTensor(P, tensor); CHKERRQ(ierr);
ierr = PetscSpaceSetFromOptions(P); CHKERRQ(ierr);
ierr = PetscSpaceSetNumComponents(P, Nc); CHKERRQ(ierr);
ierr = PetscSpaceSetNumVariables(P, dim); CHKERRQ(ierr);
ierr = PetscSpaceSetDegree(P, order, order); CHKERRQ(ierr);
ierr = PetscSpaceSetUp(P); CHKERRQ(ierr);
ierr = PetscSpacePolynomialGetTensor(P, &tensor); CHKERRQ(ierr);
/* Create dual space */
ierr = PetscDualSpaceCreate(PetscObjectComm((PetscObject) dm), &Q);
CHKERRQ(ierr);
ierr = PetscDualSpaceSetType(Q,PETSCDUALSPACELAGRANGE); CHKERRQ(ierr);
ierr = PetscObjectSetOptionsPrefix((PetscObject) Q, prefix); CHKERRQ(ierr);
ierr = PetscDualSpaceCreateReferenceCell(Q, dim, isSimplex, &K); CHKERRQ(ierr);
ierr = PetscDualSpaceSetDM(Q, K); CHKERRQ(ierr);
ierr = DMDestroy(&K); CHKERRQ(ierr);
ierr = PetscDualSpaceSetNumComponents(Q, Nc); CHKERRQ(ierr);
ierr = PetscDualSpaceSetOrder(Q, order); CHKERRQ(ierr);
ierr = PetscDualSpaceLagrangeSetTensor(Q, tensor); CHKERRQ(ierr);
ierr = PetscDualSpaceSetFromOptions(Q); CHKERRQ(ierr);
ierr = PetscDualSpaceSetUp(Q); CHKERRQ(ierr);
/* Create element */
ierr = PetscFECreate(PetscObjectComm((PetscObject) dm), fem); CHKERRQ(ierr);
ierr = PetscObjectSetOptionsPrefix((PetscObject) *fem, prefix); CHKERRQ(ierr);
ierr = PetscFESetFromOptions(*fem); CHKERRQ(ierr);
ierr = PetscFESetBasisSpace(*fem, P); CHKERRQ(ierr);
ierr = PetscFESetDualSpace(*fem, Q); CHKERRQ(ierr);
ierr = PetscFESetNumComponents(*fem, Nc); CHKERRQ(ierr);
ierr = PetscFESetUp(*fem); CHKERRQ(ierr);
ierr = PetscSpaceDestroy(&P); CHKERRQ(ierr);
ierr = PetscDualSpaceDestroy(&Q); CHKERRQ(ierr);
/* Create quadrature */
quadPointsPerEdge = PetscMax(order + 1,1);
if (isSimplex) {
ierr = PetscDTGaussJacobiQuadrature(dim, 1, quadPointsPerEdge, -1.0, 1.0,
&q); CHKERRQ(ierr);
ierr = PetscDTGaussJacobiQuadrature(dim-1, 1, quadPointsPerEdge, -1.0, 1.0,
&fq); CHKERRQ(ierr);
} else {
ierr = PetscDTGaussTensorQuadrature(dim, 1, quadPointsPerEdge, -1.0, 1.0,
&q); CHKERRQ(ierr);
ierr = PetscDTGaussTensorQuadrature(dim-1, 1, quadPointsPerEdge, -1.0, 1.0,
&fq); CHKERRQ(ierr);
}
ierr = PetscFESetQuadrature(*fem, q); CHKERRQ(ierr);
ierr = PetscFESetFaceQuadrature(*fem, fq); CHKERRQ(ierr);
ierr = PetscQuadratureDestroy(&q); CHKERRQ(ierr);
ierr = PetscQuadratureDestroy(&fq); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// -----------------------------------------------------------------------------
// PETSc Setup for Level
// -----------------------------------------------------------------------------
// This function sets up a DM for a given degree
static int SetupDMByDegree(DM dm, PetscInt degree, PetscInt ncompu,
bpType bpChoice) {
PetscInt ierr, dim, marker_ids[1] = {1};
PetscFE fe;
PetscFunctionBeginUser;
// Setup FE
ierr = DMGetDimension(dm, &dim); CHKERRQ(ierr);
ierr = PetscFECreateByDegree(dm, dim, ncompu, PETSC_FALSE, NULL, degree, &fe);
CHKERRQ(ierr);
ierr = DMSetFromOptions(dm); CHKERRQ(ierr);
ierr = DMAddField(dm, NULL, (PetscObject)fe); CHKERRQ(ierr);
// Setup DM
ierr = DMCreateDS(dm); CHKERRQ(ierr);
if (bpOptions[bpChoice].enforce_bc) {
PetscBool hasLabel;
DMHasLabel(dm, "marker", &hasLabel);
if (!hasLabel) {CreateBCLabel(dm, "marker");}
ierr = DMAddBoundary(dm, DM_BC_ESSENTIAL, "wall", "marker", 0, 0, NULL,
(void(*)(void))bpOptions[bpChoice].bcs_func,
1, marker_ids, NULL);
CHKERRQ(ierr);
}
ierr = DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL);
CHKERRQ(ierr);
ierr = PetscFEDestroy(&fe); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// -----------------------------------------------------------------------------
// libCEED Setup for Level
// -----------------------------------------------------------------------------
// Destroy libCEED operator objects
static PetscErrorCode CeedDataDestroy(CeedInt i, CeedData data) {
PetscInt ierr;
CeedVectorDestroy(&data->qdata);
CeedVectorDestroy(&data->xceed);
CeedVectorDestroy(&data->yceed);
CeedBasisDestroy(&data->basisx);
CeedBasisDestroy(&data->basisu);
CeedElemRestrictionDestroy(&data->Erestrictu);
CeedElemRestrictionDestroy(&data->Erestrictx);
CeedElemRestrictionDestroy(&data->Erestrictui);
CeedElemRestrictionDestroy(&data->Erestrictxi);
CeedElemRestrictionDestroy(&data->Erestrictqdi);
CeedQFunctionDestroy(&data->qf_apply);
CeedOperatorDestroy(&data->op_apply);
if (i > 0) {
CeedOperatorDestroy(&data->op_interp);
CeedBasisDestroy(&data->basisctof);
CeedOperatorDestroy(&data->op_restrict);
}
ierr = PetscFree(data); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// Get CEED restriction data from DMPlex
static int CreateRestrictionPlex(Ceed ceed, CeedInt P, CeedInt ncomp,
CeedElemRestriction *Erestrict, DM dm) {
PetscInt ierr;
PetscInt c, cStart, cEnd, nelem, nnodes, *erestrict, eoffset;
PetscSection section;
Vec Uloc;
PetscFunctionBeginUser;
// Get Nelem
ierr = DMGetSection(dm, §ion); CHKERRQ(ierr);
ierr = DMPlexGetHeightStratum(dm, 0, &cStart,& cEnd); CHKERRQ(ierr);
nelem = cEnd - cStart;
// Get indices
ierr = PetscMalloc1(nelem*P*P*P, &erestrict); CHKERRQ(ierr);
for (c=cStart, eoffset=0; c<cEnd; c++) {
PetscInt numindices, *indices, i;
ierr = DMPlexGetClosureIndices(dm, section, section, c, &numindices,
&indices, NULL); CHKERRQ(ierr);
for (i=0; i<numindices; i+=ncomp) {
for (PetscInt j=0; j<ncomp; j++) {
if (indices[i+j] != indices[i] + (PetscInt)(copysign(j, indices[i])))
SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP,
"Cell %D closure indices not interlaced", c);
}
// Essential boundary conditions are encoded as -(loc+1)
PetscInt loc = indices[i] >= 0 ? indices[i] : -(indices[i] + 1);
erestrict[eoffset++] = loc/ncomp;
}
ierr = DMPlexRestoreClosureIndices(dm, section, section, c, &numindices,
&indices, NULL); CHKERRQ(ierr);
}
// Setup CEED restriction
ierr = DMGetLocalVector(dm, &Uloc); CHKERRQ(ierr);
ierr = VecGetLocalSize(Uloc, &nnodes); CHKERRQ(ierr);
ierr = DMRestoreLocalVector(dm, &Uloc); CHKERRQ(ierr);
CeedElemRestrictionCreate(ceed, nelem, P*P*P, nnodes/ncomp, ncomp,
CEED_MEM_HOST, CEED_COPY_VALUES, erestrict,
Erestrict);
ierr = PetscFree(erestrict); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// Set up libCEED for a given degree
static int SetupLibceedByDegree(DM dm, Ceed ceed, CeedInt degree, CeedInt dim,
CeedInt qextra, PetscInt ncompu, PetscInt gsize,
PetscInt xlsize, bpType bpChoice, CeedData data,
PetscBool setup_rhs, CeedVector rhsceed,
CeedVector *target) {
int ierr;
DM dmcoord;
PetscSection section;
Vec coords;
const PetscScalar *coordArray;
CeedBasis basisx, basisu;
CeedElemRestriction Erestrictx, Erestrictu, Erestrictxi,
Erestrictui, Erestrictqdi;
CeedQFunction qf_setupgeo, qf_apply;
CeedOperator op_setupgeo, op_apply;
CeedVector xcoord, qdata, xceed, yceed;
CeedInt qdatasize = bpOptions[bpChoice].qdatasize, ncompx = dim, P, Q,
cStart, cEnd, nelem;
// CEED bases
P = degree + 1;
Q = P + qextra;
CeedBasisCreateTensorH1Lagrange(ceed, dim, ncompu, P, Q,
bpOptions[bpChoice].qmode, &basisu);
CeedBasisCreateTensorH1Lagrange(ceed, dim, ncompx, 2, Q,
bpOptions[bpChoice].qmode, &basisx);
// CEED restrictions
ierr = DMGetCoordinateDM(dm, &dmcoord); CHKERRQ(ierr);
ierr = DMPlexSetClosurePermutationTensor(dmcoord, PETSC_DETERMINE, NULL);
CHKERRQ(ierr);
CreateRestrictionPlex(ceed, 2, ncompx, &Erestrictx, dmcoord);
CreateRestrictionPlex(ceed, P, ncompu, &Erestrictu, dm);
ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd); CHKERRQ(ierr);
nelem = cEnd - cStart;
CeedElemRestrictionCreateIdentity(ceed, nelem, Q*Q*Q, nelem*Q*Q*Q, ncompu,
&Erestrictui); CHKERRQ(ierr);
CeedElemRestrictionCreateIdentity(ceed, nelem, Q*Q*Q, nelem*Q*Q*Q,
qdatasize, &Erestrictqdi); CHKERRQ(ierr);
CeedElemRestrictionCreateIdentity(ceed, nelem, Q*Q*Q, nelem*Q*Q*Q, ncompx,
&Erestrictxi); CHKERRQ(ierr);
// Element coordinates
ierr = DMGetCoordinatesLocal(dm, &coords); CHKERRQ(ierr);
ierr = VecGetArrayRead(coords, &coordArray); CHKERRQ(ierr);
ierr = DMGetSection(dmcoord, §ion); CHKERRQ(ierr);
CeedElemRestrictionCreateVector(Erestrictx, &xcoord, NULL);
CeedVectorSetArray(xcoord, CEED_MEM_HOST, CEED_COPY_VALUES,
(PetscScalar *)coordArray);
ierr = VecRestoreArrayRead(coords, &coordArray); CHKERRQ(ierr);
// Create the persistent vectors that will be needed in setup and apply
CeedInt nqpts;
CeedBasisGetNumQuadraturePoints(basisu, &nqpts);
CeedVectorCreate(ceed, qdatasize*nelem*nqpts, &qdata);
CeedVectorCreate(ceed, xlsize, &xceed);
CeedVectorCreate(ceed, xlsize, &yceed);
// Create the Q-function that builds the operator (i.e. computes its
// quadrature data) and set its context data
CeedQFunctionCreateInterior(ceed, 1, bpOptions[bpChoice].setupgeo,
bpOptions[bpChoice].setupgeofname, &qf_setupgeo);
CeedQFunctionAddInput(qf_setupgeo, "dx", ncompx*dim, CEED_EVAL_GRAD);
CeedQFunctionAddInput(qf_setupgeo, "weight", 1, CEED_EVAL_WEIGHT);
CeedQFunctionAddOutput(qf_setupgeo, "qdata", qdatasize, CEED_EVAL_NONE);
// Set up PDE operator
CeedInt inscale = bpOptions[bpChoice].inmode==CEED_EVAL_GRAD ? dim : 1;
CeedInt outscale = bpOptions[bpChoice].outmode==CEED_EVAL_GRAD ? dim : 1;
CeedQFunctionCreateInterior(ceed, 1, bpOptions[bpChoice].apply,
bpOptions[bpChoice].applyfname, &qf_apply);
CeedQFunctionAddInput(qf_apply, "u", ncompu*inscale,
bpOptions[bpChoice].inmode);
CeedQFunctionAddInput(qf_apply, "qdata", qdatasize, CEED_EVAL_NONE);
CeedQFunctionAddOutput(qf_apply, "v", ncompu*outscale,
bpOptions[bpChoice].outmode);
// Create the operator that builds the quadrature data for the operator
CeedOperatorCreate(ceed, qf_setupgeo, CEED_QFUNCTION_NONE,
CEED_QFUNCTION_NONE, &op_setupgeo);
CeedOperatorSetField(op_setupgeo, "dx", Erestrictx, CEED_TRANSPOSE,
basisx, CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_setupgeo, "weight", Erestrictxi, CEED_NOTRANSPOSE,
basisx, CEED_VECTOR_NONE);
CeedOperatorSetField(op_setupgeo, "qdata", Erestrictqdi, CEED_NOTRANSPOSE,
CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);
// Create the operator
CeedOperatorCreate(ceed, qf_apply, CEED_QFUNCTION_NONE, CEED_QFUNCTION_NONE,
&op_apply);
CeedOperatorSetField(op_apply, "u", Erestrictu, CEED_TRANSPOSE,
basisu, CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_apply, "qdata", Erestrictqdi, CEED_NOTRANSPOSE,
CEED_BASIS_COLLOCATED, qdata);
CeedOperatorSetField(op_apply, "v", Erestrictu, CEED_TRANSPOSE,
basisu, CEED_VECTOR_ACTIVE);
// Setup qdata
CeedOperatorApply(op_setupgeo, xcoord, qdata, CEED_REQUEST_IMMEDIATE);
// Set up RHS if needed
if (setup_rhs) {
CeedQFunction qf_setuprhs;
CeedOperator op_setuprhs;
CeedVectorCreate(ceed, nelem*nqpts*ncompu, target);
// Create the q-function that sets up the RHS and true solution
CeedQFunctionCreateInterior(ceed, 1, bpOptions[bpChoice].setuprhs,
bpOptions[bpChoice].setuprhsfname, &qf_setuprhs);
CeedQFunctionAddInput(qf_setuprhs, "x", dim, CEED_EVAL_INTERP);
CeedQFunctionAddInput(qf_setuprhs, "dx", ncompx*dim, CEED_EVAL_GRAD);
CeedQFunctionAddInput(qf_setuprhs, "weight", 1, CEED_EVAL_WEIGHT);
CeedQFunctionAddOutput(qf_setuprhs, "true_soln", ncompu, CEED_EVAL_NONE);
CeedQFunctionAddOutput(qf_setuprhs, "rhs", ncompu, CEED_EVAL_INTERP);
// Create the operator that builds the RHS and true solution
CeedOperatorCreate(ceed, qf_setuprhs, CEED_QFUNCTION_NONE,
CEED_QFUNCTION_NONE, &op_setuprhs);
CeedOperatorSetField(op_setuprhs, "x", Erestrictx, CEED_TRANSPOSE,
basisx, CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_setuprhs, "dx", Erestrictx, CEED_TRANSPOSE,
basisx, CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_setuprhs, "weight", Erestrictxi, CEED_NOTRANSPOSE,
basisx, CEED_VECTOR_NONE);
CeedOperatorSetField(op_setuprhs, "true_soln", Erestrictui, CEED_NOTRANSPOSE,
CEED_BASIS_COLLOCATED, *target);
CeedOperatorSetField(op_setuprhs, "rhs", Erestrictu, CEED_TRANSPOSE,
basisu, CEED_VECTOR_ACTIVE);
// Setup RHS and target
CeedOperatorApply(op_setuprhs, xcoord, rhsceed, CEED_REQUEST_IMMEDIATE);
CeedVectorSyncArray(rhsceed, CEED_MEM_HOST);
// Cleanup
CeedQFunctionDestroy(&qf_setuprhs);
CeedOperatorDestroy(&op_setuprhs);
}
// Cleanup
CeedQFunctionDestroy(&qf_setupgeo);
CeedOperatorDestroy(&op_setupgeo);
CeedVectorDestroy(&xcoord);
// Save libCEED data required for level
data->basisx = basisx; data->basisu = basisu;
data->Erestrictx = Erestrictx;
data->Erestrictu = Erestrictu;
data->Erestrictxi = Erestrictxi;
data->Erestrictui = Erestrictui;
data->Erestrictqdi = Erestrictqdi;
data->qf_apply = qf_apply;
data->op_apply = op_apply;
data->qdata = qdata;
data->xceed = xceed;
data->yceed = yceed;
PetscFunctionReturn(0);
}
#ifdef multigrid
// Setup libCEED level transfer operator objects
static PetscErrorCode CeedLevelTransferSetup(Ceed ceed, CeedInt numlevels,
CeedInt ncompu, bpType bpChoice, CeedData *data, CeedInt *leveldegrees,
CeedQFunction qf_restrict, CeedQFunction qf_prolong) {
// Return early if numlevels=1
if (numlevels==1)
PetscFunctionReturn(0);
// Set up each level
for (CeedInt i=1; i<numlevels; i++) {
// P coarse and P fine
CeedInt Pc = leveldegrees[i-1] + 1;
CeedInt Pf = leveldegrees[i] + 1;
// Restriction - Fine to corse
CeedBasis basisctof;
CeedOperator op_restrict;
// Basis
CeedBasisCreateTensorH1Lagrange(ceed, 3, ncompu, Pc, Pf,
CEED_GAUSS_LOBATTO, &basisctof);
// Create the restriction operator
CeedOperatorCreate(ceed, qf_restrict, CEED_QFUNCTION_NONE,
CEED_QFUNCTION_NONE, &op_restrict);
CeedOperatorSetField(op_restrict, "input", data[i]->Erestrictu,
CEED_NOTRANSPOSE, CEED_BASIS_COLLOCATED,
CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_restrict, "output", data[i-1]->Erestrictu,
CEED_TRANSPOSE, basisctof, CEED_VECTOR_ACTIVE);
// Save libCEED data required for level
data[i]->basisctof = basisctof;
data[i]->op_restrict = op_restrict;
// Interpolation - Corse to fine
CeedOperator op_interp;
// Create the prolongation operator
CeedOperatorCreate(ceed, qf_prolong, CEED_QFUNCTION_NONE,
CEED_QFUNCTION_NONE, &op_interp);
CeedOperatorSetField(op_interp, "input", data[i-1]->Erestrictu,
CEED_NOTRANSPOSE, basisctof, CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_interp, "output", data[i]->Erestrictu,
CEED_TRANSPOSE, CEED_BASIS_COLLOCATED,
CEED_VECTOR_ACTIVE);
// Save libCEED data required for level
data[i]->op_interp = op_interp;
}
PetscFunctionReturn(0);
}
#endif
// -----------------------------------------------------------------------------
// Mat Shell Functions
// -----------------------------------------------------------------------------
#ifdef multigrid
// This function returns the computed diagonal of the operator
static PetscErrorCode MatGetDiag(Mat A, Vec D) {
PetscErrorCode ierr;
UserO user;
PetscFunctionBeginUser;
ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);
ierr = VecCopy(user->diag, D); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#endif
// This function uses libCEED to compute the action of the Laplacian with
// Dirichlet boundary conditions
static PetscErrorCode MatMult_Ceed(Mat A, Vec X, Vec Y) {
PetscErrorCode ierr;
UserO user;
PetscScalar *x, *y;
PetscFunctionBeginUser;
ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);
// Global-to-local
ierr = DMGlobalToLocalBegin(user->dm, X, INSERT_VALUES, user->Xloc);
CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(user->dm, X, INSERT_VALUES, user->Xloc);
CHKERRQ(ierr);
ierr = VecZeroEntries(user->Yloc); CHKERRQ(ierr);
// Setup CEED vectors
ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);
ierr = VecGetArray(user->Yloc, &y); CHKERRQ(ierr);
CeedVectorSetArray(user->xceed, CEED_MEM_HOST, CEED_USE_POINTER, x);
CeedVectorSetArray(user->yceed, CEED_MEM_HOST, CEED_USE_POINTER, y);
// Apply CEED operator
CeedOperatorApply(user->op, user->xceed, user->yceed, CEED_REQUEST_IMMEDIATE);
CeedVectorSyncArray(user->yceed, CEED_MEM_HOST);
// Restore PETSc vectors
ierr = VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x);
CHKERRQ(ierr);
ierr = VecRestoreArray(user->Yloc, &y); CHKERRQ(ierr);
// Local-to-global
ierr = VecZeroEntries(Y); CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(user->dm, user->Yloc, ADD_VALUES, Y);
CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(user->dm, user->Yloc, ADD_VALUES, Y);
CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#ifdef multigrid
// This function uses libCEED to compute the action of the interp operator
static PetscErrorCode MatMult_Interp(Mat A, Vec X, Vec Y) {
PetscErrorCode ierr;
UserIR user;
PetscScalar *x, *y;
PetscFunctionBeginUser;
ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);
// Global-to-local
ierr = VecZeroEntries(user->Xloc); CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(user->dmc, X, INSERT_VALUES, user->Xloc);
CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(user->dmc, X, INSERT_VALUES, user->Xloc);
CHKERRQ(ierr);
ierr = VecZeroEntries(user->Yloc); CHKERRQ(ierr);
// Setup CEED vectors
ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);
ierr = VecGetArray(user->Yloc, &y); CHKERRQ(ierr);
CeedVectorSetArray(user->ceedvecc, CEED_MEM_HOST, CEED_USE_POINTER, x);
CeedVectorSetArray(user->ceedvecf, CEED_MEM_HOST, CEED_USE_POINTER, y);
// Apply CEED operator
CeedOperatorApply(user->op, user->ceedvecc, user->ceedvecf,
CEED_REQUEST_IMMEDIATE);
CeedVectorSyncArray(user->ceedvecf, CEED_MEM_HOST);
// Restore PETSc vectors
ierr = VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x);
CHKERRQ(ierr);
ierr = VecRestoreArray(user->Yloc, &y); CHKERRQ(ierr);
// Multiplicity
ierr = VecPointwiseMult(user->Yloc, user->Yloc, user->mult);
// Local-to-global
ierr = VecZeroEntries(Y); CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(user->dmf, user->Yloc, ADD_VALUES, Y);
CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(user->dmf, user->Yloc, ADD_VALUES, Y);
CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// This function uses libCEED to compute the action of the restriction operator
static PetscErrorCode MatMult_Restrict(Mat A, Vec X, Vec Y) {
PetscErrorCode ierr;
UserIR user;
PetscScalar *x, *y;
PetscFunctionBeginUser;
ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);
// Global-to-local
ierr = VecZeroEntries(user->Xloc); CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(user->dmf, X, INSERT_VALUES, user->Xloc);
CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(user->dmf, X, INSERT_VALUES, user->Xloc);
CHKERRQ(ierr);
ierr = VecZeroEntries(user->Yloc); CHKERRQ(ierr);
// Multiplicity
ierr = VecPointwiseMult(user->Xloc, user->Xloc, user->mult); CHKERRQ(ierr);
// Setup CEED vectors
ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);
ierr = VecGetArray(user->Yloc, &y); CHKERRQ(ierr);
CeedVectorSetArray(user->ceedvecf, CEED_MEM_HOST, CEED_USE_POINTER, x);
CeedVectorSetArray(user->ceedvecc, CEED_MEM_HOST, CEED_USE_POINTER, y);
// Apply CEED operator
CeedOperatorApply(user->op, user->ceedvecf, user->ceedvecc,
CEED_REQUEST_IMMEDIATE);
CeedVectorSyncArray(user->ceedvecc, CEED_MEM_HOST);
// Restore PETSc vectors
ierr = VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x);
CHKERRQ(ierr);
ierr = VecRestoreArray(user->Yloc, &y); CHKERRQ(ierr);
// Local-to-global
ierr = VecZeroEntries(Y); CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(user->dmc, user->Yloc, ADD_VALUES, Y);
CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(user->dmc, user->Yloc, ADD_VALUES, Y);
CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#endif
// This function calculates the error in the final solution
static PetscErrorCode ComputeErrorMax(UserO user, CeedOperator op_error,
Vec X, CeedVector target,
PetscReal *maxerror) {
PetscErrorCode ierr;
PetscScalar *x;
CeedVector collocated_error;
CeedInt length;
PetscFunctionBeginUser;
CeedVectorGetLength(target, &length);
CeedVectorCreate(user->ceed, length, &collocated_error);
// Global-to-local
ierr = DMGlobalToLocal(user->dm, X, INSERT_VALUES, user->Xloc); CHKERRQ(ierr);
// Setup CEED vector
ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);
CeedVectorSetArray(user->xceed, CEED_MEM_HOST, CEED_USE_POINTER, x);
// Apply CEED operator
CeedOperatorApply(op_error, user->xceed, collocated_error,
CEED_REQUEST_IMMEDIATE);
// Restore PETSc vector
VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);
// Reduce max error
*maxerror = 0;
const CeedScalar *e;
CeedVectorGetArrayRead(collocated_error, CEED_MEM_HOST, &e);
for (CeedInt i=0; i<length; i++) {
*maxerror = PetscMax(*maxerror, PetscAbsScalar(e[i]));
}
CeedVectorRestoreArrayRead(collocated_error, &e);
ierr = MPI_Allreduce(MPI_IN_PLACE, maxerror,
1, MPIU_REAL, MPIU_MAX, user->comm); CHKERRQ(ierr);
// Cleanup
CeedVectorDestroy(&collocated_error);
PetscFunctionReturn(0);
}
#endif
| {
"alphanum_fraction": 0.6447302226,
"avg_line_length": 36.1820250284,
"ext": "h",
"hexsha": "36127a97868112b55da2ffa56101bf10a930253e",
"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": "15e77cd9c9ad8c81f93cb17e681f4732bd8b573f",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jrwrigh/libCEED",
"max_forks_repo_path": "examples/petsc/setup.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "15e77cd9c9ad8c81f93cb17e681f4732bd8b573f",
"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": "jrwrigh/libCEED",
"max_issues_repo_path": "examples/petsc/setup.h",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "15e77cd9c9ad8c81f93cb17e681f4732bd8b573f",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jrwrigh/libCEED",
"max_stars_repo_path": "examples/petsc/setup.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8957,
"size": 31804
} |
#pragma once
#include <nextalign/nextalign.h>
#include <gsl/string_span>
template<typename Letter>
using SequenceSpan = gsl::basic_string_span<Letter, gsl::dynamic_extent>;
template<typename Letter>
struct InsertionInternal {
int begin;
int end;
Sequence<Letter> seq;
};
struct PeptideInternal {
std::string name;
AminoacidSequence seq;
std::vector<InsertionInternal<Aminoacid>> insertions;
};
| {
"alphanum_fraction": 0.7621359223,
"avg_line_length": 17.9130434783,
"ext": "h",
"hexsha": "73d6a177de6e530315d37ee5527e6c48cbb082d2",
"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": "f62d906034974c160eabb12ac9bf98a691646ee3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "davidcroll/nextclade",
"max_forks_repo_path": "packages/nextalign/src/nextalign_private.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3",
"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": "davidcroll/nextclade",
"max_issues_repo_path": "packages/nextalign/src/nextalign_private.h",
"max_line_length": 73,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f62d906034974c160eabb12ac9bf98a691646ee3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "davidcroll/nextclade",
"max_stars_repo_path": "packages/nextalign/src/nextalign_private.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 100,
"size": 412
} |
#ifndef IMAT_MATRIX_H
#define IMAT_MATRIX_H
#include <cstdarg>
#include <cstdlib>
#include <fstream>
#include <sstream>
#ifdef GSL
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_sort_double.h>
#endif // GSL
//#include "split_str.h"
#include "vector.h"
#include "base.h"
namespace imat {
enum Dim { kByRow = 0, kByCol = 1 }; // Choose dimention for Min, Max, Mean
// Sum, Covariance and Sort
// Matrix Class:
// Provide a C++ Matrix class, whoes data can be exposed to C numeric libraries
// (eg. GSL lib).
template <class T>
class Matrix {
// Following functions are not as efficient as operate_and_assign (+=, -= and
// *=). Try to use operate_and_assign instead of these functions whenever
// possible.
template <class TT>
friend Matrix<TT> operator- (const Matrix<TT> &lfs, const Matrix<TT> &rhs);
template <class TT>
friend Matrix<TT> operator+ (const Matrix<TT> &lfs, const Matrix<TT> &rhs);
template <class TT>
friend Matrix<TT> operator* (const Matrix<TT> &lfs, const Matrix<TT> &rhs);
template <class TT>
friend Matrix<TT> operator* (const Matrix<TT> &mat, const TT &x);
template <class TT>
friend Matrix<TT> operator* (const TT &x, const Matrix<TT> &mat);
//
// Cross Product
template <class TT>
friend void Cross(Matrix<TT> *res, const Matrix<TT> &a, const Matrix<TT> &b);
public:
Matrix() : rows_(0), cols_(0), tda_(0), data_(NULL), owner_(false) {}
~Matrix() { if (owner_) delete []data_; }
Matrix(isize_t rows, isize_t cols);
Matrix(const Matrix <T> &source);
Matrix<T> & operator= (const Matrix<T> &source);
ListInitializer<T> operator= (const T &value);
void Allocate(isize_t rows, isize_t cols); // for empty matrix only
// Matrix views: can only be created by mat.View(...)
// View raw data
void View(T *src, isize_t rows, isize_t cols, isize_t tda=kDefault);
// View submatrix: const and non-const version
void View(Matrix<T> *src,
isize_t row_0, isize_t col_0,
isize_t rows=kDefault, isize_t cols=kDefault);
void View(const Matrix<T> &src,
isize_t row_0, isize_t col_0,
isize_t rows=kDefault, isize_t cols=kDefault);
// Copy elements from a submatrix of src
void SubCopy(const Matrix<T> &src,
isize_t row_0=kDefault, isize_t col_0=kDefault,
isize_t rows=kDefault, isize_t cols=kDefault);
T & operator() (isize_t i, isize_t j);
const T & operator() (isize_t i, isize_t j) const;
Matrix<T> operator-() const;
bool operator== (const Matrix<T> &other) const;
void operator+= (const Matrix<T> &other);
void operator-= (const Matrix<T> &other);
void operator*= (const Matrix<T> &other);
void operator+= (const T &x);
void operator-= (const T &x);
void operator*= (const T &x);
void SetZero(); // Set all elements as 0
void SetAll(const T &x); // Set all elements as x
void SetUnit(); // Set square matrix as unit matrix
T Sum() const; // Sumation of all elements
T Min() const; // Minimum of all elements
T Max() const; // Maximum of all elements
double Mean() const; // Mean value of all elements
void GetRow(Vector<T> *row_view, isize_t i);
void GetCol(Vector<T> *col_view, isize_t i);
void Trans();
// Following functions are designed to operate on rows or cols:
// eg. A = [[ 1, 2, 3],
// [ 4, 5, 6],
// [ 7, 8, 9],
// [10, 11, 12]]
// A.Sum(kByRow) ==> [6, 15, 24, 33]
// A.Sum(kByCol) ==> [22, 26, 30]
//
Vector<T> Sum(Dim dimention) const;
Vector<T> Min(Dim dimention) const;
Vector<T> Max(Dim dimention) const;
Vector<double> Mean(Dim dimention) const;
void Norm(Dim dimention=kByRow); // Only for T==double
#ifdef GSL
// Get covariance matrix of data seris stored in cols or rows
Matrix<T> Cov(Dim dimention=kByCol) const; // Only for T==double
void Sort(Dim dimention=kByRow, int key=0); // Only for T==double
void Eigen(Vector<T> *eigen_value, Matrix<T> *eigen_vector); // Only for T==double
#endif // GSL
void Print() const;
void Readf(const char *filename);
void Printf(const char *filename) const;
bool empty() const { return (rows_ == 0 or cols_ == 0); }
isize_t rows() const { return rows_; }
isize_t cols() const { return cols_; }
isize_t tda() const { return tda_; }
T* data() { return data_; }
const T* data() const { return data_; }
void clear();
protected:
bool is_view_() const { return (data_ != NULL and owner_ == false); }
void copy_(const Matrix<T> &source);
void allocate_(isize_t rows, isize_t cols);
isize_t rows_;
isize_t cols_;
isize_t tda_;
T *data_;
bool owner_;
};
typedef Matrix<int> MatrixI;
typedef Matrix<double> MatrixD;
#include "matrix_inl.h"
} // namespace imat
#endif // IMAT_MATRIX_H
| {
"alphanum_fraction": 0.6249010293,
"avg_line_length": 34.8413793103,
"ext": "h",
"hexsha": "4f23ad409e837be9e9705f2f1742abc8db645505",
"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": "f282c5b17495059c8c72195a0c5dc20515b30d33",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "hongjunbai/imat",
"max_forks_repo_path": "imat/matrix.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f282c5b17495059c8c72195a0c5dc20515b30d33",
"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": "hongjunbai/imat",
"max_issues_repo_path": "imat/matrix.h",
"max_line_length": 84,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f282c5b17495059c8c72195a0c5dc20515b30d33",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "hongjunbai/imat",
"max_stars_repo_path": "imat/matrix.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1449,
"size": 5052
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
#include "ccl.h"
ccl_cl_tracer_collection_t *ccl_cl_tracer_collection_t_new(int *status) {
ccl_cl_tracer_collection_t *trc = NULL;
trc = malloc(sizeof(ccl_cl_tracer_collection_t));
if (trc == NULL)
*status = CCL_ERROR_MEMORY;
if (*status == 0) {
trc->n_tracers = 0;
// Currently CCL_MAX_TRACERS_PER_COLLECTION is hard-coded to 100.
// It should be enough for any practical application with minimal memory overhead
trc->ts = malloc(CCL_MAX_TRACERS_PER_COLLECTION*sizeof(ccl_cl_tracer_t *));
if (trc->ts == NULL) {
*status = CCL_ERROR_MEMORY;
free(trc);
trc = NULL;
}
}
return trc;
}
void ccl_cl_tracer_collection_t_free(ccl_cl_tracer_collection_t *trc) {
if (trc != NULL) {
if (trc->ts != NULL)
free(trc->ts);
free(trc);
}
}
void ccl_add_cl_tracer_to_collection(ccl_cl_tracer_collection_t *trc,
ccl_cl_tracer_t *tr, int *status) {
if (trc->n_tracers >= CCL_MAX_TRACERS_PER_COLLECTION) {
*status = CCL_ERROR_MEMORY;
return;
}
trc->ts[trc->n_tracers] = tr;
trc->n_tracers++;
}
// Takes an array of z-dependent numbers and the corresponding z values
// and returns an array of a values and the corresponding a-dependent values.
// The order of the original arrays is assumed to be ascending in z, and
// the order of the returned arrays is swapped (so it has ascending a).
static void from_z_to_a(ccl_cosmology *cosmo,
int nz, double *z_arr, double *fz_arr,
double **a_arr, double **fa_arr, int *status) {
*a_arr = NULL;
*fa_arr = NULL;
*a_arr = malloc(nz*sizeof(double));
*fa_arr = malloc(nz*sizeof(double));
if ((a_arr == NULL) || (fa_arr == NULL)) {
*status = CCL_ERROR_MEMORY;
free(*a_arr);
free(*fa_arr);
ccl_cosmology_set_status_message(
cosmo, "ccl_tracers.c: from_z_to_a(): memory allocation error\n");
}
if (*status == 0) {
int ia;
// Populate array of scale factors in reverse order
for (ia=0; ia < nz; ia++) {
(*a_arr)[ia] = 1./(1+z_arr[nz-1-ia]);
(*fa_arr)[ia] = fz_arr[nz-1-ia];
}
}
}
//Integrand for N(z) integrator
static double nz_integrand(double z, void *pars) {
ccl_f1d_t *nz_f = (ccl_f1d_t *)pars;
return ccl_f1d_t_eval(nz_f,z);
}
// Gets area of N(z) curve
static double get_nz_norm(ccl_cosmology *cosmo, ccl_f1d_t *nz_f,
double z0, double zf, int *status) {
double nz_norm = -1, nz_enorm;
// Get N(z) norm
gsl_function F;
gsl_integration_workspace *w = NULL;
F.function = &nz_integrand;
F.params = nz_f;
w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION);
if (w == NULL) {
*status = CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(
cosmo, "ccl_tracers.c: get_nz_norm(): out of memory");
}
else {
int gslstatus = gsl_integration_qag(
&F, z0, zf, 0,
cosmo->gsl_params.INTEGRATION_EPSREL,
cosmo->gsl_params.N_ITERATION,
cosmo->gsl_params.INTEGRATION_GAUSS_KRONROD_POINTS,
w, &nz_norm, &nz_enorm);
if (gslstatus != GSL_SUCCESS) {
ccl_raise_gsl_warning(gslstatus, "ccl_tracers.c: get_nz_norm():");
*status = CCL_ERROR_INTEG;
ccl_cosmology_set_status_message(
cosmo,
"ccl_tracers.c: get_nz_norm(): "
"integration error when normalizing N(z)\n");
}
}
gsl_integration_workspace_free(w);
return nz_norm;
}
static void from_z_to_chi(ccl_cosmology *cosmo, int nz, double *z_arr,
double *chi_arr, int *status) {
for (int ichi=0; ichi < nz; ichi++)
chi_arr[ichi] = ccl_comoving_radial_distance(cosmo, 1./(1+z_arr[ichi]), status);
}
void ccl_get_number_counts_kernel(ccl_cosmology *cosmo,
int nz, double *z_arr, double *nz_arr,
int normalize_nz,
double *pchi_arr, int *status) {
// Returns dn/dchi normalized to unit area from an unnormalized dn/dz.
// Prepare N(z) spline
ccl_f1d_t *nz_f = NULL;
nz_f = ccl_f1d_t_new(nz, z_arr, nz_arr, 0, 0);
if (nz_f == NULL) {
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_tracers.c: ccl_get_number_counts_kernel: "
"error initializing spline\n");
}
// Get N(z) normalization
double i_nz_norm = -1;
if (*status == 0) {
if (normalize_nz)
i_nz_norm = 1./get_nz_norm(cosmo, nz_f, z_arr[0], z_arr[nz-1], status);
else
i_nz_norm = 1;
}
if (*status == 0) {
// Populate arrays
for(int ichi=0; ichi < nz; ichi++) {
double a = 1./(1+z_arr[ichi]);
double h = cosmo->params.h*ccl_h_over_h0(cosmo,a,status)/ccl_constants.CLIGHT_HMPC;
// H(z) * dN/dz * 1/Ngal
pchi_arr[ichi] = h*nz_arr[ichi]*i_nz_norm;
}
}
ccl_f1d_t_free(nz_f);
}
//3 H0^2 Omega_M / 2
static double get_lensing_prefactor(ccl_cosmology *cosmo,int *status) {
double hub = cosmo->params.h/ccl_constants.CLIGHT_HMPC;
return 1.5*hub*hub*cosmo->params.Omega_m;
}
typedef struct {
ccl_cosmology *cosmo;
double z_max;
double z_end;
double chi_end;
double i_nz_norm;
ccl_f1d_t *nz_f;
ccl_f1d_t *sz_f;
int *status;
} integ_lensing_pars;
// Integrand for lensing kernel.
// Returns N(z) * (1 - 5*s(z)/2) * (chi(z)-chi) / chi(z)
static double lensing_kernel_integrand(double z, void *pars) {
integ_lensing_pars *p = (integ_lensing_pars *)pars;
double pz = ccl_f1d_t_eval(p->nz_f, z);
double qz;
if (p->sz_f == NULL) // No magnification factor
qz = 1;
else // With magnification factor
qz = (1 - 2.5*ccl_f1d_t_eval(p->sz_f, z));
if (z == 0)
return pz * qz;
else {
double chi = ccl_comoving_radial_distance(p->cosmo, 1./(1+z), p->status);
return (
pz * qz *
ccl_sinn(p->cosmo, chi-p->chi_end, p->status) /
ccl_sinn(p->cosmo, chi, p->status));
}
}
// Returns
// Integral[ p(z) * (1-5s(z)/2) * chi_end * (chi(z)-chi_end)/chi(z) , {z',z_end,z_max} ]
static double lensing_kernel_integrate(ccl_cosmology *cosmo,
integ_lensing_pars *pars,
gsl_integration_workspace *w) {
int gslstatus = 0;
double result, eresult;
gsl_function F;
F.function = &lensing_kernel_integrand;
F.params = pars;
gslstatus = gsl_integration_qag(
&F, pars->z_end, pars->z_max, 0,
cosmo->gsl_params.INTEGRATION_EPSREL,
cosmo->gsl_params.N_ITERATION,
cosmo->gsl_params.INTEGRATION_GAUSS_KRONROD_POINTS,
w, &result, &eresult);
if ((gslstatus != GSL_SUCCESS) || (*(pars->status))) {
ccl_raise_gsl_warning(gslstatus, "ccl_tracers.c: lensing_kernel_integrate():");
return -1;
}
return result * pars->i_nz_norm * pars->chi_end;
}
//Returns number of divisions on which
//the lensing kernel should be calculated
int ccl_get_nchi_lensing_kernel(int nz, double *z_arr, int *status) {
int nchi;
double dz = -1, z_max = -1;
//Compute redshift step
dz = (z_arr[nz-1]-z_arr[0])/(nz-1);
//How many steps to z=0?
return (int)(z_arr[nz-1]/dz+0.5);
}
//Return array with the values of chi at
//the which the lensing kernel will be
//calculated.
void ccl_get_chis_lensing_kernel(ccl_cosmology *cosmo,
int nchi, double z_max,
double *chis, int *status) {
double dz = z_max/nchi;
for(int ichi=0; ichi < nchi; ichi++) {
double z = dz*ichi+1E-15;
double a = 1./(1+z);
chis[ichi] = ccl_comoving_radial_distance(cosmo, a, status);
}
}
//Returns array with lensing kernel:
//3 * H0^2 * Omega_M / 2 / a *
// Integral[ p(z) * (1-5s(z)/2) * chi_end * (chi(z)-chi_end)/chi(z) ,
// {z',z_end,z_max} ]
void ccl_get_lensing_mag_kernel(ccl_cosmology *cosmo,
int nz, double *z_arr, double *nz_arr,
int normalize_nz, double z_max,
int nz_s, double *zs_arr, double *sz_arr,
int nchi, double *chi_arr, double *wL_arr,
int *status) {
ccl_f1d_t *nz_f = NULL;
ccl_f1d_t *sz_f = NULL;
gsl_integration_workspace *w;
integ_lensing_pars *ipar;
int local_status;
// Prepare N(z) spline
nz_f = ccl_f1d_t_new(nz, z_arr, nz_arr, 0, 0);
if (nz_f == NULL) {
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_tracers.c: get_lensing_mag_kernel: error initializing spline\n");
}
// Get N(z) normalization
double i_nz_norm = -1;
if (*status == 0) {
if (normalize_nz)
i_nz_norm = 1./get_nz_norm(cosmo, nz_f, z_arr[0], z_arr[nz-1], status);
else
i_nz_norm = 1.;
}
// Prepare magnification bias spline if needed
if (*status == 0) {
if ((nz_s > 0) && (zs_arr != NULL) && (sz_arr != NULL)) {
sz_f = ccl_f1d_t_new(nz_s, zs_arr, sz_arr, sz_arr[0], sz_arr[nz_s-1]);
if (sz_f == NULL) {
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_tracers.c: get_lensing_mag_kernel: error initializing spline\n");
}
}
}
double lens_prefac = get_lensing_prefactor(cosmo, status);
double chi, a, z, mgfac;
int ichi;
w = NULL;
ipar = NULL;
local_status = *status;
if (local_status == 0) {
ipar = malloc(sizeof(integ_lensing_pars));
w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION);
if ((ipar == NULL) || (w == NULL)) {
local_status = CCL_ERROR_MEMORY;
}
}
if (local_status == 0) {
ipar->cosmo = cosmo;
ipar->z_max = z_max;
ipar->i_nz_norm = i_nz_norm;
ipar->sz_f = sz_f;
ipar->nz_f = nz_f;
ipar->status = &local_status;
}
//Populate arrays
for (ichi=0; ichi < nchi; ichi++) {
if (local_status == 0) {
chi = chi_arr[ichi];
a = ccl_scale_factor_of_chi(cosmo, chi, &local_status);
z = 1./a-1;
// Add MG correction if needed
mgfac = 1.0;
if (fabs(cosmo->params.sigma_0))
mgfac += ccl_Sig_MG(cosmo, a, &local_status);
ipar->z_end = z;
ipar->chi_end = chi;
wL_arr[ichi] = lensing_kernel_integrate(cosmo, ipar, w)*(1+z)*lens_prefac*mgfac;
} else {
wL_arr[ichi] = NAN;
}
}
gsl_integration_workspace_free(w);
free(ipar);
if (local_status != 0) {
*status = CCL_ERROR_INTEG;
}
ccl_f1d_t_free(nz_f);
ccl_f1d_t_free(sz_f);
}
// Returns kernel for CMB lensing
// 3H0^2Om/2 * chi * (chi_s - chi) / chi_s / a
void ccl_get_kappa_kernel(ccl_cosmology *cosmo, double chi_source,
int nchi, double *chi_arr,
double *wchi, int *status) {
double lens_prefac = get_lensing_prefactor(cosmo, status) / ccl_sinn(cosmo, chi_source, status);
for (int ichi=0; ichi < nchi; ichi++) {
double chi = chi_arr[ichi];
double a = ccl_scale_factor_of_chi(cosmo, chi, status);
double mgfac = 1;
// Add MG correction if needed
if (fabs(cosmo->params.sigma_0))
mgfac += ccl_Sig_MG(cosmo, a, status);
wchi[ichi] = lens_prefac*(ccl_sinn(cosmo,chi_source-chi,status))*chi*mgfac/a;
}
}
ccl_cl_tracer_t *ccl_cl_tracer_t_new(ccl_cosmology *cosmo,
int der_bessel,
int der_angles,
int n_w, double *chi_w, double *w_w,
int na_ka, double *a_ka,
int nk_ka, double *lk_ka,
double *fka_arr,
double *fk_arr,
double *fa_arr,
int is_fka_log,
int is_factorizable,
int extrap_order_lok,
int extrap_order_hik,
int *status) {
ccl_cl_tracer_t *tr = NULL;
// Check der_bessel and der_angles are sensible
if ((der_angles < 0) || (der_angles > 2)) {
*status = CCL_ERROR_INCONSISTENT;
ccl_cosmology_set_status_message(
cosmo,
"ccl_tracers.c: ccl_cl_tracer_new: der_angles must be between 0 and 2\n");
}
if ((der_bessel < -1) || (der_bessel > 2)) {
*status = CCL_ERROR_INCONSISTENT;
ccl_cosmology_set_status_message(
cosmo,
"ccl_tracers.c: ccl_cl_tracer_new: der_bessel must be between -1 and 2\n");
}
if (*status == 0) {
tr = malloc(sizeof(ccl_cl_tracer_t));
if (tr == NULL)
*status = CCL_ERROR_MEMORY;
}
// Initialize everythin
if (*status == 0) {
tr->der_angles = der_angles;
tr->der_bessel = der_bessel;
tr->kernel = NULL; // Initialize these to NULL
tr->transfer = NULL; // Initialize these to NULL
tr->chi_min = 0;
tr->chi_max = 1E15;
}
if (*status == 0) {
// Initialize radial kernel
if ((n_w > 0) && (chi_w != NULL) && (w_w != NULL)) {
tr->kernel = ccl_f1d_t_new(n_w,chi_w,w_w,0,0);
if (tr->kernel == NULL)
*status=CCL_ERROR_MEMORY;
}
}
// Find kernel edges
if (*status == 0) {
// If no radial kernel, set limits to zero and maximum distance
if (tr->kernel == NULL) {
tr->chi_min = 0;
tr->chi_max = ccl_comoving_radial_distance(cosmo, cosmo->spline_params.A_SPLINE_MIN, status);
}
else {
int ichi;
double w_max = fabs(w_w[0]);
// Find maximum of radial kernel
for (ichi=0; ichi < n_w; ichi++) {
if (fabs(w_w[ichi]) >= w_max)
w_max = fabs(w_w[ichi]);
}
// Multiply by fraction
w_max *= CCL_FRAC_RELEVANT;
// Initialize as the original edges in case we don't find an interval
tr->chi_min = chi_w[0];
tr->chi_max = chi_w[n_w-1];
// Find minimum
for (ichi=0; ichi < n_w; ichi++) {
if (fabs(w_w[ichi]) >= w_max) {
tr->chi_min = chi_w[ichi];
break;
}
}
// Find maximum
for (ichi=n_w-1; ichi >= 0; ichi--) {
if (fabs(w_w[ichi]) >= w_max) {
tr->chi_max = chi_w[ichi];
break;
}
}
}
}
if (*status == 0) {
if ((fka_arr != NULL) || (fk_arr != NULL) || (fa_arr != NULL)) {
tr->transfer = ccl_f2d_t_new(
na_ka,a_ka, // na, a_arr
nk_ka,lk_ka, // nk, lk_arr
fka_arr, // fka_arr
fk_arr, // fk_arr
fa_arr, // fa_arr
is_factorizable, // is factorizable
extrap_order_lok, // extrap_order_lok
extrap_order_hik, // extrap_order_hik
ccl_f2d_constantgrowth, // extrap_linear_growth
is_fka_log, // is_fka_log
NULL, // growth (function)
1, // growth_factor_0 -> will assume constant transfer function
0, // growth_exponent
ccl_f2d_3, // interp_type
status);
if (tr->transfer == NULL)
*status=CCL_ERROR_MEMORY;
}
}
return tr;
}
void ccl_cl_tracer_t_free(ccl_cl_tracer_t *tr) {
if (tr != NULL) {
if (tr->transfer != NULL)
ccl_f2d_t_free(tr->transfer);
if (tr->kernel != NULL)
ccl_f1d_t_free(tr->kernel);
free(tr);
}
}
double ccl_cl_tracer_t_get_f_ell(ccl_cl_tracer_t *tr, double ell, int *status) {
if (tr != NULL) {
if (tr->der_angles == 1)
return ell*(ell+1.);
else if (tr->der_angles == 2) {
if (ell <= 1) // This is identically 0
return 0;
else if (ell <= 10) // Use full expression in this case
return sqrt((ell+2)*(ell+1)*ell*(ell-1));
else {
double lp1h = ell+0.5;
double lp1h2 = lp1h*lp1h;
if (ell <= 1000) // This is accurate to 5E-5 for l>10
return lp1h2*(1-1.25/lp1h2);
else // This is accurate to 1E-6 for l>1000
return lp1h2;
}
}
else
return 1;
}
else
return 1;
}
double ccl_cl_tracer_t_get_kernel(ccl_cl_tracer_t *tr, double chi, int *status) {
if (tr != NULL) {
if (tr->kernel != NULL)
return ccl_f1d_t_eval(tr->kernel, chi);
else
return 1;
}
else
return 1;
}
double ccl_cl_tracer_t_get_transfer(ccl_cl_tracer_t *tr,
double lk, double a, int *status) {
if (tr != NULL) {
if (tr->transfer != NULL)
return ccl_f2d_t_eval(tr->transfer, lk, a, NULL, status);
else
return 1;
}
else
return 1;
}
| {
"alphanum_fraction": 0.5942037754,
"avg_line_length": 29.304964539,
"ext": "c",
"hexsha": "d234499f6102a8398a4b2c53ba6891599ce67cdf",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z",
"max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "benediktdiemer/CCL",
"max_forks_repo_path": "src/ccl_tracers.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"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": "benediktdiemer/CCL",
"max_issues_repo_path": "src/ccl_tracers.c",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "benediktdiemer/CCL",
"max_stars_repo_path": "src/ccl_tracers.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5134,
"size": 16528
} |
/* ode-initval2/msbdf.c
*
* Copyright (C) 2009, 2010 Tuomo Keskitalo
*
* 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.
*/
/* A variable-coefficient linear multistep backward differentiation
formula (BDF) method in Nordsieck form. This stepper uses the
explicit BDF formula as predictor and implicit BDF formula as
corrector. A modified Newton iteration method is used to
solve the system of non-linear equations. Method order varies
dynamically between 1 and 5.
References:
Byrne, G. D., and Hindmarsh, A. C., A Polyalgorithm for the
Numerical Solution of Ordinary Differential Equations,
ACM Trans. Math. Software, 1 (1975), pp. 71-96.
Brown, P. N., Byrne, G. D., and Hindmarsh, A. C., VODE: A
Variable-coefficient ODE Solver, SIAM J. Sci. Stat. Comput. 10,
(1989), pp. 1038-1051.
Hindmarsh, A. C., Brown, P. N., Grant, K. E., Lee, S. L., Serban,
R., Shumaker, D. E., and Woodward, C. S., SUNDIALS: Suite of
Nonlinear and Differential/Algebraic Equation Solvers, ACM
Trans. Math. Software 31 (2005), pp. 363-396.
Note: The algorithms have been adapted for GSL ode-initval2
framework.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include "odeiv_util.h"
/* Maximum order of BDF methods */
#define MSBDF_MAX_ORD 5
/* Steps until Jacobian evaluation is forced */
#define MSBDF_JAC_WAIT 50
/* Steps until iteration matrix M evaluation is forced */
#define MSBDF_M_WAIT 20
typedef struct
{
/* Nordsieck history matrix. Includes concatenated
Nordsieck vectors [y_n, h*y_n', (h^2/2!)*y_n'', ...,
(h^ord/ord!)*d^(ord)(y_n)]. Nordsieck vector number i is located
at z[i*dim] (i=0..ord).
*/
double *z;
double *zbackup; /* backup of Nordsieck matrix */
double *ytmp; /* work area */
double *ytmp2; /* work area */
double *l; /* polynomial coefficients */
double *hprev; /* previous step sizes */
double *hprevbackup; /* backup of hprev */
size_t *ordprev; /* orders of previous calls */
size_t *ordprevbackup; /* backup of ordprev */
double *errlev; /* desired error level of y */
gsl_vector *abscor; /* absolute y values for correction */
gsl_vector *relcor; /* relative y values for correction */
gsl_vector *svec; /* saved abscor & work area */
gsl_vector *tempvec; /* work area */
const gsl_odeiv2_driver *driver; /* pointer to gsl_odeiv2_driver object */
gsl_matrix *dfdy; /* Jacobian */
double *dfdt; /* storage for time derivative of f */
gsl_matrix *M; /* Newton iteration matrix */
gsl_permutation *p; /* permutation for LU decomposition of M */
gsl_vector *rhs; /* right hand side equations (-G) */
long int ni; /* stepper call counter */
size_t ord; /* current order of method */
double tprev; /* t point of previous call */
size_t ordwait; /* counter for order change */
size_t ordwaitbackup; /* backup of ordwait */
size_t failord; /* order of convergence failure */
double failt; /* t point of convergence failure */
double ordp1coeffprev; /* saved order coefficient */
size_t nJ; /* step counter for Jacobian evaluation */
size_t nM; /* step counter for update of M */
double gammaprev; /* gamma of previous call */
double gammaprevbackup; /* backup of gammaprev */
size_t failcount; /* counter for rejected steps */
}
msbdf_state_t;
/* Introduce msbdf_reset for use in msbdf_alloc and _apply */
static int msbdf_reset (void *, size_t);
static void *
msbdf_alloc (size_t dim)
{
msbdf_state_t *state = (msbdf_state_t *) malloc (sizeof (msbdf_state_t));
if (state == 0)
{
GSL_ERROR_NULL ("failed to allocate space for msbdf_state", GSL_ENOMEM);
}
state->z = (double *) malloc ((MSBDF_MAX_ORD + 1) * dim * sizeof (double));
if (state->z == 0)
{
free (state);
GSL_ERROR_NULL ("failed to allocate space for z", GSL_ENOMEM);
}
state->zbackup =
(double *) malloc ((MSBDF_MAX_ORD + 1) * dim * sizeof (double));
if (state->zbackup == 0)
{
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for zbackup", GSL_ENOMEM);
}
state->ytmp = (double *) malloc (dim * sizeof (double));
if (state->ytmp == 0)
{
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM);
}
state->ytmp2 = (double *) malloc (dim * sizeof (double));
if (state->ytmp2 == 0)
{
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp2", GSL_ENOMEM);
}
state->l = (double *) malloc ((MSBDF_MAX_ORD + 1) * sizeof (double));
if (state->l == 0)
{
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for l", GSL_ENOMEM);
}
state->hprev = (double *) malloc (MSBDF_MAX_ORD * sizeof (double));
if (state->hprev == 0)
{
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for hprev", GSL_ENOMEM);
}
state->hprevbackup = (double *) malloc (MSBDF_MAX_ORD * sizeof (double));
if (state->hprevbackup == 0)
{
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for hprevbackup", GSL_ENOMEM);
}
state->ordprev = (size_t *) malloc (MSBDF_MAX_ORD * sizeof (size_t));
if (state->ordprev == 0)
{
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ordprev", GSL_ENOMEM);
}
state->ordprevbackup = (size_t *) malloc (MSBDF_MAX_ORD * sizeof (size_t));
if (state->ordprevbackup == 0)
{
free (state->ordprev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ordprevbackup",
GSL_ENOMEM);
}
state->errlev = (double *) malloc (dim * sizeof (double));
if (state->errlev == 0)
{
free (state->ordprevbackup);
free (state->ordprev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for errlev", GSL_ENOMEM);
}
state->abscor = gsl_vector_alloc (dim);
if (state->abscor == 0)
{
free (state->errlev);
free (state->ordprevbackup);
free (state->ordprev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for abscor", GSL_ENOMEM);
}
state->relcor = gsl_vector_alloc (dim);
if (state->relcor == 0)
{
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->ordprevbackup);
free (state->ordprev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for relcor", GSL_ENOMEM);
}
state->svec = gsl_vector_alloc (dim);
if (state->svec == 0)
{
gsl_vector_free (state->relcor);
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->ordprevbackup);
free (state->ordprev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for svec", GSL_ENOMEM);
}
state->tempvec = gsl_vector_alloc (dim);
if (state->tempvec == 0)
{
gsl_vector_free (state->svec);
gsl_vector_free (state->relcor);
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->ordprevbackup);
free (state->ordprev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for tempvec", GSL_ENOMEM);
}
state->dfdy = gsl_matrix_alloc (dim, dim);
if (state->dfdy == 0)
{
gsl_vector_free (state->tempvec);
gsl_vector_free (state->svec);
gsl_vector_free (state->relcor);
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->ordprevbackup);
free (state->ordprev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for dfdy", GSL_ENOMEM);
}
state->dfdt = (double *) malloc (dim * sizeof (double));
if (state->dfdt == 0)
{
gsl_matrix_free (state->dfdy);
gsl_vector_free (state->tempvec);
gsl_vector_free (state->svec);
gsl_vector_free (state->relcor);
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->ordprevbackup);
free (state->ordprev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for dfdt", GSL_ENOMEM);
}
state->M = gsl_matrix_alloc (dim, dim);
if (state->M == 0)
{
free (state->dfdt);
gsl_matrix_free (state->dfdy);
gsl_vector_free (state->tempvec);
gsl_vector_free (state->svec);
gsl_vector_free (state->relcor);
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->ordprevbackup);
free (state->ordprev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for M", GSL_ENOMEM);
}
state->p = gsl_permutation_alloc (dim);
if (state->p == 0)
{
gsl_matrix_free (state->M);
free (state->dfdt);
gsl_matrix_free (state->dfdy);
gsl_vector_free (state->tempvec);
gsl_vector_free (state->svec);
gsl_vector_free (state->relcor);
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->ordprevbackup);
free (state->ordprev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for p", GSL_ENOMEM);
}
state->rhs = gsl_vector_alloc (dim);
if (state->rhs == 0)
{
gsl_permutation_free (state->p);
gsl_matrix_free (state->M);
free (state->dfdt);
gsl_matrix_free (state->dfdy);
gsl_vector_free (state->tempvec);
gsl_vector_free (state->svec);
gsl_vector_free (state->relcor);
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->ordprevbackup);
free (state->ordprev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for rhs", GSL_ENOMEM);
}
msbdf_reset ((void *) state, dim);
state->driver = NULL;
return state;
}
static int
msbdf_failurehandler (void *vstate, const size_t dim, const double t)
{
/* Internal failure handler routine for msbdf. Adjusted strategy
for GSL: Decrease order if this is the second time a failure
has occurred at this order and point.
*/
msbdf_state_t *state = (msbdf_state_t *) vstate;
const size_t ord = state->ord;
if (ord > 1 && (ord - state->ordprev[0] == 0) &&
ord == state->failord && t == state->failt)
{
state->ord--;
}
/* Save information about failure */
state->failord = ord;
state->failt = t;
state->ni++;
/* Force reinitialization if failure took place at lowest
order
*/
if (ord == 1)
{
msbdf_reset (vstate, dim);
}
return GSL_SUCCESS;
}
static int
msbdf_calccoeffs (const size_t ord, const size_t ordwait,
const double h, const double hprev[],
double l[],
double *errcoeff, double *ordm1coeff,
double *ordp1coeff, double *ordp2coeff, double *gamma)
{
/* Calculates coefficients (l) of polynomial Lambda, error and
auxiliary order change evaluation coefficients.
*/
if (ord == 1)
{
l[0] = 1.0;
l[1] = 1.0;
*errcoeff = 0.5;
*ordp1coeff = 2.0;
{
const double hsum = h + hprev[0];
const double a5 = -1.5;
const double a6 = -1.0 - h / hsum;
const double c2 = 2.0 / (1.0 - a6 + a5);
*ordp2coeff = fabs (c2 * (h / hsum) * 3.0 * a5);
}
}
else
{
size_t i, j;
double hsum = h;
double coeff1 = -1.0;
double x;
/* Calculate the actual polynomial coefficients (l) */
DBL_ZERO_MEMSET (l, MSBDF_MAX_ORD + 1);
l[0] = 1.0;
l[1] = 1.0;
for (i = 2; i < ord; i++)
{
hsum += hprev[i - 2];
coeff1 += -1.0 / i;
for (j = i; j > 0; j--)
{
l[j] += h / hsum * l[j - 1];
}
}
coeff1 += -1.0 / ord;
x = -l[1] - coeff1;
for (i = ord; i > 0; i--)
{
l[i] += l[i - 1] * x;
}
#ifdef DEBUG
{
size_t di;
printf ("-- calccoeffs l: ");
for (di = 0; di < ord + 1; di++)
{
printf ("%.5e ", l[di]);
}
printf ("\n");
}
#endif
hsum += hprev[ord - 2];
{
const double coeff2 = -l[1] - h / hsum;
const double a1 = 1.0 - coeff2 + coeff1;
const double a2 = 1.0 + ord * a1;
/* Calculate error coefficient */
*errcoeff = fabs (a1 / (coeff1 * a2));
/* Calculate auxiliary coefficients used in evaluation of change
of order
*/
if (ordwait < 2)
{
const double a3 = coeff1 + 1.0 / ord;
const double a4 = coeff2 + h / hsum;
const double c1 = a3 / (1.0 - a4 + a3);
*ordm1coeff = fabs (c1 / (x / l[ord]));
*ordp1coeff = fabs (a2 / (l[ord] * (h / hsum) / x));
hsum += hprev[ord - 1];
{
const double a5 = coeff1 - 1.0 / (ord + 1.0);
const double a6 = coeff2 - h / hsum;
const double c2 = a2 / (1.0 - a6 + a5);
*ordp2coeff = fabs (c2 * (h / hsum) * (ord + 2) * a5);
}
}
}
}
*gamma = h / l[1];
#ifdef DEBUG
printf ("-- calccoeffs ordm1coeff=%.5e ", *ordm1coeff);
printf ("ordp1coeff=%.5e ", *ordp1coeff);
printf ("ordp2coeff=%.5e ", *ordp2coeff);
printf ("errcoeff=%.5e\n", *errcoeff);
#endif
return GSL_SUCCESS;
}
static int
msbdf_update (void *vstate, const size_t dim, gsl_matrix * dfdy, double *dfdt,
const double t, const double *y, const gsl_odeiv2_system * sys,
gsl_matrix * M, gsl_permutation * p,
const size_t iter, size_t * nJ, size_t * nM,
const double tprev, const double failt,
const double gamma, const double gammaprev, const double hratio)
{
/* Evaluates Jacobian dfdy and updates iteration matrix M
if criteria for update is met.
*/
/* Jacobian is evaluated
- at first step
- if MSBDF_JAC_WAIT steps have been made without re-evaluation
- in case of a convergence failure if
--- change in gamma is small, or
--- convergence failure resulted in step size decrease
*/
const double c = 0.2;
const double gammarel = fabs (gamma / gammaprev - 1.0);
if (*nJ == 0 || *nJ > MSBDF_JAC_WAIT ||
(t == failt && (gammarel < c || hratio < 1.0)))
{
#ifdef DEBUG
printf ("-- evaluate jacobian\n");
#endif
int s = GSL_ODEIV_JA_EVAL (sys, t, y, dfdy->data, dfdt);
if (s == GSL_EBADFUNC)
{
return s;
}
if (s != GSL_SUCCESS)
{
msbdf_failurehandler (vstate, dim, t);
#ifdef DEBUG
printf ("-- FAIL at jacobian function evaluation\n");
#endif
return s;
}
/* Reset counter */
*nJ = 0;
}
/* Iteration matrix M (and it's LU decomposition) is generated
- at first step
- if MSBDF_M_WAIT steps have been made without an update
- if change in gamma is significant (e.g. change in step size)
- if previous step was rejected
*/
if (*nM == 0 || *nM > MSBDF_M_WAIT || gammarel >= c ||
t == tprev || t == failt)
{
#ifdef DEBUG
printf ("-- update M, gamma=%.5e\n", gamma);
#endif
size_t i;
gsl_matrix_memcpy (M, dfdy);
gsl_matrix_scale (M, -gamma);
for (i = 0; i < dim; i++)
{
gsl_matrix_set (M, i, i, gsl_matrix_get (M, i, i) + 1.0);
}
{
int signum;
int s = gsl_linalg_LU_decomp (M, p, &signum);
if (s != GSL_SUCCESS)
{
return GSL_FAILURE;
}
}
/* Reset counter */
*nM = 0;
}
return GSL_SUCCESS;
}
static int
msbdf_corrector (void *vstate, const gsl_odeiv2_system * sys,
const double t, const double h, const size_t dim,
const double z[], const double errlev[],
const double l[], const double errcoeff,
gsl_vector * abscor, gsl_vector * relcor,
double ytmp[], double ytmp2[],
gsl_matrix * dfdy, double dfdt[], gsl_matrix * M,
gsl_permutation * p, gsl_vector * rhs,
size_t * nJ, size_t * nM,
const double tprev, const double failt,
const double gamma, const double gammaprev,
const double hprev0)
{
/* Calculates the correction step (abscor). Equation
system M = I - gamma * dfdy = -G is solved by Newton iteration.
*/
size_t mi, i;
const size_t max_iter = 3; /* Maximum number of iterations */
double convrate = 1.0; /* convergence rate */
double stepnorm = 0.0; /* norm of correction step */
double stepnormprev = 0.0; /* previous norm value */
/* Evaluate at predicted values */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, z, ytmp);
if (s == GSL_EBADFUNC)
{
return s;
}
if (s != GSL_SUCCESS)
{
msbdf_failurehandler (vstate, dim, t);
#ifdef DEBUG
printf ("-- FAIL at user function evaluation\n");
#endif
return s;
}
}
/* Calculate correction step (abscor) */
gsl_vector_set_zero (abscor);
for (mi = 0; mi < max_iter; mi++)
{
const double safety = 0.3;
const double safety2 = 0.1;
/* Generate or update Jacobian and/or iteration matrix M if needed */
if (mi == 0)
{
int s = msbdf_update (vstate, dim, dfdy, dfdt, t + h, z,
sys, M, p, mi,
nJ, nM, tprev, failt,
gamma, gammaprev,
h / hprev0);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* Evaluate the right hand side (-G) */
for (i = 0; i < dim; i++)
{
const double r = -1.0 * gsl_vector_get (abscor, i) -
z[1 * dim + i] / l[1] + gamma * ytmp[i];
gsl_vector_set (rhs, i, r);
}
/* Solve system of equations */
{
int s = gsl_linalg_LU_solve (M, p, rhs, relcor);
if (s != GSL_SUCCESS)
{
msbdf_failurehandler (vstate, dim, t);
#ifdef DEBUG
printf ("-- FAIL at LU_solve\n");
#endif
return GSL_FAILURE;
}
}
#ifdef DEBUG
{
size_t di;
printf ("-- dstep: ");
for (di = 0; di < dim; di++)
{
printf ("%.5e ", gsl_vector_get (relcor, di));
}
printf ("\n");
}
#endif
/* Add iteration results */
for (i = 0; i < dim; i++)
{
const double r =
gsl_vector_get (abscor, i) + gsl_vector_get (relcor, i);
gsl_vector_set (abscor, i, r);
ytmp2[i] = z[i] + r;
gsl_vector_set (relcor, i, gsl_vector_get (relcor, i) / errlev[i]);
}
#ifdef DEBUG
{
size_t di;
printf ("-- abscor: ");
for (di = 0; di < dim; di++)
{
printf ("%.5e ", gsl_vector_get (abscor, di));
}
printf ("\n");
}
#endif
/* Convergence test. Norms used are root-mean-square norms. */
stepnorm = gsl_blas_dnrm2 (relcor) / sqrt (dim);
if (mi > 0)
{
convrate = GSL_MAX_DBL (safety * convrate, stepnorm / stepnormprev);
}
else
{
convrate = 1.0;
}
{
const double convtest =
GSL_MIN_DBL (convrate, 1.0) * stepnorm * errcoeff / safety2;
#ifdef DEBUG
printf
("-- newt iter loop %d, errcoeff=%.5e, stepnorm =%.5e, convrate = %.5e, convtest = %.5e\n",
(int) mi, errcoeff, stepnorm, convrate, convtest);
#endif
if (convtest <= 1.0)
{
break;
}
}
/* Check for divergence during iteration */
{
const double div_const = 2.0;
if (mi > 1 && stepnorm > div_const * stepnormprev)
{
msbdf_failurehandler (vstate, dim, t);
#ifdef DEBUG
printf ("-- FAIL, diverging Newton iteration\n");
#endif
return GSL_FAILURE;
}
}
/* Evaluate at new y */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, ytmp2, ytmp);
if (s == GSL_EBADFUNC)
{
return s;
}
if (s != GSL_SUCCESS)
{
msbdf_failurehandler (vstate, dim, t);
#ifdef DEBUG
printf ("-- FAIL at user function evaluation\n");
#endif
return s;
}
}
stepnormprev = stepnorm;
}
#ifdef DEBUG
printf ("-- Newton iteration exit at mi=%d\n", (int) mi);
#endif
/* Handle convergence failure */
if (mi == max_iter)
{
msbdf_failurehandler (vstate, dim, t);
#ifdef DEBUG
printf ("-- FAIL, max_iter reached\n");
#endif
return GSL_FAILURE;
}
return GSL_SUCCESS;
}
static int
msbdf_eval_order (gsl_vector * abscor, gsl_vector * tempvec,
gsl_vector * svec, const double errcoeff,
const size_t dim, const double errlev[],
const double ordm1coeff, const double ordp1coeff,
const double ordp1coeffprev, const double ordp2coeff,
const double hprev[],
const double h, const double z[],
size_t * ord, size_t * ordwait)
{
/* Evaluates and executes change in method order (current, current-1
or current+1). Order which maximizes the step length is selected.
*/
size_t i;
/* step size estimates at current order, order-1 and order+1 */
double ordest = 0.0;
double ordm1est = 0.0;
double ordp1est = 0.0;
const double safety = 1e-6;
const double bias = 6.0;
const double bias2 = 10.0;
const double min_incr = 1.5;
/* Relative step length estimate for current order */
ordest = 1.0 / (pow (bias * gsl_blas_dnrm2 (abscor) / sqrt (dim)
* errcoeff, 1.0 / (*ord + 1)) + safety);
/* Relative step length estimate for order ord - 1 */
if (*ord > 1)
{
for (i = 0; i < dim; i++)
{
gsl_vector_set (tempvec, i, z[*ord * dim + i] / errlev[i]);
}
ordm1est = 1.0 / (pow (bias * gsl_blas_dnrm2 (tempvec) / sqrt (dim)
/ ordm1coeff, 1.0 / (*ord)) + safety);
}
else
{
ordm1est = 0.0;
}
/* Relative step length estimate for order ord + 1 */
if (*ord < MSBDF_MAX_ORD)
{
const double c = -ordp1coeff / ordp1coeffprev *
pow (h / hprev[1], *ord + 1);
for (i = 0; i < dim; i++)
{
gsl_vector_set (svec, i, gsl_vector_get (svec, i) * c +
gsl_vector_get (abscor, i));
}
ordp1est = 1.0 / (pow (bias2 * gsl_blas_dnrm2 (svec) / sqrt (dim)
/ ordp2coeff, 1.0 / (*ord + 2)) + safety);
}
else
{
ordp1est = 0.0;
}
#ifdef DEBUG
printf
("-- eval_order ord=%d, ordest=%.5e, ordm1est=%.5e, ordp1est=%.5e\n",
(int) *ord, ordest, ordm1est, ordp1est);
#endif
/* Choose order that maximises step size and increases step
size markedly compared to current step
*/
if (ordm1est > ordest && ordm1est > ordp1est && ordm1est > min_incr)
{
*ord -= 1;
#ifdef DEBUG
printf ("-- eval_order order DECREASED to %d\n", (int) *ord);
#endif
}
else if (ordp1est > ordest && ordp1est > ordm1est && ordp1est > min_incr)
{
*ord += 1;
#ifdef DEBUG
printf ("-- eval_order order INCREASED to %d\n", (int) *ord);
#endif
}
*ordwait = *ord + 2;
return GSL_SUCCESS;
}
static int
msbdf_check_no_order_decrease (size_t const ordprev[])
{
/* Checks if order has not been decreased according to order history
array. Used in stability enhancement.
*/
size_t i;
for (i = 0; i < MSBDF_MAX_ORD - 1; i++)
{
if (ordprev[i + 1] > ordprev[i])
{
return 0;
}
}
return 1;
}
static int
msbdf_check_step_size_decrease (double const hprev[])
{
/* Checks if step size has decreased markedly according to
step size history array. Used in stability enhancement.
*/
size_t i;
double max = fabs (hprev[0]);
const double min = fabs (hprev[0]);
const double decrease_limit = 0.5;
for (i = 1; i < MSBDF_MAX_ORD; i++)
{
const double h = fabs (hprev[i]);
if (h > min && h > max)
{
max = h;
}
}
if (min / max < decrease_limit)
{
return 1;
}
return 0;
}
static int
msbdf_apply (void *vstate, size_t dim, double t, double h,
double y[], double yerr[],
const double dydt_in[], double dydt_out[],
const gsl_odeiv2_system * sys)
{
/* Carries out a step by BDF linear multistep methods. */
msbdf_state_t *state = (msbdf_state_t *) vstate;
double *const z = state->z;
double *const zbackup = state->zbackup;
double *const ytmp = state->ytmp;
double *const ytmp2 = state->ytmp2;
double *const l = state->l;
double *const hprev = state->hprev;
double *const hprevbackup = state->hprevbackup;
size_t *const ordprev = state->ordprev;
size_t *const ordprevbackup = state->ordprevbackup;
double *const errlev = state->errlev;
gsl_vector *const abscor = state->abscor;
gsl_vector *const relcor = state->relcor;
gsl_vector *const svec = state->svec;
gsl_vector *const tempvec = state->tempvec;
size_t ord = state->ord; /* order for this step */
double ordm1coeff = 0.0;
double ordp1coeff = 0.0;
double ordp2coeff = 0.0;
double errcoeff = 0.0; /* error coefficient */
double gamma = 0.0; /* gamma coefficient */
const size_t max_failcount = 3;
size_t i;
#ifdef DEBUG
{
size_t di;
printf ("msbdf_apply: t=%.5e, ord=%d, h=%.5e, y:", t, (int) ord, h);
for (di = 0; di < dim; di++)
{
printf ("%.5e ", y[di]);
}
printf ("\n");
}
#endif
/* Check if t is the same as on previous stepper call (or last
failed call). This means that calculation of previous step failed
or the step was rejected, and therefore previous state will be
restored or the method will be reset.
*/
if (state->ni > 0 && (t == state->tprev || t == state->failt))
{
if (state->ni == 1)
{
/* No step has been accepted yet, reset method */
msbdf_reset (vstate, dim);
#ifdef DEBUG
printf ("-- first step was REJECTED, msbdf_reset called\n");
#endif
}
else
{
/* A succesful step has been saved, restore previous state. */
/* If previous step suggests order increase, but the step was
rejected, then do not increase order.
*/
if (ord > ordprev[0])
{
state->ord = ordprev[0];
ord = state->ord;
}
/* Restore previous state */
DBL_MEMCPY (z, zbackup, (MSBDF_MAX_ORD + 1) * dim);
DBL_MEMCPY (hprev, hprevbackup, MSBDF_MAX_ORD);
for (i = 0; i < MSBDF_MAX_ORD; i++)
{
ordprev[i] = ordprevbackup[i];
}
state->ordwait = state->ordwaitbackup;
state->gammaprev = state->gammaprevbackup;
#ifdef DEBUG
printf ("-- previous step was REJECTED, state restored\n");
#endif
}
/* If step is repeatedly rejected, then reset method */
state->failcount++;
if (state->failcount > max_failcount && state->ni > 1)
{
msbdf_reset (vstate, dim);
ord = state->ord;
#ifdef DEBUG
printf ("-- max_failcount reached, msbdf_reset called\n");
#endif
}
}
else
{
/* The previous step was accepted. Backup current state. */
DBL_MEMCPY (zbackup, z, (MSBDF_MAX_ORD + 1) * dim);
DBL_MEMCPY (hprevbackup, hprev, MSBDF_MAX_ORD);
for (i = 0; i < MSBDF_MAX_ORD; i++)
{
ordprevbackup[i] = ordprev[i];
}
state->ordwaitbackup = state->ordwait;
state->gammaprevbackup = state->gammaprev;
state->failcount = 0;
#ifdef DEBUG
if (state->ni > 0)
{
printf ("-- previous step was ACCEPTED, state saved\n");
}
#endif
}
#ifdef DEBUG
printf ("-- ord=%d, ni=%ld, ordwait=%d\n", (int) ord, state->ni,
(int) state->ordwait);
size_t di;
printf ("-- ordprev: ");
for (di = 0; di < MSBDF_MAX_ORD; di++)
{
printf ("%d ", (int) ordprev[di]);
}
printf ("\n");
#endif
/* Get desired error levels via gsl_odeiv2_control object through driver
object, which is a requirement for this stepper.
*/
if (state->driver == NULL)
{
return GSL_EFAULT;
}
else
{
size_t i;
for (i = 0; i < dim; i++)
{
if (dydt_in != NULL)
{
gsl_odeiv2_control_errlevel (state->driver->c, y[i],
dydt_in[i], h, i, &errlev[i]);
}
else
{
gsl_odeiv2_control_errlevel (state->driver->c, y[i],
0.0, h, i, &errlev[i]);
}
}
}
#ifdef DEBUG
{
size_t di;
printf ("-- errlev: ");
for (di = 0; di < dim; di++)
{
printf ("%.5e ", errlev[di]);
}
printf ("\n");
}
#endif
/* On first call initialize Nordsieck matrix */
if (state->ni == 0)
{
size_t i;
DBL_ZERO_MEMSET (z, (MSBDF_MAX_ORD + 1) * dim);
if (dydt_in != NULL)
{
DBL_MEMCPY (ytmp, dydt_in, dim);
}
else
{
int s = GSL_ODEIV_FN_EVAL (sys, t, y, ytmp);
if (s != GSL_SUCCESS)
{
return s;
}
}
DBL_MEMCPY (&z[0 * dim], y, dim);
DBL_MEMCPY (&z[1 * dim], ytmp, dim);
for (i = 0; i < dim; i++)
{
z[1 * dim + i] *= h;
}
}
/* Stability enhancement heuristic for msbdf: If order > 1 and order
has not been changed, check for decrease in step size, that is
not accompanied by a decrease in method order. This condition may
be indication of BDF method stability problems, a change in ODE
system, or convergence problems in Newton iteration. In all
cases, the strategy is to decrease method order.
*/
#ifdef DEBUG
printf ("-- check_no_order_decrease %d, check_step_size_decrease %d\n",
msbdf_check_no_order_decrease (ordprev),
msbdf_check_step_size_decrease (hprev));
#endif
if (ord > 1 &&
ord - ordprev[0] == 0 &&
msbdf_check_no_order_decrease (ordprev) &&
msbdf_check_step_size_decrease (hprev))
{
state->ord--;
state->ordwait = ord + 2;
ord = state->ord;
#ifdef DEBUG
printf ("-- stability enhancement decreased order to %d\n", (int) ord);
#endif
}
/* Sanity check */
{
const int deltaord = ord - ordprev[0];
if (deltaord > 1 || deltaord < -1)
{
printf ("-- order change %d\n", deltaord);
GSL_ERROR_NULL ("msbdf_apply too large order change", GSL_ESANITY);
}
/* Modify Nordsieck matrix if order or step length has been changed */
/* If order increased by 1, adjust Nordsieck matrix */
if (deltaord == 1)
{
if (ord > 2)
{
size_t i, j;
double hsum = h;
double coeff1 = -1.0;
double coeff2 = 1.0;
double hrelprev = 1.0;
double hrelprod = 1.0;
double hrel = 0.0;
/* Calculate coefficients used in adjustment to l */
DBL_ZERO_MEMSET (l, MSBDF_MAX_ORD + 1);
l[2] = 1.0;
for (i = 1; i < ord - 1; i++)
{
hsum += hprev[i];
hrel = hsum / h;
hrelprod *= hrel;
coeff1 -= 1.0 / (i + 1);
coeff2 += 1.0 / hrel;
for (j = i + 2; j > 1; j--)
{
l[j] *= hrelprev;
l[j] += l[j - 1];
}
hrelprev = hrel;
}
/* Scale Nordsieck matrix */
{
const double c = (-coeff1 - coeff2) / hrelprod;
for (i = 0; i < dim; i++)
{
z[ord * dim + i] = c * gsl_vector_get (abscor, i);
}
}
for (i = 2; i < ord; i++)
for (j = 0; j < dim; j++)
{
z[i * dim + j] += l[i] * z[ord * dim + j];
}
}
else
{
/* zero new vector for order incease from 1 to 2 */
DBL_ZERO_MEMSET (&z[ord * dim], dim);
}
#ifdef DEBUG
printf ("-- order increase detected, Nordsieck modified\n");
#endif
}
/* If order decreased by 1, adjust Nordsieck matrix */
if (deltaord == -1)
{
size_t i, j;
double hsum = 0.0;
/* Calculate coefficients used in adjustment to l */
DBL_ZERO_MEMSET (l, MSBDF_MAX_ORD + 1);
l[2] = 1.0;
for (i = 1; i < ord; i++)
{
hsum += hprev[i - 1];
for (j = i + 2; j > 1; j--)
{
l[j] *= hsum / h;
l[j] += l[j - 1];
}
}
/* Scale Nordsieck matrix */
for (i = 2; i < ord + 1; i++)
for (j = 0; j < dim; j++)
{
z[i * dim + j] += -l[i] * z[(ord + 1) * dim + j];
}
#ifdef DEBUG
printf ("-- order decrease detected, Nordsieck modified\n");
#endif
}
/* Scale Nordsieck vectors if step size has been changed */
if (state->ni > 0 && h != hprev[0])
{
size_t i, j;
const double hrel = h / hprev[0];
double coeff = hrel;
for (i = 1; i < ord + 1; i++)
{
for (j = 0; j < dim; j++)
{
z[i * dim + j] *= coeff;
}
coeff *= hrel;
}
#ifdef DEBUG
printf ("-- h != hprev, Nordsieck modified\n");
#endif
}
/* Calculate polynomial coefficients (l), error coefficient and
auxiliary coefficients
*/
msbdf_calccoeffs (ord, state->ordwait, h, hprev, l, &errcoeff,
º1coeff, &ordp1coeff, &ordp2coeff, &gamma);
/* Carry out the prediction step */
{
size_t i, j, k;
for (i = 1; i < ord + 1; i++)
for (j = ord; j > i - 1; j--)
for (k = 0; k < dim; k++)
{
z[(j - 1) * dim + k] += z[j * dim + k];
}
#ifdef DEBUG
{
size_t di;
printf ("-- predicted y: ");
for (di = 0; di < dim; di++)
{
printf ("%.5e ", z[di]);
}
printf ("\n");
}
#endif
}
/* Calculate correction step to abscor */
{
int s;
s = msbdf_corrector (vstate, sys, t, h, dim, z, errlev, l, errcoeff,
abscor, relcor, ytmp, ytmp2,
state->dfdy, state->dfdt, state->M,
state->p, state->rhs,
&(state->nJ), &(state->nM),
state->tprev, state->failt, gamma,
state->gammaprev, hprev[0]);
if (s != GSL_SUCCESS)
{
return s;
}
}
{
/* Add accepted final correction step to Nordsieck matrix */
size_t i, j;
for (i = 0; i < ord + 1; i++)
for (j = 0; j < dim; j++)
{
z[i * dim + j] += l[i] * gsl_vector_get (abscor, j);
}
#ifdef DEBUG
{
size_t di;
printf ("---- l: ");
for (di = 0; di < ord + 1; di++)
{
printf ("%.5e ", l[di]);
}
printf ("\n");
printf ("-- corrected y: ");
for (di = 0; di < dim; di++)
{
printf ("%.5e ", z[di]);
}
printf ("\n");
}
#endif
/* Derivatives at output */
if (dydt_out != NULL)
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, z, dydt_out);
if (s == GSL_EBADFUNC)
{
return s;
}
if (s != GSL_SUCCESS)
{
msbdf_failurehandler (vstate, dim, t);
#ifdef DEBUG
printf ("-- FAIL at user function evaluation\n");
#endif
return s;
}
}
/* Calculate error estimate */
for (i = 0; i < dim; i++)
{
yerr[i] = fabs (gsl_vector_get (abscor, i)) * errcoeff;
}
#ifdef DEBUG
{
size_t di;
printf ("-- yerr: ");
for (di = 0; di < dim; di++)
{
printf ("%.5e ", yerr[di]);
}
printf ("\n");
}
#endif
/* Save y values */
for (i = 0; i < dim; i++)
{
y[i] = z[0 * dim + i];
}
}
/* Scale abscor with errlev for later use in norm calculations */
{
size_t i;
for (i = 0; i < dim; i++)
{
gsl_vector_set (abscor, i, gsl_vector_get (abscor, i) / errlev[i]);
}
}
/* Save items needed for evaluation of order increase on next
call, if needed
*/
if (state->ordwait == 1 && ord < MSBDF_MAX_ORD)
{
size_t i;
state->ordp1coeffprev = ordp1coeff;
for (i = 0; i < dim; i++)
{
gsl_vector_set (svec, i, gsl_vector_get (abscor, i));
}
}
/* Consider and execute order change for next step */
if (state->ordwait == 0)
{
msbdf_eval_order (abscor, tempvec, svec, errcoeff, dim, errlev,
ordm1coeff, ordp1coeff,
state->ordp1coeffprev, ordp2coeff,
hprev, h, z, &(state->ord), &(state->ordwait));
}
/* Undo scaling of abscor for possible order increase on next step */
{
size_t i;
for (i = 0; i < dim; i++)
{
gsl_vector_set (abscor, i, gsl_vector_get (abscor, i) * errlev[i]);
}
}
/* Save information about current step in state and update counters */
{
size_t i;
for (i = MSBDF_MAX_ORD - 1; i > 0; i--)
{
hprev[i] = hprev[i - 1];
ordprev[i] = ordprev[i - 1];
}
}
hprev[0] = h;
ordprev[0] = ord;
#ifdef DEBUG
{
size_t di;
printf ("-- hprev: ");
for (di = 0; di < MSBDF_MAX_ORD; di++)
{
printf ("%.5e ", hprev[di]);
}
printf ("\n");
}
#endif
state->tprev = t;
state->ordwait--;
state->ni++;
state->gammaprev = gamma;
state->nJ++;
state->nM++;
#ifdef DEBUG
printf ("-- nJ=%d, nM=%d\n", (int) state->nJ, (int) state->nM);
#endif
}
return GSL_SUCCESS;
}
static int
msbdf_set_driver (void *vstate, const gsl_odeiv2_driver * d)
{
msbdf_state_t *state = (msbdf_state_t *) vstate;
state->driver = d;
return GSL_SUCCESS;
}
static int
msbdf_reset (void *vstate, size_t dim)
{
msbdf_state_t *state = (msbdf_state_t *) vstate;
size_t i;
state->ni = 0;
state->ord = 1;
state->ordwait = 2;
state->ordwaitbackup = 2;
state->failord = 0;
state->failt = GSL_NAN;
state->gammaprev = 1.0;
state->nJ = 0;
state->nM = 0;
state->failcount = 0;
DBL_ZERO_MEMSET (state->hprev, MSBDF_MAX_ORD);
DBL_ZERO_MEMSET (state->hprevbackup, MSBDF_MAX_ORD);
DBL_ZERO_MEMSET (state->z, (MSBDF_MAX_ORD + 1) * dim);
DBL_ZERO_MEMSET (state->zbackup, (MSBDF_MAX_ORD + 1) * dim);
for (i = 0; i < MSBDF_MAX_ORD; i++)
{
state->ordprev[i] = 1;
state->ordprevbackup[i] = 1;
}
#ifdef DEBUG
printf ("-- msbdf_reset called\n");
#endif
return GSL_SUCCESS;
}
static unsigned int
msbdf_order (void *vstate)
{
msbdf_state_t *state = (msbdf_state_t *) vstate;
return state->ord;
}
static void
msbdf_free (void *vstate)
{
msbdf_state_t *state = (msbdf_state_t *) vstate;
gsl_vector_free (state->rhs);
gsl_permutation_free (state->p);
gsl_matrix_free (state->M);
free (state->dfdt);
gsl_matrix_free (state->dfdy);
gsl_vector_free (state->tempvec);
gsl_vector_free (state->svec);
gsl_vector_free (state->relcor);
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->ordprevbackup);
free (state->ordprev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
}
static const gsl_odeiv2_step_type msbdf_type = {
"msbdf", /* name */
1, /* can use dydt_in? */
1, /* gives exact dydt_out? */
&msbdf_alloc,
&msbdf_apply,
&msbdf_set_driver,
&msbdf_reset,
&msbdf_order,
&msbdf_free
};
const gsl_odeiv2_step_type *gsl_odeiv2_step_msbdf = &msbdf_type;
| {
"alphanum_fraction": 0.5369183366,
"avg_line_length": 25.0495774648,
"ext": "c",
"hexsha": "d6f28737d5425cb725d95ccd8112884aabd33f57",
"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": "b723fcad149662a9af981c4e507678d9c7f106d2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "WikiGaze/Wikipedia-readers-gaze",
"max_forks_repo_path": "Integration/gsl-1.15/ode-initval2/msbdf.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b723fcad149662a9af981c4e507678d9c7f106d2",
"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": "WikiGaze/Wikipedia-readers-gaze",
"max_issues_repo_path": "Integration/gsl-1.15/ode-initval2/msbdf.c",
"max_line_length": 101,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b723fcad149662a9af981c4e507678d9c7f106d2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "WikiGaze/Wikipedia-readers-gaze",
"max_stars_repo_path": "Integration/gsl-1.15/ode-initval2/msbdf.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 12851,
"size": 44463
} |
/* stable/stable_dist.c
*
* Main Libstable source file. Definition of the StableDist structures
* and auxiliary functions to manage alpha-stable distributions.
*
* Copyright (C) 2013. Javier Royuela del Val
* Federico Simmross Wattenberg
*
* 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; version 3 of the License.
*
* 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/>.
*
*
* Javier Royuela del Val.
* E.T.S.I. Telecomunicación
* Universidad de Valladolid
* Paseo de Belén 15, 47002 Valladolid, Spain.
* jroyval@lpi.tel.uva.es
*/
#include <gsl/gsl_errno.h>
#include "stable.h"
#include <pthread.h>
#include <math.h>
#include <unistd.h>
/*----------------------------------------------------------------------------*/
/* Public part */
/*----------------------------------------------------------------------------*/
unsigned int stable_get_THREADS() { return THREADS; }
void stable_set_THREADS(unsigned int value)
{
if (value == 0) THREADS = sysconf(_SC_NPROCESSORS_ONLN);
else THREADS = value;
//printf("\nCPUs = %u\n",THREADS);
}
int stable_get_METHOD1() { return METHOD1; }
void stable_set_METHOD1(int value) { METHOD1 = value; }
int stable_get_METHOD2() { return METHOD2; }
void stable_set_METHOD2(int value) { METHOD2 = value; }
int stable_get_METHOD3() { return METHOD3; }
void stable_set_METHOD3(int value) { METHOD3 = value; }
unsigned int stable_get_IT_MAX() { return IT_MAX; }
void stable_set_IT_MAX(unsigned int value) { IT_MAX = value;}
unsigned int stable_get_INV_MAXITER() { return INV_MAXITER; }
void stable_set_INV_MAXITER(unsigned int value) { INV_MAXITER = value;}
double stable_get_relTOL() { return relTOL; }
void stable_set_relTOL(double value) {
/* Switch between integration methods according to relTOL */
relTOL = value;
if (value < 1e-12) {
stable_set_METHOD1(STABLE_QNG);
stable_set_METHOD2(STABLE_QAG2);
stable_set_METHOD3(STABLE_QAG1);
}
else if (value < 1e-8) {
stable_set_METHOD1(STABLE_QNG);
stable_set_METHOD2(STABLE_QAG2);
stable_set_METHOD3(STABLE_QAG1);
}
else {
stable_set_METHOD1(STABLE_QNG);
stable_set_METHOD2(STABLE_QAG1);
stable_set_METHOD3(STABLE_QAG1);
}
}
double stable_get_absTOL() { return absTOL; }
void stable_set_absTOL(double value)
{
absTOL = value;
//FACTOR = 1e-16;
}
/* Parameter thresholds */
/* When abs(alpha - 1)<ALPHA_TH alpha is set to 1 */
double stable_get_ALPHA_TH() { return ALPHA_TH; }
void stable_set_ALPHA_TH(double value) { ALPHA_TH = value; }
/* When 1-abs(beta)<BETA_TH beta is set to sign(beta)*1.0 */
/* When alpha = 1 and abs(beta)<BETA_TH beta is set to 0.0*/
double stable_get_BETA_TH() { return BETA_TH; }
void stable_set_BETA_TH(double value) { BETA_TH = value; }
/* When abs(x-xxi)<XXI_TH x is set to XXI */
double stable_get_XXI_TH() { return XXI_TH; }
void stable_set_XXI_TH(double value) { XXI_TH = value; }
/* When theta get closer than THETA_TH to integration interval limits theta is set to the limit value */
double stable_get_THETA_TH() { return THETA_TH; }
void stable_set_THETA_TH(double value) { THETA_TH = value; }
/* Debug purposes*/
FILE * stable_get_FINTEG() { return FINTEG; }
FILE * stable_set_FINTEG(char *name)
{
FINTEG = fopen(name,"wt");
return FINTEG;
}
/* Log-file configuration */
FILE * stable_get_FLOG() { return FLOG; }
FILE * stable_set_FLOG(char * name)
{
FLOG = fopen(name,"wt");
return FLOG;
}
int stable_setparams(StableDist *dist,
double alpha, double beta, double sigma, double mu,
int parametrization)
{
int zona;
if(dist==NULL)
{
printf("ERROR");
return(-1);
}
if((zona = stable_checkparams(alpha,beta,sigma,mu,parametrization)) == NOVALID)
{
// printf ("No valid parameters: %lf %lf %lf %lf %d\n",
// alpha, beta, sigma, mu, parametrization);
return zona;
}
dist->alpha = alpha;
dist->beta = beta;
dist->sigma = sigma;
switch (zona)
{
case STABLE_B1:
dist->beta = (dist->beta > 0) ? 1.0 : -1.0;
case STABLE:
dist->alphainvalpha1 = alpha/(alpha-1.0);
dist->xi = -beta*tan(0.5*alpha*M_PI);
dist->theta0 = atan(-dist->xi)/alpha;
//dist->k1 = pow(1.0+dist->xi*dist->xi,-0.5/(alpha-1.0));
dist->k1 = -0.5/(alpha-1.0)*log(1.0+dist->xi*dist->xi);
dist->S = pow(1.0+dist->xi*dist->xi,0.5/alpha);
dist->Vbeta1 = dist->k1 - dist->alphainvalpha1 * log(dist->alpha)
+ log(fabs(dist->alpha-1.0));
dist->stable_pdf_point = &stable_pdf_point_STABLE;
dist->stable_cdf_point = &stable_cdf_point_STABLE;
if (alpha < 1.0)
{
dist->c1 = 0.5-dist->theta0*M_1_PI;
dist->c2_part = alpha/((1.0-alpha)*M_PI);
dist->c3 = M_1_PI;
}
else
{
dist->c1 = 1.0;
dist->c2_part = alpha/((alpha-1.0)*M_PI);
dist->c3 = -M_1_PI;
}
if (alpha>1)
{
AUX1=log(log(8.5358/(relTOL))/0.9599);/*3.76;*/
AUX2=log(relTOL);/*-40;*/
}
else
{
AUX1=log(relTOL);/*-40;*/
AUX2=log(log(8.5358/(relTOL))/0.9599);/*3.76;*/
}
break;
case ALPHA_1_B1:
dist->beta = (dist->beta > 0) ? 1.0 : -1.0;
case ALPHA_1:
dist->alpha=1;
dist->c2_part = 0.5/fabs(beta);
dist->alphainvalpha1 = 0.0;
dist->xi = 0.0;
dist->theta0 = M_PI_2;
dist->k1 = log(2.0*M_1_PI);
//dist->k1 = 2.0*M_1_PI;
dist->S = 2.0*M_1_PI;
dist->c1 = 0.0;
dist->c3 = M_1_PI;
dist->Vbeta1=2.0*M_1_PI/M_E;
dist->stable_pdf_point = &stable_pdf_point_ALPHA_1;
dist->stable_cdf_point = &stable_cdf_point_ALPHA_1;
//XXI_TH = 10*EPS;
if (beta<0)
{
AUX1=log(log(8.5358/(relTOL))/0.9599);/*4;*/
AUX2=log(relTOL);/*-25;*/
}
else
{
AUX1=log(relTOL);/*-25;*/
AUX2=log(log(8.5358/(relTOL))/0.9599);/*4;*/
}
break;
case CAUCHY:
dist->beta=0;
dist->alpha=1;
dist->c2_part = 0.0;
dist->alphainvalpha1 = 0.0;
dist->xi = 0.0;
dist->theta0 = M_PI_2;
dist->k1 = log(2.0*M_1_PI);
//dist->k1 = 2.0*M_1_PI;
dist->S = 2.0*M_1_PI;
dist->c1 = 0.0;
dist->c3 = M_1_PI;
dist->Vbeta1=2.0*M_1_PI/M_E;
dist->stable_pdf_point = &stable_pdf_point_CAUCHY;
dist->stable_cdf_point = &stable_cdf_point_CAUCHY;
break;
case GAUSS:
dist->alpha=2;
dist->beta=0.0;
dist->alphainvalpha1 = 2.0;
dist->xi = 0.0;
dist->theta0 = 0.0;
dist->k1 = log(2.0);
//dist->k1 = 2.0;
dist->S = 2.0;
dist->c1 = 1.0;
dist->c2_part = 2.0*M_1_PI;
dist->c3 = -M_1_PI;
dist->Vbeta1=0.25;
dist->stable_pdf_point = &stable_pdf_point_GAUSS;
dist->stable_cdf_point = &stable_cdf_point_GAUSS;
break;
case LEVY:
dist->alpha = 0.5;
dist->beta = (2.0*(beta>0)-1.0);// 1 ó -1
dist->alphainvalpha1 = -1.0;
dist->xi = -dist->beta;
dist->theta0 = 0.5*M_PI;
dist->k1 = 0.0;
dist->S = 1.0;
dist->c1 = 0.0;
dist->c2_part = 0.5*M_1_PI;
dist->c3 = M_1_PI;
dist->Vbeta1 = dist->k1 - dist->alphainvalpha1 * log(dist->alpha)
+ log(fabs(dist->alpha-1.0));
dist->stable_pdf_point = &stable_pdf_point_LEVY;
dist->stable_cdf_point = &stable_cdf_point_LEVY;
break;
}
if (parametrization == 0)
{
dist->mu_0 = mu;
if (dist->alpha==1)
dist->mu_1 = mu-dist->beta*2*M_1_PI*dist->sigma*log(dist->sigma);
else dist->mu_1 = mu+dist->xi*dist->sigma;
}
else if (parametrization == 1)
{
dist->mu_1 = mu;
if (dist->alpha==1)
dist->mu_0 = mu+dist->beta*2*M_1_PI*dist->sigma*log(dist->sigma);
else dist->mu_0 = mu-dist->xi*dist->sigma;
}
dist->theta0_ = dist->theta0;
dist->beta_ = dist->beta;
dist->xxipow = 0.0;
dist->ZONE = zona;
return zona;
}
int stable_checkparams(double alpha, double beta, double sigma, double mu,
int parametrization)
{
/*Check parameters*/
if (0.0 >= alpha || alpha > 2.0)
{
//printf("Alpha must lie between 0.0 and 2.0.");
return NOVALID;
}
else if (beta < -1.0 || beta > 1.0)
{
//printf("Beta must lie between -1.0 and 1.0.");
return NOVALID;
}
else if (sigma <= 0.0)
{
//printf("Sigma must be positive.");
return NOVALID;
}
else if (isnan(mu) || isinf(mu))
{
//printf("Mu must be real.");
return NOVALID;
}
else if (parametrization != 0 && parametrization != 1)
{
//printf("Only parametrizations 0 and 1 are accepted.");
return NOVALID;
}
/*ZONE determination*/
if ((2.0 - alpha) <= ALPHA_TH)
return GAUSS; //GAUSS
else if (fabs(alpha-0.5) <= ALPHA_TH && fabs((fabs(beta)-1.0)) <= BETA_TH)
return LEVY; //LEVY
else if (fabs(alpha-1.0) <= ALPHA_TH && fabs(beta) <= BETA_TH)
return CAUCHY;
else if (fabs(alpha-1.0) <= ALPHA_TH) {
// if (fabs(fabs(beta)-1) <= BETA_TH) return ALPHA_1_B1;
return ALPHA_1;
}
else {
// if (fabs(fabs(beta)-1) <= BETA_TH) return STABLE_B1;
return STABLE;
}
/*When alpha=1,beta=1 Landau distribution is obtained,
but it is calculated as in the general case*/
}
StableDist * stable_create(double alpha, double beta, double sigma, double mu,
int parametrization)
{
/*gsl_error_handler_t * old_handler;
old_handler = */gsl_set_error_handler (&error_handler);
StableDist * dist = (StableDist *) malloc(sizeof (StableDist));
if (dist == NULL)
{
perror("Error during distribution creation.");
return NULL;
}
if((stable_setparams(dist,alpha,beta,sigma,mu,parametrization)) == NOVALID)
{
perror ("Error during distribution creation.");
return NULL;
}
gsl_rng_env_setup(); //leemos las variables de entorno
dist->gslworkspace = gsl_integration_workspace_alloc(IT_MAX);
dist->gslrand = gsl_rng_alloc (gsl_rng_default);
//Allow the distribution to use THREADS threads.
stable_set_THREADS(THREADS);
return dist;
}
StableDist * stable_copy(StableDist *src_dist)
{
StableDist *dist;
dist = stable_create(src_dist->alpha, src_dist->beta,
src_dist->sigma, src_dist->mu_0, 0);
return dist;
}
void stable_free(StableDist *dist)
{
if (dist == NULL)
return;
gsl_integration_workspace_free(dist->gslworkspace);
gsl_rng_free(dist->gslrand);
free(dist);
}
| {
"alphanum_fraction": 0.5906134646,
"avg_line_length": 29.4766839378,
"ext": "c",
"hexsha": "730aaf6848cf4c8cba7e6779c9fa62f7d8478e94",
"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": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "TantraLabs/gonum",
"max_forks_repo_path": "stat/distuv/libs/libstable/stable/src/stable_dist.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50",
"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": "TantraLabs/gonum",
"max_issues_repo_path": "stat/distuv/libs/libstable/stable/src/stable_dist.c",
"max_line_length": 104,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "TantraLabs/gonum",
"max_stars_repo_path": "stat/distuv/libs/libstable/stable/src/stable_dist.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3441,
"size": 11378
} |
#pragma once
#include "Rendering/Utility/peBxDF.h"
#include "Type/peColor.h"
#include <gsl.h>
namespace pe {
enum class ToneMapping { Saturate, Linear, Log };
//! \brief Performs tone mapping from the given input image to a displayable
//! 8-bit RGBA output image \param result Result image \param input Input image
//! \param imageWidth Width of the image
//! \param imageHeight Height of the image
//! \param strategy The tone-mapping strategy to use
void ToneMap(gsl::span<RGBA_8Bit> result, const gsl::span<Spectrum_t> input,
const uint32_t imageWidth, const uint32_t imageHeight,
const ToneMapping strategy);
} // namespace pe
| {
"alphanum_fraction": 0.7285067873,
"avg_line_length": 31.5714285714,
"ext": "h",
"hexsha": "4e9a0ccfa290ceac83622d5da25d6a6b74efa9a7",
"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": "e2e931e1ee8bfd3899b26f8c91e593f0d7213d64",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Mortano/Prismatic",
"max_forks_repo_path": "PrismaticPathTracer/Headers/Util/ToneMapping.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e2e931e1ee8bfd3899b26f8c91e593f0d7213d64",
"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": "Mortano/Prismatic",
"max_issues_repo_path": "PrismaticPathTracer/Headers/Util/ToneMapping.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e2e931e1ee8bfd3899b26f8c91e593f0d7213d64",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Mortano/Prismatic",
"max_stars_repo_path": "PrismaticPathTracer/Headers/Util/ToneMapping.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 161,
"size": 663
} |
/* integration/qng.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 <math.h>
#include <float.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
#include "err.c"
#include "qng.h"
int
gsl_integration_qng (const gsl_function *f,
double a, double b,
double epsabs, double epsrel,
double * result, double * abserr, size_t * neval)
{
double fv1[5], fv2[5], fv3[5], fv4[5];
double savfun[21]; /* array of function values which have been computed */
double res10, res21, res43, res87; /* 10, 21, 43 and 87 point results */
double result_kronrod, err ;
double resabs; /* approximation to the integral of abs(f) */
double resasc; /* approximation to the integral of abs(f-i/(b-a)) */
const double half_length = 0.5 * (b - a);
const double abs_half_length = fabs (half_length);
const double center = 0.5 * (b + a);
const double f_center = GSL_FN_EVAL(f, center);
int k ;
if (epsabs <= 0 && (epsrel < 50 * GSL_DBL_EPSILON || epsrel < 0.5e-28))
{
* result = 0;
* abserr = 0;
* neval = 0;
GSL_ERROR ("tolerance cannot be acheived with given epsabs and epsrel",
GSL_EBADTOL);
};
/* Compute the integral using the 10- and 21-point formula. */
res10 = 0;
res21 = w21b[5] * f_center;
resabs = w21b[5] * fabs (f_center);
for (k = 0; k < 5; k++)
{
const double abscissa = half_length * x1[k];
const double fval1 = GSL_FN_EVAL(f, center + abscissa);
const double fval2 = GSL_FN_EVAL(f, center - abscissa);
const double fval = fval1 + fval2;
res10 += w10[k] * fval;
res21 += w21a[k] * fval;
resabs += w21a[k] * (fabs (fval1) + fabs (fval2));
savfun[k] = fval;
fv1[k] = fval1;
fv2[k] = fval2;
}
for (k = 0; k < 5; k++)
{
const double abscissa = half_length * x2[k];
const double fval1 = GSL_FN_EVAL(f, center + abscissa);
const double fval2 = GSL_FN_EVAL(f, center - abscissa);
const double fval = fval1 + fval2;
res21 += w21b[k] * fval;
resabs += w21b[k] * (fabs (fval1) + fabs (fval2));
savfun[k + 5] = fval;
fv3[k] = fval1;
fv4[k] = fval2;
}
resabs *= abs_half_length ;
{
const double mean = 0.5 * res21;
resasc = w21b[5] * fabs (f_center - mean);
for (k = 0; k < 5; k++)
{
resasc +=
(w21a[k] * (fabs (fv1[k] - mean) + fabs (fv2[k] - mean))
+ w21b[k] * (fabs (fv3[k] - mean) + fabs (fv4[k] - mean)));
}
resasc *= abs_half_length ;
}
result_kronrod = res21 * half_length;
err = rescale_error ((res21 - res10) * half_length, resabs, resasc) ;
/* test for convergence. */
if (err < epsabs || err < epsrel * fabs (result_kronrod))
{
* result = result_kronrod ;
* abserr = err ;
* neval = 21;
return GSL_SUCCESS;
}
/* compute the integral using the 43-point formula. */
res43 = w43b[11] * f_center;
for (k = 0; k < 10; k++)
{
res43 += savfun[k] * w43a[k];
}
for (k = 0; k < 11; k++)
{
const double abscissa = half_length * x3[k];
const double fval = (GSL_FN_EVAL(f, center + abscissa)
+ GSL_FN_EVAL(f, center - abscissa));
res43 += fval * w43b[k];
savfun[k + 10] = fval;
}
/* test for convergence */
result_kronrod = res43 * half_length;
err = rescale_error ((res43 - res21) * half_length, resabs, resasc);
if (err < epsabs || err < epsrel * fabs (result_kronrod))
{
* result = result_kronrod ;
* abserr = err ;
* neval = 43;
return GSL_SUCCESS;
}
/* compute the integral using the 87-point formula. */
res87 = w87b[22] * f_center;
for (k = 0; k < 21; k++)
{
res87 += savfun[k] * w87a[k];
}
for (k = 0; k < 22; k++)
{
const double abscissa = half_length * x4[k];
res87 += w87b[k] * (GSL_FN_EVAL(f, center + abscissa)
+ GSL_FN_EVAL(f, center - abscissa));
}
/* test for convergence */
result_kronrod = res87 * half_length ;
err = rescale_error ((res87 - res43) * half_length, resabs, resasc);
if (err < epsabs || err < epsrel * fabs (result_kronrod))
{
* result = result_kronrod ;
* abserr = err ;
* neval = 87;
return GSL_SUCCESS;
}
/* failed to converge */
* result = result_kronrod ;
* abserr = err ;
* neval = 87;
GSL_ERROR("failed to reach tolerance with highest-order rule", GSL_ETOL) ;
}
| {
"alphanum_fraction": 0.5853704049,
"avg_line_length": 28.057591623,
"ext": "c",
"hexsha": "ecf8e624b6aa8d38538a9c89fafb3e0950af8d67",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/integration/qng.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/integration/qng.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/integration/qng.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": 1683,
"size": 5359
} |
// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
// reserved. See files LICENSE and NOTICE for details.
//
// This file is part of CEED, a collection of benchmarks, miniapps, software
// libraries and APIs for efficient high-order finite element and spectral
// element discretizations for exascale applications. For more information and
// source code availability see http://github.com/ceed.
//
// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,
// a collaborative effort of two U.S. Department of Energy organizations (Office
// of Science and the National Nuclear Security Administration) responsible for
// the planning and preparation of a capable exascale ecosystem, including
// software, applications, hardware, advanced system engineering and early
// testbed platforms, in support of the nation's exascale computing imperative.
// libCEED + PETSc Example: CEED BPs
//
// This example demonstrates a simple usage of libCEED with PETSc to solve the
// CEED BP benchmark problems, see http://ceed.exascaleproject.org/bps,
// on a closed surface, such as the one of a discrete sphere.
//
// The code uses higher level communication protocols in DMPlex.
//
// Build with:
//
// make bpssphere [PETSC_DIR=</path/to/petsc>] [CEED_DIR=</path/to/libceed>]
//
// Sample runs:
//
// bpssphere -problem bp1 -degree 3
// bpssphere -problem bp2 -degree 3
// bpssphere -problem bp3 -degree 3
// bpssphere -problem bp4 -degree 3
// bpssphere -problem bp5 -degree 3 -ceed /cpu/self
// bpssphere -problem bp6 -degree 3 -ceed /gpu/cuda
//
//TESTARGS -ceed {ceed_resource} -test -problem bp3 -degree 3 -dm_refine 2
/// @file
/// CEED BPs example using PETSc with DMPlex
/// See bps.c for a "raw" implementation using a structured grid.
/// and bpsdmplex.c for an implementation using an unstructured grid.
static const char help[] = "Solve CEED BPs on a sphere using DMPlex in PETSc\n";
#include <stdbool.h>
#include <string.h>
#include <ceed.h>
#include <petsc.h>
#include <petscdmplex.h>
#include <petscksp.h>
#include "bpssphere.h"
#include "include/sphereproblemdata.h"
#include "include/petscutils.h"
#include "include/petscversion.h"
#include "include/matops.h"
#include "include/libceedsetup.h"
#if PETSC_VERSION_LT(3,12,0)
#ifdef PETSC_HAVE_CUDA
#include <petsccuda.h>
// Note: With PETSc prior to version 3.12.0, providing the source path to
// include 'cublas_v2.h' will be needed to use 'petsccuda.h'.
#endif
#endif
int main(int argc, char **argv) {
PetscInt ierr;
MPI_Comm comm;
char ceed_resource[PETSC_MAX_PATH_LEN] = "/cpu/self",
filename[PETSC_MAX_PATH_LEN];
double my_rt_start, my_rt, rt_min, rt_max;
PetscInt degree = 3, q_extra, l_size, g_size, topo_dim = 2, num_comp_x = 3,
num_comp_u = 1, xl_size;
PetscScalar *r;
PetscBool test_mode, benchmark_mode, read_mesh, write_solution, simplex;
PetscLogStage solve_stage;
Vec X, X_loc, rhs, rhs_loc;
Mat mat_O;
KSP ksp;
DM dm;
UserO user_O;
Ceed ceed;
CeedData ceed_data;
CeedQFunction qf_error;
CeedOperator op_error;
CeedVector rhs_ceed, target;
BPType bp_choice;
VecType vec_type;
PetscMemType mem_type;
ierr = PetscInitialize(&argc, &argv, NULL, help);
if (ierr) return ierr;
comm = PETSC_COMM_WORLD;
// Read command line options
ierr = PetscOptionsBegin(comm, NULL, "CEED BPs in PETSc", NULL); CHKERRQ(ierr);
bp_choice = CEED_BP1;
ierr = PetscOptionsEnum("-problem",
"CEED benchmark problem to solve", NULL,
bp_types, (PetscEnum)bp_choice, (PetscEnum *)&bp_choice,
NULL); CHKERRQ(ierr);
num_comp_u = bp_options[bp_choice].num_comp_u;
test_mode = PETSC_FALSE;
ierr = PetscOptionsBool("-test",
"Testing mode (do not print unless error is large)",
NULL, test_mode, &test_mode, NULL); CHKERRQ(ierr);
benchmark_mode = PETSC_FALSE;
ierr = PetscOptionsBool("-benchmark",
"Benchmarking mode (prints benchmark statistics)",
NULL, benchmark_mode, &benchmark_mode, NULL);
CHKERRQ(ierr);
write_solution = PETSC_FALSE;
ierr = PetscOptionsBool("-write_solution",
"Write solution for visualization",
NULL, write_solution, &write_solution, NULL);
CHKERRQ(ierr);
degree = test_mode ? 3 : 2;
ierr = PetscOptionsInt("-degree", "Polynomial degree of tensor product basis",
NULL, degree, °ree, NULL); CHKERRQ(ierr);
q_extra = bp_options[bp_choice].q_extra;
ierr = PetscOptionsInt("-q_extra", "Number of extra quadrature points",
NULL, q_extra, &q_extra, NULL); CHKERRQ(ierr);
ierr = PetscOptionsString("-ceed", "CEED resource specifier",
NULL, ceed_resource, ceed_resource,
sizeof(ceed_resource), NULL); CHKERRQ(ierr);
read_mesh = PETSC_FALSE;
ierr = PetscOptionsString("-mesh", "Read mesh from file", NULL,
filename, filename, sizeof(filename), &read_mesh);
CHKERRQ(ierr);
simplex = PETSC_FALSE;
ierr = PetscOptionsBool("-simplex", "Use simplices, or tensor product cells",
NULL, simplex, &simplex, NULL); CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
// Setup DM
if (read_mesh) {
ierr = DMPlexCreateFromFile(PETSC_COMM_WORLD, filename, NULL, PETSC_TRUE,
&dm);
CHKERRQ(ierr);
} else {
// Create the mesh as a 0-refined sphere. This will create a cubic surface, not a box
ierr = DMPlexCreateSphereMesh(PETSC_COMM_WORLD, topo_dim, simplex, 1., &dm);
CHKERRQ(ierr);
// Set the object name
ierr = PetscObjectSetName((PetscObject)dm, "Sphere"); CHKERRQ(ierr);
// Distribute mesh over processes
{
DM dm_dist = NULL;
PetscPartitioner part;
ierr = DMPlexGetPartitioner(dm, &part); CHKERRQ(ierr);
ierr = PetscPartitionerSetFromOptions(part); CHKERRQ(ierr);
ierr = DMPlexDistribute(dm, 0, NULL, &dm_dist); CHKERRQ(ierr);
if (dm_dist) {
ierr = DMDestroy(&dm); CHKERRQ(ierr);
dm = dm_dist;
}
}
// Refine DMPlex with uniform refinement using runtime option -dm_refine
ierr = DMPlexSetRefinementUniform(dm, PETSC_TRUE); CHKERRQ(ierr);
ierr = DMSetFromOptions(dm); CHKERRQ(ierr);
ierr = ProjectToUnitSphere(dm); CHKERRQ(ierr);
// View DMPlex via runtime option
ierr = DMViewFromOptions(dm, NULL, "-dm_view"); CHKERRQ(ierr);
}
// Create DM
ierr = SetupDMByDegree(dm, degree, num_comp_u, topo_dim, false,
(BCFunction)NULL);
CHKERRQ(ierr);
// Create vectors
ierr = DMCreateGlobalVector(dm, &X); CHKERRQ(ierr);
ierr = VecGetLocalSize(X, &l_size); CHKERRQ(ierr);
ierr = VecGetSize(X, &g_size); CHKERRQ(ierr);
ierr = DMCreateLocalVector(dm, &X_loc); CHKERRQ(ierr);
ierr = VecGetSize(X_loc, &xl_size); CHKERRQ(ierr);
ierr = VecDuplicate(X, &rhs); CHKERRQ(ierr);
// Operator
ierr = PetscMalloc1(1, &user_O); CHKERRQ(ierr);
ierr = MatCreateShell(comm, l_size, l_size, g_size, g_size,
user_O, &mat_O); CHKERRQ(ierr);
ierr = MatShellSetOperation(mat_O, MATOP_MULT,
(void(*)(void))MatMult_Ceed); CHKERRQ(ierr);
// Set up libCEED
CeedInit(ceed_resource, &ceed);
CeedMemType mem_type_backend;
CeedGetPreferredMemType(ceed, &mem_type_backend);
ierr = DMGetVecType(dm, &vec_type); CHKERRQ(ierr);
if (!vec_type) { // Not yet set by user -dm_vec_type
switch (mem_type_backend) {
case CEED_MEM_HOST: vec_type = VECSTANDARD; break;
case CEED_MEM_DEVICE: {
const char *resolved;
CeedGetResource(ceed, &resolved);
if (strstr(resolved, "/gpu/cuda")) vec_type = VECCUDA;
else if (strstr(resolved, "/gpu/hip/occa"))
vec_type = VECSTANDARD; // https://github.com/CEED/libCEED/issues/678
else if (strstr(resolved, "/gpu/hip")) vec_type = VECHIP;
else vec_type = VECSTANDARD;
}
}
ierr = DMSetVecType(dm, vec_type); CHKERRQ(ierr);
}
// Print summary
if (!test_mode) {
PetscInt P = degree + 1, Q = P + q_extra;
const char *used_resource;
CeedGetResource(ceed, &used_resource);
ierr = PetscPrintf(comm,
"\n-- CEED Benchmark Problem %d on the Sphere -- libCEED + PETSc --\n"
" libCEED:\n"
" libCEED Backend : %s\n"
" libCEED Backend MemType : %s\n"
" Mesh:\n"
" Number of 1D Basis Nodes (p) : %d\n"
" Number of 1D Quadrature Points (q) : %d\n"
" Global nodes : %D\n",
bp_choice+1, ceed_resource, CeedMemTypes[mem_type_backend], P, Q,
g_size/num_comp_u); CHKERRQ(ierr);
}
// Create RHS vector
ierr = VecDuplicate(X_loc, &rhs_loc); CHKERRQ(ierr);
ierr = VecZeroEntries(rhs_loc); CHKERRQ(ierr);
ierr = VecGetArrayAndMemType(rhs_loc, &r, &mem_type); CHKERRQ(ierr);
CeedVectorCreate(ceed, xl_size, &rhs_ceed);
CeedVectorSetArray(rhs_ceed, MemTypeP2C(mem_type), CEED_USE_POINTER, r);
// Setup libCEED's objects
ierr = PetscMalloc1(1, &ceed_data); CHKERRQ(ierr);
ierr = SetupLibceedByDegree(dm, ceed, degree, topo_dim, q_extra, num_comp_x,
num_comp_u, g_size, xl_size, bp_options[bp_choice],
ceed_data, true, rhs_ceed, &target); CHKERRQ(ierr);
// Gather RHS
CeedVectorTakeArray(rhs_ceed, MemTypeP2C(mem_type), NULL);
ierr = VecRestoreArrayAndMemType(rhs_loc, &r); CHKERRQ(ierr);
ierr = VecZeroEntries(rhs); CHKERRQ(ierr);
ierr = DMLocalToGlobal(dm, rhs_loc, ADD_VALUES, rhs); CHKERRQ(ierr);
CeedVectorDestroy(&rhs_ceed);
// Create the error Q-function
CeedQFunctionCreateInterior(ceed, 1, bp_options[bp_choice].error,
bp_options[bp_choice].error_loc, &qf_error);
CeedQFunctionAddInput(qf_error, "u", num_comp_u, CEED_EVAL_INTERP);
CeedQFunctionAddInput(qf_error, "true_soln", num_comp_u, CEED_EVAL_NONE);
CeedQFunctionAddOutput(qf_error, "error", num_comp_u, CEED_EVAL_NONE);
// Create the error operator
CeedOperatorCreate(ceed, qf_error, NULL, NULL, &op_error);
CeedOperatorSetField(op_error, "u", ceed_data->elem_restr_u,
ceed_data->basis_u, CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_error, "true_soln", ceed_data->elem_restr_u_i,
CEED_BASIS_COLLOCATED, target);
CeedOperatorSetField(op_error, "error", ceed_data->elem_restr_u_i,
CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);
// Set up Mat
user_O->comm = comm;
user_O->dm = dm;
user_O->X_loc = X_loc;
ierr = VecDuplicate(X_loc, &user_O->Y_loc); CHKERRQ(ierr);
user_O->x_ceed = ceed_data->x_ceed;
user_O->y_ceed = ceed_data->y_ceed;
user_O->op = ceed_data->op_apply;
user_O->ceed = ceed;
// Setup solver
ierr = KSPCreate(comm, &ksp); CHKERRQ(ierr);
{
PC pc;
ierr = KSPGetPC(ksp, &pc); CHKERRQ(ierr);
if (bp_choice == CEED_BP1 || bp_choice == CEED_BP2) {
ierr = PCSetType(pc, PCJACOBI); CHKERRQ(ierr);
ierr = PCJacobiSetType(pc, PC_JACOBI_ROWSUM); CHKERRQ(ierr);
} else {
ierr = PCSetType(pc, PCNONE); CHKERRQ(ierr);
MatNullSpace nullspace;
ierr = MatNullSpaceCreate(PETSC_COMM_WORLD, PETSC_TRUE, 0, 0, &nullspace);
CHKERRQ(ierr);
ierr = MatSetNullSpace(mat_O, nullspace); CHKERRQ(ierr);
ierr = MatNullSpaceDestroy(&nullspace); CHKERRQ(ierr);
}
ierr = KSPSetType(ksp, KSPCG); CHKERRQ(ierr);
ierr = KSPSetNormType(ksp, KSP_NORM_NATURAL); CHKERRQ(ierr);
ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT,
PETSC_DEFAULT); CHKERRQ(ierr);
}
ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr);
ierr = KSPSetOperators(ksp, mat_O, mat_O); CHKERRQ(ierr);
// First run, if benchmarking
if (benchmark_mode) {
ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, 1);
CHKERRQ(ierr);
my_rt_start = MPI_Wtime();
ierr = KSPSolve(ksp, rhs, X); CHKERRQ(ierr);
my_rt = MPI_Wtime() - my_rt_start;
ierr = MPI_Allreduce(MPI_IN_PLACE, &my_rt, 1, MPI_DOUBLE, MPI_MIN, comm);
CHKERRQ(ierr);
// Set maxits based on first iteration timing
if (my_rt > 0.02) {
ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, 5);
CHKERRQ(ierr);
} else {
ierr = KSPSetTolerances(ksp, 1e-10, PETSC_DEFAULT, PETSC_DEFAULT, 20);
CHKERRQ(ierr);
}
}
// Timed solve
ierr = VecZeroEntries(X); CHKERRQ(ierr);
ierr = PetscBarrier((PetscObject)ksp); CHKERRQ(ierr);
// -- Performance logging
ierr = PetscLogStageRegister("Solve Stage", &solve_stage); CHKERRQ(ierr);
ierr = PetscLogStagePush(solve_stage); CHKERRQ(ierr);
// -- Solve
my_rt_start = MPI_Wtime();
ierr = KSPSolve(ksp, rhs, X); CHKERRQ(ierr);
my_rt = MPI_Wtime() - my_rt_start;
// -- Performance logging
ierr = PetscLogStagePop();
// Output results
{
KSPType ksp_type;
KSPConvergedReason reason;
PetscReal rnorm;
PetscInt its;
ierr = KSPGetType(ksp, &ksp_type); CHKERRQ(ierr);
ierr = KSPGetConvergedReason(ksp, &reason); CHKERRQ(ierr);
ierr = KSPGetIterationNumber(ksp, &its); CHKERRQ(ierr);
ierr = KSPGetResidualNorm(ksp, &rnorm); CHKERRQ(ierr);
if (!test_mode || reason < 0 || rnorm > 1e-8) {
ierr = PetscPrintf(comm,
" KSP:\n"
" KSP Type : %s\n"
" KSP Convergence : %s\n"
" Total KSP Iterations : %D\n"
" Final rnorm : %e\n",
ksp_type, KSPConvergedReasons[reason], its,
(double)rnorm); CHKERRQ(ierr);
}
if (!test_mode) {
ierr = PetscPrintf(comm," Performance:\n"); CHKERRQ(ierr);
}
{
PetscReal max_error;
ierr = ComputeErrorMax(user_O, op_error, X, target, &max_error);
CHKERRQ(ierr);
PetscReal tol = 5e-4;
if (!test_mode || max_error > tol) {
ierr = MPI_Allreduce(&my_rt, &rt_min, 1, MPI_DOUBLE, MPI_MIN, comm);
CHKERRQ(ierr);
ierr = MPI_Allreduce(&my_rt, &rt_max, 1, MPI_DOUBLE, MPI_MAX, comm);
CHKERRQ(ierr);
ierr = PetscPrintf(comm,
" Pointwise Error (max) : %e\n"
" CG Solve Time : %g (%g) sec\n",
(double)max_error, rt_max, rt_min); CHKERRQ(ierr);
}
}
if (benchmark_mode && (!test_mode)) {
ierr = PetscPrintf(comm,
" DoFs/Sec in CG : %g (%g) million\n",
1e-6*g_size*its/rt_max, 1e-6*g_size*its/rt_min); CHKERRQ(ierr);
}
}
// Output solution
if (write_solution) {
PetscViewer vtk_viewer_soln;
ierr = PetscViewerCreate(comm, &vtk_viewer_soln); CHKERRQ(ierr);
ierr = PetscViewerSetType(vtk_viewer_soln, PETSCVIEWERVTK); CHKERRQ(ierr);
ierr = PetscViewerFileSetName(vtk_viewer_soln, "solution.vtu"); CHKERRQ(ierr);
ierr = VecView(X, vtk_viewer_soln); CHKERRQ(ierr);
ierr = PetscViewerDestroy(&vtk_viewer_soln); CHKERRQ(ierr);
}
// Cleanup
ierr = VecDestroy(&X); CHKERRQ(ierr);
ierr = VecDestroy(&X_loc); CHKERRQ(ierr);
ierr = VecDestroy(&user_O->Y_loc); CHKERRQ(ierr);
ierr = MatDestroy(&mat_O); CHKERRQ(ierr);
ierr = PetscFree(user_O); CHKERRQ(ierr);
ierr = CeedDataDestroy(0, ceed_data); CHKERRQ(ierr);
ierr = DMDestroy(&dm); CHKERRQ(ierr);
ierr = VecDestroy(&rhs); CHKERRQ(ierr);
ierr = VecDestroy(&rhs_loc); CHKERRQ(ierr);
ierr = KSPDestroy(&ksp); CHKERRQ(ierr);
CeedVectorDestroy(&target);
CeedQFunctionDestroy(&qf_error);
CeedOperatorDestroy(&op_error);
CeedDestroy(&ceed);
return PetscFinalize();
}
| {
"alphanum_fraction": 0.6367249603,
"avg_line_length": 39.7907542579,
"ext": "c",
"hexsha": "60e49520c16ec51ed199fac99726c9b1256d76e1",
"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": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "wence-/libCEED",
"max_forks_repo_path": "examples/petsc/bpssphere.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"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": "wence-/libCEED",
"max_issues_repo_path": "examples/petsc/bpssphere.c",
"max_line_length": 93,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "wence-/libCEED",
"max_stars_repo_path": "examples/petsc/bpssphere.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4477,
"size": 16354
} |
/*
* -----------------------------------------------------------------
* bst_lib.h
* Binary Search Tree Library
* Version: 2.0
* Last Update: Oct 9, 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 header file for BST_LIB module, a computational
* library with routines to manipulate a binary search tree.
* -----------------------------------------------------------------
*/
#ifndef __BST_LIB_H__
#define __BST_LIB_H__
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#undef BST_RIGHT
#define BST_RIGHT 1
#undef BST_LEFT
#define BST_LEFT 0
/*
*------------------------------------------------------------
* structure of binary search tree leaf
*
* last update: Feb 2, 2009
*------------------------------------------------------------
*/
typedef struct leaf
{
gsl_vector *phi; /* composition */
gsl_vector *Rphi; /* reaction mapping */
gsl_matrix *A; /* mapping gradient matrix */
gsl_matrix *L; /* ellipsoid Cholesky matrix */
} bst_leaf;
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* structure of binary search tree node
*
* last update: Feb 2, 2009
*------------------------------------------------------------
*/
typedef struct node
{
gsl_vector *v; /* cutting plane normal vector */
double a; /* scalar a */
struct node *r_node; /* right node */
struct node *l_node; /* left node */
struct leaf *r_leaf; /* right leaf */
struct leaf *l_leaf; /* left leaf */
} bst_node;
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* function prototypes
*------------------------------------------------------------
*/
bst_leaf *bst_leaf_alloc();
bst_node* bst_node_alloc();
void bst_leaf_free(void **leaf_bl);
void bst_node_free(void **node_bl);
int bst_leaf_set(gsl_vector *phi,
gsl_vector *Rphi,
gsl_matrix *A,
gsl_matrix *L,
bst_leaf *leaf);
double bst_cutplane(gsl_vector *phi_l,
gsl_vector *phi_r,
gsl_vector *v);
int bst_node_set(bst_leaf *l_leaf,
bst_leaf *r_leaf,
bst_node *node);
int bst_node_add(unsigned int side,
bst_node *old_node,
bst_node *new_node);
int bst_search(bst_node *root,
gsl_vector *phi,
bst_node **end_node,
bst_leaf **end_leaf);
int bst_height(bst_node *root);
#endif /* __BST_LIB_H__ */
| {
"alphanum_fraction": 0.4475930352,
"avg_line_length": 23.6209677419,
"ext": "h",
"hexsha": "c63d46c2ce32fbfc62499a7387d61315ad2ba289",
"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/include/bst_lib.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "americocunhajr/CRFlowLib",
"max_issues_repo_path": "CRFlowLib-2.0/include/bst_lib.h",
"max_line_length": 68,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "americocunhajr/CRFlowLib",
"max_stars_repo_path": "CRFlowLib-2.0/include/bst_lib.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z",
"num_tokens": 591,
"size": 2929
} |
// xi2bandpow.c
// 31.08.2018
// converts xi_+/-, xi_g+/x, and xi_gg to bandpowers
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_sf_bessel.h>
#include "bjutils.h"
#define xi_pm_balance 0.5 // default weight for xi_+/- in P_E
void xi_to_derived2pt();
double K_bandpow_ee();
double K_bandpow_ne();
double K_bandpow_nn();
double apod_upper();
double apod_lower();
int main(int argc, char *argv[])
{
int i,j;
double dr,xip,xim,scale_terms,kernel;
FILE *dat;
char name[400],path[200],ident[200],outident[200];
if (argc!=14) {
printf("Syntax: %s\n1: <working directory>\n2: <input file identifier>\n3: <output file identifier>\n4: <number of input angular bins>\n5: <min input separation to use in conversion [arcmin] (xi_+ in case of ee)>\n6: <max input separation to use in conversion [arcmin] (xi_+ in case of ee)>\n7: <min input separation to use in conversion [arcmin] (xi_- in case of ee; otherwise unused)>\n8: <max input separation to use in conversion [arcmin] (xi_- in case of ee; otherwise unused)>\n9: <number of output angular bins>\n10: <min output angular frequency>\n11: <max output angular frequency>\n12: <correlation type (1: ee; 2: ne; 3: gg)>\n13: <log width of apodisation window [total width of apodised range is tmax/tmin=exp(width) in arcmin; <0 for no apodisation]>\n\n",argv[0]);
exit(-1);
}
sprintf(path,"%s",argv[1]);
sprintf(ident,"%s",argv[2]);
sprintf(outident,"%s",argv[3]);
const int NR=atoi(argv[4]);
const double angmin1=atof(argv[5]);
const double angmax1=atof(argv[6]);
const double angmin2=atof(argv[7]);
const double angmax2=atof(argv[8]);
const int NOUT=atoi(argv[9]);
const double ellmin=atof(argv[10]);
const double ellmax=atof(argv[11]);
const int corrtype=atoi(argv[12]);
const double logwidth=atof(argv[13]);
// allocations
if (corrtype>3) {
printf("Error: incorrect input for correlation type!\n");
exit(-1);
}
double *tin=bj_alloc(NR);
double *ell_centre=bj_alloc(NOUT);
double *ell_bound=bj_alloc(NOUT+1);
double *weight=bj_alloc(NR);
double *weight_xim=bj_alloc(NR);
double *pfrac=bj_alloc(NOUT);
gsl_vector *xi=gsl_vector_calloc(2*NR);
gsl_vector *derived2pt=gsl_vector_calloc(2*NOUT);
gsl_matrix *trans=gsl_matrix_calloc(2*NOUT,2*NR);
gsl_matrix *xierr=gsl_matrix_calloc(2*NR,2*NR);
gsl_matrix *derived2pterr=gsl_matrix_calloc(2*NOUT,2*NOUT);
double logbinwidth=log(ellmax/ellmin)/(1.*NOUT); // output binning
for (i=0;i<NOUT;i++) {
ell_centre[i]=ellmin*exp((i+0.5)*logbinwidth); // use log centre of bin
ell_bound[i]=ellmin*exp(i*logbinwidth);
}
ell_bound[NOUT]=ellmin*exp(NOUT*logbinwidth);
// read input data
sprintf(name,"%s/xi2bandpow_input_%s.dat",path,ident);
dat=bj_fileopen("r",name);
for (i=0;i<NR;i++) {
if (corrtype==3) {
fscanf(dat,"%lf %lf",&tin[i],&xip); //theta (bin centres; in arcmin), w_gg
xim=0.0; // use only first half of vector
}
else {
fscanf(dat,"%lf %lf %lf",&tin[i],&xip,&xim); //theta (bin centres), xi_+, xi_- for ee; theta (bin centres), xi_g+, xi_gx for ne
}
gsl_vector_set(xi,i,xip);
gsl_vector_set(xi,NR+i,xim);
gsl_matrix_set(xierr,i,i,xip*xip); // treat xi as noise, uncorrelated so diagonal
gsl_matrix_set(xierr,NR+i,NR+i,xim*xim);
if (logwidth<0) { // no apodisation
if ((tin[i]>angmin1)&&(tin[i]<angmax1)) {
weight[i]=1.0;
}
else {
weight[i]=0.0;
}
}
else {
weight[i]=apod_lower(tin[i],angmin1,logwidth)*apod_upper(tin[i],angmax1,logwidth);
}
if (corrtype==1) { //ee
if (logwidth<0) { // no apodisation
if ((tin[i]>angmin2)&&(tin[i]<angmax2)) {
weight_xim[i]=1.0;
}
else {
weight_xim[i]=0.0;
}
}
else {
weight_xim[i]=apod_lower(tin[i],angmin2,logwidth)*apod_upper(tin[i],angmax2,logwidth);
}
}
tin[i]*=PI/10800.; // convert from arcmin to radian
} // end of i loop
fclose(dat);
if ((tin[NR-1]<angmax1*PI/10800.*exp(logwidth/2.))||(corrtype==1 && tin[NR-1]<angmax2*PI/10800.*exp(logwidth/2.))) {
printf("Error: correlation function not available out to max. range requested: %g < %g ; %g\n",tin[NR-1]/PI*10800.,angmax1*exp(logwidth/2.),angmax2*PI/10800.*exp(logwidth/2.));
exit(-1);
}
if ((tin[0]>angmin1*PI/10800.*exp(-logwidth/2.))||(corrtype==1 && tin[0]>angmin2*PI/10800.*exp(-logwidth/2.))) {
printf("Error: correlation function not available out to min. range requested: %g > %g ; %g\n",tin[0]/PI*10800.,angmin1*exp(-logwidth/2.),angmin2*PI/10800.*exp(-logwidth/2.));
exit(-1);
}
sprintf(name,"%s/xi2bandpow_pmweights_%s.dat",path,ident);
if ((dat=fopen(name,"r"))==NULL) {
printf("No file %s - use pmweight of %g instead.\n",name,xi_pm_balance);
for (i=0;i<NOUT;i++) {
pfrac[i]=xi_pm_balance;
}
}
else {
printf("Using pmweights from file %s\n",name);
for (i=0;i<NOUT;i++) {
fscanf(dat,"%lf",&pfrac[i]); // xi_+/- weight in P_E; one value per output ell bin
printf("K_+ for Bin %i: %g\n",i+1,pfrac[i]);
}
fclose(dat);
}
// construct transformation matrix
logbinwidth=log(tin[NR-1]/tin[0])/(1.*NR-1.);
for (j=0;j<NR;j++) {
dr=tin[j]*(exp(0.5*logbinwidth)-exp(-0.5*logbinwidth)); // input bin width
for (i=0;i<NOUT;i++) {
scale_terms=2.*PI*dr/(tin[j]*log(ell_bound[i+1]/ell_bound[i]));
kernel=0.0;
if (corrtype==1) {
kernel=K_bandpow_ee(tin[j]*ell_bound[i+1],0)-K_bandpow_ee(tin[j]*ell_bound[i],0);
gsl_matrix_set(trans,i,j,pfrac[i]*weight[j]*kernel*scale_terms);
gsl_matrix_set(trans,NOUT+i,j,0.5*weight[j]*kernel*scale_terms);
kernel=K_bandpow_ee(tin[j]*ell_bound[i+1],1)-K_bandpow_ee(tin[j]*ell_bound[i],1);
gsl_matrix_set(trans,i,NR+j,(1.-pfrac[i])*weight_xim[j]*kernel*scale_terms);
gsl_matrix_set(trans,NOUT+i,NR+j,-0.5*weight_xim[j]*kernel*scale_terms);
}
if (corrtype==2) {
kernel=K_bandpow_ne(tin[j]*ell_bound[i+1])-K_bandpow_ne(tin[j]*ell_bound[i]);
gsl_matrix_set(trans,i,j,weight[j]*kernel*scale_terms);
gsl_matrix_set(trans,NOUT+i,NR+j,weight[j]*kernel*scale_terms);
}
if (corrtype==3) {
kernel=K_bandpow_nn(tin[j]*ell_bound[i+1])-K_bandpow_nn(tin[j]*ell_bound[i]);
gsl_matrix_set(trans,i,j,weight[j]*kernel*scale_terms);
}
}
}
// convert signals
xi_to_derived2pt(xi,xierr,trans,derived2pt,derived2pterr,2*NR,2*NOUT);
// output band powers
sprintf(name,"%s/xi2bandpow_output_%s.dat",path,outident);
dat=bj_fileopen("w",name);
fprintf(dat,"# ell PEE PEEerr PBB PBBerr\n");
for (i=0;i<NOUT;i++) {
if (corrtype==3) {
fprintf(dat,"%15.10g\t%15.10g\t%15.10g\n",ell_centre[i],gsl_vector_get(derived2pt,i),sqrt(gsl_matrix_get(derived2pterr,i,i))); // ell, bandpow, err
}
else {
fprintf(dat,"%15.10g\t%15.10g\t%15.10g\t%15.10g\t%15.10g\n",ell_centre[i],gsl_vector_get(derived2pt,i),sqrt(gsl_matrix_get(derived2pterr,i,i)),gsl_vector_get(derived2pt,NOUT+i),sqrt(gsl_matrix_get(derived2pterr,NOUT+i,NOUT+i))); // ell, E/+, err, B/x, err
}
}
fclose(dat);
sprintf(name,"%s/xi2bandpow_kernels_%s.dat",path,outident); // write kernels
dat=bj_fileopen("w",name);
for (j=0;j<NR;j++) {
fprintf(dat,"%15.10g\t",tin[j]/PI*10800.);
for (i=0;i<NOUT;i++) {
fprintf(dat,"%15.10g\t",gsl_matrix_get(trans,i,j)); // E-mode, xi_+
}
for (i=0;i<NOUT;i++) {
fprintf(dat,"%15.10g\t",gsl_matrix_get(trans,i,NR+j)); // E-mode, xi_-
}
for (i=0;i<NOUT;i++) {
fprintf(dat,"%15.10g\t",gsl_matrix_get(trans,NOUT+i,j)); // B-mode, xi_+
}
for (i=0;i<NOUT;i++) {
fprintf(dat,"%15.10g\t",gsl_matrix_get(trans,NOUT+i,NR+j)); // B-mode, xi_-
}
fprintf(dat,"\n");
}
fclose(dat);
// clean up
gsl_vector_free(xi);
gsl_vector_free(derived2pt);
gsl_matrix_free(trans);
gsl_matrix_free(xierr);
gsl_matrix_free(derived2pterr);
free(tin);
free(ell_centre);
free(ell_bound);
free(weight);
free(weight_xim);
free(pfrac);
return 0;
}
void xi_to_derived2pt(gsl_vector *xi,gsl_matrix *xierr,gsl_matrix *trans,gsl_vector *res,gsl_matrix *reserr,int nin,int nout)
{
gsl_matrix *tmp=gsl_matrix_calloc(nout,nin);
gsl_matrix *transt=gsl_matrix_calloc(nin,nout);
// signal conversion
mattimesvec_gen(trans,xi,res,nout,nin);
// error conversion
mattimesmat_gen(trans,xierr,tmp,nout,nin,nin);
matrix_transpose(trans,transt,nout,nin);
mattimesmat_gen(tmp,transt,reserr,nout,nin,nout);
gsl_matrix_free(tmp);
gsl_matrix_free(transt);
return;
}
double K_bandpow_ee(double x,int pm)
{
double res=0.0;
if (pm==0) {
res=x*gsl_sf_bessel_Jn(1,x);
}
else if (pm==1) {
res=(x-8./x)*gsl_sf_bessel_Jn(1,x)-8.*gsl_sf_bessel_Jn(2,x);
}
else {
printf("Error in routine K_bandpow_ee: invalid option for 'pm'.\n");
exit(-1);
}
return(res);
}
double K_bandpow_ne(double x)
{
return((-1.)*x*gsl_sf_bessel_Jn(1,x)-2.*gsl_sf_bessel_Jn(0,x));
}
double K_bandpow_nn(double x)
{
return(x*gsl_sf_bessel_Jn(1,x));
}
double apod_upper(double x,double scale,double logwidth)
{
double res=0.0;
double logx=log(x);
double logxmin=log(scale)-logwidth/2.;
double logxmax=log(scale)+logwidth/2.;
if (logx<=logxmin) {
res=1.;
}
else if (logx>logxmax) {
res=0.;
}
else {
res=cos(PI/2.*(logx-logxmin)/(logxmax-logxmin));
res=res*res; // cos^2
}
return(res);
}
double apod_lower(double x,double scale,double logwidth)
{
double res=0.0;
double logx=log(x);
double logxmin=log(scale)-logwidth/2.;
double logxmax=log(scale)+logwidth/2.;
if (logx<=logxmin) {
res=0.;
}
else if (logx>logxmax) {
res=1.;
}
else {
res=cos(PI/2.*(logx-logxmax)/(logxmax-logxmin));
res=res*res; // cos^2
}
return(res);
}
| {
"alphanum_fraction": 0.6473245658,
"avg_line_length": 30.2765957447,
"ext": "c",
"hexsha": "fdd7013e5fb7e7d599d273aebbaa04a438c02344",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-03-02T01:40:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-09T13:30:22.000Z",
"max_forks_repo_head_hexsha": "0de7f79cab150416859ffe58ac2d0f5659aedb5d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "KiDS-WL/Cat_to_Obs_K1000_P1",
"max_forks_repo_path": "src/bandpowers/xi2bandpow.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0de7f79cab150416859ffe58ac2d0f5659aedb5d",
"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": "KiDS-WL/Cat_to_Obs_K1000_P1",
"max_issues_repo_path": "src/bandpowers/xi2bandpow.c",
"max_line_length": 783,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "0de7f79cab150416859ffe58ac2d0f5659aedb5d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "KiDS-WL/Cat_to_Obs_K1000_P1",
"max_stars_repo_path": "src/bandpowers/xi2bandpow.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-01T08:54:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-18T12:58:03.000Z",
"num_tokens": 3448,
"size": 9961
} |
/*
# This file is part of the Astrometry.net suite.
# Licensed under a 3-clause BSD style license - see LICENSE
*/
#include <gsl/gsl_matrix_double.h>
#include <gsl/gsl_vector_double.h>
#include "compat.h"
#include "sip-utils.h"
#include "gslutils.h"
#include "mathutil.h"
#include "sip.h"
double wcs_pixel_center_for_size(double size) {
return 0.5 + 0.5 * size;
}
int sip_compute_inverse_polynomials(sip_t* sip, int NX, int NY,
double xlo, double xhi,
double ylo, double yhi) {
int inv_sip_order;
int M, N;
int i, j, p, q, gu, gv;
double maxu, maxv, minu, minv;
double u, v, U, V;
gsl_matrix *mA;
gsl_vector *b1, *b2, *x1, *x2;
tan_t* tan;
assert(sip->a_order == sip->b_order);
assert(sip->ap_order == sip->bp_order);
tan = &(sip->wcstan);
logverb("sip_compute-inverse_polynomials: A %i, AP %i\n",
sip->a_order, sip->ap_order);
/*
basic idea: lay down a grid in image, for each gridpoint, push
through the polynomial to get yourself into warped image
coordinate (but not yet lifted onto the sky). Then, using the
set of warped gridpoints as inputs, fit back to their original
grid locations as targets.
*/
inv_sip_order = sip->ap_order;
// Number of grid points to use:
if (NX == 0)
NX = 10 * (inv_sip_order + 1);
if (NY == 0)
NY = 10 * (inv_sip_order + 1);
if (xhi == 0)
xhi = tan->imagew;
if (yhi == 0)
yhi = tan->imageh;
logverb("NX,NY %i,%i, x range [%f, %f], y range [%f, %f]\n",
NX,NY, xlo, xhi, ylo, yhi);
// Number of coefficients to solve for:
// We only compute the upper triangle polynomial terms
N = (inv_sip_order + 1) * (inv_sip_order + 2) / 2;
// Number of samples to fit.
M = NX * NY;
mA = gsl_matrix_alloc(M, N);
b1 = gsl_vector_alloc(M);
b2 = gsl_vector_alloc(M);
assert(mA);
assert(b1);
assert(b2);
/*
* Rearranging formula (4), (5), and (6) from the SIP paper gives the
* following equations:
*
* +----------------------- Linear pixel coordinates in PIXELS
* | before SIP correction
* | +--- Intermediate world coordinates in DEGREES
* | |
* v v
* -1
* U = [CD11 CD12] * x
* V [CD21 CD22] y
*
* +---------------- PIXEL distortion delta from telescope to
* | linear coordinates
* | +----------- Linear PIXEL coordinates before SIP correction
* | | +--- Polynomial U,V terms in powers of PIXELS
* v v v
*
* -f(u1,v1) = p11 p12 p13 p14 p15 ... * ap1
* -f(u2,v2) = p21 p22 p23 p24 p25 ... ap2
* ...
*
* -g(u1,v1) = p11 p12 p13 p14 p15 ... * bp1
* -g(u2,v2) = p21 p22 p23 p24 p25 ... bp2
* ...
*
* which recovers the A and B's.
*/
minu = xlo - tan->crpix[0];
maxu = xhi - tan->crpix[0];
minv = ylo - tan->crpix[1];
maxv = yhi - tan->crpix[1];
// Sample grid locations.
i = 0;
for (gu=0; gu<NX; gu++) {
for (gv=0; gv<NY; gv++) {
double fuv, guv;
// Calculate grid position in original image pixels
u = (gu * (maxu - minu) / (NX-1)) + minu;
v = (gv * (maxv - minv) / (NY-1)) + minv;
// compute U=u+f(u,v) and V=v+g(u,v)
sip_calc_distortion(sip, u, v, &U, &V);
fuv = U - u;
guv = V - v;
// Polynomial terms...
j = 0;
for (p = 0; p <= inv_sip_order; p++)
for (q = 0; q <= inv_sip_order; q++) {
if (p + q > inv_sip_order)
continue;
assert(j < N);
gsl_matrix_set(mA, i, j,
pow(U, (double)p) * pow(V, (double)q));
j++;
}
assert(j == N);
gsl_vector_set(b1, i, -fuv);
gsl_vector_set(b2, i, -guv);
i++;
}
}
assert(i == M);
// Solve the linear equation.
if (gslutils_solve_leastsquares_v(mA, 2, b1, &x1, NULL, b2, &x2, NULL)) {
ANERROR("Failed to solve SIP inverse matrix equation!");
return -1;
}
// Extract the coefficients
j = 0;
for (p = 0; p <= inv_sip_order; p++)
for (q = 0; q <= inv_sip_order; q++) {
if ((p + q > inv_sip_order))
continue;
assert(j < N);
sip->ap[p][q] = gsl_vector_get(x1, j);
sip->bp[p][q] = gsl_vector_get(x2, j);
j++;
}
assert(j == N);
// Check that we found values that actually invert the polynomial.
// The error should be particularly small at the grid points.
if (true) {
// rms error accumulators:
double sumdu = 0;
double sumdv = 0;
int Z;
for (gu = 0; gu < NX; gu++) {
for (gv = 0; gv < NY; gv++) {
double newu, newv;
// Calculate grid position in original image pixels
u = (gu * (maxu - minu) / (NX-1)) + minu;
v = (gv * (maxv - minv) / (NY-1)) + minv;
sip_calc_distortion(sip, u, v, &U, &V);
sip_calc_inv_distortion(sip, U, V, &newu, &newv);
sumdu += square(u - newu);
sumdv += square(v - newv);
}
}
sumdu /= (NX*NY);
sumdv /= (NX*NY);
debug("RMS error of inverting a distortion (at the grid points, in pixels):\n");
debug(" du: %g\n", sqrt(sumdu));
debug(" dv: %g\n", sqrt(sumdu));
debug(" dist: %g\n", sqrt(sumdu + sumdv));
sumdu = 0;
sumdv = 0;
Z = 1000;
for (i=0; i<Z; i++) {
double newu, newv;
u = uniform_sample(minu, maxu);
v = uniform_sample(minv, maxv);
sip_calc_distortion(sip, u, v, &U, &V);
sip_calc_inv_distortion(sip, U, V, &newu, &newv);
sumdu += square(u - newu);
sumdv += square(v - newv);
}
sumdu /= Z;
sumdv /= Z;
debug("RMS error of inverting a distortion (at random points, in pixels):\n");
debug(" du: %g\n", sqrt(sumdu));
debug(" dv: %g\n", sqrt(sumdu));
debug(" dist: %g\n", sqrt(sumdu + sumdv));
}
gsl_matrix_free(mA);
gsl_vector_free(b1);
gsl_vector_free(b2);
gsl_vector_free(x1);
gsl_vector_free(x2);
return 0;
}
bool tan_pixel_is_inside_image(const tan_t* wcs, double x, double y) {
return (x >= 1 && x <= wcs->imagew && y >= 1 && y <= wcs->imageh);
}
bool sip_pixel_is_inside_image(const sip_t* wcs, double x, double y) {
return tan_pixel_is_inside_image(&(wcs->wcstan), x, y);
}
int* sip_filter_stars_in_field(const sip_t* sip, const tan_t* tan,
const double* xyz, const double* radec,
int N, double** p_xy, int* inds, int* p_Ngood) {
int i, Ngood;
int W, H;
double* xy = NULL;
bool allocd = false;
assert(sip || tan);
assert(xyz || radec);
assert(p_Ngood);
Ngood = 0;
if (!inds) {
inds = malloc(N * sizeof(int));
allocd = true;
}
if (p_xy)
xy = malloc(N * 2 * sizeof(double));
if (sip) {
W = (int)sip->wcstan.imagew;
H = (int)sip->wcstan.imageh;
} else {
W = (int)tan->imagew;
H = (int)tan->imageh;
}
for (i=0; i<N; i++) {
double x, y;
if (xyz) {
if (sip) {
if (!sip_xyzarr2pixelxy(sip, xyz + i*3, &x, &y))
continue;
} else {
if (!tan_xyzarr2pixelxy(tan, xyz + i*3, &x, &y))
continue;
}
} else {
if (sip) {
if (!sip_radec2pixelxy(sip, radec[i*2], radec[i*2+1], &x, &y))
continue;
} else {
if (!tan_radec2pixelxy(tan, radec[i*2], radec[i*2+1], &x, &y))
continue;
}
}
// FIXME -- check half- and one-pixel FITS issues.
if ((x < 0) || (y < 0) || (x >= W) || (y >= H))
continue;
inds[Ngood] = i;
if (xy) {
xy[Ngood * 2 + 0] = x;
xy[Ngood * 2 + 1] = y;
}
Ngood++;
}
if (allocd)
inds = realloc(inds, Ngood * sizeof(int));
if (xy)
xy = realloc(xy, Ngood * 2 * sizeof(double));
if (p_xy)
*p_xy = xy;
*p_Ngood = Ngood;
return inds;
}
| {
"alphanum_fraction": 0.4702824859,
"avg_line_length": 30.1020408163,
"ext": "c",
"hexsha": "6b2ffed853e8ef9e4fcd4c3c1f999a3673e66140",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-19T22:59:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-19T22:59:43.000Z",
"max_forks_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "mgreter/astrometrylib",
"max_forks_repo_path": "astrometrylib/src/util/sip-utils.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "mgreter/astrometrylib",
"max_issues_repo_path": "astrometrylib/src/util/sip-utils.c",
"max_line_length": 88,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mgreter/astrometrylib",
"max_stars_repo_path": "astrometrylib/src/util/sip-utils.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z",
"num_tokens": 2650,
"size": 8850
} |
// The MIT License (MIT)
//
// Copyright (c) 2018 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
// IWYU pragma: begin_exports
#include <units/bits/external/fixed_string.h>
#include <compare>
#include <cstdint>
#include <cstddef>
// IWYU pragma: end_exports
#include <gsl/gsl-lite.hpp>
namespace units {
namespace detail {
constexpr void validate_ascii_char([[maybe_unused]] char c) noexcept { gsl_Expects((c & 0x80) == 0); }
template<std::size_t N>
constexpr void validate_ascii_string([[maybe_unused]] const char (&s)[N + 1]) noexcept
{
#ifndef NDEBUG
if constexpr (N != 0)
for (size_t i = 0; i < N; ++i)
validate_ascii_char(s[i]);
#endif
}
} // namespace detail
/**
* @brief A symbol text representation
*
* This class template is responsible for definition and handling of a symbol text
* representation. In the libary it is used to define symbols of units and prefixes.
* Each symbol can have two versions: Unicode and ASCI-only.
*
* @tparam StandardCharT Character type to be used for a Unicode representation
* @tparam N The size of a Unicode symbol
* @tparam M The size of the ASCII-only symbol
*/
template<typename StandardCharT, std::size_t N, std::size_t M>
struct basic_symbol_text {
basic_fixed_string<StandardCharT, N> standard_;
basic_fixed_string<char, M> ascii_;
constexpr basic_symbol_text(char std) noexcept: standard_(std), ascii_(std) { detail::validate_ascii_char(std); }
constexpr basic_symbol_text(StandardCharT std, char a) noexcept: standard_(std), ascii_(a) { detail::validate_ascii_char(a); }
constexpr basic_symbol_text(const char (&std)[N + 1]) noexcept: standard_(std), ascii_(std) { detail::validate_ascii_string<N>(std); }
constexpr basic_symbol_text(const basic_fixed_string<char, N>& std) noexcept: standard_(std), ascii_(std) { detail::validate_ascii_string<N>(std.data_); }
constexpr basic_symbol_text(const StandardCharT (&std)[N + 1], const char (&a)[M + 1]) noexcept: standard_(std), ascii_(a) { detail::validate_ascii_string<M>(a); }
constexpr basic_symbol_text(const basic_fixed_string<StandardCharT, N>& std, const basic_fixed_string<char, M>& a) noexcept: standard_(std), ascii_(a) { detail::validate_ascii_string<M>(a.data_); }
[[nodiscard]] constexpr auto& standard() { return standard_; }
[[nodiscard]] constexpr const auto& standard() const { return standard_; }
[[nodiscard]] constexpr auto& ascii() { return ascii_; }
[[nodiscard]] constexpr const auto& ascii() const { return ascii_; }
template<std::size_t N2, std::size_t M2>
[[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + N2, M + M2> operator+(
const basic_symbol_text& lhs, const basic_symbol_text<StandardCharT, N2, M2>& rhs) noexcept
{
return basic_symbol_text<StandardCharT, N + N2, M + M2>(
lhs.standard() + rhs.standard(), lhs.ascii() + rhs.ascii());
}
template<std::size_t N2>
[[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + N2, M + N2> operator+(
const basic_symbol_text& lhs, const basic_fixed_string<StandardCharT, N2>& rhs) noexcept
{
return lhs + basic_symbol_text<StandardCharT, N2, N2>(rhs);
}
template<std::size_t N2>
[[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + N2, M + N2> operator+(
const basic_fixed_string<StandardCharT, N2>& lhs, const basic_symbol_text& rhs) noexcept
{
return basic_symbol_text<StandardCharT, N2, N2>(lhs) + rhs;
}
template<std::size_t N2>
[[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + N2 - 1, M + N2 - 1> operator+(
const basic_symbol_text& lhs, const StandardCharT (&rhs)[N2]) noexcept
{
return lhs + basic_symbol_text<StandardCharT, N2 - 1, N2 - 1>(rhs);
}
template<std::size_t N2>
[[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + N2 - 1, M + N2 - 1> operator+(
const StandardCharT (&lhs)[N2], const basic_symbol_text& rhs) noexcept
{
return basic_symbol_text<StandardCharT, N2 - 1, N2 - 1>(lhs) + rhs;
}
[[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + 1, M + 1> operator+(
const basic_symbol_text& lhs, StandardCharT rhs) noexcept
{
return lhs + basic_symbol_text<StandardCharT, 1, 1>(rhs);
}
[[nodiscard]] constexpr friend basic_symbol_text<StandardCharT, N + 1, M + 1> operator+(
StandardCharT lhs, const basic_symbol_text& rhs) noexcept
{
return basic_symbol_text<StandardCharT, 1, 1>(lhs) + rhs;
}
template<typename StandardCharT2, std::size_t N2, std::size_t M2>
[[nodiscard]] friend constexpr auto operator<=>(const basic_symbol_text& lhs,
const basic_symbol_text<StandardCharT2, N2, M2>& rhs) noexcept
{
if (const auto cmp = lhs.standard() <=> rhs.standard(); cmp != 0) return cmp;
return lhs.ascii() <=> rhs.ascii();
}
template<typename StandardCharT2, std::size_t N2, std::size_t M2>
[[nodiscard]] friend constexpr bool operator==(const basic_symbol_text& lhs,
const basic_symbol_text<StandardCharT2, N2, M2>& rhs) noexcept
{
return lhs.standard() == rhs.standard() && lhs.ascii() == rhs.ascii();
}
};
basic_symbol_text(char) -> basic_symbol_text<char, 1, 1>;
template<typename StandardCharT>
basic_symbol_text(StandardCharT, char) -> basic_symbol_text<StandardCharT, 1, 1>;
template<std::size_t N>
basic_symbol_text(const char (&)[N]) -> basic_symbol_text<char, N - 1, N - 1>;
template<std::size_t N>
basic_symbol_text(const basic_fixed_string<char, N>&) -> basic_symbol_text<char, N, N>;
template<typename StandardCharT, std::size_t N, std::size_t M>
basic_symbol_text(const StandardCharT (&)[N], const char (&)[M]) -> basic_symbol_text<StandardCharT, N - 1, M - 1>;
template<typename StandardCharT, std::size_t N, std::size_t M>
basic_symbol_text(const basic_fixed_string<StandardCharT, N>&,
const basic_fixed_string<char, M>&) -> basic_symbol_text<StandardCharT, N, M>;
} // namespace units
| {
"alphanum_fraction": 0.7131772009,
"avg_line_length": 43.2195121951,
"ext": "h",
"hexsha": "3f3466c1fd7da8d1012350c02ab9361466c5810d",
"lang": "C",
"max_forks_count": 70,
"max_forks_repo_forks_event_max_datetime": "2022-03-24T01:57:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-14T01:04:22.000Z",
"max_forks_repo_head_hexsha": "bd801c1f6e07fc38ba52398df9171709ee68125d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bebuch/units",
"max_forks_repo_path": "src/core/include/units/symbol_text.h",
"max_issues_count": 283,
"max_issues_repo_head_hexsha": "bd801c1f6e07fc38ba52398df9171709ee68125d",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T20:25:11.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-11-01T05:31:28.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "bebuch/units",
"max_issues_repo_path": "src/core/include/units/symbol_text.h",
"max_line_length": 199,
"max_stars_count": 571,
"max_stars_repo_head_hexsha": "bd801c1f6e07fc38ba52398df9171709ee68125d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bebuch/units",
"max_stars_repo_path": "src/core/include/units/symbol_text.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T14:53:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-10-17T14:57:59.000Z",
"num_tokens": 1846,
"size": 7088
} |
#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_trsm (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.773f, 0.069f, 0.45f, 0.189f };
int lda = 2;
float B[] = { -0.037f, 0.788f, 0.015f, 0.028f, -0.804f, -0.357f };
int ldb = 3;
float B_expected[] = { 0.0183269f, -0.419738f, -0.0564036f, -0.0444444f, 1.27619f, 0.566667f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1830)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.13f, -0.832f, 0.426f, 0.195f };
int lda = 2;
float B[] = { 0.504f, 0.996f, 0.872f, -0.35f, 0.518f, -0.8f };
int ldb = 3;
float B_expected[] = { -0.06384f, -0.428093f, -0.06192f, 0.105f, -0.1554f, 0.24f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1831)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.755f, -0.053f, -0.132f, -0.515f };
int lda = 2;
float B[] = { -0.735f, 0.494f, 0.072f, -0.882f, -0.112f, 0.904f };
int ldb = 3;
float B_expected[] = { 0.292053f, -0.196291f, -0.0286093f, -0.588643f, -0.0149311f, 0.533935f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1832)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.88f, -0.555f, 0.642f, 0.751f };
int lda = 2;
float B[] = { -0.411f, 0.134f, 0.657f, 0.072f, -0.007f, -0.34f };
int ldb = 3;
float B_expected[] = { 0.1233f, -0.0402f, -0.1971f, -0.100759f, 0.0279084f, 0.228538f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1833)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.478f, 0.938f, -0.731f, 0.25f };
int lda = 2;
float B[] = { -0.859f, -0.409f, -0.154f, -0.54f, 0.146f, -0.106f };
int ldb = 2;
float B_expected[] = { -1.2897f, 0.4908f, -1.08763f, 0.648f, -0.102894f, 0.1272f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1834)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.953f, 0.249f, -0.451f, -0.781f };
int lda = 2;
float B[] = { -0.4f, -0.546f, 0.839f, 0.392f, -0.445f, -0.818f };
int ldb = 2;
float B_expected[] = { 0.193874f, 0.1638f, -0.304738f, -0.1176f, 0.244175f, 0.2454f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1835)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.831f, -0.997f, -0.366f, 0.307f };
int lda = 2;
float B[] = { 0.157f, -0.02f, 0.57f, 0.309f, -0.159f, 0.266f };
int ldb = 2;
float B_expected[] = { -0.0566787f, -0.164523f, -0.205776f, -0.970224f, 0.0574007f, -0.0735227f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1836)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.842f, 0.674f, 0.03f, 0.628f };
int lda = 2;
float B[] = { -0.426f, 0.806f, 0.299f, 0.626f, -0.471f, 0.208f };
int ldb = 2;
float B_expected[] = { 0.1278f, -0.327937f, -0.0897f, -0.127342f, 0.1413f, -0.157636f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1837)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.095f, 0.301f, 0.168f, 0.934f, 0.107f, 0.068f, 0.384f, -0.201f, 0.116f };
int lda = 3;
float B[] = { 0.534f, 0.773f, -0.304f, -0.402f, 0.642f, -0.102f };
int ldb = 3;
float B_expected[] = { 1.68632f, -6.91104f, 2.39525f, -1.26947f, 1.77114f, 1.06409f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1838)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.738f, -0.353f, -0.616f, 0.304f, 0.403f, 0.739f, 0.996f, 0.329f, 0.273f };
int lda = 3;
float B[] = { -0.436f, 0.074f, 0.273f, -0.609f, 0.858f, 0.993f };
int ldb = 3;
float B_expected[] = { 0.1308f, 0.0239724f, -0.0190428f, 0.1827f, -0.192907f, -0.0427986f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1839)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.956f, 0.878f, 0.156f, 0.217f, 0.082f, -0.869f, 0.595f, 0.845f, 0.064f };
int lda = 3;
float B[] = { -0.744f, 0.662f, -0.31f, 0.811f, 0.257f, 0.98f };
int ldb = 3;
float B_expected[] = { -3.27779f, -17.3962f, 1.45312f, 7.92713f, 46.3978f, -4.59375f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1840)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.313f, -0.316f, 0.836f, 0.359f, -0.415f, 0.154f, -0.948f, -0.596f, -0.799f };
int lda = 3;
float B[] = { 0.29f, -0.291f, 0.652f, 0.614f, 0.922f, -0.063f };
int ldb = 3;
float B_expected[] = { -0.261918f, -0.0292776f, -0.1956f, -0.0710273f, -0.265336f, 0.0189f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1841)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.634f, 0.561f, 0.883f, -0.136f, 0.203f, -0.531f, 0.733f, -0.332f, 0.705f };
int lda = 3;
float B[] = { 0.133f, -0.843f, -0.179f, 0.94f, -0.656f, 0.645f };
int ldb = 2;
float B_expected[] = { 0.0629338f, -0.398896f, 0.306695f, -1.6564f, 0.358145f, -0.639766f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1842)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.742f, -0.438f, 0.991f, 0.614f, 0.108f, -0.125f, 0.736f, -0.383f, 0.0f };
int lda = 3;
float B[] = { -0.792f, -0.033f, -0.723f, 0.885f, 0.336f, 0.584f };
int ldb = 2;
float B_expected[] = { 0.2376f, 0.0099f, 0.0710136f, -0.271579f, -0.248475f, -0.286501f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1843)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.761f, 0.466f, 0.907f, -0.85f, -0.342f, -0.058f, -0.379f, -0.416f, 0.599f };
int lda = 3;
float B[] = { -0.238f, 0.013f, 0.473f, -0.626f, 0.912f, -0.003f };
int ldb = 2;
float B_expected[] = { 0.336709f, 0.329497f, 0.492375f, -0.549378f, -0.456761f, 0.0015025f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1844)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.567f, -0.532f, -0.817f, 0.85f, -0.135f, 0.797f, 0.981f, -0.75f, 0.856f };
int lda = 3;
float B[] = { -0.705f, 0.326f, 0.184f, 0.079f, -0.173f, 0.125f };
int ldb = 2;
float B_expected[] = { 0.20253f, -0.125146f, -0.0965643f, 0.0061875f, 0.0519f, -0.0375f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1845)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.859f, 0.563f, -0.61f, 0.2f };
int lda = 2;
float B[] = { -0.241f, -0.357f, -0.683f, -0.718f, 0.69f, -0.486f };
int ldb = 3;
float B_expected[] = { -0.0841676f, -0.12468f, -0.238533f, 1.31393f, -0.684026f, 1.40047f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1846)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.157f, -0.741f, 0.844f, 0.206f };
int lda = 2;
float B[] = { 0.816f, -0.692f, 0.765f, -0.408f, 0.404f, 0.764f };
int ldb = 3;
float B_expected[] = { -0.2448f, 0.2076f, -0.2295f, -0.0589968f, 0.0326316f, -0.399259f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1847)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.187f, 0.354f, -0.931f, 0.18f };
int lda = 2;
float B[] = { -0.215f, -0.645f, 0.847f, 0.014f, 0.83f, 0.761f };
int ldb = 3;
float B_expected[] = { 0.228752f, -5.85232f, -7.67336f, -0.0233333f, -1.38333f, -1.26833f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1848)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.923f, 0.27f, -0.319f, -0.856f };
int lda = 2;
float B[] = { 0.391f, 0.01f, 0.429f, 0.685f, 0.332f, -0.643f };
int ldb = 3;
float B_expected[] = { -0.182855f, -0.0347724f, -0.0671649f, -0.2055f, -0.0996f, 0.1929f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1849)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.724f, 0.201f, 0.87f, -0.638f };
int lda = 2;
float B[] = { -0.533f, 0.183f, 0.569f, 0.85f, 0.642f, -0.051f };
int ldb = 2;
float B_expected[] = { 0.220856f, 0.387218f, -0.235773f, 0.0781772f, -0.266022f, -0.386739f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1850)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.291f, 0.244f, 0.931f, 0.857f };
int lda = 2;
float B[] = { 0.008f, -0.478f, -0.252f, -0.155f, 0.419f, -0.192f };
int ldb = 2;
float B_expected[] = { -0.0024f, 0.145634f, 0.0756f, -0.0238836f, -0.1257f, 0.174627f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1851)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.634f, -0.529f, -0.344f, 0.375f };
int lda = 2;
float B[] = { -0.295f, 0.551f, 0.832f, 0.744f, -0.326f, 0.111f };
int ldb = 2;
float B_expected[] = { 0.228207f, -0.4408f, 0.890317f, -0.5952f, -0.0801653f, -0.0888f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1852)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.641f, 0.989f, 0.998f, -0.005f };
int lda = 2;
float B[] = { -0.168f, 0.465f, 0.36f, 0.356f, -0.858f, 0.879f };
int ldb = 2;
float B_expected[] = { 0.188365f, -0.1395f, -0.0023748f, -0.1068f, 0.518199f, -0.2637f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1853)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.638f, 0.389f, 0.997f, 0.909f, -0.598f, -0.43f, -0.345f, -0.897f, 0.119f };
int lda = 3;
float B[] = { 0.64f, 0.779f, -0.129f, 0.016f, 0.599f, -0.668f };
int ldb = 3;
float B_expected[] = { 0.904844f, 0.156956f, 0.32521f, 2.08405f, -0.910426f, 1.68403f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1854)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.289f, 0.641f, -0.876f, -0.503f, -0.062f, -0.987f, 0.1f, -0.105f, 0.757f };
int lda = 3;
float B[] = { -0.285f, 0.285f, 0.219f, -0.986f, -0.0f, -0.605f };
int ldb = 3;
float B_expected[] = { 0.124319f, -0.150346f, -0.0657f, 0.339965f, 0.17914f, 0.1815f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1855)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.524f, 0.018f, 0.292f, -0.573f, 0.866f, 0.749f, 0.99f, 0.101f, 0.871f };
int lda = 3;
float B[] = { 0.522f, -0.269f, -0.142f, -0.266f, -0.505f, -0.55f };
int ldb = 3;
float B_expected[] = { -0.298855f, -0.104554f, 0.400719f, 0.15229f, 0.275707f, -0.0156298f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1856)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.283f, 0.62f, -0.387f, -0.739f, -0.599f, 0.114f, 0.552f, 0.083f, -0.976f };
int lda = 3;
float B[] = { 0.202f, 0.169f, 0.7f, 0.473f, 0.86f, -0.557f };
int ldb = 3;
float B_expected[] = { -0.0606f, -0.0954834f, -0.168624f, -0.1419f, -0.362864f, 0.275547f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1857)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.185f, 0.178f, -0.22f, -0.645f, -0.585f, -0.342f, -0.594f, -0.141f, 0.944f };
int lda = 3;
float B[] = { 0.22f, -0.895f, -0.301f, -0.683f, -0.009f, -0.451f };
int ldb = 2;
float B_expected[] = { 0.888147f, -0.569939f, -0.155048f, -0.384802f, 0.00286017f, 0.143326f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1858)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.145f, 0.746f, 0.541f, 0.584f, -0.394f, 0.371f, -0.172f, -0.601f, 0.542f };
int lda = 3;
float B[] = { 0.529f, 0.636f, 0.668f, 0.848f, -0.816f, -0.925f };
int ldb = 2;
float B_expected[] = { -0.0854817f, -0.0918985f, -0.0532752f, -0.0876225f, 0.2448f, 0.2775f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1859)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.416f, -0.526f, -0.486f, -0.716f, 0.361f, 0.365f, -0.492f, 0.544f, 0.721f };
int lda = 3;
float B[] = { 0.25f, 0.746f, 0.55f, 0.836f, -0.024f, 0.226f };
int ldb = 2;
float B_expected[] = { -0.180288f, -0.537981f, -0.719755f, -1.47861f, 0.25283f, 0.291864f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1860)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.735f, -0.606f, -0.124f, 0.641f, -0.074f, -0.053f, -0.734f, 0.907f, 0.558f };
int lda = 3;
float B[] = { 0.623f, 0.392f, -0.808f, -0.022f, -0.665f, -0.616f };
int ldb = 2;
float B_expected[] = { -0.1869f, -0.1176f, 0.129139f, -0.0646656f, 0.183169f, 0.16679f };
cblas_strsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strsm(case 1861)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.584, -0.058, -0.964, -0.214 };
int lda = 2;
double B[] = { 0.073, -0.734, -0.058, -0.115, 0.513, 0.503 };
int ldb = 3;
double B_expected[] = { -0.0178370247087, 0.149492702599, 0.0332751888363, 0.053738317757, -0.239719626168, -0.235046728972 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1862)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.251, -0.8, 0.365, 0.809 };
int lda = 2;
double B[] = { -0.632, -0.611, 0.9, 0.063, -0.652, -0.841 };
int ldb = 3;
double B_expected[] = { -0.05816, -0.11326, 0.02272, 0.0063, -0.0652, -0.0841 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1863)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.833, 0.934, -0.608, 0.49 };
int lda = 2;
double B[] = { 0.336, -0.541, -0.729, -0.382, 0.741, 0.546 };
int ldb = 3;
double B_expected[] = { -0.0403361344538, 0.0649459783914, 0.0875150060024, -0.128008917853, 0.231810520126, 0.220018619693 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1864)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.824, 0.907, 0.632, -0.348 };
int lda = 2;
double B[] = { 0.351, -0.301, 0.602, 0.873, 0.031, -0.2 };
int ldb = 3;
double B_expected[] = { 0.0351, -0.0301, 0.0602, 0.0651168, 0.0221232, -0.0580464 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1865)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.427, 0.193, -0.959, -0.679 };
int lda = 2;
double B[] = { -0.646, 0.741, -0.339, 0.049, 0.734, -0.182 };
int ldb = 2;
double B_expected[] = { -0.3963857167, -0.10913107511, -0.0955986383061, -0.00721649484536, 0.232096380888, 0.0268041237113 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1866)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.282, 0.766, -0.422, -0.518 };
int lda = 2;
double B[] = { 0.269, 0.211, -0.911, -0.685, -0.777, -0.919 };
int ldb = 2;
double B_expected[] = { 0.0358042, 0.0211, -0.120007, -0.0685, -0.1164818, -0.0919 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1867)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.877, -0.818, 0.191, 0.468 };
int lda = 2;
double B[] = { 0.517, 0.669, 0.337, -0.579, 0.885, -0.677 };
int ldb = 2;
double B_expected[] = { -0.0589509692132, 0.039910485435, -0.0384264538198, -0.190882135095, -0.100912200684, -0.321038846495 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1868)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.469, 0.115, 0.284, 0.139 };
int lda = 2;
double B[] = { 0.889, -0.002, -0.686, -0.256, 0.028, 0.371 };
int ldb = 2;
double B_expected[] = { 0.0889, -0.0104235, -0.0686, -0.017711, 0.0028, 0.036778 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1869)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.218, -0.819, -0.523, 0.042, 0.545, -0.292, 0.283, 0.224, 0.247 };
int lda = 3;
double B[] = { 0.677, 0.153, -0.272, -0.226, 0.987, -0.216 };
int ldb = 3;
double B_expected[] = { -0.310550458716, -0.438607019611, -1.28619894589, 0.103669724771, 0.336890834105, 0.530329512606 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1870)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.241, 0.561, 0.164, 0.486, 0.891, -0.508, -0.596, -0.074, 0.576 };
int lda = 3;
double B[] = { -0.325, 0.382, 0.368, 0.761, -0.349, 0.324 };
int ldb = 3;
double B_expected[] = { -0.0325, 0.0564325, 0.07079771, 0.0761, -0.0775921, -0.0194971868 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1871)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.76, 0.58, -0.203, 0.053, 0.792, 0.355, -0.685, 0.449, -0.367 };
int lda = 3;
double B[] = { 0.861, -0.44, 0.842, -0.019, -0.382, -0.579 };
int ldb = 3;
double B_expected[] = { -0.0986936127734, 0.0745114634079, -0.229427792916, 0.149297547123, -0.137672708006, 0.157765667575 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1872)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.802, 0.298, 0.159, 0.333, 0.515, 0.715, -0.32, -0.217, 0.301 };
int lda = 3;
double B[] = { -0.268, 0.1, -0.631, 0.472, 0.796, 0.278 };
int ldb = 3;
double B_expected[] = { -0.0457623309, -0.0036927, -0.0631, 0.0275803442, 0.0856326, 0.0278 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1873)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.028, 0.186, -0.435, -0.747, 0.212, 0.257, 0.804, -0.595, 0.64 };
int lda = 3;
double B[] = { 0.729, -0.847, -0.577, 0.056, -0.493, 0.619 };
int ldb = 2;
double B_expected[] = { -2.60357142857, 3.025, -9.44607479784, 10.685259434, -5.58819230648, 6.23051463001 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1874)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.74, -0.091, 0.484, 0.769, 0.91, 0.817, -0.26, 0.579, 0.393 };
int lda = 3;
double B[] = { 0.109, 0.969, -0.668, 0.544, 0.753, 0.796 };
int ldb = 2;
double B_expected[] = { 0.0109, 0.0969, -0.0751821, -0.0201161, 0.1216644359, 0.1164412219 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1875)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.123, -0.328, -0.482, 0.083, -0.125, -0.712, -0.757, -0.009, 0.237 };
int lda = 3;
double B[] = { -0.18, 0.358, 0.839, -0.725, 0.73, -0.095 };
int ldb = 2;
double B_expected[] = { -5.40775366883, 2.28950005146, -2.42566413502, 0.808320675105, 0.308016877637, -0.0400843881857 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1876)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.255, -0.069, -0.137, -0.45, -0.24, 0.221, -0.509, -0.484, -0.131 };
int lda = 3;
double B[] = { -0.563, 0.993, 0.508, 0.771, 0.745, 0.233 };
int ldb = 2;
double B_expected[] = { -0.0437243505, 0.1074566983, 0.0343355, 0.0719507, 0.0745, 0.0233 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1877)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { -0.772, 0.079, -0.227, 0.998 };
int lda = 2;
double B[] = { -0.095, 0.012, -0.988, -0.722, 0.738, 0.05 };
int ldb = 3;
double B_expected[] = { -0.123056994819, 0.0155440414508, -1.27979274611, 0.733187878347, -0.740709398071, 0.051206039021 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1878)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { -0.045, 0.059, -0.61, -0.328 };
int lda = 2;
double B[] = { 0.302, -0.099, 0.521, 0.487, -0.961, 0.903 };
int ldb = 3;
double B_expected[] = { -0.302, 0.099, -0.521, -0.469182, 0.955159, -0.872261 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1879)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { -0.319, 0.642, 0.511, 0.762 };
int lda = 2;
double B[] = { 0.883, 0.987, 0.436, -0.783, 0.175, -0.973 };
int ldb = 3;
double B_expected[] = { 4.41405227952, 2.72615785879, 3.41221747752, 1.02755905512, -0.229658792651, 1.27690288714 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1880)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { 0.676, 0.038, 0.543, 0.296 };
int lda = 2;
double B[] = { 0.804, -0.28, -0.318, 0.382, -0.165, -0.007 };
int ldb = 3;
double B_expected[] = { -0.596574, 0.190405, 0.314199, -0.382, 0.165, 0.007 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1881)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { -0.722, -0.355, -0.14, -0.146 };
int lda = 2;
double B[] = { -0.44, 0.751, -0.995, 0.625, 0.16, -0.127 };
int ldb = 2;
double B_expected[] = { -0.609418282548, 5.72820931203, -1.37811634349, 5.60230334307, 0.221606648199, -1.08236253937 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1882)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { 0.817, -0.619, 0.548, 0.064 };
int lda = 2;
double B[] = { -0.756, -0.169, 0.429, -0.789, 0.79, 0.479 };
int ldb = 2;
double B_expected[] = { 0.756, -0.245288, -0.429, 1.024092, -0.79, -0.04608 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1883)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { 0.496, -0.734, -0.679, -0.697 };
int lda = 2;
double B[] = { -0.483, -0.508, -0.819, 0.237, 0.852, -0.512 };
int ldb = 2;
double B_expected[] = { -0.104772180312, -0.728837876614, 2.1543973018, 0.340028694405, -2.80479705651, -0.734576757532 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1884)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { 0.049, 0.079, -0.8, -0.762 };
int lda = 2;
double B[] = { 0.426, 0.094, 0.794, -0.098, 0.442, -0.991 };
int ldb = 2;
double B_expected[] = { -0.418574, -0.094, -0.801742, 0.098, -0.520289, 0.991 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1885)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { -0.974, 0.848, -0.765, 0.528, -0.693, 0.252, -0.135, -0.507, 0.954 };
int lda = 3;
double B[] = { 0.395, 0.791, -0.787, 0.636, 0.271, -0.905 };
int ldb = 3;
double B_expected[] = { 1.01254427581, 1.4413950829, 0.824947589099, 0.548697105717, 0.736012415258, 0.948637316562 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1886)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { 0.919, -0.513, -0.38, 0.587, -0.862, 0.598, 0.714, 0.726, 0.491 };
int lda = 3;
double B[] = { -0.056, -0.802, -0.962, 0.656, -0.195, -0.679 };
int ldb = 3;
double B_expected[] = { 0.537869412, 0.226724, 0.962, -0.506244546, -0.211042, 0.679 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1887)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { -0.287, -0.009, -0.989, -0.062, 0.714, -0.293, -0.875, 0.371, 0.728 };
int lda = 3;
double B[] = { -0.14, -0.969, 0.702, -0.317, -0.739, -0.518 };
int ldb = 3;
double B_expected[] = { -0.487804878049, 1.31478445037, -2.22062403761, -1.10452961672, 0.939102470256, -1.09460224052 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1888)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { 0.236, 0.605, 0.338, -0.926, 0.362, 0.562, -0.554, 0.076, 0.85 };
int lda = 3;
double B[] = { 0.113, 0.604, 0.859, 0.216, -0.6, -0.048 };
int ldb = 3;
double B_expected[] = { -0.113, -0.708638, -0.867745512, -0.216, 0.399984, -0.102062784 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1889)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { -0.476, 0.428, -0.214, -0.889, -0.526, -0.704, 0.458, -0.479, 0.077 };
int lda = 3;
double B[] = { 0.124, -0.007, 0.452, 0.966, 0.42, 0.369 };
int ldb = 2;
double B_expected[] = { -15.8695808776, -16.2060574143, 5.8264777048, 6.20050861686, -5.45454545455, -4.79220779221 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1890)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { 0.748, 0.242, -0.964, 0.422, -0.78, -0.595, -0.926, -0.474, 0.947 };
int lda = 3;
double B[] = { 0.242, -0.553, -0.899, -0.714, -0.084, -0.609 };
int ldb = 2;
double B_expected[] = { -0.560396352, 0.693808948, 0.938816, 1.002666, 0.084, 0.609 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1891)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { 0.808, -0.074, 0.359, -0.172, -0.934, -0.67, 0.92, -0.617, -0.383 };
int lda = 3;
double B[] = { 0.079, 0.978, 0.82, 0.444, -0.597, -0.64 };
int ldb = 2;
double B_expected[] = { -0.0977722772277, -1.2103960396, 0.885690737168, 0.571273347892, -3.19977295412, -3.80492250994 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1892)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -1;
double A[] = { 0.786, 0.922, -0.763, 0.498, -0.082, 0.538, 0.742, -0.391, -0.255 };
int lda = 3;
double B[] = { 0.911, 0.066, 0.895, 0.255, -0.547, -0.805 };
int ldb = 2;
double B_expected[] = { -0.911, -0.066, -0.055058, -0.194148, -0.118471796, 0.859093624 };
cblas_dtrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrsm(case 1893)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { -0.362f, -0.457f, -0.347f, -0.203f, -0.517f, 0.462f, 0.572f, 0.521f };
int lda = 2;
float B[] = { 0.118f, -0.593f, 0.773f, 0.053f, -0.419f, -0.096f, 0.846f, -0.311f, -0.364f, 0.161f, -0.496f, -0.393f };
int ldb = 3;
float B_expected[] = { -1.58885f, 0.58489f, -0.628497f, -0.878921f, 0.701485f, 1.08554f, 1.03347f, 0.537701f, -0.470639f, -0.207688f, -0.056162f, -0.815978f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1894) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1894) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { 0.845f, -0.654f, -0.43f, -0.834f, 0.206f, 0.414f, 0.761f, 0.961f };
int lda = 2;
float B[] = { 0.069f, 0.005f, -0.419f, 0.806f, 0.857f, 0.669f, 0.942f, 0.657f, 0.52f, 0.19f, -0.609f, -0.305f };
int ldb = 3;
float B_expected[] = { -1.07314f, -0.073878f, -1.32138f, -0.35386f, -0.029944f, 0.8495f, -0.657f, 0.942f, -0.19f, 0.52f, 0.305f, -0.609f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1895) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1895) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { -0.87f, 0.218f, 0.813f, 0.575f, -0.848f, 0.7f, -0.311f, 0.374f };
int lda = 2;
float B[] = { 0.117f, 0.758f, -0.189f, -0.768f, 0.857f, -0.269f, 0.796f, -0.592f, -0.499f, 0.977f, 0.643f, 0.282f };
int ldb = 3;
float B_expected[] = { 0.851499f, 0.0788813f, -0.881826f, -0.00372192f, -0.0586805f, -0.999761f, -1.37808f, -2.51525f, 2.45259f, 2.57925f, 1.0972f, 1.8459f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1896) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1896) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { -0.697f, -0.668f, 0.746f, -0.818f, 0.651f, 0.275f, -0.702f, -0.615f };
int lda = 2;
float B[] = { -0.876f, 0.842f, -0.848f, 0.901f, 0.75f, 0.361f, -0.702f, 0.039f, -0.41f, 0.541f, 0.489f, 0.025f };
int ldb = 3;
float B_expected[] = { -0.842f, -0.876f, -0.901f, -0.848f, -0.361f, 0.75f, 0.268242f, 0.099826f, -0.187649f, 0.389823f, 0.416261f, 0.100025f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1897) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1897) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { -0.394f, -0.65f, -0.082f, -0.632f, -0.53f, 0.483f, 0.149f, -0.192f };
int lda = 2;
float B[] = { -0.691f, 0.732f, 0.976f, 0.073f, 0.607f, 0.918f, -0.918f, 0.67f, 0.37f, -0.344f, -0.114f, -0.62f };
int ldb = 2;
float B_expected[] = { -1.39367f, -3.05481f, -3.35679f, 2.2248f, 4.33836f, -1.06673f, 1.29393f, -4.49373f, -1.89826f, 2.23995f, 1.93461f, 1.72783f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1898) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1898) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { 0.45f, 0.972f, -0.051f, 0.71f, -0.127f, -0.274f, 0.152f, 0.789f };
int lda = 2;
float B[] = { 0.683f, -0.915f, -0.773f, 0.088f, -0.28f, 0.17f, 0.818f, 0.293f, -0.551f, 0.365f, 0.899f, 0.257f };
int ldb = 2;
float B_expected[] = { 1.11563f, 0.560717f, -0.088f, -0.773f, -0.431343f, -0.256396f, -0.293f, 0.818f, -0.643965f, -0.507245f, -0.257f, 0.899f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1899) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1899) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { -0.993f, -0.028f, -0.547f, -0.251f, 0.781f, -0.315f, 0.865f, 0.229f };
int lda = 2;
float B[] = { 0.578f, 0.73f, -0.931f, 0.288f, 0.048f, 0.508f, -0.168f, 0.655f, 0.92f, -0.26f, 0.485f, 0.05f };
int ldb = 2;
float B_expected[] = { 0.718162f, -0.602325f, -0.0323644f, -1.24023f, 0.509813f, -0.0627138f, -0.410611f, 0.0227614f, -0.287729f, -0.918372f, -0.000635986f, -0.10338f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1900) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1900) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { 0.131f, -0.494f, 0.615f, -0.089f, -0.22f, -0.874f, 0.677f, 0.074f };
int lda = 2;
float B[] = { -0.276f, 0.539f, 0.647f, 0.986f, -0.34f, 0.983f, -0.819f, 0.144f, 0.361f, 0.561f, 0.178f, -0.433f };
int ldb = 2;
float B_expected[] = { -0.539f, -0.276f, -0.629951f, 0.768769f, -0.983f, -0.34f, 0.490805f, -0.697387f, -0.561f, 0.361f, 0.745886f, -0.093944f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1901) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1901) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { -0.123f, -0.726f, -0.011f, 0.245f, -0.205f, 0.77f, -0.81f, -0.973f, 0.354f, -0.835f, 0.552f, 0.396f, -0.524f, -0.204f, -0.814f, 0.284f, -0.976f, -0.835f };
int lda = 3;
float B[] = { -0.42f, 0.976f, -0.845f, 0.651f, -0.44f, -0.862f, 0.137f, 0.066f, -0.63f, 0.482f, -0.187f, 0.724f };
int ldb = 3;
float B_expected[] = { 0.783777f, -1.21156f, 0.66205f, -1.40548f, 0.886226f, 0.0391664f, -0.168468f, -0.119451f, 0.378144f, -0.774828f, 0.708857f, -0.807468f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1902) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1902) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { 0.921f, 0.167f, -0.41f, 0.578f, -0.372f, 0.106f, 0.551f, 0.668f, 0.295f, 0.855f, -0.167f, 0.976f, -0.782f, -0.777f, 0.278f, -0.98f, 0.038f, -0.832f };
int lda = 3;
float B[] = { 0.459f, 0.06f, 0.387f, 0.871f, -0.366f, 0.926f, 0.236f, -0.889f, 0.619f, 0.319f, -0.709f, 0.884f };
int ldb = 3;
float B_expected[] = { -0.06f, 0.459f, -0.630298f, 0.60987f, -0.409693f, 0.528127f, 0.889f, 0.236f, 0.181898f, 0.201918f, -0.300827f, -0.859254f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1903) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1903) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { -0.691f, -0.817f, 0.954f, -0.969f, -0.574f, -0.026f, 0.992f, 0.529f, 0.135f, -0.413f, -0.314f, -0.859f, -0.284f, -0.849f, 0.781f, 0.534f, -0.018f, 0.282f };
int lda = 3;
float B[] = { -0.028f, -0.429f, 0.066f, -0.854f, -0.316f, 0.514f, -0.465f, -0.857f, 0.286f, 0.415f, -0.486f, 0.538f };
int ldb = 3;
float B_expected[] = { 6.83575f, 2.7232f, 3.79999f, 5.15624f, -1.00015f, 1.88653f, 5.42614f, 2.69261f, 2.30584f, 3.85628f, -1.59513f, 2.00962f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1904) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1904) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { -0.839f, -0.318f, 0.175f, 0.72f, -0.683f, 0.395f, -0.279f, 0.151f, -0.71f, 0.445f, 0.533f, -0.38f, -0.749f, -0.833f, 0.871f, -0.426f, 0.195f, 0.889f };
int lda = 3;
float B[] = { 0.804f, -0.346f, 0.234f, 0.782f, 0.033f, 0.581f, 0.981f, -0.68f, 0.919f, -0.758f, 0.152f, -0.503f };
int ldb = 3;
float B_expected[] = { -0.20395f, 0.376748f, -0.290007f, -0.042249f, -0.581f, 0.033f, 1.15245f, 1.75457f, 0.255135f, 1.00089f, 0.503f, 0.152f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1905) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1905) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { -0.365f, -0.662f, 0.188f, -0.571f, 0.082f, 0.192f, -0.833f, -0.958f, 0.159f, -0.203f, 0.481f, 0.08f, -0.954f, 0.681f, -0.015f, 0.146f, -0.352f, -0.068f };
int lda = 3;
float B[] = { 0.779f, -0.691f, -0.516f, 0.148f, 0.721f, 0.217f, -0.976f, -0.963f, 0.532f, -0.366f, 0.176f, 0.4f };
int ldb = 2;
float B_expected[] = { -1.34375f, 0.302916f, 0.692272f, 0.158126f, -2.93098f, -5.71682f, 3.87247f, 3.8052f, 3.25028f, -6.53201f, -2.34332f, 2.30748f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1906) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1906) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { 0.779f, 0.065f, -0.616f, -0.245f, 0.823f, 0.689f, 0.06f, -0.164f, 0.768f, -0.727f, 0.897f, -0.556f, -0.875f, 0.862f, 0.863f, -0.085f, 0.171f, 0.063f };
int lda = 3;
float B[] = { -0.621f, 0.428f, 0.096f, 0.711f, 0.416f, -0.684f, 0.806f, 0.491f, 0.037f, -0.776f, -0.312f, 0.391f };
int ldb = 2;
float B_expected[] = { -0.428f, -0.621f, -0.711f, 0.096f, 0.811524f, 0.383068f, -0.464084f, 0.683636f, -0.866708f, -0.399047f, -0.587978f, -0.244543f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1907) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1907) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { -0.349f, 0.224f, -0.323f, 0.457f, 0.081f, 0.443f, 0.809f, 0.037f, -0.543f, 0.554f, 0.779f, 0.632f, -0.852f, -0.148f, -0.649f, -0.78f, 0.469f, -0.515f };
int lda = 3;
float B[] = { 0.162f, 0.754f, -0.978f, -0.097f, 0.986f, 0.943f, 0.676f, 0.718f, 0.204f, 0.264f, -0.124f, -0.73f };
int ldb = 2;
float B_expected[] = { 0.0811068f, 1.92921f, -3.74716f, 1.18561f, 1.80842f, -0.638944f, 0.528341f, 1.20828f, -0.471728f, -0.083028f, 0.837267f, 0.654994f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1908) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1908) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {0.0f, 1.0f};
float A[] = { -0.469f, -0.164f, -0.792f, -0.454f, 0.206f, 0.785f, 0.504f, -0.561f, 0.205f, 0.463f, -0.8f, 0.803f, 0.283f, 0.131f, 0.576f, -0.431f, 0.297f, -0.415f };
int lda = 3;
float B[] = { -0.364f, 0.853f, 0.056f, -0.78f, 0.05f, 0.223f, -0.166f, -0.097f, 0.24f, 0.721f, 0.023f, 0.508f };
int ldb = 2;
float B_expected[] = { -1.3696f, 0.527133f, 0.554099f, 0.524136f, -0.60708f, 0.820963f, -0.290931f, 0.260324f, -0.721f, 0.24f, -0.508f, 0.023f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1909) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1909) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { 0.917f, 0.367f, -0.115f, -0.321f, -0.811f, -0.563f, 0.78f, -0.742f };
int lda = 2;
float B[] = { 0.797f, 0.166f, 0.737f, -0.685f, 0.677f, -0.04f, -0.652f, 0.327f, 0.094f, -0.656f, 0.496f, -0.646f };
int ldb = 3;
float B_expected[] = { 0.811592f, -0.143789f, 0.435059f, -0.92112f, 0.621302f, -0.292277f, -0.710488f, 0.0561583f, 0.694329f, -0.137285f, 0.752465f, 0.100199f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1910) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1910) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { -0.384f, 0.783f, -0.086f, -0.649f, -0.574f, 0.216f, -0.809f, -0.608f };
int lda = 2;
float B[] = { 0.067f, -0.183f, -0.524f, 0.77f, 0.169f, 0.769f, -0.982f, -0.522f, -0.051f, -0.129f, 0.595f, 0.56f };
int ldb = 3;
float B_expected[] = { 0.067f, -0.183f, -0.524f, 0.77f, 0.169f, 0.769f, -0.857471f, -0.494255f, -0.595794f, -0.402856f, 0.110453f, 0.735815f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1911) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1911) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { 0.228f, -0.644f, 0.731f, 0.458f, 0.051f, -0.725f, 0.731f, 0.537f };
int lda = 2;
float B[] = { -0.588f, 0.01f, -0.009f, -0.374f, 0.422f, 0.758f, -0.428f, 0.263f, 0.659f, 0.171f, -0.239f, 0.968f };
int ldb = 3;
float B_expected[] = { -0.232749f, -1.39168f, -0.124158f, 0.287962f, -1.55821f, 0.0298572f, -0.208619f, 0.513035f, 0.697138f, -0.278198f, 0.419466f, 1.01607f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1912) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1912) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { -0.321f, 0.761f, 0.809f, -0.017f, -0.009f, -0.975f, 0.057f, 0.396f };
int lda = 2;
float B[] = { 0.377f, 0.776f, -0.686f, -0.561f, 0.29f, 0.601f, 0.755f, 0.518f, 0.313f, -0.394f, 0.945f, 0.395f };
int ldb = 3;
float B_expected[] = { -0.121255f, 1.51679f, -0.299033f, -0.259371f, -0.08662f, 1.52593f, 0.755f, 0.518f, 0.313f, -0.394f, 0.945f, 0.395f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1913) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1913) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { 0.186f, 0.818f, -0.142f, -0.376f, 0.332f, 0.746f, 0.413f, -0.151f };
int lda = 2;
float B[] = { -0.374f, -0.787f, 0.221f, -0.104f, 0.74f, -0.548f, 0.88f, -0.66f, 0.65f, 0.046f, -0.839f, -0.783f };
int ldb = 2;
float B_expected[] = { -1.01366f, 0.226724f, 1.10152f, 1.79962f, -0.441403f, -1.00501f, 0.588898f, 0.222456f, 0.225271f, -0.743398f, -2.5862f, -2.65075f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1914) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1914) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { -0.574f, 0.018f, -0.584f, -0.184f, 0.41f, 0.075f, 0.92f, 0.022f };
int lda = 2;
float B[] = { 0.524f, -0.234f, 0.198f, 0.079f, -0.449f, -0.433f, -0.14f, -0.201f, -0.242f, -0.368f, -0.298f, 0.693f };
int ldb = 2;
float B_expected[] = { 0.524f, -0.234f, -0.03439f, 0.13564f, -0.449f, -0.433f, 0.011615f, 0.010205f, -0.242f, -0.368f, -0.22638f, 0.86203f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1915) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1915) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { 0.422f, -0.38f, 0.919f, -0.229f, -0.849f, -0.19f, 0.02f, -0.181f };
int lda = 2;
float B[] = { 0.971f, -0.339f, 0.203f, 0.083f, 0.461f, -0.623f, 0.334f, 0.653f, 0.694f, 0.42f, 0.239f, -0.061f };
int ldb = 2;
float B_expected[] = { 3.06394f, -0.745692f, -0.330599f, 1.15808f, 8.0252f, -0.902398f, -3.36278f, 2.21688f, 0.70369f, -0.872941f, 0.477097f, 1.26772f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1916) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1916) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { 0.564f, 0.483f, -0.635f, 0.84f, 0.238f, 0.35f, 0.96f, 0.397f };
int lda = 2;
float B[] = { 0.963f, -0.513f, 0.989f, 0.404f, -0.352f, 0.924f, 0.052f, -0.059f, -0.771f, 0.341f, -0.566f, -0.844f };
int ldb = 2;
float B_expected[] = { 1.93037f, -1.08722f, 0.989f, 0.404f, -0.36854f, 0.842855f, 0.052f, -0.059f, -1.83937f, 0.2805f, -0.566f, -0.844f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1917) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1917) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { 0.182f, 0.699f, 0.303f, -0.273f, -0.363f, 0.02f, 0.991f, -0.206f, -0.347f, 0.269f, -0.384f, 0.797f, 0.392f, -0.966f, 0.347f, 0.87f, 0.016f, -0.097f };
int lda = 3;
float B[] = { 0.587f, 0.875f, -0.848f, 0.154f, -0.887f, -0.709f, 0.824f, -0.895f, 0.159f, 0.933f, -0.011f, -0.393f };
int ldb = 3;
float B_expected[] = { -14.9753f, 2.31554f, 0.613295f, 24.1527f, 5.64728f, -10.0758f, -3.79783f, -5.34545f, -5.38045f, 2.99977f, 3.92602f, -0.760993f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1918) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1918) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { 0.637f, -0.57f, 0.322f, -0.303f, 0.618f, 0.261f, 0.654f, -0.238f, 0.66f, -0.485f, 0.223f, -0.196f, -0.252f, 0.929f, -0.012f, 0.965f, 0.783f, 0.489f };
int lda = 3;
float B[] = { 0.894f, 0.93f, 0.648f, 0.914f, 0.7f, -0.138f, 0.63f, -0.173f, -0.671f, -0.327f, -0.922f, 0.816f };
int ldb = 3;
float B_expected[] = { -0.0695574f, 0.64143f, 0.518948f, 1.08197f, 0.7f, -0.138f, 1.8231f, -0.404044f, -0.62533f, -0.68968f, -0.922f, 0.816f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1919) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1919) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { 0.274f, 0.721f, -0.445f, 0.14f, 0.023f, -0.945f, 0.859f, -0.522f, -0.227f, 0.722f, 0.165f, 0.969f, -0.212f, -0.816f, 0.908f, -0.652f, -0.208f, -0.229f };
int lda = 3;
float B[] = { 0.011f, -0.818f, 0.067f, -0.191f, -0.911f, 0.84f, -0.162f, -0.951f, -0.502f, -0.21f, 0.492f, 0.767f };
int ldb = 3;
float B_expected[] = { -0.986296f, -0.390076f, -0.910328f, -1.26205f, -3.05033f, 0.930902f, -1.22716f, -0.241667f, -1.07925f, -0.600129f, -2.84941f, 5.27338f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1920) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1920) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { -0.186f, 0.118f, -0.545f, 0.784f, 0.057f, 0.39f, 0.77f, -0.518f, -0.97f, 0.271f, 0.488f, 0.637f, -0.482f, -0.993f, -0.797f, -0.945f, 0.257f, 0.3f };
int lda = 3;
float B[] = { -0.783f, 0.649f, 0.698f, 0.046f, -0.153f, 0.473f, -0.996f, -0.211f, 0.84f, 0.201f, -0.457f, 0.918f };
int ldb = 3;
float B_expected[] = { -0.783f, 0.649f, 0.964728f, -0.859324f, 0.406086f, 0.235086f, -0.996f, -0.211f, 1.71622f, -0.152458f, 0.78435f, 1.32759f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1921) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1921) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { -0.681f, -0.342f, -0.195f, -0.053f, 0.016f, -0.191f, 0.989f, -0.718f, -0.59f, 0.646f, -0.41f, -0.809f, -0.359f, -0.783f, -0.902f, 0.917f, -0.703f, 0.795f };
int lda = 3;
float B[] = { -0.27f, 0.037f, 0.349f, 0.36f, -0.293f, 0.128f, -0.481f, -0.834f, -0.815f, -0.6f, 0.728f, 0.122f };
int ldb = 2;
float B_expected[] = { -0.69977f, -2.39368f, 2.17354f, 1.74016f, 0.260417f, -1.25151f, 0.175881f, 1.93577f, 0.085191f, 0.949825f, -0.368302f, -0.590043f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1922) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1922) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { -0.132f, 0.33f, 0.357f, 0.32f, 0.833f, -0.111f, -0.192f, -0.643f, -0.622f, -0.663f, -0.58f, 0.423f, -0.874f, 0.86f, -0.281f, -0.992f, 0.055f, 0.137f };
int lda = 3;
float B[] = { 0.104f, -0.906f, -0.712f, 0.103f, -0.474f, -0.591f, 0.073f, -0.906f, -0.261f, -0.391f, 0.881f, -0.345f };
int ldb = 2;
float B_expected[] = { 0.126148f, -1.31009f, -0.0285057f, -0.554776f, -0.159469f, -0.959783f, 0.662801f, -0.128993f, -0.261f, -0.391f, 0.881f, -0.345f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1923) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1923) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { -0.353f, -0.581f, -0.648f, 0.894f, 0.825f, -0.23f, -0.529f, 0.213f, 0.568f, 0.296f, 0.372f, 0.442f, 0.515f, -0.409f, 0.222f, -0.246f, -0.524f, 0.318f };
int lda = 3;
float B[] = { -0.467f, 0.632f, 0.672f, 0.777f, -0.609f, 0.511f, -0.991f, 0.311f, -0.617f, -0.732f, -0.585f, 0.152f };
int ldb = 2;
float B_expected[] = { -0.437806f, -1.06979f, -1.49004f, 0.251317f, -2.40924f, 1.62379f, -1.09482f, 3.75003f, -1.80514f, -2.07012f, -4.8059f, -0.418185f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1924) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1924) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {1.0f, 0.0f};
float A[] = { -0.201f, -0.918f, -0.514f, -0.889f, -0.948f, 0.34f, 0.818f, 0.557f, 0.341f, 0.484f, 0.235f, 0.561f, 0.874f, -0.342f, -0.411f, -0.975f, -0.85f, -0.621f };
int lda = 3;
float B[] = { -0.389f, -0.252f, 0.322f, -0.763f, -0.839f, -0.744f, -0.946f, -0.312f, 0.051f, -0.686f, -0.626f, -0.043f };
int ldb = 2;
float B_expected[] = { -0.389f, -0.252f, 0.322f, -0.763f, -0.814918f, -1.21935f, -0.102185f, -0.417924f, -0.896001f, -0.04892f, -0.790606f, -0.720266f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1925) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1925) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.571f, 0.12f, 0.665f, 0.425f, -0.977f, -0.772f, -0.944f, -0.154f };
int lda = 2;
float B[] = { -0.357f, -0.213f, 0.57f, 0.134f, 0.089f, 0.046f, 0.027f, 0.825f, -0.127f, 0.658f, -0.332f, 0.247f };
int ldb = 3;
float B_expected[] = { 0.205417f, 0.092557f, -0.315204f, -0.0368205f, -0.0507703f, -0.0192512f, 0.238158f, 0.270895f, -0.257649f, 0.296502f, -0.140106f, 0.100105f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1926) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1926) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.051f, 0.966f, 0.04f, -0.765f, 0.276f, -0.798f, 0.766f, -0.37f };
int lda = 2;
float B[] = { 0.532f, 0.59f, 0.305f, 0.443f, 0.036f, 0.655f, -0.145f, -0.864f, -0.483f, -0.45f, -0.327f, -0.365f };
int ldb = 3;
float B_expected[] = { -0.2186f, -0.1238f, -0.1358f, -0.1024f, -0.0763f, -0.1929f, 0.043937f, 0.416881f, 0.116996f, 0.194683f, -0.0099165f, 0.142885f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1927) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1927) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.163f, -0.238f, -0.032f, 0.494f, 0.863f, 0.96f, 0.669f, 0.415f };
int lda = 2;
float B[] = { -0.724f, -0.682f, 0.034f, 0.352f, 0.42f, 0.253f, 0.186f, -0.061f, 0.278f, -0.764f, -0.484f, 0.051f };
int ldb = 3;
float B_expected[] = { -0.532386f, -1.09223f, -1.1606f, 1.43429f, 1.04476f, 0.724237f, -0.0783541f, 0.00655162f, -0.179639f, 0.27272f, 0.193877f, 0.0250509f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1928) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1928) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.533f, 0.575f, 0.808f, -0.631f, 0.185f, 0.296f, -0.757f, -0.279f };
int lda = 2;
float B[] = { -0.744f, -0.881f, -0.594f, 0.629f, -0.924f, 0.017f, -0.089f, -0.052f, 0.959f, -0.486f, 0.39f, -0.378f };
int ldb = 3;
float B_expected[] = { 0.303415f, 0.198103f, 0.0879903f, -0.363588f, 0.245042f, -0.149137f, 0.0319f, 0.0067f, -0.2391f, 0.2417f, -0.0792f, 0.1524f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1929) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1929) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.001f, -0.948f, -0.97f, -0.285f, -0.664f, -0.977f, -0.746f, 0.192f };
int lda = 2;
float B[] = { 0.997f, -0.852f, 0.87f, -0.955f, 0.007f, -0.071f, -0.263f, -0.077f, -0.856f, 0.228f, -0.81f, 0.476f };
int ldb = 2;
float B_expected[] = { 0.375027f, 0.225237f, -0.432345f, -0.0987217f, 0.0232012f, -0.00529874f, -0.112225f, 0.0682749f, -0.162707f, -0.246664f, 0.267117f, 0.237712f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1930) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1930) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.804f, 0.476f, -0.898f, -0.966f, 0.51f, -0.346f, 0.622f, -0.749f };
int lda = 2;
float B[] = { -0.964f, 0.453f, 0.799f, -0.949f, -0.055f, 0.803f, 0.99f, -0.162f, 0.913f, -0.081f, -0.057f, 0.014f };
int ldb = 2;
float B_expected[] = { 0.2439f, -0.2323f, -0.349565f, 0.398684f, -0.0638f, -0.2464f, -0.333516f, 0.295339f, -0.2658f, 0.1156f, 0.191256f, 0.0231108f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1931) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1931) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.144f, -0.611f, -0.054f, 0.618f, 0.213f, 0.49f, -0.465f, -0.488f };
int lda = 2;
float B[] = { -0.225f, -0.663f, 0.073f, -0.379f, -0.297f, 0.822f, -0.038f, -0.935f, -0.81f, 0.885f, -0.065f, 0.412f };
int ldb = 2;
float B_expected[] = { 0.287563f, -0.439427f, 0.113582f, -0.141015f, -0.375321f, -0.339988f, 0.189826f, -0.395838f, -0.655583f, 0.0702722f, -0.117522f, 0.15645f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1932) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1932) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.367f, 0.502f, -0.309f, 0.404f, 0.531f, -0.188f, 0.181f, 0.583f };
int lda = 2;
float B[] = { 0.861f, -0.648f, 0.906f, -0.402f, 0.455f, 0.412f, 0.34f, -0.248f, 0.107f, 0.507f, 0.088f, -0.593f };
int ldb = 2;
float B_expected[] = { -0.350389f, 0.252194f, -0.2316f, 0.2112f, -0.245348f, -0.0757932f, -0.0772f, 0.1084f, -0.148061f, -0.0704181f, 0.0329f, 0.1867f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1933) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1933) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.476f, 0.202f, -0.66f, 0.774f, -0.943f, -0.99f, -0.035f, 0.901f, -0.742f, -0.085f, -0.335f, -0.591f, 0.799f, 0.515f, 0.753f, 0.76f, -0.042f, -0.011f };
int lda = 3;
float B[] = { 0.025f, -0.976f, -0.44f, 0.741f, -0.126f, 0.527f, 0.743f, 0.216f, 0.661f, -0.071f, 0.564f, -0.093f };
int ldb = 3;
float B_expected[] = { -6.73789f, 0.501263f, -2.62173f, -2.22684f, -0.664138f, 3.89034f, 4.11106f, 5.79368f, -1.20958f, 3.39994f, 4.05469f, -0.945199f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1934) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1934) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.999f, 0.418f, 0.687f, 0.6f, 0.106f, -0.737f, -0.165f, 0.263f, 0.998f, -0.092f, 0.555f, -0.671f, -0.162f, -0.814f, 0.317f, 0.582f, 0.302f, -0.48f };
int lda = 3;
float B[] = { 0.699f, 0.128f, 0.296f, -0.021f, 0.654f, 0.14f, 0.008f, 0.94f, -0.963f, 0.333f, -0.481f, -0.917f };
int ldb = 3;
float B_expected[] = { -0.312717f, 0.0986958f, 0.0456624f, 0.163957f, -0.2102f, 0.0234f, 0.143952f, 0.0170999f, 0.276937f, -0.480541f, 0.236f, 0.227f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1935) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1935) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.932f, 0.532f, -0.763f, -0.029f, -0.524f, -0.938f, 0.007f, -0.445f, -0.659f, 0.709f, -0.581f, 0.825f, -0.904f, -0.453f, 0.119f, 0.964f, -0.649f, 0.48f };
int lda = 3;
float B[] = { -0.571f, 0.138f, 0.038f, -0.175f, 0.737f, 0.567f, -0.569f, 0.062f, 0.522f, -0.625f, 0.156f, 0.799f };
int ldb = 3;
float B_expected[] = { -0.0819591f, 0.15247f, -0.121808f, -0.00810757f, 0.287388f, -0.154159f, -0.0982488f, 0.13709f, -0.190946f, -0.223188f, 0.0729118f, 0.274542f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1936) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1936) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.527f, 0.272f, 0.431f, 0.642f, -0.239f, -0.254f, -0.231f, 0.766f, 0.85f, -0.09f, 0.679f, -0.898f, 0.192f, -0.651f, -0.869f, 0.859f, 0.68f, 0.03f };
int lda = 3;
float B[] = { 0.867f, 0.816f, -0.643f, 0.509f, -0.594f, -0.833f, -0.174f, 0.51f, 0.676f, 0.115f, 0.261f, -0.409f };
int ldb = 3;
float B_expected[] = { -0.3417f, -0.1581f, 0.184172f, -0.515263f, 0.82684f, 0.153742f, 0.0012f, -0.1704f, -0.0834964f, -0.0053432f, -0.216529f, 0.104369f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1937) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1937) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.606f, -0.757f, 0.503f, -0.649f, -0.269f, -0.484f, 0.626f, -0.107f, -0.867f, -0.047f, -0.779f, 0.675f, 0.249f, 0.645f, -0.755f, 0.242f, 0.941f, 0.189f };
int lda = 3;
float B[] = { -0.402f, 0.252f, -0.214f, 0.745f, 0.342f, -0.98f, -0.096f, 0.38f, -0.543f, 0.605f, 0.63f, -0.059f };
int ldb = 2;
float B_expected[] = { 0.349049f, -0.0955741f, -0.472341f, -0.259287f, -0.176304f, -0.239347f, 0.191174f, 0.170679f, 0.152979f, -0.219859f, -0.203592f, 0.0448683f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1938) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1938) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.797f, -0.288f, 0.943f, -0.821f, -0.565f, 0.73f, -0.146f, -0.967f, 0.473f, -0.095f, 0.877f, 0.178f, -0.159f, 0.021f, -0.988f, 0.296f, 0.279f, -0.513f };
int lda = 3;
float B[] = { -0.455f, 0.859f, -0.21f, 0.702f, -0.591f, -0.235f, 0.519f, 0.279f, -0.444f, 0.816f, -0.507f, 0.893f };
int ldb = 2;
float B_expected[] = { -0.136371f, -0.712172f, -0.311667f, -0.302476f, 0.337384f, -0.259056f, -0.027248f, -0.327988f, 0.0516f, -0.2892f, 0.0628f, -0.3186f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1939) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1939) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.791f, 0.19f, -0.549f, 0.994f, -0.822f, 0.679f, -0.586f, 0.042f, -0.159f, -0.86f, 0.065f, 0.943f, -0.545f, 0.403f, 0.199f, 0.76f, 0.159f, 0.715f };
int lda = 3;
float B[] = { -0.336f, 0.317f, 0.502f, 0.543f, 0.027f, 0.802f, 0.391f, 0.716f, -0.154f, 0.436f, 0.738f, -0.029f };
int ldb = 2;
float B_expected[] = { 0.119543f, -0.133991f, -0.212552f, -0.193533f, -0.239565f, -0.0842153f, -0.531028f, 0.229828f, 0.61223f, 0.265016f, 0.850081f, -0.810046f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1940) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1940) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.182f, -0.821f, -0.756f, -0.479f, -0.191f, -0.989f, -0.466f, 0.018f, 0.85f, 0.516f, -0.826f, 0.209f, -0.321f, -0.988f, -0.936f, -0.745f, -0.57f, -0.362f };
int lda = 3;
float B[] = { -0.501f, 0.915f, -0.928f, 0.722f, -0.542f, -0.828f, -0.875f, -0.981f, 0.425f, 0.347f, -0.929f, -0.596f };
int ldb = 2;
float B_expected[] = { 0.0588f, -0.3246f, 0.2062f, -0.3094f, 0.134369f, -0.0793628f, 0.368285f, -0.125876f, -0.344423f, -0.219222f, 0.402199f, -0.204129f };
cblas_ctrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrsm(case 1941) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrsm(case 1941) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.976, -0.41, -0.313, -0.779, -0.164, 0.571, 0.056, -0.526 };
int lda = 2;
double B[] = { -0.177, 0.837, 0.391, -0.853, -0.633, 0.693, -0.392, -0.356, -0.708, 0.926, -0.093, -0.337 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1942) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1942) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { -0.383, 0.141, 0.889, -0.007, -0.148, -0.068, 0.481, 0.675 };
int lda = 2;
double B[] = { 0.469, 0.735, -0.47, -0.164, 0.994, -0.483, -0.354, 0.357, 0.51, 0.523, 0.934, -0.592 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1943) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1943) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { -0.089, -0.391, -0.317, -0.349, 0.618, -0.541, -0.84, 0.31 };
int lda = 2;
double B[] = { 0.931, -0.257, -0.048, 0.633, -0.32, -0.576, -0.682, 0.953, -0.412, 0.408, -0.809, 0.092 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1944) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1944) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.599, -0.01, -0.045, 0.567, 0.827, -0.969, -0.729, 0.538 };
int lda = 2;
double B[] = { 0.971, -0.626, -0.77, -0.882, 0.434, 0.269, -0.456, 0.497, 0.289, 0.957, 0.447, -0.921 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1945) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1945) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.441, -0.501, 0.607, -0.4, -0.976, -0.523, -0.136, -0.492 };
int lda = 2;
double B[] = { 0.639, 0.872, -0.436, 0.518, 0.164, -0.04, 0.489, 0.201, 0.723, -0.958, 0.934, -0.549 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1946) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1946) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { -0.603, -0.475, 0.598, -0.666, -0.733, 0.04, 0.491, -0.592 };
int lda = 2;
double B[] = { 0.71, -0.827, 0.947, -0.364, 0.235, 0.294, 0.298, -0.401, -0.193, -0.008, 0.122, -0.47 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1947) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1947) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { -0.73, -0.823, 0.636, -0.965, 0.886, -0.236, 0.501, -0.301 };
int lda = 2;
double B[] = { 0.259, 0.701, -0.033, 0.616, -0.646, -0.177, -0.886, 0.589, -0.736, -0.303, -0.995, 0.982 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1948) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1948) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.829, -0.889, 0.382, 0.083, 0.006, -0.76, -0.338, -0.601 };
int lda = 2;
double B[] = { 0.006, 0.381, 0.241, 0.096, -0.672, 0.664, 0.952, -0.376, -0.803, 0.344, -0.09, -0.175 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1949) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1949) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.879, -0.511, -0.814, -0.94, 0.91, 0.761, 0.223, 0.03, -0.689, -0.739, -0.814, 0.463, 0.389, 0.615, -0.175, 0.129, -0.904, 0.102 };
int lda = 3;
double B[] = { 0.383, 0.328, 0.589, -0.29, 0.912, 0.327, 0.629, 0.883, -0.578, -0.708, 0.168, -0.982 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1950) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1950) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { -0.91, -0.182, 0.333, 0.193, 0.14, 0.538, 0.161, -0.034, -0.614, -0.154, 0.881, 0.842, 0.183, -0.229, 0.099, 0.062, -0.121, 0.179 };
int lda = 3;
double B[] = { -0.138, 0.109, -0.87, -0.161, 0.917, 0.443, 0.798, 0.677, -0.574, 0.327, -0.626, 0.446 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1951) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1951) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { -0.491, -0.021, -0.833, 0.921, -0.71, 0.282, 0.638, 0.223, -0.434, 0.921, -0.949, 0.457, -0.665, -0.844, -0.633, -0.874, -0.73, 0.637 };
int lda = 3;
double B[] = { -0.047, 0.714, 0.678, 0.756, 0.003, 0.359, 0.507, -0.197, -0.726, 0.873, -0.118, -0.996 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1952) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1952) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.372, 0.354, -0.537, 0.948, -0.348, 0.808, 0.573, -0.797, 0.818, 0.701, -0.749, -0.801, -0.959, -0.781, 0.727, -0.189, 0.244, 0.414 };
int lda = 3;
double B[] = { 0.852, -0.714, 0.455, 0.171, -0.128, 0.554, 0.342, -0.203, 0.669, 0.619, -0.76, 0.759 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1953) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1953) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.1, -0.975, 0.885, -0.608, -0.303, 0.87, -0.763, 0.409, 0.501, 0.522, -0.176, 0.679, -0.681, -0.815, -0.878, 0.86, 0.348, -0.65 };
int lda = 3;
double B[] = { -0.245, 0.954, -0.465, -0.931, 0.327, 0.288, -0.067, 0.252, 0.124, -0.073, -0.731, 0.176 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1954) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1954) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.572, 0.045, -0.465, 0.113, 0.996, -0.597, 0.712, 0.945, 0.053, -0.436, 0.36, 0.035, -0.489, -0.012, 0.23, 0.22, 0.068, -0.586 };
int lda = 3;
double B[] = { -0.543, -0.809, -0.641, -0.744, 0.507, -0.742, -0.279, -0.835, -0.097, -0.968, 0.984, -0.813 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1955) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1955) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.837, 0.576, -0.396, 0.013, -0.567, 0.59, 0.513, 0.824, 0.045, 0.486, 0.386, 0.766, 0.222, 0.042, 0.091, -0.008, 0.43, 0.102 };
int lda = 3;
double B[] = { 0.16, -0.958, -0.125, 0.833, 0.344, 0.213, 0.2, -0.689, 0.81, 0.415, -0.198, 0.001 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1956) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1956) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { -0.351, 0.7, -0.495, 0.448, -0.229, 0.925, -0.269, 0.251, -0.783, -0.223, 0.582, 0.373, -0.095, -0.383, -0.087, -0.043, -0.315, -0.999 };
int lda = 3;
double B[] = { -0.067, -0.104, 0.92, -0.333, 0.367, 0.995, 0.86, 0.425, 0.12, -0.756, 0.441, -0.214 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1957) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1957) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { 0.572, -0.073, 0.878, -0.688, -0.615, -0.213, -0.643, 0.809 };
int lda = 2;
double B[] = { -0.973, -0.481, 0.071, -0.71, -0.669, 0.717, -0.09, -0.304, -0.427, 0.625, 0.539, -0.565 };
int ldb = 3;
double B_expected[] = { 0.574560994608, 0.155494672389, 0.0371747871512, 0.389534544514, 0.283820482207, -0.45678514825, 0.591891359193, 0.214411302729, -0.27258111691, 0.507180331171, 0.645135319443, -0.46315922005 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1958) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1958) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.022, 0.475, 0.444, 0.252, -0.871, 0.867, -0.093, 0.264 };
int lda = 2;
double B[] = { 0.696, 0.259, 0.494, 0.162, -0.9, 0.143, 0.436, 0.487, -0.733, 0.138, -0.618, 0.572 };
int ldb = 3;
double B_expected[] = { -0.2347, -0.0081, -0.1644, 0.0008, 0.2557, -0.1329, -0.0773344, -0.0397592, 0.2792952, -0.0736264, -0.0188216, -0.2388288 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1959) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1959) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { 0.918, -0.459, 0.547, 0.887, 0.4, -0.497, 0.49, -0.313 };
int lda = 2;
double B[] = { 0.028, 0.482, -0.59, -0.533, -0.594, 0.544, -0.717, -0.524, 0.07, -0.839, 0.538, -0.548 };
int ldb = 3;
double B_expected[] = { -0.258092239243, -0.278373561582, 0.128448307703, -0.0949352940165, 0.35005709854, -0.355276452021, 0.308556833073, 0.371588344391, -0.148348709879, 0.433197660833, -0.356526626221, 0.217565644883 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1960) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1960) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.86, -0.532, -0.396, -0.116, 0.766, -0.818, -0.335, 0.271 };
int lda = 2;
double B[] = { -0.029, -0.754, -0.566, -0.108, 0.904, -0.038, 0.07, -0.476, -0.48, 0.961, 0.864, -0.593 };
int ldb = 3;
double B_expected[] = { -0.058812, 0.130312, 0.419002, 0.272588, -0.330474, -0.264172, 0.0266, 0.1498, 0.0479, -0.3363, -0.1999, 0.2643 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1961) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1961) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.043, 0.25, -0.831, 0.609, -0.896, 0.886, 0.653, 0.065 };
int lda = 2;
double B[] = { 0.548, 0.076, 0.429, 0.873, -0.559, -0.329, -0.326, -0.174, 0.633, 0.489, 0.317, -0.896 };
int ldb = 2;
double B_expected[] = { 0.239257797324, 0.64684765886, 0.889006221152, 0.139062311692, 0.0322336011438, -0.807944179397, -0.977615509726, -1.02501063893, -0.164440783851, 0.983483814822, 1.28991055447, 1.90436729944 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1962) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1962) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.268, -0.062, -0.017, 0.326, 0.561, -0.203, -0.665, 0.338 };
int lda = 2;
double B[] = { -0.46, 0.954, 0.823, 0.945, -0.825, 0.882, -0.214, -0.095, -0.935, -0.245, 0.902, 0.904 };
int ldb = 2;
double B_expected[] = { 0.0426, -0.3322, -0.297862, -0.006188, 0.1593, -0.3471, 0.054794, 0.234161, 0.305, -0.02, -0.528045, -0.107865 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1963) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1963) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.075, 0.178, -0.321, -0.056, -0.124, -0.483, 0.685, -0.052 };
int lda = 2;
double B[] = { -0.47, -0.363, 0.766, -0.961, -0.391, -0.691, 0.42, -0.339, 0.45, -0.975, 0.991, -0.198 };
int ldb = 2;
double B_expected[] = { 0.874038948948, -0.779868445448, -0.234271045009, 0.514916650598, 0.810533012472, -1.05664738101, -0.149515922946, 0.198430908039, 2.17245126703, 0.115946317124, -0.420252834642, 0.199484456348 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1964) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1964) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.206, -0.461, -0.681, 0.358, 0.21, -0.318, 0.082, -0.097 };
int lda = 2;
double B[] = { 0.576, -0.249, 0.718, 0.424, 0.728, -0.464, 0.774, 0.541, -0.112, 0.803, 0.275, -0.638 };
int ldb = 2;
double B_expected[] = { -0.343295, 0.186865, -0.2578, -0.0554, -0.3973645, 0.2566785, -0.2863, -0.0849, 0.0189315, -0.0963345, -0.0187, 0.2189 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1965) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1965) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.117, 0.983, -0.929, -0.69, -0.144, 0.28, 0.658, 0.304, -0.657, 0.543, -0.051, -0.98, -0.846, -0.484, 0.052, 0.691, 0.613, -0.178 };
int lda = 3;
double B[] = { -0.688, 0.453, -0.63, 0.067, 0.193, 0.359, -0.792, 0.307, -0.501, -0.616, -0.595, 0.817 };
int ldb = 3;
double B_expected[] = { -0.566587593051, 0.340892661842, -0.458137993587, -0.0857620879204, -0.102500656517, -0.173972458173, -1.32599192297, -0.284341349955, -0.284178293736, -0.823318590512, 0.278700120014, -0.415972885216 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1966) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1966) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { 0.773, -0.614, 0.782, -0.728, -0.727, -0.715, 0.858, -0.065, 0.922, 0.178, 0.588, 0.215, -0.92, -0.443, -0.583, -0.244, 0.996, -0.539 };
int lda = 3;
double B[] = { 0.159, 0.669, -0.692, 0.808, -0.146, 0.489, -0.385, -0.646, 0.704, -0.968, 0.551, -0.281 };
int ldb = 3;
double B_expected[] = { 0.0796383322, -0.0678193334, 0.0951193, -0.2156591, -0.0051, -0.1613, -0.2408434996, -0.0853028168, -0.0037554, 0.3083308, -0.1372, 0.1394 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1967) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1967) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.864, -0.382, -0.715, 0.227, -0.973, -0.709, -0.247, -0.601, 0.467, -0.133, 0.988, 0.937, -0.272, -0.334, 0.719, 0.992, 0.203, -0.646 };
int lda = 3;
double B[] = { 0.285, -0.409, -0.347, -0.925, -0.616, 0.422, 0.631, -0.954, -0.053, -0.255, -0.749, -0.979 };
int ldb = 3;
double B_expected[] = { -0.0215414266825, -0.165475896999, 0.469240391843, 0.538308411392, 1.71185240759, 0.063655952267, -0.0586080545035, -0.378370049976, 0.536158413721, 0.02961076215, 0.67769157898, -0.0939027988826 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1968) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1968) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.373, -0.335, -0.106, 0.542, -0.504, 0.574, -0.318, 0.043, -0.801, -0.331, 0.699, 0.776, -0.56, 0.131, 0.742, -0.692, -0.614, -0.874 };
int lda = 3;
double B[] = { -0.823, 0.929, -0.55, 0.172, -0.44, 0.067, 0.99, -0.013, 0.513, -0.438, -0.591, -0.302 };
int ldb = 3;
double B_expected[] = { 0.154, -0.361, 0.181249, -0.22802, 0.187552082, 0.008181148, -0.2957, 0.1029, -0.1997079, 0.2281373, 0.0457001502, -0.1796150434 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1969) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1969) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.912, 0.523, 0.314, -0.205, -0.895, 0.033, 0.157, -0.936, -0.582, 0.104, -0.868, 0.851, -0.131, 0.836, 0.993, 0.319, -0.684, -0.035 };
int lda = 3;
double B[] = { 0.07, -0.556, 0.018, -0.245, -0.405, 0.77, 0.888, 0.01, -0.81, -0.42, 0.66, -0.387 };
int ldb = 2;
double B_expected[] = { -0.132542904863, 0.151203976135, 0.45996395874, -0.700981460432, -0.771115355304, 0.0234040392321, 1.04091400336, -0.314874142966, -0.418936175202, -0.0443526810935, 0.218699329114, -0.27741882532 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1970) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1970) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.904, 0.983, -0.777, 0.503, 0.061, -0.442, 0.797, 0.415, -0.49, -0.466, 0.386, -0.147, -0.793, -0.381, -0.481, 0.33, 0.69, 0.35 };
int lda = 3;
double B[] = { 0.152, 0.832, 0.687, -0.287, -0.571, -0.187, -0.456, 0.631, 0.976, 0.833, -0.527, -0.188 };
int ldb = 2;
double B_expected[] = { -0.3155234788, -0.5211211034, -0.2870272698, 0.3910522396, -0.0411631, 0.0498567, 0.1600099, -0.2914973, -0.3761, -0.1523, 0.1769, 0.0037 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1971) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1971) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { 0.527, 0.434, 0.025, 0.505, 0.724, 0.961, -0.071, 0.675, -0.334, 0.259, 0.167, 0.898, 0.116, 0.723, 0.086, 0.042, -0.483, -0.862 };
int lda = 3;
double B[] = { -0.874, 0.252, 0.924, 0.251, 0.559, -0.619, -0.131, -0.286, 0.09, -0.111, 0.062, -0.973 };
int ldb = 2;
double B_expected[] = { 0.116195543731, -0.404988360492, -0.325886265381, 0.300824742268, 0.86553022636, 0.0931927221532, -0.0931167995431, -0.760087414797, 0.774460770553, -0.204189465459, -0.501996021978, -0.354684266966 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1972) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1972) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { 0.383, -0.184, 0.14, 0.131, -0.494, -0.025, -0.396, -0.183, 0.519, 0.806, -0.737, 0.764, -0.03, 0.622, -0.826, 0.605, 0.638, 0.935 };
int lda = 3;
double B[] = { 0.975, -0.816, -0.996, -0.038, -0.316, -0.31, -0.003, -0.974, 0.364, -0.217, 0.909, -0.656 };
int ldb = 2;
double B_expected[] = { -0.2109, 0.3423, 0.3026, -0.0882, 0.2001673, 0.0411059, 0.0443818, 0.2646074, -0.0213138923, 0.1426909311, 0.1794588402, 0.4128021586 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1973) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1973) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.433, -0.405, -0.008, 0.13, 0.377, -0.664, 0.421, -0.779 };
int lda = 2;
double B[] = { 0.022, -0.326, -0.905, 0.323, -0.722, 0.282, -0.877, -0.793, -0.906, -0.999, -0.607, -0.979 };
int ldb = 3;
double B_expected[] = { 0.0831887207906, -0.153137570623, -0.510564586332, -0.0447544052299, -0.412732352054, -0.0239182507667, 0.35364638809, -0.274824473121, 0.341954849059, -0.294570686181, 0.328230337479, -0.181800438645 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1974) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1974) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { 0.007, 0.289, 0.434, 0.931, 0.776, -0.861, 0.83, -0.753 };
int lda = 2;
double B[] = { 0.775, -0.299, -0.45, 0.923, 0.251, 0.934, 0.388, -0.958, -0.732, 0.263, -0.5, 0.097 };
int ldb = 3;
double B_expected[] = { -0.2026, 0.1672, 0.0427, -0.3219, -0.1687, -0.2551, -0.0883348, 0.0650146, 0.4744571, 0.0273583, 0.4510139, -0.1254463 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1975) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1975) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.768, -0.738, 0.236, 0.721, 0.691, -0.963, -0.36, -0.376 };
int lda = 2;
double B[] = { -0.822, 0.174, 0.799, 0.8, -0.985, -0.169, 0.652, -0.529, -0.51, -0.506, -0.542, -0.786 };
int ldb = 3;
double B_expected[] = { -0.212429545832, 0.508667487335, 0.591670151369, 0.238559438419, 0.40264717438, -0.154881488703, 0.500259801606, -0.0994508738781, -0.130621162022, -0.416426547, -0.0684577231932, -0.575944733113 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1976) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1976) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.294, 0.843, 0.52, 0.53, 0.392, 0.293, 0.209, 0.497 };
int lda = 2;
double B[] = { 0.765, -0.547, 0.451, -0.581, 0.166, 0.834, -0.541, 0.278, -0.832, 0.66, -0.718, -0.664 };
int ldb = 3;
double B_expected[] = { -0.1872365, 0.3339085, -0.0667796, 0.3834252, -0.2809938, -0.2009734, 0.1345, -0.1375, 0.1836, -0.2812, 0.2818, 0.1274 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1977) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1977) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { 0.642, 0.513, 0.428, 0.273, -0.612, 0.531, -0.664, 0.801 };
int lda = 2;
double B[] = { 0.429, -0.049, -0.661, 0.36, -0.247, 0.523, -0.227, 0.459, -0.902, 0.328, 0.37, -0.225 };
int ldb = 2;
double B_expected[] = { -0.161443909893, -0.0392846195877, 0.158306491417, 0.236544282705, 0.158671944063, -0.1560767799, 0.00300493937503, 0.254905467713, 0.369328020399, 0.00134777953987, -0.306971508873, -0.0836654236493 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1978) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1978) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { 0.229, -0.461, -0.279, 0.674, -0.797, -0.286, 0.397, 0.329 };
int lda = 2;
double B[] = { 0.402, 0.728, 0.824, -0.691, -0.362, 0.437, 0.192, 0.788, -0.259, 0.599, 0.79, 0.076 };
int ldb = 2;
double B_expected[] = { -0.1934, -0.1782, -0.383205, 0.202987, 0.0649, -0.1673, -0.1325225, -0.3690995, 0.0178, -0.2056, -0.289215, -0.112754 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1979) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1979) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.942, -0.832, 0.595, -0.092, 0.01, 0.001, 0.944, 0.256 };
int lda = 2;
double B[] = { 0.73, 0.488, -0.363, -0.01, -0.112, 0.169, -0.268, -0.13, -0.657, 0.573, 0.91, 0.632 };
int ldb = 2;
double B_expected[] = { 0.158268746344, 0.226988691038, 0.117355164571, -0.00345029435376, -0.0289643723553, 0.0722018494696, 0.0888981803586, 0.0370317099277, -0.233113998714, -0.101765761072, -0.305361921327, -0.187259165106 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1980) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1980) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.508, 0.053, -0.516, 0.785, -0.451, -0.53, 0.551, 0.235 };
int lda = 2;
double B[] = { -0.09, 0.46, 0.948, 0.918, -0.337, 0.012, -0.786, -0.676, 0.906, -0.38, -0.566, 0.645 };
int ldb = 2;
double B_expected[] = { -0.0713482, -0.5355066, -0.3762, -0.1806, 0.1589574, 0.2649562, 0.3034, 0.1242, 0.0168633, 0.1582089, 0.1053, -0.2501 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1981) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1981) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { 0.499, -0.268, 0.234, 0.032, -0.158, 0.684, -0.878, 0.613, 0.968, 0.812, 0.013, 0.34, -0.485, -0.565, 0.316, 0.286, -0.459, 0.637 };
int lda = 3;
double B[] = { -0.964, 0.804, 0.197, 0.141, 0.942, 0.474, 0.741, -0.441, -0.738, -0.703, -0.27, 0.98 };
int ldb = 3;
double B_expected[] = { 0.561582612433, -0.70128258354, -0.0253749021391, 0.0631927226609, 0.295313488523, -0.305260767297, -0.0937671252683, 0.884164549696, 0.000683977216651, 0.260184505619, 0.344358828778, 0.221445372699 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1982) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1982) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.453, 0.917, 0.131, 0.361, 0.087, 0.441, -0.439, 0.439, 0.777, 0.131, 0.535, 0.646, 0.508, 0.746, -0.347, -0.911, -0.874, -0.525 };
int lda = 3;
double B[] = { -0.739, -0.776, -0.049, 0.548, -0.39, -0.856, -0.757, 0.307, -0.533, -0.342, 0.431, 0.618 };
int ldb = 3;
double B_expected[] = { 0.2794424312, 0.1451980676, -0.2891898, -0.1549434, 0.2026, 0.2178, 0.2242026328, -0.0997909546, 0.3882643, 0.0019799, -0.1911, -0.1423 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1983) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1983) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.835, -0.775, -0.384, -0.128, -0.41, -0.511, -0.282, -0.341, -0.856, -0.662, 0.721, -0.939, 0.175, -0.899, 0.832, -0.519, 0.652, -0.318 };
int lda = 3;
double B[] = { -0.654, 0.105, -0.39, 0.645, 0.867, 0.045, -0.842, -0.896, -0.249, 0.419, 0.575, 0.561 };
int ldb = 3;
double B_expected[] = { -0.177337134492, -0.0485464421929, -0.0947130836909, 0.143712701441, -0.0502556531648, 0.286334558029, -0.109929498786, -0.323108217437, -0.0362323282558, 0.21056630482, -0.514117706819, 0.0792536824901 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1984) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1984) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.136, 0.272, 0.676, 0.673, -0.659, 0.668, 0.991, -0.569, -0.489, 0.581, -0.232, -0.249, -0.396, -0.832, 0.763, -0.092, 0.117, 0.108 };
int lda = 3;
double B[] = { 0.721, -0.141, -0.604, 0.318, 0.387, 0.73, -0.549, 0.302, 0.101, 0.721, -0.064, 0.673 };
int ldb = 3;
double B_expected[] = { -0.2022, 0.1144, 0.4148738, -0.1541186, -0.5047180206, 0.1126569022, 0.1345, -0.1455, -0.318479, -0.13854, 0.114359797, -0.242815912 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1985) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1985) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.578, 0.601, -0.43, -0.187, -0.934, 0.635, 0.157, -0.561, -0.964, 0.025, 0.435, -0.674, -0.575, 0.275, 0.609, 0.228, -0.202, -0.267 };
int lda = 3;
double B[] = { 0.505, -0.347, 0.213, -0.392, -0.465, -0.918, -0.737, -0.974, -0.051, 0.97, 0.066, 0.604 };
int ldb = 2;
double B_expected[] = { -0.206165616299, -0.811510964363, -0.328765954464, -0.593889594613, -0.410790365608, 0.365230809488, -0.377900693873, 0.166778025696, -0.558066070138, 0.728199798382, -0.271362172482, 0.505674752215 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1986) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1986) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.311, -0.737, -0.738, -0.214, -0.387, -0.043, -0.168, 0.563, 0.165, 0.007, -0.121, 0.408, -0.75, -0.641, -0.997, -0.347, 0.523, -0.922 };
int lda = 3;
double B[] = { 0.46, 0.376, -0.623, -0.092, 0.233, 0.981, -0.435, -0.493, 0.405, 0.855, -0.391, 0.572 };
int ldb = 2;
double B_expected[] = { -0.311417159, -0.418726217, 0.2053384662, -0.1587052684, -0.449331, -0.414523, 0.1666068, -0.1265226, -0.207, -0.216, 0.0601, -0.2107 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1987) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1987) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.288, -0.421, 0.451, 0.234, 0.67, -0.483, 0.273, 0.131, 0.005, 0.091, -0.706, -0.191, 0.285, -0.434, 0.648, -0.556, -0.886, 0.798 };
int lda = 3;
double B[] = { 0.359, -0.682, -0.618, 0.479, 0.463, 0.468, -0.43, 0.058, -0.361, -0.058, -0.028, -0.729 };
int ldb = 2;
double B_expected[] = { 0.432870841901, -0.202296442916, -0.484714722217, 0.00498299287046, -1.27917612947, -3.59551100448, 2.13407463306, 3.62604336509, 2.50059207751, 0.44116664838, -3.08374361183, -0.156015309482 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1988) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1988) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {-0.3, 0.1};
double A[] = { 0.288, 0.961, -0.571, -0.341, -0.443, 0.116, -0.928, 0.157, 0.035, 0.822, 0.733, -0.15, 0.851, -0.634, -0.769, -0.709, 0.346, -0.943 };
int lda = 3;
double B[] = { -0.708, 0.945, -0.144, 0.505, 0.827, -0.467, 0.883, 0.194, -0.607, -0.332, 0.716, -0.117 };
int ldb = 2;
double B_expected[] = { 0.1179, -0.3543, -0.0073, -0.1659, -0.2548954, -0.0197092, -0.3450402, -0.0621396, 0.4925104482, -0.0516973464, 0.0565040266, 0.1296638568 };
cblas_ztrsm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrsm(case 1989) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrsm(case 1989) imag");
};
};
};
}
| {
"alphanum_fraction": 0.528986934,
"avg_line_length": 32.1608409321,
"ext": "c",
"hexsha": "e65ba01a0160e211505a1cb6963e7147d4fe5724",
"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_trsm.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_trsm.c",
"max_line_length": 232,
"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_trsm.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": 60958,
"size": 126971
} |
/* matrix/gsl_matrix_complex_float.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATRIX_COMPLEX_FLOAT_H__
#define __GSL_MATRIX_COMPLEX_FLOAT_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_complex_float.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size1;
size_t size2;
size_t tda;
float * data;
gsl_block_complex_float * block;
int owner;
} gsl_matrix_complex_float ;
typedef struct
{
gsl_matrix_complex_float matrix;
} _gsl_matrix_complex_float_view;
typedef _gsl_matrix_complex_float_view gsl_matrix_complex_float_view;
typedef struct
{
gsl_matrix_complex_float matrix;
} _gsl_matrix_complex_float_const_view;
typedef const _gsl_matrix_complex_float_const_view gsl_matrix_complex_float_const_view;
/* Allocation */
GSL_FUN gsl_matrix_complex_float *
gsl_matrix_complex_float_alloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_complex_float *
gsl_matrix_complex_float_calloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_complex_float *
gsl_matrix_complex_float_alloc_from_block (gsl_block_complex_float * b,
const size_t offset,
const size_t n1, const size_t n2, const size_t d2);
GSL_FUN gsl_matrix_complex_float *
gsl_matrix_complex_float_alloc_from_matrix (gsl_matrix_complex_float * b,
const size_t k1, const size_t k2,
const size_t n1, const size_t n2);
GSL_FUN gsl_vector_complex_float *
gsl_vector_complex_float_alloc_row_from_matrix (gsl_matrix_complex_float * m,
const size_t i);
GSL_FUN gsl_vector_complex_float *
gsl_vector_complex_float_alloc_col_from_matrix (gsl_matrix_complex_float * m,
const size_t j);
GSL_FUN void gsl_matrix_complex_float_free (gsl_matrix_complex_float * m);
/* Views */
GSL_FUN _gsl_matrix_complex_float_view
gsl_matrix_complex_float_submatrix (gsl_matrix_complex_float * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_complex_float_view
gsl_matrix_complex_float_row (gsl_matrix_complex_float * m, const size_t i);
GSL_FUN _gsl_vector_complex_float_view
gsl_matrix_complex_float_column (gsl_matrix_complex_float * m, const size_t j);
GSL_FUN _gsl_vector_complex_float_view
gsl_matrix_complex_float_diagonal (gsl_matrix_complex_float * m);
GSL_FUN _gsl_vector_complex_float_view
gsl_matrix_complex_float_subdiagonal (gsl_matrix_complex_float * m, const size_t k);
GSL_FUN _gsl_vector_complex_float_view
gsl_matrix_complex_float_superdiagonal (gsl_matrix_complex_float * m, const size_t k);
GSL_FUN _gsl_vector_complex_float_view
gsl_matrix_complex_float_subrow (gsl_matrix_complex_float * m,
const size_t i, const size_t offset,
const size_t n);
GSL_FUN _gsl_vector_complex_float_view
gsl_matrix_complex_float_subcolumn (gsl_matrix_complex_float * m,
const size_t j, const size_t offset,
const size_t n);
GSL_FUN _gsl_matrix_complex_float_view
gsl_matrix_complex_float_view_array (float * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_complex_float_view
gsl_matrix_complex_float_view_array_with_tda (float * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_complex_float_view
gsl_matrix_complex_float_view_vector (gsl_vector_complex_float * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_complex_float_view
gsl_matrix_complex_float_view_vector_with_tda (gsl_vector_complex_float * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_complex_float_const_view
gsl_matrix_complex_float_const_submatrix (const gsl_matrix_complex_float * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_complex_float_const_view
gsl_matrix_complex_float_const_row (const gsl_matrix_complex_float * m,
const size_t i);
GSL_FUN _gsl_vector_complex_float_const_view
gsl_matrix_complex_float_const_column (const gsl_matrix_complex_float * m,
const size_t j);
GSL_FUN _gsl_vector_complex_float_const_view
gsl_matrix_complex_float_const_diagonal (const gsl_matrix_complex_float * m);
GSL_FUN _gsl_vector_complex_float_const_view
gsl_matrix_complex_float_const_subdiagonal (const gsl_matrix_complex_float * m,
const size_t k);
GSL_FUN _gsl_vector_complex_float_const_view
gsl_matrix_complex_float_const_superdiagonal (const gsl_matrix_complex_float * m,
const size_t k);
GSL_FUN _gsl_vector_complex_float_const_view
gsl_matrix_complex_float_const_subrow (const gsl_matrix_complex_float * m,
const size_t i, const size_t offset,
const size_t n);
GSL_FUN _gsl_vector_complex_float_const_view
gsl_matrix_complex_float_const_subcolumn (const gsl_matrix_complex_float * m,
const size_t j, const size_t offset,
const size_t n);
GSL_FUN _gsl_matrix_complex_float_const_view
gsl_matrix_complex_float_const_view_array (const float * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_complex_float_const_view
gsl_matrix_complex_float_const_view_array_with_tda (const float * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_complex_float_const_view
gsl_matrix_complex_float_const_view_vector (const gsl_vector_complex_float * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_complex_float_const_view
gsl_matrix_complex_float_const_view_vector_with_tda (const gsl_vector_complex_float * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_FUN void gsl_matrix_complex_float_set_zero (gsl_matrix_complex_float * m);
GSL_FUN void gsl_matrix_complex_float_set_identity (gsl_matrix_complex_float * m);
GSL_FUN void gsl_matrix_complex_float_set_all (gsl_matrix_complex_float * m, gsl_complex_float x);
GSL_FUN int gsl_matrix_complex_float_fread (FILE * stream, gsl_matrix_complex_float * m) ;
GSL_FUN int gsl_matrix_complex_float_fwrite (FILE * stream, const gsl_matrix_complex_float * m) ;
GSL_FUN int gsl_matrix_complex_float_fscanf (FILE * stream, gsl_matrix_complex_float * m);
GSL_FUN int gsl_matrix_complex_float_fprintf (FILE * stream, const gsl_matrix_complex_float * m, const char * format);
GSL_FUN int gsl_matrix_complex_float_memcpy(gsl_matrix_complex_float * dest, const gsl_matrix_complex_float * src);
GSL_FUN int gsl_matrix_complex_float_swap(gsl_matrix_complex_float * m1, gsl_matrix_complex_float * m2);
GSL_FUN int gsl_matrix_complex_float_swap_rows(gsl_matrix_complex_float * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_complex_float_swap_columns(gsl_matrix_complex_float * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_complex_float_swap_rowcol(gsl_matrix_complex_float * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_complex_float_transpose (gsl_matrix_complex_float * m);
GSL_FUN int gsl_matrix_complex_float_transpose_memcpy (gsl_matrix_complex_float * dest, const gsl_matrix_complex_float * src);
GSL_FUN int gsl_matrix_complex_float_isnull (const gsl_matrix_complex_float * m);
GSL_FUN int gsl_matrix_complex_float_ispos (const gsl_matrix_complex_float * m);
GSL_FUN int gsl_matrix_complex_float_isneg (const gsl_matrix_complex_float * m);
GSL_FUN int gsl_matrix_complex_float_isnonneg (const gsl_matrix_complex_float * m);
GSL_FUN int gsl_matrix_complex_float_add (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);
GSL_FUN int gsl_matrix_complex_float_sub (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);
GSL_FUN int gsl_matrix_complex_float_mul_elements (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);
GSL_FUN int gsl_matrix_complex_float_div_elements (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);
GSL_FUN int gsl_matrix_complex_float_scale (gsl_matrix_complex_float * a, const gsl_complex_float x);
GSL_FUN int gsl_matrix_complex_float_add_constant (gsl_matrix_complex_float * a, const gsl_complex_float x);
GSL_FUN int gsl_matrix_complex_float_add_diagonal (gsl_matrix_complex_float * a, const gsl_complex_float x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_FUN int gsl_matrix_complex_float_get_row(gsl_vector_complex_float * v, const gsl_matrix_complex_float * m, const size_t i);
GSL_FUN int gsl_matrix_complex_float_get_col(gsl_vector_complex_float * v, const gsl_matrix_complex_float * m, const size_t j);
GSL_FUN int gsl_matrix_complex_float_set_row(gsl_matrix_complex_float * m, const size_t i, const gsl_vector_complex_float * v);
GSL_FUN int gsl_matrix_complex_float_set_col(gsl_matrix_complex_float * m, const size_t j, const gsl_vector_complex_float * v);
/***********************************************************************/
/* inline functions if you are using GCC */
GSL_FUN INLINE_DECL gsl_complex_float gsl_matrix_complex_float_get(const gsl_matrix_complex_float * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL void gsl_matrix_complex_float_set(gsl_matrix_complex_float * m, const size_t i, const size_t j, const gsl_complex_float x);
GSL_FUN INLINE_DECL gsl_complex_float * gsl_matrix_complex_float_ptr(gsl_matrix_complex_float * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL const gsl_complex_float * gsl_matrix_complex_float_const_ptr(const gsl_matrix_complex_float * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
gsl_complex_float
gsl_matrix_complex_float_get(const gsl_matrix_complex_float * m,
const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
gsl_complex_float zero = {{0,0}};
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, zero) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, zero) ;
}
}
#endif
return *(gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;
}
INLINE_FUN
void
gsl_matrix_complex_float_set(gsl_matrix_complex_float * m,
const size_t i, const size_t j, const gsl_complex_float x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
}
#endif
*(gsl_complex_float *)(m->data + 2*(i * m->tda + j)) = x ;
}
INLINE_FUN
gsl_complex_float *
gsl_matrix_complex_float_ptr(gsl_matrix_complex_float * m,
const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;
}
INLINE_FUN
const gsl_complex_float *
gsl_matrix_complex_float_const_ptr(const gsl_matrix_complex_float * m,
const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (const gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_MATRIX_COMPLEX_FLOAT_H__ */
| {
"alphanum_fraction": 0.6714092141,
"avg_line_length": 41,
"ext": "h",
"hexsha": "61e19e1411621c7f8af7339aa0ce6cd207710ddb",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "deps/include/gsl/gsl_matrix_complex_float.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "berkus/music-cs",
"max_issues_repo_path": "deps/include/gsl/gsl_matrix_complex_float.h",
"max_line_length": 150,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "berkus/music-cs",
"max_stars_repo_path": "deps/include/gsl/gsl_matrix_complex_float.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3271,
"size": 14760
} |
#ifndef __DUMMY_H__
#define __DUMMY_H__
#include<stdio.h>
//#define NDEBUG
#include<stdint.h>
#include<omp.h>
#include<float.h>
#include<assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <math.h>
#include<string.h>
#include<dirent.h>
#include<sys/stat.h>
#include<sys/param.h>
#include<sys/types.h>
#include<signal.h>
//GSL library
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_blas.h>
#include<gsl/gsl_matrix.h>
#include <utility>
#include <string>
#include <iostream>
#include<iterator>
#include<map>
#include<vector>
#include <cctype>
#include<algorithm>
#include<climits>
using namespace std ;
const uint16_t loop_max=500;
uint16_t loop=0;
const double epsilon= 0.05; //error associated with user variable !
const double epsilon_m= 0.0000001; //error associated with user variable !
const double epsilon_phi= 0.0000001; //error associated with user variable !
const double epsilon_theta= 0.0000001; //error associated with user variable !
const double lower_limit_theta= 0.0000000001;
const double lower_limit_m = 0.0000000001;
const double lower_limit_phi = 0.000000001;
clock_t start;
clock_t end;
gsl_rng *rand_obj ;
double maxima_phi_i_possible=0.00000000000000000000000000000000000001;
double log_Fx_maxima_phi_i_possible=-DBL_MAX;
double * diversity;
uint32_t *freq_single_den; // freqency of theta_w in denominator
typedef struct {
bool* word_caps; // keeps tag if word at this pos was
bool* comma_present_before;
bool* period_present_before;
vector<string> word_list ;
uint32_t *int_word_list ; // Its an array to words
uint32_t *topic_usage;
int real_word_count ; //Number of words in document
int true_label ;
int sampled_label;
uint8_t *topic_list ; //Topic associated with each word
char* document_name ;
bool* priority_flag ;
bool hasPriorityWord;
int mygamma;
}document ;
#define topic_count 5 // 1 to 30 !
#define document_count 790
#define total_words_count 10000
document *d_ptr ;
//documet
//Number of topics defined in begining
int updated_doc=0 ;
//GIBBS samples count
//
int gibbs_counter=0;
const int gibbs_sample_count =25 ;
double *M_gibbs ;
double *THETA_gibbs ;
double *PHI_gibbs ;
void init_gibbs_params();
void write_model_gibbs();
void do_gibbs_expectation();
double alpha_comma_Y_gibbs=0;
double alpha_comma_N_gibbs=0;
double alpha_period_Y_gibbs=0;
double alpha_period_N_gibbs=0;
double alpha_upper_Y_gibbs=0;
double alpha_upper_N_gibbs=0;
double alpha_scale=1;
double alpha_shape=1;
const double log_ratio=log(1000);
double *M ;
double *THETA ;
double *PHI;
//File names
const char* M_file="M.bin";
const char* THETA_file="THETA.bin";
const char* PHI_file="PHI.bin";
const char* TOPIC_file="topics_list.bin";
//For keeping last maxima , this will speed up search
double *last_maxima_theta_iw;
double *last_maxima_m_ij;
double *last_maxima_phi ;
//Thread info
const int m_thread_cnt=8;
const int theta_thread_cnt=8;
//Priors
const double m_diag=500;
const double m_nondiag=1;
const double m_beta=1;
const double theta_k=1;
const double theta_beta=1;
/*
double phi_sigma_square=10000;
double phi_sigma_square=1;
double phi_mu=0;
*/
//FUNCTIONS
//INIT functions
void init(); //wrapper for all the inits
void init_model_parameters() ; //Inits model params
void init_document_params(); //INIT document structure
void init_variables();
void init_topic_assignment(document* current_doc);
void test_model();
void free_things();
//Topic update for each document
inline void update_topic_usage(document* current_doc_ptr, const uint8_t new_topic,const int old_topic );
void topic_update(document* current_doc_ptr);
void update_TOPIC();
double get_factor12(const int word_curr,const int word_next,const int t_prime,const int t_last,const int t_next,document* doc,const uint32_t mypos);
//double get_factor12(const uint32_t word_curr,const int word_next,const uint8_t t_prime,const int t_last,const int t_next,document* doc,const uint32_t mypos);
inline double get_factor2_t_i(document* current_doc_ptr, double sum);
double get_current_sum(document* doc,const uint32_t N_d, int sz);
inline void scale_pdf(double* pdf ,const int size,double sum );
inline void make_cdf_from_pdf(double* pdf ,double* cdf , const int size );
//update m_i_j
void update_M();
void update_m_ij(const int row,const int col,double * sum_den,uint32_t* freq_den,uint32_t* freq_num,uint32_t* ref);
void get_max_f_m_ij(const uint8_t i, const uint8_t j,double*log_F_max,double* maxima,double*sum_den,uint32_t*freq_den,uint32_t* freq_num,uint32_t* ref,double * maxima_possible,double * val_maxima);
double evaluate_m_ij_ll(double x0,const uint8_t i,const uint8_t j,double* sum_den,uint32_t* freq_den,uint32_t* freq_num,uint32_t* ref, double *maxima_m_ij_possible,double *log_Fx_maxima_m_ij_possible);
void m_compute_double_term_word_stat(const uint8_t i,double* sum_den ,uint32_t* freq_den,uint32_t* freq_num_i,uint32_t* w_topic_count_map);
//UPDATE THETA matrix
void update_THETA();
void update_theta_iw(const uint8_t i,const uint32_t w, double* den_single_term_header,double * sum_den,uint32_t* freq_den,const uint32_t freq_single_num,uint32_t * freq_num,const uint32_t freq_single_den_w,uint32_t * ref);
void get_max_f_theta_iw(const uint8_t i, const uint32_t w,double*log_F_max,double* maxima, double* den_single_term_header,double * sum_den,uint32_t* freq_den,const uint32_t freq_single_num,uint32_t * freq_num,const uint32_t freq_single_den_w, uint32_t* ref, double * maxima_possible,double *value_possible);
double evaluate_theta_iw_ll(double x0,const uint8_t i,const uint32_t w,const double den_single_term_header,double * sum_den,uint32_t * freq_den,const uint32_t freq_single_num,uint32_t* freq_num,const uint32_t freq_single_den_w,uint32_t* ref , double *maxima_theta_iw_possible,double *log_Fx_maxima_theta_iw_possible);
double get_den_theta_jw(const uint8_t j , const uint32_t w);
double compute_theta_single_term_denominator(const uint32_t w );
void theta_compute_double_term_word_stat(const uint32_t w,double* sum_den,uint32_t* freq_den,uint32_t* freq_single_num_w,uint32_t* freq_double_num,uint32_t* ref );
//Common codes
double inline get_number_between_two_numbers(double low, double high);
inline double rand_0_1();
void ctrl_c_handler(int single_num);
void write_model();
double timetaken(clock_t start,clock_t end , const char* mesaage);
double gamma_approx_sampler(double r,double log_F_max,double log_f_r,double maxima);
void guess_lebel(document* current_doc_ptr);
double m_diagonistics(const int i,const int j,double* sum_den,uint32_t* freq_den,uint32_t* freq_num , uint32_t* ref ,double *maxima_possible,double*value_possible,const char*msg , double maxima);
double theta_diagonistics(const int i, const int w,const double den_single_term_header,double * sum_den,uint32_t* freq_den,const uint32_t freq_single_num,uint32_t * freq_num,const uint32_t freq_single_den_w,uint32_t* ref, double *possible_maxima,double * val_at_max,const char* msg,double maxima);
int linear_scan(double*cdf , const int size,double data);
double inline get_d_2D_m(double *ptr, const int row,const int col,const int row_length);
void inline set_d_2D_m(double *ptr, const int row,const int col,double value,const int row_length);
uint32_t get_i_3D_m(const uint32_t *ptr ,int x,int y,int z,int y_size,int z_size);
void set_i_3D_m(uint32_t *ptr,int x,int y,int z,int value,int x_size,int y_size);
uint32_t inline get_i_2D_m(uint32_t *ptr, int row,int col,int row_length);
void inline set_i_2D_m(uint32_t *ptr, int row,int col,int value,int row_length);
void load_model_params();
void load_topics();
//update PHI
double evaluate_phi_i(const double x0,const uint8_t i );
void update_PHI();
void get_max_f_phi_i(const uint8_t i, double* log_Fx,double* maxima ) ; // calculate maximum of function of log !
void print_topic_corpus();
void print_model_params();
void print_system_config();
void reset_topic_usage();
uint32_t get_key_3D_m(int x,int y,int z,int x_size,int y_size);
void print_time();
//Makes word of document
//void make_int_words(document* doc);
void make_int_words(document* doc,vector<string>& word_list );
//These things cam because of new data interpretation
//Now theyi are in strings so,I will use these data structures for
//string interpretation.
void make_word_id(string word);
std::map<string , int > word_id_map;
std::map<int , string > id_word_map;
string get_word_from_id(int id);
int get_id_from_word(string word);
//while we read document we will silently populate this map for furtehr uses !
void create_word_id_id_word_map(string word);
//helper function for day to word
bool isWordStartsWithCaps(string word);
bool isCommaBeforeMe(string word) ;
bool isPeriodBeforeMe(string word) ;
//New variables for \alpha_c_Y and so on !
double alpha_comma_Y=0;
double alpha_comma_N=0;
double alpha_period_Y=0;
double alpha_period_N=0;
double alpha_upper_Y=0;
double alpha_upper_N=0;
// shape and scale of \alpha
//make string lower case
string make_lowercase_string(string word);
bool doesWordStartsUpper(string data);
const string highlight_tag_start="<:t:>";
const string highlight_tag_end="<:/t:>";
const string comma=",";
const string period=".";
double get_punctuation_multipler_num(document* doc, int pos,int t_last,int t_next );
double get_punctuation_multipler_den(document* doc, int pos,int t_last, int t_next );
#define total_configs_punctuation 8
double multiplier_values[total_configs_punctuation];
void fill_multiplier_values();
bool didReturnDBL_MAX=false;
//alpha_comma_Y
void sample_alpha_comma_Y();
void make_alpha_comma_Y_statistics(int &num_count,double* sum_den,map<int,vector<int> >& ref);
double evaluate_alpha_comma_Y_log_posterior(double x0,const int &num_count, double* sum_den,const map<int , vector<int> > & ref,double *maxima_alpha_comma_Y_possible,double *log_Fx_maxima_alpha_comma_Y_possible);
void get_max_f_alpha_comma_Y(double* log_F_max,double *maxima ,int &num_count,double*sum_den,map<int,vector<int> >& ref,double * maxima_possible,double * val_maxima);
double alpha_comma_Y_diagonistics(int &num_count,double*sum_den,map<int,vector<int> >& ref,double * possible_maxima,double * val_at_max ,const char* msg,double maxima);
//alpha_comma_N
void sample_alpha_comma_N();
void make_alpha_comma_N_statistics(int &num_count,double* sum_den,map<int,vector<int> >& ref);
double evaluate_alpha_comma_N_log_posterior(double x0,const int &num_count, double* sum_den,const map<int , vector<int> > & ref,double *maxima_alpha_comma_N_possible,double *log_Fx_maxima_alpha_comma_N_possible);
void get_max_f_alpha_comma_N(double* log_F_max,double *maxima ,int &num_count,double*sum_den,map<int,vector<int> >& ref,double * maxima_possible,double * val_maxima);
double alpha_comma_N_diagonistics(int &num_count,double*sum_den,map<int,vector<int> >& ref,double * possible_maxima,double * val_at_max ,const char* msg,double maxima);
//alpha_upper_Y
void sample_alpha_upper_Y();
void make_alpha_upper_Y_statistics(int &num_count,double* sum_den,map<int,vector<int> >& ref);
double evaluate_alpha_upper_Y_log_posterior(double x0,const int &num_count, double* sum_den,const map<int , vector<int> > & ref,double *maxima_alpha_upper_Y_possible,double *log_Fx_maxima_alpha_upper_Y_possible);
void get_max_f_alpha_upper_Y(double* log_F_max,double *maxima ,int &num_count,double*sum_den,map<int,vector<int> >& ref,double * maxima_possible,double * val_maxima);
double alpha_upper_Y_diagonistics(int &num_count,double*sum_den,map<int,vector<int> >& ref,double * possible_maxima,double * val_at_max ,const char* msg,double maxima);
//alpha_upper_N
void sample_alpha_upper_N();
void make_alpha_upper_N_statistics(int &num_count,double* sum_den,map<int,vector<int> >& ref);
double evaluate_alpha_upper_N_log_posterior(double x0,const int &num_count, double* sum_den,const map<int , vector<int> > & ref,double *maxima_alpha_upper_N_possible,double *log_Fx_maxima_alpha_upper_N_possible);
void get_max_f_alpha_upper_N(double* log_F_max,double *maxima ,int &num_count,double*sum_den,map<int,vector<int> >& ref,double * maxima_possible,double * val_maxima);
double alpha_upper_N_diagonistics(int &num_count,double*sum_den,map<int,vector<int> >& ref,double * possible_maxima,double * val_at_max ,const char* msg,double maxima);
//alpha_upper_Y
void sample_alpha_period_Y();
void make_alpha_period_Y_statistics(int &num_count,double* sum_den,map<int,vector<int> >& ref);
double evaluate_alpha_period_Y_log_posterior(double x0,const int &num_count, double* sum_den,const map<int , vector<int> > & ref,double *maxima_alpha_period_Y_possible,double *log_Fx_maxima_alpha_period_Y_possible);
void get_max_f_alpha_period_Y(double* log_F_max,double *maxima ,int &num_count,double*sum_den,map<int,vector<int> >& ref,double * maxima_possible,double * val_maxima);
double alpha_period_Y_diagonistics(int &num_count,double*sum_den,map<int,vector<int> >& ref,double * possible_maxima,double * val_at_max ,const char* msg,double maxima);
//alpha_period_N
void sample_alpha_period_N();
void make_alpha_period_N_statistics(int &num_count,double* sum_den,map<int,vector<int> >& ref);
double evaluate_alpha_period_N_log_posterior(double x0,const int &num_count, double* sum_den,const map<int , vector<int> > & ref,double *maxima_alpha_period_N_possible,double *log_Fx_maxima_alpha_period_N_possible);
void get_max_f_alpha_period_N(double* log_F_max,double *maxima ,int &num_count,double*sum_den,map<int,vector<int> >& ref,double * maxima_possible,double * val_maxima);
double alpha_period_N_diagonistics(int &num_count,double*sum_den,map<int,vector<int> >& ref,double * possible_maxima,double * val_at_max ,const char* msg,double maxima);
///home/rkumar2/final_test/data
///data1/rahul/projects/text_mining/branch/punctuation/chris_data
const char* data="/data1/rahul/projects/text_mining/branch/punctuation/chris_data/AB" ;
const char* dict_file="/data1/rahul/projects/text_mining/branch/punctuation/chris_data/word_list.txt" ;
#endif
| {
"alphanum_fraction": 0.7985417994,
"avg_line_length": 45.424437299,
"ext": "h",
"hexsha": "70d9fdbea1e01def1ee186cf479b2b756c6addbd",
"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": "6415097bf3259d9315741787d1ccdc11be2560d3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "rahul0/JBI",
"max_forks_repo_path": "models/3a/3a.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6415097bf3259d9315741787d1ccdc11be2560d3",
"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": "rahul0/JBI",
"max_issues_repo_path": "models/3a/3a.h",
"max_line_length": 318,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6415097bf3259d9315741787d1ccdc11be2560d3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "rahul0/JBI",
"max_stars_repo_path": "models/3a/3a.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3683,
"size": 14127
} |
//
// Revision.hpp
// PretendToWork
//
// Created by tqtifnypmb on 14/12/2017.
// Copyright © 2017 tqtifnypmb. All rights reserved.
//
#pragma once
#include "../rope/Range.h"
#include "../types.h"
#include <gsl/gsl>
#include <vector>
#include <string>
namespace brick
{
class Rope;
class Revision {
public:
enum class Operation {
insert,
erase,
};
Revision(size_t authorId, size_t revId, Operation op, const Range& range);
Revision(size_t authorId, size_t revId, Operation op, const Range& range, const detail::CodePointList& text);
Revision(const Revision&) = default;
Revision() = default;
void apply(gsl::not_null<Rope*> rope) const;
bool canApply(gsl::not_null<const Rope*> rope) const;
size_t authorId() const {
return authorId_;
}
bool prior(const Revision& rev) const {
return authorId() <= rev.authorId();
}
size_t revId() const {
return revId_;
}
const Range& range() const {
return range_;
}
Range& range() {
return range_;
}
int affectLength() const {
if (op() == Operation::insert) {
return static_cast<int>(cplist().size());
} else {
return range().length;
}
}
Operation op() const {
return op_;
}
bool valid() const {
return !range_.empty() && range_.location >= 0;
}
void setInvalid() {
range_.length = 0;
}
const detail::CodePointList& cplist() const {
return cplist_;
}
private:
size_t authorId_;
// revId_ only identify individual revision
// newer revision doesn't have to have greater revId_
size_t revId_;
detail::CodePointList cplist_;
Operation op_;
Range range_;
};
} // namespace brick
| {
"alphanum_fraction": 0.5781083953,
"avg_line_length": 20.0212765957,
"ext": "h",
"hexsha": "38a7c0f7595f4c23b44de88c29c4eb984ff84ddb",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tqtifnypmb/brick",
"max_forks_repo_path": "src/crdt/Revision.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tqtifnypmb/brick",
"max_issues_repo_path": "src/crdt/Revision.h",
"max_line_length": 113,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tqtifnypmb/brick",
"max_stars_repo_path": "src/crdt/Revision.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 472,
"size": 1882
} |
/* histogram/init2d.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_histogram2d.h>
gsl_histogram2d *
gsl_histogram2d_alloc (const size_t nx, const size_t ny)
{
gsl_histogram2d *h;
if (nx == 0)
{
GSL_ERROR_VAL ("histogram2d length nx must be positive integer",
GSL_EDOM, 0);
}
if (ny == 0)
{
GSL_ERROR_VAL ("histogram2d length ny must be positive integer",
GSL_EDOM, 0);
}
h = (gsl_histogram2d *) malloc (sizeof (gsl_histogram2d));
if (h == 0)
{
GSL_ERROR_VAL ("failed to allocate space for histogram2d struct",
GSL_ENOMEM, 0);
}
h->xrange = (double *) malloc ((nx + 1) * sizeof (double));
if (h->xrange == 0)
{
free (h); /* exception in constructor, avoid memory leak */
GSL_ERROR_VAL ("failed to allocate space for histogram2d x ranges",
GSL_ENOMEM, 0);
}
h->yrange = (double *) malloc ((ny + 1) * sizeof (double));
if (h->yrange == 0)
{
free (h->xrange);
free (h); /* exception in constructor, avoid memory leak */
GSL_ERROR_VAL ("failed to allocate space for histogram2d y ranges",
GSL_ENOMEM, 0);
}
h->bin = (double *) malloc (nx * ny * sizeof (double));
if (h->bin == 0)
{
free (h->xrange);
free (h->yrange);
free (h); /* exception in constructor, avoid memory leak */
GSL_ERROR_VAL ("failed to allocate space for histogram bins",
GSL_ENOMEM, 0);
}
h->nx = nx;
h->ny = ny;
return h;
}
gsl_histogram2d *
gsl_histogram2d_calloc_uniform (const size_t nx, const size_t ny,
const double xmin, const double xmax,
const double ymin, const double ymax)
{
gsl_histogram2d *h;
if (xmin >= xmax)
{
GSL_ERROR_VAL ("xmin must be less than xmax", GSL_EINVAL, 0);
}
if (ymin >= ymax)
{
GSL_ERROR_VAL ("ymin must be less than ymax", GSL_EINVAL, 0);
}
h = gsl_histogram2d_calloc (nx, ny);
if (h == 0)
{
return h;
}
{
size_t i;
for (i = 0; i < nx + 1; i++)
{
h->xrange[i] = xmin + ((double) i / (double) nx) * (xmax - xmin);
}
for (i = 0; i < ny + 1; i++)
{
h->yrange[i] = ymin + ((double) i / (double) ny) * (ymax - ymin);
}
}
return h;
}
gsl_histogram2d *
gsl_histogram2d_calloc (const size_t nx, const size_t ny)
{
gsl_histogram2d *h;
if (nx == 0)
{
GSL_ERROR_VAL ("histogram2d length nx must be positive integer",
GSL_EDOM, 0);
}
if (ny == 0)
{
GSL_ERROR_VAL ("histogram2d length ny must be positive integer",
GSL_EDOM, 0);
}
h = (gsl_histogram2d *) malloc (sizeof (gsl_histogram2d));
if (h == 0)
{
GSL_ERROR_VAL ("failed to allocate space for histogram2d struct",
GSL_ENOMEM, 0);
}
h->xrange = (double *) malloc ((nx + 1) * sizeof (double));
if (h->xrange == 0)
{
free (h); /* exception in constructor, avoid memory leak */
GSL_ERROR_VAL ("failed to allocate space for histogram2d x ranges",
GSL_ENOMEM, 0);
}
h->yrange = (double *) malloc ((ny + 1) * sizeof (double));
if (h->yrange == 0)
{
free (h->xrange);
free (h); /* exception in constructor, avoid memory leak */
GSL_ERROR_VAL ("failed to allocate space for histogram2d y ranges",
GSL_ENOMEM, 0);
}
h->bin = (double *) malloc (nx * ny * sizeof (double));
if (h->bin == 0)
{
free (h->xrange);
free (h->yrange);
free (h); /* exception in constructor, avoid memory leak */
GSL_ERROR_VAL ("failed to allocate space for histogram bins",
GSL_ENOMEM, 0);
}
{
size_t i;
for (i = 0; i < nx + 1; i++)
{
h->xrange[i] = i;
}
for (i = 0; i < ny + 1; i++)
{
h->yrange[i] = i;
}
for (i = 0; i < nx * ny; i++)
{
h->bin[i] = 0;
}
}
h->nx = nx;
h->ny = ny;
return h;
}
void
gsl_histogram2d_free (gsl_histogram2d * h)
{
free (h->xrange);
free (h->yrange);
free (h->bin);
free (h);
}
int
gsl_histogram2d_set_ranges_uniform (gsl_histogram2d * h,
double xmin, double xmax,
double ymin, double ymax)
{
size_t i;
const size_t nx = h->nx, ny = h->ny;
if (xmin >= xmax)
{
GSL_ERROR_VAL ("xmin must be less than xmax", GSL_EINVAL, 0);
}
if (ymin >= ymax)
{
GSL_ERROR_VAL ("ymin must be less than ymax", GSL_EINVAL, 0);
}
/* initialize ranges */
for (i = 0; i <= nx; i++)
{
h->xrange[i] = xmin + ((double) i / (double) nx) * (xmax - xmin);
}
for (i = 0; i <= ny; i++)
{
h->yrange[i] = ymin + ((double) i / (double) ny) * (ymax - ymin);
}
/* clear contents */
for (i = 0; i < nx * ny; i++)
{
h->bin[i] = 0;
}
return GSL_SUCCESS;
}
int
gsl_histogram2d_set_ranges (gsl_histogram2d * h,
const double xrange[], size_t xsize,
const double yrange[], size_t ysize)
{
size_t i;
const size_t nx = h->nx, ny = h->ny;
if (xsize != (nx + 1))
{
GSL_ERROR_VAL ("size of xrange must match size of histogram",
GSL_EINVAL, 0);
}
if (ysize != (ny + 1))
{
GSL_ERROR_VAL ("size of yrange must match size of histogram",
GSL_EINVAL, 0);
}
/* initialize ranges */
for (i = 0; i <= nx; i++)
{
h->xrange[i] = xrange[i];
}
for (i = 0; i <= ny; i++)
{
h->yrange[i] = yrange[i];
}
/* clear contents */
for (i = 0; i < nx * ny; i++)
{
h->bin[i] = 0;
}
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.5619047619,
"avg_line_length": 21,
"ext": "c",
"hexsha": "9895ec5c918458bcc6aaffa2be1dbf7025abdd27",
"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/histogram/init2d.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/histogram/init2d.c",
"max_line_length": 73,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/histogram/init2d.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": 1979,
"size": 6405
} |
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mpfr.h>
#include <petsc.h>
#include "../ellipsoid/ellipsoid.h"
#include "../ellipsoid/ellSolv.h"
#include "../sphere/sphere.h"
#include "../sphere/sphSolv.h"
#include "../constants.h"
#undef __FUNCT__
#define __FUNCT__ "CoulombExact"
PetscErrorCode CoulombExact(PetscReal eps1, Vec srcXYZ, Vec srcMag, Vec tarXYZ, Vec sol)
{
PetscErrorCode ierr;
PetscReal srcX, srcY, srcZ;
PetscReal tarX, tarY, tarZ;
PetscReal dx2, dy2, dz2;
PetscReal val, mag;
const PetscScalar *srcXYZArray;
const PetscScalar *srcMagArray;
const PetscScalar *tarXYZArray;
PetscScalar *solArray;
PetscInt nSrc, nTar;
PetscInt i, k;
PetscFunctionBeginUser;
ierr = VecGetSize(srcMag, &nSrc);CHKERRQ(ierr);
ierr = VecGetSize(sol, &nTar);CHKERRQ(ierr);
ierr = VecGetArrayRead(srcXYZ, &srcXYZArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(tarXYZ, &tarXYZArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(srcMag, &srcMagArray);CHKERRQ(ierr);
ierr = VecGetArray (sol , &solArray );CHKERRQ(ierr);
for(i=0; i<nTar; ++i) {
/* get target X,Y,Z */
tarX = tarXYZArray[3*i+0];
tarY = tarXYZArray[3*i+1];
tarZ = tarXYZArray[3*i+2];
for(k=0; k<nSrc; ++k) {
/* get source X,Y,Z */
srcX = srcXYZArray[3*k+0];
srcY = srcXYZArray[3*k+1];
srcZ = srcXYZArray[3*k+2];
mag = srcMagArray[k];
dx2 = (tarX-srcX)*(tarX-srcX);
dy2 = (tarY-srcY)*(tarY-srcY);
dz2 = (tarZ-srcZ)*(tarZ-srcZ);
val = mag/(eps1*PetscSqrtReal(dx2 + dy2 + dz2));
solArray[i] += val;
}
}
ierr = VecRestoreArrayRead(srcXYZ, &srcXYZArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(tarXYZ, &tarXYZArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(srcMag, &srcMagArray);CHKERRQ(ierr);
ierr = VecRestoreArray (sol , &solArray );CHKERRQ(ierr);
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.6626569038,
"avg_line_length": 29.4153846154,
"ext": "c",
"hexsha": "92c58fd8eadcbb35843fcffd7821bf624ae3b997",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "tom-klotz/ellipsoid-solvation",
"max_forks_repo_path": "src/examples/testFunctions.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "tom-klotz/ellipsoid-solvation",
"max_issues_repo_path": "src/examples/testFunctions.c",
"max_line_length": 88,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "tom-klotz/ellipsoid-solvation",
"max_stars_repo_path": "src/examples/testFunctions.c",
"max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z",
"num_tokens": 616,
"size": 1912
} |
#include <gsl/gsl_odeiv2.h>
#include "func.h"
#include "make_grid.h"
int
make_grid (struct param params, double r, double r1, double y[])
{
int status;
int *fake_jac;
/* The integrator RK8PD (Runge-Kutta Prince-Dormand) doesn't need the
* jacobian (some more sophisticated integrators do) so make this a
* null pointer. The linker will complain that the pointer type is
* incompatable since it doesn't point to a function with a bunch of
* arguments, but the pointer won't be used anyway so it doesn't
* matter. */
fake_jac = 0;
gsl_odeiv2_system sys = { func, fake_jac, 2, ¶ms };
gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new
(&sys, gsl_odeiv2_step_rk8pd,
1.0e+0, 1.0e-8, 1.0e-8);
status = gsl_odeiv2_driver_apply (d, &r, r1, y);
gsl_odeiv2_driver_free (d);
return 0;
}
| {
"alphanum_fraction": 0.7020506634,
"avg_line_length": 29.6071428571,
"ext": "c",
"hexsha": "b94a220535d108ac66db6b19d230fa49fcf66701",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158",
"max_forks_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_forks_repo_name": "bcfriesen/TOV_solver",
"max_forks_repo_path": "src/make_grid.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_issues_repo_name": "bcfriesen/TOV_solver",
"max_issues_repo_path": "src/make_grid.c",
"max_line_length": 71,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158",
"max_stars_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_stars_repo_name": "bcfriesen/TOV_solver",
"max_stars_repo_path": "src/make_grid.c",
"max_stars_repo_stars_event_max_datetime": "2015-11-14T02:27:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-14T02:27:58.000Z",
"num_tokens": 278,
"size": 829
} |
/**
*
* @precisions normal z -> c d s
*
**/
#define _TYPE PLASMA_Complex64_t
#define _PREC double
#define _LAMCH LAPACKE_dlamch_work
#define _NAME "PLASMA_zgeqrf"
/* See Lawn 41 page 120 */
#define _FMULS FMULS_GEQRF(M, N)
#define _FADDS FADDS_GEQRF(M, N)
#include "./timing.c"
#include <cblas.h>
#define COMPLEX
/* computes the residual ||A*P - Q*R||
* similar to zqpt01.f in testing.
* A is m x n
* AF is m x n, partial QR factorization of k columns of A.
* tau for Householder transformations.
* jpvt column pivots.
* work array, dimension (lwork)
* lwork >= m*n + n.
*/
double qp_residual(
int m, int n, int k,
const PLASMA_Complex64_t *A, int lda,
const PLASMA_Complex64_t *AF, int ldaf,
const PLASMA_Complex64_t *tau,
const int *jpvt,
PLASMA_Complex64_t *work, int lwork )
{
PLASMA_Complex64_t mzone = (PLASMA_Complex64_t)-1.0;
PLASMA_Complex64_t zzero = (PLASMA_Complex64_t) 0.0;
int j, ldw;
double rwork[1];
ldw = m;
if ( lwork < ldw*n + n ) {
fprintf( stderr, "Error: lwork %d too small, requires %d\n", lwork, m*n + n );
return 0.;
}
/* copy R to work, with zeros below diagonal */
LAPACKE_zlaset( LAPACK_COL_MAJOR, 'L', m-1, n, zzero, zzero, &work[1], ldw );
LAPACKE_zlacpy( LAPACK_COL_MAJOR, 'U', m, n, AF, lda, work, ldw );
/* form W = QR */
LAPACKE_zunmqr_work( LAPACK_COL_MAJOR, 'L', 'N', m, n, k,
AF, ldaf, tau, work, ldw,
&work[n*ldw], lwork-n*ldw );
//printf( "\n" );
//printf( "m %d, n %d, k %d\n", m, n, k );
//CORE_zprint( m, n, A, lda, "A" );
//CORE_zprint( m, n, AF, ldaf, "QR" );
//CORE_zprint( 1, min(m,n), tau, 1, "tau" );
//CORE_zprint( m, n, work, ldw, "Q*R" );
/* compare (subtract) j-th column of W to jpvt(j)-th column of A (jpvt is 1-based) */
for( j = 0; j < n; ++j ) {
cblas_zaxpy( m, CBLAS_SADDR(mzone), &A[(jpvt[j]-1)*lda], 1, &work[j*ldw], 1 );
}
//CORE_zprint( m, n, work, ldw, "Q*R - AP" );
return LAPACKE_zlange_work( LAPACK_COL_MAJOR, 'O', m, n, work, ldw, rwork );
}
static int
RunTest(int *iparam, double *dparam, real_Double_t *t_)
{
int info, lwork, lwork2, i;
int *jpvt;
PLASMA_Complex64_t *tau, *work, *work2;
double *rwork;
PASTE_CODE_IPARAM_LOCALS( iparam );
/* Allocate Data */
PASTE_CODE_ALLOCATE_MATRIX( A, 1, PLASMA_Complex64_t, LDA, N );
/* LAPACK needs larger size in real;
* PLASMA currently uses work and rwork for both real and complex. */
#ifdef COMPLEX
lwork = (N+1)*NB;
#else
lwork = (N+1)*NB + 2*N;
#endif
work = (PLASMA_Complex64_t*) malloc( lwork * sizeof(PLASMA_Complex64_t) );
rwork = (double*) malloc( 2*2*N * sizeof(double) );
jpvt = (int*) malloc( N * sizeof(int) );
tau = (PLASMA_Complex64_t*) malloc( 2*N * sizeof(PLASMA_Complex64_t) );
if ( jpvt == NULL || tau == NULL || work == NULL || rwork == NULL ) {
fprintf( stderr, "malloc failed\n" );
return -1;
}
/* zero out pivots (required by LAPACK) */
for( i = 0; i < N; ++i ) {
jpvt[i] = 0;
}
/* Initialize Data */
PLASMA_zplrnt(M, N, A, LDA, 123456);
/* Save A in lapack layout for check */
PASTE_CODE_ALLOCATE_COPY( Acpy, check, PLASMA_Complex64_t, A, LDA, N );
START_TIMING();
info = PLASMA_zgeqp3( M, N, A, LDA, jpvt, tau, work, rwork );
STOP_TIMING();
/* Check the solution */
if ( info != 0 ) {
printf( "\nPLASMA_zgeqp3 returned error %d.\n", info );
}
else if ( check ) {
lwork2 = (M*N + N);
work2 = (PLASMA_Complex64_t*) malloc( lwork2 * sizeof(PLASMA_Complex64_t) );
if ( work2 == NULL ) {
fprintf( stderr, "test malloc failed\n" );
return -1;
}
dparam[IPARAM_ANORM] = LAPACKE_zlange_work( LAPACK_COL_MAJOR, 'F', N, N, Acpy, LDA, rwork );
dparam[IPARAM_XNORM] = 1.;
dparam[IPARAM_BNORM] = 0.;
dparam[IPARAM_RES] = qp_residual( M, N, min(M,N), Acpy, LDA,
A, LDA, tau, jpvt, work2, lwork2 );
// /* compute result with LAPACK */
// int *jpvt2;
// PLASMA_Complex64_t *tau2;
// jpvt2 = (int*) malloc( N * sizeof(int) );
// tau2 = (PLASMA_Complex64_t*) malloc( N * sizeof(PLASMA_Complex64_t) );
// if ( jpvt2 == NULL || tau2 == NULL ) {
// fprintf( stderr, "test malloc failed\n" );
// return -1;
// }
//
// /* zero out pivots (required by LAPACK) */
// for( i = 0; i < N; ++i ) {
// jpvt2[i] = 0;
// }
//
// double time = cWtime();
// #ifdef COMPLEX
// info = LAPACKE_zgeqp3_work( LAPACK_COL_MAJOR, N, N, Acpy, LDA, jpvt2, tau2, work, lwork, rwork );
// #else
// info = LAPACKE_zgeqp3_work( LAPACK_COL_MAJOR, N, N, Acpy, LDA, jpvt2, tau2, work, lwork );
// #endif
// time = cWtime() - time;
// if ( info != 0 ) {
// printf( "qp3 returned error %d\n", info );
// }
// /* printf( " %7.3f", time ); */
//
// CORE_zprint( M, N, Acpy, LDA, "QR_L" );
// CORE_zprint( 1, min(M,N), tau2, 1, "tau_L" );
// cblas_zaxpy( LDA*N, CBLAS_SADDR(mzone), A, 1, Acpy, 1 );
// dparam[IPARAM_RES] = LAPACKE_zlange_work( LAPACK_COL_MAJOR, 'F', N, N, Acpy, LDA, rwork );
//
// cblas_zaxpy( N, CBLAS_SADDR(mzone), tau, 1, tau2, 1 );
// tnorm = cblas_dznrm2( N, tau2, 1 );
/* printf( "|t|=%.2e\n", tnorm ); */
// for( i = 0; i < N; ++i ) {
// if ( jpvt[i]+1 != jpvt2[i] ) {
// printf( "pivot mis-match jpvt[%2d]+1=%2d, jpvt2[%2d]=%2d\n", i, jpvt[i]+1, i, jpvt2[i] );
// }
// }
// free( jpvt2 );
// free( tau2 );
free( Acpy );
free( work2 );
}
/* Free data */
free( A );
free( jpvt );
free( tau );
free( work );
free( rwork );
return 0;
}
| {
"alphanum_fraction": 0.5194763729,
"avg_line_length": 31.6363636364,
"ext": "c",
"hexsha": "531a820de966cedfc414d0d8ccd191264f99d4b0",
"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/time_zgeqp3.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/time_zgeqp3.c",
"max_line_length": 108,
"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/time_zgeqp3.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2170,
"size": 6264
} |
/*
* File: rng.h
* Author: fedro
*
* Created on November 3, 2014, 5:33 PM
*/
#ifndef RNG_H
#define RNG_H
#include <gsl/gsl_rng.h>
class RNG
{
public:
RNG(const gsl_rng_type* rng_type, const int seed=0)
{
rng_ = gsl_rng_alloc(rng_type);
gsl_rng_set(rng_, seed);
}
RNG(const int seed=0)
{
rng_ = gsl_rng_alloc(gsl_rng_default);
gsl_rng_set(rng_, seed);
}
virtual ~RNG()
{
gsl_rng_free(rng_);
}
gsl_rng* get() { return rng_; }
private:
gsl_rng* rng_;
};
#endif /* RNG_H */
| {
"alphanum_fraction": 0.5749559083,
"avg_line_length": 15.3243243243,
"ext": "h",
"hexsha": "68141b1b2f7752db1eb20e034e82fb0c1f2b67c5",
"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": "8f641f73bcac2700b476663fe656fcad7d63470d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ModelDBRepository/228604",
"max_forks_repo_path": "simulation/neurophys/rng.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d",
"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": "ModelDBRepository/228604",
"max_issues_repo_path": "simulation/neurophys/rng.h",
"max_line_length": 55,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ModelDBRepository/228604",
"max_stars_repo_path": "simulation/neurophys/rng.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 170,
"size": 567
} |
/* -----------------------------------------------------------------------------
* Copyright 2021 Jonathan Haigh
* SPDX-License-Identifier: MIT
* ---------------------------------------------------------------------------*/
#ifndef SQ_INCLUDE_GUARD_system_linux_SqTypeSchemaImpl_h_
#define SQ_INCLUDE_GUARD_system_linux_SqTypeSchemaImpl_h_
#include "core/typeutil.h"
#include "system/SqTypeSchema.gen.h"
#include "system/schema.h"
#include <gsl/gsl>
namespace sq::system::linux {
class SqTypeSchemaImpl : public SqTypeSchema<SqTypeSchemaImpl> {
public:
explicit SqTypeSchemaImpl(const TypeSchema &type_schema);
SQ_ND Result get_name() const;
SQ_ND Result get_doc() const;
SQ_ND Result get_fields() const;
SQ_ND Primitive to_primitive() const override;
private:
gsl::not_null<const TypeSchema *> type_schema_;
};
} // namespace sq::system::linux
#endif // SQ_INCLUDE_GUARD_system_linux_SqTypeSchemaImpl_h_
| {
"alphanum_fraction": 0.6530612245,
"avg_line_length": 26.6,
"ext": "h",
"hexsha": "147a8e30af53480d9993ac88954e89af2a02783f",
"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": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jonathanhaigh/sq",
"max_forks_repo_path": "src/system/include/system/linux/SqTypeSchemaImpl.h",
"max_issues_count": 44,
"max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jonathanhaigh/sq",
"max_issues_repo_path": "src/system/include/system/linux/SqTypeSchemaImpl.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jonathanhaigh/sq",
"max_stars_repo_path": "src/system/include/system/linux/SqTypeSchemaImpl.h",
"max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z",
"num_tokens": 199,
"size": 931
} |
/*
* Copyright (c) 2016-2021 lymastee, All rights reserved.
* Contact: lymastee@hotmail.com
*
* This file is part of the gslib project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#ifndef res_92f78d87_1896_40fa_bc63_c52e2793c970_h
#define res_92f78d87_1896_40fa_bc63_c52e2793c970_h
#include <gslib/config.h>
#include <gslib/std.h>
__gslib_begin__
class resvdir
{
public:
resvdir(const gchar* path);
resvdir(const gchar* dir, const gchar* file);
const gchar* get_dir() const { return _dir.c_str(); }
const gchar* get_file() const { return _file.c_str(); }
const gchar* get_postfix() const;
const gchar* get_path(string& path) const;
public:
static bool is_valid_path(const gchar* path);
static bool is_valid_dir(const gchar* dir);
static const gchar* get_root(const gchar* path);
static const gchar* get_next_node(const gchar* path);
protected:
string _dir;
string _file;
};
typedef unsigned char res;
class resnode
{
public:
struct hash
{
size_t operator()(const resnode& that) const
{ return string_hash(that._key); }
};
struct equal_to
{
bool operator()(const resnode& r1, const resnode& r2) const
{ return string_hash(r1._key) == string_hash(r2._key); }
};
typedef unordered_set<resnode, hash, equal_to> resset;
typedef resset::iterator iterator;
typedef resset::const_iterator const_iterator;
typedef void (*fndestroy)(res*, int);
public:
resnode();
resnode(const gchar* key);
resnode(const resnode& that) { assign(const_cast<resnode&>(that)); }
~resnode() { destroy(); }
void set_destroy(fndestroy del) { _del = del; }
void set_resource(res* ptr, int len) { _res = ptr; _len = len; }
res* get_resource() const { return _res; }
const gchar* get_key() const { return _key.size() ? _key.c_str() : 0; }
void destroy();
void assign(resnode& that);
bool operator<(const resnode& that) const { return _key < that._key; }
iterator begin() { return _subs.begin(); }
const_iterator begin() const { return _subs.end(); }
iterator end() { return _subs.end(); }
const_iterator end() const { return _subs.end(); }
resnode* add(const gchar* key, res* ptr = 0, int len = 0);
resnode* add(resnode* node);
resnode* find(const gchar* key);
const resnode* find(const gchar* key) const;
protected:
string _key;
res* _res;
int _len;
fndestroy _del;
resset _subs;
};
class respack
{
public:
typedef resnode::resset resset;
typedef resnode::iterator iterator;
typedef resnode::const_iterator const_iterator;
typedef resnode::fndestroy fndestroy;
public:
respack(): _root(_t(":")) {}
resnode* get_root() { return &_root; }
const resnode* get_root() const { return &_root; }
resnode* add(const gchar* path) { return add(resvdir(path)); }
resnode* add(const resvdir& vdir) { return add(get_root(), resvdir::get_root(vdir.get_dir()), vdir.get_file()); }
resnode* add(resnode* node, const gchar* dir, const gchar* file);
resnode* find(const gchar* path) { return find(get_root(), resvdir::get_root(path)); }
resnode* find(resnode* node, const gchar* path);
const resnode* find(const gchar* path) const { return find(get_root(), resvdir::get_root(path)); }
const resnode* find(const resnode* node, const gchar* path) const;
resnode* reg(const gchar* path, res* ptr, int len, fndestroy del = 0)
{
if(resnode* node = add(path)) {
node->set_resource(ptr, len);
node->set_destroy(del);
return node;
}
return 0;
}
protected:
resnode _root;
};
extern respack* get_default_respack();
__gslib_end__
#endif
| {
"alphanum_fraction": 0.6594333936,
"avg_line_length": 34.5625,
"ext": "h",
"hexsha": "eea6577e0db2ed21d21aefe7906b0ad825f6a354",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/gslib/res.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/gslib/res.h",
"max_line_length": 118,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/gslib/res.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z",
"num_tokens": 1264,
"size": 4977
} |
/*
Copyright 2010-2011, D. E. Shaw Research.
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.
* Neither the name of D. E. Shaw Research nor the names of its
contributors may 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 __r123_gslmicrorng_dot_h__
#define __r123_gslmicrorng_dot_h__
#include <gsl/gsl_rng.h>
#include <string.h>
/** The macro: GSL_MICRORNG(NAME, CBRNGNAME) is the GSL
analog analog of the C++ r123::MicroURNG template. It declares a gsl_rng
type named gsl_rng_NAME which uses the underlying CBRNGNAME
and can be invoked a limited number of times between calls to NAME_reset.
When the underlying CBRNG's \c ctr_t is an \ref arrayNxW "r123arrayNxW",
and the gsl_rng_NAME may called up to \c N*2^32 times
between calls to \c NAME_reset.
\c NAME_reset takes a gsl_rng_NAME type, a counter and a key as arguments.
It restarts the micro-rng with a new base counter and key.
Note that you must call NAME_reset before the first use
of a gsl_rng. NAME_reset is not called automatically by
gsl_rng_alloc().
@code
#include <Random123/threefry.h>
#include <Random123/gsl_microrng.h> // this file
GSL_MICRORNG(microcbrng, threefry4x64, 20) // creates gsl_rng_microcbrng
int main(int argc, char** argv) {
gsl_rng *r = gsl_rng_alloc(gsl_rng_microcbrng);
threefry4x64_ctr_t c = {{}};
threefry4x64_key_t k = {{}};
for (...) {
c.v[0] = ??; // some application variable
microcbrng_reset(r, c, k);
for (...) {
// gaussian calls r several times. It is safe for
// r to be used upto 2^20 times in this loop
something[i] = gsl_ran_gaussian(r, 1.5);
}
}
}
@endcode
*/
#define GSL_MICRORNG(NAME, CBRNGNAME) \
const gsl_rng_type *gsl_rng_##NAME; \
\
typedef struct{ \
CBRNGNAME##_ctr_t ctr; \
CBRNGNAME##_ctr_t r; \
CBRNGNAME##_key_t key; \
R123_ULONG_LONG n; \
int elem; \
} NAME##_state; \
\
static unsigned long int NAME##_get(void *vstate){ \
NAME##_state *st = (NAME##_state *)vstate; \
const int N=sizeof(st->ctr.v)/sizeof(st->ctr.v[0]); \
if( st->elem == 0 ){ \
CBRNGNAME##_ctr_t c = st->ctr; \
c.v[N-1] |= st->n<<(R123_W(CBRNGNAME##_ctr_t)-32); \
st->n++; \
st->r = CBRNGNAME(c, st->key); \
st->elem = N; \
} \
return 0xffffffff & st->r.v[--st->elem]; \
} \
\
static double \
NAME##_get_double (void * vstate) \
{ \
return NAME##_get (vstate)/4294967296.; \
} \
\
static void NAME##_set(void *vstate, unsigned long int s){ \
NAME##_state *st = (NAME##_state *)vstate; \
st->elem = 0; \
st->n = ~0; /* will abort if _reset is not called */ \
} \
\
static const gsl_rng_type NAME##_type = { \
#NAME, \
0xffffffffUL, \
0, \
sizeof(NAME##_state), \
&NAME##_set, \
&NAME##_get, \
&NAME##_get_double \
}; \
\
R123_STATIC_INLINE void NAME##_reset(const gsl_rng* gr, CBRNGNAME##_ctr_t c, CBRNGNAME##_key_t k) { \
NAME##_state* state = (NAME##_state *)gr->state; \
state->ctr = c; \
state->key = k; \
state->n = 0; \
state->elem = 0; \
} \
\
const gsl_rng_type *gsl_rng_##NAME = &NAME##_type
#endif
| {
"alphanum_fraction": 0.4352272727,
"avg_line_length": 51.7647058824,
"ext": "h",
"hexsha": "370a60d598c1a04d4deb6fffb601d1043ea6c080",
"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": "bf2ae2b575445ed225bba037815a3d90c2218ea7",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "havogt/philox-wrapper",
"max_forks_repo_path": "include/philox-wrapper/external/Random123/gsl_microrng.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bf2ae2b575445ed225bba037815a3d90c2218ea7",
"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": "havogt/philox-wrapper",
"max_issues_repo_path": "include/philox-wrapper/external/Random123/gsl_microrng.h",
"max_line_length": 101,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bf2ae2b575445ed225bba037815a3d90c2218ea7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "havogt/philox-wrapper",
"max_stars_repo_path": "include/philox-wrapper/external/Random123/gsl_microrng.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1308,
"size": 7040
} |
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <gbpLib.h>
#include <gbpRNG.h>
#include <gbpMCMC.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_interp.h>
int generate_MCMC_chain(MCMC_info *MCMC) {
int flag_success;
int i_P, i_DS;
static char format_string[256];
FILE * fp_report_props;
static char filename_report_props[SID_MAX_FILENAME_LENGTH];
static int n_P;
static double * P_new;
static double ** M_new;
static double * P_last;
static double * P_chain;
static double ** M_last;
static double * P_best;
static double * P_limit_min;
static double * P_limit_max;
static RNG_info *RNG;
static int flag_report_props;
static int n_DS;
static int * n_M;
// Initialize a few things on the first call
switch(MCMC->first_chain_call) {
case GBP_TRUE:
n_P = MCMC->n_P;
P_new = MCMC->P_new;
M_new = MCMC->M_new;
P_last = MCMC->P_last;
M_last = MCMC->M_last;
P_chain = MCMC->P_chain;
P_best = MCMC->P_best;
P_limit_min = MCMC->P_limit_min;
P_limit_max = MCMC->P_limit_max;
RNG = MCMC->RNG;
n_DS = MCMC->n_DS;
n_M = MCMC->n_M;
flag_report_props = SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_REPORT_PROPS);
MCMC->first_chain_call = GBP_FALSE;
sprintf(filename_report_props, "%s/chains/report_props_%06d.dat", MCMC->filename_output_dir, MCMC->my_chain);
break;
}
// We need to compute the likelihood of the initial conditions
// if we are just starting a chain
if(MCMC->flag_init_chain)
generate_MCMC_proposition(MCMC, GBP_TRUE);
// Set the last new state to the new last state
MCMC->ln_likelihood_last = MCMC->ln_likelihood_new;
MCMC->ln_Pr_last = MCMC->ln_Pr_new;
memcpy(P_last, P_new, n_P * sizeof(double));
for(i_DS = 0; i_DS < n_DS; i_DS++)
memcpy(M_last[i_DS], M_new[i_DS], n_M[i_DS] * sizeof(double));
// Keep generating parameter sets until the mapping function is satisfied
generate_MCMC_proposition(MCMC, GBP_FALSE);
// Decide if this is a successful proposition or not...
if(MCMC->ln_likelihood_new > MCMC->ln_likelihood_chain) {
MCMC->ln_Pr_new = 0.;
flag_success = GBP_TRUE;
} else if(MCMC->my_chain == SID.My_rank) {
MCMC->ln_Pr_new = MCMC->ln_likelihood_new - MCMC->ln_likelihood_chain;
if((double)random_number(RNG) <= exp(MCMC->ln_Pr_new))
flag_success = GBP_TRUE;
else
flag_success = GBP_FALSE;
}
// fprintf(stderr,"%d %le %d\n",flag_success,MCMC->ln_Pr_new,SID_CHECK_BITFIELD_SWITCH(MCMC->mode,MCMC_MODE_PARALLEL));
// if(!SID_CHECK_BITFIELD_SWITCH(MCMC->mode,MCMC_MODE_PARALLEL))
SID_Bcast(&flag_success, 1, SID_INT, SID_MASTER_RANK, MCMC->comm);
// ... if it is, then update the chain ...
if(flag_success) {
memcpy(P_chain, P_new, (size_t)n_P * sizeof(double));
MCMC->ln_likelihood_chain = MCMC->ln_likelihood_new;
MCMC->ln_Pr_chain = MCMC->ln_Pr_new;
MCMC->n_success++;
} else
MCMC->n_fail++;
MCMC->n_propositions++;
// Report the proposition if asked to
if(flag_report_props && MCMC->my_chain == SID.My_rank) {
fp_report_props = fopen(filename_report_props, "w");
if(flag_success)
fprintf(fp_report_props, "Proposal #%09d: SUCCEEDED\n\n", MCMC->n_propositions);
else
fprintf(fp_report_props, "Proposal #%09d: REJECTED\n\n", MCMC->n_propositions);
sprintf(format_string, " %s = %%13.6le (was %%13.6le) (best is %%13.6le) (flat prior =%%13.6le -> %%13.6le)\n", MCMC->P_name_format);
for(i_P = 0; i_P < n_P; i_P++)
fprintf(fp_report_props, format_string, MCMC->P_names[i_P], P_new[i_P], P_last[i_P], P_best[i_P], P_limit_min[i_P], P_limit_max[i_P]);
fprintf(fp_report_props, "\n");
fprintf(fp_report_props,
"ln(likelihood) =%13.6le+constant (was %13.6le+constant) (best is %13.6le+constant)\n",
MCMC->ln_likelihood_new,
MCMC->ln_likelihood_last,
MCMC->ln_likelihood_best);
fprintf(fp_report_props, "ln(probability)=%13.6le\n", MCMC->ln_Pr_new);
fprintf(fp_report_props, "n_success =%09d\n", MCMC->n_success);
fprintf(fp_report_props, "n_fail =%09d\n", MCMC->n_fail);
fprintf(fp_report_props, "success rate =%.2f %%\n", (double)MCMC->n_success / (double)(MCMC->n_fail + MCMC->n_success) * 100.0);
fclose(fp_report_props);
}
return (flag_success);
}
| {
"alphanum_fraction": 0.5978196234,
"avg_line_length": 42.7542372881,
"ext": "c",
"hexsha": "4671ec55d5c86ed6f8571db334eb29985e850e7c",
"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/gbpMCMC/generate_MCMC_chain.c",
"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/gbpMCMC/generate_MCMC_chain.c",
"max_line_length": 146,
"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/gbpMCMC/generate_MCMC_chain.c",
"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": 1410,
"size": 5045
} |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
int main(int argc, char *argv[]) {
double mu = 1.0;
if (argc > 1)
mu = atof(argv[1]);
int n = 1;
if (argc > 2)
n = atoi(argv[2]);
unsigned long seed;
if (argc > 3)
seed = atol(argv[3]);
else
seed = time(NULL);
gsl_rng_env_setup();
gsl_rng *rng = gsl_rng_alloc(gsl_rng_default);
gsl_rng_set(rng, seed);
for (int i = 0; i < n; i++) {
double x = gsl_ran_exponential(rng, mu);
printf("%.12f\n", x);
}
gsl_rng_free(rng);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.5526717557,
"avg_line_length": 22.5862068966,
"ext": "c",
"hexsha": "696e1222c789c36a59c17a307501c5c5b28e87a6",
"lang": "C",
"max_forks_count": 59,
"max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z",
"max_forks_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "Gjacquenot/training-material",
"max_forks_repo_path": "Math/GSL/RNGs/generate_exp_distr.c",
"max_issues_count": 56,
"max_issues_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d",
"max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "Gjacquenot/training-material",
"max_issues_repo_path": "Math/GSL/RNGs/generate_exp_distr.c",
"max_line_length": 50,
"max_stars_count": 115,
"max_stars_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "Gjacquenot/training-material",
"max_stars_repo_path": "Math/GSL/RNGs/generate_exp_distr.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z",
"num_tokens": 202,
"size": 655
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* #include <cblas.h> */
#include <lapacke_utils.h>
#include <jni.h>
#include "org_bitbucket_ioplus_openblas_Lapacke.h"
/*
* Class: org_bitbucket_ioplus_openblas_Lapacke
* Method: sgetrf
* Signature: (II[FI[I)V
*/
JNIEXPORT void JNICALL Java_org_bitbucket_ioplus_openblas_Lapacke_sgetrf
(JNIEnv * env, jclass class,
jint m, jint n, jfloatArray a, jint lda, jintArray ipiv){
float *A;
A = (*env)->GetPrimitiveArrayCritical(env, a, 0);
int *IPIV;
IPIV = (*env)->GetPrimitiveArrayCritical(env, ipiv, 0);
LAPACKE_sgetrf(LAPACK_ROW_MAJOR,
m, n, A, lda, IPIV);
(*env)->ReleasePrimitiveArrayCritical(env, a, A, 0);
(*env)->ReleasePrimitiveArrayCritical(env, ipiv, IPIV, 0);
}
/*
* Class: org_bitbucket_ioplus_openblas_Lapacke
* Method: sgetri
* Signature: (I[FI[I)V
*/
JNIEXPORT void JNICALL
Java_org_bitbucket_ioplus_openblas_Lapacke_sgetri
(JNIEnv * env, jclass class,
jint n, jfloatArray a, jint lda, jintArray ipiv){
float *A;
A = (*env)->GetPrimitiveArrayCritical(env, a, 0);
int *IPIV;
IPIV = (*env)->GetPrimitiveArrayCritical(env, ipiv, 0);
LAPACKE_sgetri(LAPACK_ROW_MAJOR,
n, A, lda, IPIV);
(*env)->ReleasePrimitiveArrayCritical(env, a, A, 0);
(*env)->ReleasePrimitiveArrayCritical(env, ipiv, IPIV, 0);
}
/*
* Class: org_bitbucket_ioplus_openblas_Lapacke
* Method: sdeev
* Signature: (CCI[FI[F[F[FI[FI)V
*/
JNIEXPORT void JNICALL Java_org_bitbucket_ioplus_openblas_Lapacke_sdeev
(JNIEnv * env, jclass class,
jchar jobvl,
jchar jobvr,
jint n,
jfloatArray a,
jint lda,
jfloatArray wr,
jfloatArray wi,
jfloatArray vl,
jint ldvl,
jfloatArray vr,
jint ldvr){
/* jni args -> c mapping */
float *A;
float *WR;
float *WI;
float *VL;
float *VR;
A = (*env)->GetPrimitiveArrayCritical(env, a, 0);
WR = (*env)->GetPrimitiveArrayCritical(env, wr, 0);
WI = (*env)->GetPrimitiveArrayCritical(env, wi, 0);
VL = (*env)->GetPrimitiveArrayCritical(env, vl, 0);
VR = (*env)->GetPrimitiveArrayCritical(env, vr, 0);
LAPACKE_sgeev(LAPACK_ROW_MAJOR,
jobvl,
jobvr,
n,
A,
lda,
WR, // values
WI,
VL,
ldvl,
VR, // vectors
ldvr);
(*env)->ReleasePrimitiveArrayCritical(env, a, A, 0);
(*env)->ReleasePrimitiveArrayCritical(env, wr, WR, 0);
(*env)->ReleasePrimitiveArrayCritical(env, wi, WI, 0);
(*env)->ReleasePrimitiveArrayCritical(env, vr, VR, 0);
(*env)->ReleasePrimitiveArrayCritical(env, vl, VL, 0);
}
/*
* Class: org_bitbucket_ioplus_openblas_Lapacke
* Method: sgehrd
* Signature: (III[FI[F)V
*/
JNIEXPORT void JNICALL Java_org_bitbucket_ioplus_openblas_Lapacke_sgehrd
(JNIEnv * env, jclass class,
jint n,
jint ilo,
jint ihi,
jfloatArray a,
jint lda,
jfloatArray tau
){
float *A = (*env)->GetPrimitiveArrayCritical(env, a, NULL);
float *TAU = (*env)->GetPrimitiveArrayCritical(env, tau, NULL);
LAPACKE_sgehrd(LAPACK_ROW_MAJOR,n, ilo, ihi, A, lda, TAU);
(*env)->ReleasePrimitiveArrayCritical(env, a, A, 0);
(*env)->ReleasePrimitiveArrayCritical(env, tau, TAU, 0);
}
/*
* Class: org_bitbucket_ioplus_openblas_Lapacke
* Method: shseqr
* Signature: (CCIII[FI[F[F[FI)V
*/
JNIEXPORT void JNICALL Java_org_bitbucket_ioplus_openblas_Lapacke_shseqr
(JNIEnv * env, jclass class,
jchar job,
jchar compz,
jint n,
jint ilo,
jint ihi,
jfloatArray h,
jint ldh,
jfloatArray wr,
jfloatArray wi,
jfloatArray z,
jint ldz){
float *H = (*env)->GetPrimitiveArrayCritical(env, h, 0);
float *WR = (*env)->GetPrimitiveArrayCritical(env, wr, 0);
float *WI = (*env)->GetPrimitiveArrayCritical(env, wi, 0);
float *Z = (*env)->GetPrimitiveArrayCritical(env, z, 0);
LAPACKE_shseqr(LAPACK_ROW_MAJOR,
job,
compz,
n,
ilo,
ihi,
H,
ldh,
WR,
WI,
Z,
ldz);
(*env)->ReleasePrimitiveArrayCritical(env, h, H, 0);
(*env)->ReleasePrimitiveArrayCritical(env, wr, WR, 0);
(*env)->ReleasePrimitiveArrayCritical(env, wi, WI, 0);
(*env)->ReleasePrimitiveArrayCritical(env, z, Z, 0);
}
| {
"alphanum_fraction": 0.6006064544,
"avg_line_length": 25.65,
"ext": "c",
"hexsha": "40b53c567591e9673697bb1afc581c88904c4b70",
"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": "026183a9dae6ffb01f4c2b2b4f185ffa96236057",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sidec/openblas-java",
"max_forks_repo_path": "src/main/c/Lapacke.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "026183a9dae6ffb01f4c2b2b4f185ffa96236057",
"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": "sidec/openblas-java",
"max_issues_repo_path": "src/main/c/Lapacke.c",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "026183a9dae6ffb01f4c2b2b4f185ffa96236057",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sidec/openblas-java",
"max_stars_repo_path": "src/main/c/Lapacke.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1340,
"size": 4617
} |
/*
* Copyright (C) 2018-2020
* HERE Europe B.V.
* Utrecht University (The Netherlands).
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
//
// Created by Wouter Jongeling (wouter.jongeling@gmail.com)
// Modified by Mitra, Aniket on 2019-06-18.
//
/*!
* @file BrownianBridge.h
* @brief
* @authors Aniket Mitra (aniket.mitra@here.com)
* Wouter Jongeling (wouter.jongeling@gmail.com)
*/
#ifndef MOVETK_BROWNIANBRIDGE__H
#define MOVETK_BROWNIANBRIDGE__H
#include <iterator>
#include <cmath>
#include "movetk/utils/Requirements.h"
#include "movetk/utils/Iterators.h"
#include "movetk/geom/trajectory_to_interface.h"
#include "movetk/utils/Iterators.h"
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include "gsl/gsl_min.h"
/*!
* @file AlgorithmTraits.h
* @brief The Brownian Bridge Movement Model (BBMM)
* @authors Aniket Mitra (aniket.mitra@here.com)
*/
/*!
* @brief a collection of algorithms in movetk
*/
namespace movetk_algorithms {
// based on
// https://www.semanticscholar.org/paper/Computational-Movement-Analysis-Using-Brownian-Sijben/c6104979e609e12e1514b8b605a7d14fa6b5d81a
/*!
* @brief a collection of classes for BBMM
*/
namespace brownian_bridge {
/*!
* @struct ParameterTraits
* @brief This traits class serves as a collection of types
* for parameterization of BBMM
* @tparam _GeometryTraits - This class is a collection of movetk
* geometry types. For example @refitem movetk_core::MovetkGeometryKernel
* @tparam TrajectoryIterator - An iterator type.
* For example @refitem TabularTrajectory::TrajectoryIterator
*/
template<class _GeometryTraits, class TrajectoryIterator>
struct ParameterTraits {
typedef _GeometryTraits GeometryTraits;
/*!*
* @typedef ::NT
* @brief typedef of the number type defined in GeometryTraits.
* For example @refitem movetk_core::MovetkGeometryKernel::NT
* */
typedef typename GeometryTraits::NT NT;
/*!*
* @typedef ::Point
* @brief typedef of the point type defined in GeometryTraits.
* For example @refitem movetk_core::MovetkGeometryKernel::MovetkPoint
* */
typedef typename GeometryTraits::MovetkPoint Point;
/*!* @typedef ::Vector
* @brief typedef of the vector type defined in GeometryTraits.
* For example @refitem movetk_core::MovetkGeometryKernel::MovetkVector
* */
typedef typename GeometryTraits::MovetkVector Vector;
/*!* @typedef ::Parameters
*/
typedef std::tuple<Point, Point, NT, TrajectoryIterator, TrajectoryIterator> Parameters;
/*!
* @enum ParameterColumns
*
*/
enum ParameterColumns {
POINT, /*!< global enum value 1 */
MU, /*!< global enum value 1 */
SIGMA_SQUARED, /*!< global enum value 1 */
BEGIN, /*!< global enum value 1 */
END /*!< global enum value 1 */
};
};
/*!
* @class template<class GeometryTraits, class ParameterTraits,
* class Norm, class InputIterator, std::size_t MaxIter> MLE
* @brief The Maximum Likelihood Estimator
* @tparam GeometryTraits - This class is a collection of movetk
* geometry types. For example @refitem movetk_core::MovetkGeometryKernel
* @tparam ParameterTraits - This traits class serves as a collection of types
* for parameterization of BBMM
* @tparam Norm - The type that models Euclidean distance
* For example @refitem movetk_support::FiniteNorm
* @tparam InputIterator - A random access iterator type over a collection of
* tuples where each tuple is a model of type ParameterTraits::Parameters
* @tparam MaxIter - A positive integer that bounds the number of iterations in the MLE
* algorithm
*/
template<class GeometryTraits, class ParameterTraits,
class Norm, class InputIterator, std::size_t MaxIter,
typename = movetk_core::requires_random_access_iterator<InputIterator>,
typename = movetk_core::requires_tuple<
typename InputIterator::value_type>,
typename = movetk_core::requires_tuple_element_as_movetk_point<GeometryTraits,
ParameterTraits::ParameterColumns::POINT,
typename InputIterator::value_type>,
typename = movetk_core::requires_tuple_element_as_movetk_point<GeometryTraits,
ParameterTraits::ParameterColumns::MU,
typename InputIterator::value_type>,
typename = movetk_core::requires_tuple_element_as_NT<GeometryTraits,
ParameterTraits::ParameterColumns::SIGMA_SQUARED,
typename InputIterator::value_type>>
class MLE {
private:
typedef typename GeometryTraits::NT NT;
const gsl_min_fminimizer_type *T = gsl_min_fminimizer_goldensection;
gsl_min_fminimizer *s = gsl_min_fminimizer_alloc(T);
gsl_function F;
NT estimated_parameter;
std::size_t iter = 0, status;
struct fn_params {
InputIterator first;
InputIterator beyond;
};
static double fn(double sigma_squared, void *p) {
Norm norm;
struct fn_params *params = (fn_params *) p;
InputIterator it = params->first;
NT log_likelihood = 0;
while (it != params->beyond) {
typename GeometryTraits::MovetkVector v = std::get<ParameterTraits::ParameterColumns::POINT>(*it)
- std::get<ParameterTraits::ParameterColumns::MU>(*it);
NT operand1 = -LOG_TWO_PI - log(static_cast<NT>(sigma_squared));
NT operand2 = -norm(v) / (2 * sigma_squared);
log_likelihood += operand1 + operand2;
it++;
}
return -1 * log_likelihood;
}
void operator()(InputIterator first, InputIterator beyond,
NT result, NT x_lower, NT x_upper, NT eps) {
struct fn_params params;
params.first = first;
params.beyond = beyond;
F.function = &MLE::fn;
F.params = ¶ms;
status = gsl_min_fminimizer_set(s, &F, result, x_lower, x_upper);
do {
iter++;
status = gsl_min_fminimizer_iterate(s);
result = gsl_min_fminimizer_x_minimum(s);
x_lower = gsl_min_fminimizer_x_lower(s);
x_upper = gsl_min_fminimizer_x_upper(s);
status = gsl_min_test_interval(x_lower, x_upper, eps, 0.0);
if (status == GSL_SUCCESS) {
estimated_parameter = result;
break;
}
} while (status == GSL_CONTINUE && iter < MaxIter);
if (iter >= MaxIter)
estimated_parameter = result;
}
public:
/*!
*
* @param first
* @param beyond
* @param result
* @param x_lower
* @param x_upper
* @param eps
*/
MLE(InputIterator first, InputIterator beyond,
NT result, NT x_lower, NT x_upper, NT eps) {
Norm norm;
std::size_t num_elements = std::distance(first, beyond);
if (num_elements == 1) {
typename GeometryTraits::MovetkVector v = std::get<ParameterTraits::ParameterColumns::POINT>(*first)
- std::get<ParameterTraits::ParameterColumns::MU>(*first);
NT l = norm(v);
if (l < MOVETK_EPS) {
estimated_parameter = MOVETK_EPS;
return;
}
}
(*this)(first, beyond, result, x_lower, x_upper, eps);
}
/*!
*
* @param first
* @param beyond
*/
MLE(InputIterator first, InputIterator beyond) {
Norm norm;
InputIterator it = first;
NT upper_bound = 0, squared_length = 0;
std::size_t num_elements = std::distance(first, beyond);
if (num_elements == 1) {
typename GeometryTraits::MovetkVector v = std::get<ParameterTraits::ParameterColumns::POINT>(*first)
- std::get<ParameterTraits::ParameterColumns::MU>(*first);
NT l = norm(v);
if (l < MOVETK_EPS) {
estimated_parameter = MOVETK_EPS;
return;
}
}
while (it != beyond) {
typename GeometryTraits::MovetkVector v = std::get<ParameterTraits::ParameterColumns::POINT>(*it)
- std::get<ParameterTraits::ParameterColumns::MU>(*it);
NT l = norm(v);
squared_length += l;
if (l > upper_bound)
upper_bound = l;
it++;
}
NT initial_estimate = squared_length / (2 * num_elements);
(*this)(first, beyond, initial_estimate, MOVETK_EPS, upper_bound, MOVETK_EPS);
}
/*!
*
* @return
*/
NT operator()() {
return estimated_parameter;
}
/*!
*
*/
~MLE() {
gsl_min_fminimizer_free(s);
}
};
/*!
*
* @tparam GeometryTraits
* @tparam ProbeTraits
* @tparam ParameterTraits
* @tparam Norm
* @tparam GeoProjection
*/
template<class GeometryTraits, class ProbeTraits, class ParameterTraits, class Norm,
class GeoProjection>
class Model {
private:
typedef typename GeometryTraits::NT NT;
typedef typename GeometryTraits::MovetkPoint Point;
typedef typename GeometryTraits::MovetkVector Vector;
movetk_core::MakePoint<GeometryTraits> make_point;
NT joint_log_likelihood = 0;
Point mean(Point &p1, Point &p2, NT alpha) {
Vector v = p2 - p1;
v *= alpha;
return (p1 + v);
}
public:
/*!
*
* @tparam TrajectoryIterator
* @tparam OutputIterator
* @param first
* @param beyond
* @param result
*/
template<class TrajectoryIterator, class OutputIterator,
typename = movetk_core::requires_random_access_iterator<TrajectoryIterator>,
typename = movetk_core::requires_tuple<
typename TrajectoryIterator::value_type>,
typename = movetk_core::requires_tuple_element_as_arithmetic<
ProbeTraits::ProbeColumns::LAT, typename TrajectoryIterator::value_type>,
typename = movetk_core::requires_tuple_element_as_arithmetic<
ProbeTraits::ProbeColumns::LON, typename TrajectoryIterator::value_type>,
typename = movetk_core::requires_tuple_element_as_size_t<
ProbeTraits::ProbeColumns::SAMPLE_DATE, typename TrajectoryIterator::value_type>,
typename = movetk_core::requires_output_iterator<OutputIterator>,
typename = movetk_core::requires_tuple<
typename OutputIterator::value_type>,
typename = movetk_core::requires_tuple_element_as_movetk_point<GeometryTraits,
ParameterTraits::ParameterColumns::POINT,
typename OutputIterator::value_type>,
typename = movetk_core::requires_tuple_element_as_movetk_point<GeometryTraits,
ParameterTraits::ParameterColumns::MU,
typename OutputIterator::value_type>,
typename = movetk_core::requires_tuple_element_as_NT<GeometryTraits,
ParameterTraits::ParameterColumns::SIGMA_SQUARED,
typename OutputIterator::value_type>>
Model(TrajectoryIterator first, TrajectoryIterator beyond, OutputIterator result) {
auto reflat = std::get<ProbeTraits::ProbeColumns::LAT>(*first);
auto reflon = std::get<ProbeTraits::ProbeColumns::LON>(*first);
GeoProjection ref(reflat, reflon);
TrajectoryIterator tit = first;
std::size_t NumPoints = std::distance(first, beyond);
if (NumPoints == 1) {
auto lat = std::get<ProbeTraits::ProbeColumns::LAT>(*first);
auto lon = std::get<ProbeTraits::ProbeColumns::LON>(*first);
auto projected_point = ref.project(lat, lon);
Point p1 = make_point(std::cbegin(projected_point), std::cend(projected_point));
*result = std::make_tuple(p1, p1, 0, first, first);
return;
}
std::size_t multiple = (NumPoints - 1) / 2;
std::size_t remainder = (NumPoints - 1) % 2;
TrajectoryIterator last = first + 2 * multiple;
while (tit != last) {
auto lat = std::get<ProbeTraits::ProbeColumns::LAT>(*tit);
auto lon = std::get<ProbeTraits::ProbeColumns::LON>(*tit);
auto projected_point = ref.project(lat, lon);
Point p1 = make_point(std::cbegin(projected_point), std::cend(projected_point));
lat = std::get<ProbeTraits::ProbeColumns::LAT>(*(tit + 1));
lon = std::get<ProbeTraits::ProbeColumns::LON>(*(tit + 1));
projected_point = ref.project(lat, lon);
Point p2 = make_point(std::cbegin(projected_point), std::cend(projected_point));
lat = std::get<ProbeTraits::ProbeColumns::LAT>(*(tit + 2));
lon = std::get<ProbeTraits::ProbeColumns::LON>(*(tit + 2));
projected_point = ref.project(lat, lon);
Point p3 = make_point(std::cbegin(projected_point), std::cend(projected_point));
auto ts1 = std::get<ProbeTraits::ProbeColumns::SAMPLE_DATE>(*tit);
auto ts2 = std::get<ProbeTraits::ProbeColumns::SAMPLE_DATE>(*(tit + 1));
auto ts3 = std::get<ProbeTraits::ProbeColumns::SAMPLE_DATE>(*(tit + 2));
NT alpha = static_cast<NT>( ts3 - ts2 ) / static_cast<NT>( ts3 - ts1 );
Point mu = mean(p1, p3, alpha);
*result = std::make_tuple(p2, mu, 0, tit, tit + 2);
tit += 2;
}
if (remainder == 1) {
auto lat = std::get<ProbeTraits::ProbeColumns::LAT>(*last);
auto lon = std::get<ProbeTraits::ProbeColumns::LON>(*last);
auto projected_point = ref.project(lat, lon);
Point p1 = make_point(std::cbegin(projected_point), std::cend(projected_point));
lat = std::get<ProbeTraits::ProbeColumns::LAT>(*(last + 1));
lon = std::get<ProbeTraits::ProbeColumns::LON>(*(last + 1));
projected_point = ref.project(lat, lon);
Point p2 = make_point(std::cbegin(projected_point), std::cend(projected_point));
Point mu = mean(p1, p2, 0.5);
*result = std::make_tuple(mu, mu, 0, last, last + 1);
}
}
};
/*!
*
* @tparam GeometryTraits
* @tparam ParameterTraits
*/
template<class GeometryTraits, class ParameterTraits>
class ParameterSelector {
std::size_t SIZE;
public:
/*!
*
* @param size
*/
ParameterSelector(std::size_t size) : SIZE(size) {}
/*!
*
* @tparam InputIterator
* @tparam OutputIterator
* @param first
* @param beyond
* @param result
*/
template<class InputIterator, class OutputIterator,
typename = movetk_core::requires_random_access_iterator<InputIterator>,
typename = movetk_core::requires_output_iterator<OutputIterator>,
typename = movetk_core::requires_tuple<typename InputIterator::value_type>,
typename = movetk_core::requires_tuple_element_as_NT<GeometryTraits,
ParameterTraits::ParameterColumns::SIGMA_SQUARED,
typename InputIterator::value_type>,
typename = movetk_core::requires_NT<GeometryTraits,
typename OutputIterator::value_type >>
void operator()(InputIterator first, InputIterator beyond, OutputIterator result) {
assert(std::distance(first, beyond) >= SIZE);
std::vector<typename ParameterTraits::NT> coeffs;
std::transform(first, beyond, std::back_inserter(coeffs), [](auto a) {
return std::get<ParameterTraits::ParameterColumns::SIGMA_SQUARED>(a);
});
std::sort(std::begin(coeffs), std::end(coeffs));
std::size_t coeff_interval = std::distance(first, beyond) / SIZE;
for (std::size_t i = 0; i < SIZE; i++) {
std::size_t index = coeff_interval / 2 + coeff_interval * i;
*result = coeffs[index];
}
}
};
template<class GeometryTraits, class ParameterTraits, class Norm>
class LogLikelihood {
typedef typename GeometryTraits::NT NT;
typedef typename ParameterTraits::Parameters Parameters;
public:
LogLikelihood() = default;
template<class InputIterator, class OutputIterator,
typename = movetk_core::requires_random_access_iterator<InputIterator>,
typename = movetk_core::requires_output_iterator<OutputIterator>,
typename = movetk_core::requires_NT<GeometryTraits,
typename InputIterator::value_type>,
typename = movetk_core::requires_NT<GeometryTraits,
typename OutputIterator::value_type >>
void operator()(const Parameters ¶ms, InputIterator first,
InputIterator beyond, OutputIterator result) {
Norm norm;
typename GeometryTraits::MovetkVector v = std::get<ParameterTraits::ParameterColumns::POINT>(params)
- std::get<ParameterTraits::ParameterColumns::MU>(params);
InputIterator pit = first;
NT squared_length = norm(v);
while (pit != beyond) {
NT operand1 = -LOG_TWO_PI - log(*pit);
NT operand2 = -squared_length / (2 * (*pit));
NT log_likelihood = operand1 + operand2;
*result = log_likelihood;
pit++;
}
}
NT operator()(const Parameters ¶ms, NT sigma_squared) {
Norm norm;
typename GeometryTraits::MovetkVector v = std::get<ParameterTraits::ParameterColumns::POINT>(params)
- std::get<ParameterTraits::ParameterColumns::MU>(params);
NT squared_length = norm(v);
NT operand1 = -LOG_TWO_PI - log(sigma_squared);
NT operand2 = -squared_length / (2 * sigma_squared);
return (operand1 + operand2);
}
};
}
}
#endif //MOVETK_BROWNIANBRIDGE__H
| {
"alphanum_fraction": 0.5398099456,
"avg_line_length": 43.356,
"ext": "h",
"hexsha": "6a855a1514a42dfff0c0ab49589cfc48f620483e",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2021-09-11T02:27:00.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-05T21:40:07.000Z",
"max_forks_repo_head_hexsha": "cdf0c98121da6df4cadbd715fba02b05be724218",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "aniketmitra001/movetk",
"max_forks_repo_path": "src/include/movetk/algo/BrownianBridge.h",
"max_issues_count": 44,
"max_issues_repo_head_hexsha": "acbc9c5acb69dd3eb23aa7d2156ede02ed468eae",
"max_issues_repo_issues_event_max_datetime": "2021-04-08T23:56:19.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-09-11T17:40:30.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "bacusters/movetk",
"max_issues_repo_path": "src/include/movetk/algo/BrownianBridge.h",
"max_line_length": 139,
"max_stars_count": 53,
"max_stars_repo_head_hexsha": "8d261f19538e28ff36cac98a89ef067f8c26f978",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "hiteshbedre/movetk",
"max_stars_repo_path": "src/include/movetk/algo/BrownianBridge.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-05T10:04:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-09T19:52:17.000Z",
"num_tokens": 4397,
"size": 21678
} |
/* rng/knuthran2002.c
*
* Copyright (C) 2007 Brian Gough
* Copyright (C) 2001 Brian Gough, Carlo Perassi
*
* 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.
*/
/*
* This generator is taken from
*
* Donald E. Knuth, The Art of Computer Programming, Volume 2, Section 3.6
* Third Edition, Addison-Wesley,
*
* The modifications introduced in the 9th printing (2002) are
* included here; there's no backwards compatibility with the
* original. [ see http://www-cs-faculty.stanford.edu/~knuth/taocp.html ]
*
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#define BUFLEN 1009 /* length of the buffer aa[] */
#define KK 100 /* the long lag */
#define LL 37 /* the short lag */
#define MM (1L << 30) /* the modulus */
#define TT 70 /* guaranteed separation between streams */
#define is_odd(x) ((x) & 1) /* the units bit of x */
#define mod_diff(x, y) (((x) - (y)) & (MM - 1)) /* (x - y) mod MM */
static inline void ran_array (long int aa[], unsigned int n,
long int ran_x[]);
static inline unsigned long int ran_get (void *vstate);
static double ran_get_double (void *vstate);
static void ran_set (void *state, unsigned long int s);
typedef struct
{
unsigned int i;
long int aa[BUFLEN];
long int ran_x[KK]; /* the generator state */
}
ran_state_t;
static inline void
ran_array (long int aa[], unsigned int n, long int ran_x[])
{
unsigned int i;
unsigned int j;
for (j = 0; j < KK; j++)
aa[j] = ran_x[j];
for (; j < n; j++)
aa[j] = mod_diff (aa[j - KK], aa[j - LL]);
for (i = 0; i < LL; i++, j++)
ran_x[i] = mod_diff (aa[j - KK], aa[j - LL]);
for (; i < KK; i++, j++)
ran_x[i] = mod_diff (aa[j - KK], ran_x[i - LL]);
}
static inline unsigned long int
ran_get (void *vstate)
{
ran_state_t *state = (ran_state_t *) vstate;
unsigned int i = state->i;
unsigned long int v;
if (i == 0)
{
/* fill buffer with new random numbers */
ran_array (state->aa, BUFLEN, state->ran_x);
}
v = state->aa[i];
state->i = (i + 1) % KK;
return v;
}
static double
ran_get_double (void *vstate)
{
ran_state_t *state = (ran_state_t *) vstate;
return ran_get (state) / 1073741824.0; /* RAND_MAX + 1 */
}
static void
ran_set (void *vstate, unsigned long int s)
{
ran_state_t *state = (ran_state_t *) vstate;
long x[KK + KK - 1]; /* the preparation buffer */
register int j;
register int t;
register long ss;
if (s == 0 )
s = 314159; /* default seed used by Knuth */
ss = (s + 2)&(MM-2);
for (j = 0; j < KK; j++)
{
x[j] = ss; /* bootstrap the buffer */
ss <<= 1;
if (ss >= MM) /* cyclic shift 29 bits */
ss -= MM - 2;
}
x[1]++; /* make x[1] (and only x[1]) odd */
ss = s & (MM - 1);
t = TT - 1;
while (t)
{
for (j = KK - 1; j > 0; j--) /* square */
{
x[j + j] = x[j];
x[j + j - 1] = 0;
}
for (j = KK + KK - 2; j >= KK; j--)
{
x[j - (KK - LL)] = mod_diff (x[j - (KK - LL)], x[j]);
x[j - KK] = mod_diff (x[j - KK], x[j]);
}
if (is_odd (ss))
{ /* multiply by "z" */
for (j = KK; j > 0; j--)
{
x[j] = x[j - 1];
}
x[0] = x[KK]; /* shift the buffer cyclically */
x[LL] = mod_diff (x[LL], x[KK]);
}
if (ss)
ss >>= 1;
else
t--;
}
for (j = 0; j < LL; j++)
state->ran_x[j + KK - LL] = x[j];
for (; j < KK; j++)
state->ran_x[j - LL] = x[j];
for (j = 0; j< 10; j++)
ran_array(x, KK+KK-1, state->ran_x); /* warm things up */
state->i = 0;
return;
}
static const gsl_rng_type ran_type = {
"knuthran2002", /* name */
0x3fffffffUL, /* RAND_MAX = (2 ^ 30) - 1 */
0, /* RAND_MIN */
sizeof (ran_state_t),
&ran_set,
&ran_get,
&ran_get_double
};
const gsl_rng_type *gsl_rng_knuthran2002 = &ran_type;
| {
"alphanum_fraction": 0.5362556329,
"avg_line_length": 25.6947368421,
"ext": "c",
"hexsha": "838b351f61f86e14850720b2dbc8885d08230d7c",
"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/rng/knuthran2002.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/rng/knuthran2002.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/rng/knuthran2002.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": 1468,
"size": 4882
} |
/**
*
* @file qwrapper_zlacpy.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Julien Langou
* @author Henricus Bouwmeester
* @author Mathieu Faverge
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_zlacpy(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int m, int n, int nb,
const PLASMA_Complex64_t *A, int lda,
PLASMA_Complex64_t *B, int ldb)
{
DAG_CORE_LACPY;
QUARK_Insert_Task(quark, CORE_zlacpy_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, B, OUTPUT,
sizeof(int), &ldb, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlacpy_quark = PCORE_zlacpy_quark
#define CORE_zlacpy_quark PCORE_zlacpy_quark
#endif
void CORE_zlacpy_quark(Quark *quark)
{
PLASMA_enum uplo;
int M;
int N;
const PLASMA_Complex64_t *A;
int LDA;
PLASMA_Complex64_t *B;
int LDB;
quark_unpack_args_7(quark, uplo, M, N, A, LDA, B, LDB);
LAPACKE_zlacpy_work(
LAPACK_COL_MAJOR,
lapack_const(uplo),
M, N, A, LDA, B, LDB);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_zlacpy_f1(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int m, int n, int nb,
const PLASMA_Complex64_t *A, int lda,
PLASMA_Complex64_t *B, int ldb,
PLASMA_Complex64_t *fake1, int szefake1, int flag1)
{
DAG_CORE_LACPY;
if ( fake1 == B ) {
QUARK_Insert_Task(quark, CORE_zlacpy_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, B, OUTPUT | flag1,
sizeof(int), &ldb, VALUE,
0);
}
else {
QUARK_Insert_Task(quark, CORE_zlacpy_f1_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, B, OUTPUT,
sizeof(int), &ldb, VALUE,
sizeof(PLASMA_Complex64_t)*szefake1, fake1, flag1,
0);
}
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlacpy_f1_quark = PCORE_zlacpy_f1_quark
#define CORE_zlacpy_f1_quark PCORE_zlacpy_f1_quark
#endif
void CORE_zlacpy_f1_quark(Quark *quark)
{
PLASMA_enum uplo;
int M;
int N;
const PLASMA_Complex64_t *A;
int LDA;
PLASMA_Complex64_t *B;
int LDB;
void *fake1;
quark_unpack_args_8(quark, uplo, M, N, A, LDA, B, LDB, fake1);
LAPACKE_zlacpy_work(
LAPACK_COL_MAJOR,
lapack_const(uplo),
M, N, A, LDA, B, LDB);
}
| {
"alphanum_fraction": 0.4874236874,
"avg_line_length": 33.0241935484,
"ext": "c",
"hexsha": "affaaa47ba0e0b0a1359b09d07bb7604cb433f54",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas-qwrapper/qwrapper_zlacpy.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas-qwrapper/qwrapper_zlacpy.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-qwrapper/qwrapper_zlacpy.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1110,
"size": 4095
} |
/* Copyright (c) 2011-2012, Jérémy Fix. 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. */
/* * None of the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. */
/* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE */
/* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL */
/* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */
/* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */
/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */
/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#define DEBUGMODE true
#ifndef UKF_SR_STATE_NDIM_H
#define UKF_SR_STATE_NDIM_H
#include <gsl/gsl_linalg.h> // For the Cholesky decomposition
#include <gsl/gsl_math.h>
#include <gsl/gsl_blas.h>
#include "ukf_types.h"
#include "ukf_math.h"
void print_mat(const gsl_matrix * A)
{
for(unsigned int i = 0 ; i < A->size1 ; ++i)
{
for(unsigned int j = 0 ; j < A ->size2 ; ++j)
printf("%e ", gsl_matrix_get(A,i,j));
printf("\n");
}
}
void print_vec(const gsl_vector * A)
{
for(unsigned int i = 0 ; i < A->size ; ++i)
{
printf("%e ", gsl_vector_get(A,i));
}
printf("\n");
}
namespace ukf
{
/**
* @short MUST NOT BE USED !!!!!!! Square root UKF for state estimation, additive noise case
* The notations follow "Sigma-Point Kalman Filters for Probabilistic Inference in Dynamic State-Space Models",p115, PhD, van Der Merwe
*/
namespace srstate
{
/**
* @short Allocation of the vectors/matrices and initialization
*
*/
void ukf_init(ukf_param &p, ukf_state &s)
{
// Parameters for the sigma points of the process equation
p.nbSamples = 2 * p.n + 1;
p.lambda = p.alpha * p.alpha * (p.n + p.kpa) - p.n;
p.gamma = sqrt(p.n + p.lambda);
// Parameters for the sigma points of the observation equation
p.nbSamplesMeasure = 4 * p.n + 1;
p.lambda_aug = p.alpha * p.alpha * (2*p.n + p.kpa) - 2*p.n;
p.gamma_aug = sqrt(2*p.n + p.lambda_aug);
// Init the matrices used to iterate
s.xi = gsl_vector_alloc(p.n);
gsl_vector_set_zero(s.xi);
// Images of the sigma points
s.xi_prediction = gsl_matrix_alloc(p.n, p.nbSamples);
gsl_matrix_set_zero(s.xi_prediction);
s.xi_mean = gsl_vector_alloc(p.n);
gsl_vector_set_zero(s.xi_mean);
// Cholesky factor of the variance/covariance matrix Pxxi
s.Sxi = gsl_matrix_alloc(p.n,p.n);
gsl_matrix_set_identity(s.Sxi);
gsl_matrix_scale(s.Sxi, sqrt(p.prior_x));
// Cholesky factor of the variance/covariance matrix of the process noise
s.Svi = gsl_matrix_alloc(p.n,p.n);
gsl_matrix_set_identity(s.Svi);
gsl_matrix_scale(s.Svi, sqrt(p.process_noise));
s.yi_prediction = gsl_matrix_alloc(p.no, p.nbSamplesMeasure);
gsl_matrix_set_zero(s.yi_prediction);
s.yi_mean = gsl_vector_alloc(p.no);
gsl_vector_set_zero(s.yi_mean);
s.ino_yi = gsl_vector_alloc(p.no);
gsl_vector_set_zero(s.ino_yi);
// Cholesky factor of the variance/covariance matrix Pyyi
s.Syi = gsl_matrix_alloc(p.no, p.no);
gsl_matrix_set_zero(s.Syi);
s.Sni = gsl_matrix_alloc(p.no,p.no);
gsl_matrix_set_identity(s.Sni);
gsl_matrix_scale(s.Sni, sqrt(p.measurement_noise));
s.Pxyi = gsl_matrix_alloc(p.n, p.no);
gsl_matrix_set_zero(s.Pxyi);
s.sigmaPoint = gsl_vector_alloc(p.n);
gsl_vector_set_zero(s.sigmaPoint);
s.sigmaPoints = gsl_matrix_alloc(p.n, p.nbSamples);
gsl_matrix_set_zero(s.sigmaPoints);
s.sigmaPointMeasure = gsl_vector_alloc(p.n);
gsl_vector_set_zero(s.sigmaPoint);
s.sigmaPointsMeasure = gsl_matrix_alloc(p.n, p.nbSamplesMeasure);
gsl_matrix_set_zero(s.sigmaPointsMeasure);
s.U = gsl_matrix_alloc(p.n, p.no);
gsl_matrix_set_zero(s.U);
// Weights used to update the statistics
s.wm_j = gsl_vector_alloc(p.nbSamples); // Weights used to compute the mean of the sigma points images
s.wc_j = gsl_vector_alloc(p.nbSamples); // Weights used to update the covariance matrices
// Set the weights
gsl_vector_set(s.wm_j, 0, p.lambda / (p.n + p.lambda));
gsl_vector_set(s.wc_j, 0, p.lambda / (p.n + p.lambda) + (1.0 - p.alpha*p.alpha + p.beta));
for(int j = 1 ; j < p.nbSamples; j ++)
{
gsl_vector_set(s.wm_j, j, 1.0 / (2.0 * (p.n + p.lambda)));
gsl_vector_set(s.wc_j, j, 1.0 / (2.0 * (p.n + p.lambda)));
}
// Set the weights
s.wm_aug_j = gsl_vector_alloc(p.nbSamplesMeasure); // Weights used to compute the mean of the sigma points images
s.wc_aug_j = gsl_vector_alloc(p.nbSamplesMeasure); // Weights used to update the covariance matrices
gsl_vector_set(s.wm_aug_j, 0, p.lambda_aug / (2*p.n + p.lambda_aug));
gsl_vector_set(s.wc_aug_j, 0, p.lambda_aug / (2*p.n + p.lambda_aug) + (1.0 - p.alpha*p.alpha + p.beta));
for(int j = 1 ; j < p.nbSamplesMeasure; j ++)
{
gsl_vector_set(s.wm_aug_j, j, 1.0 / (2.0 * (2*p.n + p.lambda_aug)));
gsl_vector_set(s.wc_aug_j, j, 1.0 / (2.0 * (2*p.n + p.lambda_aug)));
}
s.Ki = gsl_matrix_alloc(p.n, p.no);
s.Ki_T = gsl_matrix_alloc(p.no, p.n);
// Allocate temporary matrices
s.temp_n = gsl_vector_alloc(p.n);
s.temp_no = gsl_vector_alloc(p.no);
s.temp_n_1 = gsl_matrix_alloc(p.n,1);
s.temp_1_n = gsl_matrix_alloc(1,p.n);
s.temp_n_n = gsl_matrix_alloc(p.n, p.n);
s.temp_n_no = gsl_matrix_alloc(p.n, p.no);
s.temp_no_1 = gsl_matrix_alloc(p.no,1);
s.temp_1_no = gsl_matrix_alloc(1,p.no);
s.temp_no_no = gsl_matrix_alloc(p.no, p.no);
s.temp_3n_n = gsl_matrix_alloc(3*p.n, p.n);
s.temp_2nno_no = gsl_matrix_alloc(2*p.n + p.no, p.no);
}
/**
* @short Free of memory allocation
*
*/
void ukf_free(ukf_param &p, ukf_state &s)
{
gsl_vector_free(s.xi);
gsl_matrix_free(s.xi_prediction);
gsl_vector_free(s.xi_mean);
gsl_matrix_free(s.Sxi);
gsl_matrix_free(s.Svi);
gsl_matrix_free(s.yi_prediction);
gsl_vector_free(s.yi_mean);
gsl_vector_free(s.ino_yi);
gsl_matrix_free(s.Syi);
gsl_matrix_free(s.Sni);
gsl_matrix_free(s.Pxyi);
gsl_vector_free(s.sigmaPoint);
gsl_matrix_free(s.sigmaPoints);
gsl_vector_free(s.sigmaPointMeasure);
gsl_matrix_free(s.sigmaPointsMeasure);
gsl_matrix_free(s.U);
gsl_vector_free(s.wm_j);
gsl_vector_free(s.wc_j);
gsl_vector_free(s.wm_aug_j);
gsl_vector_free(s.wc_aug_j);
gsl_matrix_free(s.Ki);
gsl_matrix_free(s.Ki_T);
gsl_vector_free(s.temp_n);
gsl_vector_free(s.temp_no);
gsl_matrix_free(s.temp_n_1);
gsl_matrix_free(s.temp_1_n);
gsl_matrix_free(s.temp_n_n);
gsl_matrix_free(s.temp_n_no);
gsl_matrix_free(s.temp_no_1);
gsl_matrix_free(s.temp_1_no);
gsl_matrix_free(s.temp_no_no);
gsl_matrix_free(s.temp_3n_n);
gsl_matrix_free(s.temp_2nno_no);
}
/**
* @short UKF-additive (zero-mean) noise case, "Kalman Filtering and Neural Networks", p.233
*
*/
template <typename FunctProcess, typename FunctObservation>
void ukf_iterate(ukf_param &p, ukf_state &s, FunctProcess f, FunctObservation h, gsl_vector* yi)
{
int i,j;
gsl_matrix_view mat_view;
gsl_vector_view vec_view;
// ************************************************** //
// ************ Compute the sigma points ************ //
// ************************************************** //
// 1- Compute the sigma points,
// Equation (3.209)
// sigmapoint_j = x_(i-1)
// sigmapoint_j = x_(i-1) + gamma * Sxi_j for 1 <= j <= n
// sigmapoint_j = x_(i-1) - gamma * Sxi_(j-(n+1)) for n+1 <= j <= 2n
gsl_matrix_set_col(s.sigmaPoints, 0, s.xi);
for(j = 1 ; j < p.n + 1 ; ++j)
for(i = 0 ; i < p.n ; ++i)
{
gsl_matrix_set(s.sigmaPoints,i,j, s.xi->data[i] + p.gamma * gsl_matrix_get(s.Sxi, i, j-1));
gsl_matrix_set(s.sigmaPoints,i,j+p.n, s.xi->data[i] - p.gamma * gsl_matrix_get(s.Sxi, i, j-1));
}
/**********************************/
/***** Time update equations *****/
/**********************************/
// Time update equations
// 0 - Compute the image of the sigma points and the mean of these images
gsl_vector_set_zero(s.xi_mean);
for(j = 0 ; j < p.nbSamples ; ++j)
{
gsl_matrix_get_col(s.sigmaPoint, s.sigmaPoints, j);
// Compute the image of the sigma points
// Eq 3.210
vec_view = gsl_matrix_column(s.xi_prediction,j);
f(s.params, s.sigmaPoint, &vec_view.vector);
// Update the mean, Eq (3.211)
for(i = 0 ; i < p.n ; ++i)
s.xi_mean->data[i] += s.wm_j->data[j] * gsl_matrix_get(s.xi_prediction,i,j);
}
// 1- Compute the QR decomposition and keeps only the upper triangular part of R
// Eq. 3.212
// We first fill the matrix Sxk^-
// with the transpose of what is in the brackets of qr { ... }
for(j = 1 ; j < p.nbSamples; ++j)
{
for(i = 0 ; i < p.n ; ++i)
{
gsl_matrix_set(s.temp_3n_n, j-1, i, sqrt(s.wc_j->data[1]) * (gsl_matrix_get(s.xi_prediction,i,j) - s.xi_mean->data[i]));
}
}
// The last rows are filled with the cholesky factor of the process noise covariance
for(j = 0 ; j < p.n ; ++j)
{
mat_view = gsl_matrix_submatrix(s.temp_3n_n, p.nbSamples-1, 0, p.n, p.n);
gsl_matrix_memcpy(&mat_view.matrix, s.Svi);
}
// We now perform the QR decomposition of s.temp_3n_n;
gsl_linalg_QR_decomp(s.temp_3n_n, s.temp_n);
// From this QR decomposition, we keep only the upper triangular part of R and copy it in s.Sxi
for( j = 0 ; j < p.n ; ++j)
{
for(i = 0 ; i < j+1 ; ++i)
gsl_matrix_set(s.Sxi, i, j, gsl_matrix_get(s.temp_3n_n, i, j));
for(i = j+1 ; i < p.n ; ++i)
gsl_matrix_set(s.Sxi, i, j, 0.0);
}
//gsl_matrix_transpose(s.Sxi);
if(DEBUGMODE) print_mat(s.Sxi);
if(DEBUGMODE) printf("\n");
// 2- Perform the cholupdate, which is a rank one update
// Eq. 3.213
for(i = 0 ; i < p.n ; ++i)
s.temp_n->data[i] = gsl_matrix_get(s.xi_prediction,i,0) - s.xi_mean->data[i];
if(DEBUGMODE) printf("Before cholupdate 1 \n");
gsl_matrix_transpose(s.Sxi);
ukf::math::choleskyUpdate(s.Sxi, ukf::math::signof(s.wc_j->data[0]) * sqrt(fabs(s.wc_j->data[0])), s.temp_n);
// Warning : Here, we keep Sxi as a triangular inferior matrix
//gsl_matrix_transpose(s.Sxi);
if(DEBUGMODE) printf("ok\n");
if(DEBUGMODE) printf("Sxi after cholupdate : \n");
if(DEBUGMODE) print_mat(s.Sxi);
// ** Augment the sigma points ** //
// Eq 3.124
// 1 - Copy the images of the original sigma points
mat_view = gsl_matrix_submatrix(s.sigmaPointsMeasure,0,0, p.n, p.nbSamples);
gsl_matrix_memcpy(&mat_view.matrix, s.xi_prediction);
// 2 - Compute the additional sigma points
for(j = 0 ; j < p.n ; ++j)
{
for(i = 0 ; i < p.n ; ++i)
{
gsl_matrix_set(s.sigmaPointsMeasure, i ,j + p.nbSamples , gsl_matrix_get(s.xi_prediction, i, 0) + p.gamma_aug * gsl_matrix_get(s.Svi, i,j));
gsl_matrix_set(s.sigmaPointsMeasure, i ,j + p.nbSamples + p.n , gsl_matrix_get(s.xi_prediction, i, 0) - p.gamma_aug * gsl_matrix_get(s.Svi, i,j));
}
}
// Compute the image of the sigma points, i.e. the associated predicted observations
// and their mean
gsl_vector_set_zero(s.yi_mean);
for(j = 0 ; j < p.nbSamplesMeasure ; ++j)
{
gsl_matrix_get_col(s.sigmaPointMeasure, s.sigmaPointsMeasure, j);
vec_view = gsl_matrix_column(s.yi_prediction,j);
h(s.sigmaPointMeasure, &vec_view.vector);
// Update the mean , eq (3.176)
for(i = 0 ; i < p.no ; ++i)
s.yi_mean->data[i] += s.wm_aug_j->data[j] * gsl_matrix_get(s.yi_prediction,i,j);
}
/*****************************************/
/***** Measurement update equations *****/
/*****************************************/
// Compute the Cholesky factor of the variance-covariance matrix of the observations
// Eq. 3.217
// First put in s.temp_2nno_no the transpose of what is in the brackets of qr{...} ,
for(j = 0 ; j < 2*p.n ; ++j)
for(i = 0 ; i < p.no ; ++i)
gsl_matrix_set(s.temp_2nno_no, j, i, sqrt(s.wc_aug_j->data[1])*(gsl_matrix_get(s.yi_prediction, i, j+1) - s.yi_mean->data[i]) );
// Copy the Cholesky factor of the covariance of the observation noise
mat_view = gsl_matrix_submatrix(s.temp_2nno_no,2*p.n, 0, p.no, p.no);
gsl_matrix_memcpy(&mat_view.matrix, s.Sni);
// We now perform the QR decomposition of s.temp_2nno_no;
gsl_linalg_QR_decomp(s.temp_2nno_no, s.temp_no);
// From this QR decomposition, we keep only the upper triangular part of R and copy it in s.Syi
for( j = 0 ; j < p.no ; ++j)
{
for(i = 0 ; i < j+1 ; ++i)
gsl_matrix_set(s.Syi, i, j, gsl_matrix_get(s.temp_2nno_no, i, j));
for(i = j+1 ; i < p.no ; ++i)
gsl_matrix_set(s.Syi, i, j, 0.0);
}
if(DEBUGMODE) printf("Syi : \n");
if(DEBUGMODE) print_mat(s.Syi);
if(DEBUGMODE) printf("\n");
//gsl_matrix_transpose(s.Syi);
// 2- Perform the cholupdate, which is a rank one update
// Eq. 3.218
// Syi is triangular superior
for(i = 0 ; i < p.no ; ++i)
s.temp_no->data[i] = gsl_matrix_get(s.yi_prediction,i,0) - s.yi_mean->data[i];
if(DEBUGMODE) print_vec(s.temp_no);
if(DEBUGMODE) printf("Before cholupdate 2 \n");
gsl_matrix_transpose(s.Syi);
ukf::math::choleskyUpdate(s.Syi, ukf::math::signof(s.wc_aug_j->data[0])*sqrt(fabs(s.wc_aug_j->data[0])), s.temp_no);
if(DEBUGMODE) printf("ok \n");
// Now, Syi is the lower triangular cholesky factor
//gsl_matrix_transpose(s.Syi);
if(DEBUGMODE) printf("Syi after cholupdate : \n");
if(DEBUGMODE) print_mat(s.Syi);
// Compute the state/observation covariance
// Eq (3.219)
gsl_matrix_set_zero(s.Pxyi);
for(j = 0 ; j < p.nbSamplesMeasure ; ++j)
{
for(i = 0 ; i < p.n ; ++i)
s.temp_n_1->data[i] = gsl_matrix_get(s.sigmaPointsMeasure,i,j) - s.xi_mean->data[i];
for(i = 0 ; i < p.no ; ++i)
s.temp_1_no->data[i] = gsl_matrix_get(s.yi_prediction,i,j) - s.yi_mean->data[i];
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, s.wc_aug_j->data[j] , s.temp_n_1, s.temp_1_no, 1.0, s.Pxyi);
//gsl_matrix_add(s.Pxyi, s.temp_n_no);
}
/*gsl_matrix_set_zero(s.Pxyi);
for(j = 0 ; j < p.nbSamples ; ++j)
{
for(i = 0 ; i < p.n ; ++i)
s.temp_n_1->data[i] = gsl_matrix_get(s.xi_prediction,i,j) - s.xi_mean->data[i];
for(i = 0 ; i < p.no ; ++i)
s.temp_1_no->data[i] = gsl_matrix_get(s.yi_prediction,i,j) - s.yi_mean->data[i];
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, s.wc_j->data[j] , s.temp_n_1, s.temp_1_no, 1.0, s.Pxyi);
//gsl_matrix_add(s.Pxyi, s.temp_n_no);
}*/
// Compute the Kalman gain,
// Eq (3.220)
// We want to solve : Kxy . Sy Sy^T = Pxy
// Which can be solved using : Sy Sy^T Kxy^T = Pxy^T
// We have a number of no systems to solve of the form S x = Pxy^T[:,i] ; S^T Kxy[:,i] = x with S being triangular
// To solve this, we make use of gsl_blas_dtrsv
for(int i = 0 ; i < p.n ; ++i)
{
vec_view = gsl_matrix_row(s.Pxyi, i);
gsl_vector_memcpy(s.temp_no, &vec_view.vector);
gsl_blas_dtrsv(CblasLower,CblasNoTrans,CblasNonUnit,s.Syi,s.temp_no);
gsl_blas_dtrsv(CblasLower,CblasTrans,CblasNonUnit,s.Syi,s.temp_no);
// And then copy the result in the ith row of Ki
vec_view = gsl_matrix_row(s.Ki, i);
gsl_vector_memcpy(&vec_view.vector, s.temp_no);
}
if(DEBUGMODE) printf("Ki : \n");
if(DEBUGMODE) print_mat(s.Ki);
// Correction : correct the estimation of the state
// Eq. 3.221
// Compute the innovations
for(i = 0 ; i < p.no ; ++i)
s.ino_yi->data[i] = yi->data[i] - s.yi_mean->data[i];
// And correct the current state estimate
gsl_blas_dgemv(CblasNoTrans, 1.0, s.Ki, s.ino_yi, 1.0, s.xi);
// Compute the matrix U = Kk Syk
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0 , s.Ki, s.Syi, 0, s.U);
if(DEBUGMODE) printf("Matrix U : \n");
if(DEBUGMODE) print_mat(s.U);
// Perform the cholesky updates of Sxi
// We perform p.no updates rank-1 update with the columns of U
if(DEBUGMODE) printf("Before cholupdate 3 \n");
for(i = 0 ; i < p.no ; ++i)
{
vec_view = gsl_matrix_column(s.U, i);
gsl_vector_memcpy(s.temp_n, &vec_view.vector);
ukf::math::choleskyUpdate(s.Sxi, -1.0, s.temp_n);
if(DEBUGMODE) printf("After cholupdate %i\n", i);
if(DEBUGMODE) print_mat(s.Sxi);
}
//printf("After cholupdate %i\n", i);
//print_mat(s.Sxi);
//if(DEBUGMODE) printf("\n");
//
// // Update of the process noise
// switch(p.process_noise_type)
// {
// case ukf::UKF_PROCESS_FIXED:
// //nothing to do
// break;
// case ukf::UKF_PROCESS_RLS:
// gsl_matrix_memcpy(s.Pvvi, s.Pxxi);
// gsl_matrix_scale(s.Pvvi, 1.0/p.process_noise-1.0);
// gsl_matrix_memcpy(s.cholPvvi, s.Pvvi);
// gsl_linalg_cholesky_decomp(s.cholPvvi);
// for(j = 0 ; j < p.n ; j++)
// for(k = j+1 ; k < p.n ; k++)
// gsl_matrix_set(s.cholPvvi,j,k,0.0);
// break;
// default:
// printf("Warning : Unrecognized process noise type\n");
// }
}
/**
* @short Evaluation of the output from the sigma points
*
*/
template <typename FunctProcess, typename FunctObservation>
void ukf_evaluate(ukf_param &p, ukf_state &s, FunctProcess f, FunctObservation h, gsl_vector* yi)
{
// int i,j,k;
// // ************************************************** //
// // ************ Compute the sigma points ************ //
// // ************************************************** //
//
// // 0 - Compute the Cholesky decomposition of s.Pxxi
// gsl_matrix_memcpy(s.cholPxxi, s.Pxxi);
// gsl_linalg_cholesky_decomp(s.cholPxxi);
// // Set all the elements of cholPvvi strictly above the diagonal to zero
// for(j = 0 ; j < p.n ; j++)
// for(k = j+1 ; k < p.n ; k++)
// gsl_matrix_set(s.cholPxxi,j,k,0.0);
//
// // 1- Compute the sigma points,
// // Equation (3.170)
// // sigmapoint_j = x_(i-1)
// // sigmapoint_j = x_(i-1) + gamma * sqrt(P_i-1)_j for 1 <= j <= n
// // sigmapoint_j = x_(i-1) - gamma * sqrt(P_i-1)_(j-(n+1)) for n+1 <= j <= 2n
// gsl_matrix_set_col(s.sigmaPoints, 0, s.xi);
// for(j = 1 ; j < p.n+1 ; ++j)
// for(i = 0 ; i < p.n ; ++i)
// {
// gsl_matrix_set(s.sigmaPoints,i,j, s.xi->data[i] + p.gamma * gsl_matrix_get(s.cholPxxi, i, j-1));
// gsl_matrix_set(s.sigmaPoints,i,j+p.n, s.xi->data[i] - p.gamma * gsl_matrix_get(s.cholPxxi, i, j-1));
// }
//
// /**********************************/
// /***** Time update equations *****/
// /**********************************/
//
// // Time update equations
// // 0 - Compute the image of the sigma points and the mean of these images
// gsl_vector_set_zero(s.xi_mean);
// for(j = 0 ; j < p.nbSamples ; ++j)
// {
// gsl_matrix_get_col(s.sigmaPoint, s.sigmaPoints, j);
// f(s.params, s.sigmaPoint, &gsl_matrix_column(s.xi_prediction,j).vector);
//
// // Update the mean, Eq (3.172)
// for(i = 0 ; i < p.n ; ++i)
// s.xi_mean->data[i] += s.wm_j->data[j] * gsl_matrix_get(s.xi_prediction,i,j);
// }
//
// // 1 - Compute the covariance of the images and add the process noise,
// // Equation (3.173)
// // Warning, s.Pxxi will now hold P_xk^-
// gsl_matrix_set_zero(s.Pxxi);
// for(j = 0 ; j < p.nbSamples ; ++j)
// {
// for(i = 0 ; i < p.n ; ++i)
// s.temp_n_1->data[i] = gsl_matrix_get(s.xi_prediction,i,j) - s.xi_mean->data[i];
//
// gsl_blas_dgemm(CblasNoTrans, CblasTrans, s.wc_j->data[j] , s.temp_n_1, s.temp_n_1, 0, s.temp_n_n);
// gsl_matrix_add(s.Pxxi, s.temp_n_n);
// }
// // Add the covariance of the evolution noise
// gsl_matrix_add(s.Pxxi, s.Pvvi);
//
// // Augment sigma points
// // Equation 3.174
// // First put the images of the initial sigma points
// gsl_matrix_memcpy(&gsl_matrix_submatrix(s.sigmaPointsMeasure, 0, 0, p.n, p.nbSamples).matrix, s.xi_prediction);
// // And add the additional sigma points eq. (7.56)
// for(j = 0 ; j < p.n ; ++j)
// {
// for(i = 0 ; i < p.n ; ++i)
// {
// gsl_matrix_set(s.sigmaPointsMeasure, i, j+p.nbSamples, gsl_matrix_get(s.xi_prediction,i,0)+p.gamma_aug*gsl_matrix_get(s.cholPvvi,i,j));
// gsl_matrix_set(s.sigmaPointsMeasure, i, j+p.nbSamples+p.n, gsl_matrix_get(s.xi_prediction,i,0)-p.gamma_aug*gsl_matrix_get(s.cholPvvi,i,j));
// }
// }
//
// // Compute the image of the sigma points through the observation equation
// // eq (3.175)
// gsl_vector_set_zero(yi);
// for(j = 0 ; j < p.nbSamplesMeasure ; ++j)
// {
// gsl_matrix_get_col(s.sigmaPointMeasure, s.sigmaPointsMeasure, j);
// h(s.sigmaPointMeasure, &gsl_matrix_column(s.yi_prediction,j).vector);
//
// // Update the mean , eq (3.176)
// for(i = 0 ; i < p.no ; ++i)
// yi->data[i] += s.wm_aug_j->data[j] * gsl_matrix_get(s.yi_prediction,i,j);
// }
}
} // srstate
} // ukf
#endif // UKF_SR_STATE_NDIM_H
| {
"alphanum_fraction": 0.504152885,
"avg_line_length": 45.2745424293,
"ext": "h",
"hexsha": "1661f845fcf670a79226277a1118c72c43620cc7",
"lang": "C",
"max_forks_count": 52,
"max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z",
"max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "bahia14/C-Kalman-filtering",
"max_forks_repo_path": "src/ukf_sr_state_ndim.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a",
"max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "bahia14/C-Kalman-filtering",
"max_issues_repo_path": "src/ukf_sr_state_ndim.h",
"max_line_length": 173,
"max_stars_count": 101,
"max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "bahia14/C-Kalman-filtering",
"max_stars_repo_path": "src/ukf_sr_state_ndim.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z",
"num_tokens": 6887,
"size": 27210
} |
/** GSLDAPCom.h - <title>GSLDAP: Common</title>
Copyright (C) 2002-2003 Free Software Foundation, Inc.
Written by: Manuel Guesdon <mguesdon@orange-concept.com>
Date: Sep 2002
$Revision$
$Date$
$Id$
This file is part of the GNUstep LDAP Library.
<license>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
</license>
**/
#ifndef _GSLDAPCom_h__
#define _GSLDAPCom_h__
#include <stdio.h>
#include <string.h>
#include <ldap.h>
#include <lber.h>
#include <sys/time.h>
#include <Foundation/NSObject.h>
#include <Foundation/NSString.h>
#include <Foundation/NSArray.h>
#include <Foundation/NSData.h>
#include <Foundation/NSDictionary.h>
#include <Foundation/NSDebug.h>
#include <Foundation/NSScanner.h>
#include <Foundation/NSCalendarDate.h>
#include <Foundation/NSException.h>
#include <GNUstepBase/GSCategories.h>
#include <gsldap/GSLDAPUtils.h>
#include <gsldap/GSLDAPConnection.h>
#include <gsldap/GSLDAPEntry.h>
#include <gsldap/GSLDAPAttribute.h>
#include <gsldap/GSLDAPObjectClass.h>
#include <gsldap/GSLDAPSyntax.h>
#include <gsldap/GSLDAPMatchingRule.h>
#include <gsldap/GSLDAPSchema.h>
#endif //_GSLDAPCom_h__
| {
"alphanum_fraction": 0.7455040872,
"avg_line_length": 30.0819672131,
"ext": "h",
"hexsha": "8f4bf7444c1b821bc91485480e8635c16ea95fe3",
"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": "da29870c44780c3101d5a90ac9380d9b8c404593",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "gnustep/gsldap",
"max_forks_repo_path": "GSLDAPCom.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "da29870c44780c3101d5a90ac9380d9b8c404593",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "gnustep/gsldap",
"max_issues_repo_path": "GSLDAPCom.h",
"max_line_length": 69,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "da29870c44780c3101d5a90ac9380d9b8c404593",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "gnustep/gsldap",
"max_stars_repo_path": "GSLDAPCom.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 484,
"size": 1835
} |
#ifndef DIFFEQ_SIM_H
#define DIFFEQ_SIM_H
#include <gsl/gsl_odeiv.h>
#include <gsl/gsl_errno.h>
#include <iostream>
#include <vector>
using namespace std;
class DiffEq_Sim {
private:
double t; //initial time
double h; //time step
double tmax; //max time
double hmin;
public:
DiffEq_Sim() {
t = 0.0; //initial time
h = 0.1; //time step
tmax = 2000;
hmin = 0.2;
};
~DiffEq_Sim() {};
int nbins;
double* y;
void printY() { for(int i=0; i < nbins; i++) { cout << y[i] << " ";} cout << endl; }
vector<double> get_state() {
vector<double> C;
C.assign(y, y + nbins);
return C;
}
double get_time() { return t; }
virtual void initialize() {}
virtual void derivative(const double y[], double dydt[]){}
static int function(double t, double const y[], double dydt[], void *params) {
DiffEq_Sim* model = static_cast <DiffEq_Sim*> (params);
model->derivative(y, dydt);
return GSL_SUCCESS;
}
int run_simulation() {
gsl_odeiv_evolve* e = gsl_odeiv_evolve_alloc(nbins);
gsl_odeiv_control* c = gsl_odeiv_control_y_new(1e-20, 0);
gsl_odeiv_step* s = gsl_odeiv_step_alloc(gsl_odeiv_step_rkf45, nbins);
gsl_odeiv_system sys = {function, NULL, nbins, this };
while (t < tmax) { //convergence check here
int status = gsl_odeiv_evolve_apply(e, c, s, &sys, &t, tmax, &h, y);
if (status != GSL_SUCCESS) { return status; }
}
return 0;
}
int step_simulation( double stepsize ) {
gsl_odeiv_evolve* e = gsl_odeiv_evolve_alloc(nbins);
gsl_odeiv_control* c = gsl_odeiv_control_y_new(1e-5, 0);
gsl_odeiv_step* s = gsl_odeiv_step_alloc(gsl_odeiv_step_rkf45, nbins);
gsl_odeiv_system sys = {function, NULL, nbins, this };
double tstop = t+stepsize;
while (t < tstop) {
int status = gsl_odeiv_evolve_apply(e, c, s, &sys, &t, tstop, &h, y);
if (status != GSL_SUCCESS) { return status; }
}
return 0;
}
/*
double* advance_simulation(double I_lim) {
while (t < 2000) { //convergence check here
int status = gsl_odeiv_evolve_apply(e, c, s, &sys, &t, t1, &h, y);
if (y[1] < I_lim) { return y; }
}
printY();
return y;
}
*/
};
#endif
| {
"alphanum_fraction": 0.5159377317,
"avg_line_length": 29.3260869565,
"ext": "h",
"hexsha": "ae05ed224d585a69a64058c856e748c3f8518236",
"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": "c0d957265608b15f216ece67363c827d01122102",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pvnuffel/test_repos",
"max_forks_repo_path": "src/DiffEq_Sim.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"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": "pvnuffel/test_repos",
"max_issues_repo_path": "src/DiffEq_Sim.h",
"max_line_length": 92,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pvnuffel/test_repos",
"max_stars_repo_path": "src/DiffEq_Sim.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 747,
"size": 2698
} |
// Copyright (c) 2021 Stig Rune Sellevag
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.
#ifndef SCILIB_LINALG_LINSOLVE_H
#define SCILIB_LINALG_LINSOLVE_H
#ifdef USE_MKL
#include <mkl.h>
#else
#include <lapacke.h>
#endif
#include <scilib/mdarray.h>
#include <scilib/linalg_impl/lapack_types.h>
#include <experimental/mdspan>
#include <exception>
#include <cassert>
#include <type_traits>
namespace Sci {
namespace Linalg {
// Solve linear system of equations.
template <class Layout>
inline void linsolve(Sci::Matrix_view<double, Layout> a,
Sci::Matrix_view<double, Layout> b)
{
namespace stdex = std::experimental;
static_assert(a.is_contiguous());
static_assert(b.is_contiguous());
assert(a.extent(0) == a.extent(1));
assert(b.extent(0) == a.extent(1));
const BLAS_INT n = static_cast<BLAS_INT>(a.extent(1));
const BLAS_INT nrhs = static_cast<BLAS_INT>(b.extent(1));
const BLAS_INT lda = n;
Sci::Vector<BLAS_INT, Layout> ipiv(n);
auto matrix_layout = LAPACK_ROW_MAJOR;
BLAS_INT ldb = nrhs;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = LAPACK_COL_MAJOR;
ldb = n;
}
BLAS_INT info = LAPACKE_dgesv(matrix_layout, n, nrhs, a.data(), lda,
ipiv.data(), b.data(), ldb);
if (info != 0) {
throw std::runtime_error("dgesv: factor U is singular");
}
}
template <class Layout, class Allocator>
inline void linsolve(Sci::Matrix<double, Layout, Allocator>& a,
Sci::Matrix<double, Layout, Allocator>& b)
{
linsolve(a.view(), b.view());
}
} // namespace Linalg
} // namespace Sci
#endif // SCILIB_LINALG_LINSOLVE_H | {
"alphanum_fraction": 0.671009772,
"avg_line_length": 26.6956521739,
"ext": "h",
"hexsha": "2b2af7ac19b953a8b4d01a688271a5e3d855fb26",
"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": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "stigrs/scilib",
"max_forks_repo_path": "include/scilib/linalg_impl/linsolve.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"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": "stigrs/scilib",
"max_issues_repo_path": "include/scilib/linalg_impl/linsolve.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "stigrs/scilib",
"max_stars_repo_path": "include/scilib/linalg_impl/linsolve.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 487,
"size": 1842
} |
/* specfunc/legendre_poly.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002 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_bessel.h>
#include <gsl/gsl_sf_exp.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_log.h>
#include <gsl/gsl_sf_pow_int.h>
#include <gsl/gsl_sf_legendre.h>
#include "error.h"
/* Calculate P_m^m(x) from the analytic result:
* P_m^m(x) = (-1)^m (2m-1)!! (1-x^2)^(m/2) , m > 0
* = 1 , m = 0
*/
static double legendre_Pmm(int m, double x)
{
if(m == 0)
{
return 1.0;
}
else
{
double p_mm = 1.0;
double root_factor = sqrt(1.0-x)*sqrt(1.0+x);
double fact_coeff = 1.0;
int i;
for(i=1; i<=m; i++)
{
p_mm *= -fact_coeff * root_factor;
fact_coeff += 2.0;
}
return p_mm;
}
}
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int
gsl_sf_legendre_P1_e(double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
{
result->val = x;
result->err = 0.0;
return GSL_SUCCESS;
}
}
int
gsl_sf_legendre_P2_e(double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
{
result->val = 0.5*(3.0*x*x - 1.0);
result->err = GSL_DBL_EPSILON * (fabs(3.0*x*x) + 1.0);
return GSL_SUCCESS;
}
}
int
gsl_sf_legendre_P3_e(double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
{
result->val = 0.5*x*(5.0*x*x - 3.0);
result->err = GSL_DBL_EPSILON * (fabs(result->val) + 0.5 * fabs(x) * (fabs(5.0*x*x) + 3.0));
return GSL_SUCCESS;
}
}
int
gsl_sf_legendre_Pl_e(const int l, const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(l < 0 || x < -1.0 || x > 1.0) {
DOMAIN_ERROR(result);
}
else if(l == 0) {
result->val = 1.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else if(l == 1) {
result->val = x;
result->err = 0.0;
return GSL_SUCCESS;
}
else if(l == 2) {
result->val = 0.5 * (3.0*x*x - 1.0);
result->err = GSL_DBL_EPSILON * (fabs(3.0*x*x) + 1.0);
/*result->err = 3.0 * GSL_DBL_EPSILON * fabs(result->val);
removed this old bogus estimate [GJ]
*/
return GSL_SUCCESS;
}
else if(x == 1.0) {
result->val = 1.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else if(x == -1.0) {
result->val = ( GSL_IS_ODD(l) ? -1.0 : 1.0 );
result->err = 0.0;
return GSL_SUCCESS;
}
else if(l < 100000) {
/* upward recurrence: l P_l = (2l-1) z P_{l-1} - (l-1) P_{l-2} */
double p_ellm2 = 1.0; /* P_0(x) */
double p_ellm1 = x; /* P_1(x) */
double p_ell = p_ellm1;
double e_ellm2 = GSL_DBL_EPSILON;
double e_ellm1 = fabs(x)*GSL_DBL_EPSILON;
double e_ell = e_ellm1;
int ell;
for(ell=2; ell <= l; ell++){
p_ell = (x*(2*ell-1)*p_ellm1 - (ell-1)*p_ellm2) / ell;
p_ellm2 = p_ellm1;
p_ellm1 = p_ell;
e_ell = 0.5*(fabs(x)*(2*ell-1.0) * e_ellm1 + (ell-1.0)*e_ellm2)/ell;
e_ellm2 = e_ellm1;
e_ellm1 = e_ell;
}
result->val = p_ell;
result->err = e_ell + l*fabs(p_ell)*GSL_DBL_EPSILON;
return GSL_SUCCESS;
}
else {
/* Asymptotic expansion.
* [Olver, p. 473]
*/
double u = l + 0.5;
double th = acos(x);
gsl_sf_result J0;
gsl_sf_result Jm1;
int stat_J0 = gsl_sf_bessel_J0_e(u*th, &J0);
int stat_Jm1 = gsl_sf_bessel_Jn_e(-1, u*th, &Jm1);
double pre;
double B00;
double c1;
/* B00 = 1/8 (1 - th cot(th) / th^2
* pre = sqrt(th/sin(th))
*/
if(th < GSL_ROOT4_DBL_EPSILON) {
B00 = (1.0 + th*th/15.0)/24.0;
pre = 1.0 + th*th/12.0;
}
else {
double sin_th = sqrt(1.0 - x*x);
double cot_th = x / sin_th;
B00 = 1.0/8.0 * (1.0 - th * cot_th) / (th*th);
pre = sqrt(th/sin_th);
}
c1 = th/u * B00;
result->val = pre * (J0.val + c1 * Jm1.val);
result->err = pre * (J0.err + fabs(c1) * Jm1.err);
result->err += GSL_SQRT_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_J0, stat_Jm1);
}
}
int
gsl_sf_legendre_Pl_array(const int lmax, const double x, double * result_array)
{
/* CHECK_POINTER(result_array) */
if(lmax < 0 || x < -1.0 || x > 1.0) {
GSL_ERROR ("domain error", GSL_EDOM);
}
else if(lmax == 0) {
result_array[0] = 1.0;
return GSL_SUCCESS;
}
else if(lmax == 1) {
result_array[0] = 1.0;
result_array[1] = x;
return GSL_SUCCESS;
}
else {
/* upward recurrence: l P_l = (2l-1) z P_{l-1} - (l-1) P_{l-2} */
double p_ellm2 = 1.0; /* P_0(x) */
double p_ellm1 = x; /* P_1(x) */
double p_ell = p_ellm1;
int ell;
result_array[0] = 1.0;
result_array[1] = x;
for(ell=2; ell <= lmax; ell++){
p_ell = (x*(2*ell-1)*p_ellm1 - (ell-1)*p_ellm2) / ell;
p_ellm2 = p_ellm1;
p_ellm1 = p_ell;
result_array[ell] = p_ell;
}
return GSL_SUCCESS;
}
}
int
gsl_sf_legendre_Pl_deriv_array(const int lmax, const double x, double * result_array, double * result_deriv_array)
{
int stat_array = gsl_sf_legendre_Pl_array(lmax, x, result_array);
if(lmax >= 0) result_deriv_array[0] = 0.0;
if(lmax >= 1) result_deriv_array[1] = 1.0;
if(stat_array == GSL_SUCCESS)
{
int ell;
if(fabs(x - 1.0)*(lmax+1.0)*(lmax+1.0) < GSL_SQRT_DBL_EPSILON)
{
/* x is near 1 */
for(ell = 2; ell <= lmax; ell++)
{
const double pre = 0.5 * ell * (ell+1.0);
result_deriv_array[ell] = pre * (1.0 - 0.25 * (1.0-x) * (ell+2.0)*(ell-1.0));
}
}
else if(fabs(x + 1.0)*(lmax+1.0)*(lmax+1.0) < GSL_SQRT_DBL_EPSILON)
{
/* x is near -1 */
for(ell = 2; ell <= lmax; ell++)
{
const double sgn = ( GSL_IS_ODD(ell) ? 1.0 : -1.0 ); /* derivative is odd in x for even ell */
const double pre = sgn * 0.5 * ell * (ell+1.0);
result_deriv_array[ell] = pre * (1.0 - 0.25 * (1.0+x) * (ell+2.0)*(ell-1.0));
}
}
else
{
const double diff_a = 1.0 + x;
const double diff_b = 1.0 - x;
for(ell = 2; ell <= lmax; ell++)
{
result_deriv_array[ell] = - ell * (x * result_array[ell] - result_array[ell-1]) / (diff_a * diff_b);
}
}
return GSL_SUCCESS;
}
else
{
return stat_array;
}
}
int
gsl_sf_legendre_Plm_e(const int l, const int m, const double x, gsl_sf_result * result)
{
/* If l is large and m is large, then we have to worry
* about overflow. Calculate an approximate exponent which
* measures the normalization of this thing.
*/
const double dif = l-m;
const double sum = l+m;
const double t_d = ( dif == 0.0 ? 0.0 : 0.5 * dif * (log(dif)-1.0) );
const double t_s = ( dif == 0.0 ? 0.0 : 0.5 * sum * (log(sum)-1.0) );
const double exp_check = 0.5 * log(2.0*l+1.0) + t_d - t_s;
/* CHECK_POINTER(result) */
if(m < 0 || l < m || x < -1.0 || x > 1.0) {
DOMAIN_ERROR(result);
}
else if(exp_check < GSL_LOG_DBL_MIN + 10.0){
/* Bail out. */
OVERFLOW_ERROR(result);
}
else {
/* Account for the error due to the
* representation of 1-x.
*/
const double err_amp = 1.0 / (GSL_DBL_EPSILON + fabs(1.0-fabs(x)));
/* P_m^m(x) and P_{m+1}^m(x) */
double p_mm = legendre_Pmm(m, x);
double p_mmp1 = x * (2*m + 1) * p_mm;
if(l == m){
result->val = p_mm;
result->err = err_amp * 2.0 * GSL_DBL_EPSILON * fabs(p_mm);
return GSL_SUCCESS;
}
else if(l == m + 1) {
result->val = p_mmp1;
result->err = err_amp * 2.0 * GSL_DBL_EPSILON * fabs(p_mmp1);
return GSL_SUCCESS;
}
else{
/* upward recurrence: (l-m) P(l,m) = (2l-1) z P(l-1,m) - (l+m-1) P(l-2,m)
* start at P(m,m), P(m+1,m)
*/
double p_ellm2 = p_mm;
double p_ellm1 = p_mmp1;
double p_ell = 0.0;
int ell;
for(ell=m+2; ell <= l; ell++){
p_ell = (x*(2*ell-1)*p_ellm1 - (ell+m-1)*p_ellm2) / (ell-m);
p_ellm2 = p_ellm1;
p_ellm1 = p_ell;
}
result->val = p_ell;
result->err = err_amp * (0.5*(l-m) + 1.0) * GSL_DBL_EPSILON * fabs(p_ell);
return GSL_SUCCESS;
}
}
}
int
gsl_sf_legendre_Plm_array(const int lmax, const int m, const double x, double * result_array)
{
/* If l is large and m is large, then we have to worry
* about overflow. Calculate an approximate exponent which
* measures the normalization of this thing.
*/
const double dif = lmax-m;
const double sum = lmax+m;
const double t_d = ( dif == 0.0 ? 0.0 : 0.5 * dif * (log(dif)-1.0) );
const double t_s = ( dif == 0.0 ? 0.0 : 0.5 * sum * (log(sum)-1.0) );
const double exp_check = 0.5 * log(2.0*lmax+1.0) + t_d - t_s;
/* CHECK_POINTER(result_array) */
if(m < 0 || lmax < m || x < -1.0 || x > 1.0) {
GSL_ERROR ("domain error", GSL_EDOM);
}
else if(m > 0 && (x == 1.0 || x == -1.0)) {
int ell;
for(ell=m; ell<=lmax; ell++) result_array[ell-m] = 0.0;
return GSL_SUCCESS;
}
else if(exp_check < GSL_LOG_DBL_MIN + 10.0){
/* Bail out. */
GSL_ERROR ("overflow", GSL_EOVRFLW);
}
else {
double p_mm = legendre_Pmm(m, x);
double p_mmp1 = x * (2.0*m + 1.0) * p_mm;
if(lmax == m){
result_array[0] = p_mm;
return GSL_SUCCESS;
}
else if(lmax == m + 1) {
result_array[0] = p_mm;
result_array[1] = p_mmp1;
return GSL_SUCCESS;
}
else {
double p_ellm2 = p_mm;
double p_ellm1 = p_mmp1;
double p_ell = 0.0;
int ell;
result_array[0] = p_mm;
result_array[1] = p_mmp1;
for(ell=m+2; ell <= lmax; ell++){
p_ell = (x*(2.0*ell-1.0)*p_ellm1 - (ell+m-1)*p_ellm2) / (ell-m);
p_ellm2 = p_ellm1;
p_ellm1 = p_ell;
result_array[ell-m] = p_ell;
}
return GSL_SUCCESS;
}
}
}
int
gsl_sf_legendre_Plm_deriv_array(
const int lmax, const int m, const double x,
double * result_array,
double * result_deriv_array)
{
if(m < 0 || m > lmax)
{
GSL_ERROR("m < 0 or m > lmax", GSL_EDOM);
}
else if(m == 0)
{
/* It is better to do m=0 this way, so we can more easily
* trap the divergent case which can occur when m == 1.
*/
return gsl_sf_legendre_Pl_deriv_array(lmax, x, result_array, result_deriv_array);
}
else
{
int stat_array = gsl_sf_legendre_Plm_array(lmax, m, x, result_array);
if(stat_array == GSL_SUCCESS)
{
int ell;
if(m == 1 && (1.0 - fabs(x) < GSL_DBL_EPSILON))
{
/* This divergence is real and comes from the cusp-like
* behaviour for m = 1. For example, P[1,1] = - Sqrt[1-x^2].
*/
GSL_ERROR("divergence near |x| = 1.0 since m = 1", GSL_EOVRFLW);
}
else if(m == 2 && (1.0 - fabs(x) < GSL_DBL_EPSILON))
{
/* m = 2 gives a finite nonzero result for |x| near 1 */
if(fabs(x - 1.0) < GSL_DBL_EPSILON)
{
for(ell = m; ell <= lmax; ell++) result_deriv_array[ell-m] = -0.25 * x * (ell - 1.0)*ell*(ell+1.0)*(ell+2.0);
}
else if(fabs(x + 1.0) < GSL_DBL_EPSILON)
{
for(ell = m; ell <= lmax; ell++)
{
const double sgn = ( GSL_IS_ODD(ell) ? 1.0 : -1.0 );
result_deriv_array[ell-m] = -0.25 * sgn * x * (ell - 1.0)*ell*(ell+1.0)*(ell+2.0);
}
}
return GSL_SUCCESS;
}
else
{
/* m > 2 is easier to deal with since the endpoints always vanish */
if(1.0 - fabs(x) < GSL_DBL_EPSILON)
{
for(ell = m; ell <= lmax; ell++) result_deriv_array[ell-m] = 0.0;
return GSL_SUCCESS;
}
else
{
const double diff_a = 1.0 + x;
const double diff_b = 1.0 - x;
result_deriv_array[0] = - m * x / (diff_a * diff_b) * result_array[0];
if(lmax-m >= 1) result_deriv_array[1] = (2.0 * m + 1.0) * (x * result_deriv_array[0] + result_array[0]);
for(ell = m+2; ell <= lmax; ell++)
{
result_deriv_array[ell-m] = - (ell * x * result_array[ell-m] - (ell+m) * result_array[ell-1-m]) / (diff_a * diff_b);
}
return GSL_SUCCESS;
}
}
}
else
{
return stat_array;
}
}
}
int
gsl_sf_legendre_sphPlm_e(const int l, int m, const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(m < 0 || l < m || x < -1.0 || x > 1.0) {
DOMAIN_ERROR(result);
}
else if(m == 0) {
gsl_sf_result P;
int stat_P = gsl_sf_legendre_Pl_e(l, x, &P);
double pre = sqrt((2.0*l + 1.0)/(4.0*M_PI));
result->val = pre * P.val;
result->err = pre * P.err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_P;
}
else if(x == 1.0 || x == -1.0) {
/* m > 0 here */
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else {
/* m > 0 and |x| < 1 here */
/* Starting value for recursion.
* Y_m^m(x) = sqrt( (2m+1)/(4pi m) gamma(m+1/2)/gamma(m) ) (-1)^m (1-x^2)^(m/2) / pi^(1/4)
*/
gsl_sf_result lncirc;
gsl_sf_result lnpoch;
double lnpre_val;
double lnpre_err;
gsl_sf_result ex_pre;
double sr;
const double sgn = ( GSL_IS_ODD(m) ? -1.0 : 1.0);
const double y_mmp1_factor = x * sqrt(2.0*m + 3.0);
double y_mm, y_mm_err;
double y_mmp1, y_mmp1_err;
gsl_sf_log_1plusx_e(-x*x, &lncirc);
gsl_sf_lnpoch_e(m, 0.5, &lnpoch); /* Gamma(m+1/2)/Gamma(m) */
lnpre_val = -0.25*M_LNPI + 0.5 * (lnpoch.val + m*lncirc.val);
lnpre_err = 0.25*M_LNPI*GSL_DBL_EPSILON + 0.5 * (lnpoch.err + fabs(m)*lncirc.err);
/* Compute exp(ln_pre) with error term, avoiding call to gsl_sf_exp_err BJG */
ex_pre.val = exp(lnpre_val);
ex_pre.err = 2.0*(sinh(lnpre_err) + GSL_DBL_EPSILON)*ex_pre.val;
sr = sqrt((2.0+1.0/m)/(4.0*M_PI));
y_mm = sgn * sr * ex_pre.val;
y_mm_err = 2.0 * GSL_DBL_EPSILON * fabs(y_mm) + sr * ex_pre.err;
y_mm_err *= 1.0 + 1.0/(GSL_DBL_EPSILON + fabs(1.0-x));
y_mmp1 = y_mmp1_factor * y_mm;
y_mmp1_err=fabs(y_mmp1_factor) * y_mm_err;
if(l == m){
result->val = y_mm;
result->err = y_mm_err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(y_mm);
return GSL_SUCCESS;
}
else if(l == m + 1) {
result->val = y_mmp1;
result->err = y_mmp1_err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(y_mmp1);
return GSL_SUCCESS;
}
else{
double y_ell = 0.0;
double y_ell_err;
int ell;
/* Compute Y_l^m, l > m+1, upward recursion on l. */
for(ell=m+2; ell <= l; ell++){
const double rat1 = (double)(ell-m)/(double)(ell+m);
const double rat2 = (ell-m-1.0)/(ell+m-1.0);
const double factor1 = sqrt(rat1*(2.0*ell+1.0)*(2.0*ell-1.0));
const double factor2 = sqrt(rat1*rat2*(2.0*ell+1.0)/(2.0*ell-3.0));
y_ell = (x*y_mmp1*factor1 - (ell+m-1.0)*y_mm*factor2) / (ell-m);
y_mm = y_mmp1;
y_mmp1 = y_ell;
y_ell_err = 0.5*(fabs(x*factor1)*y_mmp1_err + fabs((ell+m-1.0)*factor2)*y_mm_err) / fabs(ell-m);
y_mm_err = y_mmp1_err;
y_mmp1_err = y_ell_err;
}
result->val = y_ell;
result->err = y_ell_err + (0.5*(l-m) + 1.0) * GSL_DBL_EPSILON * fabs(y_ell);
return GSL_SUCCESS;
}
}
}
int
gsl_sf_legendre_sphPlm_array(const int lmax, int m, const double x, double * result_array)
{
/* CHECK_POINTER(result_array) */
if(m < 0 || lmax < m || x < -1.0 || x > 1.0) {
GSL_ERROR ("error", GSL_EDOM);
}
else if(m > 0 && (x == 1.0 || x == -1.0)) {
int ell;
for(ell=m; ell<=lmax; ell++) result_array[ell-m] = 0.0;
return GSL_SUCCESS;
}
else {
double y_mm;
double y_mmp1;
if(m == 0) {
y_mm = 0.5/M_SQRTPI; /* Y00 = 1/sqrt(4pi) */
y_mmp1 = x * M_SQRT3 * y_mm;
}
else {
/* |x| < 1 here */
gsl_sf_result lncirc;
gsl_sf_result lnpoch;
double lnpre;
const double sgn = ( GSL_IS_ODD(m) ? -1.0 : 1.0);
gsl_sf_log_1plusx_e(-x*x, &lncirc);
gsl_sf_lnpoch_e(m, 0.5, &lnpoch); /* Gamma(m+1/2)/Gamma(m) */
lnpre = -0.25*M_LNPI + 0.5 * (lnpoch.val + m*lncirc.val);
y_mm = sqrt((2.0+1.0/m)/(4.0*M_PI)) * sgn * exp(lnpre);
y_mmp1 = x * sqrt(2.0*m + 3.0) * y_mm;
}
if(lmax == m){
result_array[0] = y_mm;
return GSL_SUCCESS;
}
else if(lmax == m + 1) {
result_array[0] = y_mm;
result_array[1] = y_mmp1;
return GSL_SUCCESS;
}
else{
double y_ell;
int ell;
result_array[0] = y_mm;
result_array[1] = y_mmp1;
/* Compute Y_l^m, l > m+1, upward recursion on l. */
for(ell=m+2; ell <= lmax; ell++){
const double rat1 = (double)(ell-m)/(double)(ell+m);
const double rat2 = (ell-m-1.0)/(ell+m-1.0);
const double factor1 = sqrt(rat1*(2*ell+1)*(2*ell-1));
const double factor2 = sqrt(rat1*rat2*(2*ell+1)/(2*ell-3));
y_ell = (x*y_mmp1*factor1 - (ell+m-1)*y_mm*factor2) / (ell-m);
y_mm = y_mmp1;
y_mmp1 = y_ell;
result_array[ell-m] = y_ell;
}
}
return GSL_SUCCESS;
}
}
int
gsl_sf_legendre_sphPlm_deriv_array(
const int lmax, const int m, const double x,
double * result_array,
double * result_deriv_array)
{
if(m < 0 || lmax < m || x < -1.0 || x > 1.0)
{
GSL_ERROR ("domain", GSL_EDOM);
}
else if(m == 0)
{
/* m = 0 is easy to trap */
const int stat_array = gsl_sf_legendre_Pl_deriv_array(lmax, x, result_array, result_deriv_array);
int ell;
for(ell = 0; ell <= lmax; ell++)
{
const double prefactor = sqrt((2.0 * ell + 1.0)/(4.0*M_PI));
result_array[ell] *= prefactor;
result_deriv_array[ell] *= prefactor;
}
return stat_array;
}
else if(m == 1)
{
/* Trapping m = 1 is necessary because of the possible divergence.
* Recall that this divergence is handled properly in ..._Plm_deriv_array(),
* and the scaling factor is not large for small m, so we just scale.
*/
const int stat_array = gsl_sf_legendre_Plm_deriv_array(lmax, m, x, result_array, result_deriv_array);
int ell;
for(ell = 1; ell <= lmax; ell++)
{
const double prefactor = sqrt((2.0 * ell + 1.0)/(ell + 1.0) / (4.0*M_PI*ell));
result_array[ell-1] *= prefactor;
result_deriv_array[ell-1] *= prefactor;
}
return stat_array;
}
else
{
/* as for the derivative of P_lm, everything is regular for m >= 2 */
int stat_array = gsl_sf_legendre_sphPlm_array(lmax, m, x, result_array);
if(stat_array == GSL_SUCCESS)
{
int ell;
if(1.0 - fabs(x) < GSL_DBL_EPSILON)
{
for(ell = m; ell <= lmax; ell++) result_deriv_array[ell-m] = 0.0;
return GSL_SUCCESS;
}
else
{
const double diff_a = 1.0 + x;
const double diff_b = 1.0 - x;
result_deriv_array[0] = - m * x / (diff_a * diff_b) * result_array[0];
if(lmax-m >= 1) result_deriv_array[1] = sqrt(2.0 * m + 3.0) * (x * result_deriv_array[0] + result_array[0]);
for(ell = m+2; ell <= lmax; ell++)
{
const double c1 = sqrt(((2.0*ell+1.0)/(2.0*ell-1.0)) * ((double)(ell-m)/(double)(ell+m)));
result_deriv_array[ell-m] = - (ell * x * result_array[ell-m] - c1 * (ell+m) * result_array[ell-1-m]) / (diff_a * diff_b);
}
return GSL_SUCCESS;
}
}
else
{
return stat_array;
}
}
}
int
gsl_sf_legendre_array_size(const int lmax, const int m)
{
return lmax-m+1;
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_legendre_P1(const double x)
{
EVAL_RESULT(gsl_sf_legendre_P1_e(x, &result));
}
double gsl_sf_legendre_P2(const double x)
{
EVAL_RESULT(gsl_sf_legendre_P2_e(x, &result));
}
double gsl_sf_legendre_P3(const double x)
{
EVAL_RESULT(gsl_sf_legendre_P3_e(x, &result));
}
double gsl_sf_legendre_Pl(const int l, const double x)
{
EVAL_RESULT(gsl_sf_legendre_Pl_e(l, x, &result));
}
double gsl_sf_legendre_Plm(const int l, const int m, const double x)
{
EVAL_RESULT(gsl_sf_legendre_Plm_e(l, m, x, &result));
}
double gsl_sf_legendre_sphPlm(const int l, const int m, const double x)
{
EVAL_RESULT(gsl_sf_legendre_sphPlm_e(l, m, x, &result));
}
| {
"alphanum_fraction": 0.5628083491,
"avg_line_length": 27.0256410256,
"ext": "c",
"hexsha": "654a4b04458ff55a95cad5a424cd6a1824a84f55",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "skair39/structured",
"max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/specfunc/legendre_poly.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "skair39/structured",
"max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/specfunc/legendre_poly.c",
"max_line_length": 131,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/specfunc/legendre_poly.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": 7561,
"size": 21080
} |
/*
* Tema 2 ASC
* 2020 Spring
*/
#include <cblas.h>
#include "utils.h"
#define IDX2L(i, j, N) (((i) * (N)) + (j))
/*
* Add your BLAS implementation here
*/
double* my_solver(int N, double *A, double *B) {
int i, j;
double alpha = 1.0;
/* Calculate the final result in C matrix */
double *C = calloc(N * N, sizeof(double));
if (C == NULL) {
return NULL;
}
/* Calculate the B*At part in D */
double *D = calloc(N * N, sizeof(double));
if (D == NULL) {
return NULL;
}
/* Calculate the A * A in A_square */
double *A_square = calloc(N * N, sizeof(double));
if (A_square == NULL) {
return NULL;
}
/* Copy B matrix in D matrix */
for (i = 0; i != N; i++) {
for (j = 0; j != N; j++) {
D[IDX2L(i, j, N)] = B[IDX2L(i, j, N)];
}
}
/* Copy A matrix in A_square matrix */
for (i = 0; i != N; i++) {
for (j = 0; j != N; j++) {
if ( i <= j) {
A_square[IDX2L(i, j, N)] = A[IDX2L(i, j, N)];
}
}
}
/*
* Multiply matrixes B * At, where At is A transposed
* The result is saved in D matrix
*/
cblas_dtrmm(CblasRowMajor, CblasRight, CblasUpper, CblasTrans,
CblasNonUnit, N, N, alpha, A, N, D, N);
/*
* Multiply matrixes A * A, saved result in A_square
* Matrix A_square is a triangular matrix
*/
cblas_dtrmm(CblasRowMajor, CblasRight, CblasUpper, CblasNoTrans,
CblasNonUnit, N, N, alpha, A, N, A_square, N);
/*
* Multiply matrixes A_square * B, where A_square = A * A
* The result is saved in B matrix
*/
cblas_dtrmm(CblasRowMajor, CblasLeft, CblasUpper, CblasNoTrans,
CblasNonUnit, N, N, alpha, A_square, N, B, N);
/* Add matrixes D and B, save the result in C matrix */
for (i = 0; i != N; i++) {
for (j = 0; j != N; j++) {
C[IDX2L(i, j, N)] = D[IDX2L(i, j, N)] + B[IDX2L(i, j, N)];
}
}
/* Free memory from D and A_square */
free(D);
free(A_square);
printf("BLAS SOLVER\n");
return C;
}
| {
"alphanum_fraction": 0.5768822906,
"avg_line_length": 23.8734177215,
"ext": "c",
"hexsha": "5f9fe694ad35a52e1bb0854923524020964775c6",
"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": "169787108fd241de041e5846d4f33f9773e8ba9a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "vladutmargineanu/Code-Optimization",
"max_forks_repo_path": "solver_blas.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "169787108fd241de041e5846d4f33f9773e8ba9a",
"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": "vladutmargineanu/Code-Optimization",
"max_issues_repo_path": "solver_blas.c",
"max_line_length": 65,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "169787108fd241de041e5846d4f33f9773e8ba9a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "vladutmargineanu/Code-Optimization",
"max_stars_repo_path": "solver_blas.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 683,
"size": 1886
} |
/* ode-initval2/rk4imp.c
*
* Copyright (C) 2009, 2010 Tuomo Keskitalo
*
* 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.
*/
/* Based on rk4imp.c by Gerard Jungman */
/* Gaussian implicit 4th order Runge-Kutta method. Error estimation
is carried out by the step doubling method.
*/
/* References:
Ascher, U.M., Petzold, L.R., Computer methods for ordinary
differential and differential-algebraic equations, SIAM,
Philadelphia, 1998. ISBN 0898714125, 9780898714128
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
#include "odeiv_util.h"
#include "rksubs.c"
#include "modnewton1.c"
/* Stage of method */
#define RK4IMP_STAGE 2
typedef struct
{
gsl_matrix *A; /* Runge-Kutta coefficients */
double *y_onestep; /* Result with one step */
double *y_twostep; /* Result with two half steps */
double *ytmp; /* Temporary work space */
double *y_save; /* Backup space */
double *YZ; /* Runge-Kutta points */
double *fYZ; /* Derivatives at YZ */
gsl_matrix *dfdy; /* Jacobian matrix */
double *dfdt; /* time derivative of f */
modnewton1_state_t *esol; /* nonlinear equation solver */
double *errlev; /* desired error level of y */
const gsl_odeiv2_driver *driver; /* pointer to driver object */
}
rk4imp_state_t;
static void *
rk4imp_alloc (size_t dim)
{
rk4imp_state_t *state = (rk4imp_state_t *) malloc (sizeof (rk4imp_state_t));
if (state == 0)
{
GSL_ERROR_NULL ("failed to allocate space for rk4imp_state",
GSL_ENOMEM);
}
state->A = gsl_matrix_alloc (RK4IMP_STAGE, RK4IMP_STAGE);
if (state->A == 0)
{
free (state);
GSL_ERROR_NULL ("failed to allocate space for A", GSL_ENOMEM);
}
state->y_onestep = (double *) malloc (dim * sizeof (double));
if (state->y_onestep == 0)
{
gsl_matrix_free (state->A);
free (state);
GSL_ERROR_NULL ("failed to allocate space for y_onestep", GSL_ENOMEM);
}
state->y_twostep = (double *) malloc (dim * sizeof (double));
if (state->y_twostep == 0)
{
free (state->y_onestep);
gsl_matrix_free (state->A);
free (state);
GSL_ERROR_NULL ("failed to allocate space for y_onestep", GSL_ENOMEM);
}
state->ytmp = (double *) malloc (dim * sizeof (double));
if (state->ytmp == 0)
{
free (state->y_twostep);
free (state->y_onestep);
gsl_matrix_free (state->A);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM);
}
state->y_save = (double *) malloc (dim * sizeof (double));
if (state->y_save == 0)
{
free (state->ytmp);
free (state->y_twostep);
free (state->y_onestep);
gsl_matrix_free (state->A);
free (state);
GSL_ERROR_NULL ("failed to allocate space for y_save", GSL_ENOMEM);
}
state->YZ = (double *) malloc (dim * RK4IMP_STAGE * sizeof (double));
if (state->YZ == 0)
{
free (state->y_save);
free (state->ytmp);
free (state->y_twostep);
free (state->y_onestep);
gsl_matrix_free (state->A);
free (state);
GSL_ERROR_NULL ("failed to allocate space for YZ", GSL_ENOMEM);
}
state->fYZ = (double *) malloc (dim * RK4IMP_STAGE * sizeof (double));
if (state->fYZ == 0)
{
free (state->YZ);
free (state->y_save);
free (state->ytmp);
free (state->y_twostep);
free (state->y_onestep);
gsl_matrix_free (state->A);
free (state);
GSL_ERROR_NULL ("failed to allocate space for fYZ", GSL_ENOMEM);
}
state->dfdt = (double *) malloc (dim * sizeof (double));
if (state->dfdt == 0)
{
free (state->fYZ);
free (state->YZ);
free (state->y_save);
free (state->ytmp);
free (state->y_twostep);
free (state->y_onestep);
gsl_matrix_free (state->A);
free (state);
GSL_ERROR_NULL ("failed to allocate space for dfdt", GSL_ENOMEM);
}
state->dfdy = gsl_matrix_alloc (dim, dim);
if (state->dfdy == 0)
{
free (state->dfdt);
free (state->fYZ);
free (state->YZ);
free (state->y_save);
free (state->ytmp);
free (state->y_twostep);
free (state->y_onestep);
gsl_matrix_free (state->A);
free (state);
GSL_ERROR_NULL ("failed to allocate space for dfdy", GSL_ENOMEM);
}
state->esol = modnewton1_alloc (dim, RK4IMP_STAGE);
if (state->esol == 0)
{
gsl_matrix_free (state->dfdy);
free (state->dfdt);
free (state->fYZ);
free (state->YZ);
free (state->y_save);
free (state->ytmp);
free (state->y_twostep);
free (state->y_onestep);
gsl_matrix_free (state->A);
free (state);
GSL_ERROR_NULL ("failed to allocate space for esol", GSL_ENOMEM);
}
state->errlev = (double *) malloc (dim * sizeof (double));
if (state->errlev == 0)
{
modnewton1_free (state->esol);
gsl_matrix_free (state->dfdy);
free (state->dfdt);
free (state->fYZ);
free (state->YZ);
free (state->y_save);
free (state->ytmp);
free (state->y_twostep);
free (state->y_onestep);
gsl_matrix_free (state->A);
free (state);
GSL_ERROR_NULL ("failed to allocate space for errlev", GSL_ENOMEM);
}
state->driver = NULL;
return state;
}
static int
rk4imp_apply (void *vstate, size_t dim, double t, double h,
double y[], double yerr[],
const double dydt_in[], double dydt_out[],
const gsl_odeiv2_system * sys)
{
/* Makes a Gaussian implicit 4th order Runge-Kutta with step size h
and estimates the local error of the step.
*/
rk4imp_state_t *state = (rk4imp_state_t *) vstate;
double *const y_onestep = state->y_onestep;
double *const y_twostep = state->y_twostep;
double *const ytmp = state->ytmp;
double *const y_save = state->y_save;
double *const YZ = state->YZ; /* Runge-Kutta points */
double *const fYZ = state->fYZ;
gsl_matrix *const dfdy = state->dfdy;
double *const dfdt = state->dfdt;
double *const errlev = state->errlev;
const modnewton1_state_t *esol = state->esol;
/* Runge-Kutta coefficients */
gsl_matrix *A = state->A;
const double b[] = { 0.5, 0.5 };
const double c[] = { (3 - sqrt (3)) / 6, (3 + sqrt (3)) / 6 };
gsl_matrix_set (A, 0, 0, 1.0 / 4);
gsl_matrix_set (A, 0, 1, (3 - 2 * sqrt (3)) / 12);
gsl_matrix_set (A, 1, 0, (3 + 2 * sqrt (3)) / 12);
gsl_matrix_set (A, 1, 1, 1.0 / 4);
if (esol == NULL)
{
GSL_ERROR ("no non-linear equation solver speficied", GSL_EINVAL);
}
/* Get desired error levels via gsl_odeiv2_control object through driver
object, which is a requirement for this stepper.
*/
if (state->driver == NULL)
{
return GSL_EFAULT;
}
else
{
size_t i;
for (i = 0; i < dim; i++)
{
if (dydt_in != NULL)
{
gsl_odeiv2_control_errlevel (state->driver->c, y[i],
dydt_in[i], h, i, &errlev[i]);
}
else
{
gsl_odeiv2_control_errlevel (state->driver->c, y[i],
0.0, h, i, &errlev[i]);
}
}
}
/* Evaluate Jacobian for modnewton1 */
{
int s = GSL_ODEIV_JA_EVAL (sys, t, y, dfdy->data, dfdt);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* Calculate a single step with size h */
{
int s = modnewton1_init ((void *) esol, A, h, dfdy, sys);
if (s != GSL_SUCCESS)
{
return s;
}
}
{
int s = modnewton1_solve ((void *) esol, A, c, t, h, y,
sys, YZ, errlev);
if (s != GSL_SUCCESS)
{
return s;
}
}
{
size_t j;
for (j = 0; j < RK4IMP_STAGE; j++)
{
int s =
GSL_ODEIV_FN_EVAL (sys, t + c[j] * h, &YZ[j * dim], &fYZ[j * dim]);
if (s != GSL_SUCCESS)
{
return s;
}
}
}
{
int s = rksubs (y_onestep, h, y, fYZ, b, RK4IMP_STAGE, dim);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* Error estimation by step doubling */
{
int s = modnewton1_init ((void *) esol, A, h / 2.0, dfdy, sys);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* 1st half step */
{
int s = modnewton1_solve ((void *) esol, A, c, t, h / 2.0, y,
sys, YZ, errlev);
if (s != GSL_SUCCESS)
{
return s;
}
}
{
size_t j;
for (j = 0; j < RK4IMP_STAGE; j++)
{
int s = GSL_ODEIV_FN_EVAL (sys, t + c[j] * h / 2.0, &YZ[j * dim],
&fYZ[j * dim]);
if (s != GSL_SUCCESS)
{
return s;
}
}
}
{
int s = rksubs (ytmp, h / 2.0, y, fYZ, b, RK4IMP_STAGE, dim);
if (s != GSL_SUCCESS)
return s;
}
/* Save original y values in case of error */
DBL_MEMCPY (y_save, y, dim);
/* 2nd half step */
{
int s = modnewton1_solve ((void *) esol, A, c, t + h / 2.0, h / 2.0,
ytmp, sys, YZ, errlev);
if (s != GSL_SUCCESS)
{
return s;
}
}
{
size_t j;
for (j = 0; j < RK4IMP_STAGE; j++)
{
int s =
GSL_ODEIV_FN_EVAL (sys, t + h / 2.0 + c[j] * h / 2.0, &YZ[j * dim],
&fYZ[j * dim]);
if (s != GSL_SUCCESS)
{
return s;
}
}
}
{
int s = rksubs (y_twostep, h / 2.0, ytmp, fYZ, b, RK4IMP_STAGE, dim);
if (s != GSL_SUCCESS)
{
DBL_MEMCPY (y, y_save, dim);
return s;
}
}
/* Note: rk4imp returns y using the results from two half steps
instead of the single step since the results are freely
available and more precise.
*/
DBL_MEMCPY (y, y_twostep, dim);
/* Error estimation */
{
size_t i;
for (i = 0; i < dim; i++)
{
yerr[i] = ODEIV_ERR_SAFETY * 0.5 *
fabs (y_twostep[i] - y_onestep[i]) / 15.0;
}
}
/* Derivatives at output */
if (dydt_out != NULL)
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out);
if (s != GSL_SUCCESS)
{
/* Restore original values */
DBL_MEMCPY (y, y_save, dim);
return s;
}
}
return GSL_SUCCESS;
}
static int
rk4imp_set_driver (void *vstate, const gsl_odeiv2_driver * d)
{
rk4imp_state_t *state = (rk4imp_state_t *) vstate;
state->driver = d;
return GSL_SUCCESS;
}
static int
rk4imp_reset (void *vstate, size_t dim)
{
rk4imp_state_t *state = (rk4imp_state_t *) vstate;
DBL_ZERO_MEMSET (state->y_onestep, dim);
DBL_ZERO_MEMSET (state->y_twostep, dim);
DBL_ZERO_MEMSET (state->ytmp, dim);
DBL_ZERO_MEMSET (state->y_save, dim);
DBL_ZERO_MEMSET (state->YZ, dim * RK4IMP_STAGE);
DBL_ZERO_MEMSET (state->fYZ, dim * RK4IMP_STAGE);
return GSL_SUCCESS;
}
static unsigned int
rk4imp_order (void *vstate)
{
rk4imp_state_t *state = (rk4imp_state_t *) vstate;
state = 0; /* prevent warnings about unused parameters */
return 4;
}
static void
rk4imp_free (void *vstate)
{
rk4imp_state_t *state = (rk4imp_state_t *) vstate;
free (state->errlev);
modnewton1_free (state->esol);
gsl_matrix_free (state->dfdy);
free (state->dfdt);
free (state->fYZ);
free (state->YZ);
free (state->y_save);
free (state->ytmp);
free (state->y_twostep);
free (state->y_onestep);
gsl_matrix_free (state->A);
free (state);
}
static const gsl_odeiv2_step_type rk4imp_type = {
"rk4imp", /* name */
1, /* can use dydt_in? */
1, /* gives exact dydt_out? */
&rk4imp_alloc,
&rk4imp_apply,
&rk4imp_set_driver,
&rk4imp_reset,
&rk4imp_order,
&rk4imp_free
};
const gsl_odeiv2_step_type *gsl_odeiv2_step_rk4imp = &rk4imp_type;
| {
"alphanum_fraction": 0.5653625213,
"avg_line_length": 24.1688555347,
"ext": "c",
"hexsha": "99267169ac74ba2fe2b2ce119687cc2a43eaa67f",
"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": "b723fcad149662a9af981c4e507678d9c7f106d2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "WikiGaze/Wikipedia-readers-gaze",
"max_forks_repo_path": "Integration/gsl-1.15/ode-initval2/rk4imp.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b723fcad149662a9af981c4e507678d9c7f106d2",
"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": "WikiGaze/Wikipedia-readers-gaze",
"max_issues_repo_path": "Integration/gsl-1.15/ode-initval2/rk4imp.c",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b723fcad149662a9af981c4e507678d9c7f106d2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "WikiGaze/Wikipedia-readers-gaze",
"max_stars_repo_path": "Integration/gsl-1.15/ode-initval2/rk4imp.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3876,
"size": 12882
} |
#ifndef PHI_SVM
#define PHI_SVM
#include <float.h>
#include <vector>
#include <list>
#include <fstream>
#include <iostream>
#include <cmath>
#include <cassert>
#include <cstring>
#include <cstdlib>
#include <sys/time.h>
// BLAS dependency
#ifdef USE_MKL
#include <mkl.h>
#else
typedef int MKL_INT;
#if defined __APPLE__
#include <Accelerate/Accelerate.h>
#else
extern "C" {
#include <cblas.h>
}
#endif
#endif
#include <string>
#include <boost/serialization/serialization.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <sstream>
using namespace std;
#define BLOCKSIZE 256
#define REDUCE0 0x00000001
#define REDUCE1 0x00000002
#define MAX_PITCH 262144
#define MAX_POINTS (MAX_PITCH / sizeof(float) - 2)
#define MAXITERATIONS 100000
#define intDivideRoundUp(a, b) (a % b != 0) ? (a / b + 1) : (a / b)
enum KernelType {
NEWLINEAR,
NEWGAUSSIAN,
NEWPRECOMPUTED
};
struct Kernel_params {
float gamma;
float coef0;
int degree;
float b;
std::string kernel_type;
};
enum SelectionHeuristic {
FIRSTORDER,
SECONDORDER,
RANDOM,
ADAPTIVE
};
class PhiSVMModel {
public:
int nSamples;
int nDimension;
float epsilon;
float bLow;
float bHigh;
float* alpha;
float* f;
float* kernelDiag;
float* data;
float* labels;
PhiSVMModel() { // default constructor for training from the scratch
}
PhiSVMModel(int maxPoints, int maxDimension) { // constructor for getting an existing model
alpha = new float[maxPoints];
f = new float[maxPoints];
kernelDiag = new float[maxPoints];
data = new float[maxPoints*maxDimension];
labels = new float[maxPoints];
}
~PhiSVMModel() { // leave the data and labels to others to delete
delete alpha;
delete f;
delete kernelDiag;
}
};
class NewCache {
public:
NewCache(int nPointsIn, int cacheSizeIn);
~NewCache();
void findData(const int index, int& offset, bool& compute);
void search(const int index, int& offset, bool& compute);
void printCache();
void printStatistics();
private:
int nPoints;
int cacheSize;
class DirectoryEntry {
public:
enum {
NEVER,
EVICTED,
INCACHE
};
DirectoryEntry();
int status;
int location;
std::list<int>::iterator lruListEntry;
};
std::vector<DirectoryEntry> directory;
std::list<int> lruList;
int occupancy;
int hits;
int compulsoryMisses;
int capacityMisses;
};
class Controller {
public:
Controller(float initialGap, SelectionHeuristic currentMethodIn,
int samplingIntervalIn, int problemSize);
void addIteration(float gap);
void print();
SelectionHeuristic getMethod();
private:
bool adaptive;
int samplingInterval;
std::vector<float> progress;
std::vector<int> method;
SelectionHeuristic currentMethod;
std::vector<float> rates;
int timeSinceInspection;
int inspectionPeriod;
int beginningOfEpoch;
int middleOfEpoch;
int currentInspectionPhase;
float filter(int begin, int end);
float findRate(struct timeval* start, struct timeval* finish, int beginning,
int end);
struct timeval start;
struct timeval mid;
struct timeval finish;
};
bool hasTwoTypes(float* labels, int n);
float crossValidation(float* data, int nPoints, int nDimension,
int nFolds, float* labels, Kernel_params* kp,
float cost, SelectionHeuristic heuristicMethod,
float epsilon, float tolerance,
float* transposedData, bool shuffle);
float incrementalCrossValidation(PhiSVMModel** models, float* data, int nPoints, int nDimension,
int nFolds, float* labels, Kernel_params* kp,
float cost, SelectionHeuristic heuristicMethod,
float epsilon, float tolerance,
float* transposedData, int maxNPoints);
void svmGroupClasses(int nPoints, float* labels, int** start_ret,
int** count_ret, int* perm);
PhiSVMModel* performTraining(float* data, int nPoints, int nDimension, float* labels,
Kernel_params* kp, float cost,
SelectionHeuristic heuristicMethod, float epsilon,
float tolerance, float* transposedData, PhiSVMModel* curModel);
PhiSVMModel* performOnlineTraining(int nOldPoints, Kernel_params* kp, float cost,
SelectionHeuristic heuristicMethod, float epsilon,
float tolerance, PhiSVMModel* curModel);
template <int Kernel>
void firstOrder(float* devData, int devDataPitchInFloats,
float* devTransposedData, int devTransposedDataPitchInFloats,
float* devLabels, int nPoints, int nDimension, float epsilon,
float cEpsilon, float* devAlpha, float* devF, float alpha1Diff,
float alpha2Diff, int iLow, int iHigh, float parameterA,
float parameterB, float parameterC, float* devCache,
int devCachePitchInFloats, int iLowCacheIndex,
int iHighCacheIndex, float* devKernelDiag, void* devResult,
float cost, bool iLowCompute, bool iHighCompute, int nthreads);
void launchFirstOrder(bool iLowCompute, bool iHighCompute, int kType,
int nPoints, int nDimension, float* devData,
int devDataPitchInFloats, float* devTransposedData,
int devTransposedDataPitchInFloats, float* devLabels,
float epsilon, float cEpsilon, float* devAlpha,
float* devF, float sAlpha1Diff, float sAlpha2Diff,
int iLow, int iHigh, float parameterA, float parameterB,
float parameterC, float* devCache,
int devCachePitchInFloats, int iLowCacheIndex,
int iHighCacheIndex, float* devKernelDiag,
void* devResult, float cost, int nthreads);
template <int Kernel>
void secondOrder(float* devData, int devDataPitchInFloats,
float* devTransposedData, int devTransposedDataPitchInFloats,
float* devLabels, int nPoints, int nDimension, float epsilon,
float cEpsilon, float* devAlpha, float* devF, float alpha1Diff,
float alpha2Diff, int iLow, int iHigh, float parameterA,
float parameterB, float parameterC, float* devCache,
int devCachePitchInFloats, int iLowCacheIndex,
int iHighCacheIndex, float* devKernelDiag, void* devResult,
float cost, float bHigh, bool iHighCompute, int nthreads);
void launchSecondOrder(bool iLowCompute, bool iHighCompute, int kType,
int nPoints, int nDimension, float* devData,
int devDataPitchInFloats, float* devTransposedData,
int devTransposedDataPitchInFloats, float* devLabels,
float epsilon, float cEpsilon, float* devAlpha,
float* devF, float sAlpha1Diff, float sAlpha2Diff,
int iLow, int iHigh, float parameterA, float parameterB,
float parameterC, NewCache* kernelCache, float* devCache,
int devCachePitchInFloats, int iLowCacheIndex,
int iHighCacheIndex, float* devKernelDiag,
void* devResult, float cost, int iteration,
int nthreads);
template <int Kernel>
void initializeArrays(float* devData, int devDataPitchInFloats, float* devCache,
int devCachePitchInFloats, int nPoints, int nDimension,
float parameterA, float parameterB, float parameterC,
float* devKernelDiag, float* devAlpha, float* devF,
float* devLabels, int nthreads);
void launchInitialization(float* devData, int devDataPitchInFloats,
float* devCache, int devCachePitchInFloats,
int nPoints, int nDimension, int kType,
float parameterA, float parameterB, float parameterC,
float* devKernelDiag, float* devAlpha, float* devF,
float* devLabels, int nthreads);
template <int Kernel>
void takeFirstStep(void* devResult, float* devKernelDiag, float* devData,
int devDataPitchInFloats, float* devCache,
int devCachePitchInFloats, float* devAlpha, float cost,
int nDimension, int iLow, int iHigh, float parameterA,
float parameterB, float parameterC);
void launchTakeFirstStep(void* devResult, float* devKernelDiag, float* devData,
int devDataPitchInFloats, float* devCache,
int devCachePitchInFloats, float* devAlpha, float cost,
int nDimension, int iLow, int iHigh, int kType,
float parameterA, float parameterB, float parameterC,
int nthreads);
void performClassification(float* data, int nData, int nDimension,
Kernel_params* kp, float** p_result, PhiSVMModel* model);
void computeKernels(float* devNorms, int devNormsPitchInFloats, float* devAlpha,
int nPoints, int nSV, const KernelType kType, int degree,
float b, float* devResult);
float kernel(const float v, const int degree, const KernelType kType);
void makeSelfDots(float* devSource, int devSourcePitchInFloats, float* devDest,
int sourceCount, int sourceLength);
void makeDots(float* devDots, int devDotsPitchInFloats, float* devSVDots,
float* devDataDots, int nSV, int nPoints);
class DumpModel {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & nSamples;
ar & nDimension;
for (int i=0; i<nSamples*nDimension; i++) {
ar & trainingData[i];
}
ar & phiSVMModel->nSamples; // redundant with Model::nSamples
ar & phiSVMModel->nDimension; // for precomputed kernel, should be the same as nSamples
ar & phiSVMModel->epsilon;
ar & phiSVMModel->bLow;
ar & phiSVMModel->bHigh;
for (int i=0; i<phiSVMModel->nSamples; i++) {
ar & phiSVMModel->alpha[i];
}
for (int i=0; i<phiSVMModel->nSamples; i++) {
ar & phiSVMModel->f[i];
}
for (int i=0; i<phiSVMModel->nSamples; i++) {
ar & phiSVMModel->kernelDiag[i];
}
// the data here for precomputed kernel is the kernel matrix
for (int i=0; i<phiSVMModel->nSamples*phiSVMModel->nDimension; i++) {
ar & phiSVMModel->data[i];
}
for (int i=0; i<phiSVMModel->nSamples; i++) {
ar & phiSVMModel->labels[i];
}
}
public:
int nSamples;
int nDimension;
float* trainingData;
PhiSVMModel* phiSVMModel;
DumpModel() {}
DumpModel(int s, int d) {
nSamples = s;
nDimension = d;
trainingData = new float[s*d];
phiSVMModel = new PhiSVMModel(MAX_POINTS, MAX_POINTS);
}
~DumpModel() {
//delete trainingData;
//delete phiSVMModel->data;
//delete phiSVMModel->labels;
//delete phiSVMModel;
}
};
std::string serialize_DumpModel(DumpModel* model_ptr);
DumpModel* deserialize_DumpModel(std::string, int, int);
void DumpModelToDisk(std::string modelStr);
#endif | {
"alphanum_fraction": 0.6455008196,
"avg_line_length": 36.9140127389,
"ext": "h",
"hexsha": "b1c53dddc2937242824534496c91feb8c8d4bcb7",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2020-06-08T18:06:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-08-26T19:37:29.000Z",
"max_forks_repo_head_hexsha": "74f151d07d683fc2b1612b5b0e2cb29617b69c03",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "PrincetonUniversity/fcma-toolbox",
"max_forks_repo_path": "deps/SVM-phi/phisvm.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "74f151d07d683fc2b1612b5b0e2cb29617b69c03",
"max_issues_repo_issues_event_max_datetime": "2017-07-27T08:11:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-08-17T01:05:36.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "PrincetonUniversity/fcma-toolbox",
"max_issues_repo_path": "deps/SVM-phi/phisvm.h",
"max_line_length": 96,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "74f151d07d683fc2b1612b5b0e2cb29617b69c03",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "PrincetonUniversity/fcma-toolbox",
"max_stars_repo_path": "deps/SVM-phi/phisvm.h",
"max_stars_repo_stars_event_max_datetime": "2019-03-16T17:34:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-29T04:27:01.000Z",
"num_tokens": 2811,
"size": 11591
} |
# ifndef LANGIL_H
# define LANGIL_H
///////////////////////////////////////////////////////
////// GILLESPIE CLASS
//////
////// R. Perez-Carrasco
////// Created: 16 Nov '13
///////////////////////////////////////////////////////
/* Class for simulating master equation through langil algorythm. It defines three classes:
- langil: In charge of the integration
- species: contains a name a number and methods to change number
- reaction: contains a name, a stoiciometry associated and a pointer to a propensity computing function
*/
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <string>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <math.h>
#include <time.h>
#include <unistd.h>
#include <iomanip>
//#include <omp.h>
#include "species.h"
#include "cell_cycle.h"
#define VERBOSE 1
#define NON_VERBOSE 0
#define TIMESTEPMULT 3
#define TIMESTEP 0
#define ALL 1
#define NOWRITE 2
#define LASTPOINT 4
#define GILLESPIE 0
#define MACROSCOPIC 2
#define CLEEULER 1
#define CLEMILSTEIN 3
#define ADIABATIC true
#define NONADIABATIC false
#define GEOMETRIC true
#define NONGEOMETRIC false
#define DETERMINISTIC_TIME true
#define STOCHASTIC_TIME false
#define EXPONENTIAL_REACTION 0
#define GEOMETRIC_REACTION 1
#define DETERMINISTIC_REACTION 2
#define ADIABATIC_REACTION 3
using namespace std;
struct StructDivisionState{
double time;
double species0before;
double species1before;
double species0after;
double species1after;
};
class reaction; // defined after langil
class species; // defined after reaction
class expressionzone; // defined in a separate file
class langil{
friend class expressionzone;
// friend class reaction; // reaction have access to the state of the system
public:
langil(string outputfilename, double vol=100, int seed=-1);
void SetState(string aname, float anumber); //Set Initial conditions
double GetState(string a); // get the state of the selected species
void SetTime(double time); //Set current time
void AddSpecies(string aname, float anum); // Add a new molecular species
void AddSpeciesTimeTracking(string aname, float anum, double lifetime); // Add a molecular species with a timer
void AddCellCycleSpecies(); // add a cell cycle to the system
void addCellPhase(double duration, int type_phase); // add a cell phase to the cell cycle
void PrintSummarySpecies();
string StateString();
void Add_Reaction(string name,vector<int> stoich,double (*prop_f)(v_species&),int typeofrec = EXPONENTIAL_REACTION); // Add a reaction to the system overloaded to create directly
void UpdateTime(); // Update times for the deterministic events
void SetRunType(int rt,double dt=0);
double GillespieStep(double timelimit = -1); // Advance one step in the Gillespie algorithm. Returns time of the step. Timelimit does not react if the reaction would take more than timelimit
double LangevinEulerStep(double timelimit = -1); // Make an Euler-Maruyama integration step
double LangevinMilsteinStep(double timelimit = -1); // Make an SDE integration step with the Milstein algorithm (not tested)
double MacroStep(double timlimit = -1); // Make an Euler (deterministic) step
double MacroAdiabaticStep(double dtt); // Make an Euler step if the Adiabaitc species
double Run(double time, bool verbose=true); // React until reach time time
double RunTimes(int N,double time, bool verbose=true); // Run Run() N times
double RunTransition(bool (*prop_f)(v_species&), bool (*prop_g)(v_species&), int loops, double maxT); // Run transition between two points, if loops=1 it also records the transition trajectory
void WriteState(); // Write state in file
void WriteTempState(); // Write state in file
void WritePrevrecState(); // Write previous recorded state in file
void SetWriteState(int flag, double tl=0);// Switch betweem different states:
double (langil::*MakeStep)(double); // pointer to the actual integration chosen
// TIMESTEP: write the state every tl time lapse
// ALL: write after each reaction takes place
// NOWRITE: don't write anything in output file
double SetLangevinTimeStep(double dx); // set dt to a characteristic time that will increase with the size of the system
void Add_TimeAction(double (*actionfunc)(double));
void RunTimeAction();
void setPhaseDuration(int phase, double duration, int type_phase);
void Set_AdiabaticReaction(string aname);
void Set_GeometricReaction(string aname);
void Set_Boundary_Behaviour(void (*b_b)(v_species&, v_species&)); // Boundary behaviour
void Set_StoreDivisionTimes();// activate the storage of division times in DivisionTimes vector
void (*Boundary_Behaviour)(v_species&, v_species&); // boundary behaviour function
vector<StructDivisionState> Get_HistoryDivision();
void Reset_HistoryDivision();
void SetDivisionHistory(int b,int a);
protected:
v_species x; //value of each species. shared_ptr is used since the vector can contain species and also childrens of that class (i.e. different classes)
vector<reaction> r;//vector with all the reactions
double time; // current time of simulation
gsl_rng * rng; // allocator for the rng generator
vector<double> rnd; // rnd numbers
vector<double> xtemp; // temporal vector for integrations
v_species xtemp0,xtemp1; // temporal vector for integrations
double pro,pro0; // auxiliar variables for the program
int sto; // auxiliar value for stoichiometry
double totalprop,cumprop, detprop; // sum of the propensities
double nexttau; // time of the next step
vector<reaction>::iterator nextreaction; // reaction selected to react
vector<int>* nextstoichiometry;
double Omega; // volume of the system to change between concentrations and absolute numbers
double signal; // variable that can modulate an external signal its time course
// may be changed through time actions with Add_TimeAction
int celldivided; // flag to track possible celldivision
int geostoichiometry; // dummy variable to set random geometric stoichiometries
bool record; // Set record of the trajectory
ofstream trajfile; // File for output traj
string outputfilename; // File for output name
int fwrite; // flag for write state when integrating
double timelapse; // dt for recording if TIMESTEP
double nextrectime; // t for recording if TIMESTEP
double totaltime; // total integration time for the trajectory
double dt; // timestep used in integrations for macroscopic and langevin (if negative, it is used by Langevin as a prediction for dx)
int cellcyclespeciesidx; // index of the species vector that tracks cell cycle phases
cell_cycle cell; // cell_cycle object to manage cell cycle events
bool fStoreDivisionTimes; // flag to store Division Times
vector<StructDivisionState> DivisionHistoryVector; // Division history vector. Each component is a vector
StructDivisionState divisionstate;
vector<double(*)(double)> actionfuncvec; // vector to time action functions
};
////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
class reaction{//Class containing the info of each reaction. Each reaction added
// through the method Add_Reaction(reaction) will be stored as an element in a vector
// by langil class. The pointer x, points out to the state of the langil system and
// is managed automatically by langil when a reaction is added to a langil instance
// It has also the property "adiabatic" meaning that it is a fast variable and can always be simulated
// from its deterministic behaviour
friend class langil;
public:
reaction(string aname,vector<int> asto,double (*aprop_f)(v_species&)=NULL,int reacttype= EXPONENTIAL_REACTION,
vector<reaction>* x0=NULL){
name=aname;
stoichiometry=asto;
prop_f=aprop_f;
reactiontype=reacttype;
}
double GetPropensity(){
return prop_f(*x);
}
double GetPropensity(v_species& x0){
return prop_f(x0);
}
string GetName(){
return name;
}
void SetPropensity(double (*p_f)(v_species&)){
prop_f=p_f;
}
void SetState(v_species& x0){
x=&x0;
}
vector<int>* GetStoichiometry(){
return &stoichiometry;
}
bool IsAdiabatic(){
return (reactiontype == ADIABATIC_REACTION);
}
bool IsNotAdiabatic(){
return (reactiontype != ADIABATIC_REACTION);
}
bool IsGeometric(){
return (reactiontype == GEOMETRIC_REACTION);
}
bool IsNotGeometric(){
return (reactiontype != GEOMETRIC_REACTION);
}
bool IsNotDetermTime(){
return (reactiontype != (DETERMINISTIC_REACTION));
}
bool IsDetermTime(){
return (reactiontype == (DETERMINISTIC_REACTION));
}
void SetAdiabatic(){
reactiontype = ADIABATIC_REACTION;
}
void SetGeometric(){
reactiontype = GEOMETRIC_REACTION;
}
void SetDeterministicTime(){
reactiontype = DETERMINISTIC_REACTION;
}
protected:
string name; // name of the reactio
vector<int> stoichiometry; // stoichiometry
double (*prop_f)(v_species&); // propensity function
v_species* x; //value of each species. shared_ptr is used since the vector can contain species and also childrens of that class (i.e. different classes)
int reactiontype; // can be any of the macros EXPONENTIAL_REACTION, DETERMINISITIC_REACTION, etc.
// of the system
};
#endif
| {
"alphanum_fraction": 0.7259227832,
"avg_line_length": 37.1181102362,
"ext": "h",
"hexsha": "b5eecb5545d8e2a6d5cb4e95081883b2985c997e",
"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": "e2e41d8d00f7de9a1ba1c014d4bac8b364dbd856",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "2piruben/langil",
"max_forks_repo_path": "langil.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e2e41d8d00f7de9a1ba1c014d4bac8b364dbd856",
"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": "2piruben/langil",
"max_issues_repo_path": "langil.h",
"max_line_length": 194,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e2e41d8d00f7de9a1ba1c014d4bac8b364dbd856",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "2piruben/langil",
"max_stars_repo_path": "langil.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2323,
"size": 9428
} |
/**
* File: spce_pgp.h
* Interface to PGplot routines.
*
*/
#ifndef _SPCE_PGP_H
#define _SPCE_PGP_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_vector.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
#include "spce_pathlength.h"
#include "spce_output.h"
extern void
pgp_stamp_image (const ap_pixel * const ap_p, const int n_sub,
const object * ob, int beamnum, char filename[],
const int negative);
#endif /* !_SPCE_PGP_H */
| {
"alphanum_fraction": 0.719237435,
"avg_line_length": 19.8965517241,
"ext": "h",
"hexsha": "83470ab2765df933e20ac983b067597465d68831",
"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/spce_pgp.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/spce_pgp.h",
"max_line_length": 62,
"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/spce_pgp.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 172,
"size": 577
} |
/* cdf/hypergeometric.c
*
* Copyright (C) 2004 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.
*/
/*
* Computes the cumulative distribution function for a hypergeometric
* random variable. A hypergeometric random variable X is the number
* of elements of type 1 in a sample of size t, drawn from a population
* of size n1 + n2, in which n1 are of type 1 and n2 are of type 2.
*
* This algorithm computes Pr( X <= k ) by summing the terms from
* the mass function, Pr( X = k ).
*
* References:
*
* T. Wu. An accurate computation of the hypergeometric distribution
* function. ACM Transactions on Mathematical Software. Volume 19, number 1,
* March 1993.
* This algorithm is not used, since it requires factoring the
* numerator and denominator, then cancelling. It is more accurate
* than the algorithm used here, but the cancellation requires more
* time than the algorithm used here.
*
* W. Feller. An Introduction to Probability Theory and Its Applications,
* third edition. 1968. Chapter 2, section 6.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_randist.h>
#include "error.h"
static double
lower_tail (const unsigned int k, const unsigned int n1,
const unsigned int n2, const unsigned int t)
{
double relerr;
int i = k;
double s, P;
s = gsl_ran_hypergeometric_pdf (i, n1, n2, t);
P = s;
while (i > 0)
{
double factor =
(i / (n1 - i + 1.0)) * ((n2 + i - t) / (t - i + 1.0));
s *= factor;
P += s;
relerr = s / P;
if (relerr < GSL_DBL_EPSILON)
break;
i--;
}
return P;
}
static double
upper_tail (const unsigned int k, const unsigned int n1,
const unsigned int n2, const unsigned int t)
{
double relerr;
unsigned int i = k + 1;
double s, Q;
s = gsl_ran_hypergeometric_pdf (i, n1, n2, t);
Q = s;
while (i < t)
{
double factor =
((n1 - i) / (i + 1.0)) * ((t - i) / (n2 + i + 1.0 - t));
s *= factor;
Q += s;
relerr = s / Q;
if (relerr < GSL_DBL_EPSILON)
break;
i++;
}
return Q;
}
/*
* Pr (X <= k)
*/
double
gsl_cdf_hypergeometric_P (const unsigned int k,
const unsigned int n1,
const unsigned int n2, const unsigned int t)
{
double P;
if (t > (n1 + n2))
{
CDF_ERROR ("t larger than population size", GSL_EDOM);
}
else if (k >= n1 || k >= t)
{
P = 1.0;
}
else if (k < 0.0)
{
P = 0.0;
}
else
{
double midpoint = (int) (t * n1 / (n1 + n2));
if (k >= midpoint)
{
P = 1 - upper_tail (k, n1, n2, t);
}
else
{
P = lower_tail (k, n1, n2, t);
}
}
return P;
}
/*
* Pr (X > k)
*/
double
gsl_cdf_hypergeometric_Q (const unsigned int k,
const unsigned int n1,
const unsigned int n2, const unsigned int t)
{
double Q;
if (t > (n1 + n2))
{
CDF_ERROR ("t larger than population size", GSL_EDOM);
}
else if (k >= n1 || k >= t)
{
Q = 0.0;
}
else if (k < 0.0)
{
Q = 1.0;
}
else
{
double midpoint = (int) (t * n1 / (n1 + n2));
if (k < midpoint)
{
Q = 1 - lower_tail (k, n1, n2, t);
}
else
{
Q = upper_tail (k, n1, n2, t);
}
}
return Q;
}
| {
"alphanum_fraction": 0.5743211053,
"avg_line_length": 22.8152173913,
"ext": "c",
"hexsha": "c0dee39f5598dbfd8911908cf6da986b8aded413",
"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/cdf/hypergeometric.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/cdf/hypergeometric.c",
"max_line_length": 77,
"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/cdf/hypergeometric.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": 1239,
"size": 4198
} |
#include <assert.h>
#include <inttypes.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <gsl/gsl_math.h>
#include "imshift.h"
#include "conv1.h"
void showMatrix(double * I, size_t M, size_t N)
{
for(size_t kk = 0; kk<N; kk++) {
for(size_t ll = 0; ll<M; ll++)
{
printf("%5.2f ", I[ll*M+kk]);
}
printf("\n");
}
}
int imshift3(double * V, size_t M, size_t N, size_t P,
double dx, double dy, double dz, int method)
{
int status = 0;
double * Kx = NULL; size_t nKx;
double * Ky = NULL; size_t nKy;
double * Kz = NULL; size_t nKz;
status = generateShift(&Kx, dx, &nKx, method);
if(status != 0)
return -1;
status = generateShift(&Ky, dy, &nKy, method);
if(status != 0) {
free(Kx);
return -2;
}
status = generateShift(&Kz, dz, &nKz, method);
if(status != 0) {
free(Kx);
free(Ky);
return -3;
}
status = conv1_3(V, M, N, P,
Kx, nKx,
Ky, nKy,
Kz, nKz);
free(Kz);
free(Ky);
free(Kx);
return status;
}
int generateShift(double ** K, double delta, size_t * size, int order)
/** Allocate space for a 1D shifting kernel, K,
* shifted by delta in [-1,1]
* returns the size of the kernel in size
* order sets the polynomial order, 1 = linear, 2 = quadratic
*
* Errors:
* -1, K != NULL
* -2, no valid interpolation method selected
* -3, unable to allocate memory for the kernel
*
* */
{
if(K[0]!=NULL)
return -1;
if(order == 1)
{
size_t N = 3;
size[0] = N;
K[0] = malloc(N*sizeof(double));
if(K[0] == NULL)
return(-3);
for(size_t kk = 0; kk<N; kk++)
K[0][kk] = GSL_MAX(0, 1-fabs(kk-(1-delta)));
return 0;
}
if(order == 3)
{
size_t N = 5;
size[0] = N;
K[0] = malloc(N*sizeof(double));
if(K[0] == NULL)
return -3;
// set up and solve polynomial equation here
double a = -.5;
for(size_t kk = 0; kk < N; kk++)
{
double x = kk-(2-delta);
double ax = fabs(x);
if(ax<=1)
K[0][kk] = (a+2)*ax*ax*ax - (a+3)*ax*ax + 1;
if(ax>1)
K[0][kk] = a*ax*ax*ax -5*a*ax*ax +8*a*ax -4*a;
if(ax>2)
K[0][kk] = 0;
}
return 0;
}
return -2;
}
int main(int argc, char ** argv)
{
printf("Running %s\n", argv[0]);
if(argc>1)
printf("Warning: unused command line arguments\n");
{
printf("--> Testing kernels\n");
double * K;
double sum;
for(double delta = -.5; delta < .6; delta+=.1) {
for(int method = 1; method < 4; method = method +2)
{
K = NULL;
size_t nK = 0;
assert(generateShift(&K, delta, &nK, 3)==0);
sum = 0;
for(int kk = 0; kk<(int) nK; kk++)
sum += K[kk];
printf("delta: %f order: %d sum: %f\n", delta, method, sum);
free(K);
}
}
}
{
printf("--> Testing 1D\n");
double delta = .3;
size_t N = 10;
double * V = malloc(N*sizeof(double));
for(size_t kk=0; kk<N; kk++)
V[kk] = kk%2;
double * K = NULL;
size_t nK = 0;
assert(generateShift(&K, delta, &nK, 3)==0);
printf("Kernel:\n");
for(size_t kk = 0; kk<nK; kk++)
printf("%.1f ", K[kk]);
printf("\n");
printf("Input:\n");
for(size_t kk = 0; kk<N; kk++)
printf("%.1f ", V[kk]);
printf("\n");
double * buff = calloc(N,sizeof(double));
conv1(V, buff, N, K, nK, 1);
printf("Output\n");
for(size_t kk = 0; kk<N; kk++)
printf("%.1f ", V[kk]);
printf("\n");
free(buff);
free(K);
free(V);
}
{
printf("Testing 2D\n");
size_t M = 11;
size_t N = 11;
double * Kx = NULL;
double * Ky = NULL;
size_t nKx;
size_t nKy;
double deltax = .1;
double deltay = .6;
int method = 1;
assert(generateShift(&Kx, deltax, &nKx, method)==0);
assert(generateShift(&Ky, deltay, &nKy, method)==0);
printf("Kernels:\n");
double sum = 0;
printf(" deltax: %f\n", deltax);
for(size_t kk = 0; kk<nKx; kk++) {
printf("%5.1f ", Kx[kk]);
sum += Kx[kk];
}
printf("s: %.2f\n", sum);
sum = 0;
printf(" deltay: %f\n", deltay);
for(size_t kk = 0; kk<nKy; kk++) {
printf("%5.1f ", Ky[kk]);
sum += Ky[kk];
}
printf("s: %.2f\n", sum);
double * V = calloc(M*N, sizeof(double));
V[(M*N-1)/2] = 1;
printf("V:\n");
showMatrix(V, M, N);
double * C1 = malloc(M*N*sizeof(double));
double * C2 = malloc(M*N*sizeof(double));
memcpy(C1,V, M*N*sizeof(double));
memcpy(C2,V, M*N*sizeof(double));
conv1_3(C1, M, N, 1, Kx, nKx, Ky, nKy, NULL, 0);
conv1_3(C2, M, N, 1, Ky, nKy, Kx, nKx, NULL, 0);
printf("C1\n");
showMatrix(C1, M, N);
printf("C2\n");
showMatrix(C2, M, N);
printf("Testing symmetry, C1=C2' ... ");
for(size_t kk = 0; kk<M; kk++)
for(size_t ll = 0; ll<N; ll++)
assert(C1[kk+M*ll] == C2[ll+M*kk]);
printf("ok!\n");
free(V);
free(Ky);
free(Kx);
free(C1);
free(C2);
}
{
printf("Testing 3D\n");
double delta = .3;
size_t M = 11;
size_t N = 11;
size_t P = 11;
double * V3 = calloc(M*N*P,sizeof(double));
V3[(M*N*P-1)/2] = 1;
double * K = NULL;
size_t nK = 0;
assert(generateShift(&K, delta, &nK, 1)==0);
clock_t t1 = clock();
conv1_3(V3, M, N,P, K,nK,K,nK,K,nK);
clock_t t2 = clock();
printf("V3(:,:,6):\n");
showMatrix(V3 + M*N*6, M, N);
printf("Time: %f ms\n", (double) 1000*(t2-t1)/CLOCKS_PER_SEC);
free(V3);
free(K);
}
return 0;
}
| {
"alphanum_fraction": 0.5076079264,
"avg_line_length": 19.9014084507,
"ext": "c",
"hexsha": "f89bdf8e51831bb0be82f1ccbff8430671f12d04",
"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": "8fe0ab3610ff5473bccbac169795a0d1b72c1938",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "elgw/dotter",
"max_forks_repo_path": "common/mex/imshift.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938",
"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": "elgw/dotter",
"max_issues_repo_path": "common/mex/imshift.c",
"max_line_length": 70,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "elgw/dotter",
"max_stars_repo_path": "common/mex/imshift.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-15T08:20:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-15T08:20:13.000Z",
"num_tokens": 2022,
"size": 5652
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_histogram.h>
int
main (int argc, char **argv)
{
double a, b;
size_t n;
if (argc != 4)
{
printf ("Usage: gsl-histogram xmin xmax n\n"
"Computes a histogram of the data "
"on stdin using n bins from xmin "
"to xmax\n");
exit (0);
}
a = atof (argv[1]);
b = atof (argv[2]);
n = atoi (argv[3]);
{
double x;
gsl_histogram * h = gsl_histogram_alloc (n);
gsl_histogram_set_ranges_uniform (h, a, b);
while (fscanf (stdin, "%lg", &x) == 1)
{
gsl_histogram_increment (h, x);
}
gsl_histogram_fprintf (stdout, h, "%g", "%g");
gsl_histogram_free (h);
}
exit (0);
}
| {
"alphanum_fraction": 0.5386702849,
"avg_line_length": 19.3947368421,
"ext": "c",
"hexsha": "a3c5150094f83cfd4c4ab457af4ae1b6b87f5d6c",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/histogram.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/histogram.c",
"max_line_length": 50,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/histogram.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": 218,
"size": 737
} |
//Causal FIR filtering of each row or col of X according to dim.
//FIR impulse responses are given in matrix B.
//For dim=0, X is NxT and B is NxL
//For dim=1, X is TxN and B is LxN
//where N is the number of neurons, T the number of time points, and L the FIR filter order.
#include <stdio.h>
#include <cblas.h>
#ifdef __cplusplus
namespace codee {
extern "C" {
#endif
int fir_s (float *Y, const float *X, const float *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim);
int fir_d (double *Y, const double *X, const double *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim);
int fir_c (float *Y, const float *X, const float *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim);
int fir_z (double *Y, const double *X, const double *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim);
int fir_s (float *Y, const float *X, const float *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim)
{
const float z = 0.0f;
//Initialize Y to 0
cblas_scopy((int)(N*T),&z,0,Y,1);
if (N==1u)
{
for (size_t l=0u; l<L; l++) { cblas_saxpy((int)(T-l),B[l],&X[0],1,&Y[l],1); }
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_saxpy((int)(T-l),B[n+l*N],&X[n],(int)N,&Y[n+l*N],(int)N); }
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_saxpy((int)(T-l),B[n*L+l],&X[n*T],1,&Y[n*T+l],1); }
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_saxpy((int)(T-l),B[n*L+l],&X[n*T],1,&Y[n*T+l],1); }
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_saxpy((int)(T-l),B[n+l*N],&X[n],(int)N,&Y[n+l*N],(int)N); }
}
}
}
else
{
fprintf(stderr,"error in fir_s: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int fir_d (double *Y, const double *X, const double *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim)
{
const double z = 0.0;
//Initialize Y to 0
cblas_dcopy((int)(N*T),&z,0,Y,1);
if (N==1u)
{
for (size_t l=0u; l<L; l++) { cblas_daxpy((int)(T-l),B[l],&X[0],1,&Y[l],1); }
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_daxpy((int)(T-l),B[n+l*N],&X[n],(int)N,&Y[n+l*N],(int)N); }
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_daxpy((int)(T-l),B[n*L+l],&X[n*T],1,&Y[n*T+l],1); }
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_daxpy((int)(T-l),B[n*L+l],&X[n*T],1,&Y[n*T+l],1); }
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_daxpy((int)(T-l),B[n+l*N],&X[n],(int)N,&Y[n+l*N],(int)N); }
}
}
}
else
{
fprintf(stderr,"error in fir_d: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int fir_c (float *Y, const float *X, const float *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim)
{
const float z[2] = {0.0f,0.0f};
//Initialize Y to 0
cblas_ccopy((int)(N*T),z,0,Y,1);
if (N==1u)
{
for (size_t l=0u; l<L; l++) { cblas_caxpy((int)(T-l),&B[2*l],&X[0],1,&Y[2*l],1); }
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_caxpy((int)(T-l),&B[2*(n+l*N)],&X[2*n],(int)N,&Y[2*(n+l*N)],(int)N); }
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_caxpy((int)(T-l),&B[2*(n*L+l)],&X[2*n*T],1,&Y[2*(n*T+l)],1); }
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_caxpy((int)(T-l),&B[2*(n*L+l)],&X[2*n*T],1,&Y[2*(n*T+l)],1); }
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_caxpy((int)(T-l),&B[2*(n+l*N)],&X[2*n],(int)N,&Y[2*(n+l*N)],(int)N); }
}
}
}
else
{
fprintf(stderr,"error in fir_c: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
int fir_z (double *Y, const double *X, const double *B, const size_t N, const size_t T, const size_t L, const char iscolmajor, const size_t dim)
{
const double z[2] = {0.0,0.0};
//Initialize Y to 0
cblas_zcopy((int)(N*T),z,0,Y,1);
if (N==1u)
{
for (size_t l=0u; l<L; l++) { cblas_zaxpy((int)(T-l),&B[2*l],&X[0],1,&Y[2*l],1); }
}
else if (dim==0u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_zaxpy((int)(T-l),&B[2*(n+l*N)],&X[2*n],(int)N,&Y[2*(n+l*N)],(int)N); }
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_zaxpy((int)(T-l),&B[2*(n*L+l)],&X[2*n*T],1,&Y[2*(n*T+l)],1); }
}
}
}
else if (dim==1u)
{
if (iscolmajor)
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_zaxpy((int)(T-l),&B[2*(n*L+l)],&X[2*n*T],1,&Y[2*(n*T+l)],1); }
}
}
else
{
for (size_t n=0u; n<N; ++n)
{
for (size_t l=0u; l<L; l++) { cblas_zaxpy((int)(T-l),&B[2*(n+l*N)],&X[2*n],(int)N,&Y[2*(n+l*N)],(int)N); }
}
}
}
else
{
fprintf(stderr,"error in fir_z: dim must be 0 or 1.\n"); return 1;
}
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.4450771767,
"avg_line_length": 27.5743801653,
"ext": "c",
"hexsha": "f914bd9342ef127fa458140b06c53e22d42d0457",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/nn",
"max_forks_repo_path": "c/fir.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "erikedwards4/nn",
"max_issues_repo_path": "c/fir.c",
"max_line_length": 145,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/nn",
"max_stars_repo_path": "c/fir.c",
"max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z",
"num_tokens": 2438,
"size": 6673
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sort.h>
#include "cosmocalc.h"
gsl_spline *cosmocalc_aexpn2age_spline = NULL;
gsl_interp_accel *cosmocalc_aexpn2age_acc = NULL;
double AGE = 0;
/* function for integration using gsl integration */
static double age_integ_funct(double a, void *p)
{
return 1.0/a/hubble_noscale(a);
}
/* init function - some help from Gadget-2 applied here */
void init_cosmocalc_age_table(void)
{
#define WORKSPACE_NUM 100000
#define ABSERR 0.0
#define RELERR 1e-8
static int initFlag = 1;
static int currCosmoNum;
gsl_integration_workspace *workspace;
gsl_function F;
long i;
double result,abserr,afact;
double age_table[COSMOCALC_AGE_TABLE_LENGTH];
double aexpn_table[COSMOCALC_AGE_TABLE_LENGTH];
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);
aexpn_table[0] = 0.0;
age_table[0] = 0.0;
for(i=1;i<COSMOCALC_AGE_TABLE_LENGTH;++i)
{
afact = (1.0 - 0.0)/(COSMOCALC_AGE_TABLE_LENGTH-1.0)*((double) i);
F.function = &age_integ_funct;
gsl_integration_qag(&F,1e-12,afact,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&result,&abserr);
aexpn_table[i] = afact;
age_table[i] = result*TH/cosmoData.h;
}
gsl_integration_workspace_free(workspace);
#undef ABSERR
#undef RELERR
#undef WORKSPACE_NUM
//init the spline and accelerators
if(cosmocalc_aexpn2age_spline != NULL)
gsl_spline_free(cosmocalc_aexpn2age_spline);
cosmocalc_aexpn2age_spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_AGE_TABLE_LENGTH));
gsl_spline_init(cosmocalc_aexpn2age_spline,aexpn_table,age_table,(size_t) (COSMOCALC_AGE_TABLE_LENGTH));
if(cosmocalc_aexpn2age_acc != NULL)
gsl_interp_accel_reset(cosmocalc_aexpn2age_acc);
else
cosmocalc_aexpn2age_acc = gsl_interp_accel_alloc();
AGE = gsl_spline_eval(cosmocalc_aexpn2age_spline,1.0,cosmocalc_aexpn2age_acc);
}
}
double age(double a)
{
static int initFlag = 1;
static int currCosmoNum;
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
init_cosmocalc_age_table();
}
return gsl_spline_eval(cosmocalc_aexpn2age_spline,a,cosmocalc_aexpn2age_acc);
}
//call age first to set AGE
double lookback(double a)
{
double age_a = age(a);
return AGE - age_a;
}
| {
"alphanum_fraction": 0.7284693494,
"avg_line_length": 27.412371134,
"ext": "c",
"hexsha": "e0e4f7424d4ec0478972ab8bbba4a1c0bcbddad3",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z",
"max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "beckermr/cosmocalc",
"max_forks_repo_path": "src/ages.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "beckermr/cosmocalc",
"max_issues_repo_path": "src/ages.c",
"max_line_length": 120,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "beckermr/cosmocalc",
"max_stars_repo_path": "src/ages.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 867,
"size": 2659
} |
/* eigen/gsl_eigen.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2006, 2007 Gerard Jungman, Brian Gough, 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.
*/
#ifndef __GSL_EIGEN_H__
#define __GSL_EIGEN_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 <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.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;
double * d;
double * sd;
} gsl_eigen_symm_workspace;
GSL_FUN gsl_eigen_symm_workspace * gsl_eigen_symm_alloc (const size_t n);
GSL_FUN void gsl_eigen_symm_free (gsl_eigen_symm_workspace * w);
GSL_FUN int gsl_eigen_symm (gsl_matrix * A, gsl_vector * eval, gsl_eigen_symm_workspace * w);
typedef struct {
size_t size;
double * d;
double * sd;
double * gc;
double * gs;
} gsl_eigen_symmv_workspace;
GSL_FUN gsl_eigen_symmv_workspace * gsl_eigen_symmv_alloc (const size_t n);
GSL_FUN void gsl_eigen_symmv_free (gsl_eigen_symmv_workspace * w);
GSL_FUN int gsl_eigen_symmv (gsl_matrix * A, gsl_vector * eval, gsl_matrix * evec, gsl_eigen_symmv_workspace * w);
typedef struct {
size_t size;
double * d;
double * sd;
double * tau;
} gsl_eigen_herm_workspace;
GSL_FUN gsl_eigen_herm_workspace * gsl_eigen_herm_alloc (const size_t n);
GSL_FUN void gsl_eigen_herm_free (gsl_eigen_herm_workspace * w);
GSL_FUN int gsl_eigen_herm (gsl_matrix_complex * A, gsl_vector * eval,
gsl_eigen_herm_workspace * w);
typedef struct {
size_t size;
double * d;
double * sd;
double * tau;
double * gc;
double * gs;
} gsl_eigen_hermv_workspace;
GSL_FUN gsl_eigen_hermv_workspace * gsl_eigen_hermv_alloc (const size_t n);
GSL_FUN void gsl_eigen_hermv_free (gsl_eigen_hermv_workspace * w);
GSL_FUN int gsl_eigen_hermv (gsl_matrix_complex * A, gsl_vector * eval,
gsl_matrix_complex * evec,
gsl_eigen_hermv_workspace * w);
typedef struct {
size_t size; /* matrix size */
size_t max_iterations; /* max iterations since last eigenvalue found */
size_t n_iter; /* number of iterations since last eigenvalue found */
size_t n_evals; /* number of eigenvalues found so far */
int compute_t; /* compute Schur form T = Z^t A Z */
gsl_matrix *H; /* pointer to Hessenberg matrix */
gsl_matrix *Z; /* pointer to Schur vector matrix */
} gsl_eigen_francis_workspace;
GSL_FUN gsl_eigen_francis_workspace * gsl_eigen_francis_alloc (void);
GSL_FUN void gsl_eigen_francis_free (gsl_eigen_francis_workspace * w);
GSL_FUN void gsl_eigen_francis_T (const int compute_t,
gsl_eigen_francis_workspace * w);
GSL_FUN int gsl_eigen_francis (gsl_matrix * H, gsl_vector_complex * eval,
gsl_eigen_francis_workspace * w);
GSL_FUN int gsl_eigen_francis_Z (gsl_matrix * H, gsl_vector_complex * eval,
gsl_matrix * Z,
gsl_eigen_francis_workspace * w);
typedef struct {
size_t size; /* size of matrices */
gsl_vector *diag; /* diagonal matrix elements from balancing */
gsl_vector *tau; /* Householder coefficients */
gsl_matrix *Z; /* pointer to Z matrix */
int do_balance; /* perform balancing transformation? */
size_t n_evals; /* number of eigenvalues found */
gsl_eigen_francis_workspace *francis_workspace_p;
} gsl_eigen_nonsymm_workspace;
GSL_FUN gsl_eigen_nonsymm_workspace * gsl_eigen_nonsymm_alloc (const size_t n);
GSL_FUN void gsl_eigen_nonsymm_free (gsl_eigen_nonsymm_workspace * w);
GSL_FUN void gsl_eigen_nonsymm_params (const int compute_t, const int balance,
gsl_eigen_nonsymm_workspace *w);
GSL_FUN int gsl_eigen_nonsymm (gsl_matrix * A, gsl_vector_complex * eval,
gsl_eigen_nonsymm_workspace * w);
GSL_FUN int gsl_eigen_nonsymm_Z (gsl_matrix * A, gsl_vector_complex * eval,
gsl_matrix * Z, gsl_eigen_nonsymm_workspace * w);
typedef struct {
size_t size; /* size of matrices */
gsl_vector *work; /* scratch workspace */
gsl_vector *work2; /* scratch workspace */
gsl_vector *work3; /* scratch workspace */
gsl_matrix *Z; /* pointer to Schur vectors */
gsl_eigen_nonsymm_workspace *nonsymm_workspace_p;
} gsl_eigen_nonsymmv_workspace;
GSL_FUN gsl_eigen_nonsymmv_workspace * gsl_eigen_nonsymmv_alloc (const size_t n);
GSL_FUN void gsl_eigen_nonsymmv_free (gsl_eigen_nonsymmv_workspace * w);
GSL_FUN void gsl_eigen_nonsymmv_params (const int balance,
gsl_eigen_nonsymmv_workspace *w);
GSL_FUN int gsl_eigen_nonsymmv (gsl_matrix * A, gsl_vector_complex * eval,
gsl_matrix_complex * evec,
gsl_eigen_nonsymmv_workspace * w);
GSL_FUN int gsl_eigen_nonsymmv_Z (gsl_matrix * A, gsl_vector_complex * eval,
gsl_matrix_complex * evec, gsl_matrix * Z,
gsl_eigen_nonsymmv_workspace * w);
typedef struct {
size_t size; /* size of matrices */
gsl_eigen_symm_workspace *symm_workspace_p;
} gsl_eigen_gensymm_workspace;
GSL_FUN gsl_eigen_gensymm_workspace * gsl_eigen_gensymm_alloc (const size_t n);
GSL_FUN void gsl_eigen_gensymm_free (gsl_eigen_gensymm_workspace * w);
GSL_FUN int gsl_eigen_gensymm (gsl_matrix * A, gsl_matrix * B,
gsl_vector * eval, gsl_eigen_gensymm_workspace * w);
GSL_FUN int gsl_eigen_gensymm_standardize (gsl_matrix * A, const gsl_matrix * B);
typedef struct {
size_t size; /* size of matrices */
gsl_eigen_symmv_workspace *symmv_workspace_p;
} gsl_eigen_gensymmv_workspace;
GSL_FUN gsl_eigen_gensymmv_workspace * gsl_eigen_gensymmv_alloc (const size_t n);
GSL_FUN void gsl_eigen_gensymmv_free (gsl_eigen_gensymmv_workspace * w);
GSL_FUN int gsl_eigen_gensymmv (gsl_matrix * A, gsl_matrix * B,
gsl_vector * eval, gsl_matrix * evec,
gsl_eigen_gensymmv_workspace * w);
typedef struct {
size_t size; /* size of matrices */
gsl_eigen_herm_workspace *herm_workspace_p;
} gsl_eigen_genherm_workspace;
GSL_FUN gsl_eigen_genherm_workspace * gsl_eigen_genherm_alloc (const size_t n);
GSL_FUN void gsl_eigen_genherm_free (gsl_eigen_genherm_workspace * w);
GSL_FUN int gsl_eigen_genherm (gsl_matrix_complex * A, gsl_matrix_complex * B,
gsl_vector * eval, gsl_eigen_genherm_workspace * w);
GSL_FUN int gsl_eigen_genherm_standardize (gsl_matrix_complex * A,
const gsl_matrix_complex * B);
typedef struct {
size_t size; /* size of matrices */
gsl_eigen_hermv_workspace *hermv_workspace_p;
} gsl_eigen_genhermv_workspace;
GSL_FUN gsl_eigen_genhermv_workspace * gsl_eigen_genhermv_alloc (const size_t n);
GSL_FUN void gsl_eigen_genhermv_free (gsl_eigen_genhermv_workspace * w);
GSL_FUN int gsl_eigen_genhermv (gsl_matrix_complex * A, gsl_matrix_complex * B,
gsl_vector * eval, gsl_matrix_complex * evec,
gsl_eigen_genhermv_workspace * w);
typedef struct {
size_t size; /* size of matrices */
gsl_vector *work; /* scratch workspace */
size_t n_evals; /* number of eigenvalues found */
size_t max_iterations; /* maximum QZ iterations allowed */
size_t n_iter; /* number of iterations since last eigenvalue found */
double eshift; /* exceptional shift counter */
int needtop; /* need to compute top index? */
double atol; /* tolerance for splitting A matrix */
double btol; /* tolerance for splitting B matrix */
double ascale; /* scaling factor for shifts */
double bscale; /* scaling factor for shifts */
gsl_matrix *H; /* pointer to hessenberg matrix */
gsl_matrix *R; /* pointer to upper triangular matrix */
int compute_s; /* compute generalized Schur form S */
int compute_t; /* compute generalized Schur form T */
gsl_matrix *Q; /* pointer to left Schur vectors */
gsl_matrix *Z; /* pointer to right Schur vectors */
} gsl_eigen_gen_workspace;
GSL_FUN gsl_eigen_gen_workspace * gsl_eigen_gen_alloc (const size_t n);
GSL_FUN void gsl_eigen_gen_free (gsl_eigen_gen_workspace * w);
GSL_FUN void gsl_eigen_gen_params (const int compute_s, const int compute_t,
const int balance, gsl_eigen_gen_workspace * w);
GSL_FUN int gsl_eigen_gen (gsl_matrix * A, gsl_matrix * B,
gsl_vector_complex * alpha, gsl_vector * beta,
gsl_eigen_gen_workspace * w);
GSL_FUN int gsl_eigen_gen_QZ (gsl_matrix * A, gsl_matrix * B,
gsl_vector_complex * alpha, gsl_vector * beta,
gsl_matrix * Q, gsl_matrix * Z,
gsl_eigen_gen_workspace * w);
typedef struct {
size_t size; /* size of matrices */
gsl_vector *work1; /* 1-norm of columns of A */
gsl_vector *work2; /* 1-norm of columns of B */
gsl_vector *work3; /* real part of eigenvector */
gsl_vector *work4; /* imag part of eigenvector */
gsl_vector *work5; /* real part of back-transformed eigenvector */
gsl_vector *work6; /* imag part of back-transformed eigenvector */
gsl_matrix *Q; /* pointer to left Schur vectors */
gsl_matrix *Z; /* pointer to right Schur vectors */
gsl_eigen_gen_workspace *gen_workspace_p;
} gsl_eigen_genv_workspace;
GSL_FUN gsl_eigen_genv_workspace * gsl_eigen_genv_alloc (const size_t n);
GSL_FUN void gsl_eigen_genv_free (gsl_eigen_genv_workspace * w);
GSL_FUN int gsl_eigen_genv (gsl_matrix * A, gsl_matrix * B,
gsl_vector_complex * alpha, gsl_vector * beta,
gsl_matrix_complex * evec,
gsl_eigen_genv_workspace * w);
GSL_FUN int gsl_eigen_genv_QZ (gsl_matrix * A, gsl_matrix * B,
gsl_vector_complex * alpha, gsl_vector * beta,
gsl_matrix_complex * evec,
gsl_matrix * Q, gsl_matrix * Z,
gsl_eigen_genv_workspace * w);
typedef enum {
GSL_EIGEN_SORT_VAL_ASC,
GSL_EIGEN_SORT_VAL_DESC,
GSL_EIGEN_SORT_ABS_ASC,
GSL_EIGEN_SORT_ABS_DESC
}
gsl_eigen_sort_t;
/* Sort eigensystem results based on eigenvalues.
* Sorts in order of increasing value or increasing
* absolute value.
*
* exceptions: GSL_EBADLEN
*/
GSL_FUN int gsl_eigen_symmv_sort(gsl_vector * eval, gsl_matrix * evec,
gsl_eigen_sort_t sort_type);
GSL_FUN int gsl_eigen_hermv_sort(gsl_vector * eval, gsl_matrix_complex * evec,
gsl_eigen_sort_t sort_type);
GSL_FUN int gsl_eigen_nonsymmv_sort(gsl_vector_complex * eval,
gsl_matrix_complex * evec,
gsl_eigen_sort_t sort_type);
GSL_FUN int gsl_eigen_gensymmv_sort (gsl_vector * eval, gsl_matrix * evec,
gsl_eigen_sort_t sort_type);
GSL_FUN int gsl_eigen_genhermv_sort (gsl_vector * eval, gsl_matrix_complex * evec,
gsl_eigen_sort_t sort_type);
GSL_FUN int gsl_eigen_genv_sort (gsl_vector_complex * alpha, gsl_vector * beta,
gsl_matrix_complex * evec,
gsl_eigen_sort_t sort_type);
/* Prototypes for the schur module */
GSL_FUN int gsl_schur_gen_eigvals(const gsl_matrix *A, const gsl_matrix *B,
double *wr1, double *wr2, double *wi,
double *scale1, double *scale2);
GSL_FUN int gsl_schur_solve_equation(double ca, const gsl_matrix *A, double z,
double d1, double d2, const gsl_vector *b,
gsl_vector *x, double *s, double *xnorm,
double smin);
GSL_FUN int gsl_schur_solve_equation_z(double ca, const gsl_matrix *A,
gsl_complex *z, double d1, double d2,
const gsl_vector_complex *b,
gsl_vector_complex *x, double *s,
double *xnorm, double smin);
/* The following functions are obsolete: */
/* Eigensolve by Jacobi Method
*
* The data in the matrix input is destroyed.
*
* exceptions:
*/
GSL_FUN int
gsl_eigen_jacobi(gsl_matrix * matrix,
gsl_vector * eval,
gsl_matrix * evec,
unsigned int max_rot,
unsigned int * nrot);
/* Invert by Jacobi Method
*
* exceptions:
*/
GSL_FUN int
gsl_eigen_invert_jacobi(const gsl_matrix * matrix,
gsl_matrix * ainv,
unsigned int max_rot);
__END_DECLS
#endif /* __GSL_EIGEN_H__ */
| {
"alphanum_fraction": 0.6504319955,
"avg_line_length": 40.0893854749,
"ext": "h",
"hexsha": "366670bc273124fc44786a0f3acf2e0d27aee80c",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/VimbaCamJILA",
"max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_eigen.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/VimbaCamJILA",
"max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_eigen.h",
"max_line_length": 115,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mgreter/astrometrylib",
"max_stars_repo_path": "vendor/gsl/gsl/gsl_eigen.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z",
"num_tokens": 3529,
"size": 14352
} |
#ifndef NumericalApproximation_h
#define NumericalApproximation_h
/** This is free and unencumbered software released into the public domain.
The authors of ISIS do not claim copyright on the contents of this file.
For more details about the LICENSE terms and the AUTHORS, you will
find files of those names at the top level of this repository. **/
/* SPDX-License-Identifier: CC0-1.0 */
#include <string>
#include <vector>
#include <map>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include "IException.h"
using namespace std;
namespace Isis {
/**
* @brief NumericalApproximation provides various numerical
* analysis methods of interpolation, extrapolation and
* approximation of a tabulated set of @a x, @a y data.
*
* This class contains a merged version of the Isis classes
* @b DataInterp and @b NumericalMethods. In addition,
* some methods from @b AtmosModel were moved to this class, the
* @a CubicNeighborhood interpolation type was
* adapted from the IDL routine called @b interpol (using the
* "/spline" keyword), and several differentiation and
* integration approximation methods were created.
*
* NumericalApproximation contains 9 types of data interpolation
* routines. These routines act on x, y pairs of data points.
* The following forms of data interpolation are supported:
*
* <table>
* <tr>
* <th>Name</th>
* <th>Type (enum)</th>
* <th>MinPoints</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>Linear</td>
* <td>@a Linear</td>
* <td>2</td>
* <td>
* Linear interpolation approximates a curve by
* concatinating line segments between known data
* points. This results in a continuous curve with a
* discontinuities of the derivative at the known data
* points. This interpolation type uses the GSL
* library routines.
*
* </td>
* </tr>
* <tr>
* <td>Polynomial</td>
* <td>@a Polynomial</td>
* <td>3</td>
* <td>
* Computes a polynomial interpolation. This method
* should only be used for interpolating small numbers
* of points because polynomial interpolation introduces
* large oscillations, even for well-behaved datasets.
* The number of terms in the interpolating polynomial
* is equal to the number of points. This interpolation
* type uses the GSL library routines.
* </td>
* </tr>
* <tr>
* <td>Neville's Algorithm for Polynomial Interpolation</td>
* <td>@a PolynomialNeville</td>
* <td>3</td>
* <td>
* Polynomial interpolation using Neville's algorithm. This
* first fits a polynomial of degree 0 through each point.
* On the second iteration, the polynomial of adjoining
* indices are combined to fit through pairs of points.
* This process repeats until a pyramid of approximations is
* reached. This is based on the Newton form of the
* interpolating polynomial and the recursion relation of
* the divided differences.
* </td>
* </tr>
* <tr>
* <td>Natural Cubic Spline</td>
* <td>@a CubicNatural</td>
* <td>3</td>
* <td>
* Cubic spline with natural boundary conditions. The
* resulting curve is piecewise cubic on each interval
* with matching first and second derivatives at the
* supplied data points. The second derivative is chosen
* to be zero at the endpoints, i.e. the first and last
* points of the data set. This is also refered to as
* free boundary condtions. This interpolation type uses
* the GSL
* library routines.
* </td>
* </tr>
* <tr>
* <td>Clamped Cubic Spline</td>
* <td>@a CubicClamped</td>
* <td>3</td>
* <td>
* Cubic Spline interpolation with clamped boundary
* conditions. The resulting curve is piecewise cubic on
* each interval. For this type of boundary condition to
* hold, it is necessary to have either the values of the
* derivative at the endpoints or an accurate approximation
* to those values. In general, clamped boundary conditions
* lead to more accurate approximations since they include
* more information about the function.
* </td>
* </tr>
* <tr>
* <td>Periodic Natural Cubic Spline</td>
* <td>@a CubicNatPeriodic</td>
* <td>2</td>
* <td>
* Cubic spline with periodic boundary conditions. The
* resulting curve is piecewise cubic on each interval
* with matching first and second derivatives at the
* supplied data points. The derivatives at the first
* and last points are also matched. Note that the last
* point in the data must have the same y-value as the
* first point, otherwise the resulting periodic
* interpolation will have a discontinuity at the
* boundary. This interpolation type uses the GSL
* library routines.
* </td>
* </tr>
* <tr>
* <td>Cubic Spline about 4-point Neighborhood</td>
* <td>@a CubicNeighborhood</td>
* <td>4</td>
* <td>
* Cubic Spline interpolation using 4-pt Neighborhoods
* with natural boundary conditions. This interpolation
* type is adapted from the IDL interpol.pro application
* using the "/spline" keyword on an irregular grid.
* This type of cubic spline fits a natural cubic spline
* to the 4-point neighborhood of known data points
* surrounding the @a x value at which we wish to
* evaluate. For example, suppose {@a x<sub>0</sub>,
* @a x<sub>1</sub>, ..., @a x<sub><I>n</I></sub>} is the
* array of known domain values in the data set and @f$
* x_i \leq u < x_{i+1} @f$ for some @e i such that
* @f$ 0 \leq i \leq n @f$, then to evaluate the
* @a y value at @e u, this method of interpolation
* evaluates the ordinary cubic spline consisting of the
* data set {@a x<sub>i-1</sub>, @a x<sub>i</sub>,
* @a x<sub>i+1</sub>, @a x<sub>i+2</sub>} at
* @e u.
* </td>
* </tr>
* <tr>
* <td>Cubic Spline using Hermite cubic polynomial</td>
* <td>@a CubicHermite</td>
* <td>2</td>
* <td>
* Cubic Spline interpolation using the Hermite cubic
* polynomial (also called the unique Hermite
* interpolating fundamental polynomial of degree 3).
* This method requires the input of the slopes of the
* tangent lines of the curve (i.e. velocities, or first
* derivatives) at each of the data points. This ensures
* that the approximation has the same "shape" as the
* curve at the known data points. This interpolation type
* uses piecewise Hermite cubic polynomials for each
* interval, (@a x<sub>0</sub>, @a x<sub>1</sub>), using
* the known data points, (@a
* x<sub>0</sub>,@a f(@a x<sub>0</sub>)) and
* (@a x<sub>1</sub>,@a f(@a x<sub>1</sub>)), and their
* derivatives,
* @a f '(@a x<sub>0</sub>) and @a f '(@a
* x<sub>1</sub>). The Hermite cubic polynomial is defined
* @f[ H_3(x) =
* f(x_0)h_0(x)+f(x_1)h_1(x)
* +f\prime(x_0)\hat{h}_0(x)+f\prime(x_1)\hat{h}_1(x)
* @f]
* where
* @f$ h_k(x) =
* [1-2(x-x_k)L\prime_k(x_k)](L_k(x))^2
* @f$
* and
* @f$ \hat{h}_k(x) =
* (x-x_k)(L_k(x))^2
* @f$
* for the kth-Lagrange coefficient polynomials of degree
* n = 1,
* @f$ L_0(x) = \frac{x- x_1}{x_0-x_1}@f$ and
* @f$ L_1(x) = \frac{x- x_0}{x_1-x_0}@f$.
*
* </td>
* </tr>
* <tr>
* <td>Akima</td>
* <td>@a Akima</td>
* <td>5</td>
* <td>
* Non-rounded Akima spline with natural boundary
* conditions. This method uses non-rounded corner
* algorithm of Wodicka. This interpolation type uses the
* GSL library routines.
* </td>
* </tr>
* <tr>
* <td>Periodic Akima</td>
* <td>@a AkimaPeriodic</td>
* <td>5</td>
* <td>
* Non-rounded Akima spline with periodic boundary
* conditions. This method uses non-rounded corner
* algorithm of Wodicka. This interpolation type uses
* the GSL library routines.
* </td>
* </tr>
* </table>
*
*
* Numerical analysis approximation methods for differentiating
* and integrating unknown functions represented by a data set
* are implemented by using the interpolations on the data set
* created with a NumericalApproximation object. The Lagrange polynomial,
* @f[ L(x) =
* \sum_{k=0}^{n} \left(f(x_k) \prod_{i=0,i \neq k}^{n}
* \frac{x- x_i}{x_k-x_i}\right)
* @f]
* is used to determine formulas for numerical differentiation
* and integration.
* @n
* @b Numerical Differentiation
* @n
* The differentiation methods use difference formulas to
* approximate first and second derivatives at a domain value
* for a given a set of known (@a x,@a y) data points. Once all
* of the data points are added, a Isis::NumericalApproximation
* interpolation is used on the dataset to estimate the
* function, @f$f:x \to y@f$, mapping @a x values to
* corresponding @a y values. Then, the derivative of
* @e f evaluated at @a x<sub>0</sub> is approximated.
* To do so, a uniform step size of @a h is chosen to
* determine the distance between @a x<sub>i</sub> and @a
* x<sub>i+1</sub>.
* <table>
* <caption> Differentiation methods require the parameters
* @a a (domain value at which the derivative will be
* evaluated), @a n (number of points used in the difference
* formula), and @a h (step size of points). Note: @a a
* is denoted @a x<sub>0</sub> in the above formulas.
* </caption>
* <tr>
* <th>Numerical Differentiation Type</th>
* <th>Difference Formulas</th>
* <th>Methods Available</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>Backward Difference </td>
* <td>
* <UL>
* <LI> 2-point backward difference.
* @f[
* f\prime(x_0) \approx \frac{1}{h}[f(x_0) - f(x_0 - h)]
* @f]
* <LI> 3-point backward difference.
* @f[
* f\prime(x_0) \approx \frac{1}{2h}[3f(x_0) - 4f(x_0 - h) +
* f(x_0 - 2h)]
* @f]
* <LI> 3-point backward second difference.
* @f[
* f\prime\prime(x_0) \approx \frac{1}{h^2}[f(x_0)
* - 2f(x_0 - h) + f(x_0 - 2h)]
* @f]
* </UL>
* </td>
* <td>
* <UL>
* <LI>BackwardFirstDifference()
* <LI>BackwardSecondDifference()
* </UL>
* </td>
* <td>
* Backward difference formulas use a uniform step-size
* moving in the negative direction from the
* given @a x<sub>0</sub>. These formulas are derived
* by differentiating the Lagrange polynomials for
* @a x<sub>i</sub> = @a x<sub>0</sub> - @a ih
* and evaluating them at@a x<sub>0</sub>.
* </td>
* </tr>
* <tr>
* <td>Forward Difference </td>
* <td>
* <UL>
* <LI> 2-point forward difference.
* @f[
* f\prime(x_0) \approx \frac{1}{h}[f(x_0 + h) - f(x_0)]
* @f]
* <LI> 3-point forward difference.
* @f[
* f\prime(x_0) \approx \frac{1}{2h}[-f(x_0 + 2h) +
* 4f(x_0 + h) - 3f(x_0)]
* @f]
* <LI> 3-point forward second difference.
* @f[
* f\prime\prime(x_0) \approx \frac{1}{h^2}[f(x_0 +
* 2h) - 2f(x_0 + h) + f(x_0)]
* @f]
* </UL>
* </td>
* <td>
* <UL>
* <LI>ForwardFirstDifference()
* <LI>ForwardSecondDifference()
* </UL>
* </td>
* <td>
* Forward difference formulas use a uniform step-size
* moving in the positive direction from
* @a x<sub>0</sub>. These formulas are derived by
* differentiating the Lagrange polynomials for
* @a x<sub>i</sub> = @a x<sub>0</sub> + @a ih
* and evaluating them at@a x<sub>0</sub>.
* </td>
* </tr>
* <tr>
* <td>Center Difference </td>
* <td>
* <UL>
* <LI> 3-point center difference.
* @f[
* f\prime(x_0) \approx \frac{1}{2h}[f(x_0 + h) -
* f(x_0 - h)]
* @f]
* <LI> 5-point center difference.
* @f[
* f\prime(x_0) \approx \frac{1}{12h}[-f(x_0 + 2h) +
* 8f(x_0 +h) - 8f(x_0 - h) + f(x_0 - 2h)]
* @f]
* <LI> 3-point center second difference.
* @f[
* f\prime\prime(x_0) \approx \frac{1}{h^2}[f(x_0 + h)
* - 2f(x_0) + f(x_0 - h)]
* @f]
* <LI> 5-point center second difference.
* @f[
* f\prime\prime(x_0) \approx \frac{1}{12h^2}[-f(x_0 +
* 2h) + 16f(x_0 +h) - 30f(x_0) + 16f(x_0 - h) - f(x_0
* - 2h)]
* @f]
* </UL>
* </td>
* <td>
* <UL>
* <LI>CenterFirstDifference()
* <LI>CenterSecondDifference()
* </UL>
* </td>
* <td>
* Center difference formulas use a uniform step-size
* moving in both directions from @a x<sub>0</sub> so this
* point stays centered. These formulas are derived by
* differentiating the Lagrange polynomials for
* @a x<sub>i</sub> = @a x<sub>0</sub>
* + (@e i - (@a n - 1)/2)@a h and evaluating them
* at @a x<sub>0</sub>.
* </td>
* </tr>
* <tr>
* <td>GSL Differentiation </td>
* <td> Unknown </td>
* <td>
* <UL>
* <LI>GslFirstDerivative()
* <LI>GslSecondDerivative()
* </UL>
* </td>
* <td>
* No documentation was found about the algorithms used
* for these methods. They may only be called when
* interpolation type is one of the following: @a Linear,
* @a Polynomial, @a CubicNatural, @a CubicNatPeriodic, @a Akima, or
* @a AkimaPeriodic.
* </td>
* </tr>
* </table>
* @n
* @b Numerical Integration
* @n
* The integration methods were derived using
* @b Newton-Cotes, or @a quadrature, formulas for
* approximating integrals given a set of known (@a x,@a y)
* data points. The @a x values may be irregularly spaced, but
* must be unique and added to the dataset in ascending order.
* Once all of the data points are added, a
* Isis::NumericalApproximation interpolation is used on
* the dataset to estimate the function, @f$f:x \to y@f$,
* mapping @a x values to corresponding @a y values.
* Then, the integral of @e f on the interval from @a a
* to @a b is approximated. To do so, an algorithm for creating
* a composite formula by applying the original formula to
* segments that share a boundary point is used. The
* NumericalApproximation::InterpType chosen for
* interpolation computation seems to have little affect on the
* error between the actual integral and the return values of
* the integration methods. The BoolesRule() method varies the
* most in error. Although errors are not high for any of the
* interpolation types,
* @a CubicNatural spline interpolations seem to
* have the smallest error most often with BoolesRule(). For any
* other numerical integration method, the errors appear to be
* identical for any NumericalApproximation::InterpType except
* @a Polynomial, which usually has a slightly larger
* error than the other interpolation types. Note: A portion of
* this algorithm is derived from the IDL function int_tabulated
* for Boole's Method.
* <table>
* <caption> Integration methods require the parameters @a a,
* @a b (interval of domain over which to integrate).
* </caption>
* <tr>
* <th>Numerical Integration Type</th>
* <th>Integration Formulas</th>
* <th>Methods Available</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>Trapezoidal Rule</td>
* <td>
* <UL>
* <LI> 2-point Newton-Cotes trapezoidal rule:
* @f[
* \int_{a}^b f(x)dx \approx \frac{h}{2}[f(a) + f(b)]
* @f]
* where @e h = @a b - @a a.
* </UL>
* </td>
* <td>
* <UL>
* <LI>TrapezoidalRule()
* </UL>
* </td>
* <td>
* The 2-point closed rule, known as the trapezoidal
* rule, uses straight line segments between known data
* points to estimate the area under the curve (integral).
* This Newton-Cotes formula uses a uniform step-size of
* @e h = @a b - @a a and is derived by integrating the
* Lagrange polynomials over the closed interval [@a a,
* @a a+h] for @a x<sub>i</sub> =
* @a x<sub>0</sub> + @e ih.
* </td>
* </tr>
* <tr>
* <td>Simpson's Rule, or Simpson's 3-Point Rule </td>
* <td>
* <UL>
* <LI> 3-point Newton-Cotes, Simpson's Rule
* @f[
* \int_{a}^b f(x)dx \approx \frac{h}{3}[f(a) +
* 4f(a+h) + f(a+2h)]
* @f]
* where @e h = (@a b - @a a)/2.
* </UL>
* </td>
* <td>
* <UL>
* <LI>Simpsons3PointRule()
* </UL>
* </td>
* <td>
* The 3-point closed rule, known as Simpson's Rule or
* Simpson's 3-Point Rule, uses parabolic arcs between
* known data points to estimate the area under the curve
* (integral). This Newton-Cotes formula uses a uniform
* step-size of @e h = (@a b - @a a)/2 and is derived by
* integrating the Lagrange polynomials over the closed
* interval [@a a, @a a+2h] for @a x<sub>i</sub> =
* @a x<sub>0</sub> + @e ih.
* </td>
* </tr>
* <tr>
* <td>Simpson's 3/8 Rule, or Simpson's 4-Point Rule </td>
* <td>
* <UL>
* <LI> 4-point Newton-Cotes, Simpson's 3/8 Rule
* @f[
* \int_{a}^b f(x)dx \approx \frac{3h}{8}[f(a) +
* 3f(a+h) + 3f(a+2h) + f(a+3h)]
* @f]
* where @e h = (@a b - @a a)/3.
* </UL>
* </td>
* <td>
* <UL>
* <LI>Simpsons4PointRule()
* </UL>
* </td>
* <td>
* The 4-point closed rule, known as Simpson's 3/8 Rule or
* Simpson's 4-Point Rule, uses cubic curves between
* known data points to estimate the area under the curve
* (integral). This Newton-Cotes formula uses a uniform
* step-size of @e h = (@a b - @a a)/3 and is derived by
* integrating the Lagrange polynomials over the closed
* interval [@a a, @a a+3h] for @a x<sub>i</sub> =
* @a x<sub>0</sub> + @e ih.
* </td>
* </tr>
* <tr>
* <td>Boole's Rule </td>
* <td>
* <UL>
* <LI> 5-point Newton-Cotes, Boole's Rule
* @f[
* \int_{a}^b f(x)dx \approx \frac{2h}{45}[7f(a) +
* 32f(a+h) + 12f(a+2h) + 32f(a+3h) + 7f(a+4h)]
* @f]
* where @e h = (@a b - @a a)/4.
* </UL>
* </td>
* <td>
* <UL>
* <LI>BoolesRule()
* </UL>
* </td>
* <td>
* The 5-point closed rule, known as Boole's Rule, uses
* quartic curves between known data points to estimate
* the area under the curve (integral). This Newton-Cotes
* formula uses a uniform step-size of @e h = (@a b -
* @a a)/4 and is derived by integrating the Lagrange
* polynomials over the closed interval [@a a, @a a+4h]
* for @a x<sub>i</sub> = @a x<sub>0</sub> +
* @a ih.
* </td>
* </tr>
* <tr>
* <td>Refinements of Extended Trapezoidal Rule </td>
* <td>
* <UL>
* <LI> Extended closed trapezoidal rule
* @f[
* \int_{a}^b f(x)dx \approx h[\frac12 f(x_0) +
* f(x_1) + ... + f(x_{n-2} + \frac12
* f(x_{n-1})]
* @f]
* where @e h = (@a b - @a a)/4, @a x<sub>0</sub> =
* @a a, and @a x<sub>n-1</sub> = @a b.
* </UL>
* </td>
* <td>
* <UL>
* <LI>RefineExtendedTrap()
* </UL>
* </td>
* <td>
* The extended (or composite) trapezoidal rule can be
* used to with a series of refinements to approximate the
* integral. The first stage of refinement returns the
* ordinary trapezoidal estimate of the integral.
* Subsequent stages will improve the accuracy, where, for
* the @a n<sup>th</sup> stage 2<sup>@a n-2 </sup> interior
* points are added.
* </td>
* </tr>
* <tr>
* <td>Romberg's Method </td>
* <td>
* <UL>
* <LI> Romberg's Method for Integration </td>
* </UL>
* <td>
* <UL>
* <LI>RombergsMethod()
* </UL>
* </td>
* <td>
* Romberg's Method is a potent numerical integration
* tool. It uses the extended trapezoidal rule and
* Neville's algorithm for polynomial interpolation.
* </td>
* </tr>
* <tr>
* <td>GSL Integration </td>
* <td> Unknown </td>
* <td>
* <UL>
* <LI>GslIntegral()
* </UL>
* </td>
* <td>
* No documentation was found about the algorithm used for
* this methods. They may only be called when
* interpolation type is one of the following: @a Linear,
* @a Polynomial, @a CubicNatural, @a CubicNatPeriodic, @a Akima, or
* @a AkimaPeriodic.
* </td>
* </tr>
* </table>
*
*
* Below is an example demonstating the use of this class:
* @code
* inline double f(double x) { return (x + cos ((x * x))); }
*
* NumericalApproximation
* spline(NumericalApproximation::CubicClamped);
* for (int x = 0; x < 200 ; x++) {
* spline.addPoint(x, f(x));
* }
* spline.SetCubicClampedEndptDeriv(0,0);
* double yinterp = spline.Evaluate(50.7);
* double yextrap =
* spline.Evaluate(201,NumericalApproximation::Extrapolate);
* double deriv = spline.CenterFirstDifference(10);
* double integ =
* spline.RombergsMethod(spline.DomainMinimum(),spline.DomainMaximum());
* @endcode
*
* To compute the same data set using the Akima spline, just use the following:
* @code
* spline.Reset(NumericalApproximation::Akima);
* double yinterp = spline.Evaluate(50.7);
* double yextrap =
* spline.Evaluate(201,NumericalApproximation::NearestEndpoint);
* double deriv = spline.CenterFirstDifference(10);
* double integ =
* spline.RombergsMethod(spline.DomainMinimum(),spline.DomainMaximum());
* @endcode
*
* <h1>Caveats</h1>
* When using this class, there are some important details that
* require consideration. Several interpolation types of this
* class use the GSL library. In addition, the GSL library
* default error handling scheme has implications when used in
* C++ objects. The default behavior is to terminate the
* application when an error occurs. Options for developers are
* to turn off error trapping within the GSL, which means users
* of the library must do their own error checking, or a
* specific handler can be specified to replace the default
* mode. Neither option is well suited in object-oriented
* implementations because they apply globally, to all users of
* the library. The approach used here is to turn off error
* handling and require users to handle their own error
* checking. This is not entirely safe as any user that does
* not follow this strategy could change this behavior at
* runtime. Other options should be explored. An additional
* option is that the default behavior can be altered prior to
* building GSL but this is also problematic since this behavior
* cannot be guaranteed universally.
*
* For these types, interpolation is strictly adhered to and
* extrapolation is not handled well. If the input to be
* evaluated is outside of the
* minimum and maximum @a x values of the original data
* points, then the @a y value corresponding to the
* @a x value that is nearest to that input is returned.
* However, for sufficiently close values, the clamped cubic and
* polynomial Neville's types are fairly accurate in their
* extrapolation techniques. All differentiation and
* integration methods throw an error if the value passed is
* outside of the domain.
*
* @ingroup Math
* @author 2008-11-05 Janet Barrett, Kris Becker, K Teal
* Thompson, Jeannie Walldren
* @internal
* @history 1999-08-11 K Teal Thompson - Original version of
* NumericalMethods subroutines in Isis2.
* @history 2006-06-14 Kris Becker - Created DataInterp class
* @history 2007-02-20 Janet Barrett - Created NumericalMethods
* class from Isis2 subroutines
* @history 2007-02-20 Janet Barrett - Created AtmosModel class
* from Isis2 subroutines
* @history 2008-06-18 Christopher Austin - Fixed documentation
* for DataInterp
* @history 2008-06-18 Steven Koechle - Updated NumericalMethods
* unitTest.
* @history 2008-11-05 Jeannie Walldren - Merged DataInterp
* class, NumericalMethods class, and methods from
* AtmosModel. Modified methods from various classes
* to be able to function similarly. Added InterpType
* @a CubicNeighborhood, difference formula methods, and
* integration methods. Created new unitTest.
* @history 2008-11-12 Jeannie Walldren - Fixed documentation.
* @history 2008-12-18 Jeannie Walldren - Added address
* operator (&) to input variables of type vector,
* NumericalApproximation::InterpType, and
* NumericalApproximation::ExtrapType in
* Constructors, AddData(), Evaluate(),
* ValueToExtrapolate(), EvaluateCubicNeighborhood(),
* @history 2009-01-26 Jeannie Walldren - Fixed error
* documentation.
* @history 2009-02-12 Jeannie Walldren - Fixed documentation
* to include weblinks.
* @history 2009-07-17 Steven Lambright - Added algorithm include,
* removed macro MAX
* @history 2009-06-10 Jeannie Walldren - Added interpolation
* type CubicHermite. This involved modifying some
* methods, as well as adding variable p_fprimeOfx
* and methods AddCubicHermiteDeriv() and
* EvaluateCubicHermite(). Added Contains() method.
* @history 2009-07-02 Jeannie Walldren - Replaced Hermite
* interpolation algorithm with simpler version and
* added methods EvaluateCubicHermiteFirstDeriv and
* EvaluateCubicHermiteSecDeriv
* @history 2009-07-09 Debbie Cook - Finished Jeannie's
* modifications.
* @history 2009-08-03 Jeannie Walldren - Clean up code,
* documentation and check in changes from
* 2009-06-10, 2009-07-02, 2009-07-09
* @history 2010-07-21 Sharmila Prasad - Remove doxygen documentation
* warnings
* @history 2010-12-06 Steven Lambright - Optimized AddData(vector, vector),
* AddCubicHermiteDeriv(vector), and Init() which causes a
* very significant increase in performance when constructing a lot
* or adding a lot of data.
*/
class NumericalApproximation {
public:
/**
* This enum defines the types of interpolation supported in this class
*/
enum InterpType { Linear, //!< Linear interpolation.
Polynomial, //!< Polynomial interpolation.
PolynomialNeville, //!< Polynomial interpolation using Neville's algorithm.
CubicNatural, //!< Cubic Spline interpolation with natural boundary conditions.
CubicClamped, //!< Cubic Spline interpolation with clamped boundary conditions.
CubicNatPeriodic, //!< Cubic Spline interpolation with periodic boundary conditions.
CubicNeighborhood, //!< Cubic Spline interpolation using 4-pt Neighborhoods with natural boundary conditions.
CubicHermite, //!< Cubic Spline interpolation using the Hermite cubic polynomial.
Akima, //!< Non-rounded Akima Spline interpolation with natural boundary conditions.
AkimaPeriodic //!< Non-rounded Akima Spline interpolation with periodic boundary conditions.
};
// CONSTRUCTORS
NumericalApproximation(const NumericalApproximation::InterpType &itype = CubicNatural);
NumericalApproximation(unsigned int n, double *x, double *y,
const NumericalApproximation::InterpType &itype = CubicNatural);
NumericalApproximation(const vector <double> &x, const vector <double> &y,
const NumericalApproximation::InterpType &itype = CubicNatural);
NumericalApproximation(const NumericalApproximation &dint);
// ASSIGNMENT OPERATOR
NumericalApproximation &operator=(const NumericalApproximation &numApMeth);
// DESTRUCTOR
virtual ~NumericalApproximation();
// ACCESSOR METHODS FOR OBJECT PROPERTIES
string Name() const;
/**
* @brief Returns the enumerated type of interpolation chosen
*
* This method can be selected after all the points are added in the
* interpolation by using Compute() method.
* Note that this prints out as an integer representaion of the
* enumerated type:
* <UL>
* <LI> Linear = 0
* <LI> Polynomial = 1
* <LI> PolynomialNeville = 2
* <LI> CubicNatural = 3
* <LI> CubicClamped = 4
* <LI> CubicNatPeriodic = 5
* <LI> CubicNeighborhood = 6
* <LI> CubicHermite = 7
* <LI> Akima = 8
* <LI> AkimaPeriodic = 9
* </UL>
*
* @return NumericalApproximation::InterpType Currently assigned
* interpolation type
*/
inline InterpType InterpolationType() {
return (p_itype);
}
int MinPoints();
int MinPoints(NumericalApproximation::InterpType itype);
// ADD DATA TO OBJECT
void AddData(const double x, const double y);
void AddData(unsigned int n, double *x, double *y);
void AddData(const vector <double> &x, const vector <double> &y);
void SetCubicClampedEndptDeriv(const double yp1, const double ypn);
void AddCubicHermiteDeriv(unsigned int n, double *fprimeOfx);
void AddCubicHermiteDeriv(const vector <double> &fprimeOfx);
void AddCubicHermiteDeriv(const double fprimeOfx);
//ACCESSOR METHODS AFTER DATA IS ENTERED
double DomainMinimum();
double DomainMaximum();
bool Contains(double x);
/**
* Returns the number of the coordinates added to the data set.
*
* @return @b unsigned @b int Size of data set.
*/
inline unsigned int Size() {
return(p_x.size());
}
/**
* This enum defines the manner in which a value outside of the
* domain should be handled if passed to the Evaluate() method.
*/
enum ExtrapType { ThrowError, //!< Evaluate() throws an error if @a a is outside of the domain.
Extrapolate, //!< Evaluate() attempts to extrapolate if @a a is outside of the domain.
//!< This is only valid for NumericalApproximation::InterpType @a CubicClamped or @a PolynomialNeville
//!< and the result will be accurate only if sufficiently close to the domain boundary.
NearestEndpoint //!< Evaluate() returns the y-value of the nearest endpoint if @a a is outside of the domain.
};
// INTERPOLATION AND EXTRAPOLATION RESULTS
double Evaluate(const double a, const ExtrapType &etype = ThrowError);
vector <double> Evaluate(const vector <double> &a, const ExtrapType &etype = ThrowError);
vector <double> PolynomialNevilleErrorEstimate();
vector <double> CubicClampedSecondDerivatives();
double EvaluateCubicHermiteFirstDeriv(const double a);
double EvaluateCubicHermiteSecDeriv(const double a);
// DIFFERENTIATION METHODS
double GslFirstDerivative(const double a);
double BackwardFirstDifference(const double a, const unsigned int n = 3,
const double h = 0.1);
double ForwardFirstDifference(const double a, const unsigned int n = 3,
const double h = 0.1);
double CenterFirstDifference(const double a, const unsigned int n = 5,
const double h = 0.1);
double GslSecondDerivative(const double a);
double BackwardSecondDifference(const double a, const unsigned int n = 3,
const double h = 0.1);
double ForwardSecondDifference(const double a, const unsigned int n = 3,
const double h = 0.1);
double CenterSecondDifference(const double a, const unsigned int n = 5,
const double h = 0.1);
// INTERGRATION METHODS
double GslIntegral(const double a, const double b);
double TrapezoidalRule(const double a, const double b);
double Simpsons3PointRule(const double a, const double b);
double Simpsons4PointRule(const double a, const double b);
double BoolesRule(const double a, const double b);
double RefineExtendedTrap(double a, double b, double s, unsigned int n);
double RombergsMethod(double a, double b);
// ASSIGNMENT OPERATORS
void Reset();
void Reset(NumericalApproximation::InterpType itype);
void SetInterpType(NumericalApproximation::InterpType itype);
protected:
// == CLASS VARIABLES
// VARIABLES FOR ALL INTERP TYPES
InterpType p_itype; //!< Interpolation type
vector<double> p_x; //!< List of X values
vector<double> p_y; //!< List of Y values
bool p_dataValidated; //!< Flag variable to determine whether ValidateDataSet() has been called
// GSL INTERP VARIABLES
typedef const gsl_interp_type *InterpFunctor; //!< GSL Interpolation specs
typedef map<InterpType, InterpFunctor> FunctorList; //!< Set up a std::map of GSL interpolator functors. List of function types
typedef FunctorList::const_iterator FunctorConstIter; //!< GSL Iterator
gsl_interp_accel *p_acc; //!< Lookup accelorator
gsl_spline *p_interp; //!< Currently active interpolator
static FunctorList p_interpFunctors; //!< Maintains list of interpolator options
// CUBIC CLAMPED VARIABLES
bool p_clampedEndptsSet; //!< Flag variable to determine whether SetCubicClampedEndptDeriv() has been called after all data was added for @a CubicClamped interpolation.
bool p_clampedComputed; //!< Flag variable to determine whether ComputeCubicClamped() has been called.
double p_clampedDerivFirstPt; //!< First derivative of first x-value, p_x[0]. This is only used for the @a CubicClamped interpolation type.
double p_clampedDerivLastPt; //!< First derivative of last x-value, p_x[n-1]. This is only used for the @a CubicClamped interpolation type.
vector<double> p_clampedSecondDerivs; //!< List of second derivatives evaluated at p_x values. This is only used for the @a CubicClamped interpolation type.
// POLYNOMIAL NEVILLE VARIABLES
vector <double> p_polyNevError; //!< Estimate of error for interpolation evaluated at x. This is only used for the @a PolynomialNeville interpolation type. 91 taken from AtmosModel.
// CUBIC HERMITE VARIABLES
vector<double> p_fprimeOfx; //!< List of first derivatives corresponding to each x value in the data set (i.e. each value in p_x)
// == PROTECTED METHODS
// CREATING, DESTROYING OBJECT
void Init(NumericalApproximation::InterpType itype);
bool GslInterpType(NumericalApproximation::InterpType itype) const;
void GslAllocation(unsigned int npoints);
void GslDeallocation();
InterpFunctor GslFunctor(NumericalApproximation::InterpType itype) const;
// VERIFICATION METHODS
void GslIntegrityCheck(int gsl_status, const char *src,
int line);
void ValidateDataSet();
bool InsideDomain(const double a);
// COMPUTATION AND EVALUATION METHODS
bool GslComputed() const;
void ComputeGsl();
void ComputeCubicClamped();
double ValueToExtrapolate(const double a, const ExtrapType &etype);
double EvaluateCubicNeighborhood(const double a);
vector <double> EvaluateCubicNeighborhood(const vector <double> &a, const ExtrapType &etype);
double EvaluateCubicClamped(const double a);
double EvaluateCubicHermite(const double a);
double EvaluatePolynomialNeville(const double a);
vector <double> EvaluateForIntegration(const double a, const double b,
const unsigned int n);
int FindIntervalLowerIndex(const double a);
// STANDARDIZE ERRORS
void ReportException(IException::ErrorType type, const string &method,
const string &message, const char *filesrc,
int lineno) const;
};
};
#endif
| {
"alphanum_fraction": 0.5738706664,
"avg_line_length": 43.187568157,
"ext": "h",
"hexsha": "d6a6f7060fb097a14169d99d5d010efb5689b22c",
"lang": "C",
"max_forks_count": 164,
"max_forks_repo_forks_event_max_datetime": "2022-03-23T10:22:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-30T21:15:44.000Z",
"max_forks_repo_head_hexsha": "2c40e08caed09968ea01d5a767a676172ad20080",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "jlaura/isis3",
"max_forks_repo_path": "isis/src/base/objs/NumericalApproximation/NumericalApproximation.h",
"max_issues_count": 3825,
"max_issues_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:45:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-11T21:27:34.000Z",
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "kdl222/ISIS3",
"max_issues_repo_path": "isis/src/base/objs/NumericalApproximation/NumericalApproximation.h",
"max_line_length": 210,
"max_stars_count": 134,
"max_stars_repo_head_hexsha": "aab0e63088046690e6c031881825596c1c2cc380",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "kdl222/ISIS3",
"max_stars_repo_path": "isis/src/base/objs/NumericalApproximation/NumericalApproximation.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T03:53:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-18T00:16:24.000Z",
"num_tokens": 10969,
"size": 39603
} |
#ifndef _SNPLIB_SRC_MATH_LIB_H_
#define _SNPLIB_SRC_MATH_LIB_H_
#ifdef USE_MKL
#include <mkl.h>
#define set_num_threads mkl_set_num_threads
#endif
#ifdef USE_OPENBLAS
#ifdef _MSC_VER
#include <complex>
#define lapack_complex_float std::complex<float>
#define lapack_complex_double std::complex<double>
#endif
#include <cblas.h>
#include <lapacke.h>
#define set_num_threads openblas_set_num_threads
#endif
#endif //_SNPLIB_SRC_MATH_LIB_H_
| {
"alphanum_fraction": 0.8295454545,
"avg_line_length": 22,
"ext": "h",
"hexsha": "5cf38a7eea848fea57ef741a7f6cbaa81b09d893",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-02-17T17:20:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-17T17:20:24.000Z",
"max_forks_repo_head_hexsha": "aea1cb943a7db22faa592a53cf1132561ce50c4e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "VasLem/SNPLIB",
"max_forks_repo_path": "src/math_lib.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "aea1cb943a7db22faa592a53cf1132561ce50c4e",
"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": "VasLem/SNPLIB",
"max_issues_repo_path": "src/math_lib.h",
"max_line_length": 50,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "aea1cb943a7db22faa592a53cf1132561ce50c4e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "VasLem/SNPLIB",
"max_stars_repo_path": "src/math_lib.h",
"max_stars_repo_stars_event_max_datetime": "2021-10-05T18:01:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-21T04:55:13.000Z",
"num_tokens": 115,
"size": 440
} |
/**
*
* @file core_cgetrf.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 Mathieu Faverge
* @date 2010-11-15
* @generated c Tue Jan 7 11:44:48 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex32_t
*
* CORE_cgetrf - Computes an LU factorization of a general M-by-N matrix A
* using the tile LU algorithm with partial tile pivoting with row interchanges.
*
*******************************************************************************
*
* @param[in] m
* The number of rows of the matrix A. m >= 0.
*
* @param[in] n
* The number of columns of the matrix A. n >= 0.
*
* @param[in,out] A
* On entry, the M-by-N matrix to be factored.
* On exit, the tile factors L and U from the factorization.
*
* @param[in] lda
* The leading dimension of the array A. LDA >= max(1,M).
*
* @param[out] IPIV
* The pivot indices that define the permutations.
*
* @param[out] info
* - 0 on successful exit
* - <0 if -i, the i-th argument had an illegal value
* - >0 if i, U(i,i) is exactly zero. The factorization has been
* completed, but the factor U is exactly singular, and division by
* zero will occur if it is used to solve a system of equations.
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_cgetrf = PCORE_cgetrf
#define CORE_cgetrf PCORE_cgetrf
#endif
int CORE_cgetrf(int m, int n,
PLASMA_Complex32_t *A, int lda,
int *IPIV, int *info)
{
*info = LAPACKE_cgetrf_work(LAPACK_COL_MAJOR, m, n, A, lda, IPIV );
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.5324118208,
"avg_line_length": 31.3134328358,
"ext": "c",
"hexsha": "4105a20f6c64ddce88fff7c1c111c5527f651ab7",
"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_cgetrf.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_cgetrf.c",
"max_line_length": 81,
"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_cgetrf.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 528,
"size": 2098
} |
/**********************************\
* Test benchmark *
* *
* by *
* Elliott Forney *
* 3.15.2010 *
\**********************************/
/*
* Libraries
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <getopt.h>
#include <math.h>
#include <cblas.h>
#include "matrix.h"
#include "benchmark.h"
#include "errcheck.h"
/*
* Macros
*/
// print command line usage
#define print_usage() fprintf(stdout, "Usage: %s [-m rows] [-n cols] [-s]\n", arg[0])
// acceptable maximum relative error tolerance
#define TOLERANCE 0.01
#define DEBUG 0
/*
* Global variables
*/
// flag for simple, one line output
bool simple_out = false;
/*
* Function prototypes
*/
// parse command line arguments
void parse_args(int narg, char **arg,
long long *m, long long *n);
/*
* Function bodies
*/
// setup network
int main(int narg, char **arg)
{
// default matrix dimensions
long long m = 6400;
long long n = 0;
// parse command line arguments
parse_args(narg, arg, &m, &n);
// if n or p == 0 then set to m
if (n == 0)
n = m;
// load test matrix b
matrix a;
matrix_init(&a, m, n);
matrix_load_runif(a, 0, 1);
// create matrix to hold result
matrix result;
matrix_init(&result, m, n);
// run warm up
matrix_phi_prime(result, a);
// wait for all kernels to finish
matrix_wait();
// create a new benchmark timer
benchmark ben;
benchmark_init(&ben);
// start timer
benchmark_start_timer(&ben);
// run multiplication
matrix_phi_prime(result, a);
// wait for all kernels to finish
matrix_wait();
// stop timer
benchmark_stop_timer(&ben);
// figure giga floating point operatins per second
benchmark_add_flop(&ben, 3ll*m*n);
double gflops = benchmark_check_gflops(ben);
double time = benchmark_check_timer(ben);
// print time and gbytess
printf("Time: %f GFlopS: %f\n",
time, gflops);
// clean up
matrix_dest(&a);
matrix_dest(&result);
benchmark_dest(&ben);
// Come back soon now ya'hear!
return 0;
}
// parse command line arguments
void parse_args(int narg, char **arg,
long long *m, long long *n)
{
int opt; // getopt output
// for each argument
while ((opt = getopt(narg, arg, "sm:n:")) != -1)
{
if (opt == 's')
simple_out = true;
else if (opt == 'm')
*m = (long long)atoi(arg[optind-1]);
else if (opt == 'n')
*n = (long long)atoi(arg[optind-1]);
// print usage and quit on unknown option
else
{
print_usage();
exit(1);
}
}
// assume last non dash arg is m
if (optind < narg)
*m = (long long)atoi(arg[optind]);
}
| {
"alphanum_fraction": 0.5746189295,
"avg_line_length": 18.6821192053,
"ext": "c",
"hexsha": "74ce0a13facb71db55dc082944e02ab581d4128f",
"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": "75028a7e42e4a02460f20f1aa82c289801de1b05",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "idfah/badger",
"max_forks_repo_path": "phiprime.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "75028a7e42e4a02460f20f1aa82c289801de1b05",
"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": "idfah/badger",
"max_issues_repo_path": "phiprime.c",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "75028a7e42e4a02460f20f1aa82c289801de1b05",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "idfah/badger",
"max_stars_repo_path": "phiprime.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 774,
"size": 2821
} |
/* matrix/gsl_matrix_int.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATRIX_INT_H__
#define __GSL_MATRIX_INT_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_int.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;
int * data;
gsl_block_int * block;
int owner;
} gsl_matrix_int;
typedef struct
{
gsl_matrix_int matrix;
} _gsl_matrix_int_view;
typedef _gsl_matrix_int_view gsl_matrix_int_view;
typedef struct
{
gsl_matrix_int matrix;
} _gsl_matrix_int_const_view;
typedef const _gsl_matrix_int_const_view gsl_matrix_int_const_view;
/* Allocation */
GSL_EXPORT
gsl_matrix_int *
gsl_matrix_int_alloc (const size_t n1, const size_t n2);
GSL_EXPORT
gsl_matrix_int *
gsl_matrix_int_calloc (const size_t n1, const size_t n2);
GSL_EXPORT
gsl_matrix_int *
gsl_matrix_int_alloc_from_block (gsl_block_int * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
GSL_EXPORT
gsl_matrix_int *
gsl_matrix_int_alloc_from_matrix (gsl_matrix_int * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
GSL_EXPORT
gsl_vector_int *
gsl_vector_int_alloc_row_from_matrix (gsl_matrix_int * m,
const size_t i);
GSL_EXPORT
gsl_vector_int *
gsl_vector_int_alloc_col_from_matrix (gsl_matrix_int * m,
const size_t j);
GSL_EXPORT void gsl_matrix_int_free (gsl_matrix_int * m);
/* Views */
GSL_EXPORT
_gsl_matrix_int_view
gsl_matrix_int_submatrix (gsl_matrix_int * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_EXPORT
_gsl_vector_int_view
gsl_matrix_int_row (gsl_matrix_int * m, const size_t i);
GSL_EXPORT
_gsl_vector_int_view
gsl_matrix_int_column (gsl_matrix_int * m, const size_t j);
GSL_EXPORT
_gsl_vector_int_view
gsl_matrix_int_diagonal (gsl_matrix_int * m);
GSL_EXPORT
_gsl_vector_int_view
gsl_matrix_int_subdiagonal (gsl_matrix_int * m, const size_t k);
GSL_EXPORT
_gsl_vector_int_view
gsl_matrix_int_superdiagonal (gsl_matrix_int * m, const size_t k);
GSL_EXPORT
_gsl_matrix_int_view
gsl_matrix_int_view_array (int * base,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_int_view
gsl_matrix_int_view_array_with_tda (int * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_EXPORT
_gsl_matrix_int_view
gsl_matrix_int_view_vector (gsl_vector_int * v,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_int_view
gsl_matrix_int_view_vector_with_tda (gsl_vector_int * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_EXPORT
_gsl_matrix_int_const_view
gsl_matrix_int_const_submatrix (const gsl_matrix_int * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_EXPORT
_gsl_vector_int_const_view
gsl_matrix_int_const_row (const gsl_matrix_int * m,
const size_t i);
GSL_EXPORT
_gsl_vector_int_const_view
gsl_matrix_int_const_column (const gsl_matrix_int * m,
const size_t j);
GSL_EXPORT
_gsl_vector_int_const_view
gsl_matrix_int_const_diagonal (const gsl_matrix_int * m);
GSL_EXPORT
_gsl_vector_int_const_view
gsl_matrix_int_const_subdiagonal (const gsl_matrix_int * m,
const size_t k);
GSL_EXPORT
_gsl_vector_int_const_view
gsl_matrix_int_const_superdiagonal (const gsl_matrix_int * m,
const size_t k);
GSL_EXPORT
_gsl_matrix_int_const_view
gsl_matrix_int_const_view_array (const int * base,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_int_const_view
gsl_matrix_int_const_view_array_with_tda (const int * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_EXPORT
_gsl_matrix_int_const_view
gsl_matrix_int_const_view_vector (const gsl_vector_int * v,
const size_t n1,
const size_t n2);
GSL_EXPORT
_gsl_matrix_int_const_view
gsl_matrix_int_const_view_vector_with_tda (const gsl_vector_int * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_EXPORT int gsl_matrix_int_get(const gsl_matrix_int * m, const size_t i, const size_t j);
GSL_EXPORT void gsl_matrix_int_set(gsl_matrix_int * m, const size_t i, const size_t j, const int x);
GSL_EXPORT int * gsl_matrix_int_ptr(gsl_matrix_int * m, const size_t i, const size_t j);
GSL_EXPORT const int * gsl_matrix_int_const_ptr(const gsl_matrix_int * m, const size_t i, const size_t j);
GSL_EXPORT void gsl_matrix_int_set_zero (gsl_matrix_int * m);
GSL_EXPORT void gsl_matrix_int_set_identity (gsl_matrix_int * m);
GSL_EXPORT void gsl_matrix_int_set_all (gsl_matrix_int * m, int x);
GSL_EXPORT int gsl_matrix_int_fread (FILE * stream, gsl_matrix_int * m) ;
GSL_EXPORT int gsl_matrix_int_fwrite (FILE * stream, const gsl_matrix_int * m) ;
GSL_EXPORT int gsl_matrix_int_fscanf (FILE * stream, gsl_matrix_int * m);
GSL_EXPORT int gsl_matrix_int_fprintf (FILE * stream, const gsl_matrix_int * m, const char * format);
GSL_EXPORT int gsl_matrix_int_memcpy(gsl_matrix_int * dest, const gsl_matrix_int * src);
GSL_EXPORT int gsl_matrix_int_swap(gsl_matrix_int * m1, gsl_matrix_int * m2);
GSL_EXPORT int gsl_matrix_int_swap_rows(gsl_matrix_int * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_int_swap_columns(gsl_matrix_int * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_int_swap_rowcol(gsl_matrix_int * m, const size_t i, const size_t j);
GSL_EXPORT int gsl_matrix_int_transpose (gsl_matrix_int * m);
GSL_EXPORT int gsl_matrix_int_transpose_memcpy (gsl_matrix_int * dest, const gsl_matrix_int * src);
GSL_EXPORT int gsl_matrix_int_max (const gsl_matrix_int * m);
GSL_EXPORT int gsl_matrix_int_min (const gsl_matrix_int * m);
GSL_EXPORT void gsl_matrix_int_minmax (const gsl_matrix_int * m, int * min_out, int * max_out);
GSL_EXPORT void gsl_matrix_int_max_index (const gsl_matrix_int * m, size_t * imax, size_t *jmax);
GSL_EXPORT void gsl_matrix_int_min_index (const gsl_matrix_int * m, size_t * imin, size_t *jmin);
GSL_EXPORT void gsl_matrix_int_minmax_index (const gsl_matrix_int * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_EXPORT int gsl_matrix_int_isnull (const gsl_matrix_int * m);
GSL_EXPORT int gsl_matrix_int_add (gsl_matrix_int * a, const gsl_matrix_int * b);
GSL_EXPORT int gsl_matrix_int_sub (gsl_matrix_int * a, const gsl_matrix_int * b);
GSL_EXPORT int gsl_matrix_int_mul_elements (gsl_matrix_int * a, const gsl_matrix_int * b);
GSL_EXPORT int gsl_matrix_int_div_elements (gsl_matrix_int * a, const gsl_matrix_int * b);
GSL_EXPORT int gsl_matrix_int_scale (gsl_matrix_int * a, const double x);
GSL_EXPORT int gsl_matrix_int_add_constant (gsl_matrix_int * a, const double x);
GSL_EXPORT int gsl_matrix_int_add_diagonal (gsl_matrix_int * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_EXPORT int gsl_matrix_int_get_row(gsl_vector_int * v, const gsl_matrix_int * m, const size_t i);
GSL_EXPORT int gsl_matrix_int_get_col(gsl_vector_int * v, const gsl_matrix_int * m, const size_t j);
GSL_EXPORT int gsl_matrix_int_set_row(gsl_matrix_int * m, const size_t i, const gsl_vector_int * v);
GSL_EXPORT int gsl_matrix_int_set_col(gsl_matrix_int * m, const size_t j, const gsl_vector_int * v);
/* inline functions if you are using GCC */
#ifdef HAVE_INLINE
extern inline
int
gsl_matrix_int_get(const gsl_matrix_int * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
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_int_set(gsl_matrix_int * m, const size_t i, const size_t j, const int x)
{
#if GSL_RANGE_CHECK
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
int *
gsl_matrix_int_ptr(gsl_matrix_int * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
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 (int *) (m->data + (i * m->tda + j)) ;
}
extern inline
const int *
gsl_matrix_int_const_ptr(const gsl_matrix_int * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
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 int *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_INT_H__ */
| {
"alphanum_fraction": 0.667738478,
"avg_line_length": 32.6413994169,
"ext": "h",
"hexsha": "1a732f95fe9f2c4177681b3196111b133dfd34f4",
"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_matrix_int.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_matrix_int.h",
"max_line_length": 131,
"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_matrix_int.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2791,
"size": 11196
} |
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_vegas.h>
#include "integral.c"
#include "timer.c"
#include "timer.h"
#define N 20
double g (double *t,size_t dim, void *params);
int main (void)
{
double res, err;
// 6 dimensional integral
size_t dim = 6;
int dims=6;
//evaluating all dimensions from 0 to 1
double x1[] = { 0., 0., 0. ,0.,0.,0. };
double xu[] = { 1., 1., 1. ,1.,1.,1. };
FILE *file;
file=fopen("data.txt","w");
double rmin=1.001;
double rmax=4;
double rtot=rmin;
double rstep= (rmax-rmin)/(N);
gsl_rng *r = gsl_rng_alloc (gsl_rng_taus2);
unsigned long seed = 1UL;
gsl_rng_set (r, seed);
// 10^6 function evaluations per iteration
size_t calls = 1000000;
gsl_monte_function G= { &g, dim, &rtot};
gsl_monte_vegas_state *sv = gsl_monte_vegas_alloc (dim);
gsl_monte_vegas_init (sv);
//Vegas integration
double vegas[N];
double rval[N];
double di[N];
timer_start ();
for (int i = 0; i<=N-1; i++)
{
gsl_monte_vegas_integrate (&G,x1,xu,dim,calls/5,r,sv,&res,&err);
do
{
gsl_monte_vegas_integrate (&G, x1,xu,dim,calls,r,sv,&res,&err);
fflush (stdout);
}
while (fabs (gsl_monte_vegas_chisq (sv)-1.0) >0.2);
rtot+=rstep;
vegas[i]=res;
rval[i]=rtot;
di[i] = -.2 / pow (rtot,3.);
}
timer_stop ();
double tvegas=timer_stop();
gsl_monte_vegas_free (sv);
rtot=rmin;
printf (" %10.6f\n",tvegas);
//homemade
rtot=rmin;
double x[6];
r = gsl_rng_alloc (gsl_rng_taus2);
gsl_rng_set (r, 1UL);
double thome;
long i, j;
double r2=0.;
double home[20];
for (j = 0; j < N; j++)
{
r2=0.;
for (i = 0; i < 1.e6; i++)
{
for (int k = 0; k <= dims; k++)
{
x[k] = gsl_rng_uniform (r) ;
}
r2+= g(x,dim, &rtot);
}
res = r2/1.e6;
fflush (stdout);
rtot+=rstep;
home [j]=res;
}
timer_stop();
rtot=rmin;
thome=timer_stop();
printf (" %10.6f\n",thome);
for (int t=0;t<N;t++)
{
fprintf (file, "%10.6f %10.6f %10.6f %10.6f \n " , rval[t],fabs(-vegas[t]),fabs(-di[t]),fabs(-home[t]));
rtot+=rstep;
}
return 0;
}
| {
"alphanum_fraction": 0.5729261623,
"avg_line_length": 20.5046728972,
"ext": "c",
"hexsha": "073ce7d3caaa9b9e50d0f5c6d30127513a5887fd",
"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": "25ce6ca213186edff973cae42a954e31947514a0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jlichtman13/fin2",
"max_forks_repo_path": "mci.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "25ce6ca213186edff973cae42a954e31947514a0",
"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": "jlichtman13/fin2",
"max_issues_repo_path": "mci.c",
"max_line_length": 128,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "25ce6ca213186edff973cae42a954e31947514a0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jlichtman13/fin2",
"max_stars_repo_path": "mci.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 800,
"size": 2194
} |
#pragma once
// STL and std libs
#include <map>
#include <set>
#include <vector>
#include <list>
#include <memory>
#include <functional>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <chrono>
#include <type_traits>
// Guildline Support Library
#include <gsl.h>
//// boost and std extension
//#include <boost\signals2.hpp>
//#include <boost\any.hpp>
//#include <boost\range\iterator_range_core.hpp>
//#include <boost\range\adaptor\transformed.hpp>
//#include <boost\operators.hpp>
//#include <boost\format.hpp>
//#include <boost\filesystem.hpp>
#include <stride_range.h>
#include <tree.h>
#include <minmax>
#include "Math3D.h"
#include "SmartPointers.h"
#include "String.h"
//#if defined __AVX__
//#undef __AVX__ //#error Eigen have problem with AVX now
//#endif
//#define EIGEN_HAS_CXX11_MATH 1
//#define EIGEN_HAS_STD_RESULT_OF 1
//#define EIGEN_HAS_VARIADIC_TEMPLATES 1
//#include <Eigen\Dense>
namespace Causality
{
using time_seconds = std::chrono::duration<double>;
typedef uint64_t id_t;
using std::string;
using std::iterator_range;
//using boost::sub_range;
//namespace adaptors = boost::adaptors;
using gsl::owner;
using gsl::byte;
using gsl::not_null;
using stdx::tree_node;
using stdx::foward_tree_node;
using stdx::stride_range;
using stdx::stride_iterator;
using std::vector;
using std::map;
using std::function;
using std::unique_ptr;
using std::shared_ptr;
using std::list;
using std::weak_ptr;
} | {
"alphanum_fraction": 0.7348329925,
"avg_line_length": 20.375,
"ext": "h",
"hexsha": "b4f6a6791ea47e8f3a51dc67bfeab41579516e79",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2017-06-12T16:15:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-01-16T14:25:28.000Z",
"max_forks_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ArcEarth/SrInspection",
"max_forks_repo_path": "Causality/BCL.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9",
"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": "ArcEarth/SrInspection",
"max_issues_repo_path": "Causality/BCL.h",
"max_line_length": 57,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "63c540d1736e323a0f409914e413cb237f03c5c9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ArcEarth/SrInspection",
"max_stars_repo_path": "Causality/BCL.h",
"max_stars_repo_stars_event_max_datetime": "2020-03-31T22:20:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-07-13T18:30:33.000Z",
"num_tokens": 387,
"size": 1467
} |
#ifndef COMMON_H
#define COMMON_H
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv2.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_statistics.h>
#include <plplot/plplot.h>
#endif
| {
"alphanum_fraction": 0.7355932203,
"avg_line_length": 16.3888888889,
"ext": "h",
"hexsha": "29f565469f9ea9a105d7eb654a7bb792a6f10215",
"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": "4f815a738abad43531d02ac66f5bd0d9a1def52a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "liujiamingustc/phd",
"max_forks_repo_path": "awesome/c_cpp/cpp-cheat/gsl/common.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a",
"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": "liujiamingustc/phd",
"max_issues_repo_path": "awesome/c_cpp/cpp-cheat/gsl/common.h",
"max_line_length": 31,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4f815a738abad43531d02ac66f5bd0d9a1def52a",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "liujiamingustc/phd",
"max_stars_repo_path": "awesome/c_cpp/cpp-cheat/gsl/common.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T03:02:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-06T03:01:18.000Z",
"num_tokens": 88,
"size": 295
} |
/* integration/qk15.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_integration.h>
/* Gauss quadrature weights and kronrod quadrature abscissae and
weights as evaluated with 80 decimal digit arithmetic by
L. W. Fullerton, Bell Labs, Nov. 1981. */
static const double xgk[8] = /* abscissae of the 15-point kronrod rule */
{
0.991455371120812639206854697526329,
0.949107912342758524526189684047851,
0.864864423359769072789712788640926,
0.741531185599394439863864773280788,
0.586087235467691130294144838258730,
0.405845151377397166906606412076961,
0.207784955007898467600689403773245,
0.000000000000000000000000000000000
};
/* xgk[1], xgk[3], ... abscissae of the 7-point gauss rule.
xgk[0], xgk[2], ... abscissae to optimally extend the 7-point gauss rule */
static const double wg[4] = /* weights of the 7-point gauss rule */
{
0.129484966168869693270611432679082,
0.279705391489276667901467771423780,
0.381830050505118944950369775488975,
0.417959183673469387755102040816327
};
static const double wgk[8] = /* weights of the 15-point kronrod rule */
{
0.022935322010529224963732008058970,
0.063092092629978553290700663189204,
0.104790010322250183839876322541518,
0.140653259715525918745189590510238,
0.169004726639267902826583426598550,
0.190350578064785409913256402421014,
0.204432940075298892414161999234649,
0.209482141084727828012999174891714
};
void
gsl_integration_qk15 (const gsl_function * f, double a, double b,
double *result, double *abserr,
double *resabs, double *resasc)
{
double fv1[8], fv2[8];
gsl_integration_qk (8, xgk, wg, wgk, fv1, fv2, f, a, b, result, abserr, resabs, resasc);
}
| {
"alphanum_fraction": 0.7560679612,
"avg_line_length": 34.8169014085,
"ext": "c",
"hexsha": "bfba5176224528f656c7cff696542d24f38cec13",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/qk15.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/qk15.c",
"max_line_length": 90,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/integration/qk15.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": 811,
"size": 2472
} |
#ifndef ConditionalTest_SERIAL_H
#define ConditionalTest_SERIAL_H
#include <ace/core/core.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_statistics_double.h>
#include <gsl/gsl_randist.h>
#include "conditionaltest.h"
class ConditionalTest::Serial : public EAbstractAnalyticSerial
{
Q_OBJECT
public:
explicit Serial(ConditionalTest* parent);
virtual std::unique_ptr<EAbstractAnalyticBlock> execute(const EAbstractAnalyticBlock* block) override final;
// helper functions
bool isEmpty(QVector<QVector<double>>& matrix);
// Statistical Tests
void hypergeom(
const QVector<QString>& amx_column,
const CCMatrix::Pair& ccmPair,
int clusterIndex,
int featureIndex,
int labelIndex,
double& results);
void test_proportions(
const QVector<QString>& amx_column,
const CCMatrix::Pair& ccmPair,
int clusterIndex,
int featureIndex,
int labelIndex,
double& results);
void regression(
const QVector<QString>& amx_column,
const CCMatrix::Pair& ccmPair,
int clusterIndex,
QVector<double>& results);
private:
/*!
* Pointer to the base analytic for this object.
*/
ConditionalTest* _base;
// Performs power analysis for multiple-linear regression.
double pwr_f2_test(int u, int v, double f2, double sig_level);
};
#endif
| {
"alphanum_fraction": 0.6850944717,
"avg_line_length": 24.6379310345,
"ext": "h",
"hexsha": "a71077385ff7e6f2eac3c42a5a2fc7c264312538",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-02-26T00:01:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-12T22:03:42.000Z",
"max_forks_repo_head_hexsha": "afcd1cdde7e62e464561f0624dc6fa78e434e102",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SystemsGenetics/KINC",
"max_forks_repo_path": "src/core/conditionaltest_serial.h",
"max_issues_count": 182,
"max_issues_repo_head_hexsha": "afcd1cdde7e62e464561f0624dc6fa78e434e102",
"max_issues_repo_issues_event_max_datetime": "2022-01-30T01:25:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-07-31T07:15:15.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SystemsGenetics/KINC",
"max_issues_repo_path": "src/core/conditionaltest_serial.h",
"max_line_length": 112,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "afcd1cdde7e62e464561f0624dc6fa78e434e102",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SystemsGenetics/KINC",
"max_stars_repo_path": "src/core/conditionaltest_serial.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-10T17:20:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-08-15T13:27:35.000Z",
"num_tokens": 323,
"size": 1429
} |
#include "tmcoct.h"
#include <gsl/gsl_rng.h>
const double G_COS_0_D = 1.0 - 1.0E-14;
const double G_COS_90_D = 1.0E-7;
#define STANDARDTEST 0
/* testing program using fixed rnd seed. */
#define PARTIALREFLECTION 1
/* 1=split photon, 0=statistical reflection. */
#define COSZERO (1.0-1.0E-14)
/* cosine of about 1e-6 rad. */
#define COS90D 1.0E-6
/* cosine of about 1.57 - 1e-6 rad. */
const gsl_rng_type *T_RNG_GSL;
gsl_rng *r_RNG_GSL;
/***********************************************************
* A random number generator from Numerical Recipes in C.
****/
#define MBIG 1000000000
#define MSEED 161803398
#define MZ 0
#define FAC 1.0E-9
#undef MBIG
#undef MSEED
#undef MZ
#undef FAC
/***********************************************************
* Generate a random number between 0 and 1. Take a
* number as seed the first time entering the function.
* The seed is limited to 1<<15.
* We found that when idum is too large, ran3 may return
* numbers beyond 0 and 1.
****/
double RandomNum(void) {
static Boolean first_time = 1;
static unsigned long int idum; /* seed for ran3. */
if (first_time) {
T_RNG_GSL = gsl_rng_default;
r_RNG_GSL = gsl_rng_alloc(T_RNG_GSL);
#if STANDARDTEST /* Use fixed seed to test the program. */
printf("*** Using seed to test. ***\n");
printf("*** Remove the fixed seed after the test. ***\n");
idum = 7923;
#else
idum = (unsigned long int) time(NULL) % (1 << 15);
/* use 16-bit integer as the seed. */
#endif
printf("Random seed = %lu \n", idum);
//ran3(&idum);
gsl_rng_set(r_RNG_GSL, idum);
first_time = 0;
//idum = 1;
}
// TODO FIXME remove 1.0 -
return (1.0 - gsl_rng_uniform(r_RNG_GSL));
}
/***********************************************************
* Compute the specular reflection.
*
* If the first layer is a turbid medium, use the Fresnel
* reflection from the boundary of the first layer as the
* specular reflectance.
*
* If the first layer is glass, multiple reflections in
* the first layer is considered to get the specular
* reflectance.
*
* The subroutine assumes the Layerspecs array is correctly
* initialized.
****/
double Rspecular(double ni, double nt) {
double r1;
/* direct reflections from the 1st and 2nd layers. */
double temp;
temp = (ni - nt) / (ni + nt);
r1 = temp * temp;
return (r1);
}
/***********************************************************
* Initialize a photon packet.
****/
void LaunchPhoton(SimulationStruct *in_parm, double Rspecular, TetrahedronPhotonStruct *Photon_Ptr,
TetrahedronPhotonStruct *PhotonCont_Ptr, TetrahedronStruct *TetrahedronRoot) {
if (Photon_Ptr->FstBackReflectionFlag) {
//Most often case for biased simulations
//The photon will be re-initialized from where the bias was applied
long double LikelihoodRatioTmp = Photon_Ptr->LikelihoodRatioAfterFstBias;
CopyPhotonStruct(PhotonCont_Ptr, Photon_Ptr);
//Apply one unbiased random scatter to the split photon
Spin(regionspecs[Photon_Ptr->tetrahedron->region].g, Photon_Ptr);
if (LikelihoodRatioTmp < 1)
// Adjust the likelihoodRation to make the simulation unbiased
Photon_Ptr->LikelihoodRatio = 1 - LikelihoodRatioTmp;
else
Photon_Ptr->LikelihoodRatio = 1;
} else {
Photon_Ptr->w = 1.0 - Rspecular;
Photon_Ptr->x = in_parm->probe_x;
Photon_Ptr->y = in_parm->probe_y;
Photon_Ptr->z = in_parm->probe_z;
Photon_Ptr->s = 0.0;
Photon_Ptr->sleft = 0.0;
Photon_Ptr->ux = Photon_Ptr->uy = 0.0;
Photon_Ptr->uz = 1.0;
Photon_Ptr->dead = 0.0;
Photon_Ptr->OpticalPath = 0.0;
Photon_Ptr->MaxDepth = 0.0;
Photon_Ptr->LikelihoodRatio = 1.0;
Photon_Ptr->LikelihoodRatioAfterFstBias = 1.0;
Photon_Ptr->FstBackReflectionFlag = 0;
Photon_Ptr->LocationFstBias = -1.0;
Photon_Ptr->NumBackwardsSpecularReflections = 0;
Photon_Ptr->LikelihoodRatioIncreaseFstBias = 0;
Photon_Ptr->LikelihoodRatioIncreaseFstBias = 0;
Photon_Ptr->NextTetrahedron = -1;
Photon_Ptr->tetrahedron = TetrahedronRoot;
}
}
/***********************************************************
* Choose (sample) a new theta angle for photon propagation
* according to the anisotropy.
*
* If anisotropy g is 0, then
* cos(theta) = 2*rand-1.
* otherwise
* sample according to the Henyey-Greenstein function.
*
* Returns the cosine of the polar deflection angle theta.
****/
double SpinTheta(double g) {
double cost;
if (g == 0.0)
cost = 2.0 * RandomNum() - 1.0;
else {
double temp = (1.0 - g * g) / (1.0 - g + 2.0 * g * RandomNum());
cost = (1.0 + g * g - temp * temp) / (2.0 * g);
if (cost < -1.0) cost = -1.0;
else if (cost > 1.0) cost = 1.0;
}
return (cost);
}
double SpinThetaForwardFstBias(double g) {
double cost;
if (g == 0.0)
cost = RandomNum();
else {
double RandomNumTmp = RandomNum();
double temp = RandomNumTmp / (1 - g) + (1 - RandomNumTmp) / sqrt(g * g + 1);
cost = (g * g + 1 - 1. / (temp * temp)) / (2 * g);
if (cost < -1) cost = -1;
else if (cost > 1) cost = 1;
}
return (cost);
}
/***********************************************************
* Choose a new direction for photon propagation by
* sampling the polar deflection angle theta and the
* azimuthal angle psi.
*
* Note:
* theta: 0 - pi so sin(theta) is always positive
* feel free to use sqrt() for cos(theta).
*
* psi: 0 - 2pi
* for 0-pi sin(psi) is +
* for pi-2pi sin(psi) is -
****/
void Spin(double g,
TetrahedronPhotonStruct *Photon_Ptr) {
double cost, sint; /* cosine and sine of the */
/* polar deflection angle theta. */
double cosp, sinp; /* cosine and sine of the */
/* azimuthal angle psi. */
double ux = Photon_Ptr->ux;
double uy = Photon_Ptr->uy;
double uz = Photon_Ptr->uz;
double psi;
cost = SpinTheta(g);
sint = sqrt(1.0 - cost * cost);
/* sqrt() is faster than sin(). */
psi = 2.0 * PI * RandomNum(); /* spin psi 0-2pi. */
cosp = cos(psi);
if (psi < PI)
sinp = sqrt(1.0 - cosp * cosp);
/* sqrt() is faster than sin(). */
else
sinp = -sqrt(1.0 - cosp * cosp);
if (fabs(uz) > COSZERO) { /* normal incident. */
Photon_Ptr->ux = sint * cosp;
Photon_Ptr->uy = sint * sinp;
Photon_Ptr->uz = cost * SIGN(uz);
/* SIGN() is faster than division. */
} else {
/* regular incident. */
double temp = sqrt(1.0 - uz * uz);
Photon_Ptr->ux = sint * (ux * uz * cosp - uy * sinp)
/ temp + ux * cost;
Photon_Ptr->uy = sint * (uy * uz * cosp + ux * sinp)
/ temp + uy * cost;
Photon_Ptr->uz = -sint * cosp * temp + uz * cost;
}
}
void SpinBias37(double g,
TetrahedronPhotonStruct *Photon_Ptr,
TetrahedronPhotonStruct *PhotonCont_Ptr,
SimulationStruct *In_Ptr)
{
double g_squared = sq(g);
double cost, sint; /* cosine and sine of the */
/* polar deflection angle theta. */
double cosp, sinp; /* cosine and sine of the */
/* azimuthal angle psi. */
double ux = Photon_Ptr->ux;
double uy = Photon_Ptr->uy;
double uz = Photon_Ptr->uz;
double ux_Orig = ux;
double uy_Orig = uy;
double uz_Orig = uz;
double psi;
double BackwardBiasCoefficient = In_Ptr->BackwardBiasCoefficient;
double costg;
double costg1, costg2;
double BiasCoefficientTmp = 0;
short int ReachedTargetOpticalDepthFlag = 0;
short int ThisIsFirstBackwardBiasFlag = 0;
if (Photon_Ptr->z > In_Ptr->TargetDepthMin
&& Photon_Ptr->z < In_Ptr->TargetDepthMax
&& Photon_Ptr->uz > 0
&& !Photon_Ptr->FstBackReflectionFlag) {
// The bias backwards will be applied only if the photon is going forward
// The status of the photon prior to the bias will be saved
CopyPhotonStruct(Photon_Ptr, PhotonCont_Ptr);
ReachedTargetOpticalDepthFlag = 1;
Photon_Ptr->FstBackReflectionFlag = 1; // Bias backwards only once
Photon_Ptr->LocationFstBias = Photon_Ptr->z;
BiasCoefficientTmp = BackwardBiasCoefficient;
ThisIsFirstBackwardBiasFlag = 1;
}
/**********************************
** Biased Direction towards probe
**********************************/
double vx = In_Ptr->probe_x-Photon_Ptr->x;
double vy = In_Ptr->probe_y-Photon_Ptr->y;
double vz = In_Ptr->probe_z-Photon_Ptr->z;
double LengthVector = sqrt(sq(vx) + sq(vy) + sq(vz));
vx /= LengthVector;
vy /= LengthVector;
vz /= LengthVector;
/*********************************/
if ((Photon_Ptr->FstBackReflectionFlag
|| Photon_Ptr->NumBackwardsSpecularReflections > 0)
&& !ReachedTargetOpticalDepthFlag)
{
// It was biased at least once before, and is moving backwards
ReachedTargetOpticalDepthFlag = 2;
double NextStepSize = -log(In_Ptr->rndStepSizeInTissue) / regionspecs[Photon_Ptr->tetrahedron->region].muas;
double CurrentDistanceToOrigin = sqrt(sq(Photon_Ptr->x-In_Ptr->probe_x) + sq(Photon_Ptr->y-In_Ptr->probe_y) + sq(Photon_Ptr->z-In_Ptr->probe_z));
if (NextStepSize >= CurrentDistanceToOrigin
&& acos(-vz) <= In_Ptr->MaxCollectingAngleDeg * PI / 180) {
ReachedTargetOpticalDepthFlag = 1;
}
BiasCoefficientTmp = BackwardBiasCoefficient;
}
int BiasFunctionRandomlySelected = 0;
if (ReachedTargetOpticalDepthFlag) {
// Photon reached target optical layer or may undergo an additional biased
// scattering or unbiased scattering
// BiasFunctionRandomlySelected=1 means use biased scattering and 2 means unbiased scattering
if (RandomNum() <= In_Ptr->ProbabilityAdditionalBias)
BiasFunctionRandomlySelected = 1;
else
BiasFunctionRandomlySelected = 2;
if (ReachedTargetOpticalDepthFlag == 1
|| BiasFunctionRandomlySelected == 1) {
/*************************************************************************
** The photon is within the target depth and going forward
** The additional biased scattering is randomly chosen
** So the scattering is biased Henyey-Greenstein scattering
*************************************************************************/
cost = SpinThetaForwardFstBias(BiasCoefficientTmp);
ux = vx;
uy = vy;
uz = vz;
} else {
/**************************************************************************************
** The photon is within the target depth but the scattering is randomly selected is
** unbiased scattering
** or the photon is already going backward or it is out of target depth
**************************************************************************************/
cost = SpinTheta(g);
}
} else {
/**************************************************************************
** The photon is not within the target depth or it is not going forward
** so do unbiased scattering
**************************************************************************/
cost = SpinTheta(g);
}
if (cost < -1)
cost = -1;
else if (cost > 1)
cost = 1;
sint = sqrt(1.0 - cost * cost);
/* sqrt() is faster than sin(). */
psi = 2.0 * PI * RandomNum(); /* spin psi 0-2pi. */
cosp = cos(psi);
if (psi < PI)
sinp = sqrt(1.0 - cosp * cosp);
/* sqrt() is faster than sin(). */
else
sinp = -sqrt(1.0 - cosp * cosp);
if (fabs(uz) > COSZERO) { /* normal incident. */
Photon_Ptr->ux = sint * cosp;
Photon_Ptr->uy = sint * sinp;
Photon_Ptr->uz = cost * SIGN(uz);
/* SIGN() is faster than division. */
} else { /* regular incident. */
double temp = sqrt(1.0 - uz * uz);
Photon_Ptr->ux = sint * (ux * uz * cosp - uy * sinp)
/ temp + ux * cost;
Photon_Ptr->uy = sint * (uy * uz * cosp + ux * sinp)
/ temp + uy * cost;
Photon_Ptr->uz = -sint * cosp * temp + uz * cost;
}
costg = ux_Orig * Photon_Ptr->ux
+ uy_Orig * Photon_Ptr->uy
+ uz_Orig * Photon_Ptr->uz;
costg2 = costg;
costg1 = vx * Photon_Ptr->ux
+ vy * Photon_Ptr->uy
+ vz * Photon_Ptr->uz;
if (BiasCoefficientTmp) {
double one_plus_a_squared = 1 + sq(BiasCoefficientTmp);
double sqrt_one_plus_a_squared = sqrt(one_plus_a_squared);
double LikelihoodRatioIncreaseFactor;
if (ReachedTargetOpticalDepthFlag == 1)
/****************************************************************************************
** Likelihood for the first Bias scattering. Equation (8) of the paper:
** Malektaji, Siavash, Ivan T. Lima, and Sherif S. Sherif. "Monte Carlo simulation of
** optical coherence tomography for turbid media with arbitrary spatial distributions."
** Journal of biomedical optics 19.4 (2014): 046001-046001.
****************************************************************************************/
LikelihoodRatioIncreaseFactor = ((1.0 - g_squared) * (sqrt_one_plus_a_squared - 1.0 + BiasCoefficientTmp) *
sqrt(cube(one_plus_a_squared - 2.0 * BiasCoefficientTmp * cost))) /
(2.0 * BiasCoefficientTmp * (1.0 - BiasCoefficientTmp) *
sqrt_one_plus_a_squared * sqrt(cube(1.0 + g_squared - 2.0 * g * costg)));
else {
double cost1, cost2;
if (BiasFunctionRandomlySelected == 1) {
cost1 = cost;
cost2 = costg2;
} else {
cost1 = costg1;
cost2 = cost;
}
/*******************************************************************************************************
** The likelihood ratio of additional biased scatterings, whether the biased or the unbiased
** probability density function is randomly selected, is calculated according to the equation (9)
** of the paper:
** Malektaji, Siavash, Ivan T. Lima, and Sherif S. Sherif. "Monte Carlo simulation of
** optical coherence tomography for turbid media with arbitrary spatial distributions."
** Journal of biomedical optics 19.4 (2014): 046001-046001.
*******************************************************************************************************/
double pdf1 = (sqrt_one_plus_a_squared * BiasCoefficientTmp * (1.0 - BiasCoefficientTmp)) /
((sqrt_one_plus_a_squared - 1.0 + BiasCoefficientTmp) *
sqrt(cube(one_plus_a_squared - 2.0 * BiasCoefficientTmp * cost1)));
double pdf2 = (1.0 - g_squared) / (2.0 * cube(sqrt(1.0 + g_squared - 2.0 * g * cost2)));
LikelihoodRatioIncreaseFactor = pdf2 /
(In_Ptr->ProbabilityAdditionalBias * pdf1 +
(1.0 - In_Ptr->ProbabilityAdditionalBias) * pdf2);
}
Photon_Ptr->LikelihoodRatio *= LikelihoodRatioIncreaseFactor;
if (ThisIsFirstBackwardBiasFlag == 1) {
// In case there was a sure backward bias and that was the very first one
Photon_Ptr->LikelihoodRatioAfterFstBias = Photon_Ptr->LikelihoodRatio;
Photon_Ptr->LikelihoodRatioIncreaseFstBias = LikelihoodRatioIncreaseFactor;
}
}
}
/***********************************************************
* Move the photon s away in the current layer of medium.
****/
void Hop(TetrahedronPhotonStruct *Photon_Ptr) {
double s = Photon_Ptr->s;
Photon_Ptr->x += s * Photon_Ptr->ux;
Photon_Ptr->y += s * Photon_Ptr->uy;
Photon_Ptr->z += s * Photon_Ptr->uz;
Photon_Ptr->OpticalPath += s;
if (Photon_Ptr->MaxDepth < Photon_Ptr->z)
Photon_Ptr->MaxDepth = Photon_Ptr->z;
}
/***********************************************************
* If uz != 0, return the photon step size in glass,
* Otherwise, return 0.
*
* The step size is the distance between the current
* position and the boundary in the photon direction.
*
* Make sure uz !=0 before calling this function.
****/
/***********************************************************
* Pick a step size for a photon packet when it is in
* tissue.
* If the member sleft is zero, make a new step size
* with: -log(rnd)/(mua+mus).
* Otherwise, pick up the leftover in sleft.
*
* Layer is the index to layer.
* In_Ptr is the input parameters.
****/
void StepSizeInTissue(TetrahedronPhotonStruct *Photon_Ptr) {
if (Photon_Ptr->sleft == 0.0) { /* make a new step. */
double rnd;
do rnd = RandomNum();
while (rnd <= 0.0); /* avoid zero. */
Photon_Ptr->s = -log(rnd) * regionspecs[Photon_Ptr->tetrahedron->region].rmuas;
} else { /* take the leftover. */
Photon_Ptr->s = Photon_Ptr->sleft * regionspecs[Photon_Ptr->tetrahedron->region].rmuas;
Photon_Ptr->sleft = 0.0;
}
}
/***********************************************************
* Check if the step will hit the boundary.
* Return 1 if hit boundary.
* Return 0 otherwise.
*
* If the projected step hits the boundary, the members
* s and sleft of Photon_Ptr are updated.
****/
Boolean HitBoundary(TetrahedronPhotonStruct *Photon_Ptr) {
TetrahedronStruct *tetrahedron;
tetrahedron = Photon_Ptr->tetrahedron;
double min_distance = 1e10;
int index_of_tetrahedron_with_min_distance = -1;
double cos_normals_and_photon_direction[4];
double distance_from_face_in_photon_direction;
double perpendicular_distance;
for (int i = 0; i < 4; i++) {
cos_normals_and_photon_direction[i] = (Photon_Ptr->tetrahedron->Faces[i].Nx) * Photon_Ptr->ux +
(Photon_Ptr->tetrahedron->Faces[i].Ny) * Photon_Ptr->uy +
(Photon_Ptr->tetrahedron->Faces[i].Nz) * Photon_Ptr->uz;
}
for (int i = 0; i < 4; i++) {
if (cos_normals_and_photon_direction[i] < 0) {
perpendicular_distance = ((Photon_Ptr->tetrahedron->Faces[i].Nx) * Photon_Ptr->x +
(Photon_Ptr->tetrahedron->Faces[i].Ny) * Photon_Ptr->y +
(Photon_Ptr->tetrahedron->Faces[i].Nz) * Photon_Ptr->z + Photon_Ptr->tetrahedron->Faces[i].d);
distance_from_face_in_photon_direction = -perpendicular_distance / cos_normals_and_photon_direction[i];
if (distance_from_face_in_photon_direction < min_distance) {
min_distance = distance_from_face_in_photon_direction;
index_of_tetrahedron_with_min_distance = i;
Photon_Ptr->MinCos = cos_normals_and_photon_direction[i];
}
}
}
Boolean hit_boundary;
if (Photon_Ptr->s > min_distance) {
/* not horizontal & crossing. */
Photon_Ptr->sleft = (Photon_Ptr->s - min_distance) * regionspecs[tetrahedron->region].muas;
Photon_Ptr->s = min_distance;
hit_boundary = 1;
Photon_Ptr->NextTetrahedron = index_of_tetrahedron_with_min_distance;
} else {
hit_boundary = 0;
Photon_Ptr->NextTetrahedron = -1;
}
return hit_boundary;
}
/***********************************************************
* Drop photon weight inside the tissue (not glass).
*
* The photon is assumed not dead.
*
* The weight drop is dw = w*mua/(mua+mus).
*
* The dropped weight is assigned to the absorption array
* elements.
****/
void Drop(TetrahedronPhotonStruct *Photon_Ptr) {
double dwa; /* absorbed weight.*/
TetrahedronStruct *tetrahedron = Photon_Ptr->tetrahedron;
dwa = Photon_Ptr->w * regionspecs[tetrahedron->region].mua_muas;
Photon_Ptr->w -= dwa;
}
/***********************************************************
* The photon weight is small, and the photon packet tries
* to survive a roulette.
****/
void Roulette(TetrahedronPhotonStruct *Photon_Ptr) {
if (Photon_Ptr->w == 0.0)
Photon_Ptr->dead = 1;
else if (RandomNum() < CHANCE) /* survived the roulette.*/
Photon_Ptr->w /= CHANCE;
else
Photon_Ptr->dead = 1;
}
/***********************************************************
* Compute the Fresnel reflectance.
*
* Make sure that the cosine of the incident angle a1
* is positive, and the case when the angle is greater
* than the critical angle is ruled out.
*
* Avoid trigonometric function operations as much as
* possible, because they are computation-intensive.
****/
double
RFresnel(SimulationStruct *In_Ptr, TetrahedronPhotonStruct *Photon_Ptr, double *ux_reflected, double *uy_reflected,
double *uz_reflected, double *ux_refracted, double *uy_refracted, double *uz_refracted) {
double r;
double cosa, sina, sinb, cosb;
cosa = -(Photon_Ptr->MinCos);
double ni = regionspecs[Photon_Ptr->tetrahedron->region].n;
double nt;
if (Photon_Ptr->tetrahedron->adjTetrahedrons[Photon_Ptr->NextTetrahedron] == NULL)
nt = regionspecs[0].n;
else {
int next_region = Photon_Ptr->tetrahedron->adjTetrahedrons[Photon_Ptr->NextTetrahedron]->region;
nt = regionspecs[next_region].n;
}
sina = sqrt(1.0 - cosa * cosa);
sinb = ni * sina / nt;
cosb = sqrt(1.0 - sinb * sinb);
if (cosa > G_COS_0_D) {
r = (ni - nt)
/ (ni + nt);
r *= r;
cosb = 1;
} else if (cosa < G_COS_90_D) {
r = 1.0;
} else {
sina = sqrt(1 - cosa * cosa);
sinb = ni * sina / nt;
if (sinb >= 1) {
r = 1.0;
} else {
cosb = sqrt(1.0 - sinb * sinb);
double cosacosb = cosa * cosb;
double sinasinb = sina * sinb;
double sinacosb = sina * cosb;
double cosasinb = cosa * sinb;
double cap = cosacosb - sinasinb;
double cam = cosacosb + sinasinb;
double sap = sinacosb + cosasinb;
double sam = sinacosb - cosasinb;
r = 0.5 * sam * sam * (cam * cam + cap * cap) / (sap * sap * cam * cam);
}
}
double sbdivsa = ni / nt;
*ux_refracted = -cosb * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Nx +
sbdivsa * (cosa * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Nx + Photon_Ptr->ux);
*uy_refracted = -cosb * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Ny +
sbdivsa * (cosa * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Ny + Photon_Ptr->uy);
*uz_refracted = -cosb * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Nz +
sbdivsa * (cosa * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Nz + Photon_Ptr->uz);
*ux_reflected = 2 * cosa * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Nx + Photon_Ptr->ux;
*uy_reflected = 2 * cosa * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Ny + Photon_Ptr->uy;
*uz_reflected = 2 * cosa * Photon_Ptr->tetrahedron->Faces[Photon_Ptr->NextTetrahedron].Nz + Photon_Ptr->uz;
return r;
}
/***********************************************************
* Record the photon weight exiting the first layer(uz<0),
* no matter whether the layer is glass or not, to the
* reflection array.
*
* Update the photon weight as well.
***********************************************************/
void RecordValidationR(double Refl, SimulationStruct *In_Ptr, TetrahedronPhotonStruct *Photon_Ptr, OutStruct *Out_Ptr) {
double x = Photon_Ptr->x;
double y = Photon_Ptr->y;
short SpatialFilterFlag = 0;
if (sqrt(sq(x-In_Ptr->probe_x) + sq(y-In_Ptr->probe_y)) <
In_Ptr->MaxCollectingRadius /* The position of photon should be within the radius of the probe */
&& acos(-Photon_Ptr->uz) < In_Ptr->MaxCollectingAngleDeg * PI / 180) {
if ((In_Ptr->TypeBias == 0 || In_Ptr->TypeBias == 3))
SpatialFilterFlag = 1;
if ((Photon_Ptr->FstBackReflectionFlag && In_Ptr->TypeBias == 37 ||
Photon_Ptr->LocationFstBias == Photon_Ptr->MaxDepth
&& In_Ptr->TypeBias != 37 ||
Photon_Ptr->NumBackwardsSpecularReflections > 0))
SpatialFilterFlag = 1;
}
if (SpatialFilterFlag) {
In_Ptr->NumFilteredPhotons++;
double FilterOpticalPath = Photon_Ptr->OpticalPath;
double FilterOpticalDepth = FilterOpticalPath / 2.0;
unsigned int VectorPosition = (unsigned int) (
(FilterOpticalPath / 2.0 - In_Ptr->OpticalDepthShift)
/ (In_Ptr->CoherenceLengthSource / NUM_SUBSTEPS_RESOLUTION));
int ii;
for (ii = VectorPosition - NUM_SUBSTEPS_RESOLUTION / 2;
ii < VectorPosition + NUM_SUBSTEPS_RESOLUTION / 2;
ii++) {
if (ii >= 0 && ii < In_Ptr->NumOpticalDepthLengthSteps) {
short FilterClassI_Flag =
Photon_Ptr->MaxDepth > (FilterOpticalDepth
- In_Ptr->CoherenceLengthSource / 2.0);
double tmpPhotonContribution = Photon_Ptr->w * (1.0 - Refl) * Photon_Ptr->LikelihoodRatio;
if (FilterClassI_Flag) {
if (ii == VectorPosition)
In_Ptr->NumFilteredPhotonsClassI++;
Out_Ptr->ReflectanceClassI_Sum[ii] += tmpPhotonContribution;
if (Out_Ptr->ReflectanceClassI_Max[ii] < tmpPhotonContribution)
Out_Ptr->ReflectanceClassI_Max[ii] = tmpPhotonContribution;
Out_Ptr->ReflectanceClassI_SumSq[ii] += sq(tmpPhotonContribution);
Out_Ptr->NumClassI_PhotonsFilteredInRange[ii]++;
} else {
if (ii == VectorPosition)
In_Ptr->NumFilteredPhotonsClassII++;
if (Out_Ptr->ReflectanceClassII_Max[ii] < tmpPhotonContribution)
Out_Ptr->ReflectanceClassII_Max[ii] = tmpPhotonContribution;
Out_Ptr->ReflectanceClassII_Sum[ii] += tmpPhotonContribution;
Out_Ptr->ReflectanceClassII_SumSq[ii] += sq(tmpPhotonContribution);
Out_Ptr->NumClassII_PhotonsFilteredInRange[ii]++;
}
}
}
}
Photon_Ptr->w *= Refl;
}
/***********************************************************
* Decide whether the photon will be transmitted or be
* reflected on the bottom boundary (uz>0) of the current
* layer.
*
* If the photon is transmitted, move the photon to
* "layer+1". If "layer" is the last layer, record the
* transmitted weight as transmittance. See comments for
* CrossUpOrNot.
*
* Update the photon parmameters.
****/
void CrossOrNot(SimulationStruct *In_Ptr, TetrahedronPhotonStruct *Photon_Ptr, OutStruct *Out_Ptr) {
double uz_reflected = 0, ux_reflected = 0, uy_reflected = 0; /* cosines of transmission alpha. */
double uz_refracted = 0, ux_refracted = 0, uy_refracted = 0;
double r = 0.0; /* reflectance */
r = RFresnel(In_Ptr, Photon_Ptr, &ux_reflected, &uy_reflected, &uz_reflected, &ux_refracted, &uy_refracted,
&uz_refracted);
#if PARTIALREFLECTION
if (Photon_Ptr->tetrahedron->adjTetrahedrons[Photon_Ptr->NextTetrahedron] == NULL && r < 1.0) { /* We use actual photon splitting if the photon is exiting the media
** We store the part the is exiting and the rest will be traced */
Photon_Ptr->ux = ux_refracted;
Photon_Ptr->uy = uy_refracted;
Photon_Ptr->uz = uz_refracted;
if (Photon_Ptr->uz < 0)
RecordValidationR(r, In_Ptr, Photon_Ptr, Out_Ptr);
else {
Photon_Ptr->NumBackwardsSpecularReflections++;
Photon_Ptr->w *= r;
}
Photon_Ptr->ux = ux_reflected;
Photon_Ptr->uy = uy_reflected;
Photon_Ptr->uz = uz_reflected;
}
/* If photon is not exiting the medium we use the statistical splitting */
else if (RandomNum() > r) {/* transmitted */
Photon_Ptr->tetrahedron = Photon_Ptr->tetrahedron->adjTetrahedrons[Photon_Ptr->NextTetrahedron];
Photon_Ptr->ux = ux_refracted;
Photon_Ptr->uy = uy_refracted;
Photon_Ptr->uz = uz_refracted;
Photon_Ptr->NextTetrahedron = -1;
} else /* reflected. */
{
Photon_Ptr->NextTetrahedron = -1;
if (Photon_Ptr->uz > 0)
Photon_Ptr->NumBackwardsSpecularReflections++;
Photon_Ptr->ux = ux_reflected;
Photon_Ptr->uy = uy_reflected;
Photon_Ptr->uz = uz_reflected;
}
#else /* use just statistical splitting */
if(RandomNum() > r) { /* transmitted. */
if(Photon_Ptr->tetrahedron->adjTetrahedrons[Photon_Ptr->NextTetrahedron]==NULL) {
Photon_Ptr->ux = ux_refracted;
Photon_Ptr->uy = uy_refracted;
Photon_Ptr->uz = uz_refracted;
if (Photon_Ptr->uz<0)
RecordValidationR(0.0, In_Ptr, Photon_Ptr, Out_Ptr);
Photon_Ptr->dead = 1;
}
else {
/* Siavash Refraction Direction Cosines */
Photon_Ptr->ux = ux_refracted;
Photon_Ptr->uy = uy_refracted;
Photon_Ptr->uz = uz_refracted;
Photon_Ptr->tetrahedron=Photon_Ptr->tetrahedron->adjTetrahedrons[Photon_Ptr->NextTetrahedron];
Photon_Ptr->NextTetrahedron=-1;
}
}
else {
/* reflected. */
Photon_Ptr->ux = ux_reflected;
Photon_Ptr->uy = uy_reflected;
Photon_Ptr->uz = uz_reflected;
Photon_Ptr->NextTetrahedron=-1;
}
#endif
}
/***********************************************************
****/
/***********************************************************
* Move the photon packet in glass layer.
* Horizontal photons are killed because they will
* never interact with tissue again.
****/
/***********************************************************
* Set a step size, move the photon, drop some weight,
* choose a new photon direction for propagation.
*
* When a step size is long enough for the photon to
* hit an interface, this step is divided into two steps.
* First, move the photon to the boundary free of
* absorption or scattering, then decide whether the
* photon is reflected or transmitted.
* Then move the photon in the current or transmission
* medium with the unfinished stepsize to interaction
* site. If the unfinished stepsize is still too long,
* repeat the above process.
****/
void HopDropSpinInTissue(SimulationStruct *In_Ptr,
TetrahedronPhotonStruct *Photon_Ptr,
TetrahedronPhotonStruct *PhotonCont_Ptr,
OutStruct *Out_Ptr) {
StepSizeInTissue(Photon_Ptr);
if (HitBoundary(Photon_Ptr)) {
Hop(Photon_Ptr); /* move to boundary plane. */
CrossOrNot(In_Ptr, Photon_Ptr, Out_Ptr);
} else {
Hop(Photon_Ptr);
Drop(Photon_Ptr);
switch (In_Ptr->TypeBias) {
case 0: /* No importance sampling */
Spin(regionspecs[Photon_Ptr->tetrahedron->region].g, Photon_Ptr);
break;
case 37: /* BOE2 Biasing by Lima et al. */
SpinBias37(regionspecs[Photon_Ptr->tetrahedron->region].g, Photon_Ptr, PhotonCont_Ptr, In_Ptr);
}
}
}
void HopDropSpin(SimulationStruct *In_Ptr, TetrahedronPhotonStruct *Photon_Ptr, TetrahedronPhotonStruct *PhotonCont_Ptr,
OutStruct *Out_Ptr) {
HopDropSpinInTissue(In_Ptr, Photon_Ptr, PhotonCont_Ptr, Out_Ptr);
if (Photon_Ptr->w < WEIGHT && !Photon_Ptr->dead)
Roulette(Photon_Ptr);
}
void CopyPhotonStruct(TetrahedronPhotonStruct *OrigPhoton_Ptr, TetrahedronPhotonStruct *DestPhoton_Ptr) {
DestPhoton_Ptr->x = OrigPhoton_Ptr->x;
DestPhoton_Ptr->y = OrigPhoton_Ptr->y;
DestPhoton_Ptr->z = OrigPhoton_Ptr->z; /* Cartesian coordinates.[cm] */
DestPhoton_Ptr->ux = OrigPhoton_Ptr->ux;
DestPhoton_Ptr->uy = OrigPhoton_Ptr->uy;
DestPhoton_Ptr->uz = OrigPhoton_Ptr->uz;/* directional cosines of a photon. */
DestPhoton_Ptr->w = OrigPhoton_Ptr->w; /* weight. */
DestPhoton_Ptr->dead = OrigPhoton_Ptr->dead; /* 1 if photon is terminated. */
DestPhoton_Ptr->MinCos = OrigPhoton_Ptr->MinCos;
DestPhoton_Ptr->tetrahedron = OrigPhoton_Ptr->tetrahedron;
DestPhoton_Ptr->NextTetrahedron = OrigPhoton_Ptr->NextTetrahedron;
DestPhoton_Ptr->s = OrigPhoton_Ptr->s; /* current step size. [cm]. */
DestPhoton_Ptr->sleft = OrigPhoton_Ptr->sleft; /* step size left. dimensionless [-]. */
DestPhoton_Ptr->OpticalPath = OrigPhoton_Ptr->OpticalPath;
DestPhoton_Ptr->MaxDepth = OrigPhoton_Ptr->MaxDepth;
DestPhoton_Ptr->LikelihoodRatio = OrigPhoton_Ptr->LikelihoodRatio;
DestPhoton_Ptr->FstBackReflectionFlag = OrigPhoton_Ptr->FstBackReflectionFlag;
DestPhoton_Ptr->LocationFstBias = OrigPhoton_Ptr->LocationFstBias;
DestPhoton_Ptr->NumBackwardsSpecularReflections = OrigPhoton_Ptr->NumBackwardsSpecularReflections;
}
| {
"alphanum_fraction": 0.5645764957,
"avg_line_length": 38.0438116101,
"ext": "c",
"hexsha": "5202e3715777766f9ca9e8432cf40a8ddef1d371",
"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": "d3d9c05218f88d8428d7eea5e81f85340e9e2919",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JunyaoPu/git_OCT",
"max_forks_repo_path": "src/tmcoct_go.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d3d9c05218f88d8428d7eea5e81f85340e9e2919",
"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": "JunyaoPu/git_OCT",
"max_issues_repo_path": "src/tmcoct_go.c",
"max_line_length": 169,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d3d9c05218f88d8428d7eea5e81f85340e9e2919",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JunyaoPu/git_OCT",
"max_stars_repo_path": "src/tmcoct_go.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8729,
"size": 34734
} |
/* spmatrix/test.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 <stdio.h>
#include <unistd.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_spmatrix.h>
int status = 0;
#define BASE_GSL_COMPLEX_LONG
#include "templates_on.h"
#include "test_complex_source.c"
#include "templates_off.h"
#undef BASE_GSL_COMPLEX_LONG
#define BASE_GSL_COMPLEX
#include "templates_on.h"
#include "test_complex_source.c"
#include "templates_off.h"
#undef BASE_GSL_COMPLEX
#define BASE_GSL_COMPLEX_FLOAT
#include "templates_on.h"
#include "test_complex_source.c"
#include "templates_off.h"
#undef BASE_GSL_COMPLEX_FLOAT
#define BASE_LONG_DOUBLE
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_LONG_DOUBLE
#define BASE_DOUBLE
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_FLOAT
#define BASE_ULONG
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_ULONG
#define BASE_LONG
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_LONG
#define BASE_UINT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_UINT
#define BASE_INT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_INT
#define BASE_USHORT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_USHORT
#define BASE_SHORT
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_SHORT
#define BASE_UCHAR
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_UCHAR
#define BASE_CHAR
#include "templates_on.h"
#include "test_source.c"
#include "templates_off.h"
#undef BASE_CHAR
int
main (void)
{
const size_t num = 3;
const size_t M[] = { 53, 40, 30 };
const size_t N[] = { 107, 20, 30 };
const double density[] = { 0.3, 0.2, 0.5 };
gsl_rng * r = gsl_rng_alloc(gsl_rng_default);
size_t i;
for (i = 0; i < num; ++i)
{
test_all (M[i], N[i], density[i], r);
test_float_all (M[i], N[i], density[i], r);
test_long_double_all (M[i], N[i], density[i], r);
test_ulong_all (M[i], N[i], density[i], r);
test_long_all (M[i], N[i], density[i], r);
test_uint_all (M[i], N[i], density[i], r);
test_int_all (M[i], N[i], density[i], r);
test_ushort_all (M[i], N[i], density[i], r);
test_short_all (M[i], N[i], density[i], r);
test_uchar_all (M[i], N[i], density[i], r);
test_char_all (M[i], N[i], density[i], r);
test_complex_all (M[i], N[i], density[i], r);
test_complex_float_all (M[i], N[i], density[i], r);
test_complex_long_double_all (M[i], N[i], density[i], r);
}
gsl_rng_free(r);
exit (gsl_test_summary ());
}
| {
"alphanum_fraction": 0.7079247283,
"avg_line_length": 25.322147651,
"ext": "c",
"hexsha": "97e0a11d8c3f1ea669bddeb81be80316e9b19f52",
"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/spmatrix/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/spmatrix/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/spmatrix/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": 1014,
"size": 3773
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.