Search is not available for this dataset
text string | meta dict |
|---|---|
/* stable/stable_fit.c
*
* Functions employed by different methods of estimation implemented
* in Libstable.
*
* 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 "stable.h"
#include "mcculloch.h"
#include <gsl/gsl_complex.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_fft_real.h>
void stable_fft(double *data, const unsigned int length, double * y)
{
//int i;
memcpy ( (void *)y, (const void *) data, length*sizeof(double));
gsl_fft_real_radix2_transform (y, 1, length);
return;
}
double stable_loglikelihood(StableDist *dist, double *data, const unsigned int length)
{
double *pdf=NULL;
double l=0.0;
int i;
pdf=(double*)malloc(sizeof(double)*length);
stable_pdf(dist,data,length,pdf,NULL);
for(i=0;i<length;i++)
{
if (pdf[i]>0.0) l+=log(pdf[i]);
}
free(pdf);
return l;
}
double stable_loglike_p(stable_like_params *params)
{
double *pdf;
double l=0.0;
int i;
pdf=(double*)malloc(sizeof(double)*(params->length));
stable_pdf(params->dist,params->data,params->length,pdf,NULL);
for(i=0;i<params->length;i++)
{
if (pdf[i]>0.0) {l+=log(pdf[i]);}
}
free(pdf);
return l;
}
double stable_minusloglikelihood(const gsl_vector * theta, void * p)
{
/* Cost function to minimize, with the estimation of sigma and mu given by McCulloch at each iteration*/
double alpha=1, beta=0, sigma=1.0, mu=0.0;
double minusloglike=0;
stable_like_params * params = (stable_like_params *) p;
alpha = gsl_vector_get(theta,0);
beta = gsl_vector_get(theta,1);
/* Update sigma and mu with McCulloch. It needs nu_c nu_z*/
czab(alpha, beta, params->nu_c, params->nu_z, &sigma, &mu);
/* Check that the parameters are valid */
if(stable_setparams(params->dist, alpha, beta, sigma, mu, 0) < 0)
{
return GSL_NAN;
}
else minusloglike = -stable_loglike_p(params);
if (isinf(minusloglike) || isnan(minusloglike)) minusloglike=GSL_NAN;
return minusloglike;
}
int compare (const void * a, const void * b)
{
/* qsort compare function */
return ((*(double *)b < *(double *)a) - (*(double *)a < *(double *)b));
}
inline void get_original(const gsl_vector *s,double *a,double *b,double *c,double *m)
{
*a = M_2_PI*atan(gsl_vector_get(s,0))+1.0;
*b = M_2_PI*atan(gsl_vector_get(s,1));
*c = exp(gsl_vector_get(s,2));
*m = gsl_vector_get(s,3);
}
inline void set_expanded(gsl_vector *s,const double a,const double b,const double c,const double m)
{
gsl_vector_set(s,0,tan(M_PI_2*(a-1.0)));
gsl_vector_set(s,1,tan(M_PI_2*b));
gsl_vector_set(s,2,log(c));
gsl_vector_set(s,3,m);
}
double stable_minusloglikelihood_whole(const gsl_vector * theta, void * p)
{
/* Whole cost function to minimize in a 4D parameter space */
double alpha=1, beta=0, sigma=1.0, mu=0.0;
double minusloglike=0;
stable_like_params * params = (stable_like_params *) p;
get_original(theta,&alpha,&beta,&sigma,&mu);
/* Check that the parameters are valid */
if(stable_setparams(params->dist, alpha, beta, sigma, mu, 0) < 0)
{
perror("setparams error");
return GSL_NAN;
}
else minusloglike = -stable_loglike_p(params);
if (isinf(minusloglike) || isnan(minusloglike)) minusloglike=GSL_NAN;
return minusloglike;
}
void stable_fit_init(StableDist *dist, const double * data, const unsigned int length, double *pnu_c,double *pnu_z)
{
/* McCulloch estimation */
double *sorted=NULL;
double alpha0, beta0, sigma0, mu0;
/* We need to sort the data to get percentiles */
sorted = (double*)malloc(length*sizeof(double));
memcpy ( (void *)sorted, (const void *) data, length*sizeof(double));
qsort ( sorted, length, sizeof(double), compare);
/* Estimate the parameters. */
stab((const double *) sorted,length,0,&alpha0,&beta0,&sigma0,&mu0);
/* Set parameters in the distribution */
if(stable_setparams(dist,alpha0,beta0,sigma0,mu0, 0)<0)
{
perror("INITIAL ESTIMATED PARAMETER ARE NOT VALID");
return;
}
/* Get pnu_c and pnu_z needed for mle2d estimation */
cztab(sorted, length, pnu_c, pnu_z);
free(sorted);
return;
}
int stable_fit_iter(StableDist *dist, const double * data, const unsigned int length,const double nu_c,const double nu_z)
{
const gsl_multimin_fminimizer_type *T;
gsl_multimin_fminimizer *s;
gsl_multimin_function likelihood_func;
gsl_vector *theta, *ss;
unsigned int iter = 0;
int status=0;
double size=0;
double a=1,b=0.0,c=1,m=0.0;
stable_like_params par;
par.dist=dist;
par.data=(double *)data;
par.length=length;
par.nu_c=nu_c;
par.nu_z=nu_z;
/* Inicio: Debe haberse inicializado dist con alpha y beta de McCulloch */
theta=gsl_vector_alloc(2);
gsl_vector_set (theta, 0, dist->alpha);
gsl_vector_set (theta, 1, dist->beta);
#ifdef DEBUG
printf("%lf, %lf\n",gsl_vector_get (theta, 0),gsl_vector_get (theta, 1));
#endif
/* Saltos iniciales */
ss = gsl_vector_alloc (2);
gsl_vector_set_all (ss, 0.01);
/* Funcion a minimizar */
likelihood_func.n = 2; // Dimension 2 (alpha y beta)
likelihood_func.f = &stable_minusloglikelihood;
likelihood_func.params = (void *) (&par); // Parametros de la funcion
/* Creacion del minimizer */
T = gsl_multimin_fminimizer_nmsimplex2rand;
s = gsl_multimin_fminimizer_alloc (T, 2); /* Dimension 2*/
/* Poner funcion, estimacion inicial, saltos iniciales */
gsl_multimin_fminimizer_set (s, &likelihood_func, theta, ss);
#ifdef DEBUG
printf("5\n");
#endif
/* Iterar */
do
{
iter++;
status = gsl_multimin_fminimizer_iterate(s);
// if (status!=GSL_SUCCESS) {
// printf("Minimizer warning: %s\n",gsl_strerror(status));
// fflush(stdout);
// }
size = gsl_multimin_fminimizer_size (s);
status = gsl_multimin_test_size (size, 0.02);
/*
if (status == GSL_SUCCESS)
{
printf (" converged to minimum at\n");
}
printf ("%5d %1.5f %1.5f %1.5f %1.5f f() = %1.8e size = %.5f\n",
(int)iter,
gsl_vector_get (s->x, 0),
gsl_vector_get (s->x, 1),
p->dist->sigma,
p->dist->mu_1,
s->fval, size);
//}
*/
} while (status == GSL_CONTINUE && iter < 200);
// if (status!=GSL_SUCCESS)
// {
// printf("Minimizer warning: %s\n",gsl_strerror(status));
// fflush(stdout);
// }
/* Se recupera la estimacion alpha y beta */
gsl_vector_free(theta);
/*
theta = gsl_multimin_fminimizer_x (s);
a = gsl_vector_get (theta, 0);
b = gsl_vector_get (theta, 1);
*/
a = gsl_vector_get (s->x, 0);
b = gsl_vector_get (s->x, 1);
/* Y se estima sigma y mu para esos alpha y beta */
czab(a, b, nu_c, nu_z, &c, &m);
//printf("%5d %10.3e %10.3e %10.3e %10.3e\n",(int)iter,a,b,c,m);
// Se almacena el punto estimado en la distribucion, comprobando que es valido
if (stable_setparams(dist,a,b,c,m,0)<0)
{
perror("FINAL ESTIMATED PARAMETER ARE NOT VALID\n");
}
gsl_vector_free(ss);
gsl_multimin_fminimizer_free (s);
return status;
}
int stable_fit(StableDist *dist, const double *data, const unsigned int length)
{
double nu_c=0.0,nu_z=0.0;
int status = 0;
stable_fit_init(dist,data,length,&nu_c,&nu_z);
status=stable_fit_iter(dist,data,length,nu_c,nu_z);
return status;
}
int stable_fit_iter_whole(StableDist *dist, const double * data, const unsigned int length)
{
const gsl_multimin_fminimizer_type *T;
gsl_multimin_fminimizer *s;
gsl_multimin_function likelihood_func;
gsl_vector *theta, *ss;
unsigned int iter = 0;
int status=0;
double size=0;
double a=1,b=0.0,c=1,m=0.0;
stable_like_params par;
par.dist=dist;
par.data=(double *)data;
par.length=length;
par.nu_c=0;
par.nu_z=0;
/* Inital params (with McCulloch) */
theta=gsl_vector_alloc(4);
set_expanded(theta,dist->alpha,dist->beta,dist->sigma,dist->mu_1);
#ifdef DEBUG
printf("%lf, %lf, %lf, %lf\n",gsl_vector_get (theta, 0),gsl_vector_get (theta, 1),gsl_vector_get (theta, 2),gsl_vector_get (theta, 3));
#endif
/* Initial steps */
ss = gsl_vector_alloc (4);
gsl_vector_set_all (ss, 0.01);
/* Cost function to minimize */
likelihood_func.n = 4; // 4 Dimensions (alpha, beta, sigma, mu_0)
likelihood_func.f = &stable_minusloglikelihood_whole;
likelihood_func.params = (void *) (&par); // Cost function arguments
/* Minimizer creation */
T = gsl_multimin_fminimizer_nmsimplex2rand;
s = gsl_multimin_fminimizer_alloc (T, 4); /* 4 dimensions */
/* Set cost function, initial guess and initial steps */
gsl_multimin_fminimizer_set (s, &likelihood_func, theta, ss);
#ifdef DEBUG
printf("5\n");
#endif
/* Start iterations */
do
{
iter++;
status = gsl_multimin_fminimizer_iterate(s);
if (status!=GSL_SUCCESS) {
perror("Minimizer warning:\n");
}
size = gsl_multimin_fminimizer_size (s);
status = gsl_multimin_test_size (size, 0.002);
/*
printf(" %03d\t size = %f a_ = %f b_ = %f c_ = %f m_ = %f f_ = %f \n",iter,size,gsl_vector_get (s->x, 0),gsl_vector_get (s->x, 1),
gsl_vector_get (s->x, 2),gsl_vector_get (s->x, 3), gsl_multimin_fminimizer_minimum(s));
*/
} while (status == GSL_CONTINUE && iter < 200);
if (status!=GSL_SUCCESS)
{
perror("Minimizer warning");
}
/* Get last estimation */
gsl_vector_free(theta);
theta = gsl_multimin_fminimizer_x (s);
get_original(theta,&a,&b,&c,&m);
/* Set estimated parameters to the distribution and check if their have valid values*/
if (stable_setparams(dist,a,b,c,m,0)<0)
{
perror("FINAL ESTIMATED PARAMETER ARE NOT VALID\n");
}
gsl_vector_free(ss);
gsl_multimin_fminimizer_free (s);
return status;
}
int stable_fit_whole(StableDist *dist, const double *data, const unsigned int length)
{
// double nu_c=0.0,nu_z=0.0;
int status=0;
// stable_fit_init(dist,data,length,&nu_c,&nu_z);
// printf("McCulloch %d sampless: %f %f %f %f\n",length,dist->alpha,dist->beta,dist->sigma,dist->mu_1);
status = stable_fit_iter_whole(dist,data,length);
return status;
}
double * load_rand_data(char * filename, int N)
{
FILE * f_data;
double * data;
int i;
if ((f_data = fopen(filename,"rt")) == NULL)
{
perror("Error when opening file with random data");
}
data=(double*)malloc(N*sizeof(double));
for(i=0;i<N;i++)
{
if (EOF==fscanf(f_data,"%le\n",data+i))
{
perror("Error when reading data");
}
}
return data;
}
int stable_fit_mle(StableDist *dist, const double *data, const unsigned int length) {
return stable_fit_whole(dist,data,length);
}
int stable_fit_mle2d(StableDist *dist, const double *data, const unsigned int length) {
return stable_fit(dist,data,length);
}
| {
"alphanum_fraction": 0.6610974472,
"avg_line_length": 26.0862831858,
"ext": "c",
"hexsha": "a7a42da1d11801c5fc494894c53eb390b5395255",
"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_fit.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_fit.c",
"max_line_length": 146,
"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_fit.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3517,
"size": 11791
} |
#ifndef _FUNCTIONS_
#define _FUNCTIONS_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <limits.h>
#include <cblas.h>
#include <lapacke.h>
#include "structs.c"
#define PATH_LENGTH 32
#define LINE_LENGTH 26000
#define THRESHOLD 0.05
// Declare functions of functions.c file
int is_centroid(int *, int, int);
double rand_gaussian();
int centroids_transposition(conformation **, int *, int *, int, double **);
double **create_distances_array(conformation **, int, int, int);
#endif
| {
"alphanum_fraction": 0.6863084922,
"avg_line_length": 18.03125,
"ext": "h",
"hexsha": "72c558cf253a3c71b99b4a6cca5cbe1826864870",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b5f7baf7d94eabdddd61f20232182bcce2f57a36",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "skanel94/Software-Development-for-Algorithmic-Problems",
"max_forks_repo_path": "Part 3/Proteins/src/functions.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b5f7baf7d94eabdddd61f20232182bcce2f57a36",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "skanel94/Software-Development-for-Algorithmic-Problems",
"max_issues_repo_path": "Part 3/Proteins/src/functions.h",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b5f7baf7d94eabdddd61f20232182bcce2f57a36",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "skanel94/Software-Development-for-Algorithmic-Problems",
"max_stars_repo_path": "Part 3/Proteins/src/functions.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 138,
"size": 577
} |
/* vector/gsl_vector_long_double.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_VECTOR_LONG_DOUBLE_H__
#define __GSL_VECTOR_LONG_DOUBLE_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_block_long_double.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
long double *data;
gsl_block_long_double *block;
int owner;
}
gsl_vector_long_double;
typedef struct
{
gsl_vector_long_double vector;
} _gsl_vector_long_double_view;
typedef _gsl_vector_long_double_view gsl_vector_long_double_view;
typedef struct
{
gsl_vector_long_double vector;
} _gsl_vector_long_double_const_view;
typedef const _gsl_vector_long_double_const_view gsl_vector_long_double_const_view;
/* Allocation */
GSL_EXPORT gsl_vector_long_double *gsl_vector_long_double_alloc (const size_t n);
GSL_EXPORT gsl_vector_long_double *gsl_vector_long_double_calloc (const size_t n);
GSL_EXPORT gsl_vector_long_double *gsl_vector_long_double_alloc_from_block (gsl_block_long_double * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_EXPORT gsl_vector_long_double *gsl_vector_long_double_alloc_from_vector (gsl_vector_long_double * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_EXPORT void gsl_vector_long_double_free (gsl_vector_long_double * v);
/* Views */
GSL_EXPORT
_gsl_vector_long_double_view
gsl_vector_long_double_view_array (long double *v, size_t n);
GSL_EXPORT
_gsl_vector_long_double_view
gsl_vector_long_double_view_array_with_stride (long double *base,
size_t stride,
size_t n);
GSL_EXPORT
_gsl_vector_long_double_const_view
gsl_vector_long_double_const_view_array (const long double *v, size_t n);
GSL_EXPORT
_gsl_vector_long_double_const_view
gsl_vector_long_double_const_view_array_with_stride (const long double *base,
size_t stride,
size_t n);
GSL_EXPORT
_gsl_vector_long_double_view
gsl_vector_long_double_subvector (gsl_vector_long_double *v,
size_t i,
size_t n);
GSL_EXPORT
_gsl_vector_long_double_view
gsl_vector_long_double_subvector_with_stride (gsl_vector_long_double *v,
size_t i,
size_t stride,
size_t n);
GSL_EXPORT
_gsl_vector_long_double_const_view
gsl_vector_long_double_const_subvector (const gsl_vector_long_double *v,
size_t i,
size_t n);
GSL_EXPORT
_gsl_vector_long_double_const_view
gsl_vector_long_double_const_subvector_with_stride (const gsl_vector_long_double *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
GSL_EXPORT long double gsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i);
GSL_EXPORT void gsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x);
GSL_EXPORT long double *gsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i);
GSL_EXPORT const long double *gsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i);
GSL_EXPORT void gsl_vector_long_double_set_zero (gsl_vector_long_double * v);
GSL_EXPORT void gsl_vector_long_double_set_all (gsl_vector_long_double * v, long double x);
GSL_EXPORT int gsl_vector_long_double_set_basis (gsl_vector_long_double * v, size_t i);
GSL_EXPORT int gsl_vector_long_double_fread (FILE * stream, gsl_vector_long_double * v);
GSL_EXPORT int gsl_vector_long_double_fwrite (FILE * stream, const gsl_vector_long_double * v);
GSL_EXPORT int gsl_vector_long_double_fscanf (FILE * stream, gsl_vector_long_double * v);
GSL_EXPORT int gsl_vector_long_double_fprintf (FILE * stream, const gsl_vector_long_double * v,
const char *format);
GSL_EXPORT int gsl_vector_long_double_memcpy (gsl_vector_long_double * dest, const gsl_vector_long_double * src);
GSL_EXPORT int gsl_vector_long_double_reverse (gsl_vector_long_double * v);
GSL_EXPORT int gsl_vector_long_double_swap (gsl_vector_long_double * v, gsl_vector_long_double * w);
GSL_EXPORT int gsl_vector_long_double_swap_elements (gsl_vector_long_double * v, const size_t i, const size_t j);
GSL_EXPORT long double gsl_vector_long_double_max (const gsl_vector_long_double * v);
GSL_EXPORT long double gsl_vector_long_double_min (const gsl_vector_long_double * v);
GSL_EXPORT void gsl_vector_long_double_minmax (const gsl_vector_long_double * v, long double * min_out, long double * max_out);
GSL_EXPORT size_t gsl_vector_long_double_max_index (const gsl_vector_long_double * v);
GSL_EXPORT size_t gsl_vector_long_double_min_index (const gsl_vector_long_double * v);
GSL_EXPORT void gsl_vector_long_double_minmax_index (const gsl_vector_long_double * v, size_t * imin, size_t * imax);
GSL_EXPORT int gsl_vector_long_double_add (gsl_vector_long_double * a, const gsl_vector_long_double * b);
GSL_EXPORT int gsl_vector_long_double_sub (gsl_vector_long_double * a, const gsl_vector_long_double * b);
GSL_EXPORT int gsl_vector_long_double_mul (gsl_vector_long_double * a, const gsl_vector_long_double * b);
GSL_EXPORT int gsl_vector_long_double_div (gsl_vector_long_double * a, const gsl_vector_long_double * b);
GSL_EXPORT int gsl_vector_long_double_scale (gsl_vector_long_double * a, const double x);
GSL_EXPORT int gsl_vector_long_double_add_constant (gsl_vector_long_double * a, const double x);
GSL_EXPORT int gsl_vector_long_double_isnull (const gsl_vector_long_double * v);
#ifdef HAVE_INLINE
extern inline
long double
gsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return v->data[i * v->stride];
}
extern inline
void
gsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}
extern inline
long double *
gsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (long double *) (v->data + i * v->stride);
}
extern inline
const long double *
gsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (const long double *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_LONG_DOUBLE_H__ */
| {
"alphanum_fraction": 0.7037649003,
"avg_line_length": 36.0553191489,
"ext": "h",
"hexsha": "4c506578f482bdcd2a9d07ce4a5a65aa18e21483",
"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_vector_long_double.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_vector_long_double.h",
"max_line_length": 127,
"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_vector_long_double.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1904,
"size": 8473
} |
#ifndef _BLAS_UTIL_H_
#define _BLAS_UTIL_H_
#ifdef __BLAS_LEGACY__
#include <math.h>
#include "cblas.h"
//#include <lapacke.h> //! hasn't used
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#elif defined __APPLE__
#include <Accelerate/Accelerate.h>
#elif defined __USE_MKL__
#include <mkl.h>
#endif
#endif /* _BLAS_UTIL_H_ */
| {
"alphanum_fraction": 0.6713091922,
"avg_line_length": 17.0952380952,
"ext": "h",
"hexsha": "7f235cbddf8b157854e851c25073f08cd1a8869a",
"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": "b5a76af2be8a35ac2194865d58fe6424394c042d",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "bobye/d2suite",
"max_forks_repo_path": "d2suite/src/common/blas_util.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b5a76af2be8a35ac2194865d58fe6424394c042d",
"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": "bobye/d2suite",
"max_issues_repo_path": "d2suite/src/common/blas_util.h",
"max_line_length": 38,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "b5a76af2be8a35ac2194865d58fe6424394c042d",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "bobye/d2suite",
"max_stars_repo_path": "d2suite/src/common/blas_util.h",
"max_stars_repo_stars_event_max_datetime": "2019-08-21T04:47:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-21T04:47:05.000Z",
"num_tokens": 116,
"size": 359
} |
// 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_BLAS3_MATRIX_PRODUCT_H
#define SCILIB_LINALG_BLAS3_MATRIX_PRODUCT_H
#ifdef USE_MKL
#include <mkl.h>
#else
#include <cblas.h>
#endif
#include <scilib/mdarray.h>
#include <scilib/linalg_impl/lapack_types.h>
#include <experimental/mdspan>
#include <complex>
#include <type_traits>
namespace Sci {
namespace Linalg {
namespace stdex = std::experimental;
template <class T_a,
stdex::extents<>::size_type nrows_a,
stdex::extents<>::size_type ncols_a,
class Layout_a,
class Accessor_a,
class T_b,
stdex::extents<>::size_type nrows_b,
stdex::extents<>::size_type ncols_b,
class Layout_b,
class Accessor_b,
class T_c,
stdex::extents<>::size_type nrows_c,
stdex::extents<>::size_type ncols_c,
class Layout_c,
class Accessor_c>
requires(!std::is_const_v<T_c>)
inline void matrix_product(
stdex::mdspan<T_a, stdex::extents<nrows_a, ncols_a>, Layout_a, Accessor_a>
a,
stdex::mdspan<T_b, stdex::extents<nrows_b, ncols_b>, Layout_b, Accessor_b>
b,
stdex::mdspan<T_c, stdex::extents<nrows_c, ncols_c>, Layout_c, Accessor_c>
c)
{
static_assert(a.static_extent(1) == b.static_extent(0));
using size_type = stdex::extents<>::size_type;
const size_type n = a.extent(0);
const size_type m = a.extent(1);
const size_type p = b.extent(1);
for (size_type i = 0; i < n; ++i) {
for (size_type j = 0; j < p; ++j) {
c(i, j) = T_c{0};
for (size_type k = 0; k < m; ++k) {
c(i, j) += a(i, k) * b(k, j);
}
}
}
}
template <class Layout>
inline void matrix_product(Sci::Matrix_view<double, Layout> a,
Sci::Matrix_view<double, Layout> b,
Sci::Matrix_view<double, Layout> c)
{
constexpr double alpha = 1.0;
constexpr double beta = 0.0;
const BLAS_INT m = static_cast<BLAS_INT>(a.extent(0));
const BLAS_INT n = static_cast<BLAS_INT>(b.extent(1));
const BLAS_INT k = static_cast<BLAS_INT>(a.extent(1));
auto matrix_layout = CblasRowMajor;
BLAS_INT lda = k;
BLAS_INT ldb = n;
BLAS_INT ldc = n;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = CblasColMajor;
lda = m;
ldb = k;
ldc = m;
}
cblas_dgemm(matrix_layout, CblasNoTrans, CblasNoTrans, m, n, k, alpha,
a.data(), lda, b.data(), ldb, beta, c.data(), ldc);
}
template <class Layout>
inline void matrix_product(Sci::Matrix_view<const double, Layout> a,
Sci::Matrix_view<const double, Layout> b,
Sci::Matrix_view<double, Layout> c)
{
constexpr double alpha = 1.0;
constexpr double beta = 0.0;
const BLAS_INT m = static_cast<BLAS_INT>(a.extent(0));
const BLAS_INT n = static_cast<BLAS_INT>(b.extent(1));
const BLAS_INT k = static_cast<BLAS_INT>(a.extent(1));
auto matrix_layout = CblasRowMajor;
BLAS_INT lda = k;
BLAS_INT ldb = n;
BLAS_INT ldc = n;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = CblasColMajor;
lda = m;
ldb = k;
ldc = m;
}
cblas_dgemm(matrix_layout, CblasNoTrans, CblasNoTrans, m, n, k, alpha,
a.data(), lda, b.data(), ldb, beta, c.data(), ldc);
}
#ifdef USE_MKL
template <class Layout>
inline void matrix_product(Sci::Matrix_view<std::complex<double>, Layout> a,
Sci::Matrix_view<std::complex<double>, Layout> b,
Sci::Matrix_view<std::complex<double>, Layout> c)
{
constexpr std::complex<double> alpha = {1.0, 0.0};
constexpr std::complex<double> beta = {0.0, 0.0};
const BLAS_INT m = static_cast<BLAS_INT>(a.extent(0));
const BLAS_INT n = static_cast<BLAS_INT>(b.extent(1));
const BLAS_INT k = static_cast<BLAS_INT>(a.extent(1));
auto matrix_layout = CblasRowMajor;
BLAS_INT lda = k;
BLAS_INT ldb = n;
BLAS_INT ldc = n;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = CblasColMajor;
lda = m;
ldb = k;
ldc = m;
}
cblas_zgemm(matrix_layout, CblasNoTrans, CblasNoTrans, m, n, k, &alpha,
a.data(), lda, b.data(), ldb, &beta, c.data(), ldc);
}
template <class Layout>
inline void
matrix_product(Sci::Matrix_view<const std::complex<double>, Layout> a,
Sci::Matrix_view<const std::complex<double>, Layout> b,
Sci::Matrix_view<std::complex<double>, Layout> c)
{
constexpr std::complex<double> alpha = {1.0, 0.0};
constexpr std::complex<double> beta = {0.0, 0.0};
const BLAS_INT m = static_cast<BLAS_INT>(a.extent(0));
const BLAS_INT n = static_cast<BLAS_INT>(b.extent(1));
const BLAS_INT k = static_cast<BLAS_INT>(a.extent(1));
auto matrix_layout = CblasRowMajor;
BLAS_INT lda = k;
BLAS_INT ldb = n;
BLAS_INT ldc = n;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = CblasColMajor;
lda = m;
ldb = k;
ldc = m;
}
cblas_zgemm(matrix_layout, CblasNoTrans, CblasNoTrans, m, n, k, &alpha,
a.data(), lda, b.data(), ldb, &beta, c.data(), ldc);
}
#endif
template <class T, class Layout, class Allocator>
inline Sci::Matrix<T, Layout, Allocator>
matrix_product(const Sci::Matrix<T, Layout, Allocator>& a,
const Sci::Matrix<T, Layout, Allocator>& b)
{
using size_type = stdex::extents<>::size_type;
const size_type n = a.extent(0);
const size_type p = b.extent(1);
Sci::Matrix<T, Layout, Allocator> res(n, p);
matrix_product(a.view(), b.view(), res.view());
return res;
}
template <class T, class Layout, class Allocator>
inline void matrix_product(const Sci::Matrix<T, Layout, Allocator>& a,
const Sci::Matrix<T, Layout, Allocator>& b,
Sci::Matrix<T, Layout, Allocator>& c)
{
matrix_product(a.view(), b.view(), c.view());
}
} // namespace Linalg
} // namespace Sci
#endif // SCILIB_LINALG_BLAS3_MATRIX_PRODUCT_H
| {
"alphanum_fraction": 0.6149318463,
"avg_line_length": 31.1884057971,
"ext": "h",
"hexsha": "8b86d3e2e1633718970c9e1b112787634c4a7e3f",
"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/blas3_matrix_product.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/blas3_matrix_product.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/blas3_matrix_product.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1803,
"size": 6456
} |
/*
# This file is part of the Astrometry.net suite.
# Licensed under a 3-clause BSD style license - see LICENSE
*/
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <gsl/gsl_matrix_double.h>
#include <gsl/gsl_vector_double.h>
#include "os-features.h"
#include "sip-utils.h"
#include "gslutils.h"
#include "starutil.h"
#include "mathutil.h"
#include "errors.h"
#include "log.h"
double wcs_pixel_center_for_size(double size) {
return 0.5 + 0.5 * size;
}
void tan_rotate(const tan_t* tanin, tan_t* tanout, double angle) {
double s,c;
double newcd[4];
memmove(tanout, tanin, sizeof(tan_t));
s = sin(deg2rad(angle));
c = cos(deg2rad(angle));
newcd[0] = c*tanin->cd[0][0] + s*tanin->cd[1][0];
newcd[1] = c*tanin->cd[0][1] + s*tanin->cd[1][1];
newcd[2] = -s*tanin->cd[0][0] + c*tanin->cd[1][0];
newcd[3] = -s*tanin->cd[0][1] + c*tanin->cd[1][1];
tanout->cd[0][0] = newcd[0];
tanout->cd[0][1] = newcd[1];
tanout->cd[1][0] = newcd[2];
tanout->cd[1][1] = newcd[3];
}
int sip_ensure_inverse_polynomials(sip_t* sip) {
if ((sip->a_order == 0 && sip->b_order == 0) ||
(sip->ap_order > 0 && sip->bp_order > 0)) {
return 0;
}
sip->ap_order = sip->bp_order = MAX(sip->a_order, sip->b_order) + 1;
return sip_compute_inverse_polynomials(sip, 0, 0, 0, 0, 0, 0);
}
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)) {
ERROR("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 (log_get_level() > LOG_VERB) {
// 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;
}
anbool tan_pixel_is_inside_image(const tan_t* wcs, double x, double y) {
return (x >= 1 && x <= wcs->imagew && y >= 1 && y <= wcs->imageh);
}
anbool sip_pixel_is_inside_image(const sip_t* wcs, double x, double y) {
return tan_pixel_is_inside_image(&(wcs->wcstan), x, y);
}
anbool sip_is_inside_image(const sip_t* wcs, double ra, double dec) {
double x,y;
if (!sip_radec2pixelxy(wcs, ra, dec, &x, &y))
return FALSE;
return sip_pixel_is_inside_image(wcs, x, y);
}
anbool tan_is_inside_image(const tan_t* wcs, double ra, double dec) {
double x,y;
if (!tan_radec2pixelxy(wcs, ra, dec, &x, &y))
return FALSE;
return tan_pixel_is_inside_image(wcs, 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;
anbool 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 = sip->wcstan.imagew;
H = sip->wcstan.imageh;
} else {
W = tan->imagew;
H = 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;
}
void sip_get_radec_center(const sip_t* wcs,
double* p_ra, double* p_dec) {
double px = wcs_pixel_center_for_size(wcs->wcstan.imagew);
double py = wcs_pixel_center_for_size(wcs->wcstan.imageh);
sip_pixelxy2radec(wcs, px, py, p_ra, p_dec);
}
void tan_get_radec_center(const tan_t* wcs,
double* p_ra, double* p_dec) {
double px = wcs_pixel_center_for_size(wcs->imagew);
double py = wcs_pixel_center_for_size(wcs->imageh);
tan_pixelxy2radec(wcs, px, py, p_ra, p_dec);
}
double sip_get_radius_deg(const sip_t* wcs) {
return arcsec2deg(sip_pixel_scale(wcs) * hypot(wcs->wcstan.imagew, wcs->wcstan.imageh)/2.0);
}
double tan_get_radius_deg(const tan_t* wcs) {
return arcsec2deg(tan_pixel_scale(wcs) * hypot(wcs->imagew, wcs->imageh)/2.0);
}
void sip_get_radec_center_hms(const sip_t* wcs,
int* rah, int* ram, double* ras,
int* decsign, int* decd, int* decm, double* decs) {
double ra, dec;
sip_get_radec_center(wcs, &ra, &dec);
ra2hms(ra, rah, ram, ras);
dec2dms(dec, decsign, decd, decm, decs);
}
void sip_get_radec_center_hms_string(const sip_t* wcs,
char* rastr, char* decstr) {
double ra, dec;
sip_get_radec_center(wcs, &ra, &dec);
ra2hmsstring(ra, rastr);
dec2dmsstring(dec, decstr);
}
void sip_get_field_size(const sip_t* wcs,
double* pw, double* ph,
char** units) {
double minx = 0.5;
double maxx = (wcs->wcstan.imagew + 0.5);
double midx = (minx + maxx) / 2.0;
double miny = 0.5;
double maxy = (wcs->wcstan.imageh + 0.5);
double midy = (miny + maxy) / 2.0;
double ra1, dec1, ra2, dec2, ra3, dec3;
double w, h;
// measure width through the middle
sip_pixelxy2radec(wcs, minx, midy, &ra1, &dec1);
sip_pixelxy2radec(wcs, midx, midy, &ra2, &dec2);
sip_pixelxy2radec(wcs, maxx, midy, &ra3, &dec3);
w = arcsec_between_radecdeg(ra1, dec1, ra2, dec2) +
arcsec_between_radecdeg(ra2, dec2, ra3, dec3);
// measure height through the middle
sip_pixelxy2radec(wcs, midx, miny, &ra1, &dec1);
sip_pixelxy2radec(wcs, midx, midy, &ra2, &dec2);
sip_pixelxy2radec(wcs, midx, maxy, &ra3, &dec3);
h = arcsec_between_radecdeg(ra1, dec1, ra2, dec2) +
arcsec_between_radecdeg(ra2, dec2, ra3, dec3);
if (MIN(w, h) < 60.0) {
*units = "arcseconds";
*pw = w;
*ph = h;
} else if (MIN(w, h) < 3600.0) {
*units = "arcminutes";
*pw = w / 60.0;
*ph = h / 60.0;
} else {
*units = "degrees";
*pw = w / 3600.0;
*ph = h / 3600.0;
}
}
void sip_walk_image_boundary(const sip_t* wcs, double stepsize,
void (*callback)(const sip_t* wcs, double x, double y, double ra, double dec, void* token),
void* token) {
int i, side;
// Walk the perimeter of the image in steps of stepsize pixels
double W = wcs->wcstan.imagew;
double H = wcs->wcstan.imageh;
{
double Xmin = 0.5;
double Xmax = W + 0.5;
double Ymin = 0.5;
double Ymax = H + 0.5;
double offsetx[] = { Xmin, Xmax, Xmax, Xmin };
double offsety[] = { Ymin, Ymin, Ymax, Ymax };
double stepx[] = { +stepsize, 0, -stepsize, 0 };
double stepy[] = { 0, +stepsize, 0, -stepsize };
int Nsteps[] = { ceil(W/stepsize), ceil(H/stepsize), ceil(W/stepsize), ceil(H/stepsize) };
for (side=0; side<4; side++) {
for (i=0; i<Nsteps[side]; i++) {
double ra, dec;
double x, y;
x = MIN(Xmax, MAX(Xmin, offsetx[side] + i * stepx[side]));
y = MIN(Ymax, MAX(Ymin, offsety[side] + i * stepy[side]));
sip_pixelxy2radec(wcs, x, y, &ra, &dec);
callback(wcs, x, y, ra, dec, token);
}
}
}
}
struct radecbounds {
double rac, decc;
double ramin, ramax, decmin, decmax;
};
static void radec_bounds_callback(const sip_t* wcs, double x, double y, double ra, double dec, void* token) {
struct radecbounds* b = token;
b->decmin = MIN(b->decmin, dec);
b->decmax = MAX(b->decmax, dec);
if (ra - b->rac > 180)
// wrap-around: racenter < 180, ra has gone < 0 but been wrapped around to > 180
ra -= 360;
if (b->rac - ra > 180)
// wrap-around: racenter > 180, ra has gone > 360 but wrapped around to > 0.
ra += 360;
b->ramin = MIN(b->ramin, ra);
b->ramax = MAX(b->ramax, ra);
}
void sip_get_radec_bounds(const sip_t* wcs, int stepsize,
double* pramin, double* pramax,
double* pdecmin, double* pdecmax) {
struct radecbounds b;
sip_get_radec_center(wcs, &(b.rac), &(b.decc));
b.ramin = b.ramax = b.rac;
b.decmin = b.decmax = b.decc;
sip_walk_image_boundary(wcs, stepsize, radec_bounds_callback, &b);
// Check for poles...
// north pole
if (sip_is_inside_image(wcs, 0, 90)) {
b.ramin = 0;
b.ramax = 360;
b.decmax = 90;
}
if (sip_is_inside_image(wcs, 0, -90)) {
b.ramin = 0;
b.ramax = 360;
b.decmin = -90;
}
if (pramin) *pramin = b.ramin;
if (pramax) *pramax = b.ramax;
if (pdecmin) *pdecmin = b.decmin;
if (pdecmax) *pdecmax = b.decmax;
}
void sip_shift(const sip_t* sipin, sip_t* sipout,
double xlo, double xhi, double ylo, double yhi) {
memmove(sipout, sipin, sizeof(sip_t));
tan_transform(&(sipin->wcstan), &(sipout->wcstan),
xlo, xhi, ylo, yhi, 1.0);
}
void tan_transform(const tan_t* tanin, tan_t* tanout,
double xlo, double xhi, double ylo, double yhi,
double scale) {
memmove(tanout, tanin, sizeof(tan_t));
tanout->imagew = (xhi - xlo + 1) * scale;
tanout->imageh = (yhi - ylo + 1) * scale;
tanout->crpix[0] = (tanout->crpix[0] - (xlo - 1)) * scale;
tanout->crpix[1] = (tanout->crpix[1] - (ylo - 1)) * scale;
tanout->cd[0][0] /= scale;
tanout->cd[0][1] /= scale;
tanout->cd[1][0] /= scale;
tanout->cd[1][1] /= scale;
}
void tan_scale(const tan_t* tanin, tan_t* tanout,
double scale) {
memmove(tanout, tanin, sizeof(tan_t));
tanout->imagew *= scale;
tanout->imageh *= scale;
tanout->crpix[0] = 0.5 + scale * (tanin->crpix[0] - 0.5);
tanout->crpix[1] = 0.5 + scale * (tanin->crpix[1] - 0.5);
tanout->cd[0][0] /= scale;
tanout->cd[0][1] /= scale;
tanout->cd[1][0] /= scale;
tanout->cd[1][1] /= scale;
}
void sip_scale(const sip_t* wcsin, sip_t* wcsout,
double scale) {
int i, j;
memmove(wcsout, wcsin, sizeof(sip_t));
tan_scale(&(wcsin->wcstan), &(wcsout->wcstan), scale);
for (i=0; i<=wcsin->a_order; i++) {
for (j=0; j<=wcsin->a_order; j++) {
if (i + j > wcsin->a_order)
continue;
wcsout->a[i][j] *= pow(scale, 1 - (i+j));
}
}
for (i=0; i<=wcsin->b_order; i++) {
for (j=0; j<=wcsin->b_order; j++) {
if (i + j > wcsin->b_order)
continue;
wcsout->b[i][j] *= pow(scale, 1 - (i+j));
}
}
for (i=0; i<=wcsin->ap_order; i++) {
for (j=0; j<=wcsin->ap_order; j++) {
if (i + j > wcsin->ap_order)
continue;
wcsout->ap[i][j] *= pow(scale, 1 - (i+j));
}
}
for (i=0; i<=wcsin->bp_order; i++) {
for (j=0; j<=wcsin->bp_order; j++) {
if (i + j > wcsin->bp_order)
continue;
wcsout->bp[i][j] *= pow(scale, 1 - (i+j));
}
}
}
| {
"alphanum_fraction": 0.5118323565,
"avg_line_length": 31.7855887522,
"ext": "c",
"hexsha": "88ba8e25b7f6b3602e3436b820a8f73251cf636b",
"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": "util/sip-utils.c",
"max_issues_count": 208,
"max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z",
"max_issues_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_issues_repo_name": "juandesant/astrometry.net",
"max_issues_repo_path": "util/sip-utils.c",
"max_line_length": 120,
"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": "util/sip-utils.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z",
"num_tokens": 5795,
"size": 18086
} |
#include "tools.h"
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
gsl_rng **_random = NULL;
double tool_get_time()
{
struct timeval t;
gettimeofday(&t, NULL);
return (double)t.tv_sec + (double)t.tv_usec * 1e-6;
}
double tool_cut(double x)
{
if (x <= 0.0)
return 0.0;
if (x >= 1.0)
return 1.0;
return x;
}
void print_array(double c[], int l)
{
for (int i = 0; i < l - 1; i++)
{
printf("%.3f ", c[i]);
}
printf("%.3f\n", c[l - 1]);
}
void print_array_b(bool c[], int l)
{
for (int i = 0; i < l - 1; i++)
{
printf("%d,", c[i] ? 1 : 0);
}
printf("%d\n", c[l - 1] ? 1 : 0);
}
void print_array_i(int c[], int l)
{
for (int i = 0; i < l - 1; i++)
{
printf("%d,", c[i]);
}
printf("%d\n", c[l - 1]);
}
void print_array_ui(unsigned int c[], int l)
{
for (int i = 0; i < l - 1; i++)
{
printf("%u,", c[i]);
}
printf("%u\n", c[l - 1]);
}
void print_array_2d(bool **c, int xlen, int ylen)
{
for (int x = 0; x < xlen; x++)
{
for (int y = 0; y < ylen; y++)
{
printf("%d,", c[x][y]);
}
puts("");
}
}
void print_array_2d_d(double **c, int xlen, int ylen)
{
for (int x = 0; x < xlen; x++)
{
for (int y = 0; y < ylen; y++)
{
printf("%.2f,", c[x][y]);
}
puts("");
}
}
void tool_free_array_d(double **a, int xlen)
{
for (int x = 0; x < xlen; x++)
{
free(a[x]);
}
free(a);
}
void tool_free_array_b(bool **a, int xlen)
{
for (int x = 0; x < xlen; x++)
{
free(a[x]);
}
free(a);
}
void tool_free_array_ui(unsigned int **a, int xlen)
{
for (int x = 0; x < xlen; x++)
{
free(a[x]);
}
free(a);
}
bool **tool_alloc_array_b(int xlen, int ylen)
{
bool **a = (bool **)malloc(xlen * sizeof(bool *));
for (int x = 0; x < xlen; x++)
{
a[x] = (bool *)calloc((size_t)ylen, sizeof(bool));
}
return a;
}
unsigned int **tool_alloc_array_ui(int xlen, int ylen)
{
unsigned int **a = (unsigned int **)malloc(xlen * sizeof(unsigned int *));
for (int x = 0; x < xlen; x++)
{
a[x] = (unsigned int *)calloc((size_t)ylen, sizeof(unsigned int));
}
return a;
}
double **tool_alloc_array_d(int xlen, int ylen)
{
double **a = (double **)malloc(xlen * sizeof(double *));
for (int x = 0; x < xlen; x++)
{
a[x] = (double *)calloc((size_t)ylen, sizeof(double));
}
return a;
}
void tool_array_bool_to_double(double *res, bool *src, int len)
{
for (int i = 0; i < len; i++)
{
res[i] = src[i] ? 1.0 : 0.0;
}
}
void tool_round(double **a, int xlen, int ylen)
{
for (int x = 0; x < xlen; x++)
for (int y = 0; y < ylen; y++)
a[x][y] = round(a[x][y]);
}
static int tool_current_thread()
{
#ifdef _USE_OPENMP
return omp_get_thread_num();
#else
return 0;
#endif
}
double tool_rand()
{
return gsl_rng_uniform(_random[tool_current_thread()]);
}
/*
* Returns random int from [min, max-1]
*/
int tool_rand_i(int min, int max)
{
return min + gsl_rng_uniform_int(_random[tool_current_thread()], max - min);
}
void tool_fill_random1(double *a, int xlen, bool deterministic)
{
for (int x = 0; x < xlen; x++)
{
a[x] = tool_rand();
if (deterministic)
{
a[x] = a[x] > 0.5 ? 1 : 0;
}
}
}
void tool_fill_random1ui(unsigned int *a, int xlen, int min, int max)
{
for (int x = 0; x < xlen; x++)
{
a[x] = (unsigned int)tool_rand_i(min, max);
}
}
void tool_fill_random1i(int *a, int xlen, int min, int max)
{
for (int x = 0; x < xlen; x++)
{
a[x] = tool_rand_i(min, max);
}
}
void tool_fill_random1b(bool *a, int xlen)
{
for (int x = 0; x < xlen; x++)
{
a[x] = tool_rand() < 0.5;
}
}
void tool_fill_random(double **a, int xlen, int ylen, bool deterministic)
{
for (int x = 0; x < xlen; x++)
{
for (int y = 0; y < ylen; y++)
{
a[x][y] = tool_rand();
if (deterministic)
{
a[x][y] = a[x][y] > 0.5 ? 1 : 0;
}
}
}
}
void tool_fill_random_d(double **a, int xlen, int ylen)
{
for (int x = 0; x < xlen; x++)
{
for (int y = 0; y < ylen; y++)
{
a[x][y] = tool_rand(); // < 0.5 ? 1 : 0;
}
}
}
void tool_fill_random_b(bool **a, int xlen, int ylen)
{
for (int x = 0; x < xlen; x++)
{
double p = tool_rand();
for (int y = 0; y < ylen; y++)
{
a[x][y] = tool_rand() <= p;
}
}
}
void tool_fill_random_ui(unsigned int **a, int xlen, int ylen, int min, int max)
{
for (int x = 0; x < xlen; x++)
{
for (int y = 0; y < ylen; y++)
{
a[x][y] = (unsigned int)tool_rand_i(min, max);
}
}
}
double tool_sum(double **a, int xlen, int ylen)
{
double res = 0;
for (int x = 0; x < xlen; x++)
for (int y = 0; y < ylen; y++)
res += a[x][y];
return res;
}
int tool_foldedSize(int s, int r)
{
return s + 2 * r;
}
void tool_fold(bool *f_res, bool *u_src, int u_len, int r)
{
memcpy(f_res + r, u_src, (size_t)u_len * sizeof(bool));
memcpy(f_res, u_src + u_len - r, (size_t)r * sizeof(bool));
memcpy(f_res + r + u_len, u_src, (size_t)r * sizeof(bool));
}
void tool_fold_d(double *f_res, double *u_src, int u_len, int r)
{
memcpy(f_res + r, u_src, (size_t)u_len * sizeof(double));
memcpy(f_res, u_src + u_len - r, (size_t)r * sizeof(double));
memcpy(f_res + r + u_len, u_src, (size_t)r * sizeof(double));
}
void tool_unfold(bool u_res[], bool f_src[], int f_len, int r)
{
memcpy(u_res, f_src + r, (size_t)(f_len - 2 * r) * sizeof(bool));
}
void tool_unfold_d(double u_res[], double f_src[], int f_len, int r)
{
memcpy(u_res, f_src + r, (size_t)(f_len - 2 * r) * sizeof(double));
}
void tool_add(double **res, bool **src, int xlen, int ylen)
{
for (int x = 0; x < xlen; x++)
for (int y = 0; y < ylen; y++)
res[x][y] += src[x][y] ? 1.0 : 0.0;
}
void tool_mult(double **a, double c, int xlen, int ylen)
{
for (int x = 0; x < xlen; x++)
for (int y = 0; y < ylen; y++)
a[x][y] *= c;
}
void tool_abs_subst(double **res, bool **a, double **b, int xlen, int ylen)
{
for (int x = 0; x < xlen; x++)
for (int y = 0; y < ylen; y++)
{
res[x][y] = fabs((a[x][y] ? 1.0 : 0.0) - b[x][y]);
}
}
double tool_1d_max(double *a, int len)
{
double max = 0.0;
for (int i = 0; i < len; i++)
{
if (a[i] > max)
max = a[i];
}
return max;
}
int tool_differences(bool **a, bool **b, int xlen, int ylen)
{
int result = 0;
for (int x = 0; x < xlen; x++)
{
for (int y = 0; y < ylen; y++)
{
if (a[x][y] && !b[x][y])
result++;
if (!a[x][y] && b[x][y])
result++;
}
}
return result;
}
static int tool_num_threads()
{
#ifdef _USE_OPENMP
return omp_get_num_threads();
#else
return 1;
#endif
}
void tool_fake_random()
{
int threads = 0;
#ifdef _USE_OPENMP
#pragma omp parallel
#pragma omp master
#endif
{
threads = tool_num_threads();
const gsl_rng_type *T;
gsl_rng_env_setup();
T = gsl_rng_default;
_random = (gsl_rng **)malloc(threads * sizeof(gsl_rng *));
for (int i = 0; i < threads; i++)
{
_random[i] = gsl_rng_alloc(T);
gsl_rng_set(_random[i], 1234567890);
}
}
}
void tool_init_random()
{
int threads = 0;
#ifdef _USE_OPENMP
#pragma omp parallel
#pragma omp master
#endif
{
if (_random == NULL)
{
threads = tool_num_threads();
#ifndef _USE_RAND
#ifdef __APPLE__
srandomdev();
#else
srandom((unsigned int)tool_get_time());
#endif
#else
srand((unsigned int)tool_get_time());
#endif
const gsl_rng_type *T;
gsl_rng_env_setup();
T = gsl_rng_default;
_random = (gsl_rng **)malloc(threads * sizeof(gsl_rng *));
for (int i = 0; i < threads; i++)
{
_random[i] = gsl_rng_alloc(T);
unsigned long int seed;
#ifdef _USE_RAND
seed = (unsigned long int)rand();
#else
seed = (unsigned long int)random();
#endif
gsl_rng_set(_random[i], seed);
}
}
}
}
double tool_rand_gauss(double sigma)
{
return gsl_ran_gaussian_ziggurat(_random[tool_current_thread()], sigma);
}
int tool_cap(int a, int min, int max)
{
if (a > max)
return max;
if (a < min)
return min;
return a;
}
void tool_range(int *result, int start, int len)
{
for (int i = start; i < start + len; i++)
{
result[i - start] = i;
}
}
int *tool_alloc_range(int start, int len)
{
int *a = (int *)malloc(sizeof(int) * len);
tool_range(a, start, len);
return a;
}
#ifdef __APPLE__
int _compr(void *f, const void *a, const void *b)
{
#else
int _compr(const void *a, const void *b, void *f)
{
#endif
double *fitness = (double *)f;
int i1 = (int)(*(int *)a);
int i2 = (int)(*(int *)b);
double diff = fitness[i1] - fitness[i2];
if (diff == 0.0)
return 0;
if (diff > 0.0)
return 1;
return -1;
}
int *tool_sort_fitness_index(int *index, double *fitness, int count)
{
#ifdef __APPLE__
qsort_r(index, count, sizeof(int), fitness, _compr);
#else
qsort_r(index, count, sizeof(int), _compr, fitness);
#endif
return index;
}
#ifdef __APPLE__
int _compr_int(void *f, const void *a, const void *b)
{
#else
int _compr_int(const void *a, const void *b, void *f)
{
#endif
int *fitness = (int *)f;
int i1 = (int)(*(int *)a);
int i2 = (int)(*(int *)b);
int diff = fitness[i1] - fitness[i2];
if (diff == 0)
return 0;
if (diff > 0)
return 1;
return -1;
}
int *tool_sort_index_int(int *index, int *array, int count)
{
#ifdef __APPLE__
qsort_r(index, count, sizeof(int), array, _compr_int);
#else
qsort_r(index, count, sizeof(int), _compr_int, array);
#endif
return index;
}
bool tool_row_cmp(bool *r1, bool *r2, int len)
{
for (int i = 0; i < len; i++)
{
if (r1[i] != r2[i])
return false;
}
return true;
}
double tool_avg(double *a, int len)
{
double result = 0;
for (int i = 0; i < len; i++)
result += a[i];
return result / len;
}
double tool_max(double *a, int len)
{
double result = a[0];
for (int i = 1; i < len; i++)
{
if (result < a[i])
result = a[i];
}
return result;
}
int tool_max_i(int *a, int len)
{
int result = a[0];
for (int i = 1; i < len; i++)
{
if (result < a[i])
result = a[i];
}
return result;
}
double tool_min(double *a, int len)
{
double result = a[0];
for (int i = 1; i < len; i++)
{
if (result > a[i])
result = a[i];
}
return result;
}
int tool_min_i(int *a, int len)
{
int result = a[0];
for (int i = 1; i < len; i++)
{
if (result > a[i])
result = a[i];
}
return result;
}
double tool_max_ix(double *a, int len, int *id)
{
double result = a[0];
(*id) = 0;
for (int i = 1; i < len; i++)
{
if (result < a[i])
{
result = a[i];
(*id) = i;
}
}
return result;
}
double tool_min_ix(double *a, int len, int *id)
{
double result = a[0];
(*id) = 0;
for (int i = 1; i < len; i++)
{
if (result > a[i])
{
result = a[i];
(*id) = i;
}
}
return result;
}
double tool_1d_sum(double *a, int len)
{
double result = 0;
for (int i = 0; i < len; i++)
{
result += a[i];
}
return result;
}
bool tool_compar_b(bool *a, bool *b, int len)
{
for (int i = 0; i < len; i++)
{
if (a[i] != b[i])
return false;
}
return true;
}
bool tool_compar_d(double *a, double *b, int len)
{
for (int i = 0; i < len; i++)
{
if (a[i] != b[i])
return false;
}
return true;
}
| {
"alphanum_fraction": 0.5024987909,
"avg_line_length": 19.5987361769,
"ext": "c",
"hexsha": "ffb248a34bd9cc57a97590161145bb468f978d19",
"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": "5ae521201fa3d22306079694f3d9484d17be68e9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "houp/identify",
"max_forks_repo_path": "tools.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5ae521201fa3d22306079694f3d9484d17be68e9",
"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": "houp/identify",
"max_issues_repo_path": "tools.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5ae521201fa3d22306079694f3d9484d17be68e9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "houp/identify",
"max_stars_repo_path": "tools.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3982,
"size": 12406
} |
// xll_roots.h - GSL 1-dim root finding
// http://www.gnu.org/software/gsl/manual/html_node/One-dimensional-Root_002dFinding.html#One-dimensional-Root_002dFinding
#pragma once
#include <functional>
#include <memory>
#include <stdexcept>
#include <tuple>
#include "gsl/gsl_errno.h"
#include "gsl/gsl_roots.h"
#include "xll_math.h"
namespace gsl {
namespace root {
// root bracketing solvers
class fsolver {
gsl_root_fsolver* s;
gsl::function f;
public:
explicit fsolver(const gsl_root_fsolver_type * type)
: s{gsl_root_fsolver_alloc(type)}
{ }
fsolver(const fsolver&) = delete;
fsolver& operator=(const fsolver&) = delete;
~fsolver()
{
gsl_root_fsolver_free(s);
}
// needed for gsl_root_fsolver_* routines
gsl_root_fsolver* get() const
{
return s;
}
// syntactic sugar
operator gsl_root_fsolver*() const
{
return get();
}
int set(const std::function<double(double)>& f_, double lo, double hi)
{
f = f_;
return gsl_root_fsolver_set(s, &f, lo, hi);
}
// forward to gsl_root_fsolver_* functions
int iterate()
{
return gsl_root_fsolver_iterate(s);
}
double x_lower() const
{
return gsl_root_fsolver_x_lower(s);
}
double x_upper() const
{
return gsl_root_fsolver_x_upper(s);
}
double root() const
{
return gsl_root_fsolver_root(s);
}
// specify convergence condition
double solve(const std::function<bool(const fsolver&)>& done)
{
while (GSL_SUCCESS == iterate()) {
if (done(*this))
break;
}
return root();
}
};
// convergence helper functions
inline auto test_interval(double epsabs, double epsrel)
{
return [epsabs,epsrel](const fsolver& s) {
return GSL_SUCCESS == gsl_root_test_interval(s.x_lower(), s.x_upper(), epsabs, epsrel);
};
}
// root finding using derivatives
class fdfsolver {
gsl_root_fdfsolver* s;
// function and its derivative
gsl::function_fdf FdF;
public:
fdfsolver(const gsl_root_fdfsolver_type * type)
: s{gsl_root_fdfsolver_alloc(type)}
{ }
fdfsolver(const fdfsolver&) = delete;
fdfsolver& operator=(const fdfsolver&) = delete;
~fdfsolver()
{
gsl_root_fdfsolver_free(s);
}
// needed for gsl_root_fdfsolver_* routines
gsl_root_fdfsolver* get() const
{
return s;
}
// syntactic sugar
operator gsl_root_fdfsolver*() const
{
return s;
}
int set(const std::function<double(double)>& f, const std::function<double(double)>& df, double x0)
{
FdF = gsl::function_fdf(f, df);
return gsl_root_fdfsolver_set(s, &FdF, x0);
}
// forward to gsl_root_fdfsolver_* functions
int iterate()
{
return gsl_root_fdfsolver_iterate(s);
}
double root() const
{
return gsl_root_fdfsolver_root(s);
}
// specify convergence condition given previous root
double solve(const std::function<bool(const fdfsolver&,double)>& done)
{
double x = root();
while (GSL_SUCCESS == iterate()) {
if (done(*this, x))
break;
x = root();
}
return root();
}
};
// convergence helper functions
inline auto test_delta(double epsabs, double epsrel)
{
return [epsabs,epsrel](const fdfsolver& s, double x) -> bool {
return GSL_SUCCESS == gsl_root_test_delta(x, s.root(), epsabs, epsrel);
};
}
} // root
} // gsl
#ifdef _DEBUG
#include <cassert>
#include <vector>
//#include <gsl/gsl_poly.h>
// http://www.gnu.org/software/gsl/manual/html_node/Root-Finding-Examples.html#Root-Finding-Examples
// a x^2 + b x + c
struct quadratic_params {
double a, b, c;
};
// This is bad. Why???
inline double quadratic(double x, void *params)
{
struct quadratic_params *p
= (struct quadratic_params *) params;
double a = p->a;
double b = p->b;
double c = p->c;
return (a * x + b) * x + c;
}
inline double quadratic_deriv(double x, void *params)
{
struct quadratic_params *p
= (struct quadratic_params *) params;
double a = p->a;
double b = p->b;
// double c = p->c;
return 2.0 * a * x + b;
}
inline void quadratic_fdf(double x, void *params, double *y, double *dy)
{
struct quadratic_params *p
= (struct quadratic_params *) params;
double a = p->a;
double b = p->b;
double c = p->c;
*y = (a * x + b) * x + c;
*dy = 2.0 * a * x + b;
}
inline void test_gsl_root_fsolver()
{
// GSL example
{
gsl_root_fsolver* s = gsl_root_fsolver_alloc(gsl_root_fsolver_brent);
quadratic_params params{1.,0.,-5.}; // x^2 - 5
gsl_function F;
F.function = quadratic;
F.params = ¶ms;
double x_lo = 0.0, x_hi = 5.0;
double epsabs = 0, epsrel = 1e-5;
gsl_root_fsolver_set(s, &F, x_lo, x_hi);
while (GSL_SUCCESS == gsl_root_fsolver_iterate(s)) {
x_lo = gsl_root_fsolver_x_lower(s);
x_hi = gsl_root_fsolver_x_upper(s);
// |x_lo - x_hi| < epsabs + epsrel * min(|x_lo|, |x_hi|)
if (GSL_SUCCESS == gsl_root_test_interval(x_lo, x_hi, epsabs, epsrel))
break;
}
double root = gsl_root_fsolver_root(s);
double sqrt5 = sqrt(5.);
assert (fabs(root - sqrt5) < sqrt5*epsrel);
gsl_root_fsolver_free(s);
}
// root_fsolver class with function<double(double)>
{
gsl::root::fsolver s(gsl_root_fsolver_brent);
std::vector<double> params{-5,0,1}; // -5 + x^2
auto F = [params](double x) { return params[0] + x*(params[1] + x*params[2]); };
gsl::function F_(F);
assert (F_(0) == -5);
assert (F_.call(0) == -5);
double x_lo = 0.0, x_hi = 5.0, epsrel = 1e-6;
s.set(F, x_lo, x_hi);
double root = s.solve(gsl::root::test_interval(0, epsrel));
double sqrt5 = sqrt(5.);
assert (fabs(root - sqrt5) < sqrt5*epsrel);
}
}
inline void test_gsl_root_fdfsolver()
{
// root_fdfsolver class with function<tuple<double,double>(double)>
{
gsl::root::fdfsolver s(gsl_root_fdfsolver_newton);
// F(x) = x^2 - 5
auto F = [](double x) {
return x*x - 5;
};
auto dF = [](double x) {
return 2*x;
};
double x = 5.0, epsrel = 1e-6;
s.set(F, dF, x);
double root = s.solve(gsl::root::test_delta(0, epsrel));
double sqrt5 = sqrt(5.);
assert (fabs(root - sqrt5) < sqrt5*epsrel);
}
}
#endif // _DEBUG | {
"alphanum_fraction": 0.6576891106,
"avg_line_length": 22.032967033,
"ext": "h",
"hexsha": "19af3f0810fb1f5c32eb14d6084d9249eb0cf104",
"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": "1add2885dbdd862a7c93c1f3fbb14f335a6ffe45",
"max_forks_repo_licenses": [
"MS-PL"
],
"max_forks_repo_name": "keithalewis/fms16",
"max_forks_repo_path": "test/xll_roots.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1add2885dbdd862a7c93c1f3fbb14f335a6ffe45",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MS-PL"
],
"max_issues_repo_name": "keithalewis/fms16",
"max_issues_repo_path": "test/xll_roots.h",
"max_line_length": 122,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1add2885dbdd862a7c93c1f3fbb14f335a6ffe45",
"max_stars_repo_licenses": [
"MS-PL"
],
"max_stars_repo_name": "keithalewis/fms16",
"max_stars_repo_path": "test/xll_roots.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1942,
"size": 6015
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include <stdbool.h>
#include <png.h>
#include "beachball.h"
#include "parmt_config.h"
#ifdef PARMT_USE_INTEL
#include <mkl_lapacke.h>
#include <mkl_cblas.h>
#else
#include <lapacke.h>
#include <cblas.h>
#endif
//#include "pixmap.h"
//#include "pixmap_png.h"
//#include "pixmap_jpg.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923
#endif
#ifndef MAX
#define MAX(x,y) (((x) > (y)) ? (x) : (y))
#endif
#ifndef MIN
#define MIN(x,y) (((x) < (y)) ? (x) : (y))
#endif
#define PIXMAP_COLORS 3
static void vecstrd(const double str, const double dip, double r[3]);
static void strdv(const double r[3], double *str, double *dip);
static void crossp(const double *__restrict__ u,
const double *__restrict__ v,
double *__restrict__ n);
static void strdvec(double r[3], double *str, double *dip);
static void rotmat(const int naxis, const double theta,
double *__restrict__ r,
double *__restrict__ rt);
static void isItNear(const double *__restrict__ pt,
double *howClose,
double *__restrict__ ptold);
static double dot3(const double *__restrict__ x,
const double *__restrict__ y);
static void gemv3(const double *__restrict__ A, const double *__restrict__ x,
double *__restrict__ y);
static double transform(const double a, const double b,
const double c, const double d,
const double x);
/*
int beachball_setMomentTensor(const double m11, const double m22,
const double m33, const double m12,
const double m13, const double m23,
const enum cmopad_basis_enum basis,
struct beachballPlot_struct *beachball)
{
struct cmopad_struct cmt;
double mt[3][3], m9[9], eigs[3];
int ierr, info;
bool lexplosion, limplosion;
memset(&cmt, 0, sizeof(struct cmopad_struct));
// the edge case is for purely isotropic sources
lexplosion = false;
limplosion = false;
m9[0] = m11;
m9[1] = m12;
m9[2] = m13;
m9[3] = m12;
m9[4] = m22;
m9[5] = m23;
m9[6] = m13;
m9[7] = m23;
m9[8] = m33;
info = LAPACKE_dsyev(LAPACK_COL_MAJOR, 'N', 'L', 3, m9, 3, eigs);
if (info != 0)
{
printf("Failed classifying eigenvalues\n");
}
if ((eigs[0] > 0.0 && eigs[1] > 0.0 && eigs[2] > 0.0))
{
//printf("Source is pure explosion\n");
lexplosion = true;
}
if ((eigs[0] < 0.0 && eigs[1] < 0.0 && eigs[2] < 0.0))
{
printf("Source is pure implosion\n");
limplosion = true;
}
// copy the input moment tensor
mt[0][0] = m11;
mt[1][1] = m22;
mt[2][2] = m33;
mt[0][1] = mt[1][0] = m12;
mt[0][2] = mt[2][0] = m13;
mt[1][2] = mt[2][1] = m23;
ierr = cmopad_basis_transformMatrixM33(mt, basis, NED);
if (ierr != 0)
{
printf("Error transforming matrix\n");
return -1;
}
// decompose the moment tensor
ierr = cmopad_standardDecomposition(mt, &cmt);
if (ierr != 0)
{
printf("Failed initializing moment tensor from strike, dip, rake\n");
return -1;
}
// get the principal tension, null, and plunge axes
ierr = cmopad_MT2PrincipalAxisSystem(0, &cmt);
if (ierr != 0)
{
printf("Error computing principal axes\n");
return -1;
}
if (lexplosion || limplosion)
{
cmt.p_axis[2] = cmt.eigenvalues[0];
cmt.null_axis[2] = cmt.eigenvalues[1];
cmt.t_axis[2] = cmt.eigenvalues[2];
}
else
{
// Convert pressure, null, and tension principal axes to
// azimuth, plunge, and length
ierr += cmopad_Eigenvector2PrincipalAxis(NED, cmt.eig_pnt[0],
cmt.p_axis, cmt.p_axis);
ierr += cmopad_Eigenvector2PrincipalAxis(NED, cmt.eig_pnt[1],
cmt.null_axis, cmt.null_axis);
ierr += cmopad_Eigenvector2PrincipalAxis(NED, cmt.eig_pnt[2],
cmt.t_axis, cmt.t_axis);
if (ierr != 0)
{
printf("Error converting eigenvector to principal axis!\n");
return -1;
}
}
memcpy(&beachball->cmt, &cmt, sizeof(struct cmopad_struct));
beachball->lhaveMT = true;
return 0;
}
*/
int beachball_writePNG(const char *fileName,
size_t height, size_t width, unsigned char *bytes)
{
FILE *file = NULL;
png_structp png = NULL;
png_infop info = NULL;
png_bytepp rows = NULL;
int h;
file = fopen(fileName, "wb");
if (file == NULL){printf("failed to open file\n");}
png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png == NULL){printf("error making png struct\n");}
info = png_create_info_struct(png);
if (info == NULL){printf("error making png info struct\n");}
png_init_io(png, file);
png_set_IHDR(png, info, width, height, 8,
PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(png, info);
rows = calloc(height, sizeof(png_bytep));
for (h=0; h<(int) height; h++)
{
rows[h] = bytes + (PIXMAP_COLORS*h*(int) width);
}
png_write_rows(png, rows, height);
png_write_end(png, NULL); //info);
png_destroy_write_struct(&png, &info);
if (rows != NULL){free(rows);}
fclose(file);
return 0;
}
int beachball_draw(struct beachballPlot_struct beachball)
{
const char *fcnm = "beachball_draw\0";
struct beachBall_struct beachImage;
unsigned char *image;
double baz, bdp, bev, paz, pdp, pev, taz, tdp, tev, x, xnorm, y;
int i, i1, i2, indx, ix, iy, jy, k;
size_t npixel;
taz = beachball.tAxis[0];
tdp = beachball.tAxis[1];
tev = beachball.tAxis[2];
baz = beachball.nAxis[0];
bdp = beachball.nAxis[1];
bev = beachball.nAxis[2];
paz = beachball.pAxis[0];
pdp = beachball.pAxis[1];
pev = beachball.pAxis[2];
// normalize the moment tensor for my sanity
xnorm = MAX(fabs(tev), MAX(fabs(bev), fabs(pev)));
if (xnorm == 0.0)
{
printf("%s: Error normalization is zero %f %f %f\n", fcnm, tev, bev, pev);
return -1;
}
// compute everything describing the beachball
memset(&beachImage, 0, sizeof(struct beachBall_struct));
cliffsNodes_beachBallP(beachball.xc, beachball.yc, beachball.rad,
taz, tdp, tev,
baz, bdp, bev,
paz, pdp, pev,
beachball.nNodalLine,
beachball.nFocalSphere,
beachball.nxPixel, beachball.nyPixel,
true, true, true,
&beachImage);
// draw the image
npixel = (size_t) (beachball.nxPixel*beachball.nyPixel);
image = (unsigned char *)
calloc(PIXMAP_COLORS*npixel, sizeof(unsigned char));
// Set a white background
for (indx=0; indx<3*beachball.nxPixel*beachball.nyPixel; indx++)
{
image[indx] = 255;
}
// Draw the polarity
if (beachball.lwantPolarity)
{
for (i=0; i<beachImage.npolarity; i++)
{
x = transform(beachball.xc - beachball.rad,
beachball.xc + beachball.rad,
0, (double) (beachball.nxPixel-1),
beachImage.xPolarity[i]);
y = transform(beachball.yc - beachball.rad,
beachball.yc + beachball.rad,
0, (double) (beachball.nyPixel-1),
beachImage.yPolarity[i]);
ix = (int) (x + 0.5);
iy = (int) (y + 0.5);
ix = MAX(0, MIN(ix, beachball.nxPixel - 1));
iy = MAX(0, MIN(iy, beachball.nyPixel - 1));
jy = beachball.nyPixel - 1 - iy;
if (beachImage.polarity[i] ==-1)
{
// white
image[3*(jy*beachball.nxPixel+ix)+0] = 255;
image[3*(jy*beachball.nxPixel+ix)+1] = 255;
image[3*(jy*beachball.nxPixel+ix)+2] = 255;
}
else
{
// red
image[3*(jy*beachball.nxPixel+ix)+0] = 255;
image[3*(jy*beachball.nxPixel+ix)+1] = 0;
image[3*(jy*beachball.nxPixel+ix)+2] = 0;
}
}
}
// Add the nodal lines
if (beachball.lwantNodalLines)
{
// draw first nodal line
for (k=0; k<beachImage.nNodalLineSegs1; k++)
{
i1 = beachImage.nodalLine1Ptr[k];
i2 = beachImage.nodalLine1Ptr[k+1];
for (i=i1; i<i2; i++)
{
// start point in vector (line)
x = transform(beachball.xc - beachball.rad,
beachball.xc + beachball.rad,
0, (double) (beachball.nxPixel-1),
beachImage.xNodalLine1[2*i]);
y = transform(beachball.yc - beachball.rad,
beachball.yc + beachball.rad,
0, (double) (beachball.nyPixel-1),
beachImage.yNodalLine1[2*i]);
ix = (int) (x + 0.5);
iy = (int) (y + 0.5);
ix = MAX(0, MIN(ix, beachball.nxPixel - 1));
iy = MAX(0, MIN(iy, beachball.nyPixel - 1));
jy = beachball.nyPixel - 1 - iy;
// black
image[3*(jy*beachball.nxPixel+ix)+0] = 0;
image[3*(jy*beachball.nxPixel+ix)+1] = 0;
image[3*(jy*beachball.nxPixel+ix)+2] = 0;
// end point in vector (line)
x = transform(beachball.xc - beachball.rad,
beachball.xc + beachball.rad,
0, (double) (beachball.nxPixel-1),
beachImage.xNodalLine1[2*i+1]);
y = transform(beachball.yc - beachball.rad,
beachball.yc + beachball.rad,
0, (double) (beachball.nyPixel-1),
beachImage.yNodalLine1[2*i+1]);
ix = (int) (x + 0.5);
iy = (int) (y + 0.5);
ix = MAX(0, MIN(ix, beachball.nxPixel - 1));
iy = MAX(0, MIN(iy, beachball.nyPixel - 1));
jy = beachball.nyPixel - 1 - iy;
// black
image[3*(jy*beachball.nxPixel+ix)+0] = 0;
image[3*(jy*beachball.nxPixel+ix)+1] = 0;
image[3*(jy*beachball.nxPixel+ix)+2] = 0;
}
}
// draw second nodal line
for (k=0; k<beachImage.nNodalLineSegs2; k++)
{
i1 = beachImage.nodalLine2Ptr[k];
i2 = beachImage.nodalLine2Ptr[k+1];
for (i=i1; i<i2; i++)
{
// start point in vector (line)
x = transform(beachball.xc - beachball.rad,
beachball.xc + beachball.rad,
0, (double) (beachball.nxPixel-1),
beachImage.xNodalLine2[2*i]);
y = transform(beachball.yc - beachball.rad,
beachball.yc + beachball.rad,
0, (double) (beachball.nyPixel-1),
beachImage.yNodalLine2[2*i]);
ix = (int) (x + 0.5);
iy = (int) (y + 0.5);
ix = MAX(0, MIN(ix, beachball.nxPixel - 1));
iy = MAX(0, MIN(iy, beachball.nyPixel - 1));
jy = beachball.nyPixel - 1 - iy;
// black
image[3*(jy*beachball.nxPixel+ix)+0] = 0;
image[3*(jy*beachball.nxPixel+ix)+1] = 0;
image[3*(jy*beachball.nxPixel+ix)+2] = 0;
// end point in vector (line)
x = transform(beachball.xc - beachball.rad,
beachball.xc + beachball.rad,
0, (double) (beachball.nxPixel-1),
beachImage.xNodalLine2[2*i+1]);
y = transform(beachball.yc - beachball.rad,
beachball.yc + beachball.rad,
0, (double) (beachball.nyPixel-1),
beachImage.yNodalLine2[2*i+1]);
ix = (int) (x + 0.5);
iy = (int) (y + 0.5);
ix = MAX(0, MIN(ix, beachball.nxPixel - 1));
iy = MAX(0, MIN(iy, beachball.nyPixel - 1));
jy = beachball.nyPixel - 1 - iy;
// black
image[3*(jy*beachball.nxPixel+ix)+0] = 0;
image[3*(jy*beachball.nxPixel+ix)+1] = 0;
image[3*(jy*beachball.nxPixel+ix)+2] = 0;
}
}
}
// Draw an outline
for (i=0; i<beachImage.nFocalSphere; i++)
{
x = transform(beachball.xc - beachball.rad,
beachball.xc + beachball.rad,
0, (double) (beachball.nxPixel-1),
beachImage.xFocalSphere[i]);
y = transform(beachball.yc - beachball.rad,
beachball.yc + beachball.rad,
0, (double) (beachball.nyPixel-1),
beachImage.yFocalSphere[i]);
ix = (int) (x + 0.5);
iy = (int) (y + 0.5);
ix = MAX(0, MIN(ix, beachball.nxPixel - 1));
iy = MAX(0, MIN(iy, beachball.nyPixel - 1));
jy = beachball.nyPixel - 1 - iy;
// black
image[3*(jy*beachball.nxPixel+ix)+0] = 0;
image[3*(jy*beachball.nxPixel+ix)+1] = 0;
image[3*(jy*beachball.nxPixel+ix)+2] = 0;
}
// Write it
beachball_writePNG("temp2.png",
(size_t) beachball.nxPixel, (size_t) beachball.nyPixel,
image);
free(image);
cliffsNodes_free(&beachImage);
return 0;
}
int beachball_plotDefaults(struct beachballPlot_struct *beachball)
{
memset(beachball, 0, sizeof(struct beachballPlot_struct));
beachball->rad = 1.0;
beachball->xc = 1.5;
beachball->yc = 1.5;
beachball->nxPixel = 251;
beachball->nyPixel = 251;
beachball->nNodalLine = 3*beachball->nxPixel;
beachball->nFocalSphere = 4*beachball->nxPixel;
beachball->lwantPolarity = true;
beachball->lwantNodalLines = true;
beachball->lhaveMT = false;
return 0;
}
static double transform(const double a, const double b,
const double c, const double d,
const double x)
{
double det, c1, c2, xi;
det = 1.0/(b - a);
c1 = det*(b*c - a*d);
c2 = det*(-c + d);
xi = c1 + x*c2;
return xi;
}
//============================================================================//
int cliffsNodes_plotStations(const double xc, const double yc, const double rad,
const int nstat,
const double *__restrict__ az,
const double *__restrict__ toa,
double *__restrict__ xp,
double *__restrict__ yp);
/*!
* @brief Computes the station locations for the given azimuth
* and take-off angle on a focal sphere with radius rad
* centered at (xc, yc). This is based on Cliff Frohlich's
* stnPlt but now processes multiple stations and does no plotting.
*
* @param[in] xc x center of focal sphere
* @param[in] yc y center of focal sphere
* @param[in] rad radius of sphere
* @param[in] nstat number of stations
* @param[in] az source station azimuths (degrees) [nstat]
* @param[in] toa take off angle (degrees) from source to stations [nstat]
*
* @param[out] xp station's x location on focal sphere [nstat]
* @param[out] yp station's y location on focal sphere [nstat]
*
* @author Ben Baker
*
* @copyright BSD
*
*/
int cliffsNodes_plotStations(const double xc, const double yc, const double rad,
const int nstat,
const double *__restrict__ az,
const double *__restrict__ toa,
double *__restrict__ xp,
double *__restrict__ yp)
{
const char *fcnm = "cliffsNodes_plotStations\0";
double azrad, rp, sign, toaN;
int i;
const double sqrt2 = 1.4142135623730951;
const double degrad = M_PI/180.0;
//------------------------------------------------------------------------//
//
// error handling
if (nstat < 1 || az == NULL || toa == NULL || xp == NULL || yp == NULL)
{
if (nstat < 1){printf("%s: No stations\n", fcnm);}
if (az == NULL){printf("%s: az is NULL\n", fcnm);}
if (toa == NULL){printf("%s: toa is NULL\n", fcnm);}
if (xp == NULL){printf("%s: xp is NULL\n", fcnm);}
if (yp == NULL){printf("%s: yp is NULL\n", fcnm);}
return -1;
}
// compute point on focal shere for each station
for (i=0; i<nstat; i++)
{
// ray normally goes down
sign = 1.0;
toaN = toa[i];
// ray is going up
if (toaN > 90.)
{
toaN = 180. - toa[i];
sign =-1.;
}
rp = sign*rad*sqrt2*sin(0.5*degrad*toaN);
azrad = az[i]*degrad;
xp[i] = xc + rp*sin(azrad);
yp[i] = yc + rp*cos(azrad);
}
return 0;
}
//============================================================================//
/*!
* @brief Given the azimuth and dip of the tension and pressure eigenvectors
* in geographic coordinates along with normalized eigenvalues
* this computes the moment tensort in geographic coordinates as
* well as the rotation and transpose rotation matrices which rotate
* from a system where t=1-axis and p=2-axis. This is based on
* Cliff Frohlich's mtensor.
*
* @param[in] taz tension axis azimuth (degrees)
* @param[in] tdp tension axis dip (degrees)
* @param[in] paz pressure axis azimuth (degrees)
* @param[in] pdp pressure axis dip
* @param[in] tev1 normalized eigenvalue for tension eigenvector
* @param[in] bev1 normalized eigenvalue for null eigenvector
* @param[in] pev1 normalized eigenvalue for pressure eigenvector
*
* @param[out] mt [3 x 3] moment tensor (column major)
* @param[out] rm [3 x 3] rotation matrix as described above (column major)
* @param[out] rmt [3 x 3] transpose rotation matrix described above
* (column major)
* @author Ben Baker
*
* @copyright BSD
*
*/
void cliffsNodes_mtensor(const double taz, const double tdp,
const double paz, const double pdp,
const double tev1, const double bev1,
const double pev1,
double *__restrict__ mt,
double *__restrict__ rm,
double *__restrict__ rmt,
double *ampMax)
{
double mpt[9], sm1[9], smt1[9], sm2[9], smt2[9], sm3[9],
smt3[9], work[9], p[3], pnew[3], pxt[3], t[3], pang;
const double degrad = M_PI/180.0;
// set up moment tensor in t-p system
memset(mpt, 0, 9*sizeof(double));
mpt[0] = tev1;
mpt[4] = pev1;
mpt[8] = bev1;
// condition p-axis so that it really is perpendicular to t-axis
vecstrd(taz, tdp, t);
vecstrd(paz, pdp, p);
crossp(p, t, pxt);
crossp(t, pxt, p);
// Step 1: rotate 1-axis about 3-axis so that 1-axis lies along t azimuth
rotmat(3, taz-90., sm1, smt1);
// Step 2: rotate 1-axis about 2-axis so that 1-axis liesalong t
rotmat(2, tdp, sm2, smt2);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3,
1.0, sm2, 3, sm1, 3, 0.0, sm3, 3);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3,
1.0, smt1, 3, smt2, 3, 0.0, smt3, 3);
// in this system, p should lie in 2-3 plane
cblas_dgemv(CblasColMajor, CblasNoTrans, 3, 3,
1.0, sm3, 3, p, 1, 0.0, pnew, 1);
// Step 3: rotate about 1 axis so that 2 axis lies along p
pang = atan2(pnew[2], pnew[1])/degrad; //(3.14159/180.)
rotmat(1, -pang, sm1, smt1);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3,
1.0, sm1, 3, sm3, 3, 0.0, rm, 3);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3,
1.0, smt3, 3, smt1, 3, 0.0, rmt, 3);
// Finally: find moment tensor in space coordinates.
// This is because Mpt=RM*Mspace*RMT, thus Mspace=RMT*Mpt*RM
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3,
1.0, rmt, 3, mpt, 3, 0.0, work, 3);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3,
1.0, work, 3, rm, 3, 0.0, mt, 3);
// ampMax is the absolute maximum amplitude
*ampMax = MAX(fabs(pev1), MAX(fabs(tev1), fabs(bev1)));
return;
}
//============================================================================//
/*!
* @brief Computes the lower-hemisphere projection `beachball' diagram for a
* focal mechanism. This is based on Cliff Frohlich's bballP and
* has been translated to C and does no plotting.
*
* @param[in] xc plot coordinates (e.g. pixels) of center of
* beachball
* @param[in] yc plot coordinates (e.g. pixels) of center of
* beachball
* @param[in] rad beachball radius (e.g. pixels)
* @param[in] taz1 azimuth (degrees) of tension eigenvector
* @param[in] tdp1 dip (degrees) of tension eigenvector
* @param[in] tevI eigenvalue corresponding to tension eigenvector
* (e.g. Newton meters)
* @param[in] baz1 azimuth (degrees) of null eigenvector
* @param[in] bdp1 dip (degrees) of null eigenvector
* @param[in] bevI eigenvalue corresponding to null eigenvector
* (e.g. Newton meters)
* @param[in] paz1 azimuth (degrees) of pressure eigenvector
* @param[in] pdp1 dip (degrees) of pressure eigenvector
* @param[in] pevI eigenvalue corresponding to pressure eigenvector
* (e.g. Newton meters)
* @param[in] nNodalLine number of points to draw in nodal line.
* @param[in] nFocalSphere number of points to draw in focal sphere.
* @param[in] nxPixel number of pixels in x when drawing polarity
* @param[in] nyPixel number of pixels in y when drawing polairty
* @param[in] lwantNodalLines if true then compute the nodal lines.
* @param[in] lwantPTBAxes if true then compute the PTB axis points.
* @param[in] lwantPolarity if true then compute the polarity.
*
* @param[out] beachBall container for the pressure, tension and null axes,
* the nodal lines, and the polarity
*
* @author Ben Baker
*
* @copyright BSD
*
* @bug this routine fails if rad is not = 1.
*
*/
void cliffsNodes_beachBallP(const double xc, const double yc, const double rad,
const double taz1, const double tdp1,
const double tevI,
const double baz1, const double bdp1,
const double bevI,
const double paz1, const double pdp1,
const double pevI,
const int nNodalLine,
const int nFocalSphere,
const int nxPixel, const int nyPixel,
const bool lwantNodalLines,
const bool lwantPTBAxes,
const bool lwantPolarity,
struct beachBall_struct *beachBall)
{
double *xw1, *xw2, *yw1, *yw2;
double rm[9] __attribute__ ((aligned(64)));
double rmt[9] __attribute__ ((aligned(64)));
double tm[9] __attribute__ ((aligned(64)));
double pt[3] __attribute__ ((aligned(64)));
double ptnew[3] __attribute__ ((aligned(64)));
double ax1[3] __attribute__ ((aligned(64)));
double ax2[3] __attribute__ ((aligned(64)));
double ax3[3] __attribute__ ((aligned(64)));
double ptLine1[3] __attribute__ ((aligned(64)));
double ptLine2[3] __attribute__ ((aligned(64)));
double ptLine1Old[3] __attribute__ ((aligned(64)));
double ptLine2Old[3] __attribute__ ((aligned(64)));
double ampMax, az, baz, bdp, bev, cosPsi, cosTheta,
dip, dp, dpsi, dx, dy, evI, fclvd, fIso, howClose, rad2,
rb, rp, rpt, rpt2, rt, paz, pdp, pev, plusMin, psi,
sinsq, sinPsi, sinTheta, str,
taz, tdp, tev, theta, x, x0, xpt, y, y0, ypt;
int *pn1, *pn2, ix, ixy, iy, k, nlines, nnl1, nnl2, npts, nseg,
nx, ny, penDown, psave1, psave2;
size_t nwork;
const double sqrt2 = 1.4142135623730951;
const double sqrt2i = 1.0/sqrt2;
const double degrad = M_PI/180.0;
const double degradi = 180.0/M_PI;
const double third = 1.0/3.0;
const double tol = 0.95;
// null out result
memset(beachBall, 0, sizeof(struct beachBall_struct));
// Avoid overwriting memory
taz = taz1;
tdp = tdp1;
baz = baz1;
bdp = bdp1;
paz = paz1;
pdp = pdp1;
// Step 1: set up axes:
// - D axis ('dominant' 1-axis - with largest absolute eigenvalue)
// - M axis ('minor' 3-axis)
// - B axis ( 2-axis)
evI = (tevI + bevI + pevI)*third;
tev = tevI - evI;
bev = bevI - evI;
pev = pevI - evI;
vecstrd(paz, pdp, ax1);
vecstrd(taz, tdp, ax3);
fclvd = fabs(bev/pev);
fIso = evI/pev;
if (fabs(tev) > fabs(pev))
{
vecstrd(taz, tdp, ax1);
vecstrd(paz, pdp, ax3);
fclvd = fabs(bev/tev);
fIso = evI/tev;
}
//if (fabs(evI) > .03)
//{
// write(6,901) evI
//}
crossp(ax1, ax3, ax2);
strdvec(ax2, &baz, &bdp);
cliffsNodes_mtensor(taz, tdp, paz, pdp, tevI, bevI, pevI,
tm, rm, rmt, &Max);
// Step 2: Now: plot upper half nodal line:
// point on nodal line is represented by vector pt;
// pt is defined by two angles
// - psi is azimuth with respect to 3-axis (M-axis)
// in 2-3 plane (in B-M plane)
// - theta is angle with respect to 1 axis.
// It can be shown (i. e., cliff did it once) that:
// sin(theta)**2=(2+2*fIso)/(3+(1-2*f)*cos(2*psi))
// Additionally, a constraint corresponding to Cliff's Rule 1
// for existance of P nodal planes is applied
//psi = 0.;
//dpsi = 2.;
//npts = nNodalLine1; //1 + (int)(360.0/dpsi + 0.5); //nint((360./dpsi))
//dpsi = dpsi*degrad;
psave1 =-1;
psave2 =-1;
memset(ptLine1Old, 0, 3*sizeof(double));
memset(ptLine2Old, 0, 3*sizeof(double));
if (lwantNodalLines && nNodalLine > 1 &&
!(tevI > 0.0 && bevI > 0.0 && pevI > 0.0) &&
!(tevI < 0.0 && bevI < 0.0 && pevI < 0.0))
{
npts = nNodalLine;
psi = 0.0;
dpsi = 360.0/(double) (nNodalLine - 1);
dpsi = dpsi*degrad;
xw1 = (double *) calloc((size_t) npts, sizeof(double));
yw1 = (double *) calloc((size_t) npts, sizeof(double));
pn1 = (int *) calloc((size_t) npts+1, sizeof(int));
xw2 = (double *) calloc((size_t) npts, sizeof(double));
yw2 = (double *) calloc((size_t) npts, sizeof(double));
pn2 = (int *) calloc((size_t) npts+1, sizeof(int));
nnl1 = 0;
nnl2 = 0;
for (k=0; k<npts; k++)
{
psi = k*dpsi;
theta = 0.0;
sinsq = (2. + 2.*fIso)/(3. + (1. - 2.*fclvd)*cos(2.*psi));
if (sinsq > 0 && sinsq <= 1.0)
{
theta = asin(sqrt(sinsq));
cosTheta = cos(theta);
sinTheta = sin(theta);
cosPsi = cos(psi);
sinPsi = sin(psi);
// upper half nodal line
ptLine1[0] = cosTheta*ax1[0]
+ sinTheta*(sinPsi*ax2[0] + cosPsi*ax3[0]);
ptLine1[1] = cosTheta*ax1[1]
+ sinTheta*(sinPsi*ax2[1] + cosPsi*ax3[1]);
ptLine1[2] = cosTheta*ax1[2]
+ sinTheta*(sinPsi*ax2[2] + cosPsi*ax3[2]);
// lower half nodal line
ptLine2[0] =-cosTheta*ax1[0]
- sinTheta*(sinPsi*ax2[0] + cosPsi*ax3[0]);
ptLine2[1] =-cosTheta*ax1[1]
- sinTheta*(sinPsi*ax2[1] + cosPsi*ax3[1]);
ptLine2[2] =-cosTheta*ax1[2]
- sinTheta*(sinPsi*ax2[2] + cosPsi*ax3[2]);
isItNear(ptLine1, &howClose, ptLine1Old);
// upper half nodal line
penDown =-1;
if (ptLine1[2] < 0.0){penDown = 1;}
if (howClose < tol){penDown =-1;}
strdv(ptLine1, &str, &dip);
rpt = rad*sqrt2*sin(0.5*degrad*(90.-dip));
xpt = xc + rpt*sin(str*degrad);
ypt = yc + rpt*cos(str*degrad);
xw1[k] = xpt;
yw1[k] = ypt;
if (k == 0){pn1[k] = 3;}
if (penDown == 1 && psave1 == 1)
{
pn1[k] = 2;
//printf("%f %f\n", xpt, ypt);
}
if (penDown ==-1){pn1[k] = 3;}
nnl1 = nnl1 + 1;
psave1 = penDown;
// lower half nodal line
penDown =-1;
if (ptLine2[2] < 0.0){penDown = 1;}
if (howClose < tol){penDown =-1;}
strdv(ptLine2, &str, &dip);
rpt = rad*sqrt2*sin(0.5*degrad*(90.-dip));
xpt = xc + rpt*sin(str*degrad);
ypt = yc + rpt*cos(str*degrad);
xw2[k] = xpt;
yw2[k] = ypt;
if (k == 0){pn2[k] = 3;} // pen down
if (penDown == 1 && psave2 == 1)
{
pn2[k] = 2;
//xptsLine2[k] = xpt;
//yptsLine2[k] = ypt;
//penLine2[k] = penDwn;
}
if (penDown ==-1){pn2[k] = 3;}
nnl2 = nnl2 + 1;
psave2 = penDown;
}
} // loop on points
nwork = (size_t) (MAX(2, 2*nnl1));
beachBall->xNodalLine1 = (double *) calloc(nwork, sizeof(double));
beachBall->yNodalLine1 = (double *) calloc(nwork, sizeof(double));
nwork = (size_t) (nnl1 + 1);
beachBall->nodalLine1Ptr = (int *) calloc(nwork, sizeof(int));
nwork = (size_t) (MAX(2, 2*nnl2));
beachBall->xNodalLine2 = (double *) calloc(nwork, sizeof(double));
beachBall->yNodalLine2 = (double *) calloc(nwork, sizeof(double));
nwork = (size_t) (nnl2 + 1);
beachBall->nodalLine2Ptr = (int *) calloc(nwork, sizeof(int));
// make sure the lines end
pn1[nnl1] = 3;
pn2[nnl2] = 3;
// compute the nodal line 1 line segments
nlines = 0;
nseg = 0;
for (k=0; k<nnl1; k++)
{
// line begins
if (pn1[k] == 3 && pn1[k+1] == 2)
{
beachBall->xNodalLine1[2*nlines ] = xw1[k];
beachBall->xNodalLine1[2*nlines+1] = xw1[k+1];
beachBall->yNodalLine1[2*nlines ] = yw1[k];
beachBall->yNodalLine1[2*nlines+1] = yw1[k+1];
nlines = nlines + 1;
}
// line continues
if (pn1[k] == 2 && pn1[k+1] == 2)
{
beachBall->xNodalLine1[2*nlines ] = xw1[k];
beachBall->xNodalLine1[2*nlines+1] = xw1[k+1];
beachBall->yNodalLine1[2*nlines ] = yw1[k];
beachBall->yNodalLine1[2*nlines+1] = yw1[k+1];
nlines = nlines + 1;
}
// line ends
if (pn1[k] == 2 && pn1[k+1] == 3)
{
/*
beachBall->xNodalLine1[2*nlines ] = xw1[k];
beachBall->xNodalLine1[2*nlines+1] = xw1[k+1];
beachBall->yNodalLine1[2*nlines ] = yw1[k];
beachBall->yNodalLine1[2*nlines+1] = yw1[k+1];
nlines = nlines + 1;
*/
nseg = nseg + 1;
beachBall->nodalLine1Ptr[nseg] = nlines;
}
}
beachBall->nNodalLineSegs1 = nseg;
// compute the nodal line 2 line segments
nlines = 0;
nseg = 0;
for (k=0; k<nnl2; k++)
{
// line begins
if (pn2[k] == 3 && pn2[k+1] == 2)
{
beachBall->xNodalLine2[2*nlines ] = xw2[k];
beachBall->xNodalLine2[2*nlines+1] = xw2[k+1];
beachBall->yNodalLine2[2*nlines ] = yw2[k];
beachBall->yNodalLine2[2*nlines+1] = yw2[k+1];
nlines = nlines + 1;
}
// line continues
if (pn2[k] == 2 && pn2[k+1] == 2)
{
beachBall->xNodalLine2[2*nlines ] = xw2[k];
beachBall->xNodalLine2[2*nlines+1] = xw2[k+1];
beachBall->yNodalLine2[2*nlines ] = yw2[k];
beachBall->yNodalLine2[2*nlines+1] = yw2[k+1];
nlines = nlines + 1;
}
// line ends
if (pn2[k] == 2 && pn2[k+1] == 3)
{
beachBall->xNodalLine2[2*nlines ] = xw2[k];
beachBall->xNodalLine2[2*nlines+1] = xw2[k+1];
beachBall->yNodalLine2[2*nlines ] = yw2[k];
beachBall->yNodalLine2[2*nlines+1] = yw2[k+1];
nlines = nlines + 1;
nseg = nseg + 1;
beachBall->nodalLine2Ptr[nseg] = nlines;
}
}
beachBall->nNodalLineSegs2 = nseg;
//printf("%d %d\n", nlines, nseg);
free(pn1);
free(pn2);
free(xw1);
free(xw2);
free(yw1);
free(yw2);
}
// Step 4: Plot the, P, T, and B axes
if (lwantPTBAxes)
{
rp = rad*sqrt2*sin(0.5*degrad*(90.-pdp));
rt = rad*sqrt2*sin(0.5*degrad*(90.-tdp));
rb = rad*sqrt2*sin(0.5*degrad*(90.-bdp));
beachBall->xp = xc + rp*sin(paz*degrad);
beachBall->yp = yc + rp*cos(paz*degrad);
beachBall->xt = xc + rt*sin(taz*degrad);
beachBall->yt = yc + rt*cos(taz*degrad);
beachBall->xb = xc + rb*sin(baz*degrad);
beachBall->yb = yc + rb*cos(baz*degrad);
}
// Step 5: Plot the focal sphere
if (nFocalSphere > 1)
{
beachBall->nFocalSphere = nFocalSphere;
beachBall->xFocalSphere = (double *)
calloc((size_t) nFocalSphere, sizeof(double));
beachBall->yFocalSphere = (double *)
calloc((size_t) nFocalSphere, sizeof(double));
dpsi = 2.0*M_PI/(double) (nFocalSphere - 1);
#ifdef _OPENMP
#pragma omp simd
#endif
for (k=0; k<nFocalSphere; k++)
{
psi = (double) k*dpsi;
beachBall->xFocalSphere[k] = xc + rad*sin(psi);
beachBall->yFocalSphere[k] = yc + rad*cos(psi);
}
}
// Step 6: Plot the + and -
if (lwantPolarity && nxPixel > 0 && nyPixel > 0)
{
// begin in lower left corner
nx = nxPixel;
ny = nyPixel;
dx = 2.0*rad/(double) (nx - 1);
dy = 2.0*rad/(double) (ny - 1);
x0 = xc - rad;
y0 = yc - rad;
rad2 = rad*rad; // saves a sqrt computation when comparing distances
xw1 = (double *)calloc((size_t) (nx*ny), sizeof(double));
yw1 = (double *)calloc((size_t) (nx*ny), sizeof(double));
pn1 = (int *)calloc((size_t) (nx*ny), sizeof(int));
nwork = 0;
// loop on pixel grid
for (iy=0; iy<ny; iy++)
{
for (ix=0; ix<nx; ix++)
{
x = x0 + (double) ix*dx;
y = y0 + (double) iy*dy;
k = iy*nx + ix;
pn1[k] = 0;
xw1[k] = x;
yw1[k] = y;
// require (x,y) be in the focal sphere
rpt2 = pow(x - xc, 2) + pow(y - yc, 2);
if (rpt2 < rad2)
{
nwork = nwork + 1;
rpt = sqrt(rpt2);
// compute the azimuth
theta = atan2(y - yc, x - xc); // measure from x axis
az = (M_PI_2 - theta)*degradi; // az is measured from north
if (az < 0.0){az = az + 360.0;} // convention is [0,360]
// compute the dip
dp = (M_PI_2 - 2.0*asin(rpt*sqrt2i))*degradi;
vecstrd(az, dp, pt);
//cblas_dgemv(CblasColMajor, CblasNoTrans, 3, 3,
// 1.0, tm, 3, pt, 1, 0.0, ptnew, 1);
gemv3(tm, pt, ptnew);
plusMin = dot3(pt, ptnew);
pn1[k] =-1;
if (plusMin > 100.0*DBL_EPSILON*ampMax){pn1[k] = 1;}
} // end check on location
} // loop on x
} // loop on y
// Copy the points to be plotted
if (nwork > 0)
{
beachBall->npolarity = (int) nwork;
beachBall->xPolarity = (double *)
calloc((size_t) nwork, sizeof(double));
beachBall->yPolarity = (double *)
calloc((size_t) nwork, sizeof(double));
beachBall->polarity = (int *)
calloc((size_t) nwork, sizeof(double));
k = 0;
for (ixy=0; ixy<nx*ny; ixy++)
{
if (pn1[ixy] != 0)
{
beachBall->xPolarity[k] = xw1[ixy];
beachBall->yPolarity[k] = yw1[ixy];
beachBall->polarity[k] = pn1[ixy];
k = k + 1;
}
}
}
free(pn1);
free(xw1);
free(yw1);
}
return;
}
void cliffsNodes_free(struct beachBall_struct *beachBall)
{
if (beachBall->xNodalLine1 != NULL){free(beachBall->xNodalLine1);}
if (beachBall->yNodalLine1 != NULL){free(beachBall->yNodalLine1);}
if (beachBall->xNodalLine2 != NULL){free(beachBall->xNodalLine2);}
if (beachBall->yNodalLine2 != NULL){free(beachBall->yNodalLine2);}
if (beachBall->xFocalSphere != NULL){free(beachBall->xFocalSphere);}
if (beachBall->yFocalSphere != NULL){free(beachBall->yFocalSphere);}
if (beachBall->xPolarity != NULL){free(beachBall->xPolarity);}
if (beachBall->yPolarity != NULL){free(beachBall->yPolarity);}
if (beachBall->polarity != NULL){free(beachBall->polarity);}
if (beachBall->nodalLine1Ptr != NULL){free(beachBall->nodalLine1Ptr);}
if (beachBall->nodalLine2Ptr != NULL){free(beachBall->nodalLine2Ptr);}
memset(beachBall, 0, sizeof(struct beachBall_struct));
return;
}
//============================================================================//
/*!
* @brief Finds simple rotation matrix R and transpose R^T for rotation
* of a vector by angle theta about x, y, or z. This is based on
* Cliff Rohlich's rotmat.
*
* @param[in] naxis rotation axis. if 1 then x. if 2 then y. if 3 then z.
* @param[in] theta rotation angle (degrees)
* @param[out] r rotation matrix [3 x 3] in column major format.
* @param[out] rt tranpsose rotation matrix [3 x 3] in column major format.
*
* @author Ben Baker
*
* @copyright BSD
*
*/
static void rotmat(const int naxis, const double theta,
double *__restrict__ r,
double *__restrict__ rt)
{
double cosThetar, sinThetar, thetar;
int i, j;
const double degrad = M_PI/180.0;
memset(r, 0, 9*sizeof(double));
thetar = theta*degrad;
cosThetar = cos(thetar);
sinThetar = sin(thetar);
r[0] = cosThetar;
r[4] = cosThetar;
r[8] = cosThetar;
// naxis = x
if (naxis == 1)
{
r[0] = 1.0; // (1, 1)
r[5] = sinThetar; // (3, 2)
r[7] =-sinThetar; // (2, 3)
}
// naxis = y
else if (naxis == 2)
{
r[2] = sinThetar; // (3, 1)
r[4] = 1.0; // (2, 2)
r[6] =-sinThetar; // (1, 3)
}
// naxis = z
else if (naxis == 3)
{
r[1] = sinThetar; // (2, 1)
r[3] =-sinThetar; // (1, 2)
r[8] = 1.0; // (3, 3)
}
// Compute the transpose
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
rt[3*i+j] = r[3*j+i];
}
}
return;
}
//============================================================================//
/*!
* @brief Find components of downward pointing unit vector pole from the
* strike and dip angles. This is based on Cliff Frolich's vecstrd.
*
* @param[in] str strike angle of pole (degrees)
* @param[in] dip dip angle of pole (degrees)
*
* @param[out] r corresponding unit vector pole (3)
*
* @author Ben Baker
*
* @copyright BSD
*
*/
static void vecstrd(const double str, const double dip, double r[3])
{
double cosdip, cosstr, diprad, sindip, sinstr, strrad;
const double degrad = M_PI/180.0;
// convert to radians
strrad = str*degrad;
diprad = dip*degrad;
// compute cosines and sines
sinstr = sin(strrad);
cosstr = cos(strrad);
cosdip = cos(diprad);
sindip = sin(diprad);
// compute (x,y,z) from strike and dip for unit radius
r[0] = sinstr*cosdip;
r[1] = cosstr*cosdip;
r[2] =-sindip;
return;
}
//============================================================================//
static void isItNear(const double *__restrict__ pt,
double *howClose,
double *__restrict__ ptold)
{
*howClose = dot3(ptold, pt); //cblas_ddot(3, ptold, 1, pt, 1);
ptold[0] = pt[0];
ptold[1] = pt[1];
ptold[2] = pt[2];
return;
}
/*!
* @brief Finds the strike and dip of downward pointing unit vector. This
* is based on Cliff Frolich's strdvec.
*
* @param[in,out] r on input contains the downward pointing unit
* vector.
* if r[2] is > 0 then the unit vector is pointing
* updward. in this case then on output r3 will
* be negated.
*
* @param[out] str strike angle (degrees) \f$ s.t. \phi \in [0,360] \f$.
* @param[out] dip dip angle (degrees)
*
* @author Ben Baker
*
* @copyright BSD
*
*/
static void strdvec(double r[3], double *str, double *dip)
{
double rs;
const double degradi = 180.0/M_PI;
if (r[2] > 0.0)
{
r[0] =-r[0];
r[1] =-r[1];
r[2] =-r[2];
}
*str = atan2(r[0], r[1])*degradi;
if (*str < 0.){*str = *str + 360.;}
rs = sqrt(r[0]*r[0] + r[1]*r[1]);
*dip=atan2(-r[2], rs)*degradi;
return;
}
/*!
* @brief Cross product of 2 length 3 vectors u and v. Returns normal vector n.
*
* @param[in] u first vector in cross product u x v [3]
* @param[in] v second vector in cross product u x v [3]
*
* @param[out] n normal vector n = u x v [3]
*
* @author Ben Baker
*
* @copyright BSD
*
*/
static void crossp(const double *__restrict__ u,
const double *__restrict__ v,
double *__restrict__ n)
{
n[0] = u[1]*v[2] - u[2]*v[1];
n[1] = u[2]*v[0] - u[0]*v[2];
n[2] = u[0]*v[1] - u[1]*v[0];
return;
}
/*!
* @brief Finds strike and dip given components of unit vector. This is
* based on Cliff Frohlich's strdv.
*
* @param[in] r unit vector
* @param[out] str strike angle (degrees)
* @param[out] dip dip angle (degrees) s.t. dip down is positive
*
* @author Ben Baker
*
* @copyright BSD
*
*/
static void strdv(const double r[3], double *str, double *dip)
{
double rs;
const double degradi = 180.0/M_PI;
*str = atan2(r[0], r[1])*degradi;
rs = sqrt(r[0]*r[0] + r[1]*r[1]);
*dip = atan2(-r[2], rs)*degradi;
return;
}
/*!
* @brief Utility function for computing dot product of length 3 vector
*/
static double dot3(const double *__restrict__ x,
const double *__restrict__ y)
{
double dot;
dot = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
return dot;
}
/*!
* @brief Utility function for computing y = Ax for 3 x 3 matrix.
*/
static void gemv3(const double *__restrict__ A, const double *__restrict__ x,
double *__restrict__ y)
{
y[0] = A[0]*x[0] + A[3]*x[1] + A[6]*x[2];
y[1] = A[1]*x[0] + A[4]*x[1] + A[7]*x[2];
y[2] = A[2]*x[0] + A[5]*x[1] + A[8]*x[2];
return;
}
| {
"alphanum_fraction": 0.5041604625,
"avg_line_length": 37.835956918,
"ext": "c",
"hexsha": "7b36509686211bfc11ac4732d710fc6c8d25ddc0",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_forks_repo_licenses": [
"Intel"
],
"max_forks_repo_name": "bakerb845/parmt",
"max_forks_repo_path": "postprocess/beachball.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Intel"
],
"max_issues_repo_name": "bakerb845/parmt",
"max_issues_repo_path": "postprocess/beachball.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": "postprocess/beachball.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 13789,
"size": 45668
} |
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include "parmt_polarity.h"
#ifdef PARMT_USE_INTEL
#include <mkl_cblas.h>
#else
#include <cblas.h>
#endif
#include "ttimes.h"
#include "iscl/array/array.h"
#include "iscl/geodetic/geodetic.h"
#include "iscl/memory/memory.h"
#define LDG 8
#ifndef MAX
#define MAX(x,y) (((x) > (y)) ? (x) : (y))
#endif
static void fillBasis(const double i, const double phi,
double *__restrict__ gam,
double *__restrict__ phat,
double *__restrict__ phihat);
static double computeContraction3x3(const double *__restrict__ a,
const double *__restrict__ M,
const double *__restrict__ b);
static void setM3x3(const int k, double *__restrict__ M);
static int computePadding64f(const int n);
static int performPolaritySearch64f(const int nmt, const int ldm,
const int nobs,
const int blockSize, const int mblock,
const int Mrows, const int Kcols,
const double *__restrict__ Dmat,
const double *__restrict__ G,
const double *__restrict__ Sigma,
const double *__restrict__ mts,
double *__restrict__ phi);
/*!
* @brief Driver routine for computing the polarity Green's functions from the
* ttimes ak135 global travel time table.
*
* @param[in] globalComm Global MPI communicator.
* @param[in] parms Contains the polarity modeling parameters.
* @param[in] data The SAC data whose header information will define
* the polarity and channel information.
*
* @param[out] polarityData On exit contains the corresponding polarity Green's
* functions that can be used by the grid-search to
* estimate polarities from a given moment tensor.
*
* @result 0 indicates success.
*/
int parmt_polarity_computeTTimesGreens(
const MPI_Comm globalComm,
const struct parmtPolarityParms_struct parms,
const struct parmtData_struct data,
struct polarityData_struct *polarityData)
{
char kt0[8], kcmpnm[8], stat[8];
double G6[6], *cmpazs, *cmpincs, *deps, *evlas, *evlos,
*GxxBuf, *GyyBuf, *GzzBuf, *GxyBuf, *GxzBuf, *GyzBuf,
*stlas, *stlos, cmpinc, cmpincSAC, cmpaz, stla, stlo;
int *icomps, *observation, *polarity, *waveType, icomp, ierr, ierrAll,
iloc, iobs, ipol, it, iwav, jloc, k, kt, myid, nPolarity, nprocs;
size_t lenos;
const int master = 0;
const int nTimeVars = 11;
const enum sacHeader_enum timeVarNames[11]
= {SAC_CHAR_KA,
SAC_CHAR_KT0, SAC_CHAR_KT1, SAC_CHAR_KT2, SAC_CHAR_KT3,
SAC_CHAR_KT4, SAC_CHAR_KT5, SAC_CHAR_KT6, SAC_CHAR_KT7,
SAC_CHAR_KT8, SAC_CHAR_KT9};
//------------------------------------------------------------------------//
//
// Initialize
ierr = 0;
cmpazs = NULL;
cmpincs = NULL;
deps = NULL;
evlas = NULL;
evlos = NULL;
GxxBuf = NULL;
GyyBuf = NULL;
GzzBuf = NULL;
GxyBuf = NULL;
GxzBuf = NULL;
GyzBuf = NULL;
icomps = NULL;
observation = NULL;
polarity = NULL;
stlas = NULL;
stlos = NULL;
waveType = NULL;
memset(polarityData, 0, sizeof(struct polarityData_struct));
// ttimes uses read-only file-io and i don't want to fix it
MPI_Comm_rank(globalComm, &myid);
MPI_Comm_size(globalComm, &nprocs);
//if (myid != master){goto WAIT;}
// Verify there is a chance for something to do
if (data.nobs < 1 || data.nlocs < 1)
{
if (data.nobs < 1){fprintf(stderr, "%s: No observations\n", __func__);}
if (data.nlocs < 1){fprintf(stderr, "%s: No locations\n", __func__);}
return 0;
}
// Extract the depths in the grid-search from the first waveform
iobs = 0;
deps = memory_calloc64f(data.nlocs);
evlas = memory_calloc64f(data.nlocs);
evlos = memory_calloc64f(data.nlocs);
for (iloc=0; iloc<data.nlocs; iloc++)
{
k = iobs*data.nlocs + iloc;
ierr = sacio_getFloatHeader(SAC_FLOAT_EVDP, data.sacGxx[k].header,
&deps[iloc]);
ierr += sacio_getFloatHeader(SAC_FLOAT_EVLA, data.sacGxx[k].header,
&evlas[iloc]);
ierr += sacio_getFloatHeader(SAC_FLOAT_EVLO, data.sacGxx[k].header,
&evlos[iloc]);
if (ierr != 0)
{
fprintf(stderr, "%s: Unable to get event coordinates on %d\n",
__func__, myid);
goto ERROR;
}
}
// Compute the number of usable polarities (i.e. observations with P picks
// or S picks with first motions)
nPolarity = 0;
if (myid == master)
{
polarity = memory_calloc32i(data.nobs);
waveType = memory_calloc32i(data.nobs);
icomps = memory_calloc32i(data.nobs);
stlas = memory_calloc64f(data.nobs);
stlos = memory_calloc64f(data.nobs);
cmpazs = memory_calloc64f(data.nobs);
cmpincs = memory_calloc64f(data.nobs);
observation = array_set32i(data.nobs, -1, &ierr);
for (iobs=0; iobs<data.nobs; iobs++)
{
// Ensure the essential preliminary information is defined
ierr = sacio_getFloatHeader(SAC_FLOAT_CMPINC,
data.data[iobs].header, &cmpincSAC);
ierr += sacio_getFloatHeader(SAC_FLOAT_CMPAZ,
data.data[iobs].header, &cmpaz);
ierr += sacio_getFloatHeader(SAC_FLOAT_STLA,
data.data[iobs].header, &stla);
ierr += sacio_getFloatHeader(SAC_FLOAT_STLO,
data.data[iobs].header, &stlo);
ierr += sacio_getCharacterHeader(SAC_CHAR_KCMPNM,
data.data[iobs].header, kcmpnm);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to get header information\n",
__func__);
continue;
}
// Figure out the component
ierr = parmt_utils_getComponent(kcmpnm, cmpincSAC, &icomp);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to classify component\n", __func__);
}
// SAC to SEED convention
cmpinc = cmpincSAC - 90.0;
// Figure out the component
/*
lenos = MAX(1, strlen(kcmpnm));
icomp = 1;
if (kcmpnm[lenos-1] == 'Z' || kcmpnm[lenos-1] == '1')
{
icomp = 1;
}
else if (kcmpnm[lenos-1] == 'N' || kcmpnm[lenos-1] == '2')
{
icomp = 2;
}
else if (kcmpnm[lenos-1] == 'E' || kcmpnm[lenos-1] == '3')
{
icomp = 3;
}
else
{
fprintf(stderr, "%s: Cannot classify component %s\n", __func__, kcmpnm);
continue;
}
*/
// Get the primary pick
for (it=0; it<nTimeVars; it++)
{
ierr = sacio_getCharacterHeader(timeVarNames[it],
data.data[iobs].header,
kt0);
if (ierr == 0){break;}
}
lenos = strlen(kt0);
// Ensure the pick is defined
if (ierr == 0 && lenos > 1)
{
iwav = 1;
if (kt0[0] == 'P' || kt0[0] == 'p')
{
iwav = 1;
}
else if (kt0[0] == 'S' || kt0[0] == 's')
{
iwav = 2;
}
else
{
// surface waves will commonly be processed and not
// have polarities
if (kt0[0] == 'R' || kt0[0] == 'r' ||
kt0[0] == 'L' || kt0[0] == 'l')
{
continue;
}
fprintf(stderr, "%s: t0 phase is not a P or S phase %s\n",
__func__, kt0);
continue;
}
if (kt0[lenos-1] == '+')
{
ipol = 1;
}
else if (kt0[lenos-1] == '-')
{
ipol =-1;
}
else
{
fprintf(stderr, "%s: could not classify polarity %s\n",
__func__, kt0);
continue;
}
// let user know something happened
sacio_getCharacterHeader(SAC_CHAR_KSTNM,
data.data[iobs].header, stat);
fprintf(stdout, "%s: Polarity for %s is %d\n",
__func__, stat, ipol);
//printf("%f %f %f %f %d %d %d %d\n", stla, stlo, cmpinc, cmpaz, icomp, iobs, iwav, ipol);
// save information for modeling
stlas[nPolarity] = stla;
stlos[nPolarity] = stlo;
cmpincs[nPolarity] = cmpinc;
cmpazs[nPolarity] = cmpaz;
icomps[nPolarity] = icomp;
observation[nPolarity] = iobs;
waveType[nPolarity] = iwav;
polarity[nPolarity] = ipol;
nPolarity = nPolarity + 1;
//printf("%d %d %f %f\n", iwav, ipol, cmpinc, cmpaz);
} // End basic header info check
} // Loop on observations
} // End check on myid == master
// Tell all other processes about the forward modeling information
MPI_Bcast(&nPolarity, 1, MPI_INT, master, globalComm);
if (nPolarity == 0)
{
if (myid == master)
{
fprintf(stdout, "%s: There are no polarities\n", __func__);
}
ierr = 0;
goto ERROR;
}
if (myid != master)
{
stlas = memory_calloc64f(nPolarity);
stlos = memory_calloc64f(nPolarity);
cmpincs = memory_calloc64f(nPolarity);
cmpazs = memory_calloc64f(nPolarity);
icomps = memory_calloc32i(nPolarity);
observation = memory_calloc32i(nPolarity);
waveType = memory_calloc32i(nPolarity);
polarity = memory_calloc32i(nPolarity);
}
else
{
fprintf(stdout, "%s: Warning - i'm setting wts to unity for now\n",
__func__);
}
MPI_Bcast(stlas, nPolarity, MPI_DOUBLE, master, globalComm);
MPI_Bcast(stlos, nPolarity, MPI_DOUBLE, master, globalComm);
MPI_Bcast(cmpincs, nPolarity, MPI_DOUBLE, master, globalComm);
MPI_Bcast(cmpazs, nPolarity, MPI_DOUBLE, master, globalComm);
MPI_Bcast(icomps, nPolarity, MPI_INT, master, globalComm);
MPI_Bcast(observation, nPolarity, MPI_INT, master, globalComm);
MPI_Bcast(waveType, nPolarity, MPI_INT, master, globalComm);
MPI_Bcast(polarity, nPolarity, MPI_INT, master, globalComm);
// Set space
ierrAll = 0;
GxxBuf = memory_calloc64f(data.nlocs*nPolarity);
GyyBuf = memory_calloc64f(data.nlocs*nPolarity);
GzzBuf = memory_calloc64f(data.nlocs*nPolarity);
GxyBuf = memory_calloc64f(data.nlocs*nPolarity);
GxzBuf = memory_calloc64f(data.nlocs*nPolarity);
GyzBuf = memory_calloc64f(data.nlocs*nPolarity);
polarityData->Gxx = memory_calloc64f(data.nlocs*nPolarity);
polarityData->Gyy = memory_calloc64f(data.nlocs*nPolarity);
polarityData->Gzz = memory_calloc64f(data.nlocs*nPolarity);
polarityData->Gxy = memory_calloc64f(data.nlocs*nPolarity);
polarityData->Gxz = memory_calloc64f(data.nlocs*nPolarity);
polarityData->Gyz = memory_calloc64f(data.nlocs*nPolarity);
// Set the data
polarityData->polarity = memory_calloc64f(nPolarity);
for (ipol=0; ipol<nPolarity; ipol++)
{
polarityData->polarity[ipol] = (double) polarity[ipol];
}
// Set the weights
// TODO fix me
polarityData->wts = array_set64f(nPolarity, 1.0, &ierr);
// Compute the forward modeling matrix columns
for (jloc=0; jloc<data.nlocs; jloc=jloc+nprocs)
{
iloc = jloc + myid;
if (iloc >= data.nlocs){continue;}
// Compute the forward modeling matrix for this observation group
for (ipol=0; ipol<nPolarity; ipol++)
{
kt = iloc*nPolarity + ipol;
ierr = parmt_polarity_computeGreensRowFromTtimes(
waveType[ipol], icomps[ipol],
evlas[iloc], evlos[iloc], deps[iloc],
stlas[ipol], stlos[ipol],
cmpincs[ipol], cmpazs[ipol],
parms.ttimesTablesDir,
parms.ttimesModel,
G6);
if (ierr != 0)
{
fprintf(stderr,
"%s: Error computing polarities %d %d on PID %d\n",
__func__, iloc, ipol, myid);
ierrAll = ierrAll + 1;
continue;
}
// Save it
GxxBuf[kt] = G6[0];
GyyBuf[kt] = G6[1];
GzzBuf[kt] = G6[2];
GxyBuf[kt] = G6[3];
GxzBuf[kt] = G6[4];
GyzBuf[kt] = G6[5];
//printf("%f %f %f %e %e %e %e %e %e\n", stlas[ipol], stlos[ipol], deps[iloc], G6[0], G6[1], G6[2], G6[3], G6[4], G6[5]);
} // Loop on the polarities
//printf("\n");
} // Loop on the locations
ierr = ierrAll;
if (ierr != 0)
{
fprintf(stderr, "%s: Error computing polarities from ttimes\n",
__func__);
ierr = 1;
goto ERROR;
}
polarityData->nPolarity = nPolarity;
polarityData->nlocs = data.nlocs;
polarityData->nobs = data.nobs;
polarityData->obsMap = array_copy32i(nPolarity, observation, &ierr);
MPI_Allreduce(GxxBuf, polarityData->Gxx, data.nlocs*nPolarity,
MPI_DOUBLE, MPI_SUM, globalComm);
MPI_Allreduce(GyyBuf, polarityData->Gyy, data.nlocs*nPolarity,
MPI_DOUBLE, MPI_SUM, globalComm);
MPI_Allreduce(GzzBuf, polarityData->Gzz, data.nlocs*nPolarity,
MPI_DOUBLE, MPI_SUM, globalComm);
MPI_Allreduce(GxyBuf, polarityData->Gxy, data.nlocs*nPolarity,
MPI_DOUBLE, MPI_SUM, globalComm);
MPI_Allreduce(GxzBuf, polarityData->Gxz, data.nlocs*nPolarity,
MPI_DOUBLE, MPI_SUM, globalComm);
MPI_Allreduce(GyzBuf, polarityData->Gyz, data.nlocs*nPolarity,
MPI_DOUBLE, MPI_SUM, globalComm);
// Finally assemble Green's functions into modeling matrix
//WAIT:;
ERROR:;
MPI_Barrier(globalComm);
// free memory
memory_free64f(&GxxBuf);
memory_free64f(&GyyBuf);
memory_free64f(&GzzBuf);
memory_free64f(&GxyBuf);
memory_free64f(&GxzBuf);
memory_free64f(&GyzBuf);
memory_free64f(&deps);
memory_free64f(&evlas);
memory_free64f(&evlos);
memory_free64f(&stlas);
memory_free64f(&stlos);
memory_free64f(&cmpincs);
memory_free64f(&cmpazs);
memory_free32i(&observation);
memory_free32i(&polarity);
memory_free32i(&icomps);
memory_free32i(&waveType);
return ierr;
}
//============================================================================//
/*!
* @brief Computes the row of the Green's functions matrix for modeling
* a polarity from the ttimes model.
*
* @param[in] data Contains the pick type and channel information.
* @param[in] wavetype P_WAVE (1) indicates a P-wave.
* @param[in] wavetype S_WAVE (2) indicates an S-wave.
* @param[in] evdp Depth of the event in kilometers.
* @param[in] dirnm Directory containing the iasp-tau binary files.
* @param[in] model Name of the model, e.g., ak135.
*
* @param[out] G On exit contains the Green's functions so that for
* the i'th row of G, \f$ G_i \cdot \textbf{m} \f$
* computes an estimate of polarity. This is packed
* in order
* \f$
* \{m_{xx}, m_{yy}, m_{zz}, m_{xy}, m_{xz}, m_{yz} \}
* \f$
* and must have a dimension of at least [6].
*
* @result 0 indicates success.
*
* @copyright ISTI distributed under the Apache 2 license.
*
*/
int parmt_polarity_computeGreensRowFromData(const struct sacData_struct data,
const int wavetype,
const double evdp,
const char *dirnm,
const char *model,
double *__restrict__ G)
{
char kcmpnm[16];
double cmpaz, cmpinc, cmpincSAC, evla, evlo, stla, stlo;
int icomp, ierr;
size_t lenos;
memset(kcmpnm, 16, 16*sizeof(char));
ierr = sacio_getFloatHeader(SAC_FLOAT_CMPINC, data.header, &cmpincSAC);
ierr += sacio_getFloatHeader(SAC_FLOAT_CMPAZ, data.header, &cmpaz);
ierr += sacio_getFloatHeader(SAC_FLOAT_EVLA, data.header, &evla);
ierr += sacio_getFloatHeader(SAC_FLOAT_EVLO, data.header, &evlo);
ierr += sacio_getFloatHeader(SAC_FLOAT_STLA, data.header, &stla);
ierr += sacio_getFloatHeader(SAC_FLOAT_STLO, data.header, &stlo);
ierr += sacio_getCharacterHeader(SAC_CHAR_KCMPNM, data.header, kcmpnm);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to get header information\n", __func__);
return -1;
}
// Figure out the component
ierr = parmt_utils_getComponent(kcmpnm, cmpincSAC, &icomp);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to classify component\n", __func__);
return -1;
}
// SAC to SEED convention
cmpinc = cmpincSAC - 90.0;
// Figure out the component
lenos = MAX(1, strlen(kcmpnm));
icomp = 1;
if (kcmpnm[lenos-1] == 'Z' || kcmpnm[lenos-1] == '1')
{
icomp = 1;
}
else if (kcmpnm[lenos-1] == 'N' || kcmpnm[lenos-1] == '2')
{
icomp = 2;
}
else if (kcmpnm[lenos-1] == 'E' || kcmpnm[lenos-1] == '3')
{
icomp = 3;
}
else
{
fprintf(stderr, "%s: Can't classify component %s\n", __func__, kcmpnm);
return -1;
}
ierr = parmt_polarity_computeGreensRowFromTtimes(wavetype, icomp,
evla, evlo, evdp,
stla, stlo,
cmpinc, cmpaz,
dirnm, model,
G);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to compute G\n", __func__);
}
return ierr;
}
//============================================================================//
/*!
* @brief Computes a row of the Green's functions matrix from ttimes
*
* @param[in] wavetype If 1 then this is a P wave.
* @param[in] wavetype If 2 then this is an S wave.
* @param[in] icomp If 1 then this is the vertical channel.
* @param[in] icomp If 2 then this is the north (1 or 2) channel.
* @param[in] icomp If 3 then this is the east (2 or 3) channel.
* @param[in] evla Event latitude (degrees).
* @param[in] evlo Event longitude (degrees).
* @param[in] evdp Event depth (km).
* @param[in] stla Station latitude (degrees).
* @param[in] stlo Station longitude (degrees).
* @param[in] cmpaz Component azimuth (0 north, +90 east).
* @param[in] cmpinc Component inclination (-90 up, 0 east/north, +90 down).
* @param[in] dirnm Directory containing the ttimes precomputed binary
* files. If NULL then the default as dicated by the
* ttimes configuration will be used.
* @param[in] model Model name (e.g., ak135 or iasp91)
*
* @param[out] G Row of matrix s.t. G*m produces estimates the polarity
* at the station. Here m is packed
* \f$ \{m_{xx}, m_{yy}, m_{zz},
* m_{xy}, m_{xz}, m_{yz} \} \f$
* This must have dimension of at least 6.
*
* @author Ben Baker
*
* @copyright ISTI distributed under Apache 2
*
*/
int parmt_polarity_computeGreensRowFromTtimes(
const int wavetype, const int icomp,
const double evla, const double evlo, const double evdp,
const double stla, const double stlo,
const double cmpinc, const double cmpaz,
const char *dirnm, const char *model,
double *__restrict__ G)
{
double aoiRec, az, azSrc, baz, bazRec, dist, delta, toaSrc;
struct ttimesTravelTime_struct ttime;
int ierr;
ierr = 0;
if (G == NULL)
{
fprintf(stderr, "%s: Error G is NULL\n", __func__);
return -1;
}
memset(G, 0, 6*sizeof(double));
if (evdp < 0.0 || evdp > ttimes_getMaxDepth())
{
fprintf(stderr, "%s: Error depth must be between [0,%f]\n", __func__,
ttimes_getMaxDepth());
return -1;
}
memset(&ttime, 0, sizeof(struct ttimesTravelTime_struct));
geodetic_gps2distanceAzimuth(evla, evlo, stla, stlo,
&dist, &delta, &az, &baz);
if (wavetype == 1)
{
ierr = ttimes_getFirstPPhase(delta, evdp, dirnm, model, &ttime);
}
else if (wavetype == 2)
{
ierr = ttimes_getFirstSPhase(delta, evdp, dirnm, model, &ttime);
}
else
{
fprintf(stderr, "%s: Invalid phase type - must be 1 (P) or 2 (S)\n",
__func__);
return -1;
}
if (ierr != 0)
{
fprintf(stderr, "%s: Error computing theoretical traveltime info\n",
__func__);
return -1;
}
// Compute the column in the Green's function matrix
toaSrc = ttime.toang;
azSrc = az;
bazRec = baz;
aoiRec = ttime.aoi;
//printf("%f %f %f %f %f %f %f\n", delta, stla, stlo, toaSrc, azSrc, aoiRec, bazRec);
ierr = parmt_polarity_computeGreensMatrixRow(wavetype, icomp,
azSrc, toaSrc, bazRec, aoiRec,
cmpinc, cmpaz, G);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to compute polarity for row\n", __func__);
memset(G, 0, 6*sizeof(double));
return -1;
}
return 0;
}
//============================================================================//
/*!
* @brief Computes a column for the Green's function s.t. G*m produces an
* estimate of polarity on the icomp'th component measured in the
* far-field. The moment tensor which would be applied to this row
* is packed:
* \f$ \{m_{xx}, m_{yy}, m_{zz}, m_{xy}, m_{xz}, m_{yz} \} \f$
* with convention North, East, Down (e.g., Jost and Herrmann).
* For more see Quantitative Seismology - Aki and Richards 2002,
* Eqn 4.96 on pg 111 and Source Mechanisms of Earthquakes: Theory
* and Practice - Udias et al. pg 100..
*
* @param[in] wavetype =1 -> P wave
* =2 -> S wave
* @param[in] icomp receiver component of motion:
* =1 -> Vertical channel
* =2 -> 1 or North channel
* =3 -> 2 or East channel
* @param[in] azSrc source to receiver azimuth is measured positive from
* north (degrees)
* @param[in] toaSrc take-off angle (measured positive from x3 where x3
* points down) (degrees)
* @param[in] bazRec receiver to source back azimuth measured positive
* from north (degrees)
* @param[in] aoiRec angle of incidence at receiver
* @param[in] cmpaz component azimuth (0 north, +90 east)
* @param[in] cmpinc component inclinantion (-90 up, 0 east/north, +90 down)
*
* @param[out] G row of matrix s.t. G*m produces estimates the polarity
* at the station. Here m is packed
* \f$ \{m_{xx}, m_{yy}, m_{zz},
* m_{xy}, m_{xz}, m_{yz} \} \f$
*
* @bugs i've really only looked at the vertical p-teleseismic case - no idea
* about other phases, wavetypes
*
* @author Ben Baker
*
* @copyright ISTI distributed under Apache 2
*
*/
int parmt_polarity_computeGreensMatrixRow(const int wavetype,
const int icomp,
const double azSrc,
const double toaSrc,
const double bazRec,
const double aoiRec,
const double cmpinc,
const double cmpaz,
double *__restrict__ G)
{
double M[9], G63[18], up[6], ush[6], usv[6],
gam[3], lhat[3], phat[3], phihat[3],
cosba, cos_cmpaz, cost_rec,
r11, r12, r13, r21, r22, r23, r31, r32, r33,
sinba, sin_cmpaz,
sint_rec,
t1, t2, t3, theta, xsign, u1, u2, ue, un, uz;
int k;
const double pi180 = M_PI/180.0;
const bool lrot = true;//false;
const int P_WAVE = 1;
const int S_WAVE = 2;
//------------------------------------------------------------------------//
//
// Error check
if (icomp < 1 || icomp > 3)
{
fprintf(stderr, "%s: Invalid component\n", __func__);
return -1;
}
if (wavetype < P_WAVE || wavetype > S_WAVE)
{
fprintf(stderr, "%s: Invalid wavetype\n", __func__);
return -1;
}
// Fill the basis at the source (Aki and Richards Eqn 4.88)
fillBasis(toaSrc, azSrc, gam, phat, phihat);
// Compute the contractions for u_p, u_sv, and u_sh (A&R Eqn 4.96)
// for all 6 individual moment tensor terms
for (k=0; k<6; k++)
{
// Set the moment tensor with the k'th mt term 1 others zero
setM3x3(k, M);
// Compute contraction
up[k] = computeContraction3x3(gam, M, gam);
usv[k] = computeContraction3x3(phat, M, gam);
ush[k] = computeContraction3x3(phihat, M, gam);
}
// Fill the basis at the receiver - notice the basis uses the forward
// azimuth from the receiver to the source
fillBasis(aoiRec, (bazRec + 180.0), lhat, phat, phihat);
// Compute geometric factors at receiver
//printf("%f %f %f %f %f\n", toaSrc, azSrc, bazRec, aoiRec, cmpaz);
theta = aoiRec*pi180;
cosba = cos(bazRec*pi180);
cost_rec = cos(theta);
sinba = sin(bazRec*pi180);
sint_rec = sin(theta);
cos_cmpaz = cos(cmpaz*pi180);
sin_cmpaz = sin(cmpaz*pi180);
// Set 3D rotation matrix
r11 = cost_rec;
r21 = sint_rec;
r31 = 0.0;
r12 =-sint_rec*sinba;
r22 = cost_rec*sinba;
r32 = -cosba;
r13 =-sint_rec*cosba;
r23 = cost_rec*cosba;
r33 = sinba;
// Flip sign for receivers that acquire positive down
xsign = 1.0;
if (fabs(cmpinc - 90.0) < 1.e-4){xsign =-1.0;}
// Compute 6 x 3 subforward modeling matrix with row for up (1 channel)
if (wavetype == P_WAVE)
{
// Loop on mts terms
for (k=0; k<6; k++)
{
// Extract the (north, east, down) component
t3 =-up[k]*lhat[0]; // z-down -> z-up
//t3 = up[k]*lhat[0]; // z-up
t2 = up[k]*lhat[1]; // east
t1 = up[k]*lhat[2]; // north
// Not sure if i have to rotate LQT -> ZNE
if (lrot)
{
uz = t1*r11 + t2*r21 + t3*r31; // Z
ue = t1*r12 + t2*r22 + t3*r32; // E
un = t1*r13 + t2*r23 + t3*r33; // N
}
else
{
uz = t3;
ue = t2;
un = t1;
}
// Rotate into (1, 2)
u1 = un*cos_cmpaz + ue*sin_cmpaz;
u2 =-un*sin_cmpaz + ue*cos_cmpaz;
// Finish
G63[k*3+0] = xsign*uz;
//G63[k*3+0] =-xsign*uz;
G63[k*3+1] = u1;
G63[k*3+2] = u2;
}
}
// SH wave
else
{
// Loop on mts terms
for (k=0; k<6; k++)
{
// Extract the (north, east, down) component
t3 =-usv[k]*phat[0] - ush[k]*phihat[0]; // z-down -> z-up
t2 = usv[k]*phat[1] + ush[k]*phihat[1]; // east
t1 = usv[k]*phat[2] + ush[k]*phihat[2]; // north
// Not sure if i have to rotate LQT -> ZNE
if (lrot)
{
uz = t1*r11 + t2*r21 + t3*r31; // Z
ue = t1*r12 + t2*r22 + t3*r32; // E
un = t1*r13 + t2*r23 + t3*r33; // N
}
else
{
uz = t3;
ue = t2;
un = t1;
}
// Rotate into (1, 2)
u1 = un*cos_cmpaz + ue*sin_cmpaz;
u2 =-un*sin_cmpaz + ue*cos_cmpaz;
// Finish
G63[k*3+0] = xsign*uz;
G63[k*3+1] = u1;
G63[k*3+2] = u2;
}
}
// Copy the result - vertical
if (icomp == 1)
{
for (k=0; k<6; k++)
{
G[k] = G63[k*3+0];
}
}
// 1 component
else if (icomp == 2)
{
for (k=0; k<6; k++)
{
G[k] = G63[k*3+1];
}
}
// 2 component
else if (icomp == 3)
{
for (k=0; k<6; k++)
{
G[k] = G63[k*3+2];
}
}
return 0;
}
//============================================================================//
/*!
* @brief Fills in the basis vectors - Aki and Richards pg 108 Eqn 4.88.
*
* @param[in] i Take-off angle (degrees).
* @param[in] phi Azimuth angle (degrees).
* @param[in] gam P-wave direction. This has dimension [3].
* @param[in] phat SV-wave direction. This has dimension [3].
* @param[in] phihat SH-wave direction. This has dimension [3].
*
* @copyright ISTI distributed under the Apache 2 license.
*
*/
static void fillBasis(const double i, const double phi,
double *__restrict__ gam,
double *__restrict__ phat,
double *__restrict__ phihat)
{
double cosi, sini, cosp, sinp;
const double pi180 = M_PI/180.0;
cosi = cos(i*pi180);
sini = sin(i*pi180);
cosp = cos(phi*pi180);
sinp = sin(phi*pi180);
gam[0] = sini*cosp;
gam[1] = sini*sinp;
gam[2] = cosi;
phat[0] = cosi*cosp;
phat[1] = cosi*sinp;
phat[2] =-sini;
phihat[0] =-sinp;
phihat[1] = cosp;
phihat[2] = 0.0;
}
//============================================================================//
/*!
* @brief Sets the moment tensor matrix where the k'th moment tensor
* term is 1 and others are zero. Here moment tensor terms
* are counted {0,1,2,3,4,5} = {xx,yy,zz,xy,xz,yz}
*
* @param[in] k Moment tensor index. This is in the range [0,5] and follows
* the mapping {0,1,2,3,4,5} = {xx,yy,zz,xy,xz,yz}.
*
* @param[out] M The 3x3 NED moment tensor. This is an array of dimension [9].
*
*/
static void setM3x3(const int k, double *__restrict__ M)
{
memset(M, 0, 9*sizeof(double));
// mxx (fill mtt)
if (k == 0)
{
M[4] = 1.0; //M[0][0] = 1.0;
}
// myy (fill mpp)
else if (k == 1)
{
M[8] = 1.0; //M[1][1] = 1.0;
}
// mzz (fill mrr)
else if (k == 2)
{
M[0] = 1.0; //M[2][2] = 1.0;
}
// mxy and myz (fill mtp)
else if (k == 3)
{
M[5] =-1.0; //M[0][1] = 1.0;
M[7] =-1.0; //M[1][0] = 1.0;
}
// mxz and mzx (fill mrp)
else if (k == 4)
{
M[1] = 1.0; //M[0][2] = 1.0;
M[3] = 1.0; //M[2][0] = 1.0;
}
// myz and mzy (fill mrp)
else
{
M[2] =-1.0; //M[1][2] = 1.0;
M[6] =-1.0; //M[2][1] = 1.0;
}
/*
// mxx
if (k == 0)
{
M[0] = 1.0; //M[0][0] = 1.0;
}
// myy
else if (k == 1)
{
M[4] = 1.0; //M[1][1] = 1.0;
}
// mzz
else if (k == 2)
{
M[8] = 1.0; //M[2][2] = 1.0;
}
// mxy and myz
else if (k == 3)
{
M[1] = 1.0; //M[0][1] = 1.0;
M[3] = 1.0; //M[1][0] = 1.0;
}
// mxz and mzx
else if (k == 4)
{
M[2] = 1.0; //M[0][2] = 1.0;
M[6] = 1.0; //M[2][0] = 1.0;
}
// myz and mzy
else
{
M[5] = 1.0; //M[1][2] = 1.0;
M[7] = 1.0; //M[2][1] = 1.0;
}
*/
return;
}
//============================================================================//
/*!
* @brief Computes the contraction in Aki and Richards Eqn 4.96
* for the given basis vectors and moment tensor.
*/
static double computeContraction3x3(const double *__restrict__ a,
const double *__restrict__ M,
const double *__restrict__ b)
{
double res;
int i, ij, j;
res = 0.0;
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
ij = 3*i + j;
res = res + a[i]*M[ij]*b[j];
}
}
return res;
}
//============================================================================//
/*!
* @brief Tabulates the objective function over the earthquake locations.
*
* @param[in] locComm Location MPI communicator.
* @param[in] blockSize Block-size for performing matrix-matrix
* multiplications.
* @param[in] polarityData Contains the polarity data and the Green's functions.
* @param[in] mtloc Contains the local moment tensors in this rank's
* grid search.
*
* @param[out] phi The objective function tabulated for all locations
* and moment tensors. This is only accessed by
* master process in locComm; and for this case has
* dimension [nlocs x mtloc.nmtAll] with leading
* dimension mtloc.nmtAll. Otherwise, this can be NULL.
*
* @result 0 indicates success.
*
* @copyright ISTI distributed under the Apache 2 license.
*
*/
int polarity_performLocationSearch64f(const MPI_Comm locComm,
const int blockSize,
struct polarityData_struct polarityData,
struct localMT_struct mtloc,
double *__restrict__ phi)
{
double *Dmat, *G, *Sigma, *phiLoc, *phiWork;
int icol, ierr, ierrAll, iloc, ipol, jloc, jndx,
kt, mylocID, nlocProcs, mblock, pad;
const int nPolarity = polarityData.nPolarity;
const int Mrows = nPolarity;
const int Kcols = 6;
const int nlocs = polarityData.nlocs;
const int ldm = mtloc.ldm;
const int nmt = mtloc.nmt;
const int master = 0;
// Initialize
ierr = 0;
ierrAll = 0;
MPI_Comm_size(locComm, &nlocProcs);
MPI_Comm_rank(locComm, &mylocID);
// Compute padding for 64 bit data alignment in observations and mt blocks
pad = computePadding64f(blockSize);
mblock = blockSize + pad;
// Set space
phiLoc = memory_calloc64f(nmt);
G = memory_calloc64f(nPolarity*LDG);
Dmat = memory_calloc64f(nPolarity*mblock);
Sigma = array_set64f(nPolarity, 1.0, &ierr); // Default to identity
phiWork = memory_calloc64f(nlocs*mtloc.nmtAll);
// Set the row major data matrix where each row is an observation
for (ipol=0; ipol<nPolarity; ipol++)
{
for (icol=0; icol<mblock; icol++)
{
Dmat[ipol*mblock+icol] = polarityData.polarity[ipol];
if (icol == 1){printf("%f\n", polarityData.polarity[ipol]);}
}
}
// Input weights are given - copy them to diagonal weight matrix
if (polarityData.wts != NULL)
{
ierr = array_copy64f_work(nPolarity, polarityData.wts, Sigma);
}
// Loop on the source locations in the grid search
for (jloc=0; jloc<nlocs; jloc=jloc+nlocProcs)
{
iloc = jloc + mylocID;
kt = iloc*nPolarity;
// Assemble the row major Green's functions matrix
array_zeros64f_work(LDG*nPolarity, G);
#pragma omp simd
for (ipol=0; ipol<nPolarity; ipol++)
{
G[LDG*ipol+0] = polarityData.Gxx[kt+ipol];
G[LDG*ipol+1] = polarityData.Gyy[kt+ipol];
G[LDG*ipol+2] = polarityData.Gzz[kt+ipol];
G[LDG*ipol+3] = polarityData.Gxy[kt+ipol];
G[LDG*ipol+4] = polarityData.Gxz[kt+ipol];
G[LDG*ipol+5] = polarityData.Gyz[kt+ipol];
}
// Perform the polarity search for all mt's at this location
ierr = performPolaritySearch64f(nmt, ldm,
nPolarity,
blockSize, mblock,
Mrows, Kcols,
Dmat, G, Sigma, mtloc.mts,
phiLoc);
if (ierr != 0)
{
fprintf(stderr, "%s: Error in mt polarity search\n", __func__);
ierrAll = ierrAll + 1;
}
// Gather the moment tensor search results onto the master
jndx = 0;
if (mtloc.myid == master){jndx = iloc*mtloc.nmtAll;}
if (mtloc.commSize == 1)
{
array_copy64f_work(mtloc.nmt, phiLoc, &phiWork[jndx]);
}
else
{
MPI_Gatherv(phiLoc, mtloc.nmt, MPI_DOUBLE,
&phiWork[jndx], mtloc.nmtProc, mtloc.offset,
MPI_DOUBLE, master, mtloc.comm);
}
fprintf(stdout, "%s: mylocID: %d min: %f max: %f\n",
__func__, mylocID, array_min64f(nmt, phiLoc, &ierr),
array_max64f(nmt, phiLoc, &ierr));
}
// Reduce the search onto the master
//if (linLocComm && mylocID == master)
{
MPI_Reduce(phiWork, phi, nlocs*mtloc.nmtAll, MPI_DOUBLE,
MPI_SUM, master, locComm);
}
// Free memory
memory_free64f(&phiWork);
memory_free64f(&phiLoc);
memory_free64f(&G);
memory_free64f(&Dmat);
memory_free64f(&Sigma);
return 0;
}
//============================================================================//
/*!
* @brief Performs the polarity search for a host of moment tensors.
*
* @param[in] nmt Number of moment tensors.
* @param[in] ldm Leading dimension of moment tensor matrix. This must
* be at least 6.
* @param[in] nPolarity The number of polarities (observations).
* @param[in] blockSize Controls the number of forward problems GM to compute
* simultaneously.
* @param[in] mblock The largest block size. This serves as a leading
* dimension.
* @param[in] Mrows Number of rows in Green's functions matrix.
* @param[in] Kcols Number of columns in Green's functions matrix. This
* should be 6.
* @param[in] Dmat The polarity data replicated to the max block size.
* This has dimension [nPolarity x mblock] with leading
* dimension mblock.
* @param[in] G Forward modeling matrix. This has dimension
* [nPolarity x LDG] with leading dimension LDG.
* @param[in] Sigma These are the data weights and has dimension
* [nPolarity].
* @param[in] mts Matrix of moment tensors and has dimension [nmt x ldm].
* with leading dimension ldm.
*
* @param[out] phi The objective function (variance reduction) tabulated
* for all the moment tensors and observations. This has
* dimension [nmt].
*
* @result 0 indicates success.
*
* @copyright ISTI distributed under the Apache 2 license.
*
*/
static int performPolaritySearch64f(const int nmt, const int ldm,
const int nPolarity,
const int blockSize, const int mblock,
const int Mrows, const int Kcols,
const double *__restrict__ Dmat,
const double *__restrict__ G,
const double *__restrict__ Sigma,
const double *__restrict__ mts,
double *__restrict__ phi)
{
double *U, *Usign, *res2, *sqrtSigmaWt, res, traceSigma;
int i, ic, ierr, ipol, jmt, kmt, nmtBlocks, Ncols;
const double one = 1.0;
const double zero = 0.0;
ierr = 0;
nmtBlocks = (int) ((double) (nmt)/(double) (blockSize) + 1.0);
if (nmtBlocks*blockSize < nmt)
{
fprintf(stderr, "%s: Internal error - all mts wont be visited\n",
__func__);
return -1;
}
#ifdef __INTEL_COMPILER
__assume_aligned(G, 64);
__assume_aligned(Dmat, 64);
#endif
// The VR in Chiang 2016 is:
// (1 - \frac{ \sum_i w_i (Pol_{i,obs} - Pol_{i,est})^2 }
// { \sum_i w_i (Pol_{i,obs}^2) } )
// Because Pol_{obs} and Pol_{est} take values of + or -1 we can
// reduce the demoniator so that the VR is
// (1 - \frac{ \sum_i w_i (Pol_{i,obs} - Pol_{i,est})^2 }
// { \sum_i w_i })
// Furthermore, we can incorporate this term into the weighting
// function s.t. Sigma/trace(Sigma) to obtain
// (1 - \frac{ \sum_i \hat{Sigma} (Pol_{i,obs} - Pol_{i,est})^2)
// Finally, because we want likelihoods we want to rescale the
// residual squared from [0,4] to [0,1]. To do this we multiply
// the weight by 0.5 s.t. the residual [-2,2] goes to [-1,1] which,
// when squared, fits in the desired bounds of [0,1]; i.e. multiply by
// (1/2)^2 = 0.25
traceSigma = array_sum64f(nPolarity, Sigma, &ierr);
if (ierr != 0){traceSigma = 1.0;}
sqrtSigmaWt = memory_calloc64f(nPolarity);
#ifdef __INTEL_COMPILER
__assume_aligned(sqrtSigmaWt, ISCL_MEMORY_ALIGN);
#endif
for (i=0; i<nPolarity; i++){sqrtSigmaWt[i] = sqrt(0.25*Sigma[i]/traceSigma);}
#pragma omp parallel \
private (i, ic, ipol, jmt, kmt, Ncols, res, res2, U, Usign) \
shared (G, Dmat, mts, nmtBlocks, phi, sqrtSigmaWt) \
default (none) reduction(+:ierr)
{
U = memory_calloc64f(mblock*nPolarity);
res2 = memory_calloc64f(mblock);
Usign = memory_calloc64f(mblock*nPolarity);
#ifdef __INTEL_COMPILER
__assume_aligned(res2, ISCL_MEMORY_ALIGN);
__assume_aligned(Usign, ISCL_MEMORY_ALIGN);
#endif
#pragma omp for
for (kmt=0; kmt<nmtBlocks; kmt++)
{
jmt = kmt*blockSize;
Ncols = MIN(blockSize, nmt - jmt); // Number of columns of M
// Compute U = GM
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
Mrows, Ncols, Kcols, one, G, LDG,
&mts[ldm*jmt], ldm, zero, U, mblock);
// Make the theoretical polarity +1 or -1 to match the data
array_copysign64f_work(mblock*nPolarity, U, Usign);
memset(res2, 0, (size_t) mblock*sizeof(double));
// Compute the weighted residual
for (ipol=0; ipol<nPolarity; ipol++)
{
#pragma omp simd aligned(Dmat, Usign, res2: ISCL_MEMORY_ALIGN)
for (ic=0; ic<Ncols; ic++)
{
// Change residual range from [0,2] to [0,1] and weight
res = sqrtSigmaWt[ipol]*( Dmat[ipol*mblock+ic]
- Usign[ipol*mblock+ic]);
res2[ic] = res2[ic] + res*res;
}
}
// Compute the variance reduction and put it into objective function
for (ic=0; ic<Ncols; ic++)
{
phi[jmt+ic] = 1.0 - res2[ic];
}
} // Loop on moment tensor blocks
memory_free64f(&Usign);
memory_free64f(&U);
memory_free64f(&res2);
} // end parallel section
memory_free64f(&sqrtSigmaWt);
return 0;
}
static int computePadding64f(const int n)
{
size_t mod, pad;
int ipad;
// Set space and make G matrix
pad = 0;
mod = ((size_t) n*sizeof(double))%64;
if (mod != 0)
{
pad = (64 - mod)/sizeof(double);
}
ipad = (int) pad;
return ipad;
}
| {
"alphanum_fraction": 0.5154853094,
"avg_line_length": 37.3154859967,
"ext": "c",
"hexsha": "dc08bb56ebb3e04b85f845421b71c004db60e00a",
"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/polarity.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/polarity.c",
"max_line_length": 133,
"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/polarity.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 12549,
"size": 45301
} |
\documentclass{report}
\usepackage[T1]{fontenc}
\usepackage{bera}
\usepackage[pdftex,usenames,dvipsnames]{color}
\usepackage{listings}
\definecolor{mycode}{rgb}{0.9,0.9,1}
\lstset{language=c++,tabsize=1,basicstyle=\scriptsize,backgroundcolor=\color{mycode}}
\usepackage{hyperref}
\usepackage{fancyhdr}
\pagestyle{fancy}
\usepackage{verbatim}
\begin{document}
%\title{The Powell Class for Minimization of Functions}
%\author{G.A.}
%\maketitle
\begin{comment}
@o Minimizer.h -t
@{
/*
@i license.txt
*/
@}
\end{comment}
\section{A class to minimize a function without using Derivatives}
This requires the GNU Scientific Library, libraries and devel. headers.
Explain usage here. FIXME.
This is the structure of this file:
@o Minimizer.h -t
@{
#ifndef MINIMIZER_H
#define MINIMIZER_H
#include <iostream>
#include <vector>
#include <stdexcept>
extern "C" {
#include <gsl/gsl_multimin.h>
}
namespace PsimagLite {
@<MockVector@>
@<MyFunction@>
@<theClassHere@>
} // namespace PsimagLite
#endif // MINIMIZER_H
@}
And this is the class here:
@d theClassHere
@{
template<typename RealType,typename FunctionType>
class Minimizer {
@<privateTypedefsAndConstants@>
public:
@<constructor@>
@<destructor@>
@<publicFunctions@>
private:
@<privateFunctions@>
@<privateData@>
}; // class Minimizer
@}
@d privateTypedefsAndConstants
@{
typedef typename FunctionType::FieldType FieldType;
typedef typename Vector<FieldType>::Type VectorType;
typedef Minimizer<RealType,FunctionType> ThisType;
@}
@d privateData
@{
FunctionType& function_;
SizeType maxIter_;
const gsl_multimin_fminimizer_type *gslT_;
gsl_multimin_fminimizer *gslS_;
@}
@d constructor
@{
Minimizer(FunctionType& function,SizeType maxIter)
: function_(function),
maxIter_(maxIter),
gslT_(gsl_multimin_fminimizer_nmsimplex2),
gslS_(gsl_multimin_fminimizer_alloc(gslT_,function_.size()))
{
}
@}
@d publicFunctions
@{
@<simplex@>
@}
@d destructor
@{
~Minimizer()
{
gsl_multimin_fminimizer_free (gslS_);
}
@}
@d simplex
@{
int simplex(VectorType& minVector,RealType delta=1e-3,RealType tolerance=1e-3)
{
gsl_vector *x;
/* Starting point, */
x = gsl_vector_alloc (function_.size());
for (SizeType i=0;i<minVector.size();i++)
gsl_vector_set (x, i, minVector[i]);
gsl_vector *xs;
xs = gsl_vector_alloc (function_.size());
for (SizeType i=0;i<minVector.size();i++)
gsl_vector_set (xs, i, delta);
gsl_multimin_function func;
func.f= myFunction<FunctionType>;
func.n = function_.size();
func.params = &function_;
gsl_multimin_fminimizer_set (gslS_, &func, x, xs);
for (SizeType iter=0;iter<maxIter_;iter++) {
int status = gsl_multimin_fminimizer_iterate (gslS_);
if (status) throw RuntimeError("Minimizer::simplex(...): Error encountered\n");
RealType size = gsl_multimin_fminimizer_size(gslS_);
status = gsl_multimin_test_size(size, tolerance);
if (status == GSL_SUCCESS) {
found(minVector,gslS_->x,iter);
gsl_vector_free (x);
gsl_vector_free (xs);
return iter;
}
}
gsl_vector_free (x);
gsl_vector_free (xs);
return -1;
}
@}
@d privateFunctions
@{
@<found@>
@}
@d found
@{
void found(VectorType& minVector,gsl_vector* x,SizeType iter)
{
for (SizeType i=0;i<minVector.size();i++)
minVector[i] = gsl_vector_get(x,i);
}
@}
@d MockVector
@{
template<typename FieldType>
class MockVector {
public:
MockVector(const gsl_vector *v) : v_(v)
{
}
const FieldType& operator[](SizeType i) const
{
return v_->data[i];
}
SizeType size() const { return v_->size; }
private:
const gsl_vector *v_;
}; // class MockVector
@}
@d MyFunction
@{
template<typename FunctionType>
typename FunctionType::FieldType myFunction(const gsl_vector *v, void *params)
{
MockVector<typename FunctionType::FieldType> mv(v);
FunctionType* ft = (FunctionType *)params;
return ft->operator()(mv);
}
@}
\end{document}
| {
"alphanum_fraction": 0.7282211789,
"avg_line_length": 18.8866995074,
"ext": "w",
"hexsha": "0a18f2b0f305ccb7346011801c4693be7b9f96ab",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2019-11-22T03:33:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-04-29T17:28:00.000Z",
"max_forks_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "npatel37/PsimagLiteORNL",
"max_forks_repo_path": "src/Minimizer.w",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f",
"max_issues_repo_issues_event_max_datetime": "2019-07-08T22:56:12.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-02-02T20:28:21.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "npatel37/PsimagLiteORNL",
"max_issues_repo_path": "src/Minimizer.w",
"max_line_length": 85,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "1cdeb4530c66cd41bd0c59af9ad2ecb1069ca010",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "g1257/PsimagLite",
"max_stars_repo_path": "src/Minimizer.w",
"max_stars_repo_stars_event_max_datetime": "2021-12-05T02:37:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-08-19T16:06:52.000Z",
"num_tokens": 1136,
"size": 3834
} |
#ifndef LPC_H
#define LPC_H
#include <cmath>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_sf_trig.h>
#include <gsl/gsl_blas.h>
gsl_vector *hanning(size_t L);
double lpcCoeffs(double *lpc, gsl_vector *x, size_t order);
#endif // LPC_H
| {
"alphanum_fraction": 0.7308868502,
"avg_line_length": 15.5714285714,
"ext": "h",
"hexsha": "891d02a07b5ce3f68f5ed8b34e588c675bf0e902",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z",
"max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ichi-rika/glottal-inverse",
"max_forks_repo_path": "inc/lpc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ichi-rika/glottal-inverse",
"max_issues_repo_path": "inc/lpc.h",
"max_line_length": 59,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ichi-rika/glottal-inverse",
"max_stars_repo_path": "inc/lpc.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z",
"num_tokens": 105,
"size": 327
} |
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <gsl/span>
namespace terminal_editor {
/// Returns name of passed control character, or nullptr if given byte was not recognized.
/// ISO 30112 defines POSIX control characters as Unicode characters U+0000..U+001F, U+007F..U+009F, U+2028, and U+2029 (Unicode classes Cc, Zl, and Zp) "
/// See also: https://en.wikipedia.org/wiki/C0_and_C1_control_codes
/// @param codePoint Code point for which name to return.
const char* controlCharacterName(uint32_t codePoint);
/// Describes return value of getFirstCodePoint() function.
struct CodePointInfo {
bool valid; ///< True if valid code point was decoded. False otherwise.
gsl::span<const char> consumedInput; ///< Bytes consumed from the input data. Length will be from 1 to 6.
std::string info; ///< Arbitrary information about consumed bytes. If 'valid' is false will contain error information.
uint32_t codePoint; ///< Decoded code point. Valid only if 'valid' is true.
};
/// Figures out what grapeheme is at the begining of data and returns it.
/// See: https://pl.wikipedia.org/wiki/UTF-8#Spos%C3%B3b_kodowania
/// @note All invalid byte sequences will be rendered as hex representations, with detailed explanation why it is invalid.
/// All control characters will be rendered as symbolic replacements.
/// Tab characters will be rendered as symbolic replacement.
/// @param data Input string. It is assumed to be in UTF-8, but can contain invalid characters (which will be rendered as special Graphemes).
/// @param Returns number of bytes from input consumed.
CodePointInfo getFirstCodePoint(gsl::span<const char> data);
/// Parses a line of text into a list of CodePointInfos.
std::vector<CodePointInfo> parseLine(gsl::span<const char> inputData);
/// Analyzes given input data.
/// @param inputData Input string. It is assumed to be in UTF-8, but can contain invalid characters (which will be annotated specially).
/// @return Valid UTF-8 string that describes what original string contains.
std::string analyzeData(gsl::span<const char> inputData);
/// Appends UTF-8 representation of given code point to a string.
/// @todo Move to some string utilities.
/// @param text Text to append code point to.
/// @param codePoint UTF-32 code point to append.
void appendCodePoint(std::string& text, uint32_t codePoint);
/// Appends UTF-8 representation of given code point to an output stream.
/// @todo Move to some string utilities.
/// @param os Output stream to append code point to.
/// @param codePoint UTF-32 code point to append.
void appendCodePoint(std::ostream& os, uint32_t codePoint);
} // namespace terminal_editor
| {
"alphanum_fraction": 0.7236936292,
"avg_line_length": 50.8,
"ext": "h",
"hexsha": "b4c4f15bbd785d7ac47ba5ed8717fff3cd1fc0ed",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-12-21T00:37:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-12-21T00:37:06.000Z",
"max_forks_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Zbyl/terminal-editor",
"max_forks_repo_path": "editorlib/text_parser.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Zbyl/terminal-editor",
"max_issues_repo_path": "editorlib/text_parser.h",
"max_line_length": 154,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "375ac936f09543bab9c01fcb5a2dc8de9af83a58",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Zbyl/terminal-editor",
"max_stars_repo_path": "editorlib/text_parser.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 641,
"size": 2794
} |
#include <gsl/gsl_rng.h>
#include <gsl/gsl_sort_double.h>
int
main (void)
{
const gsl_rng_type * T;
gsl_rng * r;
size_t i, k = 5, N = 100000;
double * x = malloc (N * sizeof(double));
double * small = malloc (k * sizeof(double));
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
for (i = 0; i < N; i++)
{
x[i] = gsl_rng_uniform(r);
}
gsl_sort_smallest (small, k, x, 1, N);
printf ("%d smallest values from %d\n", k, N);
for (i = 0; i < k; i++)
{
printf ("%d: %.18f\n", i, small[i]);
}
free (x);
free (small);
gsl_rng_free (r);
return 0;
}
| {
"alphanum_fraction": 0.5472,
"avg_line_length": 16.0256410256,
"ext": "c",
"hexsha": "5b725176c69956cdceb88940872add16ce40a0f3",
"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/doc/examples/sortsmall.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/doc/examples/sortsmall.c",
"max_line_length": 48,
"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/sortsmall.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": 625
} |
/* @file mvn.c
* @title multivariate normal random variables
* @author Carl Boettiger, <cboettig@gmail.com>
*
* Based on the R function rmvnorm, from the mvtnorm package
* by Friedrich Leisch and Fabian Scheipl, implemented
* using the GSL libraries
*/
#include <gsl/gsl_math.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_eigen.h>
int mvn(gsl_rng * rng, const gsl_vector * mean, gsl_matrix * covar, gsl_vector * ANS)
{
int i;
size_t n = mean->size;
/* Calculate eigenvalues and eigenvectors of covar matrix */
gsl_vector *eval = gsl_vector_alloc (n);
gsl_matrix *evec = gsl_matrix_alloc (n, n);
gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (n);
gsl_eigen_symmv (covar, eval, evec, w);
gsl_eigen_symmv_free (w);
// gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_DESC);
/* Setup for: evec * matrix(diag(eval)) * transpose(evec) */
gsl_matrix *eval_mx = gsl_matrix_calloc (n, n);
gsl_matrix * x_M = gsl_matrix_alloc (n,n);
gsl_matrix * x_M_x = gsl_matrix_alloc (n,n);
gsl_vector_view diagonal = gsl_matrix_diagonal(eval_mx);
gsl_vector_memcpy(&diagonal.vector, eval);
for(i=0;i<n;i++)
{
gsl_vector_set( &diagonal.vector,
i,
sqrt( gsl_vector_get(&diagonal.vector, i) )
);
}
/* evec * matrix(diag(eval)) * transpose(evec) */
// gsl_blas_dsymm (CblasLeft, CblasUpper,
// 1.0, evec, eval_mx, 0.0, x_M);
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
1.0, evec, eval_mx, 0.0, x_M);
gsl_blas_dgemm (CblasNoTrans, CblasTrans,
1.0, x_M, evec, 0.0, x_M_x);
gsl_matrix_free(x_M);
gsl_matrix_free(eval_mx);
gsl_matrix_free(evec);
gsl_vector_free(eval);
gsl_vector * rnorms = gsl_vector_alloc(n);
for(i=0;i<n;i++)
{
gsl_vector_set
( rnorms, i,
gsl_ran_gaussian_ziggurat(rng, 1)
);
}
gsl_blas_dgemv( CblasTrans, 1.0, x_M_x, rnorms, 0, ANS);
gsl_vector_add(ANS, mean);
gsl_matrix_free(x_M_x);
gsl_vector_free(rnorms);
return 0;
/* answer provided through pass by reference */
}
/*
int main()
{
const int n_tips = 2;
gsl_rng * rng = gsl_rng_alloc(gsl_rng_default);
gsl_vector * simdata = gsl_vector_alloc(n_tips);
gsl_matrix * I = gsl_matrix_alloc(n_tips, n_tips);
gsl_matrix_set_identity(I);
gsl_vector * A = gsl_vector_calloc(n_tips);
gsl_vector_set_all(A, 5.);
mvn(rng, A, I, simdata);
gsl_vector_fprintf(stdout, A, "%g");
return 0;
}
*/
/*
#define N 3
int main(void)
{
double mean[] = {1,2,5};
double sigma[] = {1, 0, 0,
0, 1, .9,
0, .9, 1};
double out[N] = {0,0,0};
gsl_vector_view mean_view = gsl_vector_view_array(mean, N);
gsl_matrix_view sigma_view = gsl_matrix_view_array(sigma, N,N);
gsl_vector_view out_view = gsl_vector_view_array(out, N);
gsl_rng * rng = gsl_rng_alloc(gsl_rng_default);
int i;
for(i=0;i<10000;i++) {
mvn(rng, &mean_view.vector, &sigma_view.matrix, &out_view.vector);
printf("%g %g %g\n", out[0], out[1], out[2]);
}
return 0;
}
*/
| {
"alphanum_fraction": 0.6855324849,
"avg_line_length": 24.0806451613,
"ext": "c",
"hexsha": "96bf9c9d55209a1e01c2fed708ed01fd0354dedc",
"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": "93947673f4342266acf5af667141bd466de13b3a",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "cboettig/wrightscape",
"max_forks_repo_path": "src/mvn.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "cboettig/wrightscape",
"max_issues_repo_path": "src/mvn.c",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "cboettig/wrightscape",
"max_stars_repo_path": "src/mvn.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1010,
"size": 2986
} |
/* eigen/eigen_sort.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman, Modified: B. Gough. */
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
/* The eigen_sort below is not very good, but it is simple and
* self-contained. We can always implement an improved sort later. */
int
gsl_eigen_symmv_sort (gsl_vector * eval, gsl_matrix * evec,
gsl_eigen_sort_t sort_type)
{
if (evec->size1 != evec->size2)
{
GSL_ERROR ("eigenvector matrix must be square", GSL_ENOTSQR);
}
else if (eval->size != evec->size1)
{
GSL_ERROR ("eigenvalues must match eigenvector matrix", GSL_EBADLEN);
}
else
{
const size_t N = eval->size;
size_t i;
for (i = 0; i < N - 1; i++)
{
size_t j;
size_t k = i;
double ek = gsl_vector_get (eval, i);
/* search for something to swap */
for (j = i + 1; j < N; j++)
{
int test;
const double ej = gsl_vector_get (eval, j);
switch (sort_type)
{
case GSL_EIGEN_SORT_VAL_ASC:
test = (ej < ek);
break;
case GSL_EIGEN_SORT_VAL_DESC:
test = (ej > ek);
break;
case GSL_EIGEN_SORT_ABS_ASC:
test = (fabs (ej) < fabs (ek));
break;
case GSL_EIGEN_SORT_ABS_DESC:
test = (fabs (ej) > fabs (ek));
break;
default:
GSL_ERROR ("unrecognized sort type", GSL_EINVAL);
}
if (test)
{
k = j;
ek = ej;
}
}
if (k != i)
{
/* swap eigenvalues */
gsl_vector_swap_elements (eval, i, k);
/* swap eigenvectors */
gsl_matrix_swap_columns (evec, i, k);
}
}
return GSL_SUCCESS;
}
}
int
gsl_eigen_hermv_sort (gsl_vector * eval, gsl_matrix_complex * evec,
gsl_eigen_sort_t sort_type)
{
if (evec->size1 != evec->size2)
{
GSL_ERROR ("eigenvector matrix must be square", GSL_ENOTSQR);
}
else if (eval->size != evec->size1)
{
GSL_ERROR ("eigenvalues must match eigenvector matrix", GSL_EBADLEN);
}
else
{
const size_t N = eval->size;
size_t i;
for (i = 0; i < N - 1; i++)
{
size_t j;
size_t k = i;
double ek = gsl_vector_get (eval, i);
/* search for something to swap */
for (j = i + 1; j < N; j++)
{
int test;
const double ej = gsl_vector_get (eval, j);
switch (sort_type)
{
case GSL_EIGEN_SORT_VAL_ASC:
test = (ej < ek);
break;
case GSL_EIGEN_SORT_VAL_DESC:
test = (ej > ek);
break;
case GSL_EIGEN_SORT_ABS_ASC:
test = (fabs (ej) < fabs (ek));
break;
case GSL_EIGEN_SORT_ABS_DESC:
test = (fabs (ej) > fabs (ek));
break;
default:
GSL_ERROR ("unrecognized sort type", GSL_EINVAL);
}
if (test)
{
k = j;
ek = ej;
}
}
if (k != i)
{
/* swap eigenvalues */
gsl_vector_swap_elements (eval, i, k);
/* swap eigenvectors */
gsl_matrix_complex_swap_columns (evec, i, k);
}
}
return GSL_SUCCESS;
}
}
int
gsl_eigen_nonsymmv_sort (gsl_vector_complex * eval,
gsl_matrix_complex * evec,
gsl_eigen_sort_t sort_type)
{
if (evec->size1 != evec->size2)
{
GSL_ERROR ("eigenvector matrix must be square", GSL_ENOTSQR);
}
else if (eval->size != evec->size1)
{
GSL_ERROR ("eigenvalues must match eigenvector matrix", GSL_EBADLEN);
}
else
{
const size_t N = eval->size;
size_t i;
for (i = 0; i < N - 1; i++)
{
size_t j;
size_t k = i;
gsl_complex ek = gsl_vector_complex_get (eval, i);
/* search for something to swap */
for (j = i + 1; j < N; j++)
{
int test;
const gsl_complex ej = gsl_vector_complex_get (eval, j);
switch (sort_type)
{
case GSL_EIGEN_SORT_ABS_ASC:
test = (gsl_complex_abs (ej) < gsl_complex_abs (ek));
break;
case GSL_EIGEN_SORT_ABS_DESC:
test = (gsl_complex_abs (ej) > gsl_complex_abs (ek));
break;
case GSL_EIGEN_SORT_VAL_ASC:
case GSL_EIGEN_SORT_VAL_DESC:
default:
GSL_ERROR ("invalid sort type", GSL_EINVAL);
}
if (test)
{
k = j;
ek = ej;
}
}
if (k != i)
{
/* swap eigenvalues */
gsl_vector_complex_swap_elements (eval, i, k);
/* swap eigenvectors */
gsl_matrix_complex_swap_columns (evec, i, k);
}
}
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.4853440296,
"avg_line_length": 27.4661016949,
"ext": "c",
"hexsha": "d0755d9355dfe8f7cf60d7345632c7a919385f30",
"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/eigen/sort.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/eigen/sort.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/eigen/sort.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": 1543,
"size": 6482
} |
/**
*
* @precisions normal z -> c d s
*
**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <cblas.h>
#include <lapacke.h>
#include <plasma.h>
#include <core_blas.h>
#include "auxiliary.h"
/*-------------------------------------------------------------------
* Check the orthogonality of Q
*/
int z_check_orthogonality(int M, int N, int LDQ, PLASMA_Complex64_t *Q)
{
double alpha, beta;
double normQ;
int info_ortho;
int i;
int minMN = min(M, N);
double eps;
double *work = (double *)malloc(minMN*sizeof(double));
eps = LAPACKE_dlamch_work('e');
alpha = 1.0;
beta = -1.0;
/* Build the idendity matrix USE DLASET?*/
PLASMA_Complex64_t *Id = (PLASMA_Complex64_t *) malloc(minMN*minMN*sizeof(PLASMA_Complex64_t));
memset((void*)Id, 0, minMN*minMN*sizeof(PLASMA_Complex64_t));
for (i = 0; i < minMN; i++)
Id[i*minMN+i] = (PLASMA_Complex64_t)1.0;
/* Perform Id - Q'Q */
if (M >= N)
cblas_zherk(CblasColMajor, CblasUpper, CblasConjTrans, N, M, alpha, Q, LDQ, beta, Id, N);
else
cblas_zherk(CblasColMajor, CblasUpper, CblasNoTrans, M, N, alpha, Q, LDQ, beta, Id, M);
normQ = LAPACKE_zlansy_work(LAPACK_COL_MAJOR, 'i', 'u', minMN, Id, minMN, work);
printf("============\n");
printf("Checking the orthogonality of Q \n");
printf("||Id-Q'*Q||_oo / (N*eps) = %e \n",normQ/(minMN*eps));
if ( isnan(normQ / (minMN * eps)) || (normQ / (minMN * eps) > 10.0) ) {
printf("-- Orthogonality is suspicious ! \n");
info_ortho=1;
}
else {
printf("-- Orthogonality is CORRECT ! \n");
info_ortho=0;
}
free(work); free(Id);
return info_ortho;
}
/*------------------------------------------------------------
* Check the factorization QR
*/
int z_check_QRfactorization(int M, int N, PLASMA_Complex64_t *A1, PLASMA_Complex64_t *A2, int LDA, PLASMA_Complex64_t *Q)
{
double Anorm, Rnorm;
PLASMA_Complex64_t alpha, beta;
int info_factorization;
int i,j;
double eps;
eps = LAPACKE_dlamch_work('e');
PLASMA_Complex64_t *Ql = (PLASMA_Complex64_t *)malloc(M*N*sizeof(PLASMA_Complex64_t));
PLASMA_Complex64_t *Residual = (PLASMA_Complex64_t *)malloc(M*N*sizeof(PLASMA_Complex64_t));
double *work = (double *)malloc(max(M,N)*sizeof(double));
alpha=1.0;
beta=0.0;
if (M >= N) {
/* Extract the R */
PLASMA_Complex64_t *R = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t));
memset((void*)R, 0, N*N*sizeof(PLASMA_Complex64_t));
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'u', M, N, A2, LDA, R, N);
/* Perform Ql=Q*R */
memset((void*)Ql, 0, M*N*sizeof(PLASMA_Complex64_t));
cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, N, CBLAS_SADDR(alpha), Q, LDA, R, N, CBLAS_SADDR(beta), Ql, M);
free(R);
}
else {
/* Extract the L */
PLASMA_Complex64_t *L = (PLASMA_Complex64_t *)malloc(M*M*sizeof(PLASMA_Complex64_t));
memset((void*)L, 0, M*M*sizeof(PLASMA_Complex64_t));
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'l', M, N, A2, LDA, L, M);
/* Perform Ql=LQ */
memset((void*)Ql, 0, M*N*sizeof(PLASMA_Complex64_t));
cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, M, CBLAS_SADDR(alpha), L, M, Q, LDA, CBLAS_SADDR(beta), Ql, M);
free(L);
}
/* Compute the Residual */
for (i = 0; i < M; i++)
for (j = 0 ; j < N; j++)
Residual[j*M+i] = A1[j*LDA+i]-Ql[j*M+i];
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', M, N, Residual, M, work);
Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', M, N, A2, LDA, work);
if (M >= N) {
printf("============\n");
printf("Checking the QR Factorization \n");
printf("-- ||A-QR||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps));
}
else {
printf("============\n");
printf("Checking the LQ Factorization \n");
printf("-- ||A-LQ||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps));
}
if (isnan(Rnorm / (Anorm * N *eps)) || (Rnorm / (Anorm * N * eps) > 10.0) ) {
printf("-- Factorization is suspicious ! \n");
info_factorization = 1;
}
else {
printf("-- Factorization is CORRECT ! \n");
info_factorization = 0;
}
free(work); free(Ql); free(Residual);
return info_factorization;
}
/*------------------------------------------------------------------------
* Check the factorization of the matrix A2
*/
int z_check_LLTfactorization(int N, PLASMA_Complex64_t *A1, PLASMA_Complex64_t *A2, int LDA, int uplo)
{
double Anorm, Rnorm;
PLASMA_Complex64_t alpha;
int info_factorization;
int i,j;
double eps;
eps = LAPACKE_dlamch_work('e');
PLASMA_Complex64_t *Residual = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t));
PLASMA_Complex64_t *L1 = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t));
PLASMA_Complex64_t *L2 = (PLASMA_Complex64_t *)malloc(N*N*sizeof(PLASMA_Complex64_t));
double *work = (double *)malloc(N*sizeof(double));
memset((void*)L1, 0, N*N*sizeof(PLASMA_Complex64_t));
memset((void*)L2, 0, N*N*sizeof(PLASMA_Complex64_t));
alpha= 1.0;
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,' ', N, N, A1, LDA, Residual, N);
/* Dealing with L'L or U'U */
if (uplo == PlasmaUpper){
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L1, N);
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'u', N, N, A2, LDA, L2, N);
cblas_ztrmm(CblasColMajor, CblasLeft, CblasUpper, CblasConjTrans, CblasNonUnit, N, N, CBLAS_SADDR(alpha), L1, N, L2, N);
}
else{
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L1, N);
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,'l', N, N, A2, LDA, L2, N);
cblas_ztrmm(CblasColMajor, CblasRight, CblasLower, CblasConjTrans, CblasNonUnit, N, N, CBLAS_SADDR(alpha), L1, N, L2, N);
}
/* Compute the Residual || A -L'L|| */
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
Residual[j*N+i] = L2[j*N+i] - Residual[j*N+i];
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', N, N, Residual, N, work);
Anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', N, N, A1, LDA, work);
printf("============\n");
printf("Checking the Cholesky Factorization \n");
printf("-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \n",Rnorm/(Anorm*N*eps));
if ( isnan(Rnorm/(Anorm*N*eps)) || (Rnorm/(Anorm*N*eps) > 10.0) ){
printf("-- Factorization is suspicious ! \n");
info_factorization = 1;
}
else{
printf("-- Factorization is CORRECT ! \n");
info_factorization = 0;
}
free(Residual); free(L1); free(L2); free(work);
return info_factorization;
}
/*--------------------------------------------------------------
* Check the gemm
*/
double z_check_gemm(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K,
PLASMA_Complex64_t alpha, PLASMA_Complex64_t *A, int LDA,
PLASMA_Complex64_t *B, int LDB,
PLASMA_Complex64_t beta, PLASMA_Complex64_t *Cplasma,
PLASMA_Complex64_t *Cref, int LDC,
double *Cinitnorm, double *Cplasmanorm, double *Clapacknorm )
{
PLASMA_Complex64_t beta_const = -1.0;
double Rnorm;
double *work = (double *)malloc(max(K,max(M, N))* sizeof(double));
*Cinitnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work);
*Cplasmanorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', M, N, Cplasma, LDC, work);
cblas_zgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K,
CBLAS_SADDR(alpha), A, LDA, B, LDB, CBLAS_SADDR(beta), Cref, LDC);
*Clapacknorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work);
cblas_zaxpy(LDC * N, CBLAS_SADDR(beta_const), Cplasma, 1, Cref, 1);
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', M, N, Cref, LDC, work);
free(work);
return Rnorm;
}
/*--------------------------------------------------------------
* Check the trsm
*/
double z_check_trsm(PLASMA_enum side, PLASMA_enum uplo, PLASMA_enum trans, PLASMA_enum diag,
int M, int NRHS, PLASMA_Complex64_t alpha,
PLASMA_Complex64_t *A, int LDA,
PLASMA_Complex64_t *Bplasma, PLASMA_Complex64_t *Bref, int LDB,
double *Binitnorm, double *Bplasmanorm, double *Blapacknorm )
{
PLASMA_Complex64_t beta_const = -1.0;
double Rnorm;
double *work = (double *)malloc(max(M, NRHS)* sizeof(double));
/*double eps = LAPACKE_dlamch_work('e');*/
*Binitnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, Bref, LDB, work);
*Bplasmanorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bplasma, LDB, work);
cblas_ztrsm(CblasColMajor, (CBLAS_SIDE)side, (CBLAS_UPLO)uplo,
(CBLAS_TRANSPOSE)trans, (CBLAS_DIAG)diag, M, NRHS,
CBLAS_SADDR(alpha), A, LDA, Bref, LDB);
*Blapacknorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bref, LDB, work);
cblas_zaxpy(LDB * NRHS, CBLAS_SADDR(beta_const), Bplasma, 1, Bref, 1);
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'm', M, NRHS, Bref, LDB, work);
Rnorm = Rnorm / *Blapacknorm;
/* max(M,NRHS) * eps);*/
free(work);
return Rnorm;
}
/*--------------------------------------------------------------
* Check the solution
*/
double z_check_solution(int M, int N, int NRHS, PLASMA_Complex64_t *A, int LDA,
PLASMA_Complex64_t *B, PLASMA_Complex64_t *X, int LDB,
double *anorm, double *bnorm, double *xnorm )
{
/* int info_solution; */
double Rnorm = -1.00;
PLASMA_Complex64_t zone = 1.0;
PLASMA_Complex64_t mzone = -1.0;
double *work = (double *)malloc(max(M, N)* sizeof(double));
*anorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', M, N, A, LDA, work);
*xnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', M, NRHS, X, LDB, work);
*bnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work);
cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, NRHS, N, CBLAS_SADDR(zone), A, LDA, X, LDB, CBLAS_SADDR(mzone), B, LDB);
Rnorm = LAPACKE_zlange_work(LAPACK_COL_MAJOR, 'i', N, NRHS, B, LDB, work);
free(work);
return Rnorm;
}
| {
"alphanum_fraction": 0.5913488902,
"avg_line_length": 35.3758389262,
"ext": "c",
"hexsha": "33a65837af5a2c44d44b0994863d588d15dcdc4c",
"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/zauxiliary.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/zauxiliary.c",
"max_line_length": 134,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "timing/zauxiliary.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3577,
"size": 10542
} |
/*************************************************************************************
* Copyright (C) 2017, Trung Pham <me@trungbpham.com> *
* 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 cfeap 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 __CBLAS_WRAPPER_H__
#define __CBLAS_WRAPPER_H__
#include <stdio.h>
#include <cblas.h>
int cblw_scalar_vec_mul_x(size_t dim, double a, double *x);
int cblw_scalar_mat_mul_x(size_t col, size_t row, double a, double *X);
int cblw_scalar_vec_mul_y(size_t dim, double a, double *x, double *y);
int cblw_scalar_mat_mul_y(size_t col, size_t row, double a, double *X, double *Y);
int cblw_mat_vec_mul(size_t col, size_t row, double *A, double *x, double *y);
int cblw_mat_mat_mul(size_t rowA, size_t colB, size_t colA_rowB, double *A, double *B, double *C);
#endif //__CBLAS_WRAPPER_H__ | {
"alphanum_fraction": 0.5328630971,
"avg_line_length": 63.6530612245,
"ext": "h",
"hexsha": "e5bcaa818dcecbfc5392de353a21bb14110463d6",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-03-15T07:28:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-15T07:28:36.000Z",
"max_forks_repo_head_hexsha": "231f32c346527bd55923bd529a8ead3fba2086e4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pbtrung/cfeap.bak",
"max_forks_repo_path": "include/linalg/cblas-wrapper.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "231f32c346527bd55923bd529a8ead3fba2086e4",
"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": "pbtrung/cfeap.bak",
"max_issues_repo_path": "include/linalg/cblas-wrapper.h",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "231f32c346527bd55923bd529a8ead3fba2086e4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pbtrung/cfeap.bak",
"max_stars_repo_path": "include/linalg/cblas-wrapper.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 567,
"size": 3119
} |
/* vector/gsl_vector_complex_long_double.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_VECTOR_COMPLEX_LONG_DOUBLE_H__
#define __GSL_VECTOR_COMPLEX_LONG_DOUBLE_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_long_double.h>
#include <gsl/gsl_vector_complex.h>
#include <gsl/gsl_block_complex_long_double.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
long double *data;
gsl_block_complex_long_double *block;
int owner;
} gsl_vector_complex_long_double;
typedef struct
{
gsl_vector_complex_long_double vector;
} _gsl_vector_complex_long_double_view;
typedef _gsl_vector_complex_long_double_view gsl_vector_complex_long_double_view;
typedef struct
{
gsl_vector_complex_long_double vector;
} _gsl_vector_complex_long_double_const_view;
typedef const _gsl_vector_complex_long_double_const_view gsl_vector_complex_long_double_const_view;
/* Allocation */
GSL_FUN gsl_vector_complex_long_double *gsl_vector_complex_long_double_alloc (const size_t n);
GSL_FUN gsl_vector_complex_long_double *gsl_vector_complex_long_double_calloc (const size_t n);
GSL_FUN gsl_vector_complex_long_double *
gsl_vector_complex_long_double_alloc_from_block (gsl_block_complex_long_double * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN gsl_vector_complex_long_double *
gsl_vector_complex_long_double_alloc_from_vector (gsl_vector_complex_long_double * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN void gsl_vector_complex_long_double_free (gsl_vector_complex_long_double * v);
/* Views */
GSL_FUN _gsl_vector_complex_long_double_view
gsl_vector_complex_long_double_view_array (long double *base,
size_t n);
GSL_FUN _gsl_vector_complex_long_double_view
gsl_vector_complex_long_double_view_array_with_stride (long double *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_complex_long_double_const_view
gsl_vector_complex_long_double_const_view_array (const long double *base,
size_t n);
GSL_FUN _gsl_vector_complex_long_double_const_view
gsl_vector_complex_long_double_const_view_array_with_stride (const long double *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_complex_long_double_view
gsl_vector_complex_long_double_subvector (gsl_vector_complex_long_double *base,
size_t i,
size_t n);
GSL_FUN _gsl_vector_complex_long_double_view
gsl_vector_complex_long_double_subvector_with_stride (gsl_vector_complex_long_double *v,
size_t i,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_complex_long_double_const_view
gsl_vector_complex_long_double_const_subvector (const gsl_vector_complex_long_double *base,
size_t i,
size_t n);
GSL_FUN _gsl_vector_complex_long_double_const_view
gsl_vector_complex_long_double_const_subvector_with_stride (const gsl_vector_complex_long_double *v,
size_t i,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_long_double_view
gsl_vector_complex_long_double_real (gsl_vector_complex_long_double *v);
GSL_FUN _gsl_vector_long_double_view
gsl_vector_complex_long_double_imag (gsl_vector_complex_long_double *v);
GSL_FUN _gsl_vector_long_double_const_view
gsl_vector_complex_long_double_const_real (const gsl_vector_complex_long_double *v);
GSL_FUN _gsl_vector_long_double_const_view
gsl_vector_complex_long_double_const_imag (const gsl_vector_complex_long_double *v);
/* Operations */
GSL_FUN void gsl_vector_complex_long_double_set_zero (gsl_vector_complex_long_double * v);
GSL_FUN void gsl_vector_complex_long_double_set_all (gsl_vector_complex_long_double * v,
gsl_complex_long_double z);
GSL_FUN int gsl_vector_complex_long_double_set_basis (gsl_vector_complex_long_double * v, size_t i);
GSL_FUN int gsl_vector_complex_long_double_fread (FILE * stream,
gsl_vector_complex_long_double * v);
GSL_FUN int gsl_vector_complex_long_double_fwrite (FILE * stream,
const gsl_vector_complex_long_double * v);
GSL_FUN int gsl_vector_complex_long_double_fscanf (FILE * stream,
gsl_vector_complex_long_double * v);
GSL_FUN int gsl_vector_complex_long_double_fprintf (FILE * stream,
const gsl_vector_complex_long_double * v,
const char *format);
GSL_FUN int gsl_vector_complex_long_double_memcpy (gsl_vector_complex_long_double * dest, const gsl_vector_complex_long_double * src);
GSL_FUN int gsl_vector_complex_long_double_reverse (gsl_vector_complex_long_double * v);
GSL_FUN int gsl_vector_complex_long_double_swap (gsl_vector_complex_long_double * v, gsl_vector_complex_long_double * w);
GSL_FUN int gsl_vector_complex_long_double_swap_elements (gsl_vector_complex_long_double * v, const size_t i, const size_t j);
GSL_FUN int gsl_vector_complex_long_double_equal (const gsl_vector_complex_long_double * u,
const gsl_vector_complex_long_double * v);
GSL_FUN int gsl_vector_complex_long_double_isnull (const gsl_vector_complex_long_double * v);
GSL_FUN int gsl_vector_complex_long_double_ispos (const gsl_vector_complex_long_double * v);
GSL_FUN int gsl_vector_complex_long_double_isneg (const gsl_vector_complex_long_double * v);
GSL_FUN int gsl_vector_complex_long_double_isnonneg (const gsl_vector_complex_long_double * v);
GSL_FUN int gsl_vector_complex_long_double_add (gsl_vector_complex_long_double * a, const gsl_vector_complex_long_double * b);
GSL_FUN int gsl_vector_complex_long_double_sub (gsl_vector_complex_long_double * a, const gsl_vector_complex_long_double * b);
GSL_FUN int gsl_vector_complex_long_double_mul (gsl_vector_complex_long_double * a, const gsl_vector_complex_long_double * b);
GSL_FUN int gsl_vector_complex_long_double_div (gsl_vector_complex_long_double * a, const gsl_vector_complex_long_double * b);
GSL_FUN int gsl_vector_complex_long_double_scale (gsl_vector_complex_long_double * a, const gsl_complex_long_double x);
GSL_FUN int gsl_vector_complex_long_double_add_constant (gsl_vector_complex_long_double * a, const gsl_complex_long_double x);
GSL_FUN int gsl_vector_complex_long_double_axpby (const gsl_complex_long_double alpha, const gsl_vector_complex_long_double * x, const gsl_complex_long_double beta, gsl_vector_complex_long_double * y);
GSL_FUN INLINE_DECL gsl_complex_long_double gsl_vector_complex_long_double_get (const gsl_vector_complex_long_double * v, const size_t i);
GSL_FUN INLINE_DECL void gsl_vector_complex_long_double_set (gsl_vector_complex_long_double * v, const size_t i, gsl_complex_long_double z);
GSL_FUN INLINE_DECL gsl_complex_long_double *gsl_vector_complex_long_double_ptr (gsl_vector_complex_long_double * v, const size_t i);
GSL_FUN INLINE_DECL const gsl_complex_long_double *gsl_vector_complex_long_double_const_ptr (const gsl_vector_complex_long_double * v, const size_t i);
#ifdef HAVE_INLINE
INLINE_FUN
gsl_complex_long_double
gsl_vector_complex_long_double_get (const gsl_vector_complex_long_double * v,
const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
gsl_complex_long_double zero = {{0, 0}};
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, zero);
}
#endif
return *GSL_COMPLEX_LONG_DOUBLE_AT (v, i);
}
INLINE_FUN
void
gsl_vector_complex_long_double_set (gsl_vector_complex_long_double * v,
const size_t i, gsl_complex_long_double z)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
*GSL_COMPLEX_LONG_DOUBLE_AT (v, i) = z;
}
INLINE_FUN
gsl_complex_long_double *
gsl_vector_complex_long_double_ptr (gsl_vector_complex_long_double * v,
const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return GSL_COMPLEX_LONG_DOUBLE_AT (v, i);
}
INLINE_FUN
const gsl_complex_long_double *
gsl_vector_complex_long_double_const_ptr (const gsl_vector_complex_long_double * v,
const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return GSL_COMPLEX_LONG_DOUBLE_AT (v, i);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_COMPLEX_LONG_DOUBLE_H__ */
| {
"alphanum_fraction": 0.721570817,
"avg_line_length": 40.8593155894,
"ext": "h",
"hexsha": "8ad85a3b8cb26e893f8709fa2ecf6aee54c276fb",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_complex_long_double.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_complex_long_double.h",
"max_line_length": 201,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_vector_complex_long_double.h",
"max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z",
"num_tokens": 2302,
"size": 10746
} |
/* ode-initval/rk8pd.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Runge-Kutta 8(9), Prince-Dormand
*
* High Order Embedded Runge-Kutta Formulae
* P.J. Prince and J.R. Dormand
* J. Comp. Appl. Math.,7, pp. 67-75, 1981
*/
/* Author: G. Jungman
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv.h>
#include "odeiv_util.h"
/* Prince-Dormand constants */
static const double Abar[] = {
14005451.0 / 335480064.0,
0.0,
0.0,
0.0,
0.0,
-59238493.0 / 1068277825.0,
181606767.0 / 758867731.0,
561292985.0 / 797845732.0,
-1041891430.0 / 1371343529.0,
760417239.0 / 1151165299.0,
118820643.0 / 751138087.0,
-528747749.0 / 2220607170.0,
1.0 / 4.0
};
static const double A[] = {
13451932.0 / 455176623.0,
0.0,
0.0,
0.0,
0.0,
-808719846.0 / 976000145.0,
1757004468.0 / 5645159321.0,
656045339.0 / 265891186.0,
-3867574721.0 / 1518517206.0,
465885868.0 / 322736535.0,
53011238.0 / 667516719.0,
2.0 / 45.0
};
static const double ah[] = {
1.0 / 18.0,
1.0 / 12.0,
1.0 / 8.0,
5.0 / 16.0,
3.0 / 8.0,
59.0 / 400.0,
93.0 / 200.0,
5490023248.0 / 9719169821.0,
13.0 / 20.0,
1201146811.0 / 1299019798.0
};
static const double b21 = 1.0 / 18.0;
static const double b3[] = { 1.0 / 48.0, 1.0 / 16.0 };
static const double b4[] = { 1.0 / 32.0, 0.0, 3.0 / 32.0 };
static const double b5[] = { 5.0 / 16.0, 0.0, -75.0 / 64.0, 75.0 / 64.0 };
static const double b6[] = { 3.0 / 80.0, 0.0, 0.0, 3.0 / 16.0, 3.0 / 20.0 };
static const double b7[] = {
29443841.0 / 614563906.0,
0.0,
0.0,
77736538.0 / 692538347.0,
-28693883.0 / 1125000000.0,
23124283.0 / 1800000000.0
};
static const double b8[] = {
16016141.0 / 946692911.0,
0.0,
0.0,
61564180.0 / 158732637.0,
22789713.0 / 633445777.0,
545815736.0 / 2771057229.0,
-180193667.0 / 1043307555.0
};
static const double b9[] = {
39632708.0 / 573591083.0,
0.0,
0.0,
-433636366.0 / 683701615.0,
-421739975.0 / 2616292301.0,
100302831.0 / 723423059.0,
790204164.0 / 839813087.0,
800635310.0 / 3783071287.0
};
static const double b10[] = {
246121993.0 / 1340847787.0,
0.0,
0.0,
-37695042795.0 / 15268766246.0,
-309121744.0 / 1061227803.0,
-12992083.0 / 490766935.0,
6005943493.0 / 2108947869.0,
393006217.0 / 1396673457.0,
123872331.0 / 1001029789.0
};
static const double b11[] = {
-1028468189.0 / 846180014.0,
0.0,
0.0,
8478235783.0 / 508512852.0,
1311729495.0 / 1432422823.0,
-10304129995.0 / 1701304382.0,
-48777925059.0 / 3047939560.0,
15336726248.0 / 1032824649.0,
-45442868181.0 / 3398467696.0,
3065993473.0 / 597172653.0
};
static const double b12[] = {
185892177.0 / 718116043.0,
0.0,
0.0,
-3185094517.0 / 667107341.0,
-477755414.0 / 1098053517.0,
-703635378.0 / 230739211.0,
5731566787.0 / 1027545527.0,
5232866602.0 / 850066563.0,
-4093664535.0 / 808688257.0,
3962137247.0 / 1805957418.0,
65686358.0 / 487910083.0
};
static const double b13[] = {
403863854.0 / 491063109.0,
0.0,
0.0,
-5068492393.0 / 434740067.0,
-411421997.0 / 543043805.0,
652783627.0 / 914296604.0,
11173962825.0 / 925320556.0,
-13158990841.0 / 6184727034.0,
3936647629.0 / 1978049680.0,
-160528059.0 / 685178525.0,
248638103.0 / 1413531060.0,
0.0
};
typedef struct
{
double *k[13];
double *ytmp;
double *y0;
}
rk8pd_state_t;
static void *
rk8pd_alloc (size_t dim)
{
rk8pd_state_t *state = (rk8pd_state_t *) malloc (sizeof (rk8pd_state_t));
int i, j;
if (state == 0)
{
GSL_ERROR_NULL ("failed to allocate space for rk8pd_state", GSL_ENOMEM);
}
state->ytmp = (double *) malloc (dim * sizeof (double));
if (state->ytmp == 0)
{
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM);
}
state->y0 = (double *) malloc (dim * sizeof (double));
if (state->y0 == 0)
{
free (state->ytmp);
free (state);
GSL_ERROR_NULL ("failed to allocate space for y0", GSL_ENOMEM);
}
for (i = 0; i < 13; i++)
{
state->k[i] = (double *) malloc (dim * sizeof (double));
if (state->k[i] == 0)
{
for (j = 0; j < i; j++)
{
free (state->k[j]);
}
free (state->y0);
free (state->ytmp);
free (state);
GSL_ERROR_NULL ("failed to allocate space for k's", GSL_ENOMEM);
}
}
return state;
}
static int
rk8pd_apply (void *vstate,
size_t dim,
double t,
double h,
double y[],
double yerr[],
const double dydt_in[],
double dydt_out[], const gsl_odeiv_system * sys)
{
rk8pd_state_t *state = (rk8pd_state_t *) vstate;
size_t i;
double *const ytmp = state->ytmp;
double *const y0 = state->y0;
/* Note that k1 is stored in state->k[0] due to zero-based indexing */
double *const k1 = state->k[0];
double *const k2 = state->k[1];
double *const k3 = state->k[2];
double *const k4 = state->k[3];
double *const k5 = state->k[4];
double *const k6 = state->k[5];
double *const k7 = state->k[6];
double *const k8 = state->k[7];
double *const k9 = state->k[8];
double *const k10 = state->k[9];
double *const k11 = state->k[10];
double *const k12 = state->k[11];
double *const k13 = state->k[12];
DBL_MEMCPY (y0, y, dim);
/* k1 step */
if (dydt_in != NULL)
{
DBL_MEMCPY (k1, dydt_in, dim);
}
else
{
int s = GSL_ODEIV_FN_EVAL (sys, t, y, k1);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] = y[i] + b21 * h * k1[i];
/* k2 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[0] * h, ytmp, k2);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] = y[i] + h * (b3[0] * k1[i] + b3[1] * k2[i]);
/* k3 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[1] * h, ytmp, k3);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] = y[i] + h * (b4[0] * k1[i] + b4[2] * k3[i]);
/* k4 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[2] * h, ytmp, k4);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] = y[i] + h * (b5[0] * k1[i] + b5[2] * k3[i] + b5[3] * k4[i]);
/* k5 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[3] * h, ytmp, k5);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] = y[i] + h * (b6[0] * k1[i] + b6[3] * k4[i] + b6[4] * k5[i]);
/* k6 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[4] * h, ytmp, k6);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b7[0] * k1[i] + b7[3] * k4[i] + b7[4] * k5[i] +
b7[5] * k6[i]);
/* k7 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[5] * h, ytmp, k7);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b8[0] * k1[i] + b8[3] * k4[i] + b8[4] * k5[i] +
b8[5] * k6[i] + b8[6] * k7[i]);
/* k8 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[6] * h, ytmp, k8);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b9[0] * k1[i] + b9[3] * k4[i] + b9[4] * k5[i] +
b9[5] * k6[i] + b9[6] * k7[i] + b9[7] * k8[i]);
/* k9 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[7] * h, ytmp, k9);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b10[0] * k1[i] + b10[3] * k4[i] + b10[4] * k5[i] +
b10[5] * k6[i] + b10[6] * k7[i] + b10[7] * k8[i] +
b10[8] * k9[i]);
/* k10 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[8] * h, ytmp, k10);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b11[0] * k1[i] + b11[3] * k4[i] + b11[4] * k5[i] +
b11[5] * k6[i] + b11[6] * k7[i] + b11[7] * k8[i] +
b11[8] * k9[i] + b11[9] * k10[i]);
/* k11 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + ah[9] * h, ytmp, k11);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b12[0] * k1[i] + b12[3] * k4[i] + b12[4] * k5[i] +
b12[5] * k6[i] + b12[6] * k7[i] + b12[7] * k8[i] +
b12[8] * k9[i] + b12[9] * k10[i] + b12[10] * k11[i]);
/* k12 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, ytmp, k12);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
ytmp[i] =
y[i] + h * (b13[0] * k1[i] + b13[3] * k4[i] + b13[4] * k5[i] +
b13[5] * k6[i] + b13[6] * k7[i] + b13[7] * k8[i] +
b13[8] * k9[i] + b13[9] * k10[i] + b13[10] * k11[i] +
b13[11] * k12[i]);
/* k13 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, ytmp, k13);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* final sum */
for (i = 0; i < dim; i++)
{
const double ksum8 =
Abar[0] * k1[i] + Abar[5] * k6[i] + Abar[6] * k7[i] +
Abar[7] * k8[i] + Abar[8] * k9[i] + Abar[9] * k10[i] +
Abar[10] * k11[i] + Abar[11] * k12[i] + Abar[12] * k13[i];
y[i] += h * ksum8;
}
/* Evaluate dydt_out[]. */
if (dydt_out != NULL)
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out);
if (s != GSL_SUCCESS)
{
/* Restore initial values */
DBL_MEMCPY (y, y0, dim);
return s;
}
}
/* error estimate */
for (i = 0; i < dim; i++)
{
const double ksum8 =
Abar[0] * k1[i] + Abar[5] * k6[i] + Abar[6] * k7[i] +
Abar[7] * k8[i] + Abar[8] * k9[i] + Abar[9] * k10[i] +
Abar[10] * k11[i] + Abar[11] * k12[i] + Abar[12] * k13[i];
const double ksum7 =
A[0] * k1[i] + A[5] * k6[i] + A[6] * k7[i] + A[7] * k8[i] +
A[8] * k9[i] + A[9] * k10[i] + A[10] * k11[i] + A[11] * k12[i];
yerr[i] = h * (ksum7 - ksum8);
}
return GSL_SUCCESS;
}
static int
rk8pd_reset (void *vstate, size_t dim)
{
rk8pd_state_t *state = (rk8pd_state_t *) vstate;
int i;
for (i = 0; i < 13; i++)
{
DBL_ZERO_MEMSET (state->k[i], dim);
}
DBL_ZERO_MEMSET (state->y0, dim);
DBL_ZERO_MEMSET (state->ytmp, dim);
return GSL_SUCCESS;
}
static unsigned int
rk8pd_order (void *vstate)
{
rk8pd_state_t *state = (rk8pd_state_t *) vstate;
state = 0; /* prevent warnings about unused parameters */
return 8;
}
static void
rk8pd_free (void *vstate)
{
rk8pd_state_t *state = (rk8pd_state_t *) vstate;
int i;
for (i = 0; i < 13; i++)
{
free (state->k[i]);
}
free (state->y0);
free (state->ytmp);
free (state);
}
static const gsl_odeiv_step_type rk8pd_type = { "rk8pd", /* name */
1, /* can use dydt_in */
1, /* gives exact dydt_out */
&rk8pd_alloc,
&rk8pd_apply,
&rk8pd_reset,
&rk8pd_order,
&rk8pd_free
};
const gsl_odeiv_step_type *gsl_odeiv_step_rk8pd = &rk8pd_type;
| {
"alphanum_fraction": 0.5251452282,
"avg_line_length": 22.3977695167,
"ext": "c",
"hexsha": "37bffe9714e04e70ffe72bbec53de77720111bd2",
"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/ode-initval/rk8pd.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/ode-initval/rk8pd.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/ode-initval/rk8pd.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": 5028,
"size": 12050
} |
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <signal.h>
#include <string.h>
#include <math.h>
#include "cblas.h"
#include <lapacke.h>
#include <unistd.h>
#include <sys/types.h>
#include "spidriver_host.h"
#include "adcdriver_host.h"
#include "matrix_utils.h"
#define PI 3.1415926535
// Length of data buffer
#define NUMPTS 128
// Number of signal vectors
#define PSIG 2
// Sampling frequency. Must match the sampling frequency commanded
// to the A/D.
#define FSAMP 15625
// Parameters used in searching for peak
#define MAXRECURSIONS 5
#define NGRID 25
//===========================================================
// Utility functions for MUSIC
//-----------------------------------------------------
void find_bracket(int N, float *u, int *ileft, int *iright) {
// Given input vector y, this finds the max element,
// then returns the indices of the vectors to its
// left and right.
int i;
i = maxeltf(N, u);
if (i == 0) {
*ileft = 0;
*iright = 1;
} else if (i == (N-1)) {
*ileft = N-2;
*iright = N-1;
} else {
*ileft = i-1;
*iright = i+1;
}
return;
}
//-----------------------------------------------------
void extract_noise_vectors(float *A, int m, int n, int c, float *E) {
// This fcn takes input matrix A of size mxn. It extracts the vectors
// of A to the right, starting at col c, and puts the extracted
// vectors into E. E has size [m, n-c]
//printf("Entered extract_noise_vectors, m = %d, n = %d, c = %d\n", m, n, c);
int i, j, l;
for (i = 0; i < m; i++) {
for (j = c; j < n; j++) {
// printf("i = %d, j = %d, A[i,j] = %f\n", i, j, MATRIX_ELEMENT(A, m, n, i, j));
l = lindex(m, n-c, i, j-c);
// printf("lindex(m, n-c, i,j-c) = %d\n", l);
E[l] = MATRIX_ELEMENT(A, m, n, i, j);
}
}
}
//-----------------------------------------------------
float music_sum(float f, float *v, int Mr, int Mc) {
// This performs the sum over noise space vectors.
// Since complex numbers are not supported, I split
// the computation into two parts, real and imag.
int i, j;
float *er;
float *ei;
float *vi;
float s, tr, ti;
// printf("--> Entered music_sum, [row, col] = [%d, %d]\n", Mr, Mc);
er = (float*) malloc(Mr*sizeof(float));
ei = (float*) malloc(Mr*sizeof(float));
vi = (float*) malloc(Mr*sizeof(float));
// Create e vector
for(i=0; i<Mr; i++) {
er[i] = cos(2*PI*i*f);
ei[i] = sin(2*PI*i*f);
}
// Compute denominator
s = 0;
for(i=0; i<Mc; i++) { // iterate over columns.
// v is a matrix, so extract noise vector vi as column vector.
for(j=0; j<Mr; j++) { // iterate over rows
vi[j] = v[lindex(Mr, Mc, j, i)];
}
tr = cblas_sdot(Mr, er, 1, vi, 1);
ti = cblas_sdot(Mr, ei, 1, vi, 1);
s = s + tr*tr + ti*ti;
}
free(er);
free(ei);
free(vi);
// Must guard against returning inf or nan.
return (1.0f/s);
}
//-----------------------------------------------------
// Called when Ctrl+C is pressed - triggers the program to stop.
void stopHandler(int sig) {
adc_quit();
exit(0);
}
//==========================================================
// This is the main program. It runs a loop, takes a buffer
// of data from the A/D, then uses the MUSIC algorithm to
// compute the frequency of the input sine wave.
int main (void)
{
// Loop variables
uint32_t i, j;
// Buffers for tx and rx data from A/D registers.
uint32_t tx_buf[3];
uint32_t rx_buf[4];
// Used in LAPACK computations
int m = NUMPTS;
int info;
float superb[NUMPTS-1];
// Measured voltages from A/D
float v[NUMPTS]; // Vector of measurements
float Rxx[NUMPTS*NUMPTS]; // Covariance matrix.
float U[NUMPTS * NUMPTS];
float S[NUMPTS];
float VT[NUMPTS * NUMPTS];
float Nu[NUMPTS * (NUMPTS-PSIG)]; // Vector of noises
// Used in finding peak corresponding to dominant frequency
float f[NGRID];
float Pmu[NGRID];
int ileft, iright;
float fleft, fright, fpeak;
// Stuff used with "hit return when ready..."
char dummy[8];
printf("------------ Starting main..... -------------\n");
// Run until Ctrl+C pressed:
signal(SIGINT, stopHandler);
// Sanity check user.
if(getuid()!=0){
printf("You must run this program as root. Exiting.\n");
exit(EXIT_FAILURE);
}
// Initialize A/D converter
adc_config();
adc_set_samplerate(SAMP_RATE_15625);
adc_set_chan0();
// Now loop forever, read buffer, and compute frequency.
// printf("--------------------------------------------------\n");
while(1) {
// Do A/D read to fill buffer with NUMPTS measurements.
adc_read_multiple(NUMPTS, v);
//printf("Values read = \n");
//for (i=0; i<NUMPTS; i++) {
// printf("i = %d, v = %e\n", i, v[i]);
//}
// Zero out Rxx prior to filling it using sger
zeros(m, m, Rxx);
// Create covariance matrix by doing outer product of v with
// itself.
cblas_sger(CblasRowMajor, /* Row-major storage */
m, /* Row count for Rxx */
m, /* Col count for Rxx */
1.0f, /* scale factor to apply to v*v' */
v,
1, /* stride between elements of v. */
v,
1, /* stride between elements of v. */
Rxx,
m); /* leading dimension of matrix Rxx. */
//printf("\nMatrix Rxx (%d x %d) =\n", m, m);
//print_matrix(Rxx, m, m);
// Now compute SVD of Rxx.
info = LAPACKE_sgesvd(LAPACK_ROW_MAJOR, 'A', 'A',
m, m, Rxx,
m, S, U, m,
VT, m, superb);
if (info != 0) {
fprintf(stderr, "Error: dgesvd returned with a non-zero status (info = %d)\n", info);
return(-1);
}
//printf("\nMatrix U (%d x %d) is:\n", m, m);
//print_matrix(U, m, m);
//printf("\nVector S (%d x %d) is:\n", m, 1);
//print_matrix(S, m, 1);
//printf("\nMatrix VT (%d x %d) is:\n", m, m);
//print_matrix(VT, m, m);
// Extract noise vectors here. The noise vectors are held in Nu
extract_noise_vectors(U, m, m, PSIG, Nu);
//printf("\nMatrix Nu (%d x %d) is:\n", m, NUMPTS-PSIG);
//print_matrix(Nu, m, NUMPTS-PSIG);
// Now find max freq. Set up initial grid endpoints. Freqs are
// in units of Hz.
fleft = 0.0f;
fright = FSAMP/2.0f;
for (j=0; j<MAXRECURSIONS; j++) {
// printf("fleft = %f, fright = %f\n", fleft, fright);
// Set up search grid
linspace(fleft, fright, NGRID, f);
//printf("\nVector f =\n");
//print_matrix(f, NGRID, 1);
// Compute vector of amplitudes Pmu on grid. music_sum wants normalized
// frequencies
for (i = 0; i < NGRID; i++) {
Pmu[i] = music_sum(f[i]/FSAMP, Nu, NUMPTS, NUMPTS-PSIG);
}
//printf("\nVector Pmu =\n");
//print_matrix(Pmu, NGRID, 1);
find_bracket(NGRID, Pmu, &ileft, &iright);
fleft = f[ileft];
fright = f[iright];
}
fpeak = (fleft+fright)/2.0f; // Assume peak is average of fleft and fright
printf("Peak frequency found at f = %f Hz\n", fpeak);
// usleep(500000); // delay 1/2 sec.
}
}
| {
"alphanum_fraction": 0.5342935528,
"avg_line_length": 27,
"ext": "c",
"hexsha": "f321f365d601bc0239615e78a9fc71aeff946acd",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-02-12T20:17:55.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-02-12T20:17:55.000Z",
"max_forks_repo_head_hexsha": "46358a148ff8b925094eebe0b415a088d8fd8da4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "RobertPHeller/MusicPlaypen",
"max_forks_repo_path": "main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "46358a148ff8b925094eebe0b415a088d8fd8da4",
"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": "RobertPHeller/MusicPlaypen",
"max_issues_repo_path": "main.c",
"max_line_length": 91,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "46358a148ff8b925094eebe0b415a088d8fd8da4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "RobertPHeller/MusicPlaypen",
"max_stars_repo_path": "main.c",
"max_stars_repo_stars_event_max_datetime": "2020-04-01T08:03:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-15T10:29:24.000Z",
"num_tokens": 2193,
"size": 7290
} |
#define _GNU_SOURCE
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <glib.h>
#if HAVE_MPI
#include <mpi.h>
#endif
#include "genetic/genetic.h"
#define N_SIMULATIONS 10000
#define SEED 707l
int ntasks = 1;
unsigned int nthreads = 1;
GMutex mutex[1];
GeneticVariable v[2];
double
evaluate (Entity * entity)
{
double x, y, e1, e2;
x = genetic_get_variable (entity, v);
y = genetic_get_variable (entity, v + 1);
e1 = x + y - 3.;
e2 = x - y - 1.;
e1 = e1 * e1 + e2 * e2;
return e1;
}
int
main (int argn, char **argc)
{
FILE *file;
double *best_variables;
char *best_genome;
double xgenerations, mutation_ratio, reproduction_ratio, adaptation_ratio,
evolution_ratio, best_objective;
int rank;
unsigned int ngenerations;
#if HAVE_MPI
MPI_Init (&argn, &argc);
MPI_Comm_size (MPI_COMM_WORLD, &ntasks);
MPI_Comm_rank (MPI_COMM_WORLD, &rank);
#else
rank = 0;
#endif
nthreads = 4;
v[0].maximum = 10.;
v[0].minimum = -10.;
v[0].nbits = 30;
v[1].maximum = 10.;
v[1].minimum = -10.;
v[1].nbits = 30;
file = fopen (argc[1], "r");
if (fscanf (file, "%*s%lf%*s%lf%*s%lf%*s%lf", &xgenerations,
&mutation_ratio, &reproduction_ratio, &adaptation_ratio) != 4)
return 1;
fclose (file);
ngenerations = xgenerations;
evolution_ratio = mutation_ratio + reproduction_ratio + adaptation_ratio;
genetic_algorithm_default (2, v,
N_SIMULATIONS
/ (1 + (ngenerations - 1) * evolution_ratio),
ngenerations, mutation_ratio, reproduction_ratio,
adaptation_ratio, SEED, 0., &evaluate,
&best_genome, &best_variables, &best_objective);
if (rank == 0)
{
file = fopen (argc[2], "w");
fprintf (file, "%.14le", best_objective);
printf ("objective=%.14le\n", best_objective);
fclose (file);
g_free (best_genome);
g_free (best_variables);
}
#if HAVE_MPI
MPI_Finalize ();
#endif
return 0;
}
| {
"alphanum_fraction": 0.61328125,
"avg_line_length": 25.2839506173,
"ext": "c",
"hexsha": "b123f6bd2797ce5ef33c17669c0ef9b7f7166df4",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/mpcotool",
"max_forks_repo_path": "tests/test2/simulator.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610",
"max_issues_repo_issues_event_max_datetime": "2016-03-08T17:02:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-03-08T17:02:14.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "jburguete/mpcotool",
"max_issues_repo_path": "tests/test2/simulator.c",
"max_line_length": 78,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/mpcotool",
"max_stars_repo_path": "tests/test2/simulator.c",
"max_stars_repo_stars_event_max_datetime": "2018-12-17T14:59:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-17T14:59:29.000Z",
"num_tokens": 621,
"size": 2048
} |
/* rng/mrg.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
/* This is a fifth-order multiple recursive generator. The sequence is,
x_n = (a_1 x_{n-1} + a_5 x_{n-5}) mod m
with a_1 = 107374182, a_2 = a_3 = a_4 = 0, a_5 = 104480 and m = 2^31-1.
We initialize the generator with x_n = s_n MOD m for n = 1..5,
where s_n = (69069 * s_{n-1}) mod 2^32, and s_0 = s is the
user-supplied seed.
NOTE: According to the paper the seeds must lie in the range [0,
2^31 - 2] with at least one non-zero value -- our seeding procedure
satisfies these constraints.
We then use 6 iterations of the generator to "warm up" the internal
state.
With this initialization procedure the theoretical value of
z_{10006} is 2064828650 for s = 1. The subscript 10006 means (1)
seed the generator with s = 1, (2) do the 6 warm-up iterations
that are part of the seeding process, (3) then do 10000 actual
iterations.
The period of this generator is about 2^155.
From: P. L'Ecuyer, F. Blouin, and R. Coutre, "A search for good
multiple recursive random number generators", ACM Transactions on
Modeling and Computer Simulation 3, 87-98 (1993). */
static inline unsigned long int mrg_get (void *vstate);
static double mrg_get_double (void *vstate);
static void mrg_set (void *state, unsigned long int s);
static const long int m = 2147483647;
static const long int a1 = 107374182, q1 = 20, r1 = 7;
static const long int a5 = 104480, q5 = 20554, r5 = 1727;
typedef struct
{
long int x1, x2, x3, x4, x5;
}
mrg_state_t;
static inline unsigned long int
mrg_get (void *vstate)
{
mrg_state_t *state = (mrg_state_t *) vstate;
long int p1, h1, p5, h5;
h5 = state->x5 / q5;
p5 = a5 * (state->x5 - h5 * q5) - h5 * r5;
if (p5 > 0)
p5 -= m;
h1 = state->x1 / q1;
p1 = a1 * (state->x1 - h1 * q1) - h1 * r1;
if (p1 < 0)
p1 += m;
state->x5 = state->x4;
state->x4 = state->x3;
state->x3 = state->x2;
state->x2 = state->x1;
state->x1 = p1 + p5;
if (state->x1 < 0)
state->x1 += m;
return state->x1;
}
static double
mrg_get_double (void *vstate)
{
return mrg_get (vstate) / 2147483647.0 ;
}
static void
mrg_set (void *vstate, unsigned long int s)
{
/* An entirely adhoc way of seeding! This does **not** come from
L'Ecuyer et al */
mrg_state_t *state = (mrg_state_t *) vstate;
if (s == 0)
s = 1; /* default seed is 1 */
#define LCG(n) ((69069 * n) & 0xffffffffUL)
s = LCG (s);
state->x1 = s % m;
s = LCG (s);
state->x2 = s % m;
s = LCG (s);
state->x3 = s % m;
s = LCG (s);
state->x4 = s % m;
s = LCG (s);
state->x5 = s % m;
/* "warm it up" with at least 5 calls to go through
all the x values */
mrg_get (state);
mrg_get (state);
mrg_get (state);
mrg_get (state);
mrg_get (state);
mrg_get (state);
return;
}
static const gsl_rng_type mrg_type =
{"mrg", /* name */
2147483646, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (mrg_state_t),
&mrg_set,
&mrg_get,
&mrg_get_double};
const gsl_rng_type *gsl_rng_mrg = &mrg_type;
| {
"alphanum_fraction": 0.6475115444,
"avg_line_length": 25.9866666667,
"ext": "c",
"hexsha": "b6632a1f7ae5ffa288085b989de93bd975b2cb94",
"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/rng/mrg.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/rng/mrg.c",
"max_line_length": 74,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/rng/mrg.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": 1314,
"size": 3898
} |
#pragma once
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include <gsl\gsl>
namespace Library
{
class BlendStates final
{
public:
inline static winrt::com_ptr<ID3D11BlendState> AlphaBlending;
inline static winrt::com_ptr<ID3D11BlendState> MultiplicativeBlending;
static void Initialize(gsl::not_null<ID3D11Device*> direct3DDevice);
static void Shutdown();
BlendStates() = delete;
BlendStates(const BlendStates&) = delete;
BlendStates& operator=(const BlendStates&) = delete;
BlendStates(BlendStates&&) = delete;
BlendStates& operator=(BlendStates&&) = delete;
~BlendStates() = default;
};
} | {
"alphanum_fraction": 0.7480190174,
"avg_line_length": 25.24,
"ext": "h",
"hexsha": "195df2052f0b73e5490ec279be0f79d91baac120",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_forks_repo_path": "source/Library.Shared/BlendStates.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_issues_repo_path": "source/Library.Shared/BlendStates.h",
"max_line_length": 72,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_stars_repo_path": "source/Library.Shared/BlendStates.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 175,
"size": 631
} |
/***************************************************************************/
/* */
/* vector.c - Vector class for mruby */
/* Copyright (C) 2015 Paolo Bosetti */
/* paolo[dot]bosetti[at]unitn.it */
/* Department of Industrial Engineering, University of Trento */
/* */
/* This library is free software. You can redistribute it and/or */
/* modify it under the terms of the GNU GENERAL PUBLIC LICENSE 2.0. */
/* */
/* 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 */
/* Artistic License 2.0 for more details. */
/* */
/* See the file LICENSE */
/* */
/***************************************************************************/
#include <gsl/gsl_blas.h>
#include <gsl/gsl_statistics_double.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/gsl_rng.h>
#include "vector.h"
#pragma mark -
#pragma mark • Utilities
// Garbage collector handler, for play_data struct
// if play_data contains other dynamic data, free it too!
// Check it with GC.start
void vector_destructor(mrb_state *mrb, void *p_) {
gsl_vector *v = (gsl_vector *)p_;
gsl_vector_free(v);
};
// Creating data type and reference for GC, in a const struct
const struct mrb_data_type vector_data_type = {"vector_data",
vector_destructor};
// Utility function for getting the struct out of the wrapping IV @data
void mrb_vector_get_data(mrb_state *mrb, mrb_value self, gsl_vector **data) {
mrb_value data_value;
data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@data"));
// Loading data from data_value into p_data:
Data_Get_Struct(mrb, data_value, &vector_data_type, *data);
if (!*data)
mrb_raise(mrb, E_RUNTIME_ERROR, "Could not access @data");
}
#pragma mark -
#pragma mark • Init and accessing
// Data Initializer C function (not exposed!)
static void mrb_vector_init(mrb_state *mrb, mrb_value self, mrb_int n) {
mrb_value data_value; // this IV holds the data
gsl_vector *p_data; // pointer to the C struct
data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@data"));
// if @data already exists, free its content:
if (!mrb_nil_p(data_value)) {
Data_Get_Struct(mrb, data_value, &vector_data_type, p_data);
free(p_data);
}
// Allocate and zero-out the data struct:
p_data = gsl_vector_calloc(n);
if (!p_data)
mrb_raise(mrb, E_RUNTIME_ERROR, "Could not allocate @data");
// Wrap struct into @data:
mrb_iv_set(
mrb, self, mrb_intern_lit(mrb, "@data"), // set @data
mrb_obj_value( // with value hold in struct
Data_Wrap_Struct(mrb, mrb->object_class, &vector_data_type, p_data)));
}
static mrb_value mrb_vector_initialize(mrb_state *mrb, mrb_value self) {
mrb_int n;
mrb_get_args(mrb, "i", &n);
// Call strcut initializer:
mrb_vector_init(mrb, self, n);
mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@length"), mrb_fixnum_value(n));
mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@format"),
mrb_str_new_cstr(mrb, "%10.3f"));
return mrb_nil_value();
}
static mrb_value mrb_vector_rnd_fill(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec = NULL;
const gsl_rng_type *T;
gsl_rng *r;
mrb_int h;
mrb_vector_get_data(mrb, self, &p_vec);
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
for (h = 0; h < p_vec->size; h++) {
gsl_vector_set(p_vec, h, gsl_rng_uniform(r));
}
return self;
}
static mrb_value mrb_vector_dup(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_vector *p_vec = NULL, *p_vec_other = NULL;
mrb_value args[1];
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
args[0] = mrb_fixnum_value(p_vec->size);
other = mrb_obj_new(mrb, mrb_class_get(mrb, "Vector"), 1, args);
mrb_vector_get_data(mrb, other, &p_vec_other);
gsl_vector_memcpy(p_vec_other, p_vec);
return other;
}
static mrb_value mrb_vector_all(mrb_state *mrb, mrb_value self) {
mrb_float v;
gsl_vector *p_vec = NULL;
mrb_get_args(mrb, "f", &v);
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
gsl_vector_set_all(p_vec, v);
return self;
}
static mrb_value mrb_vector_zero(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec = NULL;
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
gsl_vector_set_zero(p_vec);
return self;
}
static mrb_value mrb_vector_basis(mrb_state *mrb, mrb_value self) {
mrb_int i;
gsl_vector *p_vec = NULL;
mrb_get_args(mrb, "i", &i);
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
gsl_vector_set_basis(p_vec, i);
return self;
}
#pragma mark -
#pragma mark • Tests
static mrb_value mrb_vector_equal(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_vector *p_vec, *p_vec_other;
mrb_get_args(mrb, "o", &other);
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
mrb_vector_get_data(mrb, other, &p_vec_other);
if (1 == gsl_vector_equal(p_vec, p_vec_other))
return mrb_true_value();
else
return mrb_false_value();
}
#pragma mark -
#pragma mark • Accessors
static mrb_value mrb_vector_get_i(mrb_state *mrb, mrb_value self) {
mrb_int i = 0;
gsl_vector *p_vec = NULL;
mrb_get_args(mrb, "i", &i);
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
if (i >= p_vec->size) {
mrb_raise(mrb, E_VECTOR_ERROR, "Vector index out of range!");
}
return mrb_float_value(mrb, gsl_vector_get(p_vec, (size_t)i));
}
static mrb_value mrb_vector_set_i(mrb_state *mrb, mrb_value self) {
mrb_int i = 0;
mrb_float f;
gsl_vector *p_vec = NULL;
mrb_get_args(mrb, "if", &i, &f);
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
if (i >= p_vec->size) {
mrb_raise(mrb, E_VECTOR_ERROR, "Vector index out of range!");
}
gsl_vector_set(p_vec, (size_t)i, (double)f);
return mrb_float_value(mrb, f);
}
static mrb_value mrb_vector_to_a(mrb_state *mrb, mrb_value self) {
int i;
mrb_value ary = mrb_nil_value();
gsl_vector *p_vec = NULL;
mrb_float e;
mrb_vector_get_data(mrb, self, &p_vec);
ary = mrb_ary_new_capa(mrb, p_vec->size);
for (i = 0; i < p_vec->size; i++) {
e = *(p_vec->data + i * p_vec->stride);
mrb_ary_set(mrb, ary, i, mrb_float_value(mrb, e));
}
return ary;
}
#pragma mark -
#pragma mark • Properties
static mrb_value mrb_vector_max(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec = NULL;
mrb_vector_get_data(mrb, self, &p_vec);
return mrb_float_value(mrb, gsl_vector_max(p_vec));
}
static mrb_value mrb_vector_min(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec = NULL;
mrb_vector_get_data(mrb, self, &p_vec);
return mrb_float_value(mrb, gsl_vector_min(p_vec));
}
static mrb_value mrb_vector_max_index(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec = NULL;
mrb_vector_get_data(mrb, self, &p_vec);
return mrb_fixnum_value(gsl_vector_max_index(p_vec));
}
static mrb_value mrb_vector_min_index(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec = NULL;
mrb_vector_get_data(mrb, self, &p_vec);
return mrb_fixnum_value(gsl_vector_min_index(p_vec));
}
#pragma mark -
#pragma mark • Operations
static mrb_value mrb_vector_add(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_vector *p_vec, *p_vec_other;
mrb_get_args(mrb, "o", &other);
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, "Vector"))) {
mrb_vector_get_data(mrb, other, &p_vec_other);
if (p_vec->size != p_vec_other->size) {
mrb_raise(mrb, E_VECTOR_ERROR, "Vector indexes don't match!");
}
gsl_vector_add(p_vec, p_vec_other);
} else if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, "Numeric"))) {
gsl_vector_add_constant(p_vec, mrb_to_flo(mrb, other));
}
return self;
}
static mrb_value mrb_vector_sub(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_vector *p_vec, *p_vec_other;
mrb_get_args(mrb, "o", &other);
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
mrb_vector_get_data(mrb, other, &p_vec_other);
if (p_vec->size != p_vec_other->size) {
mrb_raise(mrb, E_VECTOR_ERROR, "Vector dimensions don't match!");
}
gsl_vector_sub(p_vec, p_vec_other);
return self;
}
static mrb_value mrb_vector_mul(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_vector *p_vec, *p_vec_other;
mrb_get_args(mrb, "o", &other);
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, "Vector"))) {
mrb_vector_get_data(mrb, other, &p_vec_other);
if (p_vec->size != p_vec_other->size) {
mrb_raise(mrb, E_VECTOR_ERROR, "Vector indexes don't match!");
}
gsl_vector_mul(p_vec, p_vec_other);
} else if (mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, "Numeric"))) {
gsl_vector_scale(p_vec, mrb_to_flo(mrb, other));
}
return self;
}
static mrb_value mrb_vector_div(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_vector *p_vec, *p_vec_other;
mrb_get_args(mrb, "o", &other);
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
mrb_vector_get_data(mrb, other, &p_vec_other);
if (p_vec->size != p_vec_other->size) {
mrb_raise(mrb, E_VECTOR_ERROR, "Vector indexes don't match!");
}
gsl_vector_div(p_vec, p_vec_other);
return self;
}
static mrb_value mrb_vector_prod(mrb_state *mrb, mrb_value self) {
mrb_value other;
gsl_vector *p_vec, *p_vec_other;
mrb_float res;
mrb_get_args(mrb, "o", &other);
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
mrb_vector_get_data(mrb, other, &p_vec_other);
if (!mrb_obj_is_kind_of(mrb, other, mrb_class_get(mrb, "Vector"))) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "Need a Vector!");
}
if (p_vec->size != p_vec_other->size) {
mrb_raise(mrb, E_VECTOR_ERROR, "Vector indexes don't match!");
}
if (gsl_blas_ddot(p_vec, p_vec_other, &res)) {
mrb_raise(mrb, E_VECTOR_ERROR, "Cannot multiply");
}
return mrb_float_value(mrb, res);
}
static mrb_value mrb_vector_norm(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec;
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
return mrb_float_value(mrb, gsl_blas_dnrm2(p_vec));
}
static mrb_value mrb_vector_sum(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec;
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
return mrb_float_value(mrb, gsl_blas_dasum(p_vec));
}
static mrb_value mrb_vector_swap(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec;
mrb_int i, j;
mrb_get_args(mrb, "ii", &i, &j);
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
if (gsl_vector_swap_elements(p_vec, i, j)) {
mrb_raise(mrb, E_VECTOR_ERROR, "Cannot swap");
}
return self;
}
static mrb_value mrb_vector_reverse(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec;
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
if (gsl_vector_reverse(p_vec)) {
mrb_raise(mrb, E_VECTOR_ERROR, "Cannot reverse");
}
return self;
}
#pragma mark -
#pragma mark • Statistics
static mrb_value mrb_vector_mean(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec;
mrb_float result;
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
result = gsl_stats_mean(p_vec->data, p_vec->stride, p_vec->size);
return mrb_float_value(mrb, result);
}
static mrb_value mrb_vector_variance(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec;
mrb_float result;
mrb_float m;
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
if (mrb_get_args(mrb, "|f", &m) == 1) {
result = gsl_stats_variance_m(p_vec->data, p_vec->stride, p_vec->size, m);
} else {
result = gsl_stats_variance(p_vec->data, p_vec->stride, p_vec->size);
}
return mrb_float_value(mrb, result);
}
static mrb_value mrb_vector_sd(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec;
mrb_float result;
mrb_float m;
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
if (mrb_get_args(mrb, "|f", &m) == 1) {
result = gsl_stats_sd_m(p_vec->data, p_vec->stride, p_vec->size, m);
} else {
result = gsl_stats_sd(p_vec->data, p_vec->stride, p_vec->size);
}
return mrb_float_value(mrb, result);
}
static mrb_value mrb_vector_absdev(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec;
mrb_float result;
mrb_float m;
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
if (mrb_get_args(mrb, "|f", &m) == 1) {
result = gsl_stats_absdev_m(p_vec->data, p_vec->stride, p_vec->size, m);
} else {
result = gsl_stats_absdev(p_vec->data, p_vec->stride, p_vec->size);
}
return mrb_float_value(mrb, result);
}
static mrb_value mrb_vector_quantile(mrb_state *mrb, mrb_value self) {
gsl_vector *p_vec = NULL, *p_sort_vec = NULL;
mrb_float result;
mrb_float f;
mrb_int n;
// call utility for unwrapping @data into p_data:
mrb_vector_get_data(mrb, self, &p_vec);
n = mrb_get_args(mrb, "|f", &f);
if (f < 0 || f > 1) {
mrb_raise(mrb, E_VECTOR_ERROR, "Quantile must be in [0,1]");
}
p_sort_vec = gsl_vector_calloc(p_vec->size);
if (gsl_vector_memcpy(p_sort_vec, p_vec)) {
mrb_raise(mrb, E_VECTOR_ERROR, "Cannot copy vector");
}
gsl_sort_vector(p_sort_vec);
if (n == 1) {
result = gsl_stats_quantile_from_sorted_data(
p_sort_vec->data, p_sort_vec->stride, p_sort_vec->size, f);
} else {
result = gsl_stats_quantile_from_sorted_data(
p_sort_vec->data, p_sort_vec->stride, p_sort_vec->size, 0.5);
}
return mrb_float_value(mrb, result);
}
#pragma mark -
#pragma mark • Gem setup
void mrb_gsl_vector_init(mrb_state *mrb) {
struct RClass *gsl;
mrb_load_string(mrb, "class VectorError < Exception; end");
gsl = mrb_define_class(mrb, "Vector", mrb->object_class);
mrb_define_method(mrb, gsl, "all", mrb_vector_all, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "zero", mrb_vector_zero, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "basis", mrb_vector_basis, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "initialize", mrb_vector_initialize,
MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "rnd_fill", mrb_vector_rnd_fill,
MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "dup", mrb_vector_dup, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "===", mrb_vector_equal, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "[]", mrb_vector_get_i, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "[]=", mrb_vector_set_i, MRB_ARGS_REQ(2));
mrb_define_method(mrb, gsl, "to_a", mrb_vector_to_a, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "max", mrb_vector_max, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "min", mrb_vector_min, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "max_index", mrb_vector_max_index,
MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "min_index", mrb_vector_min_index,
MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "add!", mrb_vector_add, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "sub!", mrb_vector_sub, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "mul!", mrb_vector_mul, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "div!", mrb_vector_div, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "^", mrb_vector_prod, MRB_ARGS_REQ(1));
mrb_define_method(mrb, gsl, "norm", mrb_vector_norm, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "sum", mrb_vector_sum, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "swap!", mrb_vector_swap, MRB_ARGS_REQ(2));
mrb_define_method(mrb, gsl, "reverse!", mrb_vector_reverse, MRB_ARGS_NONE());
mrb_define_method(mrb, gsl, "mean", mrb_vector_mean, MRB_ARGS_OPT(1));
mrb_define_method(mrb, gsl, "variance", mrb_vector_variance, MRB_ARGS_OPT(1));
mrb_define_method(mrb, gsl, "sd", mrb_vector_sd, MRB_ARGS_OPT(1));
mrb_define_method(mrb, gsl, "absdev", mrb_vector_absdev, MRB_ARGS_OPT(1));
mrb_define_method(mrb, gsl, "quantile", mrb_vector_quantile, MRB_ARGS_OPT(1));
}
| {
"alphanum_fraction": 0.6771703807,
"avg_line_length": 34.0553359684,
"ext": "c",
"hexsha": "a2233a87b80c8b57a91ef0b046997146946f0a61",
"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": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "UniTN-Mechatronics/mruby-gsl",
"max_forks_repo_path": "src/vector.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b",
"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": "UniTN-Mechatronics/mruby-gsl",
"max_issues_repo_path": "src/vector.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "UniTN-Mechatronics/mruby-gsl",
"max_stars_repo_path": "src/vector.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4882,
"size": 17232
} |
/* gsl_sf_hermite.h
*
* Copyright (C) 2011-2014 Konrad Griessinger
*
* 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.
*/
/*----------------------------------------------------------------------*
* (konradg(at)gmx.net) *
*----------------------------------------------------------------------*/
#ifndef __GSL_SF_HERMITE_H__
#define __GSL_SF_HERMITE_H__
#include <gsl/gsl_sf_result.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
int gsl_sf_hermite_prob_e(const int n, const double x, gsl_sf_result * result);
double gsl_sf_hermite_prob(const int n, const double x);
int gsl_sf_hermite_prob_deriv_e(const int m, const int n, const double x, gsl_sf_result * result);
double gsl_sf_hermite_prob_deriv(const int m, const int n, const double x);
int gsl_sf_hermite_e(const int n, const double x, gsl_sf_result * result);
double gsl_sf_hermite(const int n, const double x);
int gsl_sf_hermite_deriv_e(const int m, const int n, const double x, gsl_sf_result * result);
double gsl_sf_hermite_deriv(const int m, const int n, const double x);
int gsl_sf_hermite_func_e(const int n, const double x, gsl_sf_result * result);
double gsl_sf_hermite_func(const int n, const double x);
int gsl_sf_hermite_func_fast_e(const int n, const double x, gsl_sf_result * result);
double gsl_sf_hermite_func_fast(const int n, const double x);
int gsl_sf_hermite_prob_array(const int nmax, const double x, double * result_array);
int gsl_sf_hermite_prob_array_deriv(const int m, const int nmax, const double x, double * result_array);
int gsl_sf_hermite_prob_deriv_array(const int mmax, const int n, const double x, double * result_array);
int gsl_sf_hermite_prob_series_e(const int n, const double x, const double * a, gsl_sf_result * result);
double gsl_sf_hermite_prob_series(const int n, const double x, const double * a);
int gsl_sf_hermite_array(const int nmax, const double x, double * result_array);
int gsl_sf_hermite_array_deriv(const int m, const int nmax, const double x, double * result_array);
int gsl_sf_hermite_deriv_array(const int mmax, const int n, const double x, double * result_array);
int gsl_sf_hermite_series_e(const int n, const double x, const double * a, gsl_sf_result * result);
double gsl_sf_hermite_series(const int n, const double x, const double * a);
int gsl_sf_hermite_func_array(const int nmax, const double x, double * result_array);
int gsl_sf_hermite_func_series_e(const int n, const double x, const double * a, gsl_sf_result * result);
double gsl_sf_hermite_func_series(const int n, const double x, const double * a);
int gsl_sf_hermite_func_der_e(const int m, const int n, const double x, gsl_sf_result * result);
double gsl_sf_hermite_func_der(const int m, const int n, const double x);
int gsl_sf_hermite_prob_zero_e(const int n, const int s, gsl_sf_result * result);
double gsl_sf_hermite_prob_zero(const int n, const int s);
int gsl_sf_hermite_zero_e(const int n, const int s, gsl_sf_result * result);
double gsl_sf_hermite_zero(const int n, const int s);
int gsl_sf_hermite_func_zero_e(const int n, const int s, gsl_sf_result * result);
double gsl_sf_hermite_func_zero(const int n, const int s);
#ifndef GSL_DISABLE_DEPRECATED
int gsl_sf_hermite_phys_e(const int n, const double x, gsl_sf_result * result);
double gsl_sf_hermite_phys(const int n, const double x);
int gsl_sf_hermite_phys_der_e(const int m, const int n, const double x, gsl_sf_result * result);
double gsl_sf_hermite_phys_der(const int m, const int n, const double x);
int gsl_sf_hermite_phys_array(const int nmax, const double x, double * result_array);
int gsl_sf_hermite_phys_series_e(const int n, const double x, const double * a, gsl_sf_result * result);
double gsl_sf_hermite_phys_series(const int n, const double x, const double * a);
int gsl_sf_hermite_phys_array_der(const int m, const int nmax, const double x, double * result_array);
int gsl_sf_hermite_phys_der_array(const int mmax, const int n, const double x, double * result_array);
int gsl_sf_hermite_phys_zero_e(const int n, const int s, gsl_sf_result * result);
double gsl_sf_hermite_phys_zero(const int n, const int s);
int gsl_sf_hermite_prob_array_der(const int m, const int nmax, const double x, double * result_array);
int gsl_sf_hermite_prob_der_array(const int mmax, const int n, const double x, double * result_array);
int gsl_sf_hermite_prob_der_e(const int m, const int n, const double x, gsl_sf_result * result);
double gsl_sf_hermite_prob_der(const int m, const int n, const double x);
#endif /* !GSL_DISABLE_DEPRECATED */
__END_DECLS
#endif /* __GSL_SF_HERMITE_H__ */
| {
"alphanum_fraction": 0.7455760202,
"avg_line_length": 55.9393939394,
"ext": "h",
"hexsha": "1d7088a0aa5b10682acb8100afd4d5978fc8c78a",
"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": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ielomariala/Hex-Game",
"max_forks_repo_path": "gsl-2.6/gsl/gsl_sf_hermite.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/gsl/gsl_sf_hermite.h",
"max_line_length": 105,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/gsl/gsl_sf_hermite.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1394,
"size": 5538
} |
// matrix/kaldi-blas.h
// Copyright 2009-2011 Ondrej Glembek; Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#ifndef KALDI_MATRIX_KALDI_BLAS_H_
#define KALDI_MATRIX_KALDI_BLAS_H_
// This file handles the #includes for BLAS, LAPACK and so on.
// It manipulates the declarations into a common format that kaldi can handle.
// However, the kaldi code will check whether HAVE_ATLAS is defined as that
// code is called a bit differently from CLAPACK that comes from other sources.
// There are three alternatives:
// (i) you have ATLAS, which includes the ATLAS implementation of CBLAS
// plus a subset of CLAPACK (but with clapack_ in the function declarations).
// In this case, define HAVE_ATLAS and make sure the relevant directories are
// in the include path.
// (ii) you have CBLAS (some implementation thereof) plus CLAPACK.
// In this case, define HAVE_CLAPACK.
// [Since CLAPACK depends on BLAS, the presence of BLAS is implicit].
// (iii) you have the MKL library, which includes CLAPACK and CBLAS.
// Note that if we are using ATLAS, no Svd implementation is supplied,
// so we define HAVE_Svd to be zero and this directs our implementation to
// supply its own "by hand" implementation which is based on TNT code.
#if (defined(HAVE_CLAPACK) && (defined(HAVE_ATLAS) || defined(HAVE_MKL))) \
|| (defined(HAVE_ATLAS) && defined(HAVE_MKL))
#error "Do not define more than one of HAVE_CLAPACK, HAVE_ATLAS and HAVE_MKL"
#endif
#ifdef HAVE_ATLAS
extern "C" {
#include <cblas.h>
#include <clapack.h>
}
#elif defined(HAVE_CLAPACK)
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
typedef __CLPK_integer integer;
typedef __CLPK_logical logical;
typedef __CLPK_real real;
typedef __CLPK_doublereal doublereal;
typedef __CLPK_complex complex;
typedef __CLPK_doublecomplex doublecomplex;
typedef __CLPK_ftnlen ftnlen;
#else
extern "C" {
// May be in /usr/[local]/include if installed; else this uses the one
// from the external/CLAPACK-* directory.
#include <cblas.h>
#include <f2c.h>
#include <clapack.h>
// get rid of macros from f2c.h -- these are dangerous.
#undef abs
#undef dabs
#undef min
#undef max
#undef dmin
#undef dmax
#undef bit_test
#undef bit_clear
#undef bit_set
}
#endif
#elif defined(HAVE_MKL)
extern "C" {
#include <mkl.h>
}
#else
#error "You need to define (using the preprocessor) either HAVE_CLAPACK or HAVE_ATLAS or HAVE_MKL (but not more than one)"
#endif
#ifdef HAVE_CLAPACK
typedef integer KaldiBlasInt;
#endif
#ifdef HAVE_MKL
typedef MKL_INT KaldiBlasInt;
#endif
#ifdef HAVE_ATLAS
// in this case there is no need for KaldiBlasInt-- this typedef is only needed
// for Svd code which is not included in ATLAS (we re-implement it).
#endif
#endif // KALDI_MATRIX_KALDI_BLAS_H_
| {
"alphanum_fraction": 0.7127959414,
"avg_line_length": 33.4716981132,
"ext": "h",
"hexsha": "23b986c07d84d574cbb2f0adfe52c3c294b00581",
"lang": "C",
"max_forks_count": 47,
"max_forks_repo_forks_event_max_datetime": "2021-11-11T20:59:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-27T06:22:57.000Z",
"max_forks_repo_head_hexsha": "861f838a2aea264a9e4ffa4df253df00a8b1247f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "UdyanSachdev/kaldi",
"max_forks_repo_path": "src/matrix/kaldi-blas.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "861f838a2aea264a9e4ffa4df253df00a8b1247f",
"max_issues_repo_issues_event_max_datetime": "2018-12-18T17:43:44.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-18T17:43:44.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "UdyanSachdev/kaldi",
"max_issues_repo_path": "src/matrix/kaldi-blas.h",
"max_line_length": 126,
"max_stars_count": 19,
"max_stars_repo_head_hexsha": "861f838a2aea264a9e4ffa4df253df00a8b1247f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "hihihippp/Kaldi",
"max_stars_repo_path": "src/matrix/kaldi-blas.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-17T06:12:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-19T10:53:38.000Z",
"num_tokens": 943,
"size": 3548
} |
/* rng/ran3.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2010 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
/* This is an implementation of the algorithm used in Knuths's
subtractive generator, with the Numerical Recipe's ran3 paramters.
It is a subtractive lagged fibonnaci generator. */
static inline unsigned long int ran3_get (void *vstate);
static double ran3_get_double (void *vstate);
static void ran3_set (void *state, unsigned long int s);
#define M_BIG 1000000000
#define M_SEED 161803398
typedef struct
{
unsigned int x;
unsigned int y;
unsigned long int buffer[56];
}
ran3_state_t;
static inline unsigned long int
ran3_get (void *vstate)
{
ran3_state_t *state = (ran3_state_t *) vstate;
long int j;
state->x++;
if (state->x == 56)
state->x = 1;
state->y++;
if (state->y == 56)
state->y = 1;
j = state->buffer[state->x] - state->buffer[state->y];
if (j < 0)
j += M_BIG;
state->buffer[state->x] = j;
return j;
}
static double
ran3_get_double (void *vstate)
{
return ran3_get (vstate) / (double) M_BIG ;
}
static void
ran3_set (void *vstate, unsigned long int s)
{
ran3_state_t *state = (ran3_state_t *) vstate;
int i, i1;
long int j, k;
if (s == 0)
s = 1; /* default seed is 1 */
j = (M_SEED - s) % M_BIG;
/* Avoid potential problem with negative values */
if (j < 0) j += M_BIG;
/* the zeroth element is never used, but we initialize it for
consistency between states */
state->buffer[0] = 0;
state->buffer[55] = j;
k = 1;
for (i = 1; i < 55; i++)
{
int n = (21 * i) % 55;
state->buffer[n] = k;
k = j - k;
if (k < 0)
k += M_BIG;
j = state->buffer[n];
}
for (i1 = 0; i1 < 4; i1++)
{
for (i = 1; i < 56; i++)
{
long int t = state->buffer[i] - state->buffer[1 + (i + 30) % 55];
if (t < 0)
t += M_BIG;
state->buffer[i] = t;
}
}
state->x = 0;
state->y = 31;
return;
}
static const gsl_rng_type ran3_type =
{"ran3", /* name */
M_BIG, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (ran3_state_t),
&ran3_set,
&ran3_get,
&ran3_get_double};
const gsl_rng_type *gsl_rng_ran3 = &ran3_type;
| {
"alphanum_fraction": 0.6112185687,
"avg_line_length": 22.8088235294,
"ext": "c",
"hexsha": "d855d2547ac4a9c659fb8ffeb56dc7b4631aaca5",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/ran3.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/rng/ran3.c",
"max_line_length": 84,
"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/rng/ran3.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": 942,
"size": 3102
} |
#ifndef ENVIRONMENT_INCLUDE
#define ENVIRONMENT_INCLUDE
#include <map>
#include <string>
#include <vector>
#include <gsl/string_span>
namespace execHelper {
namespace config {
using EnvArg = std::string;
using EnvArgs = std::vector<EnvArg>;
using EnvironmentCollection = std::map<std::string, EnvArg>;
using EnvironmentValue = std::pair<std::string, EnvArg>;
static const gsl::czstring<> ENVIRONMENT_KEY = "environment";
} // namespace config
} // namespace execHelper
#endif /* ENVIRONMENT_INCLUDE */
| {
"alphanum_fraction": 0.7544204322,
"avg_line_length": 21.2083333333,
"ext": "h",
"hexsha": "2e0889770fc3fdca636f3b72a790eb13811f04dc",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z",
"max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "exec-helper/source",
"max_forks_repo_path": "src/config/include/config/environment.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "exec-helper/source",
"max_issues_repo_path": "src/config/include/config/environment.h",
"max_line_length": 61,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "exec-helper/source",
"max_stars_repo_path": "src/config/include/config/environment.h",
"max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z",
"num_tokens": 114,
"size": 509
} |
/* matrix/gsl_matrix_uint.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_UINT_H__
#define __GSL_MATRIX_UINT_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_uint.h>
#include <gsl/gsl_blas_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size1;
size_t size2;
size_t tda;
unsigned int * data;
gsl_block_uint * block;
int owner;
} gsl_matrix_uint;
typedef struct
{
gsl_matrix_uint matrix;
} _gsl_matrix_uint_view;
typedef _gsl_matrix_uint_view gsl_matrix_uint_view;
typedef struct
{
gsl_matrix_uint matrix;
} _gsl_matrix_uint_const_view;
typedef const _gsl_matrix_uint_const_view gsl_matrix_uint_const_view;
/* Allocation */
GSL_FUN gsl_matrix_uint *
gsl_matrix_uint_alloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_uint *
gsl_matrix_uint_calloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_uint *
gsl_matrix_uint_alloc_from_block (gsl_block_uint * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
GSL_FUN gsl_matrix_uint *
gsl_matrix_uint_alloc_from_matrix (gsl_matrix_uint * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
GSL_FUN gsl_vector_uint *
gsl_vector_uint_alloc_row_from_matrix (gsl_matrix_uint * m,
const size_t i);
GSL_FUN gsl_vector_uint *
gsl_vector_uint_alloc_col_from_matrix (gsl_matrix_uint * m,
const size_t j);
GSL_FUN void gsl_matrix_uint_free (gsl_matrix_uint * m);
/* Views */
GSL_FUN _gsl_matrix_uint_view
gsl_matrix_uint_submatrix (gsl_matrix_uint * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_uint_view
gsl_matrix_uint_row (gsl_matrix_uint * m, const size_t i);
GSL_FUN _gsl_vector_uint_view
gsl_matrix_uint_column (gsl_matrix_uint * m, const size_t j);
GSL_FUN _gsl_vector_uint_view
gsl_matrix_uint_diagonal (gsl_matrix_uint * m);
GSL_FUN _gsl_vector_uint_view
gsl_matrix_uint_subdiagonal (gsl_matrix_uint * m, const size_t k);
GSL_FUN _gsl_vector_uint_view
gsl_matrix_uint_superdiagonal (gsl_matrix_uint * m, const size_t k);
GSL_FUN _gsl_vector_uint_view
gsl_matrix_uint_subrow (gsl_matrix_uint * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_uint_view
gsl_matrix_uint_subcolumn (gsl_matrix_uint * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_uint_view
gsl_matrix_uint_view_array (unsigned int * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_uint_view
gsl_matrix_uint_view_array_with_tda (unsigned int * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_uint_view
gsl_matrix_uint_view_vector (gsl_vector_uint * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_uint_view
gsl_matrix_uint_view_vector_with_tda (gsl_vector_uint * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_uint_const_view
gsl_matrix_uint_const_submatrix (const gsl_matrix_uint * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_uint_const_view
gsl_matrix_uint_const_row (const gsl_matrix_uint * m,
const size_t i);
GSL_FUN _gsl_vector_uint_const_view
gsl_matrix_uint_const_column (const gsl_matrix_uint * m,
const size_t j);
GSL_FUN _gsl_vector_uint_const_view
gsl_matrix_uint_const_diagonal (const gsl_matrix_uint * m);
GSL_FUN _gsl_vector_uint_const_view
gsl_matrix_uint_const_subdiagonal (const gsl_matrix_uint * m,
const size_t k);
GSL_FUN _gsl_vector_uint_const_view
gsl_matrix_uint_const_superdiagonal (const gsl_matrix_uint * m,
const size_t k);
GSL_FUN _gsl_vector_uint_const_view
gsl_matrix_uint_const_subrow (const gsl_matrix_uint * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_uint_const_view
gsl_matrix_uint_const_subcolumn (const gsl_matrix_uint * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_uint_const_view
gsl_matrix_uint_const_view_array (const unsigned int * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_uint_const_view
gsl_matrix_uint_const_view_array_with_tda (const unsigned int * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_uint_const_view
gsl_matrix_uint_const_view_vector (const gsl_vector_uint * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_uint_const_view
gsl_matrix_uint_const_view_vector_with_tda (const gsl_vector_uint * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_FUN void gsl_matrix_uint_set_zero (gsl_matrix_uint * m);
GSL_FUN void gsl_matrix_uint_set_identity (gsl_matrix_uint * m);
GSL_FUN void gsl_matrix_uint_set_all (gsl_matrix_uint * m, unsigned int x);
GSL_FUN int gsl_matrix_uint_fread (FILE * stream, gsl_matrix_uint * m) ;
GSL_FUN int gsl_matrix_uint_fwrite (FILE * stream, const gsl_matrix_uint * m) ;
GSL_FUN int gsl_matrix_uint_fscanf (FILE * stream, gsl_matrix_uint * m);
GSL_FUN int gsl_matrix_uint_fprintf (FILE * stream, const gsl_matrix_uint * m, const char * format);
GSL_FUN int gsl_matrix_uint_memcpy(gsl_matrix_uint * dest, const gsl_matrix_uint * src);
GSL_FUN int gsl_matrix_uint_swap(gsl_matrix_uint * m1, gsl_matrix_uint * m2);
GSL_FUN int gsl_matrix_uint_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_uint * dest, const gsl_matrix_uint * src);
GSL_FUN int gsl_matrix_uint_swap_rows(gsl_matrix_uint * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_uint_swap_columns(gsl_matrix_uint * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_uint_swap_rowcol(gsl_matrix_uint * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_uint_transpose (gsl_matrix_uint * m);
GSL_FUN int gsl_matrix_uint_transpose_memcpy (gsl_matrix_uint * dest, const gsl_matrix_uint * src);
GSL_FUN int gsl_matrix_uint_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_uint * dest, const gsl_matrix_uint * src);
GSL_FUN unsigned int gsl_matrix_uint_max (const gsl_matrix_uint * m);
GSL_FUN unsigned int gsl_matrix_uint_min (const gsl_matrix_uint * m);
GSL_FUN void gsl_matrix_uint_minmax (const gsl_matrix_uint * m, unsigned int * min_out, unsigned int * max_out);
GSL_FUN void gsl_matrix_uint_max_index (const gsl_matrix_uint * m, size_t * imax, size_t *jmax);
GSL_FUN void gsl_matrix_uint_min_index (const gsl_matrix_uint * m, size_t * imin, size_t *jmin);
GSL_FUN void gsl_matrix_uint_minmax_index (const gsl_matrix_uint * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_FUN int gsl_matrix_uint_equal (const gsl_matrix_uint * a, const gsl_matrix_uint * b);
GSL_FUN int gsl_matrix_uint_isnull (const gsl_matrix_uint * m);
GSL_FUN int gsl_matrix_uint_ispos (const gsl_matrix_uint * m);
GSL_FUN int gsl_matrix_uint_isneg (const gsl_matrix_uint * m);
GSL_FUN int gsl_matrix_uint_isnonneg (const gsl_matrix_uint * m);
GSL_FUN unsigned int gsl_matrix_uint_norm1 (const gsl_matrix_uint * m);
GSL_FUN int gsl_matrix_uint_add (gsl_matrix_uint * a, const gsl_matrix_uint * b);
GSL_FUN int gsl_matrix_uint_sub (gsl_matrix_uint * a, const gsl_matrix_uint * b);
GSL_FUN int gsl_matrix_uint_mul_elements (gsl_matrix_uint * a, const gsl_matrix_uint * b);
GSL_FUN int gsl_matrix_uint_div_elements (gsl_matrix_uint * a, const gsl_matrix_uint * b);
GSL_FUN int gsl_matrix_uint_scale (gsl_matrix_uint * a, const double x);
GSL_FUN int gsl_matrix_uint_scale_rows (gsl_matrix_uint * a, const gsl_vector_uint * x);
GSL_FUN int gsl_matrix_uint_scale_columns (gsl_matrix_uint * a, const gsl_vector_uint * x);
GSL_FUN int gsl_matrix_uint_add_constant (gsl_matrix_uint * a, const double x);
GSL_FUN int gsl_matrix_uint_add_diagonal (gsl_matrix_uint * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_FUN int gsl_matrix_uint_get_row(gsl_vector_uint * v, const gsl_matrix_uint * m, const size_t i);
GSL_FUN int gsl_matrix_uint_get_col(gsl_vector_uint * v, const gsl_matrix_uint * m, const size_t j);
GSL_FUN int gsl_matrix_uint_set_row(gsl_matrix_uint * m, const size_t i, const gsl_vector_uint * v);
GSL_FUN int gsl_matrix_uint_set_col(gsl_matrix_uint * m, const size_t j, const gsl_vector_uint * v);
/***********************************************************************/
/* inline functions if you are using GCC */
GSL_FUN INLINE_DECL unsigned int gsl_matrix_uint_get(const gsl_matrix_uint * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL void gsl_matrix_uint_set(gsl_matrix_uint * m, const size_t i, const size_t j, const unsigned int x);
GSL_FUN INLINE_DECL unsigned int * gsl_matrix_uint_ptr(gsl_matrix_uint * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL const unsigned int * gsl_matrix_uint_const_ptr(const gsl_matrix_uint * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
unsigned int
gsl_matrix_uint_get(const gsl_matrix_uint * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
}
}
#endif
return m->data[i * m->tda + j] ;
}
INLINE_FUN
void
gsl_matrix_uint_set(gsl_matrix_uint * m, const size_t i, const size_t j, const unsigned int x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
}
#endif
m->data[i * m->tda + j] = x ;
}
INLINE_FUN
unsigned int *
gsl_matrix_uint_ptr(gsl_matrix_uint * 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 (unsigned int *) (m->data + (i * m->tda + j)) ;
}
INLINE_FUN
const unsigned int *
gsl_matrix_uint_const_ptr(const gsl_matrix_uint * 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 unsigned int *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_UINT_H__ */
| {
"alphanum_fraction": 0.6510144096,
"avg_line_length": 37.9048913043,
"ext": "h",
"hexsha": "d6de1b3644fc5b136826c61372c883823bde02a0",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/VimbaCamJILA",
"max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_matrix_uint.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/VimbaCamJILA",
"max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_matrix_uint.h",
"max_line_length": 142,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mgreter/astrometrylib",
"max_stars_repo_path": "vendor/gsl/gsl/gsl_matrix_uint.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": 3381,
"size": 13949
} |
#pragma once
#include "BooleanNodes.h"
#include "BooleanDAG.h"
#include "NodeVisitor.h"
#include "VarStore.h"
#include <map>
#include "FloatSupport.h"
#include <tuple>
#include <iostream>
#ifndef _NOGSL
#include <gsl/gsl_vector.h>
#else
#include "CustomSolver.h"
#endif
#include "Util.h"
#include "Interface.h"
using namespace std;
class SimpleEvaluator: NodeVisitor
{
BooleanDAG& bdag;
map<string, int>& floatCtrls; // Maps float ctrl names to indices with grad vectors
gsl_vector* ctrls; // ctrl values
vector<double> distances; // Keeps track of distance metric for boolean nodes
double MIN_VALUE = 0.001;
Interface* inputValues;
int DEFAULT_INPUT = -32;
public:
SimpleEvaluator(BooleanDAG& bdag_p, map<string, int>& floatCtrls_p);
virtual ~SimpleEvaluator();
virtual void visit( SRC_node& node );
virtual void visit( DST_node& node );
virtual void visit( CTRL_node& node );
virtual void visit( PLUS_node& node );
virtual void visit( TIMES_node& node );
virtual void visit( ARRACC_node& node );
virtual void visit( DIV_node& node );
virtual void visit( MOD_node& node );
virtual void visit( NEG_node& node );
virtual void visit( CONST_node& node );
virtual void visit( LT_node& node );
virtual void visit( EQ_node& node );
virtual void visit( AND_node& node );
virtual void visit( OR_node& node );
virtual void visit( NOT_node& node );
virtual void visit( ARRASS_node& node );
virtual void visit( UFUN_node& node );
virtual void visit( TUPLE_R_node& node );
virtual void visit( ASSERT_node& node );
void setInputs(Interface* inputValues_p);
void run(const gsl_vector* ctrls_p);
double getErrorOnConstraint(int nodeid);
double getSqrtError(bool_node* node);
double getAssertError(bool_node* node);
double getBoolCtrlError(bool_node* node);
double getBoolExprError(bool_node* node);
double dist(int nodeid) {
return d(bdag[nodeid]);
}
void setvalue(bool_node& bn, double d) {
distances[bn.id] = d;
}
double d(bool_node& bn) {
return distances[bn.id];
}
double d(bool_node* bn) {
return d(*bn);
}
void print() {
for (int i = 0; i < bdag.size(); i++) {
cout << bdag[i]->lprint() << endl;
cout << d(bdag[i]) << endl;
}
}
bool isFloat(bool_node& bn) {
return (bn.getOtype() == OutType::FLOAT);
}
bool isFloat(bool_node* bn) {
return (bn->getOtype() == OutType::FLOAT);
}
int getInputValue(bool_node& bn) {
if (inputValues->hasValue(bn.id)) {
int val = inputValues->getValue(bn.id);
return val;
} else {
return DEFAULT_INPUT;
}
}
int getInputValue(bool_node* bn) {
return getInputValue(*bn);
}
};
| {
"alphanum_fraction": 0.6219429348,
"avg_line_length": 25.8245614035,
"ext": "h",
"hexsha": "26d51f76e7bea7304799c3d06e49d6ca928b72a9",
"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/SymbolicEvaluators/SimpleEvaluator.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/SymbolicEvaluators/SimpleEvaluator.h",
"max_line_length": 87,
"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/SymbolicEvaluators/SimpleEvaluator.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": 733,
"size": 2944
} |
#include <geometry/basic_c.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <math.h>
#include <stdio.h>
// author: Andrew Liew <liew@arch.ethz.ch>
// copyright: Copyright 2018, BLOCK Research Group - ETH Zurich
// license: MIT License
// email: liew@arch.ethz.ch
void drx_solver_c(
double tol, // Tolerance value.
int steps, // Maximum number of steps.
int summary, // Print summary at end (1:yes or 0:no).
int m, // Number of elements.
int n, // Number of nodes.
int *u, // Element start node.
int *v, // Element end node.
double *X, // Nodal co-ordinates.
double *f0, // Initial edge forces.
double *l0, // Initial edge lengths.
double *k0, // Initial edge axial stiffnesses.
int *ind_c, // Indices of compression only edges.
int *ind_t, // Indices of tension only edges.
int ind_c_n, // Length of ind_c.
int ind_t_n, // Length of ind_t.
double *B, // Constraint conditions Bx, By, Bz.
double *P, // Nodal loads Px, Py, Pz.
double *S, // Shear forces Sx, Sy, Sz.
int *rows, // Rows of Ct.
int *cols, // Columns of Ct.
double *vals, // Values of Ct.
int nv, // Length of rows/cols/vals.
double *M, // Mass matrix.
double factor, // Convergence factor.
double *V, // Nodal velocities Vx, Vy, Vz.
int *inds, // Indices of beam element start nodes.
int *indi, // Indices of beam element intermediate nodes.
int *indf, // Indices of beam element finish nodes beams.
double *EIx, // Nodal EIx flexural stiffnesses.
double *EIy, // Nodal EIy flexural stiffnesses.
int beams, // Includes beams:1 or not:0.
int nb) // Length of inds/indi/indf.
{
int a;
int b;
int c;
int i;
int j;
int k;
int nans[nb];
int ts;
double alpha;
double f[m];
double fx[m];
double fy[m];
double fz[m];
double frx[n];
double fry[n];
double frz[n];
double kappa;
double l;
double La;
double Lb;
double Lc;
double LQn;
double Lmu;
double Lc1;
double Lc2;
double Mi;
double Ms;
double q;
double res;
double Rx;
double Ry;
double Rz;
double Rn;
double Uo;
double Un;
double xd;
double yd;
double zd;
gsl_vector *Xs = gsl_vector_alloc(3);
gsl_vector *Xi = gsl_vector_alloc(3);
gsl_vector *Xf = gsl_vector_alloc(3);
gsl_vector *Qa = gsl_vector_alloc(3);
gsl_vector *Qb = gsl_vector_alloc(3);
gsl_vector *Qc = gsl_vector_alloc(3);
gsl_vector *Qn = gsl_vector_alloc(3);
gsl_vector *mu = gsl_vector_alloc(3);
gsl_vector *ex = gsl_vector_alloc(3);
gsl_vector *ey = gsl_vector_alloc(3);
gsl_vector *ez = gsl_vector_alloc(3);
gsl_vector *K = gsl_vector_alloc(3);
gsl_vector *Kx = gsl_vector_alloc(3);
gsl_vector *Ky = gsl_vector_alloc(3);
gsl_vector *Mc = gsl_vector_alloc(3);
gsl_vector *ua = gsl_vector_alloc(3);
gsl_vector *ub = gsl_vector_alloc(3);
gsl_vector *c1 = gsl_vector_alloc(3);
gsl_vector *c2 = gsl_vector_alloc(3);
gsl_matrix *Sa = gsl_matrix_alloc(nb, 3);
gsl_matrix *Sb = gsl_matrix_alloc(nb, 3);
ts = 0;
Uo = 0.;
res = 1000. * tol;
while (ts <= steps && res > tol)
{
#pragma omp parallel for private(i,j,k,xd,yd,zd,l,q)
for (i = 0; i < m; i++)
{
j = 3 * v[i];
k = 3 * u[i];
xd = X[j + 0] - X[k + 0];
yd = X[j + 1] - X[k + 1];
zd = X[j + 2] - X[k + 2];
l = gsl_hypot3(xd, yd, zd);
f[i] = f0[i] + k0[i] * (l - l0[i]);
q = f[i] / l;
fx[i] = xd * q;
fy[i] = yd * q;
fz[i] = zd * q;
}
if (ind_t_n > 0)
{
#pragma omp parallel for private(i)
for (i = 0; i < ind_t_n; i++)
{
if (f[i] < 0)
{
fx[i] = 0;
fy[i] = 0;
fz[i] = 0;
}
}
}
if (ind_c_n > 0)
{
#pragma omp parallel for private(i)
for (i = 0; i < ind_c_n; i++)
{
if (f[i] > 0)
{
fx[i] = 0;
fy[i] = 0;
fz[i] = 0;
}
}
}
if (beams)
{
#pragma omp parallel for private(i,j)
for (i = 0; i < n; i++)
{
j = i * 3;
S[j + 0] = 0.;
S[j + 1] = 0.;
S[j + 2] = 0.;
}
for (i = 0; i < nb; i++)
{
a = inds[i] * 3;
b = indi[i] * 3;
c = indf[i] * 3;
vector_from_pointer(&X[a], Xs);
vector_from_pointer(&X[b], Xi);
vector_from_pointer(&X[c], Xf);
subtract_vectors(Xi, Xs, Qa);
subtract_vectors(Xf, Xi, Qb);
subtract_vectors(Xf, Xs, Qc);
cross_vectors(Qa, Qb, Qn);
subtract_vectors(Xf, Xs, mu);
scale_vector(mu, 0.5);
La = length_vector(Qa);
Lb = length_vector(Qb);
Lc = length_vector(Qc);
LQn = length_vector(Qn);
Lmu = length_vector(mu);
alpha = acos((gsl_pow_2(La) + gsl_pow_2(Lb) - gsl_pow_2(Lc)) / (2. * La * Lb));
kappa = 2. * sin(alpha) / Lc;
gsl_vector_memcpy(ex, Qn);
gsl_vector_memcpy(ez, mu);
scale_vector(ex, 1./LQn);
scale_vector(ez, 1./Lmu);
cross_vectors(ez, ex, ey);
gsl_vector_memcpy(K, Qn);
scale_vector(K, kappa/LQn);
gsl_vector_memcpy(Kx, ex);
gsl_vector_memcpy(Ky, ey);
scale_vector(Kx, dot_vectors(K, ex));
scale_vector(Ky, dot_vectors(K, ey));
scale_vector(Kx, EIx[i]);
scale_vector(Ky, EIy[i]);
add_vectors(Kx, Ky, Mc);
cross_vectors(Mc, Qa, ua);
cross_vectors(Mc, Qb, ub);
normalize_vector(ua);
normalize_vector(ub);
cross_vectors(Qa, ua, c1);
cross_vectors(Qb, ub, c2);
Lc1 = length_vector(c1);
Lc2 = length_vector(c2);
Ms = length_vector_squared(Mc);
scale_vector(ua, Ms * Lc1 / (La * dot_vectors(Mc, c1)));
scale_vector(ub, Ms * Lc2 / (Lb * dot_vectors(Mc, c2)));
for (j = 0; j < 3; j++)
{
gsl_matrix_set(Sa, i, j, gsl_vector_get(ua, j));
gsl_matrix_set(Sb, i, j, gsl_vector_get(ub, j));
}
}
#pragma omp parallel for private(i,j)
for (i = 0; i < nb; i++)
{
nans[i] = 0;
for (j = 0; j < 3; j++)
{
if (gsl_isnan(gsl_matrix_get(Sa, i, j)) || gsl_isnan(gsl_matrix_get(Sb, i, j)))
{
nans[i] = 1;
break;
}
}
}
for (i = 0; i < nb; i++)
{
a = inds[i] * 3;
b = indi[i] * 3;
c = indf[i] * 3;
if (nans[i] == 0)
{
for (j = 0; j < 3; j++)
{
S[a + j] += gsl_matrix_get(Sa, i, j);
S[b + j] -= (gsl_matrix_get(Sa, i, j) + gsl_matrix_get(Sb, i, j));
S[c + j] += gsl_matrix_get(Sb, i, j);
}
}
}
}
#pragma omp parallel for private(i)
for (i = 0; i < n; i++)
{
frx[i] = 0;
fry[i] = 0;
frz[i] = 0;
}
for (i = 0; i < nv; i++)
{
frx[rows[i]] += vals[i] * fx[cols[i]];
fry[rows[i]] += vals[i] * fy[cols[i]];
frz[rows[i]] += vals[i] * fz[cols[i]];
}
Un = 0.;
Rn = 0.;
#pragma omp parallel for private(i,j,Rx,Ry,Rz,Mi) reduction(+:Un,Rn)
for (i = 0; i < n; i++)
{
j = 3 * i;
Rx = (P[j + 0] - S[j + 0] - frx[i]) * B[j + 0];
Ry = (P[j + 1] - S[j + 1] - fry[i]) * B[j + 1];
Rz = (P[j + 2] - S[j + 2] - frz[i]) * B[j + 2];
Rn += gsl_hypot3(Rx, Ry, Rz);
Mi = M[i] * factor;
V[j + 0] += Rx / Mi;
V[j + 1] += Ry / Mi;
V[j + 2] += Rz / Mi;
Un += Mi * (gsl_pow_2(V[j + 0]) + gsl_pow_2(V[j + 1]) + gsl_pow_2(V[j + 2]));
}
if (Un < Uo)
{
#pragma omp parallel for private(i,j)
for (i = 0; i < n; i++)
{
j = 3 * i;
V[j + 0] = 0.;
V[j + 1] = 0.;
V[j + 2] = 0.;
}
}
Uo = Un;
#pragma omp parallel for private(i,j)
for (i = 0; i < n; i++)
{
j = 3 * i;
X[j + 0] += V[j + 0];
X[j + 1] += V[j + 1];
X[j + 2] += V[j + 2];
}
res = Rn / n;
ts++;
}
if (summary == 1)
{
printf("Step: %i, Residual: %f\n", ts - 1, res);
}
}
| {
"alphanum_fraction": 0.4191721582,
"avg_line_length": 29.3413897281,
"ext": "c",
"hexsha": "5517b2b5d322a3f563d269614012cae2ff3c44fe",
"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": "129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "philianeles/compas",
"max_forks_repo_path": "src/compas_hpc/algorithms/drx_c.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1",
"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": "philianeles/compas",
"max_issues_repo_path": "src/compas_hpc/algorithms/drx_c.c",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "philianeles/compas",
"max_stars_repo_path": "src/compas_hpc/algorithms/drx_c.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2851,
"size": 9712
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
void read_matrix(int** index, int** matrix, double scaling, int N_kw, char* input_fileName)
{
FILE *fp = fopen(input_fileName, "r");
fscanf(fp, "%*[^\n]\n");
for (int ii = 0; ii < N_kw; ii++)
fscanf(fp, "%d,", &((*index)[ii]));
fscanf(fp, "%*[^\n]\n");
int tmp;
for (int ii = 0; ii < N_kw; ii++)
{
for (int jj = 0; jj < N_kw; jj++)
{
fscanf(fp, "%d,", &tmp);
(*matrix)[ii*N_kw + jj] = (int) (tmp * scaling);
}
fscanf(fp, "%*[^\n]\n");
}
fclose(fp);
}
void pad_matrix(int** matrix_padded, int** matrix, int m, double p, double q, int N_kw, int N_doc)
{
// Initialising RNG
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
// perform padding
int ii, jj;
#pragma omp parallel for private(ii, jj)
for (ii = 0; ii < N_kw; ii++)
{
for (jj = 0; jj < N_kw; jj++)
{
if (ii == jj)
(*matrix_padded)[ii*N_kw + jj] = gsl_ran_binomial(r, p, m*(*matrix)[ii*N_kw + jj]) + gsl_ran_binomial(r, q, m*(N_doc - (*matrix)[ii*N_kw + jj]));
if (ii > jj)
{
int N1 = (*matrix)[ii*N_kw + jj];
int N2 = (*matrix)[ii*N_kw + ii] + (*matrix)[jj*N_kw + jj] - 2*(*matrix)[ii*N_kw + jj];
int N3 = N_doc - N1 - N2;
int n1 = gsl_ran_binomial(r, p*p, m*N1);
int n2 = gsl_ran_binomial(r, p*q, m*N2);
int n3 = gsl_ran_binomial(r, q*q, m*N3);
(*matrix_padded)[ii*N_kw + jj] = n1 + n2 + n3;
(*matrix_padded)[jj*N_kw + ii] = n1 + n2 + n3;
}
}
}
gsl_rng_free(r);
}
void observe_matrix(gsl_matrix* matrix_obs, int** matrix_padded, int N_kw)
{
// perform observed count generation
for (int ii = 0; ii < N_kw; ii++)
for (int jj = 0; jj < N_kw; jj++)
gsl_matrix_set(matrix_obs, ii, jj, (double) ((*matrix_padded)[ii*N_kw + jj]));
}
void solution_initial(int** permutation, gsl_matrix* matrix_obs, int** matrix, int m, double p, double q, int N_kw, int N_obs, int N_doc)
{
int* diff = (int*) malloc(sizeof(int) * N_kw);
int* index = (int*) malloc(sizeof(int) * N_kw);
int* occupied = (int*) malloc(sizeof(int) * N_kw);
for (int ii = 0; ii < N_kw; ii++)
occupied[ii] = -1;
for (int ii = 0; ii < N_obs; ii++)
{
// reset index
for (int jj = 0; jj < N_kw; jj++)
index[jj] = jj;
// compute differences
for (int jj = 0; jj < N_kw; jj++)
diff[jj] = abs(gsl_matrix_get(matrix_obs, ii, ii) - m * p * (*matrix)[jj*N_kw+jj] - m * q * (N_doc - (*matrix)[jj*N_kw+jj]));
// sorting
for (int jj = 0; jj < N_kw-1; jj++)
{
for (int kk = 0; kk < N_kw-jj-1; kk++)
{
if (diff[kk] > diff[kk+1])
{
int temp = diff[kk+1];
diff[kk+1] = diff[kk];
diff[kk] = temp;
temp = index[kk+1];
index[kk+1] = index[kk];
index[kk] = temp;
}
}
}
// use the smallest index available
int idx = 0;
while (occupied[index[idx]] > 0)
idx++;
// update the data structures
(*permutation)[ii] = index[idx];
occupied[index[idx]] = 1;
}
//for (int ii = 200; ii < 250; ii++)
//{
// printf("%f\n", gsl_matrix_get(matrix_obs, ii, ii) - m * p * (*matrix)[(*permutation)[ii]*N_kw+(*permutation)[ii]] - m * q * (N_doc - (*matrix)[(*permutation)[ii]*N_kw+(*permutation)[ii]]));
//}
}
void permutation_generation(int* idx1, int* idx2, int** permutation_tmp, int** permutation, int** permutation_inv, gsl_matrix* matrix_obs, int** matrix, int m, double p, double q, int N_kw, int N_obs, int N_doc)
{
double N1_mean, N1_var, N1_lower, N1_upper, N2_mean, N2_var, N2_lower, N2_upper;
int check = -1;
int count = 0;
*idx1 = rand() % N_obs;
*idx2 = -1;
int idx_old = (*permutation)[*idx1];
int idx_new = 0;
do {
idx_new = rand() % N_kw;
count++;
if ((*permutation_inv)[idx_new] >= 0)
{
*idx2 = (*permutation_inv)[idx_new];
N1_mean = m * p * (*matrix)[idx_new*N_kw + idx_new] + m * q * (N_doc - (*matrix)[idx_new*N_kw + idx_new]);
N1_var = (*matrix)[idx_new*N_kw + idx_new] / (double) N_doc * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) * 2.0 * m;
N1_var += m * p * (1-p) * (*matrix)[idx_new*N_kw + idx_new] + m * q * (1-q) * (N_doc - (*matrix)[idx_new*N_kw + idx_new]);
N1_var = 3*sqrt(N1_var);
N1_lower = N1_mean - N1_var;
N1_upper = N1_mean + N1_var;
N2_mean = m * p * (*matrix)[idx_old*N_kw + idx_old] + m * q * (N_doc - (*matrix)[idx_old*N_kw + idx_old]);
N2_var = (*matrix)[idx_old*N_kw + idx_old] / (double) N_doc * (N_doc - (*matrix)[idx_old*N_kw + idx_old]) * 2.0 * m ;
N2_var += m * p * (1-p) * (*matrix)[idx_old*N_kw + idx_old] + m * q * (1-q)* (N_doc - (*matrix)[idx_old*N_kw + idx_old]);
N2_var = 3*sqrt(N2_var);
N2_lower = N2_mean - N2_var;
N2_upper = N2_mean + N2_var;
if ((gsl_matrix_get(matrix_obs, *idx1, *idx1) > N1_lower) && (gsl_matrix_get(matrix_obs, *idx1, *idx1) < N1_upper))
if ((gsl_matrix_get(matrix_obs, *idx2, *idx2) > N2_lower) && (gsl_matrix_get(matrix_obs, *idx2, *idx2) < N2_upper))
check = 1;
}
else
{
*idx2 = (*permutation_inv)[idx_new];
N1_mean = m * p * (*matrix)[idx_new*N_kw + idx_new] + m * q * (N_doc - (*matrix)[idx_new*N_kw + idx_new]);
N1_var = (*matrix)[idx_new*N_kw + idx_new] / (double) N_doc * (N_doc - (*matrix)[idx_new*N_kw + idx_new]) * 2.0 * m;
N1_var += m * p * (1-p) * (*matrix)[idx_new*N_kw + idx_new] + m * q * (1-q) * (N_doc - (*matrix)[idx_new*N_kw + idx_new]);
N1_var = 3*sqrt(N1_var);
N1_lower = N1_mean - N1_var;
N1_upper = N1_mean + N1_var;
if ((gsl_matrix_get(matrix_obs, *idx1, *idx1) > N1_lower) && (gsl_matrix_get(matrix_obs, *idx1, *idx1) < N1_upper))
check = 1;
}
} while ((check < 0) && (count < 200));
if (count == 200)
*idx2 = *idx1;
if (*idx1 != *idx2)
{
(*permutation_tmp)[*idx1] = idx_new;
if ((*permutation_inv)[idx_new] >= 0)
{
*idx2 = (*permutation_inv)[idx_new];
(*permutation_tmp)[*idx2] = idx_old;
}
}
} | {
"alphanum_fraction": 0.5034305317,
"avg_line_length": 32.691588785,
"ext": "c",
"hexsha": "74444982063fa556849db2cebb2493021c085dea",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE",
"max_forks_repo_path": "DPAP-SE/util.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "RethinkingSSE/Attacks-on-SSE",
"max_issues_repo_path": "DPAP-SE/util.c",
"max_line_length": 211,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE",
"max_stars_repo_path": "DPAP-SE/util.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2210,
"size": 6996
} |
#ifndef __QUANTUM_H__
#define __QUANTUM_H__
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_poly.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#endif
void WignerTransform_au(gsl_matrix_complex * dest, gsl_vector_complex * source, int grades, double dx, double dp);
void WignerTransform_SI(gsl_matrix_complex * dest,gsl_vector_complex * source, int grades, double dx, double dp); | {
"alphanum_fraction": 0.772479564,
"avg_line_length": 29.36,
"ext": "h",
"hexsha": "d3f4c0bc3f5cb81080770ca2932b90ea60c33188",
"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": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Walter-Feng/HomebrewLib",
"max_forks_repo_path": "Quantum.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Walter-Feng/HomebrewLib",
"max_issues_repo_path": "Quantum.h",
"max_line_length": 114,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Walter-Feng/HomebrewLib",
"max_stars_repo_path": "Quantum.h",
"max_stars_repo_stars_event_max_datetime": "2019-05-27T12:45:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-27T12:45:50.000Z",
"num_tokens": 212,
"size": 734
} |
#include "jfftw_Wisdom.h"
#include <fftw.h>
/*
* Class: jfftw_Wisdom
* Method: get
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_jfftw_Wisdom_get( JNIEnv * env, jclass clazz )
{
char* cwisdom = fftw_export_wisdom_to_string();
jstring wisdom = (*env)->NewStringUTF( env, cwisdom );
fftw_free( cwisdom );
return wisdom;
}
/*
* Class: jfftw_Wisdom
* Method: add
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_jfftw_Wisdom_add( JNIEnv * env, jclass clazz, jstring wisdom )
{
const char* cwisdom = (*env)->GetStringUTFChars( env, wisdom, NULL );
fftw_status s = fftw_import_wisdom_from_string( cwisdom );
(*env)->ReleaseStringUTFChars( env, wisdom, cwisdom );
if( s == FFTW_FAILURE )
{
(*env)->ThrowNew( env, (*env)->FindClass( env, "java/lang/IllegalArgumentException" ), "unable to parse wisdom" );
}
}
/*
* Class: jfftw_Wisdom
* Method: clear
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_jfftw_Wisdom_clear( JNIEnv * env, jclass clazz )
{
fftw_forget_wisdom();
}
| {
"alphanum_fraction": 0.6887417219,
"avg_line_length": 23.4888888889,
"ext": "c",
"hexsha": "66a5ccca4d41e75a1820790f6a22c05d39eaa824",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-03-09T05:30:21.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-03-08T14:04:52.000Z",
"max_forks_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "CSCSI/Triana",
"max_forks_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_Wisdom.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809",
"max_issues_repo_issues_event_max_datetime": "2016-01-22T13:06:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-08-28T13:52:42.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "CSCSI/Triana",
"max_issues_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_Wisdom.c",
"max_line_length": 116,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "da48ffaa0183f59e3fe7c6dc59d9f91234e65809",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "CSCSI/Triana",
"max_stars_repo_path": "triana-toolboxes/signalproc/src/main/java/signalproc/algorithms/c/jfftw_Wisdom.c",
"max_stars_repo_stars_event_max_datetime": "2019-01-15T21:45:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-02T10:12:13.000Z",
"num_tokens": 315,
"size": 1057
} |
/*
NAME:
bovy_det
PURPOSE:
returns the determinant of a matrix
CALLING SEQUENCE:
bovy_det(gsl_matrix * A)
INPUT:
A - matrix
OUTPUT:
det(A)
REVISION HISTORY:
2008-09-21 - Written Bovy
*/
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
double bovy_det(gsl_matrix * A){
gsl_permutation * p = gsl_permutation_alloc (A->size1);
int signum;
double det;
gsl_linalg_LU_decomp(A,p,&signum);
det= gsl_linalg_LU_det(A,signum);
gsl_permutation_free(p);
return det;
}
| {
"alphanum_fraction": 0.6743295019,
"avg_line_length": 18.6428571429,
"ext": "c",
"hexsha": "06703deec660de0ac15f52b6079f447acbc65e85",
"lang": "C",
"max_forks_count": 26,
"max_forks_repo_forks_event_max_datetime": "2021-12-13T03:37:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-05T22:21:22.000Z",
"max_forks_repo_head_hexsha": "b66d2af16503bc46d785ac9c9ba447ecc29b6fae",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "surbut/mashr",
"max_forks_repo_path": "src/bovy_det.c",
"max_issues_count": 24,
"max_issues_repo_head_hexsha": "b66d2af16503bc46d785ac9c9ba447ecc29b6fae",
"max_issues_repo_issues_event_max_datetime": "2021-11-19T01:01:22.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-07T01:42:22.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "surbut/mashr",
"max_issues_repo_path": "src/bovy_det.c",
"max_line_length": 57,
"max_stars_count": 73,
"max_stars_repo_head_hexsha": "b66d2af16503bc46d785ac9c9ba447ecc29b6fae",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "surbut/mashr",
"max_stars_repo_path": "src/bovy_det.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-21T01:27:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-22T09:22:38.000Z",
"num_tokens": 165,
"size": 522
} |
#ifndef STDAFX__H
#define STDAFX__H
#include <SDKDDKVer.h>
#if !defined(_STL_EXTRA_DISABLED_WARNINGS)
#define _STL_EXTRA_DISABLED_WARNINGS 4061 4324 4365 4514 4571 4582 4583 4623 4625 4626 4710 4774 4820 4987 5026 5027 5039
#endif
#if !defined(_SCL_SECURE_NO_WARNINGS)
#define _SCL_SECURE_NO_WARNINGS 1
#endif
#if !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS 1
#endif
#if !defined(_SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING)
#define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING 1
#endif
#define STRICT
#define NOMINMAX
#pragma warning(disable: 4668) // warning C4668: '%s' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif'
#pragma warning(disable: 4710) // warning C4710: '%s': function not inlined
#pragma warning(disable: 4711) // warning C4711: function '%s' selected for automatic inline expansion
#pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s'
#pragma warning(push)
#pragma warning(disable: 5039) // warning C5039: '%s': pointer or reference to potentially throwing function passed to extern C function under -EHc. Undefined behavior may occur if this function throws an exception.
#include <Windows.h>
#pragma warning(pop)
#pragma warning(push)
#pragma warning(disable: 4005) // warning C4005: '%s': macro redefinition
#include <Winternl.h>
#include <ntstatus.h>
#pragma warning(pop)
// disable for everything
#pragma warning(disable: 4061) // warning C4061: enumerator '%s' in switch of enum '%s' is not explicitly handled by a case label
#pragma warning(disable: 4324) // warning C4234: structure was padded due to alignment specifier
#pragma warning(disable: 4514) // warning C4514: '%s': unreferenced inline function has been removed
#pragma warning(disable: 4623) // warning C4623: '%s': default constructor was implicitly defined as deleted
#pragma warning(disable: 4625) // warning C4625: '%s': copy constructor was implicitly defined as deleted
#pragma warning(disable: 4626) // warning C4626: '%s': assignment operator was implicitly defined as deleted
#pragma warning(disable: 4710) // warning C4710: '%s': function not inlined
#pragma warning(disable: 4820) // warning C4820: '%s': '%d' bytes padding added after data member '%s'
#pragma warning(disable: 5026) // warning C5026: '%s': move constructor was implicitly defined as deleted
#pragma warning(disable: 5027) // warning C5027: '%s': move assignment operator was implicitly defined as deleted
#pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'no initialization'.
#pragma warning(disable: 26426) // warning C26426: Global initializer calls a non-constexpr function '%s' (i.22: http://go.microsoft.com/fwlink/?linkid=853919).
#pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413)
#pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414).
#pragma warning(disable: 26485) // warning C26485: Expression '%s::`vbtable'': No array to pointer decay. (bounds.3: http://go.microsoft.com/fwlink/p/?LinkID=620415)
#pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417)
#pragma warning(disable: 26499) // warning C26499: Could not find any lifetime tracking information for '%s'
// disable for standard headers
#pragma warning(push)
#pragma warning(disable: 5039) // warning C5039: '%s': pointer or reference to potentially throwing function passed to extern C function under -EHc. Undefined behavior may occur if this function throws an exception.
#pragma warning(disable: 26400) // warning C26400: Do not assign the result of an allocation or a function call with an owner<T> return value to a raw pointer, use owner<T> instead. (i.11 http://go.microsoft.com/fwlink/?linkid=845474)
#pragma warning(disable: 26401) // warning C26401: Do not delete a raw pointer that is not an owner<T>. (i.11: http://go.microsoft.com/fwlink/?linkid=845474)
#pragma warning(disable: 26408) // warning C26408: Avoid malloc() and free(), prefer the nothrow version of new with delete. (r.10 http://go.microsoft.com/fwlink/?linkid=845483)
#pragma warning(disable: 26409) // warning C26409: Avoid calling new and delete explicitly, use std::make_unique<T> instead. (r.11 http://go.microsoft.com/fwlink/?linkid=845485)
#pragma warning(disable: 26411) // warning C26411: The parameter '%s' is a reference to unique pointer and it is never reassigned or reset, use T* or T& instead. (r.33 http://go.microsoft.com/fwlink/?linkid=845479)
#pragma warning(disable: 26412) // warning C26412: Do not dereference an invalid pointer (lifetimes rule 1). 'return of %s' was invalidated at line %d by 'end of function scope (local lifetimes end)'.
#pragma warning(disable: 26413) // warning C26413: Do not dereference nullptr (lifetimes rule 2). 'nullptr' was pointed to nullptr at line %d.
#pragma warning(disable: 26423) // warning C26423: The allocation was not directly assigned to an owner.
#pragma warning(disable: 26424) // warning C26424: Failing to delete or assign ownership of allocation at line %d.
#pragma warning(disable: 26425) // warning C26425: Assigning '%s' to a static variable.
#pragma warning(disable: 26461) // warning C26461: The reference argument '%s' for function %s can be marked as const. (con.3: https://go.microsoft.com/fwlink/p/?LinkID=786684)
#pragma warning(disable: 26471) // warning C26471: Don't use reinterpret_cast. A cast from void* can use static_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417).
#pragma warning(disable: 26481) // warning C26481: Don't use pointer arithmetic. Use span instead. (bounds.1: http://go.microsoft.com/fwlink/p/?LinkID=620413)
#pragma warning(disable: 26482) // warning C26482: Only index into arrays using constant expressions. (bounds.2: http://go.microsoft.com/fwlink/p/?LinkID=620414)
#pragma warning(disable: 26490) // warning C26490: Don't use reinterpret_cast. (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417)
#pragma warning(disable: 26493) // warning C26493: Don't use C-style casts that would perform a static_cast downcast, const_cast, or reinterpret_cast. (type.4: http://go.microsoft.com/fwlink/p/?LinkID=620420)
#pragma warning(disable: 26494) // warning C26494: Variable '%s' is uninitialized. Always initialize an object. (type.5: http://go.microsoft.com/fwlink/p/?LinkID=620421)
#pragma warning(disable: 26495) // warning C26495: Variable '%s' is uninitialized. Always initialize a member variable. (type.6: http://go.microsoft.com/fwlink/p/?LinkID=620422)
#pragma warning(disable: 26496) // warning C26496: Variable '%s' is assigned only once, mark it as const. (con.4: https://go.microsoft.com/fwlink/p/?LinkID=784969)
#pragma warning(disable: 26497) // warning C26497: This function %s could be marked constexpr if compile-time evaluation is desired. (f.4: https://go.microsoft.com/fwlink/p/?LinkID=784970)
#include <cstddef>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <type_traits>
#include <utility>
#include <memory>
#include <tuple>
#include <thread>
#include <cstdlib>
// disable additionally for third-party libraries
#pragma warning(push)
#pragma warning(disable: 4365) // warning C4365: '%s': conversion from '%s' to '%s', signed/unsigned mismatch
#pragma warning(disable: 4371) // warning C4371: '%s': layout of class may have changed from a previous version of the compiler due to better packing of member '%s'
#pragma warning(disable: 4619) // warning C4619: #pragma warning: there is no warning number '%d'
#pragma warning(disable: 5031) // warning C5031: #pragma warning(pop): likely mismatch, popping warning state pushed in different file
#pragma warning(disable: 26429) // warning C26429: Symbol '%s' is never tested for nullness, it can be marked as not_null (f.23: http://go.microsoft.com/fwlink/?linkid=853921).
#pragma warning(disable: 26432) // warning C26432: If you define or delete any default operation in the type '%s', define or delete them all (c.21: http://go.microsoft.com/fwlink/?linkid=853922).
#pragma warning(disable: 26434) // warning C26434: Function '%s' hides a non-virtual function '%s' (c.128: http://go.microsoft.com/fwlink/?linkid=853923).
#pragma warning(disable: 26439) // warning C26439: This kind of function may not throw. Declare it 'noexcept' (f.6: http://go.microsoft.com/fwlink/?linkid=853927).
#pragma warning(disable: 26440) // warning C26440: Function '%s' can be declared 'noexcept' (f.6: http://go.microsoft.com/fwlink/?linkid=853927).
#pragma warning(disable: 26472) // warning C26472: Don't use a static_cast for arithmetic conversions. Use brace initialization, gsl::narrow_cast or gsl::narow (type.1: http://go.microsoft.com/fwlink/p/?LinkID=620417).
#ifndef BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE
#define BOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE
#endif
#include <gsl/gsl>
#include <fmt/format.h>
#pragma warning(pop)
#pragma warning(pop)
#endif
| {
"alphanum_fraction": 0.7588920026,
"avg_line_length": 73.0551181102,
"ext": "h",
"hexsha": "eb79b46a24443d028f08b39261d4bc4eae5d947e",
"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": "9dadec0b10ec032a31fd68e6614d94be13b66722",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "DrPizza/benchmarking-tools",
"max_forks_repo_path": "cpuid/include/stdafx.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9dadec0b10ec032a31fd68e6614d94be13b66722",
"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": "DrPizza/benchmarking-tools",
"max_issues_repo_path": "cpuid/include/stdafx.h",
"max_line_length": 234,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "9dadec0b10ec032a31fd68e6614d94be13b66722",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "DrPizza/benchmarking-tools",
"max_stars_repo_path": "cpuid/include/stdafx.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-29T06:46:52.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-06-01T06:47:14.000Z",
"num_tokens": 2475,
"size": 9278
} |
#include <stdio.h>
#include <time.h>
#include <linux/limits.h>
#include <sys/stat.h>
#include <unistd.h>
#include <math.h>
#include "Globals.h"
#include "constitutive_equations.h"
#include "Watershed.h"
#include "manufactured_solution.h"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
extern void GetLGLWeights(int N, double* w);
void *xcalloc(int items, int size)
{
void *ptr = calloc(items, size);
if (ptr == NULL)
{
printf("Unable to allocate memory\n");
exit(EXIT_FAILURE);
}
return ptr;
}
static int firstOutput = 1;
static char folderName[500];
static char ChannelHeightFileName[PATH_MAX + 1];
static char ChannelQFileName[PATH_MAX + 1];
static char KinFileName[PATH_MAX + 1];
static char JuncHeightFileName[PATH_MAX + 1];
static char JuncQFileName[PATH_MAX + 1];
static char FpHeightFileName[PATH_MAX + 1];
static char FpQFileName[PATH_MAX + 1];
void outputFloodplainDataToFile(double currtime, double finalTime, double recordTimeIntervals)
{
char openFileFormat[1];
int writeHeader = 0;
if (firstOutput)
{
time_t rawtime;
time(&rawtime);
struct tm *timeinfo = localtime(&rawtime);
sprintf(folderName, "DataOutput_%d_%02d_%02d_%02d_%02d_%02d",timeinfo->tm_year+1900, timeinfo->tm_mon+1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
if (mkdir(folderName, 0777) == -1)
perror("The following error occured while making the data output directory");
sprintf(FpHeightFileName, "%s/Floodplains.63", folderName);
sprintf(FpQFileName, "%s/Floodplains.64", folderName);
openFileFormat[0] = 'w';
writeHeader = 1;
firstOutput = 0;
}
else
{
openFileFormat[0] = 'a';
}
// Output Floodplain data
FILE *file1 = fopen(FpHeightFileName, openFileFormat);
FILE *file2 = fopen(FpQFileName, openFileFormat);
if (!file1)
printf("Error while opening file1\n");
if (!file2)
printf("Error while opening file2\n");
if (writeHeader)
{
int numRecords;
if (fmod(finalTime, recordTimeIntervals) == 0)
numRecords = finalTime/recordTimeIntervals + 1;
else
numRecords = finalTime/recordTimeIntervals + 2;
fprintf(file1, "End of Simulation Time = %lf.\nTotal Number of Records = %d\n", finalTime, numRecords);
fprintf(file1, "Number of Floodplains = %d\n", NumFloodplains);
fprintf(file2, "End of Simulation Time = %lf.\nTotal Number of Records = %d\n", finalTime, numRecords);
fprintf(file2, "Number of Floodplains = %d\n", NumFloodplains);
for (int j = 0; j < NumFloodplains; j++)
{
fprintf(file1, "Number of data points for junction %d = %d\n", j, FloodplainList[j]->NumEl);
fprintf(file2, "Number of data points for junction %d = %d\n", j, FloodplainList[j]->NumEl);
}
}
for (int i=0; i < NumFloodplains; i++)
{
fprintf(file1, "# Average H and Zeta at time %.3f for Junction %d\n", currtime, i);
fprintf(file2, "# Average Qx and Qy at time %.3f for Junction %d\n", currtime, i);
for (int j=0; j < FloodplainList[i]->NumEl; ++j)
{
double avgZeta = 0, avgHeight = 0, avgQx = 0, avgQy =0, avgz =0, zarr[3];
for(int k=0; k<3; ++k)
{
double zeta = FloodplainList[i]->zeta[j][k];
double Qx = FloodplainList[i]->Qx[j][k];
double Qy = FloodplainList[i]->Qy[j][k];
zarr[k]= FloodplainList[i]->NodalZ[j][k];
double height = zeta + zarr[k];
avgZeta += zeta;
avgHeight += height;
avgQx += Qx;
avgQy += Qy;
avgz += zarr[k];
}
fprintf(file1, "%d \t %.13f \t %.13f \n", j, avgHeight/3, avgZeta/3);
fprintf(file2, "%d \t %.13f \t %.13f\n", j, avgQx/3, avgQy/3 );
}
}
fclose(file1);
fclose(file2);
}
void output2DNodalError(double time)
{
char *fileName1 = "NodalErrorsH.out";
char *fileName2 = "NodalErrorsQ.out";
FILE* ef1 = fopen(fileName1, "w");
FILE* ef2 = fopen(fileName2, "w");
int i = 0;
for (int j=0; j < FloodplainList[i]->NumVerts; ++j)
{
double xval = FloodplainList[i]->Vx[j];
double yval = FloodplainList[i]->Vy[j];
int num_conn_els = FloodplainList[i]->ElCount[i];
double nodalZeta = 0;
double nodalQx = 0;
double nodalQy = 0;
for (int k = 0; k < num_conn_els; k++)
{
int curr_el = FloodplainList[i]->VtoEl[j][k];
int loc_v;
// find the local vertex number for curr_el
for (int v = 0; v < 3; v++)
{
if (j == FloodplainList[i]->EltoVert[curr_el*3+v])
{
loc_v = v;
break;
}
}
int loc_node = FloodplainList[i]->VtoNode[curr_el][loc_v];
nodalZeta += FloodplainList[i]->zeta[curr_el][loc_node];
nodalQx += FloodplainList[i]->Qx[curr_el][loc_node];
nodalQy += FloodplainList[i]->Qy[curr_el][loc_node];
}
nodalZeta /= num_conn_els;
nodalQx /= num_conn_els;
nodalQy /= num_conn_els;
double manzeta = getmanH(xval, yval, time);
double manQx = getQx(xval, yval, time);
double manQy = getQy(xval, yval, time);
double er1 = -nodalZeta + manzeta;
double er2 = -nodalQx + manQx;
double er3 = -nodalQy + manQy;
fprintf(ef1, "%d \t %.13f\n", j, er1);
fprintf(ef2, "%d \t %.13f \t %.13f\n", j, er2, er3);
}
fclose(ef1);
fclose(ef2);
}
void outputFloodplainNodalDataToFile(double currtime, double finalTime, double recordTimeIntervals)
{
char openFileFormat[1];
int writeHeader = 0;
if (firstOutput)
{
time_t rawtime;
time(&rawtime);
struct tm *timeinfo = localtime(&rawtime);
sprintf(folderName, "DataOutput_%d_%02d_%02d_%02d_%02d_%02d",timeinfo->tm_year+1900, timeinfo->tm_mon+1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
if (mkdir(folderName, 0777) == -1)
perror("The following error occured while making the data output directory");
sprintf(FpHeightFileName, "%s/Floodplains.63", folderName);
sprintf(FpQFileName, "%s/Floodplains.64", folderName);
openFileFormat[0] = 'w';
writeHeader = 1;
firstOutput = 0;
}
else
{
openFileFormat[0] = 'a';
}
// Output Floodplain data
FILE *file1 = fopen(FpHeightFileName, openFileFormat);
FILE *file2 = fopen(FpQFileName, openFileFormat);
if (!file1)
printf("Error while opening file1\n");
if (!file2)
printf("Error while opening file2\n");
if (writeHeader)
{
int numRecords;
if (fmod(finalTime, recordTimeIntervals) == 0)
numRecords = finalTime/recordTimeIntervals + 1;
else
numRecords = finalTime/recordTimeIntervals + 2;
fprintf(file1, "End of Simulation Time = %lf.\nTotal Number of Records = %d\n", finalTime, numRecords);
fprintf(file1, "Number of Floodplains = %d\n", NumFloodplains);
fprintf(file2, "End of Simulation Time = %lf.\nTotal Number of Records = %d\n", finalTime, numRecords);
fprintf(file2, "Number of Floodplains = %d\n", NumFloodplains);
for (int j = 0; j < NumFloodplains; j++)
{
fprintf(file1, "Number of data points for junction %d = %d\n", j, FloodplainList[j]->NumVerts);
fprintf(file2, "Number of data points for junction %d = %d\n", j, FloodplainList[j]->NumVerts);
}
}
for (int i=0; i < NumFloodplains; i++)
{
fprintf(file1, "# Nodal H at time %.3f for Junction %d\n", currtime, i);
fprintf(file2, "# Nodal Qx and Qy at time %.3f for Junction %d\n", currtime, i);
for (int j=0; j < FloodplainList[i]->NumVerts; ++j)
{
int num_conn_els = FloodplainList[i]->ElCount[i];
double nodalZeta = 0;
double nodalQx = 0;
double nodalQy = 0;
for (int k = 0; k < num_conn_els; k++)
{
int curr_el = FloodplainList[i]->VtoEl[j][k];
int loc_v;
// find the local vertex number for curr_el
for (int v = 0; v < 3; v++)
{
if (j == FloodplainList[i]->EltoVert[curr_el*3+v])
{
loc_v = v;
break;
}
}
int loc_node = FloodplainList[i]->VtoNode[curr_el][loc_v];
nodalZeta += FloodplainList[i]->zeta[curr_el][loc_node];
nodalQx += FloodplainList[i]->Qx[curr_el][loc_node];
nodalQy += FloodplainList[i]->Qy[curr_el][loc_node];
}
nodalZeta /= num_conn_els;
nodalQx /= num_conn_els;
nodalQy /= num_conn_els;
fprintf(file1, "%d \t %.13f\n", j, nodalZeta);
fprintf(file2, "%d \t %.13f \t %.13f\n", j, nodalQx, nodalQy );
}
}
fclose(file1);
fclose(file2);
}
void outputDataToFile(double currtime, double finalTime, double recordTimeIntervals)
{
char openFileFormat[1];
int writeHeader = 0;
if (firstOutput)
{
time_t rawtime;
time(&rawtime);
struct tm *timeinfo = localtime(&rawtime);
sprintf(folderName, "DataOutput_%d_%02d_%02d_%02d_%02d_%02d",timeinfo->tm_year+1900, timeinfo->tm_mon+1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
if (mkdir(folderName, 0777) == -1)
perror("The following error occured while making the data output directory");
sprintf(ChannelHeightFileName, "%s/Channels.63", folderName);
sprintf(ChannelQFileName, "%s/Channels.64", folderName);
sprintf(KinFileName, "%s/KinField.63", folderName);
sprintf(JuncHeightFileName, "%s/Junctions.63", folderName);
sprintf(JuncQFileName, "%s/Junctions.64", folderName);
//sprintf(FpHeightFileName, "%s/Floodplains.63", folderName);
//sprintf(FpQFileName, "%s/Floodplains.64", folderName);
// Move junction grid data file to this newly created folder
/*char NewJunctionGridFileName[PATH_MAX + 1];
sprintf(NewJunctionGridFileName, "%s/JunctionMesh.14", folderName);
int ret = rename("./Output/JunctionMesh.14", NewJunctionGridFileName);
if (ret != 0)
printf("Error: unable to move the junction grid file\n");
*/
// Move flowpaths file to this newly created folder
int ret;
char NewFlowPathsFileName[PATH_MAX + 1];
sprintf(NewFlowPathsFileName, "%s/FlowPaths.out", folderName);
ret = rename("./Output/FlowPaths.out", NewFlowPathsFileName);
if (ret != 0)
printf("Error: unable to move the flow paths file\n");
// Move ChannelNodes.14 to this newly created folder
/* char NewChannelsGridFileName[PATH_MAX + 1];
sprintf(NewChannelsGridFileName, "%s/Channels.14", folderName);
ret = rename("./Output/Channels.14", NewChannelsGridFileName);
if (ret != 0)
printf("Error: unable to move channels grid file\n");
*/
openFileFormat[0] = 'w';
writeHeader = 1;
firstOutput = 0;
}
else
{
openFileFormat[0] = 'a';
}
//char cwd[PATH_MAX+1];
//if (getcwd(cwd, sizeof(cwd))==NULL)
// perror("Error while getting current working directory");
//Output Channels data
FILE* file1;
FILE* file2;
file1 = fopen(ChannelHeightFileName, openFileFormat);
file2 = fopen(ChannelQFileName, openFileFormat);
//if (!file1 || !file2)
//{
// printf("Could not open file for writing. Exiting now\n");
// exit(1);
//}
if (writeHeader)
{
int numRecords;
if (fmod(finalTime, recordTimeIntervals) == 0)
numRecords = finalTime/recordTimeIntervals+1;
else
numRecords = finalTime/recordTimeIntervals + 2;
fprintf(file1, "End of Simulation Time = %lf.\nTotal Number of Records = %d\n", finalTime, numRecords);
fprintf(file1, "Number of Channels = %d\n", NumChannels);
fprintf(file2, "End of Simulation Time = %lf.\nTotal Number of Records = %d\n", finalTime, numRecords);
fprintf(file2, "NumChannels = %d\n", NumChannels);
for (int c = 0; c < NumChannels; c++)
{
fprintf(file1, "Number of data points for channel %d = %d\n", c, ChannelList[c]->NumNodes);
fprintf(file2, "Number of data points for channel %d = %d\n", c, ChannelList[c]->NumNodes);
}
}
for (int i=0; i<NumChannels; i++)
{
fprintf(file1, "# H and Zeta at time %.3f for Channel %d\n", currtime, i);
fprintf(file2, "#Q at time %.3f for Channel %d\n", currtime, i);
int NumNodes = ChannelList[i]->NumNodes;
for (int j = 0; j<NumNodes; j++)
{
double bval = ChannelList[i]->NodalB[j];
double zval = ChannelList[i]->NodalZ[j];
double x_val = ChannelList[i]->NodalX[j];
double y_val = ChannelList[i]->NodalY[j];
double A = ChannelList[i]->A[j+1];
double Q = ChannelList[i]->Q[j+1];
double m1val = ChannelList[i]->Nodalm1[j];
double m2val = ChannelList[i]->Nodalm2[j];
double H = getH(A, bval, m1val, m2val);
double zeta = H - zval;
fprintf(file1, "%.13f \t %.13f\n", H, zeta);
fprintf(file2, "%.13f\n", Q);
}
}
fclose(file1);
fclose(file2);
// Output Junction data
file1 = fopen(JuncHeightFileName, openFileFormat);
file2 = fopen(JuncQFileName, openFileFormat);
if (!file1)
printf("Error while opening file1\n");
if (!file2)
printf("Error while opening file2\n");
if (writeHeader)
{
int numRecords;
if (fmod(finalTime, recordTimeIntervals) == 0)
numRecords = finalTime/recordTimeIntervals + 1;
else
numRecords = finalTime/recordTimeIntervals + 2;
fprintf(file1, "End of Simulation Time = %lf.\nTotal Number of Records = %d\n", finalTime, numRecords);
fprintf(file1, "Number of Junctions = %d\n", NumJunctions);
fprintf(file2, "End of Simulation Time = %lf.\nTotal Number of Records = %d\n", finalTime, numRecords);
fprintf(file2, "NumJunctions = %d\n", NumJunctions);
for (int j = 0; j < NumJunctions; j++)
{
fprintf(file1, "Number of data points for junction %d = %d\n", j, JunctionList[j]->NumEl);
fprintf(file2, "Number of data points for junction %d = %d\n", j, JunctionList[j]->NumEl);
}
}
for (int i=0; i<NumJunctions; i++)
{
fprintf(file1, "# Average H and Zeta at time %.3f for Junction %d\n", currtime, i);
fprintf(file2, "# Average Qx and Qy at time %.3f for Junction %d\n", currtime, i);
for (int j=0; j<JunctionList[i]->NumEl; ++j)
{
double avgZeta = 0, avgHeight = 0, avgQx = 0, avgQy =0, avgz =0, zarr[3];
for(int k=0; k<3; ++k)
{
double zeta = JunctionList[i]->zeta[j][k];
double Qx = JunctionList[i]->Qx[j][k];
double Qy = JunctionList[i]->Qy[j][k];
zarr[k]= JunctionList[i]->NodalZ[j][k];
double height = zeta + zarr[k];
avgZeta += zeta;
avgHeight += height;
avgQx += Qx;
avgQy += Qy;
avgz += zarr[k];
}
fprintf(file1, "%d \t %.13f \t %.13f \n", j, avgHeight/3, avgZeta/3);
fprintf(file2, "%d \t %.13f \t %.13f\n", j, avgQx/3, avgQy/3 );
}
}
fclose(file1);
fclose(file2);
// Output Kinematic Field Data
// Here we assume that we are working with first order polynomials only
if (FloodplainList[0]->floodedStatus == 0)
{
file1 = fopen(KinFileName, openFileFormat);
if (writeHeader)
{
int numRecords;
if (fmod(finalTime, recordTimeIntervals) == 0)
numRecords = finalTime/recordTimeIntervals + 1;
else
numRecords = finalTime/recordTimeIntervals + 2;
fprintf(file1, "End of Simulation Time = %lf.\nTotal Number of Records = %d\n", finalTime, numRecords);
}
fprintf(file1,"# Average height at time %3.3f in Kinematic Field\n", currtime);
int NumEl = FloodplainList[0]->NumEl;
for (int i = 0; i < NumEl; i++)
{
if (KinematicElList[i]->isActive == 1)
{
double weq = KinematicElList[i]->weq;
double height = KinematicElList[i]->A[0]/weq;
if (KinematicElList[i]->numUpstreamEls > 0)
{
int numUpstreamEls = KinematicElList[i]->numUpstreamEls;
height = KinematicElList[i]->A[0]/weq;
for (int j = 0; j < numUpstreamEls; j++)
{
int el = KinematicElList[i]->upstreamEls[j];
height += KinematicElList[el]->A[1]/weq;
}
height = height/(numUpstreamEls+1);
}
//printf("%d %.13f\n", i, height);
fprintf(file1, "%d %.13f\n", i, height);
}
else
fprintf(file1, "%d %1.13f\n", i, 1e-7);
}
fclose(file1);
}
//static int previouslyFlooded = 0;
//static char fpOpenFileFormat[1];
//int writefpHeader = 0;
//// Output Floodplain data if the channels have flooded
//if (FloodplainList[0]->floodedStatus == 1)
//{
// if (previouslyFlooded)
// {
// fpOpenFileFormat[0] = 'a';
// }
// else
// {
// fpOpenFileFormat[0] = 'w';
// writefpHeader = 1;
// }
// file1 = fopen(FpHeightFileName, fpOpenFileFormat);
// file2 = fopen(FpQFileName, fpOpenFileFormat);
//
// if (!file1)
// printf("Error while opening file1\n");
// if (!file2)
// printf("Error while opening file2\n");
// if (writefpHeader)
// {
// int numRecords;
// if (fmod(finalTime, recordTimeIntervals) == 0)
// numRecords = finalTime/recordTimeIntervals + 1;
// else
// numRecords = finalTime/recordTimeIntervals + 2;
// fprintf(file1, "End of Simulation Time = %lf.\nTotal Number of Records = %d\n", finalTime, numRecords);
// fprintf(file2, "End of Simulation Time = %lf.\nTotal Number of Records = %d\n", finalTime, numRecords);
// fprintf(file1, "Number of data points for floodplain = %d\n", FloodplainList[0]->NumEl);
// fprintf(file2, "Number of data points for floodplain = %d\n", FloodplainList[0]->NumEl);
// }
//
// fprintf(file1, "# Average H and Zeta at time %.3f\n", currtime);
// fprintf(file2, "# Average Qx and Qy at time %.3f\n", currtime);
//
// for (int j=0; j<FloodplainList[0]->NumEl; ++j)
// {
// double avgZeta = 0, avgHeight = 0, avgQx = 0, avgQy =0, avgz =0, zarr[3];
// for(int k=0; k<3; ++k)
// {
// double zeta = FloodplainList[0]->zeta[j][k];
// double Qx = FloodplainList[0]->Qx[j][k];
// double Qy = FloodplainList[0]->Qy[j][k];
// zarr[k]= FloodplainList[0]->NodalZ[j][k];
// double height = zeta + zarr[k];
//
// avgZeta += zeta;
// avgHeight += height;
// avgQx += Qx;
// avgQy += Qy;
// avgz += zarr[k];
// }
// fprintf(file1, "%d \t %.13f \t %.13f \n", j, avgHeight/3, avgZeta/3);
// fprintf(file2, "%d \t %.13f \t %.13f\n", j, avgQx/3, avgQy/3 );
// }
// fclose(file1);
// fclose(file2);
// previouslyFlooded = 1;
//}
}
void calculate_l2_error_2d(double time)
{
int NumEl = FloodplainList[0]->NumEl;
int Np = FloodplainList[0]->Np;
double errsqH = 0, errsqQx = 0, errsqQy = 0;
gsl_vector *diffH = gsl_vector_alloc(Np);
gsl_vector *diffQx = gsl_vector_alloc(Np);
gsl_vector *diffQy = gsl_vector_alloc(Np);
//double max = 0;
for (int i = 0; i < NumEl; i++)
{
for (int j = 0; j < Np; j++)
{
double xval = FloodplainList[0]->NodalX[i][j];
double yval = FloodplainList[0]->NodalY[i][j];
double exactH = getmanH(xval, yval, time);
double exactQx = getQx(xval, yval, time);
double exactQy = getQy(xval, yval, time);
double compH = FloodplainList[0]->zeta[i][j];
double compQx = FloodplainList[0]->Qx[i][j];
double compQy = FloodplainList[0]->Qy[i][j];
gsl_vector_set(diffH, j, fabs(exactH-compH));
gsl_vector_set(diffQx, j, fabs(exactQx-compQx));
gsl_vector_set(diffQy, j, fabs(exactQy-compQy));
//gsl_vector_set(diffH, j, RHSZeta[i*Np+j]);
//gsl_vector_set(diffQx, j, RHSQx[i*Np+j]);
//gsl_vector_set(diffQy,j, RHSQy[i*Np+j]);
//max = fmax(fabs(exactQx - compQx), max);
}
gsl_vector *tmpH = gsl_vector_alloc(Np);
gsl_vector *tmpQx = gsl_vector_alloc(Np);
gsl_vector *tmpQy = gsl_vector_alloc(Np);
double jac = FloodplainList[0]->jac[i];
gsl_blas_dgemv(CblasNoTrans, jac, MassMatrix2D, diffH, 0.0, tmpH);
gsl_blas_dgemv(CblasNoTrans, jac, MassMatrix2D, diffQx, 0.0, tmpQx);
gsl_blas_dgemv(CblasNoTrans, jac, MassMatrix2D, diffQy, 0.0, tmpQy);
double elerrHsq, elerrQxsq, elerrQysq;
gsl_blas_ddot(diffH, tmpH, &elerrHsq);
gsl_blas_ddot(diffQx, tmpQx, &elerrQxsq);
gsl_blas_ddot(diffQy, tmpQy, &elerrQysq);
errsqH += elerrHsq;
errsqQx += elerrQxsq;
errsqQy += elerrQysq;
gsl_vector_free(tmpH);
gsl_vector_free(tmpQx);
gsl_vector_free(tmpQy);
}
gsl_vector_free(diffH);
gsl_vector_free(diffQx);
gsl_vector_free(diffQy);
printf("time at error computation = %lf\n", time);
printf("l2 error in H = %lf \n", sqrt(errsqH));
printf("l2 error in Qx = %lf \n", sqrt(errsqQx));
printf("l2 error in Qy = %lf \n", sqrt(errsqQy));
//printf("maximum difference in Qx = %lf\n", max);
}
void append_to_file(char *fileName, double time, double data)
{
FILE* file = fopen(fileName, "a");
fprintf(file, "%lf %lf\n", time,data);
fclose(file);
}
double calculateTotalWater(struct channel *Chan)
{
int NumEl = Chan->NumEl;
int Np = Chan->Np;
int P = Chan->P;
double totalWater = 0;
double LGLWeight[Np];
GetLGLWeights(P, LGLWeight);
for (int k = 0; k < NumEl; k++)
{
double water = 0;
double dh = Chan->dh[k];
for (int i = 0; i < Np; i++)
{
double m1val = Chan->Nodalm1[k*Np+i];
double m2val = Chan->Nodalm2[k*Np+i];
double bval = Chan->NodalB[k*Np+i];
double A = Chan->A[k*Np+i+1];
double h = getH(A, bval, m1val, m2val);
water += LGLWeight[i]*(h-0.0000001);
}
totalWater += 0.5*dh*water;
}
return totalWater;
}
double ftTom(double ft)
{
double meter = ft*0.3048;
return meter;
}
double mToft (double m)
{
double ft = m*3.28084;
return ft;
}
| {
"alphanum_fraction": 0.6559034732,
"avg_line_length": 30.462797619,
"ext": "c",
"hexsha": "f1f0329089e1912cd8ffba4361a4bf979edfd235",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z",
"max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "evalseth/DG-RAIN",
"max_forks_repo_path": "DGSHED/helper_routines.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "evalseth/DG-RAIN",
"max_issues_repo_path": "DGSHED/helper_routines.c",
"max_line_length": 181,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "evalseth/DG-RAIN",
"max_stars_repo_path": "DGSHED/helper_routines.c",
"max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z",
"num_tokens": 7024,
"size": 20471
} |
#include <Advent/Advent.h>
#include <DayConfig.h>
#include <Input.h>
#include <cblas.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unicode/ustdio.h>
#include <unicode/ustring.h>
enum
{
OXY = 0,
CO2,
};
typedef struct
{
size_t oxy;
size_t co2;
} Part2Count;
typedef struct
{
bool highlight;
size_t highlightWhich;
} PrintBinArrayOptions;
static void PrintHelp(void);
static void PrintVersion(void);
static void PrintBinArray(const char* array, size_t count, PrintBinArrayOptions options);
static uint64_t BinToI64(const char* bin, size_t count);
int main(int argc, char** argv)
{
CommandLineCommand command;
if (Advent_ParseCommandLine(argc, argv, &command))
{
switch (command)
{
case COMMAND_LINE_COMMAND_PRINT_HELP:
PrintHelp();
return 0;
case COMMAND_LINE_COMMAND_PRINT_HELP_ERROR:
PrintHelp();
return 1;
case COMMAND_LINE_COMMAND_PRINT_VERSION:
PrintVersion();
return 0;
default:
fprintf(stderr, "Unknown command\n");
return 2;
}
}
UChar* unicodeInput = malloc((inputText_size + 1) * sizeof(UChar));
int32_t unicodeInputSize = 0;
UErrorCode errorCode = U_ZERO_ERROR;
u_strFromUTF8(unicodeInput, (int32_t)(inputText_size + 1), &unicodeInputSize, (const char*)inputText,
(int32_t)inputText_size, &errorCode);
if (errorCode != U_ZERO_ERROR)
{
fprintf(stderr, "Unicode error: %s\n", u_errorName(errorCode));
return 3;
}
char** matrix = NULL;
size_t m = 0;
size_t n = 0;
size_t cap = 0;
size_t rowCap = 0;
size_t width = 0;
U_STRING_DECL(delim, "\r\n", 2);
UChar* saveptr;
for (UChar* iter = u_strtok_r(unicodeInput, delim, &saveptr); iter != NULL; iter = u_strtok_r(NULL, delim, &saveptr))
{
if (m == cap)
{
cap = cap ? cap * 2 : 1;
char** newMatrix = realloc(matrix, cap * sizeof(char*));
matrix = newMatrix;
memset(&matrix[m], 0, (cap - m) * sizeof(char*));
}
char* row = malloc(rowCap * sizeof(char));
matrix[m] = row;
size_t i = 0;
while (true)
{
UChar32 ci;
U16_NEXT(iter, i, -1, ci);
if (ci == 0)
{
break;
}
if (ci == '0' || ci == '1')
{
if (i > n)
{
if (n == rowCap)
{
rowCap = rowCap ? rowCap * 2 : 1;
for (size_t i = 0; i < m; i++)
{
char* row = realloc(matrix[i], rowCap * sizeof(char));
matrix[i] = row;
}
}
++n;
}
matrix[m][i - 1] = (char)ci;
}
}
++m;
}
char** transposed = malloc(n * sizeof(char*));
for (size_t i = 0; i < n; ++i)
{
transposed[i] = malloc(m * sizeof(char));
for (size_t j = 0; j < m; ++j)
{
transposed[i][j] = matrix[j][i];
}
}
// calculate!
size_t** counts = malloc(n * sizeof(size_t*));
uint64_t gamma = 0;
uint64_t epsilon = 0;
for (size_t i = 0; i < n; ++i)
{
counts[i] = calloc(2, sizeof(size_t));
for (size_t j = 0; j < m; ++j)
{
// NIT: This assumes that the matrix is a rectangle!
// If there are ANY missing elements, this will likely segfault due to
// out-of-bounds array access.
counts[i][transposed[i][j] - '0']++;
}
gamma <<= 1;
gamma |= counts[i][1] > counts[i][0];
epsilon <<= 1;
epsilon |= counts[i][0] > counts[i][1];
}
printf("%lu\n", gamma * epsilon);
Part2Count** p2counts = malloc(n * sizeof(Part2Count*));
for (size_t i = 0; i < n; ++i)
{
p2counts[i] = calloc(2, sizeof(Part2Count));
}
bool** keep = malloc(m * sizeof(bool*));
for (size_t i = 0; i < m; ++i)
{
keep[i] = malloc(2 * sizeof(bool));
keep[i][OXY] = true;
keep[i][CO2] = true;
}
size_t oxy = 0;
size_t co2 = 0;
for (size_t i = 0; i < n; ++i)
{
memset(p2counts[i], 0, 2 * sizeof(Part2Count));
for (size_t j = 0; j < m; ++j)
{
if (keep[j][OXY])
{
p2counts[i][transposed[i][j] - '0'].oxy++;
}
if (keep[j][CO2])
{
p2counts[i][transposed[i][j] - '0'].co2++;
}
}
bool selector = p2counts[i][0].oxy > p2counts[i][1].oxy;
// filter out 1's for OXY, 0's for CO2
size_t keptOxy = SIZE_MAX;
size_t keptCo2 = SIZE_MAX;
for (size_t j = 0; j < m; ++j)
{
if (keep[j][OXY])
{
if (transposed[i][j] == (p2counts[i][0].oxy > p2counts[i][1].oxy ? '1' : '0'))
{
keep[j][OXY] = false;
}
else if (keptOxy == SIZE_MAX)
{
keptOxy = j;
}
}
if (keep[j][CO2])
{
if (transposed[i][j] == (p2counts[i][0].co2 > p2counts[i][1].co2 ? '0' : '1'))
{
keep[j][CO2] = false;
}
else if (keptCo2 == SIZE_MAX)
{
keptCo2 = j;
}
}
}
if (keptOxy != SIZE_MAX)
{
oxy = keptOxy;
}
if (keptCo2 != SIZE_MAX)
{
co2 = keptCo2;
}
}
printf("Filtering complete\n");
printf("OXY: index %lu\n", oxy);
printf("OXY: ");
PrintBinArray(matrix[oxy], n, (PrintBinArrayOptions){0});
printf(" (as array)\n");
printf("OXY: %lu (as decimal)\n", BinToI64(matrix[oxy], n));
printf("CO2: index %lu\n", co2);
printf("CO2: ");
PrintBinArray(matrix[co2], n, (PrintBinArrayOptions){0});
printf(" (as array)\n");
printf("CO2: %lu (as decimal)\n", BinToI64(matrix[co2], n));
printf("Part 2: %lu\n", BinToI64(matrix[oxy], n) * BinToI64(matrix[co2], n));
for (size_t i = 0; i < m; ++i)
{
free(keep[i]);
}
free(keep);
for (size_t i = 0; i < n; ++i)
{
free(p2counts[i]);
}
free(p2counts);
for (size_t i = 0; i < m; ++i)
{
free(matrix[i]);
}
free(matrix);
for (size_t i = 0; i < n; ++i)
{
free(transposed[i]);
free(counts[i]);
}
free(transposed);
free(counts);
free(unicodeInput);
}
static void PrintHelp(void)
{
PrintVersion();
printf("Usage: %s [options]\n", ADVENT_DAY_NAME);
puts("Options:");
puts(" -h,--help Print this help message");
puts(" -V,--version Print the program version");
}
static void PrintVersion(void)
{
printf("%s v%s\n", ADVENT_DAY_NAME, PROJECT_VERSION);
}
static void PrintBinArray(const char* array, size_t count, PrintBinArrayOptions options)
{
for (size_t i = 0; i < count; ++i)
{
if (options.highlight && options.highlightWhich == i)
{
putchar('{');
}
putchar(array[i]);
if (options.highlight && options.highlightWhich == i)
{
putchar('}');
}
}
}
static uint64_t BinToI64(const char* bin, size_t count)
{
char* str = malloc(count + 1);
memcpy(str, bin, count);
str[count] = '\0';
uint64_t result = strtoul(str, NULL, 2);
free(str);
return result;
}
| {
"alphanum_fraction": 0.5475453339,
"avg_line_length": 22.993220339,
"ext": "c",
"hexsha": "2b633cb73e44859037ceea4433d383490a56c80b",
"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": "4a2ace4bee6e6f287436d763d57d575d92d1cee0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Phytolizer/aoc-2021",
"max_forks_repo_path": "C/Source/Day03/Main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4a2ace4bee6e6f287436d763d57d575d92d1cee0",
"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": "Phytolizer/aoc-2021",
"max_issues_repo_path": "C/Source/Day03/Main.c",
"max_line_length": 119,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "4a2ace4bee6e6f287436d763d57d575d92d1cee0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Phytolizer/aoc-2021",
"max_stars_repo_path": "C/Source/Day03/Main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2173,
"size": 6783
} |
#include <petsc.h>
#include "flow.h"
#include "mesh.h"
#define DIM 2 /* Geometric dimension */
#define NFIELDS 3
static const FlowFieldDescriptor PhysicsFields[] = {{"Density", "Den",1},{"Momentum", "Momentum",DIM},{"Energy", "Energy",1},{NULL,0}};
typedef enum {EULER_PAR_GAMMA,EULER_PAR_RHOR,EULER_PAR_AMACH,EULER_PAR_ITANA,EULER_PAR_SIZE} EulerParamIdx;
typedef struct {
PetscReal rho;
PetscReal rhoU[DIM];
PetscReal rhoE;
} EulerNode;
typedef union {
EulerNode eulernode;
PetscReal vals[DIM+2];
} EulerNodeUnion;
typedef struct {
PetscReal gamma;
PetscReal rhoL;
PetscReal rhoR;
PetscReal uL;
PetscReal uR;
PetscReal pL;
PetscReal pR;
PetscReal maxTime;
PetscReal length;
} Setup;
typedef struct {
PetscReal pstar,ustar,rhostarL,astarL,SL,SHL,STL,rhostarR,astarR,SR,SHR,STR,gamm1,gamp1;
} StarState;
typedef struct {
StarState starState;
Setup setup;
PetscReal cfl;
} ProblemSetup;
typedef struct{
PetscReal f;
PetscReal fprm;
} PressureFunction;
static PressureFunction f_and_fprm_rarefaction(PetscReal pstar, PetscReal pLR, PetscReal aLR, PetscReal gam, PetscReal gamm1,PetscReal gamp1) {
// compute value of pressure function for rarefaction
PressureFunction function;
function.f = ((2. * aLR) / gamm1) * (pow(pstar / pLR, 0.5 * gamm1 / gam) - 1.);
function.fprm = (aLR / pLR / gam) * pow(pstar / pLR, -0.5 * gamp1 / gam);
return function;
}
static PressureFunction f_and_fprm_shock(PetscReal pstar, PetscReal pLR, PetscReal rhoLR, PetscReal gam, PetscReal gamm1, PetscReal gamp1){
// compute value of pressure function for shock
PetscReal A = 2./gamp1/rhoLR;
PetscReal B = gamm1*pLR/gamp1;
PetscReal sqrtterm = PetscSqrtReal(A/(pstar+B));
PressureFunction function;
function.f = (pstar-pLR)*sqrtterm;
function.fprm = sqrtterm*(1.-0.5*(pstar-pLR)/(B+pstar));
return function;
}
#define EPS 1.e-6
#define MAXIT 100
static PetscErrorCode DetermineStarState(const Setup* setup, StarState* starState){
// compute the speed of sound
PetscReal aL = PetscSqrtReal(setup->gamma*setup->pL/setup->rhoL);
PetscReal aR = PetscSqrtReal(setup->gamma*setup->pR/setup->rhoR);
//first guess pstar based on two-rarefacation approximation
starState->pstar = aL+aR - 0.5*(setup->gamma-1.)*(setup->uR-setup->uL);
starState->pstar = starState->pstar / (aL/pow(setup->pL,0.5*(setup->gamma-1.)/setup->gamma) + aR/pow(setup->pR,0.5*(setup->gamma-1.)/setup->gamma) );
starState->pstar = pow(starState->pstar,2.*setup->gamma/(setup->gamma-1.));
starState->gamm1 = setup->gamma-1.;
starState->gamp1 = setup->gamma+1.;
PressureFunction fL;
if (starState->pstar <= setup->pL){
fL = f_and_fprm_rarefaction(starState->pstar, setup->pL,aL,setup->gamma,starState->gamm1,starState->gamp1);
}else{
fL = f_and_fprm_shock(starState->pstar,setup->pL,setup->rhoL,setup->gamma,starState->gamm1,starState->gamp1);
}
PressureFunction fR;
if (starState->pstar <= setup->pR) {
fR = f_and_fprm_rarefaction(starState->pstar, setup->pR, aR, setup->gamma, starState->gamm1, starState->gamp1);
}else {
fR = f_and_fprm_shock(starState->pstar, setup->pR, setup->rhoR, setup->gamma, starState->gamm1, starState->gamp1);
}
PetscReal delu = setup->uR-setup->uL;
// iterate using Newton-Rapson
if ((fL.f+fR.f+delu)> EPS) {
// iterate using Newton-Rapson
for(PetscInt it =0; it < MAXIT+4; it++){
PetscReal pold = starState->pstar;
starState->pstar = pold - (fL.f+fR.f+delu)/(fL.fprm+fR.fprm);
if(starState->pstar < 0){
starState->pstar = EPS;
}
if(2.0*PetscAbsReal(starState->pstar - pold)/(starState->pstar + pold) < EPS){
break;
}else{
if(starState->pstar < setup->pL){
fL = f_and_fprm_rarefaction(starState->pstar, setup->pL,aL,setup->gamma,starState->gamm1,starState->gamp1);
}else{
fL = f_and_fprm_shock(starState->pstar,setup->pL,setup->rhoL,setup->gamma,starState->gamm1,starState->gamp1);
}
if (starState->pstar<=setup->pR) {
fR = f_and_fprm_rarefaction(starState->pstar, setup->pR, aR, setup->gamma, starState->gamm1, starState->gamp1);
}else {
fR = f_and_fprm_shock(starState->pstar, setup->pR, setup->rhoR, setup->gamma, starState->gamm1, starState->gamp1);
}
}
if (it>MAXIT){
SETERRQ(PETSC_COMM_WORLD,1,"error in Riemann.find_pstar - did not converage for pstar" );
}
}
}
// determine rest of star state
starState->ustar = 0.5*(setup->uL+setup->uR+fR.f-fL.f);
// left star state
PetscReal pratio = starState->pstar/setup->pL;
if (starState->pstar<=setup->pL) { // rarefaction
starState->rhostarL = setup->rhoL * PetscPowReal(pratio, 1. / setup->gamma);
starState->astarL = aL * PetscPowReal(pratio, 0.5 * starState->gamm1 / setup->gamma);
starState->SHL = setup->uL - aL;
starState->STL = starState->ustar - starState->astarL;
}else { // #shock
starState->rhostarL = setup->rhoL * (pratio + starState->gamm1 / starState->gamp1) / (starState->gamm1 * pratio / starState->gamp1 + 1.);
starState->SL = setup->uL - aL * PetscSqrtReal(0.5 * starState->gamp1 / setup->gamma * pratio + 0.5 * starState->gamm1 / setup->gamma);
}
// right star state
pratio = starState->pstar/setup->pR;
if (starState->pstar<=setup->pR) { // # rarefaction
starState->rhostarR = setup->rhoR * PetscPowReal(pratio, 1. / setup->gamma);
starState->astarR = aR * PetscPowReal(pratio, 0.5 * starState->gamm1 / setup->gamma);
starState-> SHR = setup->uR + aR;
starState->STR = starState->ustar + starState->astarR;
}else { // shock
starState->rhostarR = setup->rhoR * (pratio + starState->gamm1 / starState->gamp1) / (starState->gamm1 * pratio / starState->gamp1 + 1.);
starState->SR = setup->uR + aR * PetscSqrtReal(0.5 * starState->gamp1 / setup->gamma * pratio + 0.5 * starState->gamm1 / setup->gamma);
}
return 0;
}
static void SetExactSolutionAtPoint(PetscInt dim, PetscReal xDt, const Setup* setup, const StarState* starState, EulerNode* uu){
PetscReal p;
// compute the speed of sound
PetscReal aL = PetscSqrtReal(setup->gamma*setup->pL/setup->rhoL);
PetscReal aR = PetscSqrtReal(setup->gamma*setup->pR/setup->rhoR);
for(PetscInt i =0; i < dim; i++){
uu->rhoU[i] = 0.0;
}
if (xDt <= starState->ustar) { //# left of contact surface
if (starState->pstar <= setup->pL) { // # rarefaction
if (xDt <= starState->SHL) {
uu->rho = setup->rhoL;
p = setup->pL;
uu->rhoU[0] = setup->uL*uu->rho;
}else if (xDt <=starState->STL) { //#SHL < x / t < STL
PetscReal tmp = 2. / starState->gamp1 + (starState->gamm1 / starState->gamp1 / aL) * (setup->uL - xDt);
uu->rho = setup->rhoL * pow(tmp, 2. / starState->gamm1);
uu->rhoU[0] = uu->rho * (2. / starState->gamp1) * (aL + 0.5 * starState->gamm1 * setup->uL + xDt);
p = setup->pL * pow(tmp, 2. * setup->gamma / starState->gamm1);
}else { //# STL < x/t < u*
uu->rho = starState->rhostarL;
p = starState->pstar;
uu->rhoU[0] = uu->rho * starState->ustar;
}
}else{ //# shock
if (xDt<= starState->SL) { // # xDt < SL
uu->rho = setup->rhoL;
p = setup->pL;
uu->rhoU[0] = uu->rho * setup->uL;
}else { //# SL < xDt < ustar
uu->rho = starState->rhostarL;
p = starState->pstar;
uu->rhoU[0] = uu->rho * starState->ustar;
}
}
}else{//# right of contact surface
if (starState->pstar<=setup->pR) { //# rarefaction
if (xDt>= starState->SHR) {
uu->rho = setup->rhoR;
p = setup->pR;
uu->rhoU[0] = uu->rho * setup->uR;
}else if (xDt >= starState->STR) { // # SHR < x/t < SHR
PetscReal tmp = 2./starState->gamp1 - (starState->gamm1/starState->gamp1/aR)*(setup->uR-xDt);
uu->rho = setup->rhoR*PetscPowReal(tmp,2./starState->gamm1);
uu->rhoU[0] = uu->rho * (2./starState->gamp1)*(-aR + 0.5*starState->gamm1*setup->uR+xDt);
p = setup->pR*PetscPowReal(tmp,2.*setup->gamma/starState->gamm1);
}else{ //# u* < x/t < STR
uu->rho = starState->rhostarR;
p = starState->pstar;
uu->rhoU[0] = uu->rho * starState->ustar;
}
}else {//# shock
if (xDt>= starState->SR) { // # xDt > SR
uu->rho = setup->rhoR;
p = setup->pR;
uu->rhoU[0] = uu->rho * setup->uR;
}else {//#ustar < xDt < SR
uu->rho = starState->rhostarR;
p = starState->pstar;
uu->rhoU[0] = uu->rho * starState->ustar;
}
}
}
PetscReal e = p/starState->gamm1/uu->rho;
PetscReal E = e + 0.5*(uu->rhoU[0]/uu->rho)*(uu->rhoU[0]/uu->rho);
uu->rhoE = uu->rho*E;
}
static PetscErrorCode SetExactSolutionRho(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx){
ProblemSetup* prob = (ProblemSetup*)ctx;
PetscReal xDt = (x[0]-prob->setup.length/2)/time;
EulerNode uu;
SetExactSolutionAtPoint(dim, xDt, &prob->setup, &prob->starState, &uu);
u[0] = uu.rho;
return 0;
}
static PetscErrorCode SetExactSolutionRhoU(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx){
ProblemSetup* prob = (ProblemSetup*)ctx;
PetscReal xDt = (x[0]-prob->setup.length/2)/time;
EulerNode uu;
SetExactSolutionAtPoint(dim, xDt, &prob->setup, &prob->starState, &uu);
u[0] = uu.rhoU[0];
u[1] = uu.rhoU[1];
return 0;
}
static PetscErrorCode SetExactSolutionRhoE(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx){
ProblemSetup* prob = (ProblemSetup*)ctx;
PetscReal xDt = (x[0]-prob->setup.length/2)/time;
EulerNode uu;
SetExactSolutionAtPoint(dim, xDt, &prob->setup, &prob->starState, &uu);
u[0] = uu.rhoE;
return 0;
}
static PetscErrorCode PrintVector(DM dm, Vec v, PetscInt step, const char * fileName){
Vec cellgeom;
PetscErrorCode ierr = DMPlexGetGeometryFVM(dm, NULL, &cellgeom, NULL);CHKERRQ(ierr);
PetscInt cStart, cEnd;
ierr = DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
DM dmCell;
ierr = VecGetDM(cellgeom, &dmCell);CHKERRQ(ierr);
const PetscScalar *cgeom;
ierr = VecGetArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);
const PetscScalar *x;
ierr = VecGetArrayRead(v, &x);CHKERRQ(ierr);
// print the header for each file
char filename[100];
ierr = PetscSNPrintf(filename,sizeof(filename),"%s.%d.txt",fileName, step);CHKERRQ(ierr);
PetscInt rank = 0;
PetscInt size;
ierr = MPI_Comm_rank(PetscObjectComm(dm), &rank);CHKERRMPI(ierr);
ierr = MPI_Comm_size(PetscObjectComm(dm), &size);CHKERRMPI(ierr);
for(PetscInt r =0; r < size; r++ ) {
if(r == rank) {
FILE *fptr;
if(r == 0){
fptr = fopen(filename, "w");
fprintf(fptr, "x rho u e\n");
}else{
fptr = fopen(filename, "a");
}
for (PetscInt c = cStart; c < cEnd; ++c) {
PetscFVCellGeom *cg;
const EulerNode *xc;
ierr = DMPlexPointLocalRead(dmCell, c, cgeom, &cg);
CHKERRQ(ierr);
ierr = DMPlexPointGlobalFieldRead(dm, c, 0, x, &xc);
CHKERRQ(ierr);
if(xc) {// must be real cell and not ghost
PetscReal u0 = xc->rhoU[0] / xc->rho;
fprintf(fptr, "%f %f %f %f\n", cg->centroid[0], xc->rho, u0, (xc->rhoE / xc->rho) - 0.5 * u0 * u0);
}
}
fclose(fptr);
}
MPI_Barrier(PetscObjectComm(dm));
}
ierr = VecRestoreArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(v, &x);CHKERRQ(ierr);
return 0;
}
static PetscErrorCode MonitorError(TS ts, PetscInt step, PetscReal time, Vec u, void *ctx) {
PetscFunctionBeginUser;
PetscErrorCode ierr;
// Get the DM
DM dm;
ierr = TSGetDM(ts, &dm);CHKERRQ(ierr);
// Create a copy of the u vector
Vec e;
ierr = DMCreateGlobalVector(dm, &e);CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject)e, "exact");CHKERRQ(ierr);
// Set the values
PetscErrorCode (*func[3]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {{SetExactSolutionRho, SetExactSolutionRhoU, SetExactSolutionRhoE}};
void* ctxs[3] ={ctx, ctx, ctx};
ierr = DMProjectFunction(dm,time,func,ctxs,INSERT_ALL_VALUES,e);CHKERRQ(ierr);
// just print to a file for now
ierr = PrintVector(dm, e, step, "exact");CHKERRQ(ierr);
ierr = PrintVector(dm, u, step, "solution");CHKERRQ(ierr);
PetscPrintf(PETSC_COMM_WORLD, "TS %d: %f\n", step, time);
DMRestoreGlobalVector(dm, &e);
PetscFunctionReturn(0);
}
static PetscErrorCode PhysicsBoundary_Euler_Mirror(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx)
{
const EulerNode *xI = (const EulerNode*)a_xI;
EulerNode *xG = (EulerNode*)a_xG;
ProblemSetup* prob = (ProblemSetup*)ctx;
PetscFunctionBeginUser;
xG->rho = xI->rho;
xG->rhoE = xI->rhoE;
xG->rhoU[0] = xI->rhoU[0];
xG->rhoU[1] = xI->rhoU[1];
PetscFunctionReturn(0);
}
/* PetscReal* => EulerNode* conversion */
static PetscErrorCode PhysicsBoundary_Euler_Left(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx)
{
const EulerNode *xI = (const EulerNode*)a_xI;
EulerNode *xG = (EulerNode*)a_xG;
ProblemSetup* prob = (ProblemSetup*)ctx;
PetscFunctionBeginUser;
xG->rho = prob->setup.rhoL;
PetscReal eT = prob->setup.rhoL*((prob->setup.pL /(prob->setup.gamma -1) / prob->setup.rhoL) + 0.5 * prob->setup.uL * prob->setup.uL);
xG->rhoE = eT;
xG->rhoU[0] = prob->setup.rhoL * prob->setup.uL;
xG->rhoU[1] = 0.0;
PetscFunctionReturn(0);
}
/* PetscReal* => EulerNode* conversion */
static PetscErrorCode PhysicsBoundary_Euler_Right(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx)
{
const EulerNode *xI = (const EulerNode*)a_xI;
EulerNode *xG = (EulerNode*)a_xG;
ProblemSetup* prob = (ProblemSetup*)ctx;
PetscFunctionBeginUser;
xG->rho = prob->setup.rhoR;
PetscReal eT = prob->setup.rhoR*((prob->setup.pR /(prob->setup.gamma -1)/ prob->setup.rhoR) + 0.5 * prob->setup.uR * prob->setup.uR);
xG->rhoE = eT;
xG->rhoU[0] = prob->setup.rhoR * prob->setup.uR;
xG->rhoU[1] = 0.0;
PetscFunctionReturn(0);
}
static PetscErrorCode ComputeTimeStep(TS ts){
DM dm;
PetscErrorCode ierr = TSGetDM(ts, &dm);CHKERRQ(ierr);
Vec v;
TSGetSolution(ts, &v);
ProblemSetup *problem;
ierr = DMGetApplicationContext(dm, &problem);CHKERRQ(ierr);
Vec cellgeom;
ierr = DMPlexGetGeometryFVM(dm, NULL, &cellgeom, NULL);CHKERRQ(ierr);
PetscInt cStart, cEnd;
ierr = DMPlexGetSimplexOrBoxCells(dm, 0, &cStart, &cEnd);CHKERRQ(ierr);
DM dmCell;
ierr = VecGetDM(cellgeom, &dmCell);CHKERRQ(ierr);
const PetscScalar *cgeom;
ierr = VecGetArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);
const PetscScalar *x;
ierr = VecGetArrayRead(v, &x);CHKERRQ(ierr);
PetscReal dtMin = 1.0;
for (PetscInt c = cStart; c < cEnd; ++c) {
PetscFVCellGeom *cg;
const EulerNode *xc;
ierr = DMPlexPointLocalRead(dmCell, c, cgeom, &cg);CHKERRQ(ierr);
ierr = DMPlexPointGlobalFieldRead(dm, c, 0, x, &xc);CHKERRQ(ierr);
if(xc) { // must be real cell and not ghost
PetscReal rho = xc->rho;
PetscReal u = xc->rhoU[0] / rho;
PetscReal e = (xc->rhoE / rho) - 0.5 * u * u;
PetscReal p = (problem->setup.gamma - 1) * rho * e;
PetscReal a = PetscSqrtReal(problem->setup.gamma * p / rho);
PetscReal dt = problem->cfl * cg->volume / (a + PetscAbsReal(u));
dtMin = PetscMin(dtMin, dt);
}
}
PetscInt rank;
MPI_Comm_rank(PetscObjectComm(ts), &rank);
printf("dtMin(%d): %f\n", rank,dtMin );
PetscReal dtMinGlobal;
ierr = MPI_Allreduce(&dtMin, &dtMinGlobal, 1,MPIU_REAL, MPI_MIN, PetscObjectComm(ts));
PetscPrintf(PetscObjectComm(ts), "TimeStep: %f\n", dtMinGlobal);
// ierr = TSSetTimeStep(ts, dtMinGlobal);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(cellgeom, &cgeom);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(v, &x);CHKERRQ(ierr);
return 0;
}
static void ComputeFluxRho(PetscInt dim, PetscInt Nf, const PetscReal *qp, const PetscReal *n, const EulerNode *xL, const EulerNode *xR, PetscInt numConstants, const PetscScalar constants[], PetscReal *flux, void* ctx) {
// dim - The spatial dimension
// Nf - The number of fields
// x - The coordinates at a point on the interface
// n - The normal vector to the interface
// uL - The state vector to the left of the interface
// uR - The state vector to the right of the interface
// flux - output array of flux through the interface
// numConstants - number of constant parameters
// constants - constant parameters
// ctx - optional user context
ProblemSetup* prob = (ProblemSetup*)ctx;
// this is a hack, only add in flux from left/right
if(PetscAbs(n[0]) > 1E-5) {
// Setup Godunov
Setup currentValues;
currentValues.gamma = prob->setup.gamma;
currentValues.length = prob->setup.length;
if (n[0] > 0) {
currentValues.rhoL = xL->rho;
currentValues.uL = xL->rhoU[0] / currentValues.rhoL;
PetscReal eL = (xL->rhoE / currentValues.rhoL) - 0.5 * currentValues.uL * currentValues.uL;
currentValues.pL = (prob->setup.gamma - 1) * currentValues.rhoL * eL;
currentValues.rhoR = xR->rho;
currentValues.uR = xR->rhoU[0] / currentValues.rhoR;
PetscReal eR = (xR->rhoE / currentValues.rhoR) - 0.5 * currentValues.uR * currentValues.uR;
currentValues.pR = (prob->setup.gamma - 1) * currentValues.rhoR * eR;
}else{
currentValues.rhoR = xL->rho;
currentValues.uR = xL->rhoU[0] / currentValues.rhoR;
PetscReal eR = (xL->rhoE / currentValues.rhoR) - 0.5 * currentValues.uR * currentValues.uR;
currentValues.pR = (prob->setup.gamma - 1) * currentValues.rhoR * eR;
currentValues.rhoL = xR->rho;
currentValues.uL = xR->rhoU[0] / currentValues.rhoL;
PetscReal eL = (xR->rhoE / currentValues.rhoL) - 0.5 * currentValues.uL * currentValues.uL;
currentValues.pL = (prob->setup.gamma - 1) * currentValues.rhoL * eL;
}
StarState result;
DetermineStarState(¤tValues, &result);
EulerNode exact;
SetExactSolutionAtPoint(dim, 0.0, ¤tValues, &result, &exact);
PetscReal rho = exact.rho;
PetscReal u = exact.rhoU[0]/rho;
PetscReal e = (exact.rhoE / rho) - 0.5 * u * u;
PetscReal p = (prob->setup.gamma-1) * rho * e;
flux[0] = rho * u * PetscSignReal(n[0]);
printf("flux qp[%f]: %f n:%f rL:%f rR:%f\n ", qp[0], flux[0], n[0], currentValues.rhoL, currentValues.rhoR);
// flux->rhoU[0] = (rho * u * u + p)* PetscSignReal(n[0]);
// flux->rhoU[1] = 0.0;
// PetscReal et = e + 0.5 * u * u;
// flux->rhoE = (rho * u * (et + p / rho))* PetscSignReal(n[0]);
// printf("%f,%f %f %f,%f\n", qp[0], qp[1], flux[0], n[0], n[1]);mm
}else{
flux[0] = 0.0;
// flux->rhoU[0] =0.0;
// flux->rhoU[1] = 0.0;
// flux->rhoE = 0.0;
}
// F[0][i]=rho[i]*u[i]
// F[1][i]=rho[i]*u[i]*u[i]+p[i]
// et = e[i]+0.5*u[i]*u[i]
// F[2][i]=rho[i]*u[i]*(et+p[i]/rho[i])
}
static void ComputeFluxU(PetscInt dim, PetscInt Nf, const PetscReal *qp, const PetscReal *n, const EulerNode *xL, const EulerNode *xR, PetscInt numConstants, const PetscScalar constants[], PetscReal *flux, void* ctx) {
// dim - The spatial dimension
// Nf - The number of fields
// x - The coordinates at a point on the interface
// n - The normal vector to the interface
// uL - The state vector to the left of the interface
// uR - The state vector to the right of the interface
// flux - output array of flux through the interface
// numConstants - number of constant parameters
// constants - constant parameters
// ctx - optional user context
ProblemSetup* prob = (ProblemSetup*)ctx;
// this is a hack, only add in flux from left/right
if(PetscAbs(n[0]) > 1E-5) {
// Setup Godunov
Setup currentValues;
currentValues.gamma = prob->setup.gamma;
currentValues.length = prob->setup.length;
if (n[0] > 0) {
currentValues.rhoL = xL->rho;
currentValues.uL = xL->rhoU[0] / currentValues.rhoL;
PetscReal eL = (xL->rhoE / currentValues.rhoL) - 0.5 * currentValues.uL * currentValues.uL;
currentValues.pL = (prob->setup.gamma - 1) * currentValues.rhoL * eL;
currentValues.rhoR = xR->rho;
currentValues.uR = xR->rhoU[0] / currentValues.rhoR;
PetscReal eR = (xR->rhoE / currentValues.rhoR) - 0.5 * currentValues.uR * currentValues.uR;
currentValues.pR = (prob->setup.gamma - 1) * currentValues.rhoR * eR;
}else{
currentValues.rhoR = xL->rho;
currentValues.uR = xL->rhoU[0] / currentValues.rhoR;
PetscReal eR = (xL->rhoE / currentValues.rhoR) - 0.5 * currentValues.uR * currentValues.uR;
currentValues.pR = (prob->setup.gamma - 1) * currentValues.rhoR * eR;
currentValues.rhoL = xR->rho;
currentValues.uL = xR->rhoU[0] / currentValues.rhoL;
PetscReal eL = (xR->rhoE / currentValues.rhoL) - 0.5 * currentValues.uL * currentValues.uL;
currentValues.pL = (prob->setup.gamma - 1) * currentValues.rhoL * eL;
}
StarState result;
DetermineStarState(¤tValues, &result);
EulerNode exact;
SetExactSolutionAtPoint(dim, 0.0, ¤tValues, &result, &exact);
PetscReal rho = exact.rho;
PetscReal u = exact.rhoU[0]/rho;
PetscReal e = (exact.rhoE / rho) - 0.5 * u * u;
PetscReal p = (prob->setup.gamma-1) * rho * e;
// flux[0] = (rho * u) * PetscSignReal(n[0]);
flux[0] = (rho * u * u + p)* PetscSignReal(n[0]);
flux[1] = 0.0;
// PetscReal et = e + 0.5 * u * u;
// flux->rhoE = (rho * u * (et + p / rho))* PetscSignReal(n[0]);
// printf("%f,%f %f %f %f %f\n", qp[0], qp[1], flux->rho, flux->rhoU[0], flux->rhoE, n[0]);
}else{
flux[0] = 0.0;
flux[1] = 0.0;
// flux->rhoU[0] =0.0;
// flux->rhoU[1] = 0.0;
// flux->rhoE = 0.0;
}
// F[0][i]=rho[i]*u[i]
// F[1][i]=rho[i]*u[i]*u[i]+p[i]
// et = e[i]+0.5*u[i]*u[i]
// F[2][i]=rho[i]*u[i]*(et+p[i]/rho[i])
}
static void ComputeFluxE(PetscInt dim, PetscInt Nf, const PetscReal *qp, const PetscReal *n, const EulerNode *xL, const EulerNode *xR, PetscInt numConstants, const PetscScalar constants[], PetscReal *flux, void* ctx) {
// dim - The spatial dimension
// Nf - The number of fields
// x - The coordinates at a point on the interface
// n - The normal vector to the interface
// uL - The state vector to the left of the interface
// uR - The state vector to the right of the interface
// flux - output array of flux through the interface
// numConstants - number of constant parameters
// constants - constant parameters
// ctx - optional user context
ProblemSetup* prob = (ProblemSetup*)ctx;
// this is a hack, only add in flux from left/right
if(PetscAbs(n[0]) > 1E-5) {
// Setup Godunov
Setup currentValues;
currentValues.gamma = prob->setup.gamma;
currentValues.length = prob->setup.length;
if (n[0] > 0) {
currentValues.rhoL = xL->rho;
currentValues.uL = xL->rhoU[0] / currentValues.rhoL;
PetscReal eL = (xL->rhoE / currentValues.rhoL) - 0.5 * currentValues.uL * currentValues.uL;
currentValues.pL = (prob->setup.gamma - 1) * currentValues.rhoL * eL;
currentValues.rhoR = xR->rho;
currentValues.uR = xR->rhoU[0] / currentValues.rhoR;
PetscReal eR = (xR->rhoE / currentValues.rhoR) - 0.5 * currentValues.uR * currentValues.uR;
currentValues.pR = (prob->setup.gamma - 1) * currentValues.rhoR * eR;
}else{
currentValues.rhoR = xL->rho;
currentValues.uR = xL->rhoU[0] / currentValues.rhoR;
PetscReal eR = (xL->rhoE / currentValues.rhoR) - 0.5 * currentValues.uR * currentValues.uR;
currentValues.pR = (prob->setup.gamma - 1) * currentValues.rhoR * eR;
currentValues.rhoL = xR->rho;
currentValues.uL = xR->rhoU[0] / currentValues.rhoL;
PetscReal eL = (xR->rhoE / currentValues.rhoL) - 0.5 * currentValues.uL * currentValues.uL;
currentValues.pL = (prob->setup.gamma - 1) * currentValues.rhoL * eL;
}
StarState result;
DetermineStarState(¤tValues, &result);
EulerNode exact;
SetExactSolutionAtPoint(dim, 0.0, ¤tValues, &result, &exact);
PetscReal rho = exact.rho;
PetscReal u = exact.rhoU[0]/rho;
PetscReal e = (exact.rhoE / rho) - 0.5 * u * u;
PetscReal p = (prob->setup.gamma-1) * rho * e;
// flux[0] = (rho * u) * PetscSignReal(n[0]);
// flux[0] = (rho * u * u + p)* PetscSignReal(n[0]);
// flux[1] = 0.0;
PetscReal et = e + 0.5 * u * u;
flux[0] = (rho * u * (et + p / rho))* PetscSignReal(n[0]);
// printf("%f,%f %f %f %f %f\n", qp[0], qp[1], flux->rho, flux->rhoU[0], flux->rhoE, n[0]);
}else{
flux[0] = 0.0;
// flux[1] = 0.0;
// flux->rhoU[0] =0.0;
// flux->rhoU[1] = 0.0;
// flux->rhoE = 0.0;
}
// F[0][i]=rho[i]*u[i]
// F[1][i]=rho[i]*u[i]*u[i]+p[i]
// et = e[i]+0.5*u[i]*u[i]
// F[2][i]=rho[i]*u[i]*(et+p[i]/rho[i])
}
int main(int argc, char **argv)
{
PetscErrorCode ierr;
// create the mesh
// setup the ts
DM dm; /* problem definition */
TS ts; /* timestepper */
// initialize petsc and mpi
PetscInitialize(&argc, &argv, NULL, "HELP");
// Setup the problem
ProblemSetup problem;
// case 1 - Sod problem
problem.setup.rhoL=1.0;
problem.setup.uL=0.0;
problem.setup.pL=1.0;
problem.setup.rhoR=0.125;
problem.setup.uR=0.0;
problem.setup.pR=0.1;
problem.setup.maxTime = 0.25;
problem.setup.length = 1;
problem.setup.gamma = 1.4;
problem.cfl = .5;
// case 2 - 123 problem - expansion left and expansion right
// problem.setup.rhoL=1.0;
// problem.setup.uL=-2.0;
// problem.setup.pL=0.4;
// problem.setup.rhoR=1.0;
// problem.setup.uR=2.0;
// problem.setup.pR=0.4;
// problem.setup.maxTime = 0.15;
// problem.setup.length = 1;
// problem.setup.gamma = 1.4;
// problem.cfl = 0.4;
ierr = TSCreate(PETSC_COMM_WORLD, &ts);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = TSSetType(ts, TSEULER);CHKERRQ(ierr);
//PetscErrorCode DMPlexCreateBoxMesh(MPI_Comm comm, PetscInt dim, PetscBool simplex, const PetscInt faces[], const PetscReal lower[], const PetscReal upper[], const DMBoundaryType periodicity[], PetscBool interpolate, DM *dm)
PetscReal start[] = {0.0, 0.0};
PetscReal end[] = {problem.setup.length, 1};
PetscInt nx[] = {100, 1};
DMBoundaryType bcType[] = {DM_BOUNDARY_NONE, DM_BOUNDARY_NONE};
ierr = DMPlexCreateBoxMesh(PETSC_COMM_WORLD, DIM, PETSC_FALSE, nx, start, end, bcType, PETSC_TRUE, &dm);CHKERRQ(ierr);
{
DM dmDist;
// ierr = DMSetBasicAdjacency(dm, PETSC_TRUE, PETSC_FALSE);CHKERRQ(ierr);
ierr = DMPlexDistribute(dm, 1, NULL, &dmDist);CHKERRQ(ierr);
if (dmDist) {
ierr = DMDestroy(&dm);CHKERRQ(ierr);
dm = dmDist;
}
}
ierr = DMSetFromOptions(dm);CHKERRQ(ierr);
{
DM gdm;
ierr = DMPlexConstructGhostCells(dm, NULL, NULL, &gdm);CHKERRQ(ierr);
ierr = DMDestroy(&dm);CHKERRQ(ierr);
dm = gdm;
}
// DMLabel label;
// ierr = DMGetLabel(dm, "marker", &label );CHKERRQ(ierr);
// ierr = DMLabelView(label, PETSC_VIEWER_STDOUT_WORLD);;CHKERRQ(ierr);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = TSSetDM(ts, dm);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// setup the FV
{// Setup the fields
PetscInt f, dof;
for (f=0,dof=0; f < 3; f++) {
PetscInt newDof = PhysicsFields[f].components;
// if (newDof == 1) {
PetscFV fvm;
ierr = PetscFVCreate(PETSC_COMM_WORLD, &fvm);CHKERRQ(ierr);
ierr = PetscFVSetFromOptions(fvm);CHKERRQ(ierr);
ierr = PetscFVSetNumComponents(fvm, newDof);CHKERRQ(ierr);
ierr = PetscFVSetSpatialDimension(fvm, DIM);CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) fvm,PhysicsFields[f].fieldName);CHKERRQ(ierr);
/* FV is now structured with one field having all physics as components */
ierr = DMAddField(dm, NULL, (PetscObject) fvm);CHKERRQ(ierr);
// }
// else {
// PetscInt j;
//
// for (j = 0; j < newDof; j++) {
// char compName[256] = "Unknown";
//
// ierr = PetscSNPrintf(compName,sizeof(compName),"%s_%d",PhysicsFields[f].fieldName,j);CHKERRQ(ierr);
// ierr = PetscFVSetComponentName(fvm,dof+j,compName);CHKERRQ(ierr);
// }
// }
// dof += newDof;
}
}
// Compute the star state
ierr = DetermineStarState(&problem.setup, &problem.starState);CHKERRQ(ierr);
PetscDS prob;
ierr = DMCreateDS(dm);CHKERRQ(ierr);
ierr = DMGetDS(dm, &prob);CHKERRQ(ierr);
ierr = DMSetApplicationContext(dm, &problem);CHKERRQ(ierr);
//TODO: Add flux
ierr = PetscDSSetRiemannSolver(prob, 0,ComputeFluxRho);CHKERRQ(ierr);
ierr = PetscDSSetContext(prob, 0, &problem);CHKERRQ(ierr);
ierr = PetscDSSetRiemannSolver(prob, 1,ComputeFluxU);CHKERRQ(ierr);
ierr = PetscDSSetContext(prob, 1, &problem);CHKERRQ(ierr);
ierr = PetscDSSetRiemannSolver(prob, 2,ComputeFluxE);CHKERRQ(ierr);
ierr = PetscDSSetContext(prob, 2, &problem);CHKERRQ(ierr);
ierr = PetscDSSetFromOptions(prob);CHKERRQ(ierr);
//TODO: Apply boundary
// setup the solution vector, this olds everything
Vec X;
ierr = DMCreateGlobalVector(dm, &X);CHKERRQ(ierr);
ierr = PetscObjectSetName((PetscObject) X, "solution");CHKERRQ(ierr);
// ierr = DMTSSetBoundaryLocal(dm, DMPlexTSComputeBoundary, NULL);CHKERRQ(ierr);
// ierr = DMTSSetIFunctionLocal(dm, DMPlexTSComputeIFunctionFEM, NULL);CHKERRQ(ierr);
// ierr = DMTSSetIJacobianLocal(dm, DMPlexTSComputeIJacobianFEM, NULL);CHKERRQ(ierr);
// ierr = DMTSSetRHSFunctionLocal(dm, DMPlexTSComputeRHSFunctionFVM, NULL);CHKERRQ(ierr);//TODO: This is were we set the RHS function
const PetscInt idsLeft[]= {4};
ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "wall left", "Face Sets", 0, 0, NULL, (void (*)(void)) PhysicsBoundary_Euler_Left, NULL, 1, idsLeft, &problem);CHKERRQ(ierr);
const PetscInt idsRight[]= {2};
ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "wall right", "Face Sets", 0, 0, NULL, (void (*)(void)) PhysicsBoundary_Euler_Right, NULL, 1, idsRight, &problem);CHKERRQ(ierr);
const PetscInt mirror[]= {1, 3};
ierr = PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "mirrorWall", "Face Sets", 0, 0, NULL, (void (*)(void)) PhysicsBoundary_Euler_Mirror, NULL, 2, mirror, &problem);CHKERRQ(ierr);
// ierr = DMTSSetBoundaryLocal(dm, DMPlexTSComputeBoundary, NULL);CHKERRQ(ierr);
ierr = DMTSSetRHSFunctionLocal(dm, DMPlexTSComputeRHSFunctionFVM, NULL);CHKERRQ(ierr);//TODO: This is were we set the RHS function
ierr = TSSetMaxTime(ts,problem.setup.maxTime);CHKERRQ(ierr);
ierr = TSMonitorSet(ts, MonitorError, &problem, NULL);CHKERRQ(ierr);
ierr = TSSetTimeStep(ts, 0.0008);CHKERRQ(ierr);
ierr = TSSetFromOptions(ts);CHKERRQ(ierr);
ierr = TSSetPostStep(ts, ComputeTimeStep);CHKERRQ(ierr);
// set the initial conditions
PetscErrorCode (*func[3]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx) = {SetExactSolutionRho, SetExactSolutionRhoU, SetExactSolutionRhoE};
void* ctxs[3] ={&problem, &problem, &problem};
ierr = DMProjectFunction(dm,0.0,func,ctxs,INSERT_ALL_VALUES,X);CHKERRQ(ierr);
// PetscInt rank, size;
// MPI_Comm_rank(PetscObjectComm(dm), &rank);
// MPI_Comm_size(PetscObjectComm(dm), &size);
// for(int r =0; r < size; r++) {
// if(r == rank) {
// printf("Rank: %d\n", r);
// ierr = DMView(dm, PETSC_VIEWER_STDOUT_SELF);
// CHKERRQ(ierr);
//// ierr = DMViewFromOptions(dm, NULL, "-dm_view");
//// CHKERRQ(ierr);
// }
// MPI_Barrier(PetscObjectComm(dm));
// }
// TSSetMaxSteps(ts, 1);
ierr = TSSolve(ts,X);CHKERRQ(ierr);
// ierr = TSGetSolveTime(ts,&ftime);CHKERRQ(ierr);
// ierr = TSGetStepNumber(ts,&nsteps);
// CHKERRQ(ierr);
return PetscFinalize();
} | {
"alphanum_fraction": 0.6001327217,
"avg_line_length": 40.2543554007,
"ext": "c",
"hexsha": "e8a9a9e24efde6d1c0fcb1859ff732c1aca5b494",
"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": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "mmcgurn/MattFlowCases",
"max_forks_repo_path": "euler.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651",
"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": "mmcgurn/MattFlowCases",
"max_issues_repo_path": "euler.c",
"max_line_length": 229,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1ef7ca77b447a07fdd14d1e2e902abe3e281b651",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mmcgurn/MattFlowCases",
"max_stars_repo_path": "euler.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 10856,
"size": 34659
} |
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_multifit.h>
/* Fit
*
* y = X c
*
* where X is an n x p matrix of n observations for p variables.
*
* The solution includes a possible standard form Tikhonov regularization:
*
* c = (X^T X + lambda^2 I)^{-1} X^T y
*
* where lambda^2 is the Tikhonov regularization parameter.
*
* The function multifit_linear_svd() must first be called to
* compute the SVD decomposition of X
*
* Inputs: X - least squares matrix
* y - right hand side vector
* tol - singular value tolerance
* lambda - Tikhonov regularization parameter lambda;
* ignored if <= 0
* rank - (output) effective rank
* c - (output) model coefficient vector
* rnorm - (output) residual norm ||y - X c||
* snorm - (output) solution norm ||c||
* work - workspace
*
* Notes:
* 1) The dimensions of X must match work->n and work->p which are set
* by multifit_linear_svd()
* 2) On input:
* work->A contains U
* work->Q contains Q
* work->S contains singular values
* 3) If this function is called from gsl_multifit_wlinear(), then
* the input y points to work->t, which contains sqrt(W) y. Since
* work->t is also used as scratch workspace by this function, we
* do the necessary computations with y first to avoid problems.
* 4) When lambda <= 0, singular values are truncated when:
* s_j <= tol * s_0
*/
static int
multifit_linear_solve (const gsl_matrix * X,
const gsl_vector * y,
const double tol,
const double lambda,
size_t * rank,
gsl_vector * c,
double *rnorm,
double *snorm,
gsl_multifit_linear_workspace * work)
{
const size_t n = X->size1;
const size_t p = X->size2;
if (n != work->n || p != work->p)
{
GSL_ERROR("observation matrix does not match workspace", GSL_EBADLEN);
}
else if (n != y->size)
{
GSL_ERROR("number of observations in y does not match matrix",
GSL_EBADLEN);
}
else if (p != c->size)
{
GSL_ERROR ("number of parameters c does not match matrix",
GSL_EBADLEN);
}
else if (tol <= 0)
{
GSL_ERROR ("tolerance must be positive", GSL_EINVAL);
}
else
{
const double lambda_sq = lambda * lambda;
double rho_ls = 0.0; /* contribution to rnorm from OLS */
size_t j, p_eff;
/* these inputs are previously computed by multifit_linear_svd() */
gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p);
gsl_matrix_view Q = gsl_matrix_submatrix(work->Q, 0, 0, p, p);
gsl_vector_view S = gsl_vector_subvector(work->S, 0, p);
/* workspace */
gsl_matrix_view QSI = gsl_matrix_submatrix(work->QSI, 0, 0, p, p);
gsl_vector_view xt = gsl_vector_subvector(work->xt, 0, p);
gsl_vector_view D = gsl_vector_subvector(work->D, 0, p);
gsl_vector_view t = gsl_vector_subvector(work->t, 0, n);
/*
* Solve y = A c for c
* c = Q diag(s_i / (s_i^2 + lambda_i^2)) U^T y
*/
/* compute xt = U^T y */
gsl_blas_dgemv (CblasTrans, 1.0, &A.matrix, y, 0.0, &xt.vector);
if (n > p)
{
/*
* compute OLS residual norm = || y - U U^T y ||;
* for n = p, U U^T = I, so no need to calculate norm
*/
gsl_vector_memcpy(&t.vector, y);
gsl_blas_dgemv(CblasNoTrans, -1.0, &A.matrix, &xt.vector, 1.0, &t.vector);
rho_ls = gsl_blas_dnrm2(&t.vector);
}
if (lambda > 0.0)
{
/* xt <-- [ s(i) / (s(i)^2 + lambda^2) ] .* U^T y */
for (j = 0; j < p; ++j)
{
double sj = gsl_vector_get(&S.vector, j);
double f = (sj * sj) / (sj * sj + lambda_sq);
double *ptr = gsl_vector_ptr(&xt.vector, j);
/* use D as workspace for residual norm */
gsl_vector_set(&D.vector, j, (1.0 - f) * (*ptr));
*ptr *= sj / (sj*sj + lambda_sq);
}
/* compute regularized solution vector */
gsl_blas_dgemv (CblasNoTrans, 1.0, &Q.matrix, &xt.vector, 0.0, c);
/* compute solution norm */
*snorm = gsl_blas_dnrm2(c);
/* compute residual norm */
*rnorm = gsl_blas_dnrm2(&D.vector);
if (n > p)
{
/* add correction to residual norm (see eqs 6-7 of [1]) */
*rnorm = sqrt((*rnorm) * (*rnorm) + rho_ls * rho_ls);
}
/* reset D vector */
gsl_vector_set_all(&D.vector, 1.0);
}
else
{
/* Scale the matrix Q, QSI = Q S^{-1} */
gsl_matrix_memcpy (&QSI.matrix, &Q.matrix);
{
double s0 = gsl_vector_get (&S.vector, 0);
p_eff = 0;
for (j = 0; j < p; j++)
{
gsl_vector_view column = gsl_matrix_column (&QSI.matrix, j);
double sj = gsl_vector_get (&S.vector, j);
double alpha;
if (sj <= tol * s0)
{
alpha = 0.0;
}
else
{
alpha = 1.0 / sj;
p_eff++;
}
gsl_vector_scale (&column.vector, alpha);
}
*rank = p_eff;
}
gsl_blas_dgemv (CblasNoTrans, 1.0, &QSI.matrix, &xt.vector, 0.0, c);
/* Unscale the balancing factors */
gsl_vector_div (c, &D.vector);
*snorm = gsl_blas_dnrm2(c);
*rnorm = rho_ls;
}
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.5159680639,
"avg_line_length": 30.5177664975,
"ext": "c",
"hexsha": "f65b06660806a68281a11e46b1ccf18d9d19c3cf",
"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": "0fe8819a51e069c1e010cea0975c51a2a8794c42",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "agroimpacts/imager",
"max_forks_repo_path": "C/AFMapTSComposite/linear_common.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0fe8819a51e069c1e010cea0975c51a2a8794c42",
"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": "agroimpacts/imager",
"max_issues_repo_path": "C/AFMapTSComposite/linear_common.c",
"max_line_length": 84,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0fe8819a51e069c1e010cea0975c51a2a8794c42",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "agroimpacts/imager",
"max_stars_repo_path": "C/AFMapTSComposite/linear_common.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-01T18:48:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-01T18:48:12.000Z",
"num_tokens": 1629,
"size": 6012
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
#define NCols 5
#define Nrows 4
float A[] = { 8, 4, 7, 3, 5, 1, 1, 3, 2, 1, 2, 3, 2, 0, 1, 1 , 2, 3, 4, 1};
float x[] = { -1, 2, -1, 1, 2 };
float y[Nrows];
float alpha = 1.0, beta = 0.0;
char tbuf[1024];
int main() {
int i, j;
// Print original matrix
// y = Ax
cblas_sgemv(CblasRowMajor, CblasNoTrans, Nrows, NCols, alpha, A, NCols, x, 1, beta, y, 1);
// Print resulting vector
for (j = 0; j < Nrows; j++) {
printf(" %f\n", y[j]);
}
cblas_sgemv(CblasColMajor, CblasNoTrans, Nrows, NCols, alpha, A, Nrows, x, 1, beta, y, 1);
// Print resulting vector
for (j = 0; j < Nrows; j++) {
printf(" %f\n", y[j]);
}
return 0;
}
| {
"alphanum_fraction": 0.5318595579,
"avg_line_length": 20.2368421053,
"ext": "c",
"hexsha": "7a4c7dd38c5c4351502fb315a9e1c0b831b03141",
"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": "9fc19053aadd1782d0c064e6a2d8ff3d4236eca1",
"max_forks_repo_licenses": [
"Naumen",
"Condor-1.1",
"MS-PL"
],
"max_forks_repo_name": "ramcn/flappie-x-cpp",
"max_forks_repo_path": "3test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9fc19053aadd1782d0c064e6a2d8ff3d4236eca1",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Naumen",
"Condor-1.1",
"MS-PL"
],
"max_issues_repo_name": "ramcn/flappie-x-cpp",
"max_issues_repo_path": "3test.c",
"max_line_length": 94,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "9fc19053aadd1782d0c064e6a2d8ff3d4236eca1",
"max_stars_repo_licenses": [
"Naumen",
"Condor-1.1",
"MS-PL"
],
"max_stars_repo_name": "ramcn/flappie-x-cpp",
"max_stars_repo_path": "3test.c",
"max_stars_repo_stars_event_max_datetime": "2020-01-16T17:15:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-01-16T17:15:21.000Z",
"num_tokens": 323,
"size": 769
} |
/* specfunc/gsl_sf_log.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#ifndef __GSL_SF_LOG_H__
#define __GSL_SF_LOG_H__
#include <gsl/gsl_sf_result.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* Provide a logarithm function with GSL semantics.
*
* exceptions: GSL_EDOM
*/
int gsl_sf_log_e(const double x, gsl_sf_result * result);
double gsl_sf_log(const double x);
/* Log(|x|)
*
* exceptions: GSL_EDOM
*/
int gsl_sf_log_abs_e(const double x, gsl_sf_result * result);
double gsl_sf_log_abs(const double x);
/* Complex Logarithm
* exp(lnr + I theta) = zr + I zi
* Returns argument in [-pi,pi].
*
* exceptions: GSL_EDOM
*/
int gsl_sf_complex_log_e(const double zr, const double zi, gsl_sf_result * lnr, gsl_sf_result * theta);
/* Log(1 + x)
*
* exceptions: GSL_EDOM
*/
int gsl_sf_log_1plusx_e(const double x, gsl_sf_result * result);
double gsl_sf_log_1plusx(const double x);
/* Log(1 + x) - x
*
* exceptions: GSL_EDOM
*/
int gsl_sf_log_1plusx_mx_e(const double x, gsl_sf_result * result);
double gsl_sf_log_1plusx_mx(const double x);
#ifdef HAVE_INLINE
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
extern inline
int
gsl_sf_log_e(const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x <= 0.0) {
result->val = GSL_NAN;
result->err = GSL_NAN;
GSL_ERROR ("domain error", GSL_EDOM);
}
else {
result->val = log(x);
result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
}
extern inline
int
gsl_sf_log_abs_e(const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x == 0.0) {
result->val = GSL_NAN;
result->err = GSL_NAN;
GSL_ERROR ("domain error", GSL_EDOM);
}
else {
result->val = log(fabs(x));
result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_SF_LOG_H__ */
| {
"alphanum_fraction": 0.7024764562,
"avg_line_length": 22.936,
"ext": "h",
"hexsha": "2c90a6b608706d509097f9f6a29e63caf78b2b69",
"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": "extern/include/gsl/gsl_sf_log.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": "extern/include/gsl/gsl_sf_log.h",
"max_line_length": 103,
"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": "extern/include/gsl/gsl_sf_log.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 808,
"size": 2867
} |
/* C functions for running SampleTau from Cython*/
/*System includes*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <sys/stat.h>
/*GSL includes*/
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_blas.h>
/*User includes*/
//#include "c_sample_tau.h"
static gsl_rng *ptGSLRNG;
void c_initRNG()
{
//const gsl_rng_type * T;
gsl_rng_env_setup();
//T = gsl_rng_default;
ptGSLRNG = gsl_rng_alloc (gsl_rng_mt19937);
}
void c_setRNG(unsigned long int seed)
{
//printf("GSL RNG initialise %lu\n",seed);
gsl_rng_set (ptGSLRNG, seed);
}
void c_freeRNG()
{
gsl_rng_free (ptGSLRNG);
}
void normaliseLog4(double *adLogProb)
{
double dMax = adLogProb[0], dSum = 0.0;
int b = 0;
for(b = 1; b < 4; b++){
if(adLogProb[b] > dMax){
dMax = adLogProb[b];
}
}
for(b = 0; b < 4; b++){
adLogProb[b] = adLogProb[b] - dMax;
dSum += exp(adLogProb[b]);
}
for(b = 0; b < 4; b++){
adLogProb[b] = exp(adLogProb[b])/dSum;
//printf("b=%d,p=%f\n",b,adLogProb[b]);
}
return;
}
int sample4(double *adProb, double dU){
double adCProb[4];
adCProb[0] = adProb[0];
adCProb[1] = adProb[1] + adCProb[0];
adCProb[2] = adProb[2] + adCProb[1];
adCProb[3] = 1.0;
if(dU < adCProb[0]){
return 0;
}
else if(dU < adCProb[1])
return 1;
else if(dU < adCProb[2]){
return 2;
}
else{
return 3;
}
}
int c_sample_tau (long *anTau, double* adPi, double *adEta, long* anVariants, int nV, int nG, int nS)
{
int a = 0, b = 0;
int g = 0, h = 0, v = 0, s = 0, t = 0;
int nchange = 0;
double adPSB[nS][4];
double adPSBStore[nS][4];
double dLogProb[4];
int** anTauIndex = NULL;
double u = 0.0;
anTauIndex = (int **) malloc(nV*sizeof(int*));
if(!anTauIndex)
goto memoryError;
for(v = 0; v < nV; v++){
anTauIndex[v] = (int *) malloc(nG*sizeof(int));
if(!anTauIndex[v])
goto memoryError;
for(g = 0; g < nG; g++){
for(b = 0; b < 4; b++){
int vIndex = v*4*nG + 4*g + b;
if(anTau[vIndex] == 1){
anTauIndex[v][g] = b;
break;
}
}
//printf("%d,%d,%d\n",v,g,anTauIndex[v][g]);
}
}
//loop V positions
for(v = 0; v < nV; v++){
//loop G strains
for(g = 0; g < nG; g++){
//calc contribution from all other strains
for(s = 0; s < nS; s++){
for(b = 0; b < 4; b++){
adPSBStore[s][b] = 0.0;
for(h = 0; h < nG; h++){
if(h != g){
int pIndex = s*nG + h;
int eIndex = anTauIndex[v][h]*4 + b;
adPSBStore[s][b] += adEta[eIndex]*adPi[pIndex];
}
}
}
}
for(a = 0; a < 4; a++){
for(s = 0; s < nS; s++){
for(b = 0; b < 4; b++){
adPSB[s][b] = adPSBStore[s][b];
adPSB[s][b] += adEta[a*4 + b]*adPi[s*nG + g];
}
}
dLogProb[a] = 0.0;
for(s = 0; s < nS; s++){
for(b = 0; b < 4; b++){
int vIndex = v*4*nS + 4*s + b;
double temp = ((float) anVariants[vIndex])*log(adPSB[s][b]);
//printf("s=%d,b=%d,cont=%f\n",s,b,temp);
dLogProb[a] += temp;
}
}
}
// printf("u=%f,p1=%f,p2=%f,p3=%f,p4 =%f\n",u,dLogProb[0],dLogProb[1],dLogProb[2],dLogProb[3]);
normaliseLog4(dLogProb);
u = gsl_rng_uniform (ptGSLRNG);
// printf("u=%f,p1=%f,p2=%f,p3=%f,p4 =%f\n",u,dLogProb[0],dLogProb[1],dLogProb[2],dLogProb[3]);
t = sample4(dLogProb, u);
// printf("v=%d,g=%d,tnew=%d,told=%d\n",v,g,t,anTauIndex[v][g]);
if(t != anTauIndex[v][g]){
int vIndex = v*4*nG + 4*g;
anTau[vIndex + anTauIndex[v][g]] = 0;
anTau[vIndex + t] = 1;
nchange++;
anTauIndex[v][g] = t;
}
} //finish sampling strain g
}//finish sampling position v
//Free up tau indices
for(v = 0; v < nV; v++){
free(anTauIndex[v]);
}
free(anTauIndex);
return nchange;
memoryError:
fprintf(stderr, "Failed allocating memory in c_sample_tau\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
| {
"alphanum_fraction": 0.4329560714,
"avg_line_length": 25.3058252427,
"ext": "c",
"hexsha": "4676b84bf8b5628c9ddbc8378a395685f89532c6",
"lang": "C",
"max_forks_count": 34,
"max_forks_repo_forks_event_max_datetime": "2022-03-14T12:22:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-17T20:45:46.000Z",
"max_forks_repo_head_hexsha": "3f683e75830c4862b5f2c7577ef31b4cc86bdd61",
"max_forks_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_forks_repo_name": "MatthewWolff/DESMAN",
"max_forks_repo_path": "sampletau/c_sample_tau.c",
"max_issues_count": 39,
"max_issues_repo_head_hexsha": "3f683e75830c4862b5f2c7577ef31b4cc86bdd61",
"max_issues_repo_issues_event_max_datetime": "2022-03-21T03:01:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-02T13:32:10.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_issues_repo_name": "MatthewWolff/DESMAN",
"max_issues_repo_path": "sampletau/c_sample_tau.c",
"max_line_length": 106,
"max_stars_count": 72,
"max_stars_repo_head_hexsha": "3f683e75830c4862b5f2c7577ef31b4cc86bdd61",
"max_stars_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_stars_repo_name": "MatthewWolff/DESMAN",
"max_stars_repo_path": "sampletau/c_sample_tau.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-20T08:56:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-09-08T10:43:38.000Z",
"num_tokens": 1605,
"size": 5213
} |
// $Id: pfc_libraries.h 37984 2018-10-27 15:50:30Z p20068 $
// $URL: https://svn01.fh-hagenberg.at/bin/cepheiden/vocational/teaching/ESD/SPS3/2018-WS/ILV/src/Snippets/bitmap-gsl/pfc_libraries.h $
// $Revision: 37984 $
// $Date: 2018-10-27 17:50:30 +0200 (Sa., 27 Okt 2018) $
// $Author: p20068 $
//
// Creator: Peter Kulczycki (peter.kulczycki<AT>fh-hagenberg.at)
// Creation Date:
// Copyright: (c) 2018 Peter Kulczycki (peter.kulczycki<AT>fh-hagenberg.at)
//
// License: This document contains proprietary information belonging to
// University of Applied Sciences Upper Austria, Campus
// Hagenberg. It is distributed under the Boost Software License,
// Version 1.0 (see http://www.boost.org/LICENSE_1_0.txt).
//
// Annotation: This file is part of the code snippets handed out during one
// of my HPC lessons held at the University of Applied Sciences
// Upper Austria, Campus Hagenberg.
#pragma once
#include "./pfc_macros.h"
// -------------------------------------------------------------------------------------------------
#if defined PFC_DETECTED_COMPILER_NVCC
#define PFC_DO_NOT_USE_BOOST_UNITS
#define PFC_DO_NOT_USE_GSL
#define PFC_DO_NOT_USE_VLD
#define PFC_DO_NOT_USE_WINDOWS
#endif
// -------------------------------------------------------------------------------------------------
#undef PFC_HAVE_VLD
#undef PFC_VLD_INCLUDED
#if __has_include (<vld.h>) && !defined PFC_DO_NOT_USE_VLD // Visual Leak Detector (https://kinddragon.github.io/vld)
#include <vld.h>
#define PFC_HAVE_VLD
#define PFC_VLD_INCLUDED
#pragma message ("PFC: using 'Visual Leak Detector'")
#else
#pragma message ("PFC: not using 'Visual Leak Detector'")
#endif
// -------------------------------------------------------------------------------------------------
#undef PFC_HAVE_GSL
#undef PFC_GSL_INCLUDED
#if __has_include (<gsl/gsl>) && !defined PFC_DO_NOT_USE_GSL // Guideline Support Library (https://github.com/Microsoft/GSL)
#include <gsl/gsl>
#define PFC_HAVE_GSL
#define PFC_GSL_INCLUDED
#pragma message ("PFC: using 'Guideline Support Library'")
#else
#pragma message ("PFC: not using 'Guideline Support Library'")
#endif
// -------------------------------------------------------------------------------------------------
#undef PFC_HAVE_BOOST_UNITS
#undef PFC_BOOST_UNITS_INCLUDED
#if __has_include (<boost/units/io.hpp>)
#if __has_include (<boost/units/systems/si/length.hpp>)
#if __has_include (<boost/units/systems/si/prefixes.hpp>) && !defined PFC_DO_NOT_USE_BOOST_UNITS
#include <boost/units/io.hpp> // http://www.boost.org
#include <boost/units/systems/si/length.hpp> // https://sourceforge.net/projects/boost/files/boost-binaries
#include <boost/units/systems/si/prefixes.hpp> //
#define PFC_HAVE_BOOST_UNITS
#define PFC_BOOST_UNITS_INCLUDED
#pragma message ("PFC: using 'Boost.Units'")
#else
#pragma message ("PFC: not using 'Boost.Units'")
#endif
#endif
#endif
// -------------------------------------------------------------------------------------------------
#undef PFC_HAVE_WINDOWS
#undef PFC_WINDOWS_INCLUDED
#if __has_include (<windows.h>) && !defined PFC_DO_NOT_USE_WINDOWS
#undef NOMINMAX
#define NOMINMAX
#undef STRICT
#define STRICT
#undef VC_EXTRALEAN
#define VC_EXTRALEAN
#undef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define PFC_HAVE_WINDOWS
#define PFC_WINDOWS_INCLUDED
#pragma message ("PFC: using 'windows.h'")
#else
#pragma message ("PFC: not using 'windows.h'")
#endif
| {
"alphanum_fraction": 0.6067204301,
"avg_line_length": 32.6315789474,
"ext": "h",
"hexsha": "a6dd381d444d64d59c1cc0906a7416646608e651",
"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": "86abf791cd1df1e51ed7790e3f9c52fbce7990e2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MMayr96/MandelbrotCuda",
"max_forks_repo_path": "FractalCudaVersions/pfc/pfc_libraries.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "86abf791cd1df1e51ed7790e3f9c52fbce7990e2",
"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": "MMayr96/MandelbrotCuda",
"max_issues_repo_path": "FractalCudaVersions/pfc/pfc_libraries.h",
"max_line_length": 144,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "86abf791cd1df1e51ed7790e3f9c52fbce7990e2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MMayr96/MandelbrotCuda",
"max_stars_repo_path": "FractalCudaVersions/pfc/pfc_libraries.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 943,
"size": 3720
} |
/* ode-initval/rk2imp.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Runge-Kutta 2, Gaussian implicit */
/* Author: G. Jungman
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv.h>
#include "odeiv_util.h"
typedef struct
{
double *knu;
double *ytmp;
}
rk2imp_state_t;
static void *
rk2imp_alloc (size_t dim)
{
rk2imp_state_t *state = (rk2imp_state_t *) malloc (sizeof (rk2imp_state_t));
if (state == 0)
{
GSL_ERROR_NULL ("failed to allocate space for rk2imp_state",
GSL_ENOMEM);
}
state->knu = (double *) malloc (dim * sizeof (double));
if (state->knu == 0)
{
free (state);
GSL_ERROR_NULL ("failed to allocate space for knu", GSL_ENOMEM);
}
state->ytmp = (double *) malloc (dim * sizeof (double));
if (state->ytmp == 0)
{
free (state->knu);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM);
}
return state;
}
static int
rk2imp_apply (void *vstate,
size_t dim,
double t,
double h,
double y[],
double yerr[],
const double dydt_in[],
double dydt_out[], const gsl_odeiv_system * sys)
{
rk2imp_state_t *state = (rk2imp_state_t *) vstate;
const int iter_steps = 3;
int status = 0;
int nu;
size_t i;
double *const knu = state->knu;
double *const ytmp = state->ytmp;
/* initialization step */
if (dydt_in != NULL)
{
DBL_MEMCPY (knu, dydt_in, dim);
}
else
{
int s = GSL_ODEIV_FN_EVAL (sys, t, y, knu);
GSL_STATUS_UPDATE (&status, s);
}
/* iterative solution */
for (nu = 0; nu < iter_steps; nu++)
{
for (i = 0; i < dim; i++)
{
ytmp[i] = y[i] + 0.5 * h * knu[i];
}
{
int s = GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h, ytmp, knu);
GSL_STATUS_UPDATE (&status, s);
}
}
/* assignment */
for (i = 0; i < dim; i++)
{
y[i] += h * knu[i];
yerr[i] = h * h * knu[i];
if (dydt_out != NULL)
dydt_out[i] = knu[i];
}
return status;
}
static int
rk2imp_reset (void *vstate, size_t dim)
{
rk2imp_state_t *state = (rk2imp_state_t *) vstate;
DBL_ZERO_MEMSET (state->knu, dim);
DBL_ZERO_MEMSET (state->ytmp, dim);
return GSL_SUCCESS;
}
static unsigned int
rk2imp_order (void *vstate)
{
rk2imp_state_t *state = (rk2imp_state_t *) vstate;
state = 0; /* prevent warnings about unused parameters */
return 2;
}
static void
rk2imp_free (void *vstate)
{
rk2imp_state_t *state = (rk2imp_state_t *) vstate;
free (state->knu);
free (state->ytmp);
free (state);
}
static const gsl_odeiv_step_type rk2imp_type = { "rk2imp", /* name */
1, /* can use dydt_in */
0, /* gives exact dydt_out */
&rk2imp_alloc,
&rk2imp_apply,
&rk2imp_reset,
&rk2imp_order,
&rk2imp_free
};
const gsl_odeiv_step_type *gsl_odeiv_step_rk2imp = &rk2imp_type;
| {
"alphanum_fraction": 0.6092645904,
"avg_line_length": 22.744047619,
"ext": "c",
"hexsha": "f27a76354acda10e6ced2888955068dd8d04a218",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z",
"max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pvnuffel/test_repos",
"max_forks_repo_path": "gsl_subset/ode-initval/rk2imp.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pvnuffel/test_repos",
"max_issues_repo_path": "gsl_subset/ode-initval/rk2imp.c",
"max_line_length": 78,
"max_stars_count": 30,
"max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pvnuffel/test_repos",
"max_stars_repo_path": "gsl_subset/ode-initval/rk2imp.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z",
"num_tokens": 1147,
"size": 3821
} |
#ifndef PyGSL_ERROR_HELPER_H
#define PyGSL_ERROR_HELPER_H 1
#include <pygsl/intern.h>
#include <pygsl/utils.h>
#include <gsl/gsl_errno.h>
#include <pygsl/errorno.h>
/*
* 22 Sep. 2009 Pierre Schnizer
* Uncomment only if trouble with the gsl error handler (e.g. when using
* Python with threading support (typical ufuncs). At the time of this writing
* the error handler would call python to find the approbriate python exception
*
* So I used to uncomment the macro as well as the function to ensure that
* gsl_error was not called any more within the pygsl wrappper
*/
/*
#undef GSL_ERROR
#undef GSL_ERROR_VAL
#undef GSL_ERROR_NULL
#define gsl_error()
*/
/*
* handle gsl error flags.
*
* If a flag arrives check if there was already a python error. If so leave it alone.
* We cannot return two exceptions.
*
* Otherwise:
* Should I put an exception up? E.g. some function not conforming to GSL
* Convention returning a flag, instead of calling gsl_error?
* Currently I follow that idea. But I have no more information about the reason
* than the flag.
*
* Return:
* GSL_SUCCESS ... No errornous call
* GSL_FAILURE ... errornous call
*
* If you need to return the flag e.g. "int gsl_odeiv_iterate( ... " use
* PyGSL_error_flag_to_pyint instead!
*
*/
PyGSL_API_EXTERN int
PyGSL_error_flag(long flag);
/*
* Handles gsl_error flags.
* It differs from the above that it returns the integer.
*
* Negative values mean something like go one with the iteration. These are
* converted to an python integer. Positive values flag a problem. These are
* converted to python exceptions.
*/
PyGSL_API_EXTERN PyObject *
PyGSL_error_flag_to_pyint(long flag);
/*
* Add a Python trace back frame to the python interpreter.
* Input :
* module ... the module. Pass NULL if not known.
* filename ... The filename to list in the stack frame. Pass NULL if not
* known.
* funcname ... The function name to list in the stack frame. Pass NULL if
* not known.
* lineno ... The Linenumber where the error occurred.
*/
PyGSL_API_EXTERN void
PyGSL_add_traceback(PyObject *module, const char *filename, const char *funcname, int lineno);
PyGSL_API_EXTERN int
PyGSL_warning(const char *, const char*, int, int);
#ifndef _PyGSL_API_MODULE
/* Section for modules importing the functions */
#define PyGSL_error_flag (*(int (*)(long)) PyGSL_API[PyGSL_error_flag_NUM])
#define PyGSL_error_flag_to_pyint (*(PyObject * (*)(long)) PyGSL_API[PyGSL_error_flag_to_pyint_NUM])
#define PyGSL_add_traceback (*(void (*)(PyObject *, const char *, const char *, int)) PyGSL_API[PyGSL_add_traceback_NUM])
#define PyGSL_warning (*(int (*)(const char *, const char *, int, int)) PyGSL_API[PyGSL_warning_NUM])
#endif /* _PyGSL_API_MODULE */
#define PyGSL_ERROR_FLAG(flag) \
(((long) flag == GSL_SUCCESS) && (!PyErr_Occurred())) ? GSL_SUCCESS : \
PyGSL_error_flag((long) (flag))
#define PyGSL_ERROR_FLAG_TO_PYINT(flag) \
(((long) flag <= 0) && (!PyErr_Occurred())) ? PyInt_FromLong((long) flag) : \
PyGSL_error_flag_to_pyint((long) (flag))
#endif /* PyGSL_ERROR_HELPER_H */
| {
"alphanum_fraction": 0.6609279253,
"avg_line_length": 36.8494623656,
"ext": "h",
"hexsha": "cf6f0fe2d37451ce1d933530a8ce616def0c3a9f",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/Include/pygsl/error_helpers.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/Include/pygsl/error_helpers.h",
"max_line_length": 134,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/Include/pygsl/error_helpers.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 829,
"size": 3427
} |
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#pragma once
#include <gsl/gsl>
namespace sd {
void init ();
int lsdir (gsl::czstring path);
} // namespace sd | {
"alphanum_fraction": 0.2102874433,
"avg_line_length": 38.8823529412,
"ext": "h",
"hexsha": "7960ea31f0387ee64f4ea4d0014944f8f74fd24c",
"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": "f7d8dc96ab859903e12c70c4a54cbbf51804e15f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "iwasz/zephyr-grbl-plotter",
"max_forks_repo_path": "src/sdCard.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f7d8dc96ab859903e12c70c4a54cbbf51804e15f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "iwasz/zephyr-grbl-plotter",
"max_issues_repo_path": "src/sdCard.h",
"max_line_length": 78,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "f7d8dc96ab859903e12c70c4a54cbbf51804e15f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "iwasz/zephyr-grbl-plotter",
"max_stars_repo_path": "src/sdCard.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-25T07:50:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-02T17:33:33.000Z",
"num_tokens": 78,
"size": 661
} |
#ifndef SPN_H
#define SPN_H
#include "init_cy_fde.h"
#include "matrix_util.h"
//#include <cblas.h>
typedef struct SemiCircularNet{
int p;
int d;
DCOMPLEX *Pa_h_A; // d
DCOMPLEX *Pa_omega; // 2*d
DCOMPLEX F_A[2]; //
DCOMPLEX h_A[2]; //
DCOMPLEX TG_Ge_sc[4] ; //
DCOMPLEX DG_sc[4]; //
DCOMPLEX temp_T_eta[4]; //
DCOMPLEX Dh_sc[4]; //
DCOMPLEX Psigma_G_sc[2]; //
DCOMPLEX Psigma_h_sc[2] ;//
DCOMPLEX DG_A[4]; //
DCOMPLEX Dh_A[4]; //
DCOMPLEX S[4]; //
DCOMPLEX temp_mat[4]; //
DCOMPLEX Psigma_omega[2];//
}SCN;
void
SCN_construct(SCN* self, int p , int d);
void
SCN_init(SCN* self);
void
SCN_init_forward(SCN* self);
void
SCN_init_backward(SCN* self);
void
SCN_destroy(SCN* self);
int
SCN_cauchy(SCN* self);
void
SCN_grad(SCN* self, int p, int d, double *a, double sigma, \
DCOMPLEX z,DCOMPLEX *G, DCOMPLEX *omega, DCOMPLEX *omega_sc,\
DCOMPLEX *o_grad_a, DCOMPLEX *o_grad_sigma);
/** Compute Cauchy transform of SemiCircular( returns total iterations)
* @param Z : input matrix
* @param o_G : out_put Cauchy transform
*
*/
int
cauchy_sc( int p, int d, double sigma, DCOMPLEX* Z, \
int max_iter, double thres,\
DCOMPLEX* o_G);
/** Compute Cauchy transform of Signal-Plus-Noise model( returns total iterations)
* @param Z : input matrix
* @param o_G_sc : out_put Cauchy transform
*
*/
int
cauchy_spn(int p_dim, int dim, double* a, double sigma,\
DCOMPLEX* B,\
int max_iter,double thres, \
DCOMPLEX* o_G_sc, DCOMPLEX* o_omega, DCOMPLEX* o_omega_sc);
/*
Only for debug
*/
void
grad_cauchy_spn(int p, int d, double *a, double sigma, \
DCOMPLEX z, DCOMPLEX *G, DCOMPLEX *omega, DCOMPLEX *omega_sc,\
DCOMPLEX *o_grad_a, DCOMPLEX *o_grad_sigma);
// transpose of derivation of Ge
// G : 2
// o_DGe: 2 x 2
void TG_Ge( const int p, const int d, const double sigma, \
const DCOMPLEX *G, DCOMPLEX *o_DGe);
// transpose of derivation of cauchy_sc
// G: 2
// DG: 2 x 2
void DG(const DCOMPLEX *G, const DCOMPLEX *DGe, DCOMPLEX *o_DG);
void T_eta(const int p, const int d, DCOMPLEX *o_T_eta);
void Dh(const DCOMPLEX* DG, const DCOMPLEX *T_eta, const double sigma,DCOMPLEX *o_Dh);
void Psigma_G(const int p,const int d, const double sigma, const DCOMPLEX *G, const DCOMPLEX *DGe, DCOMPLEX *o_Psigma_G);
void Psigma_h(const int p, const int d, const double sigma, const DCOMPLEX * G, const DCOMPLEX* P_sigma_G, const DCOMPLEX *T_eta,\
DCOMPLEX* o_Psigma_h);
//// Descrete
void des_DG( int p, int d, const double *a, const DCOMPLEX *W,DCOMPLEX*o_DG);
void des_Dh( const DCOMPLEX *DG, const DCOMPLEX *F,DCOMPLEX*o_Dh);
void des_Pa_h( int p, int d, const double *a, const DCOMPLEX *W, DCOMPLEX *F, DCOMPLEX *Pa_h);
/** compute gradient and loss of likelihood
* return total number of forward_iter
*
*/
int
grad_loss_cauchy_spn( int p, int d, double *a, double sigma, double scale, \
int batch_size, double *batch, \
double *o_grad_a, double *o_grad_sigma, double *o_loss);
#endif
| {
"alphanum_fraction": 0.6761252446,
"avg_line_length": 21.4405594406,
"ext": "h",
"hexsha": "68709f77efbe117082f34140305f3666f1a32704",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ThayaFluss/cnl",
"max_forks_repo_path": "src/cy_fde/spn.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ThayaFluss/cnl",
"max_issues_repo_path": "src/cy_fde/spn.h",
"max_line_length": 130,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ThayaFluss/cnl",
"max_stars_repo_path": "src/cy_fde/spn.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1051,
"size": 3066
} |
/* multifit/lmniel.c
*
* Copyright (C) 2014 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_multifit_nlin.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
#define SCALE 0
/*
* This module contains an implementation of the Levenberg-Marquardt
* algorithm for nonlinear optimization problems. This implementation
* closely follows the following works:
*
* [1] H. B. Nielsen, K. Madsen, Introduction to Optimization and
* Data Fitting, Informatics and Mathematical Modeling,
* Technical University of Denmark (DTU), 2010.
*/
typedef struct
{
gsl_matrix *A; /* J^T J */
gsl_matrix *A_copy; /* copy of J^T J */
gsl_matrix *J; /* Jacobian J(x) */
gsl_vector *diag; /* D = diag(J^T J) */
gsl_vector *rhs; /* rhs vector = -g = -J^T f */
gsl_vector *x_trial; /* trial parameter vector */
gsl_vector *f_trial; /* trial function vector */
gsl_vector *work; /* workspace length p */
long nu; /* nu */
double mu; /* LM damping parameter mu */
double tau; /* initial scale factor for mu */
} lmniel_state_t;
#include "lmmisc.c"
#define LM_ONE_THIRD (0.333333333333333)
static int lmniel_alloc (void *vstate, const size_t n, const size_t p);
static void lmniel_free(void *vstate);
static int lmniel_set(void *vstate, const gsl_vector * swts,
gsl_multifit_function_fdf *fdf,
gsl_vector *x, gsl_vector *f, gsl_vector *dx);
static int lmniel_iterate(void *vstate, const gsl_vector *swts,
gsl_multifit_function_fdf *fdf,
gsl_vector *x, gsl_vector *f, gsl_vector *dx);
static int
lmniel_alloc (void *vstate, const size_t n, const size_t p)
{
lmniel_state_t *state = (lmniel_state_t *) vstate;
state->A = gsl_matrix_alloc(p, p);
if (state->A == NULL)
{
GSL_ERROR ("failed to allocate space for A", GSL_ENOMEM);
}
state->J = gsl_matrix_alloc(n, p);
if (state->J == NULL)
{
GSL_ERROR ("failed to allocate space for J", GSL_ENOMEM);
}
state->diag = gsl_vector_alloc(p);
if (state->diag == NULL)
{
GSL_ERROR ("failed to allocate space for diag", GSL_ENOMEM);
}
state->rhs = gsl_vector_alloc(p);
if (state->rhs == NULL)
{
GSL_ERROR ("failed to allocate space for rhs", GSL_ENOMEM);
}
state->work = gsl_vector_alloc(p);
if (state->work == NULL)
{
GSL_ERROR ("failed to allocate space for work", GSL_ENOMEM);
}
state->A_copy = gsl_matrix_alloc(p, p);
if (state->A_copy == NULL)
{
GSL_ERROR ("failed to allocate space for A_copy", GSL_ENOMEM);
}
state->x_trial = gsl_vector_alloc(p);
if (state->x_trial == NULL)
{
GSL_ERROR ("failed to allocate space for x_trial", GSL_ENOMEM);
}
state->f_trial = gsl_vector_alloc(n);
if (state->f_trial == NULL)
{
GSL_ERROR ("failed to allocate space for f_trial", GSL_ENOMEM);
}
state->tau = 1.0e-3;
return GSL_SUCCESS;
} /* lmniel_alloc() */
static void
lmniel_free(void *vstate)
{
lmniel_state_t *state = (lmniel_state_t *) vstate;
if (state->A)
gsl_matrix_free(state->A);
if (state->J)
gsl_matrix_free(state->J);
if (state->diag)
gsl_vector_free(state->diag);
if (state->rhs)
gsl_vector_free(state->rhs);
if (state->work)
gsl_vector_free(state->work);
if (state->A_copy)
gsl_matrix_free(state->A_copy);
if (state->x_trial)
gsl_vector_free(state->x_trial);
if (state->f_trial)
gsl_vector_free(state->f_trial);
} /* lmniel_free() */
static int
lmniel_set(void *vstate, const gsl_vector *swts,
gsl_multifit_function_fdf *fdf, gsl_vector *x,
gsl_vector *f, gsl_vector *dx)
{
int status;
lmniel_state_t *state = (lmniel_state_t *) vstate;
const size_t p = x->size;
size_t i;
/* initialize counters for function and Jacobian evaluations */
fdf->nevalf = 0;
fdf->nevaldf = 0;
/* evaluate function and Jacobian at x and apply weight transform */
status = gsl_multifit_eval_wf(fdf, x, swts, f);
if (status)
return status;
if (fdf->df)
status = gsl_multifit_eval_wdf(fdf, x, swts, state->J);
else
status = gsl_multifit_fdfsolver_dif_df(x, swts, fdf, f, state->J);
if (status)
return status;
/* compute rhs = -J^T f */
gsl_blas_dgemv(CblasTrans, -1.0, state->J, f, 0.0, state->rhs);
#if SCALE
gsl_vector_set_zero(state->diag);
#else
gsl_vector_set_all(state->diag, 1.0);
#endif
/* set default parameters */
state->nu = 2;
#if SCALE
state->mu = state->tau;
#else
/* compute mu_0 = tau * max(diag(J^T J)) */
state->mu = -1.0;
for (i = 0; i < p; ++i)
{
gsl_vector_view c = gsl_matrix_column(state->J, i);
double result; /* (J^T J)_{ii} */
gsl_blas_ddot(&c.vector, &c.vector, &result);
state->mu = GSL_MAX(state->mu, result);
}
state->mu *= state->tau;
#endif
return GSL_SUCCESS;
} /* lmniel_set() */
/*
lmniel_iterate()
This function performs 1 iteration of the LM algorithm 6.18
from [1]. The algorithm is slightly modified to loop until we
find an acceptable step dx, in order to guarantee that each
function call contains a new input vector x.
Args: vstate - lm workspace
swts - data weights (NULL if unweighted)
fdf - function and Jacobian pointers
x - on input, current parameter vector
on output, new parameter vector x + dx
f - on input, f(x)
on output, f(x + dx)
dx - (output only) parameter step vector
Notes:
1) On input, the following must be initialized in state:
nu, mu, rhs, J
2) On output, the following are updated with the current iterates:
nu, mu, rhs, J
rhs needs to be set on each output, so that lmniel_gradient supplies
the correct g = J^T f
*/
static int
lmniel_iterate(void *vstate, const gsl_vector *swts,
gsl_multifit_function_fdf *fdf, gsl_vector *x,
gsl_vector *f, gsl_vector *dx)
{
int status;
lmniel_state_t *state = (lmniel_state_t *) vstate;
gsl_matrix *J = state->J; /* Jacobian J(x) */
gsl_matrix *A = state->A; /* J^T J */
gsl_vector *rhs = state->rhs; /* -g = -J^T f */
gsl_vector *x_trial = state->x_trial; /* trial x + dx */
gsl_vector *f_trial = state->f_trial; /* trial f(x + dx) */
gsl_vector *diag = state->diag; /* diag(D) */
double dF; /* F(x) - F(x + dx) */
double dL; /* L(0) - L(dx) */
int foundstep = 0; /* found step dx */
/* compute A = J^T J */
status = gsl_blas_dsyrk(CblasLower, CblasTrans, 1.0, J, 0.0, A);
if (status)
return status;
/* copy lower triangle to upper */
gsl_matrix_transpose_tricpy('L', 0, A, A);
#if SCALE
lmniel_update_diag(J, diag);
#endif
/* loop until we find an acceptable step dx */
while (!foundstep)
{
/* solve (A + mu*I) dx = g */
status = lmniel_calc_dx(state->mu, A, rhs, dx, state);
if (status)
return status;
/* compute x_trial = x + dx */
lmniel_trial_step(x, dx, x_trial);
/* compute f(x + dx) */
status = gsl_multifit_eval_wf(fdf, x_trial, swts, f_trial);
if (status)
return status;
/* compute dF = F(x) - F(x + dx) */
dF = lmniel_calc_dF(f, f_trial);
/* compute dL = L(0) - L(dx) = dx^T (mu*dx - g) */
dL = lmniel_calc_dL(state->mu, diag, dx, rhs);
/* check that rho = dF/dL > 0 */
if ((dL > 0.0) && (dF >= 0.0))
{
/* reduction in error, step acceptable */
double tmp;
/* update LM parameter mu */
tmp = 2.0 * (dF / dL) - 1.0;
tmp = 1.0 - tmp*tmp*tmp;
state->mu *= GSL_MAX(LM_ONE_THIRD, tmp);
state->nu = 2;
/* compute J <- J(x + dx) */
if (fdf->df)
status = gsl_multifit_eval_wdf(fdf, x_trial, swts, J);
else
status = gsl_multifit_fdfsolver_dif_df(x_trial, swts, fdf, f_trial, J);
if (status)
return status;
/* update x <- x + dx */
gsl_vector_memcpy(x, x_trial);
/* update f <- f(x + dx) */
gsl_vector_memcpy(f, f_trial);
/* compute new rhs = -J^T f */
gsl_blas_dgemv(CblasTrans, -1.0, J, f, 0.0, rhs);
foundstep = 1;
}
else
{
long nu2;
/* step did not reduce error, reject step */
state->mu *= (double) state->nu;
nu2 = state->nu << 1; /* 2*nu */
if (nu2 <= state->nu)
{
gsl_vector_view d = gsl_matrix_diagonal(A);
/*
* nu has wrapped around / overflown, reset mu and nu
* to original values and break to force another iteration
*/
/*GSL_ERROR("nu parameter has overflown", GSL_EOVRFLW);*/
state->nu = 2;
state->mu = state->tau * gsl_vector_max(&d.vector);
break;
}
state->nu = nu2;
}
} /* while (!foundstep) */
return GSL_SUCCESS;
} /* lmniel_iterate() */
static int
lmniel_gradient(void *vstate, gsl_vector * g)
{
lmniel_state_t *state = (lmniel_state_t *) vstate;
gsl_vector_memcpy(g, state->rhs);
gsl_vector_scale(g, -1.0);
return GSL_SUCCESS;
}
static int
lmniel_jac(void *vstate, gsl_matrix * J)
{
lmniel_state_t *state = (lmniel_state_t *) vstate;
int s = gsl_matrix_memcpy(J, state->J);
return s;
}
static const gsl_multifit_fdfsolver_type lmniel_type =
{
"lmniel",
sizeof(lmniel_state_t),
&lmniel_alloc,
&lmniel_set,
&lmniel_iterate,
&lmniel_gradient,
&lmniel_jac,
&lmniel_free
};
const gsl_multifit_fdfsolver_type *gsl_multifit_fdfsolver_lmniel = &lmniel_type;
| {
"alphanum_fraction": 0.6025415082,
"avg_line_length": 28.1488250653,
"ext": "c",
"hexsha": "1c3f7891f745e68609cdb2e109a4663fad04ba41",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/lmniel.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/lmniel.c",
"max_line_length": 83,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017",
"max_stars_repo_path": "gsl-2.4/multifit/lmniel.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z",
"num_tokens": 3099,
"size": 10781
} |
/* err/test_results.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_VPRINTF
#ifdef STDC_HEADERS
#include <stdarg.h>
#else
#include <varargs.h>
#endif
#endif
#include <gsl/gsl_test.h>
static unsigned int tests = 0;
static unsigned int passed = 0;
static unsigned int failed = 0;
static unsigned int verbose = 1;
void
gsl_test (int status, const char *test_description,...)
{
tests++;
if (status == 0)
{
passed++;
if (verbose)
printf ("PASS: ");
}
else
{
failed++;
if (verbose)
printf ("FAIL: ");
}
if (verbose)
{
#ifdef HAVE_VPRINTF
va_list ap;
#ifdef STDC_HEADERS
va_start (ap, test_description);
#else
va_start (ap);
#endif
vprintf (test_description, ap);
va_end (ap);
#endif
printf("\n");
fflush (stdout);
}
}
void
gsl_test_rel (double result, double expected, double relative_error,
const char *test_description,...)
{
int status ;
if (expected != 0 )
{
status = (fabs(result-expected)/fabs(expected) > relative_error) ;
}
else
{
status = (fabs(result) > relative_error) ;
}
tests++;
if (status == 0)
{
passed++;
if (verbose)
printf ("PASS: ");
}
else
{
failed++;
if (verbose)
printf ("FAIL: ");
}
if (verbose)
{
#ifdef HAVE_VPRINTF
va_list ap;
#ifdef STDC_HEADERS
va_start (ap, test_description);
#else
va_start (ap);
#endif
vprintf (test_description, ap);
va_end (ap);
#endif
if (status == 0)
{
if (strlen(test_description) < 45)
{
printf(" (%g observed vs %g expected)", result, expected) ;
}
else
{
printf(" (%g obs vs %g exp)", result, expected) ;
}
}
else
{
printf(" (%.18g observed vs %.18g expected)", result, expected) ;
}
printf ("\n") ;
fflush (stdout);
}
}
void
gsl_test_abs (double result, double expected, double absolute_error,
const char *test_description,...)
{
int status ;
status = fabs(result-expected) > absolute_error ;
tests++;
if (status == 0)
{
passed++;
if (verbose)
printf ("PASS: ");
}
else
{
failed++;
if (verbose)
printf ("FAIL: ");
}
if (verbose)
{
#ifdef HAVE_VPRINTF
va_list ap;
#ifdef STDC_HEADERS
va_start (ap, test_description);
#else
va_start (ap);
#endif
vprintf (test_description, ap);
va_end (ap);
#endif
if (status == 0)
{
if (strlen(test_description) < 45)
{
printf(" (%g observed vs %g expected)", result, expected) ;
}
else
{
printf(" (%g obs vs %g exp)", result, expected) ;
}
}
else
{
printf(" (%.18g observed vs %.18g expected)", result, expected) ;
}
printf ("\n") ;
fflush (stdout);
}
}
void
gsl_test_factor (double result, double expected, double factor,
const char *test_description,...)
{
int status;
if (result == expected)
{
status = 0;
}
else if (expected == 0.0)
{
status = (result > expected || result < expected);
}
else
{
double u = result / expected;
status = (u > factor || u < 1.0 / factor) ;
}
tests++;
if (status == 0)
{
passed++;
if (verbose)
printf ("PASS: ");
}
else
{
failed++;
if (verbose)
printf ("FAIL: ");
}
if (verbose)
{
#ifdef HAVE_VPRINTF
va_list ap;
#ifdef STDC_HEADERS
va_start (ap, test_description);
#else
va_start (ap);
#endif
vprintf (test_description, ap);
va_end (ap);
#endif
if (status == 0)
{
if (strlen(test_description) < 45)
{
printf(" (%g observed vs %g expected)", result, expected) ;
}
else
{
printf(" (%g obs vs %g exp)", result, expected) ;
}
}
else
{
printf(" (%.18g observed vs %.18g expected)", result, expected) ;
}
printf ("\n") ;
fflush (stdout);
}
}
void
gsl_test_int (int result, int expected, const char *test_description,...)
{
int status = (result != expected) ;
tests++;
if (status == 0)
{
passed++;
if (verbose)
printf ("PASS: ");
}
else
{
failed++;
if (verbose)
printf ("FAIL: ");
}
if (verbose)
{
#ifdef HAVE_VPRINTF
va_list ap;
#ifdef STDC_HEADERS
va_start (ap, test_description);
#else
va_start (ap);
#endif
vprintf (test_description, ap);
va_end (ap);
#endif
if (status == 0)
{
printf(" (%d observed vs %d expected)", result, expected) ;
}
else
{
printf(" (%d observed vs %d expected)", result, expected) ;
}
printf ("\n");
fflush (stdout);
}
}
void
gsl_test_str (const char * result, const char * expected,
const char *test_description,...)
{
int status = strcmp(result,expected) ;
tests++;
if (status == 0)
{
passed++;
if (verbose)
printf ("PASS: ");
}
else
{
failed++;
if (verbose)
printf ("FAIL: ");
}
if (verbose)
{
#ifdef HAVE_VPRINTF
va_list ap;
#ifdef STDC_HEADERS
va_start (ap, test_description);
#else
va_start (ap);
#endif
vprintf (test_description, ap);
va_end (ap);
#endif
if (status)
{
printf(" (%s observed vs %s expected)", result, expected) ;
}
printf ("\n");
fflush (stdout);
}
}
void
gsl_test_verbose (int v)
{
verbose = v;
}
int
gsl_test_summary (void)
{
if (verbose && 0) /* FIXME: turned it off, this annoys me */
printf ("%d tests, passed %d, failed %d.\n", tests, passed, failed);
if (failed != 0)
{
if (verbose && 0) /* FIXME: turned it off, this annoys me */
{
printf ("%d TEST%s FAILED.\n", failed, failed == 1 ? "" : "S");
}
return EXIT_FAILURE;
}
if (tests != passed + failed)
{
if (verbose)
printf ("TEST RESULTS DO NOT ADD UP %d != %d + %d\n",
tests, passed, failed);
return EXIT_FAILURE;
}
if (passed == tests)
{
if (verbose && 0) /* FIXME: turned it off, this annoys me */
printf ("All tests passed successfully\n");
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
| {
"alphanum_fraction": 0.5664503386,
"avg_line_length": 17.0795180723,
"ext": "c",
"hexsha": "3d4c1293673140a8dd50e6675b2b464615995260",
"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/test/results.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/test/results.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/test/results.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": 1918,
"size": 7088
} |
/**
*
* @file core_zlag2c.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
* @precisions mixed zc -> ds
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex64_t
*
* CORE_PLASMA_zlag2c converts a PLASMA_Complex64_t matrix, A, to a
* PLASMA_Complex32_t matrix, B.
*
*******************************************************************************
*
* @param[in] m
* The number of rows of the matrices A and B. m >= 0.
*
* @param[in] n
* The number of columns of the matrices A and B. n >= 0.
*
* @param[in] A
* The PLASMA_Complex64_t m-by-n matrix to convert.
*
* @param[in] lda
* The leading dimension of the array A. lda >= max(1,m).
*
* @param[out] B
* The PLASMA_Complex32_t m-by-n matrix to convert.
*
* @param[in] ldb
* The leading dimension of the array B. ldb >= max(1,m).
*
* @param[out] info
* - 0 on successful exit.
* - 1 if an entry of the matrix A is greater than the SINGLE
* PRECISION overflow threshold, in this case, the content
* of B in exit is unspecified.
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlag2c = PCORE_zlag2c
#define CORE_zlag2c PCORE_zlag2c
#endif
void CORE_zlag2c(int m, int n,
const PLASMA_Complex64_t *A, int lda,
PLASMA_Complex32_t *B, int ldb, int *info)
{
*info = LAPACKE_zlag2c_work(LAPACK_COL_MAJOR, m, n, A, lda, B, ldb);
}
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex64_t
*
* CORE_PLASMA_clag2z converts a PLASMA_Complex32_t matrix, A, to a
* PLASMA_Complex64_t matrix, B.
*
*******************************************************************************
*
* @param[in] m
* The number of rows of the matrices A and B. m >= 0.
*
* @param[in] n
* The number of columns of the matrices A and B. n >= 0.
*
* @param[in] A
* The PLASMA_Complex32_t m-by-n matrix to convert.
*
* @param[in] lda
* The leading dimension of the array A. lda >= max(1,m).
*
* @param[out] B
* The PLASMA_Complex64_t m-by-n matrix to convert.
*
* @param[in] ldb
* The leading dimension of the array B. ldb >= max(1,m).
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_clag2z = PCORE_clag2z
#define CORE_clag2z PCORE_clag2z
#endif
void CORE_clag2z(int m, int n,
const PLASMA_Complex32_t *A, int lda,
PLASMA_Complex64_t *B, int ldb)
{
LAPACKE_clag2z_work(LAPACK_COL_MAJOR, m, n, A, lda, B, ldb);
}
| {
"alphanum_fraction": 0.5263332229,
"avg_line_length": 29.8910891089,
"ext": "c",
"hexsha": "b122133a2e7446f486de79aaf36d03fd104034c8",
"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_zlag2c.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_zlag2c.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas/core_zlag2c.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 819,
"size": 3019
} |
/* blas/gsl_blas.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* Author: G. Jungman
*/
#ifndef __GSL_BLAS_H__
#define __GSL_BLAS_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>
#include <gsl/gsl_blas_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* ========================================================================
* Level 1
* ========================================================================
*/
GSL_FUN int gsl_blas_sdsdot (float alpha,
const gsl_vector_float * X,
const gsl_vector_float * Y,
float * result
);
GSL_FUN int gsl_blas_dsdot (const gsl_vector_float * X,
const gsl_vector_float * Y,
double * result
);
GSL_FUN int gsl_blas_sdot (const gsl_vector_float * X,
const gsl_vector_float * Y,
float * result
);
GSL_FUN int gsl_blas_ddot (const gsl_vector * X,
const gsl_vector * Y,
double * result
);
GSL_FUN int gsl_blas_cdotu (const gsl_vector_complex_float * X,
const gsl_vector_complex_float * Y,
gsl_complex_float * dotu);
GSL_FUN int gsl_blas_cdotc (const gsl_vector_complex_float * X,
const gsl_vector_complex_float * Y,
gsl_complex_float * dotc);
GSL_FUN int gsl_blas_zdotu (const gsl_vector_complex * X,
const gsl_vector_complex * Y,
gsl_complex * dotu);
GSL_FUN int gsl_blas_zdotc (const gsl_vector_complex * X,
const gsl_vector_complex * Y,
gsl_complex * dotc);
GSL_FUN float gsl_blas_snrm2 (const gsl_vector_float * X);
GSL_FUN float gsl_blas_sasum (const gsl_vector_float * X);
GSL_FUN double gsl_blas_dnrm2 (const gsl_vector * X);
GSL_FUN double gsl_blas_dasum (const gsl_vector * X);
GSL_FUN float gsl_blas_scnrm2 (const gsl_vector_complex_float * X);
GSL_FUN float gsl_blas_scasum (const gsl_vector_complex_float * X);
GSL_FUN double gsl_blas_dznrm2 (const gsl_vector_complex * X);
GSL_FUN double gsl_blas_dzasum (const gsl_vector_complex * X);
GSL_FUN CBLAS_INDEX_t gsl_blas_isamax (const gsl_vector_float * X);
GSL_FUN CBLAS_INDEX_t gsl_blas_idamax (const gsl_vector * X);
GSL_FUN CBLAS_INDEX_t gsl_blas_icamax (const gsl_vector_complex_float * X);
GSL_FUN CBLAS_INDEX_t gsl_blas_izamax (const gsl_vector_complex * X);
GSL_FUN int gsl_blas_sswap (gsl_vector_float * X,
gsl_vector_float * Y);
GSL_FUN int gsl_blas_scopy (const gsl_vector_float * X,
gsl_vector_float * Y);
GSL_FUN int gsl_blas_saxpy (float alpha,
const gsl_vector_float * X,
gsl_vector_float * Y);
GSL_FUN int gsl_blas_dswap (gsl_vector * X,
gsl_vector * Y);
GSL_FUN int gsl_blas_dcopy (const gsl_vector * X,
gsl_vector * Y);
GSL_FUN int gsl_blas_daxpy (double alpha,
const gsl_vector * X,
gsl_vector * Y);
GSL_FUN int gsl_blas_cswap (gsl_vector_complex_float * X,
gsl_vector_complex_float * Y);
GSL_FUN int gsl_blas_ccopy (const gsl_vector_complex_float * X,
gsl_vector_complex_float * Y);
GSL_FUN int gsl_blas_caxpy (const gsl_complex_float alpha,
const gsl_vector_complex_float * X,
gsl_vector_complex_float * Y);
GSL_FUN int gsl_blas_zswap (gsl_vector_complex * X,
gsl_vector_complex * Y);
GSL_FUN int gsl_blas_zcopy (const gsl_vector_complex * X,
gsl_vector_complex * Y);
GSL_FUN int gsl_blas_zaxpy (const gsl_complex alpha,
const gsl_vector_complex * X,
gsl_vector_complex * Y);
GSL_FUN int gsl_blas_srotg (float a[], float b[], float c[], float s[]);
GSL_FUN int gsl_blas_srotmg (float d1[], float d2[], float b1[], float b2, float P[]);
GSL_FUN int gsl_blas_srot (gsl_vector_float * X,
gsl_vector_float * Y,
float c, float s);
GSL_FUN int gsl_blas_srotm (gsl_vector_float * X,
gsl_vector_float * Y,
const float P[]);
GSL_FUN int gsl_blas_drotg (double a[], double b[], double c[], double s[]);
GSL_FUN int gsl_blas_drotmg (double d1[], double d2[], double b1[],
double b2, double P[]);
GSL_FUN int gsl_blas_drot (gsl_vector * X,
gsl_vector * Y,
const double c, const double s);
GSL_FUN int gsl_blas_drotm (gsl_vector * X,
gsl_vector * Y,
const double P[]);
GSL_FUN void gsl_blas_sscal (float alpha, gsl_vector_float * X);
GSL_FUN void gsl_blas_dscal (double alpha, gsl_vector * X);
GSL_FUN void gsl_blas_cscal (const gsl_complex_float alpha, gsl_vector_complex_float * X);
GSL_FUN void gsl_blas_zscal (const gsl_complex alpha, gsl_vector_complex * X);
GSL_FUN void gsl_blas_csscal (float alpha, gsl_vector_complex_float * X);
GSL_FUN void gsl_blas_zdscal (double alpha, gsl_vector_complex * X);
/* ===========================================================================
* Level 2
* ===========================================================================
*/
/*
* Routines with standard 4 prefixes (S, D, C, Z)
*/
GSL_FUN int gsl_blas_sgemv (CBLAS_TRANSPOSE_t TransA,
float alpha,
const gsl_matrix_float * A,
const gsl_vector_float * X,
float beta,
gsl_vector_float * Y);
GSL_FUN int gsl_blas_strmv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix_float * A,
gsl_vector_float * X);
GSL_FUN int gsl_blas_strsv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix_float * A,
gsl_vector_float * X);
GSL_FUN int gsl_blas_dgemv (CBLAS_TRANSPOSE_t TransA,
double alpha,
const gsl_matrix * A,
const gsl_vector * X,
double beta,
gsl_vector * Y);
GSL_FUN int gsl_blas_dtrmv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix * A,
gsl_vector * X);
GSL_FUN int gsl_blas_dtrsv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix * A,
gsl_vector * X);
GSL_FUN int gsl_blas_cgemv (CBLAS_TRANSPOSE_t TransA,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_vector_complex_float * X,
const gsl_complex_float beta,
gsl_vector_complex_float * Y);
GSL_FUN int gsl_blas_ctrmv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix_complex_float * A,
gsl_vector_complex_float * X);
GSL_FUN int gsl_blas_ctrsv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix_complex_float * A,
gsl_vector_complex_float * X);
GSL_FUN int gsl_blas_zgemv (CBLAS_TRANSPOSE_t TransA,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_vector_complex * X,
const gsl_complex beta,
gsl_vector_complex * Y);
GSL_FUN int gsl_blas_ztrmv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix_complex * A,
gsl_vector_complex * X);
GSL_FUN int gsl_blas_ztrsv (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,
const gsl_matrix_complex * A,
gsl_vector_complex *X);
/*
* Routines with S and D prefixes only
*/
GSL_FUN int gsl_blas_ssymv (CBLAS_UPLO_t Uplo,
float alpha,
const gsl_matrix_float * A,
const gsl_vector_float * X,
float beta,
gsl_vector_float * Y);
GSL_FUN int gsl_blas_sger (float alpha,
const gsl_vector_float * X,
const gsl_vector_float * Y,
gsl_matrix_float * A);
GSL_FUN int gsl_blas_ssyr (CBLAS_UPLO_t Uplo,
float alpha,
const gsl_vector_float * X,
gsl_matrix_float * A);
GSL_FUN int gsl_blas_ssyr2 (CBLAS_UPLO_t Uplo,
float alpha,
const gsl_vector_float * X,
const gsl_vector_float * Y,
gsl_matrix_float * A);
GSL_FUN int gsl_blas_dsymv (CBLAS_UPLO_t Uplo,
double alpha,
const gsl_matrix * A,
const gsl_vector * X,
double beta,
gsl_vector * Y);
GSL_FUN int gsl_blas_dger (double alpha,
const gsl_vector * X,
const gsl_vector * Y,
gsl_matrix * A);
GSL_FUN int gsl_blas_dsyr (CBLAS_UPLO_t Uplo,
double alpha,
const gsl_vector * X,
gsl_matrix * A);
GSL_FUN int gsl_blas_dsyr2 (CBLAS_UPLO_t Uplo,
double alpha,
const gsl_vector * X,
const gsl_vector * Y,
gsl_matrix * A);
/*
* Routines with C and Z prefixes only
*/
GSL_FUN int gsl_blas_chemv (CBLAS_UPLO_t Uplo,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_vector_complex_float * X,
const gsl_complex_float beta,
gsl_vector_complex_float * Y);
GSL_FUN int gsl_blas_cgeru (const gsl_complex_float alpha,
const gsl_vector_complex_float * X,
const gsl_vector_complex_float * Y,
gsl_matrix_complex_float * A);
GSL_FUN int gsl_blas_cgerc (const gsl_complex_float alpha,
const gsl_vector_complex_float * X,
const gsl_vector_complex_float * Y,
gsl_matrix_complex_float * A);
GSL_FUN int gsl_blas_cher (CBLAS_UPLO_t Uplo,
float alpha,
const gsl_vector_complex_float * X,
gsl_matrix_complex_float * A);
GSL_FUN int gsl_blas_cher2 (CBLAS_UPLO_t Uplo,
const gsl_complex_float alpha,
const gsl_vector_complex_float * X,
const gsl_vector_complex_float * Y,
gsl_matrix_complex_float * A);
GSL_FUN int gsl_blas_zhemv (CBLAS_UPLO_t Uplo,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_vector_complex * X,
const gsl_complex beta,
gsl_vector_complex * Y);
GSL_FUN int gsl_blas_zgeru (const gsl_complex alpha,
const gsl_vector_complex * X,
const gsl_vector_complex * Y,
gsl_matrix_complex * A);
GSL_FUN int gsl_blas_zgerc (const gsl_complex alpha,
const gsl_vector_complex * X,
const gsl_vector_complex * Y,
gsl_matrix_complex * A);
GSL_FUN int gsl_blas_zher (CBLAS_UPLO_t Uplo,
double alpha,
const gsl_vector_complex * X,
gsl_matrix_complex * A);
GSL_FUN int gsl_blas_zher2 (CBLAS_UPLO_t Uplo,
const gsl_complex alpha,
const gsl_vector_complex * X,
const gsl_vector_complex * Y,
gsl_matrix_complex * A);
/*
* ===========================================================================
* Prototypes for level 3 BLAS
* ===========================================================================
*/
/*
* Routines with standard 4 prefixes (S, D, C, Z)
*/
GSL_FUN int gsl_blas_sgemm (CBLAS_TRANSPOSE_t TransA,
CBLAS_TRANSPOSE_t TransB,
float alpha,
const gsl_matrix_float * A,
const gsl_matrix_float * B,
float beta,
gsl_matrix_float * C);
GSL_FUN int gsl_blas_ssymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo,
float alpha,
const gsl_matrix_float * A,
const gsl_matrix_float * B,
float beta,
gsl_matrix_float * C);
GSL_FUN int gsl_blas_ssyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans,
float alpha,
const gsl_matrix_float * A,
float beta,
gsl_matrix_float * C);
GSL_FUN int gsl_blas_ssyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans,
float alpha,
const gsl_matrix_float * A,
const gsl_matrix_float * B,
float beta,
gsl_matrix_float * C);
GSL_FUN int gsl_blas_strmm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
float alpha,
const gsl_matrix_float * A,
gsl_matrix_float * B);
GSL_FUN int gsl_blas_strsm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
float alpha,
const gsl_matrix_float * A,
gsl_matrix_float * B);
GSL_FUN int gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA,
CBLAS_TRANSPOSE_t TransB,
double alpha,
const gsl_matrix * A,
const gsl_matrix * B,
double beta,
gsl_matrix * C);
GSL_FUN int gsl_blas_dsymm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo,
double alpha,
const gsl_matrix * A,
const gsl_matrix * B,
double beta,
gsl_matrix * C);
GSL_FUN int gsl_blas_dsyrk (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
double alpha,
const gsl_matrix * A,
double beta,
gsl_matrix * C);
GSL_FUN int gsl_blas_dsyr2k (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
double alpha,
const gsl_matrix * A,
const gsl_matrix * B,
double beta,
gsl_matrix * C);
GSL_FUN int gsl_blas_dtrmm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
double alpha,
const gsl_matrix * A,
gsl_matrix * B);
GSL_FUN int gsl_blas_dtrsm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
double alpha,
const gsl_matrix * A,
gsl_matrix * B);
GSL_FUN int gsl_blas_cgemm (CBLAS_TRANSPOSE_t TransA,
CBLAS_TRANSPOSE_t TransB,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_matrix_complex_float * B,
const gsl_complex_float beta,
gsl_matrix_complex_float * C);
GSL_FUN int gsl_blas_csymm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_matrix_complex_float * B,
const gsl_complex_float beta,
gsl_matrix_complex_float * C);
GSL_FUN int gsl_blas_csyrk (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_complex_float beta,
gsl_matrix_complex_float * C);
GSL_FUN int gsl_blas_csyr2k (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_matrix_complex_float * B,
const gsl_complex_float beta,
gsl_matrix_complex_float * C);
GSL_FUN int gsl_blas_ctrmm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
gsl_matrix_complex_float * B);
GSL_FUN int gsl_blas_ctrsm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
gsl_matrix_complex_float * B);
GSL_FUN int gsl_blas_zgemm (CBLAS_TRANSPOSE_t TransA,
CBLAS_TRANSPOSE_t TransB,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_matrix_complex * B,
const gsl_complex beta,
gsl_matrix_complex * C);
GSL_FUN int gsl_blas_zsymm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_matrix_complex * B,
const gsl_complex beta,
gsl_matrix_complex * C);
GSL_FUN int gsl_blas_zsyrk (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_complex beta,
gsl_matrix_complex * C);
GSL_FUN int gsl_blas_zsyr2k (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_matrix_complex * B,
const gsl_complex beta,
gsl_matrix_complex *C);
GSL_FUN int gsl_blas_ztrmm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
const gsl_complex alpha,
const gsl_matrix_complex * A,
gsl_matrix_complex * B);
GSL_FUN int gsl_blas_ztrsm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,
CBLAS_DIAG_t Diag,
const gsl_complex alpha,
const gsl_matrix_complex * A,
gsl_matrix_complex * B);
/*
* Routines with prefixes C and Z only
*/
GSL_FUN int gsl_blas_chemm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_matrix_complex_float * B,
const gsl_complex_float beta,
gsl_matrix_complex_float * C);
GSL_FUN int gsl_blas_cherk (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
float alpha,
const gsl_matrix_complex_float * A,
float beta,
gsl_matrix_complex_float * C);
GSL_FUN int gsl_blas_cher2k (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
const gsl_complex_float alpha,
const gsl_matrix_complex_float * A,
const gsl_matrix_complex_float * B,
float beta,
gsl_matrix_complex_float * C);
GSL_FUN int gsl_blas_zhemm (CBLAS_SIDE_t Side,
CBLAS_UPLO_t Uplo,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_matrix_complex * B,
const gsl_complex beta,
gsl_matrix_complex * C);
GSL_FUN int gsl_blas_zherk (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
double alpha,
const gsl_matrix_complex * A,
double beta,
gsl_matrix_complex * C);
GSL_FUN int gsl_blas_zher2k (CBLAS_UPLO_t Uplo,
CBLAS_TRANSPOSE_t Trans,
const gsl_complex alpha,
const gsl_matrix_complex * A,
const gsl_matrix_complex * B,
double beta,
gsl_matrix_complex * C);
__END_DECLS
#endif /* __GSL_BLAS_H__ */
| {
"alphanum_fraction": 0.5446447969,
"avg_line_length": 37.5448613377,
"ext": "h",
"hexsha": "531e47edbdf9808460c9510ec7d8b5006cf5c618",
"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": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_blas.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_blas.h",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_blas.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5068,
"size": 23015
} |
#pragma once
#include <vector>
#include <array>
#include <iostream>
#include <stdexcept>
#include <cassert>
#include <gsl/gsl.h>
#include"utils/math.h"
namespace util{
namespace math{
template<typename T, int64_t M>
struct Vector{
Vector(gsl::span<T, M> const vals) : _val(M, T{}) {
// std::cerr<<M<<" Vector{gsl::span<M>}\n";
std::copy_n(vals.cbegin(), M, _val.begin());
assert(span[0]==_val[0]);
}
Vector() : _val(M, T{}) {
// std::cerr<<"Default construct Vector{gsl::span<M>}\n";
assert(span[0]==_val[0]);
}
//CAUTION: careful to correctly implement non-default constructor if necessary.
Vector(Vector const & vec) : _val{vec._val} {
if(!(span[0]==_val[0])) {
std::cerr<<_val.size()<<" Copy construct Vector{gsl::span<M>}\n";
std::cerr<<"Assert fails : " << span[0] << " vs " << _val[0] <<std::endl;
}
assert(span[0]==_val[0]);
// std::cerr<<_val.size()<<" Copy construct Vector{gsl::span<M>}\n";
};
Vector& operator=(const Vector& vec) {
// std::cerr<<"Copy assignment Vector{gsl::span<M>}\n";
// std::cerr<<"size: " << vec._val.size() << " vs " <<_val.size() <<std::endl;
// assert(_val.size()==vec._val.size());
// assert(span[0]==_val[0]);
std::copy_n(vec.span.cbegin(), M, _val.begin());
// span=gsl::span<T, M>{_val};
assert(span[0]==_val[0]);
// std::cerr<<"size: " << _val.size() <<std::endl;
return *this;
};
Vector& operator+=(const Vector& vec) {
auto n = span.size();
for(decltype(n)i=0; i!=n; ++i) span[i] += vec.span[i];
return *this;
}
Vector& operator-=(const Vector& vec) {
span-=vec.span;
return *this;
}
Vector& operator*=(T x) {
for(auto &v : _val) v *= x;
return *this;
}
Vector(Vector&& vec) : _val{std::move(vec._val)} {
span=gsl::span<T, M>{_val};
//Fail if nan
assert(span[0]==_val[0]);
// std::cerr<<"Move Vector{gsl::span<M>}\n";
};
auto l1_norm() const {
T norm{0.0};
for(auto x : _val) norm += std::abs(x);
return norm;
}
std::vector<T> _val;
gsl::span<T, M> span=_val; //this default is critical!
};
template<typename T, int64_t M>
struct VectorView{
VectorView(gsl::span<T, M> const vals) :span{vals} {}
gsl::span<T, M> span;
};
template<typename T, int64_t M, int64_t N>
struct Matrix{
Matrix(gsl::span<T, M,N> const vals) : _val(M*N, T{}) {
std::cerr<<M<<" "<<N<<" Matrix{gsl::span<M,N>}\n";
std::copy_n(vals.begin(), M*N, _val.begin());
}
Matrix() :_val(M*N, T{}) {}
Matrix(Matrix const & mat) : _val{mat._val}{};
Matrix& operator=(const Matrix& mat) {
std::copy_n(mat.span.cbegin(), M*N, _val.begin());
return *this;
}
Matrix(Matrix&& vec) : _val{std::move(vec._val)} {
span=gsl::span<T, M,N>{_val};
//Fail if nan
assert(span[0][0]==_val[0]);
};
std::vector<T> _val;
gsl::span<T, M, N> span=_val; //this default is critical!
};
template<typename T, int64_t M, int64_t N>
struct MatrixView{
MatrixView(gsl::span<T, M,N> const vals) : span{vals} {}
// MatrixView(gsl::span<T> const vals) : span{vals.as_array_view<T,M,N>()} {}
gsl::span<T, M, N> span;
};
template<typename T, int64_t L,int64_t M,int64_t N>
struct ThirdTensorView{
ThirdTensorView(gsl::span<T, L,M,N> const vals) : span{vals} {}
// MatrixView(gsl::span<T> const vals) : span{vals.as_array_view<T,M,N>()} {}
gsl::span<T, L, M, N> span;
};
namespace factory{
//TODO: val can be const &
template<typename T, std::size_t M>
auto Vector(std::array<T,M> &val){
const auto span = gsl::as_span(val);
return util::math::Vector<T,int64_t{M}>{span};
}
// template<typename T>
// auto Vector(std::vector<T> const &val){
// constexpr auto span = gsl::span<const T>{val};
// return util::math::Vector<T,span.size()>{span};
// }
// template<typename T>
// auto Vector(std::vector<T> const &val){
// return gsl::span<const T>{val};
// }
//
// template<typename T>
// auto Vector(T vals){
// auto a = util::math::Vector{to_cspan(vals)};
// return a;
// }
//
}//namespace util::math::factory
//TODO: use bi-dimensional index, gsl::index<2>??
template<typename T, int64_t M, int64_t N>
auto transpose(gsl::span<T,M,N> mat){
std::vector<T> tr_mat(M*N);
auto tr = gsl::span<T,N,M>{tr_mat};
for (int64_t i=0; i<mat.extent(0); ++i) {
for (int64_t j=0; j<mat.extent(1); ++j){
tr[j][i] = mat[i][j];
}
}
return Matrix<T,N,M>{tr};
}
template<typename T, int64_t M>
T dot(gsl::span<T,M> const x, gsl::span<T,M> const y){
// return std::inner_product(x.cbegin(), x.cend(), y.cbegin(), T{});
T sum{};
#pragma clang loop vectorize(enable)
for(decltype(M) i=0; i!=M; ++i){
sum+=x[i]*y[i];
}
return sum;
}
//Following also works, without template, but less safe:
// auto dot = [](auto const &x, auto const &y){
// typedef typename std::remove_reference<decltype(x[0])>::type A;
// return std::inner_product(x.cbegin(), x.cend(), y.cbegin(), A{0});
// };
template<typename T, int64_t M, int64_t N>
auto dotdot(Vector<T,M> &x, Matrix<T,M,N> &m, Vector<T,N> &y){
T sum{};
for(decltype(M) i=0; i!=M; ++i){
for(decltype(N) j=0; j!=N; ++j){
sum += x.span[i]*m.span[i][j]*y.span[j];
}
}
return sum;
}
auto mul_sum_vec=[](int64_t i, auto &out,
auto const &a, auto const &b) {
out+=a[i]*b[i];
};
auto mul_sum_mat=[](int64_t i,int64_t j, auto &out,
auto const &a, auto const &b) {
out+=a[i][j]*b[i][j];
};
}//namespace util::math
}//namespace util
| {
"alphanum_fraction": 0.5578675838,
"avg_line_length": 29.6683673469,
"ext": "h",
"hexsha": "7530ea934ce3913fabe7946d22e85a037baac252",
"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": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "uphere-co/nlp-prototype",
"max_forks_repo_path": "rnn++/utils/linear_algebra.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3",
"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": "uphere-co/nlp-prototype",
"max_issues_repo_path": "rnn++/utils/linear_algebra.h",
"max_line_length": 87,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "uphere-co/nlp-prototype",
"max_stars_repo_path": "rnn++/utils/linear_algebra.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1800,
"size": 5815
} |
//====---- Sudoku/Size.h ----====//
//
// The size definition that rules them all.
//====--------------------------------------------------------------------====//
#pragma once
#include <gsl/gsl>
#include <limits>
namespace Sudoku
{
template<int N>
struct Size
{
using index = gsl::index;
static constexpr index base = N; // 3 for default 9*9 board
static constexpr index elem = base * base; // 9 for default
static constexpr index full = elem * elem; // 81 for default
static_assert(
1 < base && base < elem && base < full && elem < full,
"struct Size: Board size out of bounds.");
static_assert(
N < std::numeric_limits<index>::max() / base &&
N < std::numeric_limits<index>::max() / elem &&
N < std::numeric_limits<index>::max() / elem / base &&
N < std::numeric_limits<index>::max() / full &&
N < std::numeric_limits<index>::max() / full / base,
"struct Size: Board size too large for system integer size.");
// fails at N > 35 when int less than 32-bits.
};
template<int N>
inline constexpr gsl::index base_size = Size<N>::base; // default 3
template<int N>
inline constexpr gsl::index elem_size = Size<N>::elem; // default 9
template<int N>
inline constexpr gsl::index full_size = Size<N>::full; // default 81
} // namespace Sudoku
| {
"alphanum_fraction": 0.584947839,
"avg_line_length": 31.9523809524,
"ext": "h",
"hexsha": "76a481d0436adc82c9cf7b367651011ec4c3902d",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-04-20T16:26:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-04-20T16:26:42.000Z",
"max_forks_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "FeodorFitsner/fwkSudoku",
"max_forks_repo_path": "Sudoku/Sudoku/Size.h",
"max_issues_count": 38,
"max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_issues_repo_issues_event_max_datetime": "2021-07-17T01:22:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-28T18:15:15.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "FeodorFitsner/fwkSudoku",
"max_issues_repo_path": "Sudoku/Sudoku/Size.h",
"max_line_length": 80,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "FeodorFitsner/fwkSudoku",
"max_stars_repo_path": "Sudoku/Sudoku/Size.h",
"max_stars_repo_stars_event_max_datetime": "2019-08-18T19:26:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-17T18:27:16.000Z",
"num_tokens": 327,
"size": 1342
} |
/*
* 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:36 EST 1999 */
#include <fftw-int.h>
#include <fftw.h>
/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -twiddle 16 */
/*
* This function contains 174 FP additions, 84 FP multiplications,
* (or, 136 additions, 46 multiplications, 38 fused multiply/add),
* 50 stack variables, and 64 memory accesses
*/
static const fftw_real K382683432 = FFTW_KONST(+0.382683432365089771728459984030398866761344562);
static const fftw_real K923879532 = FFTW_KONST(+0.923879532511286756128183189396788286822416626);
static const fftw_real K707106781 = FFTW_KONST(+0.707106781186547524400844362104849039284835938);
/*
* Generator Id's :
* $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $
* $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $
* $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $
*/
void fftw_twiddle_16(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 + 15) {
fftw_real tmp7;
fftw_real tmp91;
fftw_real tmp180;
fftw_real tmp193;
fftw_real tmp18;
fftw_real tmp194;
fftw_real tmp94;
fftw_real tmp177;
fftw_real tmp77;
fftw_real tmp88;
fftw_real tmp161;
fftw_real tmp128;
fftw_real tmp144;
fftw_real tmp162;
fftw_real tmp163;
fftw_real tmp164;
fftw_real tmp123;
fftw_real tmp143;
fftw_real tmp30;
fftw_real tmp152;
fftw_real tmp100;
fftw_real tmp136;
fftw_real tmp41;
fftw_real tmp153;
fftw_real tmp105;
fftw_real tmp137;
fftw_real tmp54;
fftw_real tmp65;
fftw_real tmp156;
fftw_real tmp117;
fftw_real tmp141;
fftw_real tmp157;
fftw_real tmp158;
fftw_real tmp159;
fftw_real tmp112;
fftw_real tmp140;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp1;
fftw_real tmp179;
fftw_real tmp6;
fftw_real tmp178;
ASSERT_ALIGNED_DOUBLE;
tmp1 = c_re(inout[0]);
tmp179 = c_im(inout[0]);
{
fftw_real tmp3;
fftw_real tmp5;
fftw_real tmp2;
fftw_real tmp4;
ASSERT_ALIGNED_DOUBLE;
tmp3 = c_re(inout[8 * iostride]);
tmp5 = c_im(inout[8 * iostride]);
tmp2 = c_re(W[7]);
tmp4 = c_im(W[7]);
tmp6 = (tmp2 * tmp3) - (tmp4 * tmp5);
tmp178 = (tmp4 * tmp3) + (tmp2 * tmp5);
}
tmp7 = tmp1 + tmp6;
tmp91 = tmp1 - tmp6;
tmp180 = tmp178 + tmp179;
tmp193 = tmp179 - tmp178;
}
{
fftw_real tmp12;
fftw_real tmp92;
fftw_real tmp17;
fftw_real tmp93;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp9;
fftw_real tmp11;
fftw_real tmp8;
fftw_real tmp10;
ASSERT_ALIGNED_DOUBLE;
tmp9 = c_re(inout[4 * iostride]);
tmp11 = c_im(inout[4 * iostride]);
tmp8 = c_re(W[3]);
tmp10 = c_im(W[3]);
tmp12 = (tmp8 * tmp9) - (tmp10 * tmp11);
tmp92 = (tmp10 * tmp9) + (tmp8 * tmp11);
}
{
fftw_real tmp14;
fftw_real tmp16;
fftw_real tmp13;
fftw_real tmp15;
ASSERT_ALIGNED_DOUBLE;
tmp14 = c_re(inout[12 * iostride]);
tmp16 = c_im(inout[12 * iostride]);
tmp13 = c_re(W[11]);
tmp15 = c_im(W[11]);
tmp17 = (tmp13 * tmp14) - (tmp15 * tmp16);
tmp93 = (tmp15 * tmp14) + (tmp13 * tmp16);
}
tmp18 = tmp12 + tmp17;
tmp194 = tmp12 - tmp17;
tmp94 = tmp92 - tmp93;
tmp177 = tmp92 + tmp93;
}
{
fftw_real tmp71;
fftw_real tmp124;
fftw_real tmp87;
fftw_real tmp121;
fftw_real tmp76;
fftw_real tmp125;
fftw_real tmp82;
fftw_real tmp120;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp68;
fftw_real tmp70;
fftw_real tmp67;
fftw_real tmp69;
ASSERT_ALIGNED_DOUBLE;
tmp68 = c_re(inout[15 * iostride]);
tmp70 = c_im(inout[15 * iostride]);
tmp67 = c_re(W[14]);
tmp69 = c_im(W[14]);
tmp71 = (tmp67 * tmp68) - (tmp69 * tmp70);
tmp124 = (tmp69 * tmp68) + (tmp67 * tmp70);
}
{
fftw_real tmp84;
fftw_real tmp86;
fftw_real tmp83;
fftw_real tmp85;
ASSERT_ALIGNED_DOUBLE;
tmp84 = c_re(inout[11 * iostride]);
tmp86 = c_im(inout[11 * iostride]);
tmp83 = c_re(W[10]);
tmp85 = c_im(W[10]);
tmp87 = (tmp83 * tmp84) - (tmp85 * tmp86);
tmp121 = (tmp85 * tmp84) + (tmp83 * tmp86);
}
{
fftw_real tmp73;
fftw_real tmp75;
fftw_real tmp72;
fftw_real tmp74;
ASSERT_ALIGNED_DOUBLE;
tmp73 = c_re(inout[7 * iostride]);
tmp75 = c_im(inout[7 * iostride]);
tmp72 = c_re(W[6]);
tmp74 = c_im(W[6]);
tmp76 = (tmp72 * tmp73) - (tmp74 * tmp75);
tmp125 = (tmp74 * tmp73) + (tmp72 * tmp75);
}
{
fftw_real tmp79;
fftw_real tmp81;
fftw_real tmp78;
fftw_real tmp80;
ASSERT_ALIGNED_DOUBLE;
tmp79 = c_re(inout[3 * iostride]);
tmp81 = c_im(inout[3 * iostride]);
tmp78 = c_re(W[2]);
tmp80 = c_im(W[2]);
tmp82 = (tmp78 * tmp79) - (tmp80 * tmp81);
tmp120 = (tmp80 * tmp79) + (tmp78 * tmp81);
}
{
fftw_real tmp126;
fftw_real tmp127;
fftw_real tmp119;
fftw_real tmp122;
ASSERT_ALIGNED_DOUBLE;
tmp77 = tmp71 + tmp76;
tmp88 = tmp82 + tmp87;
tmp161 = tmp77 - tmp88;
tmp126 = tmp124 - tmp125;
tmp127 = tmp82 - tmp87;
tmp128 = tmp126 + tmp127;
tmp144 = tmp126 - tmp127;
tmp162 = tmp124 + tmp125;
tmp163 = tmp120 + tmp121;
tmp164 = tmp162 - tmp163;
tmp119 = tmp71 - tmp76;
tmp122 = tmp120 - tmp121;
tmp123 = tmp119 - tmp122;
tmp143 = tmp119 + tmp122;
}
}
{
fftw_real tmp24;
fftw_real tmp96;
fftw_real tmp29;
fftw_real tmp97;
fftw_real tmp98;
fftw_real tmp99;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp21;
fftw_real tmp23;
fftw_real tmp20;
fftw_real tmp22;
ASSERT_ALIGNED_DOUBLE;
tmp21 = c_re(inout[2 * iostride]);
tmp23 = c_im(inout[2 * iostride]);
tmp20 = c_re(W[1]);
tmp22 = c_im(W[1]);
tmp24 = (tmp20 * tmp21) - (tmp22 * tmp23);
tmp96 = (tmp22 * tmp21) + (tmp20 * tmp23);
}
{
fftw_real tmp26;
fftw_real tmp28;
fftw_real tmp25;
fftw_real tmp27;
ASSERT_ALIGNED_DOUBLE;
tmp26 = c_re(inout[10 * iostride]);
tmp28 = c_im(inout[10 * iostride]);
tmp25 = c_re(W[9]);
tmp27 = c_im(W[9]);
tmp29 = (tmp25 * tmp26) - (tmp27 * tmp28);
tmp97 = (tmp27 * tmp26) + (tmp25 * tmp28);
}
tmp30 = tmp24 + tmp29;
tmp152 = tmp96 + tmp97;
tmp98 = tmp96 - tmp97;
tmp99 = tmp24 - tmp29;
tmp100 = tmp98 - tmp99;
tmp136 = tmp99 + tmp98;
}
{
fftw_real tmp35;
fftw_real tmp102;
fftw_real tmp40;
fftw_real tmp103;
fftw_real tmp101;
fftw_real tmp104;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp32;
fftw_real tmp34;
fftw_real tmp31;
fftw_real tmp33;
ASSERT_ALIGNED_DOUBLE;
tmp32 = c_re(inout[14 * iostride]);
tmp34 = c_im(inout[14 * iostride]);
tmp31 = c_re(W[13]);
tmp33 = c_im(W[13]);
tmp35 = (tmp31 * tmp32) - (tmp33 * tmp34);
tmp102 = (tmp33 * tmp32) + (tmp31 * tmp34);
}
{
fftw_real tmp37;
fftw_real tmp39;
fftw_real tmp36;
fftw_real tmp38;
ASSERT_ALIGNED_DOUBLE;
tmp37 = c_re(inout[6 * iostride]);
tmp39 = c_im(inout[6 * iostride]);
tmp36 = c_re(W[5]);
tmp38 = c_im(W[5]);
tmp40 = (tmp36 * tmp37) - (tmp38 * tmp39);
tmp103 = (tmp38 * tmp37) + (tmp36 * tmp39);
}
tmp41 = tmp35 + tmp40;
tmp153 = tmp102 + tmp103;
tmp101 = tmp35 - tmp40;
tmp104 = tmp102 - tmp103;
tmp105 = tmp101 + tmp104;
tmp137 = tmp101 - tmp104;
}
{
fftw_real tmp48;
fftw_real tmp108;
fftw_real tmp64;
fftw_real tmp115;
fftw_real tmp53;
fftw_real tmp109;
fftw_real tmp59;
fftw_real tmp114;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp45;
fftw_real tmp47;
fftw_real tmp44;
fftw_real tmp46;
ASSERT_ALIGNED_DOUBLE;
tmp45 = c_re(inout[iostride]);
tmp47 = c_im(inout[iostride]);
tmp44 = c_re(W[0]);
tmp46 = c_im(W[0]);
tmp48 = (tmp44 * tmp45) - (tmp46 * tmp47);
tmp108 = (tmp46 * tmp45) + (tmp44 * tmp47);
}
{
fftw_real tmp61;
fftw_real tmp63;
fftw_real tmp60;
fftw_real tmp62;
ASSERT_ALIGNED_DOUBLE;
tmp61 = c_re(inout[13 * iostride]);
tmp63 = c_im(inout[13 * iostride]);
tmp60 = c_re(W[12]);
tmp62 = c_im(W[12]);
tmp64 = (tmp60 * tmp61) - (tmp62 * tmp63);
tmp115 = (tmp62 * tmp61) + (tmp60 * tmp63);
}
{
fftw_real tmp50;
fftw_real tmp52;
fftw_real tmp49;
fftw_real tmp51;
ASSERT_ALIGNED_DOUBLE;
tmp50 = c_re(inout[9 * iostride]);
tmp52 = c_im(inout[9 * iostride]);
tmp49 = c_re(W[8]);
tmp51 = c_im(W[8]);
tmp53 = (tmp49 * tmp50) - (tmp51 * tmp52);
tmp109 = (tmp51 * tmp50) + (tmp49 * tmp52);
}
{
fftw_real tmp56;
fftw_real tmp58;
fftw_real tmp55;
fftw_real tmp57;
ASSERT_ALIGNED_DOUBLE;
tmp56 = c_re(inout[5 * iostride]);
tmp58 = c_im(inout[5 * iostride]);
tmp55 = c_re(W[4]);
tmp57 = c_im(W[4]);
tmp59 = (tmp55 * tmp56) - (tmp57 * tmp58);
tmp114 = (tmp57 * tmp56) + (tmp55 * tmp58);
}
{
fftw_real tmp113;
fftw_real tmp116;
fftw_real tmp110;
fftw_real tmp111;
ASSERT_ALIGNED_DOUBLE;
tmp54 = tmp48 + tmp53;
tmp65 = tmp59 + tmp64;
tmp156 = tmp54 - tmp65;
tmp113 = tmp48 - tmp53;
tmp116 = tmp114 - tmp115;
tmp117 = tmp113 - tmp116;
tmp141 = tmp113 + tmp116;
tmp157 = tmp108 + tmp109;
tmp158 = tmp114 + tmp115;
tmp159 = tmp157 - tmp158;
tmp110 = tmp108 - tmp109;
tmp111 = tmp59 - tmp64;
tmp112 = tmp110 + tmp111;
tmp140 = tmp110 - tmp111;
}
}
{
fftw_real tmp107;
fftw_real tmp131;
fftw_real tmp202;
fftw_real tmp204;
fftw_real tmp130;
fftw_real tmp203;
fftw_real tmp134;
fftw_real tmp199;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp95;
fftw_real tmp106;
fftw_real tmp200;
fftw_real tmp201;
ASSERT_ALIGNED_DOUBLE;
tmp95 = tmp91 - tmp94;
tmp106 = K707106781 * (tmp100 - tmp105);
tmp107 = tmp95 + tmp106;
tmp131 = tmp95 - tmp106;
tmp200 = K707106781 * (tmp137 - tmp136);
tmp201 = tmp194 + tmp193;
tmp202 = tmp200 + tmp201;
tmp204 = tmp201 - tmp200;
}
{
fftw_real tmp118;
fftw_real tmp129;
fftw_real tmp132;
fftw_real tmp133;
ASSERT_ALIGNED_DOUBLE;
tmp118 = (K923879532 * tmp112) + (K382683432 * tmp117);
tmp129 = (K382683432 * tmp123) - (K923879532 * tmp128);
tmp130 = tmp118 + tmp129;
tmp203 = tmp129 - tmp118;
tmp132 = (K382683432 * tmp112) - (K923879532 * tmp117);
tmp133 = (K382683432 * tmp128) + (K923879532 * tmp123);
tmp134 = tmp132 - tmp133;
tmp199 = tmp132 + tmp133;
}
c_re(inout[11 * iostride]) = tmp107 - tmp130;
c_re(inout[3 * iostride]) = tmp107 + tmp130;
c_re(inout[15 * iostride]) = tmp131 - tmp134;
c_re(inout[7 * iostride]) = tmp131 + tmp134;
c_im(inout[3 * iostride]) = tmp199 + tmp202;
c_im(inout[11 * iostride]) = tmp202 - tmp199;
c_im(inout[7 * iostride]) = tmp203 + tmp204;
c_im(inout[15 * iostride]) = tmp204 - tmp203;
}
{
fftw_real tmp139;
fftw_real tmp147;
fftw_real tmp196;
fftw_real tmp198;
fftw_real tmp146;
fftw_real tmp197;
fftw_real tmp150;
fftw_real tmp191;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp135;
fftw_real tmp138;
fftw_real tmp192;
fftw_real tmp195;
ASSERT_ALIGNED_DOUBLE;
tmp135 = tmp91 + tmp94;
tmp138 = K707106781 * (tmp136 + tmp137);
tmp139 = tmp135 + tmp138;
tmp147 = tmp135 - tmp138;
tmp192 = K707106781 * (tmp100 + tmp105);
tmp195 = tmp193 - tmp194;
tmp196 = tmp192 + tmp195;
tmp198 = tmp195 - tmp192;
}
{
fftw_real tmp142;
fftw_real tmp145;
fftw_real tmp148;
fftw_real tmp149;
ASSERT_ALIGNED_DOUBLE;
tmp142 = (K382683432 * tmp140) + (K923879532 * tmp141);
tmp145 = (K923879532 * tmp143) - (K382683432 * tmp144);
tmp146 = tmp142 + tmp145;
tmp197 = tmp145 - tmp142;
tmp148 = (K923879532 * tmp140) - (K382683432 * tmp141);
tmp149 = (K923879532 * tmp144) + (K382683432 * tmp143);
tmp150 = tmp148 - tmp149;
tmp191 = tmp148 + tmp149;
}
c_re(inout[9 * iostride]) = tmp139 - tmp146;
c_re(inout[iostride]) = tmp139 + tmp146;
c_re(inout[13 * iostride]) = tmp147 - tmp150;
c_re(inout[5 * iostride]) = tmp147 + tmp150;
c_im(inout[iostride]) = tmp191 + tmp196;
c_im(inout[9 * iostride]) = tmp196 - tmp191;
c_im(inout[5 * iostride]) = tmp197 + tmp198;
c_im(inout[13 * iostride]) = tmp198 - tmp197;
}
{
fftw_real tmp155;
fftw_real tmp167;
fftw_real tmp188;
fftw_real tmp190;
fftw_real tmp166;
fftw_real tmp189;
fftw_real tmp170;
fftw_real tmp185;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp151;
fftw_real tmp154;
fftw_real tmp186;
fftw_real tmp187;
ASSERT_ALIGNED_DOUBLE;
tmp151 = tmp7 - tmp18;
tmp154 = tmp152 - tmp153;
tmp155 = tmp151 + tmp154;
tmp167 = tmp151 - tmp154;
tmp186 = tmp41 - tmp30;
tmp187 = tmp180 - tmp177;
tmp188 = tmp186 + tmp187;
tmp190 = tmp187 - tmp186;
}
{
fftw_real tmp160;
fftw_real tmp165;
fftw_real tmp168;
fftw_real tmp169;
ASSERT_ALIGNED_DOUBLE;
tmp160 = tmp156 + tmp159;
tmp165 = tmp161 - tmp164;
tmp166 = K707106781 * (tmp160 + tmp165);
tmp189 = K707106781 * (tmp165 - tmp160);
tmp168 = tmp159 - tmp156;
tmp169 = tmp161 + tmp164;
tmp170 = K707106781 * (tmp168 - tmp169);
tmp185 = K707106781 * (tmp168 + tmp169);
}
c_re(inout[10 * iostride]) = tmp155 - tmp166;
c_re(inout[2 * iostride]) = tmp155 + tmp166;
c_re(inout[14 * iostride]) = tmp167 - tmp170;
c_re(inout[6 * iostride]) = tmp167 + tmp170;
c_im(inout[2 * iostride]) = tmp185 + tmp188;
c_im(inout[10 * iostride]) = tmp188 - tmp185;
c_im(inout[6 * iostride]) = tmp189 + tmp190;
c_im(inout[14 * iostride]) = tmp190 - tmp189;
}
{
fftw_real tmp43;
fftw_real tmp171;
fftw_real tmp182;
fftw_real tmp184;
fftw_real tmp90;
fftw_real tmp183;
fftw_real tmp174;
fftw_real tmp175;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp19;
fftw_real tmp42;
fftw_real tmp176;
fftw_real tmp181;
ASSERT_ALIGNED_DOUBLE;
tmp19 = tmp7 + tmp18;
tmp42 = tmp30 + tmp41;
tmp43 = tmp19 + tmp42;
tmp171 = tmp19 - tmp42;
tmp176 = tmp152 + tmp153;
tmp181 = tmp177 + tmp180;
tmp182 = tmp176 + tmp181;
tmp184 = tmp181 - tmp176;
}
{
fftw_real tmp66;
fftw_real tmp89;
fftw_real tmp172;
fftw_real tmp173;
ASSERT_ALIGNED_DOUBLE;
tmp66 = tmp54 + tmp65;
tmp89 = tmp77 + tmp88;
tmp90 = tmp66 + tmp89;
tmp183 = tmp89 - tmp66;
tmp172 = tmp157 + tmp158;
tmp173 = tmp162 + tmp163;
tmp174 = tmp172 - tmp173;
tmp175 = tmp172 + tmp173;
}
c_re(inout[8 * iostride]) = tmp43 - tmp90;
c_re(inout[0]) = tmp43 + tmp90;
c_re(inout[12 * iostride]) = tmp171 - tmp174;
c_re(inout[4 * iostride]) = tmp171 + tmp174;
c_im(inout[0]) = tmp175 + tmp182;
c_im(inout[8 * iostride]) = tmp182 - tmp175;
c_im(inout[4 * iostride]) = tmp183 + tmp184;
c_im(inout[12 * iostride]) = tmp184 - tmp183;
}
}
}
static const int twiddle_order[] =
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
fftw_codelet_desc fftw_twiddle_16_desc =
{
"fftw_twiddle_16",
(void (*)()) fftw_twiddle_16,
16,
FFTW_FORWARD,
FFTW_TWIDDLE,
352,
15,
twiddle_order,
};
| {
"alphanum_fraction": 0.5722776719,
"avg_line_length": 29.1405228758,
"ext": "c",
"hexsha": "b30c5d524b75be428125eba2db7be017f4d893bc",
"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/ftw_16.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/ftw_16.c",
"max_line_length": 119,
"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/ftw_16.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": 5636,
"size": 17834
} |
/* statistics/gsl_statistics_float.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Jim Davies, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_STATISTICS_FLOAT_H__
#define __GSL_STATISTICS_FLOAT_H__
#include <stddef.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
GSL_EXPORT double gsl_stats_float_mean (const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_variance (const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_sd (const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_variance_with_fixed_mean (const float data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_float_sd_with_fixed_mean (const float data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_float_absdev (const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_skew (const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_kurtosis (const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_lag1_autocorrelation (const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_covariance (const float data1[], const size_t stride1,const float data2[], const size_t stride2, const size_t n);
GSL_EXPORT double gsl_stats_float_variance_m (const float data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_float_sd_m (const float data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_float_absdev_m (const float data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_float_skew_m_sd (const float data[], const size_t stride, const size_t n, const double mean, const double sd);
GSL_EXPORT double gsl_stats_float_kurtosis_m_sd (const float data[], const size_t stride, const size_t n, const double mean, const double sd);
GSL_EXPORT double gsl_stats_float_lag1_autocorrelation_m (const float data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_float_covariance_m (const float data1[], const size_t stride1,const float data2[], const size_t stride2, const size_t n, const double mean1, const double mean2);
/* DEFINED FOR FLOATING POINT TYPES ONLY */
GSL_EXPORT double gsl_stats_float_wmean (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_wvariance (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_wsd (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_wvariance_with_fixed_mean (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_float_wsd_with_fixed_mean (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_float_wabsdev (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_wskew (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_wkurtosis (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_wvariance_m (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n, const double wmean);
GSL_EXPORT double gsl_stats_float_wsd_m (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n, const double wmean);
GSL_EXPORT double gsl_stats_float_wabsdev_m (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n, const double wmean);
GSL_EXPORT double gsl_stats_float_wskew_m_sd (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n, const double wmean, const double wsd);
GSL_EXPORT double gsl_stats_float_wkurtosis_m_sd (const float w[], const size_t wstride, const float data[], const size_t stride, const size_t n, const double wmean, const double wsd);
/* END OF FLOATING POINT TYPES */
GSL_EXPORT double gsl_stats_float_pvariance (const float data1[], const size_t stride1, const size_t n1, const float data2[], const size_t stride2, const size_t n2);
GSL_EXPORT double gsl_stats_float_ttest (const float data1[], const size_t stride1, const size_t n1, const float data2[], const size_t stride2, const size_t n2);
GSL_EXPORT float gsl_stats_float_max (const float data[], const size_t stride, const size_t n);
GSL_EXPORT float gsl_stats_float_min (const float data[], const size_t stride, const size_t n);
GSL_EXPORT void gsl_stats_float_minmax (float * min, float * max, const float data[], const size_t stride, const size_t n);
GSL_EXPORT size_t gsl_stats_float_max_index (const float data[], const size_t stride, const size_t n);
GSL_EXPORT size_t gsl_stats_float_min_index (const float data[], const size_t stride, const size_t n);
GSL_EXPORT void gsl_stats_float_minmax_index (size_t * min_index, size_t * max_index, const float data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_float_median_from_sorted_data (const float sorted_data[], const size_t stride, const size_t n) ;
GSL_EXPORT double gsl_stats_float_quantile_from_sorted_data (const float sorted_data[], const size_t stride, const size_t n, const double f) ;
__END_DECLS
#endif /* __GSL_STATISTICS_FLOAT_H__ */
| {
"alphanum_fraction": 0.793648427,
"avg_line_length": 70.6,
"ext": "h",
"hexsha": "352d0e94466692bf180059e2991ee735c2b7af39",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dynaryu/vaws",
"max_forks_repo_path": "src/core/gsl/include/gsl/gsl_statistics_float.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_statistics_float.h",
"max_line_length": 189,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dynaryu/vaws",
"max_stars_repo_path": "src/core/gsl/include/gsl/gsl_statistics_float.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1653,
"size": 6707
} |
/*
* author: Achim Gaedke
* created: May 2001
* file: pygsl/src/ieeemodule.c
* $Id: ieeemodule.c,v 1.7 2008/10/25 18:56:35 schnizer Exp $
*
*/
#include <pygsl/error_helpers.h>
#include <pygsl/general_helpers.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_errno.h>
/*
* constants definitions
*/
typedef struct {
char *name;
int flag;
} const_int_names;
static const_int_names ieeeConsts[] = {
/* used as precision argument in set_mode*/
{"single_precision",GSL_IEEE_SINGLE_PRECISION},
{"double_precision",GSL_IEEE_DOUBLE_PRECISION},
{"extended_precision",GSL_IEEE_EXTENDED_PRECISION},
/* used as round argument in set_mode*/
{"round_to_nearest",GSL_IEEE_ROUND_TO_NEAREST},
{"round_down",GSL_IEEE_ROUND_DOWN},
{"round_up",GSL_IEEE_ROUND_UP},
{"round_to_zero",GSL_IEEE_ROUND_TO_ZERO},
/* used as exception argument in set_mode*/
{"mask_invalid",GSL_IEEE_MASK_INVALID},
{"mask_denormalized",GSL_IEEE_MASK_DENORMALIZED},
{"mask_division_by_zero",GSL_IEEE_MASK_DIVISION_BY_ZERO},
{"mask_overflow",GSL_IEEE_MASK_OVERFLOW},
{"mask_underflow",GSL_IEEE_MASK_UNDERFLOW},
{"mask_all",GSL_IEEE_MASK_ALL},
{"trap_inexact",GSL_IEEE_TRAP_INEXACT},
/* used as type in ieee_*_rep */
{"type_nan",GSL_IEEE_TYPE_NAN},
{"type_inf",GSL_IEEE_TYPE_INF},
{"type_normal",GSL_IEEE_TYPE_NORMAL},
{"type_denormal",GSL_IEEE_TYPE_DENORMAL},
{"type_zero",GSL_IEEE_TYPE_ZERO},
/* sentinel */
{NULL,0}
};
static void define_const_ints(PyObject* module)
{
int i=0;
while (ieeeConsts[i].name!=NULL)
{
PyModule_AddIntConstant(module,ieeeConsts[i].name,ieeeConsts[i].flag);
i++;
}
return;
}
/*
* method definitions
*/
static PyObject*
set_mode(PyObject *self, PyObject *args)
{
int precision=2;
int rounding=1;
int exception_mask=GSL_IEEE_MASK_ALL;
int flag;
if (!PyArg_ParseTuple(args, "|iii", &precision, &rounding, &exception_mask))
return NULL;
flag = gsl_ieee_set_mode(precision, rounding, exception_mask);
if (GSL_SUCCESS != PyGSL_error_flag(flag))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
static PyObject*
env_setup(PyObject *self, PyObject *args)
{
gsl_ieee_env_setup();
Py_INCREF(Py_None);
return Py_None;
}
static PyObject*
bin_repr(PyObject *self, PyObject *args)
{
double x;
gsl_ieee_double_rep r;
if (!PyArg_ParseTuple(args,"d", &x))
return NULL;
gsl_ieee_double_to_rep(&x,&r);
return Py_BuildValue("(isii)",r.sign,r.mantissa,r.exponent,r.type);
}
static PyObject*
ieee_isnan(PyObject *self, PyObject *arg)
{
double tmp;
if(PyGSL_PYFLOAT_TO_DOUBLE(arg, &tmp, NULL) != GSL_SUCCESS)
return NULL;
return PyInt_FromLong(gsl_isnan(tmp));
}
static PyObject*
ieee_isinf(PyObject *self, PyObject *arg)
{
double tmp;
if(PyGSL_PYFLOAT_TO_DOUBLE(arg, &tmp, NULL) != GSL_SUCCESS)
return NULL;
return PyInt_FromLong(gsl_isinf(tmp));
}
static PyObject*
ieee_finite(PyObject *self, PyObject *arg)
{
double tmp;
if(PyGSL_PYFLOAT_TO_DOUBLE(arg, &tmp, NULL) != GSL_SUCCESS)
return NULL;
return PyInt_FromLong(gsl_finite(tmp));
}
static PyObject* ieee_nan(PyObject *self)
{
return PyFloat_FromDouble(GSL_NAN);
}
static PyObject* ieee_neginf(PyObject *self)
{
return PyFloat_FromDouble(GSL_NEGINF);
}
static PyObject* ieee_posinf(PyObject *self)
{
return PyFloat_FromDouble(GSL_POSINF);
}
/* setup gsl mode and ieee modes from environment variable GSL_IEEE_MODE */
static const char env_setup_doc[] =
"Set the IEEE mode, the GSL library should use, using the GSL_IEEE_MODE\n\
environement variable\n\
You can also use os.environ['GSL_IEEE_MODE']='<desired_behaviour>' to\n\
set the variable\n";
static const char bin_repr_doc[] =
"takes a double and returns its sign, mantissa, exponent and type\n";
static const char set_mode_doc[] =
"Sets the ieee float handling mode\n\
\tUsage:\n\
\tset_mode(precision, rounding, exception_mask)\n\
Each flag can be a combination of the constants defined in this module\n\
Raises gsl_NoHardwareSupportError if support is not available.\n\
\n\
WARNING: Use with care! It can abort your programm abnormaly!";
static const char ieee_nan_doc[] = "Returns not a number\n";
static const char ieee_neginf_doc[] = "Returns a negative infinite\n";
static const char ieee_posinf_doc[] = "Returns a positive infinite\n";
static PyMethodDef ieeeMethods[] = {
{"set_mode", set_mode, METH_VARARGS, (char*)set_mode_doc},
{"env_setup", env_setup, METH_NOARGS, (char *)env_setup_doc},
{"bin_repr", bin_repr, METH_VARARGS, NULL},
/* tests on special IEEE-FP meanings */
{"isnan",ieee_isnan,METH_O, NULL},
{"isinf",ieee_isinf,METH_O, NULL},
{"finite",ieee_finite,METH_O, NULL},
/* some special ieee-numbers */
{"nan",(PyCFunction)ieee_nan, METH_NOARGS, (char *)ieee_nan_doc},
{"neginf",(PyCFunction)ieee_neginf, METH_NOARGS, (char *)ieee_neginf_doc},
{"posinf",(PyCFunction)ieee_posinf, METH_NOARGS, (char *)ieee_posinf_doc},
{NULL, NULL} /* Sentinel */
};
DL_EXPORT(void) initieee(void)
{
PyObject* m;
m=Py_InitModule("ieee", ieeeMethods);
init_pygsl();
define_const_ints(m);
return;
}
| {
"alphanum_fraction": 0.7248024668,
"avg_line_length": 26.4744897959,
"ext": "c",
"hexsha": "78d1a003aa2117ee54254b34c2c1c7b433c573e7",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/src/ieeemodule.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/src/ieeemodule.c",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/src/ieeemodule.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1478,
"size": 5189
} |
#include "defines.h"
#include <string.h>
#include "lib.h"
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <sys/types.h>
#include <sys/stat.h>
extern REAL * opa;
extern int NTERMS;
/**
* @param float * w
* @param float * sig
* @param float * spectro
* @param int nspectro
* @param float * spectra
* @param float * d_spectra
* @param float * beta
* @param float * alpha
*
* */
int covarm(REAL *w,REAL *sig,float *spectro,int nspectro,REAL *spectra,REAL *d_spectra,REAL *beta,REAL *alpha){
int j,i,bt_nf,bt_nc,aux_nf,aux_nc;
REAL AP[NTERMS*NTERMS*NPARMS],BT[NPARMS*NTERMS];
REAL *BTaux,*APaux;
//printf("\nVALORES DEL SIGMA SQUARE\n");
for(j=0;j<NPARMS;j++){
for(i=0;i<nspectro;i++){
opa[i]= w[j]*(spectra[i+nspectro*j]-spectro[i+nspectro*j]);
}
BTaux=BT+(j*NTERMS);
APaux=AP+(j*NTERMS*NTERMS);
multmatrixIDLValueSigma(opa,nspectro,1,d_spectra+j*nspectro*NTERMS,NTERMS,nspectro,BTaux,&bt_nf,&bt_nc,sig+(nspectro*j)); //bt de tam NTERMS x 1
multmatrix_transpose_sigma(d_spectra+j*nspectro*NTERMS,NTERMS,nspectro,d_spectra+j*nspectro*NTERMS,NTERMS,nspectro,APaux,&aux_nf,&aux_nc,w[j], sig+(nspectro*j));//ap de tam NTERMS x NTERMS
}
totalParcialf(BT,NPARMS,NTERMS,beta); //beta de tam 1 x NTERMS
totalParcialMatrixf(AP,NTERMS,NTERMS,NPARMS,alpha); //alpha de tam NTERMS x NTERMS
return 1;
}
/**
* @param REAL * W
* @param REAL * sig
* @param float * spectro
* @param int nspectro
* @param REAL * spectra
* @param REAL * d_spectra
* @param REAL * beta
* @param REAL * alpha
*
* */
int covarm2(REAL *w,REAL *sig,float *spectro,int nspectro,REAL *spectra,REAL *d_spectra,REAL *beta,REAL *alpha){
int j,i,h,k,aux_nf,aux_nc;
REAL AP[NTERMS*NTERMS*NPARMS],BT[NPARMS*NTERMS];
REAL *BTaux,*APaux;
REAL sum,sum2;
for(j=0;j<NPARMS;j++){
for(i=0;i<nspectro;i++){
opa[i]= w[j]*(spectra[i+nspectro*j]-spectro[i+nspectro*j]);
}
BTaux=BT+(j*NTERMS);
APaux=AP+(j*NTERMS*NTERMS);
for ( i = 0; i < NTERMS; i++){
for ( h = 0; h < NTERMS; h++){
sum=0;
if(i==0){
sum2=0;
}
for ( k = 0; k < nspectro; k++){
REAL dAux = (*(d_spectra+j*nspectro*NTERMS+h*nspectro+k));
sum += (*(d_spectra+j*nspectro*NTERMS+i*nspectro+k) * dAux ) * (w[j]/sig[nspectro*j+k]);
if(i==0){
sum2+= ((opa[k] * dAux ))/sig[nspectro*j+k];
}
}
APaux[NTERMS*i+h] = sum;
if(i==0){
BTaux[h] = sum2;
}
}
}
}
totalParcialf(BT,NPARMS,NTERMS,beta); //beta de tam 1 x NTERMS
totalParcialMatrixf(AP,NTERMS,NTERMS,NPARMS,alpha); //alpha de tam NTERMS x NTERMS
return 1;
}
/**
* @param spectra: array with synthetic spectro
* @param nspectro: size of spectro
* @param spectro: original spectro
* @param w: array of weight for I,Q,U,V
* @param sig: array with sigma for I,Q,U,V
* @param nfree: (nspectro * NPARMS) - NTERMS, NPARAMs is 4 and NTERMS 11.
* */
REAL fchisqr(REAL * spectra,int nspectro,float *spectro,REAL *w,REAL *sig,REAL nfree){
REAL TOT,dif1,dif2,dif3,dif4;
REAL opa1,opa2,opa3,opa4;
int i,j;
TOT=0;
opa1=0;
opa2=0;
opa3=0;
opa4=0;
for(i=0;i<nspectro;i++){
dif1=spectra[i]-spectro[i];
dif2=spectra[i+nspectro]-spectro[i+nspectro];
dif3=spectra[i+nspectro*2]-spectro[i+nspectro*2];
dif4=spectra[i+nspectro*3]-spectro[i+nspectro*3];
opa1+= (((dif1*dif1)*w[0])/(sig[i]));
opa2+= (((dif2*dif2)*w[1])/(sig[i+nspectro]));
opa3+= (((dif3*dif3)*w[2])/(sig[i+nspectro*2]));
opa4+= (((dif4*dif4)*w[3])/(sig[i+nspectro*3]));
}
TOT+= opa1+opa2+opa3+opa4;
return TOT/nfree;
}
/*
Multiplica la matriz a (tamaño naf,nac)
por la matriz b (de tamaño nbf,nbc)
al estilo IDL, es decir, filas de a por columnas de b,
el resultado se almacena en resultOut (de tamaño fil,col)
El tamaño de salida (fil,col) corresponde con (nbf,nac).
El tamaño de columnas de b, nbc, debe de ser igual al de filas de a, naf.
*/
/**
* @param REAL * a
* @param int naf
* @param int nac
* @param REAL * b
* @param int nbf
* @param int nbc
* @param REAL * result
* @param int * fil
* @param int * col
* @param REAL value
* */
int multmatrixIDLValue(REAL *a,int naf,int nac,REAL *b,int nbf,int nbc,REAL *result,int *fil,int *col,REAL value){
int i,j,k;
REAL sum;
if(naf==nbc){
(*fil)=nbf;
(*col)=nac;
for ( i = 0; i < nbf; i++){
for ( j = 0; j < nac; j++){
sum=0;
for ( k = 0; k < naf; k++){
sum += a[k*nac+j] * b[i*nbc+k];
}
result[((nac)*i)+j] = sum/value;
}
}
return 1;
}
else
printf("\n \n Error en multmatrixIDLValue no coinciden nac y nbf!!!! ..\n\n");
return 0;
}
/**
*
* */
int multmatrixIDLValueSigma(REAL *a,int naf,int nac,REAL *b,int nbf,int nbc,REAL *result,int *fil,int *col, REAL * sigma){
int i,j,k;
REAL sum;
if(naf==nbc){
(*fil)=nbf;
(*col)=nac;
for ( i = 0; i < nbf; i++){
sum=0;
for ( k = 0; k < naf; k++){
sum += (((a[k] * b[i*nbc+k])))/sigma[k];
}
result[i] = sum;
}
return 1;
}
else
printf("\n \n Error en multmatrixIDLValue no coinciden nac y nbf!!!! ..\n\n");
return 0;
}
/**
* @param REAL * A
* @param int f
* @param int c
* @param REAL * result
* */
void totalParcialf(REAL * A, int f,int c,REAL * result){
int i,j;
REAL sum;
for(i=0;i<c;i++){
sum = 0;
for(j=0;j<f;j++){
sum+=A[j*c+i];
}
result[i] = sum;
}
}
/**
* @param REAL * A
* @param int f
* @param int c
* @param int p
* @param REAL * result
* */
void totalParcialMatrixf(REAL * A, int f,int c,int p,REAL *result){
int i,j,k;
REAL sum;
for(i=0;i<f;i++)
for(j=0;j<c;j++){
sum=0;
for(k=0;k<p;k++)
sum+=A[i*c+j+f*c*k];
result[i*c+j] = sum;
}
}
/**
* @param PRECISION * a
* @param int naf
* @param int nac
* @param PRECISION * b
* @param int nbf
* @param int nbc
* @param PRECISION * result
* @param int * fil
* @param int * col
*
* Multiply matrix "a"(naf,nac) with matrix "b" (nbf,nbc). Algebraic matrix multiplication style, that is,
* columns of "a" by rows of "b". The result is stored in "result"(fil,col).
* The size of columns of "a", nac, must be the same of rows of "b", nbf.
* */
int multmatrix(PRECISION *a,int naf,int nac, PRECISION *b,int nbf,int nbc,PRECISION *result,int *fil,int *col){
int i,j,k;
PRECISION sum;
if(nac==nbf){
(*fil)=naf;
(*col)=nbc;
for ( i = 0; i < naf; i++)
for ( j = 0; j < nbc; j++){
sum=0;
for ( k = 0; k < nbf; k++){
sum += a[i*nac+k] * b[k*nbc+j];
}
result[(*col)*i+j] = sum;
}
return 1;
}
return 0;
}
/**
* @param REAL * a
* @param int naf
* @param int nac
* @param REAL *b
* @param int nbf
* @param int nbc
* @param REAL * result
* @param int * fil
* @param int * col
* @param REAL value
* */
int multmatrix_transpose(REAL *a,int naf,int nac, REAL *b,int nbf,int nbc,REAL *result,int *fil,int *col,REAL value){
int i,j,k;
REAL sum;
if(nac==nbc){
(*fil)=naf;
(*col)=nbf;
for ( i = 0; i < naf; i++){
for ( j = 0; j < nbf; j++){
sum=0;
for ( k = 0; k < nbc; k++){
sum += a[i*nac+k] * b[j*nbc+k];
}
result[(*col)*i+j] = (sum)*value;
}
}
return 1;
}else{
printf("\n \n Error en multmatrix_transpose no coinciden nac y nbc!!!! ..\n\n");
}
return 0;
}
/**
* @param REAL * a
* @param int naf
* @param int nac
* @param REAL *b
* @param int nbf
* @param int nbc
* @param REAL * result
* @param int * fil
* @param int * col
* @param REAL weigth
* @param REAL * sigma
*
* */
int multmatrix_transpose_sigma(REAL *a,int naf,int nac, REAL *b,int nbf,int nbc,REAL *result,int *fil,int *col,REAL weigth, REAL * sigma){
int i,j,k;
REAL sum;
if(nac==nbc){
(*fil)=naf;
(*col)=nbf;
for ( i = 0; i < naf; i++){
for ( j = 0; j < nbf; j++){
sum=0;
for ( k = 0; k < nbc; k++){
sum += (a[i*nac+k] * b[j*nbc+k]) * (weigth/sigma[k]);
}
result[(*col)*i+j] = sum;
}
}
return 1;
}else{
printf("\n \n Error en multmatrix_transpose no coinciden nac y nbc!!!! ..\n\n");
}
return 0;
}
//Media de un vector de longitud numl
/**
* @param int nspectro
*/
int CalculaNfree(int nspectro)
{
int nfree;
nfree = 0;
nfree = (nspectro * NPARMS) - NTERMS;
return nfree;
}
/**
* @param const char * path
* */
int isDirectory(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) != 0)
return 0;
return S_ISDIR(statbuf.st_mode);
}
/**
* @param tpuntero * cabeza
* @param char * fileName
* */
void insert_in_linked_list (tpuntero *cabeza, char * fileName){
tpuntero nuevo;
nuevo = malloc(sizeof(tnodo));
strcpy(nuevo->d_name,fileName);
nuevo->next = *cabeza;
*cabeza = nuevo;
}
/**
* @param tpuntero cabeza
* @param char * fileName
* */
int checkNameInLista(tpuntero cabeza,char * fileName){
int found = 0;
while(cabeza != NULL && !found){ //Mientras cabeza no sea NULL
if(strcmp(cabeza->d_name,fileName)==0)
found = 1;
else
cabeza = cabeza->next; //Pasamos al siguiente nodo
}
return found;
}
/**
* @param tpuntero * cabeza
* */
void deleteList(tpuntero *cabeza){
tpuntero actual; //Puntero auxiliar para eliminar correctamente la lista
while(*cabeza != NULL){ //Mientras cabeza no sea NULL
actual = *cabeza; //Actual toma el valor de cabeza
*cabeza = (*cabeza)->next; //Cabeza avanza 1 posicion en la lista
free(actual); //Se libera la memoria de la posicion de Actual (el primer nodo), y cabeza queda apuntando al que ahora es el primero
}
} | {
"alphanum_fraction": 0.5893586601,
"avg_line_length": 21.3333333333,
"ext": "c",
"hexsha": "5041c1603e6a041d2c47df6c11f0c106460b6aeb",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-09-09T19:10:00.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-14T12:12:02.000Z",
"max_forks_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dcalc/hrt_pipeline",
"max_forks_repo_path": "p-milos/src/lib.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178",
"max_issues_repo_issues_event_max_datetime": "2022-03-24T14:18:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-11-05T14:03:07.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dcalc/hrt_pipeline",
"max_issues_repo_path": "p-milos/src/lib.c",
"max_line_length": 190,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dcalc/hrt_pipeline",
"max_stars_repo_path": "p-milos/src/lib.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3614,
"size": 9792
} |
/* BRAINS
* (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling
* Yan-Rong Li, liyanrong@ihep.ac.cn
* Thu, Aug 4, 2016
*/
/*!
* \file sim.c
* \brief generate mocked 2d data.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stddef.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_interp.h>
#include <mpi.h>
#include "brains.h"
/////////////////////////////////////////////////////////////////////////////////
#ifdef SpecAstro
/* baselines for 3C 273 dataset observed by the GRAVITY (Nature, 2020, 563, 657),
* unit is meter */
int n_base_sa_3c273 = 24;
double base_sa_3c273[]={
-39.847287, 18.757261,
-72.901618, -13.864206,
-105.767452, -59.897942,
-32.453674, -32.669331,
-64.714063, -78.769286,
-32.064961, -46.108491,
-53.774627, 21.045077,
-71.062525, -10.421538,
-79.670158, -55.520144,
-16.867270, -31.447448,
-25.151512, -76.555774,
-8.846202, -45.116789,
-54.064283, 19.430318,
-86.349699, -12.827258,
-115.711019, -58.525511,
-32.484928, -32.180585,
-61.579109, -77.881063,
-29.231494, -45.704607,
-52.779207, 21.321411,
-83.468788, -12.802497,
-107.827509, -59.908816,
-28.601448, -33.449429,
-50.961674, -81.626333,
-23.699820, -46.979455
};
#endif
//////////////////////////////////////////////////////////////////////////////////////
void *model;
void sim()
{
if(thistask != roottask)
return;
FILE *fp;
char fname[200];
int i, j, incr;
sim_init();
double *pm = (double *)model, error, fcon;
smooth_init(parset.n_vel_recon, TransV);
if(parset.flag_dim == -1)
{
/* note that here use sigma_hat = sigma/sqrt(tau) */
printf("sim with ln(sigma) = %f and ln(taud) = %f.\n", var_param[1], var_param[2]);
reconstruct_con_from_varmodel(exp(var_param[1]), exp(var_param[2]), 1.0, 0.0);
}
else
{
con_scale = 1.0;
line_scale = 1.0;
line_error_mean = con_error_mean = 0.01;
/* arguments: sigma_hat, tau, alapha, and syserr */
create_con_from_random(0.03, 45.0, 1.0, 0.0);
}
calculate_con_rm(model);
sprintf(fname, "%s/%s", parset.file_dir, "/data/sim_con_full.txt");
fp = fopen(fname, "w");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s\n", fname);
exit(-1);
}
for(i=0; i<parset.n_con_recon; i++)
{
fprintf(fp, "%e %e %e\n", Tcon[i]*(1.0+parset.redshift), Fcon[i]/con_scale, Fcerrs[i]/con_scale);
}
fclose(fp);
sprintf(fname, "%s/%s", parset.file_dir, "/data/sim_con.txt");
fp = fopen(fname, "w");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s\n", fname);
exit(-1);
}
if(parset.flag_dim != -2)
{
gsl_interp_init(gsl_linear, Tcon, Fcon, parset.n_con_recon);
for(i=0; i<n_con_data; i++)
{
//fprintf(fp, "%f %f %f\n", Tcon[i], Fcon[i]/con_scale, Fcerrs[i]/con_scale);
fcon = gsl_interp_eval(gsl_linear, Tcon, Fcon, Tcon_data[i], gsl_acc);
fprintf(fp, "%e %e %e\n", Tcon_data[i]*(1.0+parset.redshift),
(fcon+gsl_ran_ugaussian(gsl_r)*con_error_mean)/con_scale, con_error_mean/con_scale);
}
}
else
{
incr = fmax(0.5/(Tcon[1]-Tcon[0]), 1.0); //cadence to be 0.5day or increasement to be 1
for(i=0; i<parset.n_con_recon; i+=incr)
{
if(Tcon[i] >= 0.0)
{
fprintf(fp, "%e %e %e\n", Tcon[i]*(1.0+parset.redshift), Fcon[i]/con_scale, Fcerrs[i]/con_scale);
}
}
}
fclose(fp);
gsl_interp_init(gsl_linear, Tcon, Fcon_rm, parset.n_con_recon);
transfun_1d_cal(model, 0);
calculate_line_from_blrmodel(model, Tline, Fline, parset.n_line_recon);
sprintf(fname, "%s/%s", parset.file_dir, "/data/sim_line.txt");
fp = fopen(fname, "w");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s\n", fname);
exit(-1);
}
if(parset.flag_dim == -1)
{
error = line_error_mean * sqrt(n_line_data) * (Vline_data[1] - Vline_data[0]);
}
else
{
error = line_error_mean;
}
for(i=0; i<parset.n_line_recon; i++)
{
fprintf(fp, "%e %e %e\n", Tline[i]*(1.0+parset.redshift), Fline[i]/line_scale + gsl_ran_ugaussian(gsl_r)*error/line_scale,
error/line_scale);
}
// output transfer function.
sprintf(fname, "%s/%s", parset.file_dir, parset.tran_out_file);
fp = fopen(fname, "w");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s\n", fname);
exit(-1);
}
for(i=0; i<parset.n_tau; i++)
{
fprintf(fp, "%e %e\n", TransTau[i], Trans1D[i]);
}
fclose(fp);
transfun_2d_cal(model, TransV, Trans2D, parset.n_vel_recon, 1);
calculate_line2d_from_blrmodel(model, Tline, TransV,
Trans2D, Fline2d, parset.n_line_recon, parset.n_vel_recon);
sprintf(fname, "%s/%s", parset.file_dir, "/data/sim_line2d.txt");
fp = fopen(fname, "w");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s\n", fname);
exit(-1);
}
fprintf(fp, "# %d %d\n", parset.n_line_recon, parset.n_vel_recon);
for(i=0; i<parset.n_line_recon; i++)
{
fprintf(fp, "# %f\n", Tline[i]*(1.0+parset.redshift));
for(j=0; j<parset.n_vel_recon; j++)
{
fprintf(fp, "%e %e %e\n", TransW[j],
(Fline2d[i*parset.n_vel_recon + j] + gsl_ran_ugaussian(gsl_r)*line_error_mean*0.3)/line_scale, line_error_mean/line_scale);
}
fprintf(fp, "\n");
}
fclose(fp);
sprintf(fname, "%s/%s", parset.file_dir, "/data/sim_broadening.txt");
fp = fopen(fname, "w");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s\n", fname);
exit(-1);
}
for(i=0; i<parset.n_line_recon; i++)
{
fprintf(fp, "%f %f\n", parset.InstRes * VelUnit, parset.InstRes_err * VelUnit);
}
fclose(fp);
// output 2d transfer function
sprintf(fname, "%s/%s", parset.file_dir, parset.tran2d_out_file);
fp = fopen(fname, "w");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s\n", fname);
exit(-1);
}
fprintf(fp, "# %d %d\n", parset.n_tau, parset.n_vel_recon);
for(i=0; i<parset.n_tau; i++)
{
for(j=0; j<parset.n_vel_recon; j++)
{
fprintf(fp, "%e %e %e\n", TransV[j]*VelUnit, TransTau[i], Trans2D[i*parset.n_vel_recon + j]);
}
fprintf(fp, "\n");
}
fclose(fp);
#ifdef SpecAstro
double *sa_pm;
sa_pm = (double *)pm + num_params_blr;
sa_smooth_init(parset.n_sa_vel_recon, vel_sa, parset.sa_InstRes);
gen_sa_cloud_sample((void *)sa_pm, 3, 0);
calculate_sa_sim_with_sample(pm, vel_sa, parset.n_sa_vel_recon, base_sa, parset.n_sa_base_recon,
phase_sa, Fline_sa);
sprintf(fname, "%s/%s", parset.file_dir, "data/sim_sa.txt");
fp = fopen(fname, "w");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s.\n", fname);
exit(0);
}
// output sa line
fprintf(fp, "# %d %d %d\n", 1, parset.n_sa_vel_recon, parset.n_sa_base_recon);
for(j=0; j<parset.n_sa_vel_recon; j++)
{
fprintf(fp, "%e %e %e\n", wave_sa[j], Fline_sa[j] + gsl_ran_ugaussian(gsl_r)*sa_line_error_mean, sa_line_error_mean);
}
fprintf(fp, "\n");
for(i=0; i<parset.n_sa_base_recon; i++)
{
fprintf(fp, "# %f %f\n", base_sa[i*2], base_sa[i*2+1]);
for(j=0; j<parset.n_sa_vel_recon; j++)
{
fprintf(fp, "%e %e %e\n", wave_sa[j],
phase_sa[i*parset.n_sa_vel_recon + j]/(PhaseFactor * wave_sa[j]) + gsl_ran_ugaussian(gsl_r)*sa_phase_error_mean,
sa_phase_error_mean);
}
fprintf(fp, "\n");
}
fclose(fp);
sa_smooth_end();
#endif
smooth_end();
sim_end();
}
void sim_init()
{
int i, j, idx;
double dT, Tspan;
double *pm, Rblr, mbh;
switch(parset.flag_blrmodel)
{
case -1:
num_params_blr_model = num_params_MyTransfun2d;
transfun_1d_cal = transfun_1d_cal_mytransfun;
transfun_2d_cal = transfun_2d_cal_mytransfun;
break;
case 0:
num_params_blr_model = num_params_MyBLRmodel2d;
gen_cloud_sample = gen_cloud_sample_mymodel;
transfun_1d_cal = transfun_1d_cal_cloud;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 1:
num_params_blr_model = sizeof(BLRmodel1)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model1;
transfun_1d_cal = transfun_1d_cal_cloud;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 2:
num_params_blr_model = sizeof(BLRmodel2)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model2;
transfun_1d_cal = transfun_1d_cal_cloud;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 3:
num_params_blr_model = sizeof(BLRmodel3)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model3;
transfun_1d_cal = transfun_1d_cal_cloud;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 4:
num_params_blr_model = sizeof(BLRmodel4)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model4;
transfun_1d_cal = transfun_1d_cal_cloud;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 5:
num_params_blr_model = sizeof(BLRmodel5)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model5;
transfun_1d_cal = transfun_1d_cal_cloud;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 6:
num_params_blr_model = sizeof(BLRmodel6)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model6;
transfun_1d_cal = transfun_1d_cal_cloud;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 7:
num_params_blr_model = sizeof(BLRmodel7)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model7;
transfun_1d_cal = transfun_1d_cal_cloud;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 8:
num_params_blr_model = sizeof(BLRmodel8)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model8;
transfun_1d_cal = transfun_1d_cal_cloud;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
case 9:
num_params_blr_model = sizeof(BLRmodel9)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model9;
transfun_1d_cal = transfun_1d_cal_cloud;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
default:
num_params_blr_model = sizeof(BLRmodel1)/sizeof(double);
gen_cloud_sample = gen_cloud_sample_model1;
transfun_1d_cal = transfun_1d_cal_cloud;
transfun_2d_cal = transfun_2d_cal_cloud;
break;
}
#ifdef SpecAstro
set_sa_blr_model();
/* SA */
num_params_sa_blr = num_params_sa_blr_model + num_params_sa_extpar;
num_params_sa = num_params_sa_blr;
#endif
/* use epoch-independent broadening */
if(parset.flag_InstRes > 1)
{
num_params_res = 1;
parset.InstRes = 220.0/VelUnit;
parset.InstRes_err = 0.0;
}
else
{
parset.InstRes /= VelUnit;
parset.InstRes_err = 0.0;
}
if(parset.flag_narrowline > 1)
{
printf("# set flag_narrowline to 1.\n");
parset.flag_narrowline = 1;
}
else if(parset.flag_narrowline == 0)
{
parset.width_narrowline = 0.0;
}
parset.flag_linecenter = 0;
num_params_linecenter = 0;
parset.num_particles = 1;
which_particle_update = 0;
force_update = 1;
which_parameter_update = -1;
num_params_blr = num_params_blr_model + num_params_nlr
+ num_params_res + num_params_linecenter + 1; /* include line sys err */
num_params_var = num_params_drw + num_params_trend + num_params_difftrend + num_params_resp;
num_params_blr_tot = num_params_blr;
#ifdef SpecAstro
num_params_blr_tot += num_params_sa_blr;
#endif
num_params = num_params_blr_tot + num_params_var + parset.n_con_recon;
/* index of A and Ag */
idx_resp = num_params_blr_tot + num_params_drw + num_params_trend;
/* index of different trend */
idx_difftrend = idx_resp + num_params_resp;
model = malloc(num_params * sizeof(double));
par_fix = (int *) malloc(num_params * sizeof(int));
par_fix_val = (double *) malloc(num_params * sizeof(double));
/* setup parameters */
pm = (double *)model;
if(parset.flag_blrmodel == -1)
{
set_par_value_mytransfun_sim(pm);
}
else
{
set_par_value_sim(pm, parset.flag_blrmodel);
set_par_fix_blrmodel();
for(i=0; i<num_params_blr_model; i++)
{
if(par_fix[i] == 1)
{
pm[i] = par_fix_val[i];
}
}
}
/* spectral broadening, note this is a deviation from the input value */
pm[num_params_blr_model + num_params_nlr ] = 0.0;
pm[idx_resp + 0] = log(1.0); //A
pm[idx_resp + 1] = 0.0; //Ag
#ifdef SpecAstro
double *sa_model = pm + num_params_blr;
set_idx_par_mutual();
set_par_value_sim(sa_model, parset.flag_sa_blrmodel);
set_par_fix_sa_blrmodel();
for(i=0; i<num_params_sa_blr_model; i++)
{
if(par_fix[num_params_blr + i] == 1)
{
pm[num_params_blr + i] = par_fix_val[num_params_blr + i];
}
}
/* set the same mbh and inc */
sa_model[idx_sa_par_mutual[0]] = pm[idx_rm_par_mutual[0]]; //mbh
sa_model[idx_sa_par_mutual[1]] = pm[idx_rm_par_mutual[1]]; //inc
sa_model[num_params_sa_blr_model] = log(550.0); //DA
sa_model[num_params_sa_blr_model + 1] = 0.0; //PA
sa_model[num_params_sa_blr_model + 2] = 0.0; //FA
sa_model[num_params_sa_blr_model + 3] = 0.0; //CO
#endif
Fcon = malloc(parset.n_con_recon * sizeof(double));
Fcon_rm = malloc(parset.n_con_recon * sizeof(double));
idx = get_idx_mbh_from_blrmodel();
mbh = exp(pm[idx]);
if(parset.flag_blrmodel != 8) /* model 8 is particular */
{
Rblr = exp(pm[0]);
}
else
{
Rblr = exp(pm[9]);
}
if(parset.flag_dim == -1)
{
Tspan = Tcon_data[n_con_data -1] - Tcon_data[0];
/* set time array for continuum */
Tcon_min = Tcon_data[0] - time_back_set - 10.0;
Tcon_max = fmax(Tcon_data[n_con_data-1], Tline_data[n_line_data-1]) + fmax(0.05*Tspan, 10.0);
dT = (Tcon_max - Tcon_min)/(parset.n_con_recon -1);
for(i=0; i<parset.n_con_recon; i++)
{
Tcon[i] = Tcon_min + i*dT;
}
}
else
{
Tspan = Rblr*10.0;
rcloud_min_set = 0.0;
rcloud_max_set = Tspan/2.0;
if(parset.rcloud_max > 0.0)
rcloud_max_set = fmin(rcloud_max_set, parset.rcloud_max);
printf("RM rcloud_min_max_set: %f %f\n", rcloud_min_set, rcloud_max_set);
time_back_set = 2.0*rcloud_max_set;
Tcon_min = 0.0 - time_back_set - 10.0;
Tcon_max = Tspan + 10.0;
dT = (Tcon_max - Tcon_min)/(parset.n_con_recon -1);
for(i=0; i<parset.n_con_recon; i++)
{
Tcon[i] = Tcon_min + i*dT;
}
}
/* set Larr_rec */
for(i=0;i<parset.n_con_recon;i++)
{
Larr_rec[i*nq + 0]=1.0;
for(j=1; j<nq; j++)
Larr_rec[i*nq + j] = pow(Tcon[i], j);
}
if(parset.flag_dim == -1)
{
parset.n_line_recon = n_line_data;
parset.n_vel_recon = n_vel_data;
}
TransTau = malloc(parset.n_tau * sizeof(double));
TransV = malloc(parset.n_vel_recon * sizeof(double));
TransW = malloc(parset.n_vel_recon * sizeof(double));
Trans1D = malloc(parset.n_tau * sizeof(double));
Trans2D = malloc(parset.n_tau * parset.n_vel_recon * sizeof(double));
Tline = malloc(parset.n_line_recon * sizeof(double));
Fline = malloc(parset.n_line_recon * sizeof(double));
Fline2d = malloc(parset.n_line_recon * parset.n_vel_recon * sizeof(double));
if(parset.flag_dim == -1)
{
memcpy(Tline, Tline_data, n_line_data * sizeof(double));
memcpy(TransV, Vline_data, n_vel_data * sizeof(double));
memcpy(TransW, Wline_data, n_vel_data * sizeof(double));
}
else
{
Tline_min = 0.0;
Tline_max = Tcon_max - 1.0;
dT = (Tline_max - Tline_min)/(parset.n_line_recon - 1);
for(i=0; i<parset.n_line_recon; i++)
{
Tline[i] = Tline_min + i*dT;
}
double vel_max_set, vel_min_set;
vel_max_set = sqrt(pow(2.0*sqrt(mbh/Rblr), 2.0) + pow(2.0*parset.InstRes, 2.0));
vel_min_set = - vel_max_set;
double dVel = (vel_max_set- vel_min_set)/(parset.n_vel_recon -1.0);
for(i=0; i<parset.n_vel_recon; i++)
{
TransV[i] = vel_min_set + dVel*i;
TransW[i] = (1.0 + TransV[i]/C_Unit) * parset.linecenter * (1.0+parset.redshift);
}
}
clouds_tau = malloc(parset.n_cloud_per_task * sizeof(double));
clouds_weight = malloc(parset.n_cloud_per_task * sizeof(double));
clouds_vel = malloc(parset.n_cloud_per_task * parset.n_vel_per_cloud * sizeof(double));
if(parset.flag_save_clouds && thistask == roottask)
{
if(parset.n_cloud_per_task <= 1000)
icr_cloud_save = 1;
else
icr_cloud_save = parset.n_cloud_per_task/1000;
char fname[200];
sprintf(fname, "%s/%s", parset.file_dir, parset.cloud_out_file);
fcloud_out = fopen(fname, "w");
if(fcloud_out == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s\n", fname);
exit(-1);
}
}
#ifdef SpecAstro
double saRblr;
if(parset.flag_dim == -1)
{
parset.n_sa_vel_recon = n_vel_sa_data;
parset.n_sa_base_recon = n_base_sa_data;
}
else
{
sa_flux_norm = 1.0;
parset.n_sa_vel_recon = 40;
if(parset.flag_gravity == 1)
parset.n_sa_base_recon = n_base_sa_3c273;
else
parset.n_sa_base_recon = 20;
sa_phase_error_mean = 0.01;
sa_line_error_mean = 0.01;
}
vel_sa = malloc(parset.n_sa_vel_recon * sizeof(double));
wave_sa = malloc(parset.n_sa_vel_recon * sizeof(double));
Fline_sa = malloc(parset.n_sa_vel_recon * sizeof(double));
base_sa = malloc(parset.n_sa_base_recon * 2 * sizeof(double));
phase_sa = malloc(parset.n_sa_vel_recon * parset.n_sa_base_recon * sizeof(double));
clouds_alpha = malloc(parset.n_cloud_per_task * sizeof(double));
clouds_beta = malloc(parset.n_cloud_per_task * sizeof(double));
workspace_phase = malloc(parset.n_sa_vel_recon * 3 * sizeof(double));
if(parset.flag_sa_blrmodel != 8)
{
saRblr = exp(pm[num_params_blr]);
}
else
{
saRblr = exp(pm[num_params_blr + 9]);
}
rcloud_max_set = fmax(rcloud_max_set, saRblr * 5.0);
printf("SA rcloud_min_max_set: %f %f\n", rcloud_min_set, rcloud_max_set);
if(parset.flag_dim == -1)
{
memcpy(vel_sa, vel_sa_data, parset.n_sa_vel_recon * sizeof(double));
memcpy(wave_sa, wave_sa_data, parset.n_sa_vel_recon * sizeof(double));
memcpy(base_sa, base_sa_data, parset.n_sa_base_recon * 2 * sizeof(double));
}
else
{
double vel_max_set, vel_min_set;
vel_max_set = sqrt(pow(2.0*sqrt(mbh/saRblr), 2.0) + pow(2.0*parset.sa_InstRes, 2.0));
vel_min_set = - vel_max_set;
double dVel = (vel_max_set- vel_min_set)/(parset.n_sa_vel_recon -1.0);
for(i=0; i<parset.n_sa_vel_recon; i++)
{
vel_sa[i] = vel_min_set + dVel*i;
wave_sa[i] = (1.0 + vel_sa[i]/C_Unit) * parset.sa_linecenter * (1.0+parset.redshift);
}
if(parset.flag_gravity == 1)
memcpy(base_sa, base_sa_3c273, n_base_sa_3c273*2*sizeof(double));
else
{
double phi;
for(i=0; i<parset.n_sa_base_recon; i++)
{
phi = -PI/2.0 + PI/parset.n_sa_base_recon * i;
base_sa[i*2+0] = 100.0*cos(phi);
base_sa[i*2+1] = 100.0*sin(phi);
}
}
}
#endif
return;
}
void sim_end()
{
free(model);
free(par_fix);
free(par_fix_val);
free(Fcon);
free(Fcon_rm);
free(TransTau);
free(TransV);
free(TransW);
free(Tline);
free(Fline);
free(Fline2d);
free(Trans2D);
free(Trans1D);
free(clouds_tau);
free(clouds_weight);
free(clouds_vel);
if(parset.flag_save_clouds && thistask == roottask)
{
fclose(fcloud_out);
}
#ifdef SpecAstro
free(vel_sa);
free(wave_sa);
free(Fline_sa);
free(base_sa);
free(phase_sa);
free(clouds_alpha);
free(clouds_beta);
free(workspace_phase);
#endif
}
/*
* set parameter values for either RM or SA
*/
void set_par_value_sim(double *pm, int flag_model)
{
int i;
switch(flag_model)
{
case 0:
set_par_value_mymodel_sim(pm);
break;
case 1:
i=0;
pm[i++] = log(4.0);
pm[i++] = 0.9;
pm[i++] = 0.2;
pm[i++] = cos(20.0/180.0*PI);
pm[i++] = 40.0;
pm[i++] = 0.0;
pm[i++] = log(3.0);
pm[i++] = 0.1;
pm[i++] = 0.5;
break;
case 2:
i=0;
pm[i++] = log(4.0);
pm[i++] = 0.9;
pm[i++] = 0.2;
pm[i++] = cos(20.0/180.0*PI);
pm[i++] = 40.0;
pm[i++] = 0.0;
pm[i++] = log(3.0);
pm[i++] = log(0.01);
pm[i++] = log(0.1);
break;
case 3:
i=0;
pm[i++] = log(3.0);
pm[i++] = log(5.0);
pm[i++] = -1.0;
pm[i++] = cos(20.0/180.0*PI);
pm[i++] = 40.0;
pm[i++] = 0.0;
pm[i++] = log(3.0);
pm[i++] = 0.5;
pm[i++] = 0.5;
break;
case 4:
i=0;
pm[i++] = log(3.0);
pm[i++] = log(5.0);
pm[i++] = -1.0;
pm[i++] = cos(20.0/180.0*PI);
pm[i++] = 40.0;
pm[i++] = 0.0;
pm[i++] = log(3.0);
pm[i++] = 0.5;
pm[i++] = 0.5;
break;
case 5:
i=0;
pm[i++] = log(4.0); //mu
pm[i++] = 0.5; //Fin
pm[i++] = log(2.0); //Fout
pm[i++] = 1.5; //alpha
pm[i++] = cos(20.0/180.0*PI); //inc
pm[i++] = 40.0; //opn
pm[i++] = 0.5; //k
pm[i++] = 2.0; //gam
pm[i++] = 0.5; //xi
pm[i++] = log(2.0); //mbh
pm[i++] = 0.5; //fellip
pm[i++] = 0.5; //fflow
pm[i++] = log(0.01);
pm[i++] = log(0.1);
pm[i++] = log(0.01);
pm[i++] = log(0.1);
pm[i++] = 0.0; //theta_rot
pm[i++] = log(0.001); //sig_turb
break;
case 6:
i=0;
pm[i++] = log(4.0); // mu
pm[i++] = 1.0; // beta
pm[i++] = 0.25; // F
pm[i++] = cos(20.0/180.0*PI); // inc
pm[i++] = 40.0; // opn
pm[i++] = 0.0; // kappa
pm[i++] = 1.0; // gamma
pm[i++] = 1.0; // obscuration
pm[i++] = log(2.0); //mbh
pm[i++] = 0.5; //fellip
pm[i++] = 0.4; //fflow
pm[i++] = log(0.01); //
pm[i++] = log(0.1); //
pm[i++] = log(0.01); //
pm[i++] = log(0.1); //
pm[i++] = 0.0; // theta_rot
pm[i++] = log(0.001); // sig_turb
break;
case 7:
i=0;
pm[i++] = log(4.0); //mu
pm[i++] = 0.8; //beta
pm[i++] = 0.1; //F
pm[i++] = cos(20.0/180.0*PI);//inc
pm[i++] = 40.0; //opn
pm[i++] = 0.0; //kappa
pm[i++] = 1.0; //gamma
pm[i++] = 0.0; //xi
pm[i++] = 0.5; //fsh
pm[i++] = log(8.0); //mu_un
pm[i++] = 1.2; //beta_un
pm[i++] = 0.1; //F_un
pm[i++] = 20.0; //opn_un
pm[i++] = log(2.0); //mbh
pm[i++] = 0.5; //fellip
pm[i++] = 0.4; //fflow
pm[i++] = log(0.01);
pm[i++] = log(0.1);
pm[i++] = log(0.01);
pm[i++] = log(0.1);
pm[i++] = 0.0; //theta_rot
pm[i++] = 0.5; //fellip_un
pm[i++] = 0.4; //fflow_un
pm[i++] = log(0.001); // sig_turb
break;
case 8:
i=0;
pm[i++] = 50.0; //theta_min
pm[i++] = 20.0; //dtheta_max
pm[i++] = log(1.0); // r_min
pm[i++] = 4.0; // fr_max
pm[i++] = 1.0; // gamma
pm[i++] = 1.0; // alpha
pm[i++] = -2.0; // lambda
pm[i++] = -0.5; // k
pm[i++] = 0.0; // xi
pm[i++] = log(30.0); // Rv
pm[i++] = log(20.0); // Rblr, should larger than r_max=r_max * fr_max
pm[i++] = cos(30.0/180.0*PI); // inc
pm[i++] = log(4.0); // mbh
break;
case 9:
i=0;
pm[i++] = log(4.0); //mu
pm[i++] = 1.0; //beta
pm[i++] = 0.2; //F
pm[i++] = cos(30.0/180.0*PI); // inc
pm[i++] = 30.0; //opn
pm[i++] = log(4.0); // mbh
break;
}
return;
}
/*
* get index of mbh from a BLR model.
*
*/
int get_idx_mbh_from_blrmodel()
{
int idx = -1;
switch(parset.flag_blrmodel)
{
case 0:
idx = offsetof(MyBLRmodel, mbh);
break;
case 1:
idx = offsetof(BLRmodel1, mbh);
break;
case 2:
idx = offsetof(BLRmodel2, mbh);
break;
case 3:
idx = offsetof(BLRmodel3, mbh);
break;
case 4:
idx = offsetof(BLRmodel4, mbh);
break;
case 5:
idx = offsetof(BLRmodel5, mbh);
break;
case 6:
idx = offsetof(BLRmodel6, mbh);
break;
case 7:
idx = offsetof(BLRmodel7, mbh);
break;
case 8:
idx = offsetof(BLRmodel8, mbh);
break;
case 9:
idx = offsetof(BLRmodel9, mbh);
break;
}
return idx / sizeof(double);
} | {
"alphanum_fraction": 0.5842324322,
"avg_line_length": 26.1873015873,
"ext": "c",
"hexsha": "5c9e9b56bcda9dda8208c0fdc9d85fe0b1a1cf56",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-11-22T12:54:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-12T13:51:29.000Z",
"max_forks_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/BRAINS",
"max_forks_repo_path": "src/sim.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5",
"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": "LiyrAstroph/BRAINS",
"max_issues_repo_path": "src/sim.c",
"max_line_length": 131,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/BRAINS",
"max_stars_repo_path": "src/sim.c",
"max_stars_repo_stars_event_max_datetime": "2021-05-18T07:46:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-16T13:37:42.000Z",
"num_tokens": 8596,
"size": 24747
} |
/*
* 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:44 EST 1999 */
#include <fftw-int.h>
#include <fftw.h>
/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2hc-forward 5 */
/*
* This function contains 64 FP additions, 40 FP multiplications,
* (or, 44 additions, 20 multiplications, 20 fused multiply/add),
* 27 stack variables, and 40 memory accesses
*/
static const fftw_real K250000000 = FFTW_KONST(+0.250000000000000000000000000000000000000000000);
static const fftw_real K559016994 = FFTW_KONST(+0.559016994374947424102293417182819058860154590);
static const fftw_real K587785252 = FFTW_KONST(+0.587785252292473129168705954639072768597652438);
static const fftw_real K951056516 = FFTW_KONST(+0.951056516295153572116439333379382143405698634);
/*
* Generator Id's :
* $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $
* $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $
* $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $
*/
void fftw_hc2hc_forward_5(fftw_real *A, const fftw_complex *W, int iostride, int m, int dist)
{
int i;
fftw_real *X;
fftw_real *Y;
X = A;
Y = A + (5 * iostride);
{
fftw_real tmp70;
fftw_real tmp67;
fftw_real tmp68;
fftw_real tmp63;
fftw_real tmp71;
fftw_real tmp66;
fftw_real tmp69;
fftw_real tmp72;
ASSERT_ALIGNED_DOUBLE;
tmp70 = X[0];
{
fftw_real tmp61;
fftw_real tmp62;
fftw_real tmp64;
fftw_real tmp65;
ASSERT_ALIGNED_DOUBLE;
tmp61 = X[4 * iostride];
tmp62 = X[iostride];
tmp67 = tmp62 + tmp61;
tmp64 = X[2 * iostride];
tmp65 = X[3 * iostride];
tmp68 = tmp64 + tmp65;
tmp63 = tmp61 - tmp62;
tmp71 = tmp67 + tmp68;
tmp66 = tmp64 - tmp65;
}
Y[-iostride] = (K951056516 * tmp63) - (K587785252 * tmp66);
Y[-2 * iostride] = (K587785252 * tmp63) + (K951056516 * tmp66);
X[0] = tmp70 + tmp71;
tmp69 = K559016994 * (tmp67 - tmp68);
tmp72 = tmp70 - (K250000000 * tmp71);
X[iostride] = tmp69 + tmp72;
X[2 * iostride] = tmp72 - tmp69;
}
X = X + dist;
Y = Y - dist;
for (i = 2; i < m; i = i + 2, X = X + dist, Y = Y - dist, W = W + 4) {
fftw_real tmp13;
fftw_real tmp52;
fftw_real tmp42;
fftw_real tmp45;
fftw_real tmp49;
fftw_real tmp50;
fftw_real tmp51;
fftw_real tmp54;
fftw_real tmp53;
fftw_real tmp24;
fftw_real tmp35;
fftw_real tmp36;
ASSERT_ALIGNED_DOUBLE;
tmp13 = X[0];
tmp52 = Y[-4 * iostride];
{
fftw_real tmp18;
fftw_real tmp40;
fftw_real tmp34;
fftw_real tmp44;
fftw_real tmp23;
fftw_real tmp41;
fftw_real tmp29;
fftw_real tmp43;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp15;
fftw_real tmp17;
fftw_real tmp14;
fftw_real tmp16;
ASSERT_ALIGNED_DOUBLE;
tmp15 = X[iostride];
tmp17 = Y[-3 * iostride];
tmp14 = c_re(W[0]);
tmp16 = c_im(W[0]);
tmp18 = (tmp14 * tmp15) - (tmp16 * tmp17);
tmp40 = (tmp16 * tmp15) + (tmp14 * tmp17);
}
{
fftw_real tmp31;
fftw_real tmp33;
fftw_real tmp30;
fftw_real tmp32;
ASSERT_ALIGNED_DOUBLE;
tmp31 = X[3 * iostride];
tmp33 = Y[-iostride];
tmp30 = c_re(W[2]);
tmp32 = c_im(W[2]);
tmp34 = (tmp30 * tmp31) - (tmp32 * tmp33);
tmp44 = (tmp32 * tmp31) + (tmp30 * tmp33);
}
{
fftw_real tmp20;
fftw_real tmp22;
fftw_real tmp19;
fftw_real tmp21;
ASSERT_ALIGNED_DOUBLE;
tmp20 = X[4 * iostride];
tmp22 = Y[0];
tmp19 = c_re(W[3]);
tmp21 = c_im(W[3]);
tmp23 = (tmp19 * tmp20) - (tmp21 * tmp22);
tmp41 = (tmp21 * tmp20) + (tmp19 * tmp22);
}
{
fftw_real tmp26;
fftw_real tmp28;
fftw_real tmp25;
fftw_real tmp27;
ASSERT_ALIGNED_DOUBLE;
tmp26 = X[2 * iostride];
tmp28 = Y[-2 * iostride];
tmp25 = c_re(W[1]);
tmp27 = c_im(W[1]);
tmp29 = (tmp25 * tmp26) - (tmp27 * tmp28);
tmp43 = (tmp27 * tmp26) + (tmp25 * tmp28);
}
tmp42 = tmp40 - tmp41;
tmp45 = tmp43 - tmp44;
tmp49 = tmp40 + tmp41;
tmp50 = tmp43 + tmp44;
tmp51 = tmp49 + tmp50;
tmp54 = tmp29 - tmp34;
tmp53 = tmp18 - tmp23;
tmp24 = tmp18 + tmp23;
tmp35 = tmp29 + tmp34;
tmp36 = tmp24 + tmp35;
}
X[0] = tmp13 + tmp36;
{
fftw_real tmp46;
fftw_real tmp48;
fftw_real tmp39;
fftw_real tmp47;
fftw_real tmp37;
fftw_real tmp38;
ASSERT_ALIGNED_DOUBLE;
tmp46 = (K951056516 * tmp42) + (K587785252 * tmp45);
tmp48 = (K951056516 * tmp45) - (K587785252 * tmp42);
tmp37 = K559016994 * (tmp24 - tmp35);
tmp38 = tmp13 - (K250000000 * tmp36);
tmp39 = tmp37 + tmp38;
tmp47 = tmp38 - tmp37;
Y[-4 * iostride] = tmp39 - tmp46;
X[iostride] = tmp39 + tmp46;
X[2 * iostride] = tmp47 - tmp48;
Y[-3 * iostride] = tmp47 + tmp48;
}
Y[0] = tmp51 + tmp52;
{
fftw_real tmp55;
fftw_real tmp60;
fftw_real tmp58;
fftw_real tmp59;
fftw_real tmp56;
fftw_real tmp57;
ASSERT_ALIGNED_DOUBLE;
tmp55 = (K951056516 * tmp53) + (K587785252 * tmp54);
tmp60 = (K951056516 * tmp54) - (K587785252 * tmp53);
tmp56 = K559016994 * (tmp49 - tmp50);
tmp57 = tmp52 - (K250000000 * tmp51);
tmp58 = tmp56 + tmp57;
tmp59 = tmp57 - tmp56;
X[4 * iostride] = -(tmp55 + tmp58);
Y[-iostride] = tmp58 - tmp55;
X[3 * iostride] = -(tmp59 - tmp60);
Y[-2 * iostride] = tmp60 + tmp59;
}
}
if (i == m) {
fftw_real tmp8;
fftw_real tmp3;
fftw_real tmp6;
fftw_real tmp9;
fftw_real tmp12;
fftw_real tmp11;
fftw_real tmp7;
fftw_real tmp10;
ASSERT_ALIGNED_DOUBLE;
tmp8 = X[0];
{
fftw_real tmp1;
fftw_real tmp2;
fftw_real tmp4;
fftw_real tmp5;
ASSERT_ALIGNED_DOUBLE;
tmp1 = X[2 * iostride];
tmp2 = X[3 * iostride];
tmp3 = tmp1 - tmp2;
tmp4 = X[4 * iostride];
tmp5 = X[iostride];
tmp6 = tmp4 - tmp5;
tmp9 = tmp3 + tmp6;
tmp12 = tmp4 + tmp5;
tmp11 = tmp1 + tmp2;
}
X[2 * iostride] = tmp8 + tmp9;
tmp7 = K559016994 * (tmp3 - tmp6);
tmp10 = tmp8 - (K250000000 * tmp9);
X[0] = tmp7 + tmp10;
X[iostride] = tmp10 - tmp7;
Y[0] = -((K951056516 * tmp11) + (K587785252 * tmp12));
Y[-iostride] = -((K951056516 * tmp12) - (K587785252 * tmp11));
}
}
static const int twiddle_order[] =
{1, 2, 3, 4};
fftw_codelet_desc fftw_hc2hc_forward_5_desc =
{
"fftw_hc2hc_forward_5",
(void (*)()) fftw_hc2hc_forward_5,
5,
FFTW_FORWARD,
FFTW_HC2HC,
113,
4,
twiddle_order,
};
| {
"alphanum_fraction": 0.5864268402,
"avg_line_length": 29.1412639405,
"ext": "c",
"hexsha": "d64df79bd8ab78bfd1a02915225b94ead7a7317e",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z",
"max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "albertsgrc/ftdock-opt",
"max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_5.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "albertsgrc/ftdock-opt",
"max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_5.c",
"max_line_length": 124,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "albertsgrc/ftdock-opt",
"max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_5.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": 2606,
"size": 7839
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
/* gcc gsl_mersenne_twister.c -lgsl -lcblas */
int main(int argc, char **argv){
const gsl_rng_type * T;
gsl_rng * r;
int i, n_points;
double x;
T = gsl_rng_mt19937;
r = gsl_rng_alloc (T);
n_points = atoi(argv[1]);
for(i=0;i<n_points;i++){
x = gsl_rng_uniform(r);
fprintf(stdout, "%f\n", x);
}
return 0;
}
| {
"alphanum_fraction": 0.617866005,
"avg_line_length": 16.7916666667,
"ext": "c",
"hexsha": "1875ee221f856903231129e25890204d59a50ae8",
"lang": "C",
"max_forks_count": 18,
"max_forks_repo_forks_event_max_datetime": "2021-11-18T06:11:00.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-01-21T16:08:24.000Z",
"max_forks_repo_head_hexsha": "cbe731909413a990895809788a2ea78e9c7c0531",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ComputationalScienceUniandes/MetodosComputacionalesAvanzados",
"max_forks_repo_path": "weeks/04/code/gsl_mersenne_twister.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "cbe731909413a990895809788a2ea78e9c7c0531",
"max_issues_repo_issues_event_max_datetime": "2018-11-27T17:10:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-23T09:11:23.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ComputationalScienceUniandes/MetodosComputacionalesAvanzados",
"max_issues_repo_path": "weeks/04/code/gsl_mersenne_twister.c",
"max_line_length": 46,
"max_stars_count": 23,
"max_stars_repo_head_hexsha": "cbe731909413a990895809788a2ea78e9c7c0531",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ComputationalScienceUniandes/MetodosComputacionalesAvanzados",
"max_stars_repo_path": "weeks/04/code/gsl_mersenne_twister.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-18T06:10:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-23T13:49:41.000Z",
"num_tokens": 133,
"size": 403
} |
#ifndef __SVEC_H__
#define __SVEC_H__
#define HAVE_INLINE
#include <gsl/gsl_vector.h>
typedef gsl_vector_float *svec;
#define svec_alloc gsl_vector_float_alloc
#define svec_calloc gsl_vector_float_calloc
#define svec_free gsl_vector_float_free
#define svec_get gsl_vector_float_get
#define svec_set gsl_vector_float_set
#define svec_scale gsl_vector_float_scale
#define svec_memcpy gsl_vector_float_memcpy
#define svec_set_zero gsl_vector_float_set_zero
#define svec_add gsl_vector_float_add
void svec_print(svec x);
void svec_mul_print(svec x, double k);
void svec_randomize(svec x);
void svec_normalize(svec x);
void svec_zero(svec x);
float svec_pull(svec x, svec y, float d);
float svec_push(svec x, svec y, float d);
float svec_sqdist(svec x, svec y);
#endif
| {
"alphanum_fraction": 0.8309492848,
"avg_line_length": 26.5172413793,
"ext": "h",
"hexsha": "8e1a7ecdaa3787d66f8789df5dfa50d5d9220e1b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ai-ku/scode",
"max_forks_repo_path": "svec.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4",
"max_issues_repo_issues_event_max_datetime": "2015-02-03T17:43:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-06T18:20:04.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ai-ku/scode",
"max_issues_repo_path": "svec.h",
"max_line_length": 47,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4b7a1b3cc0a943c290c57fce50a61e3792da4ae4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ai-ku/scode",
"max_stars_repo_path": "svec.h",
"max_stars_repo_stars_event_max_datetime": "2016-07-21T18:29:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-06T16:46:05.000Z",
"num_tokens": 208,
"size": 769
} |
#include <assert.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <asf.h>
#include "asf_tiff.h"
#include <gsl/gsl_math.h>
#include <proj_api.h>
#include "asf_jpeg.h"
#include <png.h>
#include "envi.h"
#include "dateUtil.h"
#include <time.h>
#include "matrix.h"
#include <asf_nan.h>
#include <asf_endian.h>
#include <asf_meta.h>
#include <asf_export.h>
#include <asf_raster.h>
#include <float_image.h>
#include <spheroids.h>
#include <typlim.h>
#include <hdf5.h>
#define RES 16
#define MAX_PTS 256
void h5_att_double(hid_t data, hid_t space, char *name, double value)
{
hid_t attr = H5Acreate(data, name, H5T_NATIVE_DOUBLE, space, H5P_DEFAULT,
H5P_DEFAULT);
H5Awrite(attr, H5T_NATIVE_DOUBLE, &value);
H5Aclose(attr);
}
void h5_att_float(hid_t data, hid_t space, char *name, float value)
{
hid_t attr = H5Acreate(data, name, H5T_NATIVE_FLOAT, space, H5P_DEFAULT,
H5P_DEFAULT);
H5Awrite(attr, H5T_NATIVE_FLOAT, &value);
H5Aclose(attr);
}
void h5_att_int(hid_t data, hid_t space, char *name, int value)
{
hid_t attr = H5Acreate(data, name, H5T_NATIVE_INT, space, H5P_DEFAULT,
H5P_DEFAULT);
H5Awrite(attr, H5T_NATIVE_INT, &value);
H5Aclose(attr);
}
void h5_att_float2(hid_t data, hid_t space, char *name, float *value)
{
hid_t attr = H5Acreate(data, name, H5T_NATIVE_FLOAT, space, H5P_DEFAULT,
H5P_DEFAULT);
H5Awrite(attr, H5T_NATIVE_FLOAT, value);
H5Aclose(attr);
}
void h5_att_str(hid_t data, hid_t space, char *name, char *value)
{
hid_t str = H5Tcopy(H5T_C_S1);
H5Tset_size(str, strlen(value));
hid_t attr = H5Acreate(data, name, str, space, H5P_DEFAULT, H5P_DEFAULT);
H5Awrite(attr, str, value);
H5Aclose(attr);
}
void h5_value_double(hid_t file, char *group, char *name,
double value, char *long_name, char *units)
{
char meta[100];
sprintf(meta, "%s/%s", group, name);
hid_t h5_space = H5Screate(H5S_SCALAR);
hid_t h5_data = H5Dcreate(file, meta, H5T_NATIVE_DOUBLE, h5_space,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
H5Dwrite(h5_data, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);
h5_att_str(h5_data, h5_space, "long_name", long_name);
if (units && strlen(units) > 0)
h5_att_str(h5_data, h5_space, "units", units);
H5Dclose(h5_data);
H5Sclose(h5_space);
}
void h5_value_float(hid_t file, char *group, char *name,
float value, char *long_name, char *units)
{
char meta[100];
sprintf(meta, "%s/%s", group, name);
hid_t h5_space = H5Screate(H5S_SCALAR);
hid_t h5_data = H5Dcreate(file, meta, H5T_NATIVE_FLOAT, h5_space,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
H5Dwrite(h5_data, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);
h5_att_str(h5_data, h5_space, "long_name", long_name);
if (units && strlen(units) > 0)
h5_att_str(h5_data, h5_space, "units", units);
H5Dclose(h5_data);
H5Sclose(h5_space);
}
void h5_value_int(hid_t file, char *group, char *name,
int value, char *long_name, char *units)
{
char meta[100];
sprintf(meta, "%s/%s", group, name);
hid_t h5_space = H5Screate(H5S_SCALAR);
hid_t h5_data = H5Dcreate(file, meta, H5T_NATIVE_INT, h5_space,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
H5Dwrite(h5_data, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);
h5_att_str(h5_data, h5_space, "long_name", long_name);
if (units && strlen(units) > 0)
h5_att_str(h5_data, h5_space, "units", units);
H5Dclose(h5_data);
H5Sclose(h5_space);
}
void h5_value_str(hid_t file, char *group, char *name,
char *value, char *long_name, char *units)
{
char meta[100];
sprintf(meta, "%s/%s", group, name);
hid_t h5_space = H5Screate(H5S_SCALAR);
hid_t h5_str = H5Tcopy(H5T_C_S1);
H5Tset_size(h5_str, strlen(value));
hid_t h5_data = H5Dcreate(file, meta, h5_str, h5_space,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
H5Dwrite(h5_data, h5_str, H5S_ALL, H5S_ALL, H5P_DEFAULT, value);
h5_att_str(h5_data, h5_space, "long_name", long_name);
if (units && strlen(units) > 0)
h5_att_str(h5_data, h5_space, "units", units);
H5Dclose(h5_data);
H5Sclose(h5_space);
}
h5_t *initialize_h5_file(const char *output_file_name, meta_parameters *md)
{
hid_t h5_file, h5_datagroup, h5_metagroup, h5_data, h5_proj;
hid_t h5_array, h5_string, h5_time, h5_lat, h5_lon, h5_xgrid, h5_ygrid;
int ii, kk, complex=FALSE, projected=FALSE;
char *spatial_ref=NULL, *datum=NULL, *spheroid=NULL;
char dataset[50], group[50], band[5], str_attr[50], tmp[50];
double lfValue;
// Convenience variables
meta_general *mg = md->general;
meta_sar *ms = md->sar;
meta_state_vectors *mo = md->state_vectors;
meta_projection *mp = md->projection;
// Check whether data is map projected
if (mp && mp->type != SCANSAR_PROJECTION)
//asfPrintError("Image is map projected. Wrong initialization function!\n");
projected = TRUE;
// Initialize the HDF pointer structure
h5_t *h5 = (h5_t *) MALLOC(sizeof(h5_t));
int band_count = mg->band_count;
h5->var_count = band_count;
h5->var = (hid_t *) MALLOC(sizeof(hid_t)*h5->var_count);
// Check for complex data
if (mg->image_data_type == COMPLEX_IMAGE)
complex = TRUE;
// Create new HDF5 file
h5_file =
H5Fcreate(output_file_name, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
h5->file = h5_file;
// Create data space
int samples = mg->sample_count;
int lines = mg->line_count;
hsize_t dims[2] = { lines, samples };
hsize_t cdims[2] = { 100, samples };
hsize_t rdims[2] = { 1, 2 };
h5_array = H5Screate_simple(2, dims, NULL);
h5->space = h5_array;
h5_string = H5Screate(H5S_SCALAR);
hid_t h5_range = H5Screate(H5S_SIMPLE);
H5Sset_extent_simple(h5_range, 2, rdims, NULL);
// Create data structure
char **band_name = extract_band_names(mg->bands, band_count);
hid_t h5_plist = H5Pcreate(H5P_DATASET_CREATE);
H5Pset_chunk(h5_plist, 2, cdims);
H5Pset_deflate(h5_plist, 6);
// Create a data group
sprintf(group, "/data");
h5_datagroup = H5Gcreate(h5_file, group, H5P_DEFAULT, H5P_DEFAULT,
H5P_DEFAULT);
// Projection information
if (projected) {
sprintf(group, "/data/projection");
h5_proj = H5Gcreate(h5_file, group, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
if (mp->type == UNIVERSAL_TRANSVERSE_MERCATOR) {
h5_att_str(h5_proj, h5_string, "grid_mapping_name",
"transverse_mercator");
h5_att_double(h5_proj, h5_string, "scale_factor_at_central_meridian",
mp->param.utm.scale_factor);
h5_att_double(h5_proj, h5_string, "longitude_of_central_meridian",
mp->param.utm.lon0);
h5_att_double(h5_proj, h5_string, "latitude_of_projection_origin",
mp->param.utm.lat0);
h5_att_double(h5_proj, h5_string, "false_easting",
mp->param.utm.false_easting);
h5_att_double(h5_proj, h5_string, "false_northing",
mp->param.utm.false_northing);
h5_att_str(h5_proj, h5_string, "projection_x_coordinate", "xgrid");
h5_att_str(h5_proj, h5_string, "projection_y_coordinate", "ygrid");
h5_att_str(h5_proj, h5_string, "units", "meters");
h5_att_double(h5_proj, h5_string, "grid_boundary_top_projected_y",
mp->startY);
lfValue = mp->startY + mg->line_count * mp->perY;
h5_att_double(h5_proj, h5_string, "grid_boundary_bottom_projected_y",
lfValue);
lfValue = mp->startX + mg->sample_count * mp->perX;
h5_att_double(h5_proj, h5_string, "grid_boundary_right_projected_x",
lfValue);
h5_att_double(h5_proj, h5_string, "grid_boundary_left_projected_x",
mp->startX);
spatial_ref = (char *) MALLOC(sizeof(char)*1024);
datum = (char *) datum_toString(mp->datum);
spheroid = (char *) spheroid_toString(mp->spheroid);
double flat = mp->re_major/(mp->re_major - mp->re_minor);
sprintf(spatial_ref, "PROJCS[\"%s_UTM_Zone_%d%c\",GEOGCS[\"GCS_%s\",DATUM[\"D_%s\",SPHEROID[\"%s\",%.1lf,%-16.11g]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Transverse_Mercator\"],PARAMETER[\"False_Easting\",%.1lf],PARAMETER[\"False_Northing\",%.1lf],PARAMETER[\"Central_Meridian\",%.1lf],PARAMETER[\"Scale_Factor\",%.4lf],PARAMETER[\"Latitude_Of_Origin\",%.1lf],UNIT[\"Meter\",1]]",
spheroid, mp->param.utm.zone, mp->hem, spheroid, datum,
spheroid, mp->re_major, flat, mp->param.utm.false_easting,
mp->param.utm.false_northing, mp->param.utm.lon0,
mp->param.utm.scale_factor, mp->param.utm.lat0);
h5_att_str(h5_proj, h5_string, "spatial_ref", spatial_ref);
sprintf(str_attr, "+proj=utm +zone=%d", mp->param.utm.zone);
if (mg->center_latitude < 0)
strcat(str_attr, " +south");
h5_att_str(h5_proj, h5_string, "proj4text", str_attr);
h5_att_int(h5_proj, h5_string, "zone", mp->param.utm.zone);
h5_att_double(h5_proj, h5_string, "semimajor_radius", mp->re_major);
h5_att_double(h5_proj, h5_string, "semiminor_radius", mp->re_minor);
sprintf(str_attr, "%.6lf %.6lf 0 %.6lf 0 %.6lf", mp->startX, mp->perX,
mp->startY, mp->perY);
h5_att_str(h5_proj, h5_string, "GeoTransform", str_attr);
}
else if (mp->type == POLAR_STEREOGRAPHIC) {
h5_att_str(h5_proj, h5_string, "grid_mapping_name",
"polar_stereographic");
h5_att_double(h5_proj, h5_string, "straight_vertical_longitude_from_pole",
mp->param.ps.slon);
h5_att_double(h5_proj, h5_string, "latitude_of_projection_origin",
mp->param.ps.slat);
h5_att_double(h5_proj, h5_string, "scale_factor_at_projection_origin",
1.0);
h5_att_double(h5_proj, h5_string, "false_easting",
mp->param.ps.false_easting);
h5_att_double(h5_proj, h5_string, "false_northing",
mp->param.ps.false_northing);
h5_att_str(h5_proj, h5_string, "projection_x_coordinate", "xgrid");
h5_att_str(h5_proj, h5_string, "projection_y_coordinate", "ygrid");
h5_att_str(h5_proj, h5_string, "units", "meters");
h5_att_double(h5_proj, h5_string, "grid_boundary_top_projected_y",
mp->startY);
lfValue = mp->startY + mg->line_count * mp->perY;
h5_att_double(h5_proj, h5_string, "grid_boundary_bottom_projected_y",
lfValue);
lfValue = mp->startX + mg->sample_count * mp->perX;
h5_att_double(h5_proj, h5_string, "grid_boundary_right_projected_x",
lfValue);
h5_att_double(h5_proj, h5_string, "grid_boundary_left_projected_x",
mp->startX);
spatial_ref = (char *) MALLOC(sizeof(char)*1024);
double flat = mp->re_major/(mp->re_major - mp->re_minor);
sprintf(spatial_ref, "PROJCS[\"Stereographic_North_Pole\",GEOGCS[\"unnamed ellipse\",DATUM[\"D_unknown\",SPHEROID[\"Unknown\",%.3lf,%-16.11g]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0002247191011236]],PROJECTION[\"Stereographic_North_Pole\"],PARAMETER[\"standard_parallel_1\",%.4lf],PARAMETER[\"central_meridian\",%.4lf],PARAMETER[\"scale_factor\",1],PARAMETER[\"false_easting\",%.1lf],PARAMETER[\"false_northing\",%.1lf],UNIT[\"Meter\",1, AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"3411\"]]",
mp->re_major, flat, mp->param.ps.slat, mp->param.ps.slon,
mp->param.ps.false_easting, mp->param.ps.false_northing);
h5_att_str(h5_proj, h5_string, "spatial_ref", spatial_ref);
if (mp->param.ps.is_north_pole)
sprintf(str_attr, "+proj=stere +lat_0=90.0000 +lat_ts=%.4lf "
"+lon_0=%.4lf +k=1 +x_0=%.3lf +y_0=%.3lf +a=%.3lf +b=%.3lf "
"+units=m +no_defs", mp->param.ps.slat, mp->param.ps.slon,
mp->param.ps.false_easting, mp->param.ps.false_northing,
mp->re_major, mp->re_minor);
else
sprintf(str_attr, "+proj=stere +lat_0=-90.0000 +lat_ts=%.4lf "
"+lon_0=%.4lf +k=1 +x_0=%.3lf +y_0=%.3lf +a=%.3lf +b=%.3lf "
"+units=m +no_defs", mp->param.ps.slat, mp->param.ps.slon,
mp->param.ps.false_easting, mp->param.ps.false_northing,
mp->re_major, mp->re_minor);
h5_att_str(h5_proj, h5_string, "proj4text", str_attr);
h5_att_double(h5_proj, h5_string, "semimajor_radius", mp->re_major);
h5_att_double(h5_proj, h5_string, "semiminor_radius", mp->re_minor);
sprintf(str_attr, "%.6lf %.6lf 0 %.6lf 0 %.6lf", mp->startX, mp->perX,
mp->startY, mp->perY);
h5_att_str(h5_proj, h5_string, "GeoTransform", str_attr);
}
else if (mp->type == ALBERS_EQUAL_AREA) {
h5_att_str(h5_proj, h5_string, "grid_mapping_name",
"albers_conical_equal_area");
h5_att_double(h5_proj, h5_string, "standard_parallel_1",
mp->param.albers.std_parallel1);
h5_att_double(h5_proj, h5_string, "standard_parallel_2",
mp->param.albers.std_parallel2);
h5_att_double(h5_proj, h5_string, "longitude_of_central_meridian",
mp->param.albers.center_meridian);
h5_att_double(h5_proj, h5_string, "latitude_of_projection_origin",
mp->param.albers.orig_latitude);
h5_att_double(h5_proj, h5_string, "false_easting",
mp->param.albers.false_easting);
h5_att_double(h5_proj, h5_string, "false_northing",
mp->param.albers.false_northing);
h5_att_str(h5_proj, h5_string, "projection_x_coordinate", "xgrid");
h5_att_str(h5_proj, h5_string, "projection_y_coordinate", "ygrid");
h5_att_str(h5_proj, h5_string, "units", "meters");
h5_att_double(h5_proj, h5_string, "grid_boundary_top_projected_y",
mp->startY);
lfValue = mp->startY + mg->line_count * mp->perY;
h5_att_double(h5_proj, h5_string, "grid_boundary_bottom_projected_y",
lfValue);
lfValue = mp->startX + mg->sample_count * mp->perX;
h5_att_double(h5_proj, h5_string, "grid_boundary_right_projected_x",
lfValue);
h5_att_double(h5_proj, h5_string, "grid_boundary_left_projected_x",
mp->startX);
spatial_ref = (char *) MALLOC(sizeof(char)*1024);
datum = (char *) datum_toString(mp->datum);
spheroid = (char *) spheroid_toString(mp->spheroid);
double flat = mp->re_major/(mp->re_major - mp->re_minor);
sprintf(spatial_ref, "PROJCS[\"Albers_Equal_Area_Conic\",GEOGCS[\"GCS_%s\",DATUM[\"D_%s\",SPHEROID[\"%s\",%.3lf,%-16.11g]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199432955]],PROJECTION[\"Albers\"],PARAMETER[\"False_Easting\",%.3lf],PARAMETER[\"False_Northing\",%.3lf],PARAMETER[\"Central_Meridian\",%.4lf],PARAMETER[\"Standard_Parallel_1\",%.4lf],PARAMETER[\"Standard_Parallel_2\",%.4lf],PARAMETER[\"Latitude_Of_Origin\",%.4lf],UNIT[\"Meter\",1]]",
datum, datum, spheroid, mp->re_major, flat,
mp->param.albers.false_easting, mp->param.albers.false_northing,
mp->param.albers.center_meridian, mp->param.albers.std_parallel1,
mp->param.albers.std_parallel2, mp->param.albers.orig_latitude);
h5_att_str(h5_proj, h5_string, "spatial_ref", spatial_ref);
sprintf(str_attr, "+proj=aea +lat_1=%.4lf +lat_2=%.4lf +lat_0=%.4lf "
"+lon_0=%.4lf +x_0=%.3lf +y_0=%.3lf",
mp->param.albers.std_parallel1, mp->param.albers.std_parallel2,
mp->param.albers.orig_latitude, mp->param.albers.center_meridian,
mp->param.albers.false_easting, mp->param.albers.false_northing);
h5_att_str(h5_proj, h5_string, "proj4text", str_attr);
h5_att_double(h5_proj, h5_string, "semimajor_radius", mp->re_major);
h5_att_double(h5_proj, h5_string, "semiminor_radius", mp->re_minor);
sprintf(str_attr, "%.6lf %.6lf 0 %.6lf 0 %.6lf", mp->startX, mp->perX,
mp->startY, mp->perY);
h5_att_str(h5_proj, h5_string, "GeoTransform", str_attr);
}
else if (mp->type == LAMBERT_CONFORMAL_CONIC) {
h5_att_str(h5_proj, h5_string, "grid_mapping_name",
"lambert_conformal_conic");
h5_att_double(h5_proj, h5_string, "standard_parallel_1",
mp->param.lamcc.plat1);
h5_att_double(h5_proj, h5_string, "standard_parallel_2",
mp->param.lamcc.plat2);
h5_att_double(h5_proj, h5_string, "longitude_of_central_meridian",
mp->param.lamcc.lon0);
h5_att_double(h5_proj, h5_string, "latitude_of_projection_origin",
mp->param.lamcc.lat0);
h5_att_double(h5_proj, h5_string, "false_easting",
mp->param.lamcc.false_easting);
h5_att_double(h5_proj, h5_string, "false_northing",
mp->param.lamcc.false_northing);
h5_att_str(h5_proj, h5_string, "projection_x_coordinate", "xgrid");
h5_att_str(h5_proj, h5_string, "projection_y_coordinate", "ygrid");
h5_att_str(h5_proj, h5_string, "units", "meters");
h5_att_double(h5_proj, h5_string, "grid_boundary_top_projected_y",
mp->startY);
lfValue = mp->startY + mg->line_count * mp->perY;
h5_att_double(h5_proj, h5_string, "grid_boundary_bottom_projected_y",
lfValue);
lfValue = mp->startX + mg->sample_count * mp->perX;
h5_att_double(h5_proj, h5_string, "grid_boundary_right_projected_x",
lfValue);
h5_att_double(h5_proj, h5_string, "grid_boundary_left_projected_x",
mp->startX);
spatial_ref = (char *) MALLOC(sizeof(char)*1024);
datum = (char *) datum_toString(mp->datum);
spheroid = (char *) spheroid_toString(mp->spheroid);
double flat = mp->re_major/(mp->re_major - mp->re_minor);
sprintf(spatial_ref, "PROJCS[\"Lambert_Conformal_Conic\",GEOGCS[\"GCS_%s\",DATUM[\"D_%s\",SPHEROID[\"%s\",%.3lf,%-16.11g]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199432955]],PROJECTION[\"Lambert_Conformal_Conic\"],PARAMETER[\"False_Easting\",%.3lf],PARAMETER[\"False_Northing\",%.3lf],PARAMETER[\"Central_Meridian\",%.4lf],PARAMETER[\"Standard_Parallel_1\",%.4lf],PARAMETER[\"Standard_Parallel_2\",%.4lf],PARAMETER[\"Latitude_Of_Origin\",%.4lf],UNIT[\"Meter\",1]]",
datum, datum, spheroid, mp->re_major, flat,
mp->param.lamcc.false_easting, mp->param.lamcc.false_northing,
mp->param.lamcc.lon0, mp->param.lamcc.plat1,
mp->param.lamcc.plat2, mp->param.lamcc.lat0);
h5_att_str(h5_proj, h5_string, "spatial_ref", spatial_ref);
sprintf(str_attr, "+proj=lcc +lat_1=%.4lf +lat_2=%.4lf +lat_0=%.4lf "
"+lon_0=%.4lf +x_0=%.3lf +y_0=%.3lf",
mp->param.lamcc.plat1, mp->param.lamcc.plat2,
mp->param.lamcc.lat0, mp->param.lamcc.lon0,
mp->param.lamcc.false_easting, mp->param.lamcc.false_northing);
h5_att_str(h5_proj, h5_string, "proj4text", str_attr);
h5_att_double(h5_proj, h5_string, "semimajor_radius", mp->re_major);
h5_att_double(h5_proj, h5_string, "semiminor_radius", mp->re_minor);
sprintf(str_attr, "%.6lf %.6lf 0 %.6lf 0 %.6lf", mp->startX, mp->perX,
mp->startY, mp->perY);
h5_att_str(h5_proj, h5_string, "GeoTransform", str_attr);
}
else if (mp->type == LAMBERT_AZIMUTHAL_EQUAL_AREA) {
h5_att_str(h5_proj, h5_string, "grid_mapping_name",
"lambert_azimuthal_equal_area");
h5_att_double(h5_proj, h5_string, "longitude_of_projection_origin",
mp->param.lamaz.center_lon);
h5_att_double(h5_proj, h5_string, "latitude_of_projection_origin",
mp->param.lamaz.center_lat);
h5_att_double(h5_proj, h5_string, "false_easting",
mp->param.lamaz.false_easting);
h5_att_double(h5_proj, h5_string, "false_northing",
mp->param.lamaz.false_northing);
h5_att_str(h5_proj, h5_string, "projection_x_coordinate", "xgrid");
h5_att_str(h5_proj, h5_string, "projection_y_coordinate", "ygrid");
h5_att_str(h5_proj, h5_string, "units", "meters");
h5_att_double(h5_proj, h5_string, "grid_boundary_top_projected_y",
mp->startY);
lfValue = mp->startY + mg->line_count * mp->perY;
h5_att_double(h5_proj, h5_string, "grid_boundary_bottom_projected_y",
lfValue);
lfValue = mp->startX + mg->sample_count * mp->perX;
h5_att_double(h5_proj, h5_string, "grid_boundary_right_projected_x",
lfValue);
h5_att_double(h5_proj, h5_string, "grid_boundary_left_projected_x",
mp->startX);
spatial_ref = (char *) MALLOC(sizeof(char)*1024);
datum = (char *) datum_toString(mp->datum);
spheroid = (char *) spheroid_toString(mp->spheroid);
double flat = mp->re_major/(mp->re_major - mp->re_minor);
sprintf(spatial_ref, "PROJCS[\"Lambert_Azimuthal_Equal_Area\",GEOGCS[\"GCS_%s\",DATUM[\"D_%s\",SPHEROID[\"%s\",%.3lf,%-16.11g]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199432955]],PROJECTION[\"Lambert_Conformal_Conic\"],PARAMETER[\"False_Easting\",%.3lf],PARAMETER[\"False_Northing\",%.3lf],PARAMETER[\"Central_Meridian\",%.4lf],PARAMETER[\"Latitude_Of_Origin\",%.4lf],UNIT[\"Meter\",1]]",
datum, datum, spheroid, mp->re_major, flat,
mp->param.lamaz.false_easting, mp->param.lamaz.false_northing,
mp->param.lamaz.center_lon, mp->param.lamaz.center_lat);
h5_att_str(h5_proj, h5_string, "spatial_ref", spatial_ref);
sprintf(str_attr, "+proj=laea +lat_0=%.4lf +lon_0=%.4lf +x_0=%.3lf "
"+y_0=%.3lf",
mp->param.lamaz.center_lat, mp->param.lamaz.center_lon,
mp->param.lamaz.false_easting, mp->param.lamaz.false_northing);
h5_att_str(h5_proj, h5_string, "proj4text", str_attr);
h5_att_double(h5_proj, h5_string, "semimajor_radius", mp->re_major);
h5_att_double(h5_proj, h5_string, "semiminor_radius", mp->re_minor);
sprintf(str_attr, "%.6lf %.6lf 0 %.6lf 0 %.6lf", mp->startX, mp->perX,
mp->startY, mp->perY);
h5_att_str(h5_proj, h5_string, "GeoTransform", str_attr);
}
}
for (ii=0; ii<band_count; ii++) {
// Create data set
strncpy(band, band_name[ii], 2);
band[2] = '\0';
sprintf(dataset, "/data/%s_AMPLITUDE_IMAGE", band);
h5_data = H5Dcreate(h5_file, dataset, H5T_NATIVE_FLOAT, h5_array,
H5P_DEFAULT, h5_plist, H5P_DEFAULT);
h5->var[ii] = h5_data;
// Add attributes (from CF convention)
sprintf(str_attr, "%s", mg->sensor);
if (mg->image_data_type < 9)
strcat(str_attr, " radar backscatter");
if (mg->radiometry >= r_SIGMA_DB && mg->radiometry <= r_GAMMA_DB)
strcat(str_attr, " in dB");
h5_att_str(h5_data, h5_string, "long_name", str_attr);
h5_att_str(h5_data, h5_string, "cell_methods", "area: backscatter value");
h5_att_str(h5_data, h5_string, "units", "1");
h5_att_str(h5_data, h5_string, "units_description",
"unitless normalized radar cross-section");
if (mg->radiometry >= r_SIGMA && mg->radiometry <= r_GAMMA)
strcat(str_attr, " stored as powerscale");
else if (mg->radiometry >= r_SIGMA_DB && mg->radiometry <= r_GAMMA_DB)
strcat(str_attr, " stored as dB=10*log10(*)");
h5_att_float(h5_data, h5_string, "_FillValue", -999);
h5_att_str(h5_data, h5_string, "coordinates", "longitude latitude");
if (projected)
h5_att_str(h5_data, h5_string, "grid_mapping", "projection");
// Close up
H5Dclose(h5_data);
}
// Extra bands - Time
asfPrintStatus("Storing band 'time' ...\n");
float serial_date = seconds_from_str(mg->acquisition_date);
sprintf(dataset, "/data/time");
h5_time = H5Dcreate(h5_file, dataset, H5T_NATIVE_FLOAT, h5_string,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
H5Dwrite(h5_time, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT,
&serial_date);
h5_att_str(h5_time, h5_string, "units", "seconds since 1900-01-01T00:00:00Z");
h5_att_str(h5_time, h5_string, "references", "scene center time");
h5_att_str(h5_time, h5_string, "standard_name", "time");
h5_att_str(h5_time, h5_string, "axis", "T");
h5_att_str(h5_time, h5_string, "long_name", "serial date");
H5Dclose(h5_time);
// Extra bands - Longitude
int nl = mg->line_count;
int ns = mg->sample_count;
long pixel_count = mg->line_count * mg->sample_count;
double *value = (double *) MALLOC(sizeof(double)*MAX_PTS);
double *l = (double *) MALLOC(sizeof(double)*MAX_PTS);
double *s = (double *) MALLOC(sizeof(double)*MAX_PTS);
double line, sample, lat, lon, first_value;
float *lons = (float *) MALLOC(sizeof(float)*pixel_count);
asfPrintStatus("Generating band 'longitude' ...\n");
meta_get_latLon(md, 0, 0, 0.0, &lat, &lon);
if (lon < 0.0)
first_value = lon + 360.0;
else
first_value = lon;
asfPrintStatus("Calculating grid for quadratic fit ...\n");
for (ii=0; ii<RES; ii++) {
for (kk=0; kk<RES; kk++) {
line = ii * nl / RES;
sample = kk * ns / RES;
meta_get_latLon(md, line, sample, 0.0, &lat, &lon);
l[ii*RES+kk] = line;
s[ii*RES+kk] = sample;
if (lon < 0.0)
value[ii*RES+kk] = lon + 360.0;
else
value[ii*RES+kk] = lon;
}
asfLineMeter(ii, nl);
}
quadratic_2d q = find_quadratic(value, l, s, MAX_PTS);
q.A = first_value;
for (ii=0; ii<nl; ii++) {
for (kk=0; kk<ns; kk++) {
lons[ii*ns+kk] = (float)
(q.A + q.B*ii + q.C*kk + q.D*ii*ii + q.E*ii*kk + q.F*kk*kk +
q.G*ii*ii*kk + q.H*ii*kk*kk + q.I*ii*ii*kk*kk + q.J*ii*ii*ii +
q.K*kk*kk*kk) - 360.0;
if (lons[ii*ns+kk] < -180.0)
lons[ii*ns+kk] += 360.0;
}
asfLineMeter(ii, nl);
}
asfPrintStatus("Storing band 'longitude' ...\n");
sprintf(dataset, "/data/longitude");
h5_lon = H5Dcreate(h5_file, dataset, H5T_NATIVE_FLOAT, h5_array,
H5P_DEFAULT, h5_plist, H5P_DEFAULT);
H5Dwrite(h5_lon, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, lons);
h5_att_str(h5_lon, h5_string, "units", "degrees_east");
h5_att_str(h5_lon, h5_string, "long_name", "longitude");
h5_att_str(h5_lon, h5_string, "standard_name", "longitude");
float valid_range[2] = { -180.0, 180.0 };
h5_att_float2(h5_lon, h5_range, "valid_range", valid_range);
h5_att_float(h5_lon, h5_string, "_FillValue", -999);
H5Dclose(h5_lon);
FREE(lons);
// Extra bands - Latitude
float *lats = (float *) MALLOC(sizeof(float)*pixel_count);
asfPrintStatus("Generating band 'latitude' ...\n");
meta_get_latLon(md, 0, 0, 0.0, &lat, &lon);
first_value = lat + 180.0;
asfPrintStatus("Calculating grid for quadratic fit ...\n");
for (ii=0; ii<RES; ii++) {
for (kk=0; kk<RES; kk++) {
line = ii * nl / RES;
sample = kk * ns / RES;
meta_get_latLon(md, line, sample, 0.0, &lat, &lon);
l[ii*RES+kk] = line;
s[ii*RES+kk] = sample;
value[ii*RES+kk] = lat + 180.0;
}
asfLineMeter(ii, nl);
}
q = find_quadratic(value, l, s, MAX_PTS);
q.A = first_value;
for (ii=0; ii<nl; ii++) {
for (kk=0; kk<ns; kk++) {
if (mg->orbit_direction == 'A')
lats[(nl-ii-1)*ns+kk] = (float)
(q.A + q.B*ii + q.C*kk + q.D*ii*ii + q.E*ii*kk + q.F*kk*kk +
q.G*ii*ii*kk + q.H*ii*kk*kk + q.I*ii*ii*kk*kk + q.J*ii*ii*ii +
q.K*kk*kk*kk) - 180.0;
else
lats[ii*ns+kk] = (float)
(q.A + q.B*ii + q.C*kk + q.D*ii*ii + q.E*ii*kk + q.F*kk*kk +
q.G*ii*ii*kk + q.H*ii*kk*kk + q.I*ii*ii*kk*kk + q.J*ii*ii*ii +
q.K*kk*kk*kk) - 180.0;
}
asfLineMeter(ii, nl);
}
asfPrintStatus("Storing band 'latitude' ...\n");
sprintf(dataset, "/data/latitude");
h5_lat = H5Dcreate(h5_file, dataset, H5T_NATIVE_FLOAT, h5_array,
H5P_DEFAULT, h5_plist, H5P_DEFAULT);
H5Dwrite(h5_lat, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, lats);
h5_att_str(h5_lat, h5_string, "units", "degrees_north");
h5_att_str(h5_lat, h5_string, "long_name", "latitude");
h5_att_str(h5_lat, h5_string, "standard_name", "latitude");
valid_range[0] = -90.0;
valid_range[1] = 90.0;
h5_att_float2(h5_lat, h5_range, "valid_range", valid_range);
h5_att_float(h5_lat, h5_string, "_FillValue", -999);
H5Dclose(h5_lat);
FREE(lats);
if (projected) {
// Extra bands - ygrid
float *ygrids = (float *) MALLOC(sizeof(float)*pixel_count);
for (ii=0; ii<nl; ii++) {
for (kk=0; kk<ns; kk++)
ygrids[ii*ns+kk] = mp->startY + kk*mp->perY;
asfLineMeter(ii, nl);
}
asfPrintStatus("Storing band 'ygrid' ...\n");
sprintf(dataset, "/data/ygrid");
h5_ygrid = H5Dcreate(h5_file, dataset, H5T_NATIVE_FLOAT, h5_array,
H5P_DEFAULT, h5_plist, H5P_DEFAULT);
H5Dwrite(h5_ygrid, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, ygrids);
h5_att_str(h5_ygrid, h5_string, "units", "meters");
h5_att_str(h5_ygrid, h5_string, "long_name",
"projection_grid_y_coordinates");
h5_att_str(h5_ygrid, h5_string, "standard_name",
"projection_y_coordinates");
h5_att_str(h5_ygrid, h5_string, "axis", "Y");
H5Dclose(h5_ygrid);
FREE(ygrids);
// Extra bands - xgrid
float *xgrids = (float *) MALLOC(sizeof(float)*pixel_count);
for (ii=0; ii<nl; ii++) {
for (kk=0; kk<ns; kk++)
xgrids[ii*ns+kk] = mp->startX + kk*mp->perX;
asfLineMeter(ii, nl);
}
asfPrintStatus("Storing band 'xgrid' ...\n");
sprintf(dataset, "/data/xgrid");
h5_xgrid = H5Dcreate(h5_file, dataset, H5T_NATIVE_FLOAT, h5_array,
H5P_DEFAULT, h5_plist, H5P_DEFAULT);
H5Dwrite(h5_xgrid, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, xgrids);
h5_att_str(h5_xgrid, h5_string, "units", "meters");
h5_att_str(h5_xgrid, h5_string, "long_name",
"projection_grid_x_coordinates");
h5_att_str(h5_xgrid, h5_string, "standard_name",
"projection_x_coordinates");
h5_att_str(h5_xgrid, h5_string, "axis", "X");
H5Dclose(h5_xgrid);
FREE(xgrids);
}
H5Gclose(h5_datagroup);
// Adding global attributes
hid_t h5_global = H5Gopen(h5_file, "/", H5P_DEFAULT);
h5_att_str(h5_global, h5_string, "institution", "Alaska Satellite Facility");
sprintf(str_attr, "%s %s %s image", mg->sensor, mg->sensor_name, mg->mode);
h5_att_str(h5_global, h5_string, "title", str_attr);
if (mg->image_data_type == AMPLITUDE_IMAGE)
strcpy(str_attr, "SAR backcatter image");
h5_att_str(h5_global, h5_string, "source", str_attr);
h5_att_str(h5_global, h5_string, "original_file", mg->basename);
ymd_date ymd;
hms_time hms;
parse_date(mg->acquisition_date, &ymd, &hms);
if (strcmp_case(mg->sensor, "RSAT-1") == 0)
sprintf(str_attr, "Copyright Canadian Space Agency, %d", ymd.year);
else if (strncmp_case(mg->sensor, "ERS", 3) == 0)
sprintf(str_attr, "Copyright European Space Agency, %d", ymd.year);
else if (strcmp_case(mg->sensor, "JERS-1") == 0 ||
strcmp_case(mg->sensor, "ALOS") == 0)
sprintf(str_attr, "Copyright Japan Aerospace Exploration Agency , %d",
ymd.year);
h5_att_str(h5_global, h5_string, "comment", str_attr);
h5_att_str(h5_global, h5_string, "reference",
"Documentation available at: www.asf.alaska.edu");
time_t t;
struct tm *timeinfo;
time(&t);
timeinfo = gmtime(&t);
sprintf(str_attr, "%s", asctime(timeinfo));
chomp(str_attr);
strcat(str_attr, ", UTC: H5 File created.");
h5_att_str(h5_global, h5_string, "history", str_attr);
H5Gclose(h5_global);
// Metadata
sprintf(group, "/metadata");
h5_metagroup = H5Gcreate(h5_file, group, H5P_DEFAULT, H5P_DEFAULT,
H5P_DEFAULT);
// Metadata - General block
h5_value_str(h5_file, group, "general_name", mg->basename, "file_name", NULL);
h5_value_str(h5_file, group, "general_sensor", mg->sensor,
"imaging satellite", NULL);
h5_value_str(h5_file, group, "general_sensor_name", mg->sensor_name,
"imaging sensor", NULL);
h5_value_str(h5_file, group, "general_mode", mg->mode, "imaging mode", NULL);
h5_value_str(h5_file, group, "general_processor", mg->processor,
"name and version of processor", NULL);
h5_value_str(h5_file, group, "general_data_type",
data_type2str(mg->data_type), "type of samples (e.g. REAL64)",
NULL);
h5_value_str(h5_file, group, "general_image_data_type",
image_data_type2str(mg->image_data_type),
"image data type (e.g. AMPLITUDE_IMAGE)", NULL);
h5_value_str(h5_file, group, "general_radiometry",
radiometry2str(mg->radiometry), "radiometry (e.g. SIGMA)", NULL);
// FIXME: UDUNITS seconds since ...
h5_value_str(h5_file, group, "general_acquisition_date", mg->acquisition_date,
"acquisition date of image", NULL);
h5_value_int(h5_file, group, "general_orbit", mg->orbit,
"orbit number of image", NULL);
if (mg->orbit_direction == 'A')
strcpy(str_attr, "Ascending");
else
strcpy(str_attr, "Descending");
h5_value_str(h5_file, group, "general_orbit_direction", str_attr,
"orbit direction", NULL);
h5_value_int(h5_file, group, "general_frame", mg->frame,
"frame number of image", NULL);
h5_value_int(h5_file, group, "general_band_count", mg->band_count,
"number of bands in image", NULL);
h5_value_str(h5_file, group, "general_bands", mg->bands,
"bands of the sensor", NULL);
h5_value_int(h5_file, group, "general_line_count", mg->line_count,
"number of lines in image", NULL);
h5_value_int(h5_file, group, "general_sample_count", mg->sample_count,
"number of samples in image", NULL);
h5_value_int(h5_file, group, "general_start_line", mg->start_line,
"first line relative to original image", NULL);
h5_value_int(h5_file, group, "general_start_sample", mg->start_sample,
"first sample relative to original image", NULL);
h5_value_double(h5_file, group, "general_x_pixel_size", mg->x_pixel_size,
"range pixel size", "m");
h5_value_double(h5_file, group, "general_y_pixel_size", mg->y_pixel_size,
"azimuth pixel size", "m");
h5_value_double(h5_file, group, "general_center_latitude",
mg->center_latitude, "approximate image center latitude",
"degrees_north");
h5_value_double(h5_file, group, "general_center_longitude",
mg->center_longitude, "approximate image center longitude",
"degrees_east");
h5_value_double(h5_file, group, "general_re_major", mg->re_major,
"major (equator) axis of earth", "m");
h5_value_double(h5_file, group, "general_re_minor", mg->re_minor,
"minor (polar) axis of earth", "m");
h5_value_double(h5_file, group, "general_bit_error_rate", mg->bit_error_rate,
"fraction of bits which are in error", NULL);
h5_value_int(h5_file, group, "general_missing_lines", mg->missing_lines,
"number of missing lines in image", NULL);
h5_value_float(h5_file, group, "general_no_data", mg->no_data,
"value indicating no data for a pixel", NULL);
if (ms) {
if (ms->image_type == 'S')
strcpy(str_attr, "slant range");
else if (ms->image_type == 'G')
strcpy(str_attr, "ground range");
else if (ms->image_type == 'P')
strcpy(str_attr, "projected");
else if (ms->image_type == 'R')
strcpy(str_attr, "georeferenced");
h5_value_str(h5_file, group, "sar_image_type", str_attr, "image type",
NULL);
if (ms->look_direction == 'R')
strcpy(str_attr, "right");
else if (ms->look_direction == 'L')
strcpy(str_attr, "left");
h5_value_str(h5_file, group, "sar_look_direction", str_attr,
"SAR satellite look direction", NULL);
h5_value_int(h5_file, group, "sar_look_count", ms->look_count,
"number of looks to take from SLC", NULL);
h5_value_int(h5_file, group, "sar_multilook", ms->multilook,
"multilooking flag", NULL);
h5_value_int(h5_file, group, "sar_deskewed", ms->deskewed,
"zero doppler deskew flag", NULL);
h5_value_int(h5_file, group, "sar_original_line_count",
ms->original_line_count, "number of lines in original image",
NULL);
h5_value_int(h5_file, group, "sar_original_sample_count",
ms->original_sample_count,
"number of samples in original image", NULL);
h5_value_double(h5_file, group, "sar_line_increment",
ms->line_increment, "line increment for sampling", NULL);
h5_value_double(h5_file, group, "sar_sample_increment",
ms->sample_increment, "sample increment for sampling",
NULL);
h5_value_double(h5_file, group, "sar_range_time_per_pixel",
ms->range_time_per_pixel, "time per pixel in range", "s");
h5_value_double(h5_file, group, "sar_azimuth_time_per_pixel",
ms->azimuth_time_per_pixel, "time per pixel in azimuth",
"s");
h5_value_double(h5_file, group, "sar_slant_range_first_pixel",
ms->slant_range_first_pixel, "slant range to first pixel",
"m");
h5_value_double(h5_file, group, "sar_slant_shift", ms->slant_shift,
"error correction factor in slant range", "m");
h5_value_double(h5_file, group, "sar_time_shift", ms->time_shift,
"error correction factor in time", "s");
h5_value_double(h5_file, group, "sar_wavelength", ms->wavelength,
"SAR carrier wavelength", "m");
h5_value_double(h5_file, group, "sar_pulse_repetition_frequency",
ms->prf, "pulse repetition frequency", "Hz");
h5_value_double(h5_file, group, "sar_earth_radius", ms->earth_radius,
"earth radius at image center", "m");
h5_value_double(h5_file, group, "sar_satellite_height",
ms->satellite_height,
"satellite height from earth's center", "m");
h5_value_double(h5_file, group, "sar_range_doppler_centroid",
ms->range_doppler_coefficients[0], "range doppler centroid",
"Hz");
// FIXME: UDUNITS unit_description
h5_value_double(h5_file, group, "sar_range_doppler_linear",
ms->range_doppler_coefficients[1],
"range doppler per range pixel", "Hz/pixel");
// FIXME: UDUNITS unit description
h5_value_double(h5_file, group, "sar_range_doppler_quadratic",
ms->range_doppler_coefficients[2],
"range doppler per range pixel square", "Hz/pixel^2");
h5_value_double(h5_file, group, "sar_azimuth_doppler_centroid",
ms->azimuth_doppler_coefficients[0],
"azimuth doppler centroid", "Hz");
h5_value_double(h5_file, group, "sar_azimuth_doppler_linear",
ms->azimuth_doppler_coefficients[1],
"azimuth doppler per azimuth pixel", "Hz/pixel");
h5_value_double(h5_file, group, "sar_azimuth_doppler_quadratic",
ms->azimuth_doppler_coefficients[2],
"azimuth doppler per azimuth pixel square", "Hz/pixel^2");
}
if (mo) {
int vector_count = mo->vector_count;
h5_value_int(h5_file, group, "orbit_year", mo->year,
"year of image start", NULL);
h5_value_int(h5_file, group, "orbit_day_of_year", mo->julDay,
"day of year at image start", NULL);
h5_value_double(h5_file, group, "orbit_second_of_day", mo->second,
"second of day at image start", "s");
h5_value_int(h5_file, group, "orbit_vector_count", vector_count,
"number of state vectors", NULL);
for (ii=0; ii<vector_count; ii++) {
sprintf(tmp, "orbit_vector[%d]_time", ii+1);
h5_value_double(h5_file, group, tmp, mo->vecs[ii].time,
"time relative to image start", "s");
sprintf(tmp, "orbit_vector[%d]_position_x", ii+1);
h5_value_double(h5_file, group, tmp, mo->vecs[ii].vec.pos.x,
"x coordinate, earth-fixed", "m");
sprintf(tmp, "orbit_vector[%d]_position_y", ii+1);
h5_value_double(h5_file, group, tmp, mo->vecs[ii].vec.pos.y,
"y coordinate, earth-fixed", "m");
sprintf(tmp, "orbit_vector[%d]_position_z", ii+1);
h5_value_double(h5_file, group, tmp, mo->vecs[ii].vec.pos.z,
"z coordinate, earth-fixed", "m");
sprintf(tmp, "orbit_vector[%d]_velocity_x", ii+1);
h5_value_double(h5_file, group, tmp, mo->vecs[ii].vec.vel.x,
"x velocity, earth-fixed", "m/s");
sprintf(tmp, "orbit_vector[%d]_velocity_y", ii+1);
h5_value_double(h5_file, group, tmp, mo->vecs[ii].vec.vel.y,
"y velocity, earth-fixed", "m/s");
sprintf(tmp, "orbit_vector[%d]_velocity_z", ii+1);
h5_value_double(h5_file, group, tmp, mo->vecs[ii].vec.vel.z,
"z velocity, earth-fixed", "m/s");
}
}
H5Gclose(h5_metagroup);
H5Sclose(h5_string);
H5Sclose(h5_array);
// Write ASF metadata to XML file
char *output_file =
(char *) MALLOC(sizeof(char)*(strlen(output_file_name)+5));
sprintf(output_file, "%s.xml", output_file_name);
meta_write_xml(md, output_file);
FREE(output_file);
return h5;
}
void finalize_h5_file(h5_t *hdf)
{
H5Fclose(hdf->file);
// Clean up
FREE(hdf->var);
FREE(hdf);
}
| {
"alphanum_fraction": 0.6793866264,
"avg_line_length": 44.9491525424,
"ext": "c",
"hexsha": "7bce4dec757af3fe5a0f5630630c5f6c82f65c04",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z",
"max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "glshort/MapReady",
"max_forks_repo_path": "src/libasf_export/export_hdf.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "glshort/MapReady",
"max_issues_repo_path": "src/libasf_export/export_hdf.c",
"max_line_length": 510,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "glshort/MapReady",
"max_stars_repo_path": "src/libasf_export/export_hdf.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z",
"num_tokens": 13041,
"size": 39780
} |
/*
* BRAINS
* (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling
* Yan-Rong Li, liyanrong@ihep.ac.cn
* Thu, Aug 4, 2016
*/
/*!
* \file transfun.c
* \brief calculate transfer functions and emission lines
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include <mpi.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_interp.h>
#include "brains.h"
/*
* calculate (Fcon + ftrend)^Ag
*
*/
void calculate_con_rm(const void *pm)
{
int i, m;
double fcon, A, Ag, ftrend, a0=0.0, tmp;
double *pmodel = (double *)pm;
A=exp(pmodel[idx_resp]);
Ag=pmodel[idx_resp + 1];
/* add different trend in continuum and emission */
if(parset.flag_trend_diff > 0)
{
tmp = 0.0;
for(m=1; m<num_params_difftrend+1; m++)
{
tmp += pmodel[idx_difftrend + m-1] * pow_Tcon_data[m-1];
}
a0 = -tmp;
for(i=0; i<parset.n_con_recon; i++)
{
ftrend = a0;
tmp = 1.0;
for(m=1; m<num_params_difftrend+1; m++)
{
tmp *= (Tcon[i] - Tmed_data);
ftrend += pmodel[idx_difftrend + m-1] * tmp;
}
fcon = Fcon[i] + ftrend;
if(fcon > 0.0)
{
Fcon_rm[i] = A * pow(fcon, 1.0 + Ag);
}
else
{
Fcon_rm[i] = 0.0;
}
}
}
else
{
for(i=0; i<parset.n_con_recon; i++)
{
Fcon_rm[i] = A * pow(Fcon[i], 1.0+Ag);
}
}
return;
}
/*!
* This function calculate 1d line from a given BLR model.
*
* Note that continuum light curve has been obtained in advance
*
* Input:
* pm: model parameters
* Tl: epochs of line
* nl: number of points
* Output:
* Fl: line fluxes
*
*/
void calculate_line_from_blrmodel(const void *pm, double *Tl, double *Fl, int nl)
{
int i, j;
double fline, fcon_rm, tl, tc, tau, dTransTau;
dTransTau = TransTau[1] - TransTau[0];
for(i=0;i<nl;i++)
{
tl = Tl[i];
fline = 0.0;
for(j=0; j<parset.n_tau; j++)
{
tau = TransTau[j];
tc = tl - tau;
fcon_rm = gsl_interp_eval(gsl_linear, Tcon, Fcon_rm, tc, gsl_acc); /* interpolation */
fline += Trans1D[j] * fcon_rm; /* line response */
}
Fl[i] = fline * dTransTau;
}
return;
}
/*!
* This function caclulate 2d line from obtained transfer function.
*/
void calculate_line2d_from_blrmodel(const void *pm, const double *Tl, const double *transv, const double *trans2d,
double *fl2d, int nl, int nv)
{
int i, j, k;
double tau, tl, tc, fcon_rm, fnarrow, dTransTau;
double *pmodel = (double *)pm;
dTransTau = TransTau[1] - TransTau[0];
for(j=0;j<nl; j++)
{
for(i=0; i<nv; i++)
fl2d[j*nv + i] = 0.0;
tl = Tl[j];
for(k=0; k<parset.n_tau; k++)
{
tau = TransTau[k];
tc = tl - tau;
fcon_rm = gsl_interp_eval(gsl_linear, Tcon, Fcon_rm, tc, gsl_acc);
for(i=0; i<nv; i++)
{
fl2d[j*nv + i] += trans2d[k*nv+i] * fcon_rm;
}
}
for(i=0; i<nv; i++)
{
fl2d[j*nv + i] *= dTransTau;
}
}
/* add intrinsic narrow line */
if(parset.flag_narrowline != 0)
{
double flux, width, shift;
if(parset.flag_narrowline == 1) /* fixed narrow line */
{
flux = parset.flux_narrowline;
width = parset.width_narrowline;
shift = parset.shift_narrowline;
}
else if(parset.flag_narrowline == 2) /* narrow line with Gaussian priors */
{
flux = parset.flux_narrowline + pmodel[num_params_blr_model] * parset.flux_narrowline_err;
width = parset.width_narrowline + pmodel[num_params_blr_model+1] * parset.width_narrowline_err;
shift = parset.shift_narrowline + pmodel[num_params_blr_model+2] * parset.shift_narrowline_err;
}
else /* narrow line with logrithmic prior of flux */
{
flux = exp(pmodel[num_params_blr_model]);
width = parset.width_narrowline + pmodel[num_params_blr_model+1] * parset.width_narrowline_err;
shift = parset.shift_narrowline + pmodel[num_params_blr_model+2] * parset.shift_narrowline_err;
}
width = fmax(1.0e-10, width); /* make sure thant width is not zero */
for(i=0; i<nv; i++)
{
fnarrow = flux * exp( -0.5 * pow( (transv[i] - shift)/(width), 2.0) );
for(j = 0; j<nl; j++)
{
fl2d[j*nv + i] += fnarrow;
}
}
}
/* smooth the line profile */
line_gaussian_smooth_2D_FFT(transv, fl2d, nl, nv, pm);
}
/*!
* This function calculates 1d transfer function.
*/
void transfun_1d_cal_cloud(const void *pm, int flag_save)
{
/* generate cloud sample and calculate the corresponding time lags and weights */
gen_cloud_sample(pm, 1, flag_save);
transfun_1d_cal_with_sample();
return;
}
/*!
* This function calculates 1d transfer function.
*/
void transfun_1d_cal_with_sample()
{
int i, idt;
double tau_min, tau_max, dTransTau;
double Anorm, dis;
tau_min = clouds_tau[0];
tau_max = clouds_tau[0];
for(i=0; i<parset.n_cloud_per_task; i++)
{
if(tau_min > clouds_tau[i])
tau_min = clouds_tau[i];
if(tau_max < clouds_tau[i])
tau_max = clouds_tau[i];
}
dTransTau = (tau_max - tau_min)/(parset.n_tau - 1);
for(i=0; i<parset.n_tau; i++)
{
TransTau[i] = tau_min + dTransTau * i;
Trans1D[i] = 0.0;
}
for(i=0; i<parset.n_cloud_per_task; i++)
{
dis = clouds_tau[i];
idt = (dis - tau_min)/dTransTau;
//Trans1D[idt] += pow(1.0/r, 2.0*(1 + gam)) * weight;
Trans1D[idt] += clouds_weight[i];
}
/* normalize transfer function */
Anorm = 0.0;
for(i=0;i<parset.n_tau;i++)
{
Anorm += Trans1D[i];
}
Anorm *= dTransTau;
Anorm += EPS;
for(i=0; i<parset.n_tau; i++)
{
Trans1D[i] /= Anorm;
}
return;
}
/*!
* This function calculates 2d transfer function.
*/
void transfun_2d_cal_cloud(const void *pm, double *transv, double *trans2d, int n_vel, int flag_save)
{
/* generate cloud sample and calculate the corresponding time lags, LOS velocity, and weights */
gen_cloud_sample(pm, 2, flag_save);
transfun_2d_cal_with_sample(transv, trans2d, n_vel);
return;
}
/*!
* This function calculates 2d transfer function.
*/
void transfun_2d_cal_with_sample(double *transv, double *trans2d, int n_vel)
{
int i, j, idt, idV;
double tau_min, tau_max, dTransTau;
double Anorm, dis, V, dV;
tau_min = clouds_tau[0];
tau_max = clouds_tau[0];
for(i=0; i<parset.n_cloud_per_task; i++)
{
if(tau_min > clouds_tau[i])
tau_min = clouds_tau[i];
if(tau_max < clouds_tau[i])
tau_max = clouds_tau[i];
}
dTransTau = (tau_max - tau_min)/(parset.n_tau - 1);
for(i=0; i<parset.n_tau; i++)
{
TransTau[i] = tau_min + dTransTau * i;
}
dV =(transv[1] - transv[0]); /* velocity grid width */
for(i=0; i<parset.n_tau; i++)
for(j=0;j<n_vel;j++)
trans2d[i*n_vel+j]=0.0; /* cleanup of transfer function */
for(i=0; i<parset.n_cloud_per_task; i++)
{
dis = clouds_tau[i];
idt = (dis - tau_min)/dTransTau;
for(j=0; j<parset.n_vel_per_cloud; j++)
{
V = clouds_vel[i*parset.n_vel_per_cloud + j];
if(V<transv[0] || V >= transv[n_vel-1]+dV)
continue;
idV = (V - transv[0])/dV;
//trans2d[idt*n_vel + idV] += pow(1.0/r, 2.0*(1 + gam)) * weight;
trans2d[idt*n_vel + idV] += clouds_weight[i];
}
}
/* normalize transfer function */
Anorm = 0.0;
for(i=0; i<parset.n_tau; i++)
for(j=0; j<n_vel; j++)
{
Anorm += trans2d[i*n_vel+j];
}
Anorm *= (dV * dTransTau);
Anorm += EPS;
for(i=0; i<parset.n_tau; i++)
{
for(j=0; j<n_vel; j++)
{
trans2d[i*n_vel+j] /= Anorm;
}
}
return;
} | {
"alphanum_fraction": 0.593879668,
"avg_line_length": 23.2990936556,
"ext": "c",
"hexsha": "fda19e4a0c0aa81f7102e164abb46a50ed6c88b1",
"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": "b81cec02a1902df1e544542a970b66d9916a7496",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "yzxamos/BRAINS",
"max_forks_repo_path": "src/transfun.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "yzxamos/BRAINS",
"max_issues_repo_path": "src/transfun.c",
"max_line_length": 115,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "yzxamos/BRAINS",
"max_stars_repo_path": "src/transfun.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2606,
"size": 7712
} |
/*
** compute correlation matrix
**
** G.Lohmann, Feb 2011
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/gsl_histogram.h>
#include "viaio/Vlib.h"
#include "viaio/VImage.h"
#include "viaio/mu.h"
#ifdef _OPENMP
#include <omp.h>
#endif /*_OPENMP*/
#define SQR(x) ((x) * (x))
#define ABS(x) ((x) > 0 ? (x) : -(x))
extern void VNormalize(float *data,int nt,VBoolean stddev);
extern long GetAddr(VImage mapimage,int bi,int ri,int ci,int m,int k,int l);
int VNumNeigbours(size_t id,VImage map,VImage mapimage,int adjdef)
{
int nslices = VImageNBands(mapimage);
int nrows = VImageNRows(mapimage);
int ncols = VImageNColumns(mapimage);
int bi = VPixel(map,0,0,id,VShort);
int ri = VPixel(map,0,1,id,VShort);
int ci = VPixel(map,0,2,id,VShort);
if (bi < 1 || bi >= nslices-2) return 0;
if (ri < 1 || ri >= nrows-2) return 0;
if (ci < 1 || ci >= ncols-2) return 0;
int wn=1,rad2=0;
if (adjdef == 3) {
wn = 2;
rad2 = 2*2;
}
int n=0;
int k,l,m;
for (m=-wn; m<=wn; m++) {
for (k=-wn; k<=wn; k++) {
for (l=-wn; l<=wn; l++) {
long jj = GetAddr(mapimage,bi,ri,ci,m,k,l);
if (jj < 0) continue; /* outside of brain mask */
if (adjdef == 0) { /* 6 adjacency */
if (ABS(m)+ABS(k)+ABS(l) > 1) continue;
}
if (adjdef == 1) { /* 18-adjacency */
if (ABS(m) > 0 && ABS(k) > 0 && ABS(l) > 0) continue;
}
if (adjdef == 3) { /* sphere */
if (m*m + k*k + l*l > rad2) continue;
}
n++;
}
}
}
return n;
}
/* convert to ranks */
void GetRank(float *data,gsl_vector *v,gsl_permutation *perm,gsl_permutation *rank)
{
size_t i;
size_t n = v->size;
for (i=0; i<n; i++) gsl_vector_set(v,i,(double)data[i]);
gsl_sort_vector_index (perm, v);
gsl_permutation_inverse (rank, perm);
for (i=0; i<n; i++) data[i] = (float)rank->data[i];
}
double Spearman(const float *data1,const float *data2,int n)
{
int i;
double nx = (double)n;
double kx = nx*(nx*nx-1.0);
double sxy=0.0;
for (i=0; i<n; i++) {
const double u = (double)data1[i];
const double v = (double)data2[i];
const double d = (u-v);
sxy += d*d;
}
double rho = 1.0 - 6.0*sxy/kx;
return rho;
}
double Correlation(const float *data1,const float *data2,int n)
{
int i;
double corr=0;
for (i=0; i<n; i++) {
const double u = (double)data1[i];
const double v = (double)data2[i];
corr += u*v;
}
corr /= (double)n;
return corr;
}
float EdgeCorr(const float *data1,const float *data2,int n,int metric)
{
float corr=0.0;
if (metric == 0) corr = Correlation(data1,data2,n);
if (metric == 1) corr = Spearman(data1,data2,n);
if (corr > 0) return corr;
else return 0.0;
}
void GetSNR(gsl_matrix_float **X1,gsl_matrix_float **X2,int *table,int n,gsl_matrix_float *SNR,int metric)
{
long j,nvox=X1[0]->size1;
long k,s,nt=X1[0]->size2;
if (n < 3) VError(" n: %d",n);
double nx = (double)n;
double *sum1 = (double *)VCalloc(nt,sizeof(double));
double *sum2 = (double *)VCalloc(nt,sizeof(double));
gsl_vector *vec = NULL;
gsl_permutation *perm = NULL;
gsl_permutation *rank = NULL;
if (metric == 1) { /* only needed for spearman correlation */
vec = gsl_vector_calloc(nt);
perm = gsl_permutation_alloc(nt);
rank = gsl_permutation_alloc(nt);
}
double ave=0,var=0,snr=0;
for (j=0; j<nvox; j++) {
memset(sum1,0,nt*sizeof(double));
memset(sum2,0,nt*sizeof(double));
const float *pp=NULL;
for (s=0; s<n; s++) {
if (table[s] == 0)
pp = gsl_matrix_float_const_ptr(X1[s],j,0);
else
pp = gsl_matrix_float_const_ptr(X2[s],j,0);
for (k=0; k<nt; k++) {
const double x = (double)(*pp++);
sum1[k] += x;
sum2[k] += x*x;
}
}
for (k=0; k<nt; k++) {
ave = (sum1[k]/nx);
var = (sum2[k] - nx*ave*ave) / (nx - 1.0);
snr = 0;
if (var > 0) snr = ave / sqrt(var);
gsl_matrix_float_set(SNR,j,k,snr);
}
if (metric == 0) { /* pearson correlation */
float *qq = gsl_matrix_float_ptr(SNR,j,0);
VNormalize(qq,nt,TRUE);
}
if (metric == 1) { /* spearman ranks */
float *qq = gsl_matrix_float_ptr(SNR,j,0);
GetRank(qq,vec,perm,rank);
}
}
VFree(sum1);
VFree(sum2);
}
float ZMatrix(gsl_histogram *histogram,gsl_matrix_float *SNR1,gsl_matrix_float *SNR2,int n1,int n2,
VImage roi,VImage map,VImage mapimage,int adjdef,float elength,float quantile,int step,int metric)
{
size_t i;
size_t nvox=SNR1->size1;
int nt=SNR1->size2;
size_t progress=0;
int rad2 = (int)(elength*elength);
double tiny=1.0e-8;
gsl_set_error_handler_off ();
fprintf(stderr," Computing matrix...\n");
gsl_histogram_reset(histogram);
size_t nbins = gsl_histogram_bins (histogram);
double hmax = gsl_histogram_max (histogram);
double hmin = gsl_histogram_min (histogram);
double zmin = 99999.0;
double zmax = -99999.0;
int minadj = 1;
#pragma omp parallel for shared(progress,histogram) schedule(dynamic) firstprivate(SNR1,SNR2)
for (i=0; i<nvox; i+=step) {
if (i%1000 == 0) fprintf(stderr," %ld000\r",(long)progress++);
int bi = (int)VPixel(map,0,0,i,VShort);
int ri = (int)VPixel(map,0,1,i,VShort);
int ci = (int)VPixel(map,0,2,i,VShort);
int nadjx = VNumNeigbours(i,map,mapimage,adjdef);
if (nadjx < minadj) continue;
int roiflagi = 0;
if (roi != NULL) {
if (VGetPixel(roi,bi,ri,ci) > 0.5) roiflagi = 1;
}
gsl_histogram *tmphist = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (tmphist,hmin,hmax);
gsl_histogram_reset(tmphist);
const float *datax1 = gsl_matrix_float_const_ptr(SNR1,i,0);
const float *datax2 = gsl_matrix_float_const_ptr(SNR2,i,0);
size_t j=0;
for (j=0; j<i; j+=step) {
int bj = (int)VPixel(map,0,0,j,VShort);
int rj = (int)VPixel(map,0,1,j,VShort);
int cj = (int)VPixel(map,0,2,j,VShort);
int d = SQR(bi-bj) + SQR(ri-rj) + SQR(ci-cj);
if (d < rad2) continue;
int nadjy = VNumNeigbours(j,map,mapimage,adjdef);
if (nadjy < minadj) continue;
int roiflagj = 0;
if (roi != NULL) {
if (VGetPixel(roi,bj,rj,cj) > 0.5) roiflagj = 1;
if (roiflagi + roiflagj != 1) continue;
}
const float *datay1 = gsl_matrix_float_const_ptr(SNR1,j,0);
const float *datay2 = gsl_matrix_float_const_ptr(SNR2,j,0);
/* edge z-value */
double z1 = EdgeCorr(datax1,datay1,nt,metric);
double z2 = EdgeCorr(datax2,datay2,nt,metric);
double z = (z1-z2);
if (z < zmin) zmin = z;
if (z > zmax) zmax = z;
if (z < hmin) z = hmin;
if (z > hmax-tiny) z = hmax-tiny;
gsl_histogram_increment (tmphist,z);
}
#pragma omp critical
{
gsl_histogram_add (histogram,tmphist);
}
gsl_histogram_free (tmphist);
}
/* get quantile cutoff */
gsl_histogram_pdf *pdf = gsl_histogram_pdf_alloc(nbins);
gsl_histogram_pdf_init(pdf,histogram);
double lower=0,upper=0;
size_t i0=0;
for (i=nbins-1; i>=0; i--) {
gsl_histogram_get_range (histogram,i,&lower,&upper);
if (pdf->sum[i] < quantile) {
if (gsl_histogram_get_range (histogram,i,&lower,&upper) == GSL_EDOM) VError(" err hist");
i0 = i;
break;
}
}
double sum=0;
for (i=nbins-1; i>i0; i--) {
sum += gsl_histogram_get(histogram,i);
}
return (float)upper;
}
| {
"alphanum_fraction": 0.6078508086,
"avg_line_length": 25.9054054054,
"ext": "c",
"hexsha": "9f4923082c54501b20b250cd4feea18ba5ad30e2",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/ted/vted/ZMatrix.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/ted/vted/ZMatrix.c",
"max_line_length": 106,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/ted/vted/ZMatrix.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": 2650,
"size": 7668
} |
/*
* 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 loopblinn_875a5488_30b0_4449_b97a_e55c8d8a0db1_h
#define loopblinn_875a5488_30b0_4449_b97a_e55c8d8a0db1_h
#include <gslib/std.h>
#include <gslib/rtree.h>
#include <ariel/painterpath.h>
#include <ariel/delaunay.h>
__ariel_begin__
class lb_joint;
class lb_end_joint;
class lb_control_joint;
class lb_line;
class lb_polygon;
class lb_shrink_line;
class lb_shrink;
typedef vector<lb_joint*> lb_joint_list;
typedef vector<lb_line*> lb_line_list;
typedef vector<lb_polygon*> lb_polygon_list;
typedef vector<lb_shrink_line*> lb_shrink_lines;
typedef stack<lb_polygon*> lb_polygon_stack;
enum lb_joint_type
{
lbt_end_joint,
lbt_control_joint,
};
/*
* The reason why the original point and the NDC(normalized device coordinate) point should
* be separated was that we need the original point for the convenience of the error handling
* works, and we need the NDC point to do the loopblinn calculations so that the float
* point won't overflow.
*/
class __gs_novtable lb_joint abstract
{
protected:
lb_line* _prev;
lb_line* _next;
vec2 _point;
vec2 _ndcpoint;
void* _binding;
public:
lb_joint()
{
_prev = _next = nullptr;
_binding = nullptr;
}
virtual ~lb_joint() {}
virtual lb_joint_type get_type() const = 0;
virtual const vec2& get_point() const { return _point; }
virtual const vec2& get_ndc_point() const { return _ndcpoint; }
public:
void set_point(const vec2& p) { _point = p; }
void set_ndc_point(const vec2& p) { _ndcpoint = p; }
void set_prev_line(lb_line* p) { _prev = p; }
void set_next_line(lb_line* p) { _next = p; }
lb_line* get_prev_line() const { return _prev; }
lb_line* get_next_line() const { return _next; }
lb_joint* get_prev_joint() const;
lb_joint* get_next_joint() const;
bool is_adjacent_joint(const lb_joint* p) const { return p == get_prev_joint() || p == get_next_joint(); }
void set_binding(void* p) { _binding = p; }
void* get_binding() const { return _binding; }
};
class lb_end_joint:
public lb_joint
{
protected:
vec3 _klm[2];
public:
lb_end_joint() {}
lb_joint_type get_type() const override { return lbt_end_joint; }
bool prev_is_curve() const;
bool next_is_curve() const;
void set_klm(int i, const vec3& p) { _klm[i] = p; }
const vec3& get_klm(int i) const { return _klm[i]; }
};
class lb_control_joint:
public lb_joint
{
protected:
vec3 _klm;
public:
lb_control_joint() {}
lb_joint_type get_type() const override { return lbt_control_joint; }
void set_klm(const vec3& p) { _klm = p; }
const vec3& get_klm() const { return _klm; }
};
class lb_line
{
protected:
lb_joint* _joint[2];
bool _opened;
public:
lb_line()
{
_joint[0] = _joint[1] = nullptr;
_opened = false;
}
void set_opened(bool b) { _opened = b; }
bool is_opened() const { return _opened; }
void set_prev_joint(lb_joint* p) { _joint[0] = p; }
void set_next_joint(lb_joint* p) { _joint[1] = p; }
lb_joint* get_prev_joint() const { return _joint[0]; }
lb_joint* get_next_joint() const { return _joint[1]; }
lb_line* get_prev_line() const;
lb_line* get_next_line() const;
const vec2& get_prev_point() const { return _joint[0]->get_point(); }
const vec2& get_next_point() const { return _joint[1]->get_point(); }
static lb_line* get_line_between(lb_joint* j1, lb_joint* j2);
};
enum lb_span_type
{
lst_linear,
lst_quad,
lst_cubic,
};
class __gs_novtable lb_span abstract
{
protected:
rectf _rc;
public:
virtual ~lb_span() {}
virtual lb_span_type get_type() const = 0;
virtual bool can_split() const = 0;
virtual bool is_overlapped(const lb_span* span) const = 0;
public:
const rectf& get_rect() const { return _rc; }
float get_area() const { return _rc.width() * _rc.height(); }
};
typedef vector<lb_span*> lb_span_list;
typedef rtree_entity<lb_span*> lb_rtree_entity;
typedef rtree_node<lb_rtree_entity> lb_rtree_node;
typedef _tree_allocator<lb_rtree_node> lb_rtree_alloc;
typedef tree<lb_rtree_entity, lb_rtree_node, lb_rtree_alloc> lb_tree;
typedef rtree<lb_rtree_entity, quadratic_split_alg<8, 3, lb_tree>, lb_rtree_node, lb_rtree_alloc> lb_rtree;
typedef delaunay_triangulation lb_triangulator;
/*
* The polygon should be decomposed to the form like boundary - holes,
* this procedure could also be called flattening.
* After we retrieve the boundary we need to create a shrink for the boundary
* for including test, if necessary, so that we could decide if a sub path
* (case : cw - ccw - {cw}?) was a new path that ends the previous boundary.
*/
class lb_polygon
{
protected:
lb_line* _boundary;
lb_line_list _holes;
lb_rtree _mytree;
lb_triangulator _cdt;
dt_input_joints _dtjoints;
public:
lb_polygon() { _boundary = nullptr; }
void set_boundary(lb_line* p) { _boundary = p; }
void add_hole(lb_line* p) { _holes.push_back(p); }
lb_line* get_boundary() const { return _boundary; }
const lb_line_list& get_holes() const { return _holes; }
bool is_inside(const vec2& p) const;
lb_rtree& get_rtree() { return _mytree; }
void convert_to_ndc(const mat3& m);
void create_dt_joints();
void pack_constraints();
void build_cdt();
lb_triangulator& get_cdt_result() { return _cdt; }
void tracing() const;
void trace_boundary() const;
void trace_last_hole() const;
void trace_holes() const;
void trace_rtree() const { _mytree.tracing(); }
};
/*
* Notice that the path put into the loopblinn categorizer MUST be a simple polygon,
* which means you should run a xor clip process before if you can't tell whether a
* path was simple or complex.
* Another point was that the path MUST be Winding rule.
* You can also convert a path of OddEven rule to Winding by clipping.
*/
class loop_blinn_processor
{
public:
loop_blinn_processor(float w, float h) { _width = w, _height = h; }
~loop_blinn_processor();
void proceed(const painter_path& path);
lb_polygon_list& get_polygons() { return _polygons; }
lb_joint_list& get_joints() { return _joint_holdings; }
lb_line_list& get_lines() { return _line_holdings; }
void trace_polygons() const;
void trace_rtree() const;
protected:
float _width;
float _height;
lb_line_list _line_holdings;
lb_joint_list _joint_holdings;
lb_polygon_list _polygons;
lb_span_list _span_holdings;
protected:
template<class _joint>
lb_joint* create_joint(const vec2& p);
lb_line* create_line();
lb_polygon* create_polygon();
void flattening(const painter_path& path);
int flattening(const painter_path& path, int start, lb_polygon* parent, lb_polygon_stack& st);
int create_patch(lb_line*& line, const painter_path& path, int start);
lb_joint* create_segment(lb_joint* prev, const painter_path& path, int i);
void check_boundary(lb_polygon* poly);
void check_holes(lb_polygon* poly);
void check_span(lb_polygon* poly, lb_control_joint* joint);
void check_rtree(lb_polygon* poly);
void check_rtree_span(lb_polygon* poly, lb_span* span);
void split_quadratic(lb_line* line1, lb_line* line2, lb_joint* sp[5]);
void split_cubic(lb_line* line1, lb_line* line2, lb_line* line3, lb_joint* sp[7], float t);
int try_split_cubic(lb_line* line1, lb_line* line2, lb_line* line3, lb_joint* sp[7], float t);
lb_span* split_rtree_span(lb_span* span);
void split_span_recursively(lb_polygon* poly, lb_span* span);
void calc_klm_coords();
void calc_klm_coords(lb_polygon* poly);
void calc_klm_coords(lb_polygon* poly, lb_line* start);
lb_line* calc_klm_span(lb_polygon* poly, lb_line* line);
};
extern lb_line* lb_get_span(lb_line_list& span, lb_line* start);
extern void lb_get_current_span(lb_line_list& span, lb_control_joint* joint);
__ariel_end__
#endif
| {
"alphanum_fraction": 0.6820348114,
"avg_line_length": 34.9710144928,
"ext": "h",
"hexsha": "2fcc2424bd41a7c868367ea512f5b8e90eb20396",
"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/ariel/loopblinn.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/ariel/loopblinn.h",
"max_line_length": 111,
"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/ariel/loopblinn.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": 2529,
"size": 9652
} |
/*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
#include "aXe_errors.h"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_spline.h>
#include "fringe_conf.h"
#include "fringe_model.h"
#define AXE_IMAGE_PATH "AXE_IMAGE_PATH"
#define AXE_OUTPUT_PATH "AXE_OUTPUT_PATH"
#define AXE_CONFIG_PATH "AXE_CONFIG_PATH"
int
main(int argc, char *argv[])
{
char *opt;
char fconf_file[MAXCHAR];
char fconf_file_path[MAXCHAR];
char fimage_file[MAXCHAR];
char fimage_file_path[MAXCHAR];
fringe_conf *fconf;
//interpolator *filter_through;
gsl_matrix *fringe_image;
if ((argc < 3) || (opt = get_online_option("help", argc, argv))) {
fprintf(stdout,
"aXe_FRIGEN Version %s:\n"
"\n", RELEASE);
exit(1);
}
fprintf(stdout, "aXe_FRIGEN: Starting...\n");
/* Get the name of the fringe configuration file*/
strcpy(fconf_file, argv[1]);
build_path(AXE_CONFIG_PATH, fconf_file, fconf_file_path);
/* Get the configuration file name */
strcpy(fimage_file, argv[2]);
build_path(AXE_OUTPUT_PATH, fimage_file, fimage_file_path);
/* report on the input and output that will be used */
fprintf(stdout,
"aXe_FRIGEN: Input fringe configuration file: %s\n",
fconf_file_path);
fprintf(stdout,
"aXe_FRIGEN: Output fringe image name: %s\n",
fimage_file_path);
// load the fringe configuration file
fconf = load_fringe_conf(fconf_file_path);
// check whether all necessary information
// is in place, provide defaults
check_fringe_conf(fconf);
// check whether a filter throughput file is set
if (!fconf->filter_through)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_FRIGEN: No filter throughput table\n"
"is set in the fringe configuration file!\n");
// comute the fringe amplitude
fringe_image = compute_fringe_amplitude(fconf);
// save the matrix to a fits-image
gsl_to_FITSimage (fringe_image, fimage_file_path, 1, NULL);
// release the space in the fringe image
gsl_matrix_free(fringe_image);
// release the allocated memory
free_fringe_conf(fconf);
// exit the program
fprintf(stdout, "aXe_FRIGEN: Done...\n");
exit(0);
}
| {
"alphanum_fraction": 0.7015706806,
"avg_line_length": 25.4666666667,
"ext": "c",
"hexsha": "a75af892d853f0090bb482af7ef914c52f48b49b",
"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/aXe_FRIGEN.c",
"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/aXe_FRIGEN.c",
"max_line_length": 68,
"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/aXe_FRIGEN.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 646,
"size": 2292
} |
/* popGenTools.h
/
/
/ Andrew Kern
/
/
*/
#define MAXSNPS 1000000
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
struct snp{ /*SNP struct definition- meant to hold position, derived freq, sample size */
int pos, i, n, ascSize;
};
struct my_F_params{
int i, n, ascSize;
};
struct my_snpProb_params{
int i, n, ascSize;
double denom;
};
struct my_f_params{
int i,n, ascSize;
double beta;
};
struct my_lik_params{
int snpNumber, maxSampleSize, ascSize;
gsl_vector *weights, *sampleSizeVector, *betas;
struct snp *data;
gsl_matrix *sfsBools;
};
struct my_likCI_params{
int snpNumber, maxSampleSize;
gsl_vector *weights, *sampleSizeVector;
struct snp *data;
gsl_matrix *sfsBools;
double lMax, logUnits, beta_hat;
};
struct my_jointLik_params{
int snpNumber, maxSampleSize, ascSize, nstates;
gsl_vector *weights, *sampleSizeVector, *betas, *startingPoint;
struct snp *data;
gsl_matrix *sfsBools, *posts;
};
double my_f(double q, void * params);
double my_F(double beta, void * params);
double my_F2(double beta, void * p);
double my_lik(double beta, void * params);
double sfsLikBetaVector(gsl_vector *beta, void * p);
double weightedLik(double beta, void * params);
double weightedLikLook(double beta, void * params);
double weightedLikLookCI(double beta, void * params);
double likWrap(double beta);
double snpProb(double beta, void * params);
double snpProbDenomLookup(double beta, void * params);
double snpProbDenom(double beta, int sampleSize);
gsl_vector *makeSnpProbDenomVector(double beta, int maxSampleSize, gsl_vector *sampleSizeVec);
double ml_est(double * lik_beta_hat);
double weighted_ml_est(double * lik_beta_hat, void * p);
double weighted_ml_est_lookup(double * lik_beta_hat, void * p);
double weighted_ml_est_lookup_errReport(double * lik_beta_hat, void * p);
double weighted_ml_CILower_lookup(double * lik_beta_hat, void * p);
double weighted_ml_CIUpper_lookup(double * lik_beta_hat, void * p);
double wlikWrap(double beta, void * p);
double wlikWrapLook(double beta, void * p);
double wlikCIWrapLook(double beta, void * p);
gsl_vector *sampleSizeVector(struct snp data[], int snpNumber, int maxSampleSize);
gsl_matrix *summarizeSFS(int maxSampleSize, struct snp data[], int snpNumber);
gsl_matrix *summarizeSFSBool(int maxSampleSize, struct snp data[], int snpNumber);
gsl_matrix *snpProbMatrix(double beta, int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools);
gsl_matrix *snpProbMatrixNotLog(double beta, int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools);
gsl_matrix *snpProbMatrixNotLogFull(double beta, int maxSampleSize,gsl_vector *sampleSizeVector);
gsl_vector *snpProbVectorNotLog(double beta, int sampleSize);
int simulateSiteFreq(int sampleSize, double alpha, void *r);
double simpleAscertain(double sampleFreq, void *p);
double probAscertainmentGivenModel(double beta, void *p);
gsl_matrix *snpAscMatrix(int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools, int ascSize);
gsl_matrix *estimateAscSFS(int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools, int ascSize, gsl_matrix *sfsSummary);
double weightedLikLookAsc(double beta, void * p);
double wlikWrapLookAsc(double beta, void * p);
double weighted_ml_est_lookup_asc(double * lik_beta_hat, void * p);
double probAscertainmentGivenModelLookup(double beta, int sampSize, gsl_matrix *snpProbs, gsl_matrix *ascProbs);
double probAscertainmentGivenModelHemiLookup(double beta, int sampSize, gsl_vector *snpProbs, gsl_matrix *ascProbs);
double outgroupAscertain(double sampleFreq, void * p);
gsl_matrix *snpOutgroupAscMatrix(int maxSampleSize, gsl_vector *sampleSizeVector, int ascSize);
double weightedLikLookOutgroupAsc(double beta, void * p);
double wlikWrapLookOutgroupAsc(double beta, void * p);
double weighted_ml_est_lookup_outgroup_asc(double * lik_beta_hat, void * p);
double probOutgroupAscertainmentGivenModel(double beta, void *p);
double sfsLikBetaVectorOutgroupAsc(gsl_vector *betas, void * p);
| {
"alphanum_fraction": 0.7863354037,
"avg_line_length": 39.0776699029,
"ext": "h",
"hexsha": "7f9d8ced924864e61db1e166814a9557986921fa",
"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/popGenTools.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/popGenTools.h",
"max_line_length": 136,
"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/popGenTools.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1103,
"size": 4025
} |
#include "stdlib.h"
#include "stdio.h"
#include "/home/lillian/work/install_fpdebug/valgrind-3.7.0/fpdebug/fpdebug.h"
#include <gsl/gsl_sf.h>
int main(int argc, const char * argv[]) {
unsigned long int hexdouble;
int a;
a = atoi(argv[1]);
int b;
b = atoi(argv[2]);
int c;
c = atoi(argv[3]);
int d;
d = atoi(argv[4]);
int e;
e = atoi(argv[5]);
int f;
f = atoi(argv[6]);
double result = gsl_sf_coupling_6j(a, b, c, d, e, f);
//printf("%.15f\n", result);
VALGRIND_PRINT_ERROR("result", &result);
return 0;
} | {
"alphanum_fraction": 0.6607142857,
"avg_line_length": 21.9130434783,
"ext": "c",
"hexsha": "0243eebe16e740398d6a7f257587751215dea4d7",
"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": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "floatfeather/FpGenetic",
"max_forks_repo_path": "others_ori/gsl_sf_coupling_6j.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559",
"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": "floatfeather/FpGenetic",
"max_issues_repo_path": "others_ori/gsl_sf_coupling_6j.c",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "57bee06e637084c0f9d4b34b77d6ca8a9ad4c559",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "floatfeather/FpGenetic",
"max_stars_repo_path": "others_ori/gsl_sf_coupling_6j.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 170,
"size": 504
} |
#include <string.h>
#include <sys/types.h>
#include <stdint.h>
#include <math.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_wavelet.h>
#include <fftw3.h>
#include "common.h"
#include "utils.h"
#include "filters.h"
filters_t *filters_init(ANALYSIS_WAVEFORM_BASE_TYPE *inWav, size_t n)
{
filters_t *fHdl;
fHdl = (filters_t*)malloc(sizeof(filters_t));
fHdl->wavLen = n;
fHdl->respLen = 0;
fHdl->malloced = 0;
fHdl->fftUsed = 0;
fHdl->fftwNThreads = FFTW_NTHREADS_DEFAULT;
fHdl->fftwFlags = FFTW_FLAGS_DEFAULT;
if(inWav == NULL) {
fHdl->inWav = (ANALYSIS_WAVEFORM_BASE_TYPE*)
calloc(fHdl->wavLen, sizeof(ANALYSIS_WAVEFORM_BASE_TYPE));
fHdl->malloced = 1;
} else {
fHdl->inWav = inWav;
}
fHdl->outWav = (ANALYSIS_WAVEFORM_BASE_TYPE*)
calloc(fHdl->wavLen, sizeof(ANALYSIS_WAVEFORM_BASE_TYPE));
fHdl->waveletWav = (WAVELET_BASE_TYPE*)
calloc(fHdl->wavLen, sizeof(WAVELET_BASE_TYPE));
fHdl->gslDWT = gsl_wavelet_alloc(gsl_wavelet_daubechies_centered, 10);
fHdl->gslDWTWork = gsl_wavelet_workspace_alloc(fHdl->wavLen);
return fHdl;
}
/* for convolution */
filters_t *filters_init_for_convolution(ANALYSIS_WAVEFORM_BASE_TYPE *inWav, size_t n, size_t np)
{
filters_t *fHdl;
if((np > 0) && (np % 2 == 0)) {
error_printf("%s(): np = %zd is not odd!\n", __FUNCTION__, np);
return NULL;
}
fHdl = filters_init(inWav, n);
fHdl->respLen = np;
fHdl->fftUsed = 1;
fHdl->respWav = (ANALYSIS_WAVEFORM_BASE_TYPE*)
calloc(fHdl->respLen, sizeof(ANALYSIS_WAVEFORM_BASE_TYPE));
if(np > 0) {
fHdl->fftLen = (fHdl->wavLen + fHdl->respLen+1); /* zero padding */
if(fHdl->fftLen % 2) fHdl->fftLen++; /* ensure fHdl->fftLen is even */
} else {
fHdl->fftLen = fHdl->wavLen; /* for spectrum calculation */
}
if(fHdl->fftwNThreads > 0) {
if(FFTW(init_threads)() == 0) {
error_printf("fftw_init_threads error!\n");
}
FFTW(plan_with_nthreads)(fHdl->fftwNThreads);
}
fHdl->fftwWork = (FFT_BASE_TYPE*) FFTW(malloc)(sizeof(FFT_BASE_TYPE) * fHdl->fftLen);
fHdl->fftwWork1 = (FFT_BASE_TYPE*) FFTW(malloc)(sizeof(FFT_BASE_TYPE) * fHdl->fftLen);
fHdl->fftwWin = (FFT_BASE_TYPE*) FFTW(malloc)(sizeof(FFT_BASE_TYPE) * fHdl->fftLen);
filters_hanning_window(fHdl); /* Hanning window as the default */
fHdl->dt = 1.0;
fHdl->fftwPlan = FFTW(plan_r2r_1d)(fHdl->fftLen, fHdl->fftwWork, fHdl->fftwWork,
FFTW_R2HC, fHdl->fftwFlags);
fHdl->fftwPlan1 = FFTW(plan_r2r_1d)(fHdl->fftLen, fHdl->fftwWork1, fHdl->fftwWork1,
FFTW_R2HC, fHdl->fftwFlags);
fHdl->fftwPlan2 = FFTW(plan_r2r_1d)(fHdl->fftLen, fHdl->fftwWork, fHdl->fftwWork,
FFTW_HC2R, fHdl->fftwFlags);
return fHdl;
}
int filters_close(filters_t *fHdl)
{
if(fHdl->malloced) {
if(fHdl->inWav)
free(fHdl->inWav);
}
if(fHdl->outWav)
free(fHdl->outWav);
if(fHdl->fftUsed) {
if(fHdl->respWav)
free(fHdl->respWav);
FFTW(destroy_plan)(fHdl->fftwPlan);
FFTW(destroy_plan)(fHdl->fftwPlan1);
FFTW(destroy_plan)(fHdl->fftwPlan2);
FFTW(free)(fHdl->fftwWork);
FFTW(free)(fHdl->fftwWork1);
FFTW(free)(fHdl->fftwWin);
if(fHdl->fftwNThreads > 0) {
FFTW(cleanup_threads)();
FFTW(cleanup)();
}
}
gsl_wavelet_free(fHdl->gslDWT);
gsl_wavelet_workspace_free(fHdl->gslDWTWork);
if(fHdl->waveletWav)
free(fHdl->waveletWav);
return 0;
}
/* Filters should directly write into fHdl->respWav the real space
* response waveform in wrapped around order */
int filters_SavitzkyGolay(filters_t *fHdl, int m, int ld)
/* m: order of polynomial, np: number of points, ld: degree of derivative*/
{
int np;
ANALYSIS_WAVEFORM_BASE_TYPE *c;
int ipj, imj, mm, j, k, nl, nr;
double fac, sum;
gsl_permutation * p;
gsl_vector *b;
gsl_matrix *a;
np = fHdl->respLen;
if(np<1 || np<m-1 || np%2==0 || ld>m || np!=fHdl->respLen) {
error_printf("%s(): improper arguments, returning...\n", __FUNCTION__);
return 1;
}
c = calloc(np, sizeof(ANALYSIS_WAVEFORM_BASE_TYPE));
p = gsl_permutation_alloc (m+1);
b = gsl_vector_alloc(m+1);
a = gsl_matrix_alloc(m+1, m+1);
nl = np/2;
nr = nl;
for(ipj=0;ipj<=(m << 1);ipj++) {
sum=(ipj ? 0.0 : 1.0);
for(k=1;k<=nr;k++) sum += pow((double)(k),(double)(ipj));
for(k=1;k<=nl;k++) sum += pow((double)(-k),(double)(ipj));
mm=MIN(ipj,2*m-ipj);
for(imj=-mm;imj<=mm;imj+=2) gsl_matrix_set(a,(ipj+imj)/2,(ipj-imj)/2,sum);
}
gsl_linalg_LU_decomp(a, p, &k);
for (j=0;j<m+1;j++) gsl_vector_set(b,j,0.0);
gsl_vector_set(b,ld,1.0);
gsl_linalg_LU_solve (a, p, b, b);
for(k = -nl;k<=nr;k++) {
sum = gsl_vector_get(b,0);
fac = 1.0;
for (mm=1;mm<=m;mm++) sum += gsl_vector_get(b,mm)*(fac *= k);
j=(np-k) % np;
c[j]=sum; // c is in wraparound order, convenient for fft convolute
// c[nl + k] = sum;
}
memcpy(fHdl->respWav, c, np * sizeof(ANALYSIS_WAVEFORM_BASE_TYPE));
/*
for(j=0; j<np; j++) {
fprintf(stderr, "%g\n", c[j]);
}
*/
gsl_vector_free(b);
gsl_matrix_free(a);
gsl_permutation_free(p);
/*
for(k=nl; k<wavlen - nr; k++) {
sum = 0.0;
for(j=0; j<np; j++) {
sum += c[j] * inwav[k+j-nl];
outwav[k] = sum;
}
}
*/
free(c);
return 0;
}
int filters_raisedCosine(filters_t *fHdl)
{
ssize_t i;
ANALYSIS_WAVEFORM_BASE_TYPE x;
for(i=0; i<(fHdl->respLen+1)/2; i++) { /* positive side */
x = 2.0*M_PI/(ANALYSIS_WAVEFORM_BASE_TYPE)(fHdl->respLen-1)*(ANALYSIS_WAVEFORM_BASE_TYPE)i;
fHdl->respWav[i] = (1.0 + cos(x))/(ANALYSIS_WAVEFORM_BASE_TYPE)fHdl->respLen;
}
for(i=-((fHdl->respLen-1)/2); i<0; i++) { /* negative side */
/* i=-(fHdl->respLen-1)/2 cast to wrong value */
x = 2.0*M_PI/(ANALYSIS_WAVEFORM_BASE_TYPE)(fHdl->respLen-1)*(ANALYSIS_WAVEFORM_BASE_TYPE)i;
fHdl->respWav[fHdl->respLen+i] = (1.0 + cos(x))/(ANALYSIS_WAVEFORM_BASE_TYPE)fHdl->respLen;
}
return 0;
}
int filters_convolute(filters_t *fHdl)
{
size_t i;
ANALYSIS_WAVEFORM_BASE_TYPE re, im;
for(i=0; i<fHdl->wavLen; i++) {
fHdl->fftwWork[i] = fHdl->inWav[i];
}
for(i=fHdl->wavLen; i<fHdl->fftLen; i++) {
fHdl->fftwWork[i] = 0.0;
}
// fill in with respwav in wrap-around order
fHdl->fftwWork1[0] = fHdl->respWav[0];
for(i=1; i<(fHdl->respLen+1)/2; i++) {
fHdl->fftwWork1[i] = fHdl->respWav[i];
fHdl->fftwWork1[fHdl->fftLen-i] = fHdl->respWav[fHdl->respLen-i];
}
for(i=(fHdl->respLen+1)/2; i<(fHdl->fftLen-(fHdl->respLen+1)/2); i++) {
fHdl->fftwWork1[i] = 0.0;
}
// do fft
FFTW(execute)(fHdl->fftwPlan);
FFTW(execute)(fHdl->fftwPlan1);
// multiply in complex fourier space, half-complex format
fHdl->fftwWork[0] = fHdl->fftwWork[0] * fHdl->fftwWork1[0]
/ (ANALYSIS_WAVEFORM_BASE_TYPE)fHdl->fftLen;
for(i=1; i<fHdl->fftLen/2; i++) {
re = fHdl->fftwWork[i] * fHdl->fftwWork1[i]
- fHdl->fftwWork[fHdl->fftLen-i] * fHdl->fftwWork1[fHdl->fftLen-i];
im = fHdl->fftwWork[i] * fHdl->fftwWork1[fHdl->fftLen-i]
+ fHdl->fftwWork[fHdl->fftLen-i] * fHdl->fftwWork1[i];
fHdl->fftwWork[i] = re / (ANALYSIS_WAVEFORM_BASE_TYPE)fHdl->fftLen;
fHdl->fftwWork[fHdl->fftLen-i] = im / (ANALYSIS_WAVEFORM_BASE_TYPE)fHdl->fftLen;
}
fHdl->fftwWork[fHdl->fftLen/2] = fHdl->fftwWork[fHdl->fftLen/2] * fHdl->fftwWork1[fHdl->fftLen/2]
/ (ANALYSIS_WAVEFORM_BASE_TYPE)fHdl->fftLen;
// ifft
FFTW(execute)(fHdl->fftwPlan2);
// copy the output to outwav
memcpy(fHdl->outWav, fHdl->fftwWork, fHdl->wavLen * sizeof(ANALYSIS_WAVEFORM_BASE_TYPE));
return 0;
}
int filters_hanning_window(filters_t *fHdl)
{
size_t i;
fHdl->fftwS1 = 0.0; fHdl->fftwS2 = 0.0;
for(i=0; i<fHdl->fftLen; i++) {
fHdl->fftwWin[i] = 0.5 * (1.0 - cos(2*M_PI*i/(double)fHdl->fftLen));
fHdl->fftwS1 += fHdl->fftwWin[i];
fHdl->fftwS2 += fHdl->fftwWin[i] * fHdl->fftwWin[i];
}
return 0;
}
int filters_fft_spectrum(filters_t *fHdl)
{
size_t i;
for(i=0; i<fHdl->fftLen; i++) {
fHdl->fftwWork[i] = fHdl->inWav[i] * fHdl->fftwWin[i];
}
FFTW(execute)(fHdl->fftwPlan);
/* Compute linearized power spectrum into fftwWork1, in [V] for example, normalized.
* Total length should be (int)(n/2)+1 */
fHdl->fftwWork1[0] = fHdl->fftwWork[0] / fHdl->fftwS1;
for(i=1; i<(fHdl->fftLen+1)/2; i++) {
fHdl->fftwWork1[i] = hypot(fHdl->fftwWork[i],
fHdl->fftwWork[fHdl->fftLen - i]) * sqrt(2.0) / fHdl->fftwS1;
}
if(fHdl->fftLen % 2 == 0) { /* even number */
fHdl->fftwWork1[fHdl->fftLen/2] = fHdl->fftwWork[fHdl->fftLen/2] / fHdl->fftwS1;
}
/* For spectra density, normalization should be * sqrt(2.0 * dt / fftwS2) */
for(i=0; i<=fHdl->fftLen/2; i++) {
fHdl->fftwWork[i] = fHdl->fftwWork1[i] * fHdl->fftwS1 * sqrt(fHdl->dt / fHdl->fftwS2);
}
return 0;
}
int filters_DWT(filters_t *fHdl) /* discrete wavelet transform */
{
gsl_wavelet_transform_forward(fHdl->gslDWT, fHdl->waveletWav, 1, fHdl->wavLen,
fHdl->gslDWTWork);
return 0;
}
int filters_median(filters_t *fHdl, size_t n) /* median filter with moving window size n */
{
size_t i, mid=n/2;
for(i=0; i<mid;i++) /* overhang at the beginning */
fHdl->outWav[i] = quickselect(fHdl->inWav, mid+i+1, (mid+i+1)/2);
for(i=0; i<fHdl->wavLen-1 - mid; i++)
fHdl->outWav[mid+i] = quickselect(fHdl->inWav + i, n, n/2);
for(i=0; i<mid; i++) /* overhang at the end */
fHdl->outWav[fHdl->wavLen-1 - i] = quickselect(fHdl->inWav + fHdl->wavLen - (mid-i+1),
mid-i+1, (mid-i+1)/2);
return 0;
}
int filters_trapezoidal(filters_t *fHdl, size_t k, size_t l, double M)
{
double s, pp;
ssize_t i, j, jk, jl, jkl;
double vj, vjk, vjl, vjkl, dkl;
s = 0.0; pp = 0.0;
for(i=0; i<fHdl->wavLen; i++) {
j=i; jk = j-k; jl = j-l; jkl = j-k-l;
vj = j>=0 ? fHdl->inWav[j] : fHdl->inWav[0];
vjk = jk>=0 ? fHdl->inWav[jk] : fHdl->inWav[0];
vjl = jl>=0 ? fHdl->inWav[jl] : fHdl->inWav[0];
vjkl = jkl>=0 ? fHdl->inWav[jkl] : fHdl->inWav[0];
dkl = vj - vjk - vjl + vjkl;
pp = pp + dkl;
if(M>=0.0) {
s = s + pp + dkl * M;
} else { /* infinit decay time, so the input is a step function */
s = s + dkl;
}
fHdl->outWav[i] = s / (fabs(M) * (double)k);
}
return 0;
}
#ifdef FILTERS_DEBUG_ENABLEMAIN
int main(int argc, char **argv)
{
#define PLEN 1503
ANALYSIS_WAVEFORM_BASE_TYPE pulse[PLEN] = {0.0};
size_t i;
filters_t *fHdl;
i = 2;
pulse[i++]=0.0; pulse[i++]=1.0; pulse[i++]=10.0; pulse[i++]=8.0; pulse[i++]=6.0;
pulse[i++]=4.0; pulse[i++]=2.0; pulse[i++]=1.0; pulse[i++]=0.5; pulse[i++]=0.2;
i = 100;
pulse[i--]=0.0; pulse[i--]=1.0; pulse[i--]=10.0; pulse[i--]=8.0; pulse[i--]=6.0;
pulse[i--]=4.0; pulse[i--]=2.0; pulse[i--]=1.0; pulse[i--]=0.5; pulse[i--]=0.2;
fHdl = filters_init(pulse, PLEN);
filters_median(fHdl, 11);
for(i=0; i<fHdl->wavLen; i++) {
printf("%g %g\n", fHdl->inWav[i], fHdl->outWav[i]);
}
printf("\n\n");
#if 0
for(i=0; i<PLEN; i++) {
pulse[i] += 10.0 * cos(2.0 * M_PI/3.0 * i);
}
fHdl = filters_init_for_convolution(pulse, PLEN, 0);
filters_fft_spectrum(fHdl);
for(i=0; i<fHdl->fftLen; i++) {
printf("%g %g\n", fHdl->fftwWork[i], fHdl->fftwWork1[i]);
}
printf("\n\n");
#endif
#if 0
fHdl = filters_init_for_convolution(NULL, PLEN, 31);
memcpy(fHdl->inWav, pulse, PLEN * sizeof(ANALYSIS_WAVEFORM_BASE_TYPE));
filters_raisedCosine(fHdl);
filters_convolute(fHdl);
for(i=0; i<fHdl->fftLen/*PLEN*/; i++) {
// printf("%g %g\n", pulse[i], fHdl->outWav[i]);
printf("%g %g\n", fHdl->fftwWork[i], fHdl->fftwWork1[i]);
}
printf("\n\n");
filters_SavitzkyGolay(fHdl, 5, 0);
filters_convolute(fHdl);
for(i=0; i<fHdl->fftLen/*PLEN*/; i++) {
// printf("%g %g\n", pulse[i], fHdl->outWav[i]);
printf("%g %g\n", fHdl->fftwWork[i], fHdl->fftwWork1[i]);
}
#endif
filters_close(fHdl);
return EXIT_SUCCESS;
}
#endif
| {
"alphanum_fraction": 0.5731896418,
"avg_line_length": 31.7684729064,
"ext": "c",
"hexsha": "80345c1ea253adb573e93d0e6910d99f27942157",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-12-14T11:30:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-01-17T08:46:04.000Z",
"max_forks_repo_head_hexsha": "0a66a7305934f9d9da5c725a04e1e1ddcc4763c1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "AmberXiong/Mic4Test_KC705",
"max_forks_repo_path": "Software/Analysis/src/filters.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0a66a7305934f9d9da5c725a04e1e1ddcc4763c1",
"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": "AmberXiong/Mic4Test_KC705",
"max_issues_repo_path": "Software/Analysis/src/filters.c",
"max_line_length": 101,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "0a66a7305934f9d9da5c725a04e1e1ddcc4763c1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "AmberXiong/Mic4Test_KC705",
"max_stars_repo_path": "Software/Analysis/src/filters.c",
"max_stars_repo_stars_event_max_datetime": "2020-12-14T11:30:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-17T08:44:39.000Z",
"num_tokens": 4853,
"size": 12898
} |
/**
* @copyright (c) 2017 King Abdullah University of Science and Technology (KAUST).
* All rights reserved.
**/
/**
* @file codelet_zhagcm.c
*
* HiCMA codelets kernel
* HiCMA is a software package provided by King Abdullah University of Science and Technology (KAUST)
*
* @version 0.1.1
* @author Kadir Akbudak
* @date 2018-11-08
* @precisions normal z -> c d s
**/
#include "morse.h"
#include "runtime/starpu/chameleon_starpu.h"
//#include "runtime/starpu/include/runtime_codelet_z.h"
#include "runtime/starpu/runtime_codelets.h"
ZCODELETS_HEADER(hagcm)
#include <assert.h>
#include <stdio.h>
#include <stdlib.h> //FIXME remove mallocs from this code
#include <sys/time.h>//FIXME for gettimeofday
#include "hicma.h"
#include "starsh.h"
#include "starsh-spatial.h"
#include "starsh-randtlr.h"
#ifdef MKL
#include <mkl.h>
#include <mkl_lapack.h>
//#pragma message("MKL is used")
#else
#ifdef ARMPL
#include <armpl.h>
#else
#include <cblas.h>
#endif
#ifdef LAPACKE_UTILS
#include <lapacke_utils.h>
#endif
#include <lapacke.h>
//#pragma message("MKL is NOT used")
#endif
//#warning "An experimental feature is enabled!!!"
int steal_lrtile = 0; //non-zero values are for experimental reasons. Otherwise set to 0!!!!!
extern void _printmat(double * A, int m, int n, int ld);
void zhagcm( int m, int n, /*dimension of squareAD*/
double *AU,
double *AV,
double *Ark,
int ldu,
int ldv,
int tile_row_index, int tile_column_index,
int maxrank, double tol,
int A_mt)
{
int ii = tile_row_index;
int jj = tile_column_index;
if(steal_lrtile == 1 && ii == jj){
if(ii == A_mt-1) { // steal tile above
ii = ii - 1;
} else { // still tile below
ii = ii + 1;
}
}
int64_t i, j;
int lda = ldu; //FIXME ASSUMPTION
struct timeval tvalBefore, tvalAfter; // removed comma
gettimeofday (&tvalBefore, NULL);
int shape[2];
int rank = 0;
int oversample = 10;
double *work;
int *iwork;
STARSH_cluster *RC = HICMA_get_starsh_format()->row_cluster, *CC = RC;
void *RD = RC->data, *CD = RD;
double *AD;
AD = malloc(sizeof(double) * lda * n);
HICMA_get_starsh_format()->problem->kernel(m, n, RC->pivot+RC->start[ii], CC->pivot+CC->start[jj],
RD, CD, AD, lda);
int mn = m;
int mn2 = maxrank+oversample;
if(mn2 > mn)
mn2 = mn;
// Get size of temporary arrays
size_t lwork = n, lwork_sdd = (4*mn2+7)*mn2;
if(lwork_sdd > lwork)
lwork = lwork_sdd;
lwork += (size_t)mn2*(2*n+m+mn2+1);
size_t liwork = 8*mn2;
// Allocate temporary arrays
//STARSH_MALLOC(iwork, liwork);
iwork = malloc(sizeof(*iwork) * liwork);
if(iwork == NULL) {
fprintf(stderr, "%s %s %d:\t Allocation failed. No memory! liwork:%d", __FILE__, __func__, __LINE__, liwork);
exit(-1);
}
//STARSH_MALLOC(work, lwork);
work = malloc(sizeof(*work) * lwork);
if(work == NULL) {
fprintf(stderr, "%s %s %d:\t Allocation failed. No memory! lwork:%d", __FILE__, __func__, __LINE__, lwork);
exit(-1);
}
starsh_dense_dlrrsdd(m, n, AD, lda, AU, ldu, AV, ldv, &rank, maxrank, oversample, tol, work, lwork, iwork);
Ark[0] = rank;
free(work);
free(iwork);
}
/**
* HICMA_TASK_zhagcm - Generate compressed matrix from a problem determined according to current global setting of HiCMA library
*/
void HICMA_TASK_zhagcm( const MORSE_option_t *options,
int m, int n,
const MORSE_desc_t *AUV,
const MORSE_desc_t *Ark,
int Am, int An,
int ldu,
int ldv,
int maxrank, double tol,
int A_mt
)
{
struct starpu_codelet *codelet = &cl_zhagcm;
//void (*callback)(void*) = options->profiling ? cl_zhagcm_callback : NULL;
void (*callback)(void*) = NULL;
int nAUV = AUV->nb;
MORSE_BEGIN_ACCESS_DECLARATION;
MORSE_ACCESS_W(AUV, Am, An);
MORSE_ACCESS_W(Ark, Am, An);
MORSE_END_ACCESS_DECLARATION;
//printf("%s:%d: Am:%d An:%d lda:%d bigM:%d m0:%d n0:%d\n ", __FILE__, __LINE__, Am, An, lda, bigM, m0, n0);
//printf("%s %d: Am:%d An:%d ADm:%d ADn:%d ptr:%p\n", __func__, __LINE__, Am, An, ADm, ADn, ptr);
starpu_insert_task(
starpu_mpi_codelet(codelet),
STARPU_VALUE, &m, sizeof(int),
STARPU_VALUE, &n, sizeof(int),
STARPU_VALUE, &nAUV, sizeof(int),
STARPU_W, RTBLKADDR(AUV, double, Am, An),
STARPU_W, RTBLKADDR(Ark, double, Am, An),
STARPU_VALUE, &ldu, sizeof(int),
STARPU_VALUE, &ldv, sizeof(int),
STARPU_VALUE, &Am, sizeof(int),
STARPU_VALUE, &An, sizeof(int),
STARPU_VALUE, &maxrank, sizeof(int),
STARPU_VALUE, &tol, sizeof(double),
STARPU_VALUE, &A_mt, sizeof(int),
STARPU_PRIORITY, options->priority,
STARPU_CALLBACK, callback,
#if defined(CHAMELEON_CODELETS_HAVE_NAME)
STARPU_NAME, "zhagcm",
#endif
0);
}
/* cl_zhagcm_cpu_func - Generate a tile for random matrix. */
#if !defined(CHAMELEON_SIMULATION)
static void cl_zhagcm_cpu_func(void *descr[], void *cl_arg)
{
int m;
int n;
int nAUV;
double *AUV;
double *Ark;
int ldu;
int ldv;
int tile_row_index;
int tile_column_index;
int maxrank;
double tol;
int A_mt;
AUV = (double *)STARPU_MATRIX_GET_PTR(descr[0]);
Ark = (double *)STARPU_MATRIX_GET_PTR(descr[1]);
starpu_codelet_unpack_args(cl_arg, &m, &n, &nAUV, &ldu, &ldv, &tile_row_index, &tile_column_index, &maxrank, &tol, &A_mt);
double *AU = AUV;
int nAU = nAUV/2;
assert(ldu == ldv);
size_t nelm_AU = (size_t)ldu * (size_t)nAU;
double *AV = &(AUV[nelm_AU]);
//printf("(%d,%d)%d %s %d %d\n", m0/m,n0/n,MORSE_My_Mpi_Rank(), __func__, __LINE__, AD == Dense);
zhagcm( m, n,
AU,
AV,
Ark,
ldu,
ldv,
tile_row_index, tile_column_index,
maxrank, tol, A_mt
);
}
#endif /* !defined(CHAMELEON_SIMULATION) */
/*
* Codelet definition
*/
CODELETS_CPU(zhagcm, 2, cl_zhagcm_cpu_func)
| {
"alphanum_fraction": 0.5689989557,
"avg_line_length": 30.8894009217,
"ext": "c",
"hexsha": "7b9746c7b030140f537c491e1c0a7af165637b68",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T22:26:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-21T07:35:55.000Z",
"max_forks_repo_head_hexsha": "1807f9628df516d20d6265fdf0573c9bc9bf033b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "SamCao1991/hicma",
"max_forks_repo_path": "runtime/starpu/codelets/codelet_zhagcm.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "1807f9628df516d20d6265fdf0573c9bc9bf033b",
"max_issues_repo_issues_event_max_datetime": "2020-06-27T07:44:31.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-01-21T12:24:22.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "SamCao1991/hicma",
"max_issues_repo_path": "runtime/starpu/codelets/codelet_zhagcm.c",
"max_line_length": 128,
"max_stars_count": 19,
"max_stars_repo_head_hexsha": "1807f9628df516d20d6265fdf0573c9bc9bf033b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "SamCao1991/hicma",
"max_stars_repo_path": "runtime/starpu/codelets/codelet_zhagcm.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T09:37:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-11-27T11:17:49.000Z",
"num_tokens": 1966,
"size": 6703
} |
/**
* @file batchv_zgemv.c
*
* Part of API test for Batched BLAS routines.
*
* @author Samuel D. Relton
* @author Pedro V. Lara
* @author Mawussi Zounon
* @date 2016-06-01
*
* @precisions normal z -> c d s
*
**/
#include <cblas.h>
#include "bblas.h"
#define COMPLEX
void batchv_zgemv(
const enum BBLAS_TRANS *trans,
const int *m, const int *n,
const BBLAS_Complex64_t *alpha,
const BBLAS_Complex64_t **arrayA, const int *lda,
const BBLAS_Complex64_t **arrayx, const int *incx,
const BBLAS_Complex64_t *beta,
BBLAS_Complex64_t **arrayy, const int *incy,
const int batch_count, int* info)
{
/* Local variables */
// int first_index = 0;
int batch_iter = 0;
char func_name[15] = "batchv_zgemv";
if (batch_count < 0)
{
xerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1);
}
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
/* Check input arguments */
if ((trans[batch_iter] != BblasTrans) &&
(trans[batch_iter] != BblasNoTrans) &&
(trans[batch_iter] != BblasConjTrans))
{
xerbla_batch(func_name, BBLAS_ERR_TRANS, batch_iter);
info[batch_iter] = BBLAS_ERR_TRANS;
}
if (m[batch_iter] < 0)
{
xerbla_batch(func_name, BBLAS_ERR_M, batch_iter);
info[batch_iter] = BBLAS_ERR_M;
}
if (n[batch_iter] < 0)
{
xerbla_batch(func_name, BBLAS_ERR_N, batch_iter);
info[batch_iter] = BBLAS_ERR_N;
}
/* Column major */
if ((lda[batch_iter] < 1) && (lda[batch_iter] < m[batch_iter]))
{
xerbla_batch(func_name, BBLAS_ERR_LDA, batch_iter);
info[batch_iter] = BBLAS_ERR_LDA;
}
if (incx[batch_iter] < 1)
{
xerbla_batch(func_name, BBLAS_ERR_INCX, batch_iter);
info[batch_iter] = BBLAS_ERR_INCX;
}
if (incy[batch_iter] < 1)
{
xerbla_batch(func_name, BBLAS_ERR_INCY, batch_iter);
info[batch_iter] = BBLAS_ERR_INCY;
}
/* Call CBLAS */
cblas_zgemv(
BblasColMajor,
trans[batch_iter],
m[batch_iter], n[batch_iter],
CBLAS_SADDR( alpha[batch_iter] ),
arrayA[batch_iter], lda[batch_iter],
arrayx[batch_iter], incx[batch_iter],
CBLAS_SADDR( beta[batch_iter] ),
arrayy[batch_iter], incy[batch_iter]);
/* Successful */
info[batch_iter] = BBLAS_SUCCESS;
} /* End variable size for loop */
}
#undef COMPLEX
| {
"alphanum_fraction": 0.6814317673,
"avg_line_length": 23.28125,
"ext": "c",
"hexsha": "101f80764377ee4cb3805b5ae4d81565e4ff09f7",
"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": "117f3538b3ab43ade0ad53950ecac25c1a192bc7",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "sdrelton/bblas_api_test",
"max_forks_repo_path": "src/batchv_zgemv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7",
"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": "sdrelton/bblas_api_test",
"max_issues_repo_path": "src/batchv_zgemv.c",
"max_line_length": 65,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "mawussi/BBLAS-group",
"max_stars_repo_path": "src/batchv_zgemv.c",
"max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z",
"num_tokens": 771,
"size": 2235
} |
#ifndef GrowthFunctionBase_H
#define GrowthFunctionBase_H
#include <stdio.h>
#include <iostream>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#include <array>
#include <vector>
class GrowthFunctionBase{
private:
public:
GrowthFunctionBase(int id, int type, float initTime, float endTime, bool applyToColumnarLayer, bool applyToPeripodialMembrane, bool applyToBasalECM, bool applyToLateralECM){
/**
* integer id will set GrowthFunctionBase#Id. \n
* integer type will set GrowthFunctionBase#Type. \n
* floats initTime and endTime will set GrowthFunctionBase#initTime and GrowthFunctionBase#endTime respectively. \n
* booleans applyToColumnarLayer and applyToPeripodialMembrane will set GrowthFunctionBase#applyToColumnarLayer and GrowthFunctionBase#applyToPeripodialMembrane, respectively. \n
* */
this->Id = id;
this->Type = type;
this->initTime = initTime;
this->endTime = endTime;
this->applyToColumnarLayer = applyToColumnarLayer;
this->applyToPeripodialMembrane = applyToPeripodialMembrane;
this->applyToBasalECM = applyToBasalECM;
this->applyToLateralECM = applyToLateralECM;
zMin = 0;
zMax = 1.0;
} ///< The constructor of GrowthFunctionBase. Different growth functions will be derived from this class
~GrowthFunctionBase(){}
int Type; ///< The type of the growth function, 1: uniform growth, 2: Ring shaped growth, 3: Grid based growth, where growth rates read from a separate input file
int Id; ///< The unique identification number of the growth function
float initTime; ///< The initiation time of the growth, in seconds
float endTime; ///< The end time of the growth, in seconds.
bool applyToColumnarLayer; ///< Boolean stating if the growth should be applied to columnar layer
bool applyToPeripodialMembrane; ///< Boolean stating if the growth should be applied to peripodial membrane
bool applyToBasalECM; ///< Boolean stating if the growth should be applied to basal explicit ECM layer
bool applyToLateralECM ; ///< Boolean stating if the growth should be applied to lateral explicit ECM layer
bool applyTissueApical; ///< Boolean stating if the growth should be applied to apical side of the tissue
bool applyTissueBasal; ///< Boolean stating if the growth should be applied to basal side of the tissue
bool applyTissueMidLine; ///< Boolean stating if the growth should be applied to mid-line side of the tissue
double zMin; ///< Double giving the minimum z fraction of the tissue height that the growth is applied to
double zMax; ///< Double giving the maximum z fraction of the tissue height that the growth is applied to
std::vector <int> appliedEllipseBandIds; ///< The vector of integers holding the iIDs of the marker ellipse bands that the growth isapplied to
void ParentErrorMessage(std::string functionName){
std::cerr<<"You are calling the function: "<<functionName<<" from a parent here, check declaration is via pointers"<<std::endl;
}
double ParentErrorMessage(std::string functionName, double returnValue){
std::cerr<<"You are calling the function: "<<functionName<<" from a parent here, check declaration is via pointers"<<std::endl;
return returnValue;
}
int ParentErrorMessage(std::string functionName, int returnValue){
std::cerr<<"You are calling the function: "<<functionName<<" from a parent here, check declaration is via pointers"<<std::endl;
return returnValue;
}
virtual void writeSummary(std::ofstream&/*saveFileSimulationSummary*/){ParentErrorMessage("writeSummary_no_dt");} /// Virtual function of the parent to write the summary of growthFunction.
virtual void writeSummary(std::ofstream&/*saveFileSimulationSummary*/, double /*dt*/){ParentErrorMessage("writeSummary_with_dt");} /// Virtual function of the parent to write the summary of growthFunction.
virtual void getCentre(float &/*centreX*/, float &/*centreY*/){ParentErrorMessage("getCentre");} /// Virtual function of the parent to get centre of the growth function definition.
virtual float getInnerRadius(){return ParentErrorMessage("getInnerRadius",0.0);} /// Virtual function of the parent to get inner radius of the growth function definition.
virtual float getOuterRadius(){return ParentErrorMessage("getOuterRadius",0.0);} /// Virtual function of the parent to get outer radius of the growth function definition.
virtual std::array<double,3> getGrowthRate(){ParentErrorMessage("getGrowthRate");return std::array<double,3>{0.0};} /// Virtual function of the parent to get growth rate of the growth function definition.
virtual std::array<double,3> getShapeChangeRateRate(){ParentErrorMessage("getShapeChangeRateRate");return std::array<double,3>{0.0};} /// Virtual function of the parent to get shape change rate of the growth function definition.
virtual gsl_matrix* getShearAngleRotationMatrix(){ParentErrorMessage("getShearAngleRotationMatrix"); gsl_matrix* dummy = gsl_matrix_calloc(0,0); return dummy;} /// Virtual function of the parent to get rotation angle matrix of the growth function definition.
virtual double getShearAngle(){ParentErrorMessage("getShearAngle");return 0.0;} /// Virtual function of the parent to get rotation angle of the growth function definition.
virtual size_t getGridX(){return ParentErrorMessage("getGridX",0);} /// Virtual function of the parent to get gridX of the growth function definition.
virtual size_t getGridY(){return ParentErrorMessage("getGridY",0);} /// Virtual function of the parent to get gridY of the growth function definition.
virtual double getGrowthMatrixElement(int /*i*/, int /*j*/, int /*k*/){return ParentErrorMessage("getGrowthMatrixElement",0.0);} /// Virtual function of the parent to get grid matrix element of the growth function definition.
virtual double getXyShearAngleMatrixElement(int /*i*/, int /*j*/){return ParentErrorMessage("getXyShearhMatrixElement",0.0);} /// Virtual function of the parent to get grid matrix element of the growth function definition.
virtual bool isAspectRatioOverOne(int /*i*/, int /*j*/){return ParentErrorMessage("isAspectRatioOverOne",0);}/// Virtual function of the parent to check aspect ratioof the growth function definition.
virtual gsl_matrix* getXyShearRotationsMatrixElement(int /*i*/, int /*j*/){ParentErrorMessage("getShearAngleRotationMatrixElement");gsl_matrix* dummy = gsl_matrix_calloc(0,0); return dummy;} //this is used by grid based growth
virtual void getGrowthProfileAt4Corners(int /*IndexX*/, int /*IndexY*/, std::array<double,3>& /*growth0*/, std::array<double,3>&/*growth1*/, std::array<double,3>&/*growth2*/, std::array<double,3>&/*growth3*/, std::array<double,4>&/*angles*/, std::array<bool,4>&/*anglesEliminated*/){ParentErrorMessage("getGrowthProfileAt4Corners");}
virtual void setGrowtRate(double /*ex*/, double /*ey*/, double /*ez*/){ParentErrorMessage("setGrowtRate");}/// Virtual function of the parent to set growth rateof the growth function definition.
virtual void setGrowthMatrixElement(double /*ex*/, double /*ey*/, double /*ez*/, int /*i*/, int /*j*/){ParentErrorMessage("setGrowtRate");} /// Virtual function of the parent to set growth rateof the growth function definition.
};
#endif
| {
"alphanum_fraction": 0.7483713355,
"avg_line_length": 88.7710843373,
"ext": "h",
"hexsha": "b0ebad554d37f0e81130e0fb3c11eca37ddf0f07",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-07-28T12:26:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-05-06T11:38:53.000Z",
"max_forks_repo_head_hexsha": "2b436d7004a75c73f44202f31826557f5fb9f900",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "meldatozluoglu/TissueFolding_Lite",
"max_forks_repo_path": "TissueFolding/SourceCode/GrowthFunctionBase.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2b436d7004a75c73f44202f31826557f5fb9f900",
"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": "meldatozluoglu/TissueFolding_Lite",
"max_issues_repo_path": "TissueFolding/SourceCode/GrowthFunctionBase.h",
"max_line_length": 339,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "2b436d7004a75c73f44202f31826557f5fb9f900",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "meldatozluoglu/TissueFolding_Lite",
"max_stars_repo_path": "TissueFolding/SourceCode/GrowthFunctionBase.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-25T16:18:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-06-18T14:13:41.000Z",
"num_tokens": 1739,
"size": 7368
} |
#ifndef ITIMING_H
#define ITIMING_H
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <chameleon.h>
#include <al4san.h>
#include <runtime/al4san_quark.h>
#define _TYPE double
#define _PREC double
#define _LAMCH LAPACKE_dlamch_work
#define _NAME "sygv"
/* See Lawn 41 page 120 */
/* cholesky + 2 trsm's + trd */
#define _FMULS (((2. / 3.) * ((double)N * (double)N * (double)N)) + (N * (1.0 / 6.0 * N + 0.5) * N) + 2 * (N * N * (double)((N + 1) / 2.0) ))
#define _FADDS (((2. / 3.) * ((double)N * (double)N * (double)N)) + (N * (1.0 / 6.0 * N ) * N) + 2 * (N * N * (double)((N + 1) / 2.0) ))
/*
#define _FMULS ((double)N * (((1. / 6.) * (double)N + 0.5) * (double)N + (1. / 3.)))
#define _FADDS ((double)N * (((1. / 6.) * (double)N ) * (double)N - (1. / 6.)))
*/
#include "../include/flops.h"
#include<mkl_lapacke.h>
//#include <lapacke.h>
//#include <core_blas.h>
//#include <cblas.h>
#include<mkl.h>
#if defined(EIG_SCHED_STARPU)
#include <starpu.h>
#endif /* defined(EIG_SCHED_STARPU) */
#if defined(EIG_SCHED_QUARK)
#include <quark.h>
#endif /* defined(EIG_SCHED_QUARK) */
#if defined(EIG_SCHED_PARSEC)
#include <parsec.h>
#endif /* defined(EIG_SCHED_PARSEC) */
//#include <plasma.h>
#include <quark.h>
//#include "plasmatypes.h"
//#include "descriptor.h"
typedef double real_Double_t;
#define EIG_INPLACE 1
#define EIG_OUTOFPLACE 2
#if defined( _WIN32 ) || defined( _WIN64 )
#include <windows.h>
#include <time.h>
#include <sys/timeb.h>
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL
#endif
double cWtime(void);
struct timezone
{
int tz_minuteswest; /* minutes W of Greenwich */
int tz_dsttime; /* type of dst correction */
};
int gettimeofday(struct timeval* tv, struct timezone* tz)
{
FILETIME ft;
unsigned __int64 tmpres = 0;
static int tzflag;
if (NULL != tv)
{
GetSystemTimeAsFileTime(&ft);
tmpres |= ft.dwHighDateTime;
tmpres <<= 32;
tmpres |= ft.dwLowDateTime;
/*converting file time to unix epoch*/
tmpres /= 10; /*convert into microseconds*/
tmpres -= DELTA_EPOCH_IN_MICROSECS;
tv->tv_sec = (long)(tmpres / 1000000UL);
tv->tv_usec = (long)(tmpres % 1000000UL);
}
if (NULL != tz)
{
if (!tzflag)
{
_tzset();
tzflag++;
}
tz->tz_minuteswest = _timezone / 60;
tz->tz_dsttime = _daylight;
}
return 0;
}
#else /* Non-Windows */
#include <unistd.h>
#include <sys/time.h>
#include <sys/resource.h>
#endif
enum iparam_t {
IPARAM_THRDNBR, /* Number of cores */
IPARAM_THRDNBR_SUBGRP, /* Number of cores in a subgroup (NUMA node) */
IPARAM_NCUDAS,
IPARAM_NMPI,
IPARAM_P,
IPARAM_Q,
IPARAM_SCHEDULER, /* What scheduler do we choose (dyn, stat) */
IPARAM_M, /* Number of rows of the matrix */
IPARAM_N, /* Number of columns of the matrix */
IPARAM_K, /* RHS or K */
IPARAM_LDA, /* Leading dimension of A */
IPARAM_LDB, /* Leading dimension of B */
IPARAM_LDC, /* Leading dimension of C */
IPARAM_IB, /* Inner-blocking size */
IPARAM_NB, /* Number of columns in a tile */
IPARAM_MB, /* Number of rows in a tile */
IPARAM_NITER, /* Number of iteration of each test */
IPARAM_WARMUP, /* Run one test to load dynamic libraries */
IPARAM_CHECK, /* Checking activated or not */
IPARAM_VERBOSE, /* How much noise do we want? */
IPARAM_AUTOTUNING, /* Disable/enable autotuning */
IPARAM_INPUTFMT, /* Input format (Use only for getmi/gecfi) */
IPARAM_OUTPUTFMT, /* Output format (Use only for getmi/gecfi) */
IPARAM_TRACE, /* Generate trace on the first non warmup run */
IPARAM_DAG, /* Do we require to output the DOT file? */
IPARAM_ASYNC, /* Asynchronous calls */
IPARAM_MX, /* */
IPARAM_NX, /* */
IPARAM_RHBLK, /* Householder reduction parameter for QR/LQ */
IPARAM_TNTPIV_MODE, /* Tournament pivoting LU mode (LU or QR) */
IPARAM_TNTPIV_SIZE, /* Tournament pivoting LU group size */
IPARAM_INPLACE, /* InPlace/OutOfPlace translation mode */
IPARAM_MODE, /* Eigenvalue generation mode */
IPARAM_LAPACK, /* Eigenvalue dstedc using or not LAPACK */
IPARAM_MATRIX, /* FD matrix entry used for tridiagonal solvers */
IPARAM_MATRIX_CHECK, /* FD for checking results */
IPARAM_SIZEOF,
IPARAM_GEMM3M
};
enum dparam_timing {
IPARAM_TIME,
IPARAM_ANORM,
IPARAM_BNORM,
IPARAM_XNORM,
IPARAM_RES,
IPARAM_DNBPARAM
};
/*
int min( int a, int b ){
if (a<b) return(a); else return(b);
}
int max( int a, int b ){
if (a>b) return(a); else return(b);
}*/
#define PASTE_CODE_IPARAM_LOCALS(iparam) \
double t; \
double t1, t2; \
int64_t M = iparam[IPARAM_M]; \
int64_t N = iparam[IPARAM_N]; \
int64_t K = iparam[IPARAM_K]; \
int64_t NRHS = K; \
int64_t LDA = N; \
int64_t LDB = max(N, iparam[IPARAM_LDB]); \
int64_t LDC = max(K, iparam[IPARAM_LDC]); \
int64_t IB = iparam[IPARAM_IB]; \
int64_t MB = iparam[IPARAM_MB]; \
int64_t NB = iparam[IPARAM_NB]; \
int64_t MT = (M%MB==0) ? (M/MB) : (M/MB+1); \
int64_t NT = (N%NB==0) ? (N/NB) : (N/NB+1); \
int64_t P = iparam[IPARAM_P]; \
int64_t Q = iparam[IPARAM_Q]; \
int check = iparam[IPARAM_CHECK]; \
int loud = iparam[IPARAM_VERBOSE]; \
(void)M;(void)N;(void)K;(void)NRHS; \
(void)LDA;(void)LDB;(void)LDC; \
(void)IB;(void)MB;(void)NB;(void)MT;(void)NT; \
(void)check;(void)loud;
#define PASTE_CODE_IPARAM_LOCALS2(iparam) \
M = iparam[IPARAM_M]; \
N = iparam[IPARAM_N]; \
K = iparam[IPARAM_K]; \
NRHS = K; \
LDA = N; \
LDB = max(N, iparam[IPARAM_LDB]); \
LDC = max(K, iparam[IPARAM_LDC]); \
IB = iparam[IPARAM_IB]; \
MB = iparam[IPARAM_MB]; \
NB = iparam[IPARAM_NB]; \
MT = (M%MB==0) ? (M/MB) : (M/MB+1); \
NT = (N%NB==0) ? (N/NB) : (N/NB+1); \
P = iparam[IPARAM_P]; \
Q = iparam[IPARAM_Q]; \
check = iparam[IPARAM_CHECK]; \
loud = iparam[IPARAM_VERBOSE]; \
(void)M;(void)N;(void)K;(void)NRHS; \
(void)LDA;(void)LDB;(void)LDC; \
(void)IB;(void)MB;(void)NB;(void)MT;(void)NT; \
(void)check;(void)loud;
/* Paste code to allocate a matrix in desc if cond_init is true */
/*#define PASTE_CODE_ALLOCATE_MATRIX_TILE(_desc_, _cond_, _type_, _type2_, _lda_, _m_, _n_) \
PLASMA_desc *_desc_ = NULL; \
if( _cond_ ) { \
_type_ *ptr = NULL; \
ptr = (_type_*)malloc( (_lda_) * (_n_) * sizeof(_type_) ); \
if ( ! ptr ) { \
fprintf(stderr, "Our of Memory for %s\n", #_desc_); \
return -1; \
} \
PLASMA_Desc_Create(&(_desc_), ptr, _type2_, MB, NB, MB*NB, _lda_, _n_, 0, 0, _m_, _n_); \
}
#define PASTE_CODE_FREE_MATRIX(_desc_) \
if ( _desc_ != NULL ) { \
free(_desc_->mat); \
} \
PLASMA_Desc_Destroy( &_desc_ );
#define PASTE_TILE_TO_LAPACK(_desc_, _name_, _cond_, _type_, _lda_, _n_) \
_type_ *_name_ = NULL; \
if ( _cond_ ) { \
_name_ = (_type_*)malloc( (_lda_) * (_n_) * sizeof(_type_)); \
if ( ! _name_ ) { \
fprintf(stderr, "Our of Memory for %s\n", #_name_); \
return -1; \
} \
PLASMA_Tile_to_Lapack(_desc_, (void*)_name_, _lda_); \
}
#define PASTE_CODE_ALLOCATE_MATRIX(_name_, _cond_, _type_, _lda_, _n_) \
_type_ *_name_ = NULL; \
if( _cond_ ) { \
_name_ = (_type_*)malloc( (_lda_) * (_n_) * sizeof(_type_) ); \
if ( ! _name_ ) { \
fprintf(stderr, "Our of Memory for %s\n", #_name_); \
return -1; \
} \
}
#define PASTE_CODE_ALLOCATE_COPY(_name_, _cond_, _type_, _orig_, _lda_, _n_) \
_type_ *_name_ = NULL; \
if( _cond_ ) { \
_name_ = (_type_*)malloc( (_lda_) * (_n_) * sizeof(_type_) ); \
if ( ! _name_ ) { \
fprintf(stderr, "Our of Memory for %s\n", #_name_); \
return -1; \
} \
memcpy(_name_, _orig_, (_lda_) * (_n_) * sizeof(_type_) ); \
}
*/
/* Paste code to allocate a matrix in desc if cond_init is true */
#define CHAM_PASTE_CODE_ALLOCATE_MATRIX_TILE(_desc_, _cond_, _type_, _type2_, _lda_, _m_, _n_) \
CHAM_desc_t *_desc_ = NULL; \
int status ## _desc_ ; \
if( _cond_ ) { \
if (ooc) \
status ## _desc_ = CHAMELEON_Desc_Create_OOC(&(_desc_), _type2_, MB, NB, MB*NB, _lda_, _n_, 0, 0, _m_, _n_, \
P, Q); \
else if (!bigmat) \
status ## _desc_ = CHAMELEON_Desc_Create_User(&(_desc_), NULL, _type2_, MB, NB, MB*NB, _lda_, _n_, 0, 0, _m_, _n_, \
P, Q, chameleon_getaddr_null, NULL, NULL); \
else \
status ## _desc_ = CHAMELEON_Desc_Create(&(_desc_), NULL, _type2_, MB, NB, MB*NB, _lda_, _n_, 0, 0, _m_, _n_, \
P, Q); \
if (status ## _desc_ != CHAMELEON_SUCCESS) return (status ## _desc_); \
}
#define CHAM_PASTE_CODE_FREE_MATRIX(_desc_) \
CHAMELEON_Desc_Destroy( &_desc_ );
#define CHAM_PASTE_TILE_TO_LAPACK(_desc_, _name_, _cond_, _type_, _lda_, _n_) \
_type_ *_name_ = NULL; \
if ( _cond_ ) { \
_name_ = (_type_*)malloc( (_lda_) * (_n_) * sizeof(_type_)); \
if ( ! _name_ ) { \
fprintf(stderr, "Out of Memory for %s\n", #_name_); \
return -1; \
} \
CHAMELEON_Tile_to_Lapack(_desc_, (void*)_name_, _lda_); \
}
#define CHAM_PASTE_CODE_ALLOCATE_MATRIX(_name_, _cond_, _type_, _lda_, _n_) \
_type_ *_name_ = NULL; \
if( _cond_ ) { \
_name_ = (_type_*)malloc( (_lda_) * (_n_) * sizeof(_type_) ); \
if ( ! _name_ ) { \
fprintf(stderr, "Out of Memory for %s\n", #_name_); \
return -1; \
} \
}
#define CHAM_PASTE_CODE_ALLOCATE_COPY(_name_, _cond_, _type_, _orig_, _lda_, _n_) \
_type_ *_name_ = NULL; \
if( _cond_ ) { \
_name_ = (_type_*)malloc( (_lda_) * (_n_) * sizeof(_type_) ); \
if ( ! _name_ ) { \
fprintf(stderr, "Out of Memory for %s\n", #_name_); \
return -1; \
} \
memcpy(_name_, _orig_, (_lda_) * (_n_) * sizeof(_type_) ); \
}
/*********************
*
* General Macros for timing
*
*/
#define START_TIMING1() \
t1=0; \
t1 = -cWtime();
#define STOP_TIMING1() \
t1 += cWtime();
#define START_TIMING2() \
t2=0; \
t2 = -cWtime();
#define STOP_TIMING2() \
t2 += cWtime(); \
*t_ = t1+t2;
#endif /* ITIMING_H */
| {
"alphanum_fraction": 0.4605109489,
"avg_line_length": 39.5953757225,
"ext": "h",
"hexsha": "2bf863af2874fd363f2b4629610b63c2dafce286",
"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": "93bc603d2b6262439a659ef98908839f678f1c95",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ecrc/al4san",
"max_forks_repo_path": "example/gesvp/timing/timing.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "93bc603d2b6262439a659ef98908839f678f1c95",
"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": "ecrc/al4san",
"max_issues_repo_path": "example/gesvp/timing/timing.h",
"max_line_length": 141,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "93bc603d2b6262439a659ef98908839f678f1c95",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ecrc/al4san",
"max_stars_repo_path": "example/gesvp/timing/timing.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-12T19:35:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-02-25T19:18:14.000Z",
"num_tokens": 3657,
"size": 13700
} |
#include <gsl/gsl_rng.h>
#include <gsl/gsl_sort_double.h>
int
main ()
{
gsl_rng * r;
int i, k = 5, N = 100000;
double * x = malloc (N * sizeof(double));
double * small = malloc (k * sizeof(double));
gsl_rng_env_setup();
r = gsl_rng_alloc (gsl_rng_default);
for (i = 0; i < N; i++)
{
x[i] = gsl_rng_uniform(r);
}
gsl_sort_smallest (small, k, x, 1, N);
printf("%d smallest values from %d\n", k, N);
for (i = 0; i < k; i++)
{
printf ("%d: %.18f\n", i, small[i]);
}
}
| {
"alphanum_fraction": 0.5372848948,
"avg_line_length": 15.8484848485,
"ext": "c",
"hexsha": "bd18aefe9a16ca3440c1d9e55208098385cecab2",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/sort/demo.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/sort/demo.c",
"max_line_length": 47,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/sort/demo.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z",
"num_tokens": 181,
"size": 523
} |
#include "ccv.h"
#include "ccv_internal.h"
#ifdef HAVE_CBLAS
#include <cblas.h>
#elif HAVE_ACCELERATE_FRAMEWORK
#include <Accelerate/Accelerate.h>
#endif
double ccv_trace(ccv_matrix_t* mat)
{
return 0;
}
double ccv_norm(ccv_matrix_t* mat, int type)
{
return 0;
}
double ccv_normalize(ccv_matrix_t* a, ccv_matrix_t** b, int btype, int flag)
{
ccv_dense_matrix_t* da = ccv_get_dense_matrix(a);
assert(CCV_GET_CHANNEL(da->type) == CCV_C1);
ccv_declare_derived_signature(sig, da->sig != 0, ccv_sign_with_format(20, "ccv_normalize(%d)", flag), da->sig, CCV_EOF_SIGN);
btype = (btype == 0) ? CCV_GET_DATA_TYPE(da->type) | CCV_C1 : CCV_GET_DATA_TYPE(btype) | CCV_C1;
ccv_dense_matrix_t* db = *b = ccv_dense_matrix_renew(*b, da->rows, da->cols, CCV_ALL_DATA_TYPE | CCV_C1, btype, sig);
assert(db);
ccv_object_return_if_cached(db->tag.f64, db);
double sum = 0, inv;
int i, j;
unsigned char* a_ptr = da->data.u8;
unsigned char* b_ptr = db->data.u8;
switch (flag)
{
case CCV_L1_NORM:
#define for_block(_for_set, _for_get) \
for (i = 0; i < da->rows; i++) \
{ \
for (j = 0; j < da->cols; j++) \
sum += _for_get(a_ptr, j, 0); \
a_ptr += da->step; \
} \
inv = 1.0 / sum; \
a_ptr = da->data.u8; \
for (i = 0; i < da->rows; i++) \
{ \
for (j = 0; j < da->cols; j++) \
_for_set(b_ptr, j, _for_get(a_ptr, j, 0) * inv, 0); \
a_ptr += da->step; \
b_ptr += db->step; \
}
ccv_matrix_setter(db->type, ccv_matrix_getter, da->type, for_block);
#undef for_block
break;
case CCV_L2_NORM:
#define for_block(_for_set, _for_get) \
for (i = 0; i < da->rows; i++) \
{ \
for (j = 0; j < da->cols; j++) \
sum += _for_get(a_ptr, j, 0) * _for_get(a_ptr, j, 0); \
a_ptr += da->step; \
} \
sum = sqrt(sum); \
inv = 1.0 / sum; \
a_ptr = da->data.u8; \
for (i = 0; i < da->rows; i++) \
{ \
for (j = 0; j < da->cols; j++) \
_for_set(b_ptr, j, _for_get(a_ptr, j, 0) * inv, 0); \
a_ptr += da->step; \
b_ptr += db->step; \
}
ccv_matrix_setter(db->type, ccv_matrix_getter, da->type, for_block);
#undef for_block
break;
}
return db->tag.f64 = sum;
}
void ccv_sat(ccv_dense_matrix_t* a, ccv_dense_matrix_t** b, int type, int padding_pattern)
{
ccv_declare_derived_signature(sig, a->sig != 0, ccv_sign_with_format(20, "ccv_sat(%d)", padding_pattern), a->sig, CCV_EOF_SIGN);
int safe_type = (a->type & CCV_8U) ? ((a->rows * a->cols >= 0x808080) ? CCV_64S : CCV_32S) : ((a->type & CCV_32S) ? CCV_64S : a->type);
type = (type == 0) ? CCV_GET_DATA_TYPE(safe_type) | CCV_GET_CHANNEL(a->type) : CCV_GET_DATA_TYPE(type) | CCV_GET_CHANNEL(a->type);
int ch = CCV_GET_CHANNEL(a->type);
int i, j;
unsigned char* a_ptr = a->data.u8;
ccv_dense_matrix_t* db;
unsigned char* b_ptr;
switch (padding_pattern)
{
case CCV_NO_PADDING:
db = *b = ccv_dense_matrix_renew(*b, a->rows, a->cols, CCV_ALL_DATA_TYPE | CCV_GET_CHANNEL(a->type), type, sig);
ccv_object_return_if_cached(, db);
b_ptr = db->data.u8;
#define for_block(_for_set_b, _for_get_b, _for_get) \
for (j = 0; j < ch; j++) \
_for_set_b(b_ptr, j, _for_get(a_ptr, j, 0), 0); \
for (j = ch; j < a->cols * ch; j++) \
_for_set_b(b_ptr, j, _for_get_b(b_ptr, j - ch, 0) + _for_get(a_ptr, j, 0), 0); \
a_ptr += a->step; \
b_ptr += db->step; \
for (i = 1; i < a->rows; i++) \
{ \
for (j = 0; j < ch; j++) \
_for_set_b(b_ptr, j, _for_get_b(b_ptr - db->step, j, 0) + _for_get(a_ptr, j, 0), 0); \
for (j = ch; j < a->cols * ch; j++) \
_for_set_b(b_ptr, j, _for_get_b(b_ptr, j - ch, 0) - _for_get_b(b_ptr - db->step, j - ch, 0) + _for_get_b(b_ptr - db->step, j, 0) + _for_get(a_ptr, j, 0), 0); \
a_ptr += a->step; \
b_ptr += db->step; \
}
ccv_matrix_setter_getter(db->type, ccv_matrix_getter, a->type, for_block);
#undef for_block
break;
case CCV_PADDING_ZERO:
db = *b = ccv_dense_matrix_renew(*b, a->rows + 1, a->cols + 1, CCV_ALL_DATA_TYPE | CCV_GET_CHANNEL(a->type), type, sig);
ccv_object_return_if_cached(, db);
b_ptr = db->data.u8;
#define for_block(_for_set_b, _for_get_b, _for_get) \
for (j = 0; j < db->cols * ch; j++) \
_for_set_b(b_ptr, j, 0, 0); \
b_ptr += db->step; \
for (i = 0; i < a->rows; i++) \
{ \
for (j = 0; j < ch; j++) \
_for_set_b(b_ptr, j, 0, 0); \
for (j = ch; j < db->cols * ch; j++) \
_for_set_b(b_ptr, j, _for_get_b(b_ptr, j - ch, 0) - _for_get_b(b_ptr - db->step, j - ch, 0) + _for_get_b(b_ptr - db->step, j, 0) + _for_get(a_ptr, j - ch, 0), 0); \
a_ptr += a->step; \
b_ptr += db->step; \
}
ccv_matrix_setter_getter(db->type, ccv_matrix_getter, a->type, for_block);
#undef for_block
break;
}
}
double ccv_sum(ccv_matrix_t* mat, int flag)
{
ccv_dense_matrix_t* dmt = ccv_get_dense_matrix(mat);
double sum = 0;
unsigned char* m_ptr = dmt->data.u8;
int i, j, ch = CCV_GET_CHANNEL(dmt->type);
#define for_block(_, _for_get) \
switch (flag) \
{ \
case CCV_UNSIGNED: \
for (i = 0; i < dmt->rows; i++) \
{ \
for (j = 0; j < dmt->cols * ch; j++) \
sum += fabs(_for_get(m_ptr, j, 0)); \
m_ptr += dmt->step; \
} \
break; \
case CCV_SIGNED: \
default: \
for (i = 0; i < dmt->rows; i++) \
{ \
for (j = 0; j < dmt->cols * ch; j++) \
sum += _for_get(m_ptr, j, 0); \
m_ptr += dmt->step; \
} \
}
ccv_matrix_getter(dmt->type, for_block);
#undef for_block
return sum;
}
double ccv_variance(ccv_matrix_t* mat)
{
ccv_dense_matrix_t* dmt = ccv_get_dense_matrix(mat);
double mean = 0, variance = 0;
unsigned char* m_ptr = dmt->data.u8;
int i, j, ch = CCV_GET_CHANNEL(dmt->type);
#define for_block(_, _for_get) \
for (i = 0; i < dmt->rows; i++) \
{ \
for (j = 0; j < dmt->cols * ch; j++) \
{ \
mean += _for_get(m_ptr, j, 0); \
variance += _for_get(m_ptr, j, 0) * _for_get(m_ptr, j, 0); \
} \
m_ptr += dmt->step; \
}
ccv_matrix_getter(dmt->type, for_block);
#undef for_block
mean = mean / (dmt->rows * dmt->cols * ch);
variance = variance / (dmt->rows * dmt->cols * ch);
return variance - mean * mean;
}
void ccv_multiply(ccv_matrix_t* a, ccv_matrix_t* b, ccv_matrix_t** c, int type)
{
ccv_dense_matrix_t* da = ccv_get_dense_matrix(a);
ccv_dense_matrix_t* db = ccv_get_dense_matrix(b);
assert(da->rows == db->rows && da->cols == db->cols && CCV_GET_DATA_TYPE(da->type) == CCV_GET_DATA_TYPE(db->type) && CCV_GET_CHANNEL(da->type) == CCV_GET_CHANNEL(db->type));
ccv_declare_derived_signature(sig, da->sig != 0 && db->sig != 0, ccv_sign_with_literal("ccv_multiply"), da->sig, db->sig, CCV_EOF_SIGN);
int no_8u_type = (da->type & CCV_8U) ? CCV_32S : da->type;
type = (type == 0) ? CCV_GET_DATA_TYPE(no_8u_type) | CCV_GET_CHANNEL(da->type) : CCV_GET_DATA_TYPE(type) | CCV_GET_CHANNEL(da->type);
ccv_dense_matrix_t* dc = *c = ccv_dense_matrix_renew(*c, da->rows, da->cols, CCV_ALL_DATA_TYPE | CCV_GET_CHANNEL(da->type), type, sig);
ccv_object_return_if_cached(, dc);
int i, j, ch = CCV_GET_CHANNEL(da->type);
unsigned char* aptr = da->data.u8;
unsigned char* bptr = db->data.u8;
unsigned char* cptr = dc->data.u8;
#define for_block(_for_get, _for_set) \
for (i = 0; i < da->rows; i++) \
{ \
for (j = 0; j < da->cols * ch; j++) \
_for_set(cptr, j, _for_get(aptr, j, 0) * _for_get(bptr, j, 0), 0); \
aptr += da->step; \
bptr += db->step; \
cptr += dc->step; \
}
ccv_matrix_getter(da->type, ccv_matrix_setter, dc->type, for_block);
#undef for_block
}
void ccv_add(ccv_matrix_t* a, ccv_matrix_t* b, ccv_matrix_t** c, int type)
{
ccv_dense_matrix_t* da = ccv_get_dense_matrix(a);
ccv_dense_matrix_t* db = ccv_get_dense_matrix(b);
assert(da->rows == db->rows && da->cols == db->cols && CCV_GET_CHANNEL(da->type) == CCV_GET_CHANNEL(db->type));
ccv_declare_derived_signature(sig, da->sig != 0 && db->sig != 0, ccv_sign_with_literal("ccv_add"), da->sig, db->sig, CCV_EOF_SIGN);
int no_8u_type = (da->type & CCV_8U) ? CCV_32S : da->type;
type = (type == 0) ? CCV_GET_DATA_TYPE(no_8u_type) | CCV_GET_CHANNEL(da->type) : CCV_GET_DATA_TYPE(type) | CCV_GET_CHANNEL(da->type);
ccv_dense_matrix_t* dc = *c = ccv_dense_matrix_renew(*c, da->rows, da->cols, CCV_ALL_DATA_TYPE | CCV_GET_CHANNEL(da->type), type, sig);
ccv_object_return_if_cached(, dc);
int i, j, ch = CCV_GET_CHANNEL(da->type);
unsigned char* aptr = da->data.u8;
unsigned char* bptr = db->data.u8;
unsigned char* cptr = dc->data.u8;
#define for_block(_for_get_a, _for_get_b, _for_set) \
for (i = 0; i < da->rows; i++) \
{ \
for (j = 0; j < da->cols * ch; j++) \
_for_set(cptr, j, _for_get_a(aptr, j, 0) + _for_get_b(bptr, j, 0), 0); \
aptr += da->step; \
bptr += db->step; \
cptr += dc->step; \
}
ccv_matrix_getter_a(da->type, ccv_matrix_getter_b, db->type, ccv_matrix_setter, dc->type, for_block);
#undef for_block
}
void ccv_subtract(ccv_matrix_t* a, ccv_matrix_t* b, ccv_matrix_t** c, int type)
{
ccv_dense_matrix_t* da = ccv_get_dense_matrix(a);
ccv_dense_matrix_t* db = ccv_get_dense_matrix(b);
assert(da->rows == db->rows && da->cols == db->cols && CCV_GET_DATA_TYPE(da->type) == CCV_GET_DATA_TYPE(db->type) && CCV_GET_CHANNEL(da->type) == CCV_GET_CHANNEL(db->type));
ccv_declare_derived_signature(sig, da->sig != 0 && db->sig != 0, ccv_sign_with_literal("ccv_subtract"), da->sig, db->sig, CCV_EOF_SIGN);
int no_8u_type = (da->type & CCV_8U) ? CCV_32S : da->type;
type = (type == 0) ? CCV_GET_DATA_TYPE(no_8u_type) | CCV_GET_CHANNEL(da->type) : CCV_GET_DATA_TYPE(type) | CCV_GET_CHANNEL(da->type);
ccv_dense_matrix_t* dc = *c = ccv_dense_matrix_renew(*c, da->rows, da->cols, CCV_ALL_DATA_TYPE | CCV_GET_CHANNEL(da->type), type, sig);
ccv_object_return_if_cached(, dc);
int i, j, ch = CCV_GET_CHANNEL(da->type);
unsigned char* aptr = da->data.u8;
unsigned char* bptr = db->data.u8;
unsigned char* cptr = dc->data.u8;
#define for_block(_for_get, _for_set) \
for (i = 0; i < da->rows; i++) \
{ \
for (j = 0; j < da->cols * ch; j++) \
_for_set(cptr, j, _for_get(aptr, j, 0) - _for_get(bptr, j, 0), 0); \
aptr += da->step; \
bptr += db->step; \
cptr += dc->step; \
}
ccv_matrix_getter(da->type, ccv_matrix_setter, dc->type, for_block);
#undef for_block
}
void ccv_gemm(ccv_matrix_t* a, ccv_matrix_t* b, double alpha, ccv_matrix_t* c, double beta, int transpose, ccv_matrix_t** d, int type)
{
ccv_dense_matrix_t* da = ccv_get_dense_matrix(a);
ccv_dense_matrix_t* db = ccv_get_dense_matrix(b);
ccv_dense_matrix_t* dc = (c == 0) ? 0 : ccv_get_dense_matrix(c);
assert(CCV_GET_DATA_TYPE(da->type) == CCV_GET_DATA_TYPE(db->type) && CCV_GET_CHANNEL(da->type) == 1 && CCV_GET_CHANNEL(db->type) == 1 && ((transpose & CCV_A_TRANSPOSE) ? da->rows : da->cols) == ((transpose & CCV_B_TRANSPOSE) ? db->cols : db->rows));
if (dc != 0)
assert(CCV_GET_DATA_TYPE(dc->type) == CCV_GET_DATA_TYPE(da->type) && CCV_GET_CHANNEL(dc->type) == 1 && ((transpose & CCV_A_TRANSPOSE) ? da->cols : da->rows) == dc->rows && ((transpose & CCV_B_TRANSPOSE) ? db->rows : db->cols) == dc->cols);
ccv_declare_derived_signature_case(sig, ccv_sign_with_format(20, "ccv_gemm(%d)", transpose), ccv_sign_if(dc == 0 && da->sig != 0 && db->sig != 0, da->sig, db->sig, CCV_EOF_SIGN), ccv_sign_if(dc != 0 && da->sig != 0 && db->sig != 0 && dc->sig != 0, da->sig, db->sig, dc->sig, CCV_EOF_SIGN));
type = CCV_GET_DATA_TYPE(da->type) | CCV_GET_CHANNEL(da->type);
ccv_dense_matrix_t* dd = *d = ccv_dense_matrix_renew(*d, (transpose & CCV_A_TRANSPOSE) ? da->cols : da->rows, (transpose & CCV_B_TRANSPOSE) ? db->rows : db->cols, type, type, sig);
ccv_object_return_if_cached(, dd);
if (dd != dc && dc != 0)
memcpy(dd->data.u8, dc->data.u8, dc->step * dc->rows);
else if (dc == 0) // clean up dd if dc is not provided
memset(dd->data.u8, 0, dd->step * dd->rows);
#if (defined HAVE_CBLAS || defined HAVE_ACCELERATE_FRAMEWORK)
switch (CCV_GET_DATA_TYPE(dd->type))
{
case CCV_32F:
cblas_sgemm(CblasRowMajor, (transpose & CCV_A_TRANSPOSE) ? CblasTrans : CblasNoTrans, (transpose & CCV_B_TRANSPOSE) ? CblasTrans : CblasNoTrans, dd->rows, dd->cols, (transpose & CCV_A_TRANSPOSE) ? da->rows : da->cols, alpha, da->data.f32, da->cols, db->data.f32, db->cols, beta, dd->data.f32, dd->cols);
break;
case CCV_64F:
cblas_dgemm(CblasRowMajor, (transpose & CCV_A_TRANSPOSE) ? CblasTrans : CblasNoTrans, (transpose & CCV_B_TRANSPOSE) ? CblasTrans : CblasNoTrans, dd->rows, dd->cols, (transpose & CCV_A_TRANSPOSE) ? da->rows : da->cols, alpha, da->data.f64, da->cols, db->data.f64, db->cols, beta, dd->data.f64, dd->cols);
break;
}
#else
assert(0 && "You need a BLAS compatible library for this function, e.g. libatlas.");
#endif
}
| {
"alphanum_fraction": 0.6425396825,
"avg_line_length": 41.0423452769,
"ext": "c",
"hexsha": "c185c9f568783a160804f7beda31de2cffd4d091",
"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": "e098d566094850e3f77aa1cd1093f38eb8f4baa5",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "mrgloom/ccv",
"max_forks_repo_path": "lib/ccv_algebra.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e098d566094850e3f77aa1cd1093f38eb8f4baa5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "mrgloom/ccv",
"max_issues_repo_path": "lib/ccv_algebra.c",
"max_line_length": 306,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e098d566094850e3f77aa1cd1093f38eb8f4baa5",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "mrgloom/ccv",
"max_stars_repo_path": "lib/ccv_algebra.c",
"max_stars_repo_stars_event_max_datetime": "2020-12-27T13:51:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-27T13:51:53.000Z",
"num_tokens": 4616,
"size": 12600
} |
#include <stdio.h>
#include <sys/time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#define NUMBER_OF_ELEMENTS 1
#define MEAN 0
#define STANDARD_DEVIATION 1
int main (int argc, char *argv[])
{
int number_of_elements;
if (argc == 1) {
number_of_elements = NUMBER_OF_ELEMENTS;
} else if (argc == 2) {
number_of_elements = atoi(argv[1]);
} else {
fprintf(stderr, "%s\n", "Wrong number of arguments.");
fprintf(stderr, "%s\n", "Use: ./normal_numbers number_of_elements");
exit(EXIT_FAILURE);
}
double *numbers = malloc (number_of_elements * sizeof(double));
double mean = MEAN;
double standard_deviation = STANDARD_DEVIATION;
// declare the necessary random number generator variables
const gsl_rng_type *T;
gsl_rng *r;
// set the default values for the random number generator variables
gsl_rng_env_setup();
// create a seed based on time
struct timeval tv;
gettimeofday(&tv,0);
unsigned long seed = tv.tv_sec + tv.tv_usec;
// setup the generator using the seed just created
T = gsl_rng_default;
r = gsl_rng_alloc (T);
gsl_rng_set(r, seed);
// generate number_of_elements normal random numbers
for (int i = 0; i < number_of_elements; i++) {
numbers[i] = mean + gsl_ran_gaussian (r, standard_deviation);
}
// print numbers
if(number_of_elements < 10) {
for (int i = 0; i < number_of_elements; i++) {
printf (" %f", numbers[i]);
}
printf("\n");
} else {
printf("Done.\n");
}
// free memory
gsl_rng_free (r);
free(numbers);
return 0;
}
| {
"alphanum_fraction": 0.54375,
"avg_line_length": 28.6567164179,
"ext": "c",
"hexsha": "0f69e0694792514b7561aaf7b092a4321bea431a",
"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": "9117a59b246ced3d82803cfd7b82b05f8a456d97",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sernamar/random-numbers",
"max_forks_repo_path": "C/normal_numbers.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9117a59b246ced3d82803cfd7b82b05f8a456d97",
"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": "sernamar/random-numbers",
"max_issues_repo_path": "C/normal_numbers.c",
"max_line_length": 84,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9117a59b246ced3d82803cfd7b82b05f8a456d97",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sernamar/random-numbers",
"max_stars_repo_path": "C/normal_numbers.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 430,
"size": 1920
} |
/* Foundation and miscellenea for the statistics modules.
*
* Contents:
* 1. Summary statistics (means, variances)
* 2. Special functions
* 3. Standard statistical tests
* 4. Data fitting.
* 5. Unit tests.
* 6. Test driver.
* 7. Examples.
* - driver for linear regression
* - driver for G-test
* 8. License and copyright information.
*
*/
#include "esl_config.h"
#include <math.h>
#include "easel.h"
#include "esl_stats.h"
/*****************************************************************
* 1. Summary statistics calculations (means, variances)
*****************************************************************/
/* Function: esl_stats_DMean()
* Synopsis: Calculates mean and $\sigma^2$ for samples $x_i$.
*
* Purpose: Calculates the sample mean and $s^2$, the unbiased
* estimator of the population variance, for a
* sample of <n> numbers <x[0]..x[n-1]>, and optionally
* returns either or both through <ret_mean> and
* <ret_var>.
*
* <esl_stats_FMean()> and <esl_stats_IMean()> do the same,
* for float and integer vectors.
*
* Args: x - samples x[0]..x[n-1]
* n - number of samples
* opt_mean - optRETURN: mean
* opt_var - optRETURN: estimate of population variance
*
* Returns: <eslOK> on success.
*/
int
esl_stats_DMean(const double *x, int n, double *opt_mean, double *opt_var)
{
double sum = 0.;
double sqsum = 0.;
int i;
for (i = 0; i < n; i++)
{
sum += x[i];
sqsum += x[i]*x[i];
}
if (opt_mean != NULL) *opt_mean = sum / (double) n;
if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1);
return eslOK;
}
int
esl_stats_FMean(const float *x, int n, double *opt_mean, double *opt_var)
{
double sum = 0.;
double sqsum = 0.;
int i;
for (i = 0; i < n; i++)
{
sum += x[i];
sqsum += x[i]*x[i];
}
if (opt_mean != NULL) *opt_mean = sum / (double) n;
if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1);
return eslOK;
}
int
esl_stats_IMean(const int *x, int n, double *opt_mean, double *opt_var)
{
double sum = 0.;
double sqsum = 0.;
int i;
for (i = 0; i < n; i++)
{
sum += x[i];
sqsum += x[i]*x[i];
}
if (opt_mean != NULL) *opt_mean = sum / (double) n;
if (opt_var != NULL) *opt_var = (sqsum - sum*sum/(double)n) / ((double)n-1);
return eslOK;
}
/*--------------- end, summary statistics -----------------------*/
/*****************************************************************
* 2. Special functions.
*****************************************************************/
/* Function: esl_stats_LogGamma()
* Synopsis: Calculates $\log \Gamma(x)$.
*
* Purpose: Returns natural log of $\Gamma(x)$, for $x > 0$.
*
* Credit: Adapted from a public domain implementation in the
* NCBI core math library. Thanks to John Spouge and
* the NCBI. (According to NCBI, that's Dr. John
* "Gammas Galore" Spouge to you, pal.)
*
* Args: x : argument, x > 0.0
* ret_answer : RETURN: the answer
*
* Returns: Put the answer in <ret_answer>; returns <eslOK>.
*
* Throws: <eslERANGE> if $x <= 0$.
*/
int
esl_stats_LogGamma(double x, double *ret_answer)
{
int i;
double xx, tx;
double tmp, value;
static double cof[11] = {
4.694580336184385e+04,
-1.560605207784446e+05,
2.065049568014106e+05,
-1.388934775095388e+05,
5.031796415085709e+04,
-9.601592329182778e+03,
8.785855930895250e+02,
-3.155153906098611e+01,
2.908143421162229e-01,
-2.319827630494973e-04,
1.251639670050933e-10
};
/* Protect against invalid x<=0 */
if (x <= 0.0) ESL_EXCEPTION(eslERANGE, "invalid x <= 0 in esl_stats_LogGamma()");
xx = x - 1.0;
tx = tmp = xx + 11.0;
value = 1.0;
for (i = 10; i >= 0; i--) /* sum least significant terms first */
{
value += cof[i] / tmp;
tmp -= 1.0;
}
value = log(value);
tx += 0.5;
value += 0.918938533 + (xx+0.5)*log(tx) - tx;
*ret_answer = value;
return eslOK;
}
/* Function: esl_stats_Psi()
* Synopsis: Calculates $\Psi(x)$ (the digamma function).
*
* Purpose: Computes $\Psi(x)$ (the "digamma" function), which is
* the derivative of log of the Gamma function:
* $d/dx \log \Gamma(x) = \frac{\Gamma'(x)}{\Gamma(x)} = \Psi(x)$.
* Argument $x$ is $> 0$.
*
* This is J.M. Bernardo's "Algorithm AS103",
* Appl. Stat. 25:315-317 (1976).
*/
int
esl_stats_Psi(double x, double *ret_answer)
{
double answer = 0.;
double x2;
if (x <= 0.0) ESL_EXCEPTION(eslERANGE, "invalid x <= 0 in esl_stats_Psi()");
/* For small x, Psi(x) ~= -0.5772 - 1/x + O(x), we're done.
*/
if (x <= 1e-5) {
*ret_answer = -eslCONST_EULER - 1./x;
return eslOK;
}
/* For medium x, use Psi(1+x) = \Psi(x) + 1/x to c.o.v. x,
* big enough for Stirling approximation to work...
*/
while (x < 8.5) {
answer = answer - 1./x;
x += 1.;
}
/* For large X, use Stirling approximation
*/
x2 = 1./x;
answer += log(x) - 0.5 * x2;
x2 = x2*x2;
answer -= (1./12.)*x2;
answer += (1./120.)*x2*x2;
answer -= (1./252.)*x2*x2*x2;
*ret_answer = answer;
return eslOK;
}
/* Function: esl_stats_IncompleteGamma()
* Synopsis: Calculates the incomplete Gamma function.
*
* Purpose: Returns $P(a,x)$ and $Q(a,x)$ where:
*
* \begin{eqnarray*}
* P(a,x) & = & \frac{1}{\Gamma(a)} \int_{0}^{x} t^{a-1} e^{-t} dt \\
* & = & \frac{\gamma(a,x)}{\Gamma(a)} \\
* Q(a,x) & = & \frac{1}{\Gamma(a)} \int_{x}^{\infty} t^{a-1} e^{-t} dt\\
* & = & 1 - P(a,x) \\
* \end{eqnarray*}
*
* $P(a,x)$ is the CDF of a gamma density with $\lambda = 1$,
* and $Q(a,x)$ is the survival function.
*
* For $x \simeq 0$, $P(a,x) \simeq 0$ and $Q(a,x) \simeq 1$; and
* $P(a,x)$ is less prone to roundoff error.
*
* The opposite is the case for large $x >> a$, where
* $P(a,x) \simeq 1$ and $Q(a,x) \simeq 0$; there, $Q(a,x)$ is
* less prone to roundoff error.
*
* Method: Based on ideas from Numerical Recipes in C, Press et al.,
* Cambridge University Press, 1988.
*
* Args: a - for instance, degrees of freedom / 2 [a > 0]
* x - for instance, chi-squared statistic / 2 [x >= 0]
* ret_pax - RETURN: P(a,x)
* ret_qax - RETURN: Q(a,x)
*
* Return: <eslOK> on success.
*
* Throws: <eslERANGE> if <a> or <x> is out of accepted range.
* <eslENOHALT> if approximation fails to converge.
*/
int
esl_stats_IncompleteGamma(double a, double x, double *ret_pax, double *ret_qax)
{
int iter; /* iteration counter */
double pax; /* P(a,x) */
double qax; /* Q(a,x) */
if (a <= 0.) ESL_EXCEPTION(eslERANGE, "esl_stats_IncompleteGamma(): a must be > 0");
if (x < 0.) ESL_EXCEPTION(eslERANGE, "esl_stats_IncompleteGamma(): x must be >= 0");
/* For x > a + 1 the following gives rapid convergence;
* calculate Q(a,x) = \frac{\Gamma(a,x)}{\Gamma(a)},
* using a continued fraction development for \Gamma(a,x).
*/
if (x > a+1)
{
double oldp; /* previous value of p */
double nu0, nu1; /* numerators for continued fraction calc */
double de0, de1; /* denominators for continued fraction calc */
nu0 = 0.; /* A_0 = 0 */
de0 = 1.; /* B_0 = 1 */
nu1 = 1.; /* A_1 = 1 */
de1 = x; /* B_1 = x */
oldp = nu1;
for (iter = 1; iter < 100; iter++)
{
/* Continued fraction development:
* set A_j = b_j A_j-1 + a_j A_j-2
* B_j = b_j B_j-1 + a_j B_j-2
* We start with A_2, B_2.
*/
/* j = even: a_j = iter-a, b_j = 1 */
/* A,B_j-2 are in nu0, de0; A,B_j-1 are in nu1,de1 */
nu0 = nu1 + ((double)iter - a) * nu0;
de0 = de1 + ((double)iter - a) * de0;
/* j = odd: a_j = iter, b_j = x */
/* A,B_j-2 are in nu1, de1; A,B_j-1 in nu0,de0 */
nu1 = x * nu0 + (double) iter * nu1;
de1 = x * de0 + (double) iter * de1;
/* rescale */
if (de1 != 0.)
{
nu0 /= de1;
de0 /= de1;
nu1 /= de1;
de1 = 1.;
}
/* check for convergence */
if (fabs((nu1-oldp)/nu1) < 1.e-7)
{
esl_stats_LogGamma(a, &qax);
qax = nu1 * exp(a * log(x) - x - qax);
if (ret_pax != NULL) *ret_pax = 1 - qax;
if (ret_qax != NULL) *ret_qax = qax;
return eslOK;
}
oldp = nu1;
}
ESL_EXCEPTION(eslENOHALT,
"esl_stats_IncompleteGamma(): fraction failed to converge");
}
else /* x <= a+1 */
{
double p; /* current sum */
double val; /* current value used in sum */
/* For x <= a+1 we use a convergent series instead:
* P(a,x) = \frac{\gamma(a,x)}{\Gamma(a)},
* where
* \gamma(a,x) = e^{-x}x^a \sum_{n=0}{\infty} \frac{\Gamma{a}}{\Gamma{a+1+n}} x^n
* which looks appalling but the sum is in fact rearrangeable to
* a simple series without the \Gamma functions:
* = \frac{1}{a} + \frac{x}{a(a+1)} + \frac{x^2}{a(a+1)(a+2)} ...
* and it's obvious that this should converge nicely for x <= a+1.
*/
p = val = 1. / a;
for (iter = 1; iter < 10000; iter++)
{
val *= x / (a+(double)iter);
p += val;
if (fabs(val/p) < 1.e-7)
{
esl_stats_LogGamma(a, &pax);
pax = p * exp(a * log(x) - x - pax);
if (ret_pax != NULL) *ret_pax = pax;
if (ret_qax != NULL) *ret_qax = 1. - pax;
return eslOK;
}
}
ESL_EXCEPTION(eslENOHALT,
"esl_stats_IncompleteGamma(): series failed to converge");
}
/*NOTREACHED*/
return eslOK;
}
/*----------------- end, special functions ----------------------*/
/*****************************************************************
* 3. Standard statistical tests.
*****************************************************************/
/* Function: esl_stats_GTest()
* Synopsis: Calculates a G-test on 2 vs. 1 binomials.
*
* Purpose: In experiment a, we've drawn <ca> successes in <na> total
* trials; in experiment b, we've drawn <cb> successes in
* <nb> total trials. Are the counts different enough to
* conclude that the two experiments are different? The
* null hypothesis is that the successes in both experiments
* were drawn from the same binomial distribution with
* per-trial probability $p$. The tested hypothesis is that
* experiments a,b have different binomial probabilities
* $p_a,p_b$. The G-test is a log-likelihood-ratio statistic,
* assuming maximum likelihood values for $p,p_a,p_b$.
* $2G$ is distributed approximately as $X^2(1)$,
* %"X" is "Chi"
* which we use to calculate a P-value for the G statistic.
*
* Args: ca - number of positives in experiment a
* na - total number in experiment a
* cb - number of positives in experiment b
* nb - total number in experiment b
* ret_G - RETURN: G statistic, a log likelihood ratio, in nats
* ret_P - RETURN: P-value for the G-statistic
*
* Returns: <eslOK> on success.
*
* Throws: (no abnormal error conditions)
*
* Xref: Archive1999/0906-sagescore/sagescore.c
*/
int
esl_stats_GTest(int ca, int na, int cb, int nb, double *ret_G, double *ret_P)
{
double a,b,c,d,n;
double G = 0.;
a = (double) ca;
b = (double) (na - ca);
c = (double) cb;
d = (double) (nb - cb);
n = (double) na+nb;
/* Yes, the calculation here is correct; algebraic
* rearrangement of the log-likelihood-ratio with
* p_a = ca/na, p_b = cb/nb, and p = (ca+cb)/(na+nb).
* Guard against 0 probabilities; assume 0 log 0 => 0.
*/
if (a > 0.) G = a * log(a);
if (b > 0.) G += b * log(b);
if (c > 0.) G += c * log(c);
if (d > 0.) G += d * log(d);
if (n > 0.) G += n * log(n);
if (a+b > 0.) G -= (a+b) * log(a+b);
if (c+d > 0.) G -= (c+d) * log(c+d);
if (a+c > 0.) G -= (a+c) * log(a+c);
if (b+d > 0.) G -= (b+d) * log(b+d);
*ret_G = G;
return esl_stats_IncompleteGamma( 0.5, G, NULL, ret_P);
}
/* Function: esl_stats_ChiSquaredTest()
* Synopsis: Calculates a $\chi^2$ P-value.
* Incept: SRE, Tue Jul 19 11:39:32 2005 [St. Louis]
*
* Purpose: Calculate the probability that a chi-squared statistic
* with <v> degrees of freedom would exceed the observed
* chi-squared value <x>; return it in <ret_answer>. If
* this probability is less than some small threshold (say,
* 0.05 or 0.01), then we may reject the hypothesis we're
* testing.
*
* Args: v - degrees of freedom
* x - observed chi-squared value
* ret_answer - RETURN: P(\chi^2 > x)
*
* Returns: <eslOK> on success.
*
* Throws: <eslERANGE> if <v> or <x> are out of valid range.
* <eslENOHALT> if iterative calculation fails.
*/
int
esl_stats_ChiSquaredTest(int v, double x, double *ret_answer)
{
return esl_stats_IncompleteGamma((double)v/2, x/2, NULL, ret_answer);
}
/*----------------- end, statistical tests ---------------------*/
/*****************************************************************
* 4. Data fitting.
*****************************************************************/
/* Function: esl_stats_LinearRegression()
* Synopsis: Fit data to a straight line.
* Incept: SRE, Sat May 26 11:33:46 2007 [Janelia]
*
* Purpose: Fit <n> points <x[i]>, <y[i]> to a straight line
* $y = a + bx$ by linear regression.
*
* The $x_i$ are taken to be known, and the $y_i$ are taken
* to be observed quantities associated with a sampling
* error $\sigma_i$. If known, the standard deviations
* $\sigma_i$ for $y_i$ are provided in the <sigma> array.
* If they are unknown, pass <sigma = NULL>, and the
* routine will proceed with the assumption that $\sigma_i
* = 1$ for all $i$.
*
* The maximum likelihood estimates for $a$ and $b$ are
* optionally returned in <opt_a> and <opt_b>.
*
* The estimated standard deviations of $a$ and $b$ and
* their estimated covariance are optionally returned in
* <opt_sigma_a>, <opt_sigma_b>, and <opt_cov_ab>.
*
* The Pearson correlation coefficient is optionally
* returned in <opt_cc>.
*
* The $\chi^2$ P-value for the regression fit is
* optionally returned in <opt_Q>. This P-value may only be
* obtained when the $\sigma_i$ are known. If <sigma> is
* passed as <NULL> and <opt_Q> is requested, <*opt_Q> is
* set to 1.0.
*
* This routine follows the description and algorithm in
* \citep[pp.661-666]{Press93}.
*
* <n> must be greater than 2; at least two x[i] must
* differ; and if <sigma> is provided, all <sigma[i]> must
* be $>0$. If any of these conditions isn't met, the
* routine throws <eslEINVAL>.
*
* Args: x - x[0..n-1]
* y - y[0..n-1]
* sigma - sample error in observed y_i
* n - number of data points
* opt_a - optRETURN: intercept estimate
* opt_b - optRETURN: slope estimate
* opt_sigma_a - optRETURN: error in estimate of a
* opt_sigma_b - optRETURN: error in estimate of b
* opt_cov_ab - optRETURN: covariance of a,b estimates
* opt_cc - optRETURN: Pearson correlation coefficient for x,y
* opt_Q - optRETURN: X^2 P-value for linear fit
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on allocation error;
* <eslEINVAL> if a contract condition isn't met;
* <eslENORESULT> if the chi-squared test fails.
* In these cases, all optional return values are set to 0.
*/
int
esl_stats_LinearRegression(const double *x, const double *y, const double *sigma, int n,
double *opt_a, double *opt_b,
double *opt_sigma_a, double *opt_sigma_b, double *opt_cov_ab,
double *opt_cc, double *opt_Q)
{
int status;
double *t = NULL;
double S, Sx, Sy, Stt;
double Sxy, Sxx, Syy;
double a, b, sigma_a, sigma_b, cov_ab, cc, X2, Q;
double xdev, ydev;
double tmp;
int i;
/* Contract checks. */
if (n <= 2) ESL_XEXCEPTION(eslEINVAL, "n must be > 2 for linear regression fitting");
if (sigma != NULL)
for (i = 0; i < n; i++) if (sigma[i] <= 0.) ESL_XEXCEPTION(eslEINVAL, "sigma[%d] <= 0", i);
status = eslEINVAL;
for (i = 0; i < n; i++) if (x[i] != 0.) { status = eslOK; break; }
if (status != eslOK) ESL_XEXCEPTION(eslEINVAL, "all x[i] are 0.");
/* Allocations */
ESL_ALLOC(t, sizeof(double) * n);
/* S = \sum_{i=1}{n} \frac{1}{\sigma_i^2}. (S > 0.) */
if (sigma != NULL) { for (S = 0., i = 0; i < n; i++) S += 1./ (sigma[i] * sigma[i]); }
else S = (double) n;
/* S_x = \sum_{i=1}{n} \frac{x[i]}{ \sigma_i^2} (Sx real.) */
for (Sx = 0., i = 0; i < n; i++) {
if (sigma == NULL) Sx += x[i];
else Sx += x[i] / (sigma[i] * sigma[i]);
}
/* S_y = \sum_{i=1}{n} \frac{y[i]}{\sigma_i^2} (Sy real.) */
for (Sy = 0., i = 0; i < n; i++) {
if (sigma == NULL) Sy += y[i];
else Sy += y[i] / (sigma[i] * sigma[i]);
}
/* t_i = \frac{1}{\sigma_i} \left( x_i - \frac{S_x}{S} \right) (t_i real) */
for (i = 0; i < n; i++) {
t[i] = x[i] - Sx/S;
if (sigma != NULL) t[i] /= sigma[i];
}
/* S_{tt} = \sum_{i=1}^n t_i^2 (if at least one x is != 0, Stt > 0) */
for (Stt = 0., i = 0; i < n; i++) { Stt += t[i] * t[i]; }
/* b = \frac{1}{S_{tt}} \sum_{i=1}^{N} \frac{t_i y_i}{\sigma_i} */
for (b = 0., i = 0; i < n; i++) {
if (sigma != NULL) { b += t[i]*y[i] / sigma[i]; }
else { b += t[i]*y[i]; }
}
b /= Stt;
/* a = \frac{ S_y - S_x b } {S} */
a = (Sy - Sx * b) / S;
/* \sigma_a^2 = \frac{1}{S} \left( 1 + \frac{ S_x^2 }{S S_{tt}} \right) */
sigma_a = sqrt ((1. + (Sx*Sx) / (S*Stt)) / S);
/* \sigma_b = \frac{1}{S_{tt}} */
sigma_b = sqrt (1. / Stt);
/* Cov(a,b) = - \frac{S_x}{S S_{tt}} */
cov_ab = -Sx / (S * Stt);
/* Pearson correlation coefficient */
Sxy = Sxx = Syy = 0.;
for (i = 0; i < n; i++) {
if (sigma != NULL) {
xdev = (x[i] / (sigma[i] * sigma[i])) - (Sx / n);
ydev = (y[i] / (sigma[i] * sigma[i])) - (Sy / n);
} else {
xdev = x[i] - (Sx / n);
ydev = y[i] - (Sy / n);
}
Sxy += xdev * ydev;
Sxx += xdev * xdev;
Syy += ydev * ydev;
}
cc = Sxy / (sqrt(Sxx) * sqrt(Syy));
/* \chi^2 */
for (X2 = 0., i = 0; i < n; i++) {
tmp = y[i] - a - b*x[i];
if (sigma != NULL) tmp /= sigma[i];
X2 += tmp*tmp;
}
/* We can calculate a goodness of fit if we know the \sigma_i */
if (sigma != NULL) {
if (esl_stats_ChiSquaredTest(n-2, X2, &Q) != eslOK) { status = eslENORESULT; goto ERROR; }
} else Q = 1.0;
/* If we didn't use \sigma_i, adjust the sigmas for a,b */
if (sigma == NULL) {
tmp = sqrt(X2 / (double)(n-2));
sigma_a *= tmp;
sigma_b *= tmp;
}
/* Done. Set up for normal return.
*/
free(t);
if (opt_a != NULL) *opt_a = a;
if (opt_b != NULL) *opt_b = b;
if (opt_sigma_a != NULL) *opt_sigma_a = sigma_a;
if (opt_sigma_b != NULL) *opt_sigma_b = sigma_b;
if (opt_cov_ab != NULL) *opt_cov_ab = cov_ab;
if (opt_cc != NULL) *opt_cc = cc;
if (opt_Q != NULL) *opt_Q = Q;
return eslOK;
ERROR:
if (t != NULL) free(t);
if (opt_a != NULL) *opt_a = 0.;
if (opt_b != NULL) *opt_b = 0.;
if (opt_sigma_a != NULL) *opt_sigma_a = 0.;
if (opt_sigma_b != NULL) *opt_sigma_b = 0.;
if (opt_cov_ab != NULL) *opt_cov_ab = 0.;
if (opt_cc != NULL) *opt_cc = 0.;
if (opt_Q != NULL) *opt_Q = 0.;
return status;
}
/*------------------- end, data fitting -------------------------*/
/*****************************************************************
* 5. Unit tests.
*****************************************************************/
#ifdef eslSTATS_TESTDRIVE
#include "esl_random.h"
#include "esl_stopwatch.h"
#ifdef HAVE_LIBGSL
#include <gsl/gsl_sf_gamma.h>
#endif
/* The LogGamma() function is rate-limiting in hmmbuild, because it is
* used so heavily in mixture Dirichlet calculations.
* ./configure --with-gsl; [compile test driver]
* ./stats_utest -v
* runs a comparison of time/precision against GSL.
* SRE, Sat May 23 10:04:41 2009, on home Mac:
* LogGamma = 1.29u / N=1e8 = 13 nsec/call
* gsl_sf_lngamma = 1.43u / N=1e8 = 14 nsec/call
*/
static void
utest_LogGamma(ESL_RANDOMNESS *r, int N, int be_verbose)
{
char *msg = "esl_stats_LogGamma() unit test failed";
ESL_STOPWATCH *w = esl_stopwatch_Create();
double *x = malloc(sizeof(double) * N);
double *lg = malloc(sizeof(double) * N);
double *lg2 = malloc(sizeof(double) * N);
int i;
for (i = 0; i < N; i++)
x[i] = esl_random(r) * 100.;
esl_stopwatch_Start(w);
for (i = 0; i < N; i++)
if (esl_stats_LogGamma(x[i], &(lg[i])) != eslOK) esl_fatal(msg);
esl_stopwatch_Stop(w);
if (be_verbose) esl_stopwatch_Display(stdout, w, "esl_stats_LogGamma() timing: ");
#ifdef HAVE_LIBGSL
esl_stopwatch_Start(w);
for (i = 0; i < N; i++) lg2[i] = gsl_sf_lngamma(x[i]);
esl_stopwatch_Stop(w);
if (be_verbose) esl_stopwatch_Display(stdout, w, "gsl_sf_lngamma() timing: ");
for (i = 0; i < N; i++)
if (esl_DCompare(lg[i], lg2[i], 1e-2) != eslOK) esl_fatal(msg);
#endif
free(lg2);
free(lg);
free(x);
esl_stopwatch_Destroy(w);
}
/* The test of esl_stats_LinearRegression() is a statistical test,
* so we can't be too aggressive about testing results.
*
* Args:
* r - a source of randomness
* use_sigma - TRUE to pass sigma to the regression fit.
* be_verbose - TRUE to print results (manual, not automated test mode)
*/
static void
utest_LinearRegression(ESL_RANDOMNESS *r, int use_sigma, int be_verbose)
{
char msg[] = "linear regression unit test failed";
double a = -3.;
double b = 1.;
int n = 100;
double xori = -20.;
double xstep = 1.0;
double setsigma = 1.0; /* sigma on all points */
int i;
double *x = NULL;
double *y = NULL;
double *sigma = NULL;
double ae, be, siga, sigb, cov_ab, cc, Q;
if ((x = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);
if ((y = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);
if ((sigma = malloc(sizeof(double) * n)) == NULL) esl_fatal(msg);
/* Simulate some linear data */
for (i = 0; i < n; i++)
{
sigma[i] = setsigma;
x[i] = xori + i*xstep;
y[i] = esl_rnd_Gaussian(r, a + b*x[i], sigma[i]);
}
if (use_sigma) {
if (esl_stats_LinearRegression(x, y, sigma, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK) esl_fatal(msg);
} else {
if (esl_stats_LinearRegression(x, y, NULL, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK) esl_fatal(msg);
}
if (be_verbose) {
printf("Linear regression test:\n");
printf("estimated intercept a = %8.4f [true = %8.4f]\n", ae, a);
printf("estimated slope b = %8.4f [true = %8.4f]\n", be, b);
printf("estimated sigma on a = %8.4f\n", siga);
printf("estimated sigma on b = %8.4f\n", sigb);
printf("estimated cov(a,b) = %8.4f\n", cov_ab);
printf("correlation coeff = %8.4f\n", cc);
printf("P-value = %8.4f\n", Q);
}
/* The following tests are statistical.
*/
if ( fabs(ae-a) > 2*siga ) esl_fatal(msg);
if ( fabs(be-b) > 2*sigb ) esl_fatal(msg);
if ( cc < 0.95) esl_fatal(msg);
if (use_sigma) {
if (Q < 0.001) esl_fatal(msg);
} else {
if (Q != 1.0) esl_fatal(msg);
}
free(x);
free(y);
free(sigma);
}
#endif /*eslSTATS_TESTDRIVE*/
/*-------------------- end of unit tests ------------------------*/
/*****************************************************************
* 6. Test driver.
*****************************************************************/
#ifdef eslSTATS_TESTDRIVE
/* gcc -g -Wall -o stats_utest -L. -I. -DeslSTATS_TESTDRIVE esl_stats.c -leasel -lm
* gcc -DHAVE_LIBGSL -O2 -o stats_utest -L. -I. -DeslSTATS_TESTDRIVE esl_stats.c -leasel -lgsl -lm
*/
#include <stdio.h>
#include "easel.h"
#include "esl_getopts.h"
#include "esl_random.h"
#include "esl_stats.h"
static ESL_OPTIONS options[] = {
/* name type default env range togs reqs incomp help docgrp */
{"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
{"-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0},
{"-v", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "verbose: show verbose output", 0},
{"-N", eslARG_INT,"10000000", NULL, NULL, NULL, NULL, NULL, "number of trials in LogGamma test", 0},
{ 0,0,0,0,0,0,0,0,0,0},
};
static char usage[] = "[-options]";
static char banner[] = "test driver for stats special functions";
int
main(int argc, char **argv)
{
ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
ESL_RANDOMNESS *r = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
int be_verbose = esl_opt_GetBoolean(go, "-v");
int N = esl_opt_GetInteger(go, "-N");
if (be_verbose) printf("seed = %" PRIu32 "\n", esl_randomness_GetSeed(r));
utest_LogGamma(r, N, be_verbose);
utest_LinearRegression(r, TRUE, be_verbose);
utest_LinearRegression(r, FALSE, be_verbose);
esl_getopts_Destroy(go);
esl_randomness_Destroy(r);
exit(0);
}
#endif /*eslSTATS_TESTDRIVE*/
/*------------------- end of test driver ------------------------*/
/*****************************************************************
* 7. Examples.
*****************************************************************/
/* Compile: gcc -g -Wall -o example -I. -DeslSTATS_EXAMPLE esl_stats.c esl_random.c easel.c -lm
* or gcc -g -Wall -o example -I. -L. -DeslSTATS_EXAMPLE esl_stats.c -leasel -lm
*/
#ifdef eslSTATS_EXAMPLE
/*::cexcerpt::stats_example::begin::*/
/* gcc -g -Wall -o example -I. -DeslSTATS_EXAMPLE esl_stats.c esl_random.c easel.c -lm */
#include <stdio.h>
#include "easel.h"
#include "esl_random.h"
#include "esl_stats.h"
int main(void)
{
ESL_RANDOMNESS *r = esl_randomness_Create(0);
double a = -3.;
double b = 1.;
double xori = -20.;
double xstep = 1.0;
double setsigma = 1.0; /* sigma on all points */
int n = 100;
double *x = malloc(sizeof(double) * n);
double *y = malloc(sizeof(double) * n);
double *sigma = malloc(sizeof(double) * n);
int i;
double ae, be, siga, sigb, cov_ab, cc, Q;
/* Simulate some linear data, with Gaussian noise added to y_i */
for (i = 0; i < n; i++) {
sigma[i] = setsigma;
x[i] = xori + i*xstep;
y[i] = esl_rnd_Gaussian(r, a + b*x[i], sigma[i]);
}
if (esl_stats_LinearRegression(x, y, sigma, n, &ae, &be, &siga, &sigb, &cov_ab, &cc, &Q) != eslOK)
esl_fatal("linear regression failed");
printf("estimated intercept a = %8.4f [true = %8.4f]\n", ae, a);
printf("estimated slope b = %8.4f [true = %8.4f]\n", be, b);
printf("estimated sigma on a = %8.4f\n", siga);
printf("estimated sigma on b = %8.4f\n", sigb);
printf("estimated cov(a,b) = %8.4f\n", cov_ab);
printf("correlation coeff = %8.4f\n", cc);
printf("P-value = %8.4f\n", Q);
free(x); free(y); free(sigma);
esl_randomness_Destroy(r);
exit(0);
}
/*::cexcerpt::stats_example::end::*/
#endif /* eslSTATS_EXAMPLE */
#ifdef eslSTATS_EXAMPLE2
#include <stdlib.h>
#include "easel.h"
#include "esl_getopts.h"
#include "esl_stats.h"
static ESL_OPTIONS options[] = {
/* name type default env range toggles reqs incomp help docgroup*/
{ "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
};
static char usage[] = "[-options] <ca> <na> <cb> <nb>";
static char banner[] = "example from the stats module: using a G-test";
int
main(int argc, char **argv)
{
ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 4, argc, argv, banner, usage);
int ca = strtol(esl_opt_GetArg(go, 1), NULL, 10);
int na = strtol(esl_opt_GetArg(go, 2), NULL, 10);
int cb = strtol(esl_opt_GetArg(go, 3), NULL, 10);
int nb = strtol(esl_opt_GetArg(go, 4), NULL, 10);
double G, P;
int status;
if (ca > na || cb > nb) esl_fatal("argument order wrong? expect ca, na, cb, nb for ca/na, cb/nb");
if ( (status = esl_stats_GTest(ca, na, cb, nb, &G, &P)) != eslOK) esl_fatal("G-test failed?");
printf("%-10.3g %12.2f\n", P, G);
exit(0);
}
#endif /* eslSTATS_EXAMPLE2 */
/*--------------------- end of examples -------------------------*/
/*****************************************************************
* Easel - a library of C functions for biological sequence analysis
* Version h3.1b2; February 2015
* Copyright (C) 2015 Howard Hughes Medical Institute.
* Other copyrights also apply. See the COPYRIGHT file for a full list.
*
* Easel is distributed under the Janelia Farm Software License, a BSD
* license. See the LICENSE file for more details.
*
* SVN $Id: esl_stats.c 854 2013-02-25 22:00:19Z wheelert $
* SVN $URL: https://svn.janelia.org/eddylab/eddys/easel/branches/hmmer/3.1/esl_stats.c $
*****************************************************************/
| {
"alphanum_fraction": 0.5240299039,
"avg_line_length": 33.5130151844,
"ext": "c",
"hexsha": "ed133f0dbf25b0a8c054ea4ec747d2d564cc63ef",
"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": "6c1beb53922471218386b7ed24e72fb093fe457c",
"max_forks_repo_licenses": [
"Linux-OpenIB"
],
"max_forks_repo_name": "YJY-98/PROSAVA",
"max_forks_repo_path": "Linux/easel/esl_stats.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6c1beb53922471218386b7ed24e72fb093fe457c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Linux-OpenIB"
],
"max_issues_repo_name": "YJY-98/PROSAVA",
"max_issues_repo_path": "Linux/easel/esl_stats.c",
"max_line_length": 124,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6c1beb53922471218386b7ed24e72fb093fe457c",
"max_stars_repo_licenses": [
"Linux-OpenIB"
],
"max_stars_repo_name": "YJY-98/PROSAVA",
"max_stars_repo_path": "Linux/easel/esl_stats.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 9807,
"size": 30899
} |
#pragma once
/*
* (C) Copyright 2020-2021 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
/*! \defgroup ioda_cxx_variable Variables, Data Access, and Selections
* \brief The main data storage methods and objects in IODA.
* \ingroup ioda_cxx_api
*
* @{
* \file Variable.h
* \brief @link ioda_cxx_variable Interfaces @endlink for ioda::Variable and related classes.
*/
#include <cstring>
#include <gsl/gsl-lite.hpp>
#include <list>
#include <map>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "ioda/Attributes/Has_Attributes.h"
#include "ioda/Exception.h"
#include "ioda/Misc/Eigen_Compat.h"
#include "ioda/Python/Var_ext.h"
#include "ioda/Types/Marshalling.h"
#include "ioda/Types/Type.h"
#include "ioda/Types/Type_Provider.h"
#include "ioda/Variables/Fill.h"
#include "ioda/Variables/Selection.h"
#include "ioda/defs.h"
namespace ioda {
class Attribute;
class Variable;
struct VariableCreationParameters;
struct Named_Variable;
namespace detail {
class Attribute_Backend;
class Variable_Backend;
/// \brief Exists to prevent constructor conflicts when passing a backend into
/// a frontend object.
/// \ingroup ioda_cxx_variable
/// \bug Need to add a virtual resize function.
template <class Variable_Implementation = Variable>
class Variable_Base {
protected:
/// Using an opaque object to implement the backend.
std::shared_ptr<Variable_Backend> backend_;
/// @name General Functions
/// @{
Variable_Base(std::shared_ptr<Variable_Backend>);
public:
virtual ~Variable_Base();
/// @}
/// @name Metadata manipulation
/// @{
/// Attributes
Has_Attributes atts;
/// @}
/// @name General Functions
/// @{
/// Gets a handle to the underlying object that implements the backend functionality.
std::shared_ptr<Variable_Backend> get() const;
/// @}
/// @name Type-querying Functions
/// @{
/// Get type
virtual Type getType() const;
/// Get type
inline Type type() const { return getType(); }
/// Query the backend and get the type provider.
virtual detail::Type_Provider* getTypeProvider() const;
/// \brief Convenience function to check a Variable's storage type.
/// \param DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \returns True if the type matches
/// \returns False (0) if the type does not match
/// \throws ioda::Exception if an error occurred.
template <class DataType>
bool isA() const {
Type templateType = Types::GetType_Wrapper<DataType>::GetType(getTypeProvider());
return isA(templateType);
}
/// Hand-off to the backend to check equivalence
virtual bool isA(Type lhs) const;
/// Python compatability function
inline bool isA(BasicTypes dataType) const { return isA(Type(dataType, getTypeProvider())); }
/// \internal pybind11
inline bool _py_isA2(BasicTypes dataType) { return isA(dataType); }
/// Convenience function to query type
BasicTypes getBasicType() const;
/// @}
/// @name Querying Functions for Fill Values, Chunking and Compression
/// @{
/// @brief Convenience function to get fill value, attributes,
/// chunk sizes, and compression in a collective call.
/// @details This function has better performance on some engines
/// for bulk operations than calling separately.
/// @param doAtts includes attributes in the creation parameters.
/// @param doDims includes dimension scales in the creation parameters.
/// Although dimensions are attributes on some backends, we treat them
/// separately in this function.
/// @returns the filled-in VariableCreationParameters object
virtual VariableCreationParameters getCreationParameters(bool doAtts = true,
bool doDims = true) const;
/// \brief Check if a variable has a fill value set
/// \returns true if a fill value is set, false otherwise.
virtual bool hasFillValue() const;
/// Remap fill value storage type into this class.
typedef detail::FillValueData_t FillValueData_t;
/// \brief Retrieve the fill value
/// \returns an object of type FillValueData_t that stores
/// the fill value. If there is no fill value, then
/// FillValueData_t::set_ will equal false. The fill
/// value data will be stored in
/// FillValueData_t::fillValue_ (for simple types), or in
/// FillValueData_t::stringFillValue_ (for strings only).
/// \note Recommend querying isA to make sure that you
/// are reading the fill value as the correct type.
virtual FillValueData_t getFillValue() const;
/// \brief Retrieve the chunking options for the Variable.
/// \note Not all backends support chunking, but they should
/// all store the desired chunk size information in case the
/// Variable is copied to a new backend.
/// \returns a vector containing the chunk sizes.
/// \returns an empty vector if chunking is not used.
virtual std::vector<Dimensions_t> getChunkSizes() const;
/// \brief Retrieve the GZIP compression options for the Variable.
/// \note Not all backends support compression (and those that
/// do also require chunking support). They should store this
/// information anyways, in case the Variable is copied to
/// a new backend.
/// \returns a pair indicating 1) whether GZIP is requested and
/// 2) the compression level that is desired.
virtual std::pair<bool, int> getGZIPCompression() const;
/// \brief Retrieve the SZIP compression options for the Variable.
/// \note Not all backends support compression (and those that
/// do also require chunking support). They should store this
/// information anyways, in case the Variable is copied to
/// a new backend.
/// \returns a tuple indicating 1) whether SZIP is requested,
/// 2) PixelsPerBlock, and 3) general SZIP filter option flags.
virtual std::tuple<bool, unsigned, unsigned> getSZIPCompression() const;
/// @}
/// @name Data Space-Querying Functions
/// @{
// Get dataspace
// JEDI_NODISCARD DataSpace getSpace() const;
/// Get current and maximum dimensions, and number of total points.
/// \note In Python, see the dims property.
virtual Dimensions getDimensions() const;
/// \brief Resize the variable.
/// \note Not all variables are resizable. This depends
/// on backend support. For HDF5, the variable must be chunked
/// and must not exceed max_dims.
/// \note Bad things may happen if a variable's dimension scales
/// have different lengths than its dimensions. Resize them
/// together, preferably using the ObsSpace resize function.
/// \see ObsSpace::resize
/// \param newDims are the new dimensions.
virtual Variable resize(const std::vector<Dimensions_t>& newDims);
/// Attach a dimension scale to this Variable.
virtual Variable attachDimensionScale(unsigned int DimensionNumber, const Variable& scale);
/// Detach a dimension scale
virtual Variable detachDimensionScale(unsigned int DimensionNumber, const Variable& scale);
/// Set dimensions (convenience function to several invocations of attachDimensionScale).
Variable setDimScale(const std::vector<Variable>& dims);
/// Set dimensions (convenience function to several invocations of attachDimensionScale).
Variable setDimScale(const std::vector<Named_Variable>& dims);
/// Set dimensions (convenience function to several invocations of attachDimensionScale).
Variable setDimScale(const Variable& dims);
/// Set dimensions (convenience function to several invocations of attachDimensionScale).
Variable setDimScale(const Variable& dim1, const Variable& dim2);
/// Set dimensions (convenience function to several invocations of attachDimensionScale).
Variable setDimScale(const Variable& dim1, const Variable& dim2, const Variable& dim3);
/// Is this Variable used as a dimension scale?
virtual bool isDimensionScale() const;
/// Designate this table as a dimension scale
virtual Variable setIsDimensionScale(const std::string& dimensionScaleName);
/// Get the name of this Variable's defined dimension scale
inline std::string getDimensionScaleName() const {
std::string r;
getDimensionScaleName(r);
return r;
}
virtual Variable getDimensionScaleName(std::string& res) const;
/// Is a dimension scale attached to this Variable in a certain position?
virtual bool isDimensionScaleAttached(unsigned int DimensionNumber, const Variable& scale) const;
/// \brief Which dimensions are attached at which positions? This function may offer improved
/// performance on some backends compared to serial isDimensionScaleAttached calls.
/// \param scalesToQueryAgainst is a vector containing the scales. You can pass in
/// "tagged" strings that map the Variable to a name.
/// If you do not pass in a scale to check against, then this scale will not be checked and
/// will not be present in the function output.
/// \param firstOnly is specified when only one dimension can be attached to each axis (the
/// default).
/// \returns a vector with the same length as the variable's dimensionality.
/// Each variable dimension in the vector can have one or more attached scales. These scales are
/// returned as their own, inner, vector of pair<string, Variable>.
virtual std::vector<std::vector<Named_Variable>> getDimensionScaleMappings(
const std::list<Named_Variable>& scalesToQueryAgainst,
bool firstOnly = true) const;
/// @}
/// @name Writing Data
/// @{
/// \brief The fundamental write function. Backends overload this function to implement
/// all write operations.
///
/// \details This function writes a span of bytes (characters) to the backend attribute
/// storage. No type conversions take place here (see the templated conversion function,
/// below).
///
/// \param data is a span of data.
/// \param in_memory_datatype is an opaque (backend-level) object that describes the
/// placement of the data in memory. Usually ignorable - needed for complex data structures.
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
/// \throws ioda::xError if data has the wrong size.
/// \returns The variable (for chaining).
virtual Variable write(gsl::span<const char> data, const Type& in_memory_dataType,
const Selection& mem_selection = Selection::all,
const Selection& file_selection = Selection::all);
/// \brief Write the Variable
/// \note Ensure that the correct dimension ordering is preserved.
/// \note With default parameters, the entire Variable is written.
/// \tparam DataType is the type of the data to be written.
/// \tparam Marshaller is a class that serializes / deserializes data.
/// \tparam TypeWrapper translates DataType into a form that the backend understands.
/// \param data is a span of data.
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
/// \throws ioda::xError if data has the wrong size.
/// \returns The variable (for chaining).
template <class DataType, class Marshaller = Object_Accessor<DataType>,
class TypeWrapper = Types::GetType_Wrapper<DataType>>
Variable_Implementation write(const gsl::span<DataType> data,
const Selection& mem_selection = Selection::all,
const Selection& file_selection = Selection::all) {
try {
Marshaller m;
auto d = m.serialize(data);
return write(gsl::make_span<const char>(
reinterpret_cast<const char*>(d->DataPointers.data()),
d->DataPointers.size() * Marshaller::bytesPerElement_),
TypeWrapper::GetType(getTypeProvider()), mem_selection, file_selection);
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
}
/// \brief Write the Variable
/// \note Ensure that the correct dimension ordering is preserved.
/// \note With default parameters, the entire Variable is written.
/// \tparam DataType is the type of the data to be written.
/// \tparam Marshaller is a class that serializes / deserializes data.
/// \tparam TypeWrapper translates DataType into a form that the backend understands.
/// \param data is a span of data.
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
/// \throws ioda::xError if data has the wrong size.
/// \returns The variable (for chaining).
template <class DataType, class Marshaller = Object_Accessor<DataType>,
class TypeWrapper = Types::GetType_Wrapper<DataType>>
Variable_Implementation write(const gsl::span<const DataType> data,
const Selection& mem_selection = Selection::all,
const Selection& file_selection = Selection::all) {
try {
Marshaller m;
auto d = m.serialize(data);
return write(gsl::make_span<const char>(
reinterpret_cast<const char*>(d->DataPointers.data()),
d->DataPointers.size() * Marshaller::bytesPerElement_),
TypeWrapper::GetType(getTypeProvider()), mem_selection, file_selection);
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
}
/// \brief Write the variable
/// \tparam DataType is the type of the data to be written.
/// \tparam Marshaller is a class that serializes / deserializes data.
/// \tparam TypeWrapper translates DataType into a form that the backend understands.
/// \param data is a span of data.
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
/// \throws ioda::xError if data has the wrong size.
/// \returns The variable (for chaining).
template <class DataType, class Marshaller = Object_Accessor<DataType>,
class TypeWrapper = Types::GetType_Wrapper<DataType>>
Variable_Implementation write(const std::vector<DataType>& data,
const Selection& mem_selection = Selection::all,
const Selection& file_selection = Selection::all) {
try {
return this->write<DataType, Marshaller, TypeWrapper>(gsl::make_span(data), mem_selection,
file_selection);
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
}
/// \brief Write an Eigen object (a Matrix, an Array, a Block, a Map).
/// \tparam EigenClass is the type of the Eigen object being written.
/// \param d is the data to be written.
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
/// \throws ioda::xError on a dimension mismatch.
/// \returns the variable
template <class EigenClass>
Variable_Implementation writeWithEigenRegular(const EigenClass& d,
const Selection& mem_selection = Selection::all,
const Selection& file_selection = Selection::all) {
#if 1 //__has_include("Eigen/Dense")
try {
typedef typename EigenClass::Scalar ScalarType;
// If d is already in Row Major form, then this is optimized out.
Eigen::Array<ScalarType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> dout;
dout.resize(d.rows(), d.cols());
dout = d;
const auto& dconst = dout; // To make some compilers happy.
auto sp = gsl::make_span(dconst.data(), static_cast<int>(d.rows() * d.cols()));
return write<ScalarType>(sp, mem_selection, file_selection);
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
#else
static_assert(false, "The Eigen headers cannot be found, so this function cannot be used.");
#endif
}
/// \brief Write an Eigen Tensor-like object
/// \tparam EigenClass is the type of the Eigen object being written.
/// \param d is the data to be written.
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
/// \throws ioda::xError on a dimension mismatch.
/// \returns the variable
template <class EigenClass>
Variable_Implementation writeWithEigenTensor(const EigenClass& d,
const Selection& mem_selection = Selection::all,
const Selection& file_selection = Selection::all) {
#if 1 //__has_include("unsupported/Eigen/CXX11/Tensor")
try {
ioda::Dimensions dims = detail::EigenCompat::getTensorDimensions(d);
auto sp = (gsl::make_span(d.data(), dims.numElements));
auto res = write(sp, mem_selection, file_selection);
return res;
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
#else
static_assert(
false, "The Eigen unsupported/ headers cannot be found, so this function cannot be used.");
#endif
}
/// @}
/// @name Reading Data
/// @{
/// \brief Read the Variable - as char array. Ordering is row-major.
/// \details This is the fundamental read function that has to be implemented.
/// \param data is a byte-array that will hold the read data.
/// \param in_memory_dataType describes how ioda should arrange the read data in memory.
/// As floats? As doubles? Strings?
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
/// \note Ensure that the correct dimension ordering is preserved
/// \note With default parameters, the entire Variable is read
virtual Variable read(gsl::span<char> data, const Type& in_memory_dataType,
const Selection& mem_selection = Selection::all,
const Selection& file_selection = Selection::all) const;
/// \brief Read the variable into a span (range) or memory. Ordering is row-major.
/// \tparam DataType is the type of the data to be written.
/// \tparam Marshaller is a class that serializes / deserializes data.
/// \tparam TypeWrapper translates DataType into a form that the backend understands.
/// \param data is a byte-array that will hold the read data.
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
/// \todo Add in the dataspaces!
template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,
class TypeWrapper = Types::GetType_Wrapper<DataType>>
Variable_Implementation read(gsl::span<DataType> data,
const Selection& mem_selection = Selection::all,
const Selection& file_selection = Selection::all) const {
try {
const size_t numObjects = data.size();
detail::PointerOwner pointerOwner = getTypeProvider()->getReturnedPointerOwner();
Marshaller m(pointerOwner);
auto p = m.prep_deserialize(numObjects);
read(gsl::make_span<char>(
reinterpret_cast<char*>(p->DataPointers.data()),
// Logic note: sizeof mutable data type. If we are
// reading in a string, then mutable data type is char*,
// which works because address pointers have the same size.
p->DataPointers.size() * Marshaller::bytesPerElement_),
TypeWrapper::GetType(getTypeProvider()), mem_selection, file_selection);
m.deserialize(p, data);
return Variable_Implementation{backend_};
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
}
/// \brief Read the variable into a vector. Resize if needed. For a non-resizing
/// version, use a gsl::span.
/// \details Ordering is row-major.
/// \tparam DataType is the type of the data to be written.
/// \tparam Marshaller is a class that serializes / deserializes data.
/// \tparam TypeWrapper translates DataType into a form that the backend understands.
/// \param data is a byte-array that will hold the read data.
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
/// \bug Resize only if needed, and resize to the proper extent depending on
/// mem_selection and file_selection.
template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,
class TypeWrapper = Types::GetType_Wrapper<DataType>>
Variable_Implementation read(std::vector<DataType>& data,
const Selection& mem_selection = Selection::all,
const Selection& file_selection = Selection::all) const {
data.resize(getDimensions().numElements); // TODO(Ryan): remove
return read<DataType, Marshaller, TypeWrapper>(gsl::make_span(data.data(), data.size()),
mem_selection, file_selection);
}
/// \brief Read the variable into a new vector. Python convenience function.
/// \bug Get correct size based on selection operands.
/// \tparam DataType is the type of the data to be written.
/// \tparam Marshaller is a class that serializes / deserializes data.
/// \tparam TypeWrapper translates DataType into a form that the backend understands.
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,
class TypeWrapper = Types::GetType_Wrapper<DataType>>
std::vector<DataType> readAsVector(const Selection& mem_selection = Selection::all,
const Selection& file_selection = Selection::all) const {
std::vector<DataType> data(getDimensions().numElements);
read<DataType, Marshaller, TypeWrapper>(gsl::make_span(data.data(), data.size()), mem_selection,
file_selection);
return data;
}
/// \brief Valarray read convenience function. Resize if needed.
/// For a non-resizing version, use a gsl::span.
/// \tparam DataType is the type of the data to be written.
/// \tparam Marshaller is a class that serializes / deserializes data.
/// \tparam TypeWrapper translates DataType into a form that the backend understands.
/// \param data is a valarray acting as a data buffer that is filled with the
/// metadata's contents. It gets resized as needed.
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
/// \returns Another instance of this Attribute. Used for operation chaining.
/// \note data will be stored in row-major order.
template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,
class TypeWrapper = Types::GetType_Wrapper<DataType>>
Variable_Implementation read(std::valarray<DataType>& data,
const Selection& mem_selection = Selection::all,
const Selection& file_selection = Selection::all) const {
/// \bug Resize only if needed, and resize to the proper extent depending on
/// mem_selection and file_selection.
data.resize(getDimensions().numElements); // TODO(Ryan): remove
return read<DataType, Marshaller, TypeWrapper>(gsl::make_span(std::begin(data), std::end(data)),
mem_selection, file_selection);
}
/// \brief Read data into an Eigen::Array, Eigen::Matrix, Eigen::Map, etc.
/// \tparam EigenClass is a template pointing to the Eigen object.
/// This template must provide the EigenClass::Scalar typedef.
/// \tparam Resize indicates whether the Eigen object should be resized
/// if there is a dimension mismatch. Not all Eigen objects can be resized.
/// \param res is the Eigen object.
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
/// \returns Another instance of this Variable. Used for operation chaining.
/// \throws ioda::xError if the variable's dimensionality is
/// too high.
/// \throws ioda::xError if resize = false and there is a dimension mismatch.
/// \note When reading in a 1-D object, the data are read as a column vector.
template <class EigenClass, bool Resize = detail::EigenCompat::CanResize<EigenClass>::value>
Variable_Implementation readWithEigenRegular(EigenClass& res,
const Selection& mem_selection = Selection::all,
const Selection& file_selection
= Selection::all) const {
/// \bug Resize only if needed, and resize to the proper extent depending on
/// mem_selection and file_selection.
#if 1 //__has_include("Eigen/Dense")
try {
typedef typename EigenClass::Scalar ScalarType;
static_assert(
!(Resize && !detail::EigenCompat::CanResize<EigenClass>::value),
"This object cannot be resized, but you have specified that a resize is required.");
// Check that the dimensionality is 1 or 2.
const auto dims = getDimensions();
if (dims.dimensionality > 2)
throw Exception("Dimensionality too high for a regular Eigen read. Use "
"Eigen::Tensor reads instead.", ioda_Here());
int nDims[2] = {1, 1};
if (dims.dimsCur.size() >= 1) nDims[0] = gsl::narrow<int>(dims.dimsCur[0]);
if (dims.dimsCur.size() >= 2) nDims[1] = gsl::narrow<int>(dims.dimsCur[1]);
// Resize if needed.
if (Resize)
detail::EigenCompat::DoEigenResize(res, nDims[0],
nDims[1]); // nullop if the size is already correct.
else if (dims.numElements != (size_t)(res.rows() * res.cols()))
throw Exception("Size mismatch", ioda_Here());
// Array copy to preserve row vs column major format.
// Should be optimized away by the compiler if unneeded.
// Note to the reader: We are reading in the data to a temporary object.
// We can size _this_ temporary object however we want.
// The temporary is used to swap row / column indices if needed.
// It should be optimized away if not needed... making sure this happens is a todo.
Eigen::Array<ScalarType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> data_in(res.rows(),
res.cols());
auto ret = read<ScalarType>(gsl::span<ScalarType>(data_in.data(), dims.numElements),
mem_selection, file_selection);
res = data_in;
return ret;
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
#else
static_assert(false, "The Eigen headers cannot be found, so this function cannot be used.");
#endif
}
/// \brief Read data into an Eigen::Array, Eigen::Matrix, Eigen::Map, etc.
/// \tparam EigenClass is a template pointing to the Eigen object.
/// This template must provide the EigenClass::Scalar typedef.
/// \param res is the Eigen object.
/// \param mem_selection is the user's memory layout representing the location where
/// the data is read from.
/// \param file_selection is the backend's memory layout representing the
/// location where the data are written to.
/// \returns Another instance of this Variable. Used for operation chaining.
/// \throws ioda::Exception if there is a size mismatch.
/// \note When reading in a 1-D object, the data are read as a column vector.
template <class EigenClass>
Variable_Implementation readWithEigenTensor(EigenClass& res,
const Selection& mem_selection = Selection::all,
const Selection& file_selection
= Selection::all) const {
#if 1 //__has_include("unsupported/Eigen/CXX11/Tensor")
try {
// Check dimensionality of source and destination
const auto ioda_dims = getDimensions();
const auto eigen_dims = ioda::detail::EigenCompat::getTensorDimensions(res);
if (ioda_dims.numElements != eigen_dims.numElements)
throw Exception("Size mismatch for Eigen Tensor-like read.", ioda_Here());
auto sp = (gsl::make_span(res.data(), eigen_dims.numElements));
return read(sp, mem_selection, file_selection);
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
#else
static_assert(
false, "The Eigen unsupported/ headers cannot be found, so this function cannot be used.");
#endif
}
/// \internal Python binding function
template <class EigenClass>
EigenClass _readWithEigenRegular_python(const Selection& mem_selection = Selection::all,
const Selection& file_selection = Selection::all) const {
EigenClass data;
readWithEigenRegular(data, mem_selection, file_selection);
return data;
}
/// @brief Convert a selection into its backend representation
/// @param sel is the frontend selection.
/// @return The cached backend selection.
virtual Selections::SelectionBackend_t instantiateSelection(const Selection& sel) const;
/// @}
private:
/// \brief get the fill value from the netcdf specification (_FillValue attribute)
FillValueData_t getNcFillValue() const;
/// \brief check if fill data objects match, print warning if they don't match
/// \param hdfFill fill value obtained from the hdf fill value property
/// \param ncFill fill value obtained from the netcdf fill value attribute
void checkWarnFillValue(FillValueData_t & hdfFill, FillValueData_t & ncFill) const;
/// \brief run an action according to the current variable data type
/// \details this function will call the function passed to it through the action
/// parameter, giving this action a typed entity that can be identified by decltype.
/// At this point, all of the types supported by Variable_Base::getBasicType() except
/// for bool are handled in this function.
/// \param action Function object callable with a single argument which is identifiable
/// by decltype
// TODO(srh) Additional development is required to properly handle the bool data type.
template <typename Action>
auto runForVarType(const Action & action) const {
if (isA<int>()) {
int typeMe;
return action(typeMe);
} else if (isA<unsigned int>()) {
unsigned int typeMe;
return action(typeMe);
} else if (isA<float>()) {
float typeMe;
return action(typeMe);
} else if (isA<double>()) {
double typeMe;
return action(typeMe);
} else if (isA<std::string>()) {
std::string typeMe;
return action(typeMe);
} else if (isA<long>()) {
long typeMe;
return action(typeMe);
} else if (isA<unsigned long>()) {
unsigned long typeMe;
return action(typeMe);
} else if (isA<short>()) {
short typeMe;
return action(typeMe);
} else if (isA<unsigned short>()) {
unsigned short typeMe;
return action(typeMe);
} else if (isA<long long>()) {
long long typeMe;
return action(typeMe);
} else if (isA<unsigned long long>()) {
unsigned long long typeMe;
return action(typeMe);
} else if (isA<int32_t>()) {
int32_t typeMe;
return action(typeMe);
} else if (isA<uint32_t>()) {
uint32_t typeMe;
return action(typeMe);
} else if (isA<int16_t>()) {
int16_t typeMe;
return action(typeMe);
} else if (isA<uint16_t>()) {
uint16_t typeMe;
return action(typeMe);
} else if (isA<int64_t>()) {
int64_t typeMe;
return action(typeMe);
} else if (isA<uint64_t>()) {
uint64_t typeMe;
return action(typeMe);
} else if (isA<long double>()) {
long double typeMe;
return action(typeMe);
} else if (isA<char>()) {
char typeMe;
return action(typeMe);
} else if (isA<unsigned char>()) {
unsigned char typeMe;
return action(typeMe);
} else {
std::throw_with_nested(Exception("Unsupported variable data type", ioda_Here()));
}
}
};
// extern template class Variable_Base<Variable>;
} // namespace detail
/** \brief Variables store data!
* \ingroup ioda_cxx_variable
*
* A variable represents a single field of data. It can be multi-dimensional and
* usually has one or more attached **dimension scales**.
*
* Variables have Metadata, which describe the variable (i.e. valid_range, long_name, units).
* Variables can have different data types (i.e. int16_t, float, double, string, datetime).
* Variables can be resized. Depending on the backend, the data in a variable can be stored
* using chunks, and may also be compressed.
*
* The backend manages how variables are stored in memory or on disk. The functions in the
* Variable class provide methods to query and set data. The goal is to have data transfers
* involve as few copies as possible.
*
* Variable objects themselves are lightweight handles that may be passed across different
* parts of a program. Variables are always stored somewhere in a Group (or ObsSpace), so you
* can always re-open a handle.
*
* \note Thread and MPI safety depend on the specific backends used to implement a variable.
* \note A variable may be linked to multiple groups and listed under multiple names, so long as
* the storage backends are all the same.
**/
class IODA_DL Variable : public detail::Variable_Base<Variable> {
public:
/// @name General Functions
/// @{
Variable();
Variable(std::shared_ptr<detail::Variable_Backend> b);
Variable(const Variable&);
Variable& operator=(const Variable&);
virtual ~Variable();
/// @}
/// @name Python compatability objects
/// @{
detail::python_bindings::VariableIsA<Variable> _py_isA;
detail::python_bindings::VariableReadVector<Variable> _py_readVector;
detail::python_bindings::VariableReadNPArray<Variable> _py_readNPArray;
detail::python_bindings::VariableWriteVector<Variable> _py_writeVector;
detail::python_bindings::VariableWriteNPArray<Variable> _py_writeNPArray;
detail::python_bindings::VariableScales<Variable> _py_scales;
/// @}
};
namespace detail {
/// \brief Variable backends inherit from this.
class IODA_DL Variable_Backend : public Variable_Base<Variable> {
public:
virtual ~Variable_Backend();
/// Default, trivial implementation. Customizable by backends for performance.
std::vector<std::vector<Named_Variable>> getDimensionScaleMappings(
const std::list<Named_Variable>& scalesToQueryAgainst,
bool firstOnly = true) const override;
/// Default implementation. Customizable by backends for performance.
VariableCreationParameters getCreationParameters(bool doAtts = true,
bool doDims = true) const override;
protected:
Variable_Backend();
/// @brief This function de-encapsulates an Attribute's backend storage object.
/// This function is used by Variable_Backend's derivatives when accessing a
/// Variable's Attributes. IODA-internal use only.
/// @tparam Attribute_Implementation is a dummy parameter used by Attributes.
/// @param base is the Attribute whose backend you want.
/// @return The encapsulated backend object.
template <class Attribute_Implementation = Attribute>
static std::shared_ptr<Attribute_Backend> _getAttributeBackend(
const Attribute_Implementation& att) {
return att.backend_;
}
/// @brief This function de-encapsulates a Has_Attributes backend storage object.
/// IODA-internal use only.
/// @tparam Has_Attributes_Implementation is a dummy parameter for template resolution.
/// @param hatts is the Has_Attributes whose backend you want.
/// @return The encapsulated backend object.
template <class Has_Attributes_Implementation = Has_Attributes>
static std::shared_ptr<Has_Attributes_Backend> _getHasAttributesBackend(
const Has_Attributes_Implementation& hatts) {
return hatts.backend_;
}
};
} // namespace detail
/// @brief A named pair of (variable_name, ioda::Variable).
struct Named_Variable {
std::string name;
ioda::Variable var;
bool operator<(const Named_Variable& rhs) const { return name < rhs.name; }
Named_Variable() = default;
Named_Variable(const std::string& name, const ioda::Variable& var) : name(name), var(var) {}
};
} // namespace ioda
/// @}
| {
"alphanum_fraction": 0.6824904953,
"avg_line_length": 45.2853773585,
"ext": "h",
"hexsha": "96fc29c3a43142e4853ba4d98e80ceb76f5be54e",
"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": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "NOAA-EMC/ioda",
"max_forks_repo_path": "src/engines/ioda/include/ioda/Variables/Variable.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"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": "NOAA-EMC/ioda",
"max_issues_repo_path": "src/engines/ioda/include/ioda/Variables/Variable.h",
"max_line_length": 100,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "NOAA-EMC/ioda",
"max_stars_repo_path": "src/engines/ioda/include/ioda/Variables/Variable.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8590,
"size": 38402
} |
#include "emulator_struct.h"
#include "libEmu/emulator.h"
#include "libEmu/regression.h"
#include "libEmu/emulate-fns.h"
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
/*********************************************************************
Allocates emulator_struct.
*
* ccs, should be thread safe now
*********************************************************************/
emulator_struct * alloc_emulator_struct(modelstruct * model)
{
emulator_struct * e = (emulator_struct *)malloc(sizeof(emulator_struct));
double determinant_c = 0.0;
e->nparams = model->options->nparams;
e->nmodel_points = model->options->nmodel_points;
e->nregression_fns = model->options->nregression_fns;
e->nthetas = model->options->nthetas;
e->model = model;
gsl_matrix * c_matrix = gsl_matrix_alloc(e->nmodel_points, e->nmodel_points);
e->cinverse = gsl_matrix_alloc(e->nmodel_points, e->nmodel_points);
e->beta_vector = gsl_vector_alloc(e->nregression_fns);
e->h_matrix = gsl_matrix_alloc(e->nmodel_points, e->nregression_fns);
gsl_matrix * temp_matrix = gsl_matrix_alloc(e->nmodel_points, e->nmodel_points);
makeCovMatrix_es(c_matrix, e);
gsl_matrix_memcpy(temp_matrix, c_matrix);
chol_inverse_cov_matrix(model->options, temp_matrix, e->cinverse, &determinant_c);
makeHMatrix_es(e->h_matrix, e);
estimateBeta_es(e->beta_vector, e);
gsl_matrix_free(c_matrix);
gsl_matrix_free(temp_matrix);
return e;
}
/*********************************************************************
Free emulator_struct.
*********************************************************************/
void free_emulator_struct(emulator_struct * e)
{
gsl_matrix_free(e->cinverse);
gsl_matrix_free(e->h_matrix);
gsl_vector_free(e->beta_vector);
free((void *)e);
}
/**
* the following fns are wrapped versions of commonly used fns in emulator.h etc, this
* should make manipulations a little cleaner without breaking libRbind
* they also use the emulator_struct->model->fnptrs instead
*/
/**
* make the matrix of regression fns HMatrix, (thread safe?)
* uses modelstruct fnptr: (void)(makeHvector)(gsl_vector*, gsl_vector*, int);
*
* although emulator_struct contains a h_matrix, we might want this for somethign else, so it is given as the 1st arg
* the h_matrix in e is *not set* by this function
*/
void makeHMatrix_es(gsl_matrix *h_matrix, emulator_struct *e)
{
makeHMatrix_fnptr(h_matrix,
e->model->xmodel,
e->nmodel_points,
e->nparams,
e->nregression_fns,
e->model->makeHVector);
}
/**
* make a covariance matrix: makeCovMatrix_es, (thread safe?)
* uses the modelstruct fnptr (double)(*covariance_fn)(gsl_vector*, gsl_vector*, gsl_vector*, int, int)
*/
void makeCovMatrix_es(gsl_matrix *cov_matrix, emulator_struct *e)
{
makeCovMatrix_fnptr(cov_matrix,
e->model->xmodel,
e->model->thetas,
e->nmodel_points,
e->nthetas,
e->nparams,
e->model->covariance_fn);
}
/**
* compute a kvector at point k(point, emulator_struct) := { c(point, x_1), ... , c(point, x_n) }^T
*
* threadsafe
*
* requires: e->model to be init
* e->model->thetas needs to contain sensible values
*/
void makeKVector_es(gsl_vector *kvector, gsl_vector *point, emulator_struct *e)
{
makeKVector_fnptr(kvector, e->model->xmodel, point,
e->model->thetas, e->nmodel_points, e->nthetas, e->nparams,
e->model->covariance_fn);
}
/**
* estimate betas from an emulator_struct, no need to modify anything to make this threadsafe
*
* betas are set into the first vector, not in the emulator_struct
*
* @require e->cinverse and e->h_matrix to be init
*/
void estimateBeta_es(gsl_vector *beta_vector, emulator_struct *e)
{
estimateBeta(beta_vector, e->h_matrix, e->cinverse, e->model->training_vector,
e->nmodel_points, e->nregression_fns);
}
/*********************************************************************
return mean and variance at a point.
thread-safe, uses fnptrs defined in e->modelstruct
*********************************************************************/
void emulate_point(emulator_struct* e, gsl_vector * point, double * mean, double * variance)
{
gsl_vector * kplus = gsl_vector_alloc(e->nmodel_points); //allocate variable storage
gsl_vector * h_vector = gsl_vector_alloc(e->nregression_fns); //allocate variable storage
makeKVector_es(kplus, point, e);
/* use the fnptr in modelstruct */
e->model->makeHVector(h_vector, point, e->nparams);
(*mean) = makeEmulatedMean(e->cinverse, e->model->training_vector,
kplus, h_vector, e->h_matrix, e->beta_vector, e->nmodel_points);
double kappa = e->model->covariance_fn(point, point, e->model->thetas, e->nthetas, e->nparams);
(*variance) = makeEmulatedVariance(e->cinverse, kplus, h_vector,
e->h_matrix, kappa, e->nmodel_points, e->nregression_fns);
gsl_vector_free(kplus);
gsl_vector_free(h_vector);
// can we really return on void?
return;
}
| {
"alphanum_fraction": 0.6611369614,
"avg_line_length": 34.0896551724,
"ext": "c",
"hexsha": "87ee401a66a0c975c8a1a33dddd7169009b40560",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MADAI/MADAIEmulator",
"max_forks_repo_path": "src/emulator_struct.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MADAI/MADAIEmulator",
"max_issues_repo_path": "src/emulator_struct.c",
"max_line_length": 117,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jackdawjackdaw/emulator",
"max_stars_repo_path": "src/emulator_struct.c",
"max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z",
"num_tokens": 1278,
"size": 4943
} |
/* stable/stable_integration.h
*
* Functions to perform numerical integration used when calculating
* the PDF and CDF of alpha-stable distributions. Based on GSL
* numerical quadrature methods.
*
* 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
*
*/
#ifndef _STABLE_INTEGRATION_H_
#define _STABLE_INTEGRATION_H_
#include "stable.h"
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_math.h>
int stable_integration_METHODNAME(unsigned short method, char *s);
void
stable_integration(StableDist *dist,double(function)(double, void*),
double a, double b,
double epsabs, double epsrel, unsigned short limit,
double *result, double *abserr, unsigned short method);
#endif
| {
"alphanum_fraction": 0.7162329616,
"avg_line_length": 32.28,
"ext": "h",
"hexsha": "9c36bfab4ccca163b8c6486c993312f7acf525e6",
"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_integration.h",
"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_integration.h",
"max_line_length": 74,
"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_integration.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 392,
"size": 1614
} |
/* rng/ran0.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_rng.h>
/* This is an implementation of the algorithm used in Numerical
Recipe's ran0 generator. It is the same as MINSTD with an XOR mask
of 123459876 on the seed.
The period of this generator is 2^31.
Note, if you choose a seed of 123459876 it would give a degenerate
series 0,0,0,0, ... I've made that into an error. */
static inline unsigned long int ran0_get (void *vstate);
static double ran0_get_double (void *vstate);
static void ran0_set (void *state, unsigned long int s);
static const long int m = 2147483647, a = 16807, q = 127773, r = 2836;
static const unsigned long int mask = 123459876;
typedef struct
{
unsigned long int x;
}
ran0_state_t;
static inline unsigned long int
ran0_get (void *vstate)
{
ran0_state_t *state = (ran0_state_t *) vstate;
const unsigned long int x = state->x;
const long int h = x / q;
const long int t = a * (x - h * q) - h * r;
if (t < 0)
{
state->x = t + m;
}
else
{
state->x = t;
}
return state->x;
}
static double
ran0_get_double (void *vstate)
{
return ran0_get (vstate) / 2147483647.0 ;
}
static void
ran0_set (void *vstate, unsigned long int s)
{
ran0_state_t *state = (ran0_state_t *) vstate;
if (s == mask)
{
GSL_ERROR_VOID ("ran0 should not use seed == mask",
GSL_EINVAL);
}
state->x = s ^ mask;
return;
}
static const gsl_rng_type ran0_type =
{"ran0", /* name */
2147483646, /* RAND_MAX */
1, /* RAND_MIN */
sizeof (ran0_state_t),
&ran0_set,
&ran0_get,
&ran0_get_double};
const gsl_rng_type *gsl_rng_ran0 = &ran0_type;
| {
"alphanum_fraction": 0.6580570547,
"avg_line_length": 25.6831683168,
"ext": "c",
"hexsha": "108a90598816b43b0de51dadd329f9e391026689",
"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/ran0.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/ran0.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/ran0.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": 738,
"size": 2594
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_math.h> // gsl_finite
#ifdef _OPENMP
#include <omp.h>
#endif
const size_t N=10000;
const size_t T=1000;
const size_t K=20;
const size_t L=2;
const double alpha_k = 0.5;
/*
* 0: thompson sampling
* 1: uniform subset
*
*/
const unsigned int strategy = 0;
#include "helpers.h"
#include "model.h"
#include "set_counter.h"
#define to_string(arr, k) \
for (size_t i = 0; i < k-1; i++) { \
printf("%.16lf,", arr[i]); \
} \
printf("%.16lf", arr[k-1]);
unsigned int
move_gibbs(double *restrict random_numbers, double logth[K], size_t ngames,
const size_t games[ngames][L], const size_t game_counts[ngames],
const size_t win_counts[K])
{
double ll, ll_p;
double alpha;
double logth_comp_old;
double logth_Km1_old;
unsigned int accepted = 0;
for (size_t comp=0; comp<K-1; comp++) {
assert(gsl_fcmp(log_sum_exp(logth, K), 1.0, 1e-15) == 0);
ll = fullcond(comp, logth, ngames, games, game_counts, win_counts);
/* sample a suitable value for the current component */
logth_comp_old = logth[comp];
logth_Km1_old = logth[K-1];
if (logth_comp_old > logth[K-1]) {
logth[comp] = log(*random_numbers++) + logth_comp_old + log1p(exp(logth[K-1] - logth_comp_old));
logth[K-1] = logth_comp_old + log1p(exp(logth_Km1_old - logth_comp_old) - exp(logth[comp] - logth_comp_old));
} else {
logth[comp] = log(*random_numbers++) + logth_Km1_old + log1p(exp(logth_comp_old - logth_Km1_old));
logth[K-1] = logth_Km1_old + log1p(exp(logth_comp_old - logth_Km1_old) - exp(logth[comp] - logth_Km1_old));
}
/* compute full conditional density at th_p */
ll_p = fullcond(comp, logth, ngames, games, game_counts, win_counts);
alpha = *random_numbers++;
if (log(alpha) < ll_p - ll) {
/* accept */
accepted = 1;
}
else {
/* reject */
/* reset the proposed component back to its original value */
/* th[K-1] += th[comp] - th_comp_old; */
/* th[comp] = th_comp_old; */
/* assert(th[K-1] >= 0); */
logth[comp] = logth_comp_old;
logth[K-1] = logth_Km1_old;
}
}
return accepted;
}
void
resample_move(const gsl_rng *r, double logtheta[N][K], const double w[N],
const struct set_counter *games_counter, const size_t wins[K])
{
unsigned int cnt[N];
size_t accepted = 0;
gsl_ran_multinomial(r, N, N, w, cnt);
/* populate particles */
double (*logtheta_new)[K] = malloc(N * sizeof *logtheta_new);
size_t n_new = 0;
for (size_t n=0; n<N; n++) {
for (size_t i=0; i < cnt[n]; i++) {
memcpy(logtheta_new[n_new++], logtheta[n], sizeof *logtheta_new);
}
}
/* pre-generate random numbers to avoid thread synchronization */
double (*random_numbers)[2*(K-1)] = malloc(N * sizeof *random_numbers);
for (size_t n=0; n<N; n++) {
for (size_t k=0; k<2*(K-1); k++) {
random_numbers[n][k] = gsl_rng_uniform_pos(r);
}
}
/* extract game counts from the counter */
size_t ngames = games_counter->size;
size_t (*games)[L] = malloc(ngames * sizeof *games);
size_t *game_counts = malloc(ngames * sizeof *game_counts);
set_counter_keys(games_counter, games);
set_counter_values(games_counter, game_counts);
#pragma omp parallel for reduction(+:accepted)
for (size_t n=0; n<N; n++) {
accepted += move_gibbs(random_numbers[n], logtheta_new[n], ngames, games, game_counts, wins);
}
printf("# to_move = %zu\n", N);
printf("# accepted = %zu\n", accepted);
printf("# acceptance ratio = %lf\n", (double) accepted / N);
memcpy(logtheta, logtheta_new, N*K*sizeof(double));
free(logtheta_new);
free(random_numbers);
free(games);
free(game_counts);
}
void
sample_theta_star(const gsl_rng *r, double theta_star[K])
{
double a[K];
for (size_t k=0; k<K; k++) {
a[k] = alpha_k;
}
gsl_ran_dirichlet(r, K, a, theta_star);
}
void
read_theta_star(const char *file_name, double theta_star[K])
{
char buf[80];
FILE *ts = fopen(file_name, "r");
if (!ts) {
fprintf(stderr, "error reading %s\n", file_name);
exit(EXIT_FAILURE);
}
for (size_t k = 0; k<K; k++) {
if (!fgets(buf, 80, ts)) {
fprintf(stderr, "error reading %s\n", file_name);
exit(EXIT_FAILURE);
}
theta_star[k] = atof(buf);
};
fclose(ts);
}
void
sim(const gsl_rng *r, const double theta_star[K])
{
double (*logtheta)[K] = malloc(N * sizeof *logtheta);
double *w = malloc(N * sizeof(double));
double *logw = malloc(N * sizeof(double));
ones(w, N);
zeros(logw, N);
size_t *wins = calloc(K, sizeof *wins);
struct set_counter *games_counter = set_counter_alloc();
/* general info */
printf("# generator type: %s\n", gsl_rng_name(r));
printf("# seed = %lu\n", gsl_rng_default_seed);
printf("\n");
/* sample N particles from the `uniform` prior */
{
double alpha[K];
ones(alpha, K);
double theta[K];
for (size_t n = 0; n < N; n++) {
gsl_ran_dirichlet(r, K, alpha, theta);
#pragma omp simd
for (size_t k=0; k<K; k++)
logtheta[n][k] = log(theta[k]);
}
}
for(size_t t = 0; t < T; t++) {
fprintf(stderr, "t = %zu\r", t); /* for progress monitoring */
printf("# iteration = %zu\n", t);
size_t players[L];
if (strategy == 0) {
/* presentation strategy: thompson sampling */
printf("# strategy: thompson\n");
/* sample a theta from the current posterior */
gsl_ran_discrete_t *g = gsl_ran_discrete_preproc(N, w);
size_t theta_sample_idx = gsl_ran_discrete(r, g);
gsl_ran_discrete_free(g);
printf("# sampled theta: ");
to_string(logtheta[theta_sample_idx], K);
printf("\n");
/* pick L elements from current sample */
gsl_sort_largest_index(players, L, logtheta[theta_sample_idx], 1, K);
} else if (strategy == 1) {
/* presentation strategy: uniform subset */
printf("# strategy: uniform subset\n");
size_t idx[K];
for (size_t k=0; k<K; k++)
idx[k] = k;
gsl_ran_choose(r, players, L, idx, K, sizeof(size_t));
}
set_counter_add(games_counter, players);
printf("# number of unique subsets so far: %zu\n", games_counter->size);
double player_w[L];
printf("# game: ");
for (size_t l=0; l<L-1; l++) {
printf("%zu,", players[l]);
player_w[l] = theta_star[players[l]];
}
printf("%zu\n", players[L-1]);
player_w[L-1] = theta_star[players[L-1]];
printf("# player weights = ");
to_string(player_w, L);
printf("\n");
/* determine outcome using theta_star */
size_t winner;
{
gsl_ran_discrete_t *g = gsl_ran_discrete_preproc(L, player_w);
size_t wn = gsl_ran_discrete(r, g);
winner = players[wn];
gsl_ran_discrete_free(g);
}
printf("# winner: %zu\n", winner);
wins[winner]++;
/* update weights */
#pragma omp parallel for
for(size_t n = 0; n < N; n++) {
double logtheta_winner = logtheta[n][winner];
double lth_game[L];
for (size_t l=0; l<L; l++) {
lth_game[l] = logtheta[n][players[l]];
}
logw[n] += logtheta_winner - log_sum_exp(lth_game, L);
}
/* compute w from logw */
{
double lse = log_sum_exp(logw, N);
for (size_t n=0; n<N; n++) {
w[n] = exp(logw[n] - lse);
assert(gsl_finite(w[n]) == 1);
}
}
/* compute ess and perform resampling if necessary */
{
double two_logw[N];
for (size_t n=0; n<N; n++)
two_logw[n] = 2*logw[n];
double ess = exp(2*log_sum_exp(logw, N) - log_sum_exp(two_logw, N));
printf("# ess = %lf\n", ess);
if (ess < .5*N) {
printf("# resampling at iteration %zu\n", t);
resample_move(r, logtheta, w, games_counter, wins);
ones(w, N);
zeros(logw, N);
}
}
printf("\n");
}
fprintf(stderr, "\n");
/* resample at the end */
printf("# resampling at iteration %zu\n", T);
resample_move(r, logtheta, w, games_counter, wins);
/* no need to reset the weights at this point but just to be safe... */
ones(w, N);
zeros(logw, N);
for(size_t n = 0; n < N; n++) {
to_string(logtheta[n], K);
printf("\n");
}
/* cleanup */
free(logtheta);
free(w);
free(logw);
free(wins);
set_counter_free(games_counter);
}
int
main(int argc, char *argv[])
{
const gsl_rng_type *t;
gsl_rng *r;
gsl_rng_env_setup();
t = gsl_rng_default;
r = gsl_rng_alloc(t);
gsl_set_error_handler_off();
double *theta_star = malloc(K * sizeof(double));
/* read theta_star from a file */
if (argc==2)
read_theta_star(argv[1], theta_star);
else
sample_theta_star(r, theta_star);
printf("# K = %zu\n", K);
printf("# N = %zu\n", N);
printf("# T = %zu\n", T);
printf("# L = %zu\n", L);
printf("# theta_star = ");
to_string(theta_star, K);
printf("\n");
// perform simulation
sim(r, theta_star);
// cleanup
free(theta_star);
gsl_rng_free(r);
exit(EXIT_SUCCESS);
}
| {
"alphanum_fraction": 0.5529926427,
"avg_line_length": 27.7845303867,
"ext": "c",
"hexsha": "2db94cbabb24f296c09e66253a1045362fa7d98e",
"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": "af517e01a0aefa91f7a4b587fbd71a5456762c1a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ilkerg/preference-sampler",
"max_forks_repo_path": "src/sampler.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "af517e01a0aefa91f7a4b587fbd71a5456762c1a",
"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": "ilkerg/preference-sampler",
"max_issues_repo_path": "src/sampler.c",
"max_line_length": 121,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "af517e01a0aefa91f7a4b587fbd71a5456762c1a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ilkerg/preference-sampler",
"max_stars_repo_path": "src/sampler.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2745,
"size": 10058
} |
#ifndef LDA_DOC_TOPIC_PROB_SELECT_H
#define LDA_DOC_TOPIC_PROB_SELECT_H
#include "Lambda.h"
#include "LambdaCreationFunctions.h"
#include "SelectionComp.h"
#include "PDBVector.h"
#include "IntIntVectorPair.h"
#include "IntDoubleVectorPair.h"
#include "DocAssignment.h"
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <random>
#include <gsl/gsl_vector.h>
/* This class samples the topic probability for the document */
using namespace pdb;
class LDADocTopicProbSelection : public SelectionComp<IntDoubleVectorPair, DocAssignment> {
private:
Vector<double> prior;
Handle<Vector<char>> myMem;
int topicNum;
public:
ENABLE_DEEP_COPY
LDADocTopicProbSelection() {}
LDADocTopicProbSelection(Vector<double>& fromPrior) {
this->prior = fromPrior;
this->topicNum = fromPrior.size();
/* Set up the random number generator */
gsl_rng* src = gsl_rng_alloc(gsl_rng_mt19937);
std::random_device rd;
std::mt19937 gen(rd());
gsl_rng_set(src, gen());
int spaceNeeded = sizeof(gsl_rng) + src->type->size;
myMem = makeObject<Vector<char>>(spaceNeeded, spaceNeeded);
memcpy(myMem->c_ptr(), src, sizeof(gsl_rng));
memcpy(myMem->c_ptr() + sizeof(gsl_rng), src->state, src->type->size);
gsl_rng_free(src);
}
Lambda<bool> getSelection(Handle<DocAssignment> checkMe) override {
return makeLambda(checkMe, [](Handle<DocAssignment>& checkMe) { return true; });
}
Lambda<Handle<IntDoubleVectorPair>> getProjection(Handle<DocAssignment> checkMe) override {
return makeLambda(checkMe, [&](Handle<DocAssignment>& checkMe) {
gsl_rng* rng = getRng();
Vector<unsigned>& topicCount = checkMe->getVector();
Handle<Vector<double>> mySamples = makeObject<Vector<double>>(topicNum, topicNum);
double* totalProb = new double[topicNum];
for (int i = 0; i < topicNum; i++) {
totalProb[i] = (this->prior)[i] + topicCount[i];
}
/* Sample the topic probability */
gsl_ran_dirichlet(rng, topicNum, totalProb, mySamples->c_ptr());
Handle<IntDoubleVectorPair> result =
makeObject<IntDoubleVectorPair>(checkMe->getKey(), mySamples);
delete[] totalProb;
return result;
});
}
gsl_rng* getRng() {
gsl_rng* dst = (gsl_rng*)myMem->c_ptr();
dst->state = (void*)(myMem->c_ptr() + sizeof(gsl_rng));
dst->type = gsl_rng_mt19937;
return dst;
}
};
#endif
| {
"alphanum_fraction": 0.6452611219,
"avg_line_length": 29.375,
"ext": "h",
"hexsha": "c2701d596b1e5d14734b65d9da468d5ce48eb8bf",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-03-06T19:28:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-01-18T02:13:53.000Z",
"max_forks_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB",
"max_forks_repo_path": "src/sharedLibraries/headers/LDA/LDADocTopicProbSelection.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4",
"max_issues_repo_issues_event_max_datetime": "2022-01-28T23:17:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-01-28T23:17:14.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB",
"max_issues_repo_path": "src/sharedLibraries/headers/LDA/LDADocTopicProbSelection.h",
"max_line_length": 95,
"max_stars_count": 13,
"max_stars_repo_head_hexsha": "6c2dabd1a3b3f5901a97c788423fdd93cc0015d4",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "venkate5hgunda/CSE598-Spring22-Group22-NetsDB",
"max_stars_repo_path": "src/sharedLibraries/headers/LDA/LDADocTopicProbSelection.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T02:06:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-01-17T16:14:26.000Z",
"num_tokens": 634,
"size": 2585
} |
/**
*
* @file qwrapper_dlaswp.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mathieu Faverge
* @date 2010-11-15
* @generated d Tue Jan 7 11:44:58 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_dlaswp(Quark *quark, Quark_Task_Flags *task_flags,
int n, double *A, int lda,
int i1, int i2, const int *ipiv, int inc)
{
DAG_CORE_LASWP;
QUARK_Insert_Task(
quark, CORE_dlaswp_quark, task_flags,
sizeof(int), &n, VALUE,
sizeof(double)*lda*n, A, INOUT | LOCALITY,
sizeof(int), &lda, VALUE,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*n, ipiv, INPUT,
sizeof(int), &inc, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dlaswp_quark = PCORE_dlaswp_quark
#define CORE_dlaswp_quark PCORE_dlaswp_quark
#endif
void CORE_dlaswp_quark(Quark *quark)
{
int n, lda, i1, i2, inc;
int *ipiv;
double *A;
quark_unpack_args_7(quark, n, A, lda, i1, i2, ipiv, inc);
LAPACKE_dlaswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc );
}
/***************************************************************************//**
*
**/
void QUARK_CORE_dlaswp_f2(Quark *quark, Quark_Task_Flags *task_flags,
int n, double *A, int lda,
int i1, int i2, const int *ipiv, int inc,
double *fake1, int szefake1, int flag1,
double *fake2, int szefake2, int flag2)
{
DAG_CORE_LASWP;
QUARK_Insert_Task(
quark, CORE_dlaswp_f2_quark, task_flags,
sizeof(int), &n, VALUE,
sizeof(double)*lda*n, A, INOUT | LOCALITY,
sizeof(int), &lda, VALUE,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*n, ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(double)*szefake1, fake1, flag1,
sizeof(double)*szefake2, fake2, flag2,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dlaswp_f2_quark = PCORE_dlaswp_f2_quark
#define CORE_dlaswp_f2_quark PCORE_dlaswp_f2_quark
#endif
void CORE_dlaswp_f2_quark(Quark* quark)
{
int n, lda, i1, i2, inc;
int *ipiv;
double *A;
void *fake1, *fake2;
quark_unpack_args_9(quark, n, A, lda, i1, i2, ipiv, inc, fake1, fake2);
LAPACKE_dlaswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc );
}
/***************************************************************************//**
*
**/
void QUARK_CORE_dlaswp_ontile(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_desc descA, double *Aij,
int i1, int i2, const int *ipiv, int inc, double *fakepanel)
{
DAG_CORE_LASWP;
if (fakepanel == Aij) {
QUARK_Insert_Task(
quark, CORE_dlaswp_ontile_quark, task_flags,
sizeof(PLASMA_desc), &descA, VALUE,
sizeof(double)*1, Aij, INOUT | LOCALITY,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(double)*1, fakepanel, SCRATCH,
0);
} else {
QUARK_Insert_Task(
quark, CORE_dlaswp_ontile_quark, task_flags,
sizeof(PLASMA_desc), &descA, VALUE,
sizeof(double)*1, Aij, INOUT | LOCALITY,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(double)*1, fakepanel, INOUT,
0);
}
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dlaswp_ontile_quark = PCORE_dlaswp_ontile_quark
#define CORE_dlaswp_ontile_quark PCORE_dlaswp_ontile_quark
#endif
void CORE_dlaswp_ontile_quark(Quark *quark)
{
int i1, i2, inc;
int *ipiv;
double *A, *fake;
PLASMA_desc descA;
quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake);
CORE_dlaswp_ontile(descA, i1, i2, ipiv, inc);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_dlaswp_ontile_f2(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_desc descA, double *Aij,
int i1, int i2, const int *ipiv, int inc,
double *fake1, int szefake1, int flag1,
double *fake2, int szefake2, int flag2)
{
DAG_CORE_LASWP;
QUARK_Insert_Task(
quark, CORE_dlaswp_ontile_f2_quark, task_flags,
sizeof(PLASMA_desc), &descA, VALUE,
sizeof(double)*1, Aij, INOUT | LOCALITY,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(double)*szefake1, fake1, flag1,
sizeof(double)*szefake2, fake2, flag2,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dlaswp_ontile_f2_quark = PCORE_dlaswp_ontile_f2_quark
#define CORE_dlaswp_ontile_f2_quark PCORE_dlaswp_ontile_f2_quark
#endif
void CORE_dlaswp_ontile_f2_quark(Quark *quark)
{
int i1, i2, inc;
int *ipiv;
double *A;
PLASMA_desc descA;
void *fake1, *fake2;
quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, fake1, fake2);
CORE_dlaswp_ontile(descA, i1, i2, ipiv, inc);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_dswptr_ontile(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_desc descA, double *Aij,
int i1, int i2, const int *ipiv, int inc,
const double *Akk, int ldak)
{
DAG_CORE_TRSM;
QUARK_Insert_Task(
quark, CORE_dswptr_ontile_quark, task_flags,
sizeof(PLASMA_desc), &descA, VALUE,
sizeof(double)*1, Aij, INOUT | LOCALITY,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(double)*ldak, Akk, INPUT,
sizeof(int), &ldak, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dswptr_ontile_quark = PCORE_dswptr_ontile_quark
#define CORE_dswptr_ontile_quark PCORE_dswptr_ontile_quark
#endif
void CORE_dswptr_ontile_quark(Quark *quark)
{
int i1, i2, inc, ldak;
int *ipiv;
double *A, *Akk;
PLASMA_desc descA;
quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, Akk, ldak);
CORE_dswptr_ontile(descA, i1, i2, ipiv, inc, Akk, ldak);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_dlaswpc_ontile(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_desc descA, double *Aij,
int i1, int i2, const int *ipiv, int inc, double *fakepanel)
{
DAG_CORE_LASWP;
if (fakepanel == Aij) {
QUARK_Insert_Task(
quark, CORE_dlaswpc_ontile_quark, task_flags,
sizeof(PLASMA_desc), &descA, VALUE,
sizeof(double)*1, Aij, INOUT | LOCALITY,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(double)*1, fakepanel, SCRATCH,
0);
} else {
QUARK_Insert_Task(
quark, CORE_dlaswpc_ontile_quark, task_flags,
sizeof(PLASMA_desc), &descA, VALUE,
sizeof(double)*1, Aij, INOUT | LOCALITY,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(double)*1, fakepanel, INOUT,
0);
}
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dlaswpc_ontile_quark = PCORE_dlaswpc_ontile_quark
#define CORE_dlaswpc_ontile_quark PCORE_dlaswpc_ontile_quark
#endif
void CORE_dlaswpc_ontile_quark(Quark *quark)
{
int i1, i2, inc;
int *ipiv;
double *A, *fake;
PLASMA_desc descA;
quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake);
CORE_dlaswpc_ontile(descA, i1, i2, ipiv, inc);
}
| {
"alphanum_fraction": 0.4758579998,
"avg_line_length": 36.0602836879,
"ext": "c",
"hexsha": "49601903e8698a9abc3ed92390070f78495f7aac",
"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_dlaswp.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_dlaswp.c",
"max_line_length": 91,
"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_dlaswp.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2745,
"size": 10169
} |
/* $Id$ */
/*
* Copyright (c) 2014 Kristaps Dzonsons <kristaps@kcons.eu>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_histogram.h>
#include <kplot.h>
#include "extern.h"
#define BUFSZ 1024
/*
* All possible input tokens, including some which are "virtual" tokens
* in that they don't map to an exact character representation.
*/
enum token {
TOKEN_PAREN_OPEN,
TOKEN_PAREN_CLOSE,
TOKEN_ADD,
TOKEN_SUB,
TOKEN_MUL,
TOKEN_DIV,
TOKEN_EXP,
TOKEN_END,
TOKEN_NUMBER,
TOKEN_SQRT,
TOKEN_EXPF,
TOKEN_P1,
TOKEN_PN,
TOKEN_N,
TOKEN_ERROR,
TOKEN_SKIP,
TOKEN_POSITIVE,
TOKEN_NEGATIVE,
TOK__MAX
};
enum arity {
ARITY_NONE = 0,
ARITY_ONE,
ARITY_TWO
};
enum assoc {
ASSOC_NONE = 0,
ASSOC_L,
ASSOC_R,
};
struct tok {
char key; /* input identifier */
int prec; /* precedence (if applicable) */
int oper; /* is operator? */
int func; /* is function? */
enum assoc assoc; /* associativity */
enum arity arity; /* n-ary-ess */
enum htype map; /* map to htype (if applicable) */
};
static const struct tok toks[TOK__MAX] = {
{ '(', -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE__MAX }, /* TOKEN_PAREN_OPEN */
{ ')', -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE__MAX }, /* TOKEN_PAREN_CLOSE */
{ '+', 2, 1, 0, ASSOC_L, ARITY_TWO, HNODE_ADD }, /* TOKEN_ADD */
{ '-', 2, 1, 0, ASSOC_L, ARITY_TWO, HNODE_SUB }, /* TOKEN_SUB */
{ '*', 3, 1, 0, ASSOC_L, ARITY_TWO, HNODE_MUL }, /* TOKEN_MUL */
{ '/', 3, 1, 0, ASSOC_L, ARITY_TWO, HNODE_DIV }, /* TOKEN_DIV */
{ '^', 5, 1, 0, ASSOC_R, ARITY_TWO, HNODE_EXP }, /* TOKEN_EXP */
{ '\0', -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE__MAX }, /* TOKEN_END */
{ '\0', -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE_NUMBER }, /* TOKEN_NUMBER */
{ '\0', -1, 0, 1, ASSOC_NONE, ARITY_NONE, HNODE_SQRT }, /* TOKEN_SQRT */
{ '\0', -1, 0, 1, ASSOC_NONE, ARITY_NONE, HNODE_EXPF }, /* TOKEN_EXPF */
{ 'x', -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE_P1 }, /* TOKEN_P1 */
{ 'X', -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE_PN }, /* TOKEN_PN */
{ 'n', -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE_N }, /* TOKEN_N */
{ '\0', -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE__MAX }, /* TOKEN_ERROR */
{ ' ', -1, 0, 0, ASSOC_NONE, ARITY_NONE, HNODE__MAX }, /* TOKEN_SKIP */
{ '+', 4, 1, 0, ASSOC_R, ARITY_ONE, HNODE_POSITIVE }, /* TOKEN_POSITIVE */
{ '-', 4, 1, 0, ASSOC_R, ARITY_ONE, HNODE_NEGATIVE }, /* TOKEN_NEGATIVE */
};
#if 0
static void
hnode_print(struct hnode **p)
{
struct hnode **pp;
if (NULL == p)
return;
for (pp = p; NULL != *pp; pp++) {
switch ((*pp)->type) {
case (HNODE_VAR):
putchar('v');
break;
case (HNODE_P1):
putchar('x');
break;
case (HNODE_P2):
putchar('y');
break;
case (HNODE_NUMBER):
printf("%g", (*pp)->real);
break;
case (HNODE_SQRT):
printf("sqrt");
break;
case (HNODE_ADD):
putchar('+');
break;
case (HNODE_EXP):
putchar('^');
break;
case (HNODE_SUB):
putchar('-');
break;
case (HNODE_MUL):
putchar('*');
break;
case (HNODE_DIV):
putchar('/');
break;
case (HNODE_POSITIVE):
printf("+'");
break;
case (HNODE_NEGATIVE):
printf("-'");
break;
default:
abort();
}
putchar(' ');
}
putchar('\n');
}
#endif
/*
* Check if the current token (which has ARITY_ONE, we assume) is in
* fact unary.
* We do this by checking the previous token: if it's a binary operator
* or an open parenthesis, then we're a unary operator.
*/
static int
check_unary(enum token lasttok)
{
switch (lasttok) {
case (TOK__MAX):
/* FALLTHROUGH */
case (TOKEN_PAREN_OPEN):
/* FALLTHROUGH */
case (TOKEN_ADD):
/* FALLTHROUGH */
case (TOKEN_SUB):
/* FALLTHROUGH */
case (TOKEN_MUL):
/* FALLTHROUGH */
case (TOKEN_DIV):
/* FALLTHROUGH */
case (TOKEN_EXP):
return(1);
default:
break;
}
return(0);
}
/*
* Check if the current token (which has ARITY_TWO, we assume) is in
* fact binary.
* We do this by checking the previous token: if it's an operand or a
* close-paren (i.e., an operand), then we're a binary operator.
*/
static int
check_binary(enum token lasttok)
{
switch (lasttok) {
case (TOKEN_PAREN_CLOSE):
/* FALLTHROUGH */
case (TOKEN_NUMBER):
/* FALLTHROUGH */
case (TOKEN_P1):
/* FALLTHROUGH */
case (TOKEN_PN):
/* FALLTHROUGH */
case (TOKEN_N):
return(1);
default:
break;
}
return(0);
}
/*
* Extra a token from input.
* If TOKEN_ERROR, something bad has happened in the attempt to do so.
* Otherwise, this returns a valid token (possibly end of input).
*/
static enum token
tokenise(const char **v, char *buf, enum token lasttok)
{
size_t i, sz;
/* Short-circuit this case. */
if ('\0' == **v)
return(TOKEN_END);
/* Look for token in our predefined inputs. */
for (i = 0; i < TOK__MAX; i++)
if ('\0' != toks[i].key && **v == toks[i].key) {
switch (toks[i].arity) {
case (ARITY_NONE):
(*v)++;
return((enum token)i);
case (ARITY_ONE):
if ( ! check_unary(lasttok))
continue;
break;
case (ARITY_TWO):
if ( ! check_binary(lasttok))
continue;
break;
}
(*v)++;
return((enum token)i);
}
/* See if we're a real number or identifier. */
if (isdigit((int)**v) || '.' == **v) {
sz = 0;
for ( ; isdigit((int)**v) || '.' == **v; (*v)++) {
assert(sz < BUFSZ);
buf[sz++] = **v;
}
buf[sz] = '\0';
return(TOKEN_NUMBER);
} else if (isalpha((int)**v)) {
sz = 0;
for ( ; isalpha((int)**v); (*v)++) {
assert(sz < BUFSZ);
buf[sz++] = **v;
}
buf[sz] = '\0';
if (0 == strcmp(buf, "sqrt"))
return(TOKEN_SQRT);
else if (0 == strcmp(buf, "exp"))
return(TOKEN_EXPF);
}
/* Eh... */
return(TOKEN_ERROR);
}
/*
* Queue something onto the output RPN queue.
*/
static void
enqueue(struct hnode ***q, size_t *qsz, enum token tok)
{
*q = realloc(*q, ++(*qsz) * sizeof(struct hnode *));
(*q)[*qsz - 1] = calloc(1, sizeof(struct hnode));
(*q)[*qsz - 1]->type = toks[tok].map;
assert(HNODE__MAX != toks[tok].map);
}
/*
* Make sure that all operators and functions are matched with
* arguments.
* The Shunting-Yard algorithm itself doesn't do this, so we need to do
* it now.
*/
static int
check(struct hnode **p)
{
struct hnode **pp;
size_t ssz;
for (ssz = 0, pp = p; NULL != *pp; pp++)
switch ((*pp)->type) {
case (HNODE_P1):
/* FALLTHROUGH */
case (HNODE_PN):
/* FALLTHROUGH */
case (HNODE_N):
/* FALLTHROUGH */
case (HNODE_NUMBER):
ssz++;
break;
case (HNODE_POSITIVE):
/* FALLTHROUGH */
case (HNODE_NEGATIVE):
/* FALLTHROUGH */
case (HNODE_SQRT):
/* FALLTHROUGH */
case (HNODE_EXPF):
if (0 == ssz)
return(0);
break;
case (HNODE_ADD):
/* FALLTHROUGH */
case (HNODE_SUB):
/* FALLTHROUGH */
case (HNODE_MUL):
/* FALLTHROUGH */
case (HNODE_DIV):
/* FALLTHROUGH */
case (HNODE_EXP):
if (ssz < 2)
return(0);
ssz--;
break;
default:
abort();
}
return(1 == ssz);
}
/*
* Dijkstra's Shunting-Yard algorithm for converting an infix-order
* expression to prefix order.
* This returns a NULL-terminated list of expressions to evaluate in
* post-fix order.
*/
struct hnode **
hnode_parse(const char **v)
{
enum token tok, lasttok;
enum token stack[STACKSZ];
char buf[BUFSZ + 1];
struct hnode **q;
int found;
size_t i, qsz, ssz;
q = NULL;
qsz = ssz = 0;
lasttok = TOK__MAX;
while (TOKEN_END != (tok = tokenise(v, buf, lasttok))) {
switch (tok) {
case (TOKEN_ERROR):
goto err;
case (TOKEN_SKIP):
break;
case (TOKEN_P1):
/* FALLTHROUGH */
case (TOKEN_PN):
/* FALLTHROUGH */
case (TOKEN_N):
enqueue(&q, &qsz, tok);
break;
case (TOKEN_NUMBER):
enqueue(&q, &qsz, tok);
q[qsz - 1]->real = atof(buf);
break;
case (TOKEN_SQRT):
/* FALLTHROUGH */
case (TOKEN_EXPF):
/* FALLTHROUGH */
case (TOKEN_PAREN_OPEN):
assert(ssz < STACKSZ);
stack[ssz++] = tok;
break;
case (TOKEN_PAREN_CLOSE):
assert(ssz > 0);
found = 0;
do {
if (TOKEN_PAREN_OPEN == stack[--ssz])
found = 1;
else
enqueue(&q, &qsz, stack[ssz]);
} while ( ! found && ssz > 0);
assert(found);
if (ssz > 0 && toks[stack[ssz - 1]].func)
enqueue(&q, &qsz, stack[--ssz]);
break;
case (TOKEN_POSITIVE):
/* FALLTHROUGH */
case (TOKEN_NEGATIVE):
/* FALLTHROUGH */
case (TOKEN_SUB):
/* FALLTHROUGH */
case (TOKEN_MUL):
/* FALLTHROUGH */
case (TOKEN_DIV):
/* FALLTHROUGH */
case (TOKEN_EXP):
/* FALLTHROUGH */
case (TOKEN_ADD):
assert(toks[tok].prec >= 0);
assert(ASSOC_NONE != toks[tok].assoc);
while (ssz > 0 && toks[stack[ssz - 1]].oper) {
assert(toks[stack[ssz - 1]].prec >= 0);
assert(ASSOC_NONE !=
toks[stack[ssz - 1]].assoc);
if ((ASSOC_L == toks[tok].assoc
&& toks[tok].prec ==
toks[stack[ssz - 1]].prec) ||
(toks[tok].prec <
toks[stack[ssz - 1]].prec))
enqueue(&q, &qsz, stack[--ssz]);
else
break;
}
assert(ssz < STACKSZ);
stack[ssz++] = tok;
break;
default:
abort();
}
if (TOKEN_SKIP != tok)
lasttok = tok;
}
while (ssz > 0) {
--ssz;
if (TOKEN_PAREN_OPEN == stack[ssz])
goto err;
enqueue(&q, &qsz, stack[ssz]);
}
q = realloc(q, ++qsz * sizeof(struct hnode *));
q[qsz - 1] = NULL;
if ( ! check(q))
goto err;
#if 0
hnode_print(q);
#endif
return(q);
err:
for (i = 0; i < qsz; i++)
free(q[i]);
free(q);
return(NULL);
}
struct hnode **
hnode_copy(struct hnode **p)
{
struct hnode **pp;
size_t sz;
for (sz = 0, pp = p; NULL != *pp; pp++)
sz++;
pp = calloc(sz + 1, sizeof(struct hnode *));
for (sz = 0; NULL != *p; p++, sz++) {
pp[sz] = calloc(1, sizeof(struct hnode));
pp[sz]->type = (*p)->type;
pp[sz]->real = (*p)->real;
}
return(pp);
}
void
hnode_free(struct hnode **p)
{
struct hnode **pp;
if (NULL == p)
return;
for (pp = p; NULL != *pp; pp++)
free(*pp);
free(p);
}
/*
* Execute a function in prefix order given variables x (given player's
* strategy), y (other player's strategy), and var (given player's
* morality index).
*/
double
hnode_exec(const struct hnode *const *p, double x, double X, size_t n)
{
double stack[STACKSZ];
const struct hnode *const *pp;
size_t ssz;
double val;
for (ssz = 0, pp = p; NULL != *pp; pp++)
switch ((*pp)->type) {
case (HNODE_P1):
assert(ssz < STACKSZ);
stack[ssz++] = x;
break;
case (HNODE_PN):
assert(ssz < STACKSZ);
stack[ssz++] = X;
break;
case (HNODE_N):
assert(ssz < STACKSZ);
stack[ssz++] = (double)n;
break;
case (HNODE_NUMBER):
assert(ssz < STACKSZ);
stack[ssz++] = (*pp)->real;
break;
case (HNODE_SQRT):
assert(ssz > 0);
val = sqrt(stack[--ssz]);
stack[ssz++] = val;
break;
case (HNODE_EXPF):
assert(ssz > 0);
val = exp(stack[--ssz]);
stack[ssz++] = val;
break;
case (HNODE_ADD):
assert(ssz > 1);
val = stack[ssz - 2] + stack[ssz - 1];
ssz -= 2;
stack[ssz++] = val;
break;
case (HNODE_SUB):
assert(ssz > 1);
val = stack[ssz - 2] - stack[ssz - 1];
ssz -= 2;
stack[ssz++] = val;
break;
case (HNODE_MUL):
assert(ssz > 1);
val = stack[ssz - 2] * stack[ssz - 1];
ssz -= 2;
stack[ssz++] = val;
break;
case (HNODE_DIV):
assert(ssz > 1);
val = stack[ssz - 2] / stack[ssz - 1];
ssz -= 2;
stack[ssz++] = val;
break;
case (HNODE_EXP):
assert(ssz > 1);
val = pow(stack[ssz - 2], stack[ssz - 1]);
ssz -= 2;
stack[ssz++] = val;
break;
case (HNODE_POSITIVE):
assert(ssz > 0);
break;
case (HNODE_NEGATIVE):
assert(ssz > 0);
val = -(stack[--ssz]);
stack[ssz++] = val;
break;
default:
abort();
}
assert(1 == ssz);
return(stack[0]);
}
static void
hnode_test_expect(double x, double X,
double n, const char *expf, double vexp)
{
struct hnode **exp;
double v;
const char *expfp;
expfp = expf;
exp = hnode_parse((const char **)&expfp);
assert(NULL != exp);
v = hnode_exec
((const struct hnode *const *)exp, x, X, n);
g_debug("pi(x=%g, X=%g, n=%g) = %s = %g (want %g)",
x, X, n, expf, v, vexp);
hnode_free(exp);
}
void
hnode_test(void)
{
double x, X, n;
x = 10.0;
X = 20.0;
n = 2.0;
hnode_test_expect(x, X, n,
"(1 - exp(-X)) - x",
(1.0 - exp(-X)) - x);
hnode_test_expect(x, X, n,
"sqrt(1 / n * X) - 0.5 * x^2",
sqrt(1.0 / n * X) - 0.5 * pow(x, 2.0));
hnode_test_expect(x, X, n,
"x - (X - x) * x - x^2",
x - (X - x) * x - pow(x, 2.0));
hnode_test_expect(x, X, n,
"x * (1 / X) - x",
x * (1.0 / X) - x);
}
| {
"alphanum_fraction": 0.5910380881,
"avg_line_length": 21.5619967794,
"ext": "c",
"hexsha": "eeb79d3cad3fada0c42ac79f1107fd4d1d8c64ed",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f",
"max_forks_repo_licenses": [
"0BSD"
],
"max_forks_repo_name": "kristapsdz/bmigrate",
"max_forks_repo_path": "parser.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"0BSD"
],
"max_issues_repo_name": "kristapsdz/bmigrate",
"max_issues_repo_path": "parser.c",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0280a899564031a5a14af87d9264cd239a89851f",
"max_stars_repo_licenses": [
"0BSD"
],
"max_stars_repo_name": "kristapsdz/bmigrate",
"max_stars_repo_path": "parser.c",
"max_stars_repo_stars_event_max_datetime": "2018-03-03T17:13:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-03-03T17:13:19.000Z",
"num_tokens": 4603,
"size": 13390
} |
/* specfunc/dilog.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include "gsl_sf_clausen.h"
#include "gsl_sf_trig.h"
#include "gsl_sf_log.h"
#include "gsl_sf_dilog.h"
/* Evaluate series for real dilog(x)
* Sum[ x^k / k^2, {k,1,Infinity}]
*
* Converges rapidly for |x| < 1/2.
*/
static
int
dilog_series(const double x, gsl_sf_result * result)
{
const int kmax = 1000;
double sum = x;
double term = x;
int k;
for(k=2; k<kmax; k++) {
double rk = (k-1.0)/k;
term *= x;
term *= rk*rk;
sum += term;
if(fabs(term/sum) < GSL_DBL_EPSILON) break;
}
result->val = sum;
result->err = 2.0 * fabs(term);
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
if(k == kmax)
GSL_ERROR ("error", GSL_EMAXITER);
else
return GSL_SUCCESS;
}
/* Assumes x >= 0.0
*/
static
int
dilog_xge0(const double x, gsl_sf_result * result)
{
if(x > 2.0) {
const double log_x = log(x);
gsl_sf_result ser;
int stat_ser = dilog_series(1.0/x, &ser);
double t1 = M_PI*M_PI/3.0;
double t2 = ser.val;
double t3 = 0.5*log_x*log_x;
result->val = t1 - t2 - t3;
result->err = GSL_DBL_EPSILON * fabs(log_x) + ser.err;
result->err += GSL_DBL_EPSILON * (fabs(t1) + fabs(t2) + fabs(t3));
result->val += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_ser;
}
else if(x > 1.01) {
const double log_x = log(x);
const double log_term = log_x * (log(1.0-1.0/x) + 0.5*log_x);
gsl_sf_result ser;
int stat_ser = dilog_series(1.0 - 1.0/x, &ser);
double t1 = M_PI*M_PI/6.0;
double t2 = ser.val;
double t3 = log_term;
result->val = t1 + t2 - t3;
result->err = GSL_DBL_EPSILON * fabs(log_x) + ser.err;
result->err += GSL_DBL_EPSILON * (fabs(t1) + fabs(t2) + fabs(t3));
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_ser;
}
else if(x > 1.0) {
/* series around x = 1.0 */
const double eps = x - 1.0;
const double lne = log(eps);
const double c0 = M_PI*M_PI/6.0;
const double c1 = 1.0 - lne;
const double c2 = -(1.0 - 2.0*lne)/4.0;
const double c3 = (1.0 - 3.0*lne)/9.0;
const double c4 = -(1.0 - 4.0*lne)/16.0;
const double c5 = (1.0 - 5.0*lne)/25.0;
const double c6 = -(1.0 - 6.0*lne)/36.0;
const double c7 = (1.0 - 7.0*lne)/49.0;
const double c8 = -(1.0 - 8.0*lne)/64.0;
result->val = c0+eps*(c1+eps*(c2+eps*(c3+eps*(c4+eps*(c5+eps*(c6+eps*(c7+eps*c8)))))));
result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else if(x == 1.0) {
result->val = M_PI*M_PI/6.0;
result->err = 2.0 * GSL_DBL_EPSILON * M_PI*M_PI/6.0;
return GSL_SUCCESS;
}
else if(x > 0.5) {
const double log_x = log(x);
gsl_sf_result ser;
int stat_ser = dilog_series(1.0-x, &ser);
double t1 = M_PI*M_PI/6.0;
double t2 = ser.val;
double t3 = log_x*log(1.0-x);
result->val = t1 - t2 - t3;
result->err = GSL_DBL_EPSILON * fabs(log_x) + ser.err;
result->err += GSL_DBL_EPSILON * (fabs(t1) + fabs(t2) + fabs(t3));
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_ser;
}
else if(x > 0.0) {
return dilog_series(x, result);
}
else {
/* x == 0.0 */
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
}
/* Evaluate the series representation for Li2(z):
*
* Li2(z) = Sum[ |z|^k / k^2 Exp[i k arg(z)], {k,1,Infinity}]
* |z| = r
* arg(z) = theta
*
* Assumes 0 < r < 1.
*/
static
int
dilogc_series_1(double r, double cos_theta, double sin_theta,
gsl_sf_result * real_result, gsl_sf_result * imag_result)
{
double alpha = 1.0 - cos_theta;
double beta = sin_theta;
double ck = cos_theta;
double sk = sin_theta;
double rk = r;
double real_sum = r*ck;
double imag_sum = r*sk;
int kmax = 50 + (int)(22.0/(-log(r))); /* tuned for double-precision */
int k;
for(k=2; k<kmax; k++) {
double ck_tmp = ck;
ck = ck - (alpha*ck + beta*sk);
sk = sk - (alpha*sk - beta*ck_tmp);
rk *= r;
real_sum += rk/((double)k*k) * ck;
imag_sum += rk/((double)k*k) * sk;
}
real_result->val = real_sum;
real_result->err = 2.0 * kmax * GSL_DBL_EPSILON * fabs(real_sum);
imag_result->val = imag_sum;
imag_result->err = 2.0 * kmax * GSL_DBL_EPSILON * fabs(imag_sum);
return GSL_SUCCESS;
}
/* Evaluate a series for Li_2(z) when |z| is near 1.
* This is uniformly good away from z=1.
*
* Li_2(z) = Sum[ a^n/n! H_n(theta), {n, 0, Infinity}]
*
* where
* H_n(theta) = Sum[ e^(i m theta) m^n / m^2, {m, 1, Infinity}]
* a = ln(r)
*
* H_0(t) = Gl_2(t) + i Cl_2(t)
* H_1(t) = 1/2 ln(2(1-c)) + I atan2(-s, 1-c)
* H_2(t) = -1/2 + I/2 s/(1-c)
* H_3(t) = -1/2 /(1-c)
* H_4(t) = -I/2 s/(1-c)^2
* H_5(t) = 1/2 (2 + c)/(1-c)^2
* H_6(t) = I/2 s/(1-c)^5 (8(1-c) - s^2 (3 + c))
*
* assumes: 0 <= theta <= 2Pi
*/
static
int
dilogc_series_2(double r, double theta, double cos_theta, double sin_theta,
gsl_sf_result * real_result, gsl_sf_result * imag_result)
{
double a = log(r);
double omc = 1.0 - cos_theta;
double H_re[7];
double H_im[7];
double an, nfact;
double sum_re, sum_im;
gsl_sf_result Him0;
int n;
H_re[0] = M_PI*M_PI/6.0 + 0.25*(theta*theta - 2.0*M_PI*fabs(theta));
gsl_sf_clausen_e(theta, &Him0);
H_im[0] = Him0.val;
H_re[1] = -0.5*log(2.0*omc);
H_im[1] = -atan2(-sin_theta, omc);
H_re[2] = -0.5;
H_im[2] = 0.5 * sin_theta/omc;
H_re[3] = -0.5/omc;
H_im[3] = 0.0;
H_re[4] = 0.0;
H_im[4] = -0.5*sin_theta/(omc*omc);
H_re[5] = 0.5 * (2.0 + cos_theta)/(omc*omc);
H_im[5] = 0.0;
H_re[6] = 0.0;
H_im[6] = 0.5 * sin_theta/(omc*omc*omc*omc*omc)
* (8*omc - sin_theta*sin_theta*(3 + cos_theta));
sum_re = H_re[0];
sum_im = H_im[0];
an = 1.0;
nfact = 1.0;
for(n=1; n<=6; n++) {
double t;
an *= a;
nfact *= n;
t = an/nfact;
sum_re += t * H_re[n];
sum_im += t * H_im[n];
}
real_result->val = sum_re;
real_result->err = 2.0 * 6.0 * GSL_DBL_EPSILON * fabs(sum_re) + fabs(an/nfact);
imag_result->val = sum_im;
imag_result->err = 2.0 * 6.0 * GSL_DBL_EPSILON * fabs(sum_im) + Him0.err + fabs(an/nfact);
return GSL_SUCCESS;
}
/* complex dilogarithm in the unit disk
* assumes: r < 1 and 0 <= theta <= 2Pi
*/
static
int
dilogc_unitdisk(double r, double theta, gsl_sf_result * real_dl, gsl_sf_result * imag_dl)
{
const double zeta2 = M_PI*M_PI/6.0;
int stat_dilog;
gsl_sf_result cos_theta;
gsl_sf_result sin_theta;
int stat_cos = gsl_sf_cos_e(theta, &cos_theta);
int stat_sin = gsl_sf_sin_e(theta, &sin_theta);
gsl_sf_result x;
gsl_sf_result y;
gsl_sf_result x_tmp, y_tmp, r_tmp;
gsl_sf_result result_re_tmp, result_im_tmp;
double cos_theta_tmp;
double sin_theta_tmp;
x.val = r * cos_theta.val;
x.err = r * cos_theta.err;
y.val = r * sin_theta.val;
y.err = r * sin_theta.err;
/* Reflect away from z = 1 if
* we are too close.
*/
if(x.val > 0.5) {
x_tmp.val = 1.0 - x.val;
x_tmp.err = GSL_DBL_EPSILON * (1.0 + fabs(x.val)) + x.err;
y_tmp.val = -y.val;
y_tmp.err = y.err;
r_tmp.val = sqrt(x_tmp.val*x_tmp.val + y_tmp.val*y_tmp.val);
r_tmp.err = (x_tmp.err*fabs(x_tmp.val) + y_tmp.err*fabs(y_tmp.val))/fabs(r_tmp.val);
}
else {
x_tmp.val = x.val;
x_tmp.err = x.err;
y_tmp.val = y.val;
y_tmp.err = y.err;
r_tmp.val = r;
r_tmp.err = r * GSL_DBL_EPSILON;
}
cos_theta_tmp = x_tmp.val / r_tmp.val;
sin_theta_tmp = y_tmp.val / r_tmp.val;
/* Calculate dilog of the transformed variable.
*/
if(r_tmp.val < 0.98) {
stat_dilog = dilogc_series_1(r_tmp.val, cos_theta_tmp, sin_theta_tmp,
&result_re_tmp, &result_im_tmp
);
}
else {
double theta_tmp = atan2(y_tmp.val, x_tmp.val);
stat_dilog = dilogc_series_2(r_tmp.val, theta_tmp, cos_theta_tmp, sin_theta_tmp,
&result_re_tmp, &result_im_tmp
);
}
/* Unwind reflection if necessary.
*
* Li2(z) = -Li2(1-z) + zeta(2) - ln(z) ln(1-z)
*/
if(x.val > 0.5) {
double lnz = log(r); /* log(|z|) */
double lnomz = log(r_tmp.val); /* log(|1-z|) */
double argz = theta; /* arg(z) */
double argomz = atan2(y_tmp.val, x_tmp.val); /* arg(1-z) */
real_dl->val = -result_re_tmp.val + zeta2 - lnz*lnomz + argz*argomz;
real_dl->err = result_re_tmp.err;
real_dl->err += GSL_DBL_EPSILON * (zeta2 + fabs(lnz*lnomz) + fabs(argz*argomz));
real_dl->err += 2.0 * GSL_DBL_EPSILON * fabs(real_dl->val);
imag_dl->val = -result_im_tmp.val - argz*lnomz - argomz*lnz;
imag_dl->err = result_im_tmp.err;
imag_dl->err += GSL_DBL_EPSILON * (fabs(argz*lnomz) + fabs(argomz*lnz));
imag_dl->err += 2.0 * GSL_DBL_EPSILON * fabs(imag_dl->val);
}
else {
real_dl->val = result_re_tmp.val;
real_dl->err = result_re_tmp.err;
imag_dl->val = result_im_tmp.val;
imag_dl->err = result_im_tmp.err;
}
return GSL_ERROR_SELECT_3(stat_dilog, stat_sin, stat_cos);
}
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int
gsl_sf_dilog_e(const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x >= 0.0) {
return dilog_xge0(x, result);
}
else {
gsl_sf_result d1, d2;
int stat_d1 = dilog_xge0( -x, &d1);
int stat_d2 = dilog_xge0(x*x, &d2);
result->val = -d1.val + 0.5 * d2.val;
result->err = d1.err + 0.5 * d2.err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_d1, stat_d2);
}
}
int
gsl_sf_complex_dilog_e(const double r, double theta,
gsl_sf_result * real_dl, gsl_sf_result * imag_dl)
{
/* CHECK_POINTER(real_dl) */
/* CHECK_POINTER(imag_dl) */
if(r == 0.0) {
real_dl->val = 0.0;
real_dl->err = 0.0;
imag_dl->val = 0.0;
imag_dl->err = 0.0;
return GSL_SUCCESS;
}
/*
if(theta < 0.0 || theta > 2.0*M_PI) {
gsl_sf_angle_restrict_pos_e(&theta);
}
*/
/* Trap cases of real-valued argument.
*/
if(theta == 0.0) {
int stat_d;
imag_dl->val = ( r > 1.0 ? -M_PI * log(r) : 0.0 );
imag_dl->err = 2.0 * GSL_DBL_EPSILON * fabs(imag_dl->val);
stat_d = gsl_sf_dilog_e(r, real_dl);
return stat_d;
}
if(theta == M_PI) {
int stat_d;
imag_dl->val = 0.0;
imag_dl->err = 0.0;
stat_d = gsl_sf_dilog_e(-r, real_dl);
return stat_d;
}
/* Trap unit circle case.
*/
if(r == 1.0) {
gsl_sf_result theta_restrict;
int stat_r = gsl_sf_angle_restrict_pos_err_e(theta, &theta_restrict);
int stat_c;
const double term1 = theta_restrict.val*theta_restrict.val;
const double term2 = 2.0*M_PI*fabs(theta_restrict.val);
const double term1_err = 2.0 * fabs(theta_restrict.val * theta_restrict.err);
const double term2_err = 2.0*M_PI*fabs(theta_restrict.err);
real_dl->val = M_PI*M_PI/6.0 + 0.25*(term1 - term2);
real_dl->err = 2.0 * GSL_DBL_EPSILON * (M_PI*M_PI/6.0 + 0.25 * (fabs(term1) + fabs(term2)));
real_dl->err += 0.25 * (term1_err + term2_err);
real_dl->err += 2.0 * GSL_DBL_EPSILON * fabs(real_dl->val);
stat_c = gsl_sf_clausen_e(theta, imag_dl);
stat_r = 0; /* discard restrict status */
return stat_c;
}
/* Generic case.
*/
{
int stat_dilog;
double r_tmp, theta_tmp;
gsl_sf_result result_re_tmp, result_im_tmp;
/* Reduce argument to unit disk.
*/
if(r > 1.0) {
r_tmp = 1.0 / r;
theta_tmp = /* 2.0*M_PI */ - theta;
}
else {
r_tmp = r;
theta_tmp = theta;
}
/* Calculate in the unit disk.
*/
stat_dilog = dilogc_unitdisk(r_tmp, theta_tmp,
&result_re_tmp, &result_im_tmp
);
/* Unwind the inversion if necessary. We calculate
* the imaginary part explicitly if using the inversion
* because there is no simple relationship between
* arg(1-z) and arg(1 - 1/z), which is the "omega"
* term in [Lewin A.2.5 (1)].
*/
if(r > 1.0) {
const double zeta2 = M_PI*M_PI/6.0;
double x = r * cos(theta);
double y = r * sin(theta);
double omega = atan2(y, 1.0-x);
double lnr = log(r);
double pmt = M_PI - theta;
gsl_sf_result Cl_a, Cl_b, Cl_c;
double r1, r2, r3, r4, r5;
int stat_c1 = gsl_sf_clausen_e(2.0*omega, &Cl_a);
int stat_c2 = gsl_sf_clausen_e(2.0*theta, &Cl_b);
int stat_c3 = gsl_sf_clausen_e(2.0*(omega+theta), &Cl_c);
int stat_c = GSL_ERROR_SELECT_3(stat_c1, stat_c2, stat_c3);
r1 = -result_re_tmp.val;
r2 = -0.5*lnr*lnr;
r3 = 0.5*pmt*pmt;
r4 = -zeta2;
r5 = omega*lnr;
real_dl->val = r1 + r2 + r3 + r4;
real_dl->err = result_re_tmp.err;
real_dl->err += GSL_DBL_EPSILON * (fabs(r1) + fabs(r2) + fabs(r3) + fabs(r4));
real_dl->err += 2.0 * GSL_DBL_EPSILON * fabs(real_dl->val);
imag_dl->val = r5 + 0.5*(Cl_a.val + Cl_b.val - Cl_c.val);
imag_dl->err = GSL_DBL_EPSILON * fabs(r5);
imag_dl->err += GSL_DBL_EPSILON * 0.5*(fabs(Cl_a.val) + fabs(Cl_b.val) + fabs(Cl_c.val));
imag_dl->err += 0.5*(Cl_a.err + Cl_b.err + Cl_c.err);
imag_dl->err += 2.0*GSL_DBL_EPSILON * fabs(imag_dl->val);
return GSL_ERROR_SELECT_2(stat_dilog, stat_c);
}
else {
real_dl->val = result_re_tmp.val;
real_dl->err = result_re_tmp.err;
imag_dl->val = result_im_tmp.val;
imag_dl->err = result_im_tmp.err;
return stat_dilog;
}
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_dilog(const double x)
{
EVAL_RESULT(gsl_sf_dilog_e(x, &result));
}
| {
"alphanum_fraction": 0.5939572083,
"avg_line_length": 28.6281800391,
"ext": "c",
"hexsha": "82c2c982fb3f3585d964bd914b760b341c6e72b1",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/dilog.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/dilog.c",
"max_line_length": 97,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/dilog.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": 5227,
"size": 14629
} |
/**
* \file IIRFilter.h
*/
#ifndef ATK_EQ_IIRFILTER_H
#define ATK_EQ_IIRFILTER_H
#include <algorithm>
#include <cassert>
#include <vector>
#include <gsl/gsl>
#include <ATK/config.h>
#include <ATK/Core/TypeTraits.h>
#include <ATK/EQ/config.h>
namespace ATK
{
/// IIR filter template class (Direct Form I)
template<class Coefficients >
class IIRFilter final : public Coefficients
{
protected:
/// Simplify parent calls
using Parent = Coefficients;
using typename Parent::DataType;
using typename Parent::AlignedScalarVector;
using Parent::converted_inputs;
using Parent::outputs;
using Parent::coefficients_in;
using Parent::coefficients_out;
using Parent::input_sampling_rate;
using Parent::output_sampling_rate;
using Parent::nb_input_ports;
using Parent::nb_output_ports;
using Parent::in_order;
using Parent::out_order;
using Parent::input_delay;
using Parent::output_delay;
using Parent::setup;
public:
/*!
* @brief Constructor
* @param nb_channels is the number of input and output channels
*/
explicit IIRFilter(gsl::index nb_channels = 1)
:Parent(nb_channels)
{
}
/// Move constructor
IIRFilter(IIRFilter&& other)
:Parent(std::move(other))
{
}
void setup() final
{
Parent::setup();
input_delay = in_order;
output_delay = out_order;
if (out_order > 0)
{
coefficients_out_2.resize(out_order, 0);
for (unsigned int i = 1; i < out_order; ++i)
{
coefficients_out_2[i] = coefficients_out[out_order - 1] * coefficients_out[i] + coefficients_out[i - 1];
}
coefficients_out_2[0] = coefficients_out[out_order - 1] * coefficients_out[0];
}
if (out_order > 1)
{
coefficients_out_3.resize(out_order, 0);
for (unsigned int i = 0; i < 2; ++i)
{
coefficients_out_3[i] = coefficients_out[out_order - 2] * coefficients_out[i] + coefficients_out[out_order - 1] * coefficients_out_2[i];
}
for (unsigned int i = 2; i < out_order; ++i)
{
coefficients_out_3[i] = coefficients_out[out_order - 2] * coefficients_out[i] + coefficients_out[out_order - 1] * coefficients_out_2[i] + coefficients_out[i - 2];
}
if (out_order > 2)
{
coefficients_out_4.resize(out_order, 0);
for (unsigned int i = 0; i < 3; ++i)
{
coefficients_out_4[i] = coefficients_out[out_order - 3] * coefficients_out[i] + coefficients_out[out_order - 2] * coefficients_out_2[i] + coefficients_out[out_order - 1] * coefficients_out_3[i];
}
for (unsigned int i = 3; i < out_order; ++i)
{
coefficients_out_4[i] = coefficients_out[out_order - 3] * coefficients_out[i] + coefficients_out[out_order - 2] * coefficients_out_2[i] + coefficients_out[out_order - 1] * coefficients_out_3[i] + coefficients_out[i - 3];
}
}
else // out_order = 2
{
coefficients_out_4.resize(out_order, 0);
for (unsigned int i = 0; i < 2; ++i)
{
coefficients_out_4[i] = coefficients_out[out_order - 2] * coefficients_out_2[i] + coefficients_out[out_order - 1] * coefficients_out_3[i];
}
}
}
}
template<typename T>
void handle_recursive_iir(const T* ATK_RESTRICT coefficients_out_ptr, const T* ATK_RESTRICT coefficients_out_2_ptr, const T* ATK_RESTRICT coefficients_out_3_ptr, const T* ATK_RESTRICT coefficients_out_4_ptr, DataType* ATK_RESTRICT output, gsl::index size) const
{
gsl::index i = 0;
if (out_order > 2)
{
for (i = 0; i < std::min(size - 3, size); i += 4)
{
DataType tempout = output[i];
DataType tempout2 = output[i] * coefficients_out_ptr[out_order - 1] + output[i + 1];
DataType tempout3 = output[i] * coefficients_out_ptr[out_order - 2] + tempout2 * coefficients_out_ptr[out_order - 1] + output[i + 2];
DataType tempout4 = output[i] * coefficients_out_ptr[out_order - 3] + tempout2 * coefficients_out_ptr[out_order - 2] + tempout3 * coefficients_out_ptr[out_order - 1] + output[i + 3];
ATK_VECTORIZE_REMAINDER for (unsigned int j = 0; j < out_order; ++j)
{
tempout += coefficients_out_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];
tempout2 += coefficients_out_2_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];
tempout3 += coefficients_out_3_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];
tempout4 += coefficients_out_4_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];
}
output[i] = tempout;
output[i + 1] = tempout2;
output[i + 2] = tempout3;
output[i + 3] = tempout4;
}
}
else if(out_order == 2)
{
for (i = 0; i < std::min(size - 3, size); i += 4)
{
DataType tempout = output[i];
DataType tempout2 = output[i] * coefficients_out_ptr[out_order - 1] + output[i + 1];
DataType tempout3 = output[i] * coefficients_out_ptr[out_order - 2] + tempout2 * coefficients_out_ptr[out_order - 1] + output[i + 2];
DataType tempout4 = tempout2 * coefficients_out_ptr[out_order - 2] + tempout3 * coefficients_out_ptr[out_order - 1] + output[i + 3];
ATK_VECTORIZE_REMAINDER for (unsigned int j = 0; j < out_order; ++j)
{
tempout += coefficients_out_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];
tempout2 += coefficients_out_2_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];
tempout3 += coefficients_out_3_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];
tempout4 += coefficients_out_4_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];
}
output[i] = tempout;
output[i + 1] = tempout2;
output[i + 2] = tempout3;
output[i + 3] = tempout4;
}
}
for (; i < size; ++i)
{
DataType tempout = output[i];
for (unsigned int j = 0; j < out_order; ++j)
{
tempout += coefficients_out_ptr[j] * output[static_cast<int64_t>(i) - out_order + j];
}
output[i] = tempout;
}
}
void process_impl(gsl::index size) const final
{
assert(input_sampling_rate == output_sampling_rate);
assert(nb_input_ports == nb_output_ports);
assert(coefficients_in.data());
assert(out_order == 0 || coefficients_out.data() != nullptr);
const auto* ATK_RESTRICT coefficients_in_ptr = coefficients_in.data();
const auto* ATK_RESTRICT coefficients_out_ptr = coefficients_out.data();
const auto* ATK_RESTRICT coefficients_out_2_ptr = coefficients_out_2.data();
const auto* ATK_RESTRICT coefficients_out_3_ptr = coefficients_out_3.data();
const auto* ATK_RESTRICT coefficients_out_4_ptr = coefficients_out_4.data();
for(gsl::index channel = 0; channel < nb_input_ports; ++channel)
{
const DataType* ATK_RESTRICT input = converted_inputs[channel] - static_cast<int64_t>(in_order);
DataType* ATK_RESTRICT output = outputs[channel];
for(gsl::index i = 0; i < size; ++i)
{
output[i] = 0;
}
for (gsl::index j = 0; j < in_order + 1; ++j)
{
for (gsl::index i = 0; i < size; ++i)
{
output[i] += coefficients_in_ptr[j] * input[i + j];
}
}
handle_recursive_iir(coefficients_out_ptr, coefficients_out_2_ptr, coefficients_out_3_ptr, coefficients_out_4_ptr, output, size);
}
}
/// Returns the vector of internal coefficients for the MA section
const AlignedScalarVector& get_coefficients_in() const
{
return coefficients_in;
}
/// Returns the vector of internal coefficients for the AR section, without degree 0 implicitely set to -1
const AlignedScalarVector& get_coefficients_out() const
{
return coefficients_out;
}
protected:
AlignedScalarVector coefficients_out_2;
AlignedScalarVector coefficients_out_3;
AlignedScalarVector coefficients_out_4;
};
/// IIR filter template class. Transposed Direct Form II implementation
template<class Coefficients >
class IIRTDF2Filter final : public Coefficients
{
public:
/// Simplify parent calls
using Parent = Coefficients;
using typename Parent::DataType;
using typename Parent::AlignedScalarVector;
using Parent::converted_inputs;
using Parent::outputs;
using Parent::coefficients_in;
using Parent::coefficients_out;
using Parent::input_sampling_rate;
using Parent::output_sampling_rate;
using Parent::nb_input_ports;
using Parent::nb_output_ports;
using Parent::in_order;
using Parent::out_order;
using Parent::input_delay;
using Parent::output_delay;
using Parent::setup;
protected:
mutable typename Parent::AlignedVector state;
public:
explicit IIRTDF2Filter(gsl::index nb_channels = 1)
:Parent(nb_channels)
{
}
/// Move constructor
IIRTDF2Filter(IIRTDF2Filter&& other)
:Parent(std::move(other))
{
}
void setup() final
{
Parent::setup();
input_delay = in_order;
output_delay = out_order;
state.assign(nb_input_ports * (std::max(input_delay, output_delay) + 1), TypeTraits<DataType>::Zero());
}
void process_impl(gsl::index size) const final
{
assert(input_sampling_rate == output_sampling_rate);
for(gsl::index channel = 0; channel < nb_input_ports; ++channel)
{
const DataType* ATK_RESTRICT input = converted_inputs[channel];
DataType* ATK_RESTRICT output = outputs[channel];
DataType* ATK_RESTRICT current_state = &state[channel * (std::max(input_delay, output_delay) + 1)];
for(gsl::index i = 0; i < size; ++i)
{
output[i] = coefficients_in[in_order] * input[i] + current_state[0];
auto min_order = std::min(input_delay, output_delay);
for(gsl::index j = 0; j < min_order; ++j)
{
current_state[j] = current_state[j + 1] + input[i] * coefficients_in[in_order - static_cast<int64_t>(j) - 1] + output[i] * coefficients_out[out_order - static_cast<int64_t>(j) - 1];
}
for(gsl::index j = min_order; j < input_delay; ++j)
{
current_state[j] = current_state[j + 1] + input[i] * coefficients_in[in_order - static_cast<int64_t>(j) - 1];
}
for(gsl::index j = min_order; j < output_delay; ++j)
{
current_state[j] = current_state[j + 1] + output[i] * coefficients_out[out_order - static_cast<int64_t>(j) - 1];
}
}
}
}
/// Returns the vector of internal coefficients for the MA section
const AlignedScalarVector& get_coefficients_in() const
{
return coefficients_in;
}
/// Returns the vector of internal coefficients for the AR section, without degree 0 implicitely set to -1
const AlignedScalarVector& get_coefficients_out() const
{
return coefficients_out;
}
};
}
#endif
| {
"alphanum_fraction": 0.6248573686,
"avg_line_length": 36.3993610224,
"ext": "h",
"hexsha": "1406a91ebf6ff1af77bbb6db0d0466d4a50fa7fe",
"lang": "C",
"max_forks_count": 48,
"max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z",
"max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "D-J-Roberts/AudioTK",
"max_forks_repo_path": "ATK/EQ/IIRFilter.h",
"max_issues_count": 22,
"max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd",
"max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "D-J-Roberts/AudioTK",
"max_issues_repo_path": "ATK/EQ/IIRFilter.h",
"max_line_length": 265,
"max_stars_count": 249,
"max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "D-J-Roberts/AudioTK",
"max_stars_repo_path": "ATK/EQ/IIRFilter.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z",
"num_tokens": 2932,
"size": 11393
} |
#ifndef TOY_VN_GENERATOR_H
#define TOY_VN_GENERATOR_H
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <complex>
#include <vector>
#include <iomanip>
#include <stdio.h>
#include <algorithm>
#include <chrono>
#include <random>
#include <omp.h>
#include "sampled_distribution.h"
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
using namespace std;
namespace flow_generator
{
// ------------------------------------
// Initialize default parameters here.
// ------------------------------------
int n_pT = 6;
double max_pT = 3000000.0;
double min_pT = 0.0;
int order = 2;
//double eta_low = 2.0;
//double eta_high = 10.0;
int N_events_to_generate = 1000;
int N_particles_per_event = 100;
long N_total_events = 0;
long N_running_total_events = 0;
bool use_seed = true;
int seed_index = -1;
bool print_randomly_generated_data = false;
bool include_psi2_PTslope_fluctuations = false;
double v2_magnitude = 0.1;
string resultsDirectory = "./results/";
string output_name = resultsDirectory + "/data.dat";
// ------------------------------------
// Define structs and vectors.
// ------------------------------------
// struct for event information
typedef struct
{
int eventID;
int Nparticles;
vector<vector<double> > eta_vec;
vector<vector<double> > pphi_vec;
vector<vector<double> > pT_vec;
} event_data;
// declare needed vectors
vector<event_data> all_events;
vector<vector<double> > pT_vec;
vector<vector<double> > eta_vec;
vector<vector<double> > phi_vec;
vector<vector<int> > event_vec;
//---------------------------------------------------------
// Generate data randomly to mimic (non-factorizable) flow.
void generate_random_data(int dataset=-1)
{
double delta_pT = (max_pT-min_pT)/(n_pT);
pT_vec.clear();
eta_vec.clear();
phi_vec.clear();
event_vec.clear();
pT_vec = vector<vector<double> >(n_pT, vector<double> (0));
eta_vec = vector<vector<double> >(n_pT, vector<double> (0));
phi_vec = vector<vector<double> >(n_pT, vector<double> (0));
event_vec = vector<vector<int> >(n_pT, vector<int> (0));
// Set up distributions
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
default_random_engine generator;
if ( use_seed )
generator = default_random_engine(seed);
else
generator = default_random_engine(seed_index);
uniform_real_distribution<double> mean_pT_distribution(0.90, 1.10);
//const double mean_pT = mean_pT_distribution(generator);
const double mean_pT = 1.0;
exponential_distribution<double> pT_distribution( mean_pT );
normal_distribution<double> eta_distribution(0.0, 2.0);
uniform_real_distribution<double> v2_distribution(0.05, 0.45);
uniform_real_distribution<double> psi2_distribution(0.0, 2.0*M_PI);
uniform_real_distribution<double> pphi_distribution(0.0, 2.0*M_PI);
normal_distribution<double> psi2_pTslope_distribution(0.0,0.1);
auto phiFunc = [](double x, double v2) { return x + v2*sin(2.0*x); };
std::mt19937 gen;
if ( use_seed )
gen = std::mt19937(seed);
else
gen = std::mt19937(seed_index);
double fluctuation_switch_factor
= double(include_psi2_PTslope_fluctuations);
for (int iEvent = 0; iEvent < N_events_to_generate; iEvent++)
{
//double v2 = v2_distribution(generator);
double v2 = v2_magnitude;
double psi2 = 0.0*psi2_distribution(generator);
double psi2_pTslope = fluctuation_switch_factor
* psi2_pTslope_distribution(generator);
for (int iParticle = 0; iParticle < N_particles_per_event; iParticle++)
{
// ---------------------------------------------
// Try to mimic different types of flow effects
// ---------------------------------------------
const double pT_value = pT_distribution(generator);
//Sampled_distribution<> dist(phiFunc, 0.0, 2.0*M_PI, v2*pT_value / (mean_pT+pT_value));
Sampled_distribution<> dist(phiFunc, 0.0, 2.0*M_PI, v2);
const double pphi_value = dist(gen) + psi2 + psi2_pTslope*pT_value;
//const double pphi_value = dist(gen) + psi2 + 0.5*M_PI*pT_value / (mean_pT+pT_value);
// Sort into bins.
double pT = pT_value;
double eta = 0.0*eta_distribution(generator);
double phi = pphi_value;
int event = iEvent;
if(pT > max_pT)
{
//cout << "Warning: pT = " << pT << " larger than max_pT = " << max_pT << " in event = " << event << endl;
continue;
}
if(pT < min_pT)
{
//cout << "Warning: pT = " << pT << " smaller than min_pT = " << min_pT << " in event = " << event << endl;
continue;
}
else
{
int bin = int((pT-min_pT)/delta_pT);
eta_vec[bin].push_back(eta);
phi_vec[bin].push_back(phi);
pT_vec[bin].push_back(pT);
event_vec[bin].push_back(event);
//cout << "Check: " << pT << " " << eta << " " << phi << " " << event << " " << bin << endl;
}
}
}
//----------------------------------------------
all_events.clear();
all_events = vector<event_data>(N_events_to_generate);
for ( auto & this_event : all_events )
{
this_event.eta_vec = vector<vector<double> >( n_pT, vector<double>(0) );
this_event.pphi_vec = vector<vector<double> >( n_pT, vector<double>(0) );
this_event.pT_vec = vector<vector<double> >( n_pT, vector<double>(0) );
}
for (int bin = 0; bin < n_pT; bin++)
{
const int n_particles_in_this_bin = event_vec[bin].size();
for (int iParticle = 0; iParticle < n_particles_in_this_bin; iParticle++)
{
int event_ID_of_this_particle = event_vec[bin][iParticle];
all_events[event_ID_of_this_particle].eta_vec[bin].push_back( eta_vec[bin][iParticle] );
all_events[event_ID_of_this_particle].pphi_vec[bin].push_back( phi_vec[bin][iParticle] );
all_events[event_ID_of_this_particle].pT_vec[bin].push_back( pT_vec[bin][iParticle] );
all_events[event_ID_of_this_particle].eventID = event_ID_of_this_particle;
}
}
//----------------------------------------------
//----------------------------------------------
// Tally number of completed events
N_running_total_events += N_events_to_generate;
cout << "Generated " << N_particles_per_event * N_events_to_generate
<< " particles belonging to "
<< N_events_to_generate << " events."
<< endl;
cout << "Currently analyzed " << N_running_total_events
<< " / " << N_total_events << " events." << endl;
//----------------------------------------------
// Dump simulated data to file if desired
if ( print_randomly_generated_data )
{
int n_zero = static_cast<int>( log10( N_particles_per_event*N_total_events ) )-1;
string dataset_stem = ( dataset >= 0 ) ?
std::string(n_zero - std::to_string(dataset).length(), '0')
+ std::to_string( dataset ) : "";
string RNG_filename = resultsDirectory + "/event_" + dataset_stem + ".dat";
ofstream RNG_output( RNG_filename.c_str() );
for ( auto & this_event : all_events )
for (int bin = 0; bin < n_pT; bin++)
{
const int n_particles_in_this_bin = this_event.eta_vec[bin].size();
const auto & this_pT_bin = this_event.pT_vec[bin];
const auto & this_pphi_bin = this_event.pphi_vec[bin];
const auto & this_eta_bin = this_event.eta_vec[bin];
for (int iParticle = 0; iParticle < n_particles_in_this_bin; iParticle++)
RNG_output << setprecision(15) << setw(18)
/*<< this_pT_bin[iParticle] << " "
<< this_eta_bin[iParticle] << " "*/
<< this_pphi_bin[iParticle] /*<< " "
<< this_event.eventID*/ << endl;
}
RNG_output.close();
}
return;
}
}
#endif
| {
"alphanum_fraction": 0.5743559017,
"avg_line_length": 35.2109704641,
"ext": "h",
"hexsha": "7fb21322ff1fba779f413603f1c541b48f46a91a",
"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": "7a124f6fe66fb802f63a2f6f548f134fc265133f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "astrophysicist87/PHripser",
"max_forks_repo_path": "toy_vn_generator/generator/include/toy_vn_generator.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7a124f6fe66fb802f63a2f6f548f134fc265133f",
"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": "astrophysicist87/PHripser",
"max_issues_repo_path": "toy_vn_generator/generator/include/toy_vn_generator.h",
"max_line_length": 113,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7a124f6fe66fb802f63a2f6f548f134fc265133f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "astrophysicist87/PHripser",
"max_stars_repo_path": "toy_vn_generator/generator/include/toy_vn_generator.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2153,
"size": 8345
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <Accelerate/Accelerate.h>
struct _FINCHAIN {
int length; // Length of state vector
int currentIter;
double *currentState, *avgState, *varState, *proposedState, *_M2;
double logLHDCurrentState;
double accProb, avgAccProb;
gsl_rng *r;
};
typedef struct _FINCHAIN FINCHAIN;
/*
Initialises the finite dimensional chain
*/
void finmcmc_initChain(FINCHAIN *C, int n);
/*
Frees the finite dimensional chain
*/
void finmcmc_freeChain(FINCHAIN *C);
void finmcmc_printChain(FINCHAIN C);
void finmcmc_writeChain(const FINCHAIN *C, FILE *fp);
void finmcmc_gausRanVec(const FINCHAIN *C, double *x, double stdDev);
/*
Proposes a standard RWMH move
*/
void finmcmc_proposeRWMH(const FINCHAIN *C, double stdDev, double beta);
/*
Update chain
*/
void finmcmc_updateRWMH(FINCHAIN *C, double logLHDOfProposal);
//void fin_initChain(FINCHAIN *C, int n, int sizePhi);
//void sampleRMWH(CHAIN *C);
//void sampleIndependenceSampler(CHAIN *C);
//void updateMean(CHAIN *C);
//void updateVar(CHAIN *C);
//void randomPriorDraw(gsl_rng *r, double PRIOR_ALPHA, fftw_complex *randDrawCoeffs);
| {
"alphanum_fraction": 0.742211838,
"avg_line_length": 22.5263157895,
"ext": "h",
"hexsha": "06e22a796b5e372a57c4ac242a42022784fc6757",
"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": "b745c933203c52732a5daac12e84f52d7af13266",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dmcdougall/mcmclib",
"max_forks_repo_path": "mcmclib/finmcmc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266",
"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": "dmcdougall/mcmclib",
"max_issues_repo_path": "mcmclib/finmcmc.h",
"max_line_length": 85,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "b745c933203c52732a5daac12e84f52d7af13266",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dmcdougall/mcmclib",
"max_stars_repo_path": "mcmclib/finmcmc.h",
"max_stars_repo_stars_event_max_datetime": "2015-11-21T22:02:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-21T22:02:58.000Z",
"num_tokens": 377,
"size": 1284
} |
/*
* test.c
*
*
* Created by ashleyr on 30/06/2010.
* Copyright 2010 __MyCompanyName__. All rights reserved.
*
*/
#include "headera.h"
#include <stdlib.h>
//#include <malloc.h>
//#include <fstream>
//#include <iomanip>
#include <stdio.h>
#include <math.h>
//#include <string>
#include <time.h>
#include <gsl/gsl_math.h>
//#include <gsl/gsl_complex.h>
//#include <gsl/gsl_complex_math.h>
//#include <gsl/gsl_const_num.h>
//#include <gsl/gsl_const_mksa.h>
//#include <gsl/gsl_sf.h>
#include <gsl/gsl_linalg.h>
//#include <gsl/gsl_eigen.h>
//#include <gsl/gsl_blas.h>
//#include <gsl/gsl_permutation.h>
//#include <gsl/gsl_errno.h>
//#include <gsl/gsl_matrix.h>
//#include <gsl/gsl_integration.h>
//#include <gsl/gsl_monte.h>
//#include <gsl/gsl_monte_plain.h>
//#include <gsl/gsl_monte_miser.h>
//#include <gsl/gsl_monte_vegas.h>
//#include <gsl/gsl_rng.h>
//#include <gsl/gsl_randist.h>
//#include <gsl/gsl_odeiv.h>
main(int argc, char *argv[]) {
int nran = 100000;
int Nline_max =1000;
double a;
double *lcd = dvector(1,1000000);
double *lcr = dvector(1,1000000);
double *lsd = dvector(1,1000000);
double *lsr = dvector(1,1000000);
double *lzw = dvector(1,1000000);
double *lpc = dvector(1,1000000);
int i = 0;
int k = 0;
int j = 0;
int N = 0;
double ti = time(NULL);
//int nbin = 99;
double angm;
angm = atof(argv[2]);
//double minang = .2*pi/180.*angm;
double minang = 0*pi/180.;
double binsize = 0.15*angm*pi/180.;
double maxang = angm*12.*pi/180.;
int nbin = (maxang-minang)/binsize;
double binl[nbin];
double angl[nbin];
double binlpix[nbin];
double binedges[nbin+2];
//double g = minang/maxang;
for(int nb=0;nb<nbin;nb++) {
binl[nb] = 0;
binlpix[nb] = 0;
}
for(int bn=0;bn<nbin+2;bn++) {
double num = (bn);
double angle = maxang - binsize*num;
if (angle < 0) angle = 0;
double angb = maxang-binsize*num-binsize/2.;
binedges[bn] = cos(angle);
if (bn<nbin) {
angl[bn] =angb;
}
//printf("%lf %lf %lf\n",angle,binedges[bn],cos(angle));
}
char fxi_name[200];
char s1[200];
sprintf(s1,argv[1]);
strcpy(fxi_name,s1);
sprintf(fxi_name,strcat(fxi_name,"odenspczw.dat"));
FILE *fxi;
printf("%s\n",s1);
fxi=fopen(fxi_name,"r");
if (fxi == NULL) perror ("Error opening file");
int Nline=0;
const int bsz=240;
char buf[bsz];
while(fgets(buf,bsz,fxi)!= NULL) {
double cd,cr,sr,sd,zw,pc;
//if(sscanf(buf,"%*d %f %f %f %f",&cd,&cr,&sd,&sd)!=4)
// err_handler("xi input");
//puts(buf);
sscanf(buf,"%lf %lf %lf %lf %lf %lf",&sr,&cr,&sd,&cd,&zw,&pc);
//cd = 1.;
//cr = 1.;
//sr = 1.;
//sd = 1.;
lcd[Nline] = cd;
lcr[Nline] = cr;
lsr[Nline] = sr;
lsd[Nline] = sd;
lzw[Nline] = zw;
lpc[Nline] = pc;
Nline++;
}
printf("%i \n",Nline);
/* while (i<nran) {
l[i] = rand();
i = i+1;
}
*/
float be;
float r;
while (k<Nline) {
j = k+1;
while (j<Nline) {
a = lcd[k]*lcd[j]*(lcr[k]*lcr[j] + lsr[k]*lsr[j]) + lsd[k]*lsd[j];
//r = lsr[k];
be = binedges[0];
int ba = -1;
while (a > be) {
ba++;
be = binedges[ba+1];
}
if (ba > -1 && ba < nbin){
binlpix[ba] += lpc[k]*lpc[j];
binl[ba] += lzw[k]*lzw[j]*lpc[k]*lpc[j];
}
j++;
N+=1;
}
//printf("%f %f\n",be,r);
k++;
}
double tf = time(NULL)-ti;
printf("took %g\n",tf);
char foname[200];
//char sf1[200];
strcat(s1,"2ptPixclb.dat");
sprintf(foname,s1);
FILE *fo;
fo =fopen(foname,"w");
for (int ip=0; ip<nbin; ip++) {
fprintf(fo,"%g %g \n",angl[ip]*180./pi,binl[ip]/binlpix[ip]);
}
//fclose(fxi);
//exit(0);
}
| {
"alphanum_fraction": 0.5287616177,
"avg_line_length": 24.5740740741,
"ext": "c",
"hexsha": "c41cf9ab0b0c4f1fb7ed862a6cd5fc0050c30962",
"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": "aa0505b4d711e591f8a54121ea103ca3e72bdfc8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mehdirezaie/LSSutils",
"max_forks_repo_path": "scripts/analysis/pix2p_linbin.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "aa0505b4d711e591f8a54121ea103ca3e72bdfc8",
"max_issues_repo_issues_event_max_datetime": "2020-08-25T17:57:19.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-08-19T21:47:47.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "mehdirezaie/LSSutils",
"max_issues_repo_path": "scripts/analysis/pix2p_linbin.c",
"max_line_length": 78,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "aa0505b4d711e591f8a54121ea103ca3e72bdfc8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mehdirezaie/LSSutils",
"max_stars_repo_path": "scripts/analysis/pix2p_linbin.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-15T22:38:31.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-15T22:38:31.000Z",
"num_tokens": 1393,
"size": 3981
} |
//===--- Sudoku/Location_Utilities.h ---===//
//
// Utilities for class Sudoku::Location
//===----------------------------------------------------------------------===//
#pragma once
#include "Board_Section_traits.h"
#include "Location.h"
#include "Size.h"
#include "traits.h"
#include <gsl/gsl> // index
#include <vector>
#include <algorithm> // minmax_element, is_sorted, all_of
#include <iterator> // back_inserter
#include <limits> // numeric_limits
#include "Board.fwd.h" // Forward declarations
namespace Sudoku
{
//===-- function declarations ---------------------------------------------===//
template<int N>
constexpr void valid_dimensions() noexcept;
template<int N>
constexpr bool is_valid(Location<N>) noexcept;
template<int N>
constexpr bool is_valid(const std::vector<Location<N>>& locs) noexcept(true);
template<int N>
constexpr bool is_valid_size(gsl::index elem) noexcept;
template<int N>
constexpr bool is_valid_size(gsl::index row, gsl::index col) noexcept;
template<int N>
constexpr bool is_same_row(Location<N>, Location<N>) noexcept;
template<int N>
constexpr bool is_same_col(Location<N>, Location<N>) noexcept;
template<int N>
constexpr bool is_same_block(Location<N>, Location<N>) noexcept;
template<int N, typename ItrT>
constexpr bool is_same_row(ItrT begin, ItrT end) noexcept;
template<int N, typename ItrT>
constexpr bool is_same_col(ItrT begin, ItrT end) noexcept;
template<int N, typename ItrT>
constexpr bool is_same_block(ItrT begin, ItrT end) noexcept;
template<int N>
std::vector<Location<N>> get_same_row(
const Location<N>, const std::vector<Location<N>>&) noexcept(true);
template<int N>
std::vector<Location<N>> get_same_col(
const Location<N>, const std::vector<Location<N>>&) noexcept(true);
template<int N>
std::vector<Location<N>> get_same_block(
const Location<N>, const std::vector<Location<N>>&) noexcept(true);
template<int N, typename S>
constexpr bool is_same_section(S section, Location<N>) noexcept;
template<typename SectionT, int N>
bool is_same_section(SectionT, std::vector<Location<N>>&) noexcept;
template<
int N,
typename S,
typename = std::enable_if_t<
Board_Section::traits::is_Row_v<S> ||
Board_Section::traits::is_Col_v<S>>>
bool intersect_block(S section, Location<N> block_loc) noexcept;
//===----------------------------------------------------------------------===//
// Compile-time only Test
template<int N>
constexpr void valid_dimensions() noexcept
{
// input check
static_assert((base_size<N>) > 1, "base_size too small");
static_assert(
base_size<N> < elem_size<N> && elem_size<N> <= full_size<N> &&
base_size<N> < std::numeric_limits<int>::max() && // <limits>
elem_size<N> < std::numeric_limits<int>::max() &&
full_size<N> < std::numeric_limits<int>::max(),
"board size out of bounds");
// logic check
static_assert(
base_size<N> * base_size<N> == elem_size<N> &&
elem_size<N> * elem_size<N> == full_size<N>,
"size calculation broken");
}
// Test if Location on Board
template<int N>
[[nodiscard]] inline constexpr bool is_valid(const Location<N> loc) noexcept
{
return (loc.element() >= 0 && loc.element() < full_size<N>);
}
// Test if Locations on Board and if sorted (ascending)
template<int N>
[[nodiscard]] inline constexpr bool
is_valid(const std::vector<Location<N>>& locs) noexcept(true)
{ // std::is_sorted can throw std::bad_alloc
return (
!locs.empty() && (std::is_sorted(locs.cbegin(), locs.cend()) &&
locs.cbegin()->element() >= 0 &&
locs.crbegin()->element() < full_size<N>));
}
// Test row/col/block-element
template<int N>
[[nodiscard]] inline constexpr bool
is_valid_size(const gsl::index elem) noexcept
{
return (elem >= 0 && elem < elem_size<N>);
}
// Test if location on Board
template<int N>
[[nodiscard]] inline constexpr bool
is_valid_size(const gsl::index row, const gsl::index col) noexcept
{
return is_valid_size<N>(row) && is_valid_size<N>(col);
}
//===----------------------------------------------------------------------===//
// check
template<int N>
[[nodiscard]] inline constexpr bool
is_same_row(const Location<N> left, const Location<N> right) noexcept
{
return (is_valid<N>(left) && is_valid<N>(right)) &&
left.row() == right.row();
}
// check: all in same row
template<int N, typename ItrT>
[[nodiscard]] constexpr bool
is_same_row(const ItrT begin, const ItrT end) noexcept
{
{
static_assert(traits::is_forward<ItrT>);
}
if (begin == end)
return false;
const auto itr = begin + 1;
return std::all_of(
itr, end, [begin](Location<N> i) { return is_same_row<N>(*begin, i); });
}
// return all in same row
template<int N> // NOLINTNEXTLINE(bugprone-exception-escape)
[[nodiscard]] std::vector<Location<N>> get_same_row(
const Location<N> left,
const std::vector<Location<N>>& right) noexcept(true)
{ // std::copy_if could throw std::bad_alloc
std::vector<Location<N>> output{};
const auto predicate = [&left](Location<N> loc) {
return is_same_row(left, loc);
};
std::copy_if(
right.cbegin(), right.cend(), std::back_inserter(output), predicate);
return output;
}
// check
template<int N>
[[nodiscard]] inline constexpr bool
is_same_col(const Location<N> left, const Location<N> right) noexcept
{
return (is_valid<N>(left) && is_valid<N>(right)) &&
left.col() == right.col();
}
// check: all in same col
template<int N, typename ItrT>
[[nodiscard]] inline constexpr bool
is_same_col(const ItrT begin, const ItrT end) noexcept
{
{
static_assert(traits::is_forward<ItrT>);
}
if (begin == end)
return false;
const auto itr = begin + 1;
return std::all_of(
itr, end, [begin](Location<N> i) { return is_same_col<N>(*begin, i); });
}
// return all in same col
template<int N> // NOLINTNEXTLINE(bugprone-exception-escape)
[[nodiscard]] std::vector<Location<N>> get_same_col(
const Location<N> left,
const std::vector<Location<N>>& right) noexcept(true)
{ // std::copy_if could throw std::bad_alloc
std::vector<Location<N>> output{};
const auto predicate = [&left](Location<N> loc) {
return is_same_col(left, loc);
};
std::copy_if(
right.cbegin(), right.cend(), std::back_inserter(output), predicate);
return output;
}
// check
template<int N>
[[nodiscard]] inline constexpr bool
is_same_block(const Location<N> left, const Location<N> right) noexcept
{
return (is_valid<N>(left) && is_valid<N>(right)) &&
left.block() == right.block();
}
// check all in same block
template<int N, typename ItrT>
[[nodiscard]] inline constexpr bool
is_same_block(const ItrT begin, const ItrT end) noexcept
{
{
static_assert(traits::is_forward<ItrT>);
}
if (begin == end)
return false;
const auto itr = begin + 1;
return std::all_of(itr, end, [begin](Location<N> i) {
return is_same_block<N>(*begin, i);
});
}
// return all in same block
template<int N> // NOLINTNEXTLINE(bugprone-exception-escape)
[[nodiscard]] std::vector<Location<N>> get_same_block(
const Location<N> left,
const std::vector<Location<N>>& right) noexcept(true)
{ // std::copy_if could throw std::bad_alloc
std::vector<Location<N>> output{};
const auto predicate = [&left](Location<N> loc) {
return is_same_block(left, loc);
};
std::copy_if(
right.cbegin(), right.cend(), std::back_inserter(output), predicate);
return output;
}
// check: [loc] is in [section]
template<int N, typename S>
[[nodiscard]] inline constexpr bool
is_same_section(const S section, const Location<N> loc) noexcept
{
static_assert(Board_Section::traits::is_Section_v<S>);
if constexpr (Board_Section::traits::is_Row_v<S>)
return is_same_row(loc, section.cbegin().location());
else if constexpr (Board_Section::traits::is_Col_v<S>)
return is_same_col(loc, section.cbegin().location());
else
{
static_assert(Board_Section::traits::is_Block_v<S>);
return is_same_block(loc, section.cbegin().location());
}
}
// check: [section] intersects block containing [loc]
template<int N, typename S, typename>
[[nodiscard]] inline bool
intersect_block(const S section, const Location<N> block_loc) noexcept
{
for (auto itr = section.cbegin(); itr != section.cend(); ++itr)
{
if (is_same_block(block_loc, itr.location()))
{
return true;
}
}
return false;
}
// check: at least one [location] inside [section]
template<typename SectionT, int N>
[[nodiscard]] inline bool is_same_section(
SectionT const section, std::vector<Location<N>> const& locs) noexcept
{
return std::any_of(locs.cbegin(), locs.cend(), [section](Location<N> L) {
return is_same_section(section, L);
});
}
} // namespace Sudoku
| {
"alphanum_fraction": 0.681712153,
"avg_line_length": 28.4850498339,
"ext": "h",
"hexsha": "9df5873fe59fbc00c0a9592f2f84d06e0c3a0911",
"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": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "FeodorFitsner/fwkSudoku",
"max_forks_repo_path": "Sudoku/Sudoku/Location_Utilities.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"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": "FeodorFitsner/fwkSudoku",
"max_issues_repo_path": "Sudoku/Sudoku/Location_Utilities.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "FeodorFitsner/fwkSudoku",
"max_stars_repo_path": "Sudoku/Sudoku/Location_Utilities.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2165,
"size": 8574
} |
#pragma once
//=============================================================================
// EXTERNAL DECLARATIONS
//=============================================================================
#include "Core/Components/IComponentInterface.h"
#include "Core/Components/IdType.h"
#include <memory>
#include <gsl/span>
namespace engine
{
//=============================================================================
// FORWARD DECLARATIONS
//=============================================================================
class IGameObject;
using GameObjectRef = std::shared_ptr<IGameObject>;
using GameObjectWeakRef = std::weak_ptr<IGameObject>;
//=============================================================================
// INTERFACE IComponent
//=============================================================================
class IComponent
{
public:
virtual ~IComponent() {}
public:
virtual gsl::span<IdType> interfaces() = 0;
virtual void onAttached(const GameObjectRef &iGameObject) = 0;
virtual void onDetached(const GameObjectRef &iGameObject) = 0;
};
} // namespace engine
| {
"alphanum_fraction": 0.4307832423,
"avg_line_length": 31.3714285714,
"ext": "h",
"hexsha": "4a607d4b5bc5727b10074e047a626e6f4e916e63",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-09-25T22:24:16.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-09-25T22:24:16.000Z",
"max_forks_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "gaspardpetit/INF740-GameEngine",
"max_forks_repo_path": "Core/Components/IComponent.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239",
"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": "gaspardpetit/INF740-GameEngine",
"max_issues_repo_path": "Core/Components/IComponent.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "075b6563204fb3d1cf7531599f30dd296c2c9239",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "gaspardpetit/INF740-GameEngine",
"max_stars_repo_path": "Core/Components/IComponent.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 165,
"size": 1098
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** This file forms part of the Underworld geophysics modelling application. **
** **
** For full license and copyright information, please refer to the LICENSE.md file **
** located at the project root, or contact the authors. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#ifndef _writeMat_h
#define _writeMat_h
#include <petsc.h>
#include <petscmat.h>
#include <petscvec.h>
void bsscr_writeMat(Mat A, char name[], char message[]);
void bsscr_writeVec(Vec V, char name[], char message[]);
#endif
| {
"alphanum_fraction": 0.3644251627,
"avg_line_length": 51.2222222222,
"ext": "h",
"hexsha": "c6d25abbaa9f13ac37ca31b3777fe4a6a01792d4",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z",
"max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "longgangfan/underworld2",
"max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/writeMatVec.h",
"max_issues_count": 561,
"max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "longgangfan/underworld2",
"max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/writeMatVec.h",
"max_line_length": 87,
"max_stars_count": 116,
"max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "longgangfan/underworld2",
"max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/writeMatVec.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z",
"num_tokens": 291,
"size": 922
} |
// Standard libraries.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Libraries from packages outside ASF.
#include <glib.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_statistics_double.h>
// Libraries developed at ASF.
#include <asf.h>
#include <asf_meta.h>
#include <asf_raster.h>
#include <float_image.h>
#include <uint8_image.h>
#include <libasf_proj.h>
#include <spheroids.h>
#include <asf_contact.h>
#include <asf_glib.h>
#include <asf_nan.h>
// Headers defined by this library.
#include "asf_geocode.h"
const float_image_byte_order_t fibo_be = FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN;
typedef int project_t(project_parameters_t *pps, double lat, double lon,
double height, double *x, double *y, double *z, datum_type_t dtm);
typedef int project_arr_t(project_parameters_t *pps, double *lat, double *lon,
double *height, double **projected_x, double **projected_y,
double **projected_z, long length, datum_type_t dtm);
typedef int unproject_t(project_parameters_t *pps, double x, double y, double z,
double *lat, double *lon, double *height, datum_type_t dtm);
typedef int unproject_arr_t(project_parameters_t *pps, double *x, double *y,
double *z, double **lat, double **lon,
double **height, long length, datum_type_t dtm);
void location_minmax(meta_location *loc, double *minLat, double *maxLat,
double *minLon, double *maxLon)
{
int ii;
double corner_lat[4], corner_lon[4], min_x, max_x, min_y, max_y;
min_x = min_y = 9999999;
max_x = max_y = -9999999;
corner_lat[0] = loc->lat_start_near_range;
corner_lat[1] = loc->lat_start_far_range;
corner_lat[2] = loc->lat_end_near_range;
corner_lat[3] = loc->lat_end_far_range;
corner_lon[0] = loc->lon_start_near_range;
corner_lon[1] = loc->lon_start_far_range;
corner_lon[2] = loc->lon_end_near_range;
corner_lon[3] = loc->lon_end_far_range;
for (ii=0; ii<4; ii++) {
if (corner_lat[ii] < min_y)
min_y = corner_lat[ii];
if (corner_lat[ii] > max_y)
max_y = corner_lat[ii];
if (corner_lon[ii] < min_x)
min_x = corner_lon[ii];
if (corner_lon[ii] > max_x)
max_x = corner_lon[ii];
}
*minLat = min_y;
*maxLat = max_y;
*minLon = min_x;
*maxLon = max_x;
}
char *proj_info_as_string(projection_type_t projection_type,
project_parameters_t *pp, datum_type_t *datum)
{
static char ret[256];
char datum_str[256];
switch (projection_type)
{
case UNIVERSAL_TRANSVERSE_MERCATOR:
if (datum) {
sprintf(datum_str, " Datum: %s\n\n", datum_toString(*datum));
}
sprintf(ret, "Projection: UTM\n"
" Zone : %d\n%s",
pp->utm.zone,
(datum) ? datum_str : "\n");
break;
case POLAR_STEREOGRAPHIC:
if (datum) {
sprintf(datum_str, " Reference spheroid: %s\n\n", datum_toString(*datum));
}
sprintf(ret,
"Projection: Polar Stereographic\n"
" Standard parallel : %.4f\n"
" Central meridian : %.4f\n"
" Hemisphere : %c\n%s",
pp->ps.slat, pp->ps.slon, pp->ps.is_north_pole ? 'N' : 'S',
(datum) ? datum_str : "\n");
break;
case ALBERS_EQUAL_AREA:
if (datum) {
sprintf(datum_str, " Datum : %s\n\n", datum_toString(*datum));
}
sprintf(ret,
"Projection: Albers Equal Area Conic\n"
" First standard parallel : %.4f\n"
" Second standard parallel: %.4f\n"
" Central meridian : %.4f\n"
" Latitude of origin : %.4f\n%s",
pp->albers.std_parallel1, pp->albers.std_parallel2,
pp->albers.center_meridian, pp->albers.orig_latitude,
(datum) ? datum_str : "\n");
break;
case LAMBERT_CONFORMAL_CONIC:
if (datum) {
sprintf(datum_str, " Datum : %s\n\n", datum_toString(*datum));
}
sprintf(ret,
"Projection: Lambert Conformal Conic\n"
" First standard parallel : %.4f\n"
" Second standard parallel: %.4f\n"
" Central meridian : %.4f\n"
" Latitude of origin : %.4f\n%s",
pp->lamcc.plat1, pp->lamcc.plat2, pp->lamcc.lon0, pp->lamcc.lat0,
(datum) ? datum_str : "\n");
break;
case LAMBERT_AZIMUTHAL_EQUAL_AREA:
if (datum) {
sprintf(datum_str, " Datum : %s\n\n", datum_toString(*datum));
}
sprintf(ret,
"Projection: Lambert Azimuthal Equal Area\n"
" Latitude of origin: %.4f\n"
" Central meridian : %.4f\n%s",
pp->lamaz.center_lat, pp->lamaz.center_lon,
(datum) ? datum_str : "\n");
break;
case EQUI_RECTANGULAR:
if (datum) {
sprintf(datum_str, " Datum : %s\n\n", datum_toString(*datum));
}
sprintf(ret,
"Projection: Equirectangular\n"
" Latitude of origin: %.4f\n"
" Central meridian : %.4f\n%s",
pp->eqr.orig_latitude, pp->eqr.central_meridian,
(datum) ? datum_str : "\n");
break;
case EQUIDISTANT:
if (datum) {
sprintf(datum_str, " Datum : %s\n\n", datum_toString(*datum));
}
sprintf(ret,
"Projection: Equidistant\n"
" Latitude of origin: %.4f\n"
" Central meridian : %.4f\n%s",
pp->eqc.orig_latitude, pp->eqc.central_meridian,
(datum) ? datum_str : "\n");
break;
case MERCATOR:
if (datum) {
sprintf(datum_str, " Datum : %s\n\n", datum_toString(*datum));
}
sprintf(ret,
"Projection: Mercator\n"
" Standard parallel : %.4f\n"
" Latitude of origin: %.4f\n"
" Central meridian : %.4f\n%s",
pp->mer.standard_parallel, pp->mer.orig_latitude,
pp->mer.central_meridian,
(datum) ? datum_str : "\n");
break;
case SINUSOIDAL:
sprintf(ret,
"Projection: SINUSOIDAL\n"
" Longitude center : %.4f\n"
" Spherical radius : %.3f\n",
pp->sin.longitude_center, pp->sin.sphere);
break;
case SCANSAR_PROJECTION:
sprintf(ret,
"Projection: ScanSAR\n");
break;
case LAT_LONG_PSEUDO_PROJECTION:
sprintf(ret,
"Projection: Lat/Lon (pseudoprojection)\n");
break;
default:
asfPrintError("Projection type not supported!\n");
break;
}
return ret;
}
static void print_proj_info(projection_type_t projection_type,
project_parameters_t *pp, datum_type_t datum)
{
asfPrintStatus(proj_info_as_string(projection_type, pp, &datum));
}
// Blurb about what the user can do if projection errors are too
// large. Called when we detect this condition.
static void print_large_error_blurb(int force_flag)
{
if (!force_flag) {
asfPrintWarning(
"Large projection errors occurred!\n\nLarge projection errors can result\n"
"if your projection parameters do not accurately represent the scene you\n"
"are geocoding. You can either re-run geocode using the '--force' option,\n"
"or adjust your projection parameters to better reflect the scene.\n");
}
}
static int is_alos_prism(meta_parameters *meta) {
return strcmp(meta->general->sensor, "ALOS") == 0 &&
strcmp(meta->general->sensor_name, "PRISM") == 0;
}
static int is_alos_avnir(meta_parameters *meta) {
return strcmp(meta->general->sensor, "ALOS") == 0 &&
strcmp(meta->general->sensor_name, "AVNIR") == 0;
}
// Since our normal approach is to pass the datum from the input image
// on through to the (re)projected output image, reprojecting a pixel
// from a lat long pseudoprojected image requires us to do almost
// nothing. Pseudoprojected images have units of degrees, so all we
// have to do is convert as appropriate. But we still need these
// functions to use when we need to use a function pointer to perform
// a generic operation.
static int
project_lat_long_pseudo (project_parameters_t *pps, double lat, double lon,
double height, double *x, double *y, double *z,
datum_type_t datum)
{
/* Silence compiler warning about unused argument. */
pps = pps; datum = datum;
*x = lon * R2D;
*y = lat * R2D;
if (z) *z = height;
return TRUE;
}
static int
project_lat_long_pseudo_arr(project_parameters_t *pps, double *lat, double *lon,
double *height, double **x, double **y,
double **z, long length, datum_type_t datum)
{
pps = pps; datum = datum;
long ii;
double *pz;
*x = (double *) MALLOC(sizeof(double) * length);
*y = (double *) MALLOC(sizeof(double) * length);
if (z) {
*z = (double *) MALLOC(sizeof(double) * length);
pz = *z;
}
double *px = *x;
double *py = *y;
for (ii=0; ii<length; ii++) {
px[ii] = lon[ii] * R2D;
py[ii] = lat[ii] * R2D;
if (z)
pz[ii] = height[ii];
}
return TRUE;
}
static int
project_lat_long_pseudo_inv (project_parameters_t *pps, double x, double y,
double z, double *lat, double *lon,
double *height, datum_type_t datum)
{
/* Silence compiler warning about unused argument. */
pps = pps; datum = datum;
*lat = y * D2R;
*lon = x * D2R;
if (height) *height = z;
return TRUE;
}
static int
project_lat_long_pseudo_inv_arr(project_parameters_t *pps, double *x, double *y,
double *z, double **lat, double **lon,
double **height, long length,
datum_type_t datum)
{
pps = pps; datum = datum;
long ii;
*lat = (double *) MALLOC(sizeof(double) * length);
*lon = (double *) MALLOC(sizeof(double) * length);
*height = (double *) MALLOC(sizeof(double) * length);
double *plat = *lat;
double *plon = *lon;
double *pheight = *height;
for (ii=0; ii<length; ii++) {
plat[ii] = y[ii] * D2R;
plon[ii] = x[ii] * D2R;
if (height[ii])
pheight[ii] = z[ii];
}
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
//
// This comment block describes the general procedure for geocoding
// images stored in a SAR geometry. For map projecting or
// reprojecting other things (notably DEMs) a seperate code thread
// using a different procedure is used.
//
// We want to find natural cubic splines to form approximating
// functions X and Y st
//
// X(x, y) = input image x pixel coordinate of projection coordinates x, y
// Y(x, y) = input image y pixel coordinate of projection coordinates x, y
//
// The basic steps are:
//
// 1. Find the extent of the input image in projection coordinate
// space, i.e. the minimum and maximum x and y projection
// coordinates of all the pixels in the input image.
//
// 2. Find the pairs of input image pixel coordinates corresponding
// to the points of an evenly distributed grid in the output
// projection space.
//
// 3. Construct interpolating cubic splines for each column of points
// in the grid.
//
// 4. For each row in the output image, construct an interpolating
// spline over the values which result from evaluating the column
// splines at that y position.
//
// 5. Verify that the splines aren't introducing too much error away
// from the control points by examing the errors in the spline
// approximation compared to the results of the analytical
// transformation of a denser grid.
//
// The steps don't necessarily occer in exactly this order in the code
// though.
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// This is the form of the input data we want to fit splines to.
struct data_to_fit {
size_t grid_size; // Size of grid of points, in points on a side.
size_t n; // Number of transformed points (grid_size^2).
double *x_proj; // Projection x coordinates.
double *y_proj; // Projection y coordinates.
// Input image pixel coordinates put 0, 0 at the top left.
double *x_pix; // Input image pixel x coordinate.
double *y_pix; // Input image pixel y coordinate.
// These values are like the above ones, and should form a grid
// covering the same area, but are considerably more sparse.
size_t sparse_grid_size;
size_t sparse_n;
double *sparse_x_proj;
double *sparse_y_proj;
double *sparse_x_pix;
double *sparse_y_pix;
};
///////////////////////////////////////////////////////////////////////////////
//
// Hold your nose...
//
// These used to be function scoped statics in reverse_map_x and
// reverse_map_y routines, but that broke horribly when this program
// got converted into a library function because they never got reset
// between calls, so now these are globals so that we can reset them
// all to their initial state when we get to the end of the function.
// The little '_rmx' and '_rmy' suffixes help remind us that these
// globals go with the reverse_map_x and reverse_map_y routines,
// repsectively.
// True iff this is our first time through this routine.
static gboolean first_time_through_rmx = TRUE;
// Accelerators and interpolators for the all the vertical columns
// of sample points. Filled in first time through routine.
static gsl_interp_accel **y_accel_rmx;
static gsl_spline **y_spline_rmx;
// Current accelerator and interpolator. Updated when y argument is
// different between calls.
static gsl_interp_accel *crnt_accel_rmx;
static gsl_spline *crnt_rmx;
// Value of y for which current interpolator works.
static double last_y_rmx;
// True iff this is our first time through this routine.
static gboolean first_time_through_rmy = TRUE;
// Accelerators and interpolators for the all the vertical columns
// of sample points. Filled in first time through routine.
static gsl_interp_accel **y_accel_rmy;
static gsl_spline **y_spline_rmy;
// Current accelerator and interpolator. Updated when y argument is
// different between calls.
static gsl_interp_accel *crnt_accel_rmy;
static gsl_spline *crnt_rmy;
// Value of y for which current interpolator works.
static double last_y_rmy;
///////////////////////////////////////////////////////////////////////////////
// Reverse map from projection coordinates x, y to input pixel
// coordinate X. This function looks at the data to fit on the first
// time through, in order to set up vertical splines, after which this
// argument is mostly ignored. But not entirely, so you can't free or
// change the dtf. Mapping is efficient only if the y coordinates are
// usually identical between calls, since when y changes a new spline
// between splines has to be created.
static double
reverse_map_x (struct data_to_fit *dtf, double x, double y)
{
// Convenience aliases.
size_t sgs = dtf->sparse_grid_size;
double *xprojs = dtf->sparse_x_proj;
double *yprojs = dtf->sparse_y_proj;
double *xpixs = dtf->sparse_x_pix;
if ( G_UNLIKELY (first_time_through_rmx || y != last_y_rmx) ) {
if ( !first_time_through_rmx ) {
// Free the spline from the last line.
gsl_interp_accel_free (crnt_accel_rmx);
gsl_spline_free (crnt_rmx);
} else {
// Its our first time through, so set up the splines for the
// grid point columns.
y_accel_rmx = g_new (gsl_interp_accel *, sgs);
y_spline_rmx = g_new (gsl_spline *, sgs);
size_t ii;
for ( ii = 0 ; ii < sgs ; ii++ ) {
gsl_vector *cypv = gsl_vector_alloc (sgs);
gsl_vector *cxpixv = gsl_vector_alloc (sgs);
size_t jj;
for ( jj = 0 ; jj < sgs ; jj++ ) {
gsl_vector_set (cypv, jj, yprojs[jj * sgs + ii]);
gsl_vector_set (cxpixv, jj, xpixs[jj * sgs + ii]);
}
y_accel_rmx[ii] = gsl_interp_accel_alloc ();
y_spline_rmx[ii] = gsl_spline_alloc (gsl_interp_cspline, sgs);
gsl_spline_init (y_spline_rmx[ii], cypv->data, cxpixv->data, sgs);
gsl_vector_free (cxpixv);
gsl_vector_free (cypv);
}
first_time_through_rmx = FALSE;
}
// Set up the spline that runs horizontally, between the column
// splines.
crnt_accel_rmx = gsl_interp_accel_alloc ();
crnt_rmx = gsl_spline_alloc (gsl_interp_cspline, sgs);
double *crnt_points = g_new (double, sgs);
size_t ii;
for ( ii = 0 ; ii < sgs ; ii++ ) {
crnt_points[ii] = gsl_spline_eval (y_spline_rmx[ii], y, y_accel_rmx[ii]);
}
gsl_spline_init (crnt_rmx, xprojs, crnt_points, sgs);
g_free (crnt_points);
last_y_rmx = y;
}
return gsl_spline_eval (crnt_rmx, x, crnt_accel_rmx);
}
// This routine is analagous to reverse_map_x, including the same
// caveats and confusing behavior.
static double
reverse_map_y (struct data_to_fit *dtf, double x, double y)
{
size_t sgs = dtf->sparse_grid_size;
double *xprojs = dtf->sparse_x_proj;
double *yprojs = dtf->sparse_y_proj;
double *ypixs = dtf->sparse_y_pix;
if ( G_UNLIKELY (first_time_through_rmy || y != last_y_rmy) ) {
if ( !first_time_through_rmy ) {
// Free the spline from the last line.
gsl_interp_accel_free (crnt_accel_rmy);
gsl_spline_free (crnt_rmy);
} else {
// Its our first time through, so set up the splines for the
// grid point columns.
y_accel_rmy = g_new (gsl_interp_accel *, sgs);
y_spline_rmy = g_new (gsl_spline *, sgs);
size_t ii;
for ( ii = 0 ; ii < sgs ; ii++ ) {
// Current y projection value.
gsl_vector *cypv = gsl_vector_alloc (sgs);
// Current y pixel value.
gsl_vector *cypixv = gsl_vector_alloc (sgs);
size_t jj;
for ( jj = 0 ; jj < sgs ; jj++ ) {
gsl_vector_set (cypv, jj, yprojs[jj * sgs + ii]);
gsl_vector_set (cypixv, jj, ypixs[jj * sgs + ii]);
}
y_accel_rmy[ii] = gsl_interp_accel_alloc ();
y_spline_rmy[ii] = gsl_spline_alloc (gsl_interp_cspline, sgs);
gsl_spline_init (y_spline_rmy[ii], cypv->data, cypixv->data, sgs);
gsl_vector_free (cypixv);
gsl_vector_free (cypv);
}
first_time_through_rmy = FALSE;
}
// Set up the spline that runs horizontally, between the column
// splines.
crnt_accel_rmy = gsl_interp_accel_alloc ();
crnt_rmy = gsl_spline_alloc (gsl_interp_cspline, sgs);
double *crnt_points = g_new (double, sgs);
size_t ii;
for ( ii = 0 ; ii < sgs ; ii++ ) {
crnt_points[ii] = gsl_spline_eval (y_spline_rmy[ii], y, y_accel_rmy[ii]);
}
gsl_spline_init (crnt_rmy, xprojs, crnt_points, sgs);
g_free (crnt_points);
last_y_rmy = y;
}
return gsl_spline_eval (crnt_rmy, x, crnt_accel_rmy);
}
static void determine_projection_fns(int projection_type, project_t **project,
project_arr_t **project_arr, unproject_t **unproject,
unproject_arr_t **unproject_arr)
{
switch ( projection_type ) {
case UNIVERSAL_TRANSVERSE_MERCATOR:
if (project) *project = project_utm;
if (project_arr) *project_arr = project_utm_arr;
if (unproject) *unproject = project_utm_inv;
if (unproject_arr) *unproject_arr = project_utm_arr_inv;
break;
case POLAR_STEREOGRAPHIC:
if (project) *project = project_ps;
if (project_arr) *project_arr = project_ps_arr;
if (unproject) *unproject = project_ps_inv;
if (unproject_arr) *unproject_arr = project_ps_arr_inv;
break;
case ALBERS_EQUAL_AREA:
if (project) *project = project_albers;
if (project_arr) *project_arr = project_albers_arr;
if (unproject) *unproject = project_albers_inv;
if (unproject_arr) *unproject_arr = project_albers_arr_inv;
break;
case LAMBERT_CONFORMAL_CONIC:
if (project) *project = project_lamcc;
if (project_arr) *project_arr = project_lamcc_arr;
if (unproject) *unproject = project_lamcc_inv;
if (unproject_arr) *unproject_arr = project_lamcc_arr_inv;
break;
case LAMBERT_AZIMUTHAL_EQUAL_AREA:
if (project) *project = project_lamaz;
if (project_arr) *project_arr = project_lamaz_arr;
if (unproject) *unproject = project_lamaz_inv;
if (unproject_arr) *unproject_arr = project_lamaz_arr_inv;
break;
case LAT_LONG_PSEUDO_PROJECTION:
if (project) *project = project_lat_long_pseudo;
if (project_arr) *project_arr = NULL; // shouldn't need this
// if (project_arr) *project_arr = project_lat_long_pseudo_arr;
if (unproject) *unproject = project_lat_long_pseudo_inv;
if (unproject_arr) *unproject_arr = NULL; // or this
// if (unproject_arr) *unproject_arr = project_lat_long_pseudo_inv_arr;
break;
case EQUI_RECTANGULAR:
if (project) *project = project_eqr;
if (project_arr) *project_arr = project_eqr_arr;
if (unproject) *unproject = project_eqr_inv;
if (unproject_arr) *unproject_arr = project_eqr_arr_inv;
break;
case EQUIDISTANT:
if (project) *project = project_eqc;
if (project_arr) *project_arr = project_eqc_arr;
if (unproject) *unproject = project_eqc_inv;
if (unproject_arr) *unproject_arr = project_eqc_arr_inv;
break;
case MERCATOR:
if (project) *project = project_mer;
if (project_arr) *project_arr = project_mer_arr;
if (unproject) *unproject = project_mer_inv;
if (unproject_arr) *unproject_arr = project_mer_arr_inv;
break;
case SINUSOIDAL:
if (project) *project = project_sin;
if (project_arr) *project_arr = project_sin_arr;
if (unproject) *unproject = project_sin_inv;
if (unproject_arr) *unproject_arr = project_sin_arr_inv;
break;
default:
g_assert_not_reached ();
if (project) *project = NULL;
if (project_arr) *project_arr = NULL;
if (unproject) *unproject = NULL;
if (unproject_arr) *unproject_arr = NULL;
break;
}
}
// USGS seamless DEMs use < -900 to indicate "invalid" ...
// How can we generalize this?
static int usgs_invalid(float x) { return x < -900; }
// Similar to float_image_sample, except knows about invalid data
// in DEMs -- returns invalid data if any of the pixels used for
// interpolation is invalid.
static float dem_sample(FloatImage *dem, float x, float y,
float_image_sample_method_t sample_method)
{
switch (sample_method) {
case FLOAT_IMAGE_SAMPLE_METHOD_NEAREST_NEIGHBOR:
return float_image_sample(dem, x, y, sample_method);
case FLOAT_IMAGE_SAMPLE_METHOD_BILINEAR:
{
// b = "below", a = "above"
int xb = floor(x), yb = floor(y), xa = ceil(x), ya = ceil(y);
float ul = float_image_get_pixel(dem, xb, yb);
if (usgs_invalid(ul)) return ul;
float ur = float_image_get_pixel(dem, xa, yb);
if (usgs_invalid(ur)) return ur;
float ll = float_image_get_pixel(dem, xb, ya);
if (usgs_invalid(ll)) return ll;
float lr = float_image_get_pixel(dem, xa, ya);
if (usgs_invalid(lr)) return lr;
float ux = ul + (ur-ul) * (x-xb);
float lx = ll + (lr-ll) * (x-xb);
return ux + (lx-ux) * (y-yb);
}
case FLOAT_IMAGE_SAMPLE_METHOD_BICUBIC:
{
int i, j;
int xi = floor(x), yi = floor(y);
int minx = xi-1;
int miny = yi-1;
int maxx = xi+2;
int maxy = yi+2;
if (minx<0) minx=0;
if (miny<0) miny=0;
if (maxx>=(int)dem->size_x) maxx = dem->size_x-1;
if (maxy>=(int)dem->size_y) maxy = dem->size_y-1;
for (i=minx; i<=maxx; ++i)
for (j=miny; j<=maxy; ++j) {
float v = float_image_get_pixel(dem, i, j);
if (usgs_invalid(v)) return v;
}
return float_image_sample(dem, x, y, sample_method);
}
default:
asfPrintError("Invalid sampling method in dem_sample!\n");
}
return 0; // not reached
}
int asf_geocode_utm(resample_method_t resample_method, double average_height,
datum_type_t datum, double pixel_size,
char *band_id, char *in_base_name, char *out_base_name,
float background_val)
{
project_parameters_t pp;
projection_type_t projection_type = UNIVERSAL_TRANSVERSE_MERCATOR;
// force calculation of these values
pp.utm.zone = MAGIC_UNSET_INT;
pp.utm.lon0 = MAGIC_UNSET_DOUBLE;
pp.utm.lat0 = MAGIC_UNSET_DOUBLE;
return asf_geocode(&pp, projection_type, FALSE, resample_method,
average_height, datum, pixel_size, band_id,
in_base_name, out_base_name, background_val, FALSE);
}
int asf_geocode_from_proj_file(const char *projection_file,
int force_flag, resample_method_t resample_method,
double average_height, datum_type_t datum, double pixel_size,
char *band_id, char *in_base_name, char *out_base_name,
float background_val)
{
project_parameters_t pp;
projection_type_t projection_type;
datum_type_t tmp_datum = datum;
spheroid_type_t spheroid;
double sphere;
char *err=NULL;
if (!parse_proj_args_file(projection_file, &pp, &projection_type, &datum,
&spheroid, &err)) {
asfPrintError("%s",err);
}
/*
if (tmp_datum != UNKNOWN_DATUM &&
datum != tmp_datum)
{
asfPrintWarning(
"The datum read from the MapReady configuration file differs from\n"
"the datum read from the projection description file. The datum\n"
"given in the projection file will override that of the configuration\n"
"file (%s overrides %s).\n",
datum_toString(datum), datum_toString(tmp_datum));
}
*/
return asf_geocode(&pp, projection_type, force_flag, resample_method,
average_height, datum, pixel_size, band_id,
in_base_name, out_base_name, background_val, FALSE);
}
int asf_geocode(project_parameters_t *pp, projection_type_t projection_type,
int force_flag, resample_method_t resample_method,
double average_height, datum_type_t datum, double pixel_size,
char *band_id, char *in_base_name, char *out_base_name,
float background_val, int save_map_flag)
{
char *input_meta_data;
char *bands; // A string containing list of available band_id's
int ret;
int multiband = 1; // boolean - true means geocode all available bands, false means one band
int band_count;
int band_num = 0;
input_meta_data = appendExt(in_base_name, "meta");
meta_parameters *imd = meta_read(input_meta_data);
bands = STRDUP(imd->general->bands);
band_count = imd->general->band_count;
if (band_count > MAX_BANDS) {
asfPrintWarning("Data contains too many bands (%d)\n"
"asf_geocode cannot geocode more than %d bands\n",
band_count, MAX_BANDS);
}
if (band_count <= 0) {
asfPrintError("Invalid band_count in metadata (%d bands)\n", band_count);
}
// If the band_id is NULL, is empty, or is equal to 'all'
// then geocode all available bands, else geocode the selected
// band
//if (band_id) band_num = get_band_number(bands, band_count, band_id);
if (band_id == NULL ||
(band_id && (strlen(band_id) == 0)) ||
(band_id && strcmp(uc(band_id), "ALL") == 0)
) {
// Geocode all available bands
multiband = 1;
ret = asf_geocode_ext(pp, projection_type, force_flag, resample_method,
average_height, datum, pixel_size,
multiband, band_num, in_base_name,
out_base_name, background_val, save_map_flag);
if (ret != 0)
{
char **band_names = extract_band_names(imd->general->bands,
imd->general->band_count);
asfPrintError("Failed to geocode band %s\n", band_names[band_num]);
}
}
else {
// Geocode a single selected band
multiband = 0;
band_num = get_band_number(bands, band_count, band_id);
asfRequire(band_num >= 0 && band_num < MAX_BANDS,
"Selected band number out of range\n");
ret = asf_geocode_ext(pp, projection_type, force_flag, resample_method,
average_height, datum, pixel_size,
multiband, band_num, in_base_name,
out_base_name, background_val, save_map_flag);
asfRequire(ret == 0,
"Failed to geocode band number 01\n");
}
meta_free(imd);
FREE(bands);
return ret;
}
int asf_geocode_ext(project_parameters_t *pp, projection_type_t projection_type,
int force_flag, resample_method_t resample_method,
double average_height, datum_type_t datum, double pixel_size,
int multiband, int band_num, char *in_base_name,
char *out_base_name, float background_val,
int save_line_sample_mapping)
{
char *in_base_names[2];
in_base_names[0] = MALLOC(sizeof(char)*(strlen(in_base_name)+1));
strcpy(in_base_names[0], in_base_name);
in_base_names[1] = NULL;
double lat_min = -999, lon_min = -999;
double lat_max = 999, lon_max = 999;
char *overlap;
overlap = MALLOC(sizeof(char)*25);
strcpy(overlap, "OVERLAY");
return asf_mosaic(pp, projection_type, force_flag, resample_method,
average_height, datum, UNKNOWN_SPHEROID, pixel_size,
multiband, band_num, in_base_names, out_base_name,
background_val, lat_min, lat_max, lon_min, lon_max,
overlap, save_line_sample_mapping);
}
static int symmetry_test(meta_parameters *imd, double stpx, double stpy,
double average_height)
{
int ok = TRUE;
int ret1, ret2;
double st_lat, st_lon; // Symmetry test lat and long values.
ret1 = meta_get_latLon (imd, stpy, stpx, average_height,
&st_lat, &st_lon);
double strx, stry; // Symmetry test result values.
ret2 = meta_get_lineSamp (imd, st_lat, st_lon, average_height,
&stry, &strx);
// We will insist that the results are symmetric to within this
// fraction after transforming out and back.
const double sym_th = 0.15; // Symmetry threshold (pixels)
if (ret1 || ret2) {
asfPrintWarning("Symmetry test failed! %s %s.\n",
ret1 ? "meta_get_latLon returned error" : "",
ret2 ? "meta_get_lineSamp returned error" : "");
ok = FALSE;
}
if (!(fabs (strx - stpx) < sym_th && fabs (stry - stpy) < sym_th)) {
asfPrintWarning("Failed symmetry test: x- |%.5f-%.5f| = %.5f\n"
" y- |%.5f-%.5f| = %.5f (tol=%.2f)\n",
strx,stpx,fabs(strx-stpx),stry,stpy,fabs(stry-stpy),sym_th);
// Abort if the error is "horrible" (more than a pixel)
if (fabs (strx-stpx) > 10*sym_th || fabs (stry-stpy) > 10*sym_th) {
asfPrintWarning("Symmetry testing error too large!\n");
}
ok = FALSE;
}
else {
//asfPrintStatus("Point %f,%f --> symmetry test passed.\n",stpx,stpy);
}
return ok;
}
int asf_mosaic(project_parameters_t *pp, projection_type_t projection_type,
int force_flag, resample_method_t resample_method,
double average_height, datum_type_t datum,
spheroid_type_t spheroid, double pixel_size,
int multiband, int band_num, char **in_base_names,
char *out_base_name, float background_val, double lat_min,
double lat_max, double lon_min, double lon_max,
char *overlap_method, int save_line_sample_mapping)
{
int i,ret;
int process_as_byte=TRUE;
unsigned long out_of_range_negative = 0;
unsigned long out_of_range_positive = 0;
overlap_method_t overlap=OVERLAY_OVERLAP;
double pixel_size_x, pixel_size_y;
// FIXME: function needs to be extended to handle resampling of already
// geocoded data.
if (strcmp(uc(overlap_method), "MINIMUM") == 0) {
overlap = MIN_OVERLAP;
}
else if (strcmp(uc(overlap_method), "MAXIMUM") == 0) {
overlap = MAX_OVERLAP;
}
else if (strcmp(uc(overlap_method), "AVERAGE") == 0) {
//overlap = AVG_OVERLAP;
overlap = OVERLAY_OVERLAP;
asfPrintWarning("Overlap method 'AVERAGE' not yet implemented. Defaulting\n"
"to OVERLAY and continuing...\n");
}
else if (strcmp(uc(overlap_method), "NEAR RANGE") == 0) {
//overlap = NEAR_RANGE_OVERLAP;
overlap = OVERLAY_OVERLAP;
asfPrintWarning("Overlap method 'NEAR RANGE' not yet implemented. Defaulting\n"
"to OVERLAY and continuing...\n");
}
else if (strcmp(uc(overlap_method), "OVERLAY") == 0) {
overlap = OVERLAY_OVERLAP;
}
else {
asfPrintError("Overlap method '%s' not supported!\n", overlap_method);
}
// ref_input is which of the input images is the "reference" -- i.e.,
// which will be used as the template for the output metadata. This
// is decided based on which input has the most bands, since the
// output will have that many bands, too. n_bands is how many bands
// are in that reference input file.
int ref_input=0;
int n_bands=1;
meta_parameters *meta = meta_read(in_base_names[0]);
// Spit out a warning about products that have not been validated against ground
// control points
/*
if (!strstr(mg->processor, "JAXA") && !strstr(mg->processor, "ASF")) {
asfPrintStatus("\n\nNOTE: Non-ASF processed data detected. Products not processed\n"
"at the Alaska Satellite Facility may not have been fully validated\n"
"geographically against ground control points. If, after geocoding,\n"
"your results are not quite accurate geograhically, you may consider\n"
"correcting the geolocation using one of the following methods:\n\n"
"1. Obtain an appropriate DEM and reprocess the data, but this time\n"
" select terrain correction and check the \"Refine Geolocation Only\"\n"
" radio button on the Terrain Correction tab. Doing so will result\n"
" in a geographically accurate result that has NOT had terrain correction\n"
" applied to it. Of course, if you choose to apply terrain correction\n"
" by not checking this radio button, the geographic location will also\n"
" be corrected.\n"
"2. Use the asf_terrcorr command-line to do the same thing as described in 1.\n"
" above. See asf_terrcorr -help for more info.\n"
"3. If you know the necessary geographic location correction, use the\n"
" shift_geolocation command line tool to shift the scene to the correct\n"
" location.\n"
"4. If all else fails, you may try applying a height correction by checking\n"
" the \"Specify Height\" checkbox on the Geocode tab and entering a terrain\n"
" elevation (usually for the most important area of interest in the scene).\n"
" You may do the same thing with the asf_geocode command line utility. See\n"
" asf_geocode -help for more info.\n"
"5. Export your data to GeoTIFF format after geocoding then make the correction\n"
" in your favorite GIS software, making sure you choose to convert the data\n"
" to byte format on the Export tab if your GIS software is unable to view/use\n"
" floating point data or cannot re-map to byte values on the fly.\n\n");
}
*/
void (*report_func) (const char *format, ...);
report_func = force_flag ? asfPrintWarning : asfPrintError;
// Assign output filename
char *output_image = appendExt(out_base_name, "img");
char *output_meta_data = appendExt(output_image, "meta");
// Determine number of input images
int n_input_images = 0;
{
char **p = in_base_names;
while (*p++) ++n_input_images;
}
if (n_input_images == 0) {
asfPrintError("Geocode: no input images specified!\n");
}
else if (n_input_images == 1) {
if (!meta->projection)
asfPrintStatus("Geocoding %s\n", in_base_names[0]);
else if (meta->projection &&
(meta->projection->type == SCANSAR_PROJECTION ||
meta->projection->type == LAT_LONG_PSEUDO_PROJECTION))
asfPrintStatus("Geocoding %s\n", in_base_names[0]);
else
asfPrintStatus("Resampling %s\n", in_base_names[0]);
} else {
asfPrintStatus("Mosaicking %d images:\n", n_input_images);
for (i=0; i<n_input_images; ++i)
asfPrintStatus(" #%d: %s\n", i+1, in_base_names[i]);
asfPrintStatus("\nOverlapping method: %s\n\n", overlap_method);
if (meta->projection && meta->projection->type == SCANSAR_PROJECTION) {
asfPrintWarning("Mosaicking of ScanSAR along track / cross-track images is\n"
"untested. Results may vary.\n");
}
}
meta_free(meta);
// keep track of the input metadata's spheroids. For projected data,
// if they all match, then we'll go ahead and use it in the output.
spheroid_type_t *input_spheroid = NULL;
//------------------------------------------------------------------------
// Now working on determining the output file's extents
// Assign our transformation function pointers to point to the
// appropriate functions.
project_t *project;
project_arr_t *project_arr;
unproject_t *unproject;
unproject_arr_t *unproject_arr;
determine_projection_fns(projection_type, &project, &project_arr,
&unproject, &unproject_arr);
// these will hold the extents of the output image in projection
// coordinates
double min_x = DBL_MAX;
double max_x = -DBL_MAX;
double min_y = DBL_MAX;
double max_y = -DBL_MAX;
asfPrintStatus ("Determining input image extents in projection coordinate "
"space... \n");
// Loop over the input images to determine output extent
for (i=0; i<n_input_images; ++i)
{
double height_correction = 0;
char *in_base_name = STRDUP(in_base_names[i]);
if (n_input_images > 1)
asfPrintStatus("Working on input image #%d: %s\n", i+1, in_base_name);
// strip off known extensions
char *ext = findExt(in_base_name);
if (ext) *ext = '\0';
char *input_meta_data = appendExt (in_base_name, "meta");
// Input metadata.
meta_parameters *imd = meta_read (input_meta_data);
if (imd->general->data_type > REAL64) {
asfPrintError("Geocoding of complex data not supported.\n");
}
if (imd->optical) {
if (strcmp(imd->general->mode, "1A") == 0 ||
strcmp(imd->general->mode, "1B1") == 0) {
asfPrintError("Geocoding %s level %s data is not supported.\n",
imd->general->sensor_name, imd->general->mode);
}
}
// The number of bands in the output will be equal to the largest
// number of bands in all of the inputs. Any inputs that "run out"
// of bands will just be ignored when generating that particular
// band in the output image. NOTE: We still want to do this even if the
// user has used the "-band" option to actually process only one band.
if (imd->general->band_count > n_bands) {
n_bands = imd->general->band_count;
ref_input = i;
}
// If we have an already projected image as input, we will need to
// be able to unproject its coordinates back to lat long before we
// can reproject them into the desired projection, so here we select
// a function that can do that.
// Flag true iff input image not map projected or pseudoprojected.
gboolean input_projected = FALSE;
// Convenience alias (valid iff input_projected).
meta_projection *ipb = imd->projection;
project_parameters_t *ipp = (ipb) ? &imd->projection->param : NULL;
project_t *project_input;
unproject_t *unproject_input;
if ( ((imd->sar && imd->sar->image_type == 'P') || imd->general->image_data_type == DEM)
&& imd->projection && imd->projection->type != SCANSAR_PROJECTION )
{
input_projected = TRUE;
determine_projection_fns(imd->projection->type, &project_input, NULL,
&unproject_input, NULL);
}
// first time through, set up the defaults for the projection -- e.g, any
// scene-related defaults are applied.
if (i==0) {
apply_defaults (projection_type, pp, imd, &average_height, &pixel_size);
check_parameters (projection_type, datum, pp, imd, force_flag);
}
// If a pixel size is defined, we assume the user wants square pixels
if (pixel_size > 0)
pixel_size_x = pixel_size_y = pixel_size;
// Don't allow height correction to be applied to ALOS Prism or Avnir
if (average_height != 0.0 && (is_alos_prism(imd) || is_alos_avnir(imd))) {
asfPrintWarning("Specified height correction of %gm will be ignored for "
"ALOS Prism/Avnir data.\n", average_height);
average_height = 0.0;
}
if (average_height != 0.0)
asfPrintStatus("Height correction: %fm.\n", average_height);
// Old Scansar data needs a 400m height adjustment.
if (imd->sar && imd->sar->image_type == 'P' &&
imd->projection && imd->projection->type == SCANSAR_PROJECTION &&
strncmp(imd->general->processor, "ASF", 3) == 0) {
asfPrintStatus("Will apply 400m height correction for SCANSAR data.\n");
average_height -= 400;
height_correction = 400;
}
project_set_avg_height (average_height);
// Input image dimensions in pixels in x and y directions.
size_t ii_size_x = imd->general->sample_count;
size_t ii_size_y = imd->general->line_count;
// The latitude and longitude of the center of the image.
double lat_0, lon_0;
ret = meta_get_latLon (imd, ii_size_y / 2.0, ii_size_x / 2.0, average_height,
&lat_0, &lon_0);
// If the user's selected datum is NAD27 -- test it out to make sure we
// have the capability of using it. If we don't we'll fall back to WGS84.
// This is because the NAD27 transformations depend on grid shift files
// that are not available for all parts of the world (specifically, outside
// of North America).
if (datum == NAD27_DATUM) {
int ok = test_nad27(lat_0, lon_0);
double lat, lon;
if (ok) {
meta_get_latLon (imd, 0, 0, average_height, &lat, &lon);
ok = test_nad27(lat, lon);
meta_get_latLon (imd, ii_size_y, 0, average_height, &lat, &lon);
ok |= test_nad27(lat, lon);
meta_get_latLon (imd, 0, ii_size_x, average_height, &lat, &lon);
ok |= test_nad27(lat, lon);
meta_get_latLon (imd, ii_size_y, ii_size_x, average_height,
&lat, &lon);
ok |= test_nad27(lat, lon);
}
if (!ok) {
if (!force_flag) {
asfPrintError("The scene is in a region of the world that "
"doesn't have NAD27 grid shift\ndata available.\n\n"
"Use the -force option (Ignore projection errors) or adjust the\n"
"selected projection parameters (use WGS84?) to something more\n"
"appropriate for this image's region.\n");
}
else {
asfPrintWarning("The scene is in a region of the world that "
"doesn't have NAD27 grid shift\ndata available. Large errors"
" may result.\n");
}
}
}
if (input_projected) {
if (i == 0) {
input_spheroid = MALLOC(sizeof(spheroid_type_t));
*input_spheroid = imd->projection->spheroid;
} else {
if (input_spheroid && *input_spheroid != imd->projection->spheroid) {
free(input_spheroid);
input_spheroid = NULL;
}
}
}
// First we march around the entire outside of the image and compute
// projection coordinates for every pixel, keeping track of the
// minimum and maximum projection coordinates in each dimension.
// This lets us determine the exact extent of the projected image in
// projection coordinates.
{ // Scoping block.
// Number of pixels in the edge of the image.
size_t edge_point_count = 2 * ii_size_x + 2 * ii_size_y - 4;
double *lats = g_new (double, edge_point_count);
double *lons = g_new (double, edge_point_count);
size_t current_edge_point = 0;
size_t ii = 0, jj = 0;
for ( ; ii < ii_size_x - 1 ; ii++ ) {
if ( input_projected ) {
double xpc = ipb->startX + ipb->perX * ii;
double ypc = ipb->startY + ipb->perY * jj;
ret = unproject_input (ipp, xpc, ypc, ASF_PROJ_NO_HEIGHT,
&(lats[current_edge_point]),
&(lons[current_edge_point]), NULL,
imd->projection->datum);
g_assert (ret);
}
else {
ret = meta_get_latLon (imd, (double)jj, (double)ii, average_height,
&(lats[current_edge_point]),
&(lons[current_edge_point]));
//g_assert (ret == 0);
asfRequire(ret == 0, "Unable to determine latitude and longitude "
"from current edge point\n");
lats[current_edge_point] *= D2R;
lons[current_edge_point] *= D2R;
}
current_edge_point++;
asfPercentMeter((float)current_edge_point / (float)edge_point_count);
}
for ( ; jj < ii_size_y - 1 ; jj++ ) {
if ( input_projected ) {
double xpc = ipb->startX + ipb->perX * ii;
double ypc = ipb->startY + ipb->perY * jj;
ret = unproject_input (ipp, xpc, ypc, ASF_PROJ_NO_HEIGHT,
&(lats[current_edge_point]),
&(lons[current_edge_point]), NULL,
imd->projection->datum);
g_assert (ret);
}
else {
ret = meta_get_latLon (imd, (double)jj, (double)ii, average_height,
&(lats[current_edge_point]),
&(lons[current_edge_point]));
g_assert (ret == 0);
lats[current_edge_point] *= D2R;
lons[current_edge_point] *= D2R;
}
current_edge_point++;
asfPercentMeter((float)current_edge_point / (float)edge_point_count);
}
for ( ; ii > 0 ; ii-- ) {
if ( input_projected ) {
double xpc = ipb->startX + ipb->perX * ii;
double ypc = ipb->startY + ipb->perY * jj;
ret = unproject_input (ipp, xpc, ypc, ASF_PROJ_NO_HEIGHT,
&(lats[current_edge_point]),
&(lons[current_edge_point]), NULL,
imd->projection->datum);
g_assert (ret);
}
else {
ret = meta_get_latLon (imd, (double)jj, (double)ii, average_height,
&(lats[current_edge_point]),
&(lons[current_edge_point]));
g_assert (ret == 0);
lats[current_edge_point] *= D2R;
lons[current_edge_point] *= D2R;
}
current_edge_point++;
asfPercentMeter((float)current_edge_point / (float)edge_point_count);
}
for ( ; jj > 0 ; jj-- ) {
if ( input_projected ) {
double xpc = ipb->startX + ipb->perX * ii;
double ypc = ipb->startY + ipb->perY * jj;
ret = unproject_input (ipp, xpc, ypc, ASF_PROJ_NO_HEIGHT,
&(lats[current_edge_point]),
&(lons[current_edge_point]), NULL,
imd->projection->datum);
g_assert (ret);
}
else {
ret = meta_get_latLon (imd, (double)jj, (double)ii, average_height,
&(lats[current_edge_point]),
&(lons[current_edge_point]));
g_assert (ret == 0);
lats[current_edge_point] *= D2R;
lons[current_edge_point] *= D2R;
}
current_edge_point++;
asfPercentMeter((float)current_edge_point / (float)edge_point_count);
}
g_assert (current_edge_point == edge_point_count);
if (!input_projected && projection_type != LAT_LONG_PSEUDO_PROJECTION) {
// Pointers to arrays of projected coordinates to be filled in.
// The projection function will allocate this memory itself.
double *x = NULL, *y = NULL;
x = y = NULL;
// Project all the edge pixels.
ret = project_arr (pp, lats, lons, NULL, &x, &y, NULL,
edge_point_count, datum);
if (!ret) {
asfPrintError("Non-forceable projection library error occurred. Using\n"
"the -force or \"Ignore projection errors\" checkbox or \n"
"\"force = 1\" in a MapReady configuration file will\n"
"not work with the current settings and geographical area.\n");
}
// Find the extents of the image in projection coordinates.
for ( ii = 0 ; ii < edge_point_count ; ii++ ) {
if ( x[ii] < min_x ) { min_x = x[ii]; }
if ( x[ii] > max_x ) { max_x = x[ii]; }
if ( y[ii] < min_y ) { min_y = y[ii]; }
if ( y[ii] > max_y ) { max_y = y[ii]; }
}
free (y);
free (x);
}
else {
for (ii=0; ii<edge_point_count; ii++) {
lats[ii] *= R2D;
lons[ii] *= R2D;
}
for (ii=0; ii<edge_point_count; ii++) {
if (meta_is_valid_double(lons[ii]) && lons[ii] < min_x)
min_x = lons[ii];
if (meta_is_valid_double(lons[ii]) && lons[ii] > max_x)
max_x = lons[ii];
if (meta_is_valid_double(lats[ii]) && lats[ii] < min_y)
min_y = lats[ii];
if (meta_is_valid_double(lats[ii]) && lats[ii] > max_y)
max_y = lats[ii];
}
}
g_free (lons);
g_free (lats);
}
// If the input pixel size is -1, that means the user didn't specify one.
// So, we will use the FIRST input file's pixel size. The second (and
// later) times through this loop, the pixel_size will already have been
// set to the first file's pixel size, and so we'll never go into this
// if() block when i>0.
// We still assume square pixels for non-projected data
if (pixel_size < 0 && !input_projected)
{
g_assert(i==0);
pixel_size_x = pixel_size_y =
MAX(imd->general->x_pixel_size, imd->general->y_pixel_size);
asfPrintStatus("No pixel size specified.\n"
"Defaulting to larger of range or azimuth pixel size "
"from %smetadata: %f (%s pixel size)\n",
n_input_images > 1 ? "the first image's " : "",
pixel_size_x,
imd->general->x_pixel_size > imd->general->y_pixel_size ? "range" : "azimuth");
}
else if (pixel_size < 0) {
// This covers the odd cases of projected data such as UAVSAR GRD data
// that happens to have non-square pixels in the first place. We need
// to preserve the settings in this case.
pixel_size_x = imd->general->x_pixel_size;
pixel_size_y = imd->general->y_pixel_size;
}
// If all input metadata is byte, we will store everything as bytes,
// in order to save memory. (But the math will use floating point.)
if (imd->general->data_type != BYTE || resample_method == RESAMPLE_BICUBIC)
process_as_byte = FALSE;
if (imd->general->data_type == BYTE && resample_method == RESAMPLE_BICUBIC) {
asfPrintWarning(
"Using the BICUBIC resampling method for geocoding BYTE (typically optical)\n"
"data may result in out-of-range values, e.g. less than 0 or higher than 255.\n"
"Out-of-range values will be set to the closest in-range value, e.g. negative\n"
"resampled pixel values will be set to 0 (zero) and resampled pixel values that\n"
"turn out greater than 255 will be set to 255.\n"
"RECOMMENDATION: Select a different resampling method for geocoding.\n");
}
// In case of geographic information that is provided by lat/lon bands,
// the boundary needs to be extracted from the location block
if (imd->latlon)
location_minmax(imd->location, &min_y, &max_y, &min_x, &max_x);
// done with this image's metadata
meta_free(imd);
free(input_meta_data);
free(in_base_name);
// reset average_height (don't want to apply scansar correction twice,
// if we're mosaicking two scansars)
average_height += height_correction;
}
asfPrintStatus("Done.\n\nProcessing this data as: %s\n",
process_as_byte ? "BYTE" : "REAL32");
if (n_bands > 1)
asfPrintStatus("Number of bands in the output: %d\n",
multiband ? n_bands : 1);
// now apply the input lat/lon "bounding box" restriction to the
// calculated extents. Do this by converting the 4 corner points of
// the lat/lon box.
{
double x, y, z;
double bb_min_x=99999999, bb_max_x=0;
double bb_min_y=99999999, bb_max_y=0;
// this time, we update the min if we're GREATER, max if we're SMALLER
if (lat_min >= -90 && lon_min >= -180) {
project (pp, lat_min*D2R, lon_min*D2R, average_height,
&x, &y, &z, datum);
if (x < bb_min_x) bb_min_x = x; if (x > bb_max_x) bb_max_x = x;
if (y < bb_min_y) bb_min_y = y; if (y > bb_max_y) bb_max_y = y;
}
if (lat_min >= -90 && lon_max <= 180) {
project (pp, lat_min*D2R, lon_max*D2R, average_height,
&x, &y, &z, datum);
if (x < bb_min_x) bb_min_x = x; if (x > bb_max_x) bb_max_x = x;
if (y < bb_min_y) bb_min_y = y; if (y > bb_max_y) bb_max_y = y;
}
if (lat_max <= 90 && lon_min >= -180) {
project (pp, lat_max*D2R, lon_min*D2R, average_height,
&x, &y, &z, datum);
if (x < bb_min_x) bb_min_x = x; if (x > bb_max_x) bb_max_x = x;
if (y < bb_min_y) bb_min_y = y; if (y > bb_max_y) bb_max_y = y;
}
if (lat_max <= 90 && lon_max <= 180) {
project (pp, lat_max*D2R, lon_max*D2R, average_height,
&x, &y, &z, datum);
if (x < bb_min_x) bb_min_x = x; if (x > bb_max_x) bb_max_x = x;
if (y < bb_min_y) bb_min_y = y; if (y > bb_max_y) bb_max_y = y;
}
if (bb_min_x != 99999999 && bb_min_x > min_x) min_x = bb_min_x;
if (bb_max_x != 0 && bb_max_x < max_x) max_x = bb_max_x;
if (bb_min_y != 99999999 && bb_min_y > min_y) min_y = bb_min_y;
if (bb_max_y != 0 && bb_max_y < max_y) max_y = bb_max_y;
}
// Projection coordinates per pixel in output image. There is a
// significant assumption being made here: we assume that the
// projection coordinates (which are in meters) come at least
// reasonably close to the ground distances. This way, when we set
// the projection coordinates per pixel in the output image equal to
// the pixel size of the input image, we should be resampling at
// close to one-to-one (which is where resampling works and we don't
// have to worry about pixel averaging or anything).
if (projection_type == LAT_LONG_PSEUDO_PROJECTION) {
// Conversion in decimal degrees - 30 m = 1 arcsec
pixel_size_x /= 108000.0;
pixel_size_y /= 108000.0;
}
double pc_per_x = pixel_size_x;
double pc_per_y = pixel_size_y;
// Maximum pixel indicies in output image.
size_t oix_max = ceil ((max_x - min_x) / pc_per_x);
size_t oiy_max = ceil ((max_y - min_y) / pc_per_y);
// Lat/Lon of the center of the output image
double output_lat_0, output_lon_0, z;
double center_x = min_x + (max_x - min_x)/2, center_y = min_y + (max_y-min_y)/2;
unproject(pp, center_x, center_y, average_height, &output_lat_0,
&output_lon_0, &z, datum);
asfPrintStatus("Output Image Information:\n");
asfPrintStatus("Size: %dx%d LxS\n", oiy_max+1, oix_max+1);
asfPrintStatus("Center: X,Y: %.1f,%.1f Lat,Lon: %.4f,%.4f\n",
center_x, center_y, output_lat_0*R2D, output_lon_0*R2D);
if (projection_type == LAT_LONG_PSEUDO_PROJECTION) {
if (FLOAT_EQUIVALENT(pixel_size_x, pixel_size_y))
asfPrintStatus("Pixel size: %.6f degrees\n", pixel_size_x);
else {
asfPrintStatus("Pixel size x: %.6f degrees\n", pixel_size_x);
asfPrintStatus("Pixel size y: %.6f degrees\n", pixel_size_y);
}
}
else {
if (FLOAT_EQUIVALENT(pixel_size_x, pixel_size_y))
asfPrintStatus("Pixel size: %.2f m\n", pixel_size_x);
else {
asfPrintStatus("Pixel size x: %.2f m\n", pixel_size_x);
asfPrintStatus("Pixel size y: %.2f m\n", pixel_size_y);
}
}
if (average_height != 0.0)
asfPrintStatus("Height correction: %fm.\n", average_height);
print_proj_info(projection_type, pp, datum);
// Translate the command line notion of the resampling method into
// the lingo known by the float_image and uint8_image classes.
// The compiler is reassured with a default.
float_image_sample_method_t float_image_sample_method
= FLOAT_IMAGE_SAMPLE_METHOD_BILINEAR;
uint8_image_sample_method_t uint8_image_sample_method
= UINT8_IMAGE_SAMPLE_METHOD_BILINEAR;
switch ( resample_method ) {
case RESAMPLE_NEAREST_NEIGHBOR:
float_image_sample_method =
FLOAT_IMAGE_SAMPLE_METHOD_NEAREST_NEIGHBOR;
uint8_image_sample_method =
UINT8_IMAGE_SAMPLE_METHOD_NEAREST_NEIGHBOR;
break;
case RESAMPLE_BILINEAR:
float_image_sample_method =
FLOAT_IMAGE_SAMPLE_METHOD_BILINEAR;
uint8_image_sample_method =
UINT8_IMAGE_SAMPLE_METHOD_BILINEAR;
break;
case RESAMPLE_BICUBIC:
float_image_sample_method =
FLOAT_IMAGE_SAMPLE_METHOD_BICUBIC;
uint8_image_sample_method =
UINT8_IMAGE_SAMPLE_METHOD_BICUBIC;
break;
default:
g_assert_not_reached ();
}
//-------------------------------------------------------------------------
// Now working on generating the output metadata file
// Each band of the input image will map using the same mapping function
// (i.e., splines). Each input image will map using (presumably)
// different mapping functions. It is expensive to calculate the
// splines, so we should loop over the bands in the inner loop, and
// the images in the outer. This isn't too great, however, for the
// output -- ideally, we would generate the bands in the inner loop,
// to avoid having to store an array of float_images (for each band).
// We're stuck with the array, though. We can use the almost
// obsoleted banded_float_image class.
// However, if we just have one output image, we can skip the
// banded_float_image, and just write the final outputs directly,
// just as in the old geocode (in fact, it *is* the old geocode).
// Now we need some metadata for the output image. We will just
// start with the metadata from input image with the most bands,
// and add the geocoding parameters.
meta_parameters *omd = meta_read (in_base_names[ref_input]);
g_assert(omd->general->band_count == n_bands);
if (omd->stats != NULL) {
// Geocoding results in resampling. Consequently, the stats info
// that may have existed in the metadata is no longer accurate.
// Best to remove it now and let it get recalculated 'just in time'
// when some other later process needs it.
FREE(omd->stats);
omd->stats = NULL;
}
double y_pixel_size = omd->general->y_pixel_size;
if (omd->projection == NULL) {
omd->projection = meta_projection_init();
}
asfRequire(omd->general != NULL && omd->projection != NULL,
"Could not initialize output metadata structures.\n");
// Update no data value
if (!meta_is_valid_double(background_val)) background_val = 0;
if ((process_as_byte || omd->general->data_type==BYTE) && background_val<0)
background_val = 0;
if ((process_as_byte || omd->general->data_type==BYTE) && background_val>255)
background_val = 255;
omd->general->no_data = background_val;
omd->general->x_pixel_size = pixel_size_x;
omd->general->y_pixel_size = pixel_size_y;
omd->general->line_count = oiy_max + 1;
omd->general->sample_count = oix_max + 1;
if (omd->sar) {
omd->sar->image_type = 'P';
// It doesn't make sense to update these, we're just keeping them
// for 'historical' info ...
//double x_scale = pixel_size / omd->general->x_pixel_size;
//double y_scale = pixel_size / y_pixel_size;
//omd->sar->range_time_per_pixel *= x_scale;
//omd->sar->azimuth_time_per_pixel *= y_scale;
//omd->sar->range_doppler_coefficients[1] *= x_scale;
//omd->sar->range_doppler_coefficients[2] *= x_scale * x_scale;
//omd->sar->azimuth_doppler_coefficients[1] *= y_scale;
//omd->sar->azimuth_doppler_coefficients[2] *= y_scale * y_scale;
}
omd->general->start_line = 0;
omd->general->start_sample = 0;
omd->general->line_scaling = 1;
omd->general->sample_scaling = 1;
omd->projection->type = projection_type;
omd->projection->startX = min_x;
omd->projection->startY = max_y;
omd->projection->perX = pc_per_x;
omd->projection->perY = -pc_per_y;
omd->projection->height = average_height;
if (projection_type == LAT_LONG_PSEUDO_PROJECTION)
strcpy (omd->projection->units, "degrees");
else
strcpy (omd->projection->units, "meters");
if ( output_lat_0 > 0.0 ) {
omd->projection->hem = 'N';
}
else {
omd->projection->hem = 'S';
}
/* output the correct earth radii based on the datum that was used
to do the projection */
omd->projection->datum = datum;
if (datum == WGS84_DATUM) {
const double wgs84_semiminor_axis
= WGS84_SEMIMAJOR * (1 - (1 / WGS84_INV_FLATTENING));
omd->projection->re_major = WGS84_SEMIMAJOR;
omd->projection->re_minor = wgs84_semiminor_axis;
} else if (datum == NAD27_DATUM) {
// NAD27 datum is based on clark 1866 ellipsoid
const double nad27_semiminor_axis
= CLARKE1866_SEMIMAJOR * (1 - (1 / CLARKE1866_INV_FLATTENING));
omd->projection->re_major = CLARKE1866_SEMIMAJOR;
omd->projection->re_minor = nad27_semiminor_axis;
} else if (datum == NAD83_DATUM) {
// NAD83 datum is based on GRS80 ellipsoid
const double nad83_semiminor_axis
= GRS1980_SEMIMAJOR * (1 - (1 / GRS1980_INV_FLATTENING));
omd->projection->re_major = GRS1980_SEMIMAJOR;
omd->projection->re_minor = nad83_semiminor_axis;
} else if (datum == ITRF97_DATUM) {
// ITRF97 datum is based on WGS84 (btw)
const double itrf97_semiminor_axis
= INTERNATIONAL_TERRESTRIAL_REFERENCE_FRAME_1997_SEMIMAJOR *
(1 - (1 / INTERNATIONAL_TERRESTRIAL_REFERENCE_FRAME_1997_INV_FLATTENING));
omd->projection->re_major = INTERNATIONAL_TERRESTRIAL_REFERENCE_FRAME_1997_SEMIMAJOR;
omd->projection->re_minor = itrf97_semiminor_axis;
} else if (datum == HUGHES_DATUM) {
// Hughes datum uses the Hughes spheroid
const double hughes_semiminor_axis
= HUGHES_SEMIMAJOR * (1 - (1 / HUGHES_INV_FLATTENING));
omd->projection->re_major = HUGHES_SEMIMAJOR;
omd->projection->re_minor = hughes_semiminor_axis;
}
else if (datum == SAD69_DATUM) {
// SAD69 datum is based on GRS1967 ellipsoid
const double grs1967_semiminor_axis
= GRS1967_SEMIMAJOR * (1 - (1 / GRS1967_INV_FLATTENING));
omd->projection->re_major = GRS1967_SEMIMAJOR;
omd->projection->re_minor = grs1967_semiminor_axis;
}
else if (datum == ED50_DATUM) {
// ED50 datum is based on INTERNATIONAL1924 ellipsoid
const double international1924_semiminor_axis
= INTERNATIONAL1924_SEMIMAJOR *
(1 - (1 / INTERNATIONAL1924_INV_FLATTENING));
omd->projection->re_major = INTERNATIONAL1924_SEMIMAJOR;
omd->projection->re_minor = international1924_semiminor_axis;
}
else {
asfPrintError("Unsupported datum! %d\n", datum_toString(datum));
}
// NOTE: If we ever allow the user to provide a spheroid
// selection on the command line (asf_convert, asf_geocode)
// or via the GUI (asf_convert_gui) then this will need
// to change, but for now, associate a spheroid with
// the datum based on standard use.
if (spheroid == UNKNOWN_SPHEROID)
omd->projection->spheroid = datum_spheroid(datum);
else
omd->projection->spheroid = spheroid;
omd->projection->param = *pp;
free(input_spheroid);
input_spheroid = NULL;
// Special attention to Sinusoidal map projection
if (projection_type == SINUSOIDAL) {
omd->projection->spheroid = SPHERE;
omd->projection->datum = UNKNOWN_DATUM;
omd->projection->re_major = pp->sin.sphere;
omd->projection->re_minor = 0.0;
}
// Adjust bands and band_count for the case where the user
// selected to geocode only a single band out of a multi-band
// file
char **band_name =
extract_band_names(omd->general->bands, omd->general->band_count);
if (!multiband) {
if (band_name)
sprintf(omd->general->bands, "%s", band_name[band_num]);
else
strcpy(omd->general->bands, MAGIC_UNSET_STRING);
omd->general->band_count = 1;
}
meta_write (omd, output_meta_data);
//--------------------------------------------------------------------------
// Now working on generating the output images
double *projX = MALLOC(sizeof(double)*(oix_max+1));
double *projY = MALLOC(sizeof(double)*(oix_max+1)); // Is this a mistake? Use oiy_max instead?
// When mosaicing -- use banded_float_image to store the output, write
// it out after processing all inputs
// When geocoding -- use float arrays to store the output, and write it
// out line-by-line
// one and only one of these will be non-NULL. The flag output_by_line
// indicates which one
BandedFloatImage *output_bfi = NULL;
FloatImage *tfi = NULL;
UInt8Image *tbi = NULL;
float *output_line = NULL;
int output_by_line = n_input_images == 1;
if (n_input_images > 1) {
output_bfi = banded_float_image_new(n_bands, oix_max+1, oiy_max+1);
if (!output_bfi) {
asfPrintError("Cannot create new %d-banded float image of size %d samples by %d lines\n"
"Image size too large?\n",
oix_max+1, oiy_max+1);
}
if (overlap == AVG_OVERLAP) {
// Unsupported as of yet ...this code should never be reached
asfPrintError("Overlap method 'AVERAGE' not yet supported...\n");
tbi = uint8_image_new(oix_max+1, oiy_max+1);
if (!tbi) {
asfPrintError("Cannot create new unit8 image of size %d samples by %d lines\n",
"Image size too large?\n",
oix_max+1, oiy_max+1);
}
}
else if (overlap == NEAR_RANGE_OVERLAP) {
// Unsupported as of yet ...this code should never be reached
asfPrintError("Overlap method 'NEAR RANGE' not yet supported...\n");
tfi = float_image_new(oix_max+1, oiy_max+1);
if (!tfi) {
asfPrintError("Cannot create new float image of size %d samples by %d lines\n",
"Image size too large?\n",
oix_max+1, oiy_max+1);
}
}
}
else {
output_line = MALLOC(sizeof(float)*(oix_max+1));
}
// loop over the input images
for(i=0; i<n_input_images; ++i) {
// Figure out this input image's info
char *in_base_name = STRDUP(in_base_names[i]);
if (n_input_images > 1)
asfPrintStatus("\nWorking on input image #%d: %s\n", i+1, in_base_name);
// strip off known extensions
char *ext = findExt(in_base_name);
if (ext) *ext = '\0';
char *input_image = appendExt(in_base_name, "img");
char *input_meta_data = appendExt(in_base_name, "meta");
// Input metadata.
meta_parameters *imd = meta_read (input_meta_data);
// 400m correction for ScanSAR (again -- we reloaded the metadata &
// reset the average height)
double height_correction = 0;
if (imd->sar && imd->sar->image_type == 'P' &&
imd->projection && imd->projection->type == SCANSAR_PROJECTION &&
strncmp(imd->general->processor, "ASF", 3) == 0)
{
average_height -= 400;
height_correction = 400;
}
/* Confused more than it helped. RG
// Issue a warning when the chosen pixel size is smaller than the
// input pixel size.
if ( MAX(imd->general->x_pixel_size,
imd->general->y_pixel_size) > pixel_size )
{
asfPrintWarning
("Requested pixel size %lf is smaller than the input image resolution "
"(%0.1f meters).\n", pixel_size,
MAX (imd->general->x_pixel_size, imd->general->y_pixel_size));
}
*/
// We will call "resample" on the input data if the geocoding
// will significantly downsample. This is because asf_geocode will
// (with bilinear) use just 4 input pixels, which will throw away a
// lot of information when downsampling by a lot. So, when in this
// situation, we call resample first, since resample will do the
// averaging first.
// This will also result in significantly faster geocoding.
// We do not do this if we have been asked to save the line/sample
// mapping, since this will mess that up.
int do_resample = FALSE;
if (!save_line_sample_mapping &&
(pixel_size_x/3. > imd->general->x_pixel_size &&
pixel_size_y/3. > imd->general->y_pixel_size))
{
// this flag is so that we can clean up the intermediate resample file
do_resample = TRUE;
// downsample to 2x the target resolution
double resample_psx = pixel_size_x / 2.;
double resample_psy = pixel_size_y / 2.;
char *resample_file = appendToBasename(in_base_name, "_down");
asfPrintStatus("Downsampling input image to %gx%gm.\n",
resample_psx, resample_psy);
resample_to_pixsiz(in_base_name, resample_file,
resample_psx, resample_psy);
// now point to new input files for the remainder of the geocoding
FREE(input_image);
input_image = appendExt(resample_file, ".img");
FREE(input_meta_data);
input_meta_data = appendExt(resample_file, ".meta");
// re-read metadata
meta_free(imd);
imd = meta_read(input_meta_data);
FREE(resample_file);
}
// The pixel size requested by the user better not oversample by
// the factor of 2. Specifying --force will skip this check
// Only apply for metric projections (no geographic)
if (projection_type != LAT_LONG_PSEUDO_PROJECTION) {
if (!force_flag &&
imd->general->x_pixel_size > (2*pixel_size_x) ) {
report_func("Requested pixel size x %lf is smaller than the minimum "
"implied by half \nthe input image resolution "
"(%le meters), this is not supported.\n",
pixel_size_x, imd->general->x_pixel_size);
}
if (!force_flag &&
imd->general->x_pixel_size > (2*pixel_size_y) ) {
report_func("Requested pixel size y %lf is smaller than the minimum "
"implied by half \nthe input image resolution "
"(%le meters), this is not supported.\n",
pixel_size_y, imd->general->y_pixel_size);
}
}
// Input image dimensions in pixels in x and y directions.
size_t ii_size_x = imd->general->sample_count;
size_t ii_size_y = imd->general->line_count;
// The latitude and longitude of the center of the image.
double lat_0, lon_0;
ret = meta_get_latLon (imd, ii_size_y / 2.0, ii_size_x / 2.0,
average_height, &lat_0, &lon_0);
// Flag true iff input image not map projected or pseudoprojected.
gboolean input_projected = FALSE;
// Convenience alias (valid iff input_projected).
meta_projection *ipb = imd->projection;
project_parameters_t *ipp = (ipb) ? &imd->projection->param : NULL;
project_t *project_input;
unproject_t *unproject_input;
if ( ((imd->sar && imd->sar->image_type == 'P') ||
imd->general->image_data_type == DEM)
&& imd->projection && imd->projection->type != SCANSAR_PROJECTION )
{
input_projected = TRUE;
determine_projection_fns(imd->projection->type, &project_input, NULL,
&unproject_input, NULL);
}
if (imd->latlon) {
// This geocoding method does not require establishing a mapping function.
// It is rather a look up of values for a given lat/lon location.
int ii, kk, nsIn, nlIn, nsOut, nlOut, oix, oiy, nLine, nSample;
int minSample, maxSample, minLine, maxLine;
float inc, *inValues, *outValues, *lines, *samples, fValue;
float diff, minDiff;
double lat, lon, yLine, xSample;
nsIn = imd->general->sample_count;
nsOut = omd->general->sample_count;
nlOut = omd->general->line_count;
inc = omd->general->x_pixel_size;
location_minmax(omd->location, &min_y, &max_y, &min_x, &max_x);
/*
min_y = omd->location->lat_start_near_range;
min_x = omd->location->lon_start_near_range;
*/
lines = (float *) MALLOC(sizeof(float)*nsOut*nlOut);
samples = (float *) MALLOC(sizeof(float)*nsOut*nlOut);
asfPrintStatus("Establishing mapping scheme ...\n");
for (oiy=0; oiy<nlOut; oiy++) {
lat = min_y - oiy*inc;
lon = min_x;
meta_get_lineSamp(imd, lat, lon, 0.0, &yLine, &xSample);
nLine = (int)(yLine);
nSample = (int)(xSample);
for (oix=0; oix<nsOut; oix++) {
lon = min_x + oix*inc;
minLine = nLine - 4;
maxLine = nLine + 4;
minSample = nSample - 4;
maxSample = nSample + 4;
if (minLine < 0)
minLine = 0;
if (maxLine >= nlOut)
maxLine = nlOut - 1;
if (minSample < 0)
minSample = 0;
if (maxSample >= nsIn)
maxSample = nsIn - 1;
minDiff=9999999;
for (ii=minLine; ii<maxLine; ii++) {
for (kk=minSample; kk<maxSample; kk++) {
diff = fabs(imd->latlon->lat[ii*nsIn + kk] - lat) +
fabs(imd->latlon->lon[ii*nsIn + kk] - lon);
if (diff < minDiff) {
minDiff = diff;
nLine = ii;
nSample = kk;
}
}
}
lines[oiy*nsOut+oix] = nLine;
samples[oiy*nsOut+oix] = nSample;
}
/*
for (oix=0; oix<nsOut; oix++) {
lat = min_y - oiy*inc;
lon = min_x + oix*inc;
meta_get_lineSamp(imd, lat, lon, 0.0, &yLine, &xSample);
lines[oiy*nsOut+oix] = (int)(yLine + 0.5);
samples[oiy*nsOut+oix] = (int)(xSample + 0.5);
}
*/
asfPercentMeter((double)oiy/nlOut);
}
asfPrintStatus("\rProcessed 100%\n");
for (kk=0; kk<imd->general->band_count; kk++) {
if (multiband || kk == band_num) {
if (n_bands > 1) {
FILE *fpIn = FOPEN(input_image, "rb");
nsIn = imd->general->sample_count;
nlIn = imd->general->line_count;
inValues = (float *) MALLOC(sizeof(float)*nsIn*nlIn);
get_band_float_lines(fpIn, imd, kk, 0, nlIn, inValues);
FCLOSE(fpIn);
FILE *fpOut = FOPEN(output_image, kk>0 ? "ab" : "wb");
outValues = (float *) MALLOC(sizeof(float)*nsOut);
asfPrintStatus("Geocoding band: %s\n", band_name[kk]);
for (oiy=0; oiy<nlOut; oiy++) {
for (oix=0; oix<nsOut; oix++) {
nLine = lines[oiy*nsOut+oix];
nSample = samples[oiy*nsOut+oix];
fValue = inValues[nLine*nsIn + nSample];
outValues[oix] = fValue;
}
put_band_float_line(fpOut, omd, kk, oiy, outValues);
asfLineMeter(oiy, nlOut);
}
FCLOSE(fpOut);
FREE(inValues);
FREE(outValues);
}
}
}
FREE(lines);
FREE(samples);
}
else {
// This would be the place to do the resampling of geocoded images
// that happen to be in the same map projection as the mosaic but don't
// have the same pixel size.
// 'Resample' could do the trick, except it only takes file names, so
// we have plenty IO before we have the image in the size we need.
// Found a scaled version of float_image but that only takes integer
// size kernels. Not an option for flexible pixel sizes.
// Generate some mappings between output image projection
// coordinates and input image pixel coordinates, using proj. We
// compute transformations for points on a grid_size * grid_size
// grid and a sparse_grid_size * sparse_grid_size grid.
asfPrintStatus ("Performing analytical projection of a spatially "
"distributed\nsubset of input image pixels...\n");
fflush (stdout);
double x_range_size = max_x - min_x, y_range_size = max_y - min_y;
// This grid size seems to work pretty well in general for our
// products (good accuracy everywhere, decent speed).
size_t grid_size = 131;
// However, there isn't much point in using as many grid points as
// we have pixels, so for small tiles, we set this to about 10
// percent of larger image dimension in pixels.
if ( ii_size_x / grid_size < 10 && ii_size_y / grid_size < 10 ) {
grid_size = MAX (ii_size_x, ii_size_y) / 10;
if ( grid_size % 2 != 1 )
grid_size++;
}
g_assert (grid_size % 2 == 1);
size_t mapping_count = grid_size * grid_size;
struct data_to_fit dtf;
dtf.grid_size = grid_size;
dtf.n = mapping_count;
dtf.x_proj = g_new0 (double, mapping_count);
dtf.y_proj = g_new0 (double, mapping_count);
dtf.x_pix = g_new0 (double, mapping_count);
dtf.y_pix = g_new0 (double, mapping_count);
// Determine the density and stride for the sparse grid.
const size_t sparse_grid_sample_stride = 2;
const size_t sparse_grid_size = grid_size / 2 + 1;
size_t sparse_mapping_count = sparse_grid_size * sparse_grid_size;
dtf.sparse_grid_size = sparse_grid_size;
dtf.sparse_n = sparse_mapping_count;
dtf.sparse_x_proj = g_new0 (double, sparse_mapping_count);
dtf.sparse_y_proj = g_new0 (double, sparse_mapping_count);
dtf.sparse_x_pix = g_new0 (double, sparse_mapping_count);
dtf.sparse_y_pix = g_new0 (double, sparse_mapping_count);
// Spacing between grid points, in output projection coordinates.
double x_spacing = x_range_size / (grid_size - 1);
double y_spacing = y_range_size / (grid_size - 1);
// Index into the flattened list of mappings we want to produce.
size_t current_mapping = 0;
size_t current_sparse_mapping = 0;
size_t ii;
for ( ii = 0 ; ii < grid_size ; ii++ ) {
size_t jj;
for ( jj = 0 ; jj < grid_size ; jj++ ) {
g_assert (sizeof (long int) >= sizeof (size_t));
// Projection coordinates for the current grid point.
double cxproj = min_x + x_spacing * jj;
double cyproj = min_y + y_spacing * ii;
// Corresponding latitude and longitude.
double lat, lon;
ret = unproject (pp, cxproj, cyproj, ASF_PROJ_NO_HEIGHT,
&lat, &lon, NULL, datum);
if ( !ret ) {
// Details of the error should have already been printed.
asfPrintError ("Projection Error!\n");
}
lat *= R2D;
lon *= R2D;
// here we have some kludgery to handle crossing the meridian
if (fabs(lon-lon_0) > 300) {
if (lon_0 < 0 && lon > 0) lon -= 360;
if (lon_0 > 0 && lon < 0) lon += 360;
}
// Corresponding pixel indicies in input image.
double x_pix, y_pix;
if ( input_projected ) {
// Input projection coordinates of the current pixel.
double ipcx, ipcy, ipcz;
ret = project_input (ipp, D2R*lat, D2R*lon, average_height,
&ipcx, &ipcy, &ipcz, imd->projection->datum);
if ( ret == 0 ) {
g_assert_not_reached ();
}
g_assert (ret);
// Find the input image pixel indicies corresponding to input
// projection coordinates.
x_pix = (ipcx - ipb->startX) / ipb->perX;
y_pix = (ipcy - ipb->startY) / ipb->perY;
}
else {
ret = meta_get_lineSamp (imd, lat, lon, average_height,
&y_pix, &x_pix);
//g_assert (ret == 0);
if (ret != 0) {
asfPrintError("Failed to determine line and sample from "
"latitude and longitude\n"
"Lat: %f, Lon: %f\n", lat, lon);
}
}
g_assert(current_mapping < mapping_count);
dtf.x_proj[current_mapping] = cxproj;
dtf.y_proj[current_mapping] = cyproj;
dtf.x_pix[current_mapping] = x_pix;
dtf.y_pix[current_mapping] = y_pix;
if ( ii % sparse_grid_sample_stride == 0 &&
jj % sparse_grid_sample_stride == 0 ) {
g_assert(current_sparse_mapping < sparse_mapping_count);
dtf.sparse_x_proj[current_sparse_mapping] = cxproj;
dtf.sparse_y_proj[current_sparse_mapping] = cyproj;
dtf.sparse_x_pix[current_sparse_mapping] = x_pix;
dtf.sparse_y_pix[current_sparse_mapping] = y_pix;
current_sparse_mapping++;
}
current_mapping++;
asfPercentMeter((float)current_mapping / (float)(grid_size*grid_size));
}
}
// Here are some convenience macros for the spline model.
#define X_PIXEL(x, y) reverse_map_x (&dtf, x, y)
#define Y_PIXEL(x, y) reverse_map_y (&dtf, x, y)
// We want to choke if our worst point in the model is off by this
// many pixels or more.
double max_allowable_error = 1.25;
// Check the health of the our spline model by comparing the input
// image pixel coordinates predicted by the model for each point
// with the known values.
{
// This is a small image which will show a visual of the
// distribution of errors in the output grid.
FloatImage *error_map = float_image_new (grid_size, grid_size);
gsl_vector *model_x_errors = gsl_vector_alloc (dtf.n);
gsl_vector *model_y_errors = gsl_vector_alloc (dtf.n);
gsl_vector *model_errors = gsl_vector_alloc (dtf.n);
for ( ii = 0 ; ii < dtf.n ; ii++ ) {
// x pixel index in input image as predicted by model.
double xpfm = X_PIXEL (dtf.x_proj[ii], dtf.y_proj[ii]);
double ypfm = Y_PIXEL (dtf.x_proj[ii], dtf.y_proj[ii]);
double x_error = xpfm - dtf.x_pix[ii];
double y_error = ypfm - dtf.y_pix[ii];
double error_distance = sqrt (x_error*x_error + y_error*y_error);
float_image_set_pixel (error_map, ii % grid_size, ii / grid_size,
error_distance);
gsl_vector_set (model_x_errors, ii, x_error);
gsl_vector_set (model_y_errors, ii, y_error);
gsl_vector_set (model_errors, ii, error_distance);
}
// Uncomment the following 2 lines to get an image showing the
// distribution of errors in the approximating grid.
//float_image_export_as_jpeg (error_map, "error_map.jpg", grid_size, 0);
float_image_free (error_map);
double mean_error
= gsl_stats_mean (model_errors->data, model_errors->stride,
model_errors->size);
double error_standard_deviation
= gsl_stats_sd_m (model_errors->data, model_errors->stride,
model_errors->size, mean_error);
double max_x_error = gsl_vector_max (model_x_errors);
double min_x_error = gsl_vector_min (model_x_errors);
double largest_x_error;
if ( fabs (max_x_error) > fabs (min_x_error) ) {
largest_x_error = max_x_error;
}
else {
largest_x_error = min_x_error;
}
double max_y_error = gsl_vector_max (model_y_errors);
double min_y_error = gsl_vector_min (model_y_errors);
double largest_y_error;
if ( fabs (max_y_error) > fabs (min_y_error) ) {
largest_y_error = max_y_error;
}
else {
largest_y_error = min_y_error;
}
double largest_error = gsl_vector_max (model_errors);
if ( largest_error > max_allowable_error ) {
print_large_error_blurb(force_flag);
report_func("Largest error was larger than maximum allowed! "
"%f > %f\n", largest_error, max_allowable_error);
}
asfPrintStatus ("For the differences between spline model values and "
"projected values\nfor the analytically projected "
"control points:\n");
asfPrintStatus ("Mean: %g\n", mean_error);
asfPrintStatus ("Standard deviation: %g\n", error_standard_deviation);
asfPrintStatus ("Maximum (worst observed error in pixel index distance): "
"%g\n", largest_error);
asfPrintStatus ("Maximum x error (worst observed error in x pixel index): "
"%g\n", largest_x_error);
asfPrintStatus ("Maximum y error (worst observed error in y pixel index): "
"%g\n", largest_y_error);
gsl_vector_free (model_errors);
gsl_vector_free (model_y_errors);
gsl_vector_free (model_x_errors);
}
// If we don't have a projected image, we are basing things on
// meta_get_lineSamp, which is awesome. Check correctness of reverse
// mappings of some corners, as an extra paranoid check. We insist
// on the model being within this many pixels for reverse
// transformations of the projection coordinates of the corners of
// the output image back to the pixel indicies in the input image.
if ( !input_projected ) {
// The maximum corner error we are willing to tolerate.
double max_corner_error;
// The so called scansar projection has problems that prevent us
// from getting as good a match as we would like (see below about
// asymmetry or meta_get_latLon and meta_get_lineSamp).
// FIXME: Fix the broken scansar crap *HARD*.
if ( imd->sar && imd->sar->image_type == 'P' ) {
//g_assert (imd->projection->type == SCANSAR_PROJECTION);
max_corner_error = 3 * max_allowable_error;
}
else {
max_corner_error = max_allowable_error;
}
// Upper left corner.
double ul_lat, ul_lon;
ret = meta_get_latLon (imd, 0.0, 0.0, average_height, &ul_lat, &ul_lon);
g_assert (ret == 0);
// Test the symmetry of meta_get_latLon/meta_get_lineSamp. I
// believe it is pretty good for everything but scansar projected
// input data, where it is off by 1.5% or so and therefore throws
// this error check just a bit outside of a pixel. But if the
// problem is somewhere else I want to know. Skip this test for
// data with a transform block.
if (imd->sar && imd->sar->image_type != 'P' && !imd->transform) {
double start_tol = 0.2;
meta_set_lineSamp_tolerance(start_tol);
int niter=1;
while (1) {
asfPrintStatus ("Symmetry testing latLong vs. lineSamp...\n");
asfPrintStatus ("tolerance = %f\n", meta_get_lineSamp_tolerance());
int ok1,ok2,ok3,ok4,ok5,ok6,ok7,ok8,ok9;
int nl = imd->general->line_count;
int ns = imd->general->sample_count;
ok1 = symmetry_test(imd, 2, 2, average_height); // Top left
ok2 = symmetry_test(imd, nl/2, ns/2, average_height); // Middle
ok3 = symmetry_test(imd, nl-3, ns-3, average_height); // Bottom right
ok4 = symmetry_test(imd, nl-3, 2, average_height); // Bottom left
ok5 = symmetry_test(imd, 2, ns-3, average_height); // Top right
ok6 = symmetry_test(imd, 2, ns/2, average_height); // Top center
ok7 = symmetry_test(imd, nl-3, ns/2, average_height); // Bottom center
ok8 = symmetry_test(imd, nl/2, 2, average_height); // Left center
ok9 = symmetry_test(imd, nl/2, ns-3, average_height); // Right center
if (!ok1 || !ok2 || !ok3 || !ok4 || !ok5 ||
!ok6 || !ok7 || !ok8 || !ok9) {
// if any tests failed, print out which ones were ok
if (ok2)
asfPrintStatus("Symmetry test at center (%d,%d): ok\n",
nl/2, ns/2);
if (ok1)
asfPrintStatus("Symmetry test at UL corner (2,2): ok\n");
if (ok5)
asfPrintStatus("Symmetry test at UR corner (%d,%d): ok\n",
2, ns-2);
if (ok3)
asfPrintStatus("Symmetry test at BR corner (%d,%d): ok\n",
nl-3, ns-3);
if (ok4)
asfPrintStatus("Symmetry test at BL corner (%d,%d): ok\n",
nl-3, 2);
if (ok6)
asfPrintStatus("Symmetry test at top center (%d,%d): ok\n",
2, ns/2);
if (ok7)
asfPrintStatus("Symmetry test at bottom center (%d,%d): ok\n",
nl-3, ns/2);
if (ok8)
asfPrintStatus("Symmetry test at left center (%d,%d): ok\n",
nl/2, 2);
if (ok9)
asfPrintStatus("Symmetry test at right center (%d,%d): ok\n",
nl/2, ns-3);
if (niter==1 || niter==2) {
// reduce the tolerance... and try again. makes it slower
// but more accurate, and apparently we need it
asfPrintStatus("\nTightening up the tolerance of lineSamp.\n");
++niter;
meta_set_lineSamp_tolerance(start_tol / (double)niter );
continue;
}
else {
// give up!
report_func("Symmetry testing failed. Use the -force "
"(command line) option or\nthe Ignore Projection "
"Errors checkbox (MapReady Geocode Tab)\n");
// go back to the original tolerance
meta_set_lineSamp_tolerance(start_tol);
break;
}
}
else {
asfPrintStatus("Good.\n");
break;
}
}
}
double ul_x, ul_y;
project (pp, D2R * ul_lat, D2R * ul_lon, ASF_PROJ_NO_HEIGHT,
&ul_x, &ul_y, NULL, datum);
double ul_x_pix_approx = X_PIXEL (ul_x, ul_y);
if (fabs (ul_x_pix_approx) > max_corner_error ) {
print_large_error_blurb(force_flag);
report_func("Upper left x corner error was too large! %f > %f\n",
fabs (ul_x_pix_approx), max_corner_error );
}
else {
asfPrintStatus ("Upper left x corner error: %f\n",
fabs (ul_x_pix_approx));
}
double ul_y_pix_approx = Y_PIXEL (ul_x, ul_y);
if (fabs (ul_y_pix_approx) > max_corner_error ) {
print_large_error_blurb(force_flag);
report_func ("Upper left y corner error was too large! %f > %f\n",
fabs (ul_y_pix_approx), max_corner_error );
}
else {
asfPrintStatus ("Upper left y corner error: %f\n",
fabs (ul_y_pix_approx));
}
// Lower right corner.
double lr_lat, lr_lon;
ret = meta_get_latLon (imd, (float) (ii_size_y - 1),
(float) (ii_size_x - 1),
average_height, &lr_lat, &lr_lon);
g_assert (ret == 0);
double lr_x, lr_y;
project (pp, D2R * lr_lat, D2R * lr_lon, ASF_PROJ_NO_HEIGHT,
&lr_x, &lr_y, NULL, datum);
double lr_x_pix_approx = X_PIXEL (lr_x, lr_y);
double lr_x_corner_error = fabs (lr_x_pix_approx - (ii_size_x - 1));
if ( lr_x_corner_error > max_corner_error ) {
print_large_error_blurb(force_flag);
report_func ("Lower right x corner error was too large! %f > %f\n",
lr_x_corner_error, max_corner_error);
}
else {
asfPrintStatus ("Lower right x corner error: %f\n", lr_x_corner_error);
}
double lr_y_pix_approx = Y_PIXEL (lr_x, lr_y);
double lr_y_corner_error = fabs (lr_y_pix_approx - (ii_size_y - 1));
if ( lr_y_corner_error > max_corner_error ) {
print_large_error_blurb(force_flag);
report_func ("Lower right Y corner error was too large! %f > %f\n",
lr_y_corner_error, max_corner_error);
}
else {
asfPrintStatus ("Lower right y corner error: %f\n", lr_y_corner_error);
}
}
// Now the mapping function is calculated and we can apply that to
// all the bands in the file (or to the single band selected with
// the -band option)
// Now the band loop (the inner loop, see the discussion above)
// Note that we use this file's metadata band count -- if this is
// less than the number of bands in the output image, that band
// will mosaic with fewer bands.
int kk;
for (kk=0; kk<imd->general->band_count; kk++) {
if (multiband || kk == band_num) {
if (n_bands > 1)
asfPrintStatus("Geocoding band: %s\n", band_name[kk]);
// Complain if we're not using Nearest Neighbor when we shouldn't
if (kk==0 && resample_method != RESAMPLE_NEAREST_NEIGHBOR) {
if (strncmp_case(band_name[kk],"Cloude-Pottier",14)==0) {
asfPrintWarning("When geocoding Cloude-Pottier, you should be "
"using\nthe resampling method NEAREST_NEIGHBOR.\n"
"Results may not be as expected!\n");
}
else if (strncmp_case(band_name[kk],"LAYOVER_MASK",12)==0) {
asfPrintWarning("When geocoding a Layover/Shadow mask, you should "
"be using\nthe resampling method "
"NEAREST_NEIGHBOR.\n"
"Results may not be as expected!\n");
}
}
// Set up the line/sample mapping files, if requested to do so
FILE *outLineFp=NULL, *outSampFp=NULL;
float *line_out=NULL, *samp_out=NULL;
if (save_line_sample_mapping) {
asfPrintStatus("Setting up line/sample mapping files...\n");
char *line_filename = appendToBasename(output_image, "_lines");
char *line_metaname = appendExt(line_filename, ".meta");
outLineFp = FOPEN(line_filename, "wb");
meta_write(omd, line_metaname);
FREE(line_filename);
FREE(line_metaname);
char *sample_filename = appendToBasename(output_image, "_samples");
char *sample_metaname = appendExt(sample_filename, ".meta");
outSampFp = FOPEN(sample_filename, "wb");
meta_write(omd, sample_metaname);
FREE(sample_filename);
FREE(sample_metaname);
line_out = MALLOC(sizeof(float)*(oix_max+1));
samp_out = MALLOC(sizeof(float)*(oix_max+1));
// prevent doing the line/sample file again
save_line_sample_mapping = FALSE;
}
// For optical data -- we'll do processing as BYTE, to save memory
// So, only one of the {Float/UInt8}Image will be non-null
FloatImage *iim = NULL;
UInt8Image *iim_b = NULL;
asfPrintStatus("Creating tiles for the input image ...\n");
// open up the input image
if (process_as_byte)
iim_b = uint8_image_band_new_from_metadata(imd, kk, input_image);
else
iim = float_image_band_new_from_metadata(imd, kk, input_image);
asfPrintStatus("Resampling input image into output image "
"coordinate space...\n");
FILE *outFp = NULL; // only used in the line-by-line output case
if (output_by_line) {
// open for append, if multiband && this isn't the first band
outFp = FOPEN(output_image, multiband && kk>0 ? "ab" : "wb");
}
if (output_by_line)
g_assert(outFp && output_line && !output_bfi);
else
g_assert(!outFp && !output_line && output_bfi);
// Set the pixels of the output image.
size_t oix, oiy; // Output image pixel indicies.
for (oiy = 0 ; oiy <= oiy_max ; oiy++) {
asfLineMeter(oiy, oiy_max + 1 );
int oix_first_valid = -1;
int oix_last_valid = -1;
for ( oix = 0 ; oix <= oix_max ; oix++ ) {
// Projection coordinates for the center of this pixel.
double oix_pc = ((double) oix/oix_max) * (max_x-min_x) + min_x;
// We want projection coordinates to increase as we move from
// the bottom of the image to the top, so that north ends up up.
double oiy_pc = (1.0-(double)oiy/oiy_max) * (max_y-min_y) + min_y;
projX[oix] = oix_pc;
projY[oix] = oiy_pc;
// Determine pixel of interest in input image. The fractional
// part is desired, we will use some sampling method to
// interpolate between pixel values.
double input_x_pixel = X_PIXEL (oix_pc, oiy_pc);
double input_y_pixel = Y_PIXEL (oix_pc, oiy_pc);
if (line_out) {
if (input_y_pixel < 0 || input_x_pixel < 0)
line_out[oix] = 0;
else if (input_y_pixel > (ssize_t) ii_size_y - 1.0 ||
input_x_pixel > (ssize_t) ii_size_x - 1.0)
line_out[oix] = 0;
else
line_out[oix] = input_y_pixel;
}
if (samp_out) {
if (input_y_pixel < 0 || input_x_pixel < 0)
samp_out[oix] = 0;
else if (input_y_pixel > (ssize_t) ii_size_y - 1.0 ||
input_x_pixel > (ssize_t) ii_size_x - 1.0)
samp_out[oix] = 0;
else
samp_out[oix] = input_x_pixel;
}
g_assert (ii_size_x <= SSIZE_MAX);
g_assert (ii_size_y <= SSIZE_MAX);
float value, ref_value, power;
// If we are outside the extent of the input image, set to the
// fill value. We do this only on the first image -- subsequent
// images will work out the overlap with real data.
if (input_x_pixel < 0 ||
input_x_pixel > (ssize_t) ii_size_x - 1.0 ||
input_y_pixel < 0 ||
input_y_pixel > (ssize_t) ii_size_y - 1.0 ) {
if (i == 0) { // first image
if (output_by_line)
output_line[oix] = background_val;
else
banded_float_image_set_pixel(output_bfi, kk, oix, oiy,
background_val);
}
}
// Otherwise, set to the value from the appropriate position in
// the input image.
else {
if (process_as_byte) {
value =
uint8_image_sample(iim_b, input_x_pixel, input_y_pixel,
uint8_image_sample_method);
}
else if ( imd->general->image_data_type == DEM ) {
value = dem_sample(iim, input_x_pixel, input_y_pixel,
float_image_sample_method);
}
else {
if (imd->general->radiometry >= r_SIGMA_DB &&
imd->general->radiometry <= r_GAMMA_DB) {
power =
float_image_sample(iim, input_x_pixel, input_y_pixel,
float_image_sample_method);
value = 10.0 * log10(power);
}
else
value =
float_image_sample(iim, input_x_pixel, input_y_pixel,
float_image_sample_method);
if (omd->general->data_type == BYTE && value < 0.0) {
value = 0.0;
out_of_range_negative++;
}
if (omd->general->data_type == BYTE && value > 255.0) {
value = 255.0;
out_of_range_positive++;
}
}
// Now we are ready to put the pixel value into the output image
if (i > 0 && imd->general->image_data_type == DEM &&
(value == 0 || value < -900)) {
// Special case for DEMs -- we don't want to overwrite
// "good" elevations with 0s, or "no data" values
// (<-900 means "no data" for DEMs)
// So, in this situation, we don't do anything
;
}
else if (meta_is_valid_double(imd->general->no_data) &&
value == imd->general->no_data) {
// pixel is the "no data" value -- only the first image
// will set this in the output image, otherwise we risk
// overwriting real data with background.
if (i==0) {
if (output_by_line)
output_line[oix] = value;
else {
banded_float_image_set_pixel(output_bfi, kk, oix, oiy,
value);
//uint8_image_set_pixel(tbi, oix, oiy, 1);
}
}
}
else {
// Normal case, set the output pixel value
oix_last_valid = oix;
if (oix_first_valid == -1) oix_first_valid = oix;
// FIXME: AVERAGE and NEAR RANGE overlap need some work
// Have to track some values in a second image
// Overlap option: OVERLAY
// No action needed, just overwrite previous value
// New images are intialized with zeros (at least float_image
// does that). So we need to check for that when looking for
// values.
if (output_by_line) {
output_line[oix] = value;
}
else {
ref_value =
banded_float_image_get_pixel(output_bfi, kk, oix, oiy);
if (overlap == MIN_OVERLAP && ref_value != 0 &&
ref_value < value) {
value = ref_value;
}
else if (overlap == MAX_OVERLAP && ref_value != 0 &&
ref_value > value) {
value = ref_value;
}
else if (overlap == AVG_OVERLAP) {
value += ref_value;
uint8_t byte_value = uint8_image_get_pixel(tbi, oix, oiy);
if (value != 0.0) {
byte_value++;
}
uint8_image_set_pixel(tbi, oix, oiy, byte_value);
}
banded_float_image_set_pixel(output_bfi, kk, oix, oiy,
value);
}
}
}
} // end of for-each-sample-in-line set output values
// If we are reprojecting a DEM, need to account for the height
// difference between the vertical datum (NGVD27) and our WGS84
// ellipsoid. Since geoid heights closely match vertical datum
// heights, this will work for SAR imagery
if ( imd->general->image_data_type == DEM ) {
// At present, don't handle byte DEMs. Don't think such a thing
// is even possible, really.
g_assert(iim && !iim_b);
double *lat, *lon;
lat = lon = NULL; // => libproj will allocate for us
// Need to get each pixel's location in lat/lon in order to get
// the geoid height. We saved each pixel's projection coordinates,
// above, so we just to need to convert those, then use the
// lat/lon values to get the required geoid height correction,
// add it to the height at the pixel.
// Doing it like this (instead of pixel-by-pixel) allows us to
// use the array version of libproj, which is *much* faster.
unproject_arr(pp, projX, projY, NULL, &lat, &lon, NULL,
oix_max + 1, datum);
// the outer if guards against the case where no valid pixels
// were on this line (i.e., both are -1)
if (oix_first_valid > 0 && oix_last_valid > 0) {
if (output_by_line) {
for (oix = oix_first_valid; (int)oix <= oix_last_valid; ++oix) {
output_line[oix] +=
get_geoid_height(lat[oix]*R2D, lon[oix]*R2D);
}
}
else {
for (oix = oix_first_valid; (int)oix <= oix_last_valid; ++oix) {
float value = banded_float_image_get_pixel(output_bfi, kk, oix, oiy);
banded_float_image_set_pixel(output_bfi, kk, oix, oiy,
value + get_geoid_height(lat[oix]*R2D, lon[oix]*R2D));
}
}
}
free(lat);
free(lon);
}
// write the line, if we're doing line-by-line output
if (output_by_line) {
put_float_line(outFp, omd, oiy, output_line);
}
if (line_out)
put_float_line(outLineFp, omd, oiy, line_out);
if (samp_out)
put_float_line(outSampFp, omd, oiy, samp_out);
} // End of for-each-line set output values
// done writing this band
if (output_by_line)
fclose(outFp);
// close line/sample mapping files
if (outLineFp)
FCLOSE(outLineFp);
if (outSampFp)
FCLOSE(outSampFp);
FREE(line_out);
FREE(samp_out);
// free up the input image
g_assert(!iim_b || !iim);
if (process_as_byte)
uint8_image_free (iim_b);
else
float_image_free (iim);
if (imd->general->band_count == 1)
asfPrintStatus("Done resampling image.\n");
else
asfPrintStatus("Done resampling band.\n");
if (y_pixel_size < 0 && omd->projection == NULL) {
g_assert (0); /* Shouldn't be here. */
}
} // End of 'if multiband or single band and current band is requested band'
} // End of 'for each band' in the file, 'map-project the data into the file'
// if we did a downsampling, we should delete the "_down" file
if (do_resample) {
asfPrintStatus("Removing temporary downsampled file...\n");
unlink(input_meta_data);
unlink(input_image);
}
/////////////////////////////////////////////////////////////////////////
//
// Clear out all the persistent spline memory goop used by the
// reverse_map_x and reverse_map_y routines (see comments near the
// declarations of these variables).
//
size_t sgs = dtf.sparse_grid_size; // Convenience alias.
first_time_through_rmx = TRUE;
first_time_through_rmy = TRUE;
for ( ii = 0 ; ii < sgs ; ii++ ) {
gsl_interp_accel_free (y_accel_rmx[ii]);
gsl_interp_accel_free (y_accel_rmy[ii]);
gsl_spline_free (y_spline_rmx[ii]);
gsl_spline_free (y_spline_rmy[ii]);
}
g_free (y_accel_rmx);
g_free (y_accel_rmy);
g_free (y_spline_rmx);
g_free (y_spline_rmy);
gsl_interp_accel_free (crnt_accel_rmx);
gsl_interp_accel_free (crnt_accel_rmy);
gsl_spline_free (crnt_rmx);
gsl_spline_free (crnt_rmy);
/////////////////////////////////////////////////////////////////////////
// Done with the data being modeled.
g_free (dtf.sparse_y_pix);
g_free (dtf.sparse_x_pix);
g_free (dtf.sparse_y_proj);
g_free (dtf.sparse_x_proj);
g_free (dtf.y_pix);
g_free (dtf.x_pix);
g_free (dtf.y_proj);
g_free (dtf.x_proj);
// Done with the file name arguments.
free(input_meta_data);
free(input_image);
free(in_base_name);
meta_free(imd);
// reset average_height (avoid double correction for scansar 400m)
average_height += height_correction;
} //else regular geocoding
}
if (band_name) {
int kk;
for (kk=0; kk < omd->general->band_count; ++kk)
FREE(band_name[kk]);
FREE(band_name);
}
free(projX);
free(projY);
if (output_by_line)
free(output_line);
else {
// write the output image
int kk;
asfPrintStatus("\nGenerating final output.\n");
for (kk=0; kk<omd->general->band_count; ++kk) {
if (overlap == AVG_OVERLAP) {
size_t oix, oiy;
for (oiy = 0 ; oiy <= oiy_max ; oiy++)
for ( oix = 0 ; oix <= oix_max ; oix++ ) {
float value = banded_float_image_get_pixel(output_bfi, kk, oix, oiy);
//uint8_t num = uint8_image_get_pixel(tbi, oix, oiy);
//if (num > 0)
//value /= num;
banded_float_image_set_pixel(output_bfi, kk, oix, oiy, value);
}
}
FloatImage *fi = banded_float_image_get_band(output_bfi, kk);
float_image_band_store(fi, output_image, omd, kk>0);
}
banded_float_image_free(output_bfi);
if (tbi) {
uint8_image_free(tbi);
}
}
if (resample_method == BICUBIC &&
omd->general->data_type == BYTE &&
(out_of_range_negative || out_of_range_positive))
{
float num_pixels = (float)(omd->general->line_count * omd->general->sample_count);
float pct_too_negative = 100.0 * ((float)out_of_range_negative / num_pixels);
float pct_too_positive = 100.0 * ((float)out_of_range_positive / num_pixels);
asfPrintWarning(
"Out of range values resulted from the BICUBIC resampling process on BYTE data:\n"
" Too negative: %ld pixels (%0.1f%% of the image)\n"
" Too positive: %ld pixels (%0.1f%% of the image)\n",
out_of_range_negative, pct_too_negative,
out_of_range_positive, pct_too_positive);
}
meta_free (omd);
free(output_meta_data);
free(output_image);
asfPrintStatus("Geocoding complete.\n\n");
return 0;
}
| {
"alphanum_fraction": 0.62247748,
"avg_line_length": 38.4106571936,
"ext": "c",
"hexsha": "0d8dc934e139cf3c96364e6d4c51dec66aecff45",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z",
"max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "glshort/MapReady",
"max_forks_repo_path": "src/libasf_geocode/asf_geocode.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "glshort/MapReady",
"max_issues_repo_path": "src/libasf_geocode/asf_geocode.c",
"max_line_length": 102,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "glshort/MapReady",
"max_stars_repo_path": "src/libasf_geocode/asf_geocode.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z",
"num_tokens": 29336,
"size": 108126
} |
#pragma once
#include "parser.h"
#include "format.h"
#include "nameutils.h"
#include "utils.h"
#include <sfun/string_utils.h>
#include <cmdlime/errors.h>
#include <gsl/gsl>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <functional>
#include <optional>
namespace cmdlime::detail{
namespace str = sfun::string_utils;
template <FormatType formatType>
class GNUParser : public Parser<formatType>
{
using Parser<formatType>::Parser;
using FindMode = typename Parser<formatType>::FindMode;
void preProcess() override
{
checkNames();
foundParam_.clear();
foundParamPrefix_.clear();
}
void process(const std::string& token) override
{
if (str::startsWith(token, "--") && token.size() > 2)
processCommand(token);
else if (str::startsWith(token, "-") && token.size() > 1)
processShortCommand(token);
else if (!foundParam_.empty()){
this->readParam(foundParam_, token);
foundParam_.clear();
}
else
this->readArg(token);
}
void postProcess() override
{
if (!foundParam_.empty())
throw ParsingError{"Parameter '" + foundParamPrefix_ + foundParam_ + "' value can't be empty"};
}
void processCommand(std::string command)
{
command = str::after(command, "--");
auto paramValue = std::optional<std::string>{};
if (command.find('=') != std::string::npos){
paramValue = str::after(command, "=");
command = str::before(command, "=");
}
if (isParamOrFlag(command) &&
!foundParam_.empty() &&
this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)
throw ParsingError{"Parameter '" + foundParamPrefix_ + foundParam_ + "' value can't be empty"};
if (this->findParam(command, FindMode::Name) || this->findParamList(command, FindMode::Name)){
if (paramValue.has_value())
this->readParam(command, paramValue.value());
else{
foundParam_ = command;
foundParamPrefix_ = "--";
}
}
else if (this->findFlag(command, FindMode::Name))
this->readFlag(command);
else if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)
throw ParsingError{"Encountered unknown parameter or flag '--" + command + "'"};
}
void processShortCommand(std::string command)
{
auto possibleNumberArg = command;
command = str::after(command, "-");
if (isShortParamOrFlag(command)){
if (!foundParam_.empty() && this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)
throw ParsingError{"Parameter '" + foundParamPrefix_ + foundParam_ + "' value can't be empty"};
parseShortCommand(command);
}
else if (isNumber(possibleNumberArg))
this->readArg(possibleNumberArg);
else if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)
throw ParsingError{"Encountered unknown parameter or flag '-" + command + "'"};
}
void parseShortCommand(const std::string& command)
{
if (command.empty())
throw ParsingError{"Flags and parameters must have a name"};
auto paramValue = std::string{};
for(auto ch : command){
auto opt = std::string{ch};
if (!foundParam_.empty())
paramValue += opt;
else if (this->findFlag(opt, FindMode::ShortName))
this->readFlag(opt);
else if (this->findParam(opt, FindMode::ShortName)){
foundParam_ = opt;
foundParamPrefix_ = "-";
}
else if (this->findParamList(opt, FindMode::ShortName)){
foundParam_ = opt;
foundParamPrefix_ = "-";
}
else if (this->readMode_ != Parser<formatType>::ReadMode::ExitFlagsAndCommands)
throw ParsingError{"Unknown option '" + opt + "' in command '-" + command + "'"};
}
if (!foundParam_.empty() && !paramValue.empty()){
this->readParam(foundParam_, paramValue);
foundParam_.clear();
}
}
void checkLongNames()
{
auto check = [](const OptionInfo& var, const std::string& varType){
if (!std::isalpha(var.name().front()))
throw ConfigError{varType + "'s name '" + var.name() + "' must start with an alphabet character"};
if (var.name().size() > 1){
auto nonSupportedCharIt = std::find_if(var.name().begin() + 1, var.name().end(), [](char ch){return !std::isalnum(ch) && ch != '-';});
if (nonSupportedCharIt != var.name().end())
throw ConfigError{varType + "'s name '" + var.name() + "' must consist of alphanumeric characters and hyphens"};
}
};
this->forEachParamInfo([check](const OptionInfo& var){
check(var, "Parameter");
});
this->forEachParamListInfo([check](const OptionInfo& var){
check(var, "Parameter");
});
this->forEachFlagInfo([check](const OptionInfo& var){
check(var, "Flag");
});
}
void checkShortNames()
{
auto check = [](const OptionInfo& var, const std::string& varType){
if (var.shortName().empty())
return;
if (var.shortName().size() != 1)
throw ConfigError{varType + "'s short name '" + var.shortName() + "' can't have more than one symbol"};
if (!std::isalnum(var.shortName().front()))
throw ConfigError{varType + "'s short name '" + var.shortName() + "' must be an alphanumeric character"};
};
this->forEachParamInfo([check](const OptionInfo& var){
check(var, "Parameter");
});
this->forEachParamListInfo([check](const OptionInfo& var){
check(var, "Parameter");
});
this->forEachFlagInfo([check](const OptionInfo& var){
check(var, "Flag");
});
}
void checkNames()
{
checkLongNames();
checkShortNames();
}
bool isParamOrFlag(const std::string& str)
{
if (str.empty())
return false;
return this->findFlag(str, FindMode::Name) ||
this->findParam(str, FindMode::Name) ||
this->findParamList(str, FindMode::Name);
}
bool isShortParamOrFlag(const std::string& str)
{
if (str.empty())
return false;
auto opt = str.substr(0,1);
return this->findFlag(opt, FindMode::ShortName) ||
this->findParam(opt, FindMode::ShortName) ||
this->findParamList(opt, FindMode::ShortName);
}
private:
std::string foundParam_;
std::string foundParamPrefix_;
};
class GNUNameProvider{
public:
static std::string name(const std::string& optionName)
{
Expects(!optionName.empty());
return toKebabCase(optionName);
}
static std::string shortName(const std::string& optionName)
{
Expects(!optionName.empty());
return toLowerCase(optionName.substr(0, 1));
}
static std::string fullName(const std::string& optionName)
{
Expects(!optionName.empty());
return toKebabCase(optionName);
}
static std::string valueName(const std::string& typeName)
{
Expects(!typeName.empty());
return toKebabCase(templateType(typeNameWithoutNamespace(typeName)));
}
};
class GNUOutputFormatter{
public:
static std::string paramUsageName(const IParam& param)
{
auto stream = std::stringstream{};
if (param.isOptional())
stream << "[" << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">]";
else
stream << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">";
return stream.str();
}
static std::string paramListUsageName(const IParamList& param)
{
auto stream = std::stringstream{};
if (param.isOptional())
stream << "[" << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">...]";
else
stream << paramPrefix() << param.info().name() << " <" << param.info().valueName() << ">...";
return stream.str();
}
static std::string paramDescriptionName(const IParam& param, int indent = 0)
{
auto stream = std::stringstream{};
stream << std::setw(indent);
if (!param.info().shortName().empty())
stream << "-" << param.info().shortName() << ", ";
else
stream << " " << " ";
stream << "--" << param.info().name() << " <" << param.info().valueName() << ">";
return stream.str();
}
static std::string paramListDescriptionName(const IParamList& param, int indent = 0)
{
auto stream = std::stringstream{};
stream << std::setw(indent);
if (!param.info().shortName().empty())
stream << "-" << param.info().shortName() << ", ";
else
stream << " " << " ";
stream << "--" << param.info().name() << " <" << param.info().valueName() << ">";
return stream.str();
}
static std::string paramPrefix()
{
return "--";
}
static std::string flagUsageName(const IFlag& flag)
{
auto stream = std::stringstream{};
stream << "[" << flagPrefix() << flag.info().name() << "]";
return stream.str();
}
static std::string flagDescriptionName(const IFlag& flag, int indent = 0)
{
auto stream = std::stringstream{};
stream << std::setw(indent) ;
if (!flag.info().shortName().empty())
stream << "-" << flag.info().shortName() << ", ";
else
stream << " " << " ";
stream << "--" << flag.info().name();
return stream.str();
}
static std::string flagPrefix()
{
return "--";
}
static std::string argUsageName(const IArg& arg)
{
auto stream = std::stringstream{};
stream << "<" << arg.info().name() << ">";
return stream.str();
}
static std::string argDescriptionName(const IArg& arg, int indent = 0)
{
auto stream = std::stringstream{};
if (indent)
stream << std::setw(indent) << " ";
stream << "<" << arg.info().name() << "> (" << arg.info().valueName() << ")";
return stream.str();
}
static std::string argListUsageName(const IArgList& argList)
{
auto stream = std::stringstream{};
if (argList.isOptional())
stream << "[" << argList.info().name() << "...]";
else
stream << "<" << argList.info().name() << "...>";
return stream.str();
}
static std::string argListDescriptionName(const IArgList& argList, int indent = 0)
{
auto stream = std::stringstream{};
if (indent)
stream << std::setw(indent) << " ";
stream << "<" << argList.info().name() << "> (" << argList.info().valueName() << ")";
return stream.str();
}
};
template<>
struct Format<FormatType::GNU>
{
using parser = GNUParser<FormatType::GNU>;
using nameProvider = GNUNameProvider;
using outputFormatter = GNUOutputFormatter;
static constexpr bool shortNamesEnabled = true;
};
}
| {
"alphanum_fraction": 0.5503396097,
"avg_line_length": 33.8110465116,
"ext": "h",
"hexsha": "fa283da571c57e9e2de55992d27731d55d403fdd",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z",
"max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43",
"max_forks_repo_licenses": [
"MS-PL"
],
"max_forks_repo_name": "GerHobbelt/hypertextcpp",
"max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/gnuformat.h",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43",
"max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z",
"max_issues_repo_licenses": [
"MS-PL"
],
"max_issues_repo_name": "GerHobbelt/hypertextcpp",
"max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/gnuformat.h",
"max_line_length": 150,
"max_stars_count": 77,
"max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43",
"max_stars_repo_licenses": [
"MS-PL"
],
"max_stars_repo_name": "GerHobbelt/hypertextcpp",
"max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/gnuformat.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z",
"num_tokens": 2673,
"size": 11631
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include "allvars.h"
#include "proto.h"
void init()
{
int i;
double dT, T1, T2;
strcpy(fname_results, "data/results.txt");
fp_results = fopen(fname_results, "w");
#ifdef JAVELIN
fprintf(fp_results, "JAVELIN-single top-hat transfer function.\n");
printf("JAVELIN.\n");
nc_lim_low = nc_lim_up = 1;
#elif defined TOPHAT
fprintf(fp_results, "multiple top-hat transfer function.\n");
printf("TOPHATs.\n");
#else
fprintf(fp_results, "multiple Gaussian transfer function.\n");
printf("GAUSSIANs.\n");
#endif
memory_alloc_data();
read_data();
nall = ncon + nline;
nall_data = ncon_data + nline_data;
memory_alloc();
scale_con = scale_line = 1.0;
scale_light_curves();
memcpy(Fall_data, Fcon_data, ncon_data*sizeof(double));
memcpy(Fall_data+ncon_data, Fline_data, nline_data*sizeof(double));
len_con = Tcon_data[ncon_data-1] - Tcon_data[0];
len_line = Tline_data[nline_data-1] - Tline_data[0];
cad_con = 0.0;
for(i=0; i<ncon_data-1; i++)
{
cad_con += Tcon_data[i+1] - Tcon_data[i];
}
cad_con /= (ncon_data-1);
cad_line = 0.0;
for(i=0; i<nline_data-1; i++)
{
cad_line += Tline_data[i+1] - Tline_data[i];
}
cad_line /= (nline_data-1);
printf("len: %f %f\n", len_con, len_line);
printf("cad: %f %f\n", cad_con, cad_line);
T1 = Tcon_data[0];
T2 = Tcon_data[ncon_data-1];
dT = T2-T1;
T1 -= 0.1*dT;
T2 += 0.1*dT;
dT = (T2-T1)/(ncon-1.0);
for(i=0; i<ncon; i++)
Tcon[i] = T1 + dT *i;
T1 = Tline_data[0];
T2 = Tline_data[nline_data-1];
dT = T2-T1;
T1 -= 0.1*dT;
T2 += 0.1*dT;
dT = (T2-T1)/(nline-1.0);
for(i=0; i<nline; i++)
Tline[i] = T1 + dT *i;
}
void scale_light_curves()
{
int i;
double mean, norm;
mean = 0.0;
norm = 0.0;
for(i=0; i<ncon_data; i++)
{
mean += Fcon_data[i]/(Fcerrs_data[i] * Fcerrs_data[i]);
norm += 1.0/(Fcerrs_data[i] * Fcerrs_data[i]);
}
mean /= norm;
scale_con = mean;
for(i=0; i<ncon_data;i++)
{
Fcon_data[i] /= mean;
Fcerrs_data[i] /= mean;
}
mean = 0.0;
norm = 0.0;
for(i=0; i<nline_data; i++)
{
mean += Fline_data[i]/(Flerrs_data[i]*Flerrs_data[i]);
norm += 1.0/(Flerrs_data[i]*Flerrs_data[i]);
}
mean /= norm;
scale_line = mean;
for(i=0; i<nline_data;i++)
{
Fline_data[i] /= mean;
Flerrs_data[i] /= mean;
}
printf("scale: %e %e\n", scale_con, scale_line);
fprintf(fp_results, "scale: %e %e\n", scale_con, scale_line);
}
/*
*
*/
void memory_alloc_data()
{
Tcon_data = malloc(ndata_max*sizeof(double));
if(Tcon_data==NULL)
{
strcpy(str_error_exit, "Tcon_data");
error_exit(7);
}
Fcon_data = malloc(ndata_max*sizeof(double));
if(Fcon_data==NULL)
{
strcpy(str_error_exit, "Fcon_data");
error_exit(7);
}
Fcerrs_data = malloc(ndata_max*sizeof(double));
if(Fcerrs_data==NULL)
{
strcpy(str_error_exit, "Fcerrs_data");
error_exit(7);
}
Tline_data = malloc(ndata_max*sizeof(double));
if(Tline_data==NULL)
{
strcpy(str_error_exit, "Tline_data");
error_exit(7);
}
Fline_data = malloc(ndata_max*sizeof(double));
if(Fline_data==NULL)
{
strcpy(str_error_exit, "Fline_data");
error_exit(7);
}
Flerrs_data = malloc(ndata_max*sizeof(double));
if(Flerrs_data==NULL)
{
strcpy(str_error_exit, "Flerrs_data");
error_exit(7);
}
}
void memory_alloc()
{
workspace_ipiv = malloc(ndata_max*sizeof(double));
workspace = malloc(10*ndata_max*sizeof(double) + 10);
Fall_data = array_malloc(nall_data);
Smat = array_malloc(nall_data*nall_data);
Nmat = array_malloc(nall_data*nall_data);
Cmat = array_malloc(nall_data*nall_data);
ICmat = array_malloc(nall_data*nall_data);
ICvmat = array_malloc(nall_data*nall_data);
USmat = array_malloc(nall*nall_data);
ASmat = array_malloc(nall*nall);
Tmat1 = array_malloc(nall_data*nall_data);
Tmat2 = array_malloc(nall_data*nall_data);
Tmat3 = array_malloc(nall_data*nall_data);
Tmat4 = array_malloc(nall_data*nall_data);
Tcon = array_malloc(ncon);
Fcon = array_malloc(ncon);
Fcerrs = array_malloc(ncon);
Tline = array_malloc(nline);
Fline = array_malloc(nline);
Flerrs = array_malloc(nline);
theta_range = matrix_malloc(ntheta_max, 2);
theta_best = array_malloc(ntheta_max);
theta_best_var = array_malloc(ntheta_max*2);
theta_input = array_malloc(ntheta_max);
sigma_input = array_malloc(ntheta_max);
theta_fixed = malloc(ntheta_max*sizeof(int));
theta_best_con = array_malloc(ntheta_max);
theta_best_var_con = array_malloc(ntheta_max*2);
cov_matrix = array_malloc(ntheta_max * ntheta_max);
grid_tau = array_malloc(nc_lim_up);
TF_tau = array_malloc(ntau);
TF = array_malloc(ntau);
gsl_T = gsl_rng_default;
gsl_r = gsl_rng_alloc (gsl_T);
gsl_rng_set(gsl_r, time(NULL));
}
| {
"alphanum_fraction": 0.6592065107,
"avg_line_length": 22.2398190045,
"ext": "c",
"hexsha": "314730228cf2eb5e66ea30217fdcdea50c15e2d3",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-04-12T11:48:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-12-29T06:04:13.000Z",
"max_forks_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/MICA",
"max_forks_repo_path": "src/init.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"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": "LiyrAstroph/MICA",
"max_issues_repo_path": "src/init.c",
"max_line_length": 69,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/MICA",
"max_stars_repo_path": "src/init.c",
"max_stars_repo_stars_event_max_datetime": "2016-10-25T06:32:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-25T06:32:33.000Z",
"num_tokens": 1625,
"size": 4915
} |
#ifndef TTT_UTIL_TEXTURECACHE_H
#define TTT_UTIL_TEXTURECACHE_H
#include <SDL_render.h>
#include <gsl/pointers>
#include <gsl/util>
#include <vector>
#include <memory>
#include <string_view>
namespace ttt::gfx
{
// A class for caching textures for reuse.
class TextureCache final
{
public:
using SizeType = gsl::index;
SDL_Texture *load(std::string_view path, gsl::not_null<SDL_Renderer *> renderer);
void unload(SizeType index) noexcept;
void erase(SizeType index) noexcept;
void clear() noexcept;
[[nodiscard]] SDL_Texture *at(SizeType index) const noexcept;
[[nodiscard]] SDL_Texture *operator [](SizeType index) const noexcept;
[[nodiscard]] SizeType getSize() const noexcept;
[[nodiscard]] SizeType getMaxSize() const noexcept;
private:
std::vector<std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)>> textures;
};
inline void TextureCache::unload(SizeType index) noexcept { gsl::at(textures, index).reset(); }
inline void TextureCache::erase(SizeType index) noexcept { textures.erase(textures.cbegin() + index); }
inline void TextureCache::clear() noexcept { textures.clear(); }
inline SDL_Texture *TextureCache::at(SizeType index) const noexcept { return gsl::at(textures, index).get(); }
inline SDL_Texture *TextureCache::operator [](SizeType index) const noexcept { return gsl::at(textures, index).get(); }
inline TextureCache::SizeType TextureCache::getSize() const noexcept { return textures.size(); }
inline TextureCache::SizeType TextureCache::getMaxSize() const noexcept { return textures.max_size(); }
}
#endif | {
"alphanum_fraction": 0.7474683544,
"avg_line_length": 33.6170212766,
"ext": "h",
"hexsha": "4a7919c1cf518d9a7b4d1c72bf3aa7bbfff4f101",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "itsArtem/TicTacToe",
"max_forks_repo_path": "Source/Graphics/TextureCache.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "itsArtem/TicTacToe",
"max_issues_repo_path": "Source/Graphics/TextureCache.h",
"max_line_length": 120,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "itsArtem/TicTacToe",
"max_stars_repo_path": "Source/Graphics/TextureCache.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 369,
"size": 1580
} |
/*
* 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 vdir_b62819a0_88a2_4eb7_9a92_6d287a152304_h
#define vdir_b62819a0_88a2_4eb7_9a92_6d287a152304_h
#include <gslib/config.h>
#include <gslib/tree.h>
#include <gslib/pool.h>
__gslib_begin__
class dirop
{
public:
virtual void get_current_dir(string& str);
virtual bool change_dir(const gchar* path);
virtual bool make_dir(const gchar* path);
virtual bool remove_dir(const gchar* path);
};
struct vdirnode;
struct vdirfile;
typedef vdirnode vdirfolder;
typedef _treenode_wrapper<vdirnode> vdirwrapper;
typedef tree<vdirnode, vdirwrapper> vdirtree;
typedef vdirtree::iterator vdiriter;
typedef vdirtree::const_iterator vdirciter;
struct vdirnode
{
enum
{
dt_folder,
dt_file,
dt_tag,
};
string name;
public:
vdirnode() {}
vdirnode(const gchar* n) { name.assign(n); }
virtual uint get_tag() const { return dt_folder; }
virtual const gchar* get_name() const { return name.c_str(); }
void set_name(const gchar* str, int len) { name.assign(str, len); }
void set_name(const string& str) { name = str; }
void tracing() const;
};
struct vdirfile:
public vdirnode
{
vessel vsl;
public:
vdirfile() {}
vdirfile(const gchar* n): vdirnode(n) {}
virtual uint get_tag() const override { return dt_file; }
public:
const gchar* get_postfix() const;
void set_file_data(const void* ptr, int size);
void set_file_data(const gchar* filename);
};
struct vdirtag:
public vdirnode
{
void* binding;
public:
vdirtag() { binding = 0; }
vdirtag(const gchar* n): vdirnode(n) { binding = 0; }
virtual uint get_tag() const override { return dt_tag; }
void set_binding(void* p) { binding = p; }
void* get_binding() const { return binding; }
};
class vdir:
public vdirtree
{
public:
vdiriter create_folder(vdiriter pos, const gchar* name);
vdiriter create_file(vdiriter pos, const gchar* name);
vdiriter create_tag(vdiriter pos, const gchar* name);
void save(const gchar* path);
};
class vdirop:
public dirop
{
public:
vdirop(vdir& d): _dir(d) {}
virtual void get_current_dir(string& str) override;
virtual bool change_dir(const gchar* path) override;
virtual bool make_dir(const gchar* path) override;
virtual bool remove_dir(const gchar* path) override;
protected:
vdir& _dir;
vdiriter _curr;
public:
vdiriter step_or_create(vdiriter pos, const gchar* name);
vdiriter step_once(vdiriter pos, const gchar* name);
vdiriter step_to(vdiriter pos, const gchar* path);
vdiriter locate_folder(vdiriter pos, const gchar* name);
vdiriter locate_file(vdiriter pos, const gchar* name);
vdiriter create_folder(const gchar* name) { return _dir.create_folder(_curr, name); }
vdiriter create_file(const gchar* name) { return _dir.create_file(_curr, name); }
vdiriter get_current_iter() const { return _curr; }
void rewind_curr() { _curr = _dir.get_root(); }
};
__gslib_end__
#endif
| {
"alphanum_fraction": 0.6867770469,
"avg_line_length": 31.0492957746,
"ext": "h",
"hexsha": "6c9d75d369b5a29eba22dbdf8095f32b074ec6ab",
"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/vdir.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/vdir.h",
"max_line_length": 90,
"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/vdir.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": 1111,
"size": 4409
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.