Search is not available for this dataset
text string | meta dict |
|---|---|
//
// mcmc_lotkavolterra.c
//
//
// Created by Juan Pablo Molano on 15/11/15.
//
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <math.h>
#define USAGE "./mcmc_lotkavolterra.x n_burn n_steps"
//------------------------------------------------------------------------------------------------------------
void load_matrix(char *filename, float *time, float *pre, float *dep , int n);
void print_data(float *array, float *array2 , float *array3 , float *array4 , float *array5 , float *array6, float *array7, float *array8 , float *array9 , float *array10, int n_puntos);
float *reserva(int n);
float likelihood(float *y_obs, float *y_model, int n_row);
void ec_dep(float *array, float x, float y, float gamma, float delta);
void ec_pre(float *array, float x, float y, float alpha, float beta);
int min_likelihood( float *array , int n_row);
//------------------------------------------------------------------------------------------------------------
int main(int argc, char **argv){
float *tim, *pre, *dep;
float m_x , m_y , k1_x , k1_y , k2_x , k2_y , k3_x , k3_y , k4_x , k4_y;
float x1 , x2 , x3, x4, y1, y2, y3, y4 , h;
float alpha_prime, beta_prime, gamma_prime, delta_prime, l_prime, l_init, gam, alph, bet , best_alpha , best_beta, best_gamma, best_delta;
float *fit_pre, *fit_dep , *dep_init, *dep_prime , *pre_init , *pre_prime;
int i, j , n_row = 96;
float *alpha_a, *beta_a , *gamma_a , *delta_a , *walk_a, *best_dep, *best_pre;
srand48(time(NULL));
alpha_a = reserva( atof(argv[1]) + atof(argv[2]));
beta_a = reserva( atof(argv[1]) + atof(argv[2]));
gamma_a= reserva( atof(argv[1]) + atof(argv[2]));
delta_a = reserva( atof(argv[1]) + atof(argv[2]));
walk_a = reserva( atof(argv[1]) + atof(argv[2]));
alpha_a[0] = drand48();
beta_a[0] = drand48();
gamma_a[0] = drand48();
delta_a[0] = drand48();
tim = reserva(96);
pre = reserva(96);
dep = reserva(96);
fit_dep = reserva(96);
fit_pre = reserva(96);
dep_init = reserva(96);
dep_prime = reserva(96);
pre_init = reserva(96);
pre_prime = reserva(96);
best_dep = reserva(96);
best_pre = reserva(96);
load_matrix( "new_data.txt" , tim , pre , dep, 96);
h = tim[1] - tim[0];
fit_pre[0] = pre[0];
fit_dep[0] = dep[0];
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
for(i=1;i<96;i++){
ec_pre( &k1_x , fit_pre[i-1] , fit_dep[i-1] , alpha_a[0] , beta_a[0]);
ec_dep( &k1_y , fit_pre[i-1] , fit_dep[i-1] , gamma_a[0] , delta_a[0]);
x1 = fit_pre[i-1] + (h/2.0) * k1_x;
y1 = fit_dep[i-1] + (h/2.0) * k1_y;
ec_pre( &k2_x , fit_pre[i-1] , fit_dep[i-1] , alpha_a[0] , beta_a[0]);
ec_dep( &k2_y , fit_pre[i-1] , fit_dep[i-1] , gamma_a[0] , delta_a[0]);
x2 = fit_pre[i-1] + (h/2.0) * k2_x;
y2 = fit_dep[i-1] + (h/2.0) * k2_y;
ec_pre( &k3_x , fit_pre[i-1] , fit_dep[i-1] , alpha_a[0] , beta_a[0]);
ec_dep( &k3_y , fit_pre[i-1] , fit_dep[i-1] , gamma_a[0] , delta_a[0]);
x3 = fit_pre[i-1] + h * k3_x;
y3 = fit_dep[i-1] + h * k3_y;
ec_pre( &k4_x , fit_pre[i-1] , fit_dep[i-1] , alpha_a[0] , beta_a[0]);
ec_dep( &k4_y , fit_pre[i-1] , fit_dep[i-1] , gamma_a[0] , delta_a[0]);
m_x = (1.0/6.0)*(k1_x + 2.0*k2_x + 2.0*k3_x + k4_x);
m_y = (1.0/6.0)*(k1_y + 2.0*k2_y + 2.0*k3_y + k4_y);
fit_pre[i] = fit_pre[i-1] + h * m_x;
fit_dep[i] = fit_dep[i-1] + h * m_y;
}
for (i=0; i < atof(argv[1]) + atof(argv[2]); i++) {
alpha_prime = gsl_ran_gaussian(r, 0.1) + alpha_a[i];
beta_prime = gsl_ran_gaussian(r, 0.1) + beta_a[i];
gamma_prime = gsl_ran_gaussian(r, 0.1) + gamma_a[i];
delta_prime = gsl_ran_gaussian(r, 0.1) + delta_a[i];
for(j=1;j<96;j++){
dep_init[0] = dep[0];
pre_init[0] = pre[0];
ec_pre( &k1_x , pre_init[j-1] , dep_init[j-1] , alpha_a[i] , beta_a[i]);
ec_dep( &k1_y , pre_init[j-1] , dep_init[j-1] , gamma_a[i] , delta_a[i]);
x1 = pre_init[j-1] + (h/2.0) * k1_x;
y1 = dep_init[j-1] + (h/2.0) * k1_y;
ec_pre( &k2_x , pre_init[j-1] , dep_init[j-1] , alpha_a[i] , beta_a[i]);
ec_dep( &k2_y , pre_init[j-1] , dep_init[j-1] , gamma_a[i] , delta_a[i]);
x2 = pre_init[j-1] + (h/2.0) * k2_x;
y2 = dep_init[j-1] + (h/2.0) * k2_y;
ec_pre( &k3_x , pre_init[j-1] , dep_init[j-1] , alpha_a[i] , beta_a[i]);
ec_dep( &k3_y , pre_init[j-1] , dep_init[j-1] , gamma_a[i] , delta_a[i]);
x3 = pre_init[j-1] + h * k3_x;
y3 = dep_init[j-1] + h * k3_y;
ec_pre( &k4_x , pre_init[j-1] , dep_init[j-1] , alpha_a[i] , beta_a[i]);
ec_dep( &k4_y , pre_init[j-1] , dep_init[j-1] , gamma_a[i] , delta_a[i]);
m_x = (1.0/6.0)*(k1_x + 2.0*k2_x + 2.0*k3_x + k4_x);
m_y = (1.0/6.0)*(k1_y + 2.0*k2_y + 2.0*k3_y + k4_y);
pre_init[j] = pre_init[i-1] + h * m_x;
dep_init[j] = dep_init[i-1] + h * m_y;
}
for(j=1;j<96;j++){
dep_prime[0] = dep[0];
pre_prime[0] = pre[0];
ec_pre( &k1_x , pre_prime[j-1] , dep_prime[j-1] , alpha_prime , beta_prime);
ec_dep( &k1_y , pre_prime[j-1] , dep_prime[j-1] , gamma_prime , delta_prime);
x1 = pre_prime[j-1] + (h/2.0) * k1_x;
y1 = dep_prime[j-1] + (h/2.0) * k1_y;
ec_pre( &k2_x , pre_prime[j-1] , dep_prime[j-1] , alpha_prime , beta_prime);
ec_dep( &k2_y , pre_prime[j-1] , dep_prime[j-1] , gamma_prime , delta_prime);
x2 = pre_prime[j-1] + (h/2.0) * k2_x;
y2 = dep_prime[j-1] + (h/2.0) * k2_y;
ec_pre( &k3_x , pre_prime[j-1] , dep_prime[j-1] , alpha_prime , beta_prime);
ec_dep( &k3_y , pre_prime[j-1] , dep_prime[j-1] , gamma_prime , delta_prime);
x3 = pre_prime[j-1] + h * k3_x;
y3 = dep_prime[j-1] + h * k3_y;
ec_pre( &k4_x , pre_prime[j-1] , dep_prime[j-1] , alpha_prime , beta_prime);
ec_dep( &k4_y , pre_prime[j-1] , dep_prime[j-1] , gamma_prime , delta_prime);
m_x = (1.0/6.0)*(k1_x + 2.0*k2_x + 2.0*k3_x + k4_x);
m_y = (1.0/6.0)*(k1_y + 2.0*k2_y + 2.0*k3_y + k4_y);
pre_prime[j] = pre_prime[j-1] + h * m_x;
dep_prime[j] = dep_prime[j-1] + h * m_y;
}
l_prime = likelihood( dep, dep_prime , n_row) + likelihood( pre , pre_prime , n_row);
l_init = likelihood( dep , dep_init , n_row) + likelihood( pre , pre_init , n_row);
gam = l_init - l_prime;
if (gam>=0.0) {
alpha_a[i+1] = alpha_prime;
beta_a[i+1] = beta_prime;
gamma_a[i+1] = gamma_prime;
delta_a[i+1] = delta_prime;
walk_a[i+1] = l_prime;
}
else{
bet = drand48();
alph = exp(gam);
if (bet <= alph) {
alpha_a[i+1] = alpha_prime;
beta_a[i+1] = beta_prime;
gamma_a[i+1] = gamma_prime;
delta_a[i+1] = delta_prime;
walk_a[i+1] = l_prime;
}
else{
alpha_a[i+1] = alpha_a[i];
beta_a[i+1] = beta_a[i];
gamma_a[i+1] = gamma_a[i];
delta_a[i+1] = delta_a[i];
walk_a[i+1] = l_prime;
}
}
}
j = min_likelihood( walk_a , n_row);
best_alpha = alpha_a[j];
best_beta = beta_a[j];
best_gamma = gamma_a[j];
best_delta = delta_a[j];
for(i=1;i<96;i++){
best_dep[0] = dep[0];
best_pre[0] = pre[0];
ec_pre( &k1_x , best_pre[i-1] , best_dep[i-1] , best_alpha , best_beta);
ec_dep( &k1_y , best_pre[i-1] , best_dep[i-1], best_gamma , best_delta);
x1 = fit_pre[i-1] + (h/2.0) * k1_x;
y1 = fit_dep[i-1] + (h/2.0) * k1_y;
ec_pre( &k2_x , best_pre[i-1] , best_dep[i-1] , best_alpha , best_beta);
ec_dep( &k2_y , best_pre[i-1] , best_dep[i-1] , best_gamma , best_delta);
x2 = fit_pre[i-1] + (h/2.0) * k2_x;
y2 = fit_dep[i-1] + (h/2.0) * k2_y;
ec_pre( &k3_x , best_pre[i-1] , best_dep[i-1], best_alpha , best_beta);
ec_dep( &k3_y , best_pre[i-1] , best_dep[i-1], best_gamma , best_delta);
x3 = fit_pre[i-1] + h * k3_x;
y3 = fit_dep[i-1] + h * k3_y;
ec_pre( &k4_x , best_pre[i-1] , best_dep[i-1], best_alpha , best_beta);
ec_dep( &k4_y , best_pre[i-1] , best_dep[i-1] , best_gamma , best_delta);
m_x = (1.0/6.0)*(k1_x + 2.0*k2_x + 2.0*k3_x + k4_x);
m_y = (1.0/6.0)*(k1_y + 2.0*k2_y + 2.0*k3_y + k4_y);
best_pre[i] = best_pre[i-1] + h * m_x;
best_dep[i-1] = best_dep[i-1] + h * m_y;
}
print_data( tim , pre, dep, best_pre , best_pre, walk_a , alpha_a , beta_a , gamma_a , delta_a , n_row);
gsl_rng_free (r);
return 0;
}
//------------------------------------------------------------------------------------------------------------
void load_matrix(char *filename, float *time, float *pre, float *dep , int n){
FILE *in;
int i;
in=fopen(filename,"r");
if(!in){
printf("problems opening the file %s\n", filename);
exit(1);
}
for(i=0;i<(n);i++){
fscanf(in, "%f %f %f\n", &time[i], &pre[i], &dep[i]);
}
fclose(in);
}
//------------------------------------------------------------------------------------------------------------
void print_data(float *array, float *array2 , float *array3 , float *array4 , float *array5 , float *array6, float *array7, float *array8 , float *array9 , float *array10 , int n_puntos){
int i;
for(i=0;i<n_puntos;i++){
printf("%f \t %f \t %f \t %f \t %f \t %f \t %f \t %f \t %f \t %f \n", array[i] , array2[i] , array3[i] , array4[i] , array5[i] , array6[i], array7[i] , array8[i] , array9[i] , array10[i]);
}
}
//------------------------------------------------------------------------------------------------------------
float *reserva(int n){
float *array;
int i;
if(!(array = malloc(n * sizeof(float)))){
printf("Problema en reserva\n");
exit(1);
}
for(i=0;i<n ;i++){
array[i] = 0.0;
}
return array;
}
//------------------------------------------------------------------------------------------------------------
int min_likelihood( float *array , int n_row){
int i;
int ind = 0;
for(i = 1; i < n_row; i ++){
if ( array[i] < ind) {
ind = i;
}
}
return ind;
}
//------------------------------------------------------------------------------------------------------------
void ec_pre(float *array, float x, float y, float alpha, float beta){
*array = x*(alpha - beta*y);
}
//------------------------------------------------------------------------------------------------------------
void ec_dep(float *array, float x, float y, float gamma, float delta){
*array = -y*(gamma - delta*x);
}
//------------------------------------------------------------------------------------------------------------
float likelihood(float *y_obs, float *y_model, int n_row){
int i;
float c=0;
for (i=0; i<n_row; i++) {
c = c + ( y_obs[i] - y_model[i]);
}
c = (1.0/2.0)*pow(c,2);
return c;
}
| {
"alphanum_fraction": 0.4479308413,
"avg_line_length": 31.8698979592,
"ext": "c",
"hexsha": "388443c1824a51453fa738fe78cd2936cfcc20a9",
"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": "0f0691365bfe3af6e0ba5d25f9f48cadc8df99fa",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JuanMolano/Hw7",
"max_forks_repo_path": "poblaciones/mcmc_lotkavolterra.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0f0691365bfe3af6e0ba5d25f9f48cadc8df99fa",
"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": "JuanMolano/Hw7",
"max_issues_repo_path": "poblaciones/mcmc_lotkavolterra.c",
"max_line_length": 196,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0f0691365bfe3af6e0ba5d25f9f48cadc8df99fa",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JuanMolano/Hw7",
"max_stars_repo_path": "poblaciones/mcmc_lotkavolterra.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3937,
"size": 12493
} |
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <mpfr.h>
#include <petsc.h>
#include "ellipsoid.h"
#include "../sphere/sphere.h"
#include "ellSolv.h"
#undef __FUNCT__
#define __FUNCT__ "InitEllipsoidalAndConvertPoints"
PetscErrorCode InitEllipsoidalAndConvertPoints(EllipsoidalSystem *e, PetscReal a, PetscReal b, PetscReal c, Vec xyz, Vec ell)
{
PetscErrorCode ierr;
PetscLogEvent initEvent;
PetscFunctionBegin;
ierr = PetscLogEventRegister("Init ellipsoidal system", 0, &initEvent);CHKERRQ(ierr);
ierr = PetscLogEventBegin(initEvent, 0, 0, 0, 0);CHKERRQ(ierr);
ierr = initEllipsoidalSystem(e, a, b, c, 32);CHKERRQ(ierr);
ierr = PetscLogEventEnd(initEvent, 0, 0, 0, 0);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "HowMany"
PetscErrorCode HowMany(PetscInt N, PetscInt *num)
{
PetscErrorCode ierr;
PetscInt n, p;
PetscFunctionBegin;
*num = 0;
for(n = 0; n <= N; ++n) {
for(p=0; p < 2*n + 1; ++p)
*num += 1;
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "CalcEllipsoidFreeEnergy"
PetscErrorCode CalcEllipsoidFreeEnergy(EllipsoidalSystem *e, PetscReal eps1, PetscReal eps2, PetscInt nSrc, Vec srcXYZ, Vec srcMag, PetscReal tol, PetscInt Nmax, Vec tarSol, PetscReal *freeE)
{
PetscErrorCode ierr;
PetscInt flopCount;
//EllipsoidalSystem e;
PetscReal x, y, z;
PetscInt n, p, npsize;
Vec srcEll, tarEll;
PetscScalar *tarEllArray;
Vec coulCoefs, reactCoefs, extCoefs;
const PetscScalar *coulCoefsArray, *reactCoefsArray, *extCoefsArray;
const PetscScalar *srcMagArray;
Vec EnpVals, FnpVals;
const PetscScalar *EnpValsArray, *FnpValsArray;
PetscScalar *tarSolArray;
PetscFunctionBegin;
flopCount = 0;
/* init ellipsoidal system */
//ierr = initEllipsoidalSystem(&e, a, b, c);CHKERRQ(ierr);
/* initialize expansion vectors */
ierr = HowMany(Nmax, &npsize);CHKERRQ(ierr);
//ierr = VecCreateSeq(PETSC_COMM_SELF, npsize, &coulCoefs);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, npsize, &reactCoefs);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, npsize, &extCoefs);CHKERRQ(ierr);
/* initialize point vectors */
ierr = VecDuplicate(srcXYZ, &srcEll);CHKERRQ(ierr);
ierr = VecDuplicate(srcEll, &tarEll);CHKERRQ(ierr);
/* convert points from cartesian to ellipsoidal */
ierr = CartesianToEllipsoidalVec(e, srcXYZ, srcEll);CHKERRQ(ierr);
ierr = VecCopy(srcEll, tarEll);CHKERRQ(ierr); //source+target same
/* Calculate Gnp */
ierr = CalcCoulombEllCoefs(e, nSrc, srcEll, srcMag, Nmax, &coulCoefs);CHKERRQ(ierr);
/* calculate Bnp and Cnp */
ierr = CalcReactAndExtCoefsFromCoulomb(e, eps1, eps2, Nmax, coulCoefs, reactCoefs, extCoefs);
// create EnpVals and FnpVals vectors
ierr = VecCreateSeq(PETSC_COMM_SELF, nSrc, &EnpVals);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, nSrc, &FnpVals);CHKERRQ(ierr);
// get read-only pointers for expansion coefficients
ierr = VecGetArrayRead(coulCoefs, &coulCoefsArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(reactCoefs, &reactCoefsArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(extCoefs, &extCoefsArray);CHKERRQ(ierr);
// get write pointer for solution vector
ierr = VecZeroEntries(tarSol);CHKERRQ(ierr);
ierr = VecGetArray(tarSol, &tarSolArray);CHKERRQ(ierr);
PetscInt ind = 0;
for(n=0; n <= Nmax; ++n) {
for(p=0; p < 2*n+1; ++p) {
PetscReal Gnp = coulCoefsArray[ind];
PetscReal Cnp = extCoefsArray[ind];
PetscReal Bnp = reactCoefsArray[ind];
ierr = CalcSolidInteriorHarmonicVec(e, tarEll, n, p, EnpVals);CHKERRQ(ierr);
//ierr = CalcSolidExteriorHarmonicVec(&e, tarEll, n, p, FnpVals);CHKERRQ(ierr);
ierr = VecGetArrayRead(EnpVals, &EnpValsArray);CHKERRQ(ierr);
//ierr = VecGetArrayRead(FnpVals, &FnpValsArray);CHKERRQ(ierr);
for(PetscInt k=0; k < nSrc; ++k) {
PetscReal Enp = EnpValsArray[k];
//PetscReal Fnp = FnpValsArray[k];
tarSolArray[k] += Bnp*Enp; flopCount += 2;
}
ierr = VecRestoreArrayRead(EnpVals, &EnpValsArray);CHKERRQ(ierr);
//ierr = VecRestoreArrayRead(FnpVals, &FnpValsArray);CHKERRQ(ierr);
ind++;
}
}
// get read-only pointers for expansion coefficients
ierr = VecRestoreArrayRead(coulCoefs, &coulCoefsArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(reactCoefs, &reactCoefsArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(extCoefs, &extCoefsArray);CHKERRQ(ierr);
*freeE = 0;
ierr = VecGetArrayRead(srcMag, &srcMagArray);CHKERRQ(ierr);
/* calculate free energy */
for(PetscInt k=0; k < nSrc; ++k) {
printf("sum[d] = %15.15f\n", srcMagArray[k]*tarSolArray[k]);
*freeE += srcMagArray[k]*tarSolArray[k];
}
ierr = VecRestoreArrayRead(srcMag, &srcMagArray);CHKERRQ(ierr);
ierr = VecRestoreArray(tarSol, &tarSolArray);CHKERRQ(ierr);
ierr = PetscLogFlops(flopCount);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "CalcEllipsoidTester"
PetscErrorCode CalcEllipsoidTester(PetscReal a, PetscReal b, PetscReal c, PetscReal eps1, PetscReal eps2, PetscInt nSrc, Vec srcXYZ, Vec srcMag, PetscInt nTar, Vec tarXYZ, PetscInt Nmax, Vec tarSol)
{
PetscErrorCode ierr;
EllipsoidalSystem e;
PetscReal x, y, z;
PetscInt n, p, npsize;
Vec srcEll, tarEll;
PetscScalar *tarEllArray;
Vec coulCoefs, reactCoefs, extCoefs;
const PetscScalar *coulCoefsArray, *reactCoefsArray, *extCoefsArray;
Vec EnpVals, FnpVals;
const PetscScalar *EnpValsArray, *FnpValsArray;
PetscScalar *tarSolArray;
PetscFunctionBegin;
/* init ellipsoidal system */
ierr = initEllipsoidalSystem(&e, a, b, c, 32);CHKERRQ(ierr);
/* initialize expansion vectors */
ierr = HowMany(Nmax, &npsize);CHKERRQ(ierr);
//ierr = VecCreateSeq(PETSC_COMM_SELF, npsize, &coulCoefs);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, npsize, &reactCoefs);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, npsize, &extCoefs);CHKERRQ(ierr);
/* initialize ellipsoid vectors */
ierr = VecDuplicate(srcXYZ, &srcEll);CHKERRQ(ierr);
ierr = VecDuplicate(tarXYZ, &tarEll);CHKERRQ(ierr);
/* convert points from cartesian to ellipsoidal */
ierr = CartesianToEllipsoidalVec(&e, srcXYZ, srcEll);CHKERRQ(ierr);
ierr = CartesianToEllipsoidalVec(&e, tarXYZ, tarEll);CHKERRQ(ierr);
/* Calculate Gnp */
ierr = CalcCoulombEllCoefs(&e, nSrc, srcEll, srcMag, Nmax, &coulCoefs);CHKERRQ(ierr);
//printf("\n\n##################################\n########## COUL COEFS #############\n###########################################\n\n");
//printf("nmax: %d\n", Nmax);
//ierr = VecView(coulCoefs, PETSC_VIEWER_STDOUT_SELF);CHKERRQ(ierr);
//printf("\n\n##################################\n########## OVER #############\n###########################################\n\n");
/* calculate Bnp and Cnp */
ierr = CalcReactAndExtCoefsFromCoulomb(&e, eps1, eps2, Nmax, coulCoefs, reactCoefs, extCoefs);
// create EnpVals and FnpVals vectors
ierr = VecCreateSeq(PETSC_COMM_SELF, nTar, &EnpVals);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, nTar, &FnpVals);CHKERRQ(ierr);
// get read-only pointers for expansion coefficients
ierr = VecGetArrayRead(coulCoefs, &coulCoefsArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(reactCoefs, &reactCoefsArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(extCoefs, &extCoefsArray);CHKERRQ(ierr);
// get write pointer for solution vector
ierr = VecZeroEntries(tarSol);CHKERRQ(ierr);
ierr = VecGetArray(tarSol, &tarSolArray);CHKERRQ(ierr);
PetscInt ind = 0;
for(n=0; n <= Nmax; ++n) {
printf("n: %d\n", n);
for(p=0; p < 2*n+1; ++p) {
PetscReal Gnp = coulCoefsArray[ind];
PetscReal Cnp = extCoefsArray[ind];
PetscReal Bnp = reactCoefsArray[ind];
ierr = CalcSolidInteriorHarmonicVec(&e, tarEll, n, p, EnpVals);CHKERRQ(ierr);
ierr = CalcSolidExteriorHarmonicVec(&e, tarEll, n, p, FnpVals);CHKERRQ(ierr);
ierr = VecGetArrayRead(EnpVals, &EnpValsArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(FnpVals, &FnpValsArray);CHKERRQ(ierr);
for(PetscInt k=0; k < nTar; ++k) {
if(n==0 && p==0) {
tarSolArray[k] = 0;
}
PetscReal lambda;
PetscInt index = 3*k+0;
ierr = VecGetValues(tarEll, 1, &index, &lambda);CHKERRQ(ierr);
PetscReal Enp = EnpValsArray[k];
PetscReal Fnp = FnpValsArray[k];
if(PetscAbsReal(lambda) <= a)
tarSolArray[k] += Bnp*Enp; //(Gnp/eps1)*Fnp;
else {
tarSolArray[k] += Cnp*Fnp;//(Gnp/eps1)*Fnp;
}
}
ierr = VecRestoreArrayRead(EnpVals, &EnpValsArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(FnpVals, &FnpValsArray);CHKERRQ(ierr);
ind++;
}
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "CalcEllipsoidCoulombPotential"
PetscErrorCode CalcEllipsoidCoulombPotential(PetscReal a, PetscReal b, PetscReal c, PetscReal eps1, PetscReal eps2, PetscInt nCharges, Vec chargeXYZ, Vec chargeMag, PetscInt nSol, Vec solXYZ, PetscInt Nmax, Vec targetSol)
{
PetscErrorCode ierr;
Vec chargeEll;
Vec solEll;
Vec coulCoefs;
Vec FnpVals;
EllipsoidalSystem e;
PetscScalar *vecPtr;
PetscScalar *coulCoefsArray;
PetscScalar *FnpValsArray;
PetscFunctionBegin;
ierr = initEllipsoidalSystem(&e, a, b, c, 32);CHKERRQ(ierr);
// create charge ellipsoidal vec and convert from xyz
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*nCharges, &chargeEll);CHKERRQ(ierr);
printf("Converting charge points to ellipsoidal\n");
ierr = CartesianToEllipsoidalVec(&e, chargeXYZ, chargeEll);CHKERRQ(ierr);
// create solution ellipsoidal vec and convert from xyz
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*nSol, &solEll);CHKERRQ(ierr);
printf("Converting solution points to ellipsoidal\n");
ierr = CartesianToEllipsoidalVec(&e, solXYZ, solEll);CHKERRQ(ierr);
//calculate coulomb coefficients
ierr = CalcCoulombEllCoefs(&e, nCharges, chargeEll, chargeMag, Nmax, &coulCoefs);CHKERRQ(ierr);
//initialize vector for interior harmonic calculations
ierr = VecCreateSeq(PETSC_COMM_SELF, nSol, &FnpVals);CHKERRQ(ierr);
ierr = VecGetArrayRead(coulCoefs, &coulCoefsArray);CHKERRQ(ierr);
ierr = VecGetArray(targetSol, &vecPtr);CHKERRQ(ierr);
PetscInt index = 0;
for(PetscInt n=0; n<=Nmax; ++n) {
for(PetscInt p=0; p < 2*n+1; ++p) {
//calculate Enp Vals
ierr = CalcSolidExteriorHarmonicVec(&e, solEll, n, p, FnpVals);CHKERRQ(ierr);
ierr = VecGetArrayRead(FnpVals, &FnpValsArray);CHKERRQ(ierr);
for(PetscInt k=0; k<nSol; ++k) {
vecPtr[k] += coulCoefsArray[index]*FnpValsArray[k];
}
ierr = VecRestoreArrayRead(FnpVals, &FnpValsArray);CHKERRQ(ierr);
index++;
}
}
ierr = VecRestoreArray(targetSol, &vecPtr);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(coulCoefs, &coulCoefsArray);CHKERRQ(ierr);
ierr = VecDestroy(&solEll);CHKERRQ(ierr);
ierr = VecDestroy(&chargeEll);CHKERRQ(ierr);
ierr = VecDestroy(&coulCoefs);CHKERRQ(ierr);
ierr = VecDestroy(&FnpVals);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "CalcEllipsoidSolvationPotential"
PetscErrorCode CalcEllipsoidSolvationPotential(PetscReal a, PetscReal b, PetscReal c, PetscReal eps1, PetscReal eps2, PetscInt nSource, Vec sourceXYZ, Vec sourceMag, PetscInt nTarget, Vec targetXYZ, PetscInt Nmax, Vec targetSol)
{
PetscErrorCode ierr;
EllipsoidalSystem e;
PetscReal x, y, z;
PetscInt n, p;
PetscInt intPts, extPts;
Vec tarIntXYZ, tarExtXYZ;
PetscScalar *tarIntXYZArray, *tarExtXYZArray;
Vec tarIntEll, tarExtEll;
Vec srcEll, tarEll;
Vec coulCoefs, reactCoefs, extCoefs;
Vec EnpVals, FnpVals;
PetscInt *isExt;
const PetscScalar *targetXYZArray, *coulCoefsArray, *reactCoefsArray, *extCoefsArray;
PetscScalar *targetSolArray;
const PetscScalar *EnpValsArray, *FnpValsArray;
//PetscLogStage stageIntSolids, stageExtSolids;
PetscLogEvent *INTERIOR_FLOPS;
PetscLogEvent *EXTERIOR_FLOPS;
//PetscLogDouble user_log_flops;
PetscFunctionBegin;
ierr = initEllipsoidalSystem(&e, a, b, c, 32);CHKERRQ(ierr);
// calculate the number of interior and exterior points
ierr = VecGetArrayRead(targetXYZ, &targetXYZArray);CHKERRQ(ierr);
intPts = 0; extPts = 0;
for(int k=0; k < nTarget; ++k) {
x = targetXYZArray[3*k+0];
y = targetXYZArray[3*k+1];
z = targetXYZArray[3*k+2];
if((x*x)/(a*a) + (y*y)/(b*b) + (z*z)/(c*c) <= 1)
intPts++;
else
extPts++;
}
// init interior and exterior target point vectors
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*intPts, &tarIntXYZ);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*extPts, &tarExtXYZ);CHKERRQ(ierr);
// sort points into int and ext vectors
ierr = VecGetArray(tarIntXYZ, &tarIntXYZArray);CHKERRQ(ierr);
ierr = VecGetArray(tarExtXYZ, &tarExtXYZArray);CHKERRQ(ierr);
ierr = PetscMalloc1(sizeof(PetscInt)*nTarget, &isExt);CHKERRQ(ierr);
intPts = 0; extPts = 0;
for(int k=0; k < nTarget; ++k) {
x = targetXYZArray[3*k+0];
y = targetXYZArray[3*k+1];
z = targetXYZArray[3*k+2];
if((x*x)/(a*a) + (y*y)/(b*b) + (z*z)/(c*c) <= 1) {
tarIntXYZArray[3*intPts+0] = x;
tarIntXYZArray[3*intPts+1] = y;
tarIntXYZArray[3*intPts+2] = z;
isExt[k] = 0;
intPts++;
}
else {
tarExtXYZArray[3*extPts+0] = x;
tarExtXYZArray[3*extPts+1] = y;
tarExtXYZArray[3*extPts+2] = z;
isExt[k] = 1;
extPts++;
}
}
ierr = VecRestoreArray(tarIntXYZ, &tarIntXYZArray);CHKERRQ(ierr);
ierr = VecRestoreArray(tarExtXYZ, &tarExtXYZArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(targetXYZ, &targetXYZArray);CHKERRQ(ierr);
// create source ellipsoidal vec and convert from xyz
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*nSource, &srcEll);CHKERRQ(ierr);
ierr = CartesianToEllipsoidalVec(&e, sourceXYZ, srcEll);CHKERRQ(ierr);
// create target ellipsoidal vec and convert from xyz
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*nTarget, &tarEll);CHKERRQ(ierr);
ierr = CartesianToEllipsoidalVec(&e, targetXYZ, tarEll);CHKERRQ(ierr);
// create target interior ellipsoidal vec and convert from xyz
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*intPts, &tarIntEll);CHKERRQ(ierr);
ierr = CartesianToEllipsoidalVec(&e, tarIntXYZ, tarIntEll);CHKERRQ(ierr);
// create target exterior ellipsoidal vec and convert from xyz
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*extPts, &tarExtEll);CHKERRQ(ierr);
ierr = CartesianToEllipsoidalVec(&e, tarExtXYZ, tarExtEll);CHKERRQ(ierr);
// calculate coulomb coefficients
ierr = CalcCoulombEllCoefs(&e, nSource, srcEll, sourceMag, Nmax, &coulCoefs);CHKERRQ(ierr);
// init reacCoefs, extCoefs from size of coulCoefs
ierr = VecDuplicate(coulCoefs, &reactCoefs);CHKERRQ(ierr);
ierr = VecDuplicate(coulCoefs, &extCoefs);CHKERRQ(ierr);
// calc reaction and exterior expansion coefs from coulomb coefs
ierr = CalcReactAndExtCoefsFromCoulomb(&e, eps1, eps2, Nmax, coulCoefs, reactCoefs, extCoefs);
// create EnpVals and FnpVals vectors
ierr = VecCreateSeq(PETSC_COMM_SELF, intPts, &EnpVals);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, extPts, &FnpVals);CHKERRQ(ierr);
// get read-only pointers for expansion coefficients
ierr = VecGetArrayRead(coulCoefs, &coulCoefsArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(reactCoefs, &reactCoefsArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(extCoefs, &extCoefsArray);CHKERRQ(ierr);
// get write pointer for solution vector
ierr = VecZeroEntries(targetSol);CHKERRQ(ierr);
ierr = VecGetArray(targetSol, &targetSolArray);CHKERRQ(ierr);
// loop
PetscInt howmany = 0;
for(n=0; n <= Nmax; ++n) {
for(p=0; p < 2*n+1; ++p)
howmany++;
}
ierr = PetscMalloc1(sizeof(PetscLogEvent)*howmany, &INTERIOR_FLOPS);CHKERRQ(ierr);
ierr = PetscMalloc1(sizeof(PetscLogEvent)*howmany, &EXTERIOR_FLOPS);CHKERRQ(ierr);
char intStr[40] = "Interior Harmonic %d";
char extStr[40] = "Exterior Harmonic %d";
char indvIntStr[40];
char indvExtStr[40];
for(n=0; n<howmany; ++n) {
sprintf(indvIntStr, intStr, n);
sprintf(indvExtStr, extStr, n);
ierr = PetscLogEventRegister(indvIntStr, 0, INTERIOR_FLOPS+n);CHKERRQ(ierr);
ierr = PetscLogEventRegister(indvExtStr, 0, EXTERIOR_FLOPS+n);CHKERRQ(ierr);
}
PetscInt ind = 0;
PetscInt intInd;
PetscInt extInd;
for(n=0; n <= Nmax; ++n) {
printf("%d/%d\n", n, Nmax);
for(p=0; p < 2*n+1; ++p) {
PetscReal Gnp = coulCoefsArray[ind];
PetscReal Cnp = extCoefsArray[ind];
PetscReal Bnp = reactCoefsArray[ind];
// calc solid harmonics for interior,exterior points
//ierr = PetscLogStagePush(stageIntSolids);CHKERRQ(ierr);
ierr = PetscLogEventBegin(INTERIOR_FLOPS[ind],0,0,0,0);CHKERRQ(ierr);
ierr = CalcSolidInteriorHarmonicVec(&e, tarIntEll, n, p, EnpVals);CHKERRQ(ierr);
ierr = PetscLogEventEnd (INTERIOR_FLOPS[ind],0,0,0,0);CHKERRQ(ierr);
//ierr = PetscLogStagePop();
//ierr = PetscLogStagePush(stageExtSolids);CHKERRQ(ierr);
ierr = PetscLogEventBegin(EXTERIOR_FLOPS[ind],0,0,0,0);CHKERRQ(ierr);
ierr = CalcSolidExteriorHarmonicVec(&e, tarExtEll, n, p, FnpVals);CHKERRQ(ierr);
ierr = PetscLogEventEnd(EXTERIOR_FLOPS[ind],0,0,0,0);CHKERRQ(ierr);
//ierr = PetscLogStagePop();CHKERRQ(ierr);
ierr = VecGetArrayRead(EnpVals, &EnpValsArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(FnpVals, &FnpValsArray);CHKERRQ(ierr);
intInd = 0;
extInd = 0;
for(PetscInt k=0; k<nTarget; ++k) {
if(isExt[k] == 0) { // interior points
//printf("E%d%d: %15.15f\nBnp %d%d: %15.15f\n\n", n, p, n, p, EnpValsArray[intInd], reactCoefsArray[ind]);
targetSolArray[k] += reactCoefsArray[ind]*EnpValsArray[intInd];
//ierr = CalcSolidInterior
//targetSolArray[k] += Gnp*EnpValsArray[intInd];
//targetSolArray[k] += 1;
intInd++;
}
else { // exterior points
//printf("F%d%d: %15.15f\nCnp %d%d: %15.15f\n\n", n, p, n, p, FnpValsArray[intInd], extCoefsArray[ind]);
//targetSolArray[k] += extCoefsArray[ind]*FnpValsArray[extInd];
//targetSolArray[k] += (Gnp*FnpValsArray[extInd])/eps1;
targetSolArray[k] += 0;
extInd++;
}
}
ierr = VecRestoreArrayRead(EnpVals, &EnpValsArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(FnpVals, &FnpValsArray);CHKERRQ(ierr);
ind++;
}
}
//ierr = PetscLogEventEnd(SOLID_FLOPS, 0, 0, 0, 0);
ierr = VecRestoreArray(targetSol, &targetSolArray);CHKERRQ(ierr);
// restore read-only pointers for expansion coefficients
ierr = VecRestoreArrayRead(coulCoefs , &coulCoefsArray );CHKERRQ(ierr);
ierr = VecRestoreArrayRead(reactCoefs, &reactCoefsArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(extCoefs , &extCoefsArray );CHKERRQ(ierr);
//output flops to file
FILE *fpext = fopen("flopsext.txt", "w");
FILE *fpint = fopen("flopsint.txt", "w");
PetscStageLog stageLog;
ierr = PetscLogGetStageLog(&stageLog);CHKERRQ(ierr);
/*
for(int i=0; i<howmany; ++i) {
fprintf(fpext, "Ext %d = %.4e\n", i, stageLog->stageInfo[stageExtSolids].eventLog->eventInfo[EXTERIOR_FLOPS[i]].flops);
fprintf(fpint, "Int %d = %.4e\n", i, stageLog->stageInfo[stageIntSolids].eventLog->eventInfo[INTERIOR_FLOPS[i]].flops);
}
*/
ierr = VecDestroy(&tarIntXYZ);CHKERRQ(ierr);CHKERRQ(ierr);
ierr = VecDestroy(&tarExtXYZ);CHKERRQ(ierr);CHKERRQ(ierr);
ierr = VecDestroy(&tarIntEll);CHKERRQ(ierr);CHKERRQ(ierr);
ierr = VecDestroy(&tarExtEll);CHKERRQ(ierr);CHKERRQ(ierr);
ierr = VecDestroy(&srcEll);CHKERRQ(ierr);CHKERRQ(ierr);
ierr = VecDestroy(&tarEll);CHKERRQ(ierr);CHKERRQ(ierr);
ierr = VecDestroy(&coulCoefs);CHKERRQ(ierr);
ierr = VecDestroy(&reactCoefs);CHKERRQ(ierr);
ierr = VecDestroy(&extCoefs);CHKERRQ(ierr);
ierr = VecDestroy(&EnpVals); CHKERRQ(ierr);
ierr = VecDestroy(&FnpVals); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "CalcSolidInteriorHarmonic"
PetscErrorCode CalcSolidInteriorHarmonic(EllipsoidalSystem* e, PetscReal lambda, PetscReal mu, PetscReal nu, PetscInt n, PetscInt p, PetscReal *val)
{
PetscErrorCode ierr;
PetscInt signm = 1;
PetscInt signn = 1;
PetscReal eL, eM, eN;
PetscFunctionBegin;
if(mu < 0)
signm = -1;
if(nu < 0)
signn = -1;
calcLame(e, n, p, lambda, signm, signn, &eL);
calcLame(e, n, p, mu, signm, signn, &eM);
calcLame(e, n, p, nu, signm, signn, &eN);
*val = eL*eM*eN;
ierr= PetscLogFlops(3);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "CalcSolidInteriorHarmonicVec"
/*
ellPoints is ellPoints of size 3*nPoints containing ellipsoidal coordinates
outputs solid harmonics to values of size nPoints
*/
PetscErrorCode CalcSolidInteriorHarmonicVec(EllipsoidalSystem* e, Vec ellPoints, PetscInt n, PetscInt p, Vec values)
{
PetscErrorCode ierr;
PetscInt signm = 1;
PetscInt signn = 1;
PetscInt nPoints;
PetscReal lambda, mu, nu;
PetscReal eL, eM, eN;
PetscReal Enp;
const PetscScalar* ellPointsArray;
PetscFunctionBegin;
ierr = VecGetSize(ellPoints, &nPoints);CHKERRQ(ierr);
nPoints = nPoints/3;
ierr = VecGetArrayRead(ellPoints, &ellPointsArray); CHKERRQ(ierr);
for(PetscInt k=0; k<nPoints; ++k) {
lambda = ellPointsArray[3*k+0];
mu = ellPointsArray[3*k+1];
nu = ellPointsArray[3*k+2];
if(mu < 0)
signm = -1;
else signm = 1;
if(nu < 0)
signn = -1;
else signn = 1;
ierr = calcLame(e, n, p, lambda, signm, signn, &eL);
ierr = calcLame(e, n, p, mu, signm, signn, &eM);
ierr = calcLame(e, n, p, nu, signm, signn, &eN);
Enp = eL*eM*eN;
ierr = VecSetValue(values, k, Enp, INSERT_VALUES); CHKERRQ(ierr);
}
ierr = VecAssemblyBegin(values); CHKERRQ(ierr);
ierr = VecAssemblyEnd(values); CHKERRQ(ierr);
ierr = VecRestoreArrayRead(ellPoints, &ellPointsArray); CHKERRQ(ierr);
ierr = PetscLogFlops(3*nPoints);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "CalcSolidExteriorHarmonic"
PetscErrorCode CalcSolidExteriorHarmonic(EllipsoidalSystem *e, PetscReal lambda, PetscReal mu, PetscReal nu, PetscInt n, PetscInt p, PetscReal *val)
{
PetscErrorCode ierr;
PetscReal Enp, Inp;
PetscInt signm;
PetscInt signn;
PetscFunctionBegin;
if(mu < 0)
signm = -1;
else signm = 1;
if(nu < 0)
signn = -1;
else signn = 1;
ierr = CalcSolidInteriorHarmonic(e, lambda, mu, nu, n, p, &Enp);CHKERRQ(ierr);
ierr = calcI(e, n, p, lambda, signm, signn, &Inp);CHKERRQ(ierr);
*val = (2*n + 1) * Enp * Inp;
PetscLogFlops(4);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "CalcSolidExteriorHarmonicVec"
PetscErrorCode CalcSolidExteriorHarmonicVec(EllipsoidalSystem* e, Vec ellPoints, PetscInt n, PetscInt p, Vec values)
{
PetscErrorCode ierr;
PetscReal Enp, Inp, Fnp;
PetscReal lambda, mu, nu;
PetscInt signm;
PetscInt signn;
PetscInt nPoints;
const PetscScalar* ellPointsArray;
PetscFunctionBegin;
ierr = VecGetSize(ellPoints, &nPoints);CHKERRQ(ierr);
nPoints = nPoints/3;
ierr = VecGetArrayRead(ellPoints, &ellPointsArray);CHKERRQ(ierr);
for(PetscInt k=0; k<nPoints; ++k) {
lambda = ellPointsArray[3*k+0];
mu = ellPointsArray[3*k+1];
nu = ellPointsArray[3*k+2];
if(mu < 0)
signm = -1;
else signm = 1;
if(nu < 0)
signn = -1;
else signn = 1;
ierr = CalcSolidInteriorHarmonic(e, lambda, mu, nu, n, p, &Enp);CHKERRQ(ierr);
ierr = calcI(e, n, p, lambda, signm, signn, &Inp);CHKERRQ(ierr);
Fnp = (2*n + 1) * Enp * Inp;
ierr = VecSetValues(values, 1, &k, &Fnp, INSERT_VALUES);CHKERRQ(ierr);
}
ierr = VecAssemblyBegin(values);CHKERRQ(ierr); ierr = VecAssemblyEnd(values);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(ellPoints, &ellPointsArray);CHKERRQ(ierr);
ierr = PetscLogFlops(4*nPoints);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "CalcCoulombEllCoefs"
/*
GnpVals should be uninitialized. I
*/
PetscErrorCode CalcCoulombEllCoefs(EllipsoidalSystem* e, PetscInt nSource, Vec srcPoints, Vec srcCharges, PetscInt Nmax, Vec* GnpVals)
{
PetscErrorCode ierr;
PetscReal normConstant;
PetscReal Gnp;
PetscInt count;
Vec EnpVals;
const PetscScalar* EnpValsArray;
const PetscScalar* srcPointsArray;
const PetscScalar* srcChargesArray;
PetscFunctionBegin;
ierr = VecCreateSeq(PETSC_COMM_SELF, nSource, &EnpVals);CHKERRQ(ierr);
count = 0;
for(PetscInt n=0; n<=Nmax; ++n) {
for(PetscInt p=0; p<2*n+1; ++p)
count++;
}
//ierr = VecDestroy(GnpVals);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, count, GnpVals);CHKERRQ(ierr);
ierr = VecGetArrayRead(srcCharges, &srcChargesArray);CHKERRQ(ierr);
count = 0;
for(PetscInt n=0; n<=Nmax; ++n) {
for(PetscInt p=0; p<2*n+1; ++p) {
ierr = calcNormalization(e, n, p, &normConstant);CHKERRQ(ierr);
ierr = CalcSolidInteriorHarmonicVec(e, srcPoints, n, p, EnpVals);
ierr = VecGetArrayRead(EnpVals, &EnpValsArray);CHKERRQ(ierr);
Gnp = 0;
for(PetscInt k=0; k<nSource; ++k) {
Gnp += srcChargesArray[k]*EnpValsArray[k];
}
ierr = VecRestoreArrayRead(EnpVals, &EnpValsArray);CHKERRQ(ierr);
Gnp *= (4*PETSC_PI)/((2.0*n+1.0)*normConstant);
ierr = VecSetValues(*GnpVals, 1, &count, &Gnp, INSERT_VALUES);CHKERRQ(ierr);
count++;
}
}
ierr = VecAssemblyBegin(*GnpVals);CHKERRQ(ierr); ierr = VecAssemblyEnd(*GnpVals);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(srcCharges, &srcChargesArray);CHKERRQ(ierr);
ierr = VecDestroy(&EnpVals); CHKERRQ(ierr);
ierr = PetscLogFlops(count * (6 + 3*nSource));CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "CalcReactAndExtCoefsFromCoulomb"
PetscErrorCode CalcReactAndExtCoefsFromCoulomb(EllipsoidalSystem* e, PetscReal eps1, PetscReal eps2, PetscInt Nmax, Vec coulCoefs, Vec reacCoefs, Vec extCoefs)
{
PetscErrorCode ierr;
PetscReal Ea , Ia , Fa;
PetscReal EaDer, IaDer, FaDer;
PetscReal Gnp, Bnp, Cnp;
PetscReal temp;
const PetscScalar* coulCoefsArray;
PetscInt count;
PetscFunctionBegin;
ierr = VecGetArrayRead(coulCoefs, &coulCoefsArray);CHKERRQ(ierr);
count = 0;
for(PetscInt n=0; n<=Nmax; ++n) {
for(PetscInt p=0; p<2*n+1; ++p) {
Gnp = coulCoefsArray[count];
ierr = calcLame(e, n, p, e->a, 1, 1, &Ea);CHKERRQ(ierr);
ierr = calcI (e, n, p, e->a, 1, 1, &Ia);CHKERRQ(ierr);
Fa = (2*n + 1) * Ea * Ia;
calcLameDerivative(e, n, p, e->a, 1, 1, &EaDer);
calcIDerivative (e, n, p, e->a, 1, 1, &IaDer);
FaDer = (2*n + 1) * (Ea*IaDer + EaDer*Ia);
temp = (Fa/Ea)*(eps1 - eps2)/(eps1*eps2);
temp /= (1 - (eps1/eps2)*((EaDer*Fa)/(FaDer*Ea)));
Bnp = temp*Gnp;
Cnp = (eps1/eps2)*(EaDer/FaDer)*Bnp;
Cnp += (Gnp/eps2);
ierr = VecSetValues(reacCoefs, 1, &count, &Bnp, INSERT_VALUES);CHKERRQ(ierr);
ierr = VecSetValues(extCoefs, 1, &count, &Cnp, INSERT_VALUES);CHKERRQ(ierr);
count++;
}
}
ierr = VecAssemblyBegin(reacCoefs);CHKERRQ(ierr);
ierr = VecAssemblyEnd (reacCoefs);CHKERRQ(ierr);
ierr = VecAssemblyBegin(extCoefs);CHKERRQ(ierr);
ierr = VecAssemblyEnd (extCoefs);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(coulCoefs, &coulCoefsArray);CHKERRQ(ierr);
ierr = PetscLogFlops(29*count);
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.6895202574,
"avg_line_length": 35.6558018253,
"ext": "c",
"hexsha": "ea85ccd6b74b5c9ae27b5e7b911e19aaed4fe3db",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "tom-klotz/ellipsoid-solvation",
"max_forks_repo_path": "src/ellipsoid/ellSolvPetsc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "tom-klotz/ellipsoid-solvation",
"max_issues_repo_path": "src/ellipsoid/ellSolvPetsc.c",
"max_line_length": 228,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "tom-klotz/ellipsoid-solvation",
"max_stars_repo_path": "src/ellipsoid/ellSolvPetsc.c",
"max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z",
"num_tokens": 8857,
"size": 27348
} |
/*
* Copyright (c) 1997-1999 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/* This file was automatically generated --- DO NOT EDIT */
/* Generated on Sun Nov 7 20:45:10 EST 1999 */
#include <fftw-int.h>
#include <fftw.h>
/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2hc-backward 4 */
/*
* This function contains 34 FP additions, 18 FP multiplications,
* (or, 28 additions, 12 multiplications, 6 fused multiply/add),
* 15 stack variables, and 32 memory accesses
*/
static const fftw_real K1_414213562 = FFTW_KONST(+1.414213562373095048801688724209698078569671875);
static const fftw_real K2_000000000 = FFTW_KONST(+2.000000000000000000000000000000000000000000000);
/*
* Generator Id's :
* $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $
* $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $
* $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $
*/
void fftw_hc2hc_backward_4(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 + (4 * iostride);
{
fftw_real tmp39;
fftw_real tmp42;
fftw_real tmp37;
fftw_real tmp40;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp38;
fftw_real tmp41;
fftw_real tmp35;
fftw_real tmp36;
ASSERT_ALIGNED_DOUBLE;
tmp38 = X[iostride];
tmp39 = K2_000000000 * tmp38;
tmp41 = Y[-iostride];
tmp42 = K2_000000000 * tmp41;
tmp35 = X[0];
tmp36 = X[2 * iostride];
tmp37 = tmp35 + tmp36;
tmp40 = tmp35 - tmp36;
}
X[2 * iostride] = tmp37 - tmp39;
X[0] = tmp37 + tmp39;
X[3 * iostride] = tmp40 + tmp42;
X[iostride] = tmp40 - tmp42;
}
X = X + dist;
Y = Y - dist;
for (i = 2; i < m; i = i + 2, X = X + dist, Y = Y - dist, W = W + 3) {
fftw_real tmp9;
fftw_real tmp28;
fftw_real tmp18;
fftw_real tmp25;
fftw_real tmp12;
fftw_real tmp24;
fftw_real tmp21;
fftw_real tmp29;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp7;
fftw_real tmp8;
fftw_real tmp16;
fftw_real tmp17;
ASSERT_ALIGNED_DOUBLE;
tmp7 = X[0];
tmp8 = Y[-2 * iostride];
tmp9 = tmp7 + tmp8;
tmp28 = tmp7 - tmp8;
tmp16 = Y[0];
tmp17 = X[2 * iostride];
tmp18 = tmp16 - tmp17;
tmp25 = tmp16 + tmp17;
}
{
fftw_real tmp10;
fftw_real tmp11;
fftw_real tmp19;
fftw_real tmp20;
ASSERT_ALIGNED_DOUBLE;
tmp10 = X[iostride];
tmp11 = Y[-3 * iostride];
tmp12 = tmp10 + tmp11;
tmp24 = tmp10 - tmp11;
tmp19 = Y[-iostride];
tmp20 = X[3 * iostride];
tmp21 = tmp19 - tmp20;
tmp29 = tmp19 + tmp20;
}
X[0] = tmp9 + tmp12;
{
fftw_real tmp14;
fftw_real tmp22;
fftw_real tmp13;
fftw_real tmp15;
ASSERT_ALIGNED_DOUBLE;
tmp14 = tmp9 - tmp12;
tmp22 = tmp18 - tmp21;
tmp13 = c_re(W[1]);
tmp15 = c_im(W[1]);
X[2 * iostride] = (tmp13 * tmp14) + (tmp15 * tmp22);
Y[-iostride] = (tmp13 * tmp22) - (tmp15 * tmp14);
}
Y[-3 * iostride] = tmp18 + tmp21;
{
fftw_real tmp26;
fftw_real tmp30;
fftw_real tmp23;
fftw_real tmp27;
ASSERT_ALIGNED_DOUBLE;
tmp26 = tmp24 + tmp25;
tmp30 = tmp28 - tmp29;
tmp23 = c_re(W[0]);
tmp27 = c_im(W[0]);
Y[-2 * iostride] = (tmp23 * tmp26) - (tmp27 * tmp30);
X[iostride] = (tmp27 * tmp26) + (tmp23 * tmp30);
}
{
fftw_real tmp32;
fftw_real tmp34;
fftw_real tmp31;
fftw_real tmp33;
ASSERT_ALIGNED_DOUBLE;
tmp32 = tmp25 - tmp24;
tmp34 = tmp28 + tmp29;
tmp31 = c_re(W[2]);
tmp33 = c_im(W[2]);
Y[0] = (tmp31 * tmp32) - (tmp33 * tmp34);
X[3 * iostride] = (tmp33 * tmp32) + (tmp31 * tmp34);
}
}
if (i == m) {
fftw_real tmp1;
fftw_real tmp2;
fftw_real tmp3;
fftw_real tmp4;
fftw_real tmp5;
fftw_real tmp6;
ASSERT_ALIGNED_DOUBLE;
tmp1 = X[0];
tmp2 = X[iostride];
tmp3 = tmp1 - tmp2;
tmp4 = Y[0];
tmp5 = Y[-iostride];
tmp6 = tmp4 + tmp5;
X[0] = K2_000000000 * (tmp1 + tmp2);
X[2 * iostride] = -(K2_000000000 * (tmp4 - tmp5));
X[iostride] = K1_414213562 * (tmp3 - tmp6);
X[3 * iostride] = -(K1_414213562 * (tmp3 + tmp6));
}
}
static const int twiddle_order[] =
{1, 2, 3};
fftw_codelet_desc fftw_hc2hc_backward_4_desc =
{
"fftw_hc2hc_backward_4",
(void (*)()) fftw_hc2hc_backward_4,
4,
FFTW_BACKWARD,
FFTW_HC2HC,
102,
3,
twiddle_order,
};
| {
"alphanum_fraction": 0.5903856699,
"avg_line_length": 28.2010309278,
"ext": "c",
"hexsha": "d49e039a61d32d44cad6e6d131cfd8b6b4e769c7",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z",
"max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "albertsgrc/ftdock-opt",
"max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_4.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "albertsgrc/ftdock-opt",
"max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_4.c",
"max_line_length": 125,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "albertsgrc/ftdock-opt",
"max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_4.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": 1805,
"size": 5471
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#pragma once
#include <gsl/gsl-lite.hpp>
#include <nlohmann/json_fwd.hpp>
#include <cstdint>
#include <string>
namespace cb::crypto {
enum class Algorithm { MD5, SHA1, SHA256, SHA512 };
bool isSupported(Algorithm algorithm);
const int MD5_DIGEST_SIZE = 16;
const int SHA1_DIGEST_SIZE = 20;
const int SHA256_DIGEST_SIZE = 32;
const int SHA512_DIGEST_SIZE = 64;
/**
* Generate a HMAC digest of the key and data by using the given
* algorithm
*
* @throws std::invalid_argument - unsupported algorithm
* std::runtime_error - Failures generating the HMAC
*/
std::string HMAC(Algorithm algorithm,
std::string_view key,
std::string_view data);
/**
* Generate a PBKDF2_HMAC digest of the key and data by using the given
* algorithm
*
* @throws std::invalid_argument - unsupported algorithm
* std::runtime_error - Failures generating the HMAC
*/
std::string PBKDF2_HMAC(Algorithm algorithm,
std::string_view pass,
std::string_view salt,
unsigned int iterationCount);
/**
* Generate a digest by using the requested algorithm
*/
std::string digest(Algorithm algorithm, std::string_view data);
} // namespace cb::crypto
| {
"alphanum_fraction": 0.6818443804,
"avg_line_length": 30.4385964912,
"ext": "h",
"hexsha": "2e8026419794f4e8db1cd810ddb3c320e62375b2",
"lang": "C",
"max_forks_count": 71,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z",
"max_forks_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd",
"max_forks_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_forks_repo_name": "nawazish-couchbase/kv_engine",
"max_forks_repo_path": "include/cbcrypto/cbcrypto.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd",
"max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z",
"max_issues_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_issues_repo_name": "nawazish-couchbase/kv_engine",
"max_issues_repo_path": "include/cbcrypto/cbcrypto.h",
"max_line_length": 79,
"max_stars_count": 104,
"max_stars_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd",
"max_stars_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_stars_repo_name": "nawazish-couchbase/kv_engine",
"max_stars_repo_path": "include/cbcrypto/cbcrypto.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z",
"num_tokens": 407,
"size": 1735
} |
/* movstat/movmad.c
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_movstat.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_statistics.h>
/*
gsl_movstat_mad()
Apply a moving MAD to an input vector (with scale factor to make an
unbiased estimate of sigma)
Inputs: endtype - how to handle end points
x - input vector, size n
xmedian - (output) vector of median values of x, size n
xmedian_i = median of window centered on x_i
xmad - (output) vector of estimated standard deviations of x, size n
xmad_i = MAD of i-th window: 1.4826 * median(|x_i - xmedian_i|)
w - workspace
*/
int
gsl_movstat_mad(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * xmedian, gsl_vector * xmad,
gsl_movstat_workspace * w)
{
if (x->size != xmedian->size)
{
GSL_ERROR("x and xmedian vectors must have same length", GSL_EBADLEN);
}
else if (x->size != xmad->size)
{
GSL_ERROR("x and xmad vectors must have same length", GSL_EBADLEN);
}
else
{
double scale = 1.482602218505602;
int status = gsl_movstat_apply_accum(endtype, x, gsl_movstat_accum_mad, &scale, xmedian, xmad, w);
return status;
}
}
/*
gsl_movstat_mad0()
Apply a moving MAD to an input vector (without scale factor to make an
unbiased estimate of sigma)
Inputs: endtype - how to handle end points
x - input vector, size n
xmedian - (output) vector of median values of x, size n
xmedian_i = median of window centered on x_i
xmad - (output) vector of estimated standard deviations of x, size n
xmad_i = MAD of i-th window: median(|x_i - xmedian_i|)
w - workspace
*/
int
gsl_movstat_mad0(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * xmedian, gsl_vector * xmad,
gsl_movstat_workspace * w)
{
if (x->size != xmedian->size)
{
GSL_ERROR("x and xmedian vectors must have same length", GSL_EBADLEN);
}
else if (x->size != xmad->size)
{
GSL_ERROR("x and xmad vectors must have same length", GSL_EBADLEN);
}
else
{
double scale = 1.0;
int status = gsl_movstat_apply_accum(endtype, x, gsl_movstat_accum_mad, &scale, xmedian, xmad, w);
return status;
}
}
| {
"alphanum_fraction": 0.6663565891,
"avg_line_length": 33.2474226804,
"ext": "c",
"hexsha": "d1b7233eff64cc349e5551eb9ec9635b043ffd63",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/movstat/movmad.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/movstat/movmad.c",
"max_line_length": 112,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/movstat/movmad.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": 864,
"size": 3225
} |
//
// Created by root on 14.03.20.
//
#ifndef NETWORK_NETWORK_H
#define NETWORK_NETWORK_H
#include <memory>
#include <vector>
#include <functional>
#include <cblas.h>
#include <iostream>
#include <random>
#include "cmake-build-debug/data.pb.h"
#include "Utils.h"
extern std::mt19937 generator;
struct Layer {
std::unique_ptr<float[]> weights;
std::unique_ptr<float[]> biases;
std::unique_ptr<float[]> pre_activ;
std::unique_ptr<float[]> post_activ;
std::unique_ptr<float[]> deltas;
size_t num_rows;
size_t num_cols;
std::function<void()> activation;
std::function<void(float *, float *)> derivative;
void forward_pass(float *input);
};
class Network {
private:
std::vector<Layer> layers;
size_t input_size;
//looking over backprop implementation
//Something is not working correctly
template<typename Loss>
void back_propagate(float *act_output) {
{
Layer ¤t = get_output_layer();
const size_t out_neurons = current.num_rows;
std::unique_ptr<float[]> loss_deriv = std::make_unique<float[]>(out_neurons);
//Computing the derivative of the loss function with respect to the net_output
Loss::apply_deriv(current.post_activ.get(), current.post_activ.get() + out_neurons,
act_output, loss_deriv.get());
current.derivative(current.pre_activ.get(), current.deltas.get());
std::transform(current.deltas.get(), current.deltas.get() + out_neurons, loss_deriv.get(),
current.deltas.get(), std::multiplies<float>{});
}
//stuff for all the other layers
for (int l = layers.size() - 2; l >= 0; --l) {
Layer &last = layers[l + 1];
Layer ¤t = layers[l];
std::unique_ptr<float[]> deriv_out = std::make_unique<float[]>(current.num_rows);
//
current.derivative(current.pre_activ.get(), deriv_out.get());
//now we can compute the deltas of all the other layers
cblas_sgemv(CblasRowMajor, CblasTrans, last.num_rows, last.num_cols, 1.0f, last.weights.get(),
last.num_cols, last.deltas.get(),
1, 0.0f, current.deltas.get(), 1);
std::transform(current.deltas.get(), current.deltas.get() + current.num_rows, deriv_out.get(),
current.deltas.get(), std::multiplies<float>{});
}
}
public:
Network(size_t input) : input_size(input) {}
template<typename Activ>
void add_layer(size_t num_hidden) {
Layer layer;
if (layers.empty()) {
layer.num_cols = input_size;
} else {
const Layer &last = layers.back();
layer.num_cols = last.num_rows;
}
layers.emplace_back(std::move(layer));
Layer ¤t = layers.back();
current.num_rows = num_hidden;
current.weights = std::make_unique<float[]>(current.num_rows * current.num_cols);
current.biases = std::make_unique<float[]>(current.num_rows);
current.pre_activ = std::make_unique<float[]>(current.num_rows);
current.post_activ = std::make_unique<float[]>(current.num_rows);
current.deltas = std::make_unique<float[]>(current.num_rows);
//init everything but weights to zero
std::fill(current.deltas.get(), current.deltas.get() + current.num_rows, 0.0f);
std::fill(current.biases.get(), current.biases.get() + current.num_rows, 0.0f);
const int rows = current.num_rows;
float *in = current.pre_activ.get();
float *out = current.post_activ.get();
current.activation = [rows, in, out]() {
Activ::apply(in, in + rows, out);
};
current.derivative = [rows](float *in, float *out) {
Activ::apply_deriv(in, in + rows, out);
};
}
void init_weights();
template<typename Loss>
void train(Train::Data &data, float lr, size_t epoch) {
std::unique_ptr<float[]> input = std::make_unique<float[]>(input_size);
std::unique_ptr<float[]> output = std::make_unique<float[]>(get_output_layer().num_rows);
for (auto i = 0; i < epoch; ++i) {
std::shuffle(data.mutable_data()->begin(), data.mutable_data()->end(), generator);
for (auto k = 0; k < data.data_size(); ++k) {
const Train::Point &point = data.data(k);
for (auto p = 0; p < input_size; ++p) {
input[p] = point.input(p);
}
for (auto p = 0; p < get_output_layer().num_rows; ++p) {
output[p] = point.output(p);
}
forward_pass(input.get());
back_propagate<Loss>(output.get());
for (Layer &layer : layers) {
for (auto x = 0; x < layer.num_rows; ++x) {
layer.biases[x] -= lr * layer.deltas[x];
}
}
for (auto x = 0; x < layers.front().num_rows; ++x) {
for (auto y = 0; y < input_size; ++y) {
layers.front().weights[x * layers.front().num_cols + y] -=
lr * layers.front().deltas[x] * input[y];
}
}
for (auto l = 1; l < layers.size(); ++l) {
Layer &layer = layers[l];
Layer &previous = layers[l - 1];
for (auto x = 0; x < layer.num_rows; ++x) {
for (auto y = 0; y < layer.num_cols; ++y) {
layer.weights[x * layer.num_cols + y] -= lr * layer.deltas[x] * previous.post_activ[y];
}
}
}
}
}
}
void forward_pass(float *input);
Layer &get_output_layer();
const Layer &get_output_layer() const;
void train(Train::Data &data, float lr, size_t epoch);
};
#endif //NETWORK_NETWORK_H
| {
"alphanum_fraction": 0.5471050049,
"avg_line_length": 31.84375,
"ext": "h",
"hexsha": "182a77a623a939625e78f7f353be7a59c33dc8f5",
"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": "24e78c14ab7df6ae87d1aea0fbd749232d88ccfc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "CheckersGuy/Network",
"max_forks_repo_path": "Network.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "24e78c14ab7df6ae87d1aea0fbd749232d88ccfc",
"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": "CheckersGuy/Network",
"max_issues_repo_path": "Network.h",
"max_line_length": 115,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "24e78c14ab7df6ae87d1aea0fbd749232d88ccfc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "CheckersGuy/Network",
"max_stars_repo_path": "Network.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1369,
"size": 6114
} |
// 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_MATRIX_NORM_H
#define SCILIB_LINALG_MATRIX_NORM_H
#ifdef USE_MKL
#include <mkl.h>
#else
#include <lapacke.h>
#endif
#include <scilib/mdarray.h>
#include <scilib/linalg_impl/lapack_types.h>
#include <type_traits>
namespace Sci {
namespace Linalg {
namespace stdex = std::experimental;
// Matrix norm of a general rectangular matrix:
//
// Types of matrix norms:
// - M, m: largest absolute value of the matrix
// - 1, O, o: 1-norm of the matrix (maximum column sum)
// - I, i: infinity norm of the matrix (maximum row sum)
// - F, f, E, e: Frobenius norm of the matrix (square root of sum of squares)
//
template <class T, class Layout>
requires(std::is_same_v<std::remove_cv_t<T>, double>)
inline auto matrix_norm(Sci::Matrix_view<T, Layout> a, char norm)
{
static_assert(a.is_contiguous());
assert(norm == 'M' || norm == 'm' || norm == '1' || norm == 'O' ||
norm == 'o' || norm == 'I' || norm == 'i' || norm == 'F' ||
norm == 'f' || norm == 'E' || norm == 'e');
auto matrix_layout = LAPACK_ROW_MAJOR;
BLAS_INT m = static_cast<BLAS_INT>(a.extent(0));
BLAS_INT n = static_cast<BLAS_INT>(a.extent(1));
BLAS_INT lda = n;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = LAPACK_COL_MAJOR;
lda = m;
}
return LAPACKE_dlange(matrix_layout, norm, m, n, a.data(), lda);
}
template <class Layout, class Allocator>
inline double matrix_norm(const Sci::Matrix<double, Layout, Allocator>& a,
char norm)
{
return matrix_norm(a.view(), norm);
}
} // namespace Linalg
} // namespace Sci
#endif // SCILIB_LINALG_MATRIX_NORM_H
| {
"alphanum_fraction": 0.6563807531,
"avg_line_length": 28.9696969697,
"ext": "h",
"hexsha": "ccb0d32f925fa934cc000a67d530b1f74f1ada4c",
"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/matrix_norm.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/matrix_norm.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/matrix_norm.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 527,
"size": 1912
} |
//
// Created by daeyun on 7/3/17.
//
#pragma once
#include <random>
#include <algorithm>
#include <gsl/gsl_assert>
#include <cstring>
namespace scene3d {
namespace Random {
static std::mt19937 &Engine() {
thread_local static std::mt19937 engine{std::random_device{}()};
return engine;
}
template<class Iter>
static void Shuffle(Iter begin, Iter end) {
std::shuffle(begin, end, Engine());
}
static int UniformInt(int n) {
std::uniform_int_distribution<decltype(n)> dist{0, n - 1};
return dist(Engine());
}
static double Rand() {
std::uniform_real_distribution<double> dist{0, 1};
return dist(Engine());
}
// If n is greater than pool size, some items will be chosen more than once.
template<class T>
static void ChooseN(size_t n, std::vector<T> *mutable_pool, std::vector<T> *choices) {
Expects(!mutable_pool->empty());
auto left_size = mutable_pool->size();
for (int i = 0; i < n; ++i) {
std::string RandomString(size_t length);
if (left_size <= 0) {
left_size = mutable_pool->size();
}
auto &chosen = mutable_pool->at(UniformInt(left_size));
choices->push_back(chosen);
std::swap(chosen, mutable_pool->at(left_size - 1));
--left_size;
}
}
static std::string RandomString(size_t length) {
auto randchar = []() -> char {
constexpr char charset[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
auto i = UniformInt(static_cast<int>(std::strlen(charset)));
return charset[i];
};
std::string str(length, 0);
std::generate_n(str.begin(), length, randchar);
return str;
}
}
}
| {
"alphanum_fraction": 0.6644004944,
"avg_line_length": 23.4492753623,
"ext": "h",
"hexsha": "3e505a088e165880a48e5d2d014998fdd64d9487",
"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": "5caf663827ad6fe10b40bdf3763a40bc013e9205",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "daeyun/mesh-point-cloud",
"max_forks_repo_path": "lib/random_utils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5caf663827ad6fe10b40bdf3763a40bc013e9205",
"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": "daeyun/mesh-point-cloud",
"max_issues_repo_path": "lib/random_utils.h",
"max_line_length": 86,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "5caf663827ad6fe10b40bdf3763a40bc013e9205",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "daeyun/mesh-point-cloud",
"max_stars_repo_path": "lib/random_utils.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-13T00:47:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-10-17T06:14:49.000Z",
"num_tokens": 423,
"size": 1618
} |
/*
* File: array_funcs.h
* Author: fedro
*
* Created on December 10, 2014, 3:25 PM
*/
#ifndef ARRAY_FUNCS_H
#define ARRAY_FUNCS_H
#include "array.h"
#include <assert.h>
#include <gsl/gsl_statistics_double.h>
#include <cmath>
#include <complex>
#include <fstream>
namespace neurophys {
namespace arr {
template<class T>
Array<T> zeros(const size_t size)
{
// this assumes that whatever the type T, setting the memory byte-wise to
// zero means the elements become 0
Array<T> result(size);
memset(result.data(), 0, size*sizeof(T));
return result;
}
template<class T>
Array<T> ones(const size_t size)
{
Array<T> result(size);
for (int i = 0; i < size; i++)
result[i] = 1.;
return result;
}
template<class T>
const T sum(const Array<T>& ar)
{
T res = 0.;
for (int i = 0; i < ar.size(); i++)
res += ar[i];
return res;
}
template<class T>
const T max(const Array<T>& ar)
{
T max = ar[0];
for (int i = 0; i < ar.size(); i++)
if (ar[i] > max)
max = ar[i];
return max;
}
template <class T>
void columns_to_stream(std::ostream& out, const Array<T>& x, const Array<T>& y)
{
/*if (x.size() != y.size())
throw ArraySizeMismatchException();*/
for (int i = 0; i < std::min(x.size(),y.size()); i++)
out << x[i] << "\t" << y[i] << "\n";
}
template <class T>
void columns_to_stream(std::ostream& out, const Array<T>& x, const Array<T>& y,
const Array<T>& z)
{
/*if (x.size() != y.size())
throw ArraySizeMismatchException();*/
for (int i = 0; i < std::min(x.size(),y.size()); i++)
out << x[i] << "\t" << y[i] << "\t" << z[i] << "\n";
}
template <class T>
void columns_to_file(const char filename[], const Array<T>& x, const Array<T>& y)
{
std::ofstream of;
of.open(filename, std::ios::out);
columns_to_stream(of, x, y);
of.close();
}
template <class T>
void columns_to_file(const char filename[], const Array<T>& x, const Array<T>& y,
const Array<T>& z)
{
std::ofstream of;
of.open(filename, std::ios::out);
columns_to_stream(of, x, y, z);
of.close();
}
template <class T>
Array<T> downsample(const Array<T>& src, const size_t destsize)
{
assert(destsize <= src.size());
Array<T> result = zeros<double>(destsize);
const double f = static_cast<double>(destsize)/src.size();
for (int i = 0; i < src.size(); i++)
{
result[i * f] += src[i] * f;
}
return result;
}
double mean(const Array<double>& ar);
double var(const Array<double>& ar);
Array<double> range(const double a, const double b, const double inc=1);
Array<double> cos(const Array<double>& x);
Array<double> sin(const Array<double>& x);
Array<std::complex<double> > conj(const Array<std::complex<double> >& x);
Array<double> real(const Array<std::complex<double> >& x);
Array<double> imag(const Array<std::complex<double> >& x);
Array<double> abs(const Array<std::complex<double> >& x);
}}
#endif /* ARRAY_FUNCS_H */
| {
"alphanum_fraction": 0.5943735689,
"avg_line_length": 24.0708661417,
"ext": "h",
"hexsha": "5fac47e26813931670b15a83981b283a5c7997e8",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ModelDBRepository/228604",
"max_forks_repo_path": "simulation/neurophys/array_funcs.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "ModelDBRepository/228604",
"max_issues_repo_path": "simulation/neurophys/array_funcs.h",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ModelDBRepository/228604",
"max_stars_repo_path": "simulation/neurophys/array_funcs.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 847,
"size": 3057
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//#include <cem.h>
#include <mpi.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
void randperm(int*, int);
void load_double_mat(double*, int, int, int, char*);
void load_int_mat(int*, int, int, int, char*);
void load_double_array(double*, int, char*);
void load_int_array(int*, int, char*);
void load_double_value(int,char);
void load_int_value(int,char);
int mat_size_row(int*);
int find_value_in_array(int*,int,int,int);
void mat2d_prod(double*, int, int, double*, int, int, double*, int, int);
double obtainerr2_par(int,int,double*, int, int, int*, int, double*);
void least_square_solver(double*, int, int, double*, double*);
#define MASTER 0
#define FROM_MASTER 1
#define FROM_WORKER 2
int main(int argc, char **argv)
{
int n1, n2, n3;
int np, nfu;
double kv[3][3], pk[3][3], pp[8][3];
double *rp, *rpL, *rpN, *rpO;
int *map_to_cluster1, *map_to_cluster2, *map_to_cluster3;
int *nlist;
int neighbor_num;
int ncluster, ncluster2, ncluster3, ncorr_col;
int c2start, c3start;
int data;
double *E, *Ef;
int ndata;
int i, j, k, nj, nk, ctn;
int iter, max_iter;
double kT=0.0517;
int howmanycluster;
int dispfreq;
int construct_corr_mat = 0;
// mpi parameters and initialization
int numprocs, rank, mtype;
int row_dist_size;
int row_ini, row_end, row_offset;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs); // Get # processors
MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Get my rank (id)
if (numprocs>1)
printf("Parallel computing: the input files are read by all nodes. Multiple messages are not due to error!\n",numprocs);
// Construct conrrelation matrix. It can also be loaded.
if (construct_corr_mat) {
printf("Not activated yet.\n");
/* // Task: make a function to load values from clusterlist run, later
np = 48; // for 3x2x2 cell
nfu = np/2; // for 3x2x2 cell
neighbor_num = 47; // for 3x2x2 cell
ncluster2 = 10;
ncluster3 = 62;
// load lattice and cluster data
load_double_mat(kv,3,3,1,"kv.dat");
load_double_mat(rp,np,3,1,"rp.dat");
load_double_mat(rpL,npL,3,1,"rpL.dat");
load_double_mat(rpN,npN,3,1,"rpN.dat");
load_double_mat(rpO,npO,3,1,"rpO.dat");
load_double_array(cluster2,"cluster2.dat");
load_double_array(cluster3,"cluster3.dat");
load_int_array(map_to_cluster1,"map_to_cluster1.dat");
load_int_array(map_to_cluster2,"map_to_cluster2.dat");
load_int_array(map_to_cluster3,"map_to_cluster3.dat");
load_int_array(nlist,"nlist.dat");
ncluster = ncluster2+ncluster3+1+1;
ncorr_col = 1 + 2*np + 3*ncluster2 + 4*ncluster3;
c2start = 3; //2*length(cluster1)+1. Don't need -1: cluster2 idx starts from 0
c3start = 3*ncluster2 + c2start;
// load LNO occupation variable data
load_int_array(data,"LNC_occu_data.dat");
load_double_array(E,"E.dat");
load_double_array(Ef,"Ef.dat");
ndata = mat_size_row(data);
int nL[ndata];
int nC[ndata];
int nN[ndata];
for (i=0;i<ndata;i++) {
nL[i] = find_value_in_array(data,i,0);
nC[i] = find_value_in_array(data,i,1);
nN[i] = find_value_in_array(data,i,-1);
}
// initialize the correlation matrix
double corr_mat[ndata][ncorr_col];
obtain_corr_mat(corr_mat, ndata, ncorr_col, data, c2start, c3start);
// post data processing: excluding degenerate cases
int nondegenerate[ndata];
for (i=0;i<ndata;i++)
nondegenerate[i] = 1;
for (i=0;i<ndata;i++) {
for (j=0;j<i;j++) {
ctn = 1;
for (l=0;l<ncorr_col;l++)
if (corr_mat[j][l]~=corr_mat[i][l]) {
ctn = 0;
break;
}
if (ctn == 1)
if (Ef[j] < Ef[i])
nondegenerate[i] = 0;
else
nondegenerate[j] = 0;
}
for (j=i+1;j<ndata;j++) {
ctn = 1;
for (l=0;l<ncorr_col;l++)
if (corr_mat[j][l]~=corr_mat[i][l]) {
ctn = 0;
break;
}
if (ctn == 1)
if (Ef[j] < Ef[i])
nondegenerate[i] = 0;
else
nondegenerate[j] = 0;
}
}
int n_nondegenerate = 0;
for (i=0;i<ndata;i++)
if (nondegenerate[i] == 1)
n_nondegenerate++;
double corr_mat_u[n_nondegenerate][ncorr_col];
double Ef_u[n_nondegenerate];
double nC_r[n_nondegenerate];
l = 0;
for (i=0;i<ndata;i++)
if (nondegenerate[i] == 1) {
for (j=0;j<ncorr_col;j++)
corr_mat_u[l][j] = corr_mat[i][j];
Ef_u[l] = Ef[i];
nC_u[l] = nC[i];
l++;
}
// select data sets near convex hull
int n_corr_mat_ug_row = 0;
int near_convh[n_nondegenerate];
for (i=0;i<n_nondegenerate;i++)
if (Ef_u[i] < ef_conv(nC[i]) + near_convh_cutoff) {
near_convh[i] = 1;
n_corr_mat_ug_row++;
}
else
near_convh[i] = 0;
double corr_mat_ug[n_corr_mat_ug_row][ncorr_col];
double Ef_ug[n_corr_mat_ug_row];
double nC_ug[n_corr_mat_ug_row];
l = 0;
for (i=0;i<n_corr_mat_ug_row)
if (near_convh[i] == 1) {
for (j=0;j<ncorr_col;j++)
corr_mat_ug[l][j] = corr_mat_u[i][j];
Ef_ug[l] = Ef_u[i];
nC_ug[l] = nC_u[i];
l++;
}
// select the non-singular columns only
int n_non_singular_col = 0;
int col_singularity[ncorr_col];
for (i=0;i<ncorr_col;i++) {
ctn = 0;
for (j=1;j<n_corr_mat_ug_row;j++)
if (corr_mat_ug[j][i] ~= corr_mat_ug[0][i]) {
ctn = 1;
break;
}
if (ctn == 1) {
col_singularity[i] = 1; // 0:singular, 1:non-singular
n_non_singular_col++;
}
else
col_singularity[i] = 0;
}
double corr_mat_ugs[n_corr_mat_ug_row][n_non_singular_col];
int non_singular_col_id[n_non_singular_col];
l = 0;
for (i=0;i<n_non_singular_col)
if (col_singularity[i] == 1) {
for (j=0;j<n_corr_mat_ug_row;j++)
corr_mat_ugs[j][l] = corr_mat_ug[j][l];
non_singular_col_id[l] = i;
l++;
}
*/
}
// else {
int n_corr_mat_ug_row;
int n_non_singular_col;
FILE *fp;
char paramfilename[100]="param_findcluster.dat";
char corr_mat_ugs_filename[200];
fp = fopen(paramfilename, "r");
fscanf(fp, "%s %d %d %d %d %lf %d",corr_mat_ugs_filename, &n_corr_mat_ug_row, &n_non_singular_col, &howmanycluster, &max_iter, &kT, &dispfreq);
fclose(fp);
printf("n_corr_mat_ug_row=%d, n_non_singular_col=%d, howmanycluster=%d, max_iter=%d, dispfreq=%d\n",n_corr_mat_ug_row, n_non_singular_col, howmanycluster, max_iter, dispfreq);
double *corr_mat_ugs;
corr_mat_ugs = (double*) malloc(n_corr_mat_ug_row*n_non_singular_col*sizeof(double));
load_double_mat(corr_mat_ugs,n_corr_mat_ug_row,n_non_singular_col,1,corr_mat_ugs_filename);
int usefulcorr_col[n_non_singular_col];
load_int_array(usefulcorr_col,n_non_singular_col,"usefulcorr_col.dat");
double Ef_ug[n_corr_mat_ug_row];
load_double_array(Ef_ug,n_corr_mat_ug_row,"Ef_ug.dat");
int nC_ug[n_corr_mat_ug_row];
load_int_array(nC_ug,n_corr_mat_ug_row,"nC_ug.dat");
// }
printf("step1\n");
row_offset = n_corr_mat_ug_row/numprocs;
double err2_sum_from_master;
double err2_sum_from_worker;
int cluster_set1[howmanycluster];
/**** Start of MC simulation ****/
if (rank == MASTER) {
int cluster_set1_old[howmanycluster], cluster_set1_min[howmanycluster], cluster_set2[n_non_singular_col-howmanycluster];
double cvs, cvs_old, cvs_min, cvs_tol;
int select1, select2, target, candidate;
cvs_tol = 0.01;
for (i=0;i<howmanycluster;i++)
cluster_set1[i] = i;
for (i=0;i<n_non_singular_col-howmanycluster;i++)
cluster_set2[i] = i+howmanycluster;
mtype = FROM_MASTER;
for (i=1;i<numprocs;i++) {
MPI_Send(&cluster_set1, howmanycluster, MPI_INT, i, mtype, MPI_COMM_WORLD);
}
row_ini = rank * row_offset;
row_end = row_ini +row_offset;
err2_sum_from_master = obtainerr2_par(row_ini,row_end,corr_mat_ugs,n_corr_mat_ug_row,n_non_singular_col,cluster_set1,howmanycluster,Ef_ug);
printf("initial err2 = %f\n",err2_sum_from_master);
for (i=1;i<numprocs;i++) {
mtype = FROM_WORKER;
MPI_Recv(&err2_sum_from_worker, 1, MPI_DOUBLE, i, mtype, MPI_COMM_WORLD, &status);
err2_sum_from_master += err2_sum_from_worker;
}
printf("initial err2 = %f\n",err2_sum_from_master);
cvs = sqrt(err2_sum_from_master/n_corr_mat_ug_row);
cvs_min = cvs;
for (i=0;i<howmanycluster;i++)
cluster_set1_min[i] = cluster_set1[i];
printf("initial cvs = %f\n",cvs);
for (iter=0;iter<max_iter;iter++) {
select1 = (int) floor(drand48()*howmanycluster);
select2 = (int) floor(drand48()*(n_non_singular_col-howmanycluster));
target = cluster_set1[select1];
candidate = cluster_set2[select2];
cvs_old = cvs;
cluster_set1[select1] = candidate;
mtype = FROM_MASTER;
for (i=1;i<numprocs;i++) {
MPI_Send(&cluster_set1, howmanycluster, MPI_INT, i, mtype, MPI_COMM_WORLD);
}
row_ini = rank * row_offset;
row_end = row_ini +row_offset;
err2_sum_from_master = obtainerr2_par(row_ini,row_end,corr_mat_ugs,n_corr_mat_ug_row,n_non_singular_col,cluster_set1,howmanycluster,Ef_ug);
for (i=1;i<numprocs;i++) {
mtype = FROM_WORKER;
MPI_Recv(&err2_sum_from_worker, 1, MPI_DOUBLE, i, mtype, MPI_COMM_WORLD, &status);
err2_sum_from_master += err2_sum_from_worker;
}
cvs = sqrt(err2_sum_from_master/n_corr_mat_ug_row);
if (cvs < cvs_old)
cluster_set2[select2] = target;
else if (exp(-(cvs-cvs_old)/kT) > drand48())
cluster_set2[select2] = target;
else {
cluster_set1[select1] = target;
cvs = cvs_old;
}
if (cvs < cvs_min) {
for (i=0;i<howmanycluster;i++)
cluster_set1_min[i] = cluster_set1[i];
cvs_min = cvs;
}
if (cvs < cvs_tol)
break;
if (iter%dispfreq==0)
printf("iter=%8d, cvs=%f, cvs_min=%f, cvs_min/fu=%f\n",iter,cvs,cvs_min,cvs_min/72);
}
// print the result
printf("End of MC iteration. The selected clusters are...\n");
printf("ID in non-singular | ID in entire\n");
for (i=0;i<howmanycluster;i++)
printf(" %4d %4d\n",cluster_set1_min[i],usefulcorr_col[cluster_set1_min[i]]);
double err_pred, rms;
double Ef_pred[n_corr_mat_ug_row];
double *corr_mat_ugs_reduced;
corr_mat_ugs_reduced = (double*) malloc(n_corr_mat_ug_row*howmanycluster*sizeof(double));
double eci[howmanycluster];
for (i=0;i<n_corr_mat_ug_row;i++) {
for (j=0;j<howmanycluster;j++)
*(corr_mat_ugs_reduced+howmanycluster*i+j) = *(corr_mat_ugs+n_non_singular_col*i+cluster_set1_min[j]);
}
least_square_solver(corr_mat_ugs_reduced,n_corr_mat_ug_row,howmanycluster,Ef_ug,eci);
mat2d_prod(Ef_pred,n_corr_mat_ug_row,1,corr_mat_ugs_reduced,n_corr_mat_ug_row,howmanycluster,eci,howmanycluster,1);
err_pred = 0.0;
for (i=0;i<n_corr_mat_ug_row;i++)
err_pred += (Ef_ug[i] - Ef_pred[i])*(Ef_ug[i] - Ef_pred[i]);
rms = sqrt(err_pred/n_corr_mat_ug_row);
// Write result into files
FILE *fp2;
char cluster_set_filename[200];
sprintf(cluster_set_filename, "cluster_set_magN%d.dat",howmanycluster);
fp2 = fopen(cluster_set_filename,"w");
for (i=0;i<howmanycluster;i++)
fprintf(fp2,"%4d\t%4d\t%.4f\n",cluster_set1_min[i],usefulcorr_col[cluster_set1_min[i]],eci[i]);
}
else {
for (iter=0;iter<(max_iter+1);iter++) {
mtype = FROM_MASTER;
MPI_Recv(&cluster_set1, howmanycluster, MPI_INT, MASTER, mtype, MPI_COMM_WORLD, &status);
row_ini = rank * row_offset;
row_end = row_ini + row_offset;
err2_sum_from_worker = obtainerr2_par(row_ini,row_end,corr_mat_ugs,n_corr_mat_ug_row,n_non_singular_col,cluster_set1,howmanycluster,Ef_ug);
mtype = FROM_WORKER;
MPI_Send(&err2_sum_from_worker, 1, MPI_DOUBLE, MASTER, mtype, MPI_COMM_WORLD);
}
}
MPI_Finalize();
}
void load_double_mat(double *A, int Arow, int Acol, int Apgs, char *datfilename) {
FILE *fp;
int i, j, k;
double tmp;
printf("filename: %s\n", datfilename);
fp = fopen(datfilename, "r");
for (k=0;k<Apgs;k++)
for (i=0;i<Arow;i++)
for (j=0;j<Acol;j++) {
fscanf(fp, "%lf", &tmp);
*(A+Arow*Acol*k+Acol*i+j) = tmp;
}
fclose(fp);
}
void load_int_mat(int *A, int Arow, int Acol, int Apgs, char *datfilename) {
FILE *fp;
int i, j, k, tmp;
printf("filename: %s\n", datfilename);
fp = fopen(datfilename, "r");
for (k=0;k<Apgs;k++)
for (i=0;i<Arow;i++)
for (j=0;j<Acol;j++) {
fscanf(fp, "%d", &tmp);
*(A+Arow*Acol*k+Acol*i+j) = tmp;
}
fclose(fp);
}
void load_int_array(int *array, int arraysize, char *datfilename) {
FILE *fp;
int i;
printf("filename: %s\n", datfilename);
fp = fopen(datfilename, "r");
// printf("step2\n");
for (i=0;i<arraysize;i++) {
fscanf(fp, "%d", &array[i]);
// printf("%d\n",array[i]);
}
fclose(fp);
// printf("step3\n");
}
void load_double_array(double *array, int arraysize, char *datfilename) {
FILE *fp;
int i;
printf("filename: %s\n", datfilename);
fp = fopen(datfilename, "r");
// printf("step4\n");
for (i=0;i<arraysize;i++) {
fscanf(fp, "%lf", &array[i]);
// printf("%f\n",array[i]);
}
fclose(fp);
// printf("step5\n");
}
void randperm(int *a, int np) {
int i, id1, id2, id3, tmpr, num_perm;
num_perm = 100*np;
for (i=0;i<np;i++)
*(a+i) = i;
for (i=0;i<num_perm;i++) {
id1 = rand() % np;
id3 = rand() % np;
id2 = (id1 + id3) % np;
if (id1 != id2) {
tmpr = *(a+id2);
*(a+id2) = *(a+id1);
*(a+id1) = tmpr;
}
}
}
int find_value_in_array(int *A, int target_rowA, int colA, int target_value) {
int i;
for (i=0;i<colA;i++)
if (*(A+colA*target_rowA+i)==target_value)
return(i);
if (i==colA)
return(-1);
}
| {
"alphanum_fraction": 0.5539318885,
"avg_line_length": 33.2989690722,
"ext": "c",
"hexsha": "8fff13fd6c423295041fb899eadeb362ffeaa705",
"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": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "eunseok-lee/spin_atom_CE3",
"max_forks_repo_path": "src_findcluster3/test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67",
"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": "eunseok-lee/spin_atom_CE3",
"max_issues_repo_path": "src_findcluster3/test.c",
"max_line_length": 179,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "84da0f1ba2ed3cbc9e03b00fcd8bf09301f7ff67",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "eunseok-lee/spin_atom_CE3",
"max_stars_repo_path": "src_findcluster3/test.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4610,
"size": 16150
} |
#pragma once
#include "../utils/utils.h"
#include <gsl/gsl>
#include <limits>
namespace Halley {
class Compression {
public:
static Bytes compress(const Bytes& bytes);
static Bytes compress(gsl::span<const gsl::byte> bytes);
static Bytes decompress(const Bytes& bytes, size_t maxSize = std::numeric_limits<size_t>::max());
static Bytes decompress(gsl::span<const gsl::byte> bytes, size_t maxSize = std::numeric_limits<size_t>::max());
static std::shared_ptr<const char> decompressToSharedPtr(gsl::span<const gsl::byte> bytes, size_t& outSize, size_t maxSize = std::numeric_limits<size_t>::max());
static Bytes compressRaw(gsl::span<const gsl::byte> bytes, bool insertLength);
static Bytes decompressRaw(gsl::span<const gsl::byte> bytes, size_t maxSize, size_t expectedSize = 0);
};
}
| {
"alphanum_fraction": 0.7397260274,
"avg_line_length": 42.2631578947,
"ext": "h",
"hexsha": "857746ce187d8149897da8797e549106894c0bca",
"lang": "C",
"max_forks_count": 193,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z",
"max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sunhay/halley",
"max_forks_repo_path": "src/engine/utils/include/halley/bytes/compression.h",
"max_issues_count": 53,
"max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "sunhay/halley",
"max_issues_repo_path": "src/engine/utils/include/halley/bytes/compression.h",
"max_line_length": 163,
"max_stars_count": 3262,
"max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sunhay/halley",
"max_stars_repo_path": "src/engine/utils/include/halley/bytes/compression.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z",
"num_tokens": 200,
"size": 803
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
#include <fftw3.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "fftlog.h"
#define check_memory(p, name) if(p == NULL){printf("Problems to alloc %s.\n", name); return 0;}
#define Lc_MAX 1.0e+2
#define Mc_MIN 1.0e+5
#define M_max 6.0e+15
/*Structure for the peaks in the density field*/
typedef struct Halos_centers {
int x[3]; /*Index of the halo center*/
float den; /*Density of the halo's central cell*/
} PEAKS;
/*Structure for the final halos*/
typedef struct Halos {
int x[3]; /*Index of central cell of teh halo*/
int cont; /*Number of cells in the halo*/
} HALOS;
/*Barrier used for the halo definition*/
float Barrier(float S, float dc, char barrier, float a, float b, float alpha){
float resp;
/*The Press-Schechter barrier*/
if(barrier == 0)
resp = dc;
/*The Sheth-Tormen barrier*/
else if(barrier == 1)
resp = sqrt(a)*dc*(1.0 + b*pow(S/(a*dc*dc), alpha));
return resp;
}
/*Partition function for the quicksort*/
long int partition_peaks( PEAKS a[], long l, long r) {
long i, j, k;
PEAKS pivot, t;
pivot.den = a[l].den;
for(k=0;k<3;k++) pivot.x[k] = a[l].x[k];
i = l; j = r+1;
while( 1){
do ++i; while( a[i].den >= pivot.den && i < r );
do --j; while( a[j].den < pivot.den );
if( i >= j ) break;
t.den = a[i].den; a[i].den = a[j].den; a[j].den = t.den;
for(k=0;k<3;k++){ t.x[k] = a[i].x[k]; a[i].x[k] = a[j].x[k]; a[j].x[k] = t.x[k];}
}
t.den = a[l].den; a[l].den = a[j].den; a[j].den= t.den;
for(k=0;k<3;k++){ t.x[k] = a[l].x[k]; a[l].x[k] = a[j].x[k]; a[j].x[k] = t.x[k];}
return j;
}
/*The quicksort algorithm to sort the peaks list*/
void quickSort_peaks( PEAKS a[], long l, long r){
long j;
if( l < r ){
// divide and conquer
j = partition_peaks( a, l, r);
quickSort_peaks( a, l, j-1);
quickSort_peaks( a, j+1, r);
}
}
/*Define the distance between two cells*/
long int dist2(long int i, long int j, long int k){
long int resp;
resp = i*i + j*j + k*k;
return resp;
}
/*Define the cyclic sum for floats*/
float cysumf(float x, float y, float L){
float resp;
resp = x + y;
if(resp>=L) resp -= L;
if(resp<0) resp += L;
return resp;
}
/*Define the cyclic sum*/
int cysum(int i, int j, int nd){
int resp;
resp = i+j;
if(resp>=nd) resp -= nd;
if(resp<0) resp += nd;
return resp;
}
/*Window function in the Fourier space*/
double W(double k, double R){
double resp;
resp = 3.0/(pow(k*R,2))*(sin(k*R)/(k*R) - cos(k*R));
return resp;
}
/*Evaluate the square root of matter variance*/
double calc_sigma(double *k, double *P, int Nk, double R){
int i;
double resp;
resp = 0.0;
for(i=0;i<Nk-1;i++)
resp += (k[i+1] - k[i])/2.0*(P[i]*pow(k[i]*W(k[i],R), 2) + P[i+1]*pow(k[i+1]*W(k[i+1],R), 2));
return resp/(2.0*M_PI*M_PI);
}
/*Evaluate the mass function for a given sigma*/
double fh(double sigma, int model, double dc){
double resp, nu;
double B, d, e, f, g;
//Press-Schechter
if(model == 0){
nu = dc/sigma;
resp = sqrt(2.0/M_PI)*nu*exp(-nu*nu/2.0);
}
//Tinker Delta = 300
else if(model == 1){
B = 0.466;
d = 2.06;
e = 0.99;
f = 0.48;
g = 1.310;
resp = B*(pow(sigma/e, -d) + pow(sigma, -f))*exp(-g/(sigma*sigma));
}
return resp;
}
/*Find the index of the next sphere*/
int Next_Count(int *spheres, int Ncells, int count){
int i, resp;
for(i=0;i<Ncells;i++)
if(spheres[i] == count){
resp = i + 1;
break;
}
return resp;
}
/*Halo concentration*/
float f_c(float Mv, float Mstar, float z){
float resp;
resp = 9.0/(1.0 + z)*pow(Mv/Mstar, -0.13);
return resp;
}
/*Generate a random number from 0 to Rv following the NFW profile*/
float Generate_NFW(float rv, float c, float A, int seed){
float Int, rs, r, rtmp;
gsl_rng *rng_ptr;
rng_ptr = gsl_rng_alloc (gsl_rng_taus);
gsl_rng_set(rng_ptr, seed);
Int = gsl_rng_uniform(rng_ptr);
rs = rv/c;
r = gsl_rng_uniform(rng_ptr);
rtmp = r + 1.0;
while(fabs(r-rtmp) > 0.001){
rtmp = r;
r = r - ((log(1.0 + r*c) - r*c/(1.0 + r*c) - A*Int)*pow(1.0 + r*c, 2))/(c*(2.0*r*c + r*r*c*c));
}
gsl_rng_free(rng_ptr);
return r*rv;
}
/*Mean value of central galaxies*/
float Ncentral(float M, float logMmin, float siglogM){
float resp;
resp = 0.5*(1.0 + erf((log10(M) - logMmin)/siglogM));
return resp;
}
/*Mean value of satellite galaxies*/
float Nsatellite(float M, float logM0, float logM1, float alpha){
float resp;
resp = pow((M - pow(10.0, logM0))/pow(10.0, logM1), alpha);
return resp;
}
int main(int argc,char *argv[])
{
FILE *power, *den_grid, *halo_cat, *disp_cat, *light_cat, *collapse_cat;
char powerfile[100], denfile[100], halofile[100], dispfile[100], lightfile[100], collapsefile[100];
char DO_2LPT, BARRIER, out_inter, out_halos, out_collapse, DEN_GRID, DISP_CAT, DO_HOD;
int i, j, k, nx, ny, nz, nz2, Nmin, N_cores, Nk, Nr, Ncells, seed, cont_tmp, grows, grows_tmp, tmp, nmin, m, m_tmp, nsnap;
long np, cont, nh, l;
float Lc, Om0, redshift, Growth, dc, EB_a, EB_b, EB_alpha, rhoc, Hz, Omz, rhomz, Mtot, Mcell, Lx, Ly, Lz, klx, kly, klz, Normx, Normk, Dv, kx, ky, kz, kmod, *Sig_grid, sigtmp, std, den, den_tmp, factx, facty, factz, fact, phixx, phixy, phixz, phiyy, phiyz, phizz, Pobs[3], LoS[3], dist_min, dist_max, theta_min, cos_min;
double *K, *P, *R, *M, *Sig, Rmin, Rmax, *R_xi, *Xi;
fftwf_plan p1, p2;
fftwf_complex *deltak, *deltak_tmp;
float *delta;
int *flag, *sphere;
PEAKS *peaks, *tmpp;
HALOS *halos;
if (argc != 35){
printf("\nWrong number of arguments.\n");
printf("arg1: Name of the power spectrum file.\n");
printf("arg2: Size (in Mpc/h) or mass (in M_odot/h) of each cell.\n");
printf("arg3-5: Number of cells along each direction.\n");
printf("arg6: Some seed for the random number generator.\n");
printf("arg7: Use the 2LPT to move the halos? Yes (1) or No (0).\n");
printf("arg8: The Value of Omega_m today.\n");
printf("arg9: The readshift z.\n");
printf("arg10: The rate between the growth function at the final resdshit and at the redshift of the input power spectrum.\n");
printf("arg11: The value of critical density delta _{c}. Put 0 to use the fit.\n");
printf("arg12: The minimum number of partiles in a halo of the final catalogue.\n");
printf("arg13: The number of cores to use in the parallel parts.\n");
printf("arg14: Prefix for the outputs.\n");
printf("arg15: Which barrier would you like to use to find the halos?\n\tThe statical barrier (SB) (0);\n\tThe ellipsoidal barrier (EB) (1).\n");
printf("arg16: Which intermediate results would you like to save?:\n\tNo one (0);\n\tThe gaussian density grid (1);\n\tThe particles displaced with LPT (2);\n\tBoth (3).\n");
printf("arg17: How do you want the final halo catalogue?\n\tNo halo catalogue (0);\n\tThe positions and velocities in the real space (1);\n\tThe positions and velocities in the real space light cone (2);\n\tThe positions and velocities in redshift space light cone(3).\n");
printf("arg18-20: The three parameters for the ellipsoidal barrier: a, b and alpha.\n");
printf("arg21: Read the density grid (0) or compute it (1)?\n");
printf("arg22: Read the displacement field (0) or compute it (1)?\n");
printf("arg23-25: Position of the observer in units of the box size.\n");
printf("arg26-28: Direction of the line of sight.\n");
printf("arg29-30: Minimum and maximum comoving distance of the halos in this snapshot in the light cone.\n");
printf("arg31: Angular aperture of the light cone in units of pi.\n");
printf("arg32: Save the information about the collapsed particles in the light cone? Yes (1) or No (0).\n");
printf("arg33: Populate the halos with a HOD?\n\tNo (0);\n\tYes, with a single type of galaxy (1)\n\tYes, with multiple types of galaxies(2).\n");
printf("arg34: Number of this snapshot.\n");
exit(0);
}
/*Get the name of all files*/
sprintf(powerfile, "%s", argv[1]);
sprintf(denfile, "%s_den.dat", argv[14]);
sprintf(halofile, "%s_halos.dat", argv[14]);
sprintf(dispfile, "%s_disp.dat", argv[14]);
/*Parameters with specifications of the box and options for this simulation*/
Lc = atof(argv[2]); //Size or mass of each cell
nx = atoi(argv[3]); //Number of cells along the x-direction
ny = atoi(argv[4]); //Number of cells along the y-direction
nz = atoi(argv[5]); //Number of cells along the z-direction
seed = atoi(argv[6]); //Seed for the random generator (same seed gives the same final catalogue)
DO_2LPT = (char)atoi(argv[7]); //Parameter with the information about the use (or not) of second order lagrangian perturbation theory
Nmin = atoi(argv[12]); //Number of particles in the smaller final halo
N_cores = atoi(argv[13]); //Number of cores used by openmp in the parallel parts
BARRIER = (char)atoi(argv[15]); //Parameter with the information about the utilization (or not) of the EB
out_inter = (char)atoi(argv[16]); //Parameter with the information about which intermediate results must be output
out_halos = (char)atoi(argv[17]); //Parameter with the information about what to save in the final halo catalogue
out_collapse = (char)atoi(argv[32]); //Parameter with the information about the collapsed particles in the light cone
DEN_GRID = (char)atoi(argv[21]); //Compute a new density field (1) or just read it from a file (0)?
DISP_CAT = (char)atoi(argv[22]); //Compute the displacement field (1) or just read it from a file (0)?
DO_HOD = (char)atoi(argv[33]); //Populate the halos with no galaxies (0), one type of galaxy (1) or multiple types (2)?
/*Some physical parametrs used in this simulation*/
Om0 = atof(argv[8]); //Omega_m value today (z=0)
redshift = atof(argv[9]); //Redshift of the final catalogues
Growth = atof(argv[10]); //Ratio between the growth function at the final redshift and the redshift of the inpur power spectrum
dc = atof(argv[11]); //Value of the critical density for the halo formation linearly extrapoleted using linear theory to the redshift of the final catalogues
/*Parameters for the EB*/
EB_a = atof(argv[18]); //Parameter a of the EB
EB_b = atof(argv[19]); //Parameter b of the EB
EB_alpha = atof(argv[20]); //Parameter alpha of the EB
/*Parameters for the construction of the light cone*/
Pobs[0] = atof(argv[23]); //Position x of the observer in units of the box size
Pobs[1] = atof(argv[24]); //Position y of the observer in units of the box size
Pobs[2] = atof(argv[25]); //Position z of the observer in units of the box size
LoS[0] = atof(argv[26]); //Component x of the direction of the line of sight
LoS[1] = atof(argv[27]); //Component y of the direction of the line of sight
LoS[2] = atof(argv[28]); //Component z of the direction of the line of sight
/*Normalize the LoS vector*/
kmod = 0.0;
for(i=0;i<3;i++)
kmod += LoS[i]*LoS[i];
for(i=0;i<3;i++)
LoS[i] = LoS[i]/sqrt(kmod);
dist_min = atof(argv[29]); //Minimum comoving distance of this slice
dist_max = atof(argv[30]); //Maximum comoving distance of this slice
theta_min = atof(argv[31])*M_PI; //Minimum angle theta
cos_min = cos(theta_min); //Cossine of the minimum angle theta
nsnap = atoi(argv[34]); //Number of this snapshot
sprintf(lightfile, "%s_%d_LightCone.dat", argv[14], nsnap);
sprintf(collapsefile, "%s_%d_Collapse.dat", argv[14], nsnap);
/*Some derived parameters used in this simulation*/
rhoc = 2.775e+11; //Critical density in unitis of M_odot/Mpc*h^2
Hz = 100.0*sqrt(Om0*pow(1.0 + redshift, 3.0) + (1.0 - Om0)); //Hubble constant at the final redshift
Omz = Om0*pow(1.0 + redshift, 3.0)/(Om0*pow(1.0 + redshift, 3.0) + (1.0 - Om0));//Matter contrast density at the final redshift
rhomz = Om0*rhoc; //Matter density at the final redshift
Dv = (18*M_PI*M_PI + 82.0*(Omz - 1.0) - 39.0*pow(Omz - 1.0, 2.0))/Omz; //Overdensity used to put galaxies in the halos
if(Lc < Lc_MAX) //If the size of each cell was given compute the mass of each cell
Mcell = rhomz*pow(Lc, 3.0);
else if(Lc > Mc_MIN){ //If the mass of each cell was given compute the size of each cell
Mcell = Lc;
Lc = pow(Mcell/rhomz, 1.0/3.0);
}
else{ //Notify an unexpected behavior and exit
printf("A cell larger than %f [Mpc/h] or with a mass smaller than %e [M_odot/h] is not expected. Please, change this value or change the definition of Lc_MAX and Mc_MIN in the code.\n", Lc_MAX, Mc_MIN);
exit(0);
}
Lx = Lc*nx; //Compute the size of the box along the x-direction
Ly = Lc*ny; //Compute the size of the box along the y-direction
Lz = Lc*nz; //Compute the size of the box along the z-direction
Mtot = rhomz*Lx*Ly*Lz; //Compute the total mass in the box
klx = 2.0*M_PI/Lx; //Compute the fundamental frequency in the x-direction
kly = 2.0*M_PI/Ly; //Compute the fundamental frequency in the y-direction
klz = 2.0*M_PI/Lz; //Compute the fundamental frequency in the z-direction
Normx = 1.0/sqrt(Lx*Ly*Lz); //Compute the normalization needed when aplyed the FFTW3 from k to x space
Normk = sqrt(Lx*Ly*Lz)/(nx*ny*nz); //Compute the normalization needed when aplyed the FFTW3 from x to k space
nz2 = nz/2 + 1; //Quantity used to alloc the complex arrays used in the FFTW3
nmin = nx; //Determine the smaller direction
if(nmin > ny) nmin = ny;
if(nmin > nz) nmin = nz;
/*Compute the number of repetitions of this box to construct the light cone*/
float Pos[3], dist, cost, vr, Mass;
int Nrep_x, Nrep_y, Nrep_z;
if(out_halos == 2 || out_halos == 3){
Nrep_x = floor(dist_max/Lx) + 1;
Nrep_y = floor(dist_max/Ly) + 1;
Nrep_z = floor(dist_max/Lz) + 1;
}
/*Parameters of the HOD model*/
int Ngals, Ncen, Nsat;
float r, phi, theta, Rv, C, A;
float logMmin, siglogM, logM0, logM1, alpha;
logMmin = 12.44005264;
siglogM = 0.79560376;
logM0 = 11.98154109;
logM1 = 12.99600074;
alpha = 1.13717828;
/*Check some inputs before to start*/
if(out_inter == 0 && out_halos == 0){
printf("You need to choose something to output! arg16, arg17 and/or arg18 must be >0!\n");
exit(0);
}
if(nx<0 || ny<0 || nz<0){
printf("You are trying to use n = (%d, %d, %d) and it is not possible!\n", nx, ny, nz);
exit(0);
}
if(DO_2LPT < 0 || DO_2LPT >1){
printf("You are trying to use DO_2LPT = %d and it is not possible! Setting DO_2LPT = 0.\n", DO_2LPT);
DO_2LPT = 0;
}
if(Growth <= 0.0){
printf("You gave a value of the ratio between the growths of %f and it is not physical!\n", Growth);
exit(0);
}
if(Nmin < 0){
printf("You gave a negative number for the number of particles in the smaller halo (%d). Settin it in 1.\n", Nmin);
Nmin = 1;
}
if(N_cores < 0){
printf("You gave a negative number for the number of cores (%d). Settin it in 1.\n", N_cores);
N_cores = 1;
}
if(BARRIER != 0 && BARRIER != 1){
printf("You need to chose a valid barrier for the void detection! Your choice were %d.\n", BARRIER);
exit(0);
}
if(Om0>1.0 || Om0<0.0){
printf("Your Omega _{m} = %f! Put some valid value between 0.0 and 1.0.\n", Om0);
exit(0);
}
if(dc < 0.0){
printf("Your delta_{c} = %f < 0. Using the fit.\n", dc);
dc = 1.686*pow(Omz, 0.0055);
}
if(dc == 0.0)
dc = 1.686*pow(Omz, 0.0055);
if(out_halos > 1 && theta_min > 1.0){
printf("Theta min must be equal or smaller than 1! Setting it to 1.\n");
theta_min = 1.0;
cos_min = -1.0;
}
if(out_halos > 1 && LoS[0] == 0.0 && LoS[1] == 0.0 && LoS[2] == 0.0){
printf("You must give a non vanishing vector for the direction of the line of sight!\n");
exit(0);
}
if(out_collapse == 1 && out_halos < 2){
printf("It is not possible to save the information about the collapsed particles without the creation of a light cone. Ignoring this parameter.\n");
out_collapse = 0;
}
printf("\nRunning the ExSHalos!\n\
Omega_m = %.3f, z = %.3f, Growth = %.3f, H = %.2f, d_c = %.3f and Delta_virial = %.1f\n\
L = (%.5f, %.5f, %.5f), N_cells = (%d, %d, %d), M_tot = %.5e, M_cell = %.5e and seed = %d.\n", Omz, redshift, Growth, Hz, dc, Dv, Lx, Ly, Lz, nx, ny, nz, Mtot, Mcell, seed);
omp_set_num_threads(N_cores); //Set the number of cores used by the openmp
/**************************************/
/* Constructing the density grids */
/**************************************/
printf("\nConstructing the density grid in real and fourier space!\n");
/*Opennning the power spectrum file*/
power = fopen(powerfile, "r");
if (power == NULL) {
printf("Unable to open %s\n", powerfile);
exit(0);
}
/*Measuring the number of k's*/
Nk = -1;
while(!feof(power)){
fscanf(power, "%f %f", &kx, &ky);
Nk ++;
}
rewind(power);
/*Reading the power spectrum*/
K = (double *)malloc(Nk*sizeof(double));
check_memory(K, "K")
P = (double *)malloc(Nk*sizeof(double));
check_memory(P, "P")
for(i=0;i<Nk;i++){
fscanf(power, "%lf %lf", &K[i], &P[i]);
P[i] = pow((double)Growth, 2.0)*P[i];
}
fclose(power);
/*Evaluating the Sigma(R)*/
Nr = Nk;
R = (double *)malloc(Nr*sizeof(double));
check_memory(R, "R")
M = (double *)malloc(Nr*sizeof(double));
check_memory(M, "M")
Sig = (double *)malloc(Nr*sizeof(double));
check_memory(Sig, "Sig")
Rmin = (double)pow(Mcell*0.9*3.0/(4.0*M_PI*rhomz), 1.0/3.0);
Rmax = (double)pow(M_max*3.0/(4.0*M_PI*rhomz), 1.0/3.0);
for(i=0;i<Nr;i++){
R[i] = pow(10, log10(Rmin) + i*(log10(Rmax) - log10(Rmin))/(Nr-1));
M[i] = 4.0/3.0*M_PI*(double)rhomz*pow(R[i], 3);
}
for(i=0;i<Nr;i++)
Sig[i] = sqrt(calc_sigma(K, P, Nk, R[i]));
/*Interpolating the Sigma(M)*/
gsl_interp_accel *acc = gsl_interp_accel_alloc();
gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline, Nr);
gsl_spline_init(spline, M, Sig, Nr);
/*Evaluate the integral of the mass function*/
double *Int;
Int = (double *)malloc(Nr*sizeof(double));
check_memory(Int, "Int")
Int[0] = 0.0;
for(i=1;i<Nr;i++)
Int[i] = Int[i-1] - (log(Sig[i]) - log(Sig[i-1]))/2.0*(fh(Sig[i], 1, (double) dc)/pow(R[i], -3.0) + fh(Sig[i-1], 1, (double) dc)/pow(R[i-1], -3.0));
/*Interpolate the integral of the mass function as function of mass and its inverse*/
gsl_interp_accel *acc_I = gsl_interp_accel_alloc();
gsl_interp_accel *acc_InvI = gsl_interp_accel_alloc();
gsl_spline *spline_I = gsl_spline_alloc(gsl_interp_cspline, Nr);
gsl_spline *spline_InvI = gsl_spline_alloc(gsl_interp_cspline, Nr);
gsl_spline_init(spline_I, M, Int, Nr);
gsl_spline_init(spline_InvI, Int, M, Nr);
free(Int);
/*Compute the Sigma as function of the number of cells in the halo*/
Ncells = floor(M_max/Mcell);
Sig_grid = (float *)malloc(Ncells*sizeof(float));
check_memory(Sig_grid, "Sig_grid")
Sig_grid[0] = 1e+30;
for(i=1;i<Ncells;i++)
Sig_grid[i] = pow(gsl_spline_eval(spline, i*Mcell, acc), 2.0);
gsl_spline_free(spline);
gsl_interp_accel_free(acc);
free(R);
free(M);
free(Sig);
/*Read the density grid*/
if(DEN_GRID == 0){
delta = (float*)fftwf_malloc((size_t)nx*(size_t)ny*(size_t)nz*sizeof(float));
check_memory(delta, "delta")
printf("Reading the density grid\n");
den_grid = fopen(denfile, "rb");
if (den_grid == NULL) {
printf("Unable to open %s\n", denfile);
exit(0);
}
fread(&nx, sizeof(int), 1, den_grid);
fread(&ny, sizeof(int), 1, den_grid);
fread(&nz, sizeof(int), 1, den_grid);
fread(&Lc, sizeof(float), 1, den_grid);
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++){
size_t ind = (size_t)(i*ny + j)*(size_t)nz + (size_t)k;
fread(&delta[ind], sizeof(float), 1, den_grid);
delta[ind] = Growth*delta[ind];
}
fclose(den_grid);
}
/*Construct the density grid*/
if(DEN_GRID == 1){
/*Compute the Power spectrum in the box*/
R_xi = (double *)malloc(Nk*sizeof(double));
check_memory(R_xi, "R_xi")
Xi = (double *)malloc(Nk*sizeof(double));
check_memory(Xi, "Xi")
pk2xi(Nk, K, P, R_xi, Xi);
for(i=0;i<Nk;i++)
if(R_xi[i] > (double)pow(Lx*Ly*Lz, 1.0/3.0)/2.0)
Xi[i] = 0.0;
xi2pk(Nk, R_xi, Xi, K, P);
free(R_xi);
free(Xi);
/*Interpolate the power spectrum*/
acc = gsl_interp_accel_alloc();
spline = gsl_spline_alloc(gsl_interp_cspline, Nk);
gsl_spline_init(spline, K, P, Nk);
free(K);
free(P);
/*Allocating the density grids*/
delta = (float*)fftwf_malloc((size_t)nx*(size_t)ny*(size_t)nz*sizeof(float));
check_memory(delta, "delta")
deltak_tmp = (fftwf_complex *) fftwf_malloc((size_t)nx*(size_t)ny*(size_t)nz2*sizeof(fftwf_complex));
check_memory(deltak_tmp, "deltak_tmp")
deltak = (fftwf_complex *) fftwf_malloc((size_t)nx*(size_t)ny*(size_t)nz2*sizeof(fftwf_complex));
check_memory(deltak, "deltak")
/*Alloc the needed quantities for the random generator*/
gsl_rng *rng_ptr;
rng_ptr = gsl_rng_alloc (gsl_rng_taus);
gsl_rng_set(rng_ptr, seed);
/*Constructing the Fourier space density grid*/
#pragma omp parallel for private(i, j, k, kx, ky, kz, kmod, std)
for(i=0;i<nx;i++){
if(2*i<nx) kx = (float)i*klx;
else kx = (float)(i-nx)*klx;
for(j=0;j<ny;j++){
if(2*j<ny) ky = (float)j*kly;
else ky = (float)(j-ny)*kly;
for(k=0;k<nz2;k++){
kz = (float)k*klz;
if(k == nz/2) kz = -(float)nz/2.0*klz;
size_t ind = (size_t)(i*ny + j)*(size_t)nz2 + (size_t)k;
kmod = sqrt(kx*kx + ky*ky + kz*kz);
if(kmod == 0.0) kmod = pow(klx*kly*klz, 1.0/3.0)/4.0;
std = sqrt(gsl_spline_eval(spline, kmod, acc)/2.0);
/*Generate Gaussian random number with std*/
deltak[ind][0] = (float)gsl_ran_gaussian(rng_ptr, std);
deltak[ind][1] = (float)gsl_ran_gaussian(rng_ptr, std);
deltak_tmp[ind][0] = deltak[ind][0];
deltak_tmp[ind][1] = deltak[ind][1];
if(isnan(deltak_tmp[ind][0])) printf("Problem with deltak_tmp[%ld][0]\n", ind);
if(isnan(deltak_tmp[ind][1])) printf("Problem with deltak_tmp[%ld][1]\n", ind);
}
}
}
gsl_spline_free(spline);
gsl_interp_accel_free(acc);
gsl_rng_free (rng_ptr);
/*Execute the FFTW3 to compute the density grid in real space*/
p1 = fftwf_plan_dft_c2r_3d(nx, ny, nz, deltak_tmp, delta, FFTW_ESTIMATE);
fftwf_execute(p1);
fftwf_free(deltak_tmp);
/*Save the density grid*/
if(out_inter == 1 || out_inter == 3){
printf("Saving the density grid\n");
den_grid = fopen(denfile, "wb");
if (den_grid == NULL) {
printf("Unable to open %s\n", denfile);
exit(0);
}
fwrite(&nx, sizeof(int), 1, den_grid);
fwrite(&ny, sizeof(int), 1, den_grid);
fwrite(&nz, sizeof(int), 1, den_grid);
fwrite(&Lc, sizeof(float), 1, den_grid);
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++){
size_t ind = (size_t)(i*ny + j)*(size_t)nz + (size_t)k;
fwrite(&delta[ind], sizeof(float), 1, den_grid);
}
fclose(den_grid);
}
}
/*Compute the mean and std of the linear density field*/
kx = 0.0;
ky = 0.0;
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++){
size_t ind = (size_t)(i*ny + j)*(size_t)nz + (size_t)k;
delta[ind] = delta[ind]*Normx;
kx += delta[ind]*delta[ind];
ky += delta[ind];
}
kx = kx/((float)nx*(float)ny*(float)nz);
ky = ky/((float)nx*(float)ny*(float)nz);
printf("Mean = %f and Sigma = %f\n", ky, sqrt(kx - ky*ky));
/*************************/
/* Finding the halos */
/*************************/
if(out_halos != 0){
printf("\nFinding the spherical halos!\n");
/*Alloc the flag array*/
flag = (int *)malloc((size_t)nx*(size_t)ny*(size_t)nz*sizeof(int));
check_memory(flag, "flag")
/*Initialize the flag array*/
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++){
size_t ind = (size_t)(i*ny + j)*(size_t)nz + (size_t)k;
flag[ind] = -1;
}
/*Counting the number of peaks*/
np = 0;
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++){
size_t ind = (size_t)(i*ny + j)*(size_t)nz + (size_t)k;
den = delta[ind];
if(den > delta[(size_t)(cysum(i, 1, nx)*ny + j)*(size_t)nz + (size_t)k] && den > delta[(size_t)(cysum(i, -1, nx)*ny + j)*(size_t)nz + (size_t)k] && den > delta[(size_t)(i*ny + cysum(j, 1, ny))*(size_t)nz + (size_t)k] && den > delta[(size_t)(i*ny + cysum(j, -1, ny))*(size_t)nz + (size_t)k] && den > delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 1, nz)] && den > delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -1, nz)])
np++;
}
/*Alloc the array with the peaks and final halos*/
peaks = (PEAKS *)malloc(np*sizeof(PEAKS));
halos = (HALOS *)malloc(np*sizeof(HALOS));
cont = 0;
/*Save the position and density of each peak*/
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++){
size_t ind = (size_t)(i*ny + j)*(size_t)nz + (size_t)k;
den = delta[ind];
if(den > delta[(size_t)(cysum(i, 1, nx)*ny + j)*(size_t)nz + (size_t)k] && den > delta[(size_t)(cysum(i, -1, nx)*ny + j)*(size_t)nz + (size_t)k] && den > delta[(size_t)(i*ny + cysum(j, 1, ny))*(size_t)nz + (size_t)k] && den > delta[(size_t)(i*ny + cysum(j, -1, ny))*(size_t)nz + (size_t)k] && den > delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 1, nz)] && den > delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -1, nz)]){
peaks[cont].x[0] = i;
peaks[cont].x[1] = j;
peaks[cont].x[2] = k;
peaks[cont].den = den;
cont ++;
}
}
/*Check the new number of peaks and elements in the peaks array*/
if(cont != np){
printf("The number of peaks does not match. %ld != %ld!\n", np, cont);
exit(0);
}
/*Sort the peaks*/
quickSort_peaks(peaks, 0, np-1);
/*Grow the spherical halos around the density peaks*/
nh = 0;
printf("We have %ld peaks\n", np);
for(l=0;l<np;l++){
/*If this peak is already in a halo jump to teh next one*/
if(flag[(size_t)(peaks[l].x[0]*ny + peaks[l].x[1])*(size_t)nz + (size_t)peaks[l].x[2]] != -1)
continue;
/*Check if this peak is near to the slice used to construct the light cone*/
if(out_halos == 2 || out_halos == 3){
m = 1;
for(i=-Nrep_x;i<=Nrep_x;i++)
for(j=-Nrep_y;j<=Nrep_y;j++)
for(k=-Nrep_z;k<=Nrep_z;k++){
/*Compute the distance for this replic*/
Pos[0] = (peaks[l].x[0] + 0.5)*Lc + Lx*i - Pobs[0];
Pos[1] = (peaks[l].x[1] + 0.5)*Lc + Ly*j - Pobs[1];
Pos[2] = (peaks[l].x[2] + 0.5)*Lc + Lz*k - Pobs[2];
dist = 0.0;
for(m=0;m<3;m++)
dist += Pos[m]*Pos[m];
dist = sqrt(dist);
if(dist <= dist_min - Rmax || dist > dist_max + Rmax) m = 0;
/*Compute the angle theta*/
cost = 0.0;
for(m=0;m<3;m++)
cost += Pos[m]*LoS[m];
cost = cost/dist;
if(theta_min + Rmax/dist < M_PI && cost < cos(theta_min + Rmax/dist)) m = 0;
}
if(m == 0)
continue;
}
den = peaks[l].den;
den_tmp = peaks[l].den;
cont = 0;
cont_tmp = 1;
grows_tmp = 0;
/*Grows the shells up to the minimum of the barrier*/
while(den_tmp >= Barrier(Sig_grid[Ncells - 1], dc, BARRIER, EB_a, EB_b, EB_alpha)){
if(cont < cont_tmp) grows = grows_tmp;
grows_tmp ++;
den = den_tmp;
cont = cont_tmp;
den_tmp = den*(float)cont;
tmp = floor(sqrt((double) grows_tmp));
if(tmp > nmin/2) tmp = nmin/2;
for(i=-tmp;i<=tmp;i++)
for(j=-tmp;j<=tmp;j++)
for(k=-tmp;k<=tmp;k++)
if(dist2(i, j, k) == grows_tmp){
size_t ind = (size_t)(cysum(peaks[l].x[0], i, nx)*ny + cysum(peaks[l].x[1], j, ny))*(size_t)nz + (size_t)cysum(peaks[l].x[2], k, nz);
if(flag[ind] != -1)
den_tmp += -Mtot;
else
den_tmp += delta[ind];
cont_tmp ++;
}
den_tmp = den_tmp/(float)cont_tmp;
}
/*Decrease the shells up to the correct value of the barrier*/
while(den < Barrier(Sig_grid[cont], dc, BARRIER, EB_a, EB_b, EB_alpha) && cont > 0){
den_tmp = den;
cont_tmp = cont;
den = den*(float)cont;
tmp = floor(sqrt((double) grows));
if(tmp > nmin/2) tmp = nmin/2;
for(i=-tmp;i<=tmp;i++)
for(j=-tmp;j<=tmp;j++)
for(k=-tmp;k<=tmp;k++)
if(dist2(i, j, k) == grows){
size_t ind = (size_t)(cysum(peaks[l].x[0], i, nx)*ny + cysum(peaks[l].x[1], j, ny))*(size_t)nz + (size_t)cysum(peaks[l].x[2], k, nz);
den -= delta[ind];
cont --;
}
if(cont > 0) den = den/(float)cont;
if(cont < cont_tmp) grows_tmp = grows;
grows --;
}
if(cont == 0)
continue;
/*Put the correct flags to the cells*/
tmp = floor(sqrt((double) grows_tmp));
for(i=-tmp;i<=tmp;i++)
for(j=-tmp;j<=tmp;j++)
for(k=-tmp;k<=tmp;k++)
if(dist2(i, j, k) < grows_tmp){
size_t ind = (size_t)(cysum(peaks[l].x[0], i, nx)*ny + cysum(peaks[l].x[1], j, ny))*(size_t)nz + (size_t)cysum(peaks[l].x[2], k, nz);
if(flag[ind] != -1)
printf("(1): This flag != -1! Flag = %d and the new one is %ld\n", flag[ind], nh);
flag[ind] = nh;
}
/*Save the halo information*/
if(cont >= Nmin){
halos[nh].cont = cont;
for(i=0;i<3;i++)
halos[nh].x[i] = peaks[l].x[i];
nh ++;
}
else{
for(i=-tmp;i<=tmp;i++)
for(j=-tmp;j<=tmp;j++)
for(k=-tmp;k<=tmp;k++)
if(dist2(i, j, k) < grows_tmp){
size_t ind = (size_t)(cysum(peaks[l].x[0], i, nx)*ny + cysum(peaks[l].x[1], j, ny))*(size_t)nz + (size_t)cysum(peaks[l].x[2], k, nz);
flag[ind] = -2;
}
}
}
free(peaks);
free(Sig_grid);
/*Find the possible number of particles in a halo
sphere = (int *)malloc(Ncells*sizeof(int));
m = 0;
for(l=0;l<10000;l++){
if(l%100 == 0)
printf("l = %ld\n", l);
tmp = floor(sqrt((float) l));
cont = 0;
for(i=-tmp;i<=tmp;i++)
for(j=-tmp;j<=tmp;j++)
for(k=-tmp;k<=tmp;k++)
if(dist2(i, j, k) == l)
cont ++;
if(cont > 0){
if(m > 0) sphere[m] = sphere[m-1] + cont;
else sphere[m] = cont;
m ++;
}
}
/*Save this information
den_grid = fopen("Spheres.dat", "wb");
if (den_grid == NULL) {
printf("Unable to open spheres.dat\n");
exit(0);
}
fwrite(&m, sizeof(int), 1, den_grid);
for(i=0;i<m;i++)
fwrite(&sphere[i], sizeof(int), 1, den_grid);
fclose(den_grid);*/
/*Read the data with the number of cells in each sphere*/
den_grid = fopen("Spheres.dat", "rb");
if (den_grid == NULL) {
printf("Unable to open spheres.dat\n");
exit(0);
}
fread(&m, sizeof(int), 1, den_grid);
sphere = (int *)malloc(m*sizeof(int));
for(i=0;i<m;i++)
fread(&sphere[i], sizeof(int), 1, den_grid);
fclose(den_grid);
printf("We have %ld halos\n", nh);
}
/********************************/
/* Displacing the particles */
/********************************/
printf("\nDisplacing the particles using 1LPT!\n");
/*Define the arrays to store the final position, velocity and mass of each halo*/
float **velh, **posh, *Massh;
if(out_halos != 0){
gsl_rng *rng_ptr;
rng_ptr = gsl_rng_alloc (gsl_rng_taus);
gsl_rng_set(rng_ptr, seed);
Massh = (float *)malloc(nh*sizeof(float));
velh = (float **)malloc(nh*sizeof(float *));
posh = (float **)malloc(nh*sizeof(float *));
for(i=0;i<nh;i++){
velh[i] = (float *)malloc(3*sizeof(float));
posh[i] = (float *)malloc(3*sizeof(float));
for(j=0;j<3;j++){
posh[i][j] = 0.0;
velh[i][j] = 0.0;
}
cont = Next_Count(sphere, Ncells, halos[i].cont);
den_tmp = gsl_spline_eval(spline_I, halos[i].cont*Mcell, acc_I) + (gsl_spline_eval(spline_I, sphere[cont]*Mcell, acc_I) - gsl_spline_eval(spline_I, halos[i].cont*Mcell, acc_I))*gsl_rng_uniform(rng_ptr);
Massh[i] = gsl_spline_eval(spline_InvI, den_tmp, acc_InvI);
}
free(sphere);
}
/*Read the displacement field*/
if(DISP_CAT == 0){
/*Open the output file for the displacement field*/
printf("Reading the displacement field\n");
disp_cat = fopen(dispfile, "rb");
if (disp_cat == NULL) {
printf("Unable to open %s\n", dispfile);
exit(0);
}
fread(&nx, sizeof(int), 1, disp_cat);
fread(&ny, sizeof(int), 1, disp_cat);
fread(&nz, sizeof(int), 1, disp_cat);
fread(&Lc, sizeof(float), 1, disp_cat);
/*Read the displacement and add to each halo*/
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++){
size_t ind = (size_t)(i*ny + j)*(size_t)nz + (size_t)k;
if(DO_2LPT == 0){
fread(&kx, sizeof(float), 1, disp_cat);
fread(&ky, sizeof(float), 1, disp_cat);
fread(&kz, sizeof(float), 1, disp_cat);
if(out_halos != 0){
tmp = flag[ind];
if(tmp < 0) continue;
posh[tmp][0] += Growth*kx;
posh[tmp][1] += Growth*ky;
posh[tmp][2] += Growth*kz;
velh[tmp][0] += Growth*pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*kx;
velh[tmp][1] += Growth*pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*ky;
velh[tmp][2] += Growth*pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*kz;
}
}
else{
fread(&kx, sizeof(float), 1, disp_cat);
fread(&ky, sizeof(float), 1, disp_cat);
fread(&kz, sizeof(float), 1, disp_cat);
fread(&factx, sizeof(float), 1, disp_cat);
fread(&facty, sizeof(float), 1, disp_cat);
fread(&factz, sizeof(float), 1, disp_cat);
if(out_halos != 0){
tmp = flag[ind];
if(tmp < 0) continue;
posh[tmp][0] += Growth*(kx - Growth*3.0/7.0*pow(Omz, -1.0/143)*factx);
posh[tmp][1] += Growth*(ky - Growth*3.0/7.0*pow(Omz, -1.0/143)*facty);
posh[tmp][2] += Growth*(kz - Growth*3.0/7.0*pow(Omz, -1.0/143)*factz);
velh[tmp][0] += Growth*(pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*kx); //- Growth*3.0/7.0*pow(Omz, -1.0/143)*2.0*pow(Omz, 6.0/11.0)*Hz/(1.0 + redshift)*factx);
velh[tmp][1] += Growth*(pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*ky); //- Growth*3.0/7.0*pow(Omz, -1.0/143)*2.0*pow(Omz, 6.0/11.0)*Hz/(1.0 + redshift)*facty);
velh[tmp][2] += Growth*(pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*kz); //- Growth*3.0/7.0*pow(Omz, -1.0/143)*2.0*pow(Omz, 6.0/11.0)*Hz/(1.0 + redshift)*factz);
}
}
}
fclose(disp_cat);
}
/*Compute the displacement field*/
if(DISP_CAT == 1){
/*Define the arrays with the displacement field used in 2LPT*/
float *S1, *S2, *S3;
if(DO_2LPT == 1){
S1 = (float *)malloc((size_t)nx*(size_t)ny*(size_t)nz*sizeof(float));
S2 = (float *)malloc((size_t)nx*(size_t)ny*(size_t)nz*sizeof(float));
S3 = (float *)malloc((size_t)nx*(size_t)ny*(size_t)nz*sizeof(float));
}
/*Alloc deltak*/
if(DEN_GRID == 0){
deltak = (fftwf_complex *) fftwf_malloc((size_t)nx*(size_t)ny*(size_t)nz2*sizeof(fftwf_complex));
check_memory(deltak, "deltak")
}
/*Redefine the FFTW3 plan to compute the displacements*/
fftwf_destroy_plan(p1);
p1 = NULL;
p1 = fftwf_plan_dft_c2r_3d(nx, ny, nz, deltak, delta, FFTW_ESTIMATE);
/*Divide the fourier space density by the green's function*/
#pragma omp parallel for private(i, j, k, kx, ky, kz, factx, facty, factz, fact)
for(i=0;i<nx;i++){
if(2*i<nx) kx = i*klx;
else kx = (i-nx)*klx;
factx = 1.0/90.0*(2.0*cos(3.0*kx*Lc) - 27.0*cos(2.0*kx*Lc) + 270.0*cos(kx*Lc) - 245.0)/(Lc*Lc);
for(j=0;j<ny;j++){
if(2*j<ny) ky = j*kly;
else ky = (j-ny)*kly;
facty = 1.0/90.0*(2.0*cos(3.0*ky*Lc) - 27.0*cos(2.0*ky*Lc) + 270.0*cos(ky*Lc) - 245.0)/(Lc*Lc);
for(k=0;k<nz2;k++){
kz = k*klz;
if(k == nz/2) kz = -(float)nz/2.0*klz;
factz = 1.0/90.0*(2.0*cos(3.0*kz*Lc) - 27.0*cos(2.0*kz*Lc) + 270.0*cos(kz*Lc) - 245.0)/(Lc*Lc);
size_t ind = (size_t)(i*ny + j)*(size_t)nz2 + (size_t)k;
if(kx != 0.0 || ky != 0.0 || kz != 0.0){
fact = factx + facty + factz;
deltak[ind][0] = deltak[ind][0]/fact;
deltak[ind][1] = deltak[ind][1]/fact;
}
else{
deltak[ind][0] = 0.0;
deltak[ind][1] = 0.0;
}
}
}
}
/*Compute the potential at first order*/
fftwf_execute(p1);
/*Compute the first order displacements and update the position and velocity of each halo*/
if(DO_2LPT == 1){
#pragma omp parallel for private(i, j, k, tmp)
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++){
size_t ind = (size_t)(i*ny + j)*(size_t)nz + (size_t)k;
S1[ind] = -(1.0*delta[(size_t)(cysum(i, 3, nx)*ny + j)*(size_t)nz + (size_t)k] - 9.0*delta[(size_t)(cysum(i, 2, nx)*ny + j)*(size_t)nz + (size_t)k] + 45.0*delta[(size_t)(cysum(i, 1, nx)*ny + j)*(size_t)nz + (size_t)k] - 45.0*delta[(size_t)(cysum(i, -1, nx)*ny + j)*(size_t)nz + (size_t)k] + 9.0*delta[(size_t)(cysum(i, -2, nx)*ny + j)*(size_t)nz + (size_t)k] - 1.0*delta[(size_t)(cysum(i, -3, nx)*ny + j)*(size_t)nz + (size_t)k])*Normx/(60.0*Lc);
S2[ind] = -(1.0*delta[(size_t)(i*ny + cysum(j, 3, ny))*(size_t)nz + (size_t)k] - 9.0*delta[(size_t)(i*ny + cysum(j, 2, ny))*(size_t)nz + (size_t)k] + 45.0*delta[(size_t)(i*ny + cysum(j, 1, ny))*(size_t)nz + (size_t)k] - 45.0*delta[(size_t)(i*nx + cysum(j, -1, ny))*(size_t)nz + (size_t)k] + 9.0*delta[(size_t)(i*ny + cysum(j, -2, ny))*(size_t)nz + (size_t)k] - 1.0*delta[(size_t)(i*ny + cysum(j, -3, ny))*(size_t)nz + (size_t)k])*Normx/(60.0*Lc);
S3[ind] = -(1.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 3, nz)] - 9.0*delta[(size_t)(i*ny + j)*nz + (size_t)cysum(k, 2, nz)] + 45.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 1, nz)] - 45.0*delta[(size_t)(i*ny + j)*(size_t)nz + cysum(k, -1, nz)] + 9.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -2, nz)] - 1.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -3, nz)])*Normx/(60.0*Lc);
if(out_halos != 0){
tmp = flag[ind];
if(tmp < 0) continue;
posh[tmp][0] += S1[ind];
posh[tmp][1] += S2[ind];
posh[tmp][2] += S3[ind];
velh[tmp][0] += pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*S1[ind];
velh[tmp][1] += pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*S2[ind];
velh[tmp][2] += pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*S3[ind];
}
}
}
else{
/*Open the output file for the displacement field*/
if(out_inter == 2 || out_inter == 3){
printf("Saving the displaced particles\n");
disp_cat = fopen(dispfile, "wb");
if (disp_cat == NULL) {
printf("Unable to open %s\n", dispfile);
exit(0);
}
fwrite(&nx, sizeof(int), 1, disp_cat);
fwrite(&ny, sizeof(int), 1, disp_cat);
fwrite(&nz, sizeof(int), 1, disp_cat);
fwrite(&Lc, sizeof(float), 1, disp_cat);
}
#pragma omp parallel for private(i, j, k, tmp, kx, ky, kz)
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++){
size_t ind = (size_t)(i*ny + j)*(size_t)nz + (size_t)k;
/*save the displacement field*/
if(out_inter == 2 || out_inter == 3){
kx = -(1.0*delta[(size_t)(cysum(i, 3, nx)*ny + j)*(size_t)nz + (size_t)k] - 9.0*delta[(size_t)(cysum(i, 2, nx)*ny + j)*(size_t)nz + (size_t)k] + 45.0*delta[(size_t)(cysum(i, 1, nx)*ny + j)*(size_t)nz + (size_t)k] - 45.0*delta[(size_t)(cysum(i, -1, nx)*ny + j)*(size_t)nz + (size_t)k] + 9.0*delta[(size_t)(cysum(i, -2, nx)*ny + j)*(size_t)nz + (size_t)k] - 1.0*delta[(size_t)(cysum(i, -3, nx)*ny + j)*(size_t)nz + (size_t)k])*Normx/(60.0*Lc);
ky = -(1.0*delta[(size_t)(i*ny + cysum(j, 3, ny))*(size_t)nz + (size_t)k] - 9.0*delta[(size_t)(i*ny + cysum(j, 2, ny))*(size_t)nz + (size_t)k] + 45.0*delta[(size_t)(i*ny + cysum(j, 1, ny))*(size_t)nz + (size_t)k] - 45.0*delta[(size_t)(i*nx + cysum(j, -1, ny))*(size_t)nz + (size_t)k] + 9.0*delta[(size_t)(i*ny + cysum(j, -2, ny))*(size_t)nz + (size_t)k] - 1.0*delta[(size_t)(i*ny + cysum(j, -3, ny))*(size_t)nz + (size_t)k])*Normx/(60.0*Lc);
kz = -(1.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 3, nz)] - 9.0*delta[(size_t)(i*ny + j)*nz + (size_t)cysum(k, 2, nz)] + 45.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 1, nz)] - 45.0*delta[(size_t)(i*ny + j)*(size_t)nz + cysum(k, -1, nz)] + 9.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -2, nz)] - 1.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -3, nz)])*Normx/(60.0*Lc);
fwrite(&kx, sizeof(float), 1, disp_cat);
fwrite(&ky, sizeof(float), 1, disp_cat);
fwrite(&kz, sizeof(float), 1, disp_cat);
if(out_halos != 0){
tmp = flag[ind];
if(tmp < 0) continue;
posh[tmp][0] += kx;
posh[tmp][1] += ky;
posh[tmp][2] += kz;
velh[tmp][0] += pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*kx;
velh[tmp][1] += pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*ky;
velh[tmp][2] += pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*kz;
}
}
/*Do not save the displacements*/
else if(out_halos != 0){
tmp = flag[ind];
if(tmp < 0) continue;
kx = -(1.0*delta[(size_t)(cysum(i, 3, nx)*ny + j)*(size_t)nz + (size_t)k] - 9.0*delta[(size_t)(cysum(i, 2, nx)*ny + j)*(size_t)nz + (size_t)k] + 45.0*delta[(size_t)(cysum(i, 1, nx)*ny + j)*(size_t)nz + (size_t)k] - 45.0*delta[(size_t)(cysum(i, -1, nx)*ny + j)*(size_t)nz + (size_t)k] + 9.0*delta[(size_t)(cysum(i, -2, nx)*ny + j)*(size_t)nz + (size_t)k] - 1.0*delta[(size_t)(cysum(i, -3, nx)*ny + j)*(size_t)nz + (size_t)k])*Normx/(60.0*Lc);
ky = -(1.0*delta[(size_t)(i*ny + cysum(j, 3, ny))*(size_t)nz + (size_t)k] - 9.0*delta[(size_t)(i*ny + cysum(j, 2, ny))*(size_t)nz + (size_t)k] + 45.0*delta[(size_t)(i*ny + cysum(j, 1, ny))*(size_t)nz + (size_t)k] - 45.0*delta[(size_t)(i*nx + cysum(j, -1, ny))*(size_t)nz + (size_t)k] + 9.0*delta[(size_t)(i*ny + cysum(j, -2, ny))*(size_t)nz + (size_t)k] - 1.0*delta[(size_t)(i*ny + cysum(j, -3, ny))*(size_t)nz + (size_t)k])*Normx/(60.0*Lc);
kz = -(1.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 3, nz)] - 9.0*delta[(size_t)(i*ny + j)*nz + (size_t)cysum(k, 2, nz)] + 45.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 1, nz)] - 45.0*delta[(size_t)(i*ny + j)*(size_t)nz + cysum(k, -1, nz)] + 9.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -2, nz)] - 1.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -3, nz)])*Normx/(60.0*Lc);
posh[tmp][0] += kx;
posh[tmp][1] += ky;
posh[tmp][2] += kz;
velh[tmp][0] += pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*kx;
velh[tmp][1] += pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*ky;
velh[tmp][2] += pow(Omz, 5.0/9.0)*Hz/(1.0 + redshift)*kz;
}
}
if(out_inter == 2 || out_inter == 3)
fclose(disp_cat);
}
if(DO_2LPT == 1){
printf("Displacing the particles using 2LPT!\n");
/*Evaluating the second order contribution*/
p2 = fftwf_plan_dft_r2c_3d(nx, ny, nz, delta, deltak, FFTW_ESTIMATE);
/*Compute the second order "density"*/
#pragma omp parallel for private(i, j, k)
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++){
phixx = (1.0*S1[(size_t)(cysum(i, 3, nx)*ny + j)*(size_t)nz + (size_t)k] - 9.0*S1[(size_t)(cysum(i, 2, nx)*ny + j)*(size_t)nz + (size_t)k] + 45.0*S1[(size_t)(cysum(i, 1, nx)*ny + j)*(size_t)nz + (size_t)k] - 45.0*S1[(size_t)(cysum(i, -1, nx)*ny + j)*(size_t)nz + (size_t)k] + 9.0*S1[(size_t)(cysum(i, -2, nx)*ny + j)*(size_t)nz + (size_t)k] - 1.0*S1[(size_t)(cysum(i, -3, nx)*ny + j)*(size_t)nz + (size_t)k])/(60.0*Lc);
phixy = (1.0*S1[(size_t)(i*ny + cysum(j, 3, ny))*(size_t)nz + (size_t)k] - 9.0*S1[(size_t)(i*ny + cysum(j, 2, ny))*(size_t)nz + (size_t)k] + 45.0*S1[(size_t)(i*ny + cysum(j, 1, ny))*(size_t)nz + (size_t)k] - 45.0*S1[(size_t)(i*nx + cysum(j, -1, ny))*(size_t)nz + (size_t)k] + 9.0*S1[(size_t)(i*ny + cysum(j, -2, ny))*(size_t)nz + (size_t)k] - 1.0*S1[(size_t)(i*ny + cysum(j, -3, ny))*(size_t)nz + (size_t)k])/(60.0*Lc);
phixz = (1.0*S1[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 3, nz)] - 9.0*S1[(size_t)(i*ny + j)*nz + (size_t)cysum(k, 2, nz)] + 45.0*S1[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 1, nz)] - 45.0*S1[(size_t)(i*ny + j)*(size_t)nz + cysum(k, -1, nz)] + 9.0*S1[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -2, nz)] - 1.0*S1[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -3, nz)])/(60.0*Lc);
phiyy = (1.0*S2[(size_t)(i*ny + cysum(j, 3, ny))*(size_t)nz + (size_t)k] - 9.0*S2[(size_t)(i*ny + cysum(j, 2, ny))*(size_t)nz + (size_t)k] + 45.0*S2[(size_t)(i*ny + cysum(j, 1, ny))*(size_t)nz + (size_t)k] - 45.0*S2[(size_t)(i*nx + cysum(j, -1, ny))*(size_t)nz + (size_t)k] + 9.0*S2[(size_t)(i*ny + cysum(j, -2, ny))*(size_t)nz + (size_t)k] - 1.0*S2[(size_t)(i*ny + cysum(j, -3, ny))*(size_t)nz + (size_t)k])/(60.0*Lc);
phiyz = (1.0*S2[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 3, nz)] - 9.0*S2[(size_t)(i*ny + j)*nz + (size_t)cysum(k, 2, nz)] + 45.0*S2[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 1, nz)] - 45.0*S2[(size_t)(i*ny + j)*(size_t)nz + cysum(k, -1, nz)] + 9.0*S2[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -2, nz)] - 1.0*S2[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -3, nz)])/(60.0*Lc);
phizz = (1.0*S3[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 3, nz)] - 9.0*S3[(size_t)(i*ny + j)*nz + (size_t)cysum(k, 2, nz)] + 45.0*S3[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 1, nz)] - 45.0*S3[(size_t)(i*ny + j)*(size_t)nz + cysum(k, -1, nz)] + 9.0*S3[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -2, nz)] - 1.0*S3[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -3, nz)])/(60.0*Lc);
delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)k] = 1.0*(phixx*phiyy + phixx*phizz + phiyy*phizz - pow(phixy, 2.0) - pow(phixz, 2.0) - pow(phiyz, 2.0));
}
/*Go to fourier space to solve the posson equation*/
fftwf_execute(p2);
/*Divide the fourier space density by the green's function*/
#pragma omp parallel for private(i, j, k, kx, ky, kz, fact, factx, facty, factz)
for(i=0;i<nx;i++){
if(2*i<nx) kx = i*klx;
else kx = (i-nx)*klx;
factx = 1.0/90.0*(2.0*cos(3.0*kx*Lc) - 27.0*cos(2.0*kx*Lc) + 270.0*cos(kx*Lc) - 245.0)/(Lc*Lc);
for(j=0;j<ny;j++){
if(2*j<ny) ky = j*kly;
else ky = (j-ny)*kly;
facty = 1.0/90.0*(2.0*cos(3.0*ky*Lc) - 27.0*cos(2.0*ky*Lc) + 270.0*cos(ky*Lc) - 245.0)/(Lc*Lc);
for(k=0;k<nz2;k++){
kz = k*klz;
if(k == nz/2) kz = -(float)nz/2.0*klz;
factz = 1.0/90.0*(2.0*cos(3.0*kz*Lc) - 27.0*cos(2.0*kz*Lc) + 270.0*cos(kz*Lc) - 245.0)/(Lc*Lc);
size_t ind = (size_t)(i*ny + j)*(size_t)nz2 + (size_t)k;
if(kx != 0.0 || ky != 0.0 || kz != 0.0){
fact = factx + facty + factz;
deltak[ind][0] = deltak[ind][0]/fact*Normk;
deltak[ind][1] = deltak[ind][1]/fact*Normk;
}
else{
deltak[ind][0] = 0.0;
deltak[ind][1] = 0.0;
}
}
}
}
/*Come back to real space*/
fftwf_execute(p1);
/*Open the output file for the displacement field*/
if(out_inter == 2 || out_inter == 3){
printf("Saving the displaced particles\n");
disp_cat = fopen(dispfile, "wb");
if (disp_cat == NULL) {
printf("Unable to open %s\n", dispfile);
exit(0);
}
fwrite(&nx, sizeof(int), 1, disp_cat);
fwrite(&ny, sizeof(int), 1, disp_cat);
fwrite(&nz, sizeof(int), 1, disp_cat);
fwrite(&Lc, sizeof(float), 1, disp_cat);
}
/*Compute the second order displacements and velocities*/
#pragma omp parallel for private(i, j, k, kx, ky, kz, tmp)
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++){
size_t ind = (size_t)(i*ny + j)*(size_t)nz + (size_t)k;
/*save the displacement field*/
if(out_inter == 2 || out_inter == 3){
kx = (1.0*delta[(size_t)(cysum(i, 3, nx)*ny + j)*(size_t)nz + (size_t)k] - 9.0*delta[(size_t)(cysum(i, 2, nx)*ny + j)*(size_t)nz + (size_t)k] + 45.0*delta[(size_t)(cysum(i, 1, nx)*ny + j)*(size_t)nz + (size_t)k] - 45.0*delta[(size_t)(cysum(i, -1, nx)*ny + j)*(size_t)nz + (size_t)k] + 9.0*delta[(size_t)(cysum(i, -2, nx)*ny + j)*(size_t)nz + (size_t)k] - 1.0*delta[(size_t)(cysum(i, -3, nx)*ny + j)*(size_t)nz + (size_t)k])*Normx/(60.0*Lc);
ky = (1.0*delta[(size_t)(i*ny + cysum(j, 3, ny))*(size_t)nz + (size_t)k] - 9.0*delta[(size_t)(i*ny + cysum(j, 2, ny))*(size_t)nz + (size_t)k] + 45.0*delta[(size_t)(i*ny + cysum(j, 1, ny))*(size_t)nz + (size_t)k] - 45.0*delta[(size_t)(i*nx + cysum(j, -1, ny))*(size_t)nz + (size_t)k] + 9.0*delta[(size_t)(i*ny + cysum(j, -2, ny))*(size_t)nz + (size_t)k] - 1.0*delta[(size_t)(i*ny + cysum(j, -3, ny))*(size_t)nz + (size_t)k])*Normx/(60.0*Lc);
kz = (1.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 3, nz)] - 9.0*delta[(size_t)(i*ny + j)*nz + (size_t)cysum(k, 2, nz)] + 45.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 1, nz)] - 45.0*delta[(size_t)(i*ny + j)*(size_t)nz + cysum(k, -1, nz)] + 9.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -2, nz)] - 1.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -3, nz)])*Normx/(60.0*Lc);
fwrite(&S1[ind], sizeof(float), 1, disp_cat);
fwrite(&S2[ind], sizeof(float), 1, disp_cat);
fwrite(&S3[ind], sizeof(float), 1, disp_cat);
fwrite(&kx, sizeof(float), 1, disp_cat);
fwrite(&ky, sizeof(float), 1, disp_cat);
fwrite(&kz, sizeof(float), 1, disp_cat);
if(out_halos != 0){
tmp = flag[ind];
if(tmp < 0) continue;
kx = -3.0/7.0*pow(Omz, -1.0/143)*kx;
ky = -3.0/7.0*pow(Omz, -1.0/143)*ky;
kz = -3.0/7.0*pow(Omz, -1.0/143)*kz;
posh[tmp][0] += kx;
posh[tmp][1] += ky;
posh[tmp][2] += kz;
//velh[tmp][0] += 2.0*pow(Omz, 6.0/11.0)*Hz/(1.0 + redshift)*kx;
//velh[tmp][1] += 2.0*pow(Omz, 6.0/11.0)*Hz/(1.0 + redshift)*ky;
//velh[tmp][2] += 2.0*pow(Omz, 6.0/11.0)*Hz/(1.0 + redshift)*kz;
}
}
/*Do not save the displacements*/
else if(out_halos != 0){
tmp = flag[ind];
if(tmp < 0) continue;
kx = (1.0*delta[(size_t)(cysum(i, 3, nx)*ny + j)*(size_t)nz + (size_t)k] - 9.0*delta[(size_t)(cysum(i, 2, nx)*ny + j)*(size_t)nz + (size_t)k] + 45.0*delta[(size_t)(cysum(i, 1, nx)*ny + j)*(size_t)nz + (size_t)k] - 45.0*delta[(size_t)(cysum(i, -1, nx)*ny + j)*(size_t)nz + (size_t)k] + 9.0*delta[(size_t)(cysum(i, -2, nx)*ny + j)*(size_t)nz + (size_t)k] - 1.0*delta[(size_t)(cysum(i, -3, nx)*ny + j)*(size_t)nz + (size_t)k])*Normx/(60.0*Lc);
ky = (1.0*delta[(size_t)(i*ny + cysum(j, 3, ny))*(size_t)nz + (size_t)k] - 9.0*delta[(size_t)(i*ny + cysum(j, 2, ny))*(size_t)nz + (size_t)k] + 45.0*delta[(size_t)(i*ny + cysum(j, 1, ny))*(size_t)nz + (size_t)k] - 45.0*delta[(size_t)(i*nx + cysum(j, -1, ny))*(size_t)nz + (size_t)k] + 9.0*delta[(size_t)(i*ny + cysum(j, -2, ny))*(size_t)nz + (size_t)k] - 1.0*delta[(size_t)(i*ny + cysum(j, -3, ny))*(size_t)nz + (size_t)k])*Normx/(60.0*Lc);
kz = (1.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 3, nz)] - 9.0*delta[(size_t)(i*ny + j)*nz + (size_t)cysum(k, 2, nz)] + 45.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, 1, nz)] - 45.0*delta[(size_t)(i*ny + j)*(size_t)nz + cysum(k, -1, nz)] + 9.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -2, nz)] - 1.0*delta[(size_t)(i*ny + j)*(size_t)nz + (size_t)cysum(k, -3, nz)])*Normx/(60.0*Lc);
kx = -3.0/7.0*pow(Omz, -1.0/143)*kx;
ky = -3.0/7.0*pow(Omz, -1.0/143)*ky;
kz = -3.0/7.0*pow(Omz, -1.0/143)*kz;
posh[tmp][0] += kx;
posh[tmp][1] += ky;
posh[tmp][2] += kz;
//velh[tmp][0] += 2.0*pow(Omz, 6.0/11.0)*Hz/(1.0 + redshift)*kx;
//velh[tmp][1] += 2.0*pow(Omz, 6.0/11.0)*Hz/(1.0 + redshift)*ky;
//velh[tmp][2] += 2.0*pow(Omz, 6.0/11.0)*Hz/(1.0 + redshift)*kz;
}
}
if(out_inter == 2 || out_inter == 3)
fclose(disp_cat);
/*Free the FFTW memory*/
fftwf_destroy_plan(p2);
free(S1);
free(S2);
free(S3);
}
fftwf_destroy_plan(p1);
fftwf_free(deltak);
}
fftwf_free(delta);
if(out_collapse == 0 && out_halos != 0)
free(flag);
/*Compute the final position and velocity of the halos*/
if(out_halos != 0){
for(i=0;i<nh;i++){
posh[i][0] = cysumf(halos[i].x[0]*Lc + Lc/2.0, posh[i][0]/halos[i].cont, Lx);
posh[i][1] = cysumf(halos[i].x[1]*Lc + Lc/2.0, posh[i][1]/halos[i].cont, Ly);
posh[i][2] = cysumf(halos[i].x[2]*Lc + Lc/2.0, posh[i][2]/halos[i].cont, Lz);
velh[i][0] = velh[i][0]/halos[i].cont;
velh[i][1] = velh[i][1]/halos[i].cont;
velh[i][2] = velh[i][2]/halos[i].cont;
}
}
/*Saving the positions and velocities in real space*/
if(out_halos == 1){
printf("Saving the halos\n");
halo_cat = fopen(halofile, "w");
if (halo_cat == NULL) {
printf("Unable to open %s\n", halofile);
exit(0);
}
fprintf(halo_cat, "%ld\n", nh);
for(i=0;i<nh;i++){
fprintf(halo_cat, "%f %f %f %f %f %f %e %d\n", posh[i][0], posh[i][1], posh[i][2], velh[i][0], velh[i][1], velh[i][2], Massh[i], halos[i].cont);
}
fclose(halo_cat);
}
/*Putting galaxies in the halos*/
if(DO_HOD == 1){
printf("Saving the galaxies\n");
sprintf(halofile, "%s_gals.dat", argv[14]);
halo_cat = fopen(halofile, "w");
if (halo_cat == NULL) {
printf("Unable to open %s\n", halofile);
exit(0);
}
cont = 0;
for(i=0;i<nh;i++){
/*Compute the number of central and satellite galaxies*/
if(Ncentral(Massh[i], logMmin, siglogM) >= gsl_rng_uniform(rng_ptr))
Ncen = 1;
else
Ncen = 0;
Nsat = gsl_ran_poisson(rng_ptr, (double) Nsatellite(Massh[i], logM0, logM1, alpha));
Ngals = Ncen + Nsat;
if(Ngals == 0) continue;
/*Save the central galaxy*/
if(Ncen == 1){
fprintf(halo_cat, "%f %f %f %f %f %f %d\n", posh[i][0], posh[i][1], posh[i][2], velh[i][0], velh[i][1], velh[i][2], i);
cont ++;
}
/*Put the satellite galaxies following the NFW profile*/
if(Nsat > 0){
Rv = pow(3.0*Massh[i]/(4.0*M_PI*Dv*rhom), 1.0/3.0);
C = f_c(Massh[i], (float) Mstar, z);
A = log(1.0 + C) - C/(1.0 + C);
}
for(j=0;j<Nsat;j++){
phi = 2.0*M_PI*gsl_rng_uniform(rng_ptr);
theta = M_PI*gsl_rng_uniform(rng_ptr);
r = Generate_NFW(Rv, C, A, seed);
kx = cysumf(posh[i][0], r*sin(theta)*cos(phi), Lx);
ky = cysumf(posh[i][1], r*sin(theta)*sin(phi), Ly);
kz = cysumf(posh[i][2], r*cos(theta), Lz);
fprintf(halo_cat, "%f %f %f ", kx, ky, kz);
kx = velh[i][0];
ky = velh[i][1];
kz = velh[i][2];
fprintf(halo_cat, "%f %f %f %d\n", kx, ky, kz, i);
cont ++;
}
}
fclose(halo_cat);
n_bar = cont/(Lx*Ly*Lz);
printf("n_bar = %f\n", n_bar);
}
/********************************/
/*Put the halos in the lightcone*/
/********************************/
if(out_halos == 2 || out_halos == 3){
printf("\nPutting the halos in the light cone!\n");
printf("The code is using (%d, %d, %d) replicas to construct the light cone.\n", Nrep_x, Nrep_y, Nrep_z);
printf("This snapshot is in the range %f - %f [Mpc/h] with theta_min = %f.\n", dist_min, dist_max, theta_min);
/*Open the light cone file*/
light_cat = fopen(lightfile, "wb");
if (light_cat == NULL) {
printf("Unable to open %s\n", lightfile);
exit(0);
}
cont = 0;
fwrite(&cont, sizeof(long), 1, light_cat);
/*Run over all the halos and save then in the light cone file*/
for(l=0;l<nh;l++){
for(i=-Nrep_x;i<=Nrep_x;i++)
for(j=-Nrep_y;j<=Nrep_y;j++)
for(k=-Nrep_z;k<=Nrep_z;k++){
/*Compute the distance for this replic*/
Pos[0] = posh[l][0] + Lx*i - Pobs[0];
Pos[1] = posh[l][1] + Ly*j - Pobs[1];
Pos[2] = posh[l][2] + Lz*k - Pobs[2];
dist = 0.0;
for(m=0;m<3;m++)
dist += Pos[m]*Pos[m];
dist = sqrt(dist);
if(out_halos == 3){
/*Compute the distance in redshift space*/
vr = 0.0;
for(m=0;m<3;m++)
vr += velh[l][m]*Pos[m];
vr = vr/dist;
for(m=0;m<3;m++)
Pos[m] = Pos[m] + vr/Hz*(1.0 + redshift)*Pos[m]/dist;
dist = dist + vr/Hz*(1.0 + redshift);
}
if(dist <= dist_min || dist > dist_max) continue;
/*Compute the angle theta*/
cost = 0.0;
for(m=0;m<3;m++)
cost += Pos[m]*LoS[m];
cost = cost/dist;
if(cost < cos_min) continue;
/*Save the information about this halo*/
fwrite(&Pos[0], sizeof(float), 1, light_cat);
fwrite(&Pos[1], sizeof(float), 1, light_cat);
fwrite(&Pos[2], sizeof(float), 1, light_cat);
fwrite(&velh[l][0], sizeof(float), 1, light_cat);
fwrite(&velh[l][1], sizeof(float), 1, light_cat);
fwrite(&velh[l][2], sizeof(float), 1, light_cat);
fwrite(&Massh[l], sizeof(float), 1, light_cat);
cont ++;
/*Put galaxies in this halo (one type)*/
if(DO_HOD == 1){
/*Compute the number of central and satellite galaxies*/
if(Ncentral(Massh[l], logMmin, siglogM) >= gsl_rng_uniform(rng_ptr))
Ncen = 1;
else
Ncen = 0;
Nsat = gsl_ran_poisson(rng_ptr, (double) Nsatellite(Massh[l], logM0, logM1, alpha));
Ngals = Ncen + Nsat;
/*Save the total number of galaxies*/
fwrite(&Ngals, sizeof(int), 1, light_cat);
/*Save the central galaxy*/
fwrite(&Pos[0], sizeof(float), 1, light_cat);
fwrite(&Pos[1], sizeof(float), 1, light_cat);
fwrite(&Pos[2], sizeof(float), 1, light_cat);
fwrite(&velh[l][0], sizeof(float), 1, light_cat);
fwrite(&velh[l][1], sizeof(float), 1, light_cat);
fwrite(&velh[l][2], sizeof(float), 1, light_cat);
/*Put the satellite galaxies following the NFW profile*/
if(Nsat > 0){
Rv = pow(3.0*Massh[l]/(4.0*M_PI*Dv*rhom), 1.0/3.0);
C = f_c(Massh[l], (float) Mstar, z);
A = log(1.0 + C) - C/(1.0 + C);
}
for(m=0;m<Nsat;m++){
phi = 2.0*M_PI*gsl_rng_uniform(rng_ptr);
theta = M_PI*gsl_rng_uniform(rng_ptr);
r = Generate_NFW(Rv, C, A, seed);
kx = cysumf(Pos[0], r*sin(theta)*cos(phi), Lx);
ky = cysumf(Pos[1], r*sin(theta)*sin(phi), Ly);
kz = cysumf(Pos[2], r*cos(theta), Lz);
fwrite(&kx, sizeof(float), 1, light_cat);
fwrite(&ky, sizeof(float), 1, light_cat);
fwrite(&kz, sizeof(float), 1, light_cat);
kx = velh[i][0];
ky = velh[i][1];
kz = velh[i][2];
fwrite(&kx, sizeof(float), 1, light_cat);
fwrite(&ky, sizeof(float), 1, light_cat);
fwrite(&kz, sizeof(float), 1, light_cat);
}
}
}
}
rewind(light_cat);
fwrite(&cont, sizeof(long), 1, light_cat);
fclose(light_cat);
if(out_collapse == 1){
/*Open the file to save the information about the collapsed particles*/
collapse_cat = fopen(collapsefile, "wb");
if (collapse_cat == NULL) {
printf("Unable to open %s\n", collapsefile);
exit(0);
}
/*Save the information about the colapsed particles*/
int a, b, c;
cont = 0;
fwrite(&cont, sizeof(long), 1, collapse_cat);
#pragma omp parallel for private(i, j, k, a, b, c, Pos, dist, cost, tmp)
for(i=0;i<nx;i++)
for(j=0;j<ny;j++)
for(k=0;k<nz;k++){
size_t ind = (size_t)(i*ny + j)*(size_t)nz + (size_t)k;
for(a=-Nrep_x;a<=Nrep_x;a++)
for(b=-Nrep_y;b<=Nrep_y;b++)
for(c=-Nrep_z;c<=Nrep_z;c++){
/*Compute the distance for this replic*/
Pos[0] = i*Lc + Lc/2.0 + Lx*a;
Pos[1] = j*Lc + Lc/2.0 + Ly*b;
Pos[2] = k*Lc + Lc/2.0 + Lz*c;
dist = 0.0;
for(m=0;m<3;m++)
dist += Pos[m]*Pos[m];
dist = sqrt(dist);
if(dist <= dist_min || dist > dist_max) continue;
/*Compute the angle theta*/
cost = 0.0;
for(m=0;m<3;m++)
cost += Pos[m]*LoS[m];
cost = cost/dist;
if(cost < cos_min) continue;
tmp = flag[ind];
cont ++;
fwrite(&ind, sizeof(size_t), 1, collapse_cat);
fwrite(&tmp, sizeof(int), 1, collapse_cat);
fwrite(&redshift, sizeof(float), 1, collapse_cat);
}
}
rewind(collapse_cat);
fwrite(&cont, sizeof(long), 1, collapse_cat);
fclose(collapse_cat);
free(flag);
}
}
/*******************/
/* Free the memory */
/*******************/
gsl_spline_free(spline_I);
gsl_spline_free(spline_InvI);
gsl_interp_accel_free(acc_I);
gsl_interp_accel_free(acc_InvI);
if(out_halos != 0){
free(Massh);
for(i=0;i<nh;i++){
free(velh[i]);
free(posh[i]);
}
/*Free the rest*/
free(velh);
free(posh);
free(halos);
gsl_rng_free(rng_ptr);
}
return 0;
}
| {
"alphanum_fraction": 0.5988449806,
"avg_line_length": 35.9765721332,
"ext": "c",
"hexsha": "a025bd984afe135165fd81600df3a9ab7602d593",
"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": "d9b5937ffb496a75206baf788436732b7ace7717",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Voivodic/ExSHalos",
"max_forks_repo_path": "ExSHalosLC4.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d9b5937ffb496a75206baf788436732b7ace7717",
"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": "Voivodic/ExSHalos",
"max_issues_repo_path": "ExSHalosLC4.c",
"max_line_length": 450,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "d9b5937ffb496a75206baf788436732b7ace7717",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Voivodic/ExSHalos",
"max_stars_repo_path": "ExSHalosLC4.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T12:09:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-30T12:09:33.000Z",
"num_tokens": 22630,
"size": 58354
} |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef GSL_POINTERS_H
#define GSL_POINTERS_H
#include <gsl/gsl_assert> // for Ensures, Expects
#include <algorithm> // for forward
#include <iosfwd> // for ptrdiff_t, nullptr_t, ostream, size_t
#include <memory> // for shared_ptr, unique_ptr
#include <system_error> // for hash
#include <type_traits> // for enable_if_t, is_convertible, is_assignable
#if defined(_MSC_VER) && _MSC_VER < 1910
#pragma push_macro("constexpr")
#define constexpr /*constexpr*/
#endif // defined(_MSC_VER) && _MSC_VER < 1910
namespace gsl
{
//
// GSL.owner: ownership pointers
//
using std::unique_ptr;
using std::shared_ptr;
//
// owner
//
// owner<T> is designed as a bridge for code that must deal directly with owning pointers for some reason
//
// T must be a pointer type
// - disallow construction from any type other than pointer type
//
template <class T, class = std::enable_if_t<std::is_pointer<T>::value>>
using owner = T;
//
// not_null
//
// Restricts a pointer or smart pointer to only hold non-null values.
//
// Has zero size overhead over T.
//
// If T is a pointer (i.e. T == U*) then
// - allow construction from U*
// - disallow construction from nullptr_t
// - disallow default construction
// - ensure construction from null U* fails
// - allow implicit conversion to U*
//
template <class T>
class not_null
{
public:
static_assert(std::is_assignable<T&, std::nullptr_t>::value, "T cannot be assigned nullptr.");
template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>
constexpr explicit not_null(U&& u) : ptr_(std::forward<U>(u))
{
Expects(ptr_ != nullptr);
}
template <typename = std::enable_if_t<!std::is_same<std::nullptr_t, T>::value>>
constexpr explicit not_null(T u) : ptr_(u)
{
Expects(ptr_ != nullptr);
}
template <typename U, typename = std::enable_if_t<std::is_convertible<U, T>::value>>
constexpr not_null(const not_null<U>& other) : not_null(other.get())
{
}
not_null(not_null&& other) = default;
not_null(const not_null& other) = default;
not_null& operator=(const not_null& other) = default;
constexpr T get() const
{
Ensures(ptr_ != nullptr);
return ptr_;
}
constexpr operator T() const { return get(); }
constexpr T operator->() const { return get(); }
constexpr decltype(auto) operator*() const { return *get(); }
// prevents compilation when someone attempts to assign a null pointer constant
not_null(std::nullptr_t) = delete;
not_null& operator=(std::nullptr_t) = delete;
// unwanted operators...pointers only point to single objects!
not_null& operator++() = delete;
not_null& operator--() = delete;
not_null operator++(int) = delete;
not_null operator--(int) = delete;
not_null& operator+=(std::ptrdiff_t) = delete;
not_null& operator-=(std::ptrdiff_t) = delete;
void operator[](std::ptrdiff_t) const = delete;
private:
T ptr_;
};
template <class T>
auto make_not_null(T&& t) {
return gsl::not_null<std::remove_cv_t<std::remove_reference_t<T>>>{std::forward<T>(t)};
}
template <class T>
std::ostream& operator<<(std::ostream& os, const not_null<T>& val)
{
os << val.get();
return os;
}
template <class T, class U>
auto operator==(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() == rhs.get())
{
return lhs.get() == rhs.get();
}
template <class T, class U>
auto operator!=(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() != rhs.get())
{
return lhs.get() != rhs.get();
}
template <class T, class U>
auto operator<(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() < rhs.get())
{
return lhs.get() < rhs.get();
}
template <class T, class U>
auto operator<=(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() <= rhs.get())
{
return lhs.get() <= rhs.get();
}
template <class T, class U>
auto operator>(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() > rhs.get())
{
return lhs.get() > rhs.get();
}
template <class T, class U>
auto operator>=(const not_null<T>& lhs, const not_null<U>& rhs) -> decltype(lhs.get() >= rhs.get())
{
return lhs.get() >= rhs.get();
}
// more unwanted operators
template <class T, class U>
std::ptrdiff_t operator-(const not_null<T>&, const not_null<U>&) = delete;
template <class T>
not_null<T> operator-(const not_null<T>&, std::ptrdiff_t) = delete;
template <class T>
not_null<T> operator+(const not_null<T>&, std::ptrdiff_t) = delete;
template <class T>
not_null<T> operator+(std::ptrdiff_t, const not_null<T>&) = delete;
} // namespace gsl
namespace std
{
template <class T>
struct hash<gsl::not_null<T>>
{
std::size_t operator()(const gsl::not_null<T>& value) const { return hash<T>{}(value); }
};
} // namespace std
#if defined(_MSC_VER) && _MSC_VER < 1910
#undef constexpr
#pragma pop_macro("constexpr")
#endif // defined(_MSC_VER) && _MSC_VER < 1910
#endif // GSL_POINTERS_H
| {
"alphanum_fraction": 0.654236123,
"avg_line_length": 29.2412060302,
"ext": "h",
"hexsha": "a338856118419e8b1a10648677a8cb392177ef99",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-12-26T08:25:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-08-02T17:50:23.000Z",
"max_forks_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Redchards/CVRP",
"max_forks_repo_path": "include/gsl/pointers.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103",
"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": "Redchards/CVRP",
"max_issues_repo_path": "include/gsl/pointers.h",
"max_line_length": 105,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "f372f2fa06cb374ebdac2f6eee7e6fe297d94103",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Redchards/CVRP",
"max_stars_repo_path": "include/gsl/pointers.h",
"max_stars_repo_stars_event_max_datetime": "2020-08-15T05:01:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-01T14:40:11.000Z",
"num_tokens": 1455,
"size": 5819
} |
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Contains implementations of AdaDIF, TunedRwR, and PPR.
Dimitris Berberidis
University of Minnesota 2017-2018
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <cblas.h>
#include <inttypes.h>
#include <pthread.h>
#include <sys/sysinfo.h>
#include <stdbool.h>
#include "comp_engine.h"
#include "csr_handling.h"
#include "my_defs.h"
#include "parameter_opt.h"
#include "my_utils.h"
static sz_short get_threads_and_width(sz_short* , sz_short );
static double* get_coef_A(sz_long , sz_med , sz_med , sz_long* , double* ,double* , const sz_long* , double );
static double* get_coef_b(sz_long , sz_med , sz_med ,sz_med , sz_long* , double* , sz_long* );
//Multi-threaded AdaDIF method (output is soft labels)
void AdaDIF_core_multi_thread( double* soft_labels, csr_graph graph, sz_med num_seeds,
const sz_long* seed_indices, sz_short num_class, sz_short* class_ind,
sz_med* num_per_class, sz_med walk_length, double lambda, bool no_constr, bool single_thread){
sz_short NUM_THREADS, width;
NUM_THREADS = get_threads_and_width(&width, num_class);
if(single_thread) NUM_THREADS = 1;
printf("NUMBER OF THREADS: %"PRIu16" \n", (uint16_t) NUM_THREADS);
#if DEBUG
printf("WIDTH= %"PRIu16"\n", (uint16_t) width);
#endif
clock_t begin = clock();
//The following three blocks create copies of the CSR matrix
//Each copy will be used by a thread
csr_graph* graph_copies = csr_mult_deep_copy( graph, NUM_THREADS );
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Time spent copying csr_matrix: %lf\n",time_spent);
//MAIN LOOP
//Prepare data to be passed to each thread
pthread_t tid[NUM_THREADS];
pass_to_thread_type_2* data= (pass_to_thread_type_2*)malloc(NUM_THREADS*sizeof(pass_to_thread_type_2));
for(sz_short i=0;i<NUM_THREADS;i++){
(*(data+i))= (pass_to_thread_type_2) {.soft_labels=soft_labels,
.num_seeds=num_seeds,
.num_per_class=num_per_class,
.class_ind=class_ind,
.graph = graph_copies[i],
.seeds=seed_indices,
.walk_length=walk_length,
.lambda=lambda,
.from=i*width,
.no_constr = no_constr };
if(i==NUM_THREADS-1){
(data+i)->to=NUM_THREADS;
(data+i)->num_local_classes= num_class -i*width;
}else{
(data+i)->to=(i+1)*width;
(data+i)->num_local_classes=width;
}
}
//Spawn threads and start running
for(sz_short i=0;i<NUM_THREADS;i++){
pthread_create(&tid[i],NULL,AdaDIF_squezze_to_one_thread,(void*)(data+i));
}
//Wait for all threads to finish before continuing
for(sz_short i=0;i<NUM_THREADS;i++){pthread_join(tid[i], NULL);}
//Free copies and temporary arrays
csr_array_destroy(graph_copies,(sz_short)NUM_THREADS);
free(data);
}
//Here I slice the output(soft labels) and input (class_ind)
//Using aliasing on the shifted pointers such that single threaded AdaDIF_core is compeltely "blind" to the slicing process
void* AdaDIF_squezze_to_one_thread( void* param){
pass_to_thread_type_2* data = param;
double* soft_labels = data->soft_labels + (data->graph.num_nodes * data->from);
sz_short* class_ind = data->class_ind + data->num_seeds*data->from;
sz_med* num_per_class = data->num_per_class + data->from;
clock_t begin = clock();
AdaDIF_core( soft_labels, data->graph, data->num_seeds, data->seeds, data->num_local_classes, class_ind, num_per_class,
data->walk_length, data->lambda, data->no_constr);
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Thread from classes with index %"PRIu16" to %"PRIu16" finished in %lf sec \n",(uint16_t) data->from, (uint16_t) data->to, time_spent);
pthread_exit(0);
}
//Core of AdaDIF method that runs on single thread (output is soft labels)
void AdaDIF_core( double* soft_labels, csr_graph graph, sz_med num_seeds,
const sz_long* seed_indices, sz_short num_class, sz_short* class_ind,
sz_med* num_per_class, sz_med walk_length, double lambda, bool no_constr){
for(sz_short i=0;i<num_class;i++){
double* land_prob = (double*) malloc(walk_length*graph.num_nodes*sizeof(double));
double* dif_land_prob = (double*) malloc(walk_length*graph.num_nodes*sizeof(double));
sz_long* local_seeds =(sz_long*)malloc(num_per_class[i] *sizeof(sz_long));
sz_med k=0;
for(sz_med j=0;j<num_seeds;j++){
if( class_ind[i*num_seeds + j] ==1 )
local_seeds[k++] = seed_indices[j];
}
perform_random_walk(land_prob, dif_land_prob, graph , walk_length , local_seeds , num_per_class[i] );
double* theta = get_AdaDIF_parameters(graph.num_nodes,graph.degrees,land_prob,dif_land_prob,seed_indices,local_seeds,
class_ind+i*num_seeds,walk_length,num_seeds,num_per_class[i],lambda,no_constr );
#if PRINT_THETAS
printf("THETA: ");
for(int n=0;n<walk_length;n++) printf(" %.3lf",theta[n]);
printf("\n");
#endif
matvec_trans_long( soft_labels+i*graph.num_nodes , land_prob, theta, graph.num_nodes, walk_length );
//free landing probabilities
free(local_seeds);
free(land_prob);
free(dif_land_prob);
free(theta);
}
}
//Extract landing and dif probabilities by performing K steps of simple random walk on graph
void perform_random_walk(double* land_prob, double* dif_land_prob, csr_graph graph,
sz_med walk_length , sz_long* seeds , sz_med num_seeds ){
double* seed_vector = (double*) malloc(graph.num_nodes* sizeof(double));
double one_over_num_seeds = 1.0f /(double) num_seeds ;
//prepare seed vector
for(sz_long i=0;i<graph.num_nodes;i++) seed_vector[i] = 0.0f ;
for(sz_med j=0;j<num_seeds;j++) seed_vector[seeds[j]] = one_over_num_seeds ;
//do the random walk
my_CSR_matvec( land_prob, seed_vector , graph);
for(sz_med j=1;j<walk_length;j++){
my_CSR_matvec( land_prob+j*graph.num_nodes, land_prob+(j-1)*graph.num_nodes , graph);
my_array_sub( dif_land_prob+(j-1)*graph.num_nodes, land_prob+(j-1)*graph.num_nodes,
land_prob+j*graph.num_nodes, graph.num_nodes);
}
#if DEBUG
printf("LAST LAND PROBs: \n");
for(sz_long i=0;i<=100;i++) printf(" %lf ",land_prob[(walk_length-1)*graph.num_nodes + i ]) ;
printf("...................... \n");
#endif
//do one final step to obtain the last differential
double* extra_step = (double*) malloc(graph.num_nodes* sizeof(double));
my_CSR_matvec( extra_step, land_prob+ (walk_length -1)*graph.num_nodes , graph);
my_array_sub( dif_land_prob+(walk_length-1)*graph.num_nodes, land_prob+(walk_length-1)*graph.num_nodes,
extra_step, graph.num_nodes);
//free
free(seed_vector);
free(extra_step);
}
//Extract the AdaDIF diffusion coefficients
double* get_AdaDIF_parameters( sz_long N, sz_long* degrees, double* land_prob,
double* dif_land_prob, const sz_long* seed_indices,
sz_long* local_seeds, sz_short* class_ind, sz_med walk_length,
sz_med num_seeds, sz_med num_pos,double lambda, bool no_constr){
double* theta = (double*) malloc(walk_length*sizeof(double));
//A and b are the Hessian and linear component of the quadratic cost
double* A = get_coef_A(N,walk_length,num_seeds,degrees, land_prob, dif_land_prob,seed_indices,lambda);
double* b = get_coef_b(N,walk_length,num_seeds,num_pos,degrees, land_prob, local_seeds);
if(!no_constr){
simplex_constr_QP_with_PG(theta,A,b,walk_length);
}else{
hyperplane_constr_QP(theta,A,b,walk_length);
}
//free
free(b);
free(A);
return theta;
}
// This function computes how many threads will be used and how many classes will be allocated per thread
static sz_short get_threads_and_width(sz_short* width ,sz_short num_class){
sz_short num_procs=get_nprocs();
sz_short num_threads;
if(num_class<=num_procs){
num_threads = num_class;
*width=1;
}else{
num_threads = num_procs;
*width = (sz_short)ceil((double)(num_class/(double)num_threads));
}
return num_threads;
}
//Obtain slice of G as stationary distributions. (Unweighted) Seed set must be defined
//Returns numbr of itrations untill convergence
sz_med get_slice_of_G( double* G_s, sz_long* seeds, sz_med num_seeds, double tel_prob,
csr_graph graph, bool single_thread ){
//Do it SMART: Use a temporary G_s_next where you store the left hand side of iteration
//Then at eah iteration just flip pointers between G_s and G_s_next
//Multiple threads compute different slices of G_s
sz_short NUM_THREADS = get_nprocs();
printf("NUMBER OF THREADS: %"PRIu16" \n",(uint16_t) NUM_THREADS);
if(single_thread) NUM_THREADS = 1;
sz_med iter[NUM_THREADS];
csr_graph graph_scaled = csr_deep_copy_and_scale(graph,1.0f-tel_prob);
double* G_s_next=malloc(graph.num_nodes*num_seeds*sizeof(double));
//Initialization
for(sz_long i=0;i<graph.num_nodes*num_seeds;i++) G_s[i]=0.0f;
for(sz_med j=0;j<num_seeds;j++) G_s[ num_seeds*seeds[j] +j]=1.0f;
clock_t begin = clock();
//The following three blocks create copies of the CSR matrix
//Each copy will be used by a thread
csr_graph* graph_copies = csr_mult_deep_copy( graph_scaled, (sz_short) NUM_THREADS );
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Time spent copying csr_matrix: %lf\n",time_spent);
//MAIN LOOP
//Prepare data to be passed to each thread
sz_med width;
width=(sz_med)floor((double)(num_seeds/(double)NUM_THREADS));
pthread_t tid[NUM_THREADS];
pass_to_thread_type_1* data= (pass_to_thread_type_1*)malloc(NUM_THREADS*sizeof(pass_to_thread_type_1));
for(sz_short i=0;i<NUM_THREADS;i++){
(*(data+i))= (pass_to_thread_type_1) {.G_s=G_s,
.G_s_next=G_s_next,
.graph = graph_copies[i],
.seeds=seeds,
.M=num_seeds,
.tel_prob=tel_prob,
.from=i*width };
if(i==NUM_THREADS-1){
(data+i)->to=num_seeds;
}else{
(data+i)->to=(i+1)*width;
}
(data+i)->iter=&iter[i];
}
//Spawn threads and start running
for(sz_short i=0;i<NUM_THREADS;i++){
pthread_create(&tid[i],NULL,my_power_iter,(void*)(data+i));
}
//Wait for all threads to finish before continuing
for(sz_short i=0;i<NUM_THREADS;i++){pthread_join(tid[i], NULL);}
//Free copies and temporary arrays
csr_destroy(graph_scaled);
csr_array_destroy(graph_copies,(sz_short)NUM_THREADS);
free(G_s_next);
free(data);
return iter[0];
}
//Power iteration that computes a subset (from,to) of the collumns of G_s
//Data are passed via struct that can be readily used by thread
void* my_power_iter(void* param){
pass_to_thread_type_1* data = param;
sz_long* seeds=data->seeds;
double* G_s=data->G_s;
double* G_s_next= data->G_s_next;
csr_graph graph=data->graph;
//Iterate using this "back and forth method" to minimize memory access
clock_t begin = clock();
sz_med iter=0;
sz_short flag=0;
do{
iter++;
flag=(flag==1) ? 0 : 1 ;
if(flag==1){
my_CSR_matmat( G_s_next , G_s , graph , data->M , data->from, data->to);
for(sz_med j=data->from;j<data->to;j++) G_s_next[data->M*seeds[j] +j]+=data->tel_prob;
}
else{
my_CSR_matmat( G_s, G_s_next , graph , data->M, data->from, data->to);
for(sz_med j=data->from;j<data->to;j++) G_s[data->M*seeds[j] +j]+= data->tel_prob;
}
}while(iter<MAXIT && max_seed_val_difference( G_s, G_s_next , seeds ,data->M, data->from, data->to) >TOL);
if(flag==1){
for(sz_long i=0;i<graph.num_nodes;i++){
for(sz_med j=data->from;j<data->to;j++)
G_s[i*data->M + j]=G_s_next[i*data->M + j];
}
}
*(data->iter)=iter;
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Thread from column %"PRIu32" to %"PRIu32" finished in %lf sec \n", (uint32_t) data->from, (uint32_t) data->to, time_spent);
pthread_exit(0);
}
//Personalized-Pagerank single thread
void my_PPR_single_thread( double* soft_labels, csr_graph graph, sz_med num_seeds,
const sz_long* seed_indices, sz_short num_class, sz_short* class_ind,
sz_med* num_per_class, sz_med walk_length, double tel_prob){
csr_graph graph_scaled = csr_deep_copy_and_scale(graph,1.0f-tel_prob);
for(sz_short i=0;i<num_class;i++){
sz_long* local_seeds =(sz_long*)malloc(num_per_class[i] *sizeof(sz_long));
sz_med k = 0;
for(sz_med j=0;j<num_seeds;j++){
if( class_ind[i*num_seeds + j] ==1 )
local_seeds[k++] = seed_indices[j];
}
//prepare seed vector
double* soft = soft_labels + i*graph.num_nodes;
double one_over_num_seeds = 1.0f /(double) num_per_class[i] ;
for(sz_long n=0;n<graph.num_nodes;n++) soft[n] = 0.0f ;
for(sz_med j=0;j<num_per_class[i];j++) soft[local_seeds[j]] = one_over_num_seeds ;
//perform random walk with restart
sz_short flag=0;
double* soft_next=malloc(graph.num_nodes*sizeof(double));
for(sz_med j=0;j<walk_length;j++){
flag=(flag==1) ? 0 : 1 ;
if(flag==1){
my_CSR_matvec(soft_next, soft, graph_scaled );
for(sz_med k=0;k<num_per_class[i] ;k++)
soft_next[local_seeds[k]] += tel_prob*one_over_num_seeds;
}
else{
my_CSR_matvec(soft, soft_next, graph_scaled );
for(sz_med k=0;k<num_per_class[i] ;k++)
soft[local_seeds[k]] += tel_prob*one_over_num_seeds;
}
}
if(flag==1){
memcpy(soft, soft_next, graph.num_nodes*sizeof(double));
}
free(soft_next);
free(local_seeds);
}
csr_destroy(graph_scaled);
}
//find l_max norm between vecors of known length
double max_seed_val_difference(double* A, double* B, sz_long* points , sz_med num_points, sz_med from, sz_med to){
double dif;
double max_dif=0.0f;
for(sz_med i=from;i<to;i++){
dif=fabs( A[ num_points*points[i] + i] - B[ num_points*points[i] + i] );
max_dif = ( dif > max_dif ) ? dif : max_dif ;
}
return max_dif;
}
//Extract square submatrix of slice G_l that corresponds to labeled only
void extract_G_ll(double* G_ll, double* G_s, sz_long* seeds, sz_med num_seeds){
for(sz_long i=0;i<num_seeds;i++){
for(sz_med j=0;j<num_seeds;j++)
G_ll[i*num_seeds + j]=G_s[seeds[i]*num_seeds + j];
}
}
//The following two functions generate the coefficients required by the AdaDIF QP
static double* get_coef_A(sz_long N, sz_med K, sz_med L , sz_long* d ,
double* P ,double* P_dif , const sz_long* L_ind , double lambda ){
double* A = (double*) malloc(K*K*sizeof(double));
double* d_inv_times_lambda = (double*)malloc(N*sizeof(double));
for(sz_long i=0;i<N;i++) d_inv_times_lambda[i] =lambda/(double)d[i];
double* P_temp =(double*) malloc(K*N*sizeof(double));
for(sz_long i=0;i<N;i++){
for(sz_med j=0;j<K;j++)
P_temp[j*N+i]=d_inv_times_lambda[i]*P_dif[j*N+i];
}
for(sz_med i=0;i<L;i++){
for(sz_med j=0;j<K;j++)
P_temp[j*N + L_ind[i] ]+= P[j*N+L_ind[i]]/(double)d[L_ind[i]];
}
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, (int)K, (int)K, (int)N, 1.0f, P, (int)N, P_temp, (int)N, 0.0f, A, (int)K);
free(d_inv_times_lambda);
free(P_temp);
return A;
}
static double* get_coef_b(sz_long N, sz_med K, sz_med L ,sz_med num_pos , sz_long* d , double* P , sz_long* L_c ){
double two_over_L = -2.0f/(double) L;
double* b = (double*) malloc(K*sizeof(double));
for(sz_med i=0;i<K;i++) b[i]=0.0f;
for(sz_med i=0;i<K;i++){
for(sz_med j=0;j<num_pos;j++)
b[i]+=P[i*N + L_c[j]]/(double)d[L_c[j]];
b[i]*= two_over_L;
}
return b;
}
| {
"alphanum_fraction": 0.6775721594,
"avg_line_length": 29.3747680891,
"ext": "c",
"hexsha": "4e17f4a72751a02063ca3d4c8cbf0658192679cc",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2019-05-16T08:23:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-05-24T03:55:53.000Z",
"max_forks_repo_head_hexsha": "d2060a8875950694225611fcda7b757215cf65c5",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "nikolakopoulos/Adaptive-Diffusions-for-SSL",
"max_forks_repo_path": "src/comp_engine.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d2060a8875950694225611fcda7b757215cf65c5",
"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": "nikolakopoulos/Adaptive-Diffusions-for-SSL",
"max_issues_repo_path": "src/comp_engine.c",
"max_line_length": 143,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "8ca9ca6f595a5da718850f3dcf3607c9ebf51c92",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "DimBer/SSL_lib",
"max_stars_repo_path": "src/comp_engine.c",
"max_stars_repo_stars_event_max_datetime": "2019-07-31T15:11:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-05-24T03:57:57.000Z",
"num_tokens": 4576,
"size": 15833
} |
/*****************************************************************\
__
/ /
/ / __ __
/ /______ _______ / / / / ________ __ __
/ ______ \ /_____ \ / / / / / _____ | / / / /
/ / | / _______| / / / / / / /____/ / / / / /
/ / / / / _____ / / / / / / _______/ / / / /
/ / / / / /____/ / / / / / / |______ / |______/ /
/_/ /_/ |________/ / / / / \_______/ \_______ /
/_/ /_/ / /
/ /
High Level Game Framework /_/
---------------------------------------------------------------
Copyright (c) 2007-2011 - Rodrigo Braz Monteiro.
This file is subject to the terms of halley_license.txt.
\*****************************************************************/
#pragma once
#include <cmath>
#include <iostream>
#include "angle.h"
#include <halley/utils/utils.h>
#include <gsl/gsl_assert>
namespace Halley {
//////////////////////////////
// Vector4D class declaration
template <typename T=float>
class Vector4D {
private:
T mod(T a, T b) const { return a % b; }
public:
T x, y, z, w;
// Constructors
Vector4D ()
: x(0)
, y(0)
, z(0)
, w(0)
{}
Vector4D (T x, T y, T z, T w)
: x(x)
, y(y)
, z(z)
, w(w)
{}
template <typename V>
explicit Vector4D (Vector4D<V> vec)
: x(T(vec.x))
, y(T(vec.y))
, z(T(vec.z))
, w(T(vec.w))
{}
// Getter
inline T& operator[](size_t n)
{
Expects(n <= 3);
return reinterpret_cast<T*>(this)[n];
}
inline T operator[](size_t n) const
{
Expects(n <= 3);
return reinterpret_cast<const T*>(this)[n];
}
// Assignment and comparison
inline Vector4D& operator = (Vector4D param) { x = param.x; y = param.y; z = param.z; w = param.w; return *this; }
inline Vector4D& operator = (T param) { x = param; y = param; z = param; w = param; return *this; }
inline bool operator == (Vector4D param) const { return x == param.x && y == param.y && z == param.z && w == param.w; }
inline bool operator != (Vector4D param) const { return x != param.x || y != param.y || z != param.z || w != param.w; }
// Basic algebra
inline Vector4D operator + (Vector4D param) const { return Vector4D(x + param.x, y + param.y, z + param.z, w + param.w); }
inline Vector4D operator - (Vector4D param) const { return Vector4D(x - param.x, y - param.y, z - param.z, w - param.w); }
inline Vector4D operator * (Vector4D param) const { return Vector4D(x * param.x, y * param.y, z * param.z, w * param.w); }
inline Vector4D operator / (Vector4D param) const { return Vector4D(x / param.x, y / param.y, z / param.z, w / param.w); }
inline Vector4D operator % (Vector4D param) const { return Vector4D(mod(x, param.x), mod(y, param.y), mod(z, param.z), mod(w, param.w)); }
inline Vector4D modulo(Vector4D param) const { return Vector4D(Halley::modulo<T>(x, param.x), Halley::modulo<T>(y, param.y), Halley::modulo<T>(z, param.z), Halley::modulo<T>(w, param.w)); }
inline Vector4D floorDiv(Vector4D param) const { return Vector4D(Halley::floorDiv(x, param.x), Halley::floorDiv(y, param.y), Halley::floorDiv(z, param.z), Halley::floorDiv(w, param.w)); }
inline Vector4D operator - () const { return Vector4D(-x, -y, -z, -w); }
template <typename V>
inline Vector4D operator * (V param) const { return Vector4D(T(x * param), T(y * param), T(z * param), T(w * param)); }
template <typename V>
inline Vector4D operator / (V param) const { return Vector4D(T(x / param), T(y / param), T(z * param), T(w * param)); }
// In-place operations
inline Vector4D& operator += (Vector4D param) { x += param.x; y += param.y; z += param.z; w += param.w; return *this; }
inline Vector4D& operator -= (Vector4D param) { x -= param.x; y -= param.y; z -= param.z; w -= param.w; return *this; }
inline Vector4D& operator *= (const T param) { x *= param; y *= param; z *= param; w *= param; return *this; }
inline Vector4D& operator /= (const T param) { x /= param; y /= param; z /= param; w /= param; return *this; }
// Get the normalized vector (unit vector)
inline Vector4D unit () const
{
float len = length();
if (len != 0) {
return (*this) / len;
} else {
return Vector4D();
}
}
inline Vector4D normalized() const
{
return unit();
}
inline void normalize()
{
*this = unit();
}
// Dot product
inline T dot (Vector4D param) const { return (x * param.x) + (y * param.y) + (z * param.z) + (w * param.w); }
// Length
inline T length () const { return sqrt(squaredLength()); }
inline T len () const { return length(); }
// Squared length, often useful and much faster
inline T squaredLength () const { return x*x + y*y + z*z + w*w; }
// Floor
inline Vector4D floor() const { return Vector4D(floor(x), floor(y), floor(z), floor(w)); }
inline Vector4D ceil() const { return Vector4D(ceil(x), ceil(y), ceil(z), ceil(w)); }
};
////////////////////
// Global operators
template <typename T, typename V>
inline Vector4D<T> operator * (V f, const Vector4D<T> &v)
{
return Vector4D<T>(T(v.x * f), T(v.y * f), T(v.z * f), T(v.w * f));
}
template <typename T >
std::ostream& operator<< (std::ostream& ostream, const Vector4D<T>& v)
{
ostream << "(" << v.x << "," << v.y << "," << v.z << "," << v.w << ")" ; return ostream;
}
////////////
// Typedefs
using Vector4d = Vector4D<double>;
using Vector4f = Vector4D<float>;
using Vector4i = Vector4D<int>;
using Vector4s = Vector4D<short>;
using Vector4c = Vector4D<char>;
}
| {
"alphanum_fraction": 0.5437632884,
"avg_line_length": 33.7964071856,
"ext": "h",
"hexsha": "3e0e0c07d4db5698d0c59ffa0012e901f230707b",
"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": "16b6c9783e4b21377f902a9d02366c1f19450a21",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "lye/halley",
"max_forks_repo_path": "src/engine/utils/include/halley/maths/vector4.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21",
"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": "lye/halley",
"max_issues_repo_path": "src/engine/utils/include/halley/maths/vector4.h",
"max_line_length": 191,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "lye/halley",
"max_stars_repo_path": "src/engine/utils/include/halley/maths/vector4.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1741,
"size": 5644
} |
/*! \file
2D/3D median filter
\par Author:
Gabriele Lohmann, MPI-CBS
*/
/* From the Vista library: */
#include <viaio/VImage.h>
#include <viaio/Vlib.h>
#include <viaio/mu.h>
/* From the standard C library: */
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_sort.h>
#define ABS(x) ((x) > 0 ? (x) : -(x))
/*!
\fn VImage VMedianImage3d (VImage src, VImage dest, int dim, VBoolean ignore)
\param src input image
\param dest output image
\param dim kernel size (3,5,7...)
\param ignore whether to ignore zero voxels
*/
VImage
VMedianImage3d (VImage src, VImage dest, int dim, VBoolean ignore)
{
int nbands,nrows,ncols;
int i,len,len2,b,r,c,bb,rr,cc,b0,b1,r0,r1,c0,c1,d=0;
gsl_vector *vec=NULL;
double u,tiny=1.0e-8;
if (dim%2 == 0) VError("VMedianImage3d: dim (%d) must be odd",dim);
nrows = VImageNRows (src);
ncols = VImageNColumns (src);
nbands = VImageNBands (src);
if (nbands <= d) VError("VMedianImage3d: number of slices too small (%d)",nbands);
d = dim/2;
len = dim * dim * dim;
len2 = len/2;
vec = gsl_vector_calloc(len);
dest = VCopyImage(src,dest,VAllBands);
VFillImage(dest,VAllBands,0);
for (b=d; b<nbands-d; b++) {
for (r=d; r<nrows-d; r++) {
for (c=d; c<ncols-d; c++) {
u = VGetPixel(src,b,r,c);
i = 0;
b0 = b-d;
b1 = b+d;
for (bb=b0; bb<=b1; bb++) {
r0 = r-d;
r1 = r+d;
for (rr=r0; rr<=r1; rr++) {
c0 = c-d;
c1 = c+d;
for (cc=c0; cc<=c1; cc++) {
u = VGetPixel(src,bb,rr,cc);
if (ABS(u) > tiny && ignore == TRUE) {
gsl_vector_set(vec,i,u);
i++;
}
}
}
if (i < len2) continue;
gsl_sort(vec->data,vec->stride,(size_t)i);
u = gsl_stats_median_from_sorted_data(vec->data,vec->stride,i);
VSetPixel(dest,b,r,c,u);
}
}
}
}
gsl_vector_free(vec);
return dest;
}
/*!
\fn VImage VMedianImage2d (VImage src, VImage dest, int dim, VBoolean ignore)
\param src input image
\param dest output image
\param dim kernel size
\param ignore whether to ignore zero voxels
*/
VImage VMedianImage2d (VImage src, VImage dest, int dim, VBoolean ignore)
{
int nbands,nrows,ncols;
int i,len,len2,b,r,c,rr,cc,d=0;
gsl_vector *vec=NULL;
double u=0;
if (dim%2 == 0) VError("VMedianImage2d: dim (%d) must be odd",dim);
nrows = VImageNRows (src);
ncols = VImageNColumns (src);
nbands = VImageNBands (src);
d = dim/2;
len = dim * dim;
len2 = len/2;
vec = gsl_vector_calloc(len);
dest = VCopyImage(src,dest,VAllBands);
for (b=0; b<nbands; b++) {
for (r=d; r<nrows-d; r++) {
for (c=d; c<ncols-d; c++) {
gsl_vector_set_zero(vec);
u = VGetPixel(src,b,r,c);
i = 0;
for (rr=r-d; rr<=r+d; rr++) {
for (cc=c-d; cc<=c+d; cc++) {
u = VGetPixel(src,b,rr,cc);
if (ABS(u) > 0 && ignore == TRUE) {
gsl_vector_set(vec,i,u);
i++;
}
}
}
if (i < len2) continue;
gsl_sort(vec->data,vec->stride,(size_t)i);
u = gsl_stats_median_from_sorted_data(vec->data,vec->stride,i);
VSetPixel(dest,b,r,c,u);
}
}
}
gsl_vector_free(vec);
return dest;
}
| {
"alphanum_fraction": 0.5985153109,
"avg_line_length": 20.4620253165,
"ext": "c",
"hexsha": "869b0731481d7cbf6a6bc8e68ce7a9b6ea5898aa",
"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/lib_via/Median.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/lib_via/Median.c",
"max_line_length": 84,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/lib_via/Median.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": 1136,
"size": 3233
} |
/* ode-initval2/msadams.c
*
* Copyright (C) 2009, 2010 Tuomo Keskitalo
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* A variable-coefficient linear multistep Adams method in Nordsieck
form. This stepper uses explicit Adams-Bashforth (predictor) and
implicit Adams-Moulton (corrector) methods in P(EC)^m functional
iteration mode. Method order varies dynamically between 1 and 12.
References:
Byrne, G. D., and Hindmarsh, A. C., A Polyalgorithm for the
Numerical Solution of Ordinary Differential Equations,
ACM Trans. Math. Software, 1 (1975), pp. 71-96.
Brown, P. N., Byrne, G. D., and Hindmarsh, A. C., VODE: A
Variable-coefficient ODE Solver, SIAM J. Sci. Stat. Comput. 10,
(1989), pp. 1038-1051.
Hindmarsh, A. C., Brown, P. N., Grant, K. E., Lee, S. L., Serban,
R., Shumaker, D. E., and Woodward, C. S., SUNDIALS: Suite of
Nonlinear and Differential/Algebraic Equation Solvers, ACM
Trans. Math. Software 31 (2005), pp. 363-396.
Note: The algorithms have been adapted for GSL ode-initval2
framework.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
#include <gsl/gsl_blas.h>
#include "odeiv_util.h"
/* Maximum order of Adams methods */
#define MSADAMS_MAX_ORD 12
typedef struct
{
/* Nordsieck history matrix. Includes concatenated
Nordsieck vectors [y_n, h*y_n', (h^2/2!)*y_n'', ...,
(h^ord/ord!)*d^(ord)(y_n)]. Nordsieck vector number i is located
at z[i*dim] (i=0..ord).
*/
double *z;
double *zbackup; /* backup of Nordsieck matrix */
double *ytmp; /* work area */
double *ytmp2; /* work area */
double *pc; /* product term coefficients */
double *l; /* polynomial coefficients */
double *hprev; /* previous step sizes */
double *hprevbackup; /* backup of hprev */
double *errlev; /* desired error level of y */
gsl_vector *abscor; /* absolute y values for correction */
gsl_vector *relcor; /* relative y values for correction */
gsl_vector *svec; /* saved abscor & work area */
gsl_vector *tempvec; /* work area */
const gsl_odeiv2_driver *driver; /* pointer to gsl_odeiv2_driver object */
long int ni; /* stepper call counter */
size_t ord; /* current order of method */
size_t ordprev; /* order of previous call */
size_t ordprevbackup; /* backup of ordprev */
double tprev; /* t point of previous call */
size_t ordwait; /* counter for order change */
size_t ordwaitbackup; /* backup of ordwait */
size_t failord; /* order of convergence failure */
double failt; /* t point of convergence failure */
double ordm1coeff; /* saved order-1 coefficiet */
double ordp1coeffprev; /* saved order+1 coefficient */
size_t failcount; /* counter for rejected steps */
}
msadams_state_t;
/* Introduce msadams_reset for use in msadams_alloc and _apply */
static int msadams_reset (void *, size_t);
static void *
msadams_alloc (size_t dim)
{
msadams_state_t *state =
(msadams_state_t *) malloc (sizeof (msadams_state_t));
if (state == 0)
{
GSL_ERROR_NULL ("failed to allocate space for msadams_state",
GSL_ENOMEM);
}
state->z =
(double *) malloc ((MSADAMS_MAX_ORD + 1) * dim * sizeof (double));
if (state->z == 0)
{
free (state);
GSL_ERROR_NULL ("failed to allocate space for z", GSL_ENOMEM);
}
state->zbackup =
(double *) malloc ((MSADAMS_MAX_ORD + 1) * dim * sizeof (double));
if (state->zbackup == 0)
{
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for zbackup", GSL_ENOMEM);
}
state->ytmp = (double *) malloc (dim * sizeof (double));
if (state->ytmp == 0)
{
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM);
}
state->ytmp2 = (double *) malloc (dim * sizeof (double));
if (state->ytmp2 == 0)
{
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp2", GSL_ENOMEM);
}
state->pc = (double *) malloc ((MSADAMS_MAX_ORD + 1) * sizeof (double));
if (state->pc == 0)
{
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for pc", GSL_ENOMEM);
}
state->l = (double *) malloc ((MSADAMS_MAX_ORD + 1) * sizeof (double));
if (state->l == 0)
{
free (state->pc);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for l", GSL_ENOMEM);
}
state->hprev = (double *) malloc (MSADAMS_MAX_ORD * sizeof (double));
if (state->hprev == 0)
{
free (state->l);
free (state->pc);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for hprev", GSL_ENOMEM);
}
state->hprevbackup = (double *) malloc (MSADAMS_MAX_ORD * sizeof (double));
if (state->hprevbackup == 0)
{
free (state->hprev);
free (state->l);
free (state->pc);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for hprevbackup", GSL_ENOMEM);
}
state->errlev = (double *) malloc (dim * sizeof (double));
if (state->errlev == 0)
{
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->pc);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for errlev", GSL_ENOMEM);
}
state->abscor = gsl_vector_alloc (dim);
if (state->abscor == 0)
{
free (state->errlev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->pc);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for abscor", GSL_ENOMEM);
}
state->relcor = gsl_vector_alloc (dim);
if (state->relcor == 0)
{
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->pc);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for relcor", GSL_ENOMEM);
}
state->svec = gsl_vector_alloc (dim);
if (state->svec == 0)
{
gsl_vector_free (state->relcor);
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->pc);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for svec", GSL_ENOMEM);
}
state->tempvec = gsl_vector_alloc (dim);
if (state->tempvec == 0)
{
gsl_vector_free (state->svec);
gsl_vector_free (state->relcor);
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->pc);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
GSL_ERROR_NULL ("failed to allocate space for tempvec", GSL_ENOMEM);
}
msadams_reset ((void *) state, dim);
state->driver = NULL;
return state;
}
static int
msadams_failurehandler (void *vstate, const size_t dim, const double t)
{
/* Internal failure handler routine for msadams. Adjusted strategy
for GSL: Decrease order if this is the second time a failure
has occurred at this order and point.
*/
msadams_state_t *state = (msadams_state_t *) vstate;
const size_t ord = state->ord;
if (ord > 1 && (ord - state->ordprev == 0) &&
ord == state->failord && t == state->failt)
{
state->ord--;
}
/* Save information about failure */
state->failord = ord;
state->failt = t;
state->ni++;
/* Force reinitialization if failure took place at lowest
order
*/
if (ord == 1)
{
msadams_reset (vstate, dim);
}
return GSL_SUCCESS;
}
static int
msadams_calccoeffs (const size_t ord, const size_t ordwait,
const double h, const double hprev[],
double pc[], double l[],
double *errcoeff, double *ordm1coeff,
double *ordp1coeff, double *ordp2coeff)
{
/* Calculates coefficients (l) of polynomial Lambda, error and
auxiliary order change evaluation coefficients.
*/
if (ord == 1)
{
l[0] = 1.0;
l[1] = 1.0;
*errcoeff = 0.5;
*ordp1coeff = 1.0;
*ordp2coeff = 12.0;
}
else
{
size_t i, j;
double hsum = h;
double st1 = 0.0; /* sum term coefficients */
double st2 = 0.0;
/* Calculate coefficients (pc) of product terms */
DBL_ZERO_MEMSET (pc, MSADAMS_MAX_ORD + 1);
pc[0] = 1.0;
for (i = 1; i < ord; i++)
{
/* Calculate auxiliary coefficient used in evaluation of
change of order
*/
if (i == ord - 1 && ordwait == 1)
{
int s = 1;
*ordm1coeff = 0.0;
for (j = 0; j < ord - 1; j++)
{
*ordm1coeff += s * pc[j] / (j + 2);
s = -s;
}
*ordm1coeff = pc[ord - 2] / (ord * (*ordm1coeff));
}
for (j = i; j > 0; j--)
{
pc[j] += pc[j - 1] * h / hsum;
}
hsum += hprev[i - 1];
}
/* Calculate sum term 1 for error estimation */
{
int s = 1;
for (i = 0; i < ord; i++)
{
st1 += s * pc[i] / (i + 1.0);
s = -s;
}
}
/* Calculate sum term 2 for error estimation */
{
int s = 1;
for (i = 0; i < ord; i++)
{
st2 += s * pc[i] / (i + 2.0);
s = -s;
}
}
/* Calculate the actual polynomial coefficients (l) */
DBL_ZERO_MEMSET (l, MSADAMS_MAX_ORD + 1);
l[0] = 1.0;
for (i = 1; i < ord + 1; i++)
{
l[i] = pc[i - 1] / (i * st1);
}
#ifdef DEBUG
{
size_t di;
printf ("-- calccoeffs l: ");
for (di = 0; di < ord + 1; di++)
{
printf ("%.5e ", l[di]);
}
printf ("\n");
printf ("-- calccoeffs pc: ");
for (di = 0; di < ord; di++)
{
printf ("%.5e ", pc[di]);
}
printf ("\n");
printf ("-- calccoeffs st1=%.5e, st2=%.5e\n", st1, st2);
}
#endif
/* Calculate error coefficient */
*errcoeff = (h / hsum) * (st2 / st1);
/* Calculate auxiliary coefficients used in evaluation of change
of order
*/
if (ordwait < 2)
{
int s = 1;
*ordp1coeff = hsum / (h * l[ord]);
*ordp2coeff = 0.0;
for (i = ord; i > 0; i--)
{
pc[i] += pc[i - 1] * (h / hsum);
}
for (i = 0; i < ord + 1; i++)
{
*ordp2coeff += s * pc[i] / (i + 2);
s = -s;
}
*ordp2coeff = (ord + 1) * st1 / (*ordp2coeff);
}
}
#ifdef DEBUG
printf ("-- calccoeffs ordm1coeff=%.5e ", *ordm1coeff);
printf ("ordp1coeff=%.5e ", *ordp1coeff);
printf ("ordp2coeff=%.5e ", *ordp2coeff);
printf ("errcoeff=%.5e\n", *errcoeff);
#endif
return GSL_SUCCESS;
}
static int
msadams_corrector (void *vstate, const gsl_odeiv2_system * sys,
const double t, const double h, const size_t dim,
const double z[], const double errlev[],
const double l[], const double errcoeff,
gsl_vector * abscor, gsl_vector * relcor,
double ytmp[], double ytmp2[])
{
/* Calculates the correction step (abscor). Non-linear equation
system is solved by functional iteration.
*/
size_t mi, i;
const size_t max_iter = 3; /* Maximum number of iterations */
double convrate = 1.0; /* convergence rate */
double stepnorm = 0.0; /* norm of correction step */
double stepnormprev = 0.0;
/* Evaluate at predicted values */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, z, ytmp);
if (s == GSL_EBADFUNC)
{
return s;
}
if (s != GSL_SUCCESS)
{
msadams_failurehandler (vstate, dim, t);
#ifdef DEBUG
printf ("-- FAIL at user function evaluation\n");
#endif
return s;
}
}
/* Calculate correction step (abscor) */
gsl_vector_set_zero (abscor);
for (mi = 0; mi < max_iter; mi++)
{
const double safety = 0.3;
const double safety2 = 0.1;
/* Calculate new y values to ytmp2 */
for (i = 0; i < dim; i++)
{
ytmp[i] *= h;
ytmp[i] -= z[1 * dim + i];
ytmp[i] /= l[1];
ytmp2[i] = z[0 * dim + i] + ytmp[i];
}
#ifdef DEBUG
{
size_t di;
printf ("-- dstep: ");
for (di = 0; di < dim; di++)
{
printf ("%.5e ", ytmp[di]);
}
printf ("\n");
}
#endif
/* Convergence test. Norms used are root-mean-square norms. */
for (i = 0; i < dim; i++)
{
gsl_vector_set (relcor, i,
(ytmp[i] - gsl_vector_get (abscor, i)) / errlev[i]);
gsl_vector_set (abscor, i, ytmp[i]);
}
stepnorm = gsl_blas_dnrm2 (relcor) / sqrt (dim);
if (mi > 0)
{
convrate = GSL_MAX_DBL (safety * convrate, stepnorm / stepnormprev);
}
else
{
convrate = 1.0;
}
{
const double convtest =
GSL_MIN_DBL (convrate, 1.0) * stepnorm * errcoeff / safety2;
#ifdef DEBUG
printf
("-- func iter loop %d, errcoeff=%.5e, stepnorm =%.5e, convrate = %.5e, convtest = %.5e\n",
(int) mi, errcoeff, stepnorm, convrate, convtest);
#endif
if (convtest <= 1.0)
{
break;
}
}
/* Check for divergence during iteration */
{
const double div_const = 2.0;
if (mi > 1 && stepnorm > div_const * stepnormprev)
{
msadams_failurehandler (vstate, dim, t);
#ifdef DEBUG
printf ("-- FAIL, diverging functional iteration\n");
#endif
return GSL_FAILURE;
}
}
/* Evaluate at new y */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, ytmp2, ytmp);
if (s == GSL_EBADFUNC)
{
return s;
}
if (s != GSL_SUCCESS)
{
msadams_failurehandler (vstate, dim, t);
#ifdef DEBUG
printf ("-- FAIL at user function evaluation\n");
#endif
return s;
}
}
stepnormprev = stepnorm;
}
#ifdef DEBUG
printf ("-- functional iteration exit at mi=%d\n", (int) mi);
#endif
/* Handle convergence failure */
if (mi == max_iter)
{
msadams_failurehandler (vstate, dim, t);
#ifdef DEBUG
printf ("-- FAIL, max_iter reached\n");
#endif
return GSL_FAILURE;
}
return GSL_SUCCESS;
}
static int
msadams_eval_order (gsl_vector * abscor, gsl_vector * tempvec,
gsl_vector * svec, const double errcoeff,
const size_t dim, const double errlev[],
const double ordm1coeff, const double ordp1coeff,
const double ordp1coeffprev, const double ordp2coeff,
const double hprev[],
const double h, const double z[],
size_t * ord, size_t * ordwait)
{
/* Evaluates and executes change in method order (current, current-1
or current+1). Order which maximizes the step length is selected.
*/
size_t i;
/* step size estimates at current order, order-1 and order+1 */
double ordest = 0.0;
double ordm1est = 0.0;
double ordp1est = 0.0;
const double safety = 1e-6;
const double bias = 6.0;
const double bias2 = 10.0;
/* Relative step length estimate for current order */
ordest = 1.0 / (pow (bias * gsl_blas_dnrm2 (abscor) / sqrt (dim)
* errcoeff, 1.0 / (*ord + 1)) + safety);
/* Relative step length estimate for order ord - 1 */
if (*ord > 1)
{
for (i = 0; i < dim; i++)
{
gsl_vector_set (tempvec, i, z[*ord * dim + i] / errlev[i]);
}
ordm1est = 1.0 / (pow (bias * gsl_blas_dnrm2 (tempvec) / sqrt (dim)
/ ordm1coeff, 1.0 / (*ord)) + safety);
}
else
{
ordm1est = 0.0;
}
/* Relative step length estimate for order ord + 1 */
if (*ord < MSADAMS_MAX_ORD)
{
const double c = -ordp1coeff / ordp1coeffprev *
pow (h / hprev[1], *ord + 1);
for (i = 0; i < dim; i++)
{
gsl_vector_set (svec, i, gsl_vector_get (svec, i) * c +
gsl_vector_get (abscor, i));
}
ordp1est = 1.0 / (pow (bias2 * gsl_blas_dnrm2 (svec) / sqrt (dim)
/ ordp2coeff, 1.0 / (*ord + 2)) + safety);
}
else
{
ordp1est = 0.0;
}
#ifdef DEBUG
printf
("-- eval_order ord=%d, ordest=%.5e, ordm1est=%.5e, ordp1est=%.5e\n",
(int) *ord, ordest, ordm1est, ordp1est);
#endif
/* Choose order that maximises step size and increases step
size markedly compared to current step
*/
{
const double min_incr = 1.5;
if (ordm1est > ordest && ordm1est > ordp1est && ordm1est > min_incr)
{
*ord -= 1;
#ifdef DEBUG
printf ("-- eval_order order DECREASED to %d\n", (int) *ord);
#endif
}
else if (ordp1est > ordest && ordp1est > ordm1est && ordp1est > min_incr)
{
*ord += 1;
#ifdef DEBUG
printf ("-- eval_order order INCREASED to %d\n", (int) *ord);
#endif
}
}
*ordwait = *ord + 2;
return GSL_SUCCESS;
}
static int
msadams_apply (void *vstate, size_t dim, double t, double h,
double y[], double yerr[],
const double dydt_in[], double dydt_out[],
const gsl_odeiv2_system * sys)
{
/* Conducts a step by Adams linear multistep methods. */
msadams_state_t *state = (msadams_state_t *) vstate;
double *const z = state->z;
double *const zbackup = state->zbackup;
double *const ytmp = state->ytmp;
double *const ytmp2 = state->ytmp2;
double *const pc = state->pc;
double *const l = state->l;
double *const hprev = state->hprev;
double *const hprevbackup = state->hprevbackup;
double *const errlev = state->errlev;
gsl_vector *const abscor = state->abscor;
gsl_vector *const relcor = state->relcor;
gsl_vector *const svec = state->svec;
gsl_vector *const tempvec = state->tempvec;
size_t ord = state->ord;
double ordm1coeff = 0.0;
double ordp1coeff = 0.0;
double ordp2coeff = 0.0;
double errcoeff = 0.0; /* error coefficient */
int deltaord;
#ifdef DEBUG
{
size_t di;
printf ("msadams_apply: t=%.5e, ord=%d, h=%.5e, y:", t, (int) ord, h);
for (di = 0; di < dim; di++)
{
printf ("%.5e ", y[di]);
}
printf ("\n");
}
#endif
/* Check if t is the same as on previous stepper call (or last
failed call). This means that calculation of previous step failed
or the step was rejected, and therefore previous state will be
restored or the method will be reset.
*/
if (state->ni > 0 && (t == state->tprev || t == state->failt))
{
if (state->ni == 1)
{
/* No step has been accepted yet, reset method */
msadams_reset (vstate, dim);
#ifdef DEBUG
printf ("-- first step was REJECTED, msadams_reset called\n");
#endif
}
else
{
/* A succesful step has been saved, restore previous state. */
/* If previous step suggests order increase, but the step was
rejected, then do not increase order.
*/
if (ord > state->ordprev)
{
state->ord = state->ordprev;
ord = state->ord;
}
/* Restore previous state */
DBL_MEMCPY (z, zbackup, (MSADAMS_MAX_ORD + 1) * dim);
DBL_MEMCPY (hprev, hprevbackup, MSADAMS_MAX_ORD);
state->ordprev = state->ordprevbackup;
state->ordwait = state->ordwaitbackup;
#ifdef DEBUG
printf ("-- previous step was REJECTED, state restored\n");
#endif
}
/* If step is repeatedly rejected, then reset method */
state->failcount++;
{
const size_t max_failcount = 3;
if (state->failcount > max_failcount && state->ni > 1)
{
msadams_reset (vstate, dim);
ord = state->ord;
#ifdef DEBUG
printf ("-- max_failcount reached, msadams_reset called\n");
#endif
}
}
}
else
{
/* The previous step was accepted. Backup current state. */
DBL_MEMCPY (zbackup, z, (MSADAMS_MAX_ORD + 1) * dim);
DBL_MEMCPY (hprevbackup, hprev, MSADAMS_MAX_ORD);
state->ordprevbackup = state->ordprev;
state->ordwaitbackup = state->ordwait;
state->failcount = 0;
#ifdef DEBUG
if (state->ni > 0)
{
printf ("-- previous step was ACCEPTED, state saved\n");
}
#endif
}
#ifdef DEBUG
printf ("-- ord=%d, ni=%ld, ordwait=%d\n", (int) ord, state->ni,
(int) state->ordwait);
printf ("-- ordprev: %d\n", (int) state->ordprev);
#endif
/* Get desired error levels via gsl_odeiv2_control object through driver
object, which is a requirement for this stepper.
*/
if (state->driver == NULL)
{
return GSL_EFAULT;
}
else
{
size_t i;
for (i = 0; i < dim; i++)
{
if (dydt_in != NULL)
{
gsl_odeiv2_control_errlevel (state->driver->c, y[i],
dydt_in[i], h, i, &errlev[i]);
}
else
{
gsl_odeiv2_control_errlevel (state->driver->c, y[i],
0.0, h, i, &errlev[i]);
}
}
}
#ifdef DEBUG
{
size_t di;
printf ("-- errlev: ");
for (di = 0; di < dim; di++)
{
printf ("%.5e ", errlev[di]);
}
printf ("\n");
}
#endif
/* On first call initialize Nordsieck matrix */
if (state->ni == 0)
{
size_t i;
DBL_ZERO_MEMSET (z, (MSADAMS_MAX_ORD + 1) * dim);
if (dydt_in != NULL)
{
DBL_MEMCPY (ytmp, dydt_in, dim);
}
else
{
int s = GSL_ODEIV_FN_EVAL (sys, t, y, ytmp);
if (s != GSL_SUCCESS)
{
return s;
}
}
DBL_MEMCPY (&z[0 * dim], y, dim);
DBL_MEMCPY (&z[1 * dim], ytmp, dim);
for (i = 0; i < dim; i++)
{
z[1 * dim + i] *= h;
}
}
/* Sanity check */
deltaord = ord - state->ordprev;
if (deltaord > 1 || deltaord < -1)
{
printf ("-- order change %d\n", deltaord);
GSL_ERROR_NULL ("msadams_apply too large order change", GSL_ESANITY);
}
/* Modify Nordsieck matrix if order or step length has been changed */
/* If order increased by 1, initialize new Nordsieck vector */
if (deltaord == 1)
{
DBL_ZERO_MEMSET (&z[ord * dim], dim);
#ifdef DEBUG
printf ("-- order increase detected, Nordsieck modified\n");
#endif
}
/* If order decreased by 1, adjust Nordsieck matrix */
if (deltaord == -1)
{
double hsum = 0.0;
size_t i, j;
/* Calculate coefficients used in adjustment to l */
DBL_ZERO_MEMSET (l, MSADAMS_MAX_ORD + 1);
l[1] = 1.0;
for (i = 1; i < ord; i++)
{
hsum += hprev[i - 1];
for (j = i + 1; j > 0; j--)
{
l[j] *= hsum / hprev[0];
l[j] += l[j - 1];
}
}
for (i = 1; i < ord; i++)
{
l[i + 1] = (ord + 1) * l[i] / (i + 1);
}
/* Scale Nordsieck matrix */
for (i = 2; i < ord + 1; i++)
for (j = 0; j < dim; j++)
{
z[i * dim + j] += -l[i] * z[(ord + 1) * dim + j];
}
#ifdef DEBUG
printf ("-- order decrease detected, Nordsieck modified\n");
#endif
}
/* Scale Nordsieck vectors if step size has been changed */
if (state->ni > 0 && h != hprev[0])
{
size_t i, j;
const double hrel = h / hprev[0];
double coeff = hrel;
for (i = 1; i < ord + 1; i++)
{
for (j = 0; j < dim; j++)
{
z[i * dim + j] *= coeff;
}
coeff *= hrel;
}
#ifdef DEBUG
printf ("-- h != hprev, Nordsieck modified\n");
#endif
}
/* Calculate polynomial coefficients (l), error coefficient and
auxiliary coefficients
*/
msadams_calccoeffs (ord, state->ordwait, h, hprev, pc, l, &errcoeff,
º1coeff, &ordp1coeff, &ordp2coeff);
/* Carry out the prediction step */
{
size_t i, j, k;
for (i = 1; i < ord + 1; i++)
for (j = ord; j > i - 1; j--)
for (k = 0; k < dim; k++)
{
z[(j - 1) * dim + k] += z[j * dim + k];
}
#ifdef DEBUG
{
size_t di;
printf ("-- predicted y: ");
for (di = 0; di < dim; di++)
{
printf ("%.5e ", z[di]);
}
printf ("\n");
}
#endif
}
/* Calculate correction step to abscor */
{
int s;
s = msadams_corrector (vstate, sys, t, h, dim, z, errlev, l, errcoeff,
abscor, relcor, ytmp, ytmp2);
if (s != GSL_SUCCESS)
{
return s;
}
}
{
/* Add accepted final correction step to Nordsieck matrix */
size_t i, j;
for (i = 0; i < ord + 1; i++)
for (j = 0; j < dim; j++)
{
z[i * dim + j] += l[i] * gsl_vector_get (abscor, j);
}
#ifdef DEBUG
{
size_t di;
printf ("-- corrected y: ");
for (di = 0; di < dim; di++)
{
printf ("%.5e ", z[di]);
}
printf ("\n");
}
#endif
/* Derivatives at output */
if (dydt_out != NULL)
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, z, dydt_out);
if (s == GSL_EBADFUNC)
{
return s;
}
if (s != GSL_SUCCESS)
{
msadams_failurehandler (vstate, dim, t);
#ifdef DEBUG
printf ("-- FAIL at user function evaluation\n");
#endif
return s;
}
}
/* Calculate error estimate */
for (i = 0; i < dim; i++)
{
yerr[i] = fabs (gsl_vector_get (abscor, i)) * errcoeff;
}
#ifdef DEBUG
{
size_t di;
printf ("-- yerr: ");
for (di = 0; di < dim; di++)
{
printf ("%.5e ", yerr[di]);
}
printf ("\n");
}
#endif
/* Save y values */
for (i = 0; i < dim; i++)
{
y[i] = z[0 * dim + i];
}
}
/* Scale abscor with errlev for later use in norm calculations */
{
size_t i;
for (i = 0; i < dim; i++)
{
gsl_vector_set (abscor, i, gsl_vector_get (abscor, i) / errlev[i]);
}
}
/* Save items needed for evaluation of order increase on next
call, if needed
*/
if (state->ordwait == 1 && ord < MSADAMS_MAX_ORD)
{
size_t i;
state->ordp1coeffprev = ordp1coeff;
state->ordm1coeff = ordm1coeff;
for (i = 0; i < dim; i++)
{
gsl_vector_set (svec, i, gsl_vector_get (abscor, i));
}
}
/* Consider and execute order change for next step */
if (state->ordwait == 0)
{
msadams_eval_order (abscor, tempvec, svec, errcoeff, dim, errlev,
state->ordm1coeff, ordp1coeff,
state->ordp1coeffprev, ordp2coeff,
hprev, h, z, &(state->ord), &(state->ordwait));
}
/* Save information about current step in state and update counters */
{
size_t i;
state->ordprev = ord;
for (i = MSADAMS_MAX_ORD - 1; i > 0; i--)
{
hprev[i] = hprev[i - 1];
}
hprev[0] = h;
#ifdef DEBUG
{
size_t di;
printf ("-- hprev: ");
for (di = 0; di < MSADAMS_MAX_ORD; di++)
{
printf ("%.5e ", hprev[di]);
}
printf ("\n");
}
#endif
state->tprev = t;
state->ordwait--;
state->ni++;
}
return GSL_SUCCESS;
}
static int
msadams_set_driver (void *vstate, const gsl_odeiv2_driver * d)
{
msadams_state_t *state = (msadams_state_t *) vstate;
state->driver = d;
return GSL_SUCCESS;
}
static int
msadams_reset (void *vstate, size_t dim)
{
msadams_state_t *state = (msadams_state_t *) vstate;
state->ni = 0;
state->ord = 1;
state->ordprev = 1;
state->ordprevbackup = 1;
state->ordwait = 2;
state->ordwaitbackup = 2;
state->failord = 0;
state->failt = GSL_NAN;
state->failcount = 0;
DBL_ZERO_MEMSET (state->hprev, MSADAMS_MAX_ORD);
DBL_ZERO_MEMSET (state->z, (MSADAMS_MAX_ORD + 1) * dim);
#ifdef DEBUG
printf ("-- msadams_reset called\n");
#endif
return GSL_SUCCESS;
}
static unsigned int
msadams_order (void *vstate)
{
msadams_state_t *state = (msadams_state_t *) vstate;
return state->ord;
}
static void
msadams_free (void *vstate)
{
msadams_state_t *state = (msadams_state_t *) vstate;
gsl_vector_free (state->tempvec);
gsl_vector_free (state->svec);
gsl_vector_free (state->relcor);
gsl_vector_free (state->abscor);
free (state->errlev);
free (state->hprevbackup);
free (state->hprev);
free (state->l);
free (state->pc);
free (state->ytmp2);
free (state->ytmp);
free (state->zbackup);
free (state->z);
free (state);
}
static const gsl_odeiv2_step_type msadams_type = {
"msadams", /* name */
1, /* can use dydt_in? */
1, /* gives exact dydt_out? */
&msadams_alloc,
&msadams_apply,
&msadams_set_driver,
&msadams_reset,
&msadams_order,
&msadams_free
};
const gsl_odeiv2_step_type *gsl_odeiv2_step_msadams = &msadams_type;
| {
"alphanum_fraction": 0.5304271687,
"avg_line_length": 24.3178707224,
"ext": "c",
"hexsha": "3c3342cf13679a058472395e457f8fd25907441c",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ode-initval2/msadams.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/ode-initval2/msadams.c",
"max_line_length": 101,
"max_stars_count": 14,
"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/ode-initval2/msadams.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": 9284,
"size": 31978
} |
#ifndef QRTRANSPOSE_H
#define QRTRANSPOSE_H
#include <gsl/gsl_matrix.h>
#include "QR.h"
/**
* Compute and return the QR decomposition of a given matrix' transpose. If
* `M` is passed to the constructor, the `getQ` function will return the Q
* matrix in the decomposition M^T = QR et similis for `getR`.
*
* Convenient for computation of QR-backed nullspace (see NullspaceQR)
*/
class TransposeQR{
public:
TransposeQR(gsl_matrix* M);
void updateFromMatrix();
gsl_matrix* getMatrix() const;
/** Return the Q-matrix from the decomposition M^T = QR */
gsl_matrix* getQ() const;
/** Return the R-matrix from the decomposition M^T = QR */
gsl_matrix* getR() const;
private:
QR * const m_qr;
gsl_matrix * const m_origMatrix;
};
#endif
| {
"alphanum_fraction": 0.7054973822,
"avg_line_length": 21.2222222222,
"ext": "h",
"hexsha": "bb3b8593d030338c86af1019260fe52a56a53816",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_forks_repo_path": "src/math/TransposeQR.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_issues_repo_path": "src/math/TransposeQR.h",
"max_line_length": 75,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_stars_repo_path": "src/math/TransposeQR.h",
"max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z",
"num_tokens": 204,
"size": 764
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_sf_bessel.h>
#include "global.h"
#include "utility.h"
#include "constants.h"
#include <gsl/gsl_cblas.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <omp.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "steppmethods.h"
#define NUMBER_SAMPLES 1
#define NUMBER_VOLUMES 1
#define SHIFT_LATE 200
#define BINS 100
#define PDF_NR 12
// regular main but with multiple sampling runs over multiple volume fractions phi.
int
main (void){
FILE *source, *target;
source = fopen("global.h", "r"); // get source global.h at program start so as to not copy edits during run
if( source == NULL )
{
printf("cannot open global.h\n");
exit(EXIT_FAILURE);
}
SETNUMTHREADS
int i,j,l,k,m ,n;
Constants(); // draw coupling constants and other derived constants
double *t = calloc(LENGTH_T, sizeof(double));
time_t tme = time(NULL);
char ordnerLABEL[300];
char ueberordnerLABEL[300];
char ordnerLABEL_original[300];
strftime(ordnerLABEL, sizeof ordnerLABEL, "%A %c", localtime(&tme));
double squares_all_calcs[LENGTH_T][NUMBER_SAMPLES]; // for printing all squares in shared table
i = 0;
printf("\n%s\n", ordnerLABEL);
deleteSpaces(ordnerLABEL,ordnerLABEL);
strcpy (ordnerLABEL_original, ordnerLABEL); // keep original, change ordnerLABEL per run
double alpha_global = ALPHA;
double temp_global = TEMP; // macros from global make trouble when used as print arguments, hence copy to memory
sprintf(ueberordnerLABEL,"N=%d_SIM=%d_T=%1.1E_ALPH=%1.1f", OSSZI, SIMULATIONEN, temp_global, alpha_global);
char tempLABEL[300];
strcpy (tempLABEL, ordnerLABEL);
strcat(tempLABEL, LABELPREFIX);
strcat(tempLABEL, ueberordnerLABEL);
strcpy (ueberordnerLABEL, tempLABEL);
struct stat st2 = {0};
double prob_density[BINS][PDF_NR];
for (i = 0; i < BINS ; i++)
{
for (j = 0; j < PDF_NR; j++)
{
prob_density[i][j] = 0.0;
}
}
int check_times[PDF_NR];
for (j = 0; j < PDF_NR; j++)
{
check_times[j] = (int) ( 10.0 * (j+1)) ;
}
check_times[PDF_NR-1] = LENGTH_T - 1;
for (j = 0; j < PDF_NR; j++)
{
printf("check times nr %d is %d \n", j, check_times[j]);
}
printf("\nprint results into ");
printf(ueberordnerLABEL);
if (stat(ueberordnerLABEL, &st2) == -1)
{ //Teste ob Ordner existiert, erstelle Ordner
mkdir(ueberordnerLABEL, 0700);
}
if (chdir(ueberordnerLABEL)) // change into directory of simulation
{
printf("Error changing directory");
return 1;
}
// reserviere speicher fuer eine Vollständige trajektorie ------------------
m = LENGTH_T; n = ORDER;
double **z = (double **) malloc(m * sizeof(double *));
z[0] = (double *) malloc(m* n * sizeof(double));
for (i=1; i<m; i++) z[i] = z[0] + n *i;
double *squares = calloc(LENGTH_T, sizeof(double));
double *short_correlation_x = calloc(LENGTH_T, sizeof(double)); //short term (1 timestep) correlations
double *short_correlation_y = calloc(LENGTH_T, sizeof(double));
double *total_momentum_x = calloc(LENGTH_T, sizeof(double));
double *total_momentum_y = calloc(LENGTH_T, sizeof(double));
double *long_correlation_x = calloc(LENGTH_T, sizeof(double)); //longterm correlation from first timestep
double *long_correlation_y = calloc(LENGTH_T, sizeof(double));
double *squares_increase = calloc(LENGTH_T, sizeof(double)); // Increase a from assumed form x^2 0 = a t
double real_volumes[10];
double *bathp = calloc(LENGTH_T, sizeof(double));
double *bathq = calloc(LENGTH_T, sizeof(double));
double *px_correlation = calloc(LENGTH_T, sizeof(double)); // save correlation of impulse_x to px(t=0)
double *py_correlation = calloc(LENGTH_T, sizeof(double));
double *px_correlation_late = calloc(LENGTH_T, sizeof(double)); // corelation after time SHIFT_LATE
double *px_correlation_late2 = calloc(LENGTH_T, sizeof(double)); // corelation after time SHIFT_LATE
int n_zplots = SIMULATIONEN;
if (SIMULATIONEN > MAX_NR_PLOTS ) n_zplots = MAX_NR_PLOTS; // speichere maximal 30*DIM trajectorien
// reserviere speicher fuer samplepfade massives Teilchen zum plotten ------------------
m = LENGTH_T; n = DIM*n_zplots;
double **zplots = (double **) malloc(m * sizeof(double *));
zplots[0] = (double *) malloc(m* n * sizeof(double));
for (i=1; i<m; i++) zplots[i] = zplots[0] + n *i;
// reserviere speicher fuer samplepfade 1. bad Teilchen zum plotten ------------------
m = LENGTH_T; n = DIM*n_zplots;
double **qplots = (double **) malloc(m * sizeof(double *));
qplots[0] = (double *) malloc(m* n * sizeof(double));
for (i=1; i<m; i++) qplots[i] = qplots[0] + n *i;
// reserviere speicher fuer samplepfade letztes bad Teilchen zum plotten ------------------
m = LENGTH_T; n = DIM*n_zplots;
double **qlplots = (double **) malloc(m * sizeof(double *));
qlplots[0] = (double *) malloc(m* n * sizeof(double));
for (i=1; i<m; i++) qlplots[i] = qlplots[0] + n *i;
// reserviere speicher fuer samplepfade zusätzlicher Kac_Zwanzig Kraft Term ------------------
m = LENGTH_T; n = DIM*n_zplots;
double **Zwanzig_Force = (double **) malloc(m * sizeof(double *));
Zwanzig_Force[0] = (double *) malloc(m* n * sizeof(double));
for (i=1; i<m; i++) Zwanzig_Force[i] = Zwanzig_Force[0] + n *i;
// reserviere speicher fuer probability Density ------------------
m = 80; n = 80;
double **P_density = (double **) malloc(m * sizeof(double *));
P_density[0] = (double *) malloc(m* n * sizeof(double));
for (i=1; i<m; i++) P_density[i] = P_density[0] + n *i;
// reserviere speicher fuer Gitterkoordinaten ------------------
double DENSITY_POINTS = 0.0;
for(m=0; m<80; m++)
{
for(n=0; n<80; n++)
{
P_density[m][n] = 0.0;
}
}
double *EKIN = calloc(LENGTH_T, sizeof(double));
double *EBAD = calloc(LENGTH_T, sizeof(double));
double *ETOT = calloc(LENGTH_T, sizeof(double));
double *PTOT = calloc(LENGTH_T, sizeof(double));
double *PTOTY = calloc(LENGTH_T, sizeof(double));
double *LTOT = calloc(LENGTH_T, sizeof(double));
// GSL random number Setup for Taus Generator
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_ranlxd2;
r = gsl_rng_alloc (T);
gsl_rng_set(r, time(NULL)); // Seed with time
// RNG setup End //
// GSL random number Setup for Taus Generator for global rand
const gsl_rng_type * T2;
T2 = gsl_rng_ranlxd2;
RAND_GLOBAL = gsl_rng_alloc (T2);
gsl_rng_set(RAND_GLOBAL, time(NULL)); // Seed with time
// RNG setup End //
clock_t start, end;
printf("evenly spread t \n"); //set up time vec
for (i = 0; i < 10; i++) // first ten values in small steps
{
t[i] = i * TIME_STEPS/10.0;
}
for (i = 10; i < LENGTH_T; i++)
{
t[i] = (i-9) * TIME_STEPS;
}
double squarespace = 0.0;
DIFF_COEFF = KBOLTZ * TEMP/GAMMA * sin(M_PI * ALPHA ) / (M_PI * ALPHA);
if(ALPHA > 0.95)
{
DIFF_COEFF = KBOLTZ * TEMP/GAMMA;
}
LATTICE_SPACING = sqrt(2*DIM*DIFF_COEFF * pow( TIME_ARRIVAL, ALPHA) );
printf("LATTICE_SPACING = %3.3E\n", LATTICE_SPACING);
double latlength = LATTICE_SPACING;
//------------------------------EIGENTLICHE SIMULATION ------------------------------------------------------------------
int sim_count = 0;
start = clock();
time_first_contact = 0.0;
int error_count = 0;
//
for (i = 0; i < SIMULATIONEN; i++)
{
vec_zero_i(lattice_position,DIM); // set stating cell to zero !
TARGET_CONTACT = 0;
FLAG_DUMP_VALUE = 0; // set to 1 if error occures
// -------------------------BAD
Bath_Setup(y, LABEL, r); // draw intial conditions
//---------------------Bad aufgesetzt
VVerlet_parallel(ORDER, y, z, t, Poti_Handle);
end = clock();
//------------------------------auswertung Integrationsergebnisse
if ( !(FLAG_DUMP_VALUE)) // only count result without err
{
double *kahan_c = calloc(LENGTH_T, sizeof(double)); //
double *kahan_t = calloc(LENGTH_T, sizeof(double));
double *kahan_y = calloc(LENGTH_T, sizeof(double));
#pragma omp parallel for
for(l = 0; l < LENGTH_T; l++)
{
if (l>10)
{
long_correlation_x[l] += z[1][0] *z[l][0]/((double) SIMULATIONEN);
long_correlation_y[l] += z[1][1] *z[l][1]/((double) SIMULATIONEN);
}
kahan_y[l] = z[10][DIM] * z[l][DIM] / ((double) SIMULATIONEN) / (mass * KBOLTZ * TEMP)\
- kahan_c[l];
kahan_t[l] = px_correlation[l] + kahan_y[l];
kahan_c[l] = (kahan_y[l] - px_correlation[l]) - kahan_y[l];
px_correlation[l] = kahan_t[l];
py_correlation[l] += z[10][DIM + 1] * z[l][DIM + 1] / ((double) SIMULATIONEN) / (mass * KBOLTZ * TEMP);
px_correlation_late[l] += z[SHIFT_LATE][DIM] * z[l][DIM] / ((double) SIMULATIONEN) / (mass * KBOLTZ * TEMP);
px_correlation_late2[l] += z[SHIFT_LATE * 2][DIM] * z[l][DIM] / ((double) SIMULATIONEN) / (mass * KBOLTZ * TEMP);
for(j=0; j< DIM; j++)
{
if (i < n_zplots)
{
zplots[l][DIM * i + j] = z[l][j];
qplots[l][DIM * i + j] = z[l][2*DIM + j];
double Force_TEMP = 0.0;
for(int os = 0; os < OSSZI; os++)
{
Force_TEMP += (pow(coupling[os],2.0)/pow(ommega[os],2.0) - coupling[os]) * z[l][(2 + 2 * os) * DIM + j];
}
Zwanzig_Force[l][DIM * i + j]=Force_TEMP;
int i_last = OSSZI -1;
qlplots[l][DIM * i + j] = z[l][2*OSSZI*DIM + j];
}
squares[l] = squares[l] + pow(z[l][j],2.0)/((double) SIMULATIONEN);
EKIN[l] = EKIN[l] + pow(z[l][DIM+j],2.0)/(mass * SIMULATIONEN * KBOLTZ *TEMP * DIM);
for(k=0;k<OSSZI;k++)
{
bathq[l] = bathq[l] + pow(z[l][(2 + 2*k) *DIM +j],2.0)/( (double) (OSSZI*SIMULATIONEN)\
*KBOLTZ*TEMP) * pow(ommega[k],2.0)/2.0;// mittlere potentielle E pro Badteilchen
//reskaliert durch kT
bathp[l] = bathp[l] + pow(z[l][(3 + 2*k) *DIM +j],2.0)/( (double) (OSSZI*SIMULATIONEN)\
*KBOLTZ*TEMP) /2.0/massq[k]; // mittlere kinetische E pro Badteilchen
//reskaliert durch kT
EBAD[l] = EBAD[l] + pow(z[l][(3 + 2*k) *DIM +j], 2.0)/2.0\
+ 0.5 * pow(ommega[k],2.0) \
* pow(z[l][(2 + 2*k) *DIM +j] - coupling[k]/(pow(ommega[k],2.0) ) * z[l][j] , 2.0) /((double) SIMULATIONEN);
}
}
for(k=0;k<OSSZI;k++) // add p and angular momentum L for bath
{
PTOT[l] += z[l][(3 + 2*k) *DIM + 0];
PTOTY[l] += z[l][(3 + 2*k) *DIM + 1];
LTOT[l] += (z[l][(2 + 2*k) *DIM + 0] * z[l][(3 + 2*k) *DIM + 1]\
- z[l][(2 + 2*k) *DIM + 1] * z[l][(3 + 2*k) *DIM + 0]) /((double) SIMULATIONEN);
}
PTOT[l] += z[l][2];
PTOT[l] += z[l][3];
LTOT[l] += (z[l][0] * z[l][3] - z[l][1] * z[l][2]) / ((double) SIMULATIONEN);
}
if(DIM == 1)
{
// setup pdf checks
double bins = BINS * 1.0;
double dx = LATTICE_SPACING/bins;
double sims = SIMULATIONEN;
for (j = 0; j < PDF_NR; j++)
{
int t_check = check_times[j];
for (int i_bin = 0; i_bin < BINS; i_bin++)
{
double lower = -LATTICE_SPACING / 2.0 + i_bin * dx;
double upper = -LATTICE_SPACING / 2.0 + (i_bin + 1) * dx;
if ( ( z[t_check][0] <= upper) &&
( z[t_check][0] > lower)
)
{
prob_density[i_bin][j] += 1.0/sims;
}
}
}
}
sim_count += 1;
//printf("%d und t %4.2f \n", i ,((double) (end - start)));
printf("\r%d von %d mit t/count = %4.2f s und average t_rest =%4.2f h ", sim_count , SIMULATIONEN, (double) (end - start) / sim_count/ THREADS / CLOCKS_PER_SEC ,\
((double) (end - start) / sim_count/ THREADS/ CLOCKS_PER_SEC * (SIMULATIONEN - sim_count)/3600));
printf(" %d hits on Lat and avrgtcntct = %4.2f",TARGET_CONTACT, time_first_contact/(i+1) );
fflush(stdout);
for(l = 0; l < LENGTH_T; l++)
{
for (int oss_i=0; oss_i < OSSZI; oss_i++)
{
total_momentum_x[l] += z[l][(3 + 2*oss_i) *DIM + 0];
total_momentum_y[l] += z[l][(3 + 2*oss_i) *DIM + 1];
}
total_momentum_x[l] += z[l][(0 + 2*0) *DIM + 0];
total_momentum_y[l] += z[l][(0 + 2*0) *DIM + 1];
}
// -------------- end evaluation if----------------------
free(kahan_y); free(kahan_t); free(kahan_c);
}else
{
error_count++;
printf("\n err occured at calc %d, calculation dumped, %d totatl errors\n", i,error_count );
i -= 1; // do one more calculation
}
}
tme = time(NULL);
char end_label[90];
strftime( end_label, sizeof end_label, "%A %c", localtime(&tme));
printf("\n%s\n", end_label);
for(l = 0; l < LENGTH_T; l++)
{
ETOT[l] = EKIN[l] + EBAD[l];
PTOT[l] = sqrt(pow(PTOT[l]/((double) SIMULATIONEN),2.0) + pow(PTOTY[l]/((double) SIMULATIONEN),2.0));
}
for(l = 1; l < LENGTH_T; l++)
{
squares_increase[l] = (squares[l]- squares[l-1])/(t[l] - t[l-1]);
}
//------------------------------ENDE SIMULATION, speichere daten ------------------------------------------------------------------
for(m=0; m<80; m++)
{
for(n=0; n<80; n++)
{
P_density[m][n] *= 1.0/DENSITY_POINTS;
}
}
FILE *fp;
struct stat st = {0};
if (stat(ordnerLABEL, &st) == -1){ //Teste ob Ordner existiert, erstelle Ordner
mkdir(ordnerLABEL, 0700);
}
fp = fopen ("shellscript.sh", "w"); //create Shellscript to start Gnuplot from c main()
fprintf(fp, "cd %s\n", ordnerLABEL);
fprintf(fp, "gnuplot gnuplot.txt\n");
fprintf(fp, "cd ..");
fclose (fp);
// copy global.h /
// copy to same name into directory, clould be anything different
if (chdir(ordnerLABEL)) // change into directory of simulation
{
printf("Error changing directory");
return 1;
}
mkdir("plots", 0700);
mkdir("trajec", 0700);
target = fopen("global.h", "w");
if( target == NULL )
{
fclose(source);
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
char ch;
while( ( ch = fgetc(source) ) != EOF )
{
fputc(ch, target);
}
printf("File copied successfully.\n");
fclose(target);
fp = fopen ("latlength.dat", "w");
fprintf(fp, "%lf \n", latlength);
fclose (fp);
fp = fopen ("squares_rohdaten.dat", "w");
for(l = 0; l < LENGTH_T; l++){
fprintf(fp, "%1.3E %1.3E\n", t[l], squares[l]);
}
fclose (fp);
fp = fopen ("ekin.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%lf %lf\n", t[l]/TIME_ARRIVAL, EKIN[l]);
}
fclose (fp);
fp = fopen ("ekinbath.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%lf %lf\n", t[l]/TIME_ARRIVAL, bathp[l]);
}
fclose (fp);
fp = fopen ("ommega.dat", "w");
for(l = 0; l < OSSZI; l++){
fprintf(fp, "%lf\n", ommega[l]);
}
fclose (fp);
fp = fopen ("PTOT.dat", "w");
for(l = 0; l < LENGTH_T; l++){
fprintf(fp, "%lf %lf\n", t[l]/TIME_ARRIVAL, PTOT[l]);
}
fclose (fp);
fp = fopen ("P_X.dat", "w");
for(l = 0; l < LENGTH_T; l++){
fprintf(fp, "%lf %1.3e\n", t[l]/TIME_ARRIVAL, total_momentum_x[l]);
}
fclose (fp);
fp = fopen ("P_Y.dat", "w");
for(l = 0; l < LENGTH_T; l++){
fprintf(fp, "%lf %1.3e\n", t[l]/TIME_ARRIVAL, total_momentum_y[l]);
}
fclose (fp);
fp = fopen ("xshortcorellation.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%lf %lf\n", t[l]/TIME_ARRIVAL, short_correlation_x[l]/latlength/latlength);
}
fclose (fp);
fp = fopen ("yshortcorellation.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%lf %lf\n", t[l]/TIME_ARRIVAL, short_correlation_y[l]/latlength/latlength);
}
fclose (fp);
fp = fopen ("xlongcorellation.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%lf %lf\n", t[l]/TIME_ARRIVAL, long_correlation_x[l]/latlength/latlength);
}
fclose (fp);
fp = fopen ("ylongcorellation.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%lf %lf\n", t[l]/TIME_ARRIVAL, long_correlation_y[l]/latlength/latlength);
}
fclose (fp);
fp = fopen ("PX_corr.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%1.3E %1.3E\n", t[l]/TIME_ARRIVAL, px_correlation[l]);
}
fclose (fp);
fp = fopen ("PY_corr.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%1.3E %1.3E\n", t[l]/TIME_ARRIVAL, py_correlation[l]);
}
fclose (fp);
fp = fopen ("PX_corr_late.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%1.3E %1.3E\n", t[l]/TIME_ARRIVAL, px_correlation_late[l]);
}
fclose (fp);
fp = fopen ("PX_corr_late2.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%1.3E %1.3E\n", t[l]/TIME_ARRIVAL, px_correlation_late2[l]);
}
fclose (fp);
fp = fopen ("PX_corr_abs.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%1.3E %1.3E\n", t[l]/TIME_ARRIVAL, fabs(px_correlation[l]));
}
fclose (fp);
fp = fopen ("PX_corr_late_abs.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%1.3E %1.3E\n", t[l]/TIME_ARRIVAL, fabs(px_correlation_late[l]));
}
fclose (fp);
fp = fopen ("PX_corr_late2_abs.dat", "w");
for(l = 1; l < LENGTH_T; l++){
fprintf(fp, "%1.3E %1.3E\n", t[l]/TIME_ARRIVAL, fabs(px_correlation_late2[l]));
}
fclose (fp);
if (DIM == 1)
{
fp = fopen ("PDF_1D.dat", "w");
for (int pos = 0; pos < BINS; pos++)
{
fprintf(fp, "%1.3E ", -LATTICE_SPACING/2.0 + pos*LATTICE_SPACING/((double) BINS));
for(j = 0; j < PDF_NR; j++)
{
fprintf(fp, "%1.3E ", prob_density[pos][j]);
}
fprintf(fp,"\n");
}
fclose (fp);
}
// finde größtes s^2/t^alpha zum endzeitpunkt
int t_start = 10;
double temp_ende = 0.0;
for(int i_alpha = 1; i_alpha < 12; i_alpha ++){
double alpha_temp = 0.45 + 0.05 * i_alpha;
l = LENGTH_T-1;
if (temp_ende < (squares[l] / (pow(t[l], alpha_temp))) )
{
temp_ende = squares[l] / (pow(t[l], alpha_temp));
}
}
if (DIM>1)
{
char zplotsLABEL[30];
for (i = 0; i < n_zplots; i++)
{
sprintf(zplotsLABEL, "trajec/zplots%d.dat",i);
fp = fopen (zplotsLABEL, "w");
for(l = 0; l < LENGTH_T; l++){
for (j = 0; j < DIM ; j++){
fprintf(fp, "%lf ", ((zplots[l][j +i*DIM])/latlength) );
}
fprintf(fp, "\n");
}
fclose (fp);
}
for (i = 0; i < n_zplots; i++)
{
sprintf(zplotsLABEL, "trajec/qplots%d.dat",i);
fp = fopen (zplotsLABEL, "w");
for(l = 0; l < LENGTH_T; l++){
for (j = 0; j < DIM ; j++){
fprintf(fp, "%lf ", ((qplots[l][j +i*DIM])) );
}
fprintf(fp, "\n");
}
fclose (fp);
}
for (i = 0; i < n_zplots; i++)
{
sprintf(zplotsLABEL, "trajec/Zwanzig_Force%d.dat",i);
fp = fopen (zplotsLABEL, "w");
for(l = 0; l < LENGTH_T; l++){
for (j = 0; j < DIM ; j++){
fprintf(fp, "%lf ", ((Zwanzig_Force[l][j +i*DIM])) );
}
fprintf(fp, "\n");
}
fclose (fp);
}
for (i = 0; i < n_zplots; i++)
{
sprintf(zplotsLABEL, "trajec/qlplots%d.dat",i);
fp = fopen (zplotsLABEL, "w");
for(l = 0; l < LENGTH_T; l++){
for (j = 0; j < DIM ; j++){
fprintf(fp, "%lf ", ((qlplots[l][j +i*DIM])) );
}
fprintf(fp, "\n");
}
fclose (fp);
}
}
if (DIM==1)
{
char zplotsLABEL[30];
for (i = 0; i < n_zplots; i++)
{
sprintf(zplotsLABEL, "trajec/zplots%d.dat",i);
fp = fopen (zplotsLABEL, "w");
for(l = 0; l < LENGTH_T; l++){
fprintf(fp, " %lf %lf \n" ,t[l]/TIME_ARRIVAL, zplots[l][i*DIM]/latlength);
}
fclose (fp);
}
}
fp = fopen ("ETOT.dat", "w");
for(l = 0; l < LENGTH_T; l++){
fprintf(fp, "%lf %lf\n", t[l], ETOT[l]);
}
fclose (fp);
fp = fopen ("DENSITY.dat", "w");
for(m=0; m<80; m++)
{
for(n=0; n<80; n++)
{
fprintf(fp, "%1.2e ", P_density[m][n]);
}
fprintf(fp, "\n");
}
fclose (fp);
gsl_rng_free (r); gsl_rng_free (RAND_GLOBAL);
free(zplots[0]); free(zplots);
free(qplots[0]); free(qplots);
free(Zwanzig_Force[0]); free(Zwanzig_Force);
free(qlplots[0]); free(qlplots);
free (P_density[0]); free (P_density);
free(t);
free(bathp); free(bathq);
free(squares_increase);
free(short_correlation_x);
free(total_momentum_x);
free(total_momentum_y);
free(short_correlation_y);
free(long_correlation_x);
free(px_correlation); free(py_correlation);
free(px_correlation_late);
free(px_correlation_late2);
free(long_correlation_y);
free(ETOT); free(EKIN); free(EBAD);
free(PTOT); free(PTOTY);free(LTOT);
free(squares);
free(z[0]); free(z);
}
| {
"alphanum_fraction": 0.5600114717,
"avg_line_length": 31.6984848485,
"ext": "c",
"hexsha": "398f90c5ecbb1d6f68f6e6cf754d2bb0209fd717",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_forks_repo_path": "main_github.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_issues_repo_path": "main_github.c",
"max_line_length": 166,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_stars_repo_path": "main_github.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7166,
"size": 20921
} |
///
/// @file
///
/// @author Mirko Myllykoski (mirkom@cs.umu.se), Umeå University
///
/// @internal LICENSE
///
/// Copyright (c) 2019-2020, Umeå Universitet
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
///
/// 1. Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
///
/// 2. Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// 3. Neither the name of the copyright holder nor the names of its
/// contributors may be used to endorse or promote products derived from this
/// software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
///
#include <starneig_config.h>
#include <starneig/configuration.h>
#include "common.h"
#include "../common/common.h"
#include "../common/node_internal.h"
#include <starneig/gep_sm.h>
#include <cblas.h>
#include <stdlib.h>
__attribute__ ((visibility ("default")))
starneig_error_t starneig_GEP_SM_HessenbergTriangular(
int n,
double A[], int ldA,
double B[], int ldB,
double Q[], int ldQ,
double Z[], int ldZ)
{
extern void dgeqrf_(int const *, int const *, double *, int const *,
double *, double *, int const *, int *);
extern void dormqr_(char const *, char const *, int const *, int const *,
int const *, double const *, int const *, double const *, double *,
int const *, double*, const int *, int *);
extern void dgghd3_(char const *, char const *, int const *, int const *,
int const *, double *, int const *, double *, int const *, double *,
int const *, double *, int const *, double *, int const *, int *);
if (n < 1) return -1;
if (A == NULL) return -2;
if (ldA < n) return -3;
if (B == NULL) return -4;
if (ldB < n) return -5;
if (Q == NULL) return -6;
if (ldQ < n) return -7;
if (Z == NULL) return -8;
if (ldZ < n) return -9;
if (!starneig_node_initialized())
return STARNEIG_NOT_INITIALIZED;
starneig_wrappers_prepare();
starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_PARALLEL);
double *tau = NULL, *work = NULL;
int info, ilo = 1, ihi = n;
//
// allocate workspace
//
int lwork = 0;
{
int _lwork = -1;
double dlwork;
dgeqrf_(&n, &n, B, &ldB, tau, &dlwork, &_lwork, &info);
if (info != 0)
goto cleanup;
lwork = MAX(lwork, dlwork);
}
{
int _lwork = -1;
double dlwork;
dormqr_("L", "T", &n, &n, &n,
B, &ldB, tau, A, &ldA, &dlwork, &_lwork, &info);
if (info != 0)
goto cleanup;
lwork = MAX(lwork, dlwork);
}
{
int _lwork = -1;
double dlwork;
dormqr_("R", "N", &n, &n, &n,
B, &ldB, tau, Q, &ldQ, &dlwork, &_lwork, &info);
if (info != 0)
goto cleanup;
lwork = MAX(lwork, dlwork);
}
{
int _lwork = -1;
double dlwork;
dgghd3_("V", "V", &n, &ilo, &ihi,
A, &ldA, B, &ldB, Q, &ldQ, Z, &ldZ, &dlwork, &_lwork, &info);
if (info != 0)
goto cleanup;
lwork = MAX(lwork, dlwork);
}
tau = malloc(n*sizeof(double));
work = malloc(lwork*sizeof(double));
//
// reduce
//
// form B = ~Q * R
dgeqrf_(&n, &n, B, &ldB, tau, work, &lwork, &info);
if (info != 0)
goto cleanup;
// A <- ~Q^T * A
dormqr_("L", "T", &n, &n, &n, B, &ldB, tau, A, &ldA, work, &lwork, &info);
if (info != 0)
goto cleanup;
// Q <- Q * ~Q
dormqr_("R", "N", &n, &n, &n, B, &ldB, tau, Q, &ldQ, work, &lwork, &info);
if (info != 0)
goto cleanup;
// clean B (B <- R)
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
B[(size_t)i*ldB+j] = 0.0;
// reduce (A,B) to Hessenberg-triangular form
dgghd3_("V", "V", &n, &ilo, &ihi,
A, &ldA, B, &ldB, Q, &ldQ, Z, &ldZ, work, &lwork, &info);
if (info != 0)
goto cleanup;
cleanup:
starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_ORIGINAL);
starneig_wrappers_finish();
free(tau);
free(work);
return info;
}
| {
"alphanum_fraction": 0.582482028,
"avg_line_length": 29.3666666667,
"ext": "c",
"hexsha": "e4afb7763e0d87b9c0f356c95e6f90a9c02ae9b6",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z",
"max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/StarNEig",
"max_forks_repo_path": "src/wrappers/lapack.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/StarNEig",
"max_issues_repo_path": "src/wrappers/lapack.c",
"max_line_length": 80,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/StarNEig",
"max_stars_repo_path": "src/wrappers/lapack.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z",
"num_tokens": 1526,
"size": 5286
} |
/**
* author: Jochen K"upper
* created: Jan 2002
* file: pygsl/src/statisticsmodule.c
* $Id: doublemodule.c,v 1.9 2004/03/24 08:40:45 schnizer Exp $
*
* optional usage of Numeric module, available at http://numpy.sourceforge.net
* "
*/
#include <pygsl/error_helpers.h>
#include <pygsl/block_helpers.h>
#include <Python.h>
#include <gsl/gsl_statistics.h>
/* include real functions for default data-types (double in C) */
#define STATMOD_WEIGHTED
#define STATMOD_APPEND_PY_TYPE(X) X ## Float
#define STATMOD_APPEND_PYC_TYPE(X) X ## DOUBLE
#define STATMOD_FUNC_EXT(X, Y) X ## Y
#define STATMOD_PY_AS_C PyFloat_AsDouble
#define STATMOD_C_TYPE double
#define PyGSL_STATISTICS_IMPORT_API
#include "functions.c"
PyGSL_STATISTICS_INIT(double, "double")
/*
* Local Variables:
* mode: c
* c-file-style: "Stroustrup"
* End:
*/
| {
"alphanum_fraction": 0.7288941736,
"avg_line_length": 20.0238095238,
"ext": "c",
"hexsha": "faedc77cd1986fef1ea8533260bc5a4739d7b886",
"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/statistics/doublemodule.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/statistics/doublemodule.c",
"max_line_length": 78,
"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/statistics/doublemodule.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 236,
"size": 841
} |
/*
* CARP/Kaczmarz sweep on diagonally banded matrix. The essential loop is:
*
* for each row i
* x = x + w*(b(i) - A(i,:)*x)*A(i,:)'
* end
*
* The matrix is given in band storage format, where each row (stored
* contiguously in memory) of the array R stores a diagonal of the matrix with
* offset idx(j), such that
*
* A(i,i+idx(j)) = R(i,j)
*
* use (from MATLAB):
* y = sweepR_mex(R,idx,x,b,w,dir)
*
* R - matrix of diagonals of matrix A
* idx - offsets of diagonals
* x - initial guess
* b - right hand side (source)
* w - relaxation parameter (0 <= w <= 2)
* dir - if dir > 0, go through matrix rows in ascending order.
* if dir < 0, go through matrix rows in descending order.
* n_threads - OPTIONAL argument to control the number of execution
* threads solving CARP blocks in parallel. The number of threads can also
* be defined via an environment variable (OMP_NUM_THREADS), but this
* optional argument takes precedence. The default number of threads is
* one. Take care if using more than one MATLAB worker per node: each
* MATLAB worker will use OMP_NUM_THREADS, so if there are four workers on
* a node, there will be 4 x OMP_NUM_THREADS parallel CARP sweeps.
*
* Author: Art Petrenko, Tristan van Leeuwen
* Seismic Laboratory for Imaging and Modeling
* Department of Earth, Ocean, and Atmosperic Sciences
* The University of British Columbia
*
* Date: July, 2014
* You may use this code only under the conditions and terms of the
* license contained in the file LICENSE provided with this source
* code. If you do not agree to these terms you may not use this
* software.
*/
#include <stdlib.h> /* for getenv */
#include <stddef.h> /* for size_t type */
#include <string.h> /* for memcpy */
#include <pthread.h> /* for threading */
/* The following section allows this file to compile on Mac OS X 10.8.5. Pass
* the flag -DARCH_MACI64 to the compiler to activate it. */
#ifdef ARCH_MACI64
#include "pthread_barrier.h"
#include <mach/error.h>
typedef wchar_t char16_t;
#else /* not ARCH_MACI64 */
#include <error.h>
#endif /* ARCH_MACI64 */
#include <math.h>
#include <mex.h>
#include <matrix.h>
#include <blas.h>
struct copy_init_guess_data_t
{
double *copy_src_real, *copy_dst_real;
double *copy_src_imag, *copy_dst_imag;
long n_to_copy;
};
struct sweep_data_t
{
long start_row, end_row, ncol, ny, nx, haloWidth, main_diagonal_offset;
double *Rr, *Ri, *yr, *yi, *br, *bi;
long *idx;
double w;
int dir;
};
struct average_data_t
{
double *copy_src_real, *copy_dst_real;
double *copy_src_imag, *copy_dst_imag;
double *halo_1_real, *halo_2_real;
double *halo_1_imag, *halo_2_imag;
double *halo_dst_real, *halo_dst_imag;
long n_to_copy, n_in_halo;
};
struct thread_data_t
{
struct copy_init_guess_data_t copy_init_guess_data;
struct sweep_data_t sweep_data;
struct average_data_t average_data;
pthread_barrier_t *barrier;
};
void *do_sweep(void *thread_args_void)
{
struct sweep_data_t *thread_args;
/* Variables contained in thread_args_void struct */
long start_row, end_row, haloWidth, ncol, ny, nx;
/* Rr and Ri are pointers to short fat ncol-by-N matrices */
double *Rr, *Ri, *yr, *yi, *br, *bi;
long *idx;
double w;
int dir;
/* Temporary storage variables */
double cr = 0, ci = 0;
long offset, main_diagonal_offset;
/* Assign local pointers to data locations in shared memory */
thread_args = (struct sweep_data_t *) thread_args_void;
start_row = thread_args->start_row;
end_row = thread_args->end_row;
ncol = thread_args->ncol;
ny = thread_args->ny;
nx = thread_args->nx;
haloWidth = thread_args->haloWidth;
main_diagonal_offset = thread_args->main_diagonal_offset;
Rr = thread_args->Rr;
Ri = thread_args->Ri;
idx = thread_args->idx;
yr = thread_args->yr;
yi = thread_args->yi;
br = thread_args->br;
bi = thread_args->bi;
w = thread_args->w;
dir = thread_args->dir;
offset = (start_row == 0 ? 0 : haloWidth - main_diagonal_offset);
/* Kaczmarz sweep on one row block */
for(long i = (dir > 0 ? start_row : end_row-1);
dir > 0 ? i<end_row : i>=start_row;
dir > 0 ? i++ : i--)
{
if (0 <= i + main_diagonal_offset && i + main_diagonal_offset < nx){
cr = br[i + main_diagonal_offset];
ci = bi[i + main_diagonal_offset];
}
else{
//error(1,0,"Discovery of whether the iterate vector is haloed failed.");
}
/* First loop over non-zero row elements calculates inner product
* of matrix row and CARP iterate */
for(long j=0, k; j<ncol;j++){
/* i + idx[j] is the column index for the full Helmholtz matrix.
* k is the index into the vector representing the CARP iterate
* of the given block. */
k = i + idx[j] - start_row + offset;
if(0<=k && k<ny){
cr -= Rr[i*ncol + j]*yr[k] - Ri[i*ncol + j]*yi[k];
ci -= Rr[i*ncol + j]*yi[k] + Ri[i*ncol + j]*yr[k];
}
}
/* Second loop over non-zero row elements updates CARP iterate */
cr *= w;
ci *= w;
for(long j=0, k; j<ncol;j++){
k = i + idx[j] - start_row + offset;
if(0<=k && k<ny){
yr[k] += cr*Rr[i*ncol + j] + ci*Ri[i*ncol + j];
yi[k] += -cr*Ri[i*ncol + j] + ci*Rr[i*ncol + j];
}
}
}
return NULL;
}
void *average_halos(void *thread_args_void)
{
struct average_data_t *thread_args;
double *copy_src_real, *copy_dst_real;
double *copy_src_imag, *copy_dst_imag;
double *halo_1_real, *halo_2_real;
double *halo_1_imag, *halo_2_imag;
double *halo_dst_real, *halo_dst_imag;
size_t n_to_copy, n_in_halo;
/* Assign local pointer to data locations in shared memory */
thread_args = (struct average_data_t *) thread_args_void;
copy_src_real = thread_args->copy_src_real;
copy_dst_real = thread_args->copy_dst_real;
copy_src_imag = thread_args->copy_src_imag;
copy_dst_imag = thread_args->copy_dst_imag;
n_to_copy = thread_args->n_to_copy;
halo_1_real = thread_args->halo_1_real;
halo_2_real = thread_args->halo_2_real;
halo_dst_real = thread_args->halo_dst_real;
halo_1_imag = thread_args->halo_1_imag;
halo_2_imag = thread_args->halo_2_imag;
halo_dst_imag = thread_args->halo_dst_imag;
n_in_halo = thread_args->n_in_halo;
/* Copy the non-halo parts of the domain block directly to output array */
memcpy((void *)copy_dst_real, (void *)copy_src_real, sizeof(double)*n_to_copy);
memcpy((void *)copy_dst_imag, (void *)copy_src_imag, sizeof(double)*n_to_copy);
/* Average the halo parts of the domain block and copy to output array.
* NOTE: this assumes domain blocks overlap only with their nearest
* neighbour segments. */
for (long i = 0; i < n_in_halo; i++){
halo_dst_real[i] = (halo_1_real[i] + halo_2_real[i]) / 2;
halo_dst_imag[i] = (halo_1_imag[i] + halo_2_imag[i]) / 2;
}
return NULL;
}
void *sweep_and_average(void *thread_data_void)
{
struct thread_data_t *thread_data = (struct thread_data_t *) thread_data_void;
/* Copy the initial guess into the working arrays */
memcpy((void *)thread_data->copy_init_guess_data.copy_dst_real, (void *)thread_data->copy_init_guess_data.copy_src_real, sizeof(double)*thread_data->copy_init_guess_data.n_to_copy);
memcpy((void *)thread_data->copy_init_guess_data.copy_dst_imag, (void *)thread_data->copy_init_guess_data.copy_src_imag, sizeof(double)*thread_data->copy_init_guess_data.n_to_copy);
do_sweep((void *) &(thread_data->sweep_data));
pthread_barrier_wait(thread_data->barrier);
average_halos((void *) &(thread_data->average_data));
return NULL;
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
/* structs to hold all arguments to each thread in one variable */
struct sweep_data_t **thread_args_sweep = NULL;
struct average_data_t **thread_args_average = NULL;
struct thread_data_t **thread_data = NULL;
struct copy_init_guess_data_t **copy_init_guess_data = NULL;
pthread_barrier_t barrier_after_sweep_before_halo_average;
mwSize ncol, nx;
ptrdiff_t ncolBlas, idxIncBlas = 1, maxIdxLoc = 0;
mwSize haloWidth;
mwSize n_threads = 1;
char *n_threads_str = NULL;
double *Rr,*Ri,*idxd = NULL,*xr,*xi,*br,*bi,*yr,*yi;
long *idx = NULL;
double w = 0;
int dir = 1;
mwSize N=1, numGridPointsPerBlock, main_diagonal_offset;
/* Flags that are set if memory is allocated within the MEX file */
int Ri_alloc=0, xi_alloc=0, bi_alloc=0;
/* a return code flag and segment demarcation arrays */
mwSize i_thread;
mwSize *seg_bounds_hi, *seg_bounds_mid, *seg_bounds_row, *seg_bounds_lo;
/* Threading variables */
pthread_t *threadIDs = NULL;
pthread_attr_t attr;
/* Arrays to hold (overlapping) segments of yr and yi, a pair for each
* thread */
double **yr_seg = NULL, **yi_seg = NULL;
/* Allow worker threads to join back to main thread once they are done */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
/* Read input arguments; initialize complex part to zero if input is real. */
N = mxGetN(prhs[0]);
ncol = mxGetM(prhs[0]);
ncolBlas = (ptrdiff_t)ncol;
Rr = mxGetPr(prhs[0]);
if(mxIsComplex(prhs[0])){
Ri = mxGetPi(prhs[0]);
}
else{
Ri = mxCalloc(N*ncol,sizeof(double));
Ri_alloc = 1;
}
idxd = mxGetPr(prhs[1]);
nx = mxGetM(prhs[2]);
xr = mxGetPr(prhs[2]);
if(mxIsComplex(prhs[2])){
xi = mxGetPi(prhs[2]);
}
else{
xi = mxCalloc(nx,sizeof(double));
xi_alloc = 1;
}
br = mxGetPr(prhs[3]);
if(mxIsComplex(prhs[3])){
bi = mxGetPi(prhs[3]);
}
else{
bi = mxCalloc(nx,sizeof(double));
bi_alloc = 1;
}
if (mxGetM(prhs[3]) != nx){
mexPrintf('%d %d \n',mxGetM(prhs[3]),nx);
mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:NumElements",
"The number of elements in the iterate and right hand side vectors must be equal.");
}
w = mxGetScalar(prhs[4]);
dir = lrint(mxGetScalar(prhs[5]));
/* The default value for the number of threads can be overridden by an
* environment variable. */
n_threads_str = getenv("OMP_NUM_THREADS");
if (n_threads_str == NULL){
n_threads = 1;
}
else{
n_threads = strtol(n_threads_str, NULL, 10);
if(n_threads < 1){
n_threads = 1;
}
}
/* The environment variable can in turn be overridden by an optional
* argument to the mexFunction. */
if (nrhs >= 7){
if(1 <= lrint(mxGetScalar(prhs[6]))){
n_threads = lrint(mxGetScalar(prhs[6]));
}
}
/* Allocate the final output vector */
plhs[0] = mxCreateDoubleMatrix(nx, 1, mxCOMPLEX);
yr = mxGetPr(plhs[0]);
yi = mxGetPi(plhs[0]);
/* Check to make sure memory was allocated correctly */
if (Rr==NULL || Ri==NULL || idxd==NULL || xr==NULL || xi==NULL || br==NULL || bi==NULL ||
yr==NULL || yi==NULL){
mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:OutOfMemory",
"Could not allocate memory for main computational variables.");
}
if ((idx = (long *) mxCalloc(ncol, sizeof(long))) == NULL){
mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:OutOfMemory",
"Could not allocate memory for main computational variables.");
}
for (mwSize i=0; i < ncol; i++){
idx[i] = lrint(idxd[i]);
}
/* Compute (half) halo width. Remember that BLAS routines like idamax
* return FORTRAN-style indices. */
maxIdxLoc = idamax_(&ncolBlas, idxd, &idxIncBlas) - 1;
haloWidth = (mwSize)labs(idx[maxIdxLoc]);
/* Partition the iterate vector into blocks. Note that the below
* partitioning scheme is slighlty different from that in pCARPCG.m in this
* directory. The partitioning scheme of pCARPCG corresponds to
* distributing a three dimensional array with dimensions given by n
* according to Matlab's codistributor1d.defaultPartition(n(3)), and then
* vectorizing it. The partition scheme of the present file instead uses
* Matlab's codistributor1d.defaultPartion(prod(n)). In other words,
* pCARPCG divides the iterate into blocks along the slow dimension,
* whereas sweepR_mex.c does not take dimensionality into account, only the
* total number of gridpoints. This is done to avoid needing an extra input
* parameter with the the system dimensions. The seg_bounds_hi, _lo and
* _mid arrays contain indices into non-haloed vectors, while the
* seg_bounds_row array contains indices to the rows of the system matrix.
*
* yr_seg[i_thread-1] overlap yr_seg[i_thread]
* ------------------------|-----|-----|-------------------------------
* .----------------^ | ^-------------------.
* seg_bounds_lo[i_thread], seg_bounds_mid[i_thread], seg_bounds_hi[i_thread]
*/
numGridPointsPerBlock = N / n_threads;
seg_bounds_hi = (mwSize *)mxCalloc(n_threads+1,sizeof(mwSize));
seg_bounds_mid = (mwSize *)mxCalloc(n_threads+1,sizeof(mwSize));
seg_bounds_lo = (mwSize *)mxCalloc(n_threads+1,sizeof(mwSize));
seg_bounds_row = (mwSize *)mxCalloc(n_threads+1,sizeof(mwSize));
if (N == nx){
main_diagonal_offset = 0;
}
else{
/* The vector is haloed. We are only able to correctly process matrices
* with a non-zero main diagonal and symmetric off-main diagonal offsets. */
if (ncol % 2 != 1){
mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:EvenNumberOfDiags",
"Input iterate vector appears to be haloed but there is an even number of non-zero diagonals in the system matrix.");
}
main_diagonal_offset = idx[ncol/2];
for (mwSize i = 1; i <= ncol/2; i++){
if (idx[ncol/2 + i] - main_diagonal_offset != -(idx[ncol/2 - i] - main_diagonal_offset)){
mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:DiagsNotSymmetric",
"Input iterate vector appears to be haloed but the pattern of non-zero diagonals in the system matrix is not symmetric.");
}
}
}
for (i_thread=0; i_thread<n_threads; i_thread++){
/* First domain block */
if (i_thread==0){
seg_bounds_hi[i_thread] = 0;
seg_bounds_mid[i_thread] = 0;
seg_bounds_row[i_thread] = 0;
seg_bounds_lo[i_thread] = 0;
}
/* Other domain blocks */
else {
if (i_thread <= N % n_threads) {
seg_bounds_mid[i_thread] = (numGridPointsPerBlock+1)*i_thread + main_diagonal_offset;
seg_bounds_row[i_thread] = (numGridPointsPerBlock+1)*i_thread;
seg_bounds_hi[i_thread] = (numGridPointsPerBlock+1)*i_thread + haloWidth + main_diagonal_offset;
seg_bounds_lo[i_thread] = (numGridPointsPerBlock+1)*i_thread - haloWidth + main_diagonal_offset;
}
else{
seg_bounds_mid[i_thread] = (N % n_threads) + numGridPointsPerBlock*i_thread + main_diagonal_offset;
seg_bounds_row[i_thread] = (N % n_threads) + numGridPointsPerBlock*i_thread;
seg_bounds_hi[i_thread] = (N % n_threads) + numGridPointsPerBlock*i_thread + haloWidth + main_diagonal_offset;
seg_bounds_lo[i_thread] = (N % n_threads) + numGridPointsPerBlock*i_thread - haloWidth + main_diagonal_offset;
}
/* Check that halos do not overlap each other */
if (seg_bounds_lo[i_thread] < seg_bounds_hi[i_thread-1]){
mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:TooManyThreads",
"Too many threads; non-adjacent domain blocks share nearest-neighbour grid points.");
}
}
}
seg_bounds_lo[n_threads] = nx;
seg_bounds_hi[n_threads] = nx;
seg_bounds_mid[n_threads] = nx;
seg_bounds_row[n_threads] = N;
/* Allocate pointers to segments, to thread arguments and thread IDs */
thread_args_sweep = (struct sweep_data_t **)mxCalloc(n_threads, sizeof(struct sweep_data_t *));
if (n_threads > 1) {
/* Set up a barrier for synchronization of all threads save the master that
* executes mexFunction. Note that strictly speaking, only threads working
* on domain blocks that share halos need to synchronize with each other.
* */
if (pthread_barrier_init(&barrier_after_sweep_before_halo_average, NULL, n_threads)){
mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:pthreads",
"Could not initialize pthread barrier.");
}
thread_data = (struct thread_data_t **)mxCalloc(n_threads, sizeof(struct thread_data_t *));
thread_args_average = (struct average_data_t **)mxCalloc(n_threads, sizeof(struct average_data_t *));
copy_init_guess_data = (struct copy_init_guess_data_t **)mxCalloc(n_threads, sizeof(struct copy_init_guess_data_t *));
yr_seg = (double **)mxCalloc(n_threads,sizeof(double *));
yi_seg = (double **)mxCalloc(n_threads,sizeof(double *));
threadIDs = (pthread_t *)mxCalloc(n_threads,sizeof(pthread_t));
}
for (i_thread=0; i_thread<n_threads; i_thread++){
/* Allocate the segments for each thread */
if (n_threads > 1) {
yr_seg[i_thread] = (double *)mxCalloc((seg_bounds_hi[i_thread+1]-seg_bounds_lo[i_thread]),sizeof(double));
yi_seg[i_thread] = (double *)mxCalloc((seg_bounds_hi[i_thread+1]-seg_bounds_lo[i_thread]),sizeof(double));
/* Check that segments were allocated correctly */
if (yr_seg[i_thread]==NULL || yi_seg[i_thread]==NULL){
mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:pthreadsOutOfMemory",
"Could not allocate memory for thread computational variables.");
}
copy_init_guess_data[i_thread] = (struct copy_init_guess_data_t *)mxCalloc(1,sizeof(struct copy_init_guess_data_t));
copy_init_guess_data[i_thread]->copy_src_real = &xr[seg_bounds_lo[i_thread]];
copy_init_guess_data[i_thread]->copy_src_imag = &xi[seg_bounds_lo[i_thread]];
copy_init_guess_data[i_thread]->copy_dst_real = yr_seg[i_thread];
copy_init_guess_data[i_thread]->copy_dst_imag = yi_seg[i_thread];
copy_init_guess_data[i_thread]->n_to_copy = (size_t) (seg_bounds_hi[i_thread+1] - seg_bounds_lo[i_thread]);
}
/* Set thread arguments */
thread_args_sweep[i_thread] = (struct sweep_data_t *)mxCalloc(1,sizeof(struct sweep_data_t));
thread_args_sweep[i_thread]->start_row = seg_bounds_row[i_thread];
thread_args_sweep[i_thread]->end_row = seg_bounds_row[i_thread+1];
thread_args_sweep[i_thread]->ncol = ncol;
thread_args_sweep[i_thread]->ny = seg_bounds_hi[i_thread+1]-seg_bounds_lo[i_thread];
thread_args_sweep[i_thread]->nx = nx;
thread_args_sweep[i_thread]->haloWidth = haloWidth*(i_thread ? 1 : 0);
thread_args_sweep[i_thread]->main_diagonal_offset = main_diagonal_offset;
thread_args_sweep[i_thread]->Rr = Rr;
thread_args_sweep[i_thread]->Ri = Ri;
thread_args_sweep[i_thread]->idx = idx;
if (n_threads > 1){
thread_args_sweep[i_thread]->yr = yr_seg[i_thread];
thread_args_sweep[i_thread]->yi = yi_seg[i_thread];
}
else{
thread_args_sweep[i_thread]->yr = yr;
thread_args_sweep[i_thread]->yi = yi;
}
thread_args_sweep[i_thread]->br = br;
thread_args_sweep[i_thread]->bi = bi;
thread_args_sweep[i_thread]->w = w;
thread_args_sweep[i_thread]->dir = dir;
if (n_threads > 1){
/* Set the arguments for the averaging threads. Note that each
* thread is responsible for averaging the low end of its address
* range. The middle of its address range is copied, while the high
* end of its address range is left for the next thread. */
thread_args_average[i_thread] = (struct average_data_t *)mxCalloc(1,sizeof(struct average_data_t));
thread_args_average[i_thread]->copy_src_real = &(yr_seg[i_thread][seg_bounds_hi[i_thread] - seg_bounds_lo[i_thread]]);
thread_args_average[i_thread]->copy_dst_real = &(yr[seg_bounds_hi[i_thread]]);
thread_args_average[i_thread]->copy_src_imag = &(yi_seg[i_thread][seg_bounds_hi[i_thread] - seg_bounds_lo[i_thread]]);
thread_args_average[i_thread]->copy_dst_imag = &(yi[seg_bounds_hi[i_thread]]);
thread_args_average[i_thread]->n_to_copy = (size_t) (seg_bounds_lo[i_thread+1] - seg_bounds_hi[i_thread]);
thread_args_average[i_thread]->halo_1_real = &(yr_seg[i_thread-1 >= 0 ? i_thread-1 : 0][seg_bounds_lo[i_thread] - seg_bounds_lo[i_thread-1 >= 0 ? i_thread-1 : 0]]);
thread_args_average[i_thread]->halo_2_real = yr_seg[i_thread];
thread_args_average[i_thread]->halo_dst_real = &(yr[seg_bounds_lo[i_thread]]);
thread_args_average[i_thread]->halo_1_imag = &(yi_seg[i_thread-1 >= 0 ? i_thread-1 : 0][seg_bounds_lo[i_thread] - seg_bounds_lo[i_thread-1 >= 0 ? i_thread-1 : 0]]);
thread_args_average[i_thread]->halo_2_imag = yi_seg[i_thread];
thread_args_average[i_thread]->halo_dst_imag = &(yi[seg_bounds_lo[i_thread]]);
thread_args_average[i_thread]->n_in_halo = (size_t) (seg_bounds_hi[i_thread] - seg_bounds_lo[i_thread]);
thread_data[i_thread] = (struct thread_data_t *)mxCalloc(1,sizeof(struct thread_data_t));
thread_data[i_thread]->copy_init_guess_data = *copy_init_guess_data[i_thread];
thread_data[i_thread]->sweep_data = *thread_args_sweep[i_thread];
thread_data[i_thread]->average_data = *thread_args_average[i_thread];
thread_data[i_thread]->barrier = &barrier_after_sweep_before_halo_average;
}
}
if (n_threads == 1) {
/* Set the initial guess directly in the output array too */
memcpy((void *)yr, (void *)xr, sizeof(double)*nx);
memcpy((void *)yi, (void *)xi, sizeof(double)*nx);
do_sweep((void *)thread_args_sweep[0]);
}
else{
/* Sweep and average, in separate worker threads */
for (i_thread=0; i_thread<n_threads; i_thread++){
if (pthread_create(&threadIDs[i_thread], &attr, sweep_and_average, (void *)thread_data[i_thread])){
mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:pthreadCreate",
"pthread_create returned non-zero.");
}
}
/* Wait for threads to finish */
for (i_thread=0; i_thread<n_threads; i_thread++){
if (pthread_join(threadIDs[i_thread], NULL)){
mexErrMsgIdAndTxt("SLIM_release_apps:tools:algorithms:ThreeDFreqModeling:sweepR_mex:pthreadCreate",
"pthread_join returned non-zero.");
}
}
}
/* Free memory if it was allocated within the MEX file. */
if (Ri_alloc){
mxFree(Ri);
}
if (xi_alloc){
mxFree(xi);
}
if (bi_alloc){
mxFree(bi);
}
mxFree(seg_bounds_hi);
mxFree(seg_bounds_mid);
mxFree(seg_bounds_row);
mxFree(seg_bounds_lo);
if (n_threads > 1) {
mxFree(threadIDs);
}
for (i_thread=0; i_thread<n_threads; i_thread++){
mxFree(thread_args_sweep[i_thread]);
if (n_threads > 1){
mxFree(thread_args_average[i_thread]);
mxFree(thread_data[i_thread]);
mxFree(copy_init_guess_data[i_thread]);
mxFree(yr_seg[i_thread]);
mxFree(yi_seg[i_thread]);
}
}
if (n_threads > 1){
pthread_barrier_destroy(&barrier_after_sweep_before_halo_average);
mxFree(thread_args_average);
mxFree(thread_data);
mxFree(copy_init_guess_data);
mxFree(yr_seg);
mxFree(yi_seg);
}
mxFree(idx);
mxFree(thread_args_sweep);
pthread_attr_destroy(&attr);
/* Don't think I need pthread_exit() here, because pthread_join is called above */
return;
}
| {
"alphanum_fraction": 0.7098536159,
"avg_line_length": 39.2538593482,
"ext": "c",
"hexsha": "e7bdd923d7afc90df0b346237f79d53af925c0ec",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-04-27T08:46:39.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-15T02:34:32.000Z",
"max_forks_repo_head_hexsha": "3fb78e7338b9f1702dfcc0a94748ce5e86562739",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "yuanyuxin0077/SLIM-release-apps-public",
"max_forks_repo_path": "tools/deprecated/solvers/Krylov/sweepR_mex.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3fb78e7338b9f1702dfcc0a94748ce5e86562739",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "yuanyuxin0077/SLIM-release-apps-public",
"max_issues_repo_path": "tools/deprecated/solvers/Krylov/sweepR_mex.c",
"max_line_length": 182,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "4db4043a38c5a4b7ccfee87be3e43992a38e8054",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "liaman/SLIM-release-apps-public",
"max_stars_repo_path": "tools/deprecated/solvers/Krylov/sweepR_mex.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-03T13:36:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-26T02:42:22.000Z",
"num_tokens": 6637,
"size": 22885
} |
#pragma once
#include "global.h"
#ifdef USE_MKL
#include <mkl.h>
inline void* _malloc(size_t size) {return mkl_malloc(size,64);}
inline void _free(void* ptr) {return mkl_free(ptr);}
#else
#include <cblas.h>
inline void* _malloc(size_t size) {return malloc(size);}
inline void _free(void* ptr) {return free(ptr);}
#endif
void init_glorot(size_t dim_x, size_t dim_y, vec_t &weight, unsigned seed);
// symmetric sparse matrix transpose
void symmetric_csr_transpose(int N, int nnz, int* A_idx_ptr, int* A_nnz_idx,
float* A_nonzeros, float* &B_nonzeros);
// get accuracy for single-class problems
float masked_accuracy_single(int begin, int end, int count, int num_classes,
mask_t* masks, float* preds, label_t* ground_truth);
// get accuracy for multi-class problems
float masked_accuracy_multi(int begin, int end, int count, int num_classes,
mask_t* masks, float* preds, label_t* ground_truth);
void matmul_naive(const size_t x, const size_t y, const size_t z,
const float* A, const float* B, float* C);
void matmul(const size_t x, const size_t y, const size_t z,
const float_t* A, const float_t* B, float* C,
bool transA = false, bool transB = false, bool accum = false);
void l2norm(int n, int dim, const float* in, float* out);
void d_l2norm(int n, int dim, const float* feat_in, const float* grad_in, float* grad_out);
void bias_mv(int n, int len, float* x, float* b);
void reduce_sum(int n, int len, float* x, float* a);
void reduce_sum(int n, int len, float* x, vec_t &a);
// single-precision dense matrix multiply
void sgemm_cpu(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB,
const int M, const int N, const int K, const float alpha,
const float* A, const float* B, const float beta, float* C);
void csr2csc(int nrows, int ncols, int nnz,
const float* values, const int* rowptr, const int* colidx,
float* valuesT, int* rowptrT, int* colidxT);
// single-precision sparse matrix dense matrix multiply, C = A * B, A is sparse
void csrmm_cpu(const int M, const int N, const int K, const int nnz,
const float alpha, float* A_nonzeros, int* A_idx_ptr,
int* A_nonzero_idx, const float* B, const float beta, float* C, bool transA = false);
void spmm(size_t x, size_t y, size_t z, size_t nnz,
float* A_nonzeros, int* A_idx_ptr, int* A_nnz_idx,
const float* B, float* C, float* temp = NULL,
bool transA = false, bool transB = false, bool accum = false);
// matrix-vector multiply
void mvmul(const CBLAS_TRANSPOSE TransA, const int M, const int N,
const float alpha, const float* A, const float* x, const float beta, float* y);
//! add 2 arrays for n elements
void vadd_cpu(int n, const float* a, const float* b, float* out);
void scaled_vadd_cpu(int n, const float a, const float* x, const float* y, float* z);
// atomic y[i] += x[i]
void atomic_vreduce_cpu(size_t n, const float* x, float* y);
//! multiply n elements of vector by scalar
void scal(size_t n, const float alpha, float* x);
void scale(int n, const float alpha, const float* x, float* y);
void mul_scalar(size_t n, const float alpha, const float* x, float* y);
//! do dot product of 2 vectors
float dot(int n, const float* x, const float* y);
// concatenation of two vectors into one
void concat(size_t n, const float* x, const float* y, float* z);
// SAXPY stands for Single-precision A*X Plus Y"
void axpy(size_t n, const float a, float* x, float* y);
// Returns the index of the maximum value
int argmax(int num, const float* arr);
//! clear n elements of a vector
void clear_cpu(int n, float* in);
//! copy vector from in -> out; first len elements
void copy_cpu(size_t len, const float* in, float* out);
// dropout functions randomly remove weights
void dropout_cpu(size_t n, size_t m, float scale, float dropout_rate,
const float* in, mask_t* mask, float* out);
// dropout derivative: use existing dropouts in masks instead of generating them;
void d_dropout_cpu(size_t n, size_t m, float scale, const float* in,
const mask_t* mask, float* out);
void leaky_relu(float epsilon, float in, float &out);
void d_leaky_relu(float epsilon, float in, float data, float &out);
void relu_cpu(size_t n, const float* in, float* out);
void d_relu_cpu(size_t n, const float* in, const float* data, float* out);
void leaky_relu_cpu(size_t n, float epsilon, const float* in, float* out);
void d_leaky_relu_cpu(size_t n, float epsilon, const float* in, const float* data, float* out);
void softmax(size_t n, const float* in, float* out);
void d_softmax(int n, const float* p, const float* dp, float* dy);
void sigmoid(size_t n, const float* in, float* out);
void d_sigmoid(size_t n, const float*, const float* p, float* dy, const float* dp);
float cross_entropy(size_t n, const float* y, const float* p);
void d_cross_entropy(size_t n, const float* y, const float* p, float* d);
float sigmoid_cross_entropy(size_t n, const label_t* y, const float* p);
// use sigmoid instead of softmax for multi-class datasets, e.g. ppi, yelp and amazon
//inline float sigmoid_func(float x) { return 0.5 * tanh(0.5 * x) + 0.5; }
inline float sigmoid_func(float x) { return 1. / (1. + expf(-x)); }
// GPU operators
bool isnan_gpu(int n, const float_t* array); // does array contain any 'nan' element
void init_const_gpu(int n, float_t value, float_t* array);
void copy_gpu(int len, const float_t* in, float_t* out);
void vadd_gpu(const int n, const float_t* a, const float_t* b, float_t* out); // vector add
void axpy_gpu(const int n, const float_t a, const float_t* x, float_t* y); // axpy
void relu_gpu(const int n, const float_t* in, float_t* out); // ReLU
void d_relu_gpu(const int n, const float_t* in_diff, const float_t* data, float_t* out_diff); // ReLU derivative
void leaky_relu_gpu(const int n, const float_t epsilon, const float_t* in, float_t* out); // Leaky ReLU
void d_leaky_relu_gpu(const int n, const float_t epsilon,
const float_t* in_diff, const float_t* data,
float_t* out_diff); // Leaky ReLU derivative
void dropout_gpu(int n, float scale, float drop_rate, const float* in, mask_t* masks, float* out); // dropout
void d_dropout_gpu(int n, float scale, const float* in, const mask_t* masks, float* out); // dropout derivative
void sgemm_gpu(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB,
const int M, const int N, const int K, const float alpha,
const float* A, const float* B, const float beta, float* C);
void csrmm_gpu(const int M, const int N, const int K, const int nnz,
const float alpha, const float* A_nonzeros, const int* A_idx_ptr,
const int* A_nonzero_idx, const float* B, const float beta,
float* trans_C, float* C);
void softmax_cross_entropy_gpu(int len, int begin, int end,
const float_t* in_data, const mask_t* masks,
const label_t* labels, float_t* loss,
float_t* out_data);
void d_softmax_cross_entropy_gpu(int len, int bengin, int end,
const mask_t* masks, const label_t* labels,
const float_t* out_data, float_t* diff);
void sigmoid_cross_entropy_gpu(int len, int begin, int end,
const float_t* in_data, const mask_t* masks,
const label_t* labels, float_t* loss,
float_t* out_data);
void d_sigmoid_cross_entropy_gpu(int len, int bengin, int end,
const mask_t* masks, const label_t* labels,
const float_t* out_data, float_t* diff);
void scal_gpu(const int n, const float alpha, float* X);
void add_scalar_gpu(const int n, const float_t alpha, float_t* Y);
void rng_uniform_gpu(size_t n, const float_t a, const float_t b, float_t* r);
void l2_norm_gpu(size_t x, size_t y, const float_t* in, float_t* out);
void d_l2_norm_gpu(size_t x, size_t y, const float_t* in_data, float_t* in_diff, float_t* out_diff);
acc_t l2_norm_gpu(int n, const float_t* in);
acc_t masked_avg_loss_gpu(int begin, int end, int count, mask_t* masks, float_t* loss);
bool is_allocated_device(float_t* data);
void copy_masks_device(int n, mask_t* h_masks, mask_t*& d_masks);
void float_malloc_device(int n, float_t*& ptr);
void float_free_device(float_t*& ptr);
void copy_float_device(int n, float* h_ptr, float* d_ptr);
void copy_float_host(int n, const float* d_ptr, float* h_ptr);
void uint_malloc_device(int n, uint32_t*& ptr);
void uint_free_device(uint32_t*& ptr);
void copy_uint_device(int n, uint32_t* h_ptr, uint32_t* d_ptr);
void uint8_malloc_device(int n, uint8_t*& ptr);
void uint8_free_device(uint8_t*& ptr);
void copy_uint8_device(int n, uint8_t* h_ptr, uint8_t* d_ptr);
void gpu_rng_uniform(size_t n, float* r);
| {
"alphanum_fraction": 0.6842918644,
"avg_line_length": 51.7657142857,
"ext": "h",
"hexsha": "f7d3a3fdf1338c602861db8a0775417e4a8ab961",
"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": "ba799487946eed92d9e616b079b6dc17650dcc67",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "chenxuhao/GraphAIBench",
"max_forks_repo_path": "include/math_functions.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ba799487946eed92d9e616b079b6dc17650dcc67",
"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": "chenxuhao/GraphAIBench",
"max_issues_repo_path": "include/math_functions.h",
"max_line_length": 112,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ba799487946eed92d9e616b079b6dc17650dcc67",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "chenxuhao/GraphAIBench",
"max_stars_repo_path": "include/math_functions.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-05T09:38:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-01-19T14:44:50.000Z",
"num_tokens": 2418,
"size": 9059
} |
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#pragma once
#include <cblas.h>
#include "modules/perception/camera/common/camera_frame.h"
namespace apollo {
namespace perception {
namespace camera {
class BaseSimilar {
public:
virtual bool Calc(CameraFrame *frame1,
CameraFrame *frame2,
base::Blob<float> *sim) = 0;
};
class CosineSimilar : public BaseSimilar {
public:
CosineSimilar() = default;
bool Calc(CameraFrame *frame1,
CameraFrame *frame2,
base::Blob<float> *sim) override;
};
class GPUSimilar : public BaseSimilar {
public:
bool Calc(CameraFrame *frame1,
CameraFrame *frame2,
base::Blob<float> *sim) override;
};
} // namespace camera
} // namespace perception
} // namespace apollo
| {
"alphanum_fraction": 0.6298013245,
"avg_line_length": 29.6078431373,
"ext": "h",
"hexsha": "c57916c5ece081b7cfe3a12dc4e20aaf8004aef2",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-02-24T06:20:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-24T06:20:29.000Z",
"max_forks_repo_head_hexsha": "808f1d20a08efea23b718b4e423d6619c9d4b412",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "thomasgui76/apollo",
"max_forks_repo_path": "modules/perception/camera/lib/obstacle/tracker/common/similar.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "808f1d20a08efea23b718b4e423d6619c9d4b412",
"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": "thomasgui76/apollo",
"max_issues_repo_path": "modules/perception/camera/lib/obstacle/tracker/common/similar.h",
"max_line_length": 79,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "002eba4a1635d6af7f1ebd2118464bca6f86b106",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ghdawn/apollo",
"max_stars_repo_path": "modules/perception/camera/lib/obstacle/tracker/common/similar.h",
"max_stars_repo_stars_event_max_datetime": "2019-01-15T08:35:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-01-15T08:34:59.000Z",
"num_tokens": 306,
"size": 1510
} |
/* vector/gsl_vector_uint.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_UINT_H__
#define __GSL_VECTOR_UINT_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_block_uint.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;
unsigned int *data;
gsl_block_uint *block;
int owner;
}
gsl_vector_uint;
typedef struct
{
gsl_vector_uint vector;
} _gsl_vector_uint_view;
typedef _gsl_vector_uint_view gsl_vector_uint_view;
typedef struct
{
gsl_vector_uint vector;
} _gsl_vector_uint_const_view;
typedef const _gsl_vector_uint_const_view gsl_vector_uint_const_view;
/* Allocation */
GSL_EXPORT gsl_vector_uint *gsl_vector_uint_alloc (const size_t n);
GSL_EXPORT gsl_vector_uint *gsl_vector_uint_calloc (const size_t n);
GSL_EXPORT gsl_vector_uint *gsl_vector_uint_alloc_from_block (gsl_block_uint * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_EXPORT gsl_vector_uint *gsl_vector_uint_alloc_from_vector (gsl_vector_uint * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_EXPORT void gsl_vector_uint_free (gsl_vector_uint * v);
/* Views */
GSL_EXPORT
_gsl_vector_uint_view
gsl_vector_uint_view_array (unsigned int *v, size_t n);
GSL_EXPORT
_gsl_vector_uint_view
gsl_vector_uint_view_array_with_stride (unsigned int *base,
size_t stride,
size_t n);
GSL_EXPORT
_gsl_vector_uint_const_view
gsl_vector_uint_const_view_array (const unsigned int *v, size_t n);
GSL_EXPORT
_gsl_vector_uint_const_view
gsl_vector_uint_const_view_array_with_stride (const unsigned int *base,
size_t stride,
size_t n);
GSL_EXPORT
_gsl_vector_uint_view
gsl_vector_uint_subvector (gsl_vector_uint *v,
size_t i,
size_t n);
GSL_EXPORT
_gsl_vector_uint_view
gsl_vector_uint_subvector_with_stride (gsl_vector_uint *v,
size_t i,
size_t stride,
size_t n);
GSL_EXPORT
_gsl_vector_uint_const_view
gsl_vector_uint_const_subvector (const gsl_vector_uint *v,
size_t i,
size_t n);
GSL_EXPORT
_gsl_vector_uint_const_view
gsl_vector_uint_const_subvector_with_stride (const gsl_vector_uint *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
GSL_EXPORT unsigned int gsl_vector_uint_get (const gsl_vector_uint * v, const size_t i);
GSL_EXPORT void gsl_vector_uint_set (gsl_vector_uint * v, const size_t i, unsigned int x);
GSL_EXPORT unsigned int *gsl_vector_uint_ptr (gsl_vector_uint * v, const size_t i);
GSL_EXPORT const unsigned int *gsl_vector_uint_const_ptr (const gsl_vector_uint * v, const size_t i);
GSL_EXPORT void gsl_vector_uint_set_zero (gsl_vector_uint * v);
GSL_EXPORT void gsl_vector_uint_set_all (gsl_vector_uint * v, unsigned int x);
GSL_EXPORT int gsl_vector_uint_set_basis (gsl_vector_uint * v, size_t i);
GSL_EXPORT int gsl_vector_uint_fread (FILE * stream, gsl_vector_uint * v);
GSL_EXPORT int gsl_vector_uint_fwrite (FILE * stream, const gsl_vector_uint * v);
GSL_EXPORT int gsl_vector_uint_fscanf (FILE * stream, gsl_vector_uint * v);
GSL_EXPORT int gsl_vector_uint_fprintf (FILE * stream, const gsl_vector_uint * v,
const char *format);
GSL_EXPORT int gsl_vector_uint_memcpy (gsl_vector_uint * dest, const gsl_vector_uint * src);
GSL_EXPORT int gsl_vector_uint_reverse (gsl_vector_uint * v);
GSL_EXPORT int gsl_vector_uint_swap (gsl_vector_uint * v, gsl_vector_uint * w);
GSL_EXPORT int gsl_vector_uint_swap_elements (gsl_vector_uint * v, const size_t i, const size_t j);
GSL_EXPORT unsigned int gsl_vector_uint_max (const gsl_vector_uint * v);
GSL_EXPORT unsigned int gsl_vector_uint_min (const gsl_vector_uint * v);
GSL_EXPORT void gsl_vector_uint_minmax (const gsl_vector_uint * v, unsigned int * min_out, unsigned int * max_out);
GSL_EXPORT size_t gsl_vector_uint_max_index (const gsl_vector_uint * v);
GSL_EXPORT size_t gsl_vector_uint_min_index (const gsl_vector_uint * v);
GSL_EXPORT void gsl_vector_uint_minmax_index (const gsl_vector_uint * v, size_t * imin, size_t * imax);
GSL_EXPORT int gsl_vector_uint_add (gsl_vector_uint * a, const gsl_vector_uint * b);
GSL_EXPORT int gsl_vector_uint_sub (gsl_vector_uint * a, const gsl_vector_uint * b);
GSL_EXPORT int gsl_vector_uint_mul (gsl_vector_uint * a, const gsl_vector_uint * b);
GSL_EXPORT int gsl_vector_uint_div (gsl_vector_uint * a, const gsl_vector_uint * b);
GSL_EXPORT int gsl_vector_uint_scale (gsl_vector_uint * a, const double x);
GSL_EXPORT int gsl_vector_uint_add_constant (gsl_vector_uint * a, const double x);
GSL_EXPORT int gsl_vector_uint_isnull (const gsl_vector_uint * v);
#ifdef HAVE_INLINE
extern inline
unsigned int
gsl_vector_uint_get (const gsl_vector_uint * 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_uint_set (gsl_vector_uint * v, const size_t i, unsigned int 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
unsigned int *
gsl_vector_uint_ptr (gsl_vector_uint * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (unsigned int *) (v->data + i * v->stride);
}
extern inline
const unsigned int *
gsl_vector_uint_const_ptr (const gsl_vector_uint * 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 unsigned int *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_UINT_H__ */
| {
"alphanum_fraction": 0.6792949224,
"avg_line_length": 32.3489361702,
"ext": "h",
"hexsha": "cd4e7d3d3927b21388972379df85786c6742e806",
"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_uint.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_uint.h",
"max_line_length": 115,
"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_uint.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1787,
"size": 7602
} |
#include "asf.h"
#include "ceos.h"
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_roots.h>
struct pp_erfin_params {
int npixels,nlines;
double satellite_height; /* earth center to satellite height (PP "rsc") */
double slant_first; /* slant range to first pixel */
double slant_last; /* slant range to last pixel */
double nominal_pixsize_range;
};
static double getObjective(double R, void *params)
{
struct pp_erfin_params *p =
(struct pp_erfin_params *)params;
double H=p->satellite_height;
double sf=p->slant_first;
double HHRR=H*H + R*R;
/* Convert slant_first to ground range */
double g=R*acos( (HHRR - sf*sf) / (2*H*R));
/* Add width of CEOS image in ground range */
g += (p->npixels-1) * p->nominal_pixsize_range;
/* Compute slant range to last pixel */
double slant_last_R=sqrt(HHRR - 2*H*R*cos(g/R));
/* Compare with slant_last from CEOS */
return slant_last_R-p->slant_last;
}
void pp_get_corrected_vals(char *sarName, double *corrected_earth_radius,
double *corrected_azimuth_time_per_pixel)
{
int status;
int iter = 0, max_iter = 100;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
gsl_function F;
gsl_error_handler_t *prev;
struct pp_erfin_params params;
double nominal_pixsize_azimuth;
double nadir_radius; /* earth radius at nadir */
double pp_earth_radius; /* f'd up PP Earth radius from start of swath */
double seconds_per_azimuth_line; /* PP's real azimuth resolution */
double lo, hi; /* starting points for the bisection algorithm */
struct VFDRECV facdr;
get_asf_facdr(sarName, &facdr);
/* Find the PP's earth radius with an iterative search */
F.function = &getObjective;
F.params = ¶ms;
params.npixels=facdr.npixels;
params.nlines=facdr.nlines;
params.nominal_pixsize_range=facdr.rapixspc;
nominal_pixsize_azimuth=facdr.azpixspc;
nadir_radius=1.0e3*facdr.eradnadr;
params.satellite_height=1.0e3*(facdr.scalt+facdr.eradnadr);
params.slant_first=1.0e3*facdr.sltrngfp;
params.slant_last=1.0e3*facdr.sltrnglp;
prev = gsl_set_error_handler_off();
lo = nadir_radius - 2000;
hi = nadir_radius + 2000;
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc (T);
gsl_root_fsolver_set (s, &F, lo, hi);
do {
++iter;
status = gsl_root_fsolver_iterate(s);
pp_earth_radius = gsl_root_fsolver_root(s);
status = gsl_root_test_residual(
getObjective(pp_earth_radius, (void*)¶ms), 1.0e-4);
} while (status == GSL_CONTINUE && iter < max_iter);
if (status == GSL_SUCCESS) {
//printf("Converged after %d iterations.\n", iter);
//printf("PP Earth Radius: %.3f m\n",pp_earth_radius);
//printf(" (for comparison) Nadir Earth Radius: %.3f m\n",nadir_radius);
*corrected_earth_radius = pp_earth_radius;
} else {
asfPrintWarning("Failed to determine PP earth radius!\n"
"iter: %d, pp_earth_radius=%.3f, res=%.5f\n"
"Proceeding using the nadir radius: %.3f m\n"
"Starting points were: lo: %.3f -> %.4f\n"
" hi: %.3f -> %.4f\n",
iter, pp_earth_radius,
getObjective(pp_earth_radius, (void*)¶ms),
nadir_radius,
lo, getObjective(lo, (void*)¶ms),
hi, getObjective(hi, (void*)¶ms));
*corrected_earth_radius = nadir_radius;
}
gsl_set_error_handler(prev);
// Find the PP's per-second azimuth pixel spacing
seconds_per_azimuth_line=nominal_pixsize_azimuth/facdr.swathvel;
//printf("PP seconds per azimuth line: %.9f s/line\n",seconds_per_azimuth_line);
//printf(" (for comparison) PP interpolated lines per second: %.3f lines/s\n",1.0/seconds_per_azimuth_line);
//printf(" (for comparison) FACDR swath velocity: %.3f m/s\n",facdr.swathvel);
//double R=pp_earth_radius;
//double H=params.satellite_height;
//double HHRR=H*H + R*R;
//double slant=0.5*(params.slant_first+params.slant_last);
//double rg_center=R*acos( (HHRR - slant*slant) / (2*H*R));
//double vs=sqrt(facdr.scxvel*facdr.scxvel + facdr.scyvel*facdr.scyvel + facdr.sczvel*facdr.sczvel);
//double vsg = vs * pp_earth_radius/params.satellite_height*cos(rg_center/pp_earth_radius);
//printf(" (for comparison) PP-style recalc velocity: %.3f m/s\n",vsg);
*corrected_azimuth_time_per_pixel = seconds_per_azimuth_line;
// Free the solver
gsl_root_fsolver_free(s);
}
| {
"alphanum_fraction": 0.6473806017,
"avg_line_length": 37.4251968504,
"ext": "c",
"hexsha": "110ea7f2b49f2b5e6885a350d866f215fd39665d",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z",
"max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "glshort/MapReady",
"max_forks_repo_path": "src/asf_meta/pp_corrected_vals.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "glshort/MapReady",
"max_issues_repo_path": "src/asf_meta/pp_corrected_vals.c",
"max_line_length": 114,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "glshort/MapReady",
"max_stars_repo_path": "src/asf_meta/pp_corrected_vals.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": 1333,
"size": 4753
} |
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_cblas.h>
#include "tests.h"
void
test_dot (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int N = 1;
float alpha = 0.0f;
float X[] = { 0.733f };
float Y[] = { 0.825f };
int incX = 1;
int incY = -1;
float expected = 0.604725f;
float f;
f = cblas_sdsdot (N, alpha, X, incX, Y, incY);
gsl_test_rel(f, expected, flteps, "sdsdot(case 1)");
};
{
int N = 1;
float alpha = 0.1f;
float X[] = { 0.733f };
float Y[] = { 0.825f };
int incX = 1;
int incY = -1;
float expected = 0.704725f;
float f;
f = cblas_sdsdot (N, alpha, X, incX, Y, incY);
gsl_test_rel(f, expected, flteps, "sdsdot(case 2)");
};
{
int N = 1;
float alpha = 1.0f;
float X[] = { 0.733f };
float Y[] = { 0.825f };
int incX = 1;
int incY = -1;
float expected = 1.604725f;
float f;
f = cblas_sdsdot (N, alpha, X, incX, Y, incY);
gsl_test_rel(f, expected, flteps, "sdsdot(case 3)");
};
{
int N = 1;
float alpha = 0.0f;
float X[] = { -0.812f };
float Y[] = { -0.667f };
int incX = -1;
int incY = 1;
float expected = 0.541604f;
float f;
f = cblas_sdsdot (N, alpha, X, incX, Y, incY);
gsl_test_rel(f, expected, flteps, "sdsdot(case 4)");
};
{
int N = 1;
float alpha = 0.1f;
float X[] = { -0.812f };
float Y[] = { -0.667f };
int incX = -1;
int incY = 1;
float expected = 0.641604f;
float f;
f = cblas_sdsdot (N, alpha, X, incX, Y, incY);
gsl_test_rel(f, expected, flteps, "sdsdot(case 5)");
};
{
int N = 1;
float alpha = 1.0f;
float X[] = { -0.812f };
float Y[] = { -0.667f };
int incX = -1;
int incY = 1;
float expected = 1.541604f;
float f;
f = cblas_sdsdot (N, alpha, X, incX, Y, incY);
gsl_test_rel(f, expected, flteps, "sdsdot(case 6)");
};
{
int N = 1;
float alpha = 0.0f;
float X[] = { 0.481f };
float Y[] = { 0.523f };
int incX = -1;
int incY = -1;
float expected = 0.251563f;
float f;
f = cblas_sdsdot (N, alpha, X, incX, Y, incY);
gsl_test_rel(f, expected, flteps, "sdsdot(case 7)");
};
{
int N = 1;
float alpha = 0.1f;
float X[] = { 0.481f };
float Y[] = { 0.523f };
int incX = -1;
int incY = -1;
float expected = 0.351563f;
float f;
f = cblas_sdsdot (N, alpha, X, incX, Y, incY);
gsl_test_rel(f, expected, flteps, "sdsdot(case 8)");
};
{
int N = 1;
float alpha = 1.0f;
float X[] = { 0.481f };
float Y[] = { 0.523f };
int incX = -1;
int incY = -1;
float expected = 1.251563f;
float f;
f = cblas_sdsdot (N, alpha, X, incX, Y, incY);
gsl_test_rel(f, expected, flteps, "sdsdot(case 9)");
};
{
int N = 1;
float X[] = { 0.785f };
float Y[] = { -0.7f };
int incX = 1;
int incY = -1;
float expected = -0.5495f;
float f;
f = cblas_sdot(N, X, incX, Y, incY);
gsl_test_rel(f, expected, flteps, "sdot(case 10)");
};
{
int N = 1;
double X[] = { 0.79 };
double Y[] = { -0.679 };
int incX = 1;
int incY = -1;
double expected = -0.53641;
double f;
f = cblas_ddot(N, X, incX, Y, incY);
gsl_test_rel(f, expected, dbleps, "ddot(case 11)");
};
{
int N = 1;
float X[] = { 0.474f, -0.27f };
float Y[] = { -0.144f, -0.392f };
int incX = 1;
int incY = -1;
float expected[2] = {-0.174096f, -0.146928f};
float f[2];
cblas_cdotu_sub(N, X, incX, Y, incY, &f);
gsl_test_rel(f[0], expected[0], flteps, "cdotu(case 12) real");
gsl_test_rel(f[1], expected[1], flteps, "cdotu(case 12) imag");
};
{
int N = 1;
float X[] = { 0.474f, -0.27f };
float Y[] = { -0.144f, -0.392f };
int incX = 1;
int incY = -1;
float expected[2] = {0.037584f, -0.224688f};
float f[2];
cblas_cdotc_sub(N, X, incX, Y, incY, &f);
gsl_test_rel(f[0], expected[0], flteps, "cdotc(case 13) real");
gsl_test_rel(f[1], expected[1], flteps, "cdotc(case 13) imag");
};
{
int N = 1;
double X[] = { -0.87, -0.631 };
double Y[] = { -0.7, -0.224 };
int incX = 1;
int incY = -1;
double expected[2] = {0.467656, 0.63658};
double f[2];
cblas_zdotu_sub(N, X, incX, Y, incY, &f);
gsl_test_rel(f[0], expected[0], dbleps, "zdotu(case 14) real");
gsl_test_rel(f[1], expected[1], dbleps, "zdotu(case 14) imag");
};
{
int N = 1;
double X[] = { -0.87, -0.631 };
double Y[] = { -0.7, -0.224 };
int incX = 1;
int incY = -1;
double expected[2] = {0.750344, -0.24682};
double f[2];
cblas_zdotc_sub(N, X, incX, Y, incY, &f);
gsl_test_rel(f[0], expected[0], dbleps, "zdotc(case 15) real");
gsl_test_rel(f[1], expected[1], dbleps, "zdotc(case 15) imag");
};
{
int N = 1;
float X[] = { -0.457f };
float Y[] = { 0.839f };
int incX = -1;
int incY = 1;
float expected = -0.383423f;
float f;
f = cblas_sdot(N, X, incX, Y, incY);
gsl_test_rel(f, expected, flteps, "sdot(case 16)");
};
{
int N = 1;
double X[] = { 0.949 };
double Y[] = { -0.873 };
int incX = -1;
int incY = 1;
double expected = -0.828477;
double f;
f = cblas_ddot(N, X, incX, Y, incY);
gsl_test_rel(f, expected, dbleps, "ddot(case 17)");
};
{
int N = 1;
float X[] = { 0.852f, -0.045f };
float Y[] = { 0.626f, -0.164f };
int incX = -1;
int incY = 1;
float expected[2] = {0.525972f, -0.167898f};
float f[2];
cblas_cdotu_sub(N, X, incX, Y, incY, &f);
gsl_test_rel(f[0], expected[0], flteps, "cdotu(case 18) real");
gsl_test_rel(f[1], expected[1], flteps, "cdotu(case 18) imag");
};
{
int N = 1;
float X[] = { 0.852f, -0.045f };
float Y[] = { 0.626f, -0.164f };
int incX = -1;
int incY = 1;
float expected[2] = {0.540732f, -0.111558f};
float f[2];
cblas_cdotc_sub(N, X, incX, Y, incY, &f);
gsl_test_rel(f[0], expected[0], flteps, "cdotc(case 19) real");
gsl_test_rel(f[1], expected[1], flteps, "cdotc(case 19) imag");
};
{
int N = 1;
double X[] = { -0.786, -0.341 };
double Y[] = { -0.271, -0.896 };
int incX = -1;
int incY = 1;
double expected[2] = {-0.09253, 0.796667};
double f[2];
cblas_zdotu_sub(N, X, incX, Y, incY, &f);
gsl_test_rel(f[0], expected[0], dbleps, "zdotu(case 20) real");
gsl_test_rel(f[1], expected[1], dbleps, "zdotu(case 20) imag");
};
{
int N = 1;
double X[] = { -0.786, -0.341 };
double Y[] = { -0.271, -0.896 };
int incX = -1;
int incY = 1;
double expected[2] = {0.518542, 0.611845};
double f[2];
cblas_zdotc_sub(N, X, incX, Y, incY, &f);
gsl_test_rel(f[0], expected[0], dbleps, "zdotc(case 21) real");
gsl_test_rel(f[1], expected[1], dbleps, "zdotc(case 21) imag");
};
{
int N = 1;
float X[] = { -0.088f };
float Y[] = { -0.165f };
int incX = -1;
int incY = -1;
float expected = 0.01452f;
float f;
f = cblas_sdot(N, X, incX, Y, incY);
gsl_test_rel(f, expected, flteps, "sdot(case 22)");
};
{
int N = 1;
double X[] = { -0.434 };
double Y[] = { -0.402 };
int incX = -1;
int incY = -1;
double expected = 0.174468;
double f;
f = cblas_ddot(N, X, incX, Y, incY);
gsl_test_rel(f, expected, dbleps, "ddot(case 23)");
};
{
int N = 1;
float X[] = { -0.347f, 0.899f };
float Y[] = { -0.113f, -0.858f };
int incX = -1;
int incY = -1;
float expected[2] = {0.810553f, 0.196139f};
float f[2];
cblas_cdotu_sub(N, X, incX, Y, incY, &f);
gsl_test_rel(f[0], expected[0], flteps, "cdotu(case 24) real");
gsl_test_rel(f[1], expected[1], flteps, "cdotu(case 24) imag");
};
{
int N = 1;
float X[] = { -0.347f, 0.899f };
float Y[] = { -0.113f, -0.858f };
int incX = -1;
int incY = -1;
float expected[2] = {-0.732131f, 0.399313f};
float f[2];
cblas_cdotc_sub(N, X, incX, Y, incY, &f);
gsl_test_rel(f[0], expected[0], flteps, "cdotc(case 25) real");
gsl_test_rel(f[1], expected[1], flteps, "cdotc(case 25) imag");
};
{
int N = 1;
double X[] = { -0.897, -0.204 };
double Y[] = { -0.759, 0.557 };
int incX = -1;
int incY = -1;
double expected[2] = {0.794451, -0.344793};
double f[2];
cblas_zdotu_sub(N, X, incX, Y, incY, &f);
gsl_test_rel(f[0], expected[0], dbleps, "zdotu(case 26) real");
gsl_test_rel(f[1], expected[1], dbleps, "zdotu(case 26) imag");
};
{
int N = 1;
double X[] = { -0.897, -0.204 };
double Y[] = { -0.759, 0.557 };
int incX = -1;
int incY = -1;
double expected[2] = {0.567195, -0.654465};
double f[2];
cblas_zdotc_sub(N, X, incX, Y, incY, &f);
gsl_test_rel(f[0], expected[0], dbleps, "zdotc(case 27) real");
gsl_test_rel(f[1], expected[1], dbleps, "zdotc(case 27) imag");
};
}
| {
"alphanum_fraction": 0.5347143182,
"avg_line_length": 22.8802083333,
"ext": "c",
"hexsha": "8000fe723d9e7e3c0b13d57983701b21c8d36cb2",
"lang": "C",
"max_forks_count": 224,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z",
"max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "utdsimmons/ohpc",
"max_forks_repo_path": "tests/libs/gsl/tests/cblas/test_dot.c",
"max_issues_count": 1096,
"max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "utdsimmons/ohpc",
"max_issues_repo_path": "tests/libs/gsl/tests/cblas/test_dot.c",
"max_line_length": 66,
"max_stars_count": 692,
"max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "utdsimmons/ohpc",
"max_stars_repo_path": "tests/libs/gsl/tests/cblas/test_dot.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z",
"num_tokens": 3681,
"size": 8786
} |
#ifndef BIO_MATH_H_
#define BIO_MATH_H_
#include "bio/defs.h"
#include "bio/gsl.h"
#include <boost/io/ios_state.hpp>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_log.h>
#include <gsl/gsl_sf_exp.h>
#include <numeric>
BIO_NS_START
/** Calculates the log of n choose the observed counts. */
template < typename ObsIt >
double
calc_ln_n_choose(
ObsIt obs_begin,
ObsIt obs_end)
{
double result = 0.0;
unsigned n = 0;
while (obs_end != obs_begin)
{
result -= gsl_sf_lnfact(*obs_begin);
n += *obs_begin;
++obs_begin;
}
result += gsl_sf_lnfact(n);
return result;
}
/** Calculates a factor involved in the likelihood of a multinomial distribution with a dirichlet prior. */
template < typename ObsIt, typename AlphaIt >
double
calc_ln_gamma_factor(
ObsIt obs_begin,
ObsIt obs_end,
AlphaIt alpha_begin)
{
double ln_pi_gamma_alpha_obs = 0.0; //work in logarithms
double ln_pi_gamma_alpha = 0.0; //work in logarithms
double sum_alpha = 0.0;
double sum_obs = 0.0;
while (obs_end != obs_begin)
{
sum_alpha += *alpha_begin;
sum_obs += *obs_begin;
ln_pi_gamma_alpha += gsl_sf_lngamma(*alpha_begin);
ln_pi_gamma_alpha_obs += gsl_sf_lngamma(*alpha_begin + *obs_begin);
++obs_begin;
++alpha_begin;
}
double ln_result =
gsl_sf_lngamma(sum_alpha)
- ln_pi_gamma_alpha
+ ln_pi_gamma_alpha_obs
- gsl_sf_lngamma(sum_alpha + sum_obs);
return ln_result;
}
/** Calculates the log of the likelihood of seeing the observed counts under a dirichlet prior. */
template < typename ObsIt, typename AlphaIt >
double
calc_multinomial_ln_likelihood_dirichlet_prior(
ObsIt obs_begin,
ObsIt obs_end,
AlphaIt alpha_begin)
{
return calc_ln_gamma_factor(obs_begin, obs_end, alpha_begin) + calc_ln_n_choose(obs_begin, obs_end);
}
/** Calculates the log of the likelihood of seeing the observed counts under a uniform multinomial distribution. */
template < typename ObsIt >
double
calc_multinomial_ln_likelihood_uniform_dist(
ObsIt obs_begin,
ObsIt obs_end)
{
const unsigned n = std::accumulate(obs_begin, obs_end, unsigned(0));
if (0 == n)
{
return 0.0;
}
const double ln_n_choose = calc_ln_n_choose(obs_begin, obs_end);
return ln_n_choose - n * gsl_sf_log(double(obs_end - obs_begin));
}
/** Calculates the log of the likelihood of seeing the observed counts under a multinomial distribution with given p's. */
template < typename ObsIt, typename PIt >
double
calc_multinomial_ln_likelihood(
ObsIt obs_begin,
ObsIt obs_end,
PIt p_begin)
{
const unsigned n = std::accumulate(obs_begin, obs_end, unsigned(0));
if (0 == n)
{
return 0.0;
}
double result = calc_ln_n_choose(obs_begin, obs_end);
while (obs_end != obs_begin)
{
result += *obs_begin * gsl_sf_log(*p_begin);
++obs_begin;
++p_begin;
}
return result;
}
/** Calculates the ratio of evidence in favour of a uniform distribution over one with a dirichlet prior
defined by the alphas. */
template < typename ObsIt, typename AlphaIt >
double
calc_ln_multinomial_uniform_evidence(
ObsIt obs_begin,
ObsIt obs_end,
AlphaIt alpha_begin)
{
const double ln_likelihood_uniform_dist = calc_multinomial_ln_likelihood_uniform_dist(obs_begin, obs_end);
const double ln_likelihood_dirichlet_prior = calc_multinomial_ln_likelihood_dirichlet_prior(obs_begin, obs_end, alpha_begin);
return ln_likelihood_uniform_dist - ln_likelihood_dirichlet_prior;
}
/** Calculates the ratio of evidence in favour of a particular multinomial distribution (defined by the p's)
over one with a dirichlet prior defined by the alpha's. */
template < typename ObsIt, typename AlphaIt, typename PIt >
double
calc_ln_multinomial_evidence(
ObsIt obs_begin,
ObsIt obs_end,
AlphaIt alpha_begin,
PIt p_begin)
{
return
calc_multinomial_ln_likelihood(obs_begin, obs_end, p_begin)
- calc_multinomial_ln_likelihood_dirichlet_prior(obs_begin, obs_end, alpha_begin);
}
BIO_NS_END
#endif //BIO_MATH_H_
| {
"alphanum_fraction": 0.7621732445,
"avg_line_length": 23.2261904762,
"ext": "h",
"hexsha": "6d90c7f62044139e91d5ca7ba6e23b0f016e2afb",
"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": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JohnReid/biopsy",
"max_forks_repo_path": "C++/include/bio/math.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"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": "JohnReid/biopsy",
"max_issues_repo_path": "C++/include/bio/math.h",
"max_line_length": 126,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JohnReid/biopsy",
"max_stars_repo_path": "C++/include/bio/math.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1035,
"size": 3902
} |
#ifndef NETWORK_UDP_ASYNCRECEIVER_H
#define NETWORK_UDP_ASYNCRECEIVER_H
/* Base class for implementing an asynchronous UDP receiver. A derived class must implement
handle_receive which gets passed a view of the received data. The function start() will
block and should be called in its own thread. */
#include <cstdint>
#include <array>
#include <string>
#include <gsl/gsl>
#include <asio.hpp>
namespace network::udp {
class Async_receiver
{
public:
Async_receiver() : socket_{io_service_} {}
virtual ~Async_receiver();
Async_receiver(const Async_receiver&) = delete;
Async_receiver& operator=(const Async_receiver&) = delete;
void start(const std::string& ip, std::uint16_t port);
void stop();
bool is_running() const { return socket_.is_open(); }
protected:
virtual void handle_receive(gsl::span<std::uint8_t> buffer) = 0;
private:
void start_async_receive();
asio::io_service io_service_;
asio::ip::udp::socket socket_;
std::array<std::uint8_t, 128> buffer_;
};
} // namespace network::udp
#endif // NETWORK_UDP_ASYNCRECEIVER_H
| {
"alphanum_fraction": 0.7388888889,
"avg_line_length": 22.0408163265,
"ext": "h",
"hexsha": "e28adb21c1274b214e4715e5e3882e1d170537bf",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-08-30T07:57:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-11-23T11:05:16.000Z",
"max_forks_repo_head_hexsha": "7c47ea7fa7f43163f69c94f10dd39b56e4e95256",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jwkpeter/tincan",
"max_forks_repo_path": "src/network/udpasyncreceiver.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7c47ea7fa7f43163f69c94f10dd39b56e4e95256",
"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": "jwkpeter/tincan",
"max_issues_repo_path": "src/network/udpasyncreceiver.h",
"max_line_length": 91,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "7c47ea7fa7f43163f69c94f10dd39b56e4e95256",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mwkpe/tincan",
"max_stars_repo_path": "src/network/udpasyncreceiver.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-18T08:03:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-09T10:22:26.000Z",
"num_tokens": 269,
"size": 1080
} |
/* ode-initval/rk4.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Runge-Kutta 4th order, Classical */
/* Author: G. Jungman
*/
/* Reference: Abramowitz & Stegun, section 25.5. equation 25.5.10
Error estimation by step doubling, see eg. Ascher, U.M., Petzold,
L.R., Computer methods for ordinary differential and
differential-algebraic equations, SIAM, Philadelphia, 1998.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv.h>
#include "odeiv_util.h"
typedef struct
{
double *k;
double *k1;
double *y0;
double *ytmp;
double *y_onestep;
}
rk4_state_t;
static void *
rk4_alloc (size_t dim)
{
rk4_state_t *state = (rk4_state_t *) malloc (sizeof (rk4_state_t));
if (state == 0)
{
GSL_ERROR_NULL ("failed to allocate space for rk4_state", GSL_ENOMEM);
}
state->k = (double *) malloc (dim * sizeof (double));
if (state->k == 0)
{
free (state);
GSL_ERROR_NULL ("failed to allocate space for k", GSL_ENOMEM);
}
state->k1 = (double *) malloc (dim * sizeof (double));
if (state->k1 == 0)
{
free (state->k);
free (state);
GSL_ERROR_NULL ("failed to allocate space for k1", GSL_ENOMEM);
}
state->y0 = (double *) malloc (dim * sizeof (double));
if (state->y0 == 0)
{
free (state->k);
free (state->k1);
free (state);
GSL_ERROR_NULL ("failed to allocate space for y0", GSL_ENOMEM);
}
state->ytmp = (double *) malloc (dim * sizeof (double));
if (state->ytmp == 0)
{
free (state->y0);
free (state->k);
free (state->k1);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM);
}
state->y_onestep = (double *) malloc (dim * sizeof (double));
if (state->y_onestep == 0)
{
free (state->ytmp);
free (state->y0);
free (state->k);
free (state->k1);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM);
}
return state;
}
static int
rk4_step (double *y, const rk4_state_t *state,
const double h, const double t, const size_t dim,
const gsl_odeiv_system *sys)
{
/* Makes a Runge-Kutta 4th order advance with step size h. */
/* initial values of variables y. */
const double *y0 = state->y0;
/* work space */
double *ytmp = state->ytmp;
/* Runge-Kutta coefficients. Contains values of coefficient k1
in the beginning
*/
double *k = state->k;
size_t i;
/* k1 step */
for (i = 0; i < dim; i++)
{
y[i] += h / 6.0 * k[i];
ytmp[i] = y0[i] + 0.5 * h * k[i];
}
/* k2 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h, ytmp, k);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
{
y[i] += h / 3.0 * k[i];
ytmp[i] = y0[i] + 0.5 * h * k[i];
}
/* k3 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h, ytmp, k);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
{
y[i] += h / 3.0 * k[i];
ytmp[i] = y0[i] + h * k[i];
}
/* k4 step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, ytmp, k);
if (s != GSL_SUCCESS)
{
return s;
}
}
for (i = 0; i < dim; i++)
{
y[i] += h / 6.0 * k[i];
}
return GSL_SUCCESS;
}
static int
rk4_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)
{
rk4_state_t *state = (rk4_state_t *) vstate;
size_t i;
double *const k = state->k;
double *const k1 = state->k1;
double *const y0 = state->y0;
double *const y_onestep = state->y_onestep;
DBL_MEMCPY (y0, y, dim);
if (dydt_in != NULL)
{
DBL_MEMCPY (k, dydt_in, dim);
}
else
{
int s = GSL_ODEIV_FN_EVAL (sys, t, y0, k);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* Error estimation is done by step doubling procedure */
/* Save first point derivatives*/
DBL_MEMCPY (k1, k, dim);
/* First traverse h with one step (save to y_onestep) */
DBL_MEMCPY (y_onestep, y, dim);
{
int s = rk4_step (y_onestep, state, h, t, dim, sys);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* Then with two steps with half step length (save to y) */
DBL_MEMCPY (k, k1, dim);
{
int s = rk4_step (y, state, h/2.0, t, dim, sys);
if (s != GSL_SUCCESS)
{
/* Restore original values */
DBL_MEMCPY (y, y0, dim);
return s;
}
}
/* Update before second step */
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h/2.0, y, k);
if (s != GSL_SUCCESS)
{
/* Restore original values */
DBL_MEMCPY (y, y0, dim);
return s;
}
}
/* Save original y0 to k1 for possible failures */
DBL_MEMCPY (k1, y0, dim);
/* Update y0 for second step */
DBL_MEMCPY (y0, y, dim);
{
int s = rk4_step (y, state, h/2.0, t + h/2.0, dim, sys);
if (s != GSL_SUCCESS)
{
/* Restore original values */
DBL_MEMCPY (y, k1, dim);
return s;
}
}
/* Derivatives at output */
if (dydt_out != NULL) {
int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out);
if (s != GSL_SUCCESS)
{
/* Restore original values */
DBL_MEMCPY (y, k1, dim);
return s;
}
}
/* Error estimation
yerr = C * 0.5 * | y(onestep) - y(twosteps) | / (2^order - 1)
constant C is approximately 8.0 to ensure 90% of samples lie within
the error (assuming a gaussian distribution with prior p(sigma)=1/sigma.)
*/
for (i = 0; i < dim; i++)
{
yerr[i] = 4.0 * (y[i] - y_onestep[i]) / 15.0;
}
return GSL_SUCCESS;
}
static int
rk4_reset (void *vstate, size_t dim)
{
rk4_state_t *state = (rk4_state_t *) vstate;
DBL_ZERO_MEMSET (state->k, dim);
DBL_ZERO_MEMSET (state->k1, dim);
DBL_ZERO_MEMSET (state->y0, dim);
DBL_ZERO_MEMSET (state->ytmp, dim);
DBL_ZERO_MEMSET (state->y_onestep, dim);
return GSL_SUCCESS;
}
static unsigned int
rk4_order (void *vstate)
{
rk4_state_t *state = (rk4_state_t *) vstate;
state = 0; /* prevent warnings about unused parameters */
return 4;
}
static void
rk4_free (void *vstate)
{
rk4_state_t *state = (rk4_state_t *) vstate;
free (state->k);
free (state->k1);
free (state->y0);
free (state->ytmp);
free (state->y_onestep);
free (state);
}
static const gsl_odeiv_step_type rk4_type = { "rk4", /* name */
1, /* can use dydt_in */
1, /* gives exact dydt_out */
&rk4_alloc,
&rk4_apply,
&rk4_reset,
&rk4_order,
&rk4_free
};
const gsl_odeiv_step_type *gsl_odeiv_step_rk4 = &rk4_type;
| {
"alphanum_fraction": 0.5808716386,
"avg_line_length": 20.6256830601,
"ext": "c",
"hexsha": "fda74361883c9741faed4e3a03a9d70433b1df03",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ode-initval/rk4.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ode-initval/rk4.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/ode-initval/rk4.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z",
"num_tokens": 2443,
"size": 7549
} |
// Copyright 2016-2018 Lauri Juvela and Manu Airaksinen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef DEFINITIONS_H_
#define DEFINITIONS_H_
#include <gslwrap/vector_int.h>
#include <gslwrap/vector_double.h>
#include <gslwrap/matrix_double.h>
/* Enums */
enum DataType {ASCII, DOUBLE, FLOAT};
enum SignalPolarity {POLARITY_DEFAULT, POLARITY_INVERT, POLARITY_DETECT};
enum LpWeightingFunction {NONE, AME, STE};
enum WindowingFunctionType {HANN, HAMMING, BLACKMAN, COSINE, HANNING, RECT, NUTTALL};
enum ExcitationMethod {SINGLE_PULSE_EXCITATION, DNN_GENERATED_EXCITATION,
PULSES_AS_FEATURES_EXCITATION, EXTERNAL_EXCITATION, IMPULSE_EXCITATION};
/* Structures */
struct Param
{
Param();
~Param();
public:
int fs;
int frame_length;
int frame_length_long;
int frame_length_unvoiced;
int frame_shift;
int number_of_frames;
int signal_length;
int lpc_order_vt;
int lpc_order_glot;
int hnr_order;
bool use_external_f0;
std::string external_f0_filename;
bool use_external_gci;
std::string external_gci_filename;
bool use_external_lsf_vt; // inverse filtering with external vocal tract filter
std::string external_lsf_vt_filename;
bool use_external_excitation;
std::string external_excitation_filename;
std::string dnn_path_basename;
std::string data_directory;
std::string file_basename;
std::string file_path;
bool save_to_datadir_root;
DataType data_type;
bool qmf_subband_analysis;
SignalPolarity signal_polarity;
double gif_pre_emphasis_coefficient;
double unvoiced_pre_emphasis_coefficient;
bool use_iterative_gif;
LpWeightingFunction lp_weighting_function;
int lpc_order_glot_iaif;
double warping_lambda_vt;
double ame_duration_quotient;
double ame_position_quotient;
WindowingFunctionType default_windowing_function;
WindowingFunctionType psola_windowing_function;
WindowingFunctionType paf_analysis_window;
double max_pulse_len_diff;
int paf_pulse_length;
bool use_pulse_interpolation;
bool use_highpass_filtering;
bool use_waveforms_directly;
bool use_paf_unvoiced_synthesis;
bool use_velvet_unvoiced_paf;
bool extract_f0;
bool extract_gain;
bool extract_lsf_vt;
bool extract_lsf_glot;
bool extract_hnr;
bool extract_infofile;
bool extract_glottal_excitation;
bool extract_original_signal;
bool extract_gci_signal;
bool extract_pulses_as_features;
bool use_paf_energy_normalization;
int lpc_order_vt_qmf1;
int lpc_order_vt_qmf2;
double f0_max;
double f0_min;
double voicing_threshold;
double zcr_threshold;
double relative_f0_threshold;
double speed_scale;
double pitch_scale;
bool use_postfiltering;
bool use_spectral_matching;
bool use_wsola;
bool use_wsola_pitch_shift;
bool noise_gated_synthesis;
double noise_reduction_db;
double noise_gate_limit_db;
double postfilter_coefficient;
double postfilter_coefficient_glot;
bool use_trajectory_smoothing;
int lsf_vt_smooth_len;
int lsf_glot_smooth_len;
int gain_smooth_len;
int hnr_smooth_len;
int filter_update_interval_vt;
int filter_update_interval_specmatch;
double noise_gain_unvoiced;
double noise_gain_voiced;
double noise_low_freq_limit_voiced;
//double f0_check_range;
ExcitationMethod excitation_method;
bool use_pitch_synchronous_analysis;
bool use_generic_envelope;
/* directory paths for storing parameters */
std::string dir_gain;
std::string dir_lsf;
std::string dir_lsfg;
std::string dir_hnr;
std::string dir_paf;
std::string dir_f0;
std::string dir_exc;
std::string dir_syn;
std::string dir_sp;
/* extensions for parameter types */
std::string extension_gain;
std::string extension_lsf;
std::string extension_lsfg;
std::string extension_hnr;
std::string extension_paf;
std::string extension_f0;
std::string extension_exc;
std::string extension_src = ".src.wav";
std::string extension_syn;
std::string extension_wav;
std::string wav_filename;
std::string default_config_filename;
std::string user_config_filename;
};
/* Define analysis data variable struct*/
struct AnalysisData {
AnalysisData();
~AnalysisData();
int AllocateData(const Param ¶ms);
int SaveData(const Param ¶ms);
public:
gsl::vector signal;
gsl::vector fundf;
gsl::vector frame_energy;
gsl::vector_int gci_inds;
gsl::vector source_signal;
gsl::vector source_signal_iaif;
gsl::matrix poly_vocal_tract;
gsl::matrix lsf_vocal_tract;
gsl::matrix poly_glot;
gsl::matrix lsf_glot;
gsl::matrix excitation_pulses;
gsl::matrix hnr_glot;
/* QMF analysis specific */
//gsl::matrix lsf_vt_qmf1;
//gsl::matrix lsf_vt_qmf2;
//gsl::vector gain_qmf;
};
/* Define analysis data variable struct*/
struct SynthesisData {
SynthesisData();
~SynthesisData();
public:
gsl::vector signal;
gsl::vector fundf;
gsl::vector frame_energy;
gsl::vector excitation_signal;
gsl::matrix poly_vocal_tract;
gsl::matrix lsf_vocal_tract;
gsl::matrix poly_glot;
gsl::matrix lsf_glot;
gsl::matrix excitation_pulses;
gsl::matrix hnr_glot;
gsl::matrix spectrum;
/* QMF analysis specific */
//gsl::matrix lsf_vt_qmf1;
//gsl::matrix lsf_vt_qmf2;
//gsl::vector gain_qmf;
};
#endif
| {
"alphanum_fraction": 0.791066026,
"avg_line_length": 26.1348837209,
"ext": "h",
"hexsha": "cef98e502efa6e08df407dd5d6666278b3aced0c",
"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": "b7db669d7f34da92ab34742d75a8ba3c70763a65",
"max_forks_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_forks_repo_name": "entn-at/GlottDNN",
"max_forks_repo_path": "src/glott/definitions.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_issues_repo_name": "entn-at/GlottDNN",
"max_issues_repo_path": "src/glott/definitions.h",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65",
"max_stars_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_stars_repo_name": "entn-at/GlottDNN",
"max_stars_repo_path": "src/glott/definitions.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1438,
"size": 5619
} |
/*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
#include <math.h>
#include <cblas.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "PHY/TOOLS/tools_defs.h"
#include "sim.h"
#include "scm_corrmat.h"
#include "common/utils/LOG/log.h"
//#define DEBUG_CH
#include "assertions.h"
extern void print_shorts(char *s,__m128i *x);
void fill_channel_desc(channel_desc_t *chan_desc,
uint8_t nb_tx,
uint8_t nb_rx,
uint8_t nb_taps,
uint8_t channel_length,
double *amps,
double *delays,
struct complex** R_sqrt,
double Td,
double sampling_rate,
double channel_bandwidth,
double ricean_factor,
double aoa,
double forgetting_factor,
double max_Doppler,
int32_t channel_offset,
double path_loss_dB,
uint8_t random_aoa)
{
uint16_t i,j;
double delta_tau;
LOG_I(OCM,"[CHANNEL] Getting new channel descriptor, nb_tx %d, nb_rx %d, nb_taps %d, channel_length %d\n",
nb_tx,nb_rx,nb_taps,channel_length);
chan_desc->nb_tx = nb_tx;
chan_desc->nb_rx = nb_rx;
chan_desc->nb_taps = nb_taps;
chan_desc->channel_length = channel_length;
chan_desc->amps = amps;
LOG_D(OCM,"[CHANNEL] Doing delays ...\n");
if (delays==NULL) {
chan_desc->delays = (double*) malloc(nb_taps*sizeof(double));
delta_tau = Td/nb_taps;
for (i=0; i<nb_taps; i++)
chan_desc->delays[i] = ((double)i)*delta_tau;
}
else
chan_desc->delays = delays;
chan_desc->Td = Td;
chan_desc->sampling_rate = sampling_rate;
chan_desc->channel_bandwidth = channel_bandwidth;
chan_desc->ricean_factor = ricean_factor;
chan_desc->aoa = aoa;
chan_desc->random_aoa = random_aoa;
chan_desc->forgetting_factor = forgetting_factor;
chan_desc->channel_offset = channel_offset;
chan_desc->path_loss_dB = path_loss_dB;
chan_desc->first_run = 1;
chan_desc->ip = 0.0;
chan_desc->max_Doppler = max_Doppler;
chan_desc->ch = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->chF = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->a = (struct complex**) malloc(nb_taps*sizeof(struct complex*));
LOG_D(OCM,"[CHANNEL] Filling ch \n");
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->ch[i] = (struct complex*) malloc(channel_length * sizeof(struct complex));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->chF[i] = (struct complex*) malloc(1200 * sizeof(struct complex)); // allocate for up to 100 RBs, 12 samples per RB
LOG_D(OCM,"[CHANNEL] Filling a (nb_taps %d)\n",nb_taps);
for (i = 0; i<nb_taps; i++) {
LOG_D(OCM,"tap %d (%p,%zu)\n",i,&chan_desc->a[i],nb_tx*nb_rx * sizeof(struct complex));
chan_desc->a[i] = (struct complex*) malloc(nb_tx*nb_rx * sizeof(struct complex));
}
LOG_D(OCM,"[CHANNEL] Doing R_sqrt ...\n");
if (R_sqrt == NULL) {
chan_desc->R_sqrt = (struct complex**) calloc(nb_taps,sizeof(struct complex*));
for (i = 0; i<nb_taps; i++) {
chan_desc->R_sqrt[i] = (struct complex*) calloc(nb_tx*nb_rx*nb_tx*nb_rx,sizeof(struct complex));
for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) {
chan_desc->R_sqrt[i][j].x = 1.0;
chan_desc->R_sqrt[i][j].y = 0.0;
}
}
}
else {
chan_desc->R_sqrt = (struct complex**) calloc(nb_taps,sizeof(struct complex*));
for (i = 0; i<nb_taps; i++) {
//chan_desc->R_sqrt[i] = (struct complex*) calloc(nb_tx*nb_rx*nb_tx*nb_rx,sizeof(struct complex));
//chan_desc->R_sqrt = (struct complex*)&R_sqrt[i][0];
/* all chan_desc share the same R_sqrt, coming from caller */
chan_desc->R_sqrt[i] = R_sqrt[0];
}
}
for (i = 0; i<nb_taps; i++) {
for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) {
LOG_D(OCM,"Rsqrt[%d][%d] %f %f\n",i,j,chan_desc->R_sqrt[i][j].x,chan_desc->R_sqrt[i][j].y);
}
}
LOG_D(OCM,"[CHANNEL] RF %f\n",chan_desc->ricean_factor);
for (i=0;i<chan_desc->nb_taps;i++)
LOG_D(OCM,"[CHANNEL] tap %d: amp %f, delay %f\n",i,chan_desc->amps[i],chan_desc->delays[i]);
chan_desc->nb_paths=10;
reset_meas(&chan_desc->random_channel);
reset_meas(&chan_desc->interp_time);
reset_meas(&chan_desc->interp_freq);
reset_meas(&chan_desc->convolution);
}
double mbsfn_delays[] = {0,.03,.15,.31,.37,1.09,12.490,12.52,12.64,12.80,12.86,13.58,27.49,27.52,27.64,27.80,27.86,28.58};
double mbsfn_amps_dB[] = {0,-1.5,-1.4,-3.6,-0.6,-7.0,-10,-11.5,-11.4,-13.6,-10.6,-17.0,-20,-21.5,-21.4,-23.6,-20.6,-27};
double scm_c_delays[] = {0, 0.0125, 0.0250, 0.3625, 0.3750, 0.3875, 0.2500, 0.2625, 0.2750, 1.0375, 1.0500, 1.0625, 2.7250, 2.7375, 2.7500, 4.6000, 4.6125, 4.6250};
double scm_c_amps_dB[] = {0.00, -2.22, -3.98, -1.86, -4.08, -5.84, -1.08, -3.30, -5.06, -9.08, -11.30, -13.06, -15.14, -17.36, -19.12, -20.64, -22.85, -24.62};
double epa_delays[] = { 0,.03,.07,.09,.11,.19,.41};
double epa_amps_dB[] = {0.0,-1.0,-2.0,-3.0,-8.0,-17.2,-20.8};
double eva_delays[] = { 0,.03,.15,.31,.37,.71,1.09,1.73,2.51};
double eva_amps_dB[] = {0.0,-1.5,-1.4,-3.6,-0.6,-9.1,-7.0,-12.0,-16.9};
double etu_delays[] = { 0,.05,.12,.2,.23,.5,1.6,2.3,5.0};
double etu_amps_dB[] = {-1.0,-1.0,-1.0,0.0,0.0,0.0,-3.0,-5.0,-7.0};
double default_amps_lin[] = {0.3868472 , 0.3094778 , 0.1547389 , 0.0773694 , 0.0386847 , 0.0193424 , 0.0096712 , 0.0038685};
double default_amp_lin[] = {1};
double ts_shift_delays[] = {0, 1/7.68};
double ts_shift_amps[] = {0, 1};
//correlation matrix for a 2x2 channel with full Tx correlation
struct complex R_sqrt_22_corr_tap[16] = {{0.70711,0}, {0.0, 0.0}, {0.70711,0}, {0.0, 0.0},
{0.0, 0.0}, {0.70711,0}, {0.0, 0.0}, {0.70711,0},
{0.70711,0}, {0.0, 0.0}, {0.70711,0}, {0.0, 0.0},
{0.0, 0.0}, {0.70711,0}, {0.0, 0.0}, {0.70711,0}};
struct complex *R_sqrt_22_corr[1] = {R_sqrt_22_corr_tap};
//correlation matrix for a fully correlated 2x1 channel (h1==h2)
struct complex R_sqrt_21_corr_tap[4] = {{0.70711,0}, {0.70711,0}, {0.70711,0}, {0.70711,0}};
struct complex *R_sqrt_21_corr[1] = {R_sqrt_21_corr_tap};
//correlation matrix for a 2x2 channel with full Tx anti-correlation
struct complex R_sqrt_22_anticorr_tap[16] = {{0.70711,0}, {0.0, 0.0}, {-0.70711,0}, {0.0, 0.0},
{0.0, 0.0}, {0.70711,0}, {0.0, 0.0}, {-0.70711,0},
{-0.70711,0}, {0.0, 0.0}, {0.70711,0}, {0.0, 0.0},
{0.0, 0.0}, {-0.70711,0}, {0.0, 0.0}, {0.70711,0}};
struct complex *R_sqrt_22_anticorr[1] = {R_sqrt_22_anticorr_tap};
//correlation matrix for a fully anti-correlated 2x1 channel (h1==-h2)
struct complex R_sqrt_21_anticorr_tap[4] = {{0.70711,0}, {-0.70711,0}, {-0.70711,0}, {0.70711,0}};
struct complex *R_sqrt_21_anticorr[1] = {R_sqrt_21_anticorr_tap};
struct complex **R_sqrt_ptr2;
// full correlation matrix in vectorized form for 2x2 channel, where h1 is perfectly orthogonal to h2
struct complex R_sqrt_22_orthogonal_tap[16] = {{0.70711,0.0}, {0.0, 0.0}, {0.0,0.0}, {0.0, 0.0},
{0.0, 0.0}, {0.0,0.0}, {0.0, 0.0}, {0.0,0.0},
{0.0,0.0}, {0.0, 0.0}, {0.0,0.0}, {0.0, 0.0},
{0.0, 0.0}, {0.0,0.0}, {0.0, 0.0}, {0.70711,0.0}};
struct complex *R_sqrt_22_orthogonal[1] = {R_sqrt_22_orthogonal_tap};
// full correlation matrix for TM4 to make orthogonal effective channel
struct complex R_sqrt_22_orth_eff_ch_TM4_prec_real_tap[16] = {{0.70711,0.0}, {0.0, 0.0}, {0.70711,0.0}, {0.0, 0.0},
{0.0, 0.0}, {0.70711,0.0}, {0.0, 0.0}, {-0.70711,0.0},
{0.70711,0.0}, {0.0, 0.0}, {0.70711,0.0}, {0.0, 0.0},
{0.0, 0.0}, {-0.70711,0.0}, {0.0, 0.0}, {0.70711,0.0}};
struct complex *R_sqrt_22_orth_eff_ch_TM4_prec_real[1] = {R_sqrt_22_orth_eff_ch_TM4_prec_real_tap};
struct complex R_sqrt_22_orth_eff_ch_TM4_prec_imag_tap[16] = {{0.70711,0.0}, {0.0,0.0}, {0.0, -0.70711}, {0.0,0.0},
{0.0, 0.0}, {0.70711,0.0}, {0.0, 0.0}, {0.0,0.70711},
{0.0,-0.70711}, {0.0, 0.0}, {-0.70711,0.0}, {0.0, 0.0},
{0.0, 0.0}, {0.0,0.70711}, {0.0, 0.0}, {-0.70711,0.0}};
struct complex *R_sqrt_22_orth_eff_ch_TM4_prec_imag[1] = {R_sqrt_22_orth_eff_ch_TM4_prec_imag_tap};
//Correlation matrix for EPA channel
struct complex R_sqrt_22_EPA_low_tap[16] = {{1.0,0.0}, {0.0,0.0}, {0.0,0.0}, {0.0,0.0},
{0.0,0.0}, {1.0,0.0}, {0.0,0.0}, {0.0,0.0},
{0.0,0.0}, {0.0,0.0}, {1.0,0.0}, {0.0,0.0},
{0.0,0.0}, {0.0,0.0}, {0.0,0.0}, {1.0,0.0}};
struct complex *R_sqrt_22_EPA_low[1] = {R_sqrt_22_EPA_low_tap};
struct complex R_sqrt_22_EPA_high_tap[16] = {{0.7179,0.0}, {0.4500,0.0}, {0.4500,0.0}, {0.2821,0.0},
{0.4500,0.0}, {0.7179,0.0}, {0.2821,0.0}, {0.4500,0.0},
{0.4500,0.0}, {0.2821,0.0}, {0.7179,0.0}, {0.4500,0.0},
{0.2821,0.0}, {0.4500,0.0}, {0.4500,0.0}, {0.7179,0.0}};
struct complex *R_sqrt_22_EPA_high[1] = {R_sqrt_22_EPA_high_tap};
struct complex R_sqrt_22_EPA_medium_tap[16] = {{0.8375,0.0}, {0.5249,0.0}, {0.1286,0.0}, {0.0806,0.0},
{0.5249,0.0}, {0.8375,0.0}, {0.0806,0.0}, {0.1286,0.0},
{0.1286,0.0}, {0.0806,0.0}, {0.8375,0.0}, {0.5249,0.0},
{0.0806,0.0}, {0.1286,0.0}, {0.5249,0.0}, {0.8375,0.0}};
struct complex *R_sqrt_22_EPA_medium[1] = {R_sqrt_22_EPA_medium_tap};
//Rayleigh1_orth_eff_ch_TM4
channel_desc_t *new_channel_desc_scm(uint8_t nb_tx,
uint8_t nb_rx,
SCM_t channel_model,
double sampling_rate,
double channel_bandwidth,
double forgetting_factor,
int32_t channel_offset,
double path_loss_dB)
{
channel_desc_t *chan_desc = (channel_desc_t *)malloc(sizeof(channel_desc_t));
uint16_t i,j;
double sum_amps;
double aoa,ricean_factor,Td,maxDoppler;
int channel_length,nb_taps;
chan_desc->nb_tx = nb_tx;
chan_desc->nb_rx = nb_rx;
chan_desc->sampling_rate = sampling_rate;
chan_desc->channel_bandwidth = channel_bandwidth;
chan_desc->forgetting_factor = forgetting_factor;
chan_desc->channel_offset = channel_offset;
chan_desc->path_loss_dB = path_loss_dB;
chan_desc->first_run = 1;
chan_desc->ip = 0.0;
LOG_I(OCM,"Channel Model (inside of new_channel_desc_scm)=%d\n\n", channel_model);
switch (channel_model) {
case SCM_A:
LOG_W(OCM,"channel model not yet supported\n");
free(chan_desc);
return(NULL);
case SCM_B:
LOG_W(OCM,"channel model not yet supported\n");
free(chan_desc);
return(NULL);
case SCM_C:
chan_desc->nb_taps = 18;
chan_desc->Td = 4.625;
chan_desc->channel_length = (int) (2*chan_desc->sampling_rate*chan_desc->Td + 1 + 2/(M_PI*M_PI)*log(4*M_PI*chan_desc->sampling_rate*chan_desc->Td));
sum_amps = 0;
chan_desc->amps = (double*) malloc(chan_desc->nb_taps*sizeof(double));
for (i = 0; i<chan_desc->nb_taps; i++) {
chan_desc->amps[i] = pow(10,.1*scm_c_amps_dB[i]);
sum_amps += chan_desc->amps[i];
}
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->amps[i] /= sum_amps;
chan_desc->delays = scm_c_delays;
chan_desc->ricean_factor = 1;
chan_desc->aoa = 0;
chan_desc->random_aoa = 0;
chan_desc->ch = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->chF = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->a = (struct complex**) malloc(chan_desc->nb_taps*sizeof(struct complex*));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->ch[i] = (struct complex*) malloc(chan_desc->channel_length * sizeof(struct complex));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->chF[i] = (struct complex*) malloc(1200 * sizeof(struct complex));
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->a[i] = (struct complex*) malloc(nb_tx*nb_rx * sizeof(struct complex));
chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**));
if (nb_tx==2 && nb_rx==2) {
for (i = 0; i<6; i++)
chan_desc->R_sqrt[i] = (struct complex*) &R22_sqrt[i][0];
}
else if (nb_tx==2 && nb_rx==1) {
for (i = 0; i<6; i++)
chan_desc->R_sqrt[i] = (struct complex*) &R21_sqrt[i][0];
}
else if (nb_tx==1 && nb_rx==2) {
for (i = 0; i<6; i++)
chan_desc->R_sqrt[i] = (struct complex*) &R12_sqrt[i][0];
}
else {
for (i = 0; i<6; i++) {
chan_desc->R_sqrt[i] = (struct complex*) malloc(nb_tx*nb_rx*nb_tx*nb_rx * sizeof(struct complex));
for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) {
chan_desc->R_sqrt[i][j].x = 1.0;
chan_desc->R_sqrt[i][j].y = 0.0;
}
LOG_W(OCM,"correlation matrix not implemented for nb_tx==%d and nb_rx==%d, using identity\n", nb_tx, nb_rx);
}
}
break;
case SCM_D:
LOG_W(OCM,"This is not the real SCM-D model! It is just SCM-C with an additional Rice factor!\n");
chan_desc->nb_taps = 18;
chan_desc->Td = 4.625;
chan_desc->channel_length = (int) (2*chan_desc->sampling_rate*chan_desc->Td + 1 + 2/(M_PI*M_PI)*log(4*M_PI*chan_desc->sampling_rate*chan_desc->Td));
sum_amps = 0;
chan_desc->amps = (double*) malloc(chan_desc->nb_taps*sizeof(double));
for (i = 0; i<chan_desc->nb_taps; i++) {
chan_desc->amps[i] = pow(10,.1*scm_c_amps_dB[i]);
sum_amps += chan_desc->amps[i];
}
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->amps[i] /= sum_amps;
chan_desc->delays = scm_c_delays;
chan_desc->ricean_factor = 0.1;
chan_desc->aoa = 0;
chan_desc->random_aoa = 0;
chan_desc->ch = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->chF = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->a = (struct complex**) malloc(chan_desc->nb_taps*sizeof(struct complex*));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->ch[i] = (struct complex*) malloc(chan_desc->channel_length * sizeof(struct complex));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->chF[i] = (struct complex*) malloc(1200 * sizeof(struct complex));
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->a[i] = (struct complex*) malloc(nb_tx*nb_rx * sizeof(struct complex));
chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**));
if (nb_tx==2 && nb_rx==2) {
for (i = 0; i<6; i++)
chan_desc->R_sqrt[i] = (struct complex*) &R22_sqrt[i][0];
}
else if (nb_tx==2 && nb_rx==1) {
for (i = 0; i<6; i++)
chan_desc->R_sqrt[i] = (struct complex*) &R21_sqrt[i][0];
}
else if (nb_tx==1 && nb_rx==2) {
for (i = 0; i<6; i++)
chan_desc->R_sqrt[i] = (struct complex*) &R12_sqrt[i][0];
}
else {
for (i = 0; i<6; i++) {
chan_desc->R_sqrt[i] = (struct complex*) malloc(nb_tx*nb_rx*nb_tx*nb_rx * sizeof(struct complex));
for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) {
chan_desc->R_sqrt[i][j].x = 1.0;
chan_desc->R_sqrt[i][j].y = 0.0;
}
LOG_W(OCM,"correlation matrix not implemented for nb_tx==%d and nb_rx==%d, using identity\n", nb_tx, nb_rx);
}
}
break;
case EPA:
chan_desc->nb_taps = 7;
chan_desc->Td = .410;
chan_desc->channel_length = (int) (2*chan_desc->sampling_rate*chan_desc->Td + 1 + 2/(M_PI*M_PI)*log(4*M_PI*chan_desc->sampling_rate*chan_desc->Td));
sum_amps = 0;
chan_desc->amps = (double*) malloc(chan_desc->nb_taps*sizeof(double));
for (i = 0; i<chan_desc->nb_taps; i++) {
chan_desc->amps[i] = pow(10,.1*epa_amps_dB[i]);
sum_amps += chan_desc->amps[i];
}
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->amps[i] /= sum_amps;
chan_desc->delays = epa_delays;
chan_desc->ricean_factor = 1;
chan_desc->aoa = 0;
chan_desc->random_aoa = 0;
chan_desc->ch = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->chF = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->a = (struct complex**) malloc(chan_desc->nb_taps*sizeof(struct complex*));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->ch[i] = (struct complex*) malloc(chan_desc->channel_length * sizeof(struct complex));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->chF[i] = (struct complex*) malloc(1200 * sizeof(struct complex));
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->a[i] = (struct complex*) malloc(nb_tx*nb_rx * sizeof(struct complex));
if (nb_tx==2 && nb_rx==2) {
chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**));
for (i = 0; i<6; i++)
chan_desc->R_sqrt[i] = (struct complex*) &R22_sqrt[i][0];
}
else {
chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**));
for (i = 0; i<6; i++) {
chan_desc->R_sqrt[i] = (struct complex*) malloc(nb_tx*nb_rx*nb_tx*nb_rx * sizeof(struct complex));
for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) {
chan_desc->R_sqrt[i][j].x = 1.0;
chan_desc->R_sqrt[i][j].y = 0.0;
}
LOG_W(OCM,"correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n");
}
}
break;
case EPA_low:
chan_desc->nb_taps = 7;
chan_desc->Td = .410;
chan_desc->channel_length = (int) (2*chan_desc->sampling_rate*chan_desc->Td + 1 + 2/(M_PI*M_PI)*log(4*M_PI*chan_desc->sampling_rate*chan_desc->Td));
sum_amps = 0;
chan_desc->amps = (double*) malloc(chan_desc->nb_taps*sizeof(double));
for (i = 0; i<chan_desc->nb_taps; i++) {
chan_desc->amps[i] = pow(10,.1*epa_amps_dB[i]);
sum_amps += chan_desc->amps[i];
}
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->amps[i] /= sum_amps;
chan_desc->delays = epa_delays;
chan_desc->ricean_factor = 1;
chan_desc->aoa = 0;
chan_desc->random_aoa = 0;
chan_desc->ch = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->chF = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->a = (struct complex**) malloc(chan_desc->nb_taps*sizeof(struct complex*));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->ch[i] = (struct complex*) malloc(chan_desc->channel_length * sizeof(struct complex));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->chF[i] = (struct complex*) malloc(1200 * sizeof(struct complex));
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->a[i] = (struct complex*) malloc(nb_tx*nb_rx * sizeof(struct complex));
if (nb_tx==2 && nb_rx==2) {
chan_desc->R_sqrt = (struct complex**) malloc(chan_desc->nb_taps*sizeof(struct complex**));
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->R_sqrt[i] = R_sqrt_22_EPA_low[0];
}
else {
printf("Correlation matrices are implemented for 2 x 2 only");
}
/*else {
chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**));
for (i = 0; i<6; i++) {
chan_desc->R_sqrt[i] = (struct complex*) malloc(nb_tx*nb_rx*nb_tx*nb_rx * sizeof(struct complex));
for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) {
chan_desc->R_sqrt[i][j].x = 1.0;
chan_desc->R_sqrt[i][j].y = 0.0;
}
LOG_W(OCM,"correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n");
}
}*/
break;
case EPA_high:
chan_desc->nb_taps = 7;
chan_desc->Td = .410;
chan_desc->channel_length = (int) (2*chan_desc->sampling_rate*chan_desc->Td + 1 + 2/(M_PI*M_PI)*log(4*M_PI*chan_desc->sampling_rate*chan_desc->Td));
sum_amps = 0;
chan_desc->amps = (double*) malloc(chan_desc->nb_taps*sizeof(double));
for (i = 0; i<chan_desc->nb_taps; i++) {
chan_desc->amps[i] = pow(10,.1*epa_amps_dB[i]);
sum_amps += chan_desc->amps[i];
}
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->amps[i] /= sum_amps;
chan_desc->delays = epa_delays;
chan_desc->ricean_factor = 1;
chan_desc->aoa = 0;
chan_desc->random_aoa = 0;
chan_desc->ch = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->chF = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->a = (struct complex**) malloc(chan_desc->nb_taps*sizeof(struct complex*));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->ch[i] = (struct complex*) malloc(chan_desc->channel_length * sizeof(struct complex));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->chF[i] = (struct complex*) malloc(1200 * sizeof(struct complex));
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->a[i] = (struct complex*) malloc(nb_tx*nb_rx * sizeof(struct complex));
if (nb_tx==2 && nb_rx==2) {
chan_desc->R_sqrt = (struct complex**) malloc(chan_desc->nb_taps*sizeof(struct complex**));
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->R_sqrt[i] = R_sqrt_22_EPA_high[0];
}
else {
printf("Correlation matrices are implemented for 2 x 2 only");
}
/*else {
chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**));
for (i = 0; i<6; i++) {
chan_desc->R_sqrt[i] = (struct complex*) malloc(nb_tx*nb_rx*nb_tx*nb_rx * sizeof(struct complex));
for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) {
chan_desc->R_sqrt[i][j].x = 1.0;
chan_desc->R_sqrt[i][j].y = 0.0;
}
LOG_W(OCM,"correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n");
}
}*/
break;
case EPA_medium:
chan_desc->nb_taps = 7;
chan_desc->Td = .410;
chan_desc->channel_length = (int) (2*chan_desc->sampling_rate*chan_desc->Td + 1 + 2/(M_PI*M_PI)*log(4*M_PI*chan_desc->sampling_rate*chan_desc->Td));
sum_amps = 0;
chan_desc->amps = (double*) malloc(chan_desc->nb_taps*sizeof(double));
for (i = 0; i<chan_desc->nb_taps; i++) {
chan_desc->amps[i] = pow(10,.1*epa_amps_dB[i]);
sum_amps += chan_desc->amps[i];
}
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->amps[i] /= sum_amps;
chan_desc->delays = epa_delays;
chan_desc->ricean_factor = 1;
chan_desc->aoa = 0;
chan_desc->random_aoa = 0;
chan_desc->ch = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->chF = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->a = (struct complex**) malloc(chan_desc->nb_taps*sizeof(struct complex*));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->ch[i] = (struct complex*) malloc(chan_desc->channel_length * sizeof(struct complex));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->chF[i] = (struct complex*) malloc(1200 * sizeof(struct complex));
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->a[i] = (struct complex*) malloc(nb_tx*nb_rx * sizeof(struct complex));
if (nb_tx==2 && nb_rx==2) {
chan_desc->R_sqrt = (struct complex**) malloc(chan_desc->nb_taps*sizeof(struct complex**));
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->R_sqrt[i] = R_sqrt_22_EPA_medium[0];
} else {
printf("Correlation matrices are implemented for 2 x 2 only");
}
/*else {
chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**));
for (i = 0; i<6; i++) {
chan_desc->R_sqrt[i] = (struct complex*) malloc(nb_tx*nb_rx*nb_tx*nb_rx * sizeof(struct complex));
for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) {
chan_desc->R_sqrt[i][j].x = 1.0;
chan_desc->R_sqrt[i][j].y = 0.0;
}
LOG_W(OCM,"correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n");
}
}*/
break;
case EVA:
chan_desc->nb_taps = 9;
chan_desc->Td = 2.51;
chan_desc->channel_length = (int) (2*chan_desc->sampling_rate*chan_desc->Td + 1 + 2/(M_PI*M_PI)*log(4*M_PI*chan_desc->sampling_rate*chan_desc->Td));
sum_amps = 0;
chan_desc->amps = (double*) malloc(chan_desc->nb_taps*sizeof(double));
for (i = 0; i<chan_desc->nb_taps; i++) {
chan_desc->amps[i] = pow(10,.1*eva_amps_dB[i]);
sum_amps += chan_desc->amps[i];
}
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->amps[i] /= sum_amps;
chan_desc->delays = eva_delays;
chan_desc->ricean_factor = 1;
chan_desc->aoa = 0;
chan_desc->random_aoa = 0;
chan_desc->ch = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->chF = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->a = (struct complex**) malloc(chan_desc->nb_taps*sizeof(struct complex*));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->ch[i] = (struct complex*) malloc(chan_desc->channel_length * sizeof(struct complex));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->chF[i] = (struct complex*) malloc(1200 * sizeof(struct complex));
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->a[i] = (struct complex*) malloc(nb_tx*nb_rx * sizeof(struct complex));
if (nb_tx==2 && nb_rx==2) {
chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**));
for (i = 0; i<6; i++)
chan_desc->R_sqrt[i] = (struct complex*) &R22_sqrt[i][0];
}
else {
chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**));
for (i = 0; i<6; i++) {
chan_desc->R_sqrt[i] = (struct complex*) malloc(nb_tx*nb_rx*nb_tx*nb_rx * sizeof(struct complex));
for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) {
chan_desc->R_sqrt[i][j].x = 1.0;
chan_desc->R_sqrt[i][j].y = 0.0;
}
LOG_W(OCM,"correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n");
}
}
break;
case ETU:
chan_desc->nb_taps = 9;
chan_desc->Td = 5.0;
chan_desc->channel_length = (int) (2*chan_desc->sampling_rate*chan_desc->Td + 1 + 2/(M_PI*M_PI)*log(4*M_PI*chan_desc->sampling_rate*chan_desc->Td));
sum_amps = 0;
chan_desc->amps = (double*) malloc(chan_desc->nb_taps*sizeof(double));
for (i = 0; i<chan_desc->nb_taps; i++) {
chan_desc->amps[i] = pow(10,.1*etu_amps_dB[i]);
sum_amps += chan_desc->amps[i];
}
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->amps[i] /= sum_amps;
chan_desc->delays = etu_delays;
chan_desc->ricean_factor = 1;
chan_desc->aoa = 0;
chan_desc->random_aoa = 0;
chan_desc->ch = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->chF = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->a = (struct complex**) malloc(chan_desc->nb_taps*sizeof(struct complex*));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->ch[i] = (struct complex*) malloc(chan_desc->channel_length * sizeof(struct complex));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->chF[i] = (struct complex*) malloc(1200 * sizeof(struct complex));
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->a[i] = (struct complex*) malloc(nb_tx*nb_rx * sizeof(struct complex));
if (nb_tx==2 && nb_rx==2) {
chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**));
for (i = 0; i<6; i++)
chan_desc->R_sqrt[i] = (struct complex*) &R22_sqrt[i][0];
}
else {
chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex**));
for (i = 0; i<6; i++) {
chan_desc->R_sqrt[i] = (struct complex*) malloc(nb_tx*nb_rx*nb_tx*nb_rx * sizeof(struct complex));
for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) {
chan_desc->R_sqrt[i][j].x = 1.0;
chan_desc->R_sqrt[i][j].y = 0.0;
}
LOG_W(OCM,"correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n");
}
}
break;
case MBSFN:
chan_desc->nb_taps = 18;
chan_desc->Td = 28.58;
chan_desc->channel_length = (int) (2*chan_desc->sampling_rate*chan_desc->Td + 1 + 2/(M_PI*M_PI)*log(4*M_PI*chan_desc->sampling_rate*chan_desc->Td));
sum_amps = 0;
chan_desc->amps = (double*) malloc(chan_desc->nb_taps*sizeof(double));
for (i = 0; i<chan_desc->nb_taps; i++) {
chan_desc->amps[i] = pow(10,.1*mbsfn_amps_dB[i]);
sum_amps += chan_desc->amps[i];
}
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->amps[i] /= sum_amps;
chan_desc->delays = mbsfn_delays;
chan_desc->ricean_factor = 1;
chan_desc->aoa = 0;
chan_desc->random_aoa = 0;
chan_desc->ch = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->chF = (struct complex**) malloc(nb_tx*nb_rx*sizeof(struct complex*));
chan_desc->a = (struct complex**) malloc(chan_desc->nb_taps*sizeof(struct complex*));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->ch[i] = (struct complex*) malloc(chan_desc->channel_length * sizeof(struct complex));
for (i = 0; i<nb_tx*nb_rx; i++)
chan_desc->chF[i] = (struct complex*) malloc(1200 * sizeof(struct complex));
for (i = 0; i<chan_desc->nb_taps; i++)
chan_desc->a[i] = (struct complex*) malloc(nb_tx*nb_rx * sizeof(struct complex));
chan_desc->R_sqrt = (struct complex**) malloc(6*sizeof(struct complex*));
for (i = 0; i<6; i++) {
chan_desc->R_sqrt[i] = (struct complex*) malloc(nb_tx*nb_rx*nb_tx*nb_rx * sizeof(struct complex));
for (j = 0; j<nb_tx*nb_rx*nb_tx*nb_rx; j+=(nb_tx*nb_rx+1)) {
chan_desc->R_sqrt[i][j].x = 1.0;
chan_desc->R_sqrt[i][j].y = 0.0;
}
LOG_W(OCM,"correlation matrix only implemented for nb_tx==2 and nb_rx==2, using identity\n");
}
break;
case Rayleigh8:
nb_taps = 8;
Td = 0.8;
channel_length = (int)11+2*sampling_rate*Td;
ricean_factor = 1;
aoa = .03;
maxDoppler = 0;
fill_channel_desc(chan_desc,
nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amps_lin,
NULL,
NULL,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
0);
break;
case Rice8:
nb_taps = 8;
Td = 0.8;
channel_length = (int)11+2*sampling_rate*Td;
ricean_factor = 0.1;
aoa = 0.7854;
maxDoppler = 0;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amps_lin,
NULL,
NULL,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
1);
break;
case Rayleigh1:
nb_taps = 1;
Td = 0;
channel_length = 1;
ricean_factor = 1;
aoa = .03;
maxDoppler = 0;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amp_lin,
NULL,
NULL,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
0);
break;
case Rayleigh1_800:
nb_taps = 1;
Td = 0;
channel_length = 1;
ricean_factor = 1;
aoa = .03;
maxDoppler = 800;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amp_lin,
NULL,
NULL,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
0);
break;
case Rayleigh1_corr:
nb_taps = 1;
Td = 0;
channel_length = 1;
ricean_factor = 1;
aoa = .03;
maxDoppler = 0;
if ((nb_tx==2) && (nb_rx==1)) {
R_sqrt_ptr2 = R_sqrt_21_corr;
}
else if ((nb_tx==2) && (nb_rx==2)) {
R_sqrt_ptr2 = R_sqrt_22_corr;
}
else
R_sqrt_ptr2 = NULL;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amp_lin,
NULL,
R_sqrt_ptr2,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
0);
break;
case Rayleigh1_anticorr:
nb_taps = 1;
Td = 0;
channel_length = 1;
ricean_factor = 1;
aoa = .03;
maxDoppler = 0;
if ((nb_tx==2) && (nb_rx==1)) { //check this
R_sqrt_ptr2 = R_sqrt_21_anticorr;
}
else if ((nb_tx==2) && (nb_rx==2)) {
R_sqrt_ptr2 = R_sqrt_22_anticorr;
}
else
R_sqrt_ptr2 = NULL;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amp_lin,
NULL,
R_sqrt_ptr2,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
0);
break;
case Rice1:
nb_taps = 1;
Td = 0;
channel_length = 1;
ricean_factor = 0.1;
aoa = 0.7854;
maxDoppler = 0;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amp_lin,
NULL,
NULL,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
0);
break;
case AWGN:
nb_taps = 1;
Td = 0;
channel_length = 1;
ricean_factor = 0.0;
aoa = 0.0;
maxDoppler = 0;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amp_lin,
NULL,
NULL,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
0);
printf("AWGN: ricean_factor %f\n",chan_desc->ricean_factor);
break;
case TS_SHIFT:
nb_taps = 2;
Td = ts_shift_delays[1];
channel_length = 10;
ricean_factor = 0.0;
aoa = 0.0;
maxDoppler = 0;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
ts_shift_amps,
ts_shift_delays,
NULL,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
0);
printf("TS_SHIFT: ricean_factor %f\n",chan_desc->ricean_factor);
break;
case Rice1_corr:
nb_taps = 1;
Td = 0;
channel_length = 1;
ricean_factor = 0.1;
aoa = .03;
maxDoppler = 0;
if ((nb_tx==2) && (nb_rx==1)) {
R_sqrt_ptr2 = R_sqrt_21_corr;
}
else if ((nb_tx==2) && (nb_rx==2)) {
R_sqrt_ptr2 = R_sqrt_22_corr;
}
else
R_sqrt_ptr2 = NULL;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amp_lin,
NULL,
R_sqrt_ptr2,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
1);
break;
case Rice1_anticorr:
nb_taps = 1;
Td = 0;
channel_length = 1;
ricean_factor = 0.1;
aoa = .03;
maxDoppler = 0;
if ((nb_tx==2) && (nb_rx==1)) {
R_sqrt_ptr2 = R_sqrt_21_anticorr;
}
else if ((nb_tx==2) && (nb_rx==2)) {
R_sqrt_ptr2 = R_sqrt_22_anticorr;
}
else
R_sqrt_ptr2 = NULL;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amp_lin,
NULL,
R_sqrt_ptr2,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
1);
break;
case Rayleigh1_orthogonal:
nb_taps = 1;
Td = 0;
channel_length = 1;
ricean_factor = 1;
aoa = 0.03;
maxDoppler = 0;
if ((nb_tx==2) && (nb_rx==2)) {
R_sqrt_ptr2 = R_sqrt_22_orthogonal;
}
else
R_sqrt_ptr2 = NULL;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amp_lin,
NULL,
R_sqrt_ptr2,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
0);
break;
case Rayleigh1_orth_eff_ch_TM4_prec_real:
nb_taps = 1;
Td = 0;
channel_length = 1;
ricean_factor = 1;
aoa = 0.03;
maxDoppler = 0;
if ((nb_tx==2) && (nb_rx==2)) {
R_sqrt_ptr2 = R_sqrt_22_orth_eff_ch_TM4_prec_real;
}
else
R_sqrt_ptr2 = NULL;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amp_lin,
NULL,
R_sqrt_ptr2,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
1);
break;
case Rayleigh1_orth_eff_ch_TM4_prec_imag:
nb_taps = 1;
Td = 0;
channel_length = 1;
ricean_factor = 1;
aoa = 0.03;
maxDoppler = 0;
if ((nb_tx==2) && (nb_rx==2)) {
R_sqrt_ptr2 = R_sqrt_22_orth_eff_ch_TM4_prec_imag;
}
else
R_sqrt_ptr2 = NULL;
fill_channel_desc(chan_desc,nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amp_lin,
NULL,
R_sqrt_ptr2,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
0);
break;
case Rayleigh8_orth_eff_ch_TM4_prec_real:
if ((nb_tx==2) && (nb_rx==2)) {
R_sqrt_ptr2 = R_sqrt_22_orth_eff_ch_TM4_prec_real;
//R_sqrt_ptr2 = NULL;
}
else
R_sqrt_ptr2 = NULL;
nb_taps = 8;
Td = 0.8;
channel_length = (int)11+2*sampling_rate*Td;
ricean_factor = 1;
aoa = .03;
maxDoppler = 0;
fill_channel_desc(chan_desc,
nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amps_lin,
NULL,
R_sqrt_ptr2,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
0);
break;
case Rayleigh8_orth_eff_ch_TM4_prec_imag:
nb_taps = 8;
Td = 0.8;
channel_length = (int)11+2*sampling_rate*Td;
ricean_factor = 1;
aoa = .03;
maxDoppler = 0;
if ((nb_tx==2) && (nb_rx==2)) {
R_sqrt_ptr2 = R_sqrt_22_orth_eff_ch_TM4_prec_imag;
}
else
R_sqrt_ptr2 = NULL;
fill_channel_desc(chan_desc,
nb_tx,
nb_rx,
nb_taps,
channel_length,
default_amps_lin,
NULL,
R_sqrt_ptr2,
Td,
sampling_rate,
channel_bandwidth,
ricean_factor,
aoa,
forgetting_factor,
maxDoppler,
channel_offset,
path_loss_dB,
0);
break;
default:
LOG_W(OCM,"channel model not yet supported\n");
free(chan_desc);
return(NULL);
}
LOG_D(OCM,"[CHANNEL] RF %f\n",chan_desc->ricean_factor);
for (i=0;i<chan_desc->nb_taps;i++)
LOG_D(OCM,"[CHANNEL] tap %d: amp %f, delay %f\n",i,chan_desc->amps[i],chan_desc->delays[i]);
chan_desc->nb_paths = 10;
return(chan_desc);
}
int random_channel(channel_desc_t *desc, uint8_t abstraction_flag) {
double s;
int i,k,l,aarx,aatx;
struct complex anew[NB_ANTENNAS_TX*NB_ANTENNAS_RX],acorr[NB_ANTENNAS_TX*NB_ANTENNAS_RX];
struct complex phase, alpha, beta;
AssertFatal(desc->nb_tx<=NB_ANTENNAS_TX && desc->nb_rx <= NB_ANTENNAS_RX,
"random_channel.c: Error: temporary buffer for channel not big enough (%d,%d)\n",desc->nb_tx,desc->nb_rx);
start_meas(&desc->random_channel);
for (i=0;i<(int)desc->nb_taps;i++) {
for (aarx=0;aarx<desc->nb_rx;aarx++) {
for (aatx=0;aatx<desc->nb_tx;aatx++) {
anew[aarx+(aatx*desc->nb_rx)].x = sqrt(desc->ricean_factor*desc->amps[i]/2) * gaussdouble(0.0,1.0);
anew[aarx+(aatx*desc->nb_rx)].y = sqrt(desc->ricean_factor*desc->amps[i]/2) * gaussdouble(0.0,1.0);
if ((i==0) && (desc->ricean_factor != 1.0)) {
if (desc->random_aoa==1) {
desc->aoa = uniformrandom()*2*M_PI;
}
// this assumes that both RX and TX have linear antenna arrays with lambda/2 antenna spacing.
// Furhter it is assumed that the arrays are parallel to each other and that they are far enough apart so
// that we can safely assume plane wave propagation.
phase.x = cos(M_PI*((aarx-aatx)*sin(desc->aoa)));
phase.y = sin(M_PI*((aarx-aatx)*sin(desc->aoa)));
anew[aarx+(aatx*desc->nb_rx)].x += phase.x * sqrt(1.0-desc->ricean_factor);
anew[aarx+(aatx*desc->nb_rx)].y += phase.y * sqrt(1.0-desc->ricean_factor);
}
#ifdef DEBUG_CH
printf("(%d,%d,%d) %f->(%f,%f) (%f,%f) phase (%f,%f)\n",aarx,aatx,i,desc->amps[i],anew[aarx+(aatx*desc->nb_rx)].x,anew[aarx+(aatx*desc->nb_rx)].y,desc->aoa,desc->ricean_factor,phase.x,phase.y);
#endif
} //aatx
} //aarx
/*
// for debugging set a=anew;
for (aarx=0;aarx<desc->nb_rx;aarx++) {
for (aatx=0;aatx<desc->nb_tx;aatx++) {
desc->a[i][aarx+(aatx*desc->nb_rx)].x = anew[aarx+(aatx*desc->nb_rx)].x;
desc->a[i][aarx+(aatx*desc->nb_rx)].y = anew[aarx+(aatx*desc->nb_rx)].y;
printf("anew(%d,%d) = %f+1j*%f\n",aatx,aarx,anew[aarx+(aatx*desc->nb_rx)].x, anew[aarx+(aatx*desc->nb_rx)].y);
}
}
*/
//apply correlation matrix
//compute acorr = R_sqrt[i] * anew
alpha.x = 1.0;
alpha.y = 0.0;
beta.x = 0.0;
beta.y = 0.0;
cblas_zgemv(CblasRowMajor, CblasNoTrans, desc->nb_tx*desc->nb_rx, desc->nb_tx*desc->nb_rx,
(void*) &alpha, (void*) desc->R_sqrt[i/3], desc->nb_rx*desc->nb_tx,
(void*) anew, 1, (void*) &beta, (void*) acorr, 1);
/*
for (aarx=0;aarx<desc->nb_rx;aarx++) {
for (aatx=0;aatx<desc->nb_tx;aatx++) {
desc->a[i][aarx+(aatx*desc->nb_rx)].x = acorr[aarx+(aatx*desc->nb_rx)].x;
desc->a[i][aarx+(aatx*desc->nb_rx)].y = acorr[aarx+(aatx*desc->nb_rx)].y;
printf("tap %d, acorr1(%d,%d) = %f+1j*%f\n",i,aatx,aarx,acorr[aarx+(aatx*desc->nb_rx)].x, acorr[aarx+(aatx*desc->nb_rx)].y);
}
}
*/
if (desc->first_run==1){
cblas_zcopy(desc->nb_tx*desc->nb_rx, (void*) acorr, 1, (void*) desc->a[i], 1);
}
else {
// a = alpha*acorr+beta*a
// a = beta*a
// a = a+alpha*acorr
alpha.x = sqrt(1-desc->forgetting_factor);
alpha.y = 0;
beta.x = sqrt(desc->forgetting_factor);
beta.y = 0;
cblas_zscal(desc->nb_tx*desc->nb_rx, (void*) &beta, (void*) desc->a[i], 1);
cblas_zaxpy(desc->nb_tx*desc->nb_rx, (void*) &alpha, (void*) acorr, 1, (void*) desc->a[i], 1);
// desc->a[i][aarx+(aatx*desc->nb_rx)].x = (sqrt(desc->forgetting_factor)*desc->a[i][aarx+(aatx*desc->nb_rx)].x) + sqrt(1-desc->forgetting_factor)*anew.x;
// desc->a[i][aarx+(aatx*desc->nb_rx)].y = (sqrt(desc->forgetting_factor)*desc->a[i][aarx+(aatx*desc->nb_rx)].y) + sqrt(1-desc->forgetting_factor)*anew.y;
}
/*
for (aarx=0;aarx<desc->nb_rx;aarx++) {
for (aatx=0;aatx<desc->nb_tx;aatx++) {
//desc->a[i][aarx+(aatx*desc->nb_rx)].x = acorr[aarx+(aatx*desc->nb_rx)].x;
//desc->a[i][aarx+(aatx*desc->nb_rx)].y = acorr[aarx+(aatx*desc->nb_rx)].y;
printf("tap %d, a(%d,%d) = %f+1j*%f\n",i,aatx,aarx,desc->a[i][aarx+(aatx*desc->nb_rx)].x, desc->a[i][aarx+(aatx*desc->nb_rx)].y);
}
}
*/
} //nb_taps
stop_meas(&desc->random_channel);
//memset((void *)desc->ch[aarx+(aatx*desc->nb_rx)],0,(int)(desc->channel_length)*sizeof(struct complex));
if (abstraction_flag==0) {
start_meas(&desc->interp_time);
for (aarx=0; aarx<desc->nb_rx; aarx++) {
for (aatx=0; aatx<desc->nb_tx; aatx++) {
if (desc->channel_length == 1) {
desc->ch[aarx+(aatx*desc->nb_rx)][0].x = desc->a[0][aarx+(aatx*desc->nb_rx)].x;
desc->ch[aarx+(aatx*desc->nb_rx)][0].y = desc->a[0][aarx+(aatx*desc->nb_rx)].y;
} else {
for (k=0; k<(int)desc->channel_length; k++) {
desc->ch[aarx+(aatx*desc->nb_rx)][k].x = 0.0;
desc->ch[aarx+(aatx*desc->nb_rx)][k].y = 0.0;
for (l=0; l<desc->nb_taps; l++) {
if ((k - (desc->delays[l]*desc->sampling_rate) - NB_SAMPLES_CHANNEL_OFFSET) == 0)
s = 1.0;
else
s = sin(M_PI*(k - (desc->delays[l]*desc->sampling_rate) - NB_SAMPLES_CHANNEL_OFFSET))/
(M_PI*(k - (desc->delays[l]*desc->sampling_rate) - NB_SAMPLES_CHANNEL_OFFSET));
desc->ch[aarx+(aatx*desc->nb_rx)][k].x += s*desc->a[l][aarx+(aatx*desc->nb_rx)].x;
desc->ch[aarx+(aatx*desc->nb_rx)][k].y += s*desc->a[l][aarx+(aatx*desc->nb_rx)].y;
// printf("l %d : desc->ch.x %f\n",l,desc->a[l][aarx+(aatx*desc->nb_rx)].x);
} //nb_taps
#ifdef DEBUG_CH
k=0;
printf("(%d,%d,%d)->(%f,%f)\n",k,aarx,aatx,desc->ch[aarx+(aatx*desc->nb_rx)][k].x,desc->ch[aarx+(aatx*desc->nb_rx)][k].y);
#endif
}
} //channel_length
} //aatx
} //aarx
stop_meas(&desc->interp_time);
}
if (desc->first_run==1)
desc->first_run = 0;
return (0);
}
double N_RB2sampling_rate(uint16_t N_RB)
{
double sampling_rate;
switch (N_RB) {
case 6:
sampling_rate = 1.92;
break;
case 25:
sampling_rate = 7.68;
break;
case 50:
sampling_rate = 15.36;
break;
case 100:
sampling_rate = 30.72;
break;
default:
AssertFatal(1==0,"Unknown N_PRB %d",N_RB);
}
return(sampling_rate);
}
double N_RB2channel_bandwidth(uint16_t N_RB)
{
double channel_bandwidth;
switch (N_RB) {
case 6:
channel_bandwidth = 1.25;
break;
case 25:
channel_bandwidth = 5.00;
break;
case 50:
channel_bandwidth = 10.00;
break;
case 100:
channel_bandwidth = 20.00;
break;
default:
LOG_E(PHY,"Unknown N_PRB\n");
return(-1);
}
return(channel_bandwidth);
}
#ifdef RANDOM_CHANNEL_MAIN
#define sampling_rate 5.0
#define Td 2.0
main(int argc,char **argv) {
double amps[8] = {.8,.2,.1,.04,.02,.01,.005};
struct complex ch[(int)(1+2*sampling_rate*Td)],phase;
int i;
randominit();
phase.x = 1.0;
phase.y = 0;
random_channel(amps,Td, 8,sampling_rate,ch,(double)1.0,&phase);
/*
for (i=0;i<(11+2*sampling_rate*Td);i++){
printf("%f + sqrt(-1)*%f\n",ch[i].x,ch[i].y);
}
*/
}
#endif
| {
"alphanum_fraction": 0.4959606116,
"avg_line_length": 40.3652904129,
"ext": "c",
"hexsha": "8341c574da2968b8a361cdc82c3801bf8a91b998",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-05-30T08:01:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-06T16:35:41.000Z",
"max_forks_repo_head_hexsha": "3f98ecc3c84a16ee92ac796f8a5d5ba09e240c0a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Imyne/opran",
"max_forks_repo_path": "openair1/SIMULATION/TOOLS/random_channel.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3f98ecc3c84a16ee92ac796f8a5d5ba09e240c0a",
"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": "Imyne/opran",
"max_issues_repo_path": "openair1/SIMULATION/TOOLS/random_channel.c",
"max_line_length": 201,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "3f98ecc3c84a16ee92ac796f8a5d5ba09e240c0a",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Imyne/opran",
"max_stars_repo_path": "openair1/SIMULATION/TOOLS/random_channel.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-13T14:03:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-22T09:29:25.000Z",
"num_tokens": 16466,
"size": 57682
} |
#pragma once
#include <gsl/string_span>
#include <fmt/format.h>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <sstream>
#include <cctype>
#include <iosfwd>
// Thanks Stackoverflow...
std::string ucs2_to_local(const std::wstring &);
std::wstring local_to_ucs2(const std::string &);
std::string ucs2_to_utf8(const std::wstring &);
std::wstring utf8_to_ucs2(const std::string &);
// trim from start
inline std::string <rim(std::string &s) {
s.erase(s.begin(), find_if(s.begin(), s.end(), [](auto c) { return !std::isspace(c); }));
return s;
}
// trim from end
inline std::string &rtrim(std::string &s) {
s.erase(find_if(s.rbegin(), s.rend(), [](auto c) { return !std::isspace(c); }).base(), s.end());
return s;
}
// trim from both ends
inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
inline std::vector<gsl::cstring_span<>>& split(gsl::cstring_span<> s,
char delim,
std::vector<gsl::cstring_span<>>& elems,
bool trimItems = false,
bool keepEmpty = false) {
int pos = 0;
while (pos < s.size()) {
auto ch = s[pos++];
// Empty item
if (ch == delim) {
if (keepEmpty) {
elems.push_back({});
}
continue;
}
if (trimItems && isspace(ch)) {
// Skip all chars that are considered whitespace
continue;
}
auto start = pos - 1; // Start of item
size_t count = 1; // Size of item
// Seek past all of the item's content
while (pos < s.size()) {
ch = s[pos++];
if (ch == delim) {
break; // reached the end of the item
}
count++;
}
// Trim whitespace at the end of the string
if (trimItems) {
while (count > 0 && isspace(s[start + count - 1])) {
count--;
}
}
if (count != 0) {
elems.push_back(s.subspan(start, count));
} else if (keepEmpty) {
elems.push_back({});
}
}
return elems;
}
inline std::vector<gsl::cstring_span<>> split(gsl::cstring_span<> s, char delim, bool trim = false, bool keepEmpty = false) {
std::vector<gsl::cstring_span<>> elems;
split(s, delim, elems, trim, keepEmpty);
return elems;
}
inline std::vector<std::string>& split(const std::string& s, char delim, std::vector<std::string>& elems, bool trimItems = false, bool keepEmpty = false) {
std::stringstream ss(s);
std::string item;
while (getline(ss, item, delim)) {
if (trimItems) {
item = trim(item);
}
if (keepEmpty || !item.empty()) {
elems.push_back(item);
}
}
return elems;
}
inline std::vector<std::string> split(const std::string& s, char delim, bool trim = false, bool keepEmpty = false) {
std::vector<std::string> elems;
split(s, delim, elems, trim, keepEmpty);
return elems;
}
inline std::string tolower(const std::string &s) {
auto needsConversion = std::any_of(s.begin(), s.end(), [](char a) {
return std::tolower(a) != a;
});
if (needsConversion) {
std::string result = s;
std::transform(result.begin(), result.end(), result.begin(), [](char ch) { return std::tolower((int)ch); });
return result;
} else {
return s;
}
}
inline std::string tounderscore(const std::string &s) {
auto needsConversion = std::any_of(s.begin(), s.end(), [](char a) {
return a == ' ';
});
if (needsConversion) {
std::string result = s;
std::transform(result.begin(), result.end(), result.begin(), [](char ch){
if (ch == ' '){
return '_';
}
return ch;
});
return result;
}
else {
return s;
}
}
inline std::string toupper(const std::string &s) {
auto needsConversion = std::any_of(s.begin(), s.end(), [](char a) {
return std::toupper(a) != a;
});
if (needsConversion) {
std::string result = s;
std::transform(result.begin(), result.end(), result.begin(), [](char ch) { return std::toupper((int)ch); });
return result;
}
else {
return s;
}
}
// Nice to have operator for serializing vectors in the logger
namespace std {
template<typename T>
void format_arg(fmt::BasicFormatter<char> &f, const char *&format_str, const std::vector<T> &v) {
using namespace std;
f.writer().write("[");
for (size_t i = 0; i < v.size(); ++i) {
f.writer().write("{}", v[i]);
if (i != v.size() - 1) {
f.writer().write(", ");
}
}
f.writer().write("]");
}
}
inline bool endsWith(const std::string &str, const std::string &suffix) {
if (suffix.length() > str.length()) {
return false; // Short-circuit
}
return str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0;
}
| {
"alphanum_fraction": 0.6235001132,
"avg_line_length": 23.4946808511,
"ext": "h",
"hexsha": "987e0f155cb11fa8cc74e280f461fe915682d330",
"lang": "C",
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z",
"max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "edoipi/TemplePlus",
"max_forks_repo_path": "Infrastructure/include/infrastructure/stringutil.h",
"max_issues_count": 457,
"max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "edoipi/TemplePlus",
"max_issues_repo_path": "Infrastructure/include/infrastructure/stringutil.h",
"max_line_length": 155,
"max_stars_count": 69,
"max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "edoipi/TemplePlus",
"max_stars_repo_path": "Infrastructure/include/infrastructure/stringutil.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z",
"num_tokens": 1275,
"size": 4417
} |
/* integration/exponential.c
*
* Copyright (C) 2017 Konrad Griessinger, 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.
*/
/*
* The code in this module is based on IQPACK, specifically the LGPL
* implementation found in HERMITE_RULE:
* https://people.sc.fsu.edu/~jburkardt/c_src/hermite_rule/hermite_rule.html
*/
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_sf_gamma.h>
static int
exponential_check(const size_t n, const gsl_integration_fixed_params * params)
{
(void) n;
if (fabs(params->b - params->a) <= GSL_DBL_EPSILON)
{
GSL_ERROR("|b - a| too small", GSL_EDOM);
}
else if (params->a >= params->b)
{
GSL_ERROR("lower integration limit must be smaller than upper limit", GSL_EDOM);
}
else if (params->alpha <= -1.0)
{
GSL_ERROR("alpha must be > -1", GSL_EDOM);
}
else
{
return GSL_SUCCESS;
}
}
static int
exponential_init(const size_t n, double * diag, double * subdiag, gsl_integration_fixed_params * params)
{
size_t i;
double a2i = params->alpha;
/* construct the diagonal and subdiagonal elements of Jacobi matrix */
for (i = 1; i <= n; i++)
{
diag[i-1] = 0.0;
a2i += 2.0;
subdiag[i-1] = (i + params->alpha*(i%2))/sqrt( a2i*a2i - 1.0 );
}
params->zemu = 2.0/(params->alpha + 1.0);
params->shft = 0.5*(params->b + params->a);
params->slp = 0.5*(params->b - params->a);
params->al = params->alpha;
params->be = 0.0;
return GSL_SUCCESS;
}
static const gsl_integration_fixed_type exponential_type =
{
exponential_check,
exponential_init
};
const gsl_integration_fixed_type *gsl_integration_fixed_exponential = &exponential_type;
| {
"alphanum_fraction": 0.6882956879,
"avg_line_length": 28.6470588235,
"ext": "c",
"hexsha": "26079cf346ea61c866a7836a05d50838bde4f8f1",
"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/integration/exponential.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/exponential.c",
"max_line_length": 104,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/integration/exponential.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": 680,
"size": 2435
} |
#ifndef parser_496ce533_26fe_412b_8db6_e61b852be838_h
#define parser_496ce533_26fe_412b_8db6_e61b852be838_h
#include <rathen\config.h>
#include <rathen\basis.h>
#include <gslib\tree.h>
__rathen_begin__
class __gs_novtable ps_obj:
public object
{
public:
enum
{
pt_root,
pt_block,
pt_value,
pt_expression,
pt_operator,
pt_function,
pt_calling,
pt_if_statement,
pt_loop_statement,
pt_go_statement,
pt_stop_statement,
pt_exit_statement,
pt_variable,
pt_constant,
};
enum
{
vt_string,
vt_integer,
vt_float,
};
public:
ps_obj() { _parent = 0; }
ps_obj(ps_obj* parent) { _parent = parent; }
ps_obj* get_parent() const { return _parent; }
public:
virtual ~ps_obj() {}
virtual bool is_anonymous() const = 0;
protected:
ps_obj* _parent;
};
struct ps_trait_pass {};
struct ps_trait_hold {};
template<uint tag, bool anony, class ph_trait, class bsc = ps_obj>
class ps_proto:
public bsc
{
public:
ps_proto();
ps_proto(ps_obj* parent);
bool is_holder() const override;
uint get_tag() const override;
bool is_anonymous() const override;
};
template<uint tag, bool anony, class bsc>
class ps_proto<tag, anony, ps_trait_pass, bsc>:
public bsc
{
public:
ps_proto() {}
ps_proto(ps_obj* parent): bsc(parent) {}
bool is_holder() const override { return false; }
uint get_tag() const override { return tag; }
bool is_anonymous() const override { return anony; }
};
template<uint tag, bool anony, class bsc>
class ps_proto<tag, anony, ps_trait_hold, bsc>:
public bsc
{
public:
ps_proto() {}
ps_proto(ps_obj* parent): bsc(parent) {}
bool is_holder() const override { return true; }
uint get_tag() const override { return tag; }
bool is_anonymous() const override { return anony; }
public:
virtual void add_indexing(object* obj) { _indexing.add_value(obj); }
virtual indexing& get_indexing() { return _indexing; }
protected:
indexing _indexing;
public:
object* find_object(const gchar* name) { return _indexing.find_value(name); }
const object* find_object(const gchar* name) const { return _indexing.find_value(name); }
};
template<class mc, class pc>
class ps_join:
public mc,
public pc
{
public:
ps_join() {}
ps_join(ps_obj* parent): mc(parent) {}
};
class ps_comp_value
{
public:
ps_comp_value() { _type = 0, _global = false, _ref = false; }
void set_type(type* ty) { _type = ty; }
void set_global(bool g) { _global = g; }
void set_ref(bool r) { _ref = r; }
type* get_type() const { return _type; }
bool is_complex() const { return _type->is_complex(); }
bool is_global() const { return _global; }
bool is_ref() const { return _ref; }
protected:
type* _type;
bool _global;
bool _ref;
};
class ps_comp_operator
{
public:
ps_comp_operator() { _opr = 0; }
void set_opr(const oprnode* opr) { _opr = opr; }
void set_opr(const oprinfo& opr) { _opr = opr_manager::get_singleton_ptr()->get_operator(opr); }
const oprnode* get_opr_info() const { return _opr; }
bool is_unary() const { return _opr->unary; }
int get_priority() const { return _opr->prior; }
const gchar* get_opr_name() const { return _opr->opr; }
protected:
const oprnode* _opr;
};
class ps_comp_variable
{
public:
ps_comp_variable() { _value = 0; }
void set_value(ps_obj* value) { _value = value; }
ps_obj* get_value() const { return _value; }
protected:
ps_obj* _value;
};
class ps_comp_constant
{
public:
union vdif
{
int i;
real32 r;
int64 i64;
real r64;
};
public:
ps_comp_constant() {}
void set_string(const gchar* str) { _cvtag = ps_obj::vt_string, _vstr = str; }
void set_integer(int i) { _cvtag = ps_obj::vt_integer, _value.i = i; }
void set_float(real32 r) { _cvtag = ps_obj::vt_float, _value.r = r; }
uint get_value_tag() const { return _cvtag; }
const string& get_string() const { return _vstr; }
int get_integer() const { return _value.i; }
real32 get_float() const { return _value.r; }
protected:
uint _cvtag;
string _vstr;
vdif _value;
};
class ps_comp_function
{
public:
ps_comp_function() { _rety = 0, _parent = 0, _retr = false; }
void set_retv_type(type* ty) { _rety = ty; }
void set_retv_ref(bool tr) { _retr = tr; }
type* get_retv_type() const { return _rety; }
bool get_retv_ref() const { return _retr; }
void set_parent(ps_obj* obj) { _parent = obj; }
ps_obj* get_parent() const { return _parent; }
bool is_top_level() const { return _parent->get_tag() == ps_obj::pt_root; }
protected:
type* _rety;
bool _retr;
ps_obj* _parent;
};
class ps_comp_statement
{
public:
ps_comp_statement() { _condition = 0, _block = 0; }
void set_condition(ps_obj* condition) { _condition = condition; }
void set_block(ps_obj* block) { _block = block; }
ps_obj* get_condition() const { return _condition; }
ps_obj* get_block() const { return _block; }
protected:
ps_obj* _condition;
ps_obj* _block;
};
class ps_comp_if_statement:
public ps_comp_statement
{
public:
ps_comp_if_statement() { _prevbr = _nextbr = _lastbr = 0; }
void set_prev_branch(ps_obj* branch) { _prevbr = branch; }
void set_next_branch(ps_obj* branch) { _nextbr = branch; }
void set_last_branch(ps_obj* branch) { _lastbr = branch; }
ps_obj* get_prev_branch() const { return _prevbr; }
ps_obj* get_next_branch() const { return _nextbr; }
ps_obj* get_last_branch() const { return _lastbr; }
protected:
ps_obj* _prevbr;
ps_obj* _nextbr;
ps_obj* _lastbr;
};
class ps_comp_loop_statement:
public ps_comp_statement
{
};
class ps_comp_exit_statement
{
public:
ps_comp_exit_statement() { _conclusion = 0; }
void set_conclusion(ps_obj* conclusion) { _conclusion = conclusion; }
ps_obj* get_conclusion() const { return _conclusion; }
protected:
ps_obj* _conclusion;
};
typedef ps_proto<ps_obj::pt_root, true, ps_trait_hold> ps_root;
typedef ps_proto<ps_obj::pt_block, true, ps_trait_hold> ps_block;
typedef ps_proto<ps_obj::pt_value, false, ps_trait_pass, ps_join<ps_obj, ps_comp_value> > ps_value;
typedef ps_proto<ps_obj::pt_expression, true, ps_trait_pass> ps_expression;
typedef ps_proto<ps_obj::pt_operator, true, ps_trait_pass, ps_join<ps_obj, ps_comp_operator> > ps_operator;
typedef ps_proto<ps_obj::pt_function, false, ps_trait_hold, ps_join<ps_obj, ps_comp_function> > ps_function;
typedef ps_proto<ps_obj::pt_calling, true, ps_trait_pass> ps_calling;
typedef ps_proto<ps_obj::pt_go_statement, true, ps_trait_pass> ps_go_statement;
typedef ps_proto<ps_obj::pt_stop_statement, true, ps_trait_pass> ps_stop_statement;
typedef ps_proto<ps_obj::pt_if_statement, true, ps_trait_pass, ps_join<ps_obj, ps_comp_if_statement> > ps_if_statement;
typedef ps_proto<ps_obj::pt_loop_statement, true, ps_trait_pass, ps_join<ps_obj, ps_comp_loop_statement> > ps_loop_statement;
typedef ps_proto<ps_obj::pt_exit_statement, true, ps_trait_pass, ps_join<ps_obj, ps_comp_exit_statement> > ps_exit_statement;
typedef ps_proto<ps_obj::pt_variable, false, ps_trait_pass, ps_join<ps_obj, ps_comp_variable> > ps_variable;
typedef ps_proto<ps_obj::pt_constant, false, ps_trait_pass, ps_join<ps_obj, ps_comp_constant> > ps_constant;
class parser:
private tree<ps_obj, _treenode_wrapper<ps_obj> >
{
public:
typedef _treenode_wrapper<ps_obj> wrapper;
typedef ps_obj value;
typedef tree<ps_obj, wrapper> superref;
typedef superref::iterator iterator;
typedef superref::const_iterator const_iterator;
public:
parser() { insert<ps_root>(iterator()); }
const gchar* get_name() const;
void set_root(const gchar* name);
template<class _cst>
iterator insert(iterator i) { return superref::insert_tail<_cst>(i); }
template<class _cst>
iterator birth(iterator i) { return superref::birth_tail<_cst>(i); }
public:
using superref::clear;
using superref::erase;
using superref::get_root;
using superref::for_each;
using superref::detach;
using superref::attach;
using superref::debug_check;
public:
iterator find(iterator i, const gchar* name);
};
__rathen_end__
#endif
| {
"alphanum_fraction": 0.6541455161,
"avg_line_length": 29.6488294314,
"ext": "h",
"hexsha": "726b40244fb0eddf5e5230c67bfaea9a0bd54051",
"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/rathen/parser.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/rathen/parser.h",
"max_line_length": 126,
"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/rathen/parser.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": 2361,
"size": 8865
} |
#ifndef _SPC_DRIZ_H
#define _SPC_DRIZ_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_vector.h>
double sgarea(double x1, double y1, double x2, double y2, int is, int js);
double boxer(int is,int js,double *x,double *y);
#endif
| {
"alphanum_fraction": 0.7214285714,
"avg_line_length": 18.6666666667,
"ext": "h",
"hexsha": "661bf04bc41dfe17bd8b994dd0721691781f3895",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/spc_driz.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/spc_driz.h",
"max_line_length": 74,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/spc_driz.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 85,
"size": 280
} |
#pragma once
#define NOMINMAX
// Windows
#include <windows.h>
#include <winrt\Windows.Foundation.h>
// Standard
#include <string>
#include <sstream>
#if defined(DEBUG) || defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
// Guidelines Support Library
#include <gsl\gsl>
// DirectX
#include <d3d11_4.h>
#include <dxgi1_6.h>
#include <DirectXMath.h> | {
"alphanum_fraction": 0.7321428571,
"avg_line_length": 15.68,
"ext": "h",
"hexsha": "82bb3894468324193c26646fb9d59bea02a04524",
"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/1.1_Win32_Startup/pch.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/1.1_Win32_Startup/pch.h",
"max_line_length": 37,
"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/1.1_Win32_Startup/pch.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 108,
"size": 392
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_spmatrix.h>
int
main()
{
gsl_spmatrix *A = gsl_spmatrix_alloc(5, 4); /* triplet format */
gsl_spmatrix *B, *C;
size_t i, j;
/* build the sparse matrix */
gsl_spmatrix_set(A, 0, 2, 3.1);
gsl_spmatrix_set(A, 0, 3, 4.6);
gsl_spmatrix_set(A, 1, 0, 1.0);
gsl_spmatrix_set(A, 1, 2, 7.2);
gsl_spmatrix_set(A, 3, 0, 2.1);
gsl_spmatrix_set(A, 3, 1, 2.9);
gsl_spmatrix_set(A, 3, 3, 8.5);
gsl_spmatrix_set(A, 4, 0, 4.1);
printf("printing all matrix elements:\n");
for (i = 0; i < 5; ++i)
for (j = 0; j < 4; ++j)
printf("A(%zu,%zu) = %g\n", i, j,
gsl_spmatrix_get(A, i, j));
/* print out elements in triplet format */
printf("matrix in triplet format (i,j,Aij):\n");
gsl_spmatrix_fprintf(stdout, A, "%.1f");
/* convert to compressed column format */
B = gsl_spmatrix_ccs(A);
printf("matrix in compressed column format:\n");
printf("i = [ ");
for (i = 0; i < B->nz; ++i)
printf("%d, ", B->i[i]);
printf("]\n");
printf("p = [ ");
for (i = 0; i < B->size2 + 1; ++i)
printf("%d, ", B->p[i]);
printf("]\n");
printf("d = [ ");
for (i = 0; i < B->nz; ++i)
printf("%g, ", B->data[i]);
printf("]\n");
/* convert to compressed row format */
C = gsl_spmatrix_crs(A);
printf("matrix in compressed row format:\n");
printf("i = [ ");
for (i = 0; i < C->nz; ++i)
printf("%d, ", C->i[i]);
printf("]\n");
printf("p = [ ");
for (i = 0; i < C->size1 + 1; ++i)
printf("%d, ", C->p[i]);
printf("]\n");
printf("d = [ ");
for (i = 0; i < C->nz; ++i)
printf("%g, ", C->data[i]);
printf("]\n");
gsl_spmatrix_free(A);
gsl_spmatrix_free(B);
gsl_spmatrix_free(C);
return 0;
}
| {
"alphanum_fraction": 0.5346704871,
"avg_line_length": 22.6623376623,
"ext": "c",
"hexsha": "ed0018245dd66ec88206b71a4e11b3c6a3b2b315",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/doc/examples/spmatrix.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/doc/examples/spmatrix.c",
"max_line_length": 66,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/doc/examples/spmatrix.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": 681,
"size": 1745
} |
#include <stdio.h>
#include <math.h> /*per sin i cos*/
#include <stdlib.h> /*pel malloc i calloc*/
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "memory.h"
// what data to save
int writeData; /* command line input */
// simulation run time
double tStop; /* command line input */
//capacitance
double c=1.;
// leak
double glk=1;
double vlk=-70;
// Na channel
double gna=37;
double vna=55;
// Na activation [m]
double thetam=30;
double sm=15;
// Na inactivation [h]
double thetah=-39;
double sh=3.1;
double tauh0=1;
double tauh1=500;
double thh=57;
double sigmah=3;
// K channel
double gk=45;
double vk=-80;
// K activation
double thetan=-32.;
double sn=-8.;
double taun0=1;
double taun1=100.;
double thn=80.;
double sigman=26.;
// A channel
double ga; /* command line input */
// A activation [a]
double taua = 2;
double thetaa = -50;
double sigmaa = 20;
// A inactivation [b]
double taub=150;
double thetab=-70;
double sigmab=-6;
// kinetics rescaling
double phi=0.75;
// synapse
double vsyne = 0.;
double vsyni = -85.;
double gsyne, gsyni; /* command line input */
double rsyne, rsyni; /* command line input */
double betae = .2;
double betai = .18;
double te, ti, teNext,tiNext; /* synapse event times */
double v,m,b,n,a,se,si;
double minf,hinf,ninf,binf,ainf;
double tauh,taun,taua;
double ina,ik,ilk,ia,isyne,isyni;
double alphae;
//double twopi=8*atan(1.);
double twopi=3.1415926535;
int func (double t, const double x[], double dx[], void *params);
int jac (double t, const double y[], double *dfdy, double dfdt[], void *params);
int main(int argc, char *argv[]){
double *x,*dx;
double vlast,tspike;
double si0;
double rand;
int ndim=6;
int i;
FILE *output;
double tol=1.0e-5;
double mu;
//const gsl_odeiv_step_type * T = gsl_odeiv_step_rk8pd; // Runge-Kutta Prince-Dormand 8-9.
//const gsl_odeiv_step_type * T = gsl_odeiv_step_rk2imp; // Runge-Kutta 2 implicit.
const gsl_odeiv_step_type * T = gsl_odeiv_step_rk4imp; // Runge-Kutta 4 implicit.
//const gsl_odeiv_step_type * T = gsl_odeiv_step_bsimp; // Burlirsch-Stoer implicit.. Need jacobian!
//const gsl_odeiv_step_type * T = gsl_odeiv_step_gear1; // Gear 1 implicit.
//const gsl_odeiv_step_type * T = gsl_odeiv_step_gear2; // Gear 2 implicit.
gsl_odeiv_step * s = gsl_odeiv_step_alloc (T, ndim);
gsl_odeiv_control * c = gsl_odeiv_control_y_new (tol, 0.0);
gsl_odeiv_evolve * e = gsl_odeiv_evolve_alloc (ndim);
gsl_odeiv_system sys = {func, jac, ndim, &mu};
/* Random generator stuff */
const gsl_rng_type *U;
gsl_rng *r;
gsl_rng_env_setup();
U = gsl_rng_default;
r = gsl_rng_alloc (U);
/* Parameters From Command Line */
writeData = atof(argv[1]);
tStop = atof(argv[2]);
ga = atof(argv[3]);
gsyne = atof(argv[4]);
gsyni = atof(argv[5]);
rsyne = atof(argv[6]);
rsyni = atof(argv[7]);
double t, tf;
double h = 1.e-3;
int status;
char name1[100];
int number1,number2,number3;
int ncount=0;
int nite;
double sum;
if (writeData==1){ /* save all data */
sprintf(name1, "data1cpt_ga%g_ge%g_gi%g_re%.1f_ri%g.txt",ga,gsyne, gsyni, rsyne,rsyni);}
else if (writeData==2){ /* save spikes */
sprintf(name1, "spike1cpt_ga%g_ge%g_gi%g_re%.1f_ri%g.txt",ga,gsyne, gsyni, rsyne,rsyni);}
output=fopen(name1, "w");
/*open the data file*/
output=fopen(name1, "w");
if (output==NULL){
printf("Error in opening data file\n");
exit(1);
}
/*memory allocation*/
x = new_vector(0, ndim-1);
dx = new_vector(0, ndim-1);
/*Initial point*/
double v0=-70;
x[0]=v0; /* v */
x[1]=1./(1.+exp((v0-thetan)/sn)); /* n */
x[2]=1/(1+exp(-(v0-thetaa)/sigmaa)); /* a */
x[3]=1/(1+exp(-(v0-thetab)/sigmab)); /* b */
x[4]=0; /* se */
x[5]=0; /* si */
/*integrate*/
t=0.;
nite=0.;
vlast=v0;
te = 0;
ti = -999.; tiNext = 1000./rsyni; si0 = 0;
te = -999.; rand =gsl_ran_flat(r, 0,1); teNext = -1000.*log(1-rand)/(rsyne);
if (teNext<tiNext){tf=teNext;}
else {tf=tiNext;}
while (t<tStop){
while (t<tf){
status = gsl_odeiv_evolve_apply (e, c, s, &sys, &t, tf, &h, x);
if (status != GSL_SUCCESS)
break;
if (writeData==1){ /* save everything */
fprintf(output," %.5f ",t);
for (i=0;i<ndim;i++){
fprintf(output," %.5f ",x[i]);
}
fprintf(output, "\n");
}
/* spike detection */
tspike =0.;
if ((x[0]>=-10)&&(vlast<-10)){
ncount++;
tspike=t;
if (writeData==2){ /* save spikes */
fprintf(output," %.5f %.5f",tspike, si0); fprintf(output, "\n");
}
}
vlast=x[0];
nite++;
}
// generate next excitatory event
if (tf>=teNext){
te = teNext;
rand=gsl_ran_flat(r, 0,1); teNext+=-1000.*log(1-rand)/(rsyne);
// for instantaneous rise se
x[4]=1.; // ceiling at 1
si0 = x[5]; // si value at the excitatory event onset
if (writeData==2){fprintf(output," %.5f %.5f ",-tf, x[5]); fprintf(output, "\n");} /* save excitatory events */
}
// generate next inhibitory event
if (tf>=tiNext){tiNext+=1000./rsyni; x[5]=1.;} // ceiling at 1
if (teNext<tiNext){tf=teNext;}
else {tf=tiNext;}
}
if (writeData==2){fprintf(output," %.5f %.5f ",tStop , tStop); fprintf(output, "\n");}
free_vector(x,0);
free_vector(dx,0);
fclose(output);
gsl_odeiv_evolve_free (e);
gsl_odeiv_control_free (c);
gsl_odeiv_step_free (s);
}
/* Vector field we want to integrate*/
int func (double t, const double x[], double dx[], void *params)
{
double mu = *(double *)params;
double m3,n4,a3;
// general variables
v = x[0];
m = 1./(1.+exp(-(v+thetam)/sm)); // m—>minf instantaneous
n = x[1];
a = x[2] ; // 1/(1+exp(-(v-thetaa)/sigmaa)); // a->ainf instantaneous
b = x[3];
se= x[4];
si= x[5];
// currents
m3=m*m*m;
n4=n*n*n*n;
a3=a*a*a;
ina= gna*m3*(1-n)*(v-vna);
ik = gk*n4*(v-vk);
ia = ga*a3*b*(v-vk);
ilk= glk*(v-vlk);
isyne = gsyne*se*(v-vsyne);
isyni = gsyni*si*(v-vsyni);
/* update voltage */
dx[0] = - (ilk + ina + ik + ia + isyni + isyne)/c;
/* update n gating */
ninf=1./(1.+exp((v-thetan)/sn));
taun=taun0+taun1/(1+exp((v+thn)/sigman));
dx[1]=phi*(ninf-n)/taun;
/* update a gating */
ainf = 1/(1+exp(-(v-thetaa)/sigmaa));
dx[2] = (ainf-a)/taua;
/* update b gating */
binf = 1./(1+exp(-(v-thetab)/sigmab));
dx[3]=(binf-b)/taub;
/* update excitation */
dx[4] = -betae*se; // instantaneous rise, exponential decay
/* update inhibition */
dx[5] = -betai*si;
return GSL_SUCCESS;
}
/* The jacobian
* In case we wanna use implict Burslish-Stoer methods
*/
int jac (double t, const double y[], double *dfdy, double dfdt[], void *params)
{
double mu = *(double *)params;
gsl_matrix_view dfdy_mat = gsl_matrix_view_array (dfdy, 2, 2);
gsl_matrix * m = &dfdy_mat.matrix;
// Si usamos Burlish-Stoer tenemos de dar el Jacobiano
/*gsl_matrix_set (m, 0, 0, 0.0);
gsl_matrix_set (m, 0, 1, 1.0);
gsl_matrix_set (m, 1, 0, -2.0*mu*y[0]*y[1] - 1.0);
gsl_matrix_set (m, 1, 1, -mu*(y[0]*y[0] - 1.0));*/
// Si usamos otro método podemos dejar el jacobiano
// todo a cero.
gsl_matrix_set (m, 0, 0, 0.0);
gsl_matrix_set (m, 0, 0, 0.0);
gsl_matrix_set (m, 0, 0, 0.0);
gsl_matrix_set (m, 0, 0, 0.0);
dfdt[0] = 0.0;
dfdt[1] = 0.0;
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.6068763326,
"avg_line_length": 22.6024096386,
"ext": "c",
"hexsha": "21bc5b237b990651842b5e17719571e78410adde",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-10-27T02:59:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-10-27T02:59:15.000Z",
"max_forks_repo_head_hexsha": "bb6fa4caca128688c30213dd260a25d613bfb8cf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jgoldwyn/Gain-Control-With-IA",
"max_forks_repo_path": "ga.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bb6fa4caca128688c30213dd260a25d613bfb8cf",
"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": "jgoldwyn/Gain-Control-With-IA",
"max_issues_repo_path": "ga.c",
"max_line_length": 116,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "bb6fa4caca128688c30213dd260a25d613bfb8cf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jgoldwyn/Gain-Control-With-IA",
"max_stars_repo_path": "ga.c",
"max_stars_repo_stars_event_max_datetime": "2019-10-19T04:03:31.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-10-19T04:03:31.000Z",
"num_tokens": 2739,
"size": 7504
} |
/* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file mpepc_pose_follower.h
* \author Jong Jin Park
*
* Declaration of MPEPCPoseFollower.
*/
#ifndef MPEPC_POSE_FOLLOWER_H
#define MPEPC_POSE_FOLLOWER_H
#include <mpepc/trajectory/params.h>
#include <mpepc/trajectory/robot_trajectory_info.h>
#include <core/pose.h>
#include <mpepc/control/control_law_coordinates.h>
#include <nlopt.h>
#include <vector>
#include <memory>
namespace vulcan
{
namespace mpepc
{
class RobotSimulator;
class TrajectoryEvaluator;
class TaskManifold;
struct trajectory_planner_debug_info_t;
/**
* MPEPCPoseFollower optimizes velocity gain given a pose to converge to.
*
* The optimizer handles the simulate/evaluate loop internally and finds the optimal
* target along with the intermediate trajectories generated by the optimization
* algorithm. NLopt package is used for the numerical optimzation, and a number of
* different algorithms can be implemented.
*/
class MPEPCPoseFollower
{
public:
/**
* Constructor for MPEPCPoseFollower.
*
* \param params Parameters for the optimization
*/
MPEPCPoseFollower(const mpepc_optimizer_params_t& params);
/**
* Destructor for MPEPCPoseFollower.
*/
~MPEPCPoseFollower(void);
/**
* Setup sets up the optmizer with the robot simulator and trajectory evaluator to be used.
*
* \param simulator RobotSimulator to use for the trajectory generation.
* \param evaluator TrajectoryEvaluator for calculating the cost of a trajectory.
*/
void setup(RobotSimulator& simulator, TrajectoryEvaluator& evaluator); // NOTE: This feels very unsafe. A better way?
/**
* setInitialGuesses adds a goal pose (if navigation task) and the previous optimum
* to the initial guesses for local optimizer.
*
* \param task TaskManifold that contains the goal.
* \param previousMotionTarget Previous output of the metric planner, i.e. the previous optimum.
*/
void setInitialGuesses(const TaskManifold& task,
const motion_target_t& previousMotionTarget);
/**
* run runs the optimizer and finds the best motion target by evaluating the expected
* costs of an estimated trajectory generated from a candidate motion target.
*
* It returns the optimal target found, while the intermediate information including
* all trajectories considered are stored in the provided debug info instance.
*
* \param debugInfo Place to store relevant information
* \return Optimal target found
*/
motion_target_t runOptimizer(trajectory_planner_debug_info_t& debugInfo);
/**
* evaluateCost calculates the cost of a fixed-length trajectory represented by the given optimizer_target_t.
* The length of the trajectory is specified in the given instance of the planner_data_t.
*
* \param coords Optimization variable, currently encoding a target pose in the robot frame and a velocity gain for the kinematic control law.
* \return Cost of the trajectory.
*/
double evaluateCost(const double x[]);
/**
* evaluateGradient calculates the gradient around a particular point, by a simple forward differencing.
*
* \param coords Optimization variable, currently encoding a target pose in the robot frame and a velocity gain for the kinematic control law.
* \param cost Evaluated cost at the given coordinate.
* \param gradient Calculated gradient for each dimension (r, theta, delta, velocity) [output]
*/
void evaluateGradient(const double x[], double cost, double gradient[]);
bool haveFoundSolution(void) const { return haveFoundSolution_; };
// /**
// * evaluateSingleMotionTarget is a method which resets the data and info struct and evaluate a single optimizer target.
// * The optimization_info_t will hold a single trajectory considered. TODO: Do i need this?
// *
// * \param candidateMotionTarget
// * \param data
// * \param info
// */
// double evaluateSingleMotionTarget(const motion_target_t& candidateMotionTarget, const planner_data_t& data, optimization_info_t& info);
private:
// setting up the optimizer
void setupNLOpt(void);
// optimizers
nlopt_opt globalOptimizer;
nlopt_opt localOptimizer;
// simulator and evaluator
RobotSimulator* simulator_;
TrajectoryEvaluator* evaluator_;
robot_trajectory_info_t trajectory;
// debug info
trajectory_planner_debug_info_t* optimizerInfo_;
// inital robot state
pose_t robotPose_;
// target pose to converge to
pose_t targetPose_;
motion_target_t candidateMotionTarget_;
// indicator for finding a right solution
bool haveFoundSolution_;
// parameters
mpepc_optimizer_params_t params_;
};
} // mpepc
} // vulcan
#endif // MPEPC_POSE_FOLLOWER_H
| {
"alphanum_fraction": 0.7160913035,
"avg_line_length": 32.9254658385,
"ext": "h",
"hexsha": "2d5843c6cec787635313867e401180d941e6cc81",
"lang": "C",
"max_forks_count": 11,
"max_forks_repo_forks_event_max_datetime": "2022-01-20T08:56:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-13T00:04:38.000Z",
"max_forks_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "h2ssh/Vulcan",
"max_forks_repo_path": "src/mpepc/trajectory/mpepc_pose_follower.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603",
"max_issues_repo_issues_event_max_datetime": "2021-03-05T08:00:50.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-05T08:00:50.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "h2ssh/Vulcan",
"max_issues_repo_path": "src/mpepc/trajectory/mpepc_pose_follower.h",
"max_line_length": 157,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "cc46ec79fea43227d578bee39cb4129ad9bb1603",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "h2ssh/Vulcan",
"max_stars_repo_path": "src/mpepc/trajectory/mpepc_pose_follower.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-20T08:56:31.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-03-29T09:37:01.000Z",
"num_tokens": 1180,
"size": 5301
} |
#ifndef _EM_DEFS_H_
#define _EM_DEFS_H_ 1
#include <petsc.h>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <complex>
#include <tuple>
typedef std::complex<double> Complex;
typedef std::tuple<int, int> TupleII;
const double PI = 3.14159265358979323846;
const double MU = 4 * PI * 1E-7;
const Complex II = Complex(0.0, 1.0);
const double RTOD = 180.0 / PI;
const double DTOR = PI / 180.0;
const double EPS = 1.0E-6;
const int TX_SIZE = 7;
typedef Eigen::Vector3d Point;
typedef Eigen::Vector3d VectorD;
typedef Eigen::Vector3cd VectorZ;
typedef Eigen::Matrix3d Tensor;
struct PETScBlockVector {
Vec re, im;
};
enum AnisotropicForm { Isotropic = 0, Vertical = 1, Triaxial = 2, Arbitrary = 3 };
enum PolarType { XY_POLAR = -1, YX_POLAR = -2};
enum RefineStrategy { FixedNumber = 0, FixedFraction = 1 };
enum InnerPCType { Mixed = 0, AMS = 1, Direct = 2 };
enum DirectSolverType { MUMPS = 0, SUPERLUDIST = 1 };
enum ObsType {
F_EX_RI = 111,
F_EY_RI = 121,
F_EZ_RI = 131,
F_HX_RI = 141,
F_HY_RI = 151,
F_HZ_RI = 161,
F_EX_AP = 112,
F_EY_AP = 122,
F_EZ_AP = 132,
F_HX_AP = 142,
F_HY_AP = 152,
F_HZ_AP = 162,
R_XY_AP = 212,
R_YX_AP = 222,
Z_XX_RI = 311,
Z_XY_RI = 321,
Z_YX_RI = 331,
Z_YY_RI = 341,
T_ZX_RI = 351,
T_ZY_RI = 361,
Z_XX_AP = 312,
Z_XY_AP = 322,
Z_YX_AP = 332,
Z_YY_AP = 342
};
#define EM_ERR_USER -1
#endif
| {
"alphanum_fraction": 0.6685837527,
"avg_line_length": 18.0649350649,
"ext": "h",
"hexsha": "d12ac0a5dbb900d85d0e4117bad1e59777a29a77",
"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": "9129e28610d7fcb83a88021528575dfeaadad502",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "emfem/emfem",
"max_forks_repo_path": "src/em_defs.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502",
"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": "emfem/emfem",
"max_issues_repo_path": "src/em_defs.h",
"max_line_length": 82,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "emfem/emfem",
"max_stars_repo_path": "src/em_defs.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-03T12:22:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-03T12:22:37.000Z",
"num_tokens": 542,
"size": 1391
} |
/*
* vbHmmTs.c
* Model-specific core functions for VB-HMM-TS.
*
* Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN
* Copyright 2011-2015
* Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.
* All rights reserved.
*
* Ver. 1.1.0
* Last modified on 2015.09.17
*/
#include "vbHmmTs.h"
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_psi.h>
#include <string.h>
#include "rand.h"
#ifdef _OPENMP
#include "omp.h"
#endif
//// Uncomment one/both of the following defenitions to activate constraint on I or/and K.
//#define INTENSITY_CAP
//#define TRANSITION_RATE_CAP
#ifdef INTENSITY_CAP
#define maxIntensityRatio 10.0
#endif
#ifdef TRANSITION_RATE_CAP
#define minPhotonNumPerState 10.0
#endif
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
//static int isGlobalAnalysis = 0;
void setFunctions_ts(){
commonFunctions funcs;
funcs.newModelParameters = newModelParameters_ts;
funcs.freeModelParameters = freeModelParameters_ts;
funcs.newModelStats = newModelStats_ts;
funcs.freeModelStats = freeModelStats_ts;
funcs.initializeVbHmm = initializeVbHmm_ts;
funcs.pTilde_z1 = pTilde_z1_ts;
funcs.pTilde_zn_zn1 = pTilde_zn_zn1_ts;
funcs.pTilde_xn_zn = pTilde_xn_zn_ts;
funcs.calcStatsVars = calcStatsVars_ts;
funcs.maximization = maximization_ts;
funcs.varLowerBound = varLowerBound_ts;
funcs.reorderParameters = reorderParameters_ts;
funcs.outputResults = outputResults_ts;
setFunctions( funcs );
}
//void setGFunctions_ts(){
// gCommonFunctions funcs;
// funcs.newModelParameters = newModelParameters_ts;
// funcs.freeModelParameters = freeModelParameters_ts;
// funcs.newModelStats = newModelStats_ts;
// funcs.freeModelStats = freeModelStats_ts;
// funcs.newModelStatsG = newModelStatsG_ts;
// funcs.freeModelStatsG = freeModelStatsG_ts;
// funcs.initializeVbHmmG = initializeVbHmmG_ts;
// funcs.pTilde_z1 = pTilde_z1_ts;
// funcs.pTilde_zn_zn1 = pTilde_zn_zn1_ts;
// funcs.pTilde_xn_zn = pTilde_xn_zn_ts;
// funcs.calcStatsVarsG = calcStatsVarsG_ts;
// funcs.maximizationG = maximizationG_ts;
// funcs.varLowerBoundG = varLowerBoundG_ts;
// funcs.reorderParametersG = reorderParametersG_ts;
// funcs.outputResultsG = outputResultsG_ts;
// setGFunctions( funcs );
// isGlobalAnalysis = 1;
//}
void outputResults_ts( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
outputTsResults( xn, gv, iv, logFP );
}
//void outputResultsG_ts( xns, gv, ivs, logFP )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//FILE *logFP;
//{
// outputTsResultsG( xns, gv, ivs, logFP );
//}
void *newModelParameters_ts( xn, sNo )
xnDataSet *xn;
int sNo;
{
int i;
tsParameters *p = (void*)malloc( sizeof(tsParameters) );
p->uPiArr = (double*)malloc( sNo * sizeof(double) );
p->sumUPi = 0.0;
// hyperparameter for p( k(i,j) ) (i != j)
p->uKMat = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->uKMat[i] = (double*)malloc( sNo * sizeof(double) );
}
p->sumUKArr = (double*)malloc( sNo * sizeof(double) );
// hyperparameter for p( I(k) )
p->aIArr = (double*)malloc( sNo * sizeof(double) );
p->bIArr = (double*)malloc( sNo * sizeof(double) );
p->avgPi = (double *)malloc( sNo * sizeof(double) );
p->avgLnPi = (double *)malloc( sNo * sizeof(double) );
p->avgI = (double *)malloc( sNo * sizeof(double) );
p->avgLnI = (double *)malloc( sNo * sizeof(double) );
p->avgK = (double **)malloc( sNo * sizeof(double*) );
p->avgLnK = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->avgK[i] = (double *)malloc( sNo * sizeof(double) );
p->avgLnK[i] = (double *)malloc( sNo * sizeof(double) );
}
p->avgLnKI = (double *)malloc( sNo * sizeof(double) );
return p;
}
void freeModelParameters_ts( p, xn, sNo )
void **p;
xnDataSet *xn;
int sNo;
{
tsParameters *gp = *p;
int i;
free( gp->uPiArr );
for( i = 0 ; i < sNo ; i++ ){
free( gp->uKMat[i] );
}
free( gp->uKMat );
free( gp->sumUKArr );
free( gp->aIArr );
free( gp->bIArr );
free( gp->avgPi );
free( gp->avgLnPi );
free( gp->avgI );
free( gp->avgLnI );
for( i = 0 ; i < sNo ; i++ ){
free( gp->avgK[i] );
free( gp->avgLnK[i] );
}
free( gp->avgK );
free( gp->avgLnK );
free( gp->avgLnKI );
free( *p );
*p = NULL;
}
void *newModelStats_ts( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
tsStats *s = (tsStats*)malloc( sizeof(tsStats) );
int i;
s->Ni = (double *)malloc( sNo * sizeof(double) );
s->Ti = (double *)malloc( sNo * sizeof(double) );
s->Nii = (double *)malloc( sNo * sizeof(double) );
s->Nij = (double *)malloc( sNo * sizeof(double) );
s->Mij = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s->Mij[i] = (double *)malloc( sNo * sizeof(double) ); }
return s;
// } else {
//
// return NULL;
//
// }
}
void freeModelStats_ts( s, xn, gv, iv )
void **s;
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
tsStats *gs = *s;
int i;
free( gs->Ni );
free( gs->Ti );
free( gs->Nii );
free( gs->Nij );
for( i = 0 ; i < sNo ; i++ )
{ free( gs->Mij[i] ); }
free( gs->Mij );
free( gs );
*s = NULL;
// }
}
//void *newModelStatsG_ts( xns, gv, ivs)
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
// int sNo = gv->sNo;
// tsGlobalStats *gs = (tsGlobalStats*)malloc( sizeof(tsGlobalStats) );
//
// return gs;
//}
//void freeModelStatsG_ts( gs, xns, gv, ivs )
//void **gs;
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//
// free( *gs );
// *gs = NULL;
//}
void initializeVbHmm_ts( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
tsData *d = xn->data;
int sNo = gv->sNo;
tsParameters *p = gv->params;
int i, j;
// hyperparameter for p( pi(k) )
p->sumUPi = 0.0;
for( i = 0 ; i < sNo ; i++ ){
p->uPiArr[i] = 1.0;
p->sumUPi += p->uPiArr[i];
}
// hyperparameter for p( k(i,j) ) (i != j)
for( i = 0 ; i < sNo ; i++ ){
p->sumUKArr[i] = 0.0;
for( j = 0 ; j < sNo ; j++ ){
p->uKMat[i][j] = 1.0;
if( j != i ){
p->sumUKArr[i] += p->uKMat[i][j];
}
}
}
double meanI = (double)xn->N / d->T;
// hyperparameter for p( I(k) )
for( i = 0 ; i < sNo ; i++ ){
p->aIArr[i] = 1.0;
p->bIArr[i] = 1.0 / meanI;
}
initialize_indVars_ts( xn, gv, iv );
calcStatsVars_ts( xn, gv, iv );
maximization_ts( xn, gv, iv );
}
//void initializeVbHmmG_ts( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void initialize_indVars_ts( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
int i;
size_t n;
double sumPar;
for( n = 0 ; n < dLen ; n++ ){
sumPar = 0.0;
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] = enoise(1.0) + 1.0;
sumPar += gmMat[n][i];
}
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] /= sumPar;
}
}
}
xnDataSet *newXnDataSet_ts( filename )
const char *filename;
{
xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) );
xn->name = (char*)malloc( strlen(filename) + 2 );
strncpy( xn->name, filename, strlen(filename)+1 );
xn->data = (tsData*)malloc( sizeof(tsData) );
tsData *d = (tsData*)xn->data;
d->T = 0.0;
d->dt = NULL;
d->time = NULL;
return xn;
}
void freeXnDataSet_ts( xn )
xnDataSet **xn;
{
tsData *d = (tsData*)(*xn)->data;
free( d->dt );
free( d->time );
free( (*xn)->data );
free( (*xn)->name );
free( *xn );
*xn = NULL;
}
double pTilde_z1_ts( i, params )
int i;
void *params;
{
tsParameters *p = (tsParameters*)params;
return exp( p->avgLnPi[i] );
}
double pTilde_zn_zn1_ts( i, j, params )
int i, j;
void *params;
{
tsParameters *p = (tsParameters*)params;
if( i == j ){
return exp( p->avgLnI[i] - p->avgLnKI[i] );
} else {
return exp( p->avgLnK[i][i] + p->avgLnK[i][j] - p->avgLnKI[i] );
}
}
double pTilde_xn_zn_ts( xnWv, n, i, params )
xnDataSet *xnWv;
size_t n;
int i;
void *params;
{
tsParameters *p = (tsParameters*)params;
tsData *d = (tsData*)xnWv->data;
return exp( p->avgLnI[i] - p->avgI[i] * d->dt[n] );
}
void calcStatsVars_ts( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
tsData *d = (tsData*)xn->data;
tsStats *s = (tsStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *Ni = s->Ni, *Ti = s->Ti;
double *Nii = s->Nii, *Nij = s->Nij, **Mij = s->Mij;
size_t n;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
Ni[i] = 1e-10;
Ti[i] = 1e-10;
Nii[i] = 0.0;
Nij[i] = 0.0;
for( j = 0 ; j < sNo ; j++ ){
Mij[i][j] = 1e-10;
}
}
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){
Ni[i] += gmMat[n][i];
Ti[i] += gmMat[n][i] * d->dt[n];
Nii[i] += xiMat[n][i][i];
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
Mij[i][j] += xiMat[n][i][j];
Nij[i] += xiMat[n][i][j];
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){
Nii[i] = MAX( Nii[i], 1.0 );
Nij[i] = MAX( Nij[i], 1.0 );
}
}
//void calcStatsVarsG_ts( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void maximization_ts( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
tsParameters *p = (tsParameters*)gv->params;
tsStats *s = (tsStats*)iv->stats;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgK = p->avgK, **avgLnK = p->avgLnK;
double *avgLnKI = p->avgLnKI, *avgI = p->avgI, *avgLnI = p->avgLnI;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;
double **uKMat = p->uKMat, *sumUKArr = p->sumUKArr;
double *Ni = s->Ni, *Ti = s->Ti;
double *Nii = s->Nii, *Nij = s->Nij, **Mij = s->Mij;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 );
avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 );
avgK[i][i] = (Ni[i] + aIArr[i]) * Nij[i] / (Nii[i] - 1.0) / (Ti[i] + bIArr[i]);
avgLnK[i][i] = gsl_sf_psi(Ni[i] + aIArr[i]) + gsl_sf_psi(Nij[i]);
avgLnK[i][i] += -gsl_sf_psi(Nii[i]) - log(Ti[i] + bIArr[i]);
avgI[i] = (Ni[i] + aIArr[i]) / (Ti[i] + bIArr[i]);
avgLnI[i] = gsl_sf_psi(Ni[i] + aIArr[i]) - log(Ti[i] + bIArr[i]);
avgLnKI[i] = gsl_sf_psi(Ni[i] + aIArr[i]) + gsl_sf_psi(Nii[i] + Nij[i]);
avgLnKI[i] += -gsl_sf_psi(Nii[i]) - log(Ti[i] + bIArr[i]);
#ifdef INTENSITY_CAP
double meanI = (double)xnWv->N / xnWv->T;
avgI[i] = MIN( avgI[i], maxIntensityRatio * meanI );
avgLnI[i] = MIN( avgLnI[i], log(maxIntensityRatio * meanI) );
#endif
#ifdef TRANSITION_RATE_CAP
avgK[i][i] = MIN( avgK[i][i], avgI[i]/minPhotonNumPerState );
avgLnK[i][i] = MIN( avgLnK[i][i], avgLnI[i] - log(minPhotonNumPerState) );
avgLnKI[i] = MIN( avgLnKI[i], avgLnI[i] + log(1.0 + 1.0/minPhotonNumPerState) );
#endif
for( j = 0 ; j < sNo ; j++ ){
if( i != j ){
avgK[i][j] = ( uKMat[i][j] + Mij[i][j] ) / ( sumUKArr[i] + Nij[i] );
avgLnK[i][j] = gsl_sf_psi( uKMat[i][j] + Mij[i][j] ) - gsl_sf_psi( sumUKArr[i] + Nij[i] );
}
}
}
}
//void maximizationG_ts( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
double varLowerBound_ts( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
tsParameters *p = (tsParameters*)gv->params;
tsStats *s = (tsStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, *cn = iv->cn;
double *avgLnPi = p->avgLnPi, **avgLnK = p->avgLnK;
double *avgLnKI = p->avgLnKI, *avgI = p->avgI, *avgLnI = p->avgLnI;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;
double **uKMat = p->uKMat, *sumUKArr = p->sumUKArr;
double *Ni = s->Ni, *Ti = s->Ti;
double *Nii = s->Nii, *Nij = s->Nij, **Mij = s->Mij;
size_t n;
int i, j;
double lnpPi;
lnpPi = gsl_sf_lngamma(sumUPi);
double Ck = 1.0, lnpKii = (double)sNo * log(Ck);
double lnpKij = 0.0;
double lnpI = 0.0;
double lnqPi;
lnqPi = gsl_sf_lngamma(sumUPi + 1.0);
double lnqKiiI = 0.0;
double lnqKij = 0.0;
for( i = 0 ; i < sNo ; i++ ){
lnpPi += (uPiArr[i]-1) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);
lnpKii -= avgLnK[i][i];
lnpI += aIArr[i] * log(bIArr[i]) - gsl_sf_lngamma(aIArr[i]);
lnpI += (aIArr[i]-1.0)*avgLnI[i] - bIArr[i]*avgI[i];
lnqPi += (uPiArr[i]+gmMat[0][i]-1) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1));
lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]);
lnqKiiI += gsl_sf_lngamma(Nii[i] + Nij[i]) + (Ni[i] + aIArr[i]) * log(Ti[i] + bIArr[i]);
lnqKiiI += -gsl_sf_lngamma(Ni[i] + aIArr[i]) -gsl_sf_lngamma(Nii[i]);
lnqKiiI += -gsl_sf_lngamma(Nij[i]) + (Nij[i]-1.0)*avgLnK[i][i];
lnqKiiI += (Ni[i] + Nii[i] + aIArr[i] - 1.0)*avgLnI[i];
lnqKiiI += -(Nii[i] + Nij[i])*avgLnKI[i] - (Ti[i] + bIArr[i])*avgI[i];
lnpKij += gsl_sf_lngamma(sumUKArr[i]);
lnqKij += gsl_sf_lngamma(sumUKArr[i] + Nij[i]);
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
lnpKij += (uKMat[i][j]-1)*avgLnK[i][j] - gsl_sf_lngamma(uKMat[i][j]);
lnqKij += (uKMat[i][j]+Mij[i][j]-1)*(gsl_sf_psi(uKMat[i][j]+Mij[i][j])-gsl_sf_psi(sumUKArr[i]+Nij[i]));
lnqKij -= gsl_sf_lngamma( uKMat[i][j] + Mij[i][j] );
}
}
}
double lnpX = 0.0;
for( n = 0 ; n < dLen ; n++ ){
lnpX += log( cn[n] );
}
double val;
val = lnpPi + lnpKii + lnpKij + lnpI;
val -= lnqPi + lnqKiiI + lnqKij;
val += lnpX;
val += log(gsl_sf_fact(sNo));
return val;
}
//double varLowerBoundG_ts( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void reorderParameters_ts( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
tsParameters *p = (tsParameters*)gv->params;
tsStats *s = (tsStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgK = p->avgK;
double **avgLnK = p->avgLnK, *avgLnKI = p->avgLnKI;
double *avgI = p->avgI, *avgLnI = p->avgLnI;
double *Ni = s->Ni, *Ti = s->Ti;
size_t n;
int i, j;
int *index = (int*)malloc( sNo * sizeof(int) );
double *store = (double*)malloc( sNo * sizeof(double) );
double **s2D = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s2D[i] = (double*)malloc( sNo * sizeof(double) ); }
// index indicates order of avgI values (0=biggest avgI -- sNo=smallest avgI).
for( i = 0 ; i < sNo ; i++ ){
index[i] = sNo - 1;
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
if( avgI[i] < avgI[j] ){
index[i]--;
} else if( avgI[i] == avgI[j] ){
if( i < j )
{ index[i]--; }
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgI[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgI[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnI[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnI[i] = store[i]; }
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgK[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgK[i][j] = s2D[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnK[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgLnK[i][j] = s2D[i][j]; }
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnKI[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnKI[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ni[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ni[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ti[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ti[i] = store[i]; }
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }
for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }
}
for( n = 0 ; n < dLen ; n++ ){
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }
}
}
for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }
free( s2D );
free( store );
free( index );
}
//void reorderParametersG_ts( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void outputTsResults( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
tsParameters *p = (tsParameters*)gv->params;
int sNo = gv->sNo;
int i, j;
fprintf(logFP, " results: K = %d \n", sNo);
fprintf(logFP, " intensities: ( %g", p->avgI[0]);
for( i = 1 ; i < sNo ; i++ )
{ fprintf(logFP, ", %g", p->avgI[i]); }
fprintf(logFP, " ) \n");
fprintf(logFP, " pi: ( %g", p->avgPi[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgPi[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " k_matrix: [");
for( i = 0 ; i < sNo ; i++ ){
fprintf(logFP, " ( %g", p->avgK[i][0]);
for( j = 1 ; j < sNo ; j++ )
{ fprintf(logFP, ", %g", p->avgK[i][j]); }
fprintf(logFP, ")");
}
fprintf(logFP, " ] \n\n");
char fn[256];
FILE *fp;
size_t n;
sprintf( fn, "%s.param%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
fprintf(fp, "I, pi");
for( i = 0 ; i < sNo ; i++ )
{ fprintf(fp, ", K%dx", i); }
fprintf(fp, "\n");
for( i = 0 ; i < sNo ; i++ ){
fprintf(fp, "%g, %g", p->avgI[i], p->avgPi[i]);
for( j = 0 ; j < sNo ; j++ )
{ fprintf(fp, ", %g", p->avgK[j][i]); }
fprintf(fp, "\n");
}
fclose(fp);
}
sprintf( fn, "%s.Lq%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < gv->iteration ; n++ ){
fprintf( fp, "%24.20e\n", gv->LqArr[n] );
}
fclose(fp);
}
sprintf( fn, "%s.maxS%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < xn->N ; n++ ){
fprintf( fp, "%d\n", iv->stateTraj[n] );
}
fclose(fp);
}
}
//void outputTsResultsG( xns, gv, ivs, logFP )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//FILE *logFP;
//{
//}
//
| {
"alphanum_fraction": 0.498907714,
"avg_line_length": 27.7614555256,
"ext": "c",
"hexsha": "7efd7e768717c88b54d9328760280d10c81517a4",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "okamoto-kenji/varBayes-HMM",
"max_forks_repo_path": "C/vbHmmTs.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "okamoto-kenji/varBayes-HMM",
"max_issues_repo_path": "C/vbHmmTs.c",
"max_line_length": 119,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "okamoto-kenji/varBayes-HMM",
"max_stars_repo_path": "C/vbHmmTs.c",
"max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z",
"num_tokens": 7545,
"size": 20599
} |
#ifndef OPENMC_TALLIES_FILTER_CELL_INSTANCE_H
#define OPENMC_TALLIES_FILTER_CELL_INSTANCE_H
#include <cstdint>
#include <unordered_map>
#include <vector>
#include <gsl/gsl>
#include "openmc/cell.h"
#include "openmc/tallies/filter.h"
namespace openmc {
//==============================================================================
//! Specifies cell instances that tally events reside in.
//==============================================================================
class CellInstanceFilter : public Filter {
public:
//----------------------------------------------------------------------------
// Constructors, destructors
CellInstanceFilter() = default;
CellInstanceFilter(gsl::span<CellInstance> instances);
~CellInstanceFilter() = default;
//----------------------------------------------------------------------------
// Methods
std::string type() const override {return "cellinstance";}
void from_xml(pugi::xml_node node) override;
void get_all_bins(const Particle* p, int estimator, FilterMatch& match)
const override;
void to_statepoint(hid_t filter_group) const override;
std::string text_label(int bin) const override;
//----------------------------------------------------------------------------
// Accessors
const std::vector<CellInstance>& cell_instances() const { return cell_instances_; }
void set_cell_instances(gsl::span<CellInstance> instances);
private:
//----------------------------------------------------------------------------
// Data members
//! The indices of the cells binned by this filter.
std::vector<CellInstance> cell_instances_;
//! A map from cell/instance indices to filter bin indices.
std::unordered_map<CellInstance, gsl::index, CellInstanceHash> map_;
};
} // namespace openmc
#endif // OPENMC_TALLIES_FILTER_CELL_INSTANCE_H
| {
"alphanum_fraction": 0.5589353612,
"avg_line_length": 28.765625,
"ext": "h",
"hexsha": "1b2cdd425e356cadc682b83e74e755fb0910b232",
"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": "8a1b9d0350dcfc036a08023f22daf7c4a508221b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "norberto-schmidt/openmc-surftrack",
"max_forks_repo_path": "include/openmc/tallies/filter_cell_instance.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8a1b9d0350dcfc036a08023f22daf7c4a508221b",
"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": "norberto-schmidt/openmc-surftrack",
"max_issues_repo_path": "include/openmc/tallies/filter_cell_instance.h",
"max_line_length": 85,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "de99faefc93fe46a48fb4c5abcb4b88fe0eec174",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "PullRequest-Agent/openmc",
"max_stars_repo_path": "include/openmc/tallies/filter_cell_instance.h",
"max_stars_repo_stars_event_max_datetime": "2021-07-05T00:08:39.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-05T00:08:39.000Z",
"num_tokens": 340,
"size": 1841
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include <algorithm>
#include <boost/iostreams/categories.hpp>
#include <gsl/gsl>
#include <iosfwd>
#include <vector>
namespace mira
{
class memory_device
{
public:
using char_type = char;
using category = boost::iostreams::seekable_device_tag;
memory_device(std::vector<char>& memory, std::streamoff pos)
: m_pos{ pos }
, m_memory{ memory }
{}
std::streamoff position() const
{
return m_pos;
}
void reset()
{
m_pos = 0;
}
std::streamsize read(char* s, std::streamsize n)
{
// Read up to n characters from the underlying data source
// into the buffer s, returning the number of characters
// read; return -1 to indicate EOF
std::streamsize read = std::min<std::streamsize>(m_memory.size() - m_pos, n);
if (read == 0)
return -1;
std::copy(pointer(), pointer() + gsl::narrow_cast<ptrdiff_t>(read), s);
m_pos += read;
return read;
}
std::streamsize write(const char* s, std::streamsize n)
{
// Write up to n characters to the underlying
// data sink into the buffer s, returning the
// number of characters written
std::streamsize written = 0ll;
if (m_pos != gsl::narrow<std::streamoff>(m_memory.size()))
{
written = std::min<std::streamsize>(n, m_memory.size() - m_pos);
std::copy(s,
s + gsl::narrow_cast<ptrdiff_t>(written),
m_memory.begin() + gsl::narrow_cast<ptrdiff_t>(m_pos));
m_pos += written;
}
if (written < n)
{
m_memory.insert(m_memory.end(), s + written, s + n);
m_pos = gsl::narrow<std::streamoff>(m_memory.size());
}
return n;
}
std::streamoff seek(std::streamoff off, std::ios_base::seekdir way)
{
// Seek to position off and return the new stream
// position. The argument way indicates how off is
// interpretted:
// - std::ios_base::beg indicates an offset from the
// sequence beginning
// - std::ios_base::cur indicates an offset from the
// current character position
// - std::ios_base::end indicates an offset from the
// sequence end
std::streamoff next;
if (way == std::ios_base::beg)
{
next = off;
}
else if (way == std::ios_base::cur)
{
next = m_pos + off;
}
else if (way == std::ios_base::end)
{
next = m_memory.size() + off - 1;
}
else
{
throw std::ios_base::failure("bad seek direction");
}
// Check for errors
if (next < 0 || next > gsl::narrow<std::streamoff>(m_memory.size()))
{
throw std::ios_base::failure("bad seek offset");
}
m_pos = next;
return m_pos;
}
private:
char* pointer()
{
return &m_memory[gsl::narrow_cast<ptrdiff_t>(m_pos)];
}
std::streamoff m_pos{0};
std::vector<char>& m_memory;
};
}
| {
"alphanum_fraction": 0.488006617,
"avg_line_length": 29.25,
"ext": "h",
"hexsha": "181ea343b60c7abe9dedb32b298a3c5a452517ac",
"lang": "C",
"max_forks_count": 16,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z",
"max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "syntheticmagus/mageslam",
"max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/streams/memory_device.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "syntheticmagus/mageslam",
"max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/streams/memory_device.h",
"max_line_length": 89,
"max_stars_count": 70,
"max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "syntheticmagus/mageslam",
"max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/streams/memory_device.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z",
"num_tokens": 808,
"size": 3627
} |
//
// Rpc.hpp
// PretendToWork
//
// Created by tqtifnypmb on 18/12/2017.
// Copyright © 2017 tqtifnypmb. All rights reserved.
//
#pragma once
#include <memory>
#include <vector>
#include <gsl/gsl>
#include <uv.h>
#include "Request.h"
namespace brick
{
class Rpc {
public:
using RpcPeer = uv_handle_t;
using Callback = std::function<void(RpcPeer*, Request req)>;
enum class LoopState: int {
looping = 0,
closing = 1,
closed,
ready
};
Rpc(const char* ip, int port, Callback req_cb);
Rpc(const Rpc&) = delete;
Rpc& operator=(const Rpc&) = delete;
~Rpc();
void send(RpcPeer* peer, const std::string& msg);
void loop();
void close();
void close(RpcPeer* peer);
private:
void onNewConnection(uv_tcp_t* client);
void onNewMsg(uv_stream_t* client, const std::string& msg);
void onHandleClosed(uv_handle_t* handle);
static void connection_cb(uv_stream_t* server, int status);
static void read_cb(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf);
static void close_cb(uv_handle_t*);
static void write_cb(uv_write_t* req, int status);
LoopState state_;
Callback req_cb_;
std::vector<uv_tcp_t*> clients_;
gsl::owner<uv_loop_t*> loop_;
gsl::owner<uv_tcp_t*> server_;
};
} // namespace brick
| {
"alphanum_fraction": 0.6388888889,
"avg_line_length": 21.375,
"ext": "h",
"hexsha": "158a05bf2fe94af741c02f56fcbbdb0afd8de0e5",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tqtifnypmb/brick",
"max_forks_repo_path": "src/rpc/Rpc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tqtifnypmb/brick",
"max_issues_repo_path": "src/rpc/Rpc.h",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "49398f77113c57d4e256e838a5ad6b9a6381de6a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tqtifnypmb/brick",
"max_stars_repo_path": "src/rpc/Rpc.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 379,
"size": 1368
} |
// This random generator is a C++ wrapper for the GNU Scientific Library
// Copyright (C) 2001 Torbjorn Vik
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#ifndef __min_fminimizer_h
#define __min_fminimizer_h
#include <gsl/gsl_errno.h>
#include <gsl/gsl_min.h>
namespace gsl{
//! Derive this class provide a user defined function for minimisation
struct min_f
{
//! This operator must be overridden
virtual double operator()(const double& x)=0;
//! This is the function gsl calls to optimize f
static double f(double x, void *p)
{
return (*(min_f *)p)(x);
}
};
//! Class for minimizing one dimensional functions.
/*!
Usage:
- Create with optional minimize type
- Set with function object and inital bounds
- Loop the iterate function until convergence or maxIterations (extra facility)
- Recover minimum and bounds
*/
class min_fminimizer
{
public:
//! choose between gsl_min_fminimizer_goldensection and gsl_min_fminimizer_brent
min_fminimizer(const gsl_min_fminimizer_type* type=gsl_min_fminimizer_brent) : s(NULL), maxIterations(100), isSet(false)
{
s=gsl_min_fminimizer_alloc(type);
nIterations=0;
if (!s)
{
//error
//cout << "ERROR Couldn't allocate memory for minimizer" << endl;
//throw ?
exit(-1);
}
}
~min_fminimizer(){if (s) gsl_min_fminimizer_free(s);}
//! returns GSL_FAILURE if the interval does not contain a minimum
int set(min_f& function, double minimum, double x_lower, double x_upper)
{
isSet=false;
f.function = &function.f;
f.params = &function;
int status= gsl_min_fminimizer_set(s, &f, minimum, x_lower, x_upper);
if (!status)
{
isSet=true;
nIterations=0;
}
return status;
}
int set_with_values(min_f& function,
double minimum, double f_minimum,
double x_lower,double f_lower,
double x_upper, double f_upper)
{
isSet=false;
f.function = &function.f;
f.params = &function;
int status= gsl_min_fminimizer_set_with_values(s, &f, minimum, f_minimum, x_lower, f_lower, x_upper, f_upper);
if (!status)
{
isSet=true;
nIterations=0;
}
return status;
}
int iterate()
{
assert_set();
int status=gsl_min_fminimizer_iterate(s);
nIterations++;
if (status==GSL_FAILURE)
isConverged=true;
return status;
}
double minimum(){assert_set();return gsl_min_fminimizer_minimum(s);}
double x_upper(){assert_set();return gsl_min_fminimizer_x_upper(s);}
double x_lower(){assert_set();return gsl_min_fminimizer_x_lower(s);}
void SetMaxIterations(int n){maxIterations=n;}
int GetNIterations(){return nIterations;}
bool is_converged(){if (nIterations>=maxIterations) return true; if (isConverged) return true; return false;}
//string name() const;
private:
void assert_set(){if (!isSet)exit(-1);} // Old problem of error handling: TODO
bool isSet;
bool isConverged;
int nIterations;
int maxIterations;
gsl_min_fminimizer* s;
gsl_function f;
};
}; // namespace gsl
#endif //__min_fminimizer_h
| {
"alphanum_fraction": 0.723462917,
"avg_line_length": 29.25,
"ext": "h",
"hexsha": "a4e4ad37a17b6e87cc9f963534a8b0185229654c",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65",
"max_forks_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_forks_repo_name": "entn-at/GlottDNN",
"max_forks_repo_path": "src/gslwrap/min_fminimizer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_issues_repo_name": "entn-at/GlottDNN",
"max_issues_repo_path": "src/gslwrap/min_fminimizer.h",
"max_line_length": 121,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "b7db669d7f34da92ab34742d75a8ba3c70763a65",
"max_stars_repo_licenses": [
"ECL-2.0",
"Apache-2.0"
],
"max_stars_repo_name": "entn-at/GlottDNN",
"max_stars_repo_path": "src/gslwrap/min_fminimizer.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z",
"num_tokens": 969,
"size": 3627
} |
/**
*
* @file pdpotrf.c
*
* PLASMA auxiliary routines
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Jakub Kurzak
* @author Hatem Ltaief
* @author Mathieu Faverge
* @date 2010-11-15
* @generated d Tue Jan 7 11:45:10 2014
*
**/
#include "common.h"
#ifdef USE_MKL
#include <mkl_lapacke.h>
#else
#include <lapacke.h>
#endif
#if defined(USE_OMPEXT)
#include <omp_ext.h>
#endif
#define A(m,n) BLKADDR(A, double, m, n)
/***************************************************************************//**
* Parallel tile Cholesky factorization - dynamic scheduling
**/
void plasma_pdpotrf_quark(PLASMA_enum uplo, PLASMA_desc A)
{
int k, m, n;
int ldak, ldam;
int tempkm, tempmm;
double zone = (double) 1.0;
double mzone = (double)-1.0;
/*
* PlasmaLower
*/
if (uplo == PlasmaLower) {
abort();
}
/*
* PlasmaUpper
*/
else {
for (k = 0; k < A.nt; k++) {
tempkm = k == A.nt-1 ? A.n-k*A.nb : A.nb;
ldak = BLKLDD(A, k);
double *dA = A(k, k);
#if defined(USE_OMPEXT)
omp_set_task_priority(1);
#endif
#pragma omp task depend(inout:dA[0:A.mb*A.mb])
{
LAPACKE_dpotrf_work(LAPACK_COL_MAJOR, lapack_const(PlasmaUpper), tempkm, dA, ldak);
}
for (m = k+1; m < A.nt; m++) {
tempmm = m == A.nt-1 ? A.n-m*A.nb : A.nb;
double *dA = A(k, k);
double *dB = A(k, m);
#pragma omp task depend(in:dA[0:A.mb*A.mb]) depend(inout:dB[0:A.mb*A.mb])
cblas_dtrsm(
CblasColMajor,
(CBLAS_SIDE)PlasmaLeft, (CBLAS_UPLO)PlasmaUpper,
(CBLAS_TRANSPOSE)PlasmaTrans, (CBLAS_DIAG)PlasmaNonUnit,
A.mb, tempmm,
zone, dA, ldak,
dB, ldak);
}
for (m = k+1; m < A.nt; m++) {
tempmm = m == A.nt-1 ? A.n-m*A.nb : A.nb;
ldam = BLKLDD(A, m);
double *dA = A(k, m);
double *dB = A(m, m);
#pragma omp task depend(in:dA[0:A.mb*A.mb]) depend(inout:dB[0:A.mb*A.mb])
{
cblas_dsyrk(
CblasColMajor,
(CBLAS_UPLO)PlasmaUpper, (CBLAS_TRANSPOSE)PlasmaTrans,
tempmm, A.mb,
(-1.0), dA, ldak,
(1.0), dB, ldam);
}
for (n = k+1; n < m; n++) {
double *dA = A(k , n);
double *dB = A(k , m);
double *dC = A(n , m);
#pragma omp task depend(in:dA[0:A.mb*A.mb], dB[0:A.mb*A.mb]) depend(inout:dC[0:A.mb*A.mb])
cblas_dgemm(CblasColMajor, (CBLAS_TRANSPOSE)PlasmaTrans, (CBLAS_TRANSPOSE)PlasmaNoTrans,
A.mb, tempmm, A.mb,
mzone, dA, ldak,
dB, ldak,
zone, dC, A.mb);
}
}
}
}
}
| {
"alphanum_fraction": 0.4526250388,
"avg_line_length": 30.6571428571,
"ext": "c",
"hexsha": "7a7f66d34770ba7b3067a46d30b3ff5313a14cc9",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2021-01-21T11:17:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-06-22T18:44:35.000Z",
"max_forks_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "tianyi93/hpxMP_mirror",
"max_forks_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/src/pdpotrf.c",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e",
"max_issues_repo_issues_event_max_datetime": "2019-10-16T20:43:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-06-18T14:59:09.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "tianyi93/hpxMP_mirror",
"max_issues_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/src/pdpotrf.c",
"max_line_length": 108,
"max_stars_count": 22,
"max_stars_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "tianyi93/hpxMP_mirror",
"max_stars_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/src/pdpotrf.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-08T11:25:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-16T14:39:17.000Z",
"num_tokens": 925,
"size": 3219
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2018-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#pragma once
#include <mcbp/protocol/response.h>
#include <mcbp/protocol/status.h>
#include <nlohmann/json_fwd.hpp>
#include <platform/thread.h>
#include <chrono>
#include <gsl/gsl>
#include <mutex>
#include <queue>
#include <unordered_map>
#include <vector>
class Connection;
class AuthnAuthzServiceTask;
/**
* The ExternalAuthManagerThread class takes care of the scheduling between
* the authentication requests and the responses received.
*
* One of the problems is that we try to communicate between multiple
* frontend threads, which could cause deadlocks. To avoid locking
* problems we're using a dedicated thread to communicate with the
* other threads.
*/
class ExternalAuthManagerThread : public Couchbase::Thread {
public:
ExternalAuthManagerThread() : Couchbase::Thread("mcd:ext_auth") {
}
ExternalAuthManagerThread(const ExternalAuthManagerThread&) = delete;
/**
* The named (external) user logged on to the system
*/
void login(const std::string& user);
/**
* The named (external) user logged off the system
*/
void logoff(const std::string& user);
/**
* Get the list of active users defined in the system
*/
nlohmann::json getActiveUsers() const;
/**
* Add the provided connection to the list of available authentication
* providers
*/
void add(Connection& connection);
/**
* Remove the connection from the list of available providers (the
* connection may not be registered)
*/
void remove(Connection& connection);
/**
* Enqueue a SASL request to the list of requests to send to the
* RBAC provider. NOTE: This method must _NOT_ be called from the
* worker threads as that may result in a deadlock (should be
* called from the tasks execute() method when running on the
* executor threads)
*
* @param request the task to notify when the result comes back
*/
void enqueueRequest(AuthnAuthzServiceTask& request);
/**
* Received an authentication response on the provided connection
*
* @param connection the connection the message was received on
* @param response
*/
void responseReceived(const cb::mcbp::Response& response);
/**
* Request the authentication daemon to stop
*/
void shutdown();
void setPushActiveUsersInterval(std::chrono::microseconds interval) {
activeUsersPushInterval.store(interval);
condition_variable.notify_one();
}
void setRbacCacheEpoch(std::chrono::steady_clock::time_point tp);
/// Check to see if we've got an up to date RBAC entry for the user
bool haveRbacEntryForUser(const std::string& user) const;
protected:
/// The main loop of the thread
void run() override;
/**
* Process all of the requests added by the various SaslTasks by putting
* them into the queue of messages to send to the Authentication Provider.
*/
void processRequestQueue();
/**
* Process all of the response messages enqueued and notify the SaslTask
*/
void processResponseQueue();
/**
* Iterate over all of the connections marked as closed. Generate
* error responses for all outstanding requests; decrement the reference
* count and tell the thread to complete its shutdown logic.
*/
void purgePendingDeadConnections();
/// Push the list of active users to the authentication provider
void pushActiveUsers();
/// Let the daemon thread run as long as this member is set to true
bool running = true;
/// The next value to use in the opaque field
uint32_t next = 0;
/// The map between the opaque field being used and the SaslAuthTask
/// requested the operation
/// Second should be a std pair of a connection and a task, so that
/// when we remove a connection we can iterate over the entire
/// map and create aborts for the one we don't have anymore (or
/// we could redistribute them O:)
std::unordered_map<uint32_t, std::pair<Connection*, AuthnAuthzServiceTask*>>
requestMap;
/// The mutex variable used to protect access to _all_ the internal
/// members
std::mutex mutex;
/// The daemon thread will block and wait on this variable when there
/// isn't any work to do
std::condition_variable condition_variable;
/// A list of available connections to use as authentication providers
std::vector<Connection*> connections;
/**
* All of the various tasks enqueue their SASL request in this queue
* to allow the authentication provider thread to inject them into
* the worker thread (to avoid a possible deadlock)
*/
std::queue<AuthnAuthzServiceTask*> incomingRequests;
/**
* We need to pass the response information from one of the frontend
* thread back to the sasl task, and we'd like to use the same
* logic when we're terminating the connections.
*/
struct AuthResponse {
AuthResponse(uint32_t opaque, std::string payload)
: opaque(opaque),
status(cb::mcbp::Status::Etmpfail),
payload(std::move(payload)) {
}
AuthResponse(uint32_t opaque,
cb::mcbp::Status status,
cb::const_byte_buffer value)
: opaque(opaque),
status(status),
payload(reinterpret_cast<const char*>(value.data()),
value.size()) {
}
uint32_t opaque;
cb::mcbp::Status status;
std::string payload;
};
/**
* All of the various responses is stored within this queue to
* be handled by the daemon thread
*/
std::queue<std::unique_ptr<AuthResponse>> incommingResponse;
std::vector<Connection*> pendingRemoveConnection;
class ActiveUsers {
public:
void login(const std::string& user);
void logoff(const std::string& user);
nlohmann::json to_json() const;
private:
mutable std::mutex mutex;
std::unordered_map<std::string, uint32_t> users;
} activeUsers;
/**
* The interval we'll push the current active users to the external
* authentication service.
*
* The list can't be considered as "absolute" as memcached is a
* highly multithreaded application and we may have disconnects
* happening in multiple threads at the same time and we might
* have login messages waiting to acquire the lock for the map.
* The intention with the list is that we'll poll the users from
* LDAP to check if the group membership has changed since the last
* time we checked. Given that LDAP is an external system and it
* can't push change notifications to our system our guarantee
* is that the change is reflected in memcached at within 2 times
* of the interval we push these users.
*
* We don't need microseconds resolution "in production", but
* we don't want to have our unit tests wait multiple seconds
* for this message to be sent
*/
std::atomic<std::chrono::microseconds> activeUsersPushInterval{
std::chrono::minutes(5)};
/**
* The time point we last sent the list of active users to the auth
* provider
*/
std::chrono::steady_clock::time_point activeUsersLastSent;
/**
* It should be possible for the authentication provider to
* invalidate the entire cache, but we can't simply drop the
* current cache as that would cause all of the connected clients
* to be disconnected. Instead the authentication provider may
* tell us to start requesting a new RBAC entry if the cached
* one is older than a given time point. Combined with the logic
* that we'll push all of the connected users the authentication
* provider can make sure that all of the connections use the
* correct RBAC definition. Ideally we would have stored this
* as a std::chrono::steady_clock::TimePoint, but that don't
* play well with std::atomic, so we're storing the raw
* number of seconds instead.
*/
std::atomic<uint64_t> rbacCacheEpoch{{}};
};
extern std::unique_ptr<ExternalAuthManagerThread> externalAuthManager;
| {
"alphanum_fraction": 0.6753424658,
"avg_line_length": 34.9003984064,
"ext": "h",
"hexsha": "d25291d0131ee00c896b1c54444ce26b3e124f12",
"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": "a3131a099154c39a0f7b0458bf0cc4ea38363a64",
"max_forks_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_forks_repo_name": "vpn03/kv_engine",
"max_forks_repo_path": "daemon/external_auth_manager_thread.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a3131a099154c39a0f7b0458bf0cc4ea38363a64",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_issues_repo_name": "vpn03/kv_engine",
"max_issues_repo_path": "daemon/external_auth_manager_thread.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a3131a099154c39a0f7b0458bf0cc4ea38363a64",
"max_stars_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_stars_repo_name": "vpn03/kv_engine",
"max_stars_repo_path": "daemon/external_auth_manager_thread.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1959,
"size": 8760
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <time.h>
#include <sys/time.h>
#include <gsl/gsl_math.h>
#include "cosmocalc.h"
double wtime(void)
{
struct timeval tp;
gettimeofday(&tp,NULL);
return ((double) (tp.tv_sec)) + ((double) (tp.tv_usec))/1e6;
}
#define EPS 3.0e-11
void gauleg(double x1, double x2, double x[], double w[], int n)
{
int m,j,i;
double z1,z,xm,xl,pp,p3,p2,p1;
m=(n+1)/2;
xm=0.5*(x2+x1);
xl=0.5*(x2-x1);
for (i=1;i<=m;i++) {
z=cos(3.141592654*(i-0.25)/(n+0.5));
do {
p1=1.0;
p2=0.0;
for (j=1;j<=n;j++) {
p3=p2;
p2=p1;
p1=((2.0*j-1.0)*z*p2-(j-1.0)*p3)/j;
}
pp=n*(z*p1-p2)/(z*z-1.0);
z1=z;
z=z1-p1/pp;
} while (fabs(z-z1) > EPS);
x[i]=xm-xl*z;
x[n+1-i]=xm+xl*z;
w[i]=2.0*xl/((1.0-z*z)*pp*pp);
w[n+1-i]=w[i];
}
}
#undef EPS
| {
"alphanum_fraction": 0.5221843003,
"avg_line_length": 18.3125,
"ext": "c",
"hexsha": "9ae41010185a3d6632d2afd4093c21e5aec57e38",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z",
"max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "beckermr/cosmocalc",
"max_forks_repo_path": "src/utils.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "beckermr/cosmocalc",
"max_issues_repo_path": "src/utils.c",
"max_line_length": 64,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "beckermr/cosmocalc",
"max_stars_repo_path": "src/utils.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 382,
"size": 879
} |
/*
** parse second level design file
**
** G.Lohmann
*/
#include <viaio/Vlib.h>
#include <viaio/VImage.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
extern int VStringToken(char *, char *, int, int);
#define LEN 10000
int test_ascii(int val)
{
if (val >= 'a' && val <= 'z') return 1;
if (val >= 'A' && val <= 'Z') return 1;
if (val >= '0' && val <= '9') return 1;
if (val == ' ') return 1;
if (val == '\0') return 1;
if (val == '\n') return 1;
if (val == '\r') return 1;
if (val == '\t') return 1;
if (val == '\v') return 1;
if (val == '-') return 1;
if (val == '+') return 1;
if (val == '.') return 1;
return 0;
}
int line_empty(char *buf,int len)
{
int i;
for (i=0; i<len; i++) {
if (buf[i] != ' ' && buf[i] != '\n' && buf[i] != 0) return 0;
}
return 1;
}
int CheckBuffer(char *buf,int len)
{
int j;
if(strlen(buf) < 1) return 0;
if (buf[0] == '%' || buf[0] == '#' || buf[0] == '/' || buf[0] == '\n') return 0;
/* remove tabs */
for (j=0; j<len; j++) {
if (buf[0] == '\t') buf[j] = ' ';
}
if (line_empty(buf,len) > 0) return 0;
return 1;
}
int VistaFormat(char *buf,int len)
{
if (strncmp(buf,"V-data",6) == 0) return 1;
return 0;
}
/*
** read a 2nd level design file
*/
gsl_matrix *XRead2ndLevel(VString filename)
{
int i, j, nrows, ncols;
double val;
char buf[LEN], token[32];
fprintf(stderr," Reading %s\n",filename);
FILE *fp = VOpenInputFile (filename, TRUE);
if (!fp) VError(" error opening %s",filename);
nrows = ncols = 0;
while(!feof(fp)) {
memset(buf, 0, LEN);
if(!fgets(buf, LEN, fp)) continue;
if (VistaFormat(buf,LEN) > 0) VError(" Design file must be a text file");
if (CheckBuffer(buf,LEN) < 1) continue;
if (! test_ascii((int)buf[0])) VError(" Design file must be a text file");
j = 0;
while(VStringToken(buf, token, j, 30)) {
if(!sscanf(token, "%lf", &val))
VError("illegal text string in design file: %s", buf);
j++;
}
if (ncols == 0) ncols = j;
if (j < 1) continue;
else if(ncols != j)
VError(" inconsistent number of columns in row %d", nrows + 1);
nrows++;
}
rewind(fp);
/* fill design matrix */
gsl_matrix *X = gsl_matrix_calloc(nrows,ncols);
i = 0;
while(!feof(fp)) {
memset(buf, 0, LEN);
if(!fgets(buf, LEN, fp)) continue;
if (CheckBuffer(buf,LEN) < 1) continue;
j = 0;
while(VStringToken(buf, token, j, 30)) {
sscanf(token, "%lf", &val);
gsl_matrix_set(X,i,j,val);
j++;
}
if (j < 1) continue;
i++;
}
fclose(fp);
return X;
}
/* read exchangeability file */
void XReadExchange(VString filename,int *exchange,int n)
{
int len=1024;
char token[32];
char *buf = (char *)VCalloc(len,sizeof(char));
FILE *fp = VOpenInputFile (filename, TRUE);
if (!fp) VError(" error opening %s",filename);
fprintf(stderr," Reading %s\n",filename);
int nrows = 0;
while(!feof(fp)) {
memset(buf, 0, len);
if(!fgets(buf, len, fp)) break;
if (VistaFormat(buf,LEN) > 0) VError(" Exchangeability file must be a text file");
if (CheckBuffer(buf,LEN) < 1) continue;
if (! test_ascii((int)buf[0])) VError(" Exchangeability file must be a text file");
nrows++;
}
rewind(fp);
if (nrows != n)
VError(" Number of rows in exchangeability file (%d) does not match number of rows in design file (%d)",nrows,n);
int i=0,j=0,k=0;
while(!feof(fp)) {
memset(buf, 0, len);
if(!fgets(buf, len, fp)) break;
if (CheckBuffer(buf,LEN) < 1) continue;
k = 0;
while(VStringToken(buf, token, k, 30)) {
if (!sscanf(token, "%d", &j))
VError("illegal text string in exchangeability file: %s", buf);
if (j < 0) VError(" Values in exchangeability file must be non-negative");
if (j > n) VError(" Illegal value (%d) in exchangeability file, values must be <= %d",j,n);
exchange[i] = j;
k++;
}
if (k > 1) VError(" Exchangeability file must have exactly one column");
i++;
}
VFree(buf);
fclose(fp);
}
/*
int main()
{
int i,j;
gsl_matrix *X = XRead2ndLevel("bla.mat");
fprintf(stderr,"X:\n");
for (i=0; i<X->size1; i++) {
for (j=0; j<X->size2; j++) {
fprintf(stderr," %.2f",gsl_matrix_get(X,i,j));
}
fprintf(stderr,"\n");
}
fprintf(stderr,"\n");
exit(0);
}
*/
| {
"alphanum_fraction": 0.5644364616,
"avg_line_length": 22.0495049505,
"ext": "c",
"hexsha": "2c3a4a3a0d7dbd2d9bdcdff9d72e89211a5ea43d",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/stats/vlisa_2ndlevel/Read2ndLevelDesign.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/stats/vlisa_2ndlevel/Read2ndLevelDesign.c",
"max_line_length": 117,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/stats/vlisa_2ndlevel/Read2ndLevelDesign.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": 1475,
"size": 4454
} |
/* Copyright (c) 2011-2012, Jérémy Fix. All rights reserved. */
/* Redistribution and use in source and binary forms, with or without */
/* modification, are permitted provided that the following conditions are met: */
/* * Redistributions of source code must retain the above copyright notice, */
/* this list of conditions and the following disclaimer. */
/* * Redistributions in binary form must reproduce the above copyright notice, */
/* this list of conditions and the following disclaimer in the documentation */
/* and/or other materials provided with the distribution. */
/* * None of the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. */
/* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE */
/* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL */
/* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */
/* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */
/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */
/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#ifndef UKF_SAMPLES_H
#define UKF_SAMPLES_H
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sort_vector_double.h>
#include <gsl/gsl_permute_vector.h>
#include <gsl/gsl_randist.h>
#include <time.h>
#include <iostream>
namespace ukf
{
namespace samples
{
/**
* @short Generate 1D samples according to a uniform distribution :
* @brief In fact, gsl_ran_choose would do the job!!
*/
class RandomSample_1D
{
public:
static void generateSample(gsl_vector * samples, unsigned int nb_samples, double min, double max, double delta)
{
if(samples->size != nb_samples)
{
std::cerr << "[ERROR] RandomSample_1D : samples should be allocated to the size of the requested number of samples" << std::endl;
return;
}
for(unsigned int i = 0 ; i < nb_samples ; i++)
gsl_vector_set(samples, i, min + floor((max - min)*rand()/double(RAND_MAX)/delta) * delta );
}
};
/**
* @short Generate 2D samples according to a uniform distribution
* and put them alternativaly at the odd/even positions
*/
class RandomSample_2D
{
public:
static void generateSample(gsl_vector * samples, unsigned int nb_samples, double minx, double maxx, double deltax, double miny, double maxy, double deltay)
{
if(samples->size != 2*nb_samples)
{
std::cerr << "[ERROR] RandomSample_2D : samples should be allocated to the size of the 2 times the requested number of samples" << std::endl;
return;
}
gsl_vector_view vec_view = gsl_vector_subvector_with_stride (samples, 0, 2, nb_samples);
RandomSample_1D::generateSample(&vec_view.vector, nb_samples, minx, maxx, deltax);
vec_view = gsl_vector_subvector_with_stride (samples, 1, 2, nb_samples);
RandomSample_1D::generateSample(&vec_view.vector, nb_samples, miny, maxy, deltay);
}
};
/**
* @short Generate 3D samples according to a uniform distribution
* and put them alternativaly at the odd/even positions
*/
class RandomSample_3D
{
public:
static void generateSample(gsl_vector * samples, unsigned int nb_samples, double minx, double maxx, double deltax, double miny, double maxy, double deltay, double minz, double maxz, double deltaz)
{
if(samples->size != 3*nb_samples)
{
std::cerr << "[ERROR] RandomSample_2D : samples should be allocated to the size of the 2 times the requested number of samples" << std::endl;
return;
}
gsl_vector_view vec_view = gsl_vector_subvector_with_stride (samples, 0, 3, nb_samples);
RandomSample_1D::generateSample(&vec_view.vector, nb_samples, minx, maxx, deltax);
vec_view = gsl_vector_subvector_with_stride (samples, 1, 3, nb_samples);
RandomSample_1D::generateSample(&vec_view.vector, nb_samples, miny, maxy, deltay);
vec_view = gsl_vector_subvector_with_stride (samples, 2, 3, nb_samples);
RandomSample_1D::generateSample(&vec_view.vector, nb_samples, minz, maxz, deltaz);
}
};
/**
* @short Extract the indexes of the nb_samples highest values of a vector
* Be carefull, this function is extracting the indexes as, the way it is used, it doesn't not to which sample a vector index corresponds
*/
class MaximumIndexes_1D
{
public:
static void generateSample(gsl_vector * v, gsl_vector * indexes_samples, unsigned int nb_samples)
{
if(indexes_samples->size != nb_samples)
{
std::cerr << "[ERROR] MaximumIndexes_1D : samples should be allocated to the size of the requested number of samples" << std::endl;
return;
}
if(nb_samples > v->size)
{
std::cerr << "[ERROR] MaximumIndexes_1D : the vector v must hold at least nb_samples elements" << std::endl;
return;
}
gsl_permutation * p = gsl_permutation_alloc(v->size);
gsl_sort_vector_index(p,v);
for(unsigned int i = 0 ; i < nb_samples ; i++)
gsl_vector_set(indexes_samples, i, gsl_permutation_get(p, p->size - i - 1));
gsl_permutation_free(p);
}
};
/**
* @short Extract the indexes of the nb_samples highest values of a matrix
* Be carefull, this function is extracting the indexes as, the way it is used, it doesn't not to which sample a vector index corresponds
*/
class MaximumIndexes_2D
{
public:
static void generateSample(gsl_matrix * m, gsl_vector * indexes_samples, unsigned int nb_samples)
{
if(indexes_samples->size != 2*nb_samples)
{
std::cerr << "[ERROR] MaximumIndexes_2D : samples should be allocated to the size of 2 times the requested number of samples" << std::endl;
return;
}
if(nb_samples > m->size1 * m->size2 )
{
std::cerr << "[ERROR] MaximumIndexes_2D : the vector v must hold at least nb_samples elements" << std::endl;
return;
}
gsl_permutation * p = gsl_permutation_alloc(m->size1 * m->size2);
// We cast the matrix in a vector ordered in row-major and get the permutation to order the data by increasing value
gsl_vector_view vec_view = gsl_vector_view_array(m->data,m->size1 * m->size2);
gsl_sort_vector_index(p,&vec_view.vector);
// The indexes stored in p are in row-major order
// we then convert the nb_samples first indexes into matrix indexes and copy them in indexes_samples
int k,l;
for(unsigned int i = 0 ; i < nb_samples ; i++)
{
// Line
k = gsl_permutation_get(p,p->size - i - 1) / m->size2;
// Column
l = gsl_permutation_get(p,p->size - i - 1) % m->size2;
gsl_vector_set(indexes_samples, 2 * i, k);
gsl_vector_set(indexes_samples, 2 * i + 1, l);
}
gsl_permutation_free(p);
}
};
/**
* @short Generate 1D samples according to a discrete vectorial distribution
*/
class DistributionSample_1D
{
public:
static void generateSample(gsl_vector * v, gsl_vector * indexes_samples, unsigned int nb_samples)
{
if(indexes_samples->size != nb_samples)
{
std::cerr << "[ERROR] RandomSample_1D : samples should be allocated to the size of the requested number of samples" << std::endl;
return;
}
// Generating nb_samples samples from an array of weights for each index is easily done in the gsl with gsl_ran_discrete_* methods
// the weights v do not need to add up to one
gsl_rng * r = gsl_rng_alloc(gsl_rng_default);
// Init the random seed
gsl_rng_set(r, time(NULL));
gsl_ran_discrete_t * ran_pre = gsl_ran_discrete_preproc(v->size, v->data);
for(unsigned int i = 0 ; i < nb_samples ; i++)
gsl_vector_set(indexes_samples, i , gsl_ran_discrete(r, ran_pre));
gsl_ran_discrete_free(ran_pre);
gsl_rng_free(r);
}
};
/**
* @short Generate 2D samples according to a discrete matricial distribution
*/
class DistributionSample_2D
{
public:
static void generateSample(gsl_matrix * m, gsl_vector * indexes_samples, unsigned int nb_samples)
{
if(indexes_samples->size != 2*nb_samples)
{
std::cerr << "[ERROR] RandomSample_1D : samples should be allocated to the size of the requested number of samples" << std::endl;
return;
}
// To generate 2D samples according to a matrix of weights
// we simply cast the matrix into a vector, ask DistributionSample_1D to do the job
// and then convert the linear row-major indexes back into 2D indexes
gsl_vector * samples_tmp = gsl_vector_alloc(nb_samples);
gsl_vector_view vec_view = gsl_vector_view_array(m->data,m->size1 * m->size2);
DistributionSample_1D::generateSample(&vec_view.vector, samples_tmp, nb_samples);
int k,l;
for(unsigned int i = 0 ; i < nb_samples ; i++)
{
k = int(gsl_vector_get(samples_tmp,i)) / m->size2;
l = int(gsl_vector_get(samples_tmp,i)) % m->size2;
gsl_vector_set(indexes_samples, 2*i, k);
gsl_vector_set(indexes_samples, 2*i+1, l);
}
gsl_vector_free(samples_tmp);
}
};
}
}
#endif // UKF_SAMPLES_H
| {
"alphanum_fraction": 0.5905932656,
"avg_line_length": 45.6341463415,
"ext": "h",
"hexsha": "e5afd0e7f5115350ab7e0f81e0677ec4f24e3f47",
"lang": "C",
"max_forks_count": 52,
"max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z",
"max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "bahia14/C-Kalman-filtering",
"max_forks_repo_path": "src/ukf_samples.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a",
"max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "bahia14/C-Kalman-filtering",
"max_issues_repo_path": "src/ukf_samples.h",
"max_line_length": 208,
"max_stars_count": 101,
"max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "bahia14/C-Kalman-filtering",
"max_stars_repo_path": "src/ukf_samples.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z",
"num_tokens": 2424,
"size": 11226
} |
// Computational routines for one-dimensional orthogonal polynomial transforms.
#ifndef FASTTRANSFORMS_H
#define FASTTRANSFORMS_H
#include <stdlib.h>
#include <math.h>
#include <immintrin.h>
#include <cblas.h>
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#define omp_get_num_threads() 1
#endif
#define M_SQRT_PI 1.772453850905516027 /* sqrt(pi) */
#define M_1_SQRT_PI 0.564189583547756287 /* 1/sqrt(pi) */
#define M_SQRT_PI_2 0.886226925452758014 /* sqrt(pi)/2 */
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
#if __SSE2__
#define VECTOR_SIZE_2 2
typedef double double2 __attribute__ ((vector_size (VECTOR_SIZE_2*8)));
#define vall2(x) ((double2) _mm_set1_pd(x))
#define vload2(v) ((double2) _mm_loadu_pd(v))
#define vstore2(u, v) (_mm_storeu_pd(u, v))
#endif
#if __AVX__
#define VECTOR_SIZE_4 4
typedef double double4 __attribute__ ((vector_size (VECTOR_SIZE_4*8)));
#define vall4(x) ((double4) _mm256_set1_pd(x))
#define vload4(v) ((double4) _mm256_loadu_pd(v))
#define vstore4(u, v) (_mm256_storeu_pd(u, v))
#endif
#if __AVX512F__
#define VECTOR_SIZE_8 8
typedef double double8 __attribute__ ((vector_size (VECTOR_SIZE_8*8)));
#define vall8(x) ((double8) _mm512_set1_pd(x))
#define vload8(v) ((double8) _mm512_loadu_pd(v))
#define vstore8(u, v) (_mm512_storeu_pd(u, v))
#endif
static inline double stirlingseries(const double z);
static inline double Aratio(const int n, const double alpha, const double beta);
static inline double Analphabeta(const int n, const double alpha, const double beta);
static inline double lambda(const double x);
static inline double lambda2(const double x, const double l1, const double l2);
double * plan_leg2cheb(const int normleg, const int normcheb, const int n);
double * plan_cheb2leg(const int normcheb, const int normleg, const int n);
double * plan_ultra2ultra(const int normultra1, const int normultra2, const int n, const double lambda1, const double lambda2);
double * plan_jac2jac(const int normjac1, const int normjac2, const int n, const double alpha, const double beta, const double gamma);
typedef struct {
double * s;
double * c;
int n;
} RotationPlan;
void freeRotationPlan(RotationPlan * RP);
RotationPlan * plan_rotsphere(const int n);
void kernel_sph_hi2lo(const RotationPlan * RP, const int m, double * A);
void kernel_sph_lo2hi(const RotationPlan * RP, const int m, double * A);
void kernel_sph_hi2lo_SSE(const RotationPlan * RP, const int m, double * A);
void kernel_sph_lo2hi_SSE(const RotationPlan * RP, const int m, double * A);
void kernel_sph_hi2lo_AVX(const RotationPlan * RP, const int m, double * A);
void kernel_sph_lo2hi_AVX(const RotationPlan * RP, const int m, double * A);
void kernel_sph_hi2lo_AVX512(const RotationPlan * RP, const int m, double * A);
void kernel_sph_lo2hi_AVX512(const RotationPlan * RP, const int m, double * A);
RotationPlan * plan_rottriangle(const int n, const double alpha, const double beta, const double gamma);
void kernel_tri_hi2lo(const RotationPlan * RP, const int m, double * A);
void kernel_tri_lo2hi(const RotationPlan * RP, const int m, double * A);
void kernel_tri_hi2lo_SSE(const RotationPlan * RP, const int m, double * A);
void kernel_tri_lo2hi_SSE(const RotationPlan * RP, const int m, double * A);
void kernel_tri_hi2lo_AVX(const RotationPlan * RP, const int m, double * A);
void kernel_tri_lo2hi_AVX(const RotationPlan * RP, const int m, double * A);
void kernel_tri_hi2lo_AVX512(const RotationPlan * RP, const int m, double * A);
void kernel_tri_lo2hi_AVX512(const RotationPlan * RP, const int m, double * A);
RotationPlan * plan_rotdisk(const int n);
void kernel_disk_hi2lo(const RotationPlan * RP, const int m, double * A);
void kernel_disk_lo2hi(const RotationPlan * RP, const int m, double * A);
void kernel_disk_hi2lo_SSE(const RotationPlan * RP, const int m, double * A);
void kernel_disk_lo2hi_SSE(const RotationPlan * RP, const int m, double * A);
void kernel_disk_hi2lo_AVX(const RotationPlan * RP, const int m, double * A);
void kernel_disk_lo2hi_AVX(const RotationPlan * RP, const int m, double * A);
void kernel_disk_hi2lo_AVX512(const RotationPlan * RP, const int m, double * A);
void kernel_disk_lo2hi_AVX512(const RotationPlan * RP, const int m, double * A);
typedef struct {
double * s1;
double * c1;
double * s2;
double * c2;
double * s3;
double * c3;
int n;
int s;
} SpinRotationPlan;
void freeSpinRotationPlan(SpinRotationPlan * SRP);
SpinRotationPlan * plan_rotspinsphere(const int n, const int s);
void kernel_spinsph_hi2lo(const SpinRotationPlan * SRP, const int m, double * A);
void kernel_spinsph_lo2hi(const SpinRotationPlan * SRP, const int m, double * A);
void kernel_spinsph_hi2lo_SSE(const SpinRotationPlan * SRP, const int m, double * A);
void kernel_spinsph_lo2hi_SSE(const SpinRotationPlan * SRP, const int m, double * A);
void kernel_spinsph_hi2lo_AVX(const SpinRotationPlan * SRP, const int m, double * A);
void kernel_spinsph_lo2hi_AVX(const SpinRotationPlan * SRP, const int m, double * A);
void kernel_spinsph_hi2lo_AVX512(const SpinRotationPlan * SRP, const int m, double * A);
void kernel_spinsph_lo2hi_AVX512(const SpinRotationPlan * SRP, const int m, double * A);
static inline void apply_givens(const double S, const double C, double * X, double * Y);
static inline void apply_givens_t(const double S, const double C, double * X, double * Y);
static inline void apply_givens_SSE(const double S, const double C, double * X, double * Y);
static inline void apply_givens_t_SSE(const double S, const double C, double * X, double * Y);
static inline void apply_givens_AVX(const double S, const double C, double * X, double * Y);
static inline void apply_givens_t_AVX(const double S, const double C, double * X, double * Y);
static inline void apply_givens_AVX512(const double S, const double C, double * X, double * Y);
static inline void apply_givens_t_AVX512(const double S, const double C, double * X, double * Y);
void execute_sph_hi2lo(const RotationPlan * RP, double * A, const int M);
void execute_sph_lo2hi(const RotationPlan * RP, double * A, const int M);
void execute_sph_hi2lo_SSE(const RotationPlan * RP, double * A, double * B, const int M);
void execute_sph_lo2hi_SSE(const RotationPlan * RP, double * A, double * B, const int M);
void execute_sph_hi2lo_AVX(const RotationPlan * RP, double * A, double * B, const int M);
void execute_sph_lo2hi_AVX(const RotationPlan * RP, double * A, double * B, const int M);
void execute_sph_hi2lo_AVX512(const RotationPlan * RP, double * A, double * B, const int M);
void execute_sph_lo2hi_AVX512(const RotationPlan * RP, double * A, double * B, const int M);
void execute_tri_hi2lo(const RotationPlan * RP, double * A, const int M);
void execute_tri_lo2hi(const RotationPlan * RP, double * A, const int M);
void execute_tri_hi2lo_SSE(const RotationPlan * RP, double * A, double * B, const int M);
void execute_tri_lo2hi_SSE(const RotationPlan * RP, double * A, double * B, const int M);
void execute_tri_hi2lo_AVX(const RotationPlan * RP, double * A, double * B, const int M);
void execute_tri_lo2hi_AVX(const RotationPlan * RP, double * A, double * B, const int M);
void execute_tri_hi2lo_AVX512(const RotationPlan * RP, double * A, double * B, const int M);
void execute_tri_lo2hi_AVX512(const RotationPlan * RP, double * A, double * B, const int M);
void execute_disk_hi2lo(const RotationPlan * RP, double * A, const int M);
void execute_disk_lo2hi(const RotationPlan * RP, double * A, const int M);
void execute_disk_hi2lo_SSE(const RotationPlan * RP, double * A, double * B, const int M);
void execute_disk_lo2hi_SSE(const RotationPlan * RP, double * A, double * B, const int M);
void execute_disk_hi2lo_AVX(const RotationPlan * RP, double * A, double * B, const int M);
void execute_disk_lo2hi_AVX(const RotationPlan * RP, double * A, double * B, const int M);
void execute_disk_hi2lo_AVX512(const RotationPlan * RP, double * A, double * B, const int M);
void execute_disk_lo2hi_AVX512(const RotationPlan * RP, double * A, double * B, const int M);
void execute_spinsph_hi2lo(const SpinRotationPlan * SRP, double * A, const int M);
void execute_spinsph_lo2hi(const SpinRotationPlan * SRP, double * A, const int M);
void execute_spinsph_hi2lo_SSE(const SpinRotationPlan * SRP, double * A, double * B, const int M);
void execute_spinsph_lo2hi_SSE(const SpinRotationPlan * SRP, double * A, double * B, const int M);
void execute_spinsph_hi2lo_AVX(const SpinRotationPlan * SRP, double * A, double * B, const int M);
void execute_spinsph_lo2hi_AVX(const SpinRotationPlan * SRP, double * A, double * B, const int M);
void execute_spinsph_hi2lo_AVX512(const SpinRotationPlan * SRP, double * A, double * B, const int M);
void execute_spinsph_lo2hi_AVX512(const SpinRotationPlan * SRP, double * A, double * B, const int M);
typedef struct {
RotationPlan * RP;
double * B;
double * P1;
double * P2;
double * P1inv;
double * P2inv;
} SphericalHarmonicPlan;
void freeSphericalHarmonicPlan(SphericalHarmonicPlan * P);
SphericalHarmonicPlan * plan_sph2fourier(const int n);
void execute_sph2fourier(const SphericalHarmonicPlan * P, double * A, const int N, const int M);
void execute_fourier2sph(const SphericalHarmonicPlan * P, double * A, const int N, const int M);
typedef struct {
RotationPlan * RP;
double * B;
double * P1;
double * P2;
double * P3;
double * P4;
double * P1inv;
double * P2inv;
double * P3inv;
double * P4inv;
double alpha;
double beta;
double gamma;
} TriangularHarmonicPlan;
void freeTriangularHarmonicPlan(TriangularHarmonicPlan * P);
TriangularHarmonicPlan * plan_tri2cheb(const int n, const double alpha, const double beta, const double gamma);
void execute_tri2cheb(const TriangularHarmonicPlan * P, double * A, const int N, const int M);
void execute_cheb2tri(const TriangularHarmonicPlan * P, double * A, const int N, const int M);
static void alternate_sign(double * A, const int N);
static void chebyshev_normalization(double * A, const int N, const int M);
static void chebyshev_normalization_t(double * A, const int N, const int M);
void permute(const double * A, double * B, const int N, const int M, const int L);
void permute_t(double * A, const double * B, const int N, const int M, const int L);
void permute_sph(const double * A, double * B, const int N, const int M, const int L);
void permute_t_sph(double * A, const double * B, const int N, const int M, const int L);
void permute_tri(const double * A, double * B, const int N, const int M, const int L);
void permute_t_tri(double * A, const double * B, const int N, const int M, const int L);
#define permute_disk(A, B, N, M, L) permute_sph(A, B, N, M, L)
#define permute_t_disk(A, B, N, M, L) permute_t_sph(A, B, N, M, L)
#define permute_spinsph(A, B, N, M, L) permute_sph(A, B, N, M, L)
#define permute_t_spinsph(A, B, N, M, L) permute_t_sph(A, B, N, M, L)
void swap(double * A, double * B, const int N);
void warp(double * A, const int N, const int M, const int L);
void warp_t(double * A, const int N, const int M, const int L);
#endif //FASTTRANSFORMS_H
| {
"alphanum_fraction": 0.736114802,
"avg_line_length": 43.0877862595,
"ext": "h",
"hexsha": "2ff8913c3b4fd974fb6d063ba3ae1fec71c284cc",
"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": "4b1ef29c950c61e4a6344951b9627267e69cf43f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dawese/FastTransforms",
"max_forks_repo_path": "src/fasttransforms.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4b1ef29c950c61e4a6344951b9627267e69cf43f",
"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": "dawese/FastTransforms",
"max_issues_repo_path": "src/fasttransforms.h",
"max_line_length": 134,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "4b1ef29c950c61e4a6344951b9627267e69cf43f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dawese/FastTransforms",
"max_stars_repo_path": "src/fasttransforms.h",
"max_stars_repo_stars_event_max_datetime": "2018-06-15T02:50:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-15T02:50:55.000Z",
"num_tokens": 3301,
"size": 11289
} |
#pragma once
#include <gsl/string_span.h>
using zstr = gsl::zstring<>;
using czstr = gsl::czstring<>;
using zwstr = gsl::wzstring<>;
using czwstr = gsl::cwzstring<>;
| {
"alphanum_fraction": 0.6904761905,
"avg_line_length": 18.6666666667,
"ext": "h",
"hexsha": "a9e9e57120d79bec480f78b42dbcf7e3a351b899",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-06-17T16:46:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-08-28T14:37:01.000Z",
"max_forks_repo_head_hexsha": "62e2722eba1b75ef82f7c1328585873d08bb41cc",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "lcmftianci/licodeanalysis",
"max_forks_repo_path": "StormWebrtc/External/sb/cstr.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "62e2722eba1b75ef82f7c1328585873d08bb41cc",
"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": "lcmftianci/licodeanalysis",
"max_issues_repo_path": "StormWebrtc/External/sb/cstr.h",
"max_line_length": 32,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "62e2722eba1b75ef82f7c1328585873d08bb41cc",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "lcmftianci/licodeanalysis",
"max_stars_repo_path": "StormWebrtc/External/sb/cstr.h",
"max_stars_repo_stars_event_max_datetime": "2019-12-24T14:29:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-17T14:01:21.000Z",
"num_tokens": 54,
"size": 168
} |
/*
NAME:
bovy_randvec
PURPOSE:
returns a (uniform) random vector with a maximum length
CALLING SEQUENCE:
bovy_randvec(gsl_vector * eps, int d, double length)
INPUT:
d - dimension of the vector
length - maximum length of the random vector
OUTPUT:
eps - random vector
REVISION HISTORY:
2008-09-21
*/
#include <math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_rng.h>
#include <proj_gauss_mixtures.h>
void bovy_randvec(gsl_vector * eps, int d, double length){
length /= sqrt((double)d);
int dd;
for (dd = 0; dd != d; ++dd)
gsl_vector_set(eps,dd,(2.*gsl_rng_uniform(randgen)-1.)*length);
return;
}
| {
"alphanum_fraction": 0.6475770925,
"avg_line_length": 23.4827586207,
"ext": "c",
"hexsha": "1e98c0afd84df31e49f7f06505f4b4f9cfad1142",
"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": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution",
"max_forks_repo_path": "src/bovy_randvec.c",
"max_issues_count": 24,
"max_issues_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780",
"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": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution",
"max_issues_repo_path": "src/bovy_randvec.c",
"max_line_length": 67,
"max_stars_count": 73,
"max_stars_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution",
"max_stars_repo_path": "src/bovy_randvec.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": 200,
"size": 681
} |
#ifndef TTT_UTIL_UTILITIES_H
#define TTT_UTIL_UTILITIES_H
#include <SDL_keyboard.h>
#include <gsl/util>
namespace ttt::util
{
// Used to avoid having to cast std::size_t to gsl::index.
template<typename Container>
[[nodiscard]] inline gsl::index getSize(const Container &container) noexcept
{
return gsl::narrow_cast<gsl::index>(container.size());
}
}
#endif | {
"alphanum_fraction": 0.7479674797,
"avg_line_length": 20.5,
"ext": "h",
"hexsha": "619440b130fe821d0f76796de6a6bf314893a3ca",
"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/Utilities/Utilities.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/Utilities/Utilities.h",
"max_line_length": 77,
"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/Utilities/Utilities.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 93,
"size": 369
} |
/* linalg/hesstri.c
*
* Copyright (C) 2006, 2007 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 <stdlib.h>
#include <math.h>
#include <config.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include "givens.c"
/*
* This module contains routines related to the Hessenberg-Triangular
* reduction of two general real matrices
*
* See Golub & Van Loan, "Matrix Computations", 3rd ed, sec 7.7.4
*/
/*
gsl_linalg_hesstri_decomp()
Perform a reduction to generalized upper Hessenberg form.
Given A and B, this function overwrites A with an upper Hessenberg
matrix H = U^T A V and B with an upper triangular matrix R = U^T B V
with U and V orthogonal.
See Golub & Van Loan, "Matrix Computations" (3rd ed) algorithm 7.7.1
Inputs: A - real square matrix
B - real square matrix
U - (output) if non-null, U is stored here on output
V - (output) if non-null, V is stored here on output
work - workspace (length n)
Return: success or error
*/
int
gsl_linalg_hesstri_decomp(gsl_matrix * A, gsl_matrix * B, gsl_matrix * U,
gsl_matrix * V, gsl_vector * work)
{
const size_t N = A->size1;
if ((N != A->size2) || (N != B->size1) || (N != B->size2))
{
GSL_ERROR ("Hessenberg-triangular reduction requires square matrices",
GSL_ENOTSQR);
}
else if (N != work->size)
{
GSL_ERROR ("length of workspace must match matrix dimension",
GSL_EBADLEN);
}
else
{
double cs, sn; /* rotation parameters */
size_t i, j; /* looping */
gsl_vector_view xv, yv; /* temporary views */
/* B -> Q^T B = R (upper triangular) */
gsl_linalg_QR_decomp(B, work);
/* A -> Q^T A */
gsl_linalg_QR_QTmat(B, work, A);
/* initialize U and V if desired */
if (U)
{
gsl_linalg_QR_unpack(B, work, U, B);
}
else
{
/* zero out lower triangle of B */
for (j = 0; j < N - 1; ++j)
{
for (i = j + 1; i < N; ++i)
gsl_matrix_set(B, i, j, 0.0);
}
}
if (V)
gsl_matrix_set_identity(V);
if (N < 3)
return GSL_SUCCESS; /* nothing more to do */
/* reduce A and B */
for (j = 0; j < N - 2; ++j)
{
for (i = N - 1; i >= (j + 2); --i)
{
/* step 1: rotate rows i - 1, i to kill A(i,j) */
/*
* compute G = [ CS SN ] so that G^t [ A(i-1,j) ] = [ * ]
* [-SN CS ] [ A(i, j) ] [ 0 ]
*/
create_givens(gsl_matrix_get(A, i - 1, j),
gsl_matrix_get(A, i, j),
&cs,
&sn);
/* invert so drot() works correctly (G -> G^t) */
sn = -sn;
/* compute G^t A(i-1:i, j:n) */
xv = gsl_matrix_subrow(A, i - 1, j, N - j);
yv = gsl_matrix_subrow(A, i, j, N - j);
gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);
/* compute G^t B(i-1:i, i-1:n) */
xv = gsl_matrix_subrow(B, i - 1, i - 1, N - i + 1);
yv = gsl_matrix_subrow(B, i, i - 1, N - i + 1);
gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);
if (U)
{
/* accumulate U: U -> U G */
xv = gsl_matrix_column(U, i - 1);
yv = gsl_matrix_column(U, i);
gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);
}
/* step 2: rotate columns i, i - 1 to kill B(i, i - 1) */
create_givens(-gsl_matrix_get(B, i, i),
gsl_matrix_get(B, i, i - 1),
&cs,
&sn);
/* invert so drot() works correctly (G -> G^t) */
sn = -sn;
/* compute B(1:i, i-1:i) G */
xv = gsl_matrix_subcolumn(B, i - 1, 0, i + 1);
yv = gsl_matrix_subcolumn(B, i, 0, i + 1);
gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);
/* apply to A(1:n, i-1:i) */
xv = gsl_matrix_column(A, i - 1);
yv = gsl_matrix_column(A, i);
gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);
if (V)
{
/* accumulate V: V -> V G */
xv = gsl_matrix_column(V, i - 1);
yv = gsl_matrix_column(V, i);
gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);
}
}
}
return GSL_SUCCESS;
}
} /* gsl_linalg_hesstri_decomp() */
| {
"alphanum_fraction": 0.5014466546,
"avg_line_length": 31.7816091954,
"ext": "c",
"hexsha": "59f78c9207a7b907a56da22fa37676fcde0b120f",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "skair39/structured",
"max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/linalg/hesstri.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "skair39/structured",
"max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/linalg/hesstri.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/linalg/hesstri.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": 1540,
"size": 5530
} |
/* rng/test.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
void rng_test (const gsl_rng_type * T, unsigned long int seed, unsigned int n,
unsigned long int result);
void rng_float_test (const gsl_rng_type * T);
void generic_rng_test (const gsl_rng_type * T);
void rng_state_test (const gsl_rng_type * T);
void rng_parallel_state_test (const gsl_rng_type * T);
void rng_read_write_test (const gsl_rng_type * T);
int rng_max_test (gsl_rng * r, unsigned long int *kmax, unsigned long int ran_max) ;
int rng_min_test (gsl_rng * r, unsigned long int *kmin, unsigned long int ran_min, unsigned long int ran_max) ;
int rng_sum_test (gsl_rng * r, double *sigma);
int rng_bin_test (gsl_rng * r, double *sigma);
#define N 10000
#define N2 200000
int
main (void)
{
const gsl_rng_type ** rngs = gsl_rng_types_setup(); /* get all rng types */
const gsl_rng_type ** r ;
gsl_ieee_env_setup ();
gsl_rng_env_setup ();
/* specific tests of known results for 10000 iterations with seed = 1 */
rng_test (gsl_rng_rand, 1, 10000, 1910041713);
rng_test (gsl_rng_randu, 1, 10000, 1623524161);
rng_test (gsl_rng_cmrg, 1, 10000, 719452880);
rng_test (gsl_rng_minstd, 1, 10000, 1043618065);
rng_test (gsl_rng_mrg, 1, 10000, 2064828650);
rng_test (gsl_rng_taus, 1, 10000, 2733957125UL);
rng_test (gsl_rng_taus2, 1, 10000, 2733957125UL);
rng_test (gsl_rng_taus113, 1, 1000, 1925420673UL);
rng_test (gsl_rng_transputer, 1, 10000, 1244127297UL);
rng_test (gsl_rng_vax, 1, 10000, 3051034865UL);
/* Borosh13 test value from PARI: (1812433253^10000)%(2^32) */
rng_test (gsl_rng_borosh13, 1, 10000, 2513433025UL);
/* Fishman18 test value from PARI: (62089911^10000)%(2^31-1) */
rng_test (gsl_rng_fishman18, 1, 10000, 330402013UL);
/* Fishman2x test value from PARI:
((48271^10000)%(2^31-1) - (40692^10000)%(2^31-249))%(2^31-1) */
rng_test (gsl_rng_fishman2x, 1, 10000, 540133597UL);
/* Knuthran2 test value from PARI:
{ xn1=1; xn2=1; for (n=1,10000,
xn = (271828183*xn1 - 314159269*xn2)%(2^31-1);
xn2=xn1; xn1=xn; print(xn); ) } */
rng_test (gsl_rng_knuthran2, 1, 10000, 1084477620UL);
/* Knuthran test value taken from p188 in Knuth Vol 2. 3rd Ed */
rng_test (gsl_rng_knuthran, 310952, 1009 * 2009 + 1, 461390032);
/* Knuthran improved test value from Knuth's source */
rng_test (gsl_rng_knuthran2002, 310952, 1, 708622036);
rng_test (gsl_rng_knuthran2002, 310952, 2, 1005450560);
rng_test (gsl_rng_knuthran2002, 310952, 100 * 2009 + 1, 995235265);
rng_test (gsl_rng_knuthran2002, 310952, 1009 * 2009 + 1, 704987132);
/* Lecuyer21 test value from PARI: (40692^10000)%(2^31-249) */
rng_test (gsl_rng_lecuyer21, 1, 10000, 2006618587UL);
/* Waterman14 test value from PARI: (1566083941^10000)%(2^32) */
rng_test (gsl_rng_waterman14, 1, 10000, 3776680385UL);
/* specific tests of known results for 10000 iterations with seed = 6 */
/* Coveyou test value from PARI:
x=6; for(n=1,10000,x=(x*(x+1))%(2^32);print(x);) */
rng_test (gsl_rng_coveyou, 6, 10000, 1416754246UL);
/* Fishman20 test value from PARI: (6*48271^10000)%(2^31-1) */
rng_test (gsl_rng_fishman20, 6, 10000, 248127575UL);
/* FIXME: the ranlux tests below were made by running the fortran code and
getting the expected value from that. An analytic calculation
would be preferable. */
rng_test (gsl_rng_ranlux, 314159265, 10000, 12077992);
rng_test (gsl_rng_ranlux389, 314159265, 10000, 165942);
rng_test (gsl_rng_ranlxs0, 1, 10000, 11904320);
/* 0.709552764892578125 * ldexp(1.0,24) */
rng_test (gsl_rng_ranlxs1, 1, 10000, 8734328);
/* 0.520606517791748047 * ldexp(1.0,24) */
rng_test (gsl_rng_ranlxs2, 1, 10000, 6843140);
/* 0.407882928848266602 * ldexp(1.0,24) */
rng_test (gsl_rng_ranlxd1, 1, 10000, 1998227290UL);
/* 0.465248546261094020 * ldexp(1.0,32) */
rng_test (gsl_rng_ranlxd2, 1, 10000, 3949287736UL);
/* 0.919515205581550532 * ldexp(1.0,32) */
/* FIXME: the tests below were made by running the original code in
the ../random directory and getting the expected value from
that. An analytic calculation would be preferable. */
rng_test (gsl_rng_slatec, 1, 10000, 45776);
rng_test (gsl_rng_uni, 1, 10000, 9214);
rng_test (gsl_rng_uni32, 1, 10000, 1155229825);
rng_test (gsl_rng_zuf, 1, 10000, 3970);
/* The tests below were made by running the original code and
getting the expected value from that. An analytic calculation
would be preferable. */
rng_test (gsl_rng_r250, 1, 10000, 1100653588);
rng_test (gsl_rng_mt19937, 4357, 1000, 1186927261);
rng_test (gsl_rng_mt19937_1999, 4357, 1000, 1030650439);
rng_test (gsl_rng_mt19937_1998, 4357, 1000, 1309179303);
rng_test (gsl_rng_tt800, 0, 10000, 2856609219UL);
rng_test (gsl_rng_ran0, 0, 10000, 1115320064);
rng_test (gsl_rng_ran1, 0, 10000, 1491066076);
rng_test (gsl_rng_ran2, 0, 10000, 1701364455);
rng_test (gsl_rng_ran3, 0, 10000, 186340785);
rng_test (gsl_rng_ranmar, 1, 10000, 14428370);
rng_test (gsl_rng_rand48, 0, 10000, 0xDE095043UL);
rng_test (gsl_rng_rand48, 1, 10000, 0xEDA54977UL);
rng_test (gsl_rng_random_glibc2, 0, 10000, 1908609430);
rng_test (gsl_rng_random8_glibc2, 0, 10000, 1910041713);
rng_test (gsl_rng_random32_glibc2, 0, 10000, 1587395585);
rng_test (gsl_rng_random64_glibc2, 0, 10000, 52848624);
rng_test (gsl_rng_random128_glibc2, 0, 10000, 1908609430);
rng_test (gsl_rng_random256_glibc2, 0, 10000, 179943260);
rng_test (gsl_rng_random_bsd, 0, 10000, 1457025928);
rng_test (gsl_rng_random8_bsd, 0, 10000, 1910041713);
rng_test (gsl_rng_random32_bsd, 0, 10000, 1663114331);
rng_test (gsl_rng_random64_bsd, 0, 10000, 864469165);
rng_test (gsl_rng_random128_bsd, 0, 10000, 1457025928);
rng_test (gsl_rng_random256_bsd, 0, 10000, 1216357476);
rng_test (gsl_rng_random_libc5, 0, 10000, 428084942);
rng_test (gsl_rng_random8_libc5, 0, 10000, 1910041713);
rng_test (gsl_rng_random32_libc5, 0, 10000, 1967452027);
rng_test (gsl_rng_random64_libc5, 0, 10000, 2106639801);
rng_test (gsl_rng_random128_libc5, 0, 10000, 428084942);
rng_test (gsl_rng_random256_libc5, 0, 10000, 116367984);
rng_test (gsl_rng_ranf, 0, 10000, 2152890433UL);
rng_test (gsl_rng_ranf, 2, 10000, 339327233);
/* Test constant relationship between int and double functions */
for (r = rngs ; *r != 0; r++)
rng_float_test (*r);
/* Test save/restore functions */
for (r = rngs ; *r != 0; r++)
rng_state_test (*r);
for (r = rngs ; *r != 0; r++)
rng_parallel_state_test (*r);
for (r = rngs ; *r != 0; r++)
rng_read_write_test (*r);
/* generic statistical tests (these are just to make sure that we
don't get any crazy results back from the generator, i.e. they
aren't a test of the algorithm, just the implementation) */
for (r = rngs ; *r != 0; r++)
generic_rng_test (*r);
exit (gsl_test_summary ());
}
void
rng_test (const gsl_rng_type * T, unsigned long int seed, unsigned int n,
unsigned long int result)
{
gsl_rng *r = gsl_rng_alloc (T);
unsigned int i;
unsigned long int k = 0;
int status;
if (seed != 0)
{
gsl_rng_set (r, seed);
}
for (i = 0; i < n; i++)
{
k = gsl_rng_get (r);
}
status = (k != result);
gsl_test (status, "%s, %u steps (%u observed vs %u expected)",
gsl_rng_name (r), n, k, result);
gsl_rng_free (r);
}
void
rng_float_test (const gsl_rng_type * T)
{
gsl_rng *ri = gsl_rng_alloc (T);
gsl_rng *rf = gsl_rng_alloc (T);
double u, c ;
unsigned int i;
unsigned long int k = 0;
int status = 0 ;
do
{
k = gsl_rng_get (ri);
u = gsl_rng_get (rf);
}
while (k == 0) ;
c = k / u ;
for (i = 0; i < N2; i++)
{
k = gsl_rng_get (ri);
u = gsl_rng_get (rf);
if (c*k != u)
{
status = 1 ;
break ;
}
}
gsl_test (status, "%s, ratio of int to double (%g observed vs %g expected)",
gsl_rng_name (ri), c, k/u);
gsl_rng_free (ri);
gsl_rng_free (rf);
}
void
rng_state_test (const gsl_rng_type * T)
{
unsigned long int test_a[N], test_b[N];
int i;
gsl_rng *r = gsl_rng_alloc (T);
gsl_rng *r_save = gsl_rng_alloc (T);
for (i = 0; i < N; ++i)
{
gsl_rng_get (r); /* throw away N iterations */
}
gsl_rng_memcpy (r_save, r); /* save the intermediate state */
for (i = 0; i < N; ++i)
{
test_a[i] = gsl_rng_get (r);
}
gsl_rng_memcpy (r, r_save); /* restore the intermediate state */
gsl_rng_free (r_save);
for (i = 0; i < N; ++i)
{
test_b[i] = gsl_rng_get (r);
}
{
int status = 0;
for (i = 0; i < N; ++i)
{
status |= (test_b[i] != test_a[i]);
}
gsl_test (status, "%s, random number state consistency",
gsl_rng_name (r));
}
gsl_rng_free (r);
}
void
rng_parallel_state_test (const gsl_rng_type * T)
{
unsigned long int test_a[N], test_b[N];
unsigned long int test_c[N], test_d[N];
double test_e[N], test_f[N];
int i;
gsl_rng *r1 = gsl_rng_alloc (T);
gsl_rng *r2 = gsl_rng_alloc (T);
for (i = 0; i < N; ++i)
{
gsl_rng_get (r1); /* throw away N iterations */
}
gsl_rng_memcpy (r2, r1); /* save the intermediate state */
for (i = 0; i < N; ++i)
{
/* check that there is no hidden state intermixed between r1 and r2 */
test_a[i] = gsl_rng_get (r1);
test_b[i] = gsl_rng_get (r2);
test_c[i] = gsl_rng_uniform_int (r1, 1234);
test_d[i] = gsl_rng_uniform_int (r2, 1234);
test_e[i] = gsl_rng_uniform (r1);
test_f[i] = gsl_rng_uniform (r2);
}
{
int status = 0;
for (i = 0; i < N; ++i)
{
status |= (test_b[i] != test_a[i]);
status |= (test_c[i] != test_d[i]);
status |= (test_e[i] != test_f[i]);
}
gsl_test (status, "%s, parallel random number state consistency",
gsl_rng_name (r1));
}
gsl_rng_free (r1);
gsl_rng_free (r2);
}
void
rng_read_write_test (const gsl_rng_type * T)
{
unsigned long int test_a[N], test_b[N];
int i;
gsl_rng *r = gsl_rng_alloc (T);
for (i = 0; i < N; ++i)
{
gsl_rng_get (r); /* throw away N iterations */
}
{ /* save the state to a binary file */
FILE *f = fopen("test.dat", "wb");
gsl_rng_fwrite(f, r);
fclose(f);
}
for (i = 0; i < N; ++i)
{
test_a[i] = gsl_rng_get (r);
}
{ /* read the state from a binary file */
FILE *f = fopen("test.dat", "rb");
gsl_rng_fread(f, r);
fclose(f);
}
for (i = 0; i < N; ++i)
{
test_b[i] = gsl_rng_get (r);
}
{
int status = 0;
for (i = 0; i < N; ++i)
{
status |= (test_b[i] != test_a[i]);
}
gsl_test (status, "%s, random number generator read and write",
gsl_rng_name (r));
}
gsl_rng_free (r);
}
void
generic_rng_test (const gsl_rng_type * T)
{
gsl_rng *r = gsl_rng_alloc (T);
const char *name = gsl_rng_name (r);
unsigned long int kmax = 0, kmin = 1000;
double sigma = 0;
const unsigned long int ran_max = gsl_rng_max (r);
const unsigned long int ran_min = gsl_rng_min (r);
int status = rng_max_test (r, &kmax, ran_max);
gsl_test (status,
"%s, observed vs theoretical maximum (%lu vs %lu)",
name, kmax, ran_max);
status = rng_min_test (r, &kmin, ran_min, ran_max);
gsl_test (status,
"%s, observed vs theoretical minimum (%lu vs %lu)",
name, kmin, ran_min);
status = rng_sum_test (r, &sigma);
gsl_test (status,
"%s, sum test within acceptable sigma (observed %.2g sigma)",
name, sigma);
status = rng_bin_test (r, &sigma);
gsl_test (status,
"%s, bin test within acceptable chisq (observed %.2g sigma)",
name, sigma);
gsl_rng_set (r, 1); /* set seed to 1 */
status = rng_max_test (r, &kmax, ran_max);
gsl_rng_set (r, 1); /* set seed to 1 */
status |= rng_min_test (r, &kmin, ran_min, ran_max);
gsl_rng_set (r, 1); /* set seed to 1 */
status |= rng_sum_test (r, &sigma);
gsl_test (status, "%s, maximum and sum tests for seed=1", name);
gsl_rng_set (r, 12345); /* set seed to a "typical" value */
status = rng_max_test (r, &kmax, ran_max);
gsl_rng_set (r, 12345); /* set seed to a "typical" value */
status |= rng_min_test (r, &kmin, ran_min, ran_max);
gsl_rng_set (r, 12345); /* set seed to a "typical" value */
status |= rng_sum_test (r, &sigma);
gsl_test (status, "%s, maximum and sum tests for non-default seeds", name);
gsl_rng_free (r);
}
int
rng_max_test (gsl_rng * r, unsigned long int *kmax, unsigned long int ran_max)
{
unsigned long int actual_uncovered;
double expect_uncovered;
int status;
unsigned long int max = 0;
int i;
for (i = 0; i < N2; ++i)
{
unsigned long int k = gsl_rng_get (r);
if (k > max)
max = k;
}
*kmax = max;
actual_uncovered = ran_max - max;
expect_uncovered = (double) ran_max / (double) N2;
status = (max > ran_max) || (actual_uncovered > 7 * expect_uncovered) ;
return status;
}
int
rng_min_test (gsl_rng * r, unsigned long int *kmin,
unsigned long int ran_min, unsigned long int ran_max)
{
unsigned long int actual_uncovered;
double expect_uncovered;
int status;
unsigned long int min = 1000000000UL;
int i;
for (i = 0; i < N2; ++i)
{
unsigned long int k = gsl_rng_get (r);
if (k < min)
min = k;
}
*kmin = min;
actual_uncovered = min - ran_min;
expect_uncovered = (double) ran_max / (double) N2;
status = (min < ran_min) || (actual_uncovered > 7 * expect_uncovered);
return status;
}
int
rng_sum_test (gsl_rng * r, double *sigma)
{
double sum = 0;
int i, status;
for (i = 0; i < N2; ++i)
{
double x = gsl_rng_uniform (r) - 0.5;
sum += x;
}
sum /= N2;
/* expect the average to have a variance of 1/(12 n) */
*sigma = sum * sqrt (12.0 * N2);
/* more than 3 sigma is an error (increased to 3.1 to avoid false alarms) */
status = (fabs (*sigma) > 3.1 || fabs(*sigma) < 0.003);
if (status) {
fprintf(stderr,"sum=%g, sigma=%g\n",sum,*sigma);
}
return status;
}
#define BINS 17
#define EXTRA 10
int
rng_bin_test (gsl_rng * r, double *sigma)
{
int count[BINS+EXTRA];
double chisq = 0;
int i, status;
for (i = 0; i < BINS+EXTRA; i++)
count[i] = 0 ;
for (i = 0; i < N2; i++)
{
int j = gsl_rng_uniform_int (r, BINS);
count[j]++ ;
}
chisq = 0 ;
for (i = 0; i < BINS; i++)
{
double x = (double)N2/(double)BINS ;
double d = (count[i] - x) ;
chisq += (d*d) / x;
}
*sigma = sqrt(chisq/BINS) ;
/* more than 3 sigma is an error */
status = (fabs (*sigma) > 3 || fabs(*sigma) < 0.003);
for (i = BINS; i < BINS+EXTRA; i++)
{
if (count[i] != 0)
{
status = 1 ;
gsl_test (status,
"%s, wrote outside range in bin test "
"(%d observed vs %d expected)",
gsl_rng_name(r), i, BINS - 1);
}
}
return status;
}
| {
"alphanum_fraction": 0.6287658521,
"avg_line_length": 26.807628524,
"ext": "c",
"hexsha": "8b267a289bdc027181ed147658111e1c564eed79",
"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/test.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/rng/test.c",
"max_line_length": 111,
"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/test.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 5604,
"size": 16165
} |
// This is a plugin program that serves mainly as an example of how
// analysis programs for ssv should be written, and gives people
// something to cut and paste from. It computes and prints histogram
// information about the tiles it analyzes.
#include <stdlib.h>
#include <glib.h>
#include <gsl/gsl_histogram.h>
#include <float_image.h>
// As specified in the analysis interface provided by ssv, the first
// argument (after argv[0], the invocation name) is the number of
// tiles being passed into the analysis plugin. The second and
// succeeding arguments are also as as described in the output
// produced by 'ssv --help'.
#define TILE_COUNT_ARGUMENT_POSITION 1
// This type describes the information that we get passed for each
// tile.
typedef struct {
GString *base_name;
size_t width, height;
GString *file_name;
FloatImage *tile;
} tile_spec_type;
int
main (int argc, char **argv)
{
char *prog_name = argv[0];
prog_name = prog_name; // You might use this for reporting errors.
// How many image tiles are we getting passed?
int tile_count = atoi (argv[TILE_COUNT_ARGUMENT_POSITION]);
// Print a string showing how we were invoked.
GString *invocation = g_string_new ("");
int ii;
for ( ii = 0 ; ii < argc ; ii++ ) {
g_string_append_printf (invocation, "%s ", argv[ii]);
}
g_print ("\nRunning analysis program '%s'...\n", invocation->str);
g_string_free (invocation, TRUE);
// Read the argument into an array of tile_spec_type structures.
GPtrArray *tile_specs = g_ptr_array_new ();
int current_arg = TILE_COUNT_ARGUMENT_POSITION + 1;
for ( ii = 0 ; ii < tile_count ; ii++ ) {
tile_spec_type *cs = g_new (tile_spec_type, 1); // Current spec.
cs->base_name = g_string_new (argv[current_arg++]);
cs->width = atoi (argv[current_arg++]);
cs->height = atoi (argv[current_arg++]);
cs->file_name = g_string_new (argv[current_arg++]);
cs->tile = float_image_new_from_file (cs->width, cs->height,
cs->file_name->str, 0,
FLOAT_IMAGE_BYTE_ORDER_BIG_ENDIAN);
g_ptr_array_add (tile_specs, cs);
}
g_print ("\nGot %d total structures to process.\n", tile_count);
// Compute and print histograms and other information for each tile.
for ( ii = 0 ; ii < tile_specs->len ; ii++ ) {
// Current tile spec.
tile_spec_type *cs = g_ptr_array_index (tile_specs, ii);
g_print ("\nTile from image %s\n", cs->base_name->str);
g_print ("Width: %llu\n", (long long unsigned int) cs->width);
g_print ("Height: %llu\n", (long long unsigned int) cs->height);
if ( cs->width == 0 || cs->height == 0 ) {
g_print ("Tile of zero area, nothing to analyze.\n");
}
else {
g_print ("Histogram:\n");
const size_t bin_count = 20;
gsl_histogram *hg = gsl_histogram_alloc (bin_count);
// The test data I use is from an originally byte-valued image; if
// you have a different sort of image a histogram covering only
// this data region may be pretty dull.
gsl_histogram_set_ranges_uniform (hg, 0.0, 255.0);
guint jj, kk;
for ( jj = 0 ; jj < cs->width ; jj++ ) {
for ( kk = 0 ; kk < cs->height ; kk++ ) {
float pv = float_image_get_pixel (cs->tile, jj, kk);
gsl_histogram_increment (hg, pv);
}
}
g_print (" Range Start Range End Occurences\n");
g_print ("-----------------------------------------\n");
gsl_histogram_fprintf (stdout, hg, "%13.2f", "%13.0f");
gsl_histogram_free (hg);
}
g_print ("\n");
}
// Free the tile specifications array.
for ( ii = 0 ; ii < tile_specs->len ; ii++ ) {
tile_spec_type *cs = g_ptr_array_index (tile_specs, ii);
float_image_free (cs->tile);
g_string_free (cs->file_name, TRUE);
g_string_free (cs->base_name, TRUE);
g_free (cs);
}
g_ptr_array_free (tile_specs, TRUE);
exit (EXIT_SUCCESS);
}
| {
"alphanum_fraction": 0.6545688546,
"avg_line_length": 35.3181818182,
"ext": "c",
"hexsha": "4100a63328c2127c8e71d94e71e873974e2d3ef4",
"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/ssv/plugin_histogram.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/ssv/plugin_histogram.c",
"max_line_length": 72,
"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/ssv/plugin_histogram.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": 1042,
"size": 3885
} |
#ifndef METHODS_HELLER_H
#define METHODS_HELLER_H
#include <gsl/gsl_multimin.h>
namespace method {
// use your method name to create a subspace for your
// implementation of details
namespace heller_cwa {
namespace details {
struct HellerParam {
// exp(a[0] p^2 + a[1] p + a[2] p q + a[3] q + a[4] q^2 + a[5])
// alpha = 0.5 / a[0]
// delta = a[1]
// epsilon = a[2]
arma::cx_vec a;
arma::mat points;
math::Polynomial<cx_double> V_eff_0;
double mass;
};
inline
cx_double heller_gaussian(const arma::cx_vec & a,
const double q,
const double p) {
return std::exp(a(0) * std::pow(p, 2)
+ a(1) * p
+ a(2) * p * q
+ a(3) * q
+ a(4) * std::pow(q, 2)
+ a(5));
}
inline
arma::cx_vec heller_gaussian(const arma::cx_vec & a,
const arma::mat & points) {
if (points.n_rows != 2) {
throw Error("heller_gaussian only supports one-dimensional phase space");
}
arma::cx_vec result(points.n_cols);
#pragma omp parallel for
for (arma::uword i = 0; i < result.n_elem; i++) {
result(i) = heller_gaussian(a, points(0, i), points(1, i));
}
return result;
}
inline
math::Gaussian<cx_double> heller_gaussian(const arma::cx_vec & a) {
const arma::cx_mat binomial{{{-a(4) * 2.0, -a(2)}, {-a(2), -a(0) * 2.0}}};
const arma::cx_mat covariance = arma::inv(binomial);
const arma::cx_vec center = covariance * arma::cx_vec{a(3),a(1)};
return math::Gaussian<cx_double>(covariance, center,
std::exp(a(5)) * std::exp(0.5 * arma::dot(center, arma::cx_vec{a(3),a(1)})));
}
template<typename Potential>
arma::mat force(const Potential & potential,
const arma::mat & positions) {
arma::mat result = arma::mat(arma::size(positions));
#pragma omp parallel for
for (arma::uword i = 0; i < positions.n_cols; i++) {
const arma::vec position = positions.col(i);
for (arma::uword j = 0; j < positions.n_rows; j++) {
result(j, i) = -potential.derivative(j).at(position);
}
}
return result;
}
template<typename Function>
inline
auto effective_potential(const Function & potential,
const cx_double alpha,
const cx_double delta,
const cx_double epsilon,
const arma::uword l,
const arma::uword cut_off) {
if (potential.dim() > 1) {
throw Error("Currently effective potential is only valid "
"for one dimensional potential");
}
const auto functor = [alpha](const Function & function) -> Function {
return function.derivative(0).derivative(0) / 8.0 / alpha;
};
const auto a = exp(functor, derivative(potential, arma::uvec{l}), cut_off) *
std::pow(-1, l + 1);
const auto b = exp(functor, derivative(potential, arma::uvec{l}), cut_off);
const std::vector<math::Polynomial<cx_double>>
a_inner =
{math::Polynomial<cx_double>(
arma::cx_vec{1.0 + epsilon / 2.0,
cx_double{0.0, 1.0} / 2.0 / alpha,
0.5 * delta},
lmat{{1, 0, 0},
{0, 1, 0}})};
const std::vector<math::Polynomial<cx_double>>
b_inner =
{math::Polynomial<cx_double>(
arma::cx_vec{1.0 - epsilon / 2.0,
-cx_double{0.0, 1.0} / 2.0 / alpha,
-0.5 * delta},
lmat{{1, 0, 0},
{0, 1, 0}})};
const auto combined = (a(a_inner) + b(b_inner)) * 0.5;
return combined;
}
inline
math::Polynomial<cx_double> E_function(const arma::cx_vec & a,
const arma::cx_vec & a_derivatives,
const math::Polynomial<cx_double> & V_eff_0,
const double mass) {
if (a.n_elem != 6 || a_derivatives.n_elem != 6) {
throw Error(
"The number of elements for a's or their derivatives is invalid for E function");
}
const math::Polynomial<cx_double> without_derivatives(
arma::cx_vec{-a(2) / mass, -2.0 * a(4) / mass, -a(3) / mass},
lmat{{{0, 1, 0}, {2, 1, 1}}}
);
const math::Polynomial<cx_double> derivatives(
arma::cx_vec{-a_derivatives(0),
-a_derivatives(1),
-a_derivatives(2),
-a_derivatives(3),
-a_derivatives(4),
-a_derivatives(5)},
lmat{{{0, 0, 1, 1, 2, 0}, {2, 1, 1, 0, 0, 0}}}
);
return without_derivatives + derivatives - V_eff_0 * cx_double{0.0, 2.0};
}
inline
double I_function(
const arma::cx_vec & a,
const arma::cx_vec & a_derivatives,
const arma::mat & points,
const math::Polynomial<cx_double> & V_eff_0,
const double mass) {
return arma::sum(arma::pow(arma::abs(
at(E_function(a, a_derivatives, V_eff_0, mass), points)
% heller_gaussian(a, points)), 2));
}
inline
arma::vec I_function_derivative(
const arma::cx_vec & a,
const arma::cx_vec & a_derivatives,
const arma::mat & points,
const math::Polynomial<cx_double> & V_eff_0,
const double mass
) {
arma::vec result(12);
const auto E_func = E_function(a, a_derivatives, V_eff_0, mass);
const auto polynomial_term_list = lmat{{{0, 0, 1, 1, 2, 0}, {2, 1, 1, 0, 0, 0}}};
#pragma omp parallel for
for (arma::uword i = 0; i < 6; i++) {
const lvec E_derivative_term = polynomial_term_list.col(i);
const auto E_derivative =
math::polynomial::Term<double>(1.0, E_derivative_term);
result(i) = -arma::sum(2.0 *
arma::real(at(E_func.conj() * E_derivative, points))
%
arma::pow(arma::abs(heller_gaussian(a, points)), 2));
result(i + 6) = arma::sum(2.0 *
arma::imag(
at(E_func.conj() * E_derivative, points))
%
arma::pow(arma::abs(heller_gaussian(a, points)),
2));
}
return result;
}
inline
double I_function_gsl_wrapper(
const gsl_vector * a_derivatives,
void * param
) {
const HellerParam heller_param = *(HellerParam *) param;
const arma::cx_vec a = heller_param.a;
const arma::vec a_derivatives_all = gsl::convert_vec(a_derivatives);
const arma::cx_vec a_derivatives_arma =
arma::cx_vec{a_derivatives_all.rows(0, 5),
a_derivatives_all.rows(6, 11)};
return I_function(a,
a_derivatives_arma,
heller_param.points,
heller_param.V_eff_0,
heller_param.mass);
}
inline
void I_function_derivative_gsl_wrapper(
const gsl_vector * a_derivatives,
void * param,
gsl_vector * g
) {
const HellerParam heller_param = *(HellerParam *) param;
const arma::cx_vec a = heller_param.a;
const arma::vec a_derivatives_all = gsl::convert_vec(a_derivatives);
const arma::cx_vec a_derivatives_arma =
arma::cx_vec{a_derivatives_all.rows(0, 5),
a_derivatives_all.rows(6, 11)};
const auto result_pointer =
gsl::convert_vec(I_function_derivative(a,
a_derivatives_arma,
heller_param.points,
heller_param.V_eff_0,
heller_param.mass));
gsl_vector_memcpy(g, result_pointer);
gsl_vector_free(result_pointer);
}
inline
void I_function_fdf_gsl_wrapper(
const gsl_vector * a_derivatives,
void * param,
double * f,
gsl_vector * g
) {
I_function_derivative_gsl_wrapper(a_derivatives, param, g);
*f = I_function_gsl_wrapper(a_derivatives, param);
}
inline
arma::cx_vec a_derivative(HellerParam input,
const double initial_step_size,
const double tolerance,
const double gradient_tolerance,
const size_t total_steps) {
/* allocate memory for minimization process */
const auto minimizer_type = gsl_multimin_fdfminimizer_vector_bfgs2;
auto minimizer_environment = gsl_multimin_fdfminimizer_alloc(minimizer_type,
12);
/* assigning function to minimizer object */
gsl_multimin_function_fdf minimizer_object;
minimizer_object.f = &I_function_gsl_wrapper;
minimizer_object.df = &I_function_derivative_gsl_wrapper;
minimizer_object.fdf = &I_function_fdf_gsl_wrapper;
minimizer_object.n = 12;
minimizer_object.params = (void *) &input;
/* starting point */
const auto a_derivatives = gsl_vector_calloc(12);
/* set environment */
gsl_multimin_fdfminimizer_set(minimizer_environment,
&minimizer_object, a_derivatives,
initial_step_size, tolerance);
size_t iter = 0;
int status = GSL_CONTINUE;
do {
iter++;
status = gsl_multimin_fdfminimizer_iterate(minimizer_environment);
if (status) {
throw Error(gsl_strerror(status));
}
status = gsl_multimin_test_gradient(minimizer_environment->gradient,
gradient_tolerance);
if (status == GSL_SUCCESS) {
const arma::vec result = gsl::convert_vec(minimizer_environment->x);
gsl_multimin_fdfminimizer_free(minimizer_environment);
gsl_vector_free(a_derivatives);
return arma::cx_vec{result.rows(arma::span(0, 5)),
result.rows(arma::span(6, 11))};
}
} while (status == GSL_CONTINUE && iter < total_steps);
return arma::ones<arma::cx_vec>(6) * 2.8375;
}
} // namespace details
struct State {
public:
arma::mat points;
arma::vec weights;
arma::vec masses;
// Establish an easy way to construct your State
template<typename PhaseSpaceDistribution>
State(const PhaseSpaceDistribution & initial,
const arma::uvec & grid,
const arma::mat & range,
const arma::vec & masses) :
points(math::space::points_generate(grid, range)),
weights(arma::real(at(initial, points))),
masses(masses) {
if (grid.n_rows != range.n_rows) {
throw Error("Different dimension between the grid and the range");
}
if (grid.n_rows != 2 * masses.n_rows) {
throw Error("Different dimension between the grid and the masses");
}
}
template<typename PhaseSpaceDistribution>
State(const PhaseSpaceDistribution & initial,
const arma::uvec & grid,
const arma::mat & range) :
points(math::space::points_generate(grid, range)),
weights(arma::real(at(initial, points))),
masses(arma::ones<arma::vec>(grid.n_elem / 2)) {
if (grid.n_elem % 2 != 0) {
throw Error("Odd number of dimension - it is not likely a phase space");
}
if (grid.n_rows != range.n_rows) {
throw Error("Different dimension between the grid and the range");
}
if (grid.n_rows != 2 * masses.n_rows) {
throw Error("Different dimension between the grid and the masses");
}
}
inline
State(const arma::mat & points,
const arma::vec & weights,
const arma::vec & masses) :
points(points),
weights(weights),
masses(masses) {
if (points.n_cols != weights.n_elem) {
throw Error("Different number of points and corresponding weights");
}
if (points.n_rows != 2 * masses.n_rows) {
throw Error("Different dimension between the points and the masses");
}
}
inline
arma::uword dim() const {
return points.n_rows / 2;
}
inline
State normalise() const {
return State(this->points, this->weights / arma::sum(this->weights),
this->masses);
}
template<typename Function>
arma::vec expectation(const std::vector<Function> & function) const {
arma::vec result(function.size());
#pragma omp parallel for
for (arma::uword i = 0; i < result.n_elem; i++) {
if (function[i].dim() != this->dim() * 2) {
throw Error(
"The dimension of the function is invalid for the calculation of expectation");
}
result(i) = arma::dot(at(function[i], this->points), weights) /
arma::sum(weights);
}
return result;
}
template<typename Function>
double expectation(const Function & function) const {
const arma::vec result = at(function, this->points);
return arma::dot(result, weights) / arma::sum(weights);
}
inline
arma::vec positional_expectation() const {
arma::uword dim = this->dim();
return this->points.rows(0, dim - 1) * this->weights /
arma::sum(this->weights);
}
inline
arma::vec momentum_expectation() const {
arma::uword dim = this->dim();
return this->points.rows(dim, 2 * dim - 1) * this->weights /
arma::sum(this->weights);
}
State operator+(const State & B) const {
if (!arma::approx_equal(this->weights, B.weights, "abs_diff", 1e-16) ||
!arma::approx_equal(this->masses, B.masses, "abs_diff", 1e-16)) {
throw Error("Different cwa states are being added");
}
return State(this->points + B.points, this->weights, this->masses);
}
State operator*(const double B) const {
return State(this->points * B, this->weights, this->masses);
}
};
template<typename Potential>
struct Operator {
private:
PropagationType type = Classic;
public:
Potential potential;
Operator(const State & state,
const Potential & potential) :
potential(potential) {}
inline
PropagationType propagation_type() const {
return Classic;
}
State operator()(const State & state) const {
arma::mat p_submatrix = state.points.rows(state.dim(), 2 * state.dim() - 1);
p_submatrix.each_col() /= state.masses;
const arma::mat change_list =
arma::join_cols(p_submatrix,
details::force(potential,
state.points.rows(0, state.dim() - 1)));
return State(change_list, state.weights, state.masses);
}
};
} // namespace heller
}
#endif //METHODS_HELLER_H
| {
"alphanum_fraction": 0.5911126662,
"avg_line_length": 29.4639175258,
"ext": "h",
"hexsha": "265ad30b4648fbe888e96e8e5d8fa51e6eeb10aa",
"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": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Walter-Feng/Quartz",
"max_forks_repo_path": "include/quartz_internal/details/methods/heller_cwa.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b",
"max_issues_repo_issues_event_max_datetime": "2020-06-17T05:26:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-02-27T04:46:41.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Walter-Feng/Quartz",
"max_issues_repo_path": "include/quartz_internal/details/methods/heller_cwa.h",
"max_line_length": 91,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Walter-Feng/Quartz",
"max_stars_repo_path": "include/quartz_internal/details/methods/heller_cwa.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-01T01:27:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-18T09:34:46.000Z",
"num_tokens": 3672,
"size": 14290
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** 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 __BSSCR_SUM_h__
#define __BSSCR_SUM_h__
#include <petsc.h>
#include <petscmat.h>
#include <petscvec.h>
#include <petscksp.h>
#include <petscpc.h>
#include <StGermain/libStGermain/src/StGermain.h>
#include <StgDomain/libStgDomain/src/StgDomain.h>
#include <StgFEM/libStgFEM/src/StgFEM.h>
#include <PICellerator/libPICellerator/src/PICellerator.h>
#include <Underworld/libUnderworld/src/Underworld.h>
#include "Solvers/KSPSolvers/src/KSPSolvers.h"
#include "common-driver-utils.h"
#include "BSSCR.h" /* includes StokesBlockKSPInterface.h */
//void bsscr_summary(KSP_BSSCR * bsscrp_self, KSP ksp_S, KSP ksp_inner, Mat K,Mat Korig,Mat K2,Mat D,Mat G,Mat C,Vec u,Vec p,Vec f,Vec h,Vec t,
void bsscr_summary(KSP_BSSCR * bsscrp_self, KSP ksp_S, KSP ksp_inner, Mat K,Mat K2,Mat D,Mat G,Mat C,Vec u,Vec p,Vec f,Vec h,Vec t,
double penaltyNumber,PetscTruth KisJustK,double mgSetupTime, double RHSSolveTime, double scrSolveTime,double a11SingleSolveTime);
#endif
| {
"alphanum_fraction": 0.5560887822,
"avg_line_length": 50.5151515152,
"ext": "h",
"hexsha": "62eacfea83a534d0032ed24d84d8aac16711fc90",
"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": "76991c475ac565e092e99a364370fbae15bb40ac",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "rbeucher/underworld2",
"max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/summary.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac",
"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": "rbeucher/underworld2",
"max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/summary.h",
"max_line_length": 143,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "rbeucher/underworld2",
"max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/summary.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 554,
"size": 1667
} |
/* #################################################
* # stochastic simulation of adapting populations #
* # with varying constraint type #
* # and exponential mutation kernel #
* #################################################
*
* 2012-2015, Lukas Geyrhofer, lukas.geyrhofer@ds.mpg.de
*
*
* #################################################
*
* simplest usage (population size 1e7):
* ./travelingwavepeak_exp -N 1e7 1> out.txt 2> conf.txt
*
* ################################################# */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>
#include <mcheck.h>
int space = 300;
int space0 = 100;
double dx = 1e-2;
int maxSteps = 1000;
int outputstep = 100;
int quiet = 0;
int noise = 0; // noise can assume 4 different values:
// value in code cmdline description
// 0 (default) populationsize is constrained to 1, no noise is added
// constraint could be any value
// 1 N fixedN, set by parameter -N POPSIZE
// 2 u U ustar, set by parameter -u UFILENAME
// if ustar-profile is in finer grid than simulation, use parameter -U LATTICERATIO
// 3 n g timetrace, population size is constrained using a (single column) textfile,
// where the entries are the current population size
// use also parameter -g STEPS to indicate the number of timesteps (steps! not time in generations)
// between two values in this textfile
// 4 y U ustar, use file from -y UFILENAME
// no stochastic dynamics, noise is not added, only the constraint is used
// if ustar-profile is in finer grid than simulation, use parameter -U LATTICERATIO
double populationsize = 1.;
double populationvariance;
double xg,varg,xcmax,xnose;
int correctformeanfitness =0;
int printhistotype = 1;
int printfixationprob = 0;
int allshifts = 0;
int shiftthreshold = 1;
double current_mean_fitness = 0.;
int read_from_file = 0;
int write_to_file = 0;
char c_infile[128],c_outfile[128];
int have_u_infile = 0;
char u_infile[128];
double *u_read,*u;
int dens_ustar_latticeratio = 1;
int u_space,u_space0;
double u_dx;
double wavespeed = 0.;
double speedprefactor;
double epsilon = 1e-2;
double twoepssqrt;
double *nn;
double *tmp;
double *x;
double mutationrate = 1e-5;
double *mutation_inflow;
double mutation_outflow;
double mutation_sigma = 1e-2;
gsl_rng* rg; /* gsl, global generator */
const gsl_rng_type* T;
unsigned long int randseed = 0;
int averagepopdens = 0;
int averagepopdens_center = 1;
int averagepopdens_resolution = 1;
int averagepopdens_havefile = 0;
double *averagepopdens_dens;
char averagepopdens_outputfile[128];
double averagepopdens_count = 0.;
double averagepopdens_dx;
int averagepopdens_space;
int averagepopdens_space0;
int averagepopdens_lower;
int averagepopdens_higher;
double *timetrace_popsize;
char timetrace_filename[128];
int timetrace_ps_interval = 100;
int timetrace_length;
int print_error(char *msg) {
fprintf(stderr,"ERROR: %s\n",msg);
exit(1);
}
// ************************************************************
// ** parameters
// ************************************************************
void parsecomamndline(int argn, char *argv[]) {
char c;
while((c = getopt(argn,argv,"s:z:d:S:e:D:O:qQi:o:R:N:CM:u:U:T:H:h:Pn:g:y:F")) != -1) {
switch(c) {
case 's': space = atoi(optarg);
break;
case 'z': space0 = atoi(optarg);
break;
case 'd': dx = atof(optarg);
break;
case 'i': strcpy(c_infile,optarg);
read_from_file = 1;
break;
case 'o': strcpy(c_outfile,optarg);
write_to_file = 1;
break;
case 'u': strcpy(u_infile,optarg);
if(noise > 0)print_error("Only a single constraint-type can be used (either option -N POPSIZE or -u FILENAME or -n FILENAME_TIMETRACE)");
noise = 2;
break;
case 'y': strcpy(u_infile,optarg);
if(noise > 0)print_error("Only a single constraint-type can be used (either option -N POPSIZE or -u FILENAME or -n FILENAME_TIMETRACE or -y FILENAME)");
noise = 4;
break;
case 'U': if((noise == 2)||(noise == 4)) {
dens_ustar_latticeratio = atoi(optarg);
}else{
print_error("option -u FILENAME needed before option -U RATIO");
}
break;
case 'S': maxSteps = atoi(optarg);
break;
case 'e': epsilon = atof(optarg);
break;
case 'D': mutationrate = atof(optarg);
break;
case 'O': outputstep = atoi(optarg);
break;
case 'q': quiet = 2;
break;
case 'Q': quiet = 1;
break;
case 'R': randseed =atoi(optarg);
break;
case 'N': populationsize = atof(optarg);
if(noise > 0)print_error("Only a single constraint-type can be used (either option -N POPSIZE or -u FILENAME or -n FILENAME_TIMETRACE)");
noise = 1;
break;
case 'C': correctformeanfitness = 1;
break;
case 'M': mutation_sigma = atof(optarg);
break;
case 'T': shiftthreshold = atoi(optarg);
break;
case 'h': strcpy(averagepopdens_outputfile,optarg);
averagepopdens_havefile = 1;
averagepopdens = 1;
break;
case 'H': averagepopdens = 1;
averagepopdens_resolution = atoi(optarg);
if(averagepopdens_resolution < 0) {
averagepopdens_resolution *= -1;
averagepopdens_center = 0;
}
break;
case 'P': printhistotype = 0;
break;
case 'F': printfixationprob = 1;
break;
case 'n': strcpy(timetrace_filename,optarg);
if(noise > 0)print_error("Only a single constraint-type can be used (either option -N POPSIZE or -u FILENAME or -n FILENAME_TIMETRACE)");
noise = 3;
break;
case 'g': timetrace_ps_interval = atoi(optarg);
break;
}
}
if(randseed==0)randseed=time(NULL);
}
// ************************************************************
// ** input and output for configuration files
// ************************************************************
void read_popdens(int importparameters) {
int i;
int icount,dcount;
int *ival;
double *dval;
int c_space,c_space0;
double c_dx;
FILE *fp;
fp = fopen(c_infile,"rb");
if(fp != NULL) {
fread(&icount,sizeof(int),1,fp);
fread(&dcount,sizeof(int),1,fp);
fread(&c_dx,sizeof(double),1,fp);
fread(&c_space,sizeof(int),1,fp);
fread(&c_space0,sizeof(int),1,fp);
if(importparameters) {
space = c_space;
space0 = c_space0;
dx = c_dx;
}
if(icount>0) {
ival = (int*)malloc(icount*sizeof(int));
fread(ival,sizeof(int),icount,fp);
free(ival);
}
if(dcount>0) {
dval = (double*)malloc(dcount*sizeof(int));
fread(dval,sizeof(double),dcount,fp);
free(dval);
}
if(space != c_space)print_error("lattice does not match!");
nn = (double*)malloc(space*sizeof(double));
fread(nn,sizeof(double),space,fp);
for(i=0;i<space;i++) {
nn[i] *= dx;
}
fclose(fp);
}else{
print_error("could not open c-infile");
}
}
void write_popdens() {
int icount=0,dcount=0;
int i;
FILE *fpc;
fpc=fopen(c_outfile,"wb");
if(fpc != NULL) {
fwrite(&icount,sizeof(int),1,fpc);
fwrite(&dcount,sizeof(int),1,fpc);
fwrite(&dx,sizeof(double),1,fpc);
fwrite(&space,sizeof(int),1,fpc);
fwrite(&space0,sizeof(int),1,fpc);
for(i=0;i<space;i++)nn[i] /= dx;
fwrite(nn,sizeof(double),space,fpc);
fclose(fpc);
}else{
print_error("could not open c-outfile");
}
}
void read_constraint(int importparameters) {
int icount,dcount;
int *ival;
double *dval;
FILE *fp;
fp = fopen(u_infile,"rb");
if(fp!=NULL) {
fread(&icount,sizeof(int),1,fp);
fread(&dcount,sizeof(int),1,fp);
fread(&u_dx,sizeof(double),1,fp);
fread(&u_space,sizeof(int),1,fp);
fread(&u_space0,sizeof(int),1,fp);
if(icount>0) {
ival = (int*)malloc(icount*sizeof(int));
fread(ival,sizeof(int),icount,fp);
free(ival);
}
if(dcount>=3) {
dval = (double*)malloc(dcount*sizeof(int));
fread(dval,sizeof(double),dcount,fp);
mutationrate = dval[0];
wavespeed = dval[1];
mutation_sigma = dval[2];
free(dval);
}else{
print_error("not enough values in constraint file! need at least 3 double parameters: mutationrate, wavespeed, mutationsigma!");
}
if(importparameters) {
space = u_space/dens_ustar_latticeratio;
space0 = u_space0/dens_ustar_latticeratio;
dx = u_dx*dens_ustar_latticeratio;
}else{
if((space*dens_ustar_latticeratio != u_space)||(space0*dens_ustar_latticeratio != u_space0))print_error("lattice does not match! u");
}
u_read = (double*)malloc(u_space*sizeof(double));
fread(u_read,sizeof(double),u_space,fp);
fclose(fp);
}else{
print_error("could not open ufile");
}
u = (double*)malloc(space*sizeof(double));
}
void flat_constraint(double size) {
int i;
u=(double*)malloc(space*sizeof(double));
for(i=0;i<space;i++)u[i] = 1./size;
}
void initialize_with_gaussian_popdens() {
int i;
double startvariance;
if((noise == 2)||(noise == 4)) {
startvariance = wavespeed;
}else{
// Good et al., PNAS (2012)
startvariance = mutation_sigma*mutation_sigma*2*log(mutation_sigma*populationsize)/(log(mutation_sigma/mutationrate)*log(mutation_sigma/mutationrate));
// behaves weird for extremal parameter values.
// catch those cases and set on standard value: density takes half of the box
if(startvariance < 0) {
startvariance = (0.25*space*space*dx*dx);
}
}
for(i=0;i<space;i++) {
nn[i] = exp(-(i-space0)*(i-space0)*dx*dx/(2.*startvariance));
}
}
void print_u(int time) {
int i;
for(i=0;i<space;i++) {
fprintf(stderr,"%10.6lf %10.6lf %16.10e\n",time*epsilon,(i-space0+allshifts)*dx,u[i]);
}
fprintf(stderr,"\n");
}
// ************************************************************
// ** timetrace
// ************************************************************
void read_timetrace() {
int i;
timetrace_length = (int)(maxSteps/timetrace_ps_interval)+1;
FILE *fp;
timetrace_popsize = (double*)malloc(timetrace_length*sizeof(double));
fp = fopen(timetrace_filename,"r");
if(fp != NULL) {
for(i=0;i<timetrace_length;i++) {
fscanf(fp,"%lf",&timetrace_popsize[i]);
}
}else{
print_error("could not open timetrace file");
}
fclose(fp);
}
double get_timetrace_popsize(int step) {
int i;
if(step%timetrace_ps_interval == 0) {
return timetrace_popsize[step/timetrace_ps_interval];
}else{
int lasttimepoint = (int)floor(step/timetrace_ps_interval);
int nexttimepoint = lasttimepoint + 1;
double fractimepoint = (1.*(step%timetrace_ps_interval))/(1.*timetrace_ps_interval);
return fractimepoint*timetrace_popsize[nexttimepoint] + (1-fractimepoint)*timetrace_popsize[lasttimepoint];
}
}
// ************************************************************
// ** screen output
// ************************************************************
void print_populationdensity(int timestep) {
int i;
double corr = allshifts*dx;
if(correctformeanfitness)corr += current_mean_fitness;
for(i=0;i<space;i++) {
fprintf(stderr,"%lf %14.10lf %20.10e",timestep*epsilon,(i-space0)*dx+corr,nn[i]);
if(printfixationprob)fprintf(stderr," %20.10e",u[i]);
fprintf(stderr,"\n");
if(printhistotype) {
fprintf(stderr,"%lf %14.10lf %20.10e",timestep*epsilon,(i-space0+1)*dx+corr,nn[i]);
if(printfixationprob)fprintf(stderr," %20.10e",u[i]);
fprintf(stderr,"\n");
}
}
fprintf(stderr,"\n");
}
// ************************************************************
// ** average popdens
// ************************************************************
void init_averagepopdens() {
averagepopdens_dx = dx/(1.*averagepopdens_resolution);
averagepopdens_space = space*averagepopdens_resolution;
averagepopdens_space0 = space0*averagepopdens_resolution;
averagepopdens_dens = (double*)calloc(averagepopdens_space,sizeof(double));
averagepopdens_lower = (int)(-averagepopdens_resolution/2);
averagepopdens_higher = (int)(averagepopdens_resolution/2);
if(averagepopdens_higher - averagepopdens_lower < averagepopdens_resolution)averagepopdens_higher++;
}
void update_averagepopdens() {
int i,j,idx;
int offset=0;
if(averagepopdens_center) {
offset = (int)(current_mean_fitness/dx*averagepopdens_resolution);
}
for(i=0;i<space;i++) {
for(j=averagepopdens_lower;j<averagepopdens_higher;j++) {
idx = i*averagepopdens_resolution+j-offset;
if((averagepopdens_space > idx) &&( idx >= 0))
averagepopdens_dens[idx] += nn[i];
}
}
averagepopdens_count += 1.;
}
void write_averagepopdens() {
int i;
FILE *fp;
if(averagepopdens_havefile == 1) {
fp = fopen(averagepopdens_outputfile,"w");
}else{
fp = stdout;
}
for(i=0;i<averagepopdens_space;i++) {
fprintf(fp,"%lf %e\n",(i-averagepopdens_space0)*averagepopdens_dx,averagepopdens_dens[i]/averagepopdens_count);
}
if(averagepopdens_havefile == 1) {
fclose(fp);
}
free(averagepopdens_dens);
}
// ************************************************************
// ** main algorithm
// ************************************************************
void update_u(int timestep) {
// bug if shiftthreshold -T >1, use shiftthreshold only with fixedN
int i,j;
int baseshift;
double fracshift;
baseshift = (int)floor(current_mean_fitness/u_dx);
fracshift = current_mean_fitness/u_dx - 1.*baseshift;
i = 0;
for(j=0;j<u_space;j++) {
if ( j + baseshift + fracshift > (i+.5)*dens_ustar_latticeratio) {
u[i] += (1.-fracshift)*u_read[j];
u[i] /= (1.*dens_ustar_latticeratio);
i++;
if(i>=space)break;
u[i] = fracshift*u_read[j];
}else{
u[i] += u_read[j];
}
}
}
void shift_population_backward(int step) {
int i;
for(i=0;i<space-step;i++) nn[i] = nn[i+step];
for(i=space-step;i<space;i++) nn[i] = 0.;
}
void shift_population_forward(int step) {
int i;
for(i=space-1;i>-step;i--) nn[i] = nn[i+step];
for(i=-step;i>=0;i--) nn[i] = 0.;
}
void shift_population(int timestep) {
int shift = (int)floor(current_mean_fitness/dx);
if(shift >= shiftthreshold) {shift_population_backward(shift);}
if(shift <= -shiftthreshold) {shift_population_forward(-shift);}
allshifts += shift;
current_mean_fitness -= shift*dx;
}
void reproduce(int timestep) {
int i,j;
double tmpn;
long int poiss;
if((noise == 2)||(noise==4)) {
current_mean_fitness = timestep*wavespeed*epsilon - allshifts*dx;
} // else: current_mean_fitness was already updated at end of last timestep
// with function "populationconstraint" below and is still at the correct value
if((current_mean_fitness/dx >= shiftthreshold) || (current_mean_fitness/dx <= -shiftthreshold)) {
shift_population(timestep);
}
tmp[0] = 0.;
tmp[space-1] = 0.;
for(i=1;i<space-1;i++) {
tmpn = nn[i]*(1.+(x[i]-current_mean_fitness)*epsilon-mutation_outflow);
for(j = 1;j<i;j++) tmpn += mutation_inflow[j]*nn[i-j];
if(tmpn<0) {
tmpn = 0.;
}else if((noise > 0)&&(noise != 4)) {
if(tmpn < 1.e9) { // Poisson-RNG breaks down for parameters > 1e9. see GSL doc.
// use smaller bins if this occurs too often or population size too large
tmp[i] = tmpn + twoepssqrt*(gsl_ran_poisson(rg,tmpn)-tmpn);
}else{ // neglect noise term if occupancy is too large,
tmp[i] = tmpn; // dynamics can be assumed to be almost deterministic then
}
}else{
tmp[i] = tmpn;
}
}
memcpy(&nn[1],&tmp[1],(space-2)*sizeof(double));
}
double populationconstraint(int timestep) {
int i;
double constraint = 0., inv, sumxg = 0., sumxxg = 0.;
double popdens_0thmom = 0.;
double popdens_1stmom = 0.;
double popdens_2ndmom = 0.;
double cmax = 0.;
int havenose = 0;
if((noise == 2)||(noise == 4)) {
update_u(timestep);
}
for(i=space-1;i>=0;i--) {
if (nn[i] > cmax) {
cmax=nn[i];
xcmax = x[i];
}
if((havenose==0)&&(nn[i]>1)) {
havenose = 1;
xnose = x[i];
}
constraint += nn[i]*u[i];
sumxg += x[i] * nn[i] * u[i];
sumxxg += x[i] * x[i] * nn[i] * u[i];
popdens_0thmom += nn[i];
popdens_1stmom += x[i]*nn[i];
popdens_2ndmom += x[i]*x[i]*nn[i];
}
current_mean_fitness = popdens_1stmom/popdens_0thmom;
populationvariance = popdens_2ndmom/popdens_0thmom - current_mean_fitness*current_mean_fitness;
populationsize = popdens_0thmom;
xg = sumxg/constraint;
varg = sumxxg/constraint - xg*xg;
inv = 1./constraint;
if(noise==3) {
inv *= get_timetrace_popsize(timestep);
}
for(i=0;i<space;i++) nn[i] *= inv;
populationsize *= inv;
return inv;
}
// ************************************************************
// ** initialization
// ************************************************************
int initialize() {
int i;
if(read_from_file) {
read_popdens(1);
if(noise == 0)flat_constraint(1.);
if(noise == 1)flat_constraint(populationsize);
if((noise == 2)||(noise == 4)) {
read_constraint(0);
update_u(0);
}
if(noise == 3) {
flat_constraint(1.);
read_timetrace();
}
}else{
if(noise == 0)flat_constraint(1.);
if(noise == 1)flat_constraint(populationsize);
if((noise == 2) || (noise == 4)) {
read_constraint(1);
update_u(0);
}
if(noise == 3) {
flat_constraint(1.);
read_timetrace();
}
nn = (double*)malloc(space*sizeof(double));
initialize_with_gaussian_popdens();
}
tmp = (double*)malloc(space*sizeof(double));
gsl_rng_env_setup();
T = gsl_rng_default;
rg = gsl_rng_alloc(T);
gsl_rng_set(rg, randseed);
twoepssqrt = sqrt(2.*epsilon);
speedprefactor = wavespeed/dx*epsilon;
x = (double*)malloc(space*sizeof(double));
mutation_inflow = (double*)malloc(space*sizeof(double));
mutation_outflow = 0.;
mutation_inflow[0] = 0.;
for(i=1;i<space;i++) {
x[i] = (i-space0)*dx;
mutation_inflow[i] = epsilon*mutationrate*exp(-i*dx/mutation_sigma)*(1.-exp(-dx/mutation_sigma));
mutation_outflow += mutation_inflow[i];
}
if(quiet<2) {
printf("#################################################################################\n");
printf("# stochastic simulation of adapting population with exponential mutation kernel #\n");
printf("#################################################################################\n");
printf("# mutationrate = %e\n",mutationrate);
printf("# mutation_sigma = %e\n",mutation_sigma);
if(noise==0) {
printf("# constraint = deterministic\n");
}
if(noise==1) {
printf("# constraint = fixedN\n");
printf("# populationsize = %e\n",populationsize);
}
if(noise==2) {
printf("# constraint = ustar\n");
printf("# ufile = %s\n",u_infile);
printf("# wavespeed = %e\n",wavespeed);
}
if(noise==3) {
printf("# constraint = fixedN, timetrace\n");
printf("# timetracefile = %s\n",timetrace_filename);
}
if(noise==4) {
printf("# constraint = ustar, non-stochastic\n");
printf("# ufile = %s\n",u_infile);
printf("# wavespeed = %e\n",wavespeed);
}
printf("# (lattice) space = %d\n",space);
printf("# (lattice) space0 = %d\n",space0);
printf("# (lattice) dx = %e\n",dx);
printf("# randseed = %d\n",randseed);
}
}
// ************************************************************
// ** cleanup
// ************************************************************
void cleanup() {
free(nn);
free(tmp);
free(x);
free(mutation_inflow);
free(u);
if((noise == 2)||(noise == 4)) {
free(u_read);
}
if(noise == 3) {
free(timetrace_popsize);
}
gsl_rng_free(rg);
}
// ************************************************************
// ** main
// ************************************************************
int main(int argn, char *argv[]) {
int i,j;
double v,lambda = 1.;
parsecomamndline(argn,argv);
initialize();
lambda = populationconstraint(0);
if (quiet<2) fprintf(stdout,"%10.3lf %20.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e\n",0.0,current_mean_fitness,populationvariance,populationsize,lambda,xg,varg,allshifts*dx+xcmax,allshifts*dx+xnose);
if(averagepopdens) {
init_averagepopdens();
}
for(i=1;i<=maxSteps;i++) {
reproduce(i);
lambda = populationconstraint(i);
if(i%outputstep == 0) {
if (quiet<2)fprintf(stdout,"%10.3lf %20.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e\n",i*epsilon,allshifts*dx + current_mean_fitness,populationvariance,populationsize,lambda,xg,varg,allshifts*dx+xcmax,allshifts*dx+xnose);
if (quiet==0) print_populationdensity(i);
if (averagepopdens) update_averagepopdens();
}
}
if(write_to_file)write_popdens();
if(averagepopdens)write_averagepopdens();
cleanup();
return 0;
}
| {
"alphanum_fraction": 0.5920531674,
"avg_line_length": 26.958068615,
"ext": "c",
"hexsha": "7181b4d2a760ab15940484bd810c6f1bae23ea37",
"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": "073a021b3d09f162445cb2ad38a7308a3e08465d",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "lukasgeyrhofer/adaptivewaves",
"max_forks_repo_path": "stochastics/travelingwavepeak_exp.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "073a021b3d09f162445cb2ad38a7308a3e08465d",
"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": "lukasgeyrhofer/adaptivewaves",
"max_issues_repo_path": "stochastics/travelingwavepeak_exp.c",
"max_line_length": 229,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "073a021b3d09f162445cb2ad38a7308a3e08465d",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "lukasgeyrhofer/adaptivewaves",
"max_stars_repo_path": "stochastics/travelingwavepeak_exp.c",
"max_stars_repo_stars_event_max_datetime": "2020-02-26T23:07:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-01-12T19:36:44.000Z",
"num_tokens": 6120,
"size": 21216
} |
#if !defined(incompressibleFlow_h)
#define incompressibleFlow_h
#include <petsc.h>
// Define the test field number
typedef enum { VTEST, QTEST, WTEST } LowMachFlowTestFields;
typedef enum { STROUHAL, REYNOLDS, PECLET, MU, K, CP, TOTAL_INCOMPRESSIBLE_FLOW_PARAMETERS } IncompressibleFlowParametersTypes;
PETSC_EXTERN const char* incompressibleFlowParametersTypeNames[TOTAL_INCOMPRESSIBLE_FLOW_PARAMETERS + 1];
typedef enum { VEL, PRES, TEMP, TOTAL_INCOMPRESSIBLE_FLOW_FIELDS } IncompressibleFlowFields;
typedef enum { MOM, MASS, ENERGY, TOTAL_INCOMPRESSIBLE_SOURCE_FIELDS } IncompressibleSourceFields;
// Incompressible Kernels
PETSC_EXTERN void IncompressibleFlow_vIntegrandTestFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],
const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[],
const PetscScalar a_x[], PetscReal t, const PetscReal X[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]);
PETSC_EXTERN void IncompressibleFlow_vIntegrandTestGradientFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[],
const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[],
const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal X[], PetscInt numConstants,
const PetscScalar constants[], PetscScalar f1[]);
PETSC_EXTERN void IncompressibleFlow_wIntegrandTestFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],
const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[],
const PetscScalar a_x[], PetscReal t, const PetscReal X[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]);
PETSC_EXTERN void IncompressibleFlow_wIntegrandTestGradientFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[],
const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[],
const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal X[], PetscInt numConstants,
const PetscScalar constants[], PetscScalar f1[]);
PETSC_EXTERN void IncompressibleFlow_qIntegrandTestFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],
const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[],
const PetscScalar a_x[], PetscReal t, const PetscReal X[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]);
PETSC_EXTERN void IncompressibleFlow_g1_qu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],
const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g1[]);
PETSC_EXTERN void IncompressibleFlow_g0_vu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],
const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);
PETSC_EXTERN void IncompressibleFlow_g1_vu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],
const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g1[]);
PETSC_EXTERN void IncompressibleFlow_g2_vp(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],
const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g2[]);
PETSC_EXTERN void IncompressibleFlow_g3_vu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],
const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g3[]);
PETSC_EXTERN void IncompressibleFlow_g0_wT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],
const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);
PETSC_EXTERN void IncompressibleFlow_g0_wu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],
const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);
PETSC_EXTERN void IncompressibleFlow_g1_wT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],
const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g1[]);
PETSC_EXTERN void IncompressibleFlow_g3_wT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],
const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],
PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g3[]);
#endif | {
"alphanum_fraction": 0.64628872,
"avg_line_length": 133.671875,
"ext": "h",
"hexsha": "3481f830ab84cf42427b2d2bb0684b9e73f68972",
"lang": "C",
"max_forks_count": 17,
"max_forks_repo_forks_event_max_datetime": "2022-03-21T18:46:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-10T22:34:57.000Z",
"max_forks_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "mtmcgurn-buffalo/ablate",
"max_forks_repo_path": "ablateCore/flow/incompressibleFlow.h",
"max_issues_count": 124,
"max_issues_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b",
"max_issues_repo_issues_event_max_datetime": "2022-03-28T14:44:31.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-14T15:30:48.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "mtmcgurn-buffalo/ablate",
"max_issues_repo_path": "ablateCore/flow/incompressibleFlow.h",
"max_line_length": 198,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mtmcgurn-buffalo/ablate",
"max_stars_repo_path": "ablateCore/flow/incompressibleFlow.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-20T19:54:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-19T21:29:10.000Z",
"num_tokens": 1845,
"size": 8555
} |
/*
============================================================================
Name : mathutils.h
Author : Davide Malvezzi
Version : 1.0
Copyright :
Description : Math utils function
============================================================================
*/
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <gsl/gsl_rng.h>
#ifndef M_PI
#define M_PI 3.14159265359
#endif
#ifndef max
#define max( a, b ) ( ((a) > (b)) ? (a) : (b) )
#endif
#ifndef min
#define min( a, b ) ( ((a) < (b)) ? (a) : (b) )
#endif
#ifndef swapv
#define swapv(x, y) do { __typeof__(x) SWAP = x; x = y; y = SWAP; } while (0)
#endif
extern gsl_rng* rng;
extern void randInit();
extern int randInt(int min, int max);
extern float randFloat(float min, float max);
extern int isZero(float val);
extern double fast_sin(double x);
extern double fast_cos(double x);
extern double fast_atan(double x);
#define sin_f fast_sin
#define cos_f fast_cos
#define atan_f fast_atan
#endif
| {
"alphanum_fraction": 0.5734513274,
"avg_line_length": 19.1525423729,
"ext": "h",
"hexsha": "733c323c7b5ec43520f0849389fb2ddbf07b137f",
"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": "a154aaae98aa28ba6d164b7aa8462b87a838ba48",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "DavideMalvezzi/ChangePointGA",
"max_forks_repo_path": "src/ChangePointGA/src/utils/mathutils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a154aaae98aa28ba6d164b7aa8462b87a838ba48",
"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": "DavideMalvezzi/ChangePointGA",
"max_issues_repo_path": "src/ChangePointGA/src/utils/mathutils.h",
"max_line_length": 78,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "a154aaae98aa28ba6d164b7aa8462b87a838ba48",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "DavideMalvezzi/ChangePointGA",
"max_stars_repo_path": "src/ChangePointGA/src/utils/mathutils.h",
"max_stars_repo_stars_event_max_datetime": "2019-10-08T13:48:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-14T10:59:09.000Z",
"num_tokens": 295,
"size": 1130
} |
#ifndef libceed_solids_examples_setup_libceed_h
#define libceed_solids_examples_setup_libceed_h
#include <ceed.h>
#include <petsc.h>
#include "../include/structs.h"
// -----------------------------------------------------------------------------
// libCEED Functions
// -----------------------------------------------------------------------------
// Destroy libCEED objects
PetscErrorCode CeedDataDestroy(CeedInt level, CeedData data);
// Utility function - essential BC dofs are encoded in closure indices as -(i+1)
PetscInt Involute(PetscInt i);
// Utility function to create local CEED restriction from DMPlex
PetscErrorCode CreateRestrictionFromPlex(Ceed ceed, DM dm, CeedInt height,
DMLabel domain_label, CeedInt value, CeedElemRestriction *elem_restr);
// Utility function to get Ceed Restriction for each domain
PetscErrorCode GetRestrictionForDomain(Ceed ceed, DM dm, CeedInt height,
DMLabel domain_label, PetscInt value,
CeedInt Q, CeedInt q_data_size,
CeedElemRestriction *elem_restr_q,
CeedElemRestriction *elem_restr_x,
CeedElemRestriction *elem_restr_qd_i);
// Set up libCEED for a given degree
PetscErrorCode SetupLibceedFineLevel(DM dm, DM dm_energy, DM dm_diagnostic,
Ceed ceed, AppCtx app_ctx,
CeedQFunctionContext phys_ctx,
ProblemData problem_data,
PetscInt fine_level, PetscInt num_comp_u,
PetscInt U_g_size, PetscInt U_loc_size,
CeedVector force_ceed,
CeedVector neumann_ceed, CeedData *data);
// Set up libCEED multigrid level for a given degree
PetscErrorCode SetupLibceedLevel(DM dm, Ceed ceed, AppCtx app_ctx,
ProblemData problem_data, PetscInt level,
PetscInt num_comp_u, PetscInt U_g_size,
PetscInt U_loc_size, CeedVector fine_mult,
CeedData *data);
#endif // libceed_solids_examples_setup_libceed_h
| {
"alphanum_fraction": 0.5593293207,
"avg_line_length": 49.4893617021,
"ext": "h",
"hexsha": "5b29e6f75d3a58f1122cf0a0ec637c35a1611801",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "wence-/libCEED",
"max_forks_repo_path": "examples/solids/include/setup-libceed.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "wence-/libCEED",
"max_issues_repo_path": "examples/solids/include/setup-libceed.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "wence-/libCEED",
"max_stars_repo_path": "examples/solids/include/setup-libceed.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 450,
"size": 2326
} |
/* cdf/geometric.c
*
* Copyright (C) 2004 Jason H. Stover.
* Copyright (C) 2010 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_cdf.h>
#include "error.h"
/* Pr (X <= k), i.e., the probability of n or fewer failures until the
first success. */
double
gsl_cdf_geometric_P (const unsigned int k, const double p)
{
double P, a, q;
if (p > 1.0 || p < 0.0)
{
CDF_ERROR ("p < 0 or p > 1", GSL_EDOM);
}
if (k < 1)
{
return 0.0;
}
q = 1.0 - p;
a = (double) k;
if (p < 0.5)
{
P = -expm1 (a * log1p (-p));
}
else
{
P = 1.0 - pow (q, a);
}
return P;
}
double
gsl_cdf_geometric_Q (const unsigned int k, const double p)
{
double Q, a, q;
if (p > 1.0 || p < 0.0)
{
CDF_ERROR ("p < 0 or p > 1", GSL_EDOM);
}
if (k < 1)
{
return 1.0;
}
q = 1.0 - p;
a = (double) k;
if (p < 0.5)
{
Q = exp (a * log1p (-p));
}
else
{
Q = pow (q, a);
}
return Q;
}
| {
"alphanum_fraction": 0.5937325126,
"avg_line_length": 19.6373626374,
"ext": "c",
"hexsha": "d9b7744dada0c0ecf4d5eb43dee1abc074537150",
"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": "92728bb89692fda1705a0dee436592d97922a6cb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "parasol-ppl/PPL_utils",
"max_forks_repo_path": "folding_libs/gsl-1.14/cdf/geometric.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb",
"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": "parasol-ppl/PPL_utils",
"max_issues_repo_path": "folding_libs/gsl-1.14/cdf/geometric.c",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "parasol-ppl/PPL_utils",
"max_stars_repo_path": "folding_libs/gsl-1.14/cdf/geometric.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 582,
"size": 1787
} |
/*
*
* Author : Pierre Schnizer <schnizer@users.sourceforge.net>
* Date : 5. October 2003
* Only used to test the error handling of pygsl.
*/
#include <Python.h>
#include <gsl/gsl_errno.h>
#include <pygsl/error_helpers.h>
static char trigger_doc [] = "Calls gsl_error with the passed error number";
static PyObject *module;
static PyObject*
trigger(PyObject *self, PyObject *args)
{
int gsl_errno = GSL_SUCCESS;
FUNC_MESS_BEGIN();
if (0 == PyArg_ParseTuple(args, "i", &gsl_errno)){
PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__ - 1);
return NULL;
}
/*
*
* 25. October 2008
* set the internal gsl_error_handler to off
*
*/
pygsl_error("Just a test to see what pygsl is doing!",
__FILE__, __LINE__, gsl_errno);
if (PyGSL_ERROR_FLAG(gsl_errno) != GSL_SUCCESS){
FUNC_MESS_FAILED();
return NULL;
}
FUNC_MESS_END();
Py_INCREF(Py_None);
return (Py_None);
}
static PyMethodDef errortestMethods[] = {
/*densities*/
{"trigger", trigger, METH_VARARGS, trigger_doc},
{NULL, NULL, 0, NULL}
};
DL_EXPORT(void) initerrortest(void)
{
PyObject *m=NULL;
m = Py_InitModule("errortest", errortestMethods);
assert(m);
module = m;
init_pygsl();
return;
}
| {
"alphanum_fraction": 0.6714399364,
"avg_line_length": 20.606557377,
"ext": "c",
"hexsha": "22ecfdb3e449eca322b126e60e43a6073c95cee8",
"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/errortestmodule.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/errortestmodule.c",
"max_line_length": 76,
"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/errortestmodule.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 359,
"size": 1257
} |
#ifndef rpsr_f7f329f9_ae61_4fcf_b0c9_8a96216ed0e0_h
#define rpsr_f7f329f9_ae61_4fcf_b0c9_8a96216ed0e0_h
#include <rathen\config.h>
/*
* This version of API wrappers were used by the flex & bison due to the cpp generator was still unstable.
* Any kind of cpp style announcement should not appear in the header file.
*/
#ifndef __cplusplus
#ifdef _UNICODE
typedef wchar_t rchar;
#else
typedef char rchar;
#endif
#else
#include <gslib\string.h>
typedef gs::gchar rchar;
#endif
#ifndef __cplusplus
typedef void rpswrap;
typedef void rpsobj;
typedef void rpsparser;
#else
#include <rathen\parser.h>
typedef gs::rathen::parser::wrapper rpswrap;
typedef gs::rathen::ps_obj rpsobj;
typedef gs::rathen::parser rpsparser;
#endif
/* file: parser.h, line: 14 */
enum rpobj_tag
{
rpt_root,
rpt_block,
rpt_value,
rpt_expression,
rpt_operator,
rpt_function,
rpt_calling,
rpt_if_statement,
rpt_loop_statement,
rpt_go_statement,
rpt_stop_statement,
rpt_exit_statement,
rpt_variable,
rpt_constant,
};
enum rpv_tag
{
rvt_string,
rvt_integer,
rvt_float,
};
enum rps_encoding
{
rpe_ascii,
rpe_utf8,
rpe_utf16,
// ...
};
typedef struct
{
rps_encoding encoding;
const char* file;
char* source;
char* current;
int length;
int line;
int position;
}
rgcontext;
typedef struct
{
rps_encoding encoding;
const rchar* file;
char* source;
char* current;
int length;
int line;
int position;
const rchar* keyword;
rpsparser* parser;
rpswrap* wrapper;
}
rpscontext;
#ifdef __cplusplus
extern "C" {
#endif
extern void rathen_yy_setup(rgcontext* context, const char* file, rps_encoding encoding = rpe_utf8);
extern void rathen_yy_ssetup(rgcontext* context, const char* file, char* source, int length, rps_encoding encoding = rpe_utf8);
extern void rathen_yy_release(rgcontext* context);
extern rpscontext* rathen_yy_select(rpscontext* context);
extern void rathen_yy_parse(rpsparser* ps, const char* file);
extern void rathen_yy_sparse(rpsparser* ps, const char* file, char* source, int length);
extern int rathen_yy_read(char* buff, int* bytes, int cap);
extern bool rathen_is_type(const rchar* str, int len = -1);
extern bool rathen_is_keyword(const rchar* str, int len = -1);
extern rpsparser* rathen_create_parser(const rchar* name);
extern void rathen_destroy_parser(rpsparser* rps);
extern rpswrap* rathen_get_root(rpsparser* rps);
extern rpswrap* rathen_create_value(rpscontext* context, const rchar* name, const rchar* tyname, bool ref);
extern rpswrap* rathen_create_function(rpscontext* context, const rchar* name, const rchar* retyname, bool retref);
extern rpswrap* rathen_create_constant(rpscontext* context, const rchar* name, rpv_tag tag, const rchar* vstr);
//extern rpswrap* rathen_create();
#ifdef __cplusplus
};
#endif
#endif
| {
"alphanum_fraction": 0.6807900605,
"avg_line_length": 25.9421487603,
"ext": "h",
"hexsha": "2550ca62721d3a7cccfa45ec1463e46cea7c078d",
"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/rathen/rpsr.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/rathen/rpsr.h",
"max_line_length": 128,
"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/rathen/rpsr.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": 861,
"size": 3139
} |
#include <complex.h>
#include <math.h>
//#include <gsl/gsl_sf.h>
#include <stdio.h>
#include <stdlib.h>
#include "specfunc.h"
/*
* to compile as a library (that can be used by specfunc.py):
*
* cc -fPIC -c -O2 specfunc.c -o specfunc.o
* cc --shared specfunc.o -o libspecfunc.so
*
* if the gamma-function stuff an dthe parabolic cylinder function is commented
* in, you need
*
* cc --shared specfunc.o -o libspecfunc.so -lgslcblas -lgsl
*
* instead
*
* hyp2f1 and hyp1f1 seem to work well, the parabolic cylinder functions pcfd
* are problematic for anything but small arguments
*
* felix, june 2014
*/
#define PREC_WARN_LIMIT 1e99 // warn if individual terms in the series are larger than this
// XXX 4. 12. 14: set to high value because contrary to what I thought I had
// understood, there seem to be many perfectly fine cases where individual
// terms in the sum are higher than 10^15
// hypergeometric function for |z| < 1
double complex hyp2f1(const double complex a, const double complex b,
const double complex c, const double complex z, sf_prms_and_info_t* p)
{
double frac = p->tol;
double complex n = 0;
double complex summand = a*b/c * z;
double complex sum = 1. + summand;
p->prec_warning = 0;
for (n = 2; (creal(n) < p->max_iter) && (frac >= p->tol); n++)
{
summand *= (a+n-1)*(b+n-1)/(c+n-1) * z/n;
p->prec_warning = p->prec_warning | (creal(summand) > PREC_WARN_LIMIT)
| (cimag(summand) > PREC_WARN_LIMIT);
sum += summand;
frac = fabs(creal(summand/sum)) + fabs(cimag((summand/sum)));
}
p->iters_needed = (int)creal(n);
p->tol_achieved = frac;
return sum;
}
// confluent hypergeometric function
double complex hyp1f1(const double complex a, const double complex b,
const double complex z, sf_prms_and_info_t* p)
{
double frac = p->tol;
double complex n = 0;
double complex summand = a/b * z;
double complex sum = 1. + summand;
p->prec_warning = 0;
for (n = 2; (creal(n) < p->max_iter) && (frac >= p->tol) ; n++)
{
summand = summand/(b+n-1) * (a+n-1) * (z/n);
p->prec_warning = p->prec_warning | (creal(summand) > PREC_WARN_LIMIT)
| (cimag(summand) > PREC_WARN_LIMIT);
sum += summand;
frac = fabs(creal(summand/sum)) + fabs(cimag((summand/sum)));
}
p->iters_needed = (int)creal(n);
p->tol_achieved = frac;
return sum;
}
void hyp1f1_a_arr(const double complex* a, const double complex b,
const double complex z, double complex* out,
size_t n_arr, sf_prms_and_info_t* p)
{
double complex f = 0.;
double frac = 0.;
double maxfrac = p->tol;
double complex n = 0;
double complex* summand =
(double complex*)malloc(sizeof(double complex) * n_arr);
int i = 0;
for (i = 0; i < n_arr; i++)
{
summand[i] = a[i]/b * z;
out[i] = 1. + summand[i];
}
p->prec_warning = 0;
for (n = 2; (creal(n) < p->max_iter) && (maxfrac >= p->tol) ; n++)
{
maxfrac = 0;
f = 1./(b+n-1) * z / n; // same for all a
for (i = 0; i < n_arr; i++)
{
summand[i] *= f * (a[i]+n-1);
p->prec_warning = p->prec_warning | (creal(summand[i]) > PREC_WARN_LIMIT)
| (cimag(summand[i]) > PREC_WARN_LIMIT);
out[i] += summand[i];
frac = fabs(creal(summand[i]/out[i]))
+ fabs(cimag((summand[i]/out[i])));
maxfrac = frac > maxfrac ? frac : maxfrac;
}
}
p->iters_needed = (int)creal(n);
p->tol_achieved = maxfrac;
free(summand);
}
void hyp1f1_b_arr(const double complex a, const double complex* b,
const double complex z, double complex* out,
size_t n_arr, sf_prms_and_info_t* p)
{
double complex f = 0.;
double frac = 0.;
double maxfrac = p->tol;
double complex n = 0;
double complex* summand =
(double complex*)malloc(sizeof(double complex) * n_arr);
int i = 0;
for (i = 0; i < n_arr; i++)
{
summand[i] = a/b[i] * z;
out[i] = 1. + summand[i];
}
p->prec_warning = 0;
for (n = 2; (creal(n) < p->max_iter) && (maxfrac >= p->tol) ; n++)
{
maxfrac = 0;
f = (a+n-1) * z / n; // same for all b
for (i = 0; i < n_arr; i++)
{
summand[i] *= f / (b[i]+n-1);
p->prec_warning = p->prec_warning | (creal(summand[i]) > PREC_WARN_LIMIT)
| (cimag(summand[i]) > PREC_WARN_LIMIT);
out[i] += summand[i];
frac = fabs(creal(summand[i]/out[i]))
+ fabs(cimag((summand[i]/out[i])));
maxfrac = frac > maxfrac ? frac : maxfrac;
}
}
p->iters_needed = (int)creal(n);
p->tol_achieved = maxfrac;
free(summand);
}
void hyp1f1_z_arr(const double complex a, const double complex b,
const double complex* z, double complex* out,
size_t n_arr, sf_prms_and_info_t* p)
{
double complex f = 0.;
double frac = 0.;
double maxfrac = p->tol;
double complex n = 0;
double complex* summand =
(double complex*)malloc(sizeof(double complex) * n_arr);
int i = 0;
for (i = 0; i < n_arr; i++)
{
summand[i] = a/b * z[i];
out[i] = 1. + summand[i];
}
p->prec_warning = 0;
for (n = 2; (creal(n) < p->max_iter) && (maxfrac >= p->tol) ; n++)
{
maxfrac = 0;
f = (a+n-1)/(b+n-1) / n; // same for all z
for (i = 0; i < n_arr; i++)
{
summand[i] *= f * z[i];
p->prec_warning = p->prec_warning | (creal(summand[i]) > PREC_WARN_LIMIT)
| (cimag(summand[i]) > PREC_WARN_LIMIT);
out[i] += summand[i];
frac = fabs(creal(summand[i]/out[i]))
+ fabs(cimag((summand[i]/out[i])));
maxfrac = frac > maxfrac ? frac : maxfrac;
}
}
p->iters_needed = (int)creal(n);
p->tol_achieved = maxfrac;
free(summand);
}
void hyp1f1_all_arr(const double complex* a, const double complex* b,
const double complex* z, double complex* out,
size_t n_arr, sf_prms_and_info_t* p)
{
int i = 0;
for (i = 0; i < n_arr; i++)
out[i] = hyp1f1(a[i], b[i], z[i], p);
}
/*
double complex cgamma(const double complex z)
{
gsl_sf_result lnabs = {0, 0};
gsl_sf_result arg = {0, 0};
gsl_sf_lngamma_complex_e(creal(z), cimag(z), &lnabs, &arg);
return cexp(lnabs.val+1j*arg.val);
}
// parabolic cylinder function -- this is only ok for small parameters
double complex pcfd(const double complex nu, const double complex z,
sf_prms_and_info_t* p)
{
return cpow(2, nu/2)*cexp(-z*z/4) * csqrt(M_PI) *
(1./cgamma((1-nu)/2) * hyp1f1(-nu/2, 1./2, z*z/2, p)
- csqrt(2.)*z/cgamma(-nu/2)
* hyp1f1((1-nu)/2, 3./2, z*z/2, p));
}
void pcfd_nu_arr(const double complex* nu, const double complex z,
double complex* out, size_t n_arr, sf_prms_and_info_t* p)
{
int i = 0;
for (i = 0; i < n_arr; i++)
{
out[i] = pcfd(nu[i], z, p);
}
}
void pcfd_z_arr(const double complex nu, const double complex* z,
double complex* out, size_t n_arr, sf_prms_and_info_t* p)
{
int i = 0;
for (i = 0; i < n_arr; i++)
{
out[i] = pcfd(nu, z[i], p);
}
}
*/
void hyp2f1_a_arr(const double complex* a, const double complex b,
const double complex c, const double complex z, double complex* out,
size_t n_arr, sf_prms_and_info_t* p)
{
double complex f = 0.;
double frac = 0.;
double maxfrac = p->tol;
double complex n = 0;
double complex* summand =
(double complex*)malloc(sizeof(double complex) * n_arr);
int i = 0;
for (i = 0; i < n_arr; i++)
{
summand[i] = a[i]*b/c * z;
out[i] = 1. + summand[i];
}
p->prec_warning = 0;
for (n = 2; (creal(n) < p->max_iter) && (maxfrac >= p->tol) ; n++)
{
maxfrac = 0;
f = (b+n-1)/(c+n-1) * z / n; // same for all a
for (i = 0; i < n_arr; i++)
{
summand[i] *= f * (a[i]+n-1);
p->prec_warning = p->prec_warning | (creal(summand[i]) > PREC_WARN_LIMIT)
| (cimag(summand[i]) > PREC_WARN_LIMIT);
out[i] += summand[i];
frac = fabs(creal(summand[i]/out[i]))
+ fabs(cimag((summand[i]/out[i])));
maxfrac = frac > maxfrac ? frac : maxfrac;
}
}
p->iters_needed = (int)creal(n);
p->tol_achieved = maxfrac;
free(summand);
}
void hyp2f1_b_arr(const double complex a, const double complex* b,
const double complex c, const double complex z, double complex* out,
size_t n_arr, sf_prms_and_info_t* p)
{
hyp2f1_a_arr(b, a, c, z, out, n_arr, p);
}
void hyp2f1_c_arr(const double complex a, const double complex b,
const double complex* c, const double complex z, double complex* out,
size_t n_arr, sf_prms_and_info_t* p)
{
double complex f = 0.;
double frac = 0.;
double maxfrac = p->tol;
double complex n = 0;
double complex* summand =
(double complex*)malloc(sizeof(double complex) * n_arr);
int i = 0;
for (i = 0; i < n_arr; i++)
{
summand[i] = a*b/c[i] * z;
out[i] = 1. + summand[i];
}
p->prec_warning = 0;
for (n = 2; (creal(n) < p->max_iter) && (maxfrac >= p->tol) ; n++)
{
maxfrac = 0;
f = (a+n-1)*(b+n-1) * z / n; // same for all a
for (i = 0; i < n_arr; i++)
{
summand[i] *= f / (c[i]+n-1);
p->prec_warning = p->prec_warning | (creal(summand[i]) > PREC_WARN_LIMIT)
| (cimag(summand[i]) > PREC_WARN_LIMIT);
out[i] += summand[i];
frac = fabs(creal(summand[i]/out[i]))
+ fabs(cimag((summand[i]/out[i])));
maxfrac = frac > maxfrac ? frac : maxfrac;
}
}
p->iters_needed = (int)creal(n);
p->tol_achieved = maxfrac;
free(summand);
}
// hyp2d1 for an array of z values
void hyp2f1_z_arr(const double complex a, const double complex b,
const double complex c, const double complex* z, double complex* out,
size_t n_arr, sf_prms_and_info_t* p)
{
double complex f = 0.;
double frac = 0.;
double maxfrac = p->tol;
double complex n = 0;
double complex* summand =
(double complex*)malloc(sizeof(double complex) * n_arr);
int i = 0;
for (i = 0; i < n_arr; i++)
{
summand[i] = a*b/c * z[i];
out[i] = 1. + summand[i];
}
p->prec_warning = 0;
for (n = 2; (creal(n) < p->max_iter) && (maxfrac >= p->tol) ; n++)
{
maxfrac = 0;
f = (a+n-1)*(b+n-1)/(c+n-1) / n; // same for all zs
for (i = 0; i < n_arr; i++)
{
summand[i] *= f * z[i];
p->prec_warning = p->prec_warning | (creal(summand[i]) > PREC_WARN_LIMIT)
| (cimag(summand[i]) > PREC_WARN_LIMIT);
out[i] += summand[i];
frac = fabs(creal(summand[i]/out[i]))
+ fabs(cimag((summand[i]/out[i])));
maxfrac = frac > maxfrac ? frac : maxfrac;
}
}
p->iters_needed = (int)creal(n);
p->tol_achieved = maxfrac;
free(summand);
}
void hyp2f1_all_arr(const double complex* a, const double complex* b,
const double complex* c, const double complex* z, double complex* out,
size_t n_arr, sf_prms_and_info_t* p)
{
int i = 0;
for (i = 0; i < n_arr; i++)
out[i] = hyp2f1(a[i], b[i], c[i], z[i], p);
}
| {
"alphanum_fraction": 0.5295095594,
"avg_line_length": 31.7414248021,
"ext": "c",
"hexsha": "10bdcfe23b6da02e88fdf2bc01a2645f1bf591cb",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ModelDBRepository/228604",
"max_forks_repo_path": "analytics/specfunc/specfunc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "ModelDBRepository/228604",
"max_issues_repo_path": "analytics/specfunc/specfunc.c",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ModelDBRepository/228604",
"max_stars_repo_path": "analytics/specfunc/specfunc.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3738,
"size": 12030
} |
/* matrix/gsl_matrix_char.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_CHAR_H__
#define __GSL_MATRIX_CHAR_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_char.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;
char * data;
gsl_block_char * block;
int owner;
} gsl_matrix_char;
typedef struct
{
gsl_matrix_char matrix;
} _gsl_matrix_char_view;
typedef _gsl_matrix_char_view gsl_matrix_char_view;
typedef struct
{
gsl_matrix_char matrix;
} _gsl_matrix_char_const_view;
typedef const _gsl_matrix_char_const_view gsl_matrix_char_const_view;
/* Allocation */
GSL_FUN gsl_matrix_char *
gsl_matrix_char_alloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_char *
gsl_matrix_char_calloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_char *
gsl_matrix_char_alloc_from_block (gsl_block_char * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
GSL_FUN gsl_matrix_char *
gsl_matrix_char_alloc_from_matrix (gsl_matrix_char * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
GSL_FUN gsl_vector_char *
gsl_vector_char_alloc_row_from_matrix (gsl_matrix_char * m,
const size_t i);
GSL_FUN gsl_vector_char *
gsl_vector_char_alloc_col_from_matrix (gsl_matrix_char * m,
const size_t j);
GSL_FUN void gsl_matrix_char_free (gsl_matrix_char * m);
/* Views */
GSL_FUN _gsl_matrix_char_view
gsl_matrix_char_submatrix (gsl_matrix_char * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_char_view
gsl_matrix_char_row (gsl_matrix_char * m, const size_t i);
GSL_FUN _gsl_vector_char_view
gsl_matrix_char_column (gsl_matrix_char * m, const size_t j);
GSL_FUN _gsl_vector_char_view
gsl_matrix_char_diagonal (gsl_matrix_char * m);
GSL_FUN _gsl_vector_char_view
gsl_matrix_char_subdiagonal (gsl_matrix_char * m, const size_t k);
GSL_FUN _gsl_vector_char_view
gsl_matrix_char_superdiagonal (gsl_matrix_char * m, const size_t k);
GSL_FUN _gsl_vector_char_view
gsl_matrix_char_subrow (gsl_matrix_char * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_char_view
gsl_matrix_char_subcolumn (gsl_matrix_char * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_char_view
gsl_matrix_char_view_array (char * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_char_view
gsl_matrix_char_view_array_with_tda (char * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_char_view
gsl_matrix_char_view_vector (gsl_vector_char * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_char_view
gsl_matrix_char_view_vector_with_tda (gsl_vector_char * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_char_const_view
gsl_matrix_char_const_submatrix (const gsl_matrix_char * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_char_const_view
gsl_matrix_char_const_row (const gsl_matrix_char * m,
const size_t i);
GSL_FUN _gsl_vector_char_const_view
gsl_matrix_char_const_column (const gsl_matrix_char * m,
const size_t j);
GSL_FUN _gsl_vector_char_const_view
gsl_matrix_char_const_diagonal (const gsl_matrix_char * m);
GSL_FUN _gsl_vector_char_const_view
gsl_matrix_char_const_subdiagonal (const gsl_matrix_char * m,
const size_t k);
GSL_FUN _gsl_vector_char_const_view
gsl_matrix_char_const_superdiagonal (const gsl_matrix_char * m,
const size_t k);
GSL_FUN _gsl_vector_char_const_view
gsl_matrix_char_const_subrow (const gsl_matrix_char * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_char_const_view
gsl_matrix_char_const_subcolumn (const gsl_matrix_char * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_char_const_view
gsl_matrix_char_const_view_array (const char * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_char_const_view
gsl_matrix_char_const_view_array_with_tda (const char * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_char_const_view
gsl_matrix_char_const_view_vector (const gsl_vector_char * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_char_const_view
gsl_matrix_char_const_view_vector_with_tda (const gsl_vector_char * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_FUN void gsl_matrix_char_set_zero (gsl_matrix_char * m);
GSL_FUN void gsl_matrix_char_set_identity (gsl_matrix_char * m);
GSL_FUN void gsl_matrix_char_set_all (gsl_matrix_char * m, char x);
GSL_FUN int gsl_matrix_char_fread (FILE * stream, gsl_matrix_char * m) ;
GSL_FUN int gsl_matrix_char_fwrite (FILE * stream, const gsl_matrix_char * m) ;
GSL_FUN int gsl_matrix_char_fscanf (FILE * stream, gsl_matrix_char * m);
GSL_FUN int gsl_matrix_char_fprintf (FILE * stream, const gsl_matrix_char * m, const char * format);
GSL_FUN int gsl_matrix_char_memcpy(gsl_matrix_char * dest, const gsl_matrix_char * src);
GSL_FUN int gsl_matrix_char_swap(gsl_matrix_char * m1, gsl_matrix_char * m2);
GSL_FUN int gsl_matrix_char_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_char * dest, const gsl_matrix_char * src);
GSL_FUN int gsl_matrix_char_swap_rows(gsl_matrix_char * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_char_swap_columns(gsl_matrix_char * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_char_swap_rowcol(gsl_matrix_char * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_char_transpose (gsl_matrix_char * m);
GSL_FUN int gsl_matrix_char_transpose_memcpy (gsl_matrix_char * dest, const gsl_matrix_char * src);
GSL_FUN int gsl_matrix_char_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_char * dest, const gsl_matrix_char * src);
GSL_FUN char gsl_matrix_char_max (const gsl_matrix_char * m);
GSL_FUN char gsl_matrix_char_min (const gsl_matrix_char * m);
GSL_FUN void gsl_matrix_char_minmax (const gsl_matrix_char * m, char * min_out, char * max_out);
GSL_FUN void gsl_matrix_char_max_index (const gsl_matrix_char * m, size_t * imax, size_t *jmax);
GSL_FUN void gsl_matrix_char_min_index (const gsl_matrix_char * m, size_t * imin, size_t *jmin);
GSL_FUN void gsl_matrix_char_minmax_index (const gsl_matrix_char * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_FUN int gsl_matrix_char_equal (const gsl_matrix_char * a, const gsl_matrix_char * b);
GSL_FUN int gsl_matrix_char_isnull (const gsl_matrix_char * m);
GSL_FUN int gsl_matrix_char_ispos (const gsl_matrix_char * m);
GSL_FUN int gsl_matrix_char_isneg (const gsl_matrix_char * m);
GSL_FUN int gsl_matrix_char_isnonneg (const gsl_matrix_char * m);
GSL_FUN int gsl_matrix_char_add (gsl_matrix_char * a, const gsl_matrix_char * b);
GSL_FUN int gsl_matrix_char_sub (gsl_matrix_char * a, const gsl_matrix_char * b);
GSL_FUN int gsl_matrix_char_mul_elements (gsl_matrix_char * a, const gsl_matrix_char * b);
GSL_FUN int gsl_matrix_char_div_elements (gsl_matrix_char * a, const gsl_matrix_char * b);
GSL_FUN int gsl_matrix_char_scale (gsl_matrix_char * a, const double x);
GSL_FUN int gsl_matrix_char_scale_rows (gsl_matrix_char * a, const gsl_vector_char * x);
GSL_FUN int gsl_matrix_char_scale_columns (gsl_matrix_char * a, const gsl_vector_char * x);
GSL_FUN int gsl_matrix_char_add_constant (gsl_matrix_char * a, const double x);
GSL_FUN int gsl_matrix_char_add_diagonal (gsl_matrix_char * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_FUN int gsl_matrix_char_get_row(gsl_vector_char * v, const gsl_matrix_char * m, const size_t i);
GSL_FUN int gsl_matrix_char_get_col(gsl_vector_char * v, const gsl_matrix_char * m, const size_t j);
GSL_FUN int gsl_matrix_char_set_row(gsl_matrix_char * m, const size_t i, const gsl_vector_char * v);
GSL_FUN int gsl_matrix_char_set_col(gsl_matrix_char * m, const size_t j, const gsl_vector_char * v);
/***********************************************************************/
/* inline functions if you are using GCC */
GSL_FUN INLINE_DECL char gsl_matrix_char_get(const gsl_matrix_char * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL void gsl_matrix_char_set(gsl_matrix_char * m, const size_t i, const size_t j, const char x);
GSL_FUN INLINE_DECL char * gsl_matrix_char_ptr(gsl_matrix_char * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL const char * gsl_matrix_char_const_ptr(const gsl_matrix_char * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
char
gsl_matrix_char_get(const gsl_matrix_char * 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_char_set(gsl_matrix_char * m, const size_t i, const size_t j, const char 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
char *
gsl_matrix_char_ptr(gsl_matrix_char * 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 (char *) (m->data + (i * m->tda + j)) ;
}
INLINE_FUN
const char *
gsl_matrix_char_const_ptr(const gsl_matrix_char * 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 char *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_CHAR_H__ */
| {
"alphanum_fraction": 0.6652932804,
"avg_line_length": 36.4726775956,
"ext": "h",
"hexsha": "9a691829abc335d744efd1658b4dc00cb1e36461",
"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": "0073e0515b87610b7f88ad2b07fc7d23618c159a",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "zhanghe9704/jspec2",
"max_forks_repo_path": "include/gsl/gsl_matrix_char.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a",
"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": "zhanghe9704/jspec2",
"max_issues_repo_path": "include/gsl/gsl_matrix_char.h",
"max_line_length": 141,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "zhanghe9704/jspec2",
"max_stars_repo_path": "include/gsl/gsl_matrix_char.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": 3339,
"size": 13349
} |
/* roots/demo1.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Reid Priedhorsky, 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 <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_roots.h>
#include "demof.h"
#include "demof.c"
int
main ()
{
int status;
int iterations = 0, max_iterations = 100;
gsl_root_fdfsolver *s;
double x0, x = 5.0, r_expected = sqrt (5.0);
gsl_function_fdf FDF;
struct quadratic_params params = {1.0, 0.0, -5.0};
FDF.f = &quadratic;
FDF.df = &quadratic_deriv;
FDF.fdf = &quadratic_fdf;
FDF.params = ¶ms;
s = gsl_root_fdfsolver_alloc (gsl_root_fdfsolver_newton);
gsl_root_fdfsolver_set (s, &FDF, x);
printf ("using %s method\n", gsl_root_fdfsolver_name (s));
printf ("%-5s %10s %10s %10s %10s\n",
"iter", "root", "actual", "err", "err(est)");
do
{
iterations++;
status = gsl_root_fdfsolver_iterate (s);
x0 = x;
x = gsl_root_fdfsolver_root (s);
status = gsl_root_test_delta (x, x0, 0, 0.001);
if (status == GSL_SUCCESS)
printf ("Converged:\n");
printf ("%5d %10.7f %10.7f %+10.7f %10.7f\n",
iterations, x, r_expected, x - r_expected, x - x0);
}
while (status == GSL_CONTINUE && iterations < max_iterations);
}
| {
"alphanum_fraction": 0.668,
"avg_line_length": 29.8507462687,
"ext": "c",
"hexsha": "9d8eb47c66051195b19f17792124063dcd295d55",
"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/roots/demo1.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/roots/demo1.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/roots/demo1.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": 607,
"size": 2000
} |
/* rng/taus.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_rng.h>
/* This is a maximally equidistributed combined Tausworthe
generator. The sequence is,
x_n = (s1_n ^ s2_n ^ s3_n)
s1_{n+1} = (((s1_n & 4294967294) <<12) ^ (((s1_n <<13) ^ s1_n) >>19))
s2_{n+1} = (((s2_n & 4294967288) << 4) ^ (((s2_n << 2) ^ s2_n) >>25))
s3_{n+1} = (((s3_n & 4294967280) <<17) ^ (((s3_n << 3) ^ s3_n) >>11))
computed modulo 2^32. In the three formulas above '^' means
exclusive-or (C-notation), not exponentiation. Note that the
algorithm relies on the properties of 32-bit unsigned integers (it
is formally defined on bit-vectors of length 32). I have added a
bitmask to make it work on 64 bit machines.
We initialize the generator with s1_1 .. s3_1 = s_n MOD m, where
s_n = (69069 * s_{n-1}) mod 2^32, and s_0 = s is the user-supplied
seed.
The theoretical value of x_{10007} is 2733957125. The subscript
10007 means (1) seed the generator with s=1 (2) do six warm-up
iterations, (3) then do 10000 actual iterations.
The period of this generator is about 2^88.
From: P. L'Ecuyer, "Maximally Equidistributed Combined Tausworthe
Generators", Mathematics of Computation, 65, 213 (1996), 203--213.
This is available on the net from L'Ecuyer's home page,
http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme.ps
ftp://ftp.iro.umontreal.ca/pub/simulation/lecuyer/papers/tausme.ps
Update: April 2002
There is an erratum in the paper "Tables of Maximally
Equidistributed Combined LFSR Generators", Mathematics of
Computation, 68, 225 (1999), 261--269:
http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps
... the k_j most significant bits of z_j must be non-
zero, for each j. (Note: this restriction also applies to the
computer code given in [4], but was mistakenly not mentioned in
that paper.)
This affects the seeding procedure by imposing the requirement
s1 > 1, s2 > 7, s3 > 15.
The generator taus2 has been added to satisfy this requirement.
The original taus generator is unchanged.
Update: November 2002
There was a bug in the correction to the seeding procedure for s2.
It affected the following seeds 254679140 1264751179 1519430319
2274823218 2529502358 3284895257 3539574397 (s2 < 8).
*/
static inline unsigned long int taus_get (void *vstate);
static double taus_get_double (void *vstate);
static void taus_set (void *state, unsigned long int s);
typedef struct
{
unsigned long int s1, s2, s3;
}
taus_state_t;
static inline unsigned long
taus_get (void *vstate)
{
taus_state_t *state = (taus_state_t *) vstate;
#define MASK 0xffffffffUL
#define TAUSWORTHE(s,a,b,c,d) (((s &c) <<d) &MASK) ^ ((((s <<a) &MASK)^s) >>b)
state->s1 = TAUSWORTHE (state->s1, 13, 19, 4294967294UL, 12);
state->s2 = TAUSWORTHE (state->s2, 2, 25, 4294967288UL, 4);
state->s3 = TAUSWORTHE (state->s3, 3, 11, 4294967280UL, 17);
return (state->s1 ^ state->s2 ^ state->s3);
}
static double
taus_get_double (void *vstate)
{
return taus_get (vstate) / 4294967296.0 ;
}
static void
taus_set (void *vstate, unsigned long int s)
{
taus_state_t *state = (taus_state_t *) vstate;
if (s == 0)
s = 1; /* default seed is 1 */
#define LCG(n) ((69069 * n) & 0xffffffffUL)
state->s1 = LCG (s);
state->s2 = LCG (state->s1);
state->s3 = LCG (state->s2);
/* "warm it up" */
taus_get (state);
taus_get (state);
taus_get (state);
taus_get (state);
taus_get (state);
taus_get (state);
return;
}
static void
taus2_set (void *vstate, unsigned long int s)
{
taus_state_t *state = (taus_state_t *) vstate;
if (s == 0)
s = 1; /* default seed is 1 */
#define LCG(n) ((69069 * n) & 0xffffffffUL)
state->s1 = LCG (s);
if (state->s1 < 2) state->s1 += 2UL;
state->s2 = LCG (state->s1);
if (state->s2 < 8) state->s2 += 8UL;
state->s3 = LCG (state->s2);
if (state->s3 < 16) state->s3 += 16UL;
/* "warm it up" */
taus_get (state);
taus_get (state);
taus_get (state);
taus_get (state);
taus_get (state);
taus_get (state);
return;
}
static const gsl_rng_type taus_type =
{"taus", /* name */
0xffffffffUL, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (taus_state_t),
&taus_set,
&taus_get,
&taus_get_double};
const gsl_rng_type *gsl_rng_taus = &taus_type;
static const gsl_rng_type taus2_type =
{"taus2", /* name */
0xffffffffUL, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (taus_state_t),
&taus2_set,
&taus_get,
&taus_get_double};
const gsl_rng_type *gsl_rng_taus2 = &taus2_type;
| {
"alphanum_fraction": 0.6583783784,
"avg_line_length": 30,
"ext": "c",
"hexsha": "fd039f54025f618e35b8b97ddf49f6964940e970",
"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/taus.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/taus.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/taus.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": 1806,
"size": 5550
} |
#ifndef _H_MAIN
#define _H_MAIN
#define CPP 0
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <gsl/gsl_linalg.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#if CPP
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#endif
#define WW 640
#define WH 480
#define RAD(d) (d) * (M_PI/180)
#define ZEROCHK(i) ((i) == 0)?0:i
extern GLFWwindow *window;
extern GLuint tr_vb;
extern GLuint tr_c_vb;
extern GLuint va;
extern GLuint vs;
extern GLuint fs;
extern GLuint shader_bin;
uint64_t timer[10];
extern void cookTriangle(void);
extern void cookCube(void);
extern uint64_t getCycles(void);
extern char * readFile(char *);
extern void debugSC(GLuint);
extern uint64_t getCycles(void);
extern gsl_matrix * m_new_diag(uint32_t);
extern gsl_matrix * m_new(uint32_t, uint32_t);
extern void m_setT(gsl_matrix *, double, double, double, uint8_t);
extern void m_setRy(gsl_matrix *, double, uint8_t);
extern void m_mul(gsl_matrix *, gsl_matrix *, gsl_matrix *);
extern void m_print(gsl_matrix *, uint8_t, uint8_t);
extern void m_array(gsl_matrix *, uint8_t, uint8_t, float *);
extern void glmPerspective(double, double, double, double, gsl_matrix *);
extern void normalize(double *, uint8_t, double *);
extern double getVectorLength(double *, uint8_t);
extern void getCrossV3(double *, double *, double *);
extern double scalar(double *, double *, uint8_t);
extern void subVec(double *, double *, uint8_t, double *);
extern void glmLookAt(double *, double *, double *, gsl_matrix *);
extern void m_set_all(gsl_matrix *, double);
#include "lib.c"
#include "mat.c"
#endif | {
"alphanum_fraction": 0.7415128052,
"avg_line_length": 27.0806451613,
"ext": "h",
"hexsha": "cfd24e5e839b325235fd778a4247365f608df89d",
"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": "b5d2a4adce90fe34b78edb6b7a29671b84fb4a70",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gtsh77/GL_playground",
"max_forks_repo_path": "src/main.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b5d2a4adce90fe34b78edb6b7a29671b84fb4a70",
"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": "gtsh77/GL_playground",
"max_issues_repo_path": "src/main.h",
"max_line_length": 73,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b5d2a4adce90fe34b78edb6b7a29671b84fb4a70",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gtsh77/GL_playground",
"max_stars_repo_path": "src/main.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 444,
"size": 1679
} |
/* ode-initval/rk2.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 2(3), Euler-Cauchy */
/* Author: G. Jungman
*/
/* Reference: Abramowitz & Stegun, section 25.5. Runge-Kutta 2nd (25.5.7)
and 3rd (25.5.8) order methods */
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv.h>
#include "odeiv_util.h"
typedef struct
{
double *k1;
double *k2;
double *k3;
double *ytmp;
}
rk2_state_t;
static void *
rk2_alloc (size_t dim)
{
rk2_state_t *state = (rk2_state_t *) malloc (sizeof (rk2_state_t));
if (state == 0)
{
GSL_ERROR_NULL ("failed to allocate space for rk2_state", GSL_ENOMEM);
}
state->k1 = (double *) malloc (dim * sizeof (double));
if (state->k1 == 0)
{
free (state);
GSL_ERROR_NULL ("failed to allocate space for k1", GSL_ENOMEM);
}
state->k2 = (double *) malloc (dim * sizeof (double));
if (state->k2 == 0)
{
free (state->k1);
free (state);
GSL_ERROR_NULL ("failed to allocate space for k2", GSL_ENOMEM);
}
state->k3 = (double *) malloc (dim * sizeof (double));
if (state->k3 == 0)
{
free (state->k2);
free (state->k1);
free (state);
GSL_ERROR_NULL ("failed to allocate space for k2", GSL_ENOMEM);
}
state->ytmp = (double *) malloc (dim * sizeof (double));
if (state->ytmp == 0)
{
free (state->k3);
free (state->k2);
free (state->k1);
free (state);
GSL_ERROR_NULL ("failed to allocate space for k2", GSL_ENOMEM);
}
return state;
}
static int
rk2_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)
{
rk2_state_t *state = (rk2_state_t *) vstate;
size_t i;
double *const k1 = state->k1;
double *const k2 = state->k2;
double *const k3 = state->k3;
double *const ytmp = state->ytmp;
/* k1 step */
/* k1 = f(t,y) */
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;
}
}
/* k2 step */
/* k2 = f(t + 0.5*h, y + 0.5*k1) */
for (i = 0; i < dim; i++)
{
ytmp[i] = y[i] + 0.5 * h * k1[i];
}
{
int s = GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h, ytmp, k2);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* k3 step */
/* for 3rd order estimates, is used for error estimation
k3 = f(t + h, y - k1 + 2*k2) */
for (i = 0; i < dim; i++)
{
ytmp[i] = y[i] + h * (-k1[i] + 2.0 * k2[i]);
}
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, ytmp, k3);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* final sum */
for (i = 0; i < dim; i++)
{
/* Save original values if derivative evaluation below fails */
ytmp[i] = y[i];
{
const double ksum3 = (k1[i] + 4.0 * k2[i] + k3[i]) / 6.0;
y[i] += h * ksum3;
}
}
/* Derivatives at output */
if (dydt_out != NULL)
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out);
if (s != GSL_SUCCESS)
{
/* Restore original values */
DBL_MEMCPY (y, ytmp, dim);
return s;
}
}
/* Error estimation */
for (i = 0; i < dim; i++)
{
const double ksum3 = (k1[i] + 4.0 * k2[i] + k3[i]) / 6.0;
yerr[i] = h * (k2[i] - ksum3);
}
return GSL_SUCCESS;
}
static int
rk2_reset (void *vstate, size_t dim)
{
rk2_state_t *state = (rk2_state_t *) vstate;
DBL_ZERO_MEMSET (state->k1, dim);
DBL_ZERO_MEMSET (state->k2, dim);
DBL_ZERO_MEMSET (state->k3, dim);
DBL_ZERO_MEMSET (state->ytmp, dim);
return GSL_SUCCESS;
}
static unsigned int
rk2_order (void *vstate)
{
rk2_state_t *state = (rk2_state_t *) vstate;
state = 0; /* prevent warnings about unused parameters */
return 2;
}
static void
rk2_free (void *vstate)
{
rk2_state_t *state = (rk2_state_t *) vstate;
free (state->k1);
free (state->k2);
free (state->k3);
free (state->ytmp);
free (state);
}
static const gsl_odeiv_step_type rk2_type = { "rk2", /* name */
1, /* can use dydt_in */
1, /* gives exact dydt_out */
&rk2_alloc,
&rk2_apply,
&rk2_reset,
&rk2_order,
&rk2_free
};
const gsl_odeiv_step_type *gsl_odeiv_step_rk2 = &rk2_type;
| {
"alphanum_fraction": 0.5747038594,
"avg_line_length": 20.8525896414,
"ext": "c",
"hexsha": "e7696d1146f08bef6144280fd929fa2b75698a84",
"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/rk2.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/rk2.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/rk2.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": 1716,
"size": 5234
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include "compearth.h"
#ifdef COMPEARTH_USE_MKL
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wstrict-prototypes"
#endif
#include <mkl_cblas.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#else
#include <cblas.h>
#endif
#define deg 180.0/M_PI;
/*!
* @brief Returns the angle between two vectors, in degrees.
*
* @param[in] n Length of vectors.
* @param[in] va Initial vector. This is an array of dimension [n].
* @param[in] vb Rotate vector. This is an array of dimension [n].
*
* @result Rotation angle in degrees between va and vb.
*
* @author Ben Baker
*
* @copyright MIT
*
*/
double compearth_matlab_fangle(const int n,
const double *__restrict__ va,
const double *__restrict__ vb)
{
double angle, magVa, magVb, xden, xnum;
xnum = cblas_ddot(n, va, 1, vb, 1);
magVa = cblas_dnrm2(n, va, 1);
magVb = cblas_dnrm2(n, vb, 1);
xden = magVa*magVb;
angle = (double) NAN;
if (xden > 0.0){angle = acos(xnum/xden)*deg;}
return angle;
}
| {
"alphanum_fraction": 0.6519607843,
"avg_line_length": 25.5,
"ext": "c",
"hexsha": "97a161f4f758df8ca0b5babc648a503da44219da",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z",
"max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "carltape/mtbeach",
"max_forks_repo_path": "c_src/fangle.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "carltape/mtbeach",
"max_issues_repo_path": "c_src/fangle.c",
"max_line_length": 70,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "OUCyf/mtbeach",
"max_stars_repo_path": "c_src/fangle.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z",
"num_tokens": 345,
"size": 1224
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
/* Gaussian function */
double tgauss(double x,double sigma)
{
double y,z,a=2.506628273;
z = x / sigma;
y = exp((double)-z*z*0.5)/(sigma * a);
return y;
}
/* create a Gaussian kernel for convolution */
gsl_vector *CGaussKernel(double sigma)
{
int i,dim,n;
double x,u,step;
gsl_vector *kernel;
/* no temporal smoothing */
if (sigma < 0.001) return NULL;
dim = 4.0 * sigma + 1;
n = 2*dim+1;
step = 1;
kernel = gsl_vector_alloc(n);
x = -(float)dim;
for (i=0; i<n; i++) {
u = tgauss(x,sigma);
gsl_vector_set(kernel,i,u);
x += step;
}
return kernel;
}
/* fill gaussian matrix */
void GaussMatrix(gsl_matrix *S,gsl_vector *kernel)
{
int dim = kernel->size/2;
int i,j,k;
gsl_matrix_set_zero(S);
for (i=0; i<S->size1; i++) {
double sum = 0;
for (j=0; j<S->size2; j++) {
k = i-j+dim;
if (k < 0 || k >= kernel->size) continue;
double x = gsl_vector_get(kernel,k);
sum += x;
gsl_matrix_set(S,i,j,x);
}
/* normalize */
for (j=0; j<S->size2; j++) {
double x = gsl_matrix_get(S,i,j);
gsl_matrix_set(S,i,j,x/sum);
}
}
}
void VectorConvolve(const double *src,gsl_vector *dst,gsl_vector *kernel)
{
int i,j,k,len,n,dim;
double sum;
dim = kernel->size/2;
len = dst->size;
n = len - dim;
for (i=dim; i<n; i++) {
sum = 0;
k=0;
for (j=i-dim; j<=i+dim; j++) {
sum += src[j] * kernel->data[k];
k++;
}
dst->data[i] = sum;
}
/* Randbehandlung */
for (i=0; i<dim; i++) {
dst->data[i] = src[i];
}
for (i=n; i<len; i++) {
dst->data[i] = src[i];
}
}
| {
"alphanum_fraction": 0.5502257336,
"avg_line_length": 17.898989899,
"ext": "c",
"hexsha": "fe39a2b51ca32b065c3de6f4450be0f804e4f2dd",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/stats/vlisa_precoloring/gauss.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/stats/vlisa_precoloring/gauss.c",
"max_line_length": 73,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/stats/vlisa_precoloring/gauss.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": 610,
"size": 1772
} |
#include <stdio.h>
#include <getopt.h>
#include <omp.h>
#include <math.h>
#include <string.h>
#ifdef __APPLE__
#include <cblas.h>
#define set_num_threads(x) openblas_set_num_threads(x)
#define get_num_threads() openblas_get_num_threads()
#else
#include <mkl.h>
#define set_num_threads(x) mkl_set_num_threads(x)
#define get_num_threads() mkl_get_num_threads()
#endif
double norm_inf_mat_Y11(double *X, int n, int extra);
int main(int argc, char **argv) {
int n, i, j;
char *filename = NULL;
double tolerance = 1e-8;
int option = 0;
int threads_num = 1;
while ((option = getopt(argc, argv, "t:f:")) != -1) {
switch (option) {
case 'f':
filename = optarg;
break;
case 't':
threads_num = atoi(optarg);
break;
default:
printf("Usage: mexp -f string \n");
return 0;
}
}
if (filename == NULL) {
printf("Usage: mexp -t num_threads -f string \n");
return 0;
}
double *A = NULL, *R = NULL, *B = NULL, *W = NULL;
double *x, *r, *p, *w;
FILE *file = fopen(filename, "rb");
if (!file) {
printf("Unable to open file!");
return 0;
}
fread(&n, sizeof(int), 1, file);
A = (double *) malloc((n + 1) * (n + 1) * sizeof(double));
R = (double *) malloc((n + 1) * (n + 1) * sizeof(double));
B = (double *) malloc((n + 1) * sizeof(double));
W = (double *) malloc(n * sizeof(double));
x = (double *) malloc(n * sizeof(double));
r = (double *) malloc(n * sizeof(double));
p = (double *) malloc(n * sizeof(double));
w = (double *) malloc(n * sizeof(double));
printf("set_threads_num:%d\t", threads_num++);
fseek(file, 0, SEEK_SET);
fread(&n, sizeof(int), 1, file);
//fseek(file, sizeof(int), SEEK_SET);
memset(A, 0, sizeof(double) * (n + 1) * (n + 1));
memset(R, 0, sizeof(double) * (n + 1) * (n + 1));
for (i = 0; i < n; ++i) {
fread(A + i * (n + 1), sizeof(double), (size_t) n, file);
}
memset(B, 0, sizeof(double) * (n + 1));
fread(B, sizeof(double), (size_t) n, file);
set_num_threads(threads_num);
omp_set_num_threads(threads_num);
cblas_dcopy(n, B, 1, A + n, n + 1);
double omp_time = omp_get_wtime();
double lambda = norm_inf_mat_Y11(A, n, 1);
//init Y matrix
for (i = 0; i < n; ++i) {
double *A_T = A + i * (n + 1);
#pragma omp parallel for
for (j = 0; j < n; ++j) {
A_T[j] = -A_T[j] / lambda;
}
}
#pragma omp parallel for
for (i = 0; i < (n + 1) * (n + 1); i += n + 2) {
A[i] += 1;
}
#pragma omp parallel for
for (i = n; i < (n + 1) * n; i += n + 1) {
A[i] /= lambda;
}
#pragma omp parallel for
for (i = 0; i < n; ++i) {
double *A_T = A + n * (n + 1);
A_T[i] = 0.0;
}
A[(n + 1) * (n + 1)] = 1.0;
//loop
double a, b, *T;
size_t index;
int itern = 0;
while (1) {
a = norm_inf_mat_Y11(A, n, 1);
index = cblas_idamax(n, A + n, n + 1);
b = A[(index + 1) * (n + 1) - 1];
if (a / b < tolerance)
break;
else {
//R = A*A
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n + 1, n + 1,
n + 1, 1.0, A, n + 1, A, n + 1, 0.0, R, n + 1);
T = A;
A = R;
R = T;
itern++;
}
}
omp_time = omp_get_wtime() - omp_time;
cblas_dcopy(n, A + n, n + 1, B, 1);
/*
* check result
*/
for (i = 0; i < n; ++i) {
if (fabs(B[i] - 1) > 1e-3) {
printf("MEXP ERR %f\t", B[i]);
break;
}
}
printf("mexp_iter:%d\t", itern);
printf("omp_time:%f\t", omp_time);
fseek(file, 0, SEEK_SET);
fread(&n, sizeof(int), 1, file);
fread(A, sizeof(double), (size_t) (n * n), file);
memset(B, 0, sizeof(double) * (n + 1));
fread(B, sizeof(double), (size_t) n, file);
#pragma omp parallel for
for (i = 0; i < n; ++i) {
W[i] = 1.0;
//B[i] /= A[i*(n+1)];
//cblas_dscal(n,1/A[i*(n+1)],A+i*n,1);
}
omp_time = omp_get_wtime();
int iteration = 0;
double alpha, beta, rho_new = 0.0, rho_old;
memset(x, 0, sizeof(double) * n);
cblas_dcopy(n, B, 1, r, 1); //r <- B
rho_new = cblas_ddot(n, r, 1, r, 1);
double w_norm2 = sqrt(rho_new);
while (1) {
if (sqrt(rho_new) / w_norm2 < tolerance) {
break;
}
iteration++;
if (iteration == 1) {
cblas_dcopy(n, r, 1, p, 1); //p <- r
} else {
beta = rho_new / rho_old;
cblas_dscal(n, beta, p, 1); // p <- beta * p
cblas_daxpy(n, 1.0, r, 1, p, 1); // p <- r + pcd
}
cblas_dsymv(CblasRowMajor, CblasUpper, n, 1.0, A, n, p, 1, 0.0, w, 1);
alpha = rho_new / cblas_ddot(n, p, 1, w, 1);
cblas_daxpy(n, alpha, p, 1, x, 1);
cblas_daxpy(n, -alpha, w, 1, r, 1); // r = r - alpha* w
rho_old = rho_new;
rho_new = cblas_ddot(n, r, 1, r, 1); //rho_new = r' dot r;
}
printf("cg_it: %d\t", iteration);
printf("cg_omp_time: %f", omp_get_wtime() - omp_time);
/*
* check result
*/
for (i = 0; i < n; ++i) {
if (fabs(x[i] - 1) > 1e-3) {
printf(" CG ERR %f\t", x[i]);
break;
}
}
printf("\n");
free(A);
free(B);
free(W);
free(R);
free(x);
free(r);
free(p);
free(w);
fclose(file);
}
double norm_inf_mat_Y11(double *X, int n, int extra) {
double lambda = 0.0, lambda_t;
int i;
for (i = 0; i < n; ++i) {
lambda_t = cblas_dasum(n, X + (i * (n + extra)), 1);
if (lambda_t > lambda)
lambda = lambda_t;
}
return lambda;
}
| {
"alphanum_fraction": 0.476392663,
"avg_line_length": 26.0530973451,
"ext": "c",
"hexsha": "e71626977a87940e5f54b2684de94b590b295f91",
"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": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "baishuai/MEXP",
"max_forks_repo_path": "openmp/openmp_all.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599",
"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": "baishuai/MEXP",
"max_issues_repo_path": "openmp/openmp_all.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d2fe69b49a6c13ccfb8404bce3d161cf0043d599",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "baishuai/MEXP",
"max_stars_repo_path": "openmp/openmp_all.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2018,
"size": 5888
} |
#ifndef LOGGER_INCLUDE
#define LOGGER_INCLUDE
#include <gsl/string_span>
#include "log/log.h"
BOOST_LOG_GLOBAL_LOGGER(exec_helper_test_logger, execHelper::log::LoggerType);
static const gsl::czstring<> LOG_CHANNEL = "test";
#define LOG(x) \
BOOST_LOG_STREAM_CHANNEL_SEV(exec_helper_test_logger::get(), LOG_CHANNEL, \
execHelper::log::x) \
<< boost::log::add_value(fileLog, __FILE__) \
<< boost::log::add_value(lineLog, __LINE__)
#endif /* LOGGER_INCLUDE */
| {
"alphanum_fraction": 0.5585443038,
"avg_line_length": 37.1764705882,
"ext": "h",
"hexsha": "1a698dc7e9e84db43661b08a202e017f66e26444",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z",
"max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "exec-helper/source",
"max_forks_repo_path": "test/catch/include/unittest/logger.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "exec-helper/source",
"max_issues_repo_path": "test/catch/include/unittest/logger.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "exec-helper/source",
"max_stars_repo_path": "test/catch/include/unittest/logger.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": 121,
"size": 632
} |
#ifndef BASIS_PURSUIT_A_H
#define BASIS_PURSUIT_A_H
#include "Matrix.h"
#include "APPROX2.h"
#include "ALM_I_APPROX.h"
#include <string>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <stdio.h> /* printf */
#include <time.h>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <ctime>
#include <math.h>
/*This class solves problem of the form f(x)+g(x) under the constraint Mx=c by IPALM_APPROX;
where f(x)=0 and g(x)=frac{lambda2}{2}|x|_2+lambda1 |x|_1.
*/
template<typename L, typename D>
class Basis_pursuit_a: public ALM_I_APPROX<L, D>
{
private:
D lambda1;
D lambda2;
Matrix<L,D> my_M;
Matrix<L,D> my_A;
D val_lambda_f;
protected:
public:
Basis_pursuit_a(const char* Matrix_file,D val_lambda1, D val_lambda2)
:ALM_I_APPROX<L,D>(), my_M(Matrix_file)
{
lambda1=val_lambda1;
lambda2=val_lambda2;
val_lambda_f=0;
this->val_mu_f=0;
this->val_mu_g=lambda2;
}
L get_n(){return my_M.nfeatures;}
L get_m(){return my_M.nsamples;}
inline D gradient_of_phi_j(D x1, L i){
return 0;
}
inline D value_of_g_i(D x, L i){
return lambda2*x*x/2+lambda1*fabs(x);
}
inline D value_of_phi_j(D x1, L i){return 0;}
inline D prox_of_g_i(D x1,D x2,D x3, L i){
return compute_one_step(1.0/x2, x1, x3)-x3;
}
D compute_one_step(D tau, D u, D x){
D new_x;
if(x>tau*(lambda1+u))
new_x=(x-tau*(lambda1+u))/(1+lambda2*tau);
else if(x<tau*(u-lambda1))
new_x=(x-tau*(u-lambda1))/(1+lambda2*tau);
else
new_x=0;
return new_x;
}
inline D feasible_dual(vector<D> & x, vector<D> & y){
if(lambda2+this->beta_s>0)
{
return 1;
}
else
{
D scal=1;
L l=x.size();
for(L i=0;i<l;i++)
if(fabs(x[i]+y[i])>lambda1)
scal=min(lambda1/fabs(x[i]+y[i]),scal);
return scal;
}
}
inline D rescale(vector<D> & x, vector<D> & y){
D scal=1;
L l=x.size();
for(L i=0;i<l;i++){
if(fabs(x[i]+y[i])>lambda1){
scal=min(lambda1/fabs(x[i]+y[i]),scal);
}
}
return scal;
}
inline D value_of_phistar_i(D x,L i) {return 0;}
inline D value_of_g_tilde_star(D scal,vector<D> & x, vector<D> & y){
if(lambda2+this->tau_s*this->beta_s>0)
{
D res=0;
D ip=0;
L l=x.size();
for(L i=0;i<l;i++)
{
ip=max(fabs(x[i]+y[i]+this->tau_s*this->beta_s*this->x_s[i])-lambda1,0.0);
res+=ip*ip;
}
D xsnorm=0;
for(L i=0;i<l;i++)
xsnorm+=this->tau_s*this->beta_s/2*this->x_s[i]*this->x_s[i];
return res/2/(lambda2+this->tau_s*this->beta_s)-xsnorm;
}
else
{
return 0;
}
}
inline D value_of_g_star(D scal,vector<D> & x, vector<D> & y){
return 0;
}
inline void set_matrix_M(){
this->data_M=my_M;
}
inline void set_matrix_A(){
this->data_A.nsamples=0;
this->data_A.nfeatures=this->data_M.nfeatures;
this->data_A.nnz=0;
this->data_A.ptr.resize(1,0);
this->data_A.ptr_t.resize(this->data_M.nfeatures+1,0);
}
inline D distance_to_subgradient_of_g(){
D res=0;
D tmp;
D xv;
for(L i=0;i<this->n;i++){
tmp=-this->gradient_of_f[i]-this->M_tlambda_s[i];
xv=this->x_s[i];
if(xv>0) res+=(tmp-lambda2*xv-lambda1)*(tmp-lambda2*xv-lambda1);
else if(xv<0) res+=(tmp-lambda2*xv+lambda1)*(tmp-lambda2*xv+lambda1);
else if(tmp-lambda2*xv>lambda1) res+=(tmp-lambda2*xv-lambda1)*(tmp-lambda2*xv-lambda1);
else if(tmp-lambda2*xv<-lambda1) res+=(tmp-lambda2*xv+lambda1)*(tmp-lambda2*xv+lambda1);
else res+=0;
}
return sqrt(res);
}
inline D subgradient_of_Tx(){
D res=0;
D tmp;
D xv;
for(L i=0;i<this->n;i++){
xv=this->Tx[i];
tmp=this->gradient_of_Tx[i]+ lambda2*xv+this->tau_s*this->beta_s*(xv- this->x_s[i]);
if(xv>0) res+=(tmp+ lambda1)*(tmp+ lambda1);
else if(xv<0) res+=(tmp-lambda1)*(tmp-lambda1);
else if(tmp>lambda1) res+=(tmp-lambda1)*(tmp-lambda1);
else if(tmp<-lambda1) res+=(tmp+lambda1)*(tmp+lambda1);
else res+=0;
}
return sqrt(res);
}
void ALM_I_APPROX_solver(D beta_0, D epsilon_0, D eta, D rho,vector<D> & x0,vector<D> & y0,L val_tau, L max_nb_outer, L p_N_1, L p_N_2,string filename1, string filename2, D time){
this->ALM_I_APPROX_solve_with_APPROX(beta_0, epsilon_0, eta, rho,x0,y0, val_tau, max_nb_outer, p_N_1, p_N_2, val_lambda_f, filename1, filename2, time);
}
};
#endif
| {
"alphanum_fraction": 0.5811473662,
"avg_line_length": 22.7621359223,
"ext": "h",
"hexsha": "aea54df6030f1fde3d1c22c0a0904330ae5647f4",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_forks_repo_licenses": [
"BSD-Source-Code"
],
"max_forks_repo_name": "lifei16/supplementary_code",
"max_forks_repo_path": "IPALM_OPENMP/Basis_pursuit_a.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-Source-Code"
],
"max_issues_repo_name": "lifei16/supplementary_code",
"max_issues_repo_path": "IPALM_OPENMP/Basis_pursuit_a.h",
"max_line_length": 183,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_stars_repo_licenses": [
"BSD-Source-Code"
],
"max_stars_repo_name": "lifei16/supplementary_code",
"max_stars_repo_path": "IPALM_OPENMP/Basis_pursuit_a.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1552,
"size": 4689
} |
/*
Copyright (c) 2016-2017 Hong Xu
This file is part of WCSPLift.
WCSPLift 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.
WCSPLift 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 WCSPLift. If not, see <http://www.gnu.org/licenses/>.
*/
/** \file WCSPInstance.h
*
* Define the definition of WCSP instances and the constraints in it. Algorithms that can be applied
* directly on WCSP instances, i.e., the min-sum message passing algorithm \cite xkk17 and integer
* linear programming \cite xkk17a, are also included in this file.
*/
#ifndef WCSPINSTANCE_H_
#define WCSPINSTANCE_H_
#include <array>
#include <cstdint>
#include <istream>
#include <map>
#include <numeric>
#include <set>
#include <stdexcept>
#include <utility>
#include <vector>
#include <boost/dynamic_bitset.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <cblas.h>
#include "global.h"
#include "RunningTime.h"
#include "LinearProgramSolver.h"
/** \brief Weighted constraint.
*
* This class describes a weighted constraint. It consists of the IDs of the variables as well as
* how the weight corresponding to each assignment.
*
* \tparam VarIdType The type of variable IDs. It must be an integer type and defaults to \p
* intmax_t.
*
* \tparam WeightType The type of weights. It must be a numeric type and defaults to \p double.
*
* \tparam ValueType The type of values of all variables in the constraint. It should usually be a
* bitset type and defaults to \p boost::dynamic_bitset<>.
*/
template < class VarIdType = intmax_t,
class WeightType = double,
class ValueType = boost::dynamic_bitset<>, // The type of the values to represent each constraint
class NonBooleanValueType = size_t>
class Constraint
{
public:
/** Alias of \p VarIDType. */
typedef VarIdType variable_id_t;
/** Alias of \p ValueType. */
typedef ValueType value_t;
/** Alias of \p WeightType. */
typedef WeightType weight_t;
/** Alias of \p NonBooleanValueType. */
typedef NonBooleanValueType non_boolean_value_t;
private:
// This class is only used for Polynomial key comparison. This function ensures keys with
// a smaller number of variables must precede larger number of variables.
class PolynomialKeyComparison
{
public:
bool operator () (const std::set<variable_id_t>& a, const std::set<variable_id_t>& b) const
{
if (a.size() > b.size())
return true;
if (a.size() < b.size())
return false;
return a < b;
}
};
public:
/** The polynomial form of constraints consisting of the coefficient of each term (each term is
* represented by an assignment of values to variables). */
typedef std::map<std::set<variable_id_t>, weight_t, PolynomialKeyComparison> Polynomial;
private:
std::vector<variable_id_t> nonBooleanVariables;
std::vector<variable_id_t> variables;
std::map<value_t, weight_t> weights;
std::map<std::vector<non_boolean_value_t>, weight_t> nonBooleanWeights;
public:
/** Alias of \p Constraint<VarIdType, WeightType, ValueType, NonBooleanValueType>, i.e., the
* class type itself. */
typedef Constraint<VarIdType, WeightType, ValueType, NonBooleanValueType> self_t;
/** \brief Get the list of the IDs of non-Boolean variables in the constraint.
*
* \return A list of variable IDs.
*/
inline const std::vector<variable_id_t>& getNonBooleanVariables() const noexcept
{
return nonBooleanVariables;
}
/** \brief Get the list of the IDs of variables in the constraint.
*
* \return A list of variable IDs.
*/
inline const std::vector<variable_id_t>& getVariables() const noexcept
{
return variables;
}
/** \brief Get the ID of the <tt>i</tt>'th variable.
*
* \param[in] i The index of the variable of which to get the ID.
*
* \return The ID of the <tt>i</tt>'th variable.
*/
inline variable_id_t getVariable(size_t i) const noexcept
{
return variables.at(i);
}
/** \brief Set the IDs of the variables in the constraint from a \p std::vector<variable_id_t>
* object.
*
* \param[in] variables: A list of variable IDs to set.
*/
inline void setVariables(const std::vector<variable_id_t>& variables) noexcept
{
this->variables = variables;
this->weights.clear();
}
/** \brief Set the IDs of the non-Boolean variables in the constraint from a \p
* std::vector<variable_id_t> object.
*
* \param[in] variables: A list of variable IDs to set.
*/
inline void setNonBooleanVariables(const std::vector<variable_id_t>& variables) noexcept
{
this->nonBooleanVariables = variables;
this->weights.clear();
}
/** \brief Set the IDs of the variables in the constraint from a range of iterators.
*
* \param[in] b the beginning iterator.
*
* \param[in] e the ending iterator.
*/
template<class Iter>
inline void setVariables(Iter b, Iter e) noexcept
{
variables.clear();
std::copy(b, e, std::back_inserter(variables));
}
/** \brief Set the weight of a given assignment of values to variables specified by \p v to \p
* w.
*
* \param[in] v An assignment of values to variables.
*
* \param[in] w A weight.
*
* \return A reference to the class object itself.
*/
inline self_t& setWeight(const value_t& v, weight_t w)
{
weights[v] = w;
return *this;
}
/** \brief Set the weight of a given assignment of values to non-Boolean variables specified by
* \p v to \p w.
*
* \param[in] v An assignment of values to variables.
*
* \param[in] w A weight.
*
* \return A reference to the class object itself.
*/
inline self_t& setWeight(const std::vector<non_boolean_value_t>& v, weight_t w)
{
nonBooleanWeights[v] = w;
return *this;
}
/** \brief Get the weight of a given assignment of values to variables specified by \p v.
*
* \param[in] v The assignment of values to variables.
*
* \return The weight of a given assignment of values to variables specified by \p v.
*/
inline weight_t getWeight(const value_t& v) const noexcept
{
auto it = weights.find(v);
if (it == weights.end()) // not found, return 0
return weight_t();
return it->second;
}
/** \brief Get the weight of a given assignment of values to non-Boolean variables specified by
* \p v.
*
* \param[in] v The assignment of values to variables.
*
* \return The weight of a given assignment of values to variables specified by \p v.
*/
inline weight_t getWeight(const std::vector<non_boolean_value_t>& v) const noexcept
{
auto it = nonBooleanWeights.find(v);
if (it == nonBooleanWeights.end()) // not found, return 0
return weight_t();
return it->second;
}
/** \brief Get a map object that maps assignments of values to variables to weights.
*
* \return A map object that maps assignments of values to variables to weights.
*/
inline const std::map<value_t, weight_t> getWeights() const noexcept
{
return weights;
}
/** \brief Represent the constraint using a \p boost::property_tree::ptree object.
*
* \param[out] t A \p boost::property_tree::ptree object that represents the constraint.
*/
void toPropertyTree(boost::property_tree::ptree& t) const
{
using namespace boost::property_tree;
t.clear();
// put the variables
ptree vs;
for (auto& v : variables)
vs.push_back(
std::make_pair("", ptree(std::to_string(v))));
t.put_child("variables", vs);
// put the weights
ptree ws;
for (auto& w : weights)
{
ptree we;
for (size_t i = 0; i < getVariables().size(); ++ i)
{
if (w.first[i])
we.push_back(std::make_pair("", ptree("1")));
else
we.push_back(std::make_pair("", ptree("0")));
}
we.push_back(std::make_pair("", ptree(std::to_string(w.second))));
ws.push_back(std::make_pair("", we));
}
t.put_child("weights", ws);
}
/** \brief Compute the coefficients of the polynomial converted from a constraint according to
* \cite k08.
*
* \param[out] p A Constraint::Polynomial object corresponding to the polynomial representation
* of the constraint.
*/
void toPolynomial(Polynomial& p) const noexcept
{
size_t s = getVariables().size();
// we basically solve A * x = b
size_t max_int = ((size_t) 1) << s;
// matrix a
double * a = new double[max_int * max_int];
memset(a, 0, max_int * max_int * sizeof(double));
/// \cond
#define ENTRY(a, x, y) a[(y) * max_int + (x)]
/// \endcond
// set the first column to 1
for (size_t i = 0; i < max_int; ++ i)
ENTRY(a, i, 0) = 1.0;
// Set the lower triangle. The row number corresponds to the assignments of variables, and
// the col number corresponds to terms of the polynomial in the following order:
// X_1, X_2, X_1 X_2, X_3, X_1 X_3, X_2 X_3, X_1 X_2 X_3...
for (size_t i = 1; i < max_int; ++ i)
for (size_t j = 1; j <= i; ++ j)
// (i|j)==i : the 1-bits integer i includes all the 1-bits of j
ENTRY(a, i, j) = ((i | j) == i) ? 1.0 : 0.0;
#undef ENTRY
// assign the vector b
double * x = new double[max_int];
for (size_t i = 0; i < max_int; ++ i)
x[i] = getWeight(value_t(s, i));
cblas_dtrsv(CblasColMajor, CblasLower, CblasNoTrans, CblasUnit, max_int, a, max_int, x, 1);
delete[] a;
// Insert all the coefficients into the polynomial.
for (size_t i = 0; i < max_int; ++ i)
{
typename Polynomial::key_type k;
for (size_t j = 0; j < s; ++ j)
if ((((size_t) 1u) << j) & i)
k.insert(getVariable(j));
p[k] += x[i];
}
delete[] x;
}
};
/** \brief A WCSP instance.
*
* This class describes a WCSP instance. It consists a set of constraints.
*
* \tparam VarIdType The type of variable IDs. It must be an integer type and defaults to \p
* intmax_t.
*
* \tparam WeightType The type of weights. It must be a numeric type and defaults to \p double.
*
* \tparam ConstraintValueType The type of values of all variables in the constraints in the WCSP
* instance. It should usually be a bitset type and defaults to \p boost::dynamic_bitset<>.
*/
template <class VarIdType = intmax_t, class WeightType = double,
class ConstraintValueType = boost::dynamic_bitset<>,
class NonBooleanValueType = size_t>
class WCSPInstance
{
public:
/** Alias of \p VarIdType. */
typedef VarIdType variable_id_t;
/** Alias of \p WeightType. */
typedef WeightType weight_t;
/** Alias of \p ConstraintValueType. */
typedef ConstraintValueType constraint_value_t;
/** Alias of \p NonBooleanValueType. */
typedef NonBooleanValueType non_boolean_value_t;
public:
/** Alias of the Constraint type in the WCSP instance, i.e., \p
* Constraint<variable_id_t,weight_t,constraint_value_t>.
*/
typedef Constraint<variable_id_t, weight_t, constraint_value_t> constraint_t;
private:
std::vector<constraint_t> constraints;
// map from non-Boolean variables to their Boolean variable representations
std::vector<std::vector<variable_id_t> > nonBooleanVariables;
public:
/** \brief Get the mapping from original variables to Boolean variables.
*
* \return The mapping.
*/
inline const std::vector<std::vector<variable_id_t> >& getNonBooleanVariables()
const noexcept
{
return nonBooleanVariables;
}
/** \brief Display the mapping from original variables to Boolean variables.
*/
inline void displayNonBooleanVariableMapping() const noexcept
{
std:: cout << "--- Non-Boolean Variable Mapping BEGINS ---" << std::endl;
for (auto i = 0; i < nonBooleanVariables.size(); ++ i)
{
std::cout << i << '\t';
for (auto j : nonBooleanVariables[i])
{
std::cout << j << ' ';
}
std::cout << std::endl;
}
std:: cout << "--- Non-Boolean Variable Mapping ENDS ---" << std::endl;
}
/** \brief Get the list of constraints.
*
* \return A list of \p constraint_t objects.
*/
inline const std::vector<constraint_t>& getConstraints() const noexcept
{
return constraints;
}
/** \brief Get the <tt>i</tt>'th constraint.
*
* \param[in] i The index of the Constraint object to get.
*
* \return The <tt>i</tt>'th constraint.
*/
inline const constraint_t& getConstraint(size_t i) const noexcept
{
return constraints.at(i);
}
/** \brief Compute the total weight corresponding to an assignment of values to all variables.
*
* \param[in] assignments The assignment of values to all variables.
*
* \return The computed total weight.
*/
inline weight_t computeTotalWeight(
const std::map<variable_id_t, non_boolean_value_t>& assignments) const noexcept
{
weight_t tw = 0;
for (const auto& c : constraints)
{
std::vector<non_boolean_value_t> val(c.getNonBooleanVariables().size());
for (size_t i = 0; i < c.getNonBooleanVariables().size(); ++ i)
{
try
{
val[i] = assignments.at(c.getNonBooleanVariables().at(i));
} catch (std::out_of_range& e)
{
// Here, it means the variable assignments does not hold
// c.getNonBooleanVariables().at(i) -- the CCG does not contain that variable.
// This may well be that the variable itself is a "dummy" variable -- the value
// of it does not affect the total weight. In this case, we always assign zero
// (or anything else) to it.
val[i] = 0;
}
}
tw += c.getWeight(val);
}
return tw;
}
public:
/** \brief Load a problem instance from a stream.
*
* \param[in] f The input stream.
*/
void load(std::istream& f);
/** \brief Load the problem in DIMACS format. The format specification is at
* http://graphmod.ics.uci.edu/group/WCSP_file_format
*
* \param[in] f The input stream.
*/
void loadDimacs(std::istream& f);
/** \brief Load the problem in UAI format. The format specification is at
* http://www.hlt.utdallas.edu/~vgogate/uai14-competition/modelformat.html
*
* \param[in] f The input stream.
*/
void loadUAI(std::istream& f);
/** List of supported input file formats.
*/
enum class Format
{
DIMACS,
UAI
};
/** \brief Construct a WCSP instance from an input stream in a given format.
*
* \param[in] f The input stream.
*
* \param[in] format The format of \p f.
*/
WCSPInstance(std::istream& f, Format format)
{
switch (format)
{
case Format::DIMACS:
loadDimacs(f);
break;
case Format::UAI:
loadUAI(f);
break;
}
}
/** \brief Convert this WCSP instance to a human-readable string.
*
* \return The human-readable string.
*/
std::string toString() const noexcept
{
std::stringstream ss;
ss << '{' << std::endl;
for (auto& c : constraints)
{
ss << c;
}
return ss.str();
}
/** \brief Solve the WCSP instance using the min-sum message passing algorithm.
*
* \param[in] delta The threshold for convergence determination. That is, the algorithm
* terminates iff all messages change within \p delta compared with the previous iteration.
*
* \return A solution to the WCSP instance.
*/
std::map<variable_id_t, bool> solveUsingMessagePassing(weight_t delta) const noexcept
{
std::map<variable_id_t, std::set<const constraint_t*> > constraint_list_for_v;
// Initialize all messages.
std::map<std::pair<variable_id_t, const constraint_t*>, std::array<weight_t, 2> > msgs_v_to_c;
std::map<std::pair<const constraint_t*, variable_id_t>, std::array<weight_t, 2> > msgs_c_to_v;
for (const auto& c : constraints)
{
for (auto v : c.getVariables())
{
constraint_list_for_v[v].insert(&c);
msgs_v_to_c[std::make_pair(v, &c)] = {0, 0};
msgs_c_to_v[std::make_pair(&c, v)] = {0, 0};
}
}
bool converged = false;
uintmax_t num_iterations = 0;
do
{
if (RunningTime::GetInstance().isTimeOut()) // time's up
break;
++ num_iterations;
converged = true;
auto msgs_v_to_c0 = msgs_v_to_c;
auto msgs_c_to_v0 = msgs_c_to_v;
// Update all the messages from variables to constraints.
for (auto& it : msgs_v_to_c)
{
auto v = it.first.first;
auto c = it.first.second;
std::array<weight_t, 2> m = {0, 0};
for (auto nc : constraint_list_for_v.at(v))
{
if (nc != c)
{
const auto m_to_v = msgs_c_to_v0.find(std::make_pair(nc, v))->second;
m[0] += m_to_v.at(0);
m[1] += m_to_v.at(1);
}
}
it.second = m;
// is it now convergent?
if (converged)
{
auto old_m = msgs_v_to_c0.at(it.first);
if (std::abs(old_m.at(0) - m.at(0)) > delta ||
std::abs(old_m.at(1) - m.at(1)) > delta)
converged = false;
}
}
// Update all the messages from constraints to variables.
for (auto& it : msgs_c_to_v)
{
auto c = it.first.first;
auto v = it.first.second;
std::vector<std::array<weight_t, 2> > m_to_c;
m_to_c.reserve(c->getVariables().size());
std::vector<variable_id_t> v_ids;
v_ids.reserve(c->getVariables().size());
size_t self_index; // index of the variable itself
for (size_t i = 0; i < c->getVariables().size(); ++ i)
{
auto nv = c->getVariable(i);
m_to_c.push_back(msgs_v_to_c0.at(std::make_pair(nv, c)));
v_ids.push_back(nv);
if (nv == v)
self_index = i;
}
std::array<weight_t, 2> m = {
std::numeric_limits<weight_t>::max(), std::numeric_limits<weight_t>::max()
};
// TODO: Change the iteration which does not have an upper limit of number of bits.
for (unsigned long i = 0; i < (1ul << c->getVariables().size()); ++ i)
{
constraint_value_t values(c->getVariables().size(), i);
weight_t sum = c->getWeight(values);
for (size_t j = 0; j < c->getVariables().size(); ++ j)
if (c->getVariable(j) != v)
sum += msgs_v_to_c0.at(
std::make_pair(c->getVariable(j), c))[values[j] ? 1 : 0];
size_t index_update = values[self_index] ? 1 : 0;
if (m[index_update] > sum)
m[index_update] = sum;
}
auto m_min = m[0] < m[1] ? m[0] : m[1];
m[0] -= m_min;
m[1] -= m_min;
it.second = m;
// is it now convergent?
if (converged)
{
auto old_m = msgs_c_to_v0.at(it.first);
if (std::abs(old_m.at(0) - m.at(0)) > delta ||
std::abs(old_m.at(1) - m.at(1)) > delta)
converged = false;
}
}
} while (!converged);
std::cout << "Number of iterations: " << num_iterations << std::endl;
// compute the variable values
std::map<variable_id_t, std::array<weight_t, 2> > assignments_w;
converged = true;
for (const auto& c : constraints)
for (auto v : c.getVariables())
{
assignments_w[v][0] += msgs_c_to_v[std::make_pair(&c, v)][0];
assignments_w[v][1] += msgs_c_to_v[std::make_pair(&c, v)][1];
if (isinf(assignments_w[v][0]) || isinf(assignments_w[v][1]))
converged = false;
}
std::map<variable_id_t, bool> assignments;
for (const auto& a : assignments_w)
assignments[a.first] = a.second[0] > a.second[1] ? a.second[1] : a.second[0];
if (!converged)
std::cout << "*** Message passing not converged! ***" << std::endl;
return assignments;
}
/** \brief Solve the WCSP instance using linear programming.
*
* \param[in] lps The linear program solver to be used.
*
* \return A solution to the WCSP instance.
*/
std::map<variable_id_t, non_boolean_value_t> solveUsingLinearProgramming(
LinearProgramSolver& lps) const noexcept
{
lps.reset();
lps.setTimeLimit(RunningTime::GetInstance().getTimeLimit().count());
lps.setObjectiveType(LinearProgramSolver::ObjectiveType::MIN);
auto constraints = this->getConstraints();
// Every variable needs a unary constraint. This is the indices of all unary constraints.
std::vector<size_t> unary_indices(this->getNonBooleanVariables().size(),
std::numeric_limits<size_t>::max());
size_t num_unary = 0;
for (size_t i = 0; i < constraints.size(); ++ i)
{
auto& vs = constraints.at(i).getVariables();
if (vs.size() == 1) // unary constraint
{
unary_indices[vs.at(0)] = i;
++ num_unary;
}
}
constraints.reserve(constraints.size() + unary_indices.size() - num_unary);
for (variable_id_t i = 0; i < unary_indices.size(); ++ i)
{
// no unary constraint for this var
if (unary_indices.at(i) == std::numeric_limits<size_t>::max())
{
constraint_t cons;
cons.setNonBooleanVariables(std::vector<variable_id_t>{i});
constraints.push_back(std::move(cons));
unary_indices[i] = constraints.size() - 1;
}
}
std::vector<std::vector<LinearProgramSolver::variable_id_t> > lp_variables(
constraints.size());
// add LP variables and constraints
for (size_t i = 0; i < constraints.size(); ++ i)
{
size_t num_values = 1;
// Cartesian product of all values
for (const auto& nbv : constraints.at(i).getNonBooleanVariables())
num_values *= nonBooleanVariables[nbv].size() + 1;
lp_variables[i].reserve(num_values);
for (size_t j = 0; j < num_values; ++ j) // add all variables
{
std::vector<non_boolean_value_t> val;
val.reserve(constraints.at(i).getNonBooleanVariables().size());
size_t j0 = j;
for (const auto& nbv : constraints.at(i).getNonBooleanVariables())
{
size_t d = nonBooleanVariables[nbv].size() + 1;
val.push_back(j0 % d);
j0 /= d;
}
lp_variables[i].push_back(lps.addVariable(constraints.at(i).getWeight(val)));
}
// Only one value in a WCSP constraint can take effect.
lps.addConstraint(lp_variables[i], std::vector<double>(num_values, 1.0), 1.0,
LinearProgramSolver::ConstraintType::EQUAL);
}
// Add constraints that make sure LP variables that represent overlapped WCSP variables are
// consistent.
for (size_t i = 0; i < lp_variables.size(); ++ i)
{
for (size_t j : unary_indices)
{
if (j <= i) // Don't do a pair twice.
continue;
// Get the overlap map.
std::vector<std::pair<size_t, size_t> > overlapped_variables;
// Whether a variable is overlapping?
std::vector<bool> vs_overlap_p[2];
vs_overlap_p[0].resize(constraints.at(i).getNonBooleanVariables().size());
vs_overlap_p[1].resize(constraints.at(j).getNonBooleanVariables().size());
std::array<std::vector<size_t>, 2> domain_sizes;
domain_sizes[0].reserve(constraints.at(i).getNonBooleanVariables().size());
domain_sizes[1].reserve(constraints.at(j).getNonBooleanVariables().size());
std::vector<size_t> overlapped_domain_sizes;
for (size_t z = 0; z < 2; ++ z)
{
size_t c = z ? j : i;
for (size_t k = 0; k < constraints.at(c).getNonBooleanVariables().size();
++ k)
domain_sizes[z].push_back(
nonBooleanVariables[
constraints.at(c).getNonBooleanVariables()[k]].size() + 1);
}
for (size_t k0 = 0; k0 < constraints.at(i).getNonBooleanVariables().size(); ++ k0)
for (size_t k1 = 0; k1 < constraints.at(j).getNonBooleanVariables().size(); ++ k1)
{
if (constraints.at(i).getNonBooleanVariables()[k0] ==
constraints.at(j).getNonBooleanVariables()[k1])
{
overlapped_variables.push_back(std::make_pair(k0, k1));
overlapped_domain_sizes.push_back(
nonBooleanVariables[
constraints.at(i).getNonBooleanVariables()[k0]].size() + 1
);
vs_overlap_p[0][k0] = true;
vs_overlap_p[1][k1] = true;
break;
}
}
std::vector<non_boolean_value_t> vs[2];
vs[0].resize(constraints.at(i).getNonBooleanVariables().size());
vs[1].resize(constraints.at(j).getNonBooleanVariables().size());
if (overlapped_domain_sizes.empty()) // no overlapping
continue;
// Cartesian product of all values of overlapped variables
size_t num_values = std::accumulate(overlapped_domain_sizes.begin(),
overlapped_domain_sizes.end(),
1, std::multiplies<size_t>());
for (size_t k = 0; k < num_values; ++ k)
{
size_t k0 = k;
for (const auto& ov : overlapped_variables)
{
size_t d = nonBooleanVariables[
constraints.at(i).getNonBooleanVariables()[ov.first]].size() + 1;
non_boolean_value_t val = k0 % d;
k0 /= d;
vs[0][ov.first] = val;
vs[1][ov.second] = val;
}
// non-overlapped variables
std::array<std::vector<non_boolean_value_t>, 2> vs_non_overlapped;
vs_non_overlapped[0].resize((vs[0].size() - overlapped_variables.size()));
vs_non_overlapped[1].resize((vs[1].size() - overlapped_variables.size()));
std::vector<LinearProgramSolver::variable_id_t> lp_vs; // LP variables
std::vector<double> coefs;
for (size_t z = 0; z < 2; ++ z)
{
size_t l;
do {
for (l = 0; l < vs[z].size(); ++ l)
{
if (vs_overlap_p[z][l])
continue;
++ vs[z][l];
if (vs[z][l] >= domain_sizes[z][l])
vs[z][l] = 0;
else
break;
}
size_t index = 0; // index corresponding to the variable values vs[z]
size_t cur_base = 1;
for (size_t m = 0; m < vs[z].size(); ++ m)
{
index += cur_base * vs[z][m];
cur_base *= domain_sizes[z][m];
}
if (z == 0)
{
lp_vs.push_back(lp_variables[i][index]);
coefs.push_back(1.0);
}
else
{
lp_vs.push_back(lp_variables[j][index]);
coefs.push_back(-1.0);
}
} while (l != vs[z].size());
}
lps.addConstraint(lp_vs, coefs, 0.0,
LinearProgramSolver::ConstraintType::EQUAL);
}
}
}
std::vector<double> assignments;
lps.solve(assignments);
// Compute the solutions from assignments
std::map<variable_id_t, non_boolean_value_t> solution;
for (size_t i : unary_indices)
for (size_t j = 0; j < lp_variables[i].size(); ++ j)
{
if (assignments[lp_variables[i][j]] > 0.99)
{
solution[constraints.at(i).getNonBooleanVariables().at(0)] = j;
break;
}
}
return solution;
}
};
template <class VarIdType, class WeightType, class ConstraintValueType, class NonBooleanValueType>
void WCSPInstance<VarIdType, WeightType, ConstraintValueType, NonBooleanValueType>::loadDimacs(
std::istream& f)
{
std::string line;
std::string tmp;
size_t max_domain_size;
size_t nv, nc; // number of variables, number of constraints
// first line: problem_name number_of_variables max_domain_size number_of_constraints
// global_upper_bound
std::getline(f, line);
std::istringstream ss(line);
ss >> tmp; // name
ss >> nv;
ss >> max_domain_size; // max domain size
ss >> nc;
ss >> tmp; // ignore global upper bound
// domain size of all variables
std::getline(f, line);
ss.clear();
ss.str(line);
variable_id_t cur_var_id = 0;
nonBooleanVariables.clear();
nonBooleanVariables.reserve(nv);
for (size_t i = 0; i < nv; ++ i)
{
size_t domain_size;
ss >> domain_size;
// Boolean variables corresponding to the current variable
std::vector<variable_id_t> vs(domain_size-1);
std::iota(vs.begin(), vs.end(), cur_var_id);
cur_var_id += vs.size();
nonBooleanVariables.push_back(std::move(vs));
}
constraints.clear();
constraints.resize(nc);
// iterate over constraints
for (size_t i = 0; i < nc; ++ i)
{
size_t arity;
weight_t default_cost;
size_t ntuples; // number of tuples not having the default cost
std::getline(f, line);
ss.clear();
ss.str(line);
ss >> arity;
// load the variables in the constraint
std::vector<variable_id_t> non_bool_variables;
non_bool_variables.reserve(arity);
// load the corresponding Boolean variables in the constraint
std::vector<variable_id_t> variables;
variables.reserve(arity*max_domain_size);
for (size_t j = 0; j < arity; ++ j)
{
variable_id_t vid;
ss >> vid;
non_bool_variables.push_back(vid);
const auto& nbv = nonBooleanVariables[vid];
variables.insert(variables.end(), nbv.begin(), nbv.end());
}
constraints[i].setVariables(std::move(variables));
constraints[i].setNonBooleanVariables(std::move(non_bool_variables));
ss >> default_cost;
// TODO: More efficient handling
if (default_cost > std::abs(1e-6)) // non-zero default cost
{
constraint_value_t values;
values.resize(constraints[i].getVariables().size());
unsigned long te = (1u << constraints[i].getVariables().size());
for (unsigned long l = 0; l < te; ++ l)
{
for (unsigned long k = 0; k < values.size(); ++ k)
values.set(k, (l & (1u << k)) ? 1 : 0);
constraints[i].setWeight(values, default_cost);
}
}
ss >> ntuples;
// load the entries in the constraints
for (size_t j = 0; j < ntuples; ++ j)
{
weight_t cost;
constraint_value_t values;
values.resize(constraints[i].getVariables().size());
values.set();
std::vector<non_boolean_value_t> non_boolean_values(arity);
std::getline(f, line);
ss.clear();
ss.str(line);
for (size_t k = 0, cur_bit = 0; k < arity; ++ k)
{
int val;
ss >> val;
non_boolean_values[k] = val;
size_t bvs = nonBooleanVariables[constraints[i].getNonBooleanVariables()[k]].size();
if (bvs == 1)
values.set(cur_bit ++, val ? true : false);
else
{
if (val != 0)
values.set(cur_bit + val - 1, false);
cur_bit += bvs;
}
}
ss >> cost;
constraints[i].setWeight(std::move(non_boolean_values), cost);
constraints[i].setWeight(std::move(values), cost);
}
}
}
template <class VarIdType, class WeightType, class ConstraintValueType, class NonBooleanValueType>
void WCSPInstance<VarIdType, WeightType, ConstraintValueType, NonBooleanValueType>::loadUAI(
std::istream& f)
{
std::string line;
std::string tmp;
size_t nv, nc; // number of variables, number of constraints
// first line: MARKOV, just ignore it
std::getline(f, tmp);
// second line: number of variables
{
std::getline(f, line);
std::istringstream ss(line);
ss >> nv; // number of variables
}
// third line: arity
{
std::getline(f, line);
std::istringstream ss(line);
variable_id_t cur_var_id = 0;
nonBooleanVariables.clear();
nonBooleanVariables.reserve(nv);
for (size_t i = 0; i < nv; ++ i)
{
size_t domain_size;
ss >> domain_size;
// Boolean varaibles corresponding to the current variable
std::vector<variable_id_t> vs(domain_size-1);
std::iota(vs.begin(), vs.end(), cur_var_id);
cur_var_id += vs.size();
nonBooleanVariables.push_back(std::move(vs));
}
}
// fourth line: number of constraints
{
std::getline(f, line);
std::istringstream ss(line);
ss >> nc;
constraints.clear();
constraints.resize(nc);
}
// iterate over constraints
for (size_t i = 0; i < nc; ++ i)
{
size_t arity;
std::getline(f, line);
std::istringstream ss(line);
ss >> arity;
// Load the variables in the constraint. We load it reversely because UAI format arrange
// their constraint value reversely as we do.
std::vector<variable_id_t> variables;
std::vector<variable_id_t> non_bool_variables(arity);
for (size_t j = 0; j < arity; ++ j)
{
variable_id_t vid;
ss >> vid;
non_bool_variables[arity-j-1] = vid;
variables.insert(variables.end(),
nonBooleanVariables[vid].rbegin(),
nonBooleanVariables[vid].rend());
}
std::reverse(variables.begin(), variables.end());
constraints[i].setVariables(std::move(variables));
constraints[i].setNonBooleanVariables(std::move(non_bool_variables));
}
// iterate over constraints
for (size_t i = 0; i < nc; ++ i)
{
size_t ntuples;
f >> ntuples; // number of entries
// load the entries in the constraints
std::vector<weight_t> costs(ntuples);
for (size_t j = 0; j < ntuples; ++ j)
f >> costs[j];
// normalization constant
weight_t sum(std::accumulate(costs.begin(), costs.end(), weight_t()));
// set the value of each tuple
for (size_t j = 0; j < ntuples; ++ j)
{
costs[j] = -std::log(costs[j] / sum);
if (!std::isfinite(costs[j]))
costs[j] = 1e6;
constraint_value_t values;
std::vector<non_boolean_value_t> non_boolean_values;
non_boolean_values.reserve(constraints[i].getNonBooleanVariables().size());
size_t j0 = j;
for (const auto& nbv : constraints[i].getNonBooleanVariables())
{
auto d = nonBooleanVariables[nbv].size() + 1;
size_t cur_val = j0 % d;
non_boolean_values.push_back(cur_val);
if (d == 2)
values.push_back(cur_val ? true : false);
else
{
for (size_t k = 1; k < d; ++ k)
{
if (cur_val == k)
values.push_back(false);
else
values.push_back(true);
}
}
j0 /= d;
}
constraints[i].setWeight(std::move(values), costs[j]);
constraints[i].setWeight(std::move(non_boolean_values), costs[j]);
}
}
}
/** \brief Write a Constraint object to a stream in a human-readable form.
*
* \param[in] o The stream to write to.
*
* \param[in] c The constraint object to be write to \p o.
*
* \return The stream \p o.
*/
template <class ...T>
std::ostream& operator << (std::ostream& o, const Constraint<T...>& c)
{
boost::property_tree::ptree t;
c.toPropertyTree(t);
boost::property_tree::write_json(o, t, true);
return o;
}
#endif /* WCSPINSTANCE_H_ */
| {
"alphanum_fraction": 0.5389583179,
"avg_line_length": 34.763496144,
"ext": "h",
"hexsha": "d5f22849f5c4556ecdbaab8d1b1f49bce22842c0",
"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": "fb2dbc97b69360f5d1fb67d84749e44afcdf48c3",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "nandofioretto/py_dcop",
"max_forks_repo_path": "third_parties/wcsp/src/WCSPInstance.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fb2dbc97b69360f5d1fb67d84749e44afcdf48c3",
"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": "nandofioretto/py_dcop",
"max_issues_repo_path": "third_parties/wcsp/src/WCSPInstance.h",
"max_line_length": 109,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "fb2dbc97b69360f5d1fb67d84749e44afcdf48c3",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "nandofioretto/py_dcop",
"max_stars_repo_path": "third_parties/wcsp/src/WCSPInstance.h",
"max_stars_repo_stars_event_max_datetime": "2018-09-28T12:54:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-08-06T08:55:36.000Z",
"num_tokens": 9309,
"size": 40569
} |
/*
Performing approximate Bayesian computation sequential Monte Carlo (Toni et al.
2009) on a beta-binomial model.
Synthetic data is generated by `ground_truth_and_analysis.ipynb`.
This script writes particles.csv, where each row corresponds to a particle and
each column corresponds to a round of SMC.
Defining #DEBUG_MODE will silence all writing to stdout. One may then add
printf statements in the code, and perhaps write the output to file as:
`./run.sh > output.txt`
TODO: Export all functions which are specific to the beta-binomial model into
smc.h, and perhaps rename smc.h as beta_binomial.h
Author: Juvid Aryaman
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sort_double.h>
#include <gsl/gsl_statistics.h>
#define N_DATA 50
#define N_TRUTH 10
#define PRIOR_ALPHA 0.5
#define PRIOR_BETA 0.5
#define N_PARTICLES 5000
#define N_ROUNDS_SMC 50
#define KERNEL_SD 0.05
#define QUANTILE_ACCEPT_DISTANCE 0.8
#define RND gsl_rng_uniform(r)
#define SEED 1
#define DISTANCE_THRESHOLD_INIT 10
#define OUTFILE_NAME "particles.csv"
//#define DEBUG_MODE
#include "smc.h"
int main(int argc, char *argv[]) {
/* set up GSL RNG */
gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);
/* end of GSL setup */
gsl_rng_set(r, SEED);
/////////////////////////
/*Read data*/
/////////////////////////
FILE *data_pointer;
data_pointer = fopen("binom_data.csv", "r");
int data[N_DATA];
int i, j, read_error_status;
for (i=0; i < N_DATA; i++){
read_error_status = fscanf(data_pointer, "%d\n", &data[i]);
}
if (read_error_status != 1){printf("Error reading data\n"); return 0;}
/////////////////////////
/*Initialise variables*/
/////////////////////////
/*Make a (N_ROUNDS_SMC X N_PARTICLES) array to store all particles at all rounds
of SMC*/
double** theta_particle;
theta_particle = (double**) malloc(N_ROUNDS_SMC * sizeof(double*));
for (i = 0; i < N_ROUNDS_SMC; i++){
theta_particle[i] = (double*) malloc(N_PARTICLES * sizeof(double));
}
double distance_threshold = DISTANCE_THRESHOLD_INIT;
int *simulated_data = (int*) malloc(N_DATA * sizeof(int));
double *distance = malloc(N_PARTICLES * sizeof(double));
double *weight = malloc(N_PARTICLES * sizeof(double));
double weight_normalizer = 0.0;
int time_smc=0; // an index of each round of SMC
int param_index_chosen;
/////////////////////////
/*Perform ABC SMC*/
/////////////////////////
/*For every round of SMC*/
for (time_smc = 0; time_smc < N_ROUNDS_SMC; time_smc++) {
#ifndef DEBUG_MODE
printf("Round %d of SMC\n", time_smc);
#endif
/*Draw or perturb a particle and compute distance*/
for (i = 0; i < N_PARTICLES; i++) {
distance[i] = distance_threshold + 1.0; // reset distance of particle i
while (distance[i] > distance_threshold) {
if (time_smc == 0) {
// Sample from the prior
theta_particle[0][i] = gsl_ran_beta(r, PRIOR_ALPHA, PRIOR_BETA);
}
else{
/*Sample from the old weights and perturb*/
param_index_chosen = weighted_choice(r, weight);
if ((param_index_chosen < 0)||(param_index_chosen >= N_PARTICLES)) {
printf("Error in param_index_chosen\n"); return -1;
}
theta_particle[time_smc][i] =
theta_particle[time_smc-1][param_index_chosen] +
gsl_ran_gaussian(r, KERNEL_SD);
// check if bounds of prior exceeded
if((theta_particle[time_smc][i]<0) || (theta_particle[time_smc][i] > 1)) continue;
}
// Simulate a candidate dataset
for (j = 0; j < N_DATA; j++) {
simulated_data[j] = gsl_ran_binomial(r, theta_particle[time_smc][i], N_TRUTH);
}
// Compute distance between data and simulation
distance[i] = distance_metric(data, simulated_data);
}
}
#ifndef DEBUG_MODE
printf("Particles sampled.\n");
#endif
/*Compute weights*/
if (time_smc==0){ for (i = 0; i < N_PARTICLES; i++) weight[i] = 1.0;}
else{
weight_normalizer = 0.0;
for (i = 0; i < N_PARTICLES; i++) {
weight_normalizer += weight[i]*kernel_pdf(theta_particle[time_smc-1][i],
theta_particle[time_smc][i]);
}
for (i = 0; i < N_PARTICLES; i++) {
weight[i] = prior_pdf(theta_particle[time_smc][i])/weight_normalizer;
}
}
/*Normalise weights*/
weight_normalizer = 0.0;
for (i = 0; i < N_PARTICLES; i++) weight_normalizer += weight[i];
for (i = 0; i < N_PARTICLES; i++) weight[i] = weight[i]/weight_normalizer;
/* Resample weights*/
distance_threshold = update_distance_threshold(distance);
}
#ifndef DEBUG_MODE
printf("Writing particles to file\n");
#endif
write_particles_to_csv(theta_particle);
#ifndef DEBUG_MODE
printf("Done!\n");
#endif
return 0; //return from main
} //close main
| {
"alphanum_fraction": 0.6596804316,
"avg_line_length": 27.2259887006,
"ext": "c",
"hexsha": "94f51bb74201f935f590a796c7ddad5882350d71",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-07-02T14:25:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-07-02T14:25:20.000Z",
"max_forks_repo_head_hexsha": "df270b58d35d1248079e4651988ded4074237bfc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jaryaman/ML_demos",
"max_forks_repo_path": "Notebooks/ABC_SMC/Beta_binomial_model/smc.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "df270b58d35d1248079e4651988ded4074237bfc",
"max_issues_repo_issues_event_max_datetime": "2020-09-28T14:21:39.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-21T18:23:19.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jaryaman/ML_demos",
"max_issues_repo_path": "Notebooks/ABC_SMC/Beta_binomial_model/smc.c",
"max_line_length": 87,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "df270b58d35d1248079e4651988ded4074237bfc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jaryaman/ML_demos",
"max_stars_repo_path": "Notebooks/ABC_SMC/Beta_binomial_model/smc.c",
"max_stars_repo_stars_event_max_datetime": "2018-07-31T16:51:10.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-28T18:14:12.000Z",
"num_tokens": 1328,
"size": 4819
} |
#pragma once
#include "icommand.h"
#include "optioninfo.h"
#include "configaccess.h"
#include "config.h"
#include "format.h"
#include "streamreader.h"
#include <gsl/gsl>
#include <cmdlime/errors.h>
#include <cmdlime/customnames.h>
#include <cmdlime/detail/configaccess.h>
#include <cmdlime/detail/flag.h>
#include <sstream>
#include <functional>
#include <memory>
namespace cmdlime::detail{
template <typename TConfig>
class Command : public ICommand{
public:
enum class Type{
Normal,
SubCommand
};
Command(const std::string& name,
std::function<std::optional<TConfig>&()> commandGetter,
Type type)
: info_(name, {}, {})
, commandGetter_(commandGetter)
, type_(type)
{
}
OptionInfo& info() override
{
return info_;
}
const OptionInfo& info() const override
{
return info_;
}
private:
void read(const std::vector<std::string>& commandLine) override
{
auto& commandCfg = commandGetter_();
if (!commandCfg.has_value()){
commandCfg.emplace();
if (helpFlag_){
detail::ConfigAccess<TConfig>(*commandCfg).addFlag(std::move(helpFlag_));
detail::ConfigAccess<TConfig>(*commandCfg).addHelpFlagToCommands(programName_);
}
}
commandCfg->read(commandLine);
}
void enableHelpFlag(const std::string& programName) override
{
programName_ = programName + " " + info_.name();
using NameProvider = typename detail::Format<detail::ConfigAccess<TConfig>::format()>::nameProvider;
helpFlag_ = std::make_unique<detail::Flag>(NameProvider::name("help"),
std::string{},
[this]()->bool&{return helpFlagValue_;},
detail::Flag::Type::Exit);
helpFlag_->info().addDescription("show usage info and exit");
}
bool isHelpFlagSet() const override
{
return helpFlagValue_;
}
bool isSubCommand() const override
{
return type_ == Type::SubCommand;
}
std::string usageInfo() const override
{
auto& commandCfg = commandGetter_();
if (!commandCfg.has_value())
return {};
return commandCfg->usageInfo(programName_);
}
std::string usageInfoDetailed() const override
{
auto& commandCfg = commandGetter_();
if (!commandCfg.has_value())
return {};
return commandCfg->usageInfoDetailed(programName_);
}
std::vector<not_null<ICommand*>> commandList() override
{
auto& commandCfg = commandGetter_();
if (!commandCfg.has_value())
return {};
return detail::ConfigAccess<TConfig>(*commandCfg).commandList();
}
private:
OptionInfo info_;
std::function<std::optional<TConfig>&()> commandGetter_;
Type type_;
std::string programName_;
std::unique_ptr<IFlag> helpFlag_;
bool helpFlagValue_ = false;
};
template<typename T, typename TConfig>
class CommandCreator{
using NameProvider = typename Format<ConfigAccess<TConfig>::format()>::nameProvider;
public:
CommandCreator(TConfig& cfg,
const std::string& varName,
std::function<std::optional<T>&()> commandGetter,
typename Command<T>::Type type = Command<T>::Type::Normal)
: cfg_(cfg)
{
static_assert (std::is_base_of_v<Config<ConfigAccess<TConfig>::format()>, T>,
"Command's type must be a subclass of Config<FormatType> and have the same format as its parent config.");
Expects(!varName.empty());
command_ = std::make_unique<Command<T>>(NameProvider::fullName(varName), commandGetter, type);
}
CommandCreator<T, TConfig>& operator<<(const std::string& info)
{
command_->info().addDescription(info);
return *this;
}
CommandCreator<T, TConfig>& operator<<(const Name& customName)
{
command_->info().resetName(customName.value());
return *this;
}
operator std::optional<T>()
{
ConfigAccess<TConfig>{cfg_}.addCommand(std::move(command_));
return std::optional<T>{};
}
private:
std::unique_ptr<Command<T>> command_;
TConfig& cfg_;
};
template <typename T, typename TConfig>
CommandCreator<T, TConfig> makeCommandCreator(TConfig& cfg,
const std::string& varName,
std::function<std::optional<T>&()> commandGetter,
typename Command<T>::Type type = Command<T>::Type::Normal)
{
return CommandCreator<T, TConfig>{cfg, varName, commandGetter, type};
}
}
| {
"alphanum_fraction": 0.5900532133,
"avg_line_length": 29.7926829268,
"ext": "h",
"hexsha": "7730e2fcc9ebed7d0e7ecc56ef7f3f2406bbfb02",
"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/command.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/command.h",
"max_line_length": 129,
"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/command.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": 1054,
"size": 4886
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gbpLib.h>
#include <gbpMath.h>
#include <gbpCosmo_linear_theory.h>
#include <gsl/gsl_multimin.h>
typedef struct init_gbpCosmo2gbpCosmo_integrand_params_struct init_gbpCosmo2gbpCosmo_integrand_params;
struct init_gbpCosmo2gbpCosmo_integrand_params_struct {
double inv_s;
double z_source;
double z_target;
double R_1;
double R_2;
cosmo_info ** cosmo_source;
cosmo_info ** cosmo_target;
int n_int;
gsl_integration_workspace *wspace;
};
double init_gbpCosmo2gbpCosmo_integrand(double R, void *params_in) {
init_gbpCosmo2gbpCosmo_integrand_params *params = (init_gbpCosmo2gbpCosmo_integrand_params *)params_in;
double inv_s = params->inv_s;
double z_source = params->z_source;
double z_target = params->z_target;
cosmo_info ** cosmo_source = params->cosmo_source;
cosmo_info ** cosmo_target = params->cosmo_target;
return (pow(1. - (sigma_R(cosmo_source, inv_s * R, z_source, PSPEC_LINEAR_TF, PSPEC_ALL_MATTER)) /
(sigma_R(cosmo_target, R, z_target, PSPEC_LINEAR_TF, PSPEC_ALL_MATTER)),
2.) /
R);
}
double init_gbpCosmo2gbpCosmo_minimize_function(const gsl_vector *v_i, void *params_in) {
// Set variable integrand parameters
init_gbpCosmo2gbpCosmo_integrand_params *params = (init_gbpCosmo2gbpCosmo_integrand_params *)params_in;
params->inv_s = gsl_vector_get(v_i, 0);
params->z_target = gsl_vector_get(v_i, 1);
// Perform integral to minimize
gsl_function integrand;
double delta_i;
double abs_error;
integrand.function = init_gbpCosmo2gbpCosmo_integrand;
integrand.params = params_in;
gsl_integration_qag(&integrand, params->R_1, params->R_2, 0, 1e-3, params->n_int, GSL_INTEG_GAUSS61, params->wspace, &delta_i, &abs_error);
return (delta_i / take_ln(params->R_2 / params->R_1));
}
void init_gbpCosmo2gbpCosmo(cosmo_info ** cosmo_source,
cosmo_info ** cosmo_target,
double z_min,
double M_min,
double M_max,
gbpCosmo2gbpCosmo_info *gbpCosmo2gbpCosmo) {
SID_log("Initializing cosmology scaling...", SID_LOG_OPEN | SID_LOG_TIMER);
SID_set_verbosity(SID_SET_VERBOSITY_RELATIVE, -1);
// Store some infor in the gbpCosmo2gbpCosmo_info structure
gbpCosmo2gbpCosmo->M_min = M_min;
gbpCosmo2gbpCosmo->M_max = M_max;
gbpCosmo2gbpCosmo->z_min = z_min;
gbpCosmo2gbpCosmo->cosmo_source = (*cosmo_source);
gbpCosmo2gbpCosmo->cosmo_target = (*cosmo_target);
// Perform minimization
// const gsl_multimin_fminimizer_type *T=gsl_multimin_fminimizer_nmsimplex2;
const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
gsl_multimin_fminimizer * s = NULL;
gsl_vector * ss, *x;
gsl_multimin_function minex_func;
// Starting point
x = gsl_vector_alloc(2);
gsl_vector_set(x, 0, 1.); // inv_s
gsl_vector_set(x, 1, z_min); // z_scaled
// Set initial step sizes to 1
ss = gsl_vector_alloc(2);
gsl_vector_set_all(ss, 1.0);
// Set parameters
init_gbpCosmo2gbpCosmo_integrand_params params;
params.cosmo_source = cosmo_source;
params.cosmo_target = cosmo_target;
params.z_source = z_min;
params.R_1 = R_of_M(M_min, *cosmo_source);
params.R_2 = R_of_M(M_max, *cosmo_source);
params.inv_s = gsl_vector_get(x, 0);
params.z_target = gsl_vector_get(x, 1);
params.n_int = 100;
params.wspace = gsl_integration_workspace_alloc(params.n_int);
// Initialize method
minex_func.n = 2;
minex_func.f = init_gbpCosmo2gbpCosmo_minimize_function;
minex_func.params = (void *)(¶ms);
s = gsl_multimin_fminimizer_alloc(T, 2);
gsl_multimin_fminimizer_set(s, &minex_func, x, ss);
// Perform minimization
double size;
int status;
size_t iter = 0;
size_t iter_max = 200;
do {
iter++;
status = gsl_multimin_fminimizer_iterate(s);
if(status)
SID_exit_error("Error encountered during minimisation in init_gbpCosmo2gbpCosmo() (status=%d).",
SID_ERROR_LOGIC, status);
size = gsl_multimin_fminimizer_size(s);
status = gsl_multimin_test_size(size, 1e-2);
} while(status == GSL_CONTINUE && iter <= iter_max);
if(status != GSL_SUCCESS)
SID_exit_error("Failed to converge during minimisation in init_gbpCosmo2gbpCosmo() (status=%d,iter=%d).",
SID_ERROR_LOGIC, status, iter);
// Finalize results
double Omega_M_source = ((double *)ADaPS_fetch(*cosmo_source, "Omega_M"))[0];
double H_Hubble_source = 1e2 * ((double *)ADaPS_fetch(*cosmo_source, "h_Hubble"))[0];
double Omega_M_target = ((double *)ADaPS_fetch(*cosmo_target, "Omega_M"))[0];
double H_Hubble_target = 1e2 * ((double *)ADaPS_fetch(*cosmo_target, "h_Hubble"))[0];
gbpCosmo2gbpCosmo->s_L = 1. / gsl_vector_get(s->x, 0);
gbpCosmo2gbpCosmo->s_M = (Omega_M_target * H_Hubble_target) / (Omega_M_source * H_Hubble_source) * pow((gbpCosmo2gbpCosmo->s_L), 3.);
gbpCosmo2gbpCosmo->z_min_scaled = gsl_vector_get(s->x, 1);
;
// Calculate growth factors needed for
// determining redshift mappings
gbpCosmo2gbpCosmo->D_prime_z_min = linear_growth_factor(z_min, cosmo_target);
gbpCosmo2gbpCosmo->D_z_scaled = linear_growth_factor(gbpCosmo2gbpCosmo->z_min_scaled, cosmo_source);
gbpCosmo2gbpCosmo->D_ratio = gbpCosmo2gbpCosmo->D_prime_z_min / gbpCosmo2gbpCosmo->D_z_scaled;
// Clean-up
gsl_vector_free(x);
gsl_vector_free(ss);
gsl_multimin_fminimizer_free(s);
gsl_integration_workspace_free(params.wspace);
SID_set_verbosity(SID_SET_VERBOSITY_DEFAULT);
SID_log("Done.", SID_LOG_CLOSE);
}
| {
"alphanum_fraction": 0.625893808,
"avg_line_length": 45.3310344828,
"ext": "c",
"hexsha": "a9895a0b7bd4cd30a76d2f7e470af99c69242f7e",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpAstro/gbpCosmo/linear_theory/init_gbpCosmo2gbpCosmo.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpAstro/gbpCosmo/linear_theory/init_gbpCosmo2gbpCosmo.c",
"max_line_length": 146,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpAstro/gbpCosmo/linear_theory/init_gbpCosmo2gbpCosmo.c",
"max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z",
"num_tokens": 1816,
"size": 6573
} |
#pragma once
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include <DirectXMath.h>
#include <gsl\gsl>
namespace Library
{
class SamplerStates final
{
public:
inline static winrt::com_ptr<ID3D11SamplerState> TrilinearWrap;
inline static winrt::com_ptr<ID3D11SamplerState> TrilinearMirror;
inline static winrt::com_ptr<ID3D11SamplerState> TrilinearClamp;
inline static winrt::com_ptr<ID3D11SamplerState> TrilinearBorder;
inline static winrt::com_ptr<ID3D11SamplerState> PointClamp;
inline static winrt::com_ptr<ID3D11SamplerState> DepthMap;
inline static winrt::com_ptr<ID3D11SamplerState> ShadowMap;
inline static winrt::com_ptr<ID3D11SamplerState> PcfShadowMap;
static DirectX::XMVECTORF32 BorderColor;
static DirectX::XMVECTORF32 ShadowMapBorderColor;
static void Initialize(gsl::not_null<ID3D11Device*> direct3DDevice);
static void Shutdown();
SamplerStates() = delete;
SamplerStates(const SamplerStates&) = delete;
SamplerStates& operator=(const SamplerStates&) = delete;
SamplerStates(SamplerStates&&) = delete;
SamplerStates& operator=(SamplerStates&&) = delete;
~SamplerStates() = default;
};
} | {
"alphanum_fraction": 0.7856525497,
"avg_line_length": 33.0571428571,
"ext": "h",
"hexsha": "6dac2ba238b9c589f3ebae3ae0dbf432f1a52b63",
"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/SamplerStates.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/SamplerStates.h",
"max_line_length": 70,
"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/SamplerStates.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 318,
"size": 1157
} |
/*
* Copyright 2009-2018 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _GSL_BOOST_UBLAS_MATRIX_PROD_
#define _GSL_BOOST_UBLAS_MATRIX_PROD_
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <gsl/gsl_blas.h>
namespace boost { namespace numeric { namespace ublas {
/*
* GSL has separate implementations for floats and doubles
* hence we first have specializations for these two types
* TSeparate templates for diagonal and symmetric matreces
* and their combinations. To check whether a specific
* routine is called, define GSLDEBUG
*/
// partial specialization for double precision (dgemm))
template<class F, class A>
inline matrix<double,F,A> // prod( m1, m2 )
prod(const matrix<double,F,A> &m1, const matrix<double,F,A> &m2)
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;34mGSL [CMD,CM]\x1b[0;39m\n" << std::flush;
#endif
gsl_matrix_const_view mA = gsl_matrix_const_view_array (&m1(0,0), m1.size1(), m1.size2());
gsl_matrix_const_view mB = gsl_matrix_const_view_array (&m2(0,0), m2.size1(), m2.size2());
boost::numeric::ublas::matrix<double,F,A> AxB( m1.size1(), m2.size2() );
gsl_matrix_view mC = gsl_matrix_view_array (&AxB(0,0), AxB.size1(), AxB.size2());
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
1.0, &mA.matrix, &mB.matrix,
0.0, &mC.matrix);
return AxB;
}
// partial specialization for single precision (sgemm))
template<class F, class A>
inline matrix<float,F,A> // prod( m1, m2 )
prod(const matrix<float,F,A> &m1, const matrix<float,F,A> &m2)
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;34mGSL [CMS,CM]\x1b[0;39m\n" << std::flush;
#endif
gsl_matrix_float_const_view mA = gsl_matrix_float_const_view_array (&m1(0,0), m1.size1(), m1.size2());
gsl_matrix_float_const_view mB = gsl_matrix_float_const_view_array (&m2(0,0), m2.size1(), m2.size2());
boost::numeric::ublas::matrix<float,F,A> AxB( m1.size1(), m2.size2() );
gsl_matrix_float_view mC = gsl_matrix_float_view_array (&AxB(0,0), AxB.size1(), AxB.size2());
gsl_blas_sgemm (CblasNoTrans, CblasNoTrans,
1.0, &mA.matrix, &mB.matrix,
0.0, &mC.matrix);
return AxB;
}
// full specialization
template<class T, class F, class A>
inline matrix<T,F,A> // prod( m1, m2 )
prod(const matrix<T,F,A> &m1, const matrix<T,F,A> &m2)
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;34mGSL [CM,CM]\x1b[0;39m -> " << std::flush;
#endif
return prod(m1,m2);
}
/// transpose products
template<class T, class F, class A>
inline matrix<T,F,A> // prod( trans(m1), m2 )
prod(const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m1, const matrix<T,F,A> &m2)
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;32mGSL [CTM,CM]\x1b[0;39m -> " << std::flush;
#endif
boost::numeric::ublas::matrix<T,F,A> _m1 = m1;
return prod(_m1,m2);
}
template<class T, class F, class A>
inline matrix<T,F,A> // prod( m1, trans(m2) )
prod(const matrix<T,F,A> &m1, const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m2)
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;32mGSL [CM,CTM]\x1b[0;39m -> " << std::flush;
#endif
const boost::numeric::ublas::matrix<T,F,A> _m2 = m2;
return prod(m1,_m2);
}
template<class T, class F, class A>
inline matrix<T,F,A> // prod( trans(m1), trans(m2) )
prod(const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m1, const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m2)
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;32mGSL [CTM,CTM]\x1b[0;39m -> " << std::flush;
#endif
boost::numeric::ublas::matrix<T,F,A> _m1 = m1;
boost::numeric::ublas::matrix<T,F,A> _m2 = m2;
return prod(_m1,_m2);
}
/// diagonal matrix
template<class T, class F, class L, class A>
inline matrix<T,F,A> // prod( diagonal m1, m2 )
prod(const diagonal_matrix<T,L,A> &m1, const matrix<T,F,A> &m2 )
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;33mGSL [CDM, CM]\x1b[0;39m -> " << std::flush;
#endif
const matrix<T,F,A> _m1 = m1;
return prod(_m1,m2);
}
template<class T, class F, class L, class A>
inline matrix<T,F,A> // prod( m1, diagonal m2 )
prod(const matrix<T,F,A> &m1, const diagonal_matrix<T,L,A> &m2 )
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;33mGSL [CM, CDM]\x1b[0;39m -> " << std::flush;
#endif
const matrix<T,F,A> _m2 = m2;
return prod(m1,_m2);
}
template<class T, class F, class L, class A>
inline matrix<T,F,A> // prod( diagonal m1, diagonal m2 )
prod(const diagonal_matrix<T,L,A> &m1, const diagonal_matrix<T,L,A> &m2 )
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;33mGSL [CDM, CM]\x1b[0;39m -> " << std::flush;
#endif
const matrix<T,F,A> _m1 = m1;
const matrix<T,F,A> _m2 = m2;
return prod(_m1,_m2);
}
template<class T, class F, class L, class A>
inline matrix<T,F,A> // prod( diagonal m1, transpose m2 )
prod(const diagonal_matrix<T,L,A> &m1, const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m2)
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;33mGSL [CDM, CTM]\x1b[0;39m -> " << std::flush;
#endif
const matrix<T,F,A> _m1 = m1;
const matrix<T,F,A> _m2 = m2;
return prod(_m1,_m2);
}
template<class T, class F, class L, class A>
inline matrix<T,F,A> // prod( transpose m1, diagonal m2 )
prod(const matrix_unary2<matrix<T,F,A>,scalar_identity<T> > &m1, const diagonal_matrix<T,L,A> &m2)
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;33mGSL [CTM, CDM]\x1b[0;39m -> " << std::flush;
#endif
const matrix<T,F,A> _m1 = m1;
const matrix<T,F,A> _m2 = m2;
return prod(_m1,_m2);
}
// symmetric matrix
template<class T, class F, class A, class TRI, class L>
inline matrix<T,F,A> // prod( symmetric m1, m2 )
prod(symmetric_matrix<T, TRI, L, A> &m1, matrix<T,F,A> &m2 )
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;33mGSL [CSM, CM]\x1b[0;39m -> " << std::flush;
#endif
assert( m1.size1() == m2.size1() );
const matrix<T,F,A> _m1 = m1;
return prod(_m1, m2 );
}
template<class T, class F, class A, class TRI, class L>
inline matrix<T,F,A> // prod( m1, symmetric m2 )
prod( matrix<T,F,A> &m1, symmetric_matrix<T, TRI, L, A> &m2 )
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;33mGSL [CSM, CM]\x1b[0;39m -> " << std::flush;
#endif
assert( m1.size1() == m2.size1() );
const matrix<T,F,A> _m2 = m2;
return prod(m1, _m2 );
}
template<class T, class F, class A, class TRI, class L>
inline matrix<T,F,A> // prod( symmetric m1, symmetric m2 )
prod(symmetric_matrix<T, TRI, L, A> &m1, symmetric_matrix<T, TRI, L, A> &m2 )
{
#ifdef GSLDEBUG
std::cout << "\x1b[0;33mGSL [CSM, CM]\x1b[0;39m -> " << std::flush;
#endif
assert( m1.size1() == m2.size1() );
const matrix<T,F,A> _m1 = m1;
const matrix<T,F,A> _m2 = m2;
return prod(_m1, _m2 );
}
}}}
#endif // _GSL_BOOST_UBLAS_MATRIX_PROD_
| {
"alphanum_fraction": 0.5565328087,
"avg_line_length": 35.8547717842,
"ext": "h",
"hexsha": "3adf97710750d226f2fdff9ce995576710c00080",
"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": "8461ba9d012c7e171a05e0b114b59d0523fc9a56",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "mbarbry/ctp",
"max_forks_repo_path": "include/votca/ctp/votca_gsl_boost_ublas_matrix_prod.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8461ba9d012c7e171a05e0b114b59d0523fc9a56",
"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": "mbarbry/ctp",
"max_issues_repo_path": "include/votca/ctp/votca_gsl_boost_ublas_matrix_prod.h",
"max_line_length": 133,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8461ba9d012c7e171a05e0b114b59d0523fc9a56",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "mbarbry/ctp",
"max_stars_repo_path": "include/votca/ctp/votca_gsl_boost_ublas_matrix_prod.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2696,
"size": 8641
} |
#ifndef GSLMATRIX_H
#define GSLMATRIX_H
#include <gsl/gsl_matrix_double.h> //Science Library header file
#include <gsl/gsl_linalg.h>
#include "Matrix.h"
template<typename T>
class GSLMatrix : public Matrix<T>
{
private:
gsl_matrix *_matrix; //Pointer to the gsl_matrix struct
void setMatrix(gsl_matrix* newMatrix);
public:
GSLMatrix(int nRow, int nCol);
~GSLMatrix();
void resize(int nRow, int nCol); //If the matrix has elements in it should it keep those elements or is it ok if they are lost?
T getElement(int i, int j) const;
void setElement(int i, int j, T value);
gsl_matrix* getMatrix() const;
int getSize() const;
void setZero();
void invert();
Matrix<T>* operator*(const Matrix<T>* RHS);
Matrix<T>* operator+(const Matrix<T>* RHS);
Matrix<T>* operator-(const Matrix<T>* RHS);
void operator=(const GSLMatrix<T>* RHS);
};
template<typename T>
GSLMatrix<T>::GSLMatrix(int nRow, int nCol)
{
_matrix = gsl_matrix_alloc(nRow, nCol);
}
template<typename T>
GSLMatrix<T>::~GSLMatrix()
{
if(_matrix != NULL)
gsl_matrix_free(_matrix);
}
template<typename T>
void GSLMatrix<T>::setMatrix(gsl_matrix* newMatrix)
{
//Free the old matrix, if there is one
if(_matrix != NULL)
gsl_matrix_free(_matrix);
_matrix = newMatrix;
}
template<typename T>
void GSLMatrix<T>::resize(int nRow, int nCol)
{
if(_matrix != NULL)
gsl_matrix_free(_matrix);
_matrix = NULL;
_matrix = gsl_matrix_alloc(nRow, nCol);
}
template<typename T>
T GSLMatrix<T>::getElement(int i, int j) const
{
return gsl_matrix_get(_matrix, i, j);
}
template<typename T>
void GSLMatrix<T>::setElement(int i, int j, T value)
{
gsl_matrix_set(_matrix, i, j, value);
}
template<typename T>
void GSLMatrix<T>::invert()
{
int sigNum;
//gsl_matrix for the output
gsl_matrix* outputMatrix = gsl_matrix_alloc(_matrix->size1, _matrix->size1 );
//Allocate permutation matrix
gsl_permutation* permutationM = gsl_permutation_alloc(_matrix->size1);
//get the LU decomposition of the matrix
gsl_linalg_LU_decomp((gsl_matrix*) _matrix, permutationM, &sigNum);
//invert the matrix
gsl_linalg_LU_invert(_matrix, permutationM, outputMatrix);
this->setMatrix(outputMatrix);
gsl_permutation_free(permutationM);
}
template<typename T>
gsl_matrix* GSLMatrix<T>::getMatrix() const
{
return _matrix;
}
template<typename T>
int GSLMatrix<T>::getSize() const
{
return _matrix->size1;
}
template<typename T>
void GSLMatrix<T>::setZero()
{
gsl_matrix_set_zero (_matrix);
}
template<typename T>
Matrix<T>* GSLMatrix<T>::operator*(const Matrix<T>* RHS)
{
//Check if its the same size
if(_matrix->size1 != RHS->getSize() || _matrix->size1 != _matrix->size1)
return NULL;
//Check if its the same type (GSL Matrix)
if(dynamic_cast<const GSLMatrix<T>*> (RHS) == NULL)
throw Error (InvalidParam, "GSLMatrix<T>::operator*",
"RHS is not a GSLMatrix");
//Create the new result matrix
GSLMatrix<T> *result = new GSLMatrix<T>(_matrix->size1, _matrix->size1);
result->setZero();
//For each row
for(int row = 0; row < _matrix->size1; row++)
{
//for each element in that row
for(int element = 0; element < _matrix->size2; element++)
{
//calculate the value for the current element
for(int i = 0; i < _matrix->size1; i++)
{
result->setElement(row, element, (result->getElement(row, element) ) + this->getElement(row, i) * RHS->getElement(i,element));
}
}
}
return result;
}
template<typename T>
Matrix<T>* GSLMatrix<T>::operator+(const Matrix<T>* RHS)
{
//Check if its the same size
if(_matrix->size1 != RHS->getSize() || _matrix->size1 != _matrix->size1)
return NULL;
//Check if its the same type (GSL Matrix)
if(dynamic_cast<const GSLMatrix<T>*> (RHS) == NULL)
throw Error (InvalidParam, "GSLMatrix<T>::operator*",
"RHS is not a GSLMatrix");
GSLMatrix<T> *result = new GSLMatrix<T>(_matrix->size1, _matrix->size1); //Create the new result matrix
result->setZero();
//For each row
for(int row = 0; row < _matrix->size1; row++)
{
//for each element in that row
for(int element = 0; element < _matrix->size1; element++)
{
result->setElement(row, element, this->getElement(row, element) + RHS->getElement(row, element) );
}
}
return result;
}
template<typename T>
Matrix<T>* GSLMatrix<T>::operator-(const Matrix<T>* RHS)
{
if(_matrix->size1 != RHS->getSize() || _matrix->size1 != _matrix->size1) //Check if its the same size
return NULL;
//Check if its the same type (GSL Matrix)
if(dynamic_cast<const GSLMatrix<T>*> (RHS) == NULL)
throw Error (InvalidParam, "GSLMatrix<T>::operator*",
"RHS is not a GSLMatrix");
GSLMatrix<T> *result = new GSLMatrix<T>(RHS->getSize(), RHS->getSize()); //Create the new result matrix
result->setZero();
//For each row
for(int row = 0; row < _matrix->size1; row++)
{
//for each element in that row
for(int element = 0; element < _matrix->size1; element++)
{
result->setElement(row, element, this->getElement(row, element) - RHS->getElement(row, element) );
}
}
return result;
}
template<typename T>
void GSLMatrix<T>::operator=(const GSLMatrix<T>* RHS)
{
if(_matrix->size1 != RHS->getSize() )
{
gsl_matrix_free(_matrix);
gsl_matrix_alloc(RHS->getSize(), RHS->getSize());
}
gsl_matrix_memcpy(_matrix, RHS->getMatrix());
}
#endif
| {
"alphanum_fraction": 0.6588868941,
"avg_line_length": 23.4033613445,
"ext": "h",
"hexsha": "81d52449fa432881868ed385d6bf28eca0eacf6b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-02-13T20:08:14.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-02-13T20:08:14.000Z",
"max_forks_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35",
"max_forks_repo_licenses": [
"AFL-2.1"
],
"max_forks_repo_name": "xuanyuanstar/psrchive_CDFT",
"max_forks_repo_path": "More/MEAL/MEAL/GSLMatrix.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"AFL-2.1"
],
"max_issues_repo_name": "xuanyuanstar/psrchive_CDFT",
"max_issues_repo_path": "More/MEAL/MEAL/GSLMatrix.h",
"max_line_length": 129,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35",
"max_stars_repo_licenses": [
"AFL-2.1"
],
"max_stars_repo_name": "xuanyuanstar/psrchive_CDFT",
"max_stars_repo_path": "More/MEAL/MEAL/GSLMatrix.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1498,
"size": 5570
} |
#ifndef __LLVUTILS_H__
#define __LLVUTILS_H__ 1
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_cdf.h>
#include "constants.h"
#include "struct.h"
#include "EOBNRv2HMROMstruct.h"
#include "EOBNRv2HMROM.h"
#include "wip.h"
#include "likelihood.h"
#include "splinecoeffs.h"
#include "LLVFDresponse.h"
#include "LLVnoise.h"
/***************** Structures for parameters *****************/
/* Parameters for the generation of a LLV waveform (in the form of a list of modes) */
typedef struct tagLLVParams {
double tRef; /* reference time (s) - GPS time at the frequency representing coalescence */
double phiRef; /* reference phase (rad) - phase at the frequency representing coalescence (or at fRef if specified) */
double m1; /* mass of companion 1 (solar masses) */
double m2; /* mass of companion 2 (solar masses) */
double distance; /* distance of source (Mpc) */
double ra; /* right ascension of the source (rad) */
double dec; /* declination of the source (rad) */
double inclination; /* inclination of L relative to line of sight (rad) */
double polarization; /* polarization angle (rad) */
int nbmode; /* number of modes to generate (starting with 22) - defaults to 5 (all modes) */
} LLVParams;
/* Global parameters for the waveform generation and overlap computation */
typedef struct tagLLVGlobalParams {
double fRef; /* reference frequency (Hz, default 0 which is interpreted as Mf=0.14) */
double minf; /* Minimal frequency (Hz) - when set to 0 (default), use the first frequency covered by the noise data of the detector */
double maxf; /* Maximal frequency (Hz) - when set to 0 (default), use the last frequency covered by the noise data of the detector */
int setphiRefatfRef; /* Flag for adjusting the FD phase at phiRef at the given fRef, which depends also on tRef - if false, treat phiRef simply as an orbital phase shift (minus an observer phase shift) (default=1) */
int nbmodeinj; /* number of modes to include in the injection (starting with 22) - defaults to 5 (all modes) */
int nbmodetemp; /* number of modes to include in the templates (starting with 22) - defaults to 5 (all modes) */
int tagint; /* Tag choosing the integrator: 0 for wip (default), 1 for linear integration */
int tagnetwork; /* Tag choosing the network of detectors to use */
int nbptsoverlap; /* Number of points to use in loglinear overlaps (default 32768) */
int constL; /* set all logLikelihood to 0 - allows to sample from the prior for testing */
} LLVGlobalParams;
typedef struct tagLLVPrior {
double deltaT; /* width of time prior centered on injected value (s) (default 0.1) */
double comp_min; /* minimum component mass (solar masses) (default 4) */
double comp_max; /* maximum component mass (solar masses) (default 50) */
double mtot_min; /* minimum total mass (solar masses) (default 8) */
double mtot_max; /* maximum total mass (solar masses) (default 100) */
double qmax; /* maximum asymmetric mass ratio (>=1) (default 12) */
double dist_min; /* minimum distance of source (Mpc) (default 1) */
double dist_max; /* maximum distance of source (Mpc) (default 1e4) */
double ra_min; /* minimum ra (rad, default 0) - for testing */
double ra_max; /* maximum ra (rad, default 2pi) - for testing */
double dec_min; /* minimum dec (rad, default 0) - for testing */
double dec_max; /* maximum dec (rad, default pi) - for testing */
double phase_min; /* minimum phase (rad, default 0) - for testing */
double phase_max; /* maximum phase (rad, default 2pi) - for testing */
double pol_min; /* minimum polarization (rad, default 0) - for testing */
double pol_max; /* maximum polarization (rad, default 2pi) - for testing */
double inc_min; /* minimum inclination (rad, default 0) - for testing */
double inc_max; /* maximum inclination (rad, default pi) - for testing */
double fix_m1;
double fix_m2;
double fix_time;
double fix_ra;
double fix_dec;
double fix_phase;
double fix_pol;
double fix_dist;
double fix_inc;
int pin_m1;
int pin_m2;
int pin_time;
int pin_ra;
int pin_dec;
int pin_phase;
int pin_pol;
int pin_dist;
int pin_inc;
double snr_target;
int rescale_distprior;
int flat_distprior;
} LLVPrior;
typedef struct tagLLVRunParams {
double eff; /* target efficiency (default 0.1) */
double tol; /* logZ tolerance (default 0.5) */
int nlive; /* number of live points (default 1000) */
char outroot[200]; /* output root (default "chains/LLVinference_") */
int bambi; /* run BAMBI? (default 0) */
int resume; /* resume form previous run? (default 0) */
int maxiter; /* max number of iterations (default 0 - ignore) */
char netfile[200]; /* NN settings file (default "LLVinference.inp") */
int mmodal; /* use multimodal decomposition ? */
int maxcls; /* max number of modes in multimodal decomposition */
int nclspar; /* number of parameters to use for multimodal decomposition - in the order of the cube */
double ztol; /* in multimodal decomposition, modes with lnZ lower than Ztol are ignored */
int seed; /* seed the inference by setting one of the live points to the injection ? */
} LLVRunParams;
/************ Structures for signals and injections ************/
// typedef struct tagLLVSignal
// {
// struct tagListmodesCAmpPhaseFrequencySeries* LHOSignal; /* Signal in LHO, in the form of a list of the contribution of each mode */
// struct tagListmodesCAmpPhaseFrequencySeries* LLOSignal; /* Signal in LLO, in the form of a list of the contribution of each mode */
// struct tagListmodesCAmpPhaseFrequencySeries* VIRGOSignal; /* Signal in VIRGO, in the form of a list of the contribution of each mode */
// double LHOhh; /* Inner product (h|h) for LHO */
// double LLOhh; /* Inner product (h|h) for LLO */
// double VIRGOhh; /* Inner product (h|h) for VIRGO */
// } LLVSignal;
typedef struct tagLLVSignalCAmpPhase
{
struct tagListmodesCAmpPhaseFrequencySeries* LHOSignal; /* Signal in LHO, in the form of a list of the contribution of each mode */
struct tagListmodesCAmpPhaseFrequencySeries* LLOSignal; /* Signal in LLO, in the form of a list of the contribution of each mode */
struct tagListmodesCAmpPhaseFrequencySeries* VIRGOSignal; /* Signal in VIRGO, in the form of a list of the contribution of each mode */
double LLVhh; /* Combined Inner product (h|h) for dectectors LHV */
} LLVSignalCAmpPhase;
typedef struct tagLLVInjectionCAmpPhase
{
struct tagListmodesCAmpPhaseSpline* LHOSplines; /* Signal in LHO, in the form of a list of splines for the contribution of each mode */
struct tagListmodesCAmpPhaseSpline* LLOSplines; /* Signal in LLO, in the form of a list of splines for the contribution of each mode */
struct tagListmodesCAmpPhaseSpline* VIRGOSplines; /* Signal in VIRGO, in the form of a list of splines for the contribution of each mode */
double LLVss; /* Combined Inner product (s|s) for dectectors LHV */
} LLVInjectionCAmpPhase;
typedef struct tagLLVSignalReIm /* We don't store the SNRs here, as we will use -1/2(h-s|h-s) for the likelihood */
{
struct tagReImFrequencySeries* LHOSignal; /* Signal in LHO, in the form of a Re/Im frequency series where the modes have been summed */
struct tagReImFrequencySeries* LLOSignal; /* Signal in LLO, in the form of a Re/Im frequency series where the modes have been summed */
struct tagReImFrequencySeries* VIRGOSignal; /* Signal in VIRGO, in the form of a Re/Im frequency series where the modes have been summed */
} LLVSignalReIm;
typedef struct tagLLVInjectionReIm /* Storing the vectors of frequencies and noise values - We don't store the SNRs here, as we will use -1/2(h-s|h-s) for the likelihood */
{
struct tagReImFrequencySeries* LHOSignal; /* Signal in LHO, in the form of a Re/Im frequency series where the modes have been summed */
struct tagReImFrequencySeries* LLOSignal; /* Signal in LLO, in the form of a Re/Im frequency series where the modes have been summed */
struct tagReImFrequencySeries* VIRGOSignal; /* Signal in VIRGO, in the form of a Re/Im frequency series where the modes have been summed */
gsl_vector* freq; /* Vector of frequencies of the injection (assumed to be the same for LHO, LLO, VIRGO) */
gsl_vector* noisevaluesLHO; /* Vector of noise values on freq LHO */
gsl_vector* noisevaluesLLO; /* Vector of noise values on freq LLO */
gsl_vector* noisevaluesVIRGO; /* Vector of noise values on freq VIRGO */
} LLVInjectionReIm;
/************ Functions for LLV parameters, injection, likelihood, prior ************/
/* Parsing parameters for the generation of a LLV waveform, from the command line */
/* Masses are input in solar masses and distances in Mpc - converted in SI for the internals */
void parse_args_LLV(ssize_t argc, char **argv,
LLVParams* params,
LLVGlobalParams* globalparams,
LLVPrior* prior,
LLVRunParams* run,
LLVParams* addparams);
/* Functions to print the parameters of the run in files for reference */
int print_parameters_to_file_LLV(
LLVParams* params,
LLVGlobalParams* globalparams,
LLVPrior* prior,
LLVRunParams* run);
int print_rescaleddist_to_file_LLV(
LLVParams* params,
LLVGlobalParams* globalparams,
LLVPrior* prior,
LLVRunParams* run);
/* Initialization and clean-up for LLVSignal structures */
void LLVSignalCAmpPhase_Cleanup(LLVSignalCAmpPhase* signal);
void LLVSignalCAmpPhase_Init(LLVSignalCAmpPhase** signal);
void LLVInjectionCAmpPhase_Cleanup(LLVInjectionCAmpPhase* signal);
void LLVInjectionCAmpPhase_Init(LLVInjectionCAmpPhase** signal);
void LLVSignalReIm_Cleanup(LLVSignalReIm* signal);
void LLVSignalReIm_Init(LLVSignalReIm** signal);
void LLVInjectionReIm_Cleanup(LLVInjectionReIm* signal);
void LLVInjectionReIm_Init(LLVInjectionReIm** signal);
/* Function generating a LLV signal as a list of modes in CAmp/Phase form, from LLV parameters */
int LLVGenerateSignalCAmpPhase(
struct tagLLVParams* params, /* Input: set of LLV parameters of the signal */
struct tagLLVSignalCAmpPhase* signal); /* Output: structure for the generated signal */
/* Function generating a LLV injection as a list of modes, given as preinterpolated splines, from LLV parameters */
int LLVGenerateInjectionCAmpPhase(
struct tagLLVParams* injectedparams, /* Input: set of LLV parameters of the signal */
struct tagLLVInjectionCAmpPhase* signal); /* Output: structure for the generated signal */
/* Function generating a LLV signal as a frequency series in Re/Im form where the modes have been summed, from LLV parameters - takes as argument the frequencies on which to evaluate */
int LLVGenerateSignalReIm(
struct tagLLVParams* params, /* Input: set of LLV parameters of the template */
gsl_vector* freq, /* Input: frequencies on which evaluating the waveform (from the injection) */
struct tagLLVSignalReIm* signal); /* Output: structure for the generated signal */
/* Function generating a LLV injection as a frequency series in Re/Im form where the modes have been summed, from LLV parameters - frequencies on which to evaluate are to be determined internally */
int LLVGenerateInjectionReIm(
struct tagLLVParams* injectedparams, /* Input: set of LLV parameters of the injection */
double fLow, /* Input: starting frequency (from argument minf) */
double fHigh, /* Input: upper frequency (from argument maxf) */
int nbpts, /* Input: number of frequency samples */
int tagsampling, /* Input: tag for using linear (0) or logarithmic (1) sampling */
struct tagLLVInjectionReIm* signal); /* Output: structure for the generated signal */
// checks prior boundaires
int PriorBoundaryCheck(LLVPrior *prior, double *Cube);
// Prior functions from Cube to physical parameters
// x1 is min, x2 is max when specified
// r is Cube value
double CubeToFlatPrior(double r, double x1, double x2);
double CubeToLogFlatPrior(double r, double x1, double x2);
double CubeToPowerPrior(double p, double r, double x1, double x2);
double CubeToGaussianPrior(double r, double mean, double sigma);
double CubeToSinPrior(double r, double x1, double x2);
double CubeToCosPrior(double r, double x1, double x2);
/* Prior functions from physical parameters to Cube
x1 is min, x2 is max when specified
y is physical value */
double FlatPriorToCube(double y, double x1, double x2);
double LogFlatPriorToCube(double y, double x1, double x2);
double PowerPriorToCube(double p, double y, double x1, double x2);
double SinPriorToCube(double y, double x1, double x2);
double CosPriorToCube(double y, double x1, double x2);
/* log-Likelihood functions */
double CalculateLogLCAmpPhase(LLVParams *params, LLVInjectionCAmpPhase* injection);
double CalculateLogLReIm(LLVParams *params, LLVInjectionReIm* injection);
/************ Global Parameters ************/
extern LLVParams* injectedparams;
extern LLVGlobalParams* globalparams;
extern LLVPrior* priorParams;
double logZdata;
#endif
| {
"alphanum_fraction": 0.6810104903,
"avg_line_length": 57.6666666667,
"ext": "h",
"hexsha": "7af16db351b28f970c657f4917de347d4617dc1e",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "JohnGBaker/flare",
"max_forks_repo_path": "LLVinference/LLVutils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "JohnGBaker/flare",
"max_issues_repo_path": "LLVinference/LLVutils.h",
"max_line_length": 224,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "JohnGBaker/flare",
"max_stars_repo_path": "LLVinference/LLVutils.h",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 3476,
"size": 14013
} |
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysinfo.h>
#include <sys/time.h>
#define PRINT_MAX 100 // don't print more than 100 elements
#define MEAN 0
#define STANDARD_DEVIATION 1
struct arguments {
double *array;
int start;
int end;
unsigned long seed;
};
void * initialize_array (void *arguments) {
/* Get arguments */
struct arguments *args = (struct arguments *) arguments;
double *array = args->array;
int start = args->start;
int end = args->end;
unsigned long seed = args->seed;
/* Create a new random number generator */
const gsl_rng_type *T;
gsl_rng *r;
gsl_rng_env_setup(); // set the default values for the random number generator variables
T = gsl_rng_default;
r = gsl_rng_alloc (T);
gsl_rng_set(r, seed); // setup the generator using the seed we got from the main function
/* Using the GSL library, initialize the array with normal random values */
for (int i = start; i < end; i++) {
array[i] = MEAN + gsl_ran_gaussian (r, STANDARD_DEVIATION);;
}
/* Free memory */
gsl_rng_free (r);
/* Exit thread when finished */
pthread_exit(NULL);
}
int main (int argc, char* argv[])
{
int i;
int number_of_elements;
int number_of_threads;
if (argc == 3) {
number_of_elements = atoi(argv[1]);
number_of_threads = atoi(argv[2]);
} else {
fprintf(stderr, "%s:\n", "Wrong number of arguments.");
fprintf(stderr, "%s:\n", "Use: ./avoid_race_condition number_of_elements number_of_threads");
exit(EXIT_FAILURE);
}
int elements_per_thread = number_of_elements / number_of_threads;
double *array = (double *) malloc(number_of_elements * sizeof(double));
pthread_t *threads = (pthread_t *) malloc(number_of_threads * sizeof(pthread_t));
struct arguments *args = (struct arguments *) malloc(number_of_threads * sizeof(struct arguments));;
srand(time(NULL)); // need to to use a new seed each time we run the program
// create threads
for (i = 0; i < number_of_threads; i++) {
args[i].array = array;
args[i].start = i * elements_per_thread;
if (i == number_of_threads - 1) { // in the last thread, process the remaining elements in case
// that NUMBER_OF_ELEMENTS is not divisible by NUMBER_OF_THREADS
args[i].end = number_of_elements;
} else {
args[i].end = args[i]. start + elements_per_thread;
}
args[i].seed = random();
// create the threads
if(pthread_create(&threads[i], NULL, initialize_array, (void *) &args[i]) == -1) {
fprintf(stderr, "%s %d\n", "Can't create thread number", i);
}
}
// wait until every thread ends
for (i = 0; i < number_of_threads; i++) {
if (pthread_join(threads[i], NULL) == -1) {
fprintf(stderr, "%s %d\n", "Can't join thread number", i);
}
}
// print numbers
if(number_of_elements <= PRINT_MAX) {
for (i = 0; i < number_of_elements; i++) {
printf (" %f", array[i]);
}
printf("\n");
} else {
printf("(Array size = %d. Printing only its first and last elements)\n", number_of_elements);
printf("%f %f ... %f %f\n", array[0], array[1], array[number_of_elements -2], array[number_of_elements -1]);
}
// free memory
free(array);
free(threads);
free(args);
return 0;
}
| {
"alphanum_fraction": 0.5494310999,
"avg_line_length": 34.0948275862,
"ext": "c",
"hexsha": "a2a037b981a864d3d4fd6ca4722181a7c74195f8",
"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/p_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/p_normal_numbers.c",
"max_line_length": 124,
"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/p_normal_numbers.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 886,
"size": 3955
} |
/**
*
* @file qwrapper_zlaset.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 Hatem Ltaief
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_zlaset(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int M, int N,
PLASMA_Complex64_t alpha, PLASMA_Complex64_t beta,
PLASMA_Complex64_t *A, int LDA)
{
DAG_CORE_LASET;
QUARK_Insert_Task(quark, CORE_zlaset_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &M, VALUE,
sizeof(int), &N, VALUE,
sizeof(PLASMA_Complex64_t), &alpha, VALUE,
sizeof(PLASMA_Complex64_t), &beta, VALUE,
sizeof(PLASMA_Complex64_t)*LDA*N, A, OUTPUT,
sizeof(int), &LDA, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlaset_quark = PCORE_zlaset_quark
#define CORE_zlaset_quark PCORE_zlaset_quark
#endif
void CORE_zlaset_quark(Quark *quark)
{
PLASMA_enum uplo;
int M;
int N;
PLASMA_Complex64_t alpha;
PLASMA_Complex64_t beta;
PLASMA_Complex64_t *A;
int LDA;
quark_unpack_args_7(quark, uplo, M, N, alpha, beta, A, LDA);
LAPACKE_zlaset_work(
LAPACK_COL_MAJOR,
lapack_const(uplo),
M, N, alpha, beta, A, LDA);
}
| {
"alphanum_fraction": 0.5422495803,
"avg_line_length": 29.2950819672,
"ext": "c",
"hexsha": "3eee9f80789329bab006f2dc6aaac05e53ebdc64",
"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_zlaset.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_zlaset.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas-qwrapper/qwrapper_zlaset.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 502,
"size": 1787
} |
/**
* Copyright (c) 2019-2020 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Imported from:
*
* @file core_blas.h
*
* PLASMA auxiliary routines
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.8.0
* @author Jakub Kurzak
* @author Hatem Ltaief
* @date 2010-11-15
*
**/
#ifndef _PLASMA_CORE_BLAS_H_
#define _PLASMA_CORE_BLAS_H_
#include "cores/dplasma_plasmatypes.h"
#include "cores/descriptor.h"
#include <cblas.h>
#include <lapacke.h>
#include "cores/core_zblas.h"
#include "cores/core_dblas.h"
#include "cores/core_cblas.h"
#include "cores/core_sblas.h"
#include "cores/core_zcblas.h"
#include "cores/core_dsblas.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Coreblas Error
*/
#define coreblas_error(k, str) fprintf(stderr, "%s: Parameter %d / %s\n", __func__, k, str);
/* CBLAS requires for scalar arguments to be passed by address rather than by value */
#ifndef CBLAS_SADDR
#define CBLAS_SADDR( _val_ ) &(_val_)
#endif
/** ****************************************************************************
* External interface of the GKK algorithm for InPlace Layout Translation
**/
int GKK_minloc(int n, int *T);
void GKK_BalanceLoad(int thrdnbr, int *Tp, int *leaders, int nleaders, int L);
int GKK_getLeaderNbr(int me, int ne, int *nleaders, int **leaders);
void CORE_pivot_update(int m, int n, int *ipiv, int *indices,
int offset, int init);
#ifdef __cplusplus
}
#endif
#endif /* _PLASMA_CORE_BLAS_H_ */
| {
"alphanum_fraction": 0.6555223881,
"avg_line_length": 26.171875,
"ext": "h",
"hexsha": "b52b461867611b12b580f506c5223640aa14e01c",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z",
"max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "therault/dplasma",
"max_forks_repo_path": "src/cores/core_blas.h",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "therault/dplasma",
"max_issues_repo_path": "src/cores/core_blas.h",
"max_line_length": 92,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "therault/dplasma",
"max_stars_repo_path": "src/cores/core_blas.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z",
"num_tokens": 453,
"size": 1675
} |
#pragma once
#include <gsl/gsl>
#include <map>
#include "halley/text/halleystring.h"
#include "halley/maths/vector4.h"
namespace Halley
{
class Path;
class Image;
struct ImageData;
class AsepriteExternalReader
{
public:
static std::vector<ImageData> importAseprite(String baseName, gsl::span<const gsl::byte> fileData, bool trim);
private:
static std::vector<ImageData> loadImagesFromPath(Path tmp, bool crop);
static std::map<int, int> getSpriteDurations(Path jsonPath);
static void processFrameData(String baseName, std::vector<ImageData>& frameData, std::map<int, int> durations);
};
class AsepriteReader
{
public:
static std::vector<ImageData> importAseprite(String baseName, gsl::span<const gsl::byte> fileData, bool trim);
};
}
| {
"alphanum_fraction": 0.75,
"avg_line_length": 25.3333333333,
"ext": "h",
"hexsha": "9af78cc8effd03a4dacee0de80924dd5eb5b6f9d",
"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": "16b6c9783e4b21377f902a9d02366c1f19450a21",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "lye/halley",
"max_forks_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21",
"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": "lye/halley",
"max_issues_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h",
"max_line_length": 113,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "lye/halley",
"max_stars_repo_path": "src/tools/tools/src/sprites/aseprite_reader.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 200,
"size": 760
} |
/* cdf/betainv.c
*
* Copyright (C) 2004 Free Software Foundation, Inc.
* Copyright (C) 2006, 2007 Brian Gough
* Written by Jason H. Stover.
* Modified for GSL by 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* Invert the Beta distribution.
*
* References:
*
* Roger W. Abernathy and Robert P. Smith. "Applying Series Expansion
* to the Inverse Beta Distribution to Find Percentiles of the
* F-Distribution," ACM Transactions on Mathematical Software, volume
* 19, number 4, December 1993, pages 474-480.
*
* G.W. Hill and A.W. Davis. "Generalized asymptotic expansions of a
* Cornish-Fisher type," Annals of Mathematical Statistics, volume 39,
* number 8, August 1968, pages 1264-1273.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_randist.h>
#include "error.h"
static double
bisect (double x, double P, double a, double b, double xtol, double Ptol)
{
double x0 = 0, x1 = 1, Px;
while (fabs(x1 - x0) > xtol) {
Px = gsl_cdf_beta_P (x, a, b);
if (fabs(Px - P) < Ptol) {
/* return as soon as approximation is good enough, including on
the first iteration */
return x;
} else if (Px < P) {
x0 = x;
} else if (Px > P) {
x1 = x;
}
x = 0.5 * (x0 + x1);
}
return x;
}
double
gsl_cdf_beta_Pinv (const double P, const double a, const double b)
{
double x, mean;
if (P < 0.0 || P > 1.0)
{
CDF_ERROR ("P must be in range 0 < P < 1", GSL_EDOM);
}
if (a < 0.0)
{
CDF_ERROR ("a < 0", GSL_EDOM);
}
if (b < 0.0)
{
CDF_ERROR ("b < 0", GSL_EDOM);
}
if (P == 0.0)
{
return 0.0;
}
if (P == 1.0)
{
return 1.0;
}
if (P > 0.5)
{
return gsl_cdf_beta_Qinv (1 - P, a, b);
}
mean = a / (a + b);
if (P < 0.1)
{
/* small x */
double lg_ab = gsl_sf_lngamma (a + b);
double lg_a = gsl_sf_lngamma (a);
double lg_b = gsl_sf_lngamma (b);
double lx = (log (a) + lg_a + lg_b - lg_ab + log (P)) / a;
if (lx <= 0) {
x = exp (lx); /* first approximation */
x *= pow (1 - x, -(b - 1) / a); /* second approximation */
} else {
x = mean;
}
if (x > mean)
x = mean;
}
else
{
/* Use expected value as first guess */
x = mean;
}
/* Do bisection to get closer */
x = bisect (x, P, a, b, 0.01, 0.01);
{
double lambda, dP, phi;
unsigned int n = 0;
start:
dP = P - gsl_cdf_beta_P (x, a, b);
phi = gsl_ran_beta_pdf (x, a, b);
if (dP == 0.0 || n++ > 64)
goto end;
lambda = dP / GSL_MAX (2 * fabs (dP / x), phi);
{
double step0 = lambda;
double step1 = -((a - 1) / x - (b - 1) / (1 - x)) * lambda * lambda / 2;
double step = step0;
if (fabs (step1) < fabs (step0))
{
step += step1;
}
else
{
/* scale back step to a reasonable size when too large */
step *= 2 * fabs (step0 / step1);
};
if (x + step > 0 && x + step < 1)
{
x += step;
}
else
{
x = sqrt (x) * sqrt (mean); /* try a new starting point */
}
if (fabs (step0) > 1e-10 * x)
goto start;
}
end:
if (fabs(dP) > GSL_SQRT_DBL_EPSILON * P)
{
GSL_ERROR_VAL("inverse failed to converge", GSL_EFAILED, GSL_NAN);
}
return x;
}
}
double
gsl_cdf_beta_Qinv (const double Q, const double a, const double b)
{
if (Q < 0.0 || Q > 1.0)
{
CDF_ERROR ("Q must be inside range 0 < Q < 1", GSL_EDOM);
}
if (a < 0.0)
{
CDF_ERROR ("a < 0", GSL_EDOM);
}
if (b < 0.0)
{
CDF_ERROR ("b < 0", GSL_EDOM);
}
if (Q == 0.0)
{
return 1.0;
}
if (Q == 1.0)
{
return 0.0;
}
if (Q > 0.5)
{
return gsl_cdf_beta_Pinv (1 - Q, a, b);
}
else
{
return 1 - gsl_cdf_beta_Pinv (Q, b, a);
};
}
| {
"alphanum_fraction": 0.5426421405,
"avg_line_length": 21.1681415929,
"ext": "c",
"hexsha": "b9efb1dad035cdd7c787be4dadb4dd31248d9109",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "skair39/structured",
"max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/cdf/betainv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "skair39/structured",
"max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/cdf/betainv.c",
"max_line_length": 78,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "parasol-ppl/PPL_utils",
"max_stars_repo_path": "folding_libs/gsl-1.14/cdf/betainv.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z",
"num_tokens": 1561,
"size": 4784
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gbpLib.h>
#include <gbpMath.h>
#include <gbpCosmo_core.h>
#include <gbpCosmo_NFW_etc.h>
#include <gsl/gsl_sf_expint.h>
double rho_NFW(double r, double M_vir, double z, int mode, cosmo_info **cosmo) {
double c_vir;
double R_vir;
double g_c;
double rho_o;
double x;
set_NFW_params(M_vir, z, mode, cosmo, &c_vir, &R_vir);
g_c = 1. / (log(1. + c_vir) - c_vir / (1. + c_vir));
rho_o = M_vir * g_c / (FOUR_PI * pow(R_vir / c_vir, 3.));
x = r * c_vir / R_vir;
return (rho_o / (x * pow(1. + x, 2.)));
}
| {
"alphanum_fraction": 0.6124794745,
"avg_line_length": 27.6818181818,
"ext": "c",
"hexsha": "1781ae38f5edf356f97571a6d10fa2078634e98e",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/rho_NFW.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/rho_NFW.c",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/rho_NFW.c",
"max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z",
"num_tokens": 235,
"size": 609
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2020-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#pragma once
#include <folly/lang/Assume.h>
#include <gsl/gsl-lite.hpp>
#include <array>
#include <ratio>
#include <string>
#include <string_view>
namespace cb::stats {
// Enum of the relevant base units used by convention in Prometheus
enum class BaseUnit {
None, // used for text stats where units aren't relevant
Count, // Generic count which does not meet a better unit
Seconds,
Bytes,
Ratio,
};
/**
* Type representing a unit (kilobytes, microseconds etc.).
* This is encoded as a BaseUnit (see above) and a scaling factor stored as
* two integers (see std::ratio).
*
* Thus,
* kilobytes -> bytes, 1000/1
* microseconds -> seconds, 1/1000000
*
* Given a numerical value in this unit, the scaling factor indicates
* how to convert the value back to the base unit.
*
* 10 kilobytes
* 10 * 1000 / 1
* -> 10000 bytes
*
* This can be performed using the toBaseUnit method -
*
* Unit(std::kilo{}, BaseUnit::Bytes).toBaseUnit(10) == 10000
*
* Units will usually be used through the constexpr values
* in namespace units
*
* units::kilobytes.toBaseUnit(10) == 10000
*/
class Unit {
public:
explicit constexpr Unit(BaseUnit baseUnit)
: Unit(std::ratio<1>{}, baseUnit) {
}
template <class RatioType>
constexpr Unit(RatioType ratio, BaseUnit baseUnit)
: numerator(gsl::narrow_cast<int64_t>(RatioType::num)),
denominator(gsl::narrow_cast<int64_t>(RatioType::den)),
baseUnit(baseUnit) {
}
/**
* Scale a value of the current unit (e.g., milliseconds) to the base
* unit (e.g., seconds).
*/
[[nodiscard]] constexpr double toBaseUnit(double value) const {
return (value * numerator) / denominator;
}
[[nodiscard]] std::string_view getSuffix() const {
using namespace std::string_view_literals;
switch (baseUnit) {
case BaseUnit::None:
case BaseUnit::Count:
return ""sv;
case BaseUnit::Seconds:
return "_seconds"sv;
case BaseUnit::Bytes:
return "_bytes"sv;
case BaseUnit::Ratio:
return "_ratio"sv;
}
folly::assume_unreachable();
}
private:
int64_t numerator;
int64_t denominator;
BaseUnit baseUnit;
};
namespace units {
constexpr Unit none{std::ratio<1>{}, BaseUnit::None};
constexpr Unit count{std::ratio<1>{}, BaseUnit::Count};
// floating point between 0 and 1, this is already in the correct base unit
constexpr Unit ratio{std::ratio<1>{}, BaseUnit::Ratio};
// percents should be scaled down to ratios for Prometheus
constexpr Unit percent{std::ratio<1, 100>{}, BaseUnit::Ratio};
// time units
constexpr Unit nanoseconds{std::nano{}, BaseUnit::Seconds};
constexpr Unit microseconds{std::micro{}, BaseUnit::Seconds};
constexpr Unit milliseconds{std::milli{}, BaseUnit::Seconds};
constexpr Unit seconds{std::ratio<1>{}, BaseUnit::Seconds};
constexpr Unit minutes{std::ratio<60>{}, BaseUnit::Seconds};
constexpr Unit hours{std::ratio<60 * 60>{}, BaseUnit::Seconds};
constexpr Unit days{std::ratio<60 * 60 * 24>{}, BaseUnit::Seconds};
// Note: std ratio definitions are powers of 10, not 2
// e.g., kilo = std::ratio<1000, 1>
// so 1 kilobyte = 1000 bytes
// if powers of 2 are explicitly needed, IEC prefixes
// (kibi, gibi, tebi) could easily be defined.
// byte units
constexpr Unit bits{std::ratio<1, 8>{}, BaseUnit::Bytes};
constexpr Unit bytes{std::ratio<1>{}, BaseUnit::Bytes};
constexpr Unit kilobytes{std::kilo{}, BaseUnit::Bytes};
constexpr Unit megabytes{std::mega{}, BaseUnit::Bytes};
constexpr Unit gigabytes{std::giga{}, BaseUnit::Bytes};
} // namespace units
} // namespace cb::stats | {
"alphanum_fraction": 0.6710526316,
"avg_line_length": 31.4285714286,
"ext": "h",
"hexsha": "316c1df8278744e1dedf015ef57dc07e0433b871",
"lang": "C",
"max_forks_count": 71,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z",
"max_forks_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd",
"max_forks_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_forks_repo_name": "nawazish-couchbase/kv_engine",
"max_forks_repo_path": "include/statistics/units.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd",
"max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z",
"max_issues_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_issues_repo_name": "nawazish-couchbase/kv_engine",
"max_issues_repo_path": "include/statistics/units.h",
"max_line_length": 79,
"max_stars_count": 104,
"max_stars_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd",
"max_stars_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_stars_repo_name": "nawazish-couchbase/kv_engine",
"max_stars_repo_path": "include/statistics/units.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z",
"num_tokens": 1093,
"size": 4180
} |
/*
* 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 painterport_eca0917d_5109_4de2_ae6f_18d5c163d02c_h
#define painterport_eca0917d_5109_4de2_ae6f_18d5c163d02c_h
#include <gslib/rtree.h>
#include <ariel/painter.h>
__ariel_begin__
class painter_obj;
typedef rtree_entity<painter_obj*> painter_obj_entity;
typedef rtree_node<painter_obj_entity> painter_obj_node;
typedef _tree_allocator<painter_obj_node> painter_obj_alloc;
typedef tree<painter_obj_entity, painter_obj_node, painter_obj_alloc> painter_obj_tree;
typedef rtree<painter_obj_entity, quadratic_split_alg<25, 10, painter_obj_tree>, painter_obj_node, painter_obj_alloc> painter_obj_rtree;
typedef vector<painter_obj*> painter_objs;
class __gs_novtable painter_obj abstract
{
public:
enum type
{
po_line,
po_rect,
po_path,
po_text,
};
public:
painter_obj(const painter_context& ctx): _ctx(ctx) {}
virtual ~painter_obj() {}
virtual type get_type() const = 0;
virtual rectf& get_rect(rectf& rc) const = 0;
protected:
painter_context _ctx;
public:
const painter_context& get_context() const { return _ctx; }
};
class painter_line_obj:
public painter_obj
{
public:
painter_line_obj(const painter_context& ctx, const pointf& p1, const pointf& p2): painter_obj(ctx), _p1(p1), _p2(p2) {}
virtual type get_type() const override { return po_line; }
virtual rectf& get_rect(rectf& rc) const override;
private:
pointf _p1;
pointf _p2;
};
class painter_rect_obj:
public painter_obj
{
public:
painter_rect_obj(const painter_context& ctx, const rectf& rc): painter_obj(ctx), _rc(rc) {}
virtual type get_type() const override { return po_rect; }
virtual rectf& get_rect(rectf& rc) const override { return rc = _rc; }
private:
rectf _rc;
};
class painter_path_obj:
public painter_obj
{
public:
painter_path_obj(const painter_context& ctx, painter_path& take_me): painter_obj(ctx) { _path.swap(take_me); }
painter_path_obj(const painter_context& ctx, const painter_path& path): painter_obj(ctx), _path(path) {}
virtual type get_type() const override { return po_path; }
virtual rectf& get_rect(rectf& rc) const override;
rectf& rebuild_rect(rectf& rc) const;
private:
painter_path _path;
mutable bool _rc_valid = false;
mutable rectf _rc;
};
class painter_text_obj:
public painter_obj
{
public:
painter_text_obj(const painter_context& ctx, const string& txt, const pointf& p, const color& cr): painter_obj(ctx), _text(txt), _pos(p), _cr(cr) {}
virtual type get_type() const override { return po_text; }
virtual rectf& get_rect(rectf& rc) const override;
private:
string _text;
pointf _pos;
color _cr;
};
class painterport:
public painter
{
public:
virtual ~painterport();
virtual void resize(int w, int h) override {}
virtual void draw_path(const painter_path& path) override;
virtual void draw_line(const vec2& p1, const vec2& p2) override;
virtual void draw_rect(const rectf& rc) override;
virtual void draw_text(const gchar* str, float x, float y, const color& cr, int length) override;
virtual void on_draw_begin() override;
protected:
painter_obj_rtree _rtree;
public:
rectf& get_area_rect(rectf& rc) const;
void query_objs(painter_objs& objs, const rectf& rc);
protected:
void add_obj(painter_obj* obj);
void clear_objs();
};
__ariel_end__
#endif
| {
"alphanum_fraction": 0.7161964472,
"avg_line_length": 31.6887417219,
"ext": "h",
"hexsha": "06131fc0dd7dce0581f1bf427d60a0bc20103a16",
"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/painterport.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/painterport.h",
"max_line_length": 152,
"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/painterport.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": 1181,
"size": 4785
} |
#include <ceed.h>
#include <petsc.h>
#include "../problems/mooney-rivlin.h"
// Build libCEED context object
PetscErrorCode PhysicsContext_MR(MPI_Comm comm, Ceed ceed, Units *units,
CeedQFunctionContext *ctx) {
PetscErrorCode ierr;
Physics_MR phys;
PetscFunctionBegin;
ierr = PetscMalloc1(1, units); CHKERRQ(ierr);
ierr = PetscMalloc1(1, &phys); CHKERRQ(ierr);
ierr = ProcessPhysics_MR(comm, phys, *units); CHKERRQ(ierr);
CeedQFunctionContextCreate(ceed, ctx);
CeedQFunctionContextSetData(*ctx, CEED_MEM_HOST, CEED_COPY_VALUES,
sizeof(*phys), phys);
ierr = PetscFree(phys); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// Build libCEED smoother context object
PetscErrorCode PhysicsSmootherContext_MR(MPI_Comm comm, Ceed ceed,
CeedQFunctionContext ctx, CeedQFunctionContext *ctx_smoother) {
PetscErrorCode ierr;
PetscScalar nu_smoother = 0;
PetscBool nu_flag = PETSC_FALSE;
Physics_MR phys, phys_smoother;
PetscFunctionBegin;
ierr = PetscOptionsBegin(comm, NULL,
"Mooney Rivlin physical parameters for smoother", NULL);
CHKERRQ(ierr);
ierr = PetscOptionsScalar("-nu_smoother", "Poisson's ratio for smoother",
NULL, nu_smoother, &nu_smoother, &nu_flag);
CHKERRQ(ierr);
if (nu_smoother < 0 ||
nu_smoother >= 0.5) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP,
"Mooney-Rivlin model requires Poisson ratio -nu option in [0, .5)");
ierr = PetscOptionsEnd(); CHKERRQ(ierr); // End of setting Physics
if (nu_flag) {
// Copy context
CeedQFunctionContextGetData(ctx, CEED_MEM_HOST, &phys);
ierr = PetscMalloc1(1, &phys_smoother); CHKERRQ(ierr);
ierr = PetscMemcpy(phys_smoother, phys, sizeof(*phys)); CHKERRQ(ierr);
CeedQFunctionContextRestoreData(ctx, &phys);
// Create smoother context
CeedQFunctionContextCreate(ceed, ctx_smoother);
phys_smoother->lambda = 2 * (phys_smoother->mu_1 + phys_smoother->mu_2) *
nu_smoother / (1 - 2*nu_smoother);
CeedQFunctionContextSetData(*ctx_smoother, CEED_MEM_HOST, CEED_COPY_VALUES,
sizeof(*phys_smoother), phys_smoother);
ierr = PetscFree(phys_smoother); CHKERRQ(ierr);
} else {
*ctx_smoother = NULL;
}
PetscFunctionReturn(0);
}
// Process physics options - Mooney-Rivlin
PetscErrorCode ProcessPhysics_MR(MPI_Comm comm, Physics_MR phys, Units units) {
PetscErrorCode ierr;
PetscReal nu = -1;
phys->mu_1 = -1;
phys->mu_2 = -1;
phys->lambda = -1;
units->meter = 1; // 1 meter in scaled length units
units->second = 1; // 1 second in scaled time units
units->kilogram = 1; // 1 kilogram in scaled mass units
PetscFunctionBeginUser;
ierr = PetscOptionsBegin(comm, NULL, "Mooney Rivlin physical parameters", NULL);
CHKERRQ(ierr);
ierr = PetscOptionsScalar("-mu_1", "Material Property mu_1", NULL,
phys->mu_1, &phys->mu_1, NULL); CHKERRQ(ierr);
if (phys->mu_1 < 0) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP,
"Mooney-Rivlin model requires non-negative -mu_1 option (Pa)");
ierr = PetscOptionsScalar("-mu_2", "Material Property mu_2", NULL,
phys->mu_2, &phys->mu_2, NULL); CHKERRQ(ierr);
if (phys->mu_2 < 0) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP,
"Mooney-Rivlin model requires non-negative -mu_2 option (Pa)");
ierr = PetscOptionsScalar("-nu", "Poisson ratio", NULL,
nu, &nu, NULL); CHKERRQ(ierr);
if (nu < 0 || nu >= 0.5) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP,
"Mooney-Rivlin model requires Poisson ratio -nu option in [0, .5)");
phys->lambda = 2 * (phys->mu_1 + phys->mu_2) * nu / (1 - 2*nu);
ierr = PetscOptionsScalar("-units_meter", "1 meter in scaled length units",
NULL, units->meter, &units->meter, NULL);
CHKERRQ(ierr);
units->meter = fabs(units->meter);
ierr = PetscOptionsScalar("-units_second", "1 second in scaled time units",
NULL, units->second, &units->second, NULL);
CHKERRQ(ierr);
units->second = fabs(units->second);
ierr = PetscOptionsScalar("-units_kilogram", "1 kilogram in scaled mass units",
NULL, units->kilogram, &units->kilogram, NULL);
CHKERRQ(ierr);
units->kilogram = fabs(units->kilogram);
ierr = PetscOptionsEnd(); CHKERRQ(ierr); // End of setting Physics
// Define derived units
units->Pascal = units->kilogram / (units->meter * PetscSqr(units->second));
// Scale material parameters based on units of Pa
phys->mu_1 *= units->Pascal;
phys->mu_2 *= units->Pascal;
phys->lambda *= units->Pascal;
PetscFunctionReturn(0);
}; | {
"alphanum_fraction": 0.6410677618,
"avg_line_length": 38.96,
"ext": "c",
"hexsha": "a9c44b5b0d145180422a316482dfdcf98e61995b",
"lang": "C",
"max_forks_count": 41,
"max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z",
"max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "AdelekeBankole/libCEED",
"max_forks_repo_path": "examples/solids/problems/mooney-rivlin.c",
"max_issues_count": 781,
"max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "AdelekeBankole/libCEED",
"max_issues_repo_path": "examples/solids/problems/mooney-rivlin.c",
"max_line_length": 105,
"max_stars_count": 123,
"max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "AdelekeBankole/libCEED",
"max_stars_repo_path": "examples/solids/problems/mooney-rivlin.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z",
"num_tokens": 1326,
"size": 4870
} |
/* altHtmlPages.c - Program to create a web based browser
of altsplice predicitions. */
#include "common.h"
#include "bed.h"
#include "hash.h"
#include "options.h"
#include "chromKeeper.h"
#include "binRange.h"
#include "obscure.h"
#include "linefile.h"
#include "dystring.h"
#include "altGraphX.h"
#include "altSpliceSite.h"
#include "hdb.h"
#include "dnaseq.h"
#include <gsl/gsl_math.h>
#include <gsl/gsl_statistics_double.h>
struct junctSet
/* A set of beds with a common start or end. */
{
struct junctSet *next; /* Next in list. */
char *chrom; /* Chromosome. */
int chromStart; /* Smallest start. */
int chromEnd; /* Largest end. */
char *name; /* Name of junction. */
int junctCount; /* Number of junctions in set. */
char strand[2]; /* + or - depending on which strand. */
int genePSetCount; /* Number of gene probe sets. */
char **genePSets; /* Gene probe set name. */
char *hName; /* Human name for locus or affy id if not present. */
int maxJunctCount; /* Maximum size of bedArray. */
char **junctPSets; /* Beds in the cluster. */
int junctDupCount; /* Number of redundant junctions in set. */
int maxJunctDupCount; /* Maximum size of bedDupArray. */
char **dupJunctPSets; /* Redundant beds in the cluster. */
int junctUsedCount; /* Number of juction sets used. */
char **junctUsed; /* Names of actual junction probe sets used. */
boolean cassette; /* Is cassette exon set? */
char *exonPsName; /* Cassette exon probe set if available. */
double **junctProbs; /* Matrix of junction probabilities, rows are junctUsed. */
double **geneProbs; /* Matrix of gene set probabilities, rows are genePSets. */
double *exonPsProbs; /* Exon probe set probabilities if cassette. */
double **junctIntens; /* Matrix of junction intensities, rows are junctUsed. */
double **geneIntens; /* Matrix of gene set intensities, rows are genePSets. */
double *exonPsIntens; /* Exon probe set intensities if cassette. */
boolean expressed; /* TRUE if one form of this junction set is expressed. */
boolean altExpressed; /* TRUE if more than one form of this junction set is expressed. */
double score; /* Score of being expressed overall. */
double exonCorr; /* Correlation of exon probe set with include junction if appropriate. */
double exonSkipCorr; /* Correlation of exon probe set with skip junction if appropriate. */
double probCorr; /* Correlation of exon probe set prob and include probs. */
double probSkipCorr; /* Correlation of exon probe set prob skip junction if appropriate. */
double exonSjPercent; /* Percentage of includes confirmed by exon probe set. */
double sjExonPercent; /* Percentage of exons confirmed by sj probe set. */
int exonAgree; /* Number of times exon agrees with matched splice junction */
int exonDisagree; /* Number of times exon disagrees with matched splice junction. */
int sjAgree; /* Number of times sj agrees with matched exon */
int sjDisagree; /* Number of times sj disagrees with matched exon. */
int sjExp; /* Number of times sj expressed. */
int exonExp; /* Number of times exon expressed. */
int spliceType; /* Type of splicing event. */
};
struct resultM
/* Wrapper for a matrix of results. */
{
struct hash *nameIndex; /* Hash with integer index for each row name. */
int colCount; /* Number of columns in matrix. */
char **colNames; /* Column Names for matrix. */
int rowCount; /* Number of rows in matrix. */
char **rowNames; /* Row names for matrix. */
double **matrix; /* The actual data for the resultM. */
};
struct altCounts
{
char *gene; /*Name of gene. */
int count; /* Number of alternative sites possible. */
int jsExpressed; /* Number of alternative sites where one isoform expressed. */
int jsAltExpressed; /* Number of alternative sites that are alternatively expressed. */
};
static struct optionSpec optionSpecs[] =
/* Our acceptable options to be called with. */
{
{"help", OPTION_BOOLEAN},
{"junctFile", OPTION_STRING},
{"probFile", OPTION_STRING},
{"intensityFile", OPTION_STRING},
{"bedFile", OPTION_STRING},
{"sortByExonCorr", OPTION_BOOLEAN},
{"sortByExonPercent", OPTION_BOOLEAN},
{"htmlPrefix", OPTION_STRING},
{"hybeFile", OPTION_STRING},
{"presThresh", OPTION_FLOAT},
{"absThresh", OPTION_FLOAT},
{"strictDisagree", OPTION_BOOLEAN},
{"exonStats", OPTION_STRING},
{"spreadSheet", OPTION_STRING},
{"doSjRatios", OPTION_BOOLEAN},
{"log2Ratio", OPTION_BOOLEAN},
{"ratioFile", OPTION_STRING},
{"junctPsMap", OPTION_STRING},
{"agxFile", OPTION_STRING},
{"db", OPTION_STRING},
{"spliceTypes", OPTION_STRING},
{"tissueSpecific", OPTION_STRING},
{"outputDna", OPTION_STRING},
{"cassetteBed", OPTION_STRING},
{"geneStats", OPTION_STRING},
{"tissueExpThresh", OPTION_INT},
{"geneJsStats", OPTION_STRING},
{"brainSpecific", OPTION_STRING},
{NULL, 0}
};
static char *optionDescripts[] =
/* Description of our options for usage summary. */
{
"Display this message.",
"File containing junctionSets from plotAndCountAltsMultGs.R log.",
"File containing summarized probability of expression for each probe set.",
"File containing expression values for each probe set.",
"File containing beds for each probe set.",
"Flag to sort by exon correlation when present.",
"Flag to sort by exon percent agreement with splice junction when present.",
"Prefix for html files, i.e. <prefix>lists.html and <prefix>frame.html",
"File giving names and ids for hybridizations.",
"Optional threshold at which to call expressed.",
"Optional threshold at which to call not expressed.",
"Call disagreements only if below absense threshold instead of below present thresh.",
"File to output confirming exon stats to.",
"File to output spreadsheet format picks to.",
"[optional] Calculate ratios of sj to other sj in same junction set.",
"[optional] Transform ratios with log base 2.",
"[optional] File to store sjRatios in.",
"[optional] Print out the probe sets in a junction set and quit.",
"[optional] File with graphs to determine types.",
"[optional] Database that graphs are from.",
"[optional] Try to determine types of splicing in junction sets.",
"[optional] Output tissues specific isoforms to file specified.",
"[optional] Output dna associated with a junction to this file.",
"[optional] Output splice sites for cassette exons.",
"[optional] Output stats about genes, junctions expressed, junctions alt to file name.",
"[optional] Number of tissues that must express a probe set before considred expressed.",
"[optional] Print out junction sets per gene stats.",
"[optional] Output brain specific isoforms to file specified.",
};
int tissueExpThresh = 0; /* Number of tissues that must express probe set. */
double presThresh = 0; /* Probability above which we consider
* something expressed. */
double absThresh = 0; /* Probability below which we consider
* something not expressed. */
double disagreeThresh = 0; /* Probability below which we consider
* something to disagree. */
FILE *exonPsStats = NULL; /* File to output exon probe set
confirmation stats into. */
FILE *geneCounts = NULL; /* Print out the gene junction counts. */
boolean doJunctionTypes = FALSE; /* Should we try to determine what type of splice type is out there? */
FILE *bedJunctTypeOut = NULL; /* File to write out bed types to. */
struct hash *junctBedHash = NULL;
FILE *cassetteBedOut = NULL; /* File to write cassette bed records to. */
/* Counts of different alternative splicing
events. */
int alt3Count = 0;
int alt3SoftCount = 0;
int alt5Count = 0;
int alt5SoftCount = 0;
int altCassetteCount = 0;
int otherCount = 0;
/* Counts of different alternative splicing
events that are expressed. */
int alt3ExpCount = 0;
int alt3SoftExpCount = 0;
int alt5ExpCount = 0;
int alt5SoftExpCount = 0;
int altCassetteExpCount = 0;
int otherExpCount = 0;
/* Counts of different alternative splicing
events that are expressed. */
int alt3ExpAltCount = 0;
int alt3SoftExpAltCount = 0;
int alt5ExpAltCount = 0;
int alt5SoftExpAltCount = 0;
int altCassetteExpAltCount = 0;
int otherExpAltCount = 0;
int noDna = 0;
int withDna = 0;
void usage()
/** Print usage and quit. */
{
int i=0;
warn("altHtmlPages - Program to create a web based browser\n"
"of altsplice predicitions. Now extended to do some intitial\n"
"analysis as well.\n"
"options are:");
for(i=0; i<ArraySize(optionSpecs) -1; i++)
fprintf(stderr, " -%s -- %s\n", optionSpecs[i].name, optionDescripts[i]);
errAbort("\nusage:\n ");
}
void printJunctSetProbes(struct junctSet *jsList)
/* Print out a mapping from junctionSets to probe sets. */
{
char *fileName = optionVal("junctPsMap",NULL);
FILE *out = NULL;
int i = 0;
struct junctSet *js = NULL;
assert(fileName);
out = mustOpen(fileName, "w");
for(js = jsList; js != NULL; js = js->next)
{
for(i = 0; i < js->maxJunctCount; i++)
fprintf(out, "%s\t%s\n", js->name, js->junctPSets[i]);
for(i = 0; i < js->junctDupCount; i++)
fprintf(out, "%s\t%s\n", js->name, js->dupJunctPSets[i]);
for(i = 0; i < js->genePSetCount; i++)
fprintf(out, "%s\t%s\n", js->name, js->genePSets[i]);
}
carefulClose(&out);
}
struct resultM *readResultMatrix(char *fileName)
/* Read in an R style result table. */
{
struct lineFile *lf = lineFileOpen(fileName, TRUE);
struct resultM *rM = NULL;
char **words = NULL;
int colCount=0, i=0;
char *line = NULL;
double **M = NULL;
int rowCount =0;
int rowMax = 1000;
char **rowNames = NULL;
char **colNames = NULL;
struct hash *iHash = newHash(12);
char buff[256];
char *tmp;
/* Get the headers. */
lineFileNextReal(lf, &line);
while(line[0] == '\t')
line++;
colCount = chopString(line, "\t", NULL, 0);
AllocArray(colNames, colCount);
AllocArray(words, colCount+1);
AllocArray(rowNames, rowMax);
AllocArray(M, rowMax);
tmp = cloneString(line);
chopByChar(tmp, '\t', colNames, colCount);
while(lineFileNextRow(lf, words, colCount+1))
{
if(rowCount+1 >=rowMax)
{
ExpandArray(rowNames, rowMax, 2*rowMax);
ExpandArray(M, rowMax, 2*rowMax);
rowMax = rowMax*2;
}
safef(buff, sizeof(buff), "%s", words[0]);
tmp=strchr(buff,':');
if(tmp != NULL)
{
assert(tmp);
tmp=strchr(tmp+1,':');
assert(tmp);
tmp[0]='\0';
}
hashAddInt(iHash, buff, rowCount);
rowNames[rowCount] = cloneString(words[0]);
AllocArray(M[rowCount], colCount);
for(i=1; i<=colCount; i++) /* Starting at 1 here as name is 0. */
{
M[rowCount][i-1] = atof(words[i]);
}
rowCount++;
}
AllocVar(rM);
rM->nameIndex = iHash;
rM->colCount = colCount;
rM->colNames = colNames;
rM->rowCount = rowCount;
rM->rowNames = rowNames;
rM->matrix = M;
return rM;
}
struct junctSet *junctSetLoad(char *row[], int colCount)
/* Load up a junct set. */
{
struct junctSet *js = NULL;
int index = 1;
int count = 0;
AllocVar(js);
if(colCount > 14)
index = 1;
else
index = 0;
js->chrom = cloneString(row[index++]);
js->chromStart = sqlUnsigned(row[index++]);
js->chromEnd = sqlUnsigned(row[index++]);
js->name = cloneString(row[index++]);
js->junctCount = js->maxJunctDupCount = sqlUnsigned(row[index++]);
js->strand[0] = row[index++][0];
js->genePSetCount = sqlUnsigned(row[index++]);
sqlStringDynamicArray(row[index++], &js->genePSets, &count);
js->hName = cloneString(row[index++]);
sqlStringDynamicArray(row[index++], &js->junctPSets, &js->maxJunctCount);
js->junctDupCount = sqlUnsigned(row[index++]);
sqlStringDynamicArray(row[index++], &js->dupJunctPSets, &count);
js->cassette = atoi(row[index++]);
js->exonPsName = cloneString(row[index++]);
if(colCount != 14) /* If the junctions used fields not present fill them in later. */
{
js->junctUsedCount = sqlUnsigned(row[index++]);
sqlStringDynamicArray(row[index++], &js->junctUsed, &count);
}
js->spliceType = altOther;
return js;
}
struct junctSet *junctSetLoadAll(char *fileName)
/* Load all of the junct sets out of a fileName. */
{
struct junctSet *list = NULL, *el = NULL;
struct lineFile *lf = lineFileOpen(fileName, TRUE);
int numFields = 0;
char *line = NULL;
char **row = NULL;
lineFileNextReal(lf, &line);
numFields = chopByWhite(line, NULL, 0);
assert(numFields);
lineFileReuse(lf);
AllocArray(row, numFields);
while(lineFileNextRowTab(lf, row, numFields))
{
el = junctSetLoad(row, numFields);
slAddHead(&list, el);
}
lineFileClose(&lf);
slReverse(&lf);
return list;
}
void fillInProbs(struct junctSet *jsList, struct resultM *probM)
/* Fill in the probability of expression for each junctSet's junction
and gene probe sets. */
{
struct junctSet *js = NULL;
int i = 0, j = 0;
for(js = jsList; js != NULL; js = js->next)
{
/* Allocate junction probability matrix arrays. */
AllocArray(js->junctProbs, js->junctUsedCount);
for(i = 0; i < js->junctUsedCount; i++)
AllocArray(js->junctProbs[i], probM->colCount);
/* Fill in the values. */
for(i = 0; i < js->junctUsedCount; i++)
{
int row = hashIntValDefault(probM->nameIndex, js->junctUsed[i], -1);
if(row != -1)
{
for(j = 0; j < probM->colCount; j++)
js->junctProbs[i][j] = probM->matrix[row][j];
}
else
{
for(j = 0; j < probM->colCount; j++)
js->junctProbs[i][j] = -1;
}
}
/* Allocate memory for gene sets. */
AllocArray(js->geneProbs, js->genePSetCount);
for(i = 0; i < js->genePSetCount; i++)
AllocArray(js->geneProbs[i], probM->colCount);
/* Fill in the values. */
for(i = 0; i < js->genePSetCount; i++)
{
int row = hashIntValDefault(probM->nameIndex, js->genePSets[i], -1);
if(row != -1)
{
for(j = 0; j < probM->colCount; j++)
js->geneProbs[i][j] = probM->matrix[row][j];
}
else
{
for(j = 0; j < probM->colCount; j++)
js->geneProbs[i][j] = -1;
}
}
/* Allocate the cassette exon probabilities if present. */
if(js->cassette && differentWord(js->exonPsName, "NA"))
{
int row = hashIntValDefault(probM->nameIndex, js->exonPsName, -1);
if(row != -1)
{
AllocArray(js->exonPsProbs, probM->colCount);
for(j = 0; j < probM->colCount; j++)
js->exonPsProbs[j] = probM->matrix[row][j];
}
}
}
}
void fillInIntens(struct junctSet *jsList, struct resultM *intenM)
/* Fill in the intenability of expression for each junctSet's junction
and gene probe sets. */
{
struct junctSet *js = NULL;
int i = 0, j = 0;
for(js = jsList; js != NULL; js = js->next)
{
/* Allocate junction intenability matrix arrays. */
AllocArray(js->junctIntens, js->junctUsedCount);
for(i = 0; i < js->junctUsedCount; i++)
AllocArray(js->junctIntens[i], intenM->colCount);
/* Fill in the values. */
for(i = 0; i < js->junctUsedCount; i++)
{
int row = hashIntValDefault(intenM->nameIndex, js->junctUsed[i], -1);
if(row != -1)
{
for(j = 0; j < intenM->colCount; j++)
js->junctIntens[i][j] = intenM->matrix[row][j];
}
else
{
for(j = 0; j < intenM->colCount; j++)
js->junctIntens[i][j] = -1;
}
}
/* Allocate memory for gene sets. */
AllocArray(js->geneIntens, js->genePSetCount);
for(i = 0; i < js->genePSetCount; i++)
AllocArray(js->geneIntens[i], intenM->colCount);
/* Fill in the values. */
for(i = 0; i < js->genePSetCount; i++)
{
int row = hashIntValDefault(intenM->nameIndex, js->genePSets[i], -1);
if(row != -1)
{
for(j = 0; j < intenM->colCount; j++)
js->geneIntens[i][j] = intenM->matrix[row][j];
}
else
{
for(j = 0; j < intenM->colCount; j++)
js->geneIntens[i][j] = -1;
}
}
/* Allocate the cassette exon intenabilities if present. */
if(js->cassette && differentWord(js->exonPsName, "NA"))
{
int row = hashIntValDefault(intenM->nameIndex, js->exonPsName, -1);
if(row != -1)
{
AllocArray(js->exonPsIntens, intenM->colCount);
for(j = 0; j < intenM->colCount; j++)
js->exonPsIntens[j] = intenM->matrix[row][j];
}
}
}
}
double covariance(double *X, double *Y, int count)
/* Compute the covariance for two vectors.
cov(X,Y) = E[XY] - E[X]E[Y]
page 326 Sheldon Ross "A First Course in Probability" 1998
*/
{
double cov = gsl_stats_covariance(X, 1, Y, 1, count);
return cov;
}
double correlation(double *X, double *Y, int count)
/* Compute the correlation between X and Y
correlation(X,Y) = cov(X,Y)/ squareRt(var(X)var(Y))
page 332 Sheldon Ross "A First Course in Probability" 1998
*/
{
double varX = gsl_stats_variance(X, 1, count);
double varY = gsl_stats_variance(Y, 1, count);
double covXY = gsl_stats_covariance(X, 1, Y, 1, count);
double correlation = covXY / sqrt(varX *varY);
return correlation;
}
double calcMinCorrelation(struct junctSet *js, int *expressed, int tissueCount, int colCount)
/* Loop through all combinations of junction sets that are expressed
and calculate the minimum correlation between the two in tissues
if they are expressed in at least 1. */
{
double minCorr = 2; /* Correlation always <= 1, 2 is a good max. */
double corr = 0;
int i = 0, j = 0;
for(i = 0; i < js->junctUsedCount; i++)
{
/* If there isn't any expression for this junction don't bother. */
if(expressed[i] == 0)
continue;
for(j = 0; j < js->junctUsedCount; j++)
{
/* Corralation when i == j is 1, don't bother. */
if(i == j)
continue;
/* If there isn't any expression for this junction don't bother. */
if(expressed[j] == 0)
continue;
/* Calculate correlation. */
corr = correlation(js->junctIntens[i], js->junctIntens[j], colCount);
if(minCorr > corr)
minCorr = corr;
}
}
return minCorr;
}
int includeJsIx(struct junctSet *js, struct hash *bedHash)
/* Return the index of the include junction for a cassette exon. */
{
int includeIx = 0;
struct bed *bed1 = NULL, *bed2 = NULL;
assert(js->cassette);
if(js->junctUsedCount < 2)
return 0;
bed1 = hashMustFindVal(bedHash, js->junctUsed[0]);
bed2 = hashMustFindVal(bedHash, js->junctUsed[1]);
if(bed1->chromEnd - bed1->chromStart > bed2->chromEnd - bed2->chromStart)
includeIx = 1;
else
includeIx = 0;
return includeIx;
}
int skipJsIx(struct junctSet *js, struct hash *bedHash)
/* Return the index of the skip junction for a cassette exon. */
{
int skipIx = 0;
struct bed *bed1 = NULL, *bed2 = NULL;
assert(js->cassette);
if(js->junctUsedCount < 2)
return 0;
bed1 = hashMustFindVal(bedHash, js->junctUsed[0]);
bed2 = hashMustFindVal(bedHash, js->junctUsed[1]);
if(bed1->chromEnd - bed1->chromStart > bed2->chromEnd - bed2->chromStart)
skipIx = 0;
else
skipIx = 1;
return skipIx;
}
boolean geneExpressed(struct junctSet *js, int colIx)
/* Is the gene at junctIx expressed above the
threshold in colIx? */
{
int i = 0;
for(i = 0; i < js->genePSetCount; i++)
{
if(js->geneProbs[i][colIx] >= presThresh)
return TRUE;
}
return FALSE;
}
boolean junctionExpressed(struct junctSet *js, int colIx, int junctIx)
/* Is the junction at junctIx expressed above the
thresnhold in colIx? */
{
boolean geneExp = FALSE;
boolean junctExp = FALSE;
int i = 0;
geneExp = geneExpressed(js, colIx);
if(geneExp && js->junctProbs[junctIx][colIx] >= presThresh)
junctExp = TRUE;
return junctExp;
}
boolean exonExpressed(struct junctSet *js, int colIx)
/* Is the junction at junctIx expressed above the
threshold in colIx? */
{
boolean geneExp = FALSE;
boolean exonExp = FALSE;
int i = 0;
for(i = 0; i < js->genePSetCount; i++)
{
if(js->geneProbs[i][colIx] >= presThresh)
geneExp = TRUE;
}
if(geneExp && js->exonPsProbs[colIx] >= presThresh)
exonExp = TRUE;
return exonExp;
}
double calcExonPercent(struct junctSet *js, struct hash *bedHash, struct resultM *probM)
/* Calculate how often the exon probe set is called expressed
when probe set is. */
{
int includeIx = includeJsIx(js, bedHash);
int both = 0;
int jsOnly = 0;
double percent = 0;
int i = 0;
for(i = 0; i < probM->colCount; i++)
{
if(junctionExpressed(js, i, includeIx) &&
js->exonPsProbs[i] >= presThresh)
{
both++;
jsOnly++;
js->exonAgree++;
}
else if(junctionExpressed(js, i, includeIx) &&
js->exonPsProbs[i] < disagreeThresh)
{
js->exonDisagree++;
jsOnly++;
}
}
if(jsOnly > 0)
percent = (double)both/jsOnly;
else
percent = -1;
return percent;
}
double calcSjPercent(struct junctSet *js, struct hash *bedHash, struct resultM *probM)
/* Calculate how often the sj probe set is called expressed
when exon probe set is. */
{
int includeIx = includeJsIx(js, bedHash);
int both = 0;
int exonOnly = 0;
double percent = 0;
int i = 0;
for(i = 0; i < probM->colCount; i++)
{
if(junctionExpressed(js, i, includeIx) &&
js->exonPsProbs[i] >= presThresh)
{
both++;
exonOnly++;
js->sjAgree++;
}
else if(exonExpressed(js, i) &&
js->junctProbs[includeIx][i] < disagreeThresh)
{
exonOnly++;
js->sjDisagree++;
}
}
if(exonOnly > 0)
percent = (double)both/exonOnly;
else
percent = -1;
return percent;
}
double calcExonSjCorrelation(struct junctSet *js, struct hash *bedHash, struct resultM *intenM)
/* Calcualate the correltation between the exon probe
set and the appropriate splice junction set. */
{
double corr = -2;
int includeIx = includeJsIx(js, bedHash);
corr = correlation(js->junctIntens[includeIx], js->exonPsIntens, intenM->colCount);
return corr;
}
double calcExonSjSkipCorrelation(struct junctSet *js, struct hash *bedHash, struct resultM *intenM)
/* Calcualate the correltation between the exon probe
set and the appropriate skip splice junction set. */
{
double corr = -2;
int skipIx = skipJsIx(js, bedHash);
corr = correlation(js->junctIntens[skipIx], js->exonPsIntens, intenM->colCount);
return corr;
}
double calcExonSjProbCorrelation(struct junctSet *js, struct hash *bedHash, struct resultM *probM)
/* Calcualate the correltation between the exon probe
set and the appropriate splice junction set. */
{
double corr = -2;
int includeIx = includeJsIx(js, bedHash);
corr = correlation(js->junctProbs[includeIx], js->exonPsProbs, probM->colCount);
return corr;
}
double calcExonSjSkipProbCorrelation(struct junctSet *js, struct hash *bedHash, struct resultM *probM)
/* Calcualate the correltation between the exon probe
set and the appropriate splice junction set. */
{
double corr = -2;
int skipIx = skipJsIx(js, bedHash);
corr = correlation(js->junctProbs[skipIx], js->exonPsProbs, probM->colCount);
return corr;
}
void calcExonCorrelation(struct junctSet *jsList, struct hash *bedHash,
struct resultM *intenM, struct resultM *probM)
/* Calculate exon correlation if available. */
{
struct junctSet *js = NULL;
for(js = jsList; js != NULL; js = js->next)
{
if(js->junctUsedCount == 2 &&
js->cassette == 1 && differentWord(js->exonPsName, "NA") &&
js->exonPsIntens != NULL && js->exonPsProbs != NULL)
{
js->exonCorr = calcExonSjCorrelation(js, bedHash, intenM);
js->exonSkipCorr = calcExonSjSkipCorrelation(js, bedHash, intenM);
js->probCorr = calcExonSjProbCorrelation(js, bedHash, probM);
js->probSkipCorr = calcExonSjSkipProbCorrelation(js, bedHash, probM);
js->exonSjPercent = calcExonPercent(js, bedHash, probM);
js->sjExonPercent = calcSjPercent(js, bedHash, probM);
if(js->altExpressed && exonPsStats)
fprintf(exonPsStats, "%s\t%.2f\t%.2f\t%.2f\t%d\t%d\t%d\t%d\t%.2f\t%.2f\t%.2f\n",
js->exonPsName, js->exonCorr, js->exonSjPercent, js->sjExonPercent,
js->exonAgree, js->exonDisagree, js->sjAgree, js->sjDisagree, js->probCorr,
js->exonSkipCorr, js->probSkipCorr);
}
}
}
void countExpSpliceType(int type)
/* Record the counts of different alt-splice types. */
{
switch(type)
{
case alt3Prime:
alt3ExpCount++;
break;
case alt5Prime:
alt5ExpCount++;
break;
case alt3PrimeSoft:
alt3SoftExpCount++;
break;
case alt5PrimeSoft:
alt5SoftExpCount++;
break;
case altCassette:
altCassetteExpCount++;
break;
case altOther:
otherExpCount++;
break;
deafult:
warn("Don't recognize type: %d", type);
}
}
void countExpAltSpliceType(int type)
/* Record the counts of different alt-splice types. */
{
switch(type)
{
case alt3Prime:
alt3ExpAltCount++;
break;
case alt5Prime:
alt5ExpAltCount++;
break;
case alt3PrimeSoft:
alt3SoftExpAltCount++;
break;
case alt5PrimeSoft:
alt5SoftExpAltCount++;
break;
case altCassette:
altCassetteExpAltCount++;
break;
case altOther:
otherExpAltCount++;
break;
deafult:
warn("Don't recognize type: %d", type);
}
}
void logOneJunctSet(struct hash *geneHash, struct junctSet *js)
/* Log that a gene is expressed. */
{
struct altCounts *ac = NULL;
ac = hashFindVal(geneHash, js->genePSets[0]);
if(ac == NULL)
{
AllocVar(ac);
ac->gene = js->genePSets[0];
ac->count++;
hashAdd(geneHash, js->genePSets[0], ac);
}
else
ac->count++;
}
void logOneExpressed(struct hash *geneHash, struct junctSet *js)
/* Log an expressed event. */
{
struct altCounts *ac = NULL;
ac = hashMustFindVal(geneHash, js->genePSets[0]);
ac->jsExpressed++;
}
void logOneAltExpressed(struct hash *geneHash, struct junctSet *js)
/* Log an AltExpressed event. */
{
struct altCounts *ac = NULL;
ac = hashMustFindVal(geneHash, js->genePSets[0]);
ac->jsAltExpressed++;
}
void printAltCounts(void *val)
/* Print out the junction sets. */
{
struct altCounts *ac = (struct altCounts *)val;
if(geneCounts != NULL)
fprintf(geneCounts, "%s\t%d\t%d\t%d\n", ac->gene, ac->count,
ac->jsExpressed, ac->jsAltExpressed);
}
int calcExpressed(struct junctSet *jsList, struct resultM *probMat)
/* Loop through and calculate expression and score where score is correlation. */
{
struct junctSet *js = NULL;
int i = 0, j = 0, k = 0;
double minCor = 2; /* Correlation is always between -1 and 1, 2 is
* good max. */
struct hash *geneHash = newHash(10);
char *geneJsOutName = optionVal("geneJsStats", NULL);
char *geneOutName = optionVal("geneStats", NULL);
FILE *geneOut = NULL;
double *X = NULL;
double *Y = NULL;
int elementCount;
int colCount = probMat->colCount;
int rowCount = probMat->rowCount;
int colIx = 0, junctIx = 0; /* Column and Junction indexes. */
int junctOneExp = 0, junctTwoExp = 0; /* What are the counts of
* expressed and alts. */
tissueExpThresh = optionInt("tissueExpThresh",1);
if(geneOutName != NULL)
geneOut = mustOpen(geneOutName, "w");
if(geneJsOutName != NULL)
geneCounts = mustOpen(geneJsOutName, "w");
for(js = jsList; js != NULL; js = js->next)
{
int **expressed = NULL;
int totalTissues = 0;
int junctExpressed = 0;
int geneExpCount = 0;
int altExpTissues = 0;
int jsExpCount = 0;
AllocArray(expressed, js->junctUsedCount);
for(i = 0; i < js->junctUsedCount; i++)
AllocArray(expressed[i], colCount);
/* Loop through and see how many junctions
are actually expressed and in how many tissues. */
for(colIx = 0; colIx < colCount; colIx++)
{
int anyExpressed = 0;
int jsExpressed = 0;
if(geneExpressed(js, colIx))
geneExpCount++;
for(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)
{
if(junctionExpressed(js, colIx, junctIx) == TRUE)
{
expressed[junctIx][colIx]++;
if(expressed[junctIx][colIx] >= tissueExpThresh)
anyExpressed++;
}
if(js->junctProbs[junctIx][colIx] >= presThresh)
jsExpressed++;
}
if(anyExpressed > 0)
totalTissues++;
if(jsExpressed >= tissueExpThresh)
jsExpCount++;
if(jsExpressed >= tissueExpThresh * 2)
altExpTissues++;
}
/* Set number expressed. */
for(i = 0; i < js->junctUsedCount; i++)
{
for(j = 0; j < colCount; j++)
{
int numTissueExpressed = 0;
if(expressed[i][j])
{
/* If this junction has been expressed more than
the threshold stop counting and move on to the
next on. */
if(++numTissueExpressed >= tissueExpThresh)
{
junctExpressed++;
break;
}
}
}
}
/* Record that there is a junction set for this gene. */
logOneJunctSet(geneHash, js);
/* If one tissue expressed set is expressed. */
if(junctExpressed >= 1)
{
js->expressed = TRUE;
logOneExpressed(geneHash, js);
junctOneExp++;
}
/* If two tissues are expressed set is alternative expressed. */
if(junctExpressed >= 2)
{
js->altExpressed = TRUE;
logOneAltExpressed(geneHash, js);
junctTwoExp++;
}
if(js->altExpressed == TRUE)
{
js->score = calcMinCorrelation(js, expressed[0], totalTissues, colCount);
/* countExpSpliceType(js->spliceType);*/
}
else
js->score = BIGNUM;
if(geneOut)
{
char *tmpName = cloneString(js->junctUsed[0]);
char *tmp = NULL;
tmp = strchr(tmpName, '@');
assert(tmp);
*tmp = '\0';
fprintf(geneOut, "%s\t%s\t%d\t%d\t%d\n", js->name, tmpName, geneExpCount, jsExpCount, altExpTissues);
freez(&tmpName);
}
for(i = 0; i < js->junctUsedCount; i++)
freez(&expressed[i]);
freez(&expressed);
}
carefulClose(&geneOut);
hashTraverseVals(geneHash, printAltCounts);
freeHashAndVals(&geneHash);
carefulClose(&geneCounts);
warn("%d junctions expressed above p-val %.2f, %d alternative (%.2f%%)",
junctOneExp, presThresh, junctTwoExp, 100*((double)junctTwoExp/junctOneExp));
}
int junctSetScoreCmp(const void *va, const void *vb)
/* Compare to sort based on score, smallest to largest. */
{
const struct junctSet *a = *((struct junctSet **)va);
const struct junctSet *b = *((struct junctSet **)vb);
if( a->score > b->score)
return 1;
else if(a->score < b->score)
return -1;
return 0;
}
int junctSetExonCorrCmp(const void *va, const void *vb)
/* Compare to sort based on score, smallest to largest. */
{
const struct junctSet *a = *((struct junctSet **)va);
const struct junctSet *b = *((struct junctSet **)vb);
if( a->exonCorr > b->exonCorr)
return -1;
else if(a->exonCorr < b->exonCorr)
return 1;
return 0;
}
int junctSetExonPercentCmp(const void *va, const void *vb)
/* Compare to sort based on score, smallest to largest. */
{
const struct junctSet *a = *((struct junctSet **)va);
const struct junctSet *b = *((struct junctSet **)vb);
double dif = a->exonSjPercent > b->exonSjPercent;
if(dif == 0)
{
if( a->exonCorr > b->exonCorr)
return -1;
else if(a->exonCorr < b->exonCorr)
return 1;
}
if( a->exonSjPercent > b->exonSjPercent)
return -1;
else if(a->exonSjPercent < b->exonSjPercent)
return 1;
return 0;
}
void makePlotLinks(struct junctSet *js, struct dyString *buff)
{
dyStringClear(buff);
dyStringPrintf(buff, "<a target=\"plots\" href=\"./noAltTranStartJunctSet/altPlot/%s.%d-%d.%s.png\">[all]</a> ",
js->chrom, js->chromStart, js->chromEnd, js->hName);
dyStringPrintf(buff, "<a target=\"plots\" href=\"./noAltTranStartJunctSet/altPlot.median/%s.%d-%d.%s.png\">[median]</a> ",
js->chrom, js->chromStart, js->chromEnd, js->hName);
}
void makeJunctMdbGenericLink(struct junctSet *js, struct dyString *buff, char *name, struct resultM *probM, char *suffix)
{
int offSet = 100;
int i = 0;
dyStringClear(buff);
dyStringPrintf(buff, "<a target=\"plots\" href=\"http://mdb1-sugnet.gi.ucsc.edu/cgi-bin/mdbSpliceGraph?mdbsg.calledSelf=on&coordString=%s:%c:%s:%d-%d&mdbsg.cs=%d&mdbsg.ce=%d&mdbsg.expName=%s&mdbsg.probeSummary=on&mdbsg.toScale=on%s\">",
"mm2", js->strand[0], js->chrom, js->chromStart, js->chromEnd,
js->chromStart - offSet, js->chromEnd + offSet, "AffyMouseSplice1-02-2004", suffix);
dyStringPrintf(buff, "%s", name);
dyStringPrintf(buff, "</a> ");
}
void makeJunctExpressedTissues(struct junctSet *js, struct dyString *buff, int junctIx, struct resultM *probM)
{
int offSet = 100;
int i = 0;
struct dyString *dy = newDyString(1048);
char anchor[128];
dyStringClear(buff);
for(i = 0; i < probM->colCount; i++)
{
if(js->junctProbs[junctIx][i] >= presThresh &&
geneExpressed(js, i))
{
safef(anchor, sizeof(anchor), "#%s", probM->colNames[i]);
makeJunctMdbGenericLink(js, dy, probM->colNames[i], probM, anchor);
dyStringPrintf(buff, "%s, ", dy->string);
}
}
dyStringFree(&dy);
}
/* void makeJunctExpressedTissues(struct junctSet *js, struct dyString *buff, int junctIx, struct resultM *probM) */
/* { */
/* int offSet = 100; */
/* int i = 0; */
/* dyStringClear(buff); */
/* for(i = 0; i < probM->colCount; i++) */
/* { */
/* if(js->junctProbs[junctIx][i] >= presThresh && */
/* geneExpressed(js, i)) */
/* dyStringPrintf(buff, "%s, ", probM->colNames[i]); */
/* } */
/* } */
void makeJunctExpressedLink(struct junctSet *js, struct dyString *buff, int junctIx, struct resultM *probM)
{
int offSet = 100;
int i = 0;
dyStringClear(buff);
dyStringPrintf(buff, "<a target=\"plots\" href=\"http://mdb1-sugnet.gi.ucsc.edu/cgi-bin/mdbSpliceGraph?mdbsg.calledSelf=on&coordString=%s:%c:%s:%d-%d&mdbsg.cs=%d&mdbsg.ce=%d&mdbsg.expName=%s&mdbsg.probeSummary=on&mdbsg.toScale=on\">",
"mm2", js->strand[0], js->chrom, js->chromStart, js->chromEnd,
js->chromStart - offSet, js->chromEnd + offSet, "AffyMouseSplice1-02-2004");
for(i = 0; i < probM->colCount; i++)
{
if(js->junctProbs[junctIx][i] >= presThresh &&
geneExpressed(js, i))
dyStringPrintf(buff, "%s,", probM->colNames[i]);
}
dyStringPrintf(buff, "</a> ");
}
void makeJunctNotExpressedTissues(struct junctSet *js, struct dyString *buff, int junctIx, struct resultM *probM)
{
int offSet = 100;
int i = 0;
struct dyString *dy = newDyString(1048);
char anchor[128];
dyStringClear(buff);
for(i = 0; i < probM->colCount; i++)
{
if(js->junctProbs[junctIx][i] <= absThresh)
{
safef(anchor, sizeof(anchor), "#%s", probM->colNames[i]);
makeJunctMdbGenericLink(js, dy, probM->colNames[i], probM, anchor);
dyStringPrintf(buff, "%s, ", dy->string);
}
}
dyStringFree(&dy);
}
void makeJunctMdbLink(struct junctSet *js, struct hash *bedHash,
struct dyString *buff, int junctIx, struct resultM *probM)
{
int offSet = 100;
int i = 0;
dyStringClear(buff);
dyStringPrintf(buff, "<a target=\"plots\" href=\"http://mdb1-sugnet.gi.ucsc.edu/cgi-bin/mdbSpliceGraph?mdbsg.calledSelf=on&coordString=%s:%c:%s:%d-%d&mdbsg.cs=%d&mdbsg.ce=%d&mdbsg.expName=%s&mdbsg.probeSummary=on&mdbsg.toScale=on\">",
"mm2", js->strand[0], js->chrom, js->chromStart, js->chromEnd,
js->chromStart - offSet, js->chromEnd + offSet, "AffyMouseSplice1-02-2004");
dyStringPrintf(buff, "%s", js->junctUsed[junctIx]);
dyStringPrintf(buff, "</a> ");
if(js->cassette == 1 && js->exonPsProbs != NULL)
{
if(junctIx == includeJsIx(js, bedHash))
{
dyStringPrintf(buff, "<b> Inc.</b>");
}
}
}
void makeGbCoordLink(struct junctSet *js, int chromStart, int chromEnd, struct dyString *buff)
/* Make a link to the genome browser with links highlighted. */
{
int junctIx = 0;
int offSet = 100;
dyStringClear(buff);
dyStringPrintf(buff, "<a target=\"browser\" href=\"http://hgwdev-sugnet.gi.ucsc.edu/cgi-bin/hgTracks?position=%s:%d-%d&splicesPFt=red&splicesPlt=or&splicesP_name=", js->chrom, chromStart - offSet, chromEnd + offSet);
for(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)
dyStringPrintf(buff, "%s ", js->junctUsed[junctIx]);
if(js->exonPsName != NULL && differentWord(js->exonPsName, "NA"))
dyStringPrintf(buff, "%s ", js->exonPsName);
dyStringPrintf(buff, "\">%s</a>", js->name);
}
void makeGbClusterLink(struct junctSet *js, struct dyString *buff)
{
makeGbCoordLink(js, js->chromStart, js->chromEnd, buff);
}
void makeGbLink(struct junctSet *js, struct dyString *buff)
{
int junctIx = 0;
int offSet = 100;
dyStringClear(buff);
if(js->hName[0] != 'G' || strlen(js->hName) != 8)
{
dyStringPrintf(buff, "<a target=\"browser\" href=\"http://hgwdev-sugnet.gi.ucsc.edu/cgi-bin/hgTracks?position=%s&splicesPFt=red&splicesPlt=or&splicesP_name=", js->hName);
for(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)
dyStringPrintf(buff, "%s ", js->junctUsed[junctIx]);
dyStringPrintf(buff, "\">%s</a>", js->hName);
}
else
dyStringPrintf(buff, "%s", js->hName);
}
char *spliceTypeName(int t)
/* Return the splice type names. */
{
switch(t)
{
case alt5Prime:
return "alt5";
case alt3Prime:
return "alt3";
case altCassette:
return "altCass";
case altRetInt:
return "altRetInt";
case altOther:
return "altOther";
case alt3PrimeSoft:
return "txEnd";
case alt5PrimeSoft:
return "txStart";
default:
return "unknown";
}
return NULL;
}
void outputLinks(struct junctSet **jsList, struct hash *bedHash, struct resultM *probM, FILE *out)
/* Output a report for each junction set. */
{
struct junctSet *js = NULL;
int colIx = 0, junctIx = 0;
struct dyString *dy = newDyString(2048);
if(optionExists("sortByExonCorr"))
slSort(jsList, junctSetExonCorrCmp);
else if(optionExists("sortByExonPercent"))
slSort(jsList, junctSetExonPercentCmp);
else
slSort(jsList, junctSetScoreCmp);
fprintf(out, "<ol>\n");
for(js = *jsList; js != NULL; js = js->next)
{
if(js->score <= 1)
{
char affyName[256];
boolean gray = FALSE;
char *tmp = NULL;
char *col = NULL;
fprintf(out, "<li>");
fprintf(out, "<table bgcolor=\"#000000\" border=0 cellspacing=0 cellpadding=1><tr><td>");
fprintf(out, "<table bgcolor=\"#FFFFFF\" width=100%%>\n");
fprintf(out, "<tr><td bgcolor=\"#7896be\">");
makeGbClusterLink(js, dy);
fprintf(out, "<b>Id:</b> %s ", dy->string);
makeGbLink(js, dy);
fprintf(out, "<b>GeneName:</b> %s ", dy->string);
makePlotLinks(js, dy);
fprintf(out, "<b>Plots:</b> %s ", dy->string);
fprintf(out, "<b>Score:</b> %.2f", js->score);
fprintf(out, "<b> Type:</b> %s", spliceTypeName(js->spliceType));
safef(affyName, sizeof(affyName), "%s", js->junctUsed[0]);
tmp = strchr(affyName, '@');
assert(tmp);
*tmp = '\0';
fprintf(out, "<a target=_new href=\"https://bioinfo.affymetrix.com/Collab/"
"Manuel_Ares/WebTools/asViewer.asp?gene=%s\"> <b> Affy </b></a>\n", affyName);
fprintf(out, "</td></tr>\n<tr><td>");
if(js->cassette == 1 && js->exonPsProbs != NULL)
{
fprintf(out,
"<b>Exon Corr:</b> %.2f <b>Exon %%:</b> %.2f <b>Junct %%:</b> %.2f "
"<b>Expressed:</b> %d</td></tr><tr><td>\n",
js->exonCorr, js->exonSjPercent, js->sjExonPercent, js->exonAgree + js->exonDisagree);
fprintf(out, "<b>Exon ps:</b> %s</td></tr><tr><td>\n", js->exonPsName);
}
fprintf(out, "<table width=100%%>\n");
for(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)
{
col = "#bebebe";
makeJunctMdbLink(js, bedHash, dy, junctIx, probM);
fprintf(out, "<tr><td bgcolor=\"%s\"><b>Junct:</b> %s</td></tr>", col, dy->string);
makeJunctExpressedTissues(js, dy, junctIx, probM);
col = "#ffffff";
fprintf(out, "<tr><td bgcolor=\"%s\"><b>Exp:</b> %s </td></tr>",col, dy->string);
makeJunctNotExpressedTissues(js, dy, junctIx, probM);
fprintf(out, "<tr><td bgcolor=\"%s\"><b>Not Exp:</b> %s </td></tr>", col, dy->string);
}
fprintf(out, "</table></td></tr>\n");
fprintf(out, "</table></td></tr></table><br></li>\n");
}
}
}
char *findBestDuplicate(struct junctSet *js, struct resultM *intenM)
/* Loop through the junction duplicate set and see which one
has the best correlation to a gene set. */
{
double bestCorr = -2;
double corr = 0;
int gsRow = 0;
int sjRow = 0;
char *bestJunct = NULL;
int junctIx = 0, geneIx = 0;
for(junctIx = 0; junctIx < js->junctDupCount; junctIx++)
{
for(geneIx = 0; geneIx < js->genePSetCount; geneIx++)
{
gsRow = hashIntValDefault(intenM->nameIndex, js->genePSets[geneIx], -1);
sjRow = hashIntValDefault(intenM->nameIndex, js->dupJunctPSets[junctIx], -1);
if(gsRow == -1 || sjRow == -1)
continue;
corr = correlation(intenM->matrix[gsRow], intenM->matrix[sjRow], intenM->colCount);
if(corr >= bestCorr)
{
bestCorr = corr;
bestJunct = js->dupJunctPSets[junctIx];
}
}
}
return bestJunct;
}
double identity(double d)
/* Return d. Seems dumb but avoids a lot of if/else blocks... */
{
return d;
}
double log2(double d)
/* Return log base 2 of d. */
{
double ld = 0;
assert(d != 0);
ld = log(d)/log(2);
return ld;
}
void calcJunctSetRatios(struct junctSet *jsList, struct resultM *intenM)
/* Caluclate the ratio of junction to every other junction in
the set. */
{
char *outFile = optionVal("ratioFile", NULL);
boolean doLog = optionExists("log2Ratio");
struct junctSet *js = NULL;
int i = 0, j = 0, expIx = 0;
int numIx = 0, denomIx = 0;
FILE *out = NULL;
FILE *redundant = NULL;
double **mat = intenM->matrix;
int colCount = intenM->colCount;
double (*transform)(double d) = NULL;
struct hash *nIndex = intenM->nameIndex;
char buff[4096];
if(outFile == NULL)
errAbort("Must specify a ratioFile to print ratios to.");
if(doLog)
transform = log2;
else
transform = identity;
safef(buff, sizeof(buff), "%s.redundant", outFile);
redundant = mustOpen(buff, "w");
out = mustOpen(outFile, "w");
/* Print the header. */
fprintf(out, "YORF\tNAME\t");
for(i = 0; i < colCount-1; i++)
fprintf(out, "%s\t", intenM->colNames[i]);
fprintf(out, "%s\n", intenM->colNames[i]);
for(js = jsList; js != NULL; js = js->next)
{
char **jPSets = js->junctPSets;
char **djPSets = js->dupJunctPSets;
int jCount = js->maxJunctCount;
int dCount = js->junctDupCount;
char *gsName = NULL;
if(strstr(js->genePSets[0], "EX") && js->genePSetCount == 2)
gsName = js->genePSets[1];
else
gsName = js->genePSets[0];
for(i = 0; i < jCount; i++)
{
numIx = hashIntValDefault(nIndex, jPSets[i], -1);
if(numIx == -1)
errAbort("Can't find %s in hash.", jPSets[i]);
/* Calc ratios for the rest of the probe sets. */
for(j = i+1; j < jCount; j++)
{
denomIx = hashIntValDefault(nIndex, jPSets[j], -1);
if(numIx == -1)
errAbort("Can't find %s in hash.", jPSets[j]);
fprintf(out, "%s;%s\t%s\t", jPSets[i], jPSets[j], gsName);
for(expIx = 0; expIx < colCount - 1; expIx++)
{
assert(pow(2,mat[denomIx][expIx]) != 0);
fprintf(out, "%f\t", transform(pow(2,mat[numIx][expIx]) / pow(2,mat[denomIx][expIx])) );
}
fprintf(out, "%f\n", transform(pow(2,mat[numIx][expIx]) / pow(2,mat[denomIx][expIx])) );
}
/* Calc ratios for the dup probe sets. */
if(dCount > 1)
fprintf(redundant, "%s", js->name);
for(j = 0; j < dCount; j++)
{
denomIx = hashIntValDefault(nIndex, djPSets[j], -1);
if(numIx == -1)
errAbort("Can't find %s in hash.", djPSets[j]);
fprintf(out, "%s;%s\t%s\t", jPSets[i], djPSets[j], gsName);
if(dCount > 1)
fprintf(redundant, "\t%s;%s", jPSets[i], djPSets[j]);
for(expIx = 0; expIx < colCount - 1; expIx++)
{
assert(pow(2,mat[denomIx][expIx]) != 0);
fprintf(out, "%f\t", transform(pow(2,mat[numIx][expIx]) / pow(2,mat[denomIx][expIx])) );
}
fprintf(out, "%f\n", transform(pow(2,mat[numIx][expIx]) / pow(2,mat[denomIx][expIx])) );
}
if(dCount > 1)
fprintf( redundant, "\n");
}
/* Get the ratios of the duplicate probes to eachother. */
for(i = 0; i < dCount; i++)
{
numIx = hashIntValDefault(nIndex, djPSets[i], -1);
if(numIx == -1)
errAbort("Can't find %s in hash.", djPSets[i]);
/* Calc ratios for the rest of the dup probe sets. */
for(j = i+1; j < dCount; j++)
{
denomIx = hashIntValDefault(nIndex, djPSets[j], -1);
if(numIx == -1)
errAbort("Can't find %s in hash.", djPSets[j]);
fprintf(out, "%s;%s\t%s\t", djPSets[i], djPSets[j], gsName);
for(expIx = 0; expIx < colCount - 1; expIx++)
{
assert(pow(2,mat[denomIx][expIx]) != 0);
fprintf(out, "%f\t", transform(pow(2,mat[numIx][expIx]) / pow(2,mat[denomIx][expIx])) );
}
fprintf(out, "%f\n", transform(pow(2,mat[numIx][expIx]) / pow(2,mat[denomIx][expIx])) );
}
}
}
carefulClose(&out);
carefulClose(&redundant);
}
void fillInJunctUsed(struct junctSet *jsList, struct resultM *intenM)
/* If it isn't already determined, figures out which junctions we're
using. */
{
struct junctSet *js = NULL;
char *bestDup = NULL;
int i = 0;
for(js = jsList; js != NULL; js = js->next)
{
if(js->junctUsedCount != 0) /* If it has already been filled in forget about it. */
continue;
if(js->junctDupCount == 0) /* Trivial if there are no redundant sets to choose from. */
{
js->junctUsedCount = js->maxJunctCount;
AllocArray(js->junctUsed, js->junctUsedCount);
for(i = 0; i < js->junctUsedCount; i++)
js->junctUsed[i] = cloneString(js->junctPSets[i]);
}
else /* Go find the redundant junction that correlates best with a gene probe set. */
{
js->junctUsedCount = js->maxJunctCount + 1;
AllocArray(js->junctUsed, js->junctUsedCount);
for(i = 0; i < js->junctUsedCount - 1; i++)
js->junctUsed[i] = cloneString(js->junctPSets[i]);
bestDup = findBestDuplicate(js, intenM);
if(bestDup != NULL)
js->junctUsed[i] = cloneString(bestDup);
else
js->junctUsedCount--;
}
}
}
struct hash *hashBeds(char *fileName)
/* Hash all of the beds in a file. */
{
struct bed *bedList = NULL, *bed = NULL;
struct hash *bedHash = newHash(12);
bedList = bedLoadAll(fileName);
for(bed = bedList; bed != NULL; bed = bed->next)
{
hashAddUnique(bedHash, bed->name, bed);
}
return bedHash;
}
int agxVertexByPos(struct altGraphX *agx, int position)
/* Return the vertex index by to position. */
{
int *vPos = agx->vPositions;
int vC = agx->vertexCount;
int i = 0;
for(i = 0; i < vC; i++)
if(vPos[i] == position)
return i;
return -1;
}
int bedSpliceStart(const struct bed *bed)
/* Return the start of the bed splice site. */
{
assert(bed->blockSizes);
return bed->chromStart + bed->blockSizes[0];
}
int bedSpliceEnd(const struct bed *bed)
/* Return the end of the bed splice site. */
{
assert(bed->blockSizes);
return bed->chromStart + bed->chromStarts[1];
}
boolean connectToDownStreamSoft(struct altGraphX *ag, bool **em, int v)
/* Does this vertex (v) connect to a downstream vertex to
create an soft ended exon. */
{
int i = 0;
int vC = ag->vertexCount;
unsigned char *vT = ag->vTypes;
for(i = 0; i < vC; i++)
{
if(em[v][i] && vT[i] == ggSoftEnd &&
getSpliceEdgeType(ag, altGraphXGetEdgeNum(ag, v, i)) == ggExon)
return TRUE;
}
return FALSE;
}
boolean connectToUpstreamSoft(struct altGraphX *ag, bool **em, int v)
/* Does this vertex (v) connect to a upstream vertex to
create an soft started exon. */
{
int i = 0;
int vC = ag->vertexCount;
unsigned char *vT = ag->vTypes;
for(i = 0; i < vC; i++)
{
if(em[i][v] && vT[i] == ggSoftStart &&
getSpliceEdgeType(ag, altGraphXGetEdgeNum(ag, i, v)) == ggExon)
return TRUE;
}
return FALSE;
}
int translateStrand(int type, char strand)
/* Translate the type by strand. If the strand is negative
both alt3Prime and alt5Prime are flipped. */
{
boolean isNeg = strand == '-';
if(type == alt3Prime && isNeg)
type = alt5Prime;
else if(type == alt3PrimeSoft && isNeg)
type = alt5PrimeSoft;
else if(type == alt5Prime && isNeg)
type = alt3Prime;
else if(type == alt5PrimeSoft && isNeg)
type = alt3PrimeSoft;
return type;
}
void outputJunctDna(char *bedName, struct altGraphX *ag, FILE *dnaOut)
/* Write out the dna for a given junction in the
sense orientation. */
{
struct bed *bed = NULL;
bool **em = NULL;
unsigned char *vTypes = NULL;
int *vPos = NULL;
int start1 = -1, end1 = -1, start2 = -1, end2 = -1;
struct dnaSeq *upSeq1 = NULL, *downSeq1 = NULL, *exonSeq1 = NULL;
struct dnaSeq *upSeq2 = NULL, *downSeq2 = NULL, *exonSeq2 = NULL;
bed = hashMustFindVal(junctBedHash, bedName);
em = altGraphXCreateEdgeMatrix(ag);
end1 = agxVertexByPos(ag, bedSpliceStart(bed));
start2 = agxVertexByPos(ag, bedSpliceEnd(bed));
if(end1 == -1 || start2 == -1)
{
altGraphXFreeEdgeMatrix(&em, ag->vertexCount);
noDna++;
return;
}
end2 = agxFindClosestDownstreamVertex(ag, em, start2);
start1 = agxFindClosestUpstreamVertex(ag, em, end1);
if(end2 == -1 || start1 == -1)
{
altGraphXFreeEdgeMatrix(&em, ag->vertexCount);
noDna++;
return;
}
vPos = ag->vPositions;
upSeq1 = hChromSeq(bed->chrom, vPos[start1]-200, vPos[start1]);
exonSeq1 = hChromSeq(bed->chrom, vPos[start1], vPos[end1]);
downSeq1 = hChromSeq(bed->chrom, vPos[end1], vPos[end1]+200);
upSeq2 = hChromSeq(bed->chrom, vPos[start2]-200, vPos[start2]);
exonSeq2 = hChromSeq(bed->chrom, vPos[start2], vPos[end2]);
downSeq2 = hChromSeq(bed->chrom, vPos[end2], vPos[end2]+200);
if(bed->strand[0] == '-')
{
reverseComplement(upSeq1->dna, upSeq1->size);
reverseComplement(exonSeq1->dna, exonSeq1->size);
reverseComplement(downSeq1->dna, downSeq1->size);
reverseComplement(upSeq2->dna, upSeq2->size);
reverseComplement(exonSeq2->dna, exonSeq2->size);
reverseComplement(downSeq2->dna, downSeq2->size);
fprintf(dnaOut, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
bedName, downSeq2->dna, exonSeq2->dna, upSeq2->dna,
downSeq1->dna, exonSeq1->dna, upSeq1->dna);
}
else
{
fprintf(dnaOut, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
bedName, upSeq1->dna, exonSeq1->dna, upSeq2->dna,
upSeq2->dna, exonSeq2->dna, downSeq2->dna);
}
dnaSeqFree(&upSeq1);
dnaSeqFree(&exonSeq1);
dnaSeqFree(&downSeq1);
dnaSeqFree(&upSeq2);
dnaSeqFree(&exonSeq2);
dnaSeqFree(&downSeq2);
altGraphXFreeEdgeMatrix(&em, ag->vertexCount);
withDna++;
}
void outputDnaForJunctSet(struct junctSet *js, FILE *dnaOut)
/* For each junction in a junction set. Cut out the dna for the exon
associated with it. Format is junctName 3'intron exon '5intron
*/
{
bool **em = NULL;
int type = -1;
struct binElement *be = NULL, *beList = NULL, *beStrand = NULL;
unsigned char *vTypes = NULL;
struct altGraphX *ag = NULL, *agList = NULL;
int i = 0;
beList = chromKeeperFind(js->chrom, js->chromStart, js->chromEnd);
for(be = beList; be != NULL; be = be->next)
{
ag = be->val;
if(ag->strand[0] == js->strand[0])
slSafeAddHead(&agList, ag);
}
slFreeList(&beList);
/* Can't do much with no graphs or too many graphs. */
if(agList == NULL || slCount(agList) != 1)
return;
ag = agList;
/* Do the individual junctions. */
for(i = 0; i < js->maxJunctCount; i++)
{
outputJunctDna(js->junctPSets[i], ag, dnaOut);
}
for(i = 0; i < js->junctDupCount; i++)
{
outputJunctDna(js->dupJunctPSets[i], ag, dnaOut);
}
}
void outputDnaForAllJuctSets(struct junctSet *jsList)
/* Loop through and output dna for all of the junctions. */
{
char *db = optionVal("db", NULL);
char *dnaFile = optionVal("outputDna", NULL);
FILE *dnaOut = NULL;
struct junctSet *js = NULL;
if(db == NULL)
errAbort("Must specify db when specifying outputDna.");
assert(dnaFile);
hSetDb(db);
dnaOut = mustOpen(dnaFile, "w");
for(js = jsList; js != NULL; js = js->next)
{
outputDnaForJunctSet(js, dnaOut);
}
warn("%d with dna, %d without dna", withDna, noDna);
carefulClose(&dnaOut);
}
void outputCassetteBed(struct junctSet *js, struct bed *bedUp, struct bed *bedDown,
struct altGraphX *ag, bool **em, int start, int ve1, int ve2,
int altBpStart, int altBpEnd)
/* Write out a cassette bed to a file. */
{
struct bed bed;
if(js->altExpressed && cassetteBedOut)
{
bed.chrom = bedUp->chrom;
bed.chromStart = ag->vPositions[altBpStart];
bed.chromEnd = ag->vPositions[altBpEnd];
bed.name = js->name;
bed.strand[0] = bedUp->strand[0];
bed.score = altCassette;
bedTabOutN(&bed,6,cassetteBedOut);
}
}
int spliceTypeForJunctSet(struct junctSet *js)
/* Determine the alternative splicing type for a junction set. This
function is a little long as I have to convert into altGraphX and do
some strand specific things. */
{
bool **em = NULL;
int type = -1;
struct binElement *be = NULL;
int ssPos[4];
int ssCount = 0;
struct bed *bedUp = NULL, *bedDown = NULL;
unsigned char *vTypes = NULL;
struct altGraphX *ag = NULL;
/* Can't have more than three introns and be a simple
process. */
if(js->maxJunctCount + js->junctDupCount > 3)
return -1;
be = chromKeeperFind(js->chrom, js->chromStart, js->chromEnd);
if(slCount(be) == 1)
ag = be->val;
slFreeList(&be);
if(ag == NULL)
return -1;
vTypes = ag->vTypes;
em = altGraphXCreateEdgeMatrix(ag);
/* Get the beds. If their are enough primar junctions
use them. Otherwise use the duplicates. */
if(js->maxJunctCount >= 2)
{
bedUp = hashMustFindVal(junctBedHash, js->junctPSets[0]);
bedDown = hashMustFindVal(junctBedHash, js->junctPSets[1]);
}
else
{
bedUp = hashMustFindVal(junctBedHash, js->junctPSets[0]);
bedDown = hashMustFindVal(junctBedHash, js->dupJunctPSets[0]);
}
/* Sort the beds. */
if(bedUp->chromStart > bedDown->chromStart ||
(bedDown->chromStart == bedDown->chromStart &&
bedUp->chromEnd > bedDown->chromEnd))
{
struct bed *tmp = bedUp;
bedUp = bedDown;
bedDown = tmp;
}
/* If same start type check for alternative 3' splice. */
if(bedUp->chromStart == bedDown->chromStart)
{
int start = -1, ve1 = -1, ve2 = -2;
int altBpStart = 0, altBpEnd = 0, firstVertex = 0, lastVertex = 0;
int isThreePrime = -1;
start = agxVertexByPos(ag, bedSpliceStart(bedUp));
ve1 = agxVertexByPos(ag, bedSpliceEnd(bedUp));
ve2 = agxVertexByPos(ag, bedSpliceEnd(bedDown));
isThreePrime = agxIsAlt3Prime(ag, em, start, ve1, ve2,
&altBpStart, &altBpEnd, &firstVertex, &lastVertex);
if(isThreePrime)
type = alt3Prime;
else if(agxIsAlt3PrimeSoft(ag, em, start, ve1, ve2,
&altBpStart, &altBpEnd, &firstVertex, &lastVertex))
{
type = alt3PrimeSoft;
}
else if(agxIsCassette(ag, em, start, ve1, ve2,
&altBpStart, &altBpEnd, &firstVertex, &lastVertex))
{
type = altCassette;
js->cassette = TRUE;
}
/* outputAlt3Dna(js, bedUp, bedDown, ag, em, start, ve1, ve2, altBpStart, altBpEnd) */
if(type == altCassette)
outputCassetteBed(js, bedUp, bedDown, ag, em, start, ve1, ve2, altBpStart, altBpEnd);
type = translateStrand(type, ag->strand[0]);
}
/* If same end then check for an alternative 5' splice site. */
else if(bedUp->chromEnd == bedDown->chromEnd)
{
int start1 = -1, start2 = -1, ve1 = -1, ve2 = -2;
int altBpStart = 0, altBpEnd = 0, firstVertex = 0, lastVertex = 0;
int isFivePrime = -1;
ve1 = agxVertexByPos(ag, bedSpliceStart(bedUp));
ve2 = agxVertexByPos(ag, bedSpliceStart(bedDown));
start1 = agxFindClosestUpstreamVertex(ag, em, ve1);
start2 = agxFindClosestUpstreamVertex(ag, em, ve2);
if(start1 == start2)
{
if(agxIsAlt5Prime(ag, em, start1, ve1, ve2,
&altBpStart, &altBpEnd, &firstVertex, &lastVertex))
type = alt5Prime;
}
else if(agxIsAlt5PrimeSoft(ag, em, start1, start2, ve1, ve2,
&altBpStart, &altBpEnd, &firstVertex, &lastVertex))
/* Check for alternative transcription starts. */
{
type = alt5PrimeSoft;
}
else /* Could be a cassette. */
{
int start = -1;
int end = agxVertexByPos(ag, bedSpliceEnd(bedDown));
start = agxVertexByPos(ag, bedSpliceStart(bedUp));
if(agxIsCassette(ag, em, start, start2, end,
&altBpStart, &altBpEnd, &firstVertex, &lastVertex))
{
type = altCassette;
js->cassette = TRUE;
}
if(type == altCassette)
outputCassetteBed(js, bedUp, bedDown, ag, em, start, ve1, ve2, altBpStart, altBpEnd);
}
type = translateStrand(type, ag->strand[0]);
}
if(js->cassette && type != altCassette)
js->cassette == FALSE;
altGraphXFreeEdgeMatrix(&em, ag->vertexCount);
return type;
}
void countSpliceType(int type)
/* Record the counts of different alt-splice types. */
{
switch(type)
{
case alt3Prime:
alt3Count++;
break;
case alt5Prime:
alt5Count++;
break;
case alt3PrimeSoft:
alt3SoftCount++;
break;
case alt5PrimeSoft:
alt5SoftCount++;
break;
case altCassette:
altCassetteCount++;
break;
default:
otherCount++;
}
}
void outputBedsForJunctSet(int type, struct junctSet *js)
/* Write out the beds for the junction set with the
type as the scores. */
{
struct bed *bed = NULL;
int i = 0;
for(i = 0; i < js->maxJunctCount; i++)
{
bed = hashFindVal(junctBedHash, js->junctPSets[i]);
bed->score = type;
bedTabOutN(bed, 12, bedJunctTypeOut);
}
for(i = 0; i < js->junctDupCount; i++)
{
bed = hashFindVal(junctBedHash, js->dupJunctPSets[i]);
bed->score = type;
bedTabOutN(bed, 12, bedJunctTypeOut);
}
}
void determineSpliceTypes(struct junctSet *jsList)
{
int type = -1;
struct junctSet *js = NULL;
for(js = jsList; js != NULL; js = js->next)
{
type = spliceTypeForJunctSet(js);
if(type == -1)
type = altOther;
js->spliceType = type;
countSpliceType(type);
outputBedsForJunctSet(type, js);
}
}
void outputTissueSpecific(struct junctSet *jsList, struct resultM *probM, struct hash *bedHash)
/* Output alternatively spliced isoforms that are tissue specific. */
{
struct junctSet *js = NULL;
char *tissueSpecific = optionVal("tissueSpecific", NULL);
FILE *tsOut = NULL;
int tsCount = 0;
tissueExpThresh = optionInt("tissueExpThresh",1);
assert(tissueSpecific);
tsOut = mustOpen(tissueSpecific, "w");
for(js = jsList; js != NULL; js = js->next)
{
int junctIx = 0;
if(js->altExpressed != TRUE)
continue;
for(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)
{
boolean isSkip = FALSE;
boolean isInclude = FALSE;
int count = 0;
int tissueIx = 0;
int colIx = 0, rowIx = 0;
if(js->spliceType == altCassette)
{
isSkip = (skipJsIx(js, bedHash) == junctIx);
isInclude = (includeJsIx(js, bedHash) == junctIx);
}
for(colIx = 0; colIx < probM->colCount; colIx++)
{
if(junctionExpressed(js, colIx, junctIx) == TRUE)
{
tissueIx = colIx;
count++;
}
}
if(count == 1)
{
int otherJunctIx = 0;
/* Require that at least one other junction is expressed in another tissue. */
for(otherJunctIx = 0; otherJunctIx < js->junctUsedCount; otherJunctIx++)
{
int otherColIx = 0;
if(otherJunctIx == junctIx)
continue;
for(otherColIx = 0; otherColIx < probM->colCount; otherColIx++)
{
if(otherColIx == tissueIx)
continue;
if(junctionExpressed(js, otherColIx, otherJunctIx))
{
fprintf(tsOut, "%s\t%s\t%d\t%d\t%d\n", js->junctUsed[junctIx], probM->colNames[tissueIx],
js->spliceType, isSkip, isInclude);
tsCount++;
otherJunctIx = js->junctUsedCount+1; /* To end the outer loop. */
break; /* to end the inner loop. */
}
}
}
}
}
}
warn("%d junctions are tissue specific", tsCount);
carefulClose(&tsOut);
}
void outputBrainSpecific(struct junctSet *jsList, struct resultM *probM, struct hash *bedHash)
/* Output alternatively spliced isoforms that are brain specific. */
{
struct junctSet *js = NULL;
char *brainSpecific = optionVal("brainSpecific", NULL);
FILE *bsOut = NULL;
int bsCount = 0;
boolean *isBrain = NULL;
int i = 0, j = 0;
char *brainTissues[] = {"cerebellum","cerebral_hemisphere","cortex","medial_eminence","olfactory_bulb","pinealgland","thalamus"};
tissueExpThresh = optionInt("tissueExpThresh",1);
assert(brainSpecific);
AllocArray(isBrain, probM->colCount);
for(i = 0; i < probM->colCount; i++)
{
for(j = 0; j < ArraySize(brainTissues); j++)
{
if(sameWord(brainTissues[j], probM->colNames[i]))
{
isBrain[i] = TRUE;
break;
}
}
}
bsOut = mustOpen(brainSpecific, "w");
for(js = jsList; js != NULL; js = js->next)
{
int junctIx = 0;
/* if(js->altExpressed != TRUE) */
/* continue; */
for(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)
{
boolean isSkip = FALSE;
boolean isInclude = FALSE;
int count = 0;
int brainIx = 0;
int colIx = 0, rowIx = 0;
for(colIx = 0; colIx < probM->colCount; colIx++)
{
if((junctionExpressed(js, colIx, junctIx) == TRUE ||
geneExpressed(js, colIx) == TRUE)
&& isBrain[colIx])
{
brainIx = colIx;
if(js->spliceType == altCassette)
{
isSkip = (skipJsIx(js, bedHash) == junctIx);
isInclude = (includeJsIx(js, bedHash) == junctIx);
}
count++;
}
else if(junctionExpressed(js, colIx, junctIx) == TRUE && !isBrain[colIx])
{
count = -1;
break;
}
}
if(count >= tissueExpThresh)
{
int otherJunctIx = 0;
/* Require that at least one other junction is expressed in another non-brain tissue. */
for(otherJunctIx = 0; otherJunctIx < js->junctUsedCount; otherJunctIx++)
{
int otherJunctExpCount = 0;
int otherColIx = 0;
if(otherJunctIx == junctIx)
continue;
for(otherColIx = 0; otherColIx < probM->colCount; otherColIx++)
{
if(isBrain[otherColIx])
continue;
if(junctionExpressed(js, otherColIx, otherJunctIx))
{
otherJunctExpCount++;
if(otherJunctExpCount >= tissueExpThresh)
{
int includeIx = junctIx;
int before = 0;
if(js->spliceType == altCassette)
includeIx = includeJsIx(js, bedHash);
fprintf(bsOut, "%s\t%s\t%d\t%d\t%d\n", js->name, probM->colNames[brainIx],
js->spliceType, isSkip, isInclude);
bsCount++;
otherJunctIx = js->junctUsedCount+1; /* To end the outer loop. */
break; /* to end the inner loop. */
}
}
}
}
}
}
}
freez(&isBrain);
warn("%d junctions are brain specific", bsCount);
carefulClose(&bsOut);
}
void altHtmlPages(char *junctFile, char *probFile, char *intensityFile, char *bedFile)
/* Do a top level summary. */
{
struct junctSet *jsList = NULL;
struct junctSet *js = NULL;
struct resultM *probM = NULL;
struct resultM *intenM = NULL;
int setCount = 0;
int junctIx = 0, i = 0;
FILE *htmlOut = NULL;
FILE *htmlFrame = NULL;
FILE *spreadSheet = NULL;
char *spreadSheetName = optionVal("spreadSheet", NULL);
char *browserName = "hgwdev-sugnet.cse";
char nameBuff[2048];
char *htmlPrefix = optionVal("htmlPrefix", "");
struct hash *bedHash = NULL;
char *db = "mm2";
assert(junctFile);
jsList = junctSetLoadAll(junctFile);
warn("Loaded %d records from %s", slCount(jsList), junctFile);
if(optionExists("junctPsMap"))
{
printJunctSetProbes(jsList);
exit(0);
}
assert(intensityFile);
intenM = readResultMatrix(intensityFile);
warn("Loaded %d rows and %d columns from %s", intenM->rowCount, intenM->colCount, intensityFile);
if(optionExists("doSjRatios"))
{
calcJunctSetRatios(jsList, intenM);
exit(0);
}
assert(probFile);
assert(bedFile);
probM = readResultMatrix(probFile);
warn("Loaded %d rows and %d columns from %s", probM->rowCount, probM->colCount, probFile);
fillInJunctUsed(jsList, intenM);
fillInProbs(jsList, probM);
fillInIntens(jsList, intenM);
bedHash = hashBeds(bedFile);
junctBedHash = bedHash;
calcExpressed(jsList, probM);
if(doJunctionTypes)
{
determineSpliceTypes(jsList);
warn("%d altCassette, %d alt3, %d alt5, %d altTranStart %d altTranEnd, %d other",
altCassetteCount, alt3Count, alt5SoftCount,
alt5Count, alt3SoftCount, otherCount);
for(js = jsList; js != NULL; js = js->next)
{
if(js->expressed)
countExpSpliceType(js->spliceType);
if(js->altExpressed)
countExpAltSpliceType(js->spliceType);
}
warn("%d altCassette, %d alt3, %d alt5, %d altTranStart %d altTranEnd, %d other expressed",
altCassetteExpCount, alt3ExpCount, alt5SoftExpCount,
alt5ExpCount, alt3SoftExpCount, otherExpCount);
warn("%d altCassette, %d alt3, %d alt5, %d altTranStart %d altTranEnd, %d other expressed alternatively",
altCassetteExpAltCount, alt3ExpAltCount, alt5SoftExpAltCount,
alt5ExpAltCount, alt3SoftExpAltCount, otherExpAltCount);
}
calcExonCorrelation(jsList, bedHash, intenM, probM);
warn("Calculating expression");
if(optionExists("tissueSpecific"))
{
outputTissueSpecific(jsList, probM, bedHash);
}
if(optionExists("brainSpecific"))
{
outputBrainSpecific(jsList, probM, bedHash);
}
if(optionExists("outputDna"))
outputDnaForAllJuctSets(jsList);
/* Write out the lists. */
warn("Writing out links.");
safef(nameBuff, sizeof(nameBuff), "%s%s", htmlPrefix, "lists.html");
htmlOut = mustOpen(nameBuff, "w");
fprintf(htmlOut, "<html><body>\n");
outputLinks(&jsList, bedHash, probM, htmlOut);
fprintf(htmlOut, "</body></html>\n");
carefulClose(&htmlOut);
/* Loop through and output a spreadsheet compatible file
with the names of junction sets. */
if(spreadSheetName != NULL)
{
spreadSheet = mustOpen(spreadSheetName, "w");
for(js = jsList; js != NULL; js = js->next)
{
if(js->altExpressed)
{
fprintf(spreadSheet, "%s\t%s\t", js->hName, js->name);
for(junctIx = 0; junctIx < js->junctUsedCount; junctIx++)
{
fprintf(spreadSheet, "\t%s\t", js->junctUsed[junctIx]);
for(i = 0; i < probM->colCount; i++)
{
if(js->junctProbs[junctIx][i] >= presThresh &&
geneExpressed(js, i))
fprintf(spreadSheet, "%s,", probM->colNames[i]);
}
}
fprintf(spreadSheet, "\n");
}
}
carefulClose(&spreadSheet);
}
/* Write out the frames. */
safef(nameBuff, sizeof(nameBuff), "%s%s", htmlPrefix, "frame.html");
htmlFrame = mustOpen(nameBuff, "w");
fprintf(htmlFrame, "<html><head><title>Junction Sets</title></head>\n"
"<frameset cols=\"30%,70%\">\n"
" <frame name=\"_list\" src=\"./%s%s\">\n"
" <frameset rows=\"50%,50%\">\n"
" <frame name=\"browser\" src=\"http://%s.ucsc.edu/cgi-bin/hgTracks?db=%s&position=%s:%d-%d\">\n"
" <frame name=\"plots\" src=\"http://%s.ucsc.edu/cgi-bin/hgTracks?db=%s&position=%s:%d-%d\">\n"
" </frameset>\n"
"</frameset>\n"
"</html>\n", htmlPrefix, "lists.html",
browserName, db, jsList->chrom, jsList->chromStart, jsList->chromEnd,
browserName, db, jsList->chrom, jsList->chromStart, jsList->chromEnd);
}
void agxLoadChromKeeper(char *file)
/* Load the agx's in the file into the chromKeeper. */
{
char *db = optionVal("db", NULL);
struct altGraphX *agx = NULL, *agxList = NULL;
if(db == NULL)
errAbort("Must specify a database when loading agxs.");
chromKeeperInit(db);
agxList = altGraphXLoadAll(file);
for(agx = agxList; agx != NULL; agx = agx->next)
{
chromKeeperAdd(agx->tName, agx->tStart, agx->tEnd, agx);
}
doJunctionTypes = TRUE;
}
int main(int argc, char *argv[])
{
char *exonPsFile = NULL;
FILE *agxFile = NULL;
char *agxFileName = NULL;
char *cassetteBedOutName = NULL;
if(argc == 1)
usage();
optionInit(&argc, argv, optionSpecs);
if(optionExists("help"))
usage();
presThresh = optionFloat("presThresh", .9);
absThresh = optionFloat("absThresh", .1);
agxFileName = optionVal("agxFile", NULL);
if(agxFileName != NULL)
{
char *spliceTypeFile = optionVal("spliceTypes", NULL);
if(spliceTypeFile == NULL)
errAbort("Must specify spliceTypes flag when specifying agxFile");
bedJunctTypeOut = mustOpen(spliceTypeFile, "w");
agxLoadChromKeeper(agxFileName);
}
cassetteBedOutName = optionVal("cassetteBed", NULL);
if(cassetteBedOutName != NULL)
{
cassetteBedOut = mustOpen(cassetteBedOutName, "w");
}
if((exonPsFile = optionVal("exonStats", NULL)) != NULL)
{
exonPsStats = mustOpen(exonPsFile, "w");
fprintf(exonPsStats,
"#name\tcorrelation\texonSjPercent\tsjExonPercent\t"
"exonAgree\texonDisagree\tsjAgree\tsjDisagree\tprobCorr\tskipCorr\tskipProbCorr\n");
}
if(optionExists("strictDisagree"))
disagreeThresh = absThresh;
else
disagreeThresh = presThresh;
altHtmlPages(optionVal("junctFile", NULL), optionVal("probFile", NULL),
optionVal("intensityFile", NULL), optionVal("bedFile", NULL));
carefulClose(&exonPsStats);
carefulClose(&bedJunctTypeOut);
carefulClose(&cassetteBedOut);
return 0;
}
| {
"alphanum_fraction": 0.6546855507,
"avg_line_length": 30.485458613,
"ext": "c",
"hexsha": "c832b9dfe7e3ddc2dd8ded76f7e7904e3ef42d76",
"lang": "C",
"max_forks_count": 80,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T16:36:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-04-16T10:39:48.000Z",
"max_forks_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "andypohl/kent",
"max_forks_repo_path": "src/hg/altSplice/affySplice/altHtmlPages.c",
"max_issues_count": 60,
"max_issues_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1",
"max_issues_repo_issues_event_max_datetime": "2022-03-30T15:21:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-03T15:15:06.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "andypohl/kent",
"max_issues_repo_path": "src/hg/altSplice/affySplice/altHtmlPages.c",
"max_line_length": 237,
"max_stars_count": 171,
"max_stars_repo_head_hexsha": "af7a004c8f3fa909cd8c2cfc2e5bea60e3421cd1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "andypohl/kent",
"max_stars_repo_path": "src/hg/altSplice/affySplice/altHtmlPages.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T20:21:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-22T15:16:02.000Z",
"num_tokens": 21553,
"size": 68135
} |
/**
* @file lapacke_demo.c
* @brief Demonstrate LAPACKE functionality by performing QR decomposition.
*
* Linking Intel MKL can be a pain, but the Intel Math Kernel Library Link Line
* Advisor helps generate the linker line for you, which on Ubuntu 20.04 LTS is
*
* -Wl,--no-as-needed -lmkl_intel_lp64 -lmkl_gnu_thread
* -lmkl_core -lgomp -lpthread -lm -ldl
*
* Note we replace -lmkl_intel_lp64 with -lmkl_intel_ilp64 for 64-bit ints.
* Read more in Intel's Using the ILP64 Interface vs. LP64 Interface article.
* The compiler flag required on Ubuntu 20.04 LTS is -m64. OOTB, Intel MKL does
* not work with GSL since CBLAS declarations are re-declared, so all
* GSL-related code is included only if we are not linking with Intel MKL.
*
* Both OpenBLAS and LAPACKE can be linked, although without ldconfig,
* `-L/path/to/OpenBLAS -Wl,-rpath -Wl,/path/to/OpenBLAS` must be provided in
* the former case since OpenBLAS by default is not installed in a directory
* that is scanned during linking and during runtime.
*
* To link to CBLAS and LAPACKE separately, one should link against liblapacke
* and libblas, using a proper runtime linker path specification.
*/
#include <stdlib.h>
#include <stdio.h>
// use LAPACKE includes if passed this preprocessor flag (by -D)
#if defined(LAPACKE_INCLUDE)
#include <lapacke.h>
/**
* replace use of MKL_INT with normal int. int size changes if we link against
* libmkl_intel_ilp64 (64 bit int) instead of libmkl_intel_lp64 (32 bit int),
* so it's better to just use MKL_INT and #define it as int otherwise.
*/
#define MKL_INT int
// use Intel MKL includes if passed this preprocessor flag
#elif defined(MKL_INCLUDE)
#include <mkl.h>
// else error, no BLAS + LAPACK includes specified
#else
// silence error squiggles in VS Code (__INTELLISENSE__ always defined)
#ifndef __INTELLISENSE__
#error "no LAPACKE includes specified. try -DLAPACKE_INCLUDE or -DMKL_INCLUDE"
#endif /* __INTELLISENSE__ */
#endif
// optionally include GSL headers
#ifdef GSL_INCLUDE
// can't link GSL with Intel MKL since identifiers are re-declared in headers
#ifdef MKL_INCLUDE
#error "-DMKL_INCLUDE cannot be specified with -DGSL_INCLUDE"
#else
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#endif /* MKL_INCLUDE */
#endif /* GSL_INCLUDE */
// silence error squiggles in VS Code
#ifdef __INTELLISENSE__
#include <mkl.h>
#endif /* __INTELLISENSE__ */
// defines for the main (variable-sized arrays can't use initializers)
#define NROW 4
#define NCOL 3
#define RANK 3
#define SIZE (NROW * NCOL)
// the matrix initializer we will use
#define MAT_INIT {5, 9, 1, -4, -1, 3, 4, -2, -9, -3, 7, 6}
/**
* Simple function to print out a matrix laid out in row-major as a vector.
*
* @param mat `double *` giving elements in the matrix, length `nrow` * `ncol`.
* @param nrow `int` giving number of rows
* @param ncol `int` giving number of columns
* @returns -1 on error, 0 on success
*/
static int print_matrix(const double *mat, int nrow, int ncol)
{
if (mat == NULL || nrow < 1 || ncol < 1) {
return -1;
}
for (int i = 0; i < nrow; i++) {
printf("[ ");
for (int j = 0; j < ncol; j++) {
printf("% .3e ", mat[i * ncol + j]);
}
printf("]\n");
}
return 0;
}
int main(int argc, char **argv)
{
/**
* [ 5 9 1 ]
* represents the matrix [ -4 -1 3 ]
* [ 4 -2 -9 ]
* [ -3 7 6 ]
*
* obviously larger arrays should be put on the heap. it's even better to
* have aligned memory with mkl_malloc or posix_memalign.
*/
double mat[SIZE] = MAT_INIT;
// the (NCOL, NCOL) upper triangular matrix R for the QR of mat.
double u_mat[NCOL * NCOL];
// the resulting (NROW, NCOL) orthogonal matrix Q for mat/temp matrix.
double o_mat[SIZE] = MAT_INIT;
// coefficients for the elementary reflectors
double tau[RANK];
// zero elements below main diagonal of u_mat with zeros + print mat
for (MKL_INT i = 1; i < NCOL; i++) {
for (MKL_INT j = 0; j < i; j++) {
u_mat[i * NCOL + j] = 0;
}
}
printf("original matrix A:\n");
print_matrix(mat, NROW, NCOL);
/**
* perform QR on mat (on o_mat really, which is overwritten). now, o_mat's
* upper triangle is R from the QR factorization of mat, where the remaining
* m - i elements per ith column (1-indexing) give the nonzero (excluding
* leading 1) trailing parts of the orthogonal vectors used to define the
* RANK Householder matrices whose product is Q from the QR factorization.
*/
LAPACKE_dgeqrf(LAPACK_ROW_MAJOR, NROW, NCOL, o_mat, NCOL, tau);
// copy appropriate elements into u_mat + print
for (MKL_INT i = 0; i < NCOL; i++) {
for (MKL_INT j = i; j < NCOL; j++) {
u_mat[i * NCOL + j] = o_mat[i * NCOL + j];
}
}
printf("\nR from QR of A:\n");
print_matrix(u_mat, NCOL, NCOL);
// retrieve Q from QR of mat from o_mat (holds Householder vectors) + print
LAPACKE_dorgqr(LAPACK_ROW_MAJOR, NROW, NCOL, RANK, o_mat, NCOL, tau);
printf("\nQ from QR of A:\n");
print_matrix(o_mat, NROW, NCOL);
// silence error squiggles in VS Code
#ifndef __INTELLISENSE__
// include GSL code generating a random Gaussian matrix ifdef GSL_INCLUDE
#ifdef GSL_INCLUDE
printf("\nGSL enabled: -DGSL_INCLUDE specified\n\n");
// allocate Mersenne Twister PRNG + seed it
gsl_rng *rng = gsl_rng_alloc(gsl_rng_mt19937);
if (rng == NULL) {
fprintf(stderr, "FATAL: unable to allocate new gsl_rng\n");
return EXIT_FAILURE;
}
gsl_rng_set(rng, 7L);
// initialize random matrix with standard Gaussian entries + print
double r_mat[NROW * NCOL];
for (int i = 0; i < NROW; i++) {
for (int j = 0; j < NCOL; j++) {
r_mat[i * NCOL + j] = gsl_ran_gaussian(rng, 1);
}
}
printf("random Gaussian matrix:\n");
print_matrix(r_mat, NROW, NCOL);
// free gsl_rng and return
gsl_rng_free(rng);
#else
printf("\nGSL disabled: -DGSL_INCLUDE not specified\n\n");
#endif /* GSL_INCLUDE */
#endif /* __INTELLISENSE__ */
return EXIT_SUCCESS;
} | {
"alphanum_fraction": 0.6768443638,
"avg_line_length": 35.226744186,
"ext": "c",
"hexsha": "c41d55764c632483d805ca64dff4b30acfaa583e",
"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": "ff5f9932b19f82162bc0d9d46b341d42805f942b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "phetdam/numpy-lapacke-demo",
"max_forks_repo_path": "lapacke_demo/lapacke_demo.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ff5f9932b19f82162bc0d9d46b341d42805f942b",
"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": "phetdam/numpy-lapacke-demo",
"max_issues_repo_path": "lapacke_demo/lapacke_demo.c",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "ff5f9932b19f82162bc0d9d46b341d42805f942b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "phetdam/npy_openblas_demo",
"max_stars_repo_path": "lapacke_demo/lapacke_demo.c",
"max_stars_repo_stars_event_max_datetime": "2021-10-16T00:59:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-10-16T00:59:11.000Z",
"num_tokens": 1803,
"size": 6059
} |
/* integration/err.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
static double rescale_error (double err, const double result_abs, const double result_asc) ;
static double
rescale_error (double err, const double result_abs, const double result_asc)
{
err = fabs(err) ;
if (result_asc != 0 && err != 0)
{
double scale = pow((200 * err / result_asc), 1.5) ;
if (scale < 1)
{
err = result_asc * scale ;
}
else
{
err = result_asc ;
}
}
if (result_abs > GSL_DBL_MIN / (50 * GSL_DBL_EPSILON))
{
double min_err = 50 * GSL_DBL_EPSILON * result_abs ;
if (min_err > err)
{
err = min_err ;
}
}
return err ;
}
| {
"alphanum_fraction": 0.6407588739,
"avg_line_length": 27.6949152542,
"ext": "c",
"hexsha": "a9f9f008824ef856bc04bf1590b9ffb30da5195c",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/integration/err.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/integration/err.c",
"max_line_length": 92,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/integration/err.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": 421,
"size": 1634
} |
#pragma once
#include <gsl.h>
#include <mitkPythonService.h>
#include "PythonSolverSetupServiceActivator.h"
namespace crimson
{
inline QVariant getClassVariable(PythonQtObjectPtr obj, QString variableName)
{
return PythonQtObjectPtr{obj.getVariable("__class__")}.getVariable(variableName);
}
inline PythonQtObjectPtr clonePythonObject(PythonQtObjectPtr object)
{
Expects(!object.isNull());
auto pythonService = PythonSolverSetupServiceActivator::getPythonService();
pythonService->Execute("import copy");
auto result = PythonQtObjectPtr{
pythonService->GetPythonManager()->mainContext().call("copy.deepcopy", QVariantList{QVariant::fromValue(object)})};
Ensures(!result.isNull());
return result;
}
} // namespace crimson | {
"alphanum_fraction": 0.7643979058,
"avg_line_length": 26.3448275862,
"ext": "h",
"hexsha": "8afba3cf219738cd8af5480fa1d16bba4d3eee73",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z",
"max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "carthurs/CRIMSONGUI",
"max_forks_repo_path": "Modules/PythonSolverSetupService/src/SolverSetupPythonUtils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"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": "carthurs/CRIMSONGUI",
"max_issues_repo_path": "Modules/PythonSolverSetupService/src/SolverSetupPythonUtils.h",
"max_line_length": 123,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "carthurs/CRIMSONGUI",
"max_stars_repo_path": "Modules/PythonSolverSetupService/src/SolverSetupPythonUtils.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z",
"num_tokens": 168,
"size": 764
} |
#include "allelefreq.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <gsl/gsl_sf_psi.h>
#include <gsl/gsl_errno.h>
void P_update_simple(const uint8_t* G, const double* zetabeta, const double* zetagamma, const double* xi, const double* beta, const double* gamma, double* var_beta, double* var_gamma, long N, long L, long K)
{
uint8_t genotype;
long idx, n, l, k;
double theta_beta_sum, theta_gamma_sum;
double *var_beta_tmp, *var_gamma_tmp;
var_beta_tmp = (double*) malloc(K * sizeof(double));
var_gamma_tmp = (double*) malloc(K * sizeof(double));
//printf("\n----------- Beginning P_update_simple.\n");
// loop over loci
for (l=0; l<L; l++) {
for (k=0; k<K; k++) {
var_beta_tmp[k] = 0.0;
var_gamma_tmp[k] = 0.0;
}
// loop over samples
//printf("\nl,n,g,beta_sum,gamma_sum,zb1,zg1,zb2,zg2\n");
for (n=0; n<N; n++) {
//printf("%ld,", l);
//printf("%ld,", n);
genotype = G[n * L + l];
//printf("%d,", genotype);
// missing data do not contribute
if (genotype!=3) {
// Add across the components to compute the normalizing constant
// for the indicator variables.
// These are already exponentiated, so they are terms from exp(log likelihood).
// xi: exp(E(log(probability of population k for individual n))
// zetabeta: exp(E(log(probability of allele l for population k))
//
// compute xi*zeta_{beta,gamma}
theta_beta_sum = 0.0;
theta_gamma_sum = 0.0;
for (k=0; k<K; k++) {
// In my notation:
// theta_beta is the indicator that allele A is in population k.
// theta_gamma is the indicator that allele A is in population k.
theta_beta_sum += xi[n * K + k] * zetabeta[l * K + k];
theta_gamma_sum += xi[n * K + k] * zetagamma[l * K + k];
}
//printf("%f,", theta_beta_sum);
//printf("%f,", theta_gamma_sum);
// increment var_{beta,gamma}_tmp
for (k=0; k<K; k++) {
// genotype is either 0, 1, or 2.
// If it is 2, both alleles count towards beta.
// If it is 0, both alleles count towards gamma.
// If it is 1, each allele gets one.
// Note that this is all multiplied by zetabeta and zetagamma below.
var_beta_tmp[k] += (double) genotype * xi[n * K + k] / theta_beta_sum;
var_gamma_tmp[k] += (double) (2 - genotype) * xi[n * K + k] / theta_gamma_sum;
idx = l * K + k;
//printf("%f,", zetabeta[idx] * xi[n * K + k] / theta_beta_sum);
//printf("%f,", zetagamma[idx] * xi[n * K + k] / theta_gamma_sum);
}
}
//printf("\n");
}
// compute var_{beta,gamma}
for (k=0; k<K; k++) {
// The variables <beta> and <gamma> are the priors.
idx = l * K + k;
var_beta[idx] = beta[idx] + zetabeta[idx] * var_beta_tmp[k];
var_gamma[idx] = gamma[idx] + zetagamma[idx] * var_gamma_tmp[k];
}
}
free( var_beta_tmp );
free( var_gamma_tmp );
}
void P_update_logistic(const double* Dvarbeta, const double* Dvargamma, const double* mu, const double* Lambda, double* var_beta, double* var_gamma, double mintol, long L, long K)
{
/*
`Dvarbeta` and `Dvargamma` are a function of the values of `var_beta` and `var_gamma`. This
dependence, however, is explicit on a set of latent populations assignments which in-turn
depend on the variational parameters estimated at the previous step. So, the variables
`Dvarbeta` and `Dvargamma` do not have to be updated.
*/
long l, k, idx, numvar, update;
long iter = 0;
double tol = 10.0;
double tmptol;
double beta, gamma;
double A, pbetagamma, pbeta, pgamma, ppbeta, ppgamma;
double A_1, B_1, C_1, A_2, B_2, C_2;
/*
Iterate until succesive estimates are sufficiently similar
or the number of iterations exceeds 1000.
*/
while (tol>mintol && iter<1000) {
numvar = 0;
tol = 0.0;
// loop over loci
for (l=0; l<L; l++) {
// only update a locus, if all its variational parameters
// satisfy positivity constraints.
update = 1;
for (k=0; k<K; k++) {
if (var_beta[l*K+k]<=0 || var_gamma[l*K+k]<=0) {
update = 0;
}
}
if (update==1) {
// loop over populations
for (k=0; k<K; k++) {
idx = l*K+k;
// compute pseudo-hyperparameters
pbetagamma = gsl_sf_psi_1(var_beta[idx]+var_gamma[idx]);
pbeta = gsl_sf_psi_1(var_beta[idx]);
pgamma = gsl_sf_psi_1(var_gamma[idx]);
ppbeta = gsl_sf_psi_n(2, var_beta[idx]);
ppgamma = gsl_sf_psi_n(2, var_gamma[idx]);
A_1 = pbeta-pbetagamma;
B_1 = -1.*pbetagamma;
A_2 = -1.*pbetagamma;
B_2 = pgamma-pbetagamma;
A = (gsl_sf_psi(var_beta[idx]) - gsl_sf_psi(var_gamma[idx]) - mu[l])*Lambda[k];
C_1 = -1.*A*pbeta - 0.5*Lambda[k]*ppbeta;
C_2 = A*pgamma - 0.5*Lambda[k]*ppgamma;
beta = (C_1*B_2-C_2*B_1)/(A_1*B_2-A_2*B_1);
gamma = (C_1*A_2-C_2*A_1)/(B_1*A_2-B_2*A_1);
// compute var_{beta,gamma}
tmptol = var_beta[idx];
var_beta[idx] = beta + Dvarbeta[idx];
tol += fabs(var_beta[idx]-tmptol);
tmptol = var_gamma[idx];
var_gamma[idx] = gamma + Dvargamma[idx];
tol += fabs(var_gamma[idx]-tmptol);
numvar += 1;
}
}
}
// compute convergence tolerance
tol = 0.5*tol/numvar;
iter += 1;
}
// printf("tol = %.8f, iter = %lu\n",tol,iter);
}
| {
"alphanum_fraction": 0.5108985416,
"avg_line_length": 36.6494252874,
"ext": "c",
"hexsha": "b38021f7b5a51d0737a337a553ca9670d11f0d0a",
"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": "28ae576d9ea4693419a2080cad0008911bf625e0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "rgiordan/fastStructure",
"max_forks_repo_path": "vars/C_allelefreq.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "28ae576d9ea4693419a2080cad0008911bf625e0",
"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": "rgiordan/fastStructure",
"max_issues_repo_path": "vars/C_allelefreq.c",
"max_line_length": 207,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "28ae576d9ea4693419a2080cad0008911bf625e0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "rgiordan/fastStructure",
"max_stars_repo_path": "vars/C_allelefreq.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1714,
"size": 6377
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.