Search is not available for this dataset
text string | meta dict |
|---|---|
/* filter/rmedian.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.
*/
/*
* This module contains routines related to the recursive median filter. The
* algorithm is based on this paper,
*
* [1] S-J Ko, Y. H. Lee, and A. T. Fam, Efficient Implementation of One-Dimensional
* Recursive Median Filters, IEEE Transactions on Circuits and Systems, Vol 37,
* No 11, 1990.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_filter.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_movstat.h>
typedef struct
{
const gsl_movstat_accum * minmax_acc; /* minimum/maximum accumulator */
void *minmax_state; /* minimum/maximum accumulator workspace */
} rmedian_state_t;
static size_t rmedian_size(const size_t n);
static int rmedian_init(const size_t n, void * vstate);
static int rmedian_insert(const double x, void * vstate);
static int rmedian_delete(void * vstate);
static int rmedian_get(void * params, double * result, const void * vstate);
static const gsl_movstat_accum rmedian_accum_type;
gsl_filter_rmedian_workspace *
gsl_filter_rmedian_alloc(const size_t K)
{
gsl_filter_rmedian_workspace *w;
size_t state_size;
w = calloc(1, sizeof(gsl_filter_rmedian_workspace));
if (w == 0)
{
GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM);
}
w->H = K / 2;
w->K = 2*w->H + 1;
w->minmaxacc = gsl_movstat_accum_minmax;
w->window = malloc(w->K * sizeof(double));
if (w->window == NULL)
{
gsl_filter_rmedian_free(w);
GSL_ERROR_NULL ("failed to allocate space for window", GSL_ENOMEM);
}
state_size = rmedian_size(w->H + 1);
w->state = malloc(state_size);
if (w->state == NULL)
{
gsl_filter_rmedian_free(w);
GSL_ERROR_NULL ("failed to allocate space for min/max state", GSL_ENOMEM);
}
w->movstat_workspace_p = gsl_movstat_alloc_with_size(state_size, 0, w->H);
if (!w->movstat_workspace_p)
{
gsl_filter_rmedian_free(w);
GSL_ERROR_NULL ("failed to allocate space for movstat workspace", GSL_ENOMEM);
}
return w;
}
void
gsl_filter_rmedian_free(gsl_filter_rmedian_workspace * w)
{
if (w->state)
free(w->state);
if (w->window)
free(w->window);
if (w->movstat_workspace_p)
gsl_movstat_free(w->movstat_workspace_p);
free(w);
}
/*
gsl_filter_rmedian()
Recursive median filter
Inputs: endtype - end point handling
x - input vector
y - output vector
w - workspace
*/
int
gsl_filter_rmedian(const gsl_filter_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_filter_rmedian_workspace * w)
{
if (x->size != y->size)
{
GSL_ERROR("input and output vectors must have same length", GSL_EBADLEN);
}
else
{
int status = GSL_SUCCESS;
const size_t n = x->size;
const int H = (int) w->H;
double yprev;
int wsize;
/* find median of first window to initialize filter */
wsize = gsl_movstat_fill(endtype, x, 0, H, H, w->window);
yprev = gsl_stats_median(w->window, 1, wsize);
gsl_vector_set(y, 0, yprev);
if (x->size > 1)
{
gsl_vector_const_view xv = gsl_vector_const_subvector(x, 1, n - 1);
gsl_vector_view yv = gsl_vector_subvector(y, 1, n - 1);
/* apply recursive median filter to x[2:end] */
status = gsl_movstat_apply_accum(endtype, &xv.vector, &rmedian_accum_type, (void *) &yprev, &yv.vector,
NULL, w->movstat_workspace_p);
}
return status;
}
}
static size_t
rmedian_size(const size_t n)
{
size_t size = 0;
const gsl_movstat_accum * acc = gsl_movstat_accum_minmax;
size += sizeof(rmedian_state_t);
size += (acc->size)(n);
return size;
}
static int
rmedian_init(const size_t n, void * vstate)
{
rmedian_state_t * state = (rmedian_state_t *) vstate;
state->minmax_acc = gsl_movstat_accum_minmax;
state->minmax_state = (void *) ((unsigned char *) vstate + sizeof(rmedian_state_t));
(state->minmax_acc->init)(n, state->minmax_state);
return GSL_SUCCESS;
}
static int
rmedian_insert(const double x, void * vstate)
{
rmedian_state_t * state = (rmedian_state_t *) vstate;
return (state->minmax_acc->insert)(x, state->minmax_state);
}
static int
rmedian_delete(void * vstate)
{
rmedian_state_t * state = (rmedian_state_t *) vstate;
return (state->minmax_acc->delete_oldest)(state->minmax_state);
}
static int
rmedian_get(void * params, double * result, const void * vstate)
{
const rmedian_state_t * state = (const rmedian_state_t *) vstate;
double *yprev = (double *) params; /* previous filter output */
double y; /* new filter output */
double xminmax[2];
/* get minimum/maximum values of {x_i,...,x_{i+H}} */
(state->minmax_acc->get)(NULL, xminmax, state->minmax_state);
/* y = median [ yprev, xmin, xmax ] */
if (*yprev <= xminmax[0])
y = xminmax[0];
else if (*yprev <= xminmax[1])
y = *yprev;
else
y = xminmax[1];
*result = y;
*yprev = y;
return GSL_SUCCESS;
}
static const gsl_movstat_accum rmedian_accum_type =
{
rmedian_size,
rmedian_init,
rmedian_insert,
rmedian_delete,
rmedian_get
};
| {
"alphanum_fraction": 0.6746728508,
"avg_line_length": 26.5947136564,
"ext": "c",
"hexsha": "e57169a3ac5f1e3ae2a056a98ce2be7ff32c8cd7",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/filter/rmedian.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/filter/rmedian.c",
"max_line_length": 122,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/filter/rmedian.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": 1656,
"size": 6037
} |
#include <gsl/gsl_rng.h>
#include "allvars.h"
// file names
char fname_param[100];
char fname_con[100], fname_line[100], fname_results[100];
FILE *fp_results;
// transfer function parameters
double tau_lim_low, tau_lim_up;
int nc, nc_lim_low, nc_lim_up, nc_best;
double *grid_tau;
const int ntau=200;
double *TF_tau, *TF;
// mcmc
const int ntheta_max = 200;
int ntheta;
int nmcmc, nbuilt;
double *workspace;
int flag_detrend, flag_sim, flag_mcmc;
double *Cmat, *ICmat, *Smat, *Nmat, *USmat, *ASmat;
double *ICvmat, *Tmat1, *Tmat2, *Tmat3, *Tmat4;
double *cov_matrix;
double **theta_range, *theta_best, *theta_best_var;
double *theta_input, *sigma_input;
int *theta_fixed;
double *theta_best_con, *theta_best_var_con;
const gsl_rng_type * gsl_T;
const gsl_rng * gsl_r;
// light curve data
const int ndata_max=500;
int ncon_data, nline_data, nall_data;
double *Tcon_data, *Tline_data, *Fcon_data, *Fcerrs_data, *Fline_data, *Flerrs_data;
double *Fall_data;
double scale_con, scale_line;
double len_con, len_line, cad_con, cad_line;
int ncon=500, nline=500, nall;
double *Tcon, *Fcon, *Fcerrs, *Tline, *Fline, *Flerrs;
// error exit
char str_error_exit[200];
// mathematic functions
int *workspace_ipiv; | {
"alphanum_fraction": 0.7526793075,
"avg_line_length": 22.8867924528,
"ext": "c",
"hexsha": "9d472ce75cf0525743249a5f3368382613a7b2bd",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-04-12T11:48:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-12-29T06:04:13.000Z",
"max_forks_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/MICA",
"max_forks_repo_path": "src/allvars.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "LiyrAstroph/MICA",
"max_issues_repo_path": "src/allvars.c",
"max_line_length": 84,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/MICA",
"max_stars_repo_path": "src/allvars.c",
"max_stars_repo_stars_event_max_datetime": "2016-10-25T06:32:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-25T06:32:33.000Z",
"num_tokens": 389,
"size": 1213
} |
//STARTWHOLE
static char help[] = "Solve a tridiagonal system of arbitrary size.\n"
"Option prefix = tri_.\n";
#include <petsc.h>
int main(int argc,char **args) {
PetscErrorCode ierr;
Vec x, b, xexact;
Mat A;
KSP ksp;
int m = 4, i, Istart, Iend, j[3];
double v[3], xval, errnorm;
PetscInitialize(&argc,&args,NULL,help);
ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"tri_","options for tri",""); CHKERRQ(ierr);
ierr = PetscOptionsInt("-m","dimension of linear system","tri.c",m,&m,NULL); CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
ierr = VecCreate(PETSC_COMM_WORLD,&x); CHKERRQ(ierr);
ierr = VecSetSizes(x,PETSC_DECIDE,m); CHKERRQ(ierr);
ierr = VecSetFromOptions(x); CHKERRQ(ierr);
ierr = VecDuplicate(x,&b); CHKERRQ(ierr);
ierr = VecDuplicate(x,&xexact); CHKERRQ(ierr);
ierr = MatCreate(PETSC_COMM_WORLD,&A); CHKERRQ(ierr);
ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,m,m); CHKERRQ(ierr);
ierr = MatSetOptionsPrefix(A,"a_"); CHKERRQ(ierr);
ierr = MatSetFromOptions(A); CHKERRQ(ierr);
ierr = MatSetUp(A); CHKERRQ(ierr);
ierr = MatGetOwnershipRange(A,&Istart,&Iend); CHKERRQ(ierr);
for (i=Istart; i<Iend; i++) {
if (i == 0) {
v[0] = 3.0; v[1] = -1.0;
j[0] = 0; j[1] = 1;
ierr = MatSetValues(A,1,&i,2,j,v,INSERT_VALUES); CHKERRQ(ierr);
} else {
v[0] = -1.0; v[1] = 3.0; v[2] = -1.0;
j[0] = i-1; j[1] = i; j[2] = i+1;
if (i == m-1) {
ierr = MatSetValues(A,1,&i,2,j,v,INSERT_VALUES); CHKERRQ(ierr);
} else {
ierr = MatSetValues(A,1,&i,3,j,v,INSERT_VALUES); CHKERRQ(ierr);
}
}
xval = exp(cos(i));
ierr = VecSetValues(xexact,1,&i,&xval,INSERT_VALUES); CHKERRQ(ierr);
}
ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = VecAssemblyBegin(xexact); CHKERRQ(ierr);
ierr = VecAssemblyEnd(xexact); CHKERRQ(ierr);
ierr = MatMult(A,xexact,b); CHKERRQ(ierr);
ierr = KSPCreate(PETSC_COMM_WORLD,&ksp); CHKERRQ(ierr);
ierr = KSPSetOperators(ksp,A,A); CHKERRQ(ierr);
ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr);
ierr = KSPSolve(ksp,b,x); CHKERRQ(ierr);
ierr = VecAXPY(x,-1.0,xexact); CHKERRQ(ierr);
ierr = VecNorm(x,NORM_2,&errnorm); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"error for m = %d system is |x-xexact|_2 = %.1e\n",m,errnorm); CHKERRQ(ierr);
KSPDestroy(&ksp); MatDestroy(&A);
VecDestroy(&x); VecDestroy(&b); VecDestroy(&xexact);
return PetscFinalize();
}
//ENDWHOLE
| {
"alphanum_fraction": 0.6031629275,
"avg_line_length": 38.2957746479,
"ext": "c",
"hexsha": "52d3afa88cd5ce62c1c745cf6439421941375a89",
"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": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mapengfei-nwpu/p4pdes",
"max_forks_repo_path": "c/ch2/tri.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"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": "mapengfei-nwpu/p4pdes",
"max_issues_repo_path": "c/ch2/tri.c",
"max_line_length": 95,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mapengfei-nwpu/p4pdes",
"max_stars_repo_path": "c/ch2/tri.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 868,
"size": 2719
} |
/*
* Copyright 2009-2019 The VOTCA-MPIP 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.
*
* author: Denis Andrienko
*/
#ifndef __VOTCA_CTP_GSL_H
#define __VOTCA_CTP_GSL_H
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_eigen.h>
#include <boost/numeric/conversion/cast.hpp>
#define DEBUG_LINALG
#ifdef DEBUG_LINALG
#include <chrono>
#endif
using namespace std;
namespace ub = boost::numeric::ublas;
namespace votca { namespace ctp { namespace linalg {
/**
* \brief inverts A
* @param A symmetric positive definite matrix
* @param V inverse matrix
*/
inline void invert_symm( const ub::matrix<double> &A, ub::matrix<double> &V){
// matrix inversion using gsl
#ifdef DEBUG_LINALG
auto start = std::chrono::system_clock::now();
#endif
gsl_error_handler_t *handler = gsl_set_error_handler_off();
const size_t N = A.size1();
// signum s (for LU decomposition)
int s;
//make copy of A as A is destroyed by GSL
ub::matrix<double> work=A;
V.resize(N, N, false);
// Define all the used matrices
gsl_matrix_view A_view = gsl_matrix_view_array(&work(0,0), N, N);
gsl_matrix_view V_view = gsl_matrix_view_array(&V(0,0), N, N);
gsl_permutation * perm = gsl_permutation_alloc (N);
// Make LU decomposition of matrix A_view
gsl_linalg_LU_decomp (&A_view.matrix, perm, &s);
// Invert the matrix A_view
(void)gsl_linalg_LU_invert (&A_view.matrix, perm, &V_view.matrix);
gsl_set_error_handler(handler);
#ifdef DEBUG_LINALG
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "\n... ... ... \x1b[0;34mGSL Invert"
<< "[" << A.size1() << "x" << A.size2() << "]"
<< " time: " << elapsed_seconds.count()
<< "s\x1b[0;39m";
#endif
}
/**
* \brief eigenvalues of a symmetric matrix A*x=E*x
* @param E vector of eigenvalues
* @param V input: matrix to diagonalize
* @param V output: eigenvectors
*
* This function wraps gsl_eigen_symmv / DSYEV
*
*/
inline void eigenvalues_symm(const ub::matrix<double> &A,
ub::vector<double> &E,
ub::matrix<double> &V)
{
#ifdef DEBUG_LINALG
auto start = std::chrono::system_clock::now();
#endif
gsl_error_handler_t *handler = gsl_set_error_handler_off();
const size_t N = A.size1();
// gsl does not handle conversion of a symmetric_matrix
ub::matrix<double> _A( N,N );
_A = A;
E.resize(N, false);
V.resize(N, N, false);
gsl_matrix_view A_view = gsl_matrix_view_array(&_A(0,0), N, N);
gsl_vector_view E_view = gsl_vector_view_array(&E(0), N);
gsl_matrix_view V_view = gsl_matrix_view_array(&V(0,0), N, N);
gsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(N);
#ifdef NDEBUG
(void)gsl_eigen_symmv(&A_view.matrix, &E_view.vector, &V_view.matrix, w);
#else
int status = gsl_eigen_symmv(&A_view.matrix, &E_view.vector, &V_view.matrix, w);
assert(status == 0);
#endif
gsl_eigen_symmv_sort(&E_view.vector, &V_view.matrix, GSL_EIGEN_SORT_VAL_ASC);
gsl_eigen_symmv_free(w);
gsl_set_error_handler(handler);
//return (status == 0);
#ifdef DEBUG_LINALG
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "\n... ... ... \x1b[0;34mGSL Eigenvalues"
<< "[" << A.size1() << "x" << A.size2() << "]"
<< " time: " << elapsed_seconds.count()
<< "s\x1b[0;39m";
#endif
};
}}}
/*
* Since ublas has very slow prod() function, we overwrite it here
* by the gsl (blas) product function. GSL has separate implementations
* for floats and doubles hence we have two specializations for these types
* Separate templates are provided for diagonal and symmetric matreces
* and their combinations. To check whether a specific routine is called,
* define the GSLDEBUG flag
*/
namespace boost { namespace numeric { namespace ublas {
// 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 DEBUG_LINALG
auto start = std::chrono::system_clock::now();
#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());
#ifdef NDEBUG
(void)gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
1.0, &mA.matrix, &mB.matrix,
0.0, &mC.matrix);
#else
int status = gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
1.0, &mA.matrix, &mB.matrix,
0.0, &mC.matrix);
assert(status == 0);
#endif
#ifdef DEBUG_LINALG
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "\n... ... ... \x1b[0;34mGSL "
<< "[" << m1.size1() << "x" << m1.size2() << "]"
<< "*[" << m2.size1() << "x" << m2.size2() << "]"
<< " time: " << elapsed_seconds.count()
<< "s\x1b[0;39m";
#endif
return AxB;
}
// 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 DEBUG_LINALG
auto start = std::chrono::system_clock::now();
#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);
#ifdef DEBUG_LINALG
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "\n... ... ... \x1b[0;34mGSL "
<< "[" << m1.size1() << "x" << m1.size2() << "]"
<< "*[" << m2.size1() << "x" << m2.size2() << "]"
<< " time: " << elapsed_seconds.count()
<< "s\x1b[0;39m";
#endif
return AxB;
}
}}}
#endif // __VOTCA_CTP_GSL_H
| {
"alphanum_fraction": 0.6053868632,
"avg_line_length": 33.2109704641,
"ext": "h",
"hexsha": "a4f631f6aae9608238970967c5035000061d25d7",
"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": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "jimbach/ctp",
"max_forks_repo_path": "include/votca/ctp/gsl.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b",
"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": "jimbach/ctp",
"max_issues_repo_path": "include/votca/ctp/gsl.h",
"max_line_length": 109,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "jimbach/ctp",
"max_stars_repo_path": "include/votca/ctp/gsl.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2179,
"size": 7871
} |
#ifndef TRANS_UTIL
#define TRANS_UTIL
#define prefetch(x) __builtin_prefetch(x)
#define prefetch_for_r(x) __builtin_prefetch(x, 0, 3)
#define prefetch_for_w(x) __builtin_prefetch(x, 1, 3)
#include <stdarg.h>
#include <gsl/gsl_vector.h>
#include "../include/type.h"
int setulb_(integer *, integer *, doublereal *,
doublereal *, doublereal *, integer *, doublereal *, doublereal *,
doublereal *, doublereal *, doublereal *, integer *, char *,
integer *, char *, logical *, integer *, doublereal *, integer *);
double cuscumsum(gsl_vector *vec, double (*fun) (double, va_list), int argc, ...);
int parse_title(char* str, char** output);
int str_to_vector(char* str, gsl_vector** vec);
int parse_line(char* str, char** id, size_t* id_n, gsl_vector** inc1,
gsl_vector** skp1, gsl_vector** inc2, gsl_vector** skp2,
int* inclu_len, int* skip_len);
int parse_file(const char* filename, diff_list_node* list, char** title);
double logit(double i);
double cumprod(const gsl_vector* vec);
double sum_for_multivar(const double i, va_list argv);
double sum_for_multivar_der(const double i, va_list argv);
double myfunc_marginal_2der(const double x, const double I, const double S,
const double beta, const double var,
const int inclu_len, const int skip_len);
double sum_for_marginal(const double i, va_list argv);
double sum_for_marginal_der(const double i, va_list argv);
odiff* diff_alloc(gsl_vector* inc1, gsl_vector* inc2,
gsl_vector* skp1, gsl_vector* skp2,
int inclu_len, int skip_len, int flag, char* id);
int diff_append(diff_list_node* header, odiff* data);
void mp_threadpool(int nthread, int ntask, void* (*func)(void *), void** datum, void **ret);
double l_bfgs_b_wrapper(integer n, integer m, doublereal x[], doublereal l[],
doublereal u[], integer nbd[],
double (*fp) (const double x[], va_list argv),
void (*gp) (const double x[], double res[], va_list argv),
doublereal factr, doublereal pgtol, integer iprint,
int maxfun, int maxiter, int argc, ...);
#endif
| {
"alphanum_fraction": 0.6451897617,
"avg_line_length": 35.40625,
"ext": "h",
"hexsha": "e1560a0fb4f384d8c798f17815f01cf467da6057",
"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": "ef04603c71dab9d14863ecac5ac598ef97732c4e",
"max_forks_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_forks_repo_name": "yharlne/rmats-turbo",
"max_forks_repo_path": "rMATS_C/include/util.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ef04603c71dab9d14863ecac5ac598ef97732c4e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_issues_repo_name": "yharlne/rmats-turbo",
"max_issues_repo_path": "rMATS_C/include/util.h",
"max_line_length": 92,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ef04603c71dab9d14863ecac5ac598ef97732c4e",
"max_stars_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_stars_repo_name": "yharlne/rmats-turbo",
"max_stars_repo_path": "rMATS_C/include/util.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 567,
"size": 2266
} |
// MIT License
//
// Copyright (c) 2020 SunnyCase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include <chino/ddk/kernel.h>
#include <cstdint>
#include <gsl/gsl-lite.hpp>
namespace chino::arch
{
// No asynchronous interrupt is supported by this target
// Only save callee saved registers in context
struct armv7m_thread_context
{
uintptr_t r4;
uintptr_t r5;
uintptr_t r6;
uintptr_t r7;
uintptr_t r8;
uintptr_t r9;
uintptr_t r10;
uintptr_t r11;
uintptr_t lr;
uintptr_t sp;
uintptr_t stack_bottom;
};
using thread_context_t = armv7m_thread_context;
struct armv7m_arch
{
static constexpr size_t ALLOCATE_ALIGNMENT = 8;
static uint32_t current_processor() noexcept { return 0; }
static void yield_processor() noexcept;
static uintptr_t disable_irq() noexcept;
static void restore_irq(uintptr_t state) noexcept;
static void init_thread_context(thread_context_t &context, gsl::span<uintptr_t> stack, kernel::thread_thunk_t start, void *arg0, void *arg1) noexcept;
[[noreturn]] static void start_schedule(thread_context_t &context) noexcept;
static void yield(thread_context_t &old_context, thread_context_t &new_context) noexcept;
static void init_stack_check() noexcept;
};
using arch_t = armv7m_arch;
}
| {
"alphanum_fraction": 0.7546117546,
"avg_line_length": 34.7910447761,
"ext": "h",
"hexsha": "674a5f4c6e1e129a86f0af45b1e38f96e4cd44f3",
"lang": "C",
"max_forks_count": 20,
"max_forks_repo_forks_event_max_datetime": "2021-09-13T10:14:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-05-18T03:54:08.000Z",
"max_forks_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dotnetGame/chino-os",
"max_forks_repo_path": "src/hal/include/chino/arch/arm/armv7-m/arch.h",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2",
"max_issues_repo_issues_event_max_datetime": "2020-04-30T14:46:51.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-05-15T02:15:33.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dotnetGame/chino-os",
"max_issues_repo_path": "src/hal/include/chino/arch/arm/armv7-m/arch.h",
"max_line_length": 154,
"max_stars_count": 137,
"max_stars_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "chino-os/chino-os",
"max_stars_repo_path": "src/hal/include/chino/arch/arm/armv7-m/arch.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-10T11:42:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-04-28T09:50:17.000Z",
"num_tokens": 537,
"size": 2331
} |
#ifndef UTIL_H
#define UTIL_H
#include <iostream>
#include <stdio.h>
#include <vector>
#include <Eigen/Core>
#include <Eigen/SparseCore>
#include <Eigen/Householder>
#include <assert.h>
#include <time.h>
#include <sys/time.h>
#include <random>
#include <atomic>
#ifdef USE_MKL
#include <mkl_cblas.h>
#include <mkl_lapacke.h>
#include <mkl_lapack.h>
#else
#include <cblas.h>
#include <lapacke.h>
#endif
typedef Eigen::SparseMatrix<double, 0, int> SpMat;
typedef Eigen::VectorBlock<Eigen::Matrix<double, -1, 1, 0, -1, 1>, -1> Segment;
typedef Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, -1, -1> MatrixBlock;
bool are_connected(Eigen::VectorXi &a, Eigen::VectorXi &b, SpMat &A);
bool should_be_disconnected(int lvl1, int lvl2, int sep1, int sep2);
double elapsed(timeval& start, timeval& end);
void swap2perm(Eigen::VectorXi* swap, Eigen::VectorXi* perm);
bool isperm(Eigen::VectorXi* perm);
SpMat symmetric_graph(SpMat& A);
typedef timeval timer;
timer wctime();
/* Concatenate the matrices vertically in the vector H */
void concatenate(std::vector<Eigen::MatrixXd*> H, Eigen::MatrixXd* V);
Eigen::MatrixXd Vconcatenate(std::vector<Eigen::MatrixXd*> H);
void rVconcatenate(std::vector<Eigen::MatrixXd*> H, Eigen::MatrixXd& Hc);
Eigen::VectorXd Vconcatenate(std::vector<Eigen::VectorXd*> H);
/* Concatenate the matrices horizontally in the vector H */
Eigen::MatrixXd Hconcatenate(std::vector<Eigen::MatrixXd*> H);
/* Reverse the concatenation*/
void rHconcatenate(std::vector<Eigen::MatrixXd*> H, Eigen::MatrixXd& Hc);
/**
* C <- alpha A * B + beta C
* C <- alpha A^T * B + beta C
* C <- alpha A * B^T + beta C
* C <- alpha A^T * B^T + beta C
* Gemm
*/
void gemm(Eigen::MatrixXd* A, Eigen::MatrixXd* B, Eigen::MatrixXd* C, CBLAS_TRANSPOSE tA, CBLAS_TRANSPOSE tB, double alpha, double beta);
/** Return a new
* C <- alpha A^(/T) * B^(/T)
**/
Eigen::MatrixXd* gemm_new(Eigen::MatrixXd* A, Eigen::MatrixXd* B, CBLAS_TRANSPOSE tA, CBLAS_TRANSPOSE tB, double alpha);
/**
* C <- C - A * A^T
*/
void syrk(Eigen::MatrixXd* A, Eigen::MatrixXd* C);
/**
* A <- L, L L^T = A
* Return != 0 if potf failed (not spd)
*/
int potf(Eigen::MatrixXd* A);
/**
* A <- [L\U] (lower and upper)
* p <- swap (NOT a permutation)
* A[p] = L*U
* L is unit diagonal
* U is not
* Return != 0 if getf failed (singular)
*/
int getf(Eigen::MatrixXd* A, Eigen::VectorXi* swap);
/**
* Compute an estimated 1-norm condition number of A using its LU or Cholesky factorization
*/
double rcond_1_getf(Eigen::MatrixXd* A_LU, double A_1_norm);
double rcond_1_potf(Eigen::MatrixXd* A_LLT, double A_1_norm);
/**
* B <- B * L^(-1)
* B <- B * L^(-T)
* B <- B * U^(-1)
* B <- B * U^(-T)
*/
void trsm_right(Eigen::MatrixXd* L, Eigen::MatrixXd* B, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag);
/**
* B <- L^(-1) * B
* B <- L^(-T) * B
* B <- U^(-1) * B
* B <- U^(-T) * B
*/
void trsm_left(Eigen::MatrixXd* L, Eigen::MatrixXd* B, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag);
/**
* x <- L^(-1) * x
* x <- L^(-T) * x
* x <- U^(-1) * x
* x <- U^(-T) * x
*/
void trsv(Eigen::MatrixXd* L, Segment* x, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, CBLAS_DIAG diag);
/**
* x <- L^T * x
*/
void trmv_trans(Eigen::MatrixXd* L, Segment* x);
/**
* A <- L^T * A
*/
void trmm_trans(Eigen::MatrixXd* L, Eigen::MatrixXd* A);
/**
* x2 <- x2 - A21 * x1
*/
void gemv_notrans(Eigen::MatrixXd* A21, Segment* x1, Segment* x2);
/**
* x2 <- x2 - A12^T * x1
*/
void gemv_trans(Eigen::MatrixXd* A12, Segment* x1, Segment* x2);
/**
* AP = QR
*/
void geqp3(Eigen::MatrixXd* A, Eigen::VectorXi* jpvt, Eigen::VectorXd* tau);
/**
* Form householder vector from x
*/
double house(Eigen::VectorXd& x);
/**
* RRQR with truncation when the max R_ii < tol
*/
void rrqr(Eigen::MatrixXd* A, Eigen::VectorXi* jpvt, Eigen::VectorXd* tau, double& tol, int& rank);
// template<typename T>
// Eigen::MatrixXd get_gaussian(const int rows, const int cols, T* gen);
template<typename T>
Eigen::MatrixXd get_gaussian(const int rows, const int cols, T* gen) {
std::normal_distribution<double> norm_dist(0.0, 1.0);
Eigen::MatrixXd W(rows, cols);
for(int j = 0; j < cols; j++){
for(int i = 0; i < rows; i++){
W(i,j) = norm_dist(*gen);
}
}
Eigen::VectorXd col_norms = W.colwise().norm();
assert(col_norms.size() == cols);
assert(col_norms.minCoeff() >= 0);
if (col_norms.minCoeff() > 0) {
return W.normalized();
}
return W;
}
Eigen::MatrixXd get_uniform(const int rows, const int cols);
void random_rrqr(const Eigen::MatrixXd* A, Eigen::MatrixXd* v, Eigen::VectorXd* h, double tol, std::function<Eigen::MatrixXd(int,int)> gen_gaussian);
// void laqps(Eigen::MatrixXd* A, Eigen::VectorXi* jpvt, Eigen::VectorXd* tau, double& tol, int block_size, int& rank);
void laqps(Eigen::MatrixXd* A, Eigen::VectorXi* jpvt, Eigen::VectorXd* tau, double& tol, int block_size, int& rank);
/**
* A = U S U^T
* Compute the full EVD, where if A is mxm, U is mxm and S is mxm
*/
void geevd(Eigen::MatrixXd* A, Eigen::MatrixXd* U, Eigen::VectorXd* S);
/**
* A = U S VT
* Compute the full SVD, where if A is mxn, U is mxm, V is nxn, and S is min(M,N)
* VT is V^T, *not* V.
*/
void gesvd(Eigen::MatrixXd* A, Eigen::MatrixXd* U, Eigen::VectorXd* S, Eigen::MatrixXd* VT);
/**
* Compute the singular values of a matrix A
* A = m x n matrix
* S = min(M,N) vector
*/
void gesvd_values(Eigen::MatrixXd* A, Eigen::VectorXd* S);
/**
* x <- Q * x
* A <- Q * A
*/
void ormqr_notrans(Eigen::MatrixXd* v, Eigen::VectorXd* h, Segment* x);
void ormqr_notrans_left(Eigen::MatrixXd* v, Eigen::VectorXd* h, Eigen::MatrixXd* A);
/**
* A <- A * Q
* */
void ormqr_notrans_right(Eigen::MatrixXd* v, Eigen::VectorXd* h, Eigen::MatrixXd* A);
/**
* x <- Q^T * x
* A <- Q^T * A
*/
void ormqr_trans(Eigen::MatrixXd* v, Eigen::VectorXd* h, Segment* x);
void ormqr_trans_left(Eigen::MatrixXd* v, Eigen::VectorXd* h, Eigen::MatrixXd* A);
/**
* A <- A * Q
* A <- A * Q^T
* A <- Q * A
* A <- Q^T * A
*/
void ormqr(Eigen::MatrixXd* v, Eigen::VectorXd* h, Eigen::MatrixXd* A, char side, char trans);
/**
* Create the thin Q
*/
void orgqr(Eigen::MatrixXd* v, Eigen::VectorXd* h);
/* Finds upper triangular matrix T such that,
H = I - V * T * V^T
using Householder vectors V and their norms tau
H = Householder reflector matrix
*/
void larft(Eigen::MatrixXd* V, Eigen::VectorXd* tau, Eigen::MatrixXd* T);
/* Apply householder vectors on a rectangular matrix
V = [1 * * * *
v(1) 1 * * *
v(1) v(2) * * *
v(1) v(2) v(3) * *];
H = H(1) H(2) H(3) ... H(k)
C <- H^T C
*/
void larfb(Eigen::MatrixXd* V, Eigen::MatrixXd* T, Eigen::MatrixXd* C);
void larfb(Eigen::MatrixXd* V, Eigen::MatrixXd* T, Eigen::VectorXd* C, char side = 'L', char trans = 'T', char direct = 'F', char storev = 'C');
/**
* A = QR
*/
void geqrf(Eigen::MatrixXd* A, Eigen::VectorXd* tau);
int choose_rank(Eigen::VectorXd& s, double tol, bool rel = true);
std::size_t hashv(std::vector<size_t> vals);
// Hash function for Eigen matrix and vector.
// The code is from `hash_combine` function of the Boost library. See
// http://www.boost.org/doc/libs/1_55_0/doc/html/hash/reference.html#boost.hash_combine .
template<typename T>
struct matrix_hash : std::unary_function<T, size_t> {
std::size_t operator()(T const& matrix) const {
// Note that it is oblivious to the storage order of Eigen matrix (column- or
// row-major). It will give you the same hash value for two different matrices if they
// are the transpose of each other in different storage order.
size_t seed = 0;
for (size_t i = 0; i < matrix.size(); ++i) {
auto elem = *(matrix.data() + i);
seed ^= std::hash<typename T::Scalar>()(elem) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
};
void block2dense(Eigen::VectorXi &rowval, Eigen::VectorXi &colptr, Eigen::VectorXd &nnzval, int i, int j, int li, int lj, Eigen::MatrixXd *dst, bool transpose);
Eigen::MatrixXd linspace_nd(int n, int dim);
// Returns A[p,p]
SpMat symm_perm(SpMat &A, Eigen::VectorXi &p);
// Permute the columns of non-square matrix A
SpMat col_perm(SpMat &A, Eigen::VectorXi &p);
// Random vector with seed
Eigen::VectorXd random(int size, int seed);
Eigen::MatrixXd random(int rows, int cols, int seed);
// Print vector
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
for(auto v_ : v) {
os << v_ << " " ;
}
os << std::endl;
return os;
}
#endif
| {
"alphanum_fraction": 0.6398373984,
"avg_line_length": 28.6046511628,
"ext": "h",
"hexsha": "01cfbe26bb2a18ceab1e024a6ffbb749db918df9",
"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": "4fd28b1a23c73feb914b40e4285d5a076ffc9058",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Abeynaya/spaQR_public",
"max_forks_repo_path": "include/util.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4fd28b1a23c73feb914b40e4285d5a076ffc9058",
"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": "Abeynaya/spaQR_public",
"max_issues_repo_path": "include/util.h",
"max_line_length": 160,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "4fd28b1a23c73feb914b40e4285d5a076ffc9058",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Abeynaya/spaQR_public",
"max_stars_repo_path": "include/util.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2740,
"size": 8610
} |
/*
KGSX: Biomolecular Kino-geometric Sampling and Fitting of Experimental Data
Yao et al, Proteins. 2012 Jan;80(1):25-43
e-mail: latombe@cs.stanford.edu, vdbedem@slac.stanford.edu, julie.bernauer@inria.fr
Copyright (C) 2011-2013 Stanford University
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:
This entire text, including 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, CONTRIBUTORS 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 KGS_RELATIVEMSDDIRECTION_H
#define KGS_RELATIVEMSDDIRECTION_H
#include <gsl/gsl_vector.h>
#include <tuple>
#include <vector>
#include "core/graph/KinTree.h"
#include "Direction.h"
#include "Selection.h"
class RelativeMSDDirection: public Direction {
public:
RelativeMSDDirection( std::vector< std::tuple<Atom*, Atom*, double> > &relativeDistances);
protected:
void computeGradient(Configuration* conf, Configuration* target, gsl_vector* ret);
private:
std::vector< std::tuple<Atom*, Atom*, double> > &m_relativeDistances;
};
#endif //KGS_RELATIVEMSDDIRECTION_H
| {
"alphanum_fraction": 0.7352222765,
"avg_line_length": 38.6226415094,
"ext": "h",
"hexsha": "59204bf8c05be568b59fcccbc719582fc931a93a",
"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/directions/RelativeMSDDirection.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/directions/RelativeMSDDirection.h",
"max_line_length": 92,
"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/directions/RelativeMSDDirection.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": 467,
"size": 2047
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include <iosfwd>
#include <gsl\gsl>
#include <vector>
#include "Data\Data.h"
#include "Data\TimeUnits.h"
#include <Plat/CameraDevice/CameraSettings.h>
namespace mage
{
namespace binary_data
{
constexpr uint64_t LATEST_BINARY_VERSION = 3;
constexpr uint64_t LATEST_CALIBRATION_VERSION = 2;
// portable strings for device information
struct DeviceInformation
{
std::string Id;
std::string DeviceName;
std::string DeviceManufacturer;
std::string DeviceHardwareVersion;
std::string DeviceFirmwareVersion;
};
struct HeaderData
{
uint64_t BinaryVersion;
uint64_t CalibrationVersion;
calibration::LinearFocalLengthModel Calibration;
mage::Size ImageSize;
mage::PixelFormat FormatOfPixels;
DeviceInformation DeviceInformation;
HeaderData(const uint64_t& b, const uint64_t& m, const calibration::LinearFocalLengthModel& c, const mage::Size& size, const mage::PixelFormat &fp, const mage::binary_data::DeviceInformation& deviceInfo)
: BinaryVersion{ b }, CalibrationVersion{ m }, Calibration{ c }, ImageSize{ size }, FormatOfPixels{ fp }, DeviceInformation{ deviceInfo }
{}
HeaderData()
: BinaryVersion{ LATEST_BINARY_VERSION },
CalibrationVersion{ LATEST_CALIBRATION_VERSION },
Calibration{},
ImageSize{},
FormatOfPixels{ mage::PixelFormat::GRAYSCALE8 },
DeviceInformation{ "n/a", "n/a", "n/a", "n/a" }
{}
};
struct FileFrameData
{
uint64_t CorrelationId;
hundred_nanoseconds TimeStamp;
mira::CameraSettings CameraSettings;
std::vector<uint8_t> Pixels;
FileFrameData(const uint64_t& correlationId, const hundred_nanoseconds& t, const mira::CameraSettings& cameraSettings, std::vector<uint8_t> p)
: CorrelationId{ correlationId }, TimeStamp{ t }, CameraSettings{ cameraSettings }, Pixels{ std::move(p) }
{}
FileFrameData() = default;
FileFrameData(FileFrameData&&) = default;
};
void SerializeCaptureHeaderData(std::fstream& outputFile, const HeaderData& data);
void SerializeFrameData(std::fstream& outputFile, const FileFrameData& data);
bool DeSerializeHeaderData(std::istream& inputFile, HeaderData& data);
FileFrameData DeSerializeFrameData(std::istream& inputFile, HeaderData& headerData);
}
}
| {
"alphanum_fraction": 0.6260869565,
"avg_line_length": 35.3846153846,
"ext": "h",
"hexsha": "b9d9d0897527e15906b137f6b5cd200046d49bc2",
"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": "Core/MAGESLAM/Source/Serialization/BinarySerializer.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": "Core/MAGESLAM/Source/Serialization/BinarySerializer.h",
"max_line_length": 215,
"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": "Core/MAGESLAM/Source/Serialization/BinarySerializer.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": 576,
"size": 2760
} |
// https://stackoverflow.com/questions/66536134/gsl-gsl-linalg-sv-decomp-returning-u-and-v-reversed
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_linalg.h>
void pretty_print(const gsl_matrix * M)
{
// Get the dimension of the matrix.
int rows = M->size1;
int cols = M->size2;
// Now print out the data in a square format.
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
printf("%f ", gsl_matrix_get(M, i, j));
}
printf("\n");
}
printf("\n");
}
void pretty_print_vector(const gsl_vector * M)
{
int cols = M->size;
for(int j = 0; j < cols; j++){
printf("%f ", gsl_vector_get(M, j));
}
printf("\n");
}
int
main()
{
const size_t M = 4;
const size_t N = 5;
double A_data[] = {
1.0, 0.0, 0.0, 0.0, 2.0,
0.0, 0.0, 3.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 2.0, 0.0, 0.0, 0.0 };
gsl_matrix_view A = gsl_matrix_view_array(A_data, 4, 5);
gsl_matrix * B = gsl_matrix_alloc(N, M);
gsl_matrix * V = gsl_matrix_alloc(M, M);
gsl_vector * S = gsl_vector_alloc(M);
gsl_vector * work = gsl_vector_alloc(M);
gsl_matrix_transpose_memcpy(B, &A.matrix);
gsl_linalg_SV_decomp(B, V, S, work);
printf("U:\n");
pretty_print(V);
printf("S:\n");
pretty_print_vector(S);
printf("V:\n");
pretty_print(B);
gsl_matrix_free(B);
gsl_matrix_free(V);
gsl_vector_free(S);
gsl_vector_free(work);
return 0;
} | {
"alphanum_fraction": 0.6147757256,
"avg_line_length": 21.6571428571,
"ext": "c",
"hexsha": "35e7b665e73355d5fefecbab536c95339e08393c",
"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": "fceabadef49ffe6ed25dfef38e3dc418f309e128",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "al2698/sp",
"max_forks_repo_path": "07-lib/gsl/svd1.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fceabadef49ffe6ed25dfef38e3dc418f309e128",
"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": "al2698/sp",
"max_issues_repo_path": "07-lib/gsl/svd1.c",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "fceabadef49ffe6ed25dfef38e3dc418f309e128",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "al2698/sp",
"max_stars_repo_path": "07-lib/gsl/svd1.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 535,
"size": 1516
} |
#pragma once
// Windows
#if defined(_WIN32)
#if !defined(NOMINMAX)
#define NOMINMAX
#endif
#include <windows.h>
#endif
// Standard
#include <cstdlib>
#include <exception>
#include <stdexcept>
#include <cassert>
#include <string>
#include <vector>
#include <map>
#include <memory>
#include <cstdint>
#include <sstream>
#include <fstream>
#include <chrono>
#include <functional>
#include <algorithm>
#include <iterator>
#if defined(DEBUG) || defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif
// Guidline Support Library
#include <gsl/gsl>
// OpenGL
#include <GL/gl3w.h>
#define GLFW_INCLUDE_GLCOREARB
#include <GLFW/glfw3.h>
#if defined(_LINUX)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
#endif
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#if defined(_LINUX)
#pragma GCC diagnostic pop
#endif
//#include <SOIL/SOIL.h>
// Assimp
#if defined(_LINUX)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
#endif
#include <assimp/scene.h>
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#if defined(_LINUX)
#pragma GCC diagnostic pop
#endif
// Local
#include "ServiceContainer.h"
namespace Library
{
extern ServiceContainer GlobalServices;
} | {
"alphanum_fraction": 0.7546728972,
"avg_line_length": 17.3513513514,
"ext": "h",
"hexsha": "58c31478292d98801e87c6a11e396dab0924a960",
"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": "628e9aed116022175cc0c59c88ace7688309628c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "DakkyDaWolf/OpenGL",
"max_forks_repo_path": "source/Library.Shared/pch.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c",
"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": "DakkyDaWolf/OpenGL",
"max_issues_repo_path": "source/Library.Shared/pch.h",
"max_line_length": 45,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "DakkyDaWolf/OpenGL",
"max_stars_repo_path": "source/Library.Shared/pch.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 315,
"size": 1284
} |
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_sf_gegenbauer.h>
#include "scf.h"
/* Given the coefficients stored mat_cos and mat_sin, this code does
* the summation to compute the potential and accelerations
*
* scf_potential() is the full 3D treatment for the host halo
*
* scf_potential_spherical() is the spherically symmetric treatment
* for the subhalos. This spherical code skips the loops over l,m
* so it's simpler.
*/
float scf_potential(float* a, double* mat_cos, double* mat_sin, int orbit_nmax, int orbit_lmax, float x, float y, float z)
{
double x2 = (double)x * (double)x;
double y2 = (double)y * (double)y;
double r = sqrt(x2+y2+(double)z*(double)z);
double r_xy = sqrt(x2+y2);
double phi = atan2((double)y, (double)x);
double sin_theta = r_xy / r;
double sin_phi = (double)y / r_xy;
double cos_theta = (double)z / r;
double cos_phi = (double)x / r_xy;
double cos_theta_for_Plm = cos_theta;
#ifdef USE_GSL_GEGENBAUER_HOST
double xi = (r-1.0)/(r+1.0);
#endif
double a_r = 0.0;
double a_t = 0.0;
double a_p = 0.0;
int n,l,m;
float C_lm = 0.0f;
float D_lm = 0.0f;
float E_lm = 0.0f;
float F_lm = 0.0f;
float this_Phi_nl = 0.f;
float this_dPhi_nl_dr = 0.f;
#ifdef USE_GSL_GEGENBAUER_HOST
double* Cna_2l_32_array = (double*)malloc((orbit_nmax+1)*sizeof(double));
double* Cna_2l_52_array = (double*)malloc(orbit_nmax*sizeof(double));
#endif
double this_P_lm = 0.0;
double this_dP_lm = 0.0;
double* P_l;
double* dP_l;
int P_size;
float cos_mphi;
float sin_mphi;
float pot = 0.f;
a[0] = 0.f;
a[1] = 0.f;
a[2] = 0.f;
for(m=0; m<=orbit_lmax; m++)
{
cos_mphi = cos(m*phi);
sin_mphi = sin(m*phi);
P_size = orbit_lmax - m + 1;
P_l = (double*)malloc(P_size*sizeof(double));
dP_l = (double*)malloc(P_size*sizeof(double));
gsl_sf_legendre_Plm_deriv_array(orbit_lmax, m, cos_theta_for_Plm, P_l, dP_l);
for(l=m; l<=orbit_lmax; l++)
{
C_lm = 0.f;
D_lm = 0.f;
E_lm = 0.f;
F_lm = 0.f;
#ifdef USE_GSL_GEGENBAUER_HOST
gsl_sf_gegenpoly_array(orbit_nmax, 2*l+1.5, xi, Cna_2l_32_array);
if(orbit_nmax > 0)
gsl_sf_gegenpoly_array(orbit_nmax-1, 2*l+2.5, xi, Cna_2l_52_array);
#endif
for(n=0; n<=orbit_nmax; n++)
{
#ifdef USE_GSL_GEGENBAUER_HOST
this_Phi_nl = Phi_nl(Cna_2l_32_array[n], l, r);
if(n>0)
this_dPhi_nl_dr = dPhi_nl_dr(Cna_2l_52_array[n-1], this_Phi_nl, n, l, r);
else
this_dPhi_nl_dr = dPhi_nl_dr(1e99, this_Phi_nl, n, l, r);
#else
this_Phi_nl = Phi_nl(n,l,r);
this_dPhi_nl_dr = dPhi_nl_dr(this_Phi_nl, n, l, r);
#endif
C_lm += mat_cos[ind(n,l,m)] * this_Phi_nl;
D_lm += mat_sin[ind(n,l,m)] * this_Phi_nl;
E_lm += mat_cos[ind(n,l,m)] * this_dPhi_nl_dr;
F_lm += mat_sin[ind(n,l,m)] * this_dPhi_nl_dr;
}
this_P_lm = P_l[l-m];
this_dP_lm = dP_l[l-m] * -sin_theta;
pot += this_P_lm * (C_lm*cos_mphi + D_lm*sin_mphi);
a_r += this_P_lm * (E_lm*cos_mphi + F_lm*sin_mphi);
a_t += this_dP_lm * (C_lm*cos_mphi + D_lm*sin_mphi);
a_p += m * this_P_lm * (D_lm*cos_mphi - C_lm*sin_mphi);
} // l loop
free(P_l);
free(dP_l);
} // m loop
a_r = -a_r;
a_t = -a_t/r;
a_p = -a_p/r_xy;
a[0] = a_r*sin_theta*cos_phi + a_t*cos_theta*cos_phi - a_p*sin_phi;
a[1] = a_r*sin_theta*sin_phi + a_t*cos_theta*sin_phi + a_p*cos_phi;
a[2] = a_r*cos_theta - a_t*sin_theta;
a[0] *= G;
a[1] *= G;
a[2] *= G;
pot *= G;
#ifdef USE_GSL_GEGENBAUER_HOST
free(Cna_2l_32_array);
free(Cna_2l_52_array);
#endif
return pot;
}
float scf_potential_spherical(float* a, float* mat_cos, int orbit_nmax, float x, float y, float z)
{
float x2 = x*x;
float y2 = y*y;
float r = sqrt(x2+y2+z*z);
float r_xy = sqrt(x2+y2);
#ifdef USE_GSL_GEGENBAUER_SUBHALO
float xi = (r-1.0f)/(r+1.0f);
#endif
float sin_theta = r_xy / r;
float sin_phi = y / r_xy;
float cos_theta = z / r;
float cos_phi = x / r_xy;
float this_Phi_n0 = 0.f;
float this_dPhi_n0_dr = 0.f;
#ifdef USE_GSL_GEGENBAUER_SUBHALO
double* Cna_32_array = (double*)malloc((orbit_nmax+1)*sizeof(double));
double* Cna_52_array = (double*)malloc(orbit_nmax*sizeof(double));
gsl_sf_gegenpoly_array(orbit_nmax, 1.5, xi, Cna_32_array);
gsl_sf_gegenpoly_array(orbit_nmax-1, 2.5, xi, Cna_52_array);
#endif
float C_lm = 0.0f;
float E_lm = 0.0f;
int n;
for(n=0; n<=orbit_nmax; n++)
{
#ifdef USE_GSL_GEGENBAUER_SUBHALO
this_Phi_n0 = Phi_n0(Cna_32_array[n], r);
if(n>0)
this_dPhi_n0_dr = dPhi_n0_dr(Cna_52_array[n-1], this_Phi_n0, n, r);
else
this_dPhi_n0_dr = dPhi_n0_dr(1e99, this_Phi_n0, n, r);
#else
this_Phi_n0 = Phi_n0(n,r);
this_dPhi_n0_dr = dPhi_n0_dr(this_Phi_n0, n, r);
#endif
C_lm += mat_cos[n] * this_Phi_n0;
E_lm += mat_cos[n] * this_dPhi_n0_dr;
}
float pot = C_lm;
float a_r = -E_lm;
a[0] = G * a_r*sin_theta*cos_phi;
a[1] = G * a_r*sin_theta*sin_phi;
a[2] = G * a_r*cos_theta;
pot = G * pot;
#ifdef USE_GSL_GEGENBAUER_SUBHALO
free(Cna_32_array);
free(Cna_52_array);
#endif
return pot;
}
| {
"alphanum_fraction": 0.579742877,
"avg_line_length": 26.1636363636,
"ext": "c",
"hexsha": "8ddfa731140821c6faf343e205eca4e1f82d246b",
"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": "e04d8738e92333f546ec6ef4b4f61c7e87456aba",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "wayne927/vl2-scf",
"max_forks_repo_path": "scf_potential.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e04d8738e92333f546ec6ef4b4f61c7e87456aba",
"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": "wayne927/vl2-scf",
"max_issues_repo_path": "scf_potential.c",
"max_line_length": 122,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "e04d8738e92333f546ec6ef4b4f61c7e87456aba",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "wayne927/vl2-scf",
"max_stars_repo_path": "scf_potential.c",
"max_stars_repo_stars_event_max_datetime": "2017-03-08T23:45:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-07T19:05:02.000Z",
"num_tokens": 1955,
"size": 5756
} |
#if !defined(XEOL_H_INCLUDED)
#define XEOL_H_INCLUDED
#include "FileEnumerator.h"
#include "Utils.h"
#include <filesystem>
#include <gsl/gsl>
#include <iosfwd>
#include <string>
class Xeol
{
public:
static int usage(::std::ostream& strm, const ::std::string& progName,
const char* pMsg);
Xeol(::gsl::span<const char*const> args);
int run() const;
Xeol(const Xeol&) = delete;
Xeol& operator=(const Xeol&) = delete;
Xeol(Xeol&&) = delete;
Xeol& operator=(Xeol&&) = delete;
PRIVATE_EXCEPT_IN_TEST:
/// \brief EolType contains the enum constants that indicate the type of
/// end-of-line for a text file.
enum class EolType
{
INDETERMINATE, ///< File contains no ends-of-line
MIXED, ///< Inconsistent end-of-line convention, may be binary
DOS, ///< End-of-line is "\r\n"
MACINTOSH, ///< End-of-line is "\r" (now archaic)
UNIX ///< End-of-line is "\n"
};
using Path = ::std::filesystem::path;
void queryFile(const Path& p) const;
void translateFile(const Path& p) const;
static char getIndicatorLetter(EolType eolType);
static ::std::string toEolString(EolType eolType);
static ::std::string displayPath(const Path& p);
/// \brief Scans the input file, counts the end-of-line types, and
/// optionally translates the ends-of-line into the provided stream.
///
/// If pOut is null, then the method simply counts the end-of-line types and
/// returns the corresponding EolType constant. In this case, the
/// targetEolType parameter is ignored.
///
/// If pOut is not null, then the method additionally translates the file
/// into *pOut. In this case, targetEolType must be one of DOS, MACINTOSH,
/// or UNIX.
static EolType scanFile(::std::istream& in,
/* out */ size_t& numDosEols, /* out */ size_t& numMacEols,
/* out */ size_t& numUnixEols, /* out */ size_t& totalEols,
::std::ostream* pOut = nullptr, EolType targetEolType = EolType::INDETERMINATE);
static void replaceOriginalFileWithTemp(const Path& originalPath,
const Path& tempPath);
bool m_isInQueryMode;
EolType m_targetEolType;
bool m_forceTranslation;
FileEnumerator m_fileEnumerator;
};
#endif // XEOL_H_INCLUDED
| {
"alphanum_fraction": 0.7068403909,
"avg_line_length": 29.8472222222,
"ext": "h",
"hexsha": "3881718bcc827c6aadfa12e1a725a2a597abf087",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "IanEmmons/CmdLineUtil",
"max_forks_repo_path": "Xeol.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "IanEmmons/CmdLineUtil",
"max_issues_repo_path": "Xeol.h",
"max_line_length": 82,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "IanEmmons/CmdLineUtil",
"max_stars_repo_path": "Xeol.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 621,
"size": 2149
} |
#pragma once
#include <halley/utils/utils.h>
#include <vector>
#include <gsl/gsl>
#include "halley/data_structures/flat_map.h"
#include "halley/maths/vector2.h"
#include "halley/maths/rect.h"
#include "halley/file/path.h"
#include <map>
#include <unordered_map>
#include <cstdint>
#include <utility>
#include <set>
#include "halley/data_structures/maybe.h"
#include "halley/maths/colour.h"
#include "halley/maths/vector4.h"
namespace Halley
{
class String;
class SerializerOptions
{
public:
constexpr static int maxVersion = 1;
int version = 0;
bool exhaustiveDictionary = false;
std::function< std::optional< size_t >( const String& string ) > stringToIndex;
std::function< const String&( size_t index ) > indexToString;
SerializerOptions() = default;
SerializerOptions( int version ) :
version( version )
{ }
};
class SerializerState
{
};
class ByteSerializationBase
{
public:
ByteSerializationBase( SerializerOptions options ) :
options( std::move( options ) )
{ }
SerializerState* setState( SerializerState* state );
template < typename T >
T* getState() const
{
return static_cast< T* >( state );
}
int getVersion() const { return version; }
void setVersion( int v ) { version = v; }
protected:
SerializerOptions options;
private:
SerializerState* state = nullptr;
int version = 0;
};
class Serializer : public ByteSerializationBase
{
public:
Serializer( SerializerOptions options );
explicit Serializer( gsl::span< gsl::byte > dst, SerializerOptions options );
template < typename T, typename std::enable_if< std::is_convertible< T, std::function< void( Serializer& ) > >::value, int >::type = 0 >
static Bytes toBytes( const T& f, SerializerOptions options = {} )
{
auto dry = Serializer( options );
f( dry );
Bytes result( dry.getSize() );
auto s = Serializer( gsl::as_writable_bytes( gsl::span< Halley::Byte >( result ) ), options );
f( s );
return result;
}
template < typename T, typename std::enable_if< !std::is_convertible< T, std::function< void( Serializer& ) > >::value, int >::type = 0 >
static Bytes toBytes( const T& value, SerializerOptions options = {} )
{
return toBytes( [ &value ]( Serializer& s ) { s << value; }, options );
}
size_t getSize() const { return size; }
Serializer& operator<<( bool val ) { return serializePod( val ); }
Serializer& operator<<( int8_t val ) { return serializeInteger( val ); }
Serializer& operator<<( uint8_t val ) { return serializeInteger( val ); }
Serializer& operator<<( int16_t val ) { return serializeInteger( val ); }
Serializer& operator<<( uint16_t val ) { return serializeInteger( val ); }
Serializer& operator<<( int32_t val ) { return serializeInteger( val ); }
Serializer& operator<<( uint32_t val ) { return serializeInteger( val ); }
Serializer& operator<<( int64_t val ) { return serializeInteger( val ); }
Serializer& operator<<( uint64_t val ) { return serializeInteger( val ); }
Serializer& operator<<( float val ) { return serializePod( val ); }
Serializer& operator<<( double val ) { return serializePod( val ); }
Serializer& operator<<( const std::string& str );
Serializer& operator<<( const String& str );
Serializer& operator<<( const Path& path );
Serializer& operator<<( gsl::span< const gsl::byte > span );
Serializer& operator<<( const Bytes& bytes );
template < typename T >
Serializer& operator<<( const std::vector< T >& val )
{
unsigned int sz = static_cast< unsigned int >( val.size() );
*this << sz;
for ( unsigned int i = 0; i < sz; i++ )
{
*this << val[ i ];
}
return *this;
}
template < typename T, typename U >
Serializer& operator<<( const FlatMap< T, U >& val )
{
*this << static_cast< unsigned int >( val.size() );
for ( auto& kv : val )
{
*this << kv.first << kv.second;
}
return *this;
}
template < typename T, typename U >
Serializer& operator<<( const std::map< T, U >& val )
{
*this << static_cast< unsigned int >( val.size() );
for ( auto& kv : val )
{
*this << kv.first << kv.second;
}
return *this;
}
template < typename T, typename U >
Serializer& operator<<( const std::unordered_map< T, U >& val )
{
std::map< T, U > m;
for ( auto& kv : val )
{
m[ kv.first ] = kv.second;
}
return ( *this << m );
}
template < typename T >
Serializer& operator<<( const std::set< T >& val )
{
unsigned int sz = static_cast< unsigned int >( val.size() );
*this << sz;
for ( auto& v : val )
{
*this << v;
}
return *this;
}
template < typename T >
Serializer& operator<<( const Vector2D< T >& val )
{
return *this << val.x << val.y;
}
template < typename T >
Serializer& operator<<( const Vector3D< T >& val )
{
return *this << val.x << val.y << val.z;
}
template < typename T >
Serializer& operator<<( const Vector4D< T >& val )
{
return *this << val.x << val.y << val.z << val.w;
}
template < typename T >
Serializer& operator<<( const Colour4< T >& val )
{
return *this << val.r << val.g << val.b << val.a;
}
template < typename T >
Serializer& operator<<( const Rect2D< T >& val )
{
return *this << val.getTopLeft() << val.getBottomRight();
}
template < typename T, typename U >
Serializer& operator<<( const std::pair< T, U >& p )
{
return *this << p.first << p.second;
}
template < typename T >
Serializer& operator<<( const std::optional< T >& p )
{
if ( p )
{
return *this << true << p.value();
}
else
{
return *this << false;
}
}
template < typename T >
Serializer& operator<<( const Range< T >& p )
{
return *this << p.start << p.end;
}
template < typename T, std::enable_if_t< std::is_enum< T >::value == true, int > = 0 >
Serializer& operator<<( const T& val )
{
using B = typename std::underlying_type< T >::type;
return *this << B( val );
}
template < typename T, std::enable_if_t< std::is_enum< T >::value == false, int > = 0 >
Serializer& operator<<( const T& val )
{
val.serialize( *this );
return *this;
}
size_t getPosition() const { return size; }
private:
size_t size = 0;
gsl::span< gsl::byte > dst;
bool dryRun;
template < typename T >
Serializer& serializePod( T val )
{
if ( !dryRun )
{
memcpy( dst.data() + size, &val, sizeof( T ) );
}
size += sizeof( T );
return *this;
}
template < typename T >
Serializer& serializeInteger( T val )
{
if ( options.version >= 1 )
{
// Variable-length
if constexpr ( std::is_signed_v< T > )
{
serializeVariableInteger( static_cast< uint64_t >( val >= 0 ? val : -( val + 1 ) ), val < 0 );
}
else
{
serializeVariableInteger( val, {} );
}
return *this;
}
else
{
// Fixed length
return serializePod( val );
}
}
void serializeVariableInteger( uint64_t val, std::optional< bool > sign );
};
class Deserializer : public ByteSerializationBase
{
public:
Deserializer( gsl::span< const gsl::byte > src, SerializerOptions options = {} );
Deserializer( const Bytes& src, SerializerOptions options = {} );
template < typename T >
static T fromBytes( const Bytes& src, SerializerOptions options = {} )
{
T result;
Deserializer s( src, std::move( options ) );
s >> result;
return result;
}
template < typename T >
static T fromBytes( gsl::span< const gsl::byte > src, SerializerOptions options = {} )
{
T result;
Deserializer s( src, std::move( options ) );
s >> result;
return result;
}
template < typename T >
static void fromBytes( T& target, const Bytes& src, SerializerOptions options = {} )
{
Deserializer s( src, std::move( options ) );
s >> target;
}
template < typename T >
static void fromBytes( T& target, gsl::span< const gsl::byte > src, SerializerOptions options = {} )
{
Deserializer s( src, std::move( options ) );
s >> target;
}
Deserializer& operator>>( bool& val ) { return deserializePod( val ); }
Deserializer& operator>>( int8_t& val ) { return deserializeInteger( val ); }
Deserializer& operator>>( uint8_t& val ) { return deserializeInteger( val ); }
Deserializer& operator>>( int16_t& val ) { return deserializeInteger( val ); }
Deserializer& operator>>( uint16_t& val ) { return deserializeInteger( val ); }
Deserializer& operator>>( int32_t& val ) { return deserializeInteger( val ); }
Deserializer& operator>>( uint32_t& val ) { return deserializeInteger( val ); }
Deserializer& operator>>( int64_t& val ) { return deserializeInteger( val ); }
Deserializer& operator>>( uint64_t& val ) { return deserializeInteger( val ); }
Deserializer& operator>>( float& val ) { return deserializePod( val ); }
Deserializer& operator>>( double& val ) { return deserializePod( val ); }
Deserializer& operator>>( std::string& str );
Deserializer& operator>>( String& str );
Deserializer& operator>>( Path& p );
Deserializer& operator>>( gsl::span< gsl::byte > span );
Deserializer& operator>>( Bytes& bytes );
template < typename T >
Deserializer& operator>>( std::vector< T >& val )
{
unsigned int sz;
*this >> sz;
ensureSufficientBytesRemaining( sz ); // Expect at least one byte per vector entry
val.clear();
val.reserve( sz );
for ( unsigned int i = 0; i < sz; i++ )
{
val.push_back( T() );
*this >> val[ i ];
}
return *this;
}
template < typename T, typename U >
Deserializer& operator>>( FlatMap< T, U >& val )
{
unsigned int sz;
*this >> sz;
ensureSufficientBytesRemaining( sz * 2 ); // Expect at least two bytes per map entry
std::vector< std::pair< T, U > > tmpData( sz );
for ( unsigned int i = 0; i < sz; i++ )
{
*this >> tmpData[ i ].first >> tmpData[ i ].second;
}
val = FlatMap< T, U >( boost::container::ordered_unique_range_t(), tmpData.begin(), tmpData.end() );
return *this;
}
template < typename T, typename U >
Deserializer& operator>>( std::map< T, U >& val )
{
unsigned int sz;
*this >> sz;
ensureSufficientBytesRemaining( size_t( sz ) * 2 ); // Expect at least two bytes per map entry
for ( unsigned int i = 0; i < sz; i++ )
{
T key;
U value;
*this >> key >> value;
val[ key ] = std::move( value );
}
return *this;
}
template < typename T, typename U >
Deserializer& operator>>( std::unordered_map< T, U >& val )
{
unsigned int sz;
*this >> sz;
ensureSufficientBytesRemaining( sz * 2 ); // Expect at least two bytes per map entry
for ( unsigned int i = 0; i < sz; i++ )
{
T key;
U value;
*this >> key >> value;
val[ key ] = std::move( value );
}
return *this;
}
template < typename T >
Deserializer& operator>>( std::set< T >& val )
{
unsigned int sz;
*this >> sz;
ensureSufficientBytesRemaining( sz ); // Expect at least one byte per set entry
val.clear();
for ( unsigned int i = 0; i < sz; i++ )
{
T v;
*this >> v;
val.insert( std::move( v ) );
}
return *this;
}
template < typename T >
Deserializer& operator>>( Vector2D< T >& val )
{
*this >> val.x;
*this >> val.y;
return *this;
}
template < typename T >
Deserializer& operator>>( Vector3D< T >& val )
{
*this >> val.x;
*this >> val.y;
*this >> val.z;
return *this;
}
template < typename T >
Deserializer& operator>>( Vector4D< T >& val )
{
*this >> val.x;
*this >> val.y;
*this >> val.z;
*this >> val.w;
return *this;
}
template < typename T >
Deserializer& operator>>( Colour4< T >& val )
{
*this >> val.r;
*this >> val.g;
*this >> val.b;
*this >> val.a;
return *this;
}
template < typename T >
Deserializer& operator>>( Rect2D< T >& val )
{
Vector2D< T > p1, p2;
*this >> p1;
*this >> p2;
val = Rect2D< T >( p1, p2 );
return *this;
}
template < typename T, typename U >
Deserializer& operator>>( std::pair< T, U >& p )
{
return *this >> p.first >> p.second;
}
template < typename T >
Deserializer& operator>>( Range< T >& p )
{
return *this >> p.start >> p.end;
}
template < typename T >
Deserializer& operator>>( std::optional< T >& p )
{
bool present;
*this >> present;
if ( present )
{
T tmp;
*this >> tmp;
p = tmp;
}
else
{
p = std::optional< T >();
}
return *this;
}
template < typename T, std::enable_if_t< std::is_enum< T >::value == true, int > = 0 >
Deserializer& operator>>( T& val )
{
typename std::underlying_type< T >::type tmp;
*this >> tmp;
val = T( tmp );
return *this;
}
template < typename T, std::enable_if_t< std::is_enum< T >::value == false, int > = 0 >
Deserializer& operator>>( T& val )
{
val.deserialize( *this );
return *this;
}
template < typename T >
void peek( T& val )
{
const auto oldPos = pos;
*this >> val;
pos = oldPos;
}
size_t getPosition() const { return pos; }
private:
size_t pos = 0;
gsl::span< const gsl::byte > src;
template < typename T >
Deserializer& deserializePod( T& val )
{
ensureSufficientBytesRemaining( sizeof( T ) );
memcpy( &val, src.data() + pos, sizeof( T ) );
pos += sizeof( T );
return *this;
}
template < typename T >
Deserializer& deserializeInteger( T& val )
{
if ( options.version >= 1 )
{
// Variable-length
bool sign;
uint64_t temp;
deserializeVariableInteger( temp, sign, std::is_signed_v< T > );
if ( sign )
{
int64_t signedTemp = -int64_t( temp ) - 1;
val = static_cast< T >( signedTemp );
}
else
{
val = static_cast< T >( temp );
}
return *this;
}
else
{
// Fixed length
return deserializePod( val );
}
}
void deserializeVariableInteger( uint64_t& val, bool& sign, bool isSigned );
void ensureSufficientBytesRemaining( size_t bytes );
size_t getBytesRemaining() const;
};
} // namespace Halley
| {
"alphanum_fraction": 0.4811283498,
"avg_line_length": 31.0420315236,
"ext": "h",
"hexsha": "608e674d5d353383cae4a95a82d71e75fd7a1701",
"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": "f828b74a6bbe7f172a7dba84e72429d3163bd61c",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "chidddy/halley",
"max_forks_repo_path": "src/engine/utils/include/halley/bytes/byte_serializer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c",
"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": "chidddy/halley",
"max_issues_repo_path": "src/engine/utils/include/halley/bytes/byte_serializer.h",
"max_line_length": 145,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "chidddy/halley",
"max_stars_repo_path": "src/engine/utils/include/halley/bytes/byte_serializer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3936,
"size": 17725
} |
/*! \file SpecialFunctions.h
* \brief header file defining several special functions
This is a work in progress as generally can always call gsl for most of the functions.
*/
#ifndef SPECIALFUNCTIONS_H
#define SPECIALFUNCTIONS_H
#include <iostream>
#include <complex>
#include <Precision.h>
#include <cmath>
#include <gsl/gsl_sf.h>
using namespace std;
namespace Math
{
//factorial
int Factorial(int k);
//Gamma function not yet idependently implemented (using just gsl but if want arbitrary precision must
//implement at some point.
//complete gamma function
//Double_t GammaFunc(Double_t a);
//Calculates the normalized (regularized) upper incomplete gamma function (upper integral).
//Double_t GammaFunc(Double_t a, Double_t x);
//Again same issue with Gamma Functions, not yet implemented for arbitrary precision
//calculates spherical harmonics
//Double_t SphericalHarmonic(Double_t theta, Double_t phi, int l, int m);
//just real component
//Double_t SphericalHarmonicR(Double_t theta, Double_t phi, int l, int m);
//just imaginary component
//Double_t SphericalHarmonicI(Double_t theta, Double_t phi, int l, int m);
}
#endif
| {
"alphanum_fraction": 0.7487394958,
"avg_line_length": 29.75,
"ext": "h",
"hexsha": "dfa66388bc3494d30c5de7556a79309303abc2b8",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-10-23T00:21:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-23T02:58:07.000Z",
"max_forks_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ICRAR/NBodylib",
"max_forks_repo_path": "src/Math/SpecialFunctions.h",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8",
"max_issues_repo_issues_event_max_datetime": "2021-07-27T06:31:03.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-21T16:49:12.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ICRAR/NBodylib",
"max_issues_repo_path": "src/Math/SpecialFunctions.h",
"max_line_length": 107,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ICRAR/NBodylib",
"max_stars_repo_path": "src/Math/SpecialFunctions.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 279,
"size": 1190
} |
#ifndef TNet_Types_h
#define TNet_Types_h
#ifdef HAVE_ATLAS
extern "C"{
#include <cblas.h>
#include <clapack.h>
}
#endif
namespace TNet
{
// TYPEDEFS ..................................................................
#if DOUBLEPRECISION
typedef double BaseFloat;
#else
typedef float BaseFloat;
#endif
#ifndef UINT_16
typedef unsigned short UINT_16 ;
typedef unsigned UINT_32 ;
typedef short INT_16 ;
typedef int INT_32 ;
typedef float FLOAT_32 ;
typedef double DOUBLE_64 ;
#endif
// ...........................................................................
// The following declaration assumes that SSE instructions are enabled
// and that we are using GNU C/C++ compiler, which defines the __attribute__
// notation.
//
// ENABLE_SSE is defined in <config.h>. Its value depends on options given
// in the configure phase of builidng the library
#if defined(__GNUC__ )
// vector of four single floats
typedef float v4sf __attribute__((vector_size(16)));
// vector of two single doubles
typedef double v2sd __attribute__((vector_size(16)));
typedef BaseFloat BaseFloat16Aligned __attribute__((aligned(16))) ;
typedef union
{
v4sf v;
float f[4];
} f4vector;
typedef union
{
v2sd v;
double f[2];
} d2vector;
#endif // ENABLE_SSE && defined(__GNUC__ )
typedef enum
{
#ifdef HAVE_ATLAS
TRANS = CblasTrans,
NO_TRANS = CblasNoTrans
#else
TRANS = 'T',
NO_TRANS = 'N'
#endif
} MatrixTrasposeType;
} // namespace TNet
#endif // #ifndef TNet_Types_h
| {
"alphanum_fraction": 0.5998781973,
"avg_line_length": 20.7848101266,
"ext": "h",
"hexsha": "6a5bfac14b99140720fdfd97be71bada2bee2490",
"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": "0381dcb95d9482c36a24d95af16155da9c12f43d",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "troylee/nnet-asr",
"max_forks_repo_path": "src/KaldiLib/Types.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d",
"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": "troylee/nnet-asr",
"max_issues_repo_path": "src/KaldiLib/Types.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "troylee/nnet-asr",
"max_stars_repo_path": "src/KaldiLib/Types.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 421,
"size": 1642
} |
/*
Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com>
Licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#include <cblas.h>
#include "morn_tensor.h"
void _GetRowData0(float *tdata,float *data,int height,int width,int y_locate,int x_locate)
{
if(y_locate<0) {memset(data,0,width*sizeof(float)); return;}
if(y_locate>=height) {memset(data,0,width*sizeof(float)); return;}
tdata = tdata+y_locate*width;
if(x_locate<0)
{
memset(data,0,(0-x_locate)*sizeof(float));
memcpy(data-x_locate,tdata,(width+x_locate)*sizeof(float));
return;
}
if(x_locate>0)
{
memcpy(data,tdata+x_locate,(width-x_locate)*sizeof(float));
memset(data+width-x_locate,0,x_locate*sizeof(float));
return;
}
memcpy(data,tdata,width*sizeof(float));
}
void _GetRowData(float *tdata,float *data,int height,int width,int y_locate,int x_locate,int stride)
{
if(y_locate<0) {memset(data,0,width/stride*sizeof(float)); return;}
if(y_locate>=height) {memset(data,0,width/stride*sizeof(float)); return;}
tdata = tdata+y_locate*width;
int i=x_locate;int n=0;
for(;i<0 ;i+=stride) {data[n]=0; n++;}
for(;i<MIN(width,width+x_locate);i+=stride) {data[n]=tdata[i];n++;}
for(;i<width+x_locate ;i+=stride) {data[n]=0; n++;}
}
void _SetRowData(float *tdata,float *data,int height,int width,int y_locate,int x_locate,int stride)
{
if(y_locate<0) return;
if(y_locate>=height) return;
tdata = tdata+y_locate*width;
int i=x_locate;int n=0;
for(;i<0 ;i+=stride) { n++;}
for(;i<MIN(width,width+x_locate);i+=stride) {tdata[i]+=data[n];n++;}
//for(;i<width+x_locate ;i+=stride) { n++;}
}
void ConvTensorToMatData0(MTensor *tns,int bc,float *mdata,int knl_height,int knl_width)
{
int height = tns->height;
int width = tns->width;
int channel= tns->channel;
// int mheight= knl_height*knl_width*channel+1;
int mwidth = width*height;
int x1=0-(knl_width /2);int x2=x1+knl_width -1;
int y1=0-(knl_height/2);int y2=y1+knl_height-1;
float *tdata = tns->data[bc];
for(int c=0;c<channel;c++)
{
int k=0;
{
for(int i=x1;i<=x2;i++)
{
float *data = mdata + k*mwidth;k++;
for(int n=y1;n<y1+height;n++)
{
_GetRowData0(tdata,data,height,width,n,i);
data+=width;
}
}
}
for(int j=y1+1+height-1;j<=y2+height-1;j++)
{
for(int i=x1;i<=x2;i++)
{
float *data = mdata + k*mwidth;k++;
memcpy(data,data-knl_width*mwidth+width,(mwidth-width)*sizeof(float));
_GetRowData0(tdata,data+(mwidth-width),height,width,j,i);
}
}
tdata+=width*height;
mdata+=mwidth*knl_height*knl_width;
}
for(int i=0;i<mwidth;i++) mdata[i]=1.0;
}
void ConvTensorToMatData(MTensor *tns,int bc,float *mdata,int knl_height,int knl_width,int y_stride,int x_stride)
{
if((x_stride==1)&&(y_stride==1)) {ConvTensorToMatData0(tns,bc,mdata,knl_height,knl_width);return;}
int height = tns->height;
int width = tns->width;
int channel= tns->channel;
int out_width = width/x_stride;
int out_height=height/y_stride;
// int mheight= knl_height*knl_width*channel+1;
int mwidth = out_width*out_height;
int x1=0-(knl_width /2);int x2=x1+knl_width -1;
int y1=0-(knl_height/2);int y2=y1+knl_height-1;
float *tdata = tns->data[bc];
for(int c=0;c<channel;c++)
{
int k=0;
for(int j=y1;j<=y2;j++)for(int i=x1;i<=x2;i++)
{
float *data = mdata + k*mwidth;k++;
for(int n=j;n<j+height;n+=y_stride)
{
_GetRowData(tdata,data,height,width,n,i,x_stride);
data+=out_width;
}
}
tdata+=width*height;
mdata+=mwidth*knl_height*knl_width;
}
for(int i=0;i<mwidth;i++) mdata[i]=1.0;
}
void ConvMatDataToTensor(float *mdata,MTensor *tns,int bc,int knl_height,int knl_width,int y_stride,int x_stride)
{
int height = tns->height;
int width = tns->width;
int channel= tns->channel;
int out_width = width/x_stride;
int out_height=height/y_stride;
// int mheight= knl_height*knl_width*channel+1;
int mwidth = out_height*out_width;
// printf("height=%d,width=%d,channel=%d,out_height=%d,out_width=%d\n",height,width,channel,out_height,out_width);
int x1=0-(knl_width /2);int x2=x1+knl_width -1;
int y1=0-(knl_height/2);int y2=y1+knl_height-1;
float *tdata = tns->data[bc];
for(int c=0;c<channel;c++)
{
int k=0;
for(int j=y1;j<=y2;j++)for(int i=x1;i<=x2;i++)
{
float *data = mdata + k*mwidth;k++;
for(int n=j;n<j+height;n+=y_stride)
{
_SetRowData(tdata,data,height,width,n,i,x_stride);
data+=out_width;
}
}
tdata+=width*height;
mdata+=mwidth*knl_height*knl_width;
}
}
struct TensorConvPara
{
MLayer *prev;
int knl_num;
int knl_height;
int knl_width;
int x_stride;
int y_stride;
int res_valid;
float rate;
float decay;
float momentum;
};
void *mTensorConvPara(MFile *ini,char *name)
{
struct TensorConvPara *para = (struct TensorConvPara *)mMalloc(sizeof(struct TensorConvPara));
para->prev = mNetworkLayer(ini,mINIRead(ini,name,"prev"));
mException((para->prev == NULL),EXIT,"invalid prev");
para->res_valid = (strcmp("Input",mLayerType(para->prev))!=0);
para->knl_num = 1; mINIRead(ini,name,"knl_num" ,"%d",&(para->knl_num ));
para->knl_height= 1; mINIRead(ini,name,"knl_height","%d",&(para->knl_height));
para->knl_width = 1; mINIRead(ini,name,"knl_width" ,"%d",&(para->knl_width ));
para->x_stride = 1; mINIRead(ini,name,"x_stride" ,"%d",&(para->x_stride ));
para->y_stride = 1; mINIRead(ini,name,"y_stride" ,"%d",&(para->y_stride ));
para->rate =0.001;if(mINIRead(ini,name,"rate" ,"%f",&(para->rate ))==NULL) mINIRead(ini,"para","rate" ,"%f",&(para->rate ));
para->momentum=0.9 ;if(mINIRead(ini,name,"momentum","%f",&(para->momentum))==NULL) mINIRead(ini,"para","momentum","%f",&(para->momentum));
para->decay =0.01 ;if(mINIRead(ini,name,"decay" ,"%f",&(para->decay ))==NULL) mINIRead(ini,"para","decay" ,"%f",&(para->decay ));
mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,"invalid para decay");
return para;
}
struct HandleTensorConv
{
float *mat;
float *kernel;
float *update;
};
void endTensorConv(void *info)
{
struct HandleTensorConv *handle = (struct HandleTensorConv *)info;
if(handle->mat != NULL) mFree(handle->mat);
if(handle->kernel!= NULL) mFree(handle->kernel);
if(handle->update!= NULL) mFree(handle->update);
}
#define HASH_TensorConv 0x9087d39c
void TensorConvSet(MLayer *layer)
{
if(layer->state != DFLT) return;
// mException(strcmp("Conv",mLayerType(layer)),EXIT,"invalid layer type");
struct TensorConvPara *para = (struct TensorConvPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *res= para->prev->res;
MTensor *out= layer->tns;
MHandle *hdl=mHandle(out,TensorConv);
struct HandleTensorConv *handle = (struct HandleTensorConv *)(hdl->handle);
int out_height= in->height/para->y_stride;
int out_width = in->width /para->x_stride;
int mwidth = (out_height*out_width);
int mheight= para->knl_height*para->knl_width*in->channel+1;
int data_size = para->knl_num*mheight;
mTensorRedefine(out,in->batch,para->knl_num,out_height,out_width,NULL);
if(morn_network_flag == MORN_TRAIN)
{
if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data);
else
{
// printf("llllllllllllllllllllllllll layer->name=%s\n",layer->name);
mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);
}
if(morn_network_flag==MORN_TRAIN)
{
if(handle->update != NULL) mFree(handle->update);
handle->update =(float *)mMalloc(data_size*sizeof(float));
memset(handle->update,0,data_size*sizeof(float));
}
}
if(handle->kernel !=NULL) mFree(handle->kernel);
handle->kernel = (float *)mMalloc(data_size*sizeof(float));
if(morn_network_parafile==NULL)
{
float scale = sqrt(2.0f/mheight);
for(int i=0;i<data_size;i++)
handle->kernel[i] = mNormalRand(0.0f,1.0f)*scale;
}
else
{
mNetworkParaRead(layer,"kernel",handle->kernel,data_size*sizeof(float));
}
if(handle->mat!=NULL) mFree(handle->mat);
handle->mat = (float *)mMalloc(mheight*mwidth*sizeof(float));
hdl->valid = 1;
}
void mTensorConvForward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
struct TensorConvPara *para = (struct TensorConvPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *out=layer->tns;
// printf("in->data[0][0]=%f\n",in->data[0][0]);
TensorConvSet(layer);
MHandle *hdl=mHandle(out,TensorConv);
struct HandleTensorConv *handle = (struct HandleTensorConv *)(hdl->handle);
int mwidth = (out->height*out->width);
int mheight= para->knl_height*para->knl_width*in->channel+1;
float *kernel_data= handle->kernel;
float *in_data = handle->mat;
for(int b=0;b<in->batch;b++)
{
// printf("ccccccccccccccc in->width=%d\n",in->width);
ConvTensorToMatData(in,b,in_data,para->knl_height,para->knl_width,para->y_stride,para->x_stride);
// printf("ccccccccccccccc in->width=%d\n",in->width);
float *out_data = out->data[b];
// printf("\nweight=\n");for(int ii=0;ii<100;ii++) printf("%f,",kernel_data[ii]);
// printf("\ndata=\n");for(int ii=0;ii<100;ii++) printf("%f,",in_data[ii]*255);
// printf("\ndata2352=\n");for(int ii=2352;ii<2352+100;ii++) printf("%f,",in_data[ii]*255);
// printf("\ndata6272=\n");for(int ii=6272;ii<6272+100;ii++) printf("%f,",in_data[ii]*255);
// printf("\ndata10192=\n");for(int ii=10192;ii<10192+100;ii++) printf("%f,",in_data[ii]*255);
// printf("\ndata=\n");for(int ii=784*5;ii<784*5+100;ii++) printf("%f,",in_data[ii]*255);
// printf("\ndata=\n");for(int ii=784*25;ii<784*25+100;ii++) printf("%f,",in_data[ii]*255);
// printf("\ndata=\n");for(int ii=10000;ii<10000+100;ii++) printf("%f,",in_data[ii]*255);
// float sum=0;
// for(int ii=0;ii<75;ii++)
// {
// sum+=(kernel_data[ii]*in_data[mwidth*ii]);
// printf("a[ii]=%f,b[n*ii]=%f,sum=%f,ii=%d,ii*mwidth=%d\n",kernel_data[ii],in_data[mwidth*ii]*255,sum,ii,ii*mwidth);
// }
// printf("\nsum=%f\n",sum);
// printf("para->knl_num=%d,mwidth=%d,mheight=%d\n",para->knl_num,mwidth,mheight);
cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,
para->knl_num,mwidth,mheight,
1.0f,
kernel_data,mheight,
in_data,mwidth,
0.0f, out_data,mwidth);
// printf("\nout=\n");for(int ii=00;ii<200;ii++) printf("%f,",out_data[ii]);
}
layer->state = MORN_FORWARD;
}
void mTensorConvBackward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
struct TensorConvPara *para = (struct TensorConvPara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *res= para->prev->res;
MTensor *out=layer->res;
MHandle *hdl=mHandle(layer->tns,TensorConv);
struct HandleTensorConv *handle = (struct HandleTensorConv *)(hdl->handle);
mException((hdl->valid == 0),EXIT,"no forward operate");
int mwidth = (out->height*out->width);
int mheight= para->knl_height*para->knl_width*in->channel+1;
float *kernel_data= handle->kernel;
float *update_data= handle->update;
float * in_data= handle->mat;
float * res_data= handle->mat;
mNetworkParaWrite(layer,"kernel",kernel_data,para->knl_num*mheight*sizeof(float));
float beta = para->momentum;
for(int b=0;b<out->batch;b++)
{
ConvTensorToMatData(in,b,in_data,para->knl_height,para->knl_width,para->y_stride,para->x_stride);
float *out_data = out->data[b];
// printf("m=%d,n=%d,k=%d\n",para->knl_num,mheight,mwidth);
// printf("\ndelta=\n");for(int ii=00;ii<200;ii++) printf("%f,",0-2*out_data[ii]);
// printf("\nin=\n");for(int ii=00;ii<200;ii++) printf("%f,",in_data[ii]);
// printf("\nupdate0=\n");for(int ii=00;ii<75;ii++) printf("%f,",0-update_data[ii]*2*beta);
cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,
para->knl_num,mheight,mwidth,
1.0f,//1.0f/mwidth,
out_data,mwidth,
in_data,mwidth,
beta,
update_data,mheight);
// printf("\nupdate1=\n");for(int ii=00;ii<75;ii++) printf("%f,",0-update_data[ii]*2);
// printf("\nupdate=\n");for(int ii=760;ii<760+75;ii++) printf("%f,",update_data[ii]);
// printf("\nbias_updates=\n");for(int ii=0;ii<32;ii++) printf("%f,",update_data[ii*76+75]);
beta = 1.0;
}
// for(int i=0;i<28;i++)printf("%f,",in_data[i]);printf("\n");
// for(int i=0;i<8;i++) printf("%f,",kernel_data[i]);
// printf("aaaaaaaaaaa,para->knl_num=%d,mwidth=%d\n",para->knl_num,mwidth);
if(para->res_valid)
{
// if(para->prev->state == MORN_FORWARD)
// {
// printf("conv res set 0,conv res set 0,conv res set 0,conv res set 0,conv res set 0res->batch=%d\n",res->batch);
// for(int b=0;b<res->batch;b++)
// }
for(int b=0;b<in->batch;b++)
{
float *out_data = out->data[b];
if(para->prev->state == MORN_FORWARD)
memset(res->data[b],0,in->height*in->width*in->channel*sizeof(float));
// printf("\nconvdelta=\n");for(int ii=200;ii<400;ii++) printf("%f,",out_data[ii]);
// printf("\nconvkernel=\n");for(int ii=00;ii<200;ii++) printf("%f,",kernel_data[ii]);
cblas_sgemm(CblasRowMajor,CblasTrans,CblasNoTrans,
mheight,mwidth,para->knl_num,
1.0f,
kernel_data,mheight,
out_data,mwidth,
0.0, res_data,mwidth);
// printf("\nconvdeltaout=\n");for(int ii=00;ii<200;ii++) printf("%f,",0-res_data[ii]*2);
ConvMatDataToTensor(res_data,res,b,para->knl_height,para->knl_width,para->y_stride,para->x_stride);
// printf("mheight=%d,mwidth=%d\n",mheight,mwidth);
// printf("\nconvimd=\n");for(int ii=200;ii<400;ii++) printf("%f,",res->data[0][ii]);
}
para->prev->state = MORN_BACKWARD;
}
// printf("\nkernel_data0=\n");for(int ii=0;ii<200;ii++) printf("%f,",kernel_data[ii]);
// printf("\nupdate_data=\n");for(int ii=0;ii<200;ii++) printf("%f,",update_data[ii]);
// printf("%s:update_data=%f,kernel_data=%f,%f\n",layer->name,update_data[10],kernel_data[10],kernel_data[10]-(para->rate/(float)(in->batch))*update_data[10]);
cblas_saxpby(para->knl_num*mheight,
(0.0f-(para->rate/(float)(in->batch))),update_data,1,
(1.0f-(para->decay*para->rate)) ,kernel_data,1);
// printf("\nkernel_data1=\n");for(int ii=0;ii<200;ii++) printf("%f,",kernel_data[ii]);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
void GroupConvTensorToMatData(MTensor *tns,int bc,float *mdata,int knl_channel,int knl_height,int knl_width,int c_stride,int y_stride,int x_stride)
{
int height = tns->height;
int width = tns->width;
int channel= tns->channel;
int out_width = width/x_stride;
int out_height = height/y_stride;
int out_channel=(channel-knl_channel/2+1)/c_stride;
int mwidth = knl_height*knl_width*knl_channel+1;
int mheight= out_height*out_width;
int x0=(width -(out_width -1)*x_stride)/2;
int y0=(height-(out_height-1)*y_stride)/2;
float *tdata = tns->data[bc];
int tsize = tns->height*tns->width;
int k,i,j,c;
for(k=0;k<out_channel;k++)
{
for(j=0;j<out_width;j++)
{
int n=y0 -knl_height/2;
int m=x0+j*x_stride-knl_width /2;
for(i=0;i<mwidth-1;i+=knl_channel)
{
int h= i/(knl_width*knl_channel) +n;if(h<0)h=0;else if(h>=height)h=height-1;
int w=(i%(knl_width*knl_channel))/knl_channel+m;if(w<0)w=0;else if(w>= width)w= width-1;
for(c=0;c<knl_channel;c++)
mdata[(k*mheight+j)*mwidth+i+c]=tdata[MIN((c+k*c_stride),channel-1)*tsize+h*width+w];
}
mdata[(k*mheight+j)*mwidth+mwidth-1]=1.0f;
}
for(j=out_width;j<mheight;j++)
{
int num=MAX(0,(knl_height-y_stride))*knl_width*knl_channel;
if(num>0) memcpy(mdata+(k*mheight+j)*mwidth,mdata+((k*mheight+j)-out_width)*mwidth+y_stride*knl_width*knl_channel,num*sizeof(float));
int n=y0+j/out_width*y_stride-knl_height/2;
int m=x0+j%out_width*x_stride-knl_width /2;
for(i=num;i<mwidth-1;i+=knl_channel)
{
int h= i/(knl_width*knl_channel) +n;if(h<0)h=0;else if(h>=height)h=height-1;
int w=(i%(knl_width*knl_channel))/knl_channel+m;if(w<0)w=0;else if(w>= width)w= width-1;
for(c=0;c<knl_channel;c++)
mdata[(k*mheight+j)*mwidth+i+c]=tdata[MIN((c+k*c_stride),channel-1)*tsize+h*width+w];
}
mdata[(k*mheight+j)*mwidth+mwidth-1]=1.0f;
}
}
}
void GroupConvMatDataToTensor(float *mdata,MTensor *tns,int bc,int knl_channel,int knl_height,int knl_width,int c_stride,int y_stride,int x_stride)
{
int height = tns->height;
int width = tns->width;
int channel= tns->channel;
int out_width = width/x_stride;
int out_height=height/y_stride;
int out_channel=(channel-knl_channel/2+1)/c_stride;
int mwidth = knl_height*knl_width*knl_channel+1;
int mheight= out_height*out_width;
int x0=(width -(out_width -1)*x_stride)/2;
int y0=(height-(out_height-1)*y_stride)/2;
float *tdata = tns->data[bc];
int tsize = tns->height*tns->width;
int k,i,j,c;
for(k=0;k<out_channel;k++)for(j=0;j<mheight;j++)
{
int n=y0+j/out_width*y_stride+knl_height/2+1-knl_height;
int m=x0+j%out_width*x_stride+knl_width /2+1-knl_width ;
for(i=0;i<mwidth-1;i+=knl_channel)
{
int h= i/(knl_width*knl_channel) +n;if(h<0)h=0;else if(h>=height)h=height-1;
int w=(i%(knl_width*knl_channel))/knl_channel+m;if(w<0)w=0;else if(w>= width)w= width-1;
for(c=0;c<knl_channel;c++)
tdata[MIN((c+k*c_stride),channel-1)*tsize+h*width+w]+=mdata[(k*mheight+j)*mwidth+i+c];
}
}
}
struct TensorGroupConvPara
{
MLayer *prev;
int knl_num;
int knl_height;
int knl_width;
int x_stride;
int y_stride;
int res_valid;
float rate;
float decay;
float momentum;
int knl_channel;
int c_stride;
};
void *mTensorGroupConvPara(MFile *ini,char *name)
{
struct TensorGroupConvPara *para = (struct TensorGroupConvPara *)mMalloc(sizeof(struct TensorConvPara));
char *value = mINIRead(ini,name,"prev");
para->prev = mNetworkLayer(ini,value);
mException((para->prev == NULL),EXIT,"invalid prev");
para->res_valid = (strcmp("Input",mLayerType(para->prev))!=0);
value = mINIRead(ini,name,"knl_num");
if(value != NULL) para->knl_num= atoi(value);else para->knl_num= 1;
value = mINIRead(ini,name,"knl_channel");
if(value != NULL) para->knl_channel= atoi(value);else para->knl_channel= DFLT;
value = mINIRead(ini,name,"knl_height");
if(value != NULL) para->knl_height= atoi(value);else para->knl_height= 1;
value = mINIRead(ini,name,"knl_width");
if(value != NULL) para->knl_width= atoi(value);else para->knl_width= 1;
value = mINIRead(ini,name,"c_stride");
if(value != NULL) para->c_stride= atoi(value);else para->c_stride= para->knl_channel;
value = mINIRead(ini,name,"x_stride");
if(value != NULL) para->x_stride= atoi(value);else para->x_stride= 1;
value = mINIRead(ini,name,"y_stride");
if(value != NULL) para->y_stride= atoi(value);else para->y_stride= 1;
value = mINIRead(ini,name,"rate");
if(value != NULL) para->rate = atof(value);
else
{
value = mINIRead(ini,"para","rate");
if(value != NULL) para->rate = atof(value);
else para->rate = 0.001;
}
value = mINIRead(ini,name,"decay");
if(value != NULL) para->decay = atof(value);
else
{
value = mINIRead(ini,"para","decay");
if(value != NULL) para->decay = atof(value);
else para->decay = 0.01;
}
mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,"invalid para decay");
value = mINIRead(ini,name,"momentum");
if(value != NULL) para->momentum = atof(value);
else
{
value = mINIRead(ini,"para","momentum");
if(value != NULL) para->momentum = atof(value);
else para->momentum = 0.9;
}
return para;
}
struct HandleTensorGroupConv
{
float *mat;
float *kernel;
float *update;
};
void endTensorGroupConv(void *info)
{
struct HandleTensorGroupConv *handle = (struct HandleTensorGroupConv *)info;
if(handle->mat != NULL) mFree(handle->mat);
if(handle->kernel!= NULL) mFree(handle->kernel);
if(handle->update!= NULL) mFree(handle->update);
}
#define HASH_TensorGroupConv 0x82866393
void TensorGroupConvSet(MLayer *layer)
{
if(layer->state != DFLT) return;
struct TensorGroupConvPara *para = (struct TensorGroupConvPara *)(layer->para);
if(para->knl_channel<=0)
{
layer->type_index=mTensorRegisterIndex("Conv");
return;
}
MTensor *in = para->prev->tns;
MTensor *res= para->prev->res;
MTensor *out= layer->tns;
MHandle *hdl=mHandle(out,TensorGroupConv);
struct HandleTensorGroupConv *handle = (struct HandleTensorGroupConv *)(hdl->handle);
int out_height= in->height/para->y_stride;
int out_width = in->width /para->x_stride;
int out_channel=(in->channel-para->knl_channel/2+1)/para->c_stride;
int mheight = (out_height*out_width*out_channel);
int mwidth = para->knl_height*para->knl_width*para->knl_channel+1;
int data_size = para->knl_num*mwidth;
mTensorRedefine(out,in->batch,para->knl_num*out_channel,out_height,out_width,NULL);
if(morn_network_flag == MORN_TRAIN)
{
if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data);
else mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);
if(handle->update != NULL) mFree(handle->update);
handle->update =(float *)mMalloc(data_size*sizeof(float));
memset(handle->update,0,data_size*sizeof(float));
}
if(handle->kernel !=NULL) mFree(handle->kernel);
handle->kernel = (float *)mMalloc(data_size*sizeof(float));
if(morn_network_parafile==NULL)
{
float scale = sqrt(2.0f/mwidth);
for(int i=0;i<data_size;i++)
handle->kernel[i] = scale*mNormalRand(0.0f,1.0f);
}
else
{
mNetworkParaRead(layer,"kernel",handle->kernel,data_size*sizeof(float));
}
if(handle->mat!=NULL) mFree(handle->mat);
handle->mat = (float *)mMalloc(mheight*mwidth*sizeof(float));
hdl->valid = 1;
}
void mTensorGroupConvForward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
struct TensorGroupConvPara *para = (struct TensorGroupConvPara *)(layer->para);
if(para->knl_channel<=0) return mTensorConvForward(layer);
mException(strcmp("GroupConv",mLayerType(layer)),EXIT,"invalid layer type");
MTensor *in = para->prev->tns;
MTensor *out=layer->tns;
TensorGroupConvSet(layer);
MHandle *hdl=mHandle(out,TensorGroupConv);
struct HandleTensorGroupConv *handle = (struct HandleTensorGroupConv *)(hdl->handle);
int out_channel=(in->channel-para->knl_channel/2+1)/para->c_stride;
int mheight = (out->height*out->width*out_channel);
int mwidth = para->knl_height*para->knl_width*para->knl_channel+1;
float *kernel_data= handle->kernel;
float *in_data = handle->mat;
for(int b=0;b<in->batch;b++)
{
GroupConvTensorToMatData(in,b,in_data,para->knl_channel,para->knl_height,para->knl_width,para->c_stride,para->y_stride,para->x_stride);
float *out_data = out->data[b];
in_data[mwidth-1]=1.0f;
cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasTrans,
para->knl_num,mheight,mwidth,
1.0f,
kernel_data,mwidth,
in_data,mwidth,
0.0f, out_data,mheight);
}
layer->state = MORN_FORWARD;
}
void mTensorGroupConvBackward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
struct TensorGroupConvPara *para = (struct TensorGroupConvPara *)(layer->para);
if(para->knl_channel<=0) return mTensorConvBackward(layer);
mException(strcmp("GroupConv",mLayerType(layer)),EXIT,"invalid layer type");
MTensor *in = para->prev->tns;
MTensor *res= para->prev->res;
MTensor *out=layer->res;
MHandle *hdl=mHandle(layer->tns,TensorGroupConv);
struct HandleTensorGroupConv *handle = (struct HandleTensorGroupConv *)(hdl->handle);
mException((hdl->valid == 0),EXIT,"no forward operate");
int out_channel=(in->channel-para->knl_channel/2+1)/para->c_stride;
int mheight = (out->height*out->width*out_channel);
int mwidth = para->knl_height*para->knl_width*para->knl_channel+1;
float *kernel_data= handle->kernel;
float *update_data= handle->update;
float * in_data= handle->mat;
float * res_data= handle->mat;
mNetworkParaWrite(layer,"kernel",kernel_data,para->knl_num*mwidth*sizeof(float));
for(int b=0;b<in->batch;b++)
{
GroupConvTensorToMatData(in,b,in_data,para->knl_channel,para->knl_height,para->knl_width,para->c_stride,para->y_stride,para->x_stride);
float *out_data = out->data[b];
in_data[mwidth-1]=1.0f;
cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,
para->knl_num,mwidth,mheight,
1.0f,
out_data,mheight,
in_data,mwidth,
(b==0)?para->momentum:1.0f,
update_data,mwidth);
}
cblas_saxpby(para->knl_num*mwidth,
(0.0f-(para->rate/(float)(in->batch))),update_data,1,
(1.0f-(para->rate*para->decay)) ,kernel_data,1);
if(para->res_valid==0) return;
if(para->prev->state == MORN_FORWARD)
{
for(int b=0;b<res->batch;b++)
memset(res->data[b],0,in->height*in->width*in->channel*sizeof(float));
para->prev->state = MORN_BACKWARD;
}
for(int b=0;b<in->batch;b++)
{
float *out_data = out->data[b];
cblas_sgemm(CblasRowMajor,CblasTrans,CblasNoTrans,
mheight,mwidth,para->knl_num,
1.0f,
out_data,mheight,
kernel_data,mwidth,
0.0, res_data,mwidth);
GroupConvMatDataToTensor(res_data,res,b,para->knl_channel,para->knl_height,para->knl_width,para->c_stride,para->y_stride,para->x_stride);
}
} | {
"alphanum_fraction": 0.5935454984,
"avg_line_length": 37.1278772379,
"ext": "c",
"hexsha": "e3ecdae8d493f4c18049a05c1fa17043811df667",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-06-23T08:08:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-23T08:08:02.000Z",
"max_forks_repo_head_hexsha": "fa4f0aae3d7c22f8643665c4bc1297b14b50c9d0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Shaka0723/Morn",
"max_forks_repo_path": "src/deep_learning/morn_tensor_conv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fa4f0aae3d7c22f8643665c4bc1297b14b50c9d0",
"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": "Shaka0723/Morn",
"max_issues_repo_path": "src/deep_learning/morn_tensor_conv.c",
"max_line_length": 501,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "fa4f0aae3d7c22f8643665c4bc1297b14b50c9d0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Shaka0723/Morn",
"max_stars_repo_path": "src/deep_learning/morn_tensor_conv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8520,
"size": 29034
} |
/**
*/
#include <math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_multiroots.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
#include "spc_trace_functions.h"
#include "disp_conf.h"
#include "trace_conf.h"
#include "crossdisp_utils.h"
/*
* Function: print_state
* The function prints a status report
* on a multi-dimensional root finding
* solver onto the screen
*
* Parameters:
* @param iter - the iteration number
* @param s - the multi-d solver
*/
void print_state (size_t iter, gsl_multiroot_fsolver *s)
{
printf ("iter = %3zu x = % .3f % .3f "
"f(x) = % .3e % .3e\n",
iter,
gsl_vector_get (s->x, 0),
gsl_vector_get (s->x, 1),
gsl_vector_get (s->f, 0),
gsl_vector_get (s->f, 1));
// print: current x-value, y-value, x-error, y-error
}
/*
* Function: drizzle_distort
* This function can be passed to a gsl multi-d function.
* It defines the function:
* x'=f'(x,y) = f(x,y)-x_0
* y'=g'(x,y) = g(x,y)-y_0
* with f(x,y) and g(x,y) the equations to undistort
* the coordinates x and y, respectively and the
* constants x_0 and y_0.
* Solving for f'(x,y)=g'(x,y)=0.0
* means to find (x,y) such that
* f(x,y) = x_0 and g(x,y) = y_0.
*
* Parameters:
* @param x - the input x,y
* @param params - the parameters for the function
* @param f - the result values in x,y
*
* Returns:
* @return GSL_SUCCESS - always
*/
int
drizzle_distort(const gsl_vector * x, void *params, gsl_vector * f)
{
// extract the components from the parameter-structure
gsl_matrix *coeffs = ((drz_pars *) params)->coeffs;
px_point npixels = ((drz_pars *) params)->npixels;
d_point offset = ((drz_pars *) params)->offset;
d_point xy_in;
d_point xy_out;
// extract the input
xy_in.x = gsl_vector_get(x,0);
xy_in.y = gsl_vector_get(x,1);
// undistort the input
xy_out = get_drz_position(xy_in, coeffs, npixels);
// subtract the input
xy_out.x = xy_out.x-offset.x;
xy_out.y = xy_out.y-offset.y;
// set the output
gsl_vector_set(f, 0, xy_out.x);
gsl_vector_set(f, 1, xy_out.y);
// return always the same
return GSL_SUCCESS;
}
/*
* Function: distort_point
* The function finds the distorted coordinates
* for a given undistorted coordinate and the
* transformations to get the undistorted coordinates.
* This function makes the inverse transformation
* to the drizzle transformation.
*
* Parameters:
* @param coeffs - the drizzle coefficients
* @param pixmax - the image dimensions
* @param xy_image - the undistorted (x,y)
*
* Returns:
* @return xy_ret - the distorted (x,y)
*/
d_point
distort_point(gsl_matrix *coeffs, const px_point pixmax, d_point xy_image)
{
const gsl_multiroot_fsolver_type *msolve_type;
gsl_multiroot_fsolver *msolve;
int status;
size_t iter = 0;
//const size_t n = 2;
gsl_multiroot_function mult_func;
drz_pars *drzpars;
gsl_vector *xy_in = gsl_vector_alloc(2);
gsl_vector *xy_out = gsl_vector_alloc(2);
d_point xy_ret;
// set up the parameters for the
// multi-d function
drzpars = (drz_pars *) malloc(sizeof(drz_pars));
drzpars->coeffs = coeffs;
drzpars->offset = xy_image;
drzpars->npixels = pixmax;
// set up the multi-d function
mult_func.f = &drizzle_distort;
mult_func.n = 2;
mult_func.params = drzpars;
// set the starting coordinates
gsl_vector_set(xy_in, 0, xy_image.x);
gsl_vector_set(xy_in, 1, xy_image.y);
// allocate and initialize the multi-d solver
msolve_type = gsl_multiroot_fsolver_dnewton;
msolve = gsl_multiroot_fsolver_alloc (msolve_type, 2);
gsl_multiroot_fsolver_set (msolve, &mult_func, xy_in);
// print_state (iter, msolve);
// iterate
do
{
// count the number of iterations
iter++;
// do an iteration
status = gsl_multiroot_fsolver_iterate (msolve);
// print_state (iter, msolve);
// check if solver is stuck
if (status)
break;
// evaluate the iteration
status = gsl_multiroot_test_residual (msolve->f, 1e-7);
}
while (status == GSL_CONTINUE && iter < 1000);
// chek for the break conditions
// transfer the result to the return struct
xy_ret.x = gsl_vector_get(msolve->x,0);
xy_ret.y = gsl_vector_get(msolve->x,1);
// deallocate the different structures
gsl_multiroot_fsolver_free (msolve);
gsl_vector_free(xy_in);
gsl_vector_free(xy_out);
// return the result
return xy_ret;
}
/*
* Function: undistort_point
*
* Parameters:
* @param coeffs - the drizzle coefficients
* @param pixmax - the image dimensions
* @param xy_image - the undistorted (x,y)
*
* Returns:
* @return xy_new - the undistorted (x,y)
*/
d_point
undistort_point(gsl_matrix *coeffs, const px_point pixmax, d_point xy_image)
{
d_point xy_new;
xy_new = get_drz_position(xy_image, coeffs, pixmax);
return xy_new;
}
/*
* Function: get_crossdisp_matrix
* The function extracts the drizzle coefficients stored in the
* keyword headers of an image extension and creates a matrix
* to store those coefficients. The matrix is returned.
* Currently the drizzle coefficients are ALWAYS stored in the
* primary header of the grism images. For this reason
* all keywords are read from extension '1' (hardcoded).
*
* Parameters:
* @param filename - the image filename
* @param sci_numext - the extension number
*
* Returns:
* @return ret - the matrix with the drizzle coefficients
*/
gsl_matrix *
get_crossdisp_matrix(char * filename, int sci_numext)
{
int ncoeffs;
int i;
gsl_matrix * ret;
//px_point pixmax;
char templt[FLEN_CARD];
float acoeff, tmp;
// get the number of coefficients
tmp = get_float_from_keyword(filename, 1, "DRZCNUM");
// tmp = get_float_from_keyword(filename, sci_numext, "DRZCNUM");
if (isnan(tmp)){
// in case that the keyword does not exist,
// find a nice way out of the door
aXe_message(aXe_M_FATAL, __FILE__, __LINE__,
"Could not find drizzle keywords in: %s\n", filename);
ret = gsl_matrix_alloc(1,1);
gsl_matrix_set(ret, 0,0,GSL_NAN);
return ret;
}
else {
// cast the value to int
ncoeffs = (int)tmp;
}
// allocate the matrix, set it to the default
ret = gsl_matrix_alloc(2,ncoeffs);
gsl_matrix_set_all (ret, 0.0);
// go over the number of coefficients
for (i=0; i<ncoeffs; i++){
// set the name for the x-coefficient, get it and store it
sprintf (templt, "DRZ%1iX%02i", sci_numext, i+1);
// acoeff = get_float_from_keyword(filename, sci_numext, templt);
acoeff = get_float_from_keyword(filename, 1, templt);
gsl_matrix_set(ret, 0,i,acoeff);
// set the name for the y-coefficient, get it and store it
sprintf (templt, "DRZ%1iY%02i", sci_numext, i+1);
// acoeff = get_float_from_keyword(filename, sci_numext, templt);
acoeff = get_float_from_keyword(filename, 1, templt);
gsl_matrix_set(ret, 1,i,acoeff);
}
// return the matrix
return ret;
}
/*
* Function: get_axis_scales
* The function computes the distance scale along the major and
* minor half axis of an object. The distance scale is subject
* to changes due to the image distortion.
*
* Parameters:
* @param actbeam - the beam to get the drizzle scales for
* @param drzcoeffs - the drizzle coefficients
* @param pixmax - the image dimensions
*
* Returns:
* @return ret - the drizzle scales along major and minor half axis
*/
d_point
get_axis_scales(beam actbeam, gsl_matrix * drzcoeffs, px_point pixmax){
d_point dispnt;
d_point drz_ref;
d_point drz_dis;
d_point ret;
// find a dummy point along the major half axis
dispnt.x = actbeam.refpoint.x + cos(actbeam.aorient);
dispnt.y = actbeam.refpoint.y + sin(actbeam.aorient);
// compute the undistorted coos for the refpoint
drz_ref = get_drz_position(actbeam.refpoint, drzcoeffs, pixmax);
// compute the undistorted coos for the dummy point
drz_dis = get_drz_position(dispnt, drzcoeffs, pixmax);
// compute the scale along the major axis
ret.x = sqrt((drz_ref.x-drz_dis.x)*(drz_ref.x-drz_dis.x) +
(drz_ref.y-drz_dis.y)*(drz_ref.y-drz_dis.y));
// find a dummy point along the minor half axis
dispnt.x = actbeam.refpoint.x + cos(actbeam.aorient + M_PI/2.0);
dispnt.y = actbeam.refpoint.y + sin(actbeam.aorient + M_PI/2.0);
// compute the undistorted coos for the dummy point
drz_dis = get_drz_position(dispnt, drzcoeffs, pixmax);
// compute the scale along the minor axis
ret.y = sqrt((drz_ref.x-drz_dis.x)*(drz_ref.x-drz_dis.x) +
(drz_ref.y-drz_dis.y)*(drz_ref.y-drz_dis.y));
// return the result
return ret;
}
/*
* Function: get_crossdisp_scale
* The function computes the drizzle scale in cross-
* dispersion direction for a given point and the
* drizzle parameters of an image.
*
* Parameters:
* @param trace - the object trace
* @param refpnt - the reference point
* @param drzcoeffs - the drizzle coefficients
* @param pixmax - the image dimensions
*
* Returns:
* @return crscale - the drizzle scale in crossdispersion
* direction
*/
double
get_crossdisp_scale(trace_func *trace, d_point refpnt, gsl_matrix * drzcoeffs,
px_point pixmax)
{
double crscale;
double phi_trace;
//int beamID = 0;
d_point dispnt;
d_point drz_ref;
d_point drz_dis;
// get the trace angle
phi_trace = atan2 (trace->deriv (0.0, trace->data), 1.0);
// compute a dummy point along the cross-dispersion direction
dispnt.x = refpnt.x + cos(phi_trace + M_PI/2.0);
dispnt.y = refpnt.y + sin(phi_trace + M_PI/2.0);
// get the undistorted positions of the refpoint and
// the dummy point
drz_ref = get_drz_position(refpnt, drzcoeffs, pixmax);
drz_dis = get_drz_position(dispnt, drzcoeffs, pixmax);
// compute the drizzle scale
crscale = sqrt((drz_ref.x-drz_dis.x)*(drz_ref.x-drz_dis.x) +
(drz_ref.y-drz_dis.y)*(drz_ref.y-drz_dis.y));
// return the drizzle scale
return crscale;
}
/*
* Function: evaln
* The function evaluates the drizzle coefficients to return
* either the x- or y-value in the undistorted system.
* This is a translation of a fortran function with
* the identical name inside the drizzle package.
*
* Parameters:
* @param x - the x-value in the distorted system
* @param y - the y-value in the distorted system
* @param drzcoeffs - the drizzle coefficients
* @param row - which row of the coefficients to evaluate
*
* Returns:
* @return ret - the undistorted coordinate value
*/
double
evaln(double x, double y, gsl_matrix * drzcoeffs, int row){
double ret=0.0;
int order;
int n,m,nc,ncoeffs;
order = 0;
ncoeffs = 1;
// derive the number of 'orders'
while(ncoeffs+order+2 <= (int)drzcoeffs->size2){
ncoeffs = ncoeffs+order+2;
order++;
}
// add each individual term
nc = 0;
for (n=1; n < order+2; n++){
for (m=1; m < n+1; m++){
ret = ret + gsl_matrix_get(drzcoeffs,row,nc) * pow(x,(double)(n-m)) * pow(y,(double)(m-1));
nc++;
}
}
// give back the result
return ret;
}
/*
* Function: devalndx
* The function numerically differentiates the
* function 'evaln' with respect to the x-axis.
*
* Parameters:
* @param x - the x-value in the distorted system
* @param y - the y-value in the distorted system
* @param drzcoeffs - the drizzle coefficients
* @param row - which row of the coefficients to evaluate
*
* Returns:
* @return ret - the differential
*/
double
devalndx(double x, double y, gsl_matrix * drzcoeffs, int row){
double ret=0.0;
int order;
int n,m,nc,ncoeffs;
// derive the number of 'orders'
order = 0;
ncoeffs = 1;
while(ncoeffs+order+2 <= (int)drzcoeffs->size2){
ncoeffs = ncoeffs+order+2;
order++;
}
// add each individual term
nc = 0;
for (n=1; n < order+2; n++){
for (m=1; m < n; m++){
ret = ret + gsl_matrix_get(drzcoeffs,row,nc) * (double)(n-m) * pow(x,(double)(n-m-1)) * pow(y,(double)(m-1));
nc++;
}
nc++;
}
// return the result
return ret;
}
/*
* Function: devalndy
* The function numerically differentiates the
* function 'evaln' with respect to the y-axis.
*
* Parameters:
* @param x - the x-value in the distorted system
* @param y - the y-value in the distorted system
* @param drzcoeffs - the drizzle coefficients
* @param row - which row of the coefficients to evaluate
*
* Returns:
* @return ret - the differential
*/
double
devalndy(double x, double y, gsl_matrix * drzcoeffs, int row){
double ret=0.0;
int order;
int n,m,nc,ncoeffs;
// derive the number of 'orders'
order = 0;
ncoeffs = 1;
while(ncoeffs+order+2 <= (int)drzcoeffs->size2){
ncoeffs = ncoeffs+order+2;
order++;
}
// add each individual term
nc = 0;
for (n=1; n < order+2; n++){
nc++;
for (m=2; m < n+1; m++){
ret = ret + gsl_matrix_get(drzcoeffs,row,nc) * pow(x,(double)(n-m)) * (double)(m-1) * pow(y,(double)(m-2));
nc++;
}
}
// return the result
return ret;
}
/*
* Function: get_jacobian
*
* Parameters:
* @param i -
* @param j -
* @param drzcoeffs - the drizzle coefficients
* @param width -
* @param height -
*
* Returns:
* @return ret -
*/
gsl_matrix *
get_jacobian(int i, int j, gsl_matrix * drzcoeffs, int width, int height){
double xr, yr;
gsl_matrix * ret;
ret = gsl_matrix_alloc(2,2);
gsl_matrix_set_all (ret, 0.0);
xr = (double)i - ((double)(width/2)+1.0);
yr = (double)j - ((double)(height/2)+1.0);
gsl_matrix_set(ret, 0, 0, devalndx( xr, yr, drzcoeffs, 0));
gsl_matrix_set(ret, 0, 1, devalndy( xr, yr, drzcoeffs, 0));
gsl_matrix_set(ret, 1, 0, devalndx( xr, yr, drzcoeffs, 1));
gsl_matrix_set(ret, 1, 1, devalndy( xr, yr, drzcoeffs, 1));
return ret;
}
/*
* Function: get_det_jacobian
*
* Parameters:
* @param i -
* @param j -
* @param drzcoeffs - the drizzle coefficients
* @param width -
* @param height -
*
* Returns:
* @return ret -
*/
double
get_det_jacobian(int i, int j, gsl_matrix * drzcoeffs, int width, int height){
gsl_matrix * jacob;
double ret;
jacob = get_jacobian(i,j,drzcoeffs,width,height);
ret = gsl_matrix_get(jacob, 0, 0) * gsl_matrix_get(jacob, 1, 1)
-gsl_matrix_get(jacob, 0, 1) * gsl_matrix_get(jacob, 1, 0);
gsl_matrix_free(jacob);
return ret;
}
/*
* Function: get_drz_position
* The function transforms distorted coordinates image to undistorted
* image coordinates. As an assumption, the undistorted image
* has the same dimension as the distorted.
*
* Parameters:
* @param in_point - the coordinates in the distorted frame
* @param drzcoeffs - the drizzle coefficients
* @param pixmax - the image dimension of the distorted frame
*
* Returns:
* @return: ou_point - the coordinates in the undistorted frame
*/
d_point
get_drz_position(d_point in_point, gsl_matrix *drzcoeffs, px_point pixmax)
{
d_point ou_point;
double xr, yr;
double xn, yn;
// transform the input coos into the drizzle system
xr = in_point.x - ((double)(pixmax.x/2)+1.0);
yr = in_point.y - ((double)(pixmax.y/2)+1.0);
// ou_point.x = evaln(xr,yr,drzcoeffs,0);
// ou_point.y = evaln(xr,yr,drzcoeffs,1);
// get the undistorted coos in the drizzle system
xn = evaln(xr,yr,drzcoeffs,0);
yn = evaln(xr,yr,drzcoeffs,1);
// transform back into the image system,
// assuming identical image dimensions
ou_point.x = xn + ((double)(pixmax.x/2)+1.0);
ou_point.y = yn + ((double)(pixmax.y/2)+1.0);
// return the undistorted coos
return ou_point;
}
/*
* Function: get_drz_position_free
* The function transforms distorted coordinates image to undistorted
* image coordinates. The size of the input and output image are free.
*
* Parameters:
* @param in_point - the coordinates in the distorted frame
* @param drzcoeffs - the drizzle coefficients
* @param pix_in - the image dimension of the distorted frame
* @param pix_out - the image dimension of the distorted frame
*
* Returns:
* @return: ou_point - the coordinates in the undistorted frame
*/
d_point
get_drz_position_free(d_point in_point, gsl_matrix *drzcoeffs,
px_point pix_in, px_point pix_out)
{
d_point ou_point;
double xr, yr;
double xn, yn;
// transform the input coos into the drizzle system
xr = in_point.x - ((double)(pix_in.x/2)+1.0);
yr = in_point.y - ((double)(pix_in.y/2)+1.0);
// ou_point.x = evaln(xr,yr,drzcoeffs,0);
// ou_point.y = evaln(xr,yr,drzcoeffs,1);
// get the undistorted coos in the drizzle system
xn = evaln(xr,yr,drzcoeffs,0);
yn = evaln(xr,yr,drzcoeffs,1);
// transform back into the image system,
// assuming identical image dimensions
ou_point.x = xn + ((double)(pix_out.x/2)+1.0);
ou_point.y = yn + ((double)(pix_out.y/2)+1.0);
// return the undistorted coos
return ou_point;
}
trace_func *
get_tracefunc_at(char *filename, d_point p){
int beamID = 0;
trace_func *trace;
tracestruct *tstruct;
tstruct = get_tracestruct_at_pos (filename, beamID, p);
trace = vector_to_trace_polyN ( tstruct->pol );
return trace;
}
| {
"alphanum_fraction": 0.6694057057,
"avg_line_length": 25.9474474474,
"ext": "c",
"hexsha": "78ab7c0408f82d087c7d9b067bb6baa4ce45d4c2",
"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/crossdisp_utils.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/crossdisp_utils.c",
"max_line_length": 115,
"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/crossdisp_utils.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5191,
"size": 17281
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
#include "cosmocalc.h"
#define ODEGROWTH //the integral formulation is onyl correct for LCDM, any wCDM cosmology will not work
#ifdef ODEGROWTH
#define LNAINITGROWTH (log(AEXPN_MIN_GROWTH))
#define ABSERR 1e-8
#define RELERR 1e-8
#define HSTART 1e-4
#define ODE_TYPE gsl_odeiv2_step_rk8pd
static int growth_ode_sys_w0wa(double t, const double y[], double dydt[], void *params);
//ODE for growth from Komatsu et al. 2009, ApJS, 180, 330 (WMAP5 paper)
static int growth_ode_sys_w0wa(double t, const double y[], double dydt[], void *params)
{
double a = exp(t); //t = log(a)
double weffa = weff(a);
double ha = hubble_noscale(a);
double omegaDEa = cosmoData.OmegaL/ha/ha/pow(a,3.0*(1.0 + weffa));
double omegaKa = cosmoData.OmegaK/a/a/ha/ha;
dydt[0] = y[1];
dydt[1] = (1.5*weffa*omegaDEa - 0.5*omegaKa - 2.5)*y[1] - (2.0*omegaKa + 1.5*(1.0 - weffa)*omegaDEa)*y[0];
return GSL_SUCCESS;
}
double growth_function_exact(double a)
{
gsl_odeiv2_system odesys = {growth_ode_sys_w0wa, NULL, 2, NULL};
gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new(&odesys,ODE_TYPE,HSTART,ABSERR,RELERR);
double lna_init;
double lna_final,y[2];
double ga,gnorm;
int status;
//do g(a) unormalized
y[0] = 1.0;
y[1] = 0.0;
lna_init = LNAINITGROWTH;
lna_final = log(a);
status = gsl_odeiv2_driver_apply(d,&lna_init,lna_final,y);
ga = y[0]*a;
if(status != GSL_SUCCESS)
{
fprintf(stderr,"error in integrating growth function! a = %lf\n",a);
assert(status == GSL_SUCCESS);
}
//do g(a = 1.0) to get normalization
y[0] = 1.0;
y[1] = 0.0;
lna_init = LNAINITGROWTH;
lna_final = 0.0;
status = gsl_odeiv2_driver_apply(d,&lna_init,lna_final,y);
gnorm = y[0];
if(status != GSL_SUCCESS)
{
fprintf(stderr,"error in integrating growth function! a = %lf\n",a);
assert(status == GSL_SUCCESS);
}
gsl_odeiv2_driver_free(d);
return ga/gnorm;
}
double growth_function_exact_nonorm(double a)
{
gsl_odeiv2_system odesys = {growth_ode_sys_w0wa, NULL, 2, NULL};
gsl_odeiv2_driver *d = gsl_odeiv2_driver_alloc_y_new(&odesys,ODE_TYPE,HSTART,ABSERR,RELERR);
double lna_init;
double lna_final,y[2];
double ga;
int status;
//do g(a) unormalized
y[0] = 1.0;
y[1] = 0.0;
lna_init = LNAINITGROWTH;
lna_final = log(a);
status = gsl_odeiv2_driver_apply(d,&lna_init,lna_final,y);
ga = y[0]*a;
if(status != GSL_SUCCESS)
{
fprintf(stderr,"error in integrating growth function! a = %lf\n",a);
assert(status == GSL_SUCCESS);
}
return ga;
}
double growth_function(double a)
{
static int initFlag = 1;
static int currCosmoNum;
static double growth_function_norm;
static gsl_spline *cosmocalc_growth_function_spline = NULL;
static gsl_interp_accel *cosmocalc_growth_function_acc = NULL;
double growth_function_table[COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH];
double a_table[COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH];
long i;
gsl_odeiv2_system odesys = {growth_ode_sys_w0wa, NULL, 2, NULL};
gsl_odeiv2_driver *d;
double afact,lna_init;
double lna_final,y[2];
int status;
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
//init ODE integrator
d = gsl_odeiv2_driver_alloc_y_new(&odesys,ODE_TYPE,HSTART,ABSERR,RELERR);
for(i=0;i<COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH;++i)
{
//get scale factor
afact = log((1e-3 + AEXPN_MAX)/AEXPN_MIN_GROWTH)/(COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH-1.0)*((double) i) + log(AEXPN_MIN_GROWTH);
a_table[i] = afact;
//do growth function integration
//init ODE
y[0] = 1.0;
y[1] = 0.0;
lna_init = LNAINITGROWTH;
lna_final = afact;
status = gsl_odeiv2_driver_apply(d,&lna_init,lna_final,y);
growth_function_table[i] = y[0]*exp(afact);
if(status != GSL_SUCCESS)
{
fprintf(stderr,"error in integrating growth function! a = %lf\n",a);
assert(status == GSL_SUCCESS);
}
}
//get normalization
y[0] = 1.0;
y[1] = 0.0;
lna_init = LNAINITGROWTH;
lna_final = 0.0;
status = gsl_odeiv2_driver_apply(d,&lna_init,lna_final,y);
growth_function_norm = y[0];
if(status != GSL_SUCCESS)
{
fprintf(stderr,"error in integrating growth function! a = %lf\n",1.0);
assert(status == GSL_SUCCESS);
}
//free ODE stuff
gsl_odeiv2_driver_free(d);
//init the spline and accelerators
if(cosmocalc_growth_function_spline != NULL)
gsl_spline_free(cosmocalc_growth_function_spline);
cosmocalc_growth_function_spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH));
gsl_spline_init(cosmocalc_growth_function_spline,a_table,growth_function_table,(size_t) (COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH));
if(cosmocalc_growth_function_acc != NULL)
gsl_interp_accel_reset(cosmocalc_growth_function_acc);
else
cosmocalc_growth_function_acc = gsl_interp_accel_alloc();
}
return gsl_spline_eval(cosmocalc_growth_function_spline,log(a),cosmocalc_growth_function_acc)/growth_function_norm;
}
#else
static double growth_function_integ_funct(double a, void *p);
/* function for integration using gsl integration */
static double growth_function_integ_funct(double a, void *p)
{
double hubblefac = hubble_noscale(a);
double adot = a*hubblefac;
double alim = (*((double*)p));
return 1.0/adot/adot/adot*hubble_noscale(alim);
}
double growth_function_exact(double a)
{
#define WORKSPACE_NUM 100000
#define ABSERR 0.0
#define RELERR 1e-8
gsl_integration_workspace *workspace;
gsl_function F;
double result,abserr,afact,norm;
workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);
afact = a;
F.function = &growth_function_integ_funct;
F.params = &(afact);
gsl_integration_qag(&F,0.0,afact,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&result,&abserr);
afact = 1.0;
F.params = &(afact);
gsl_integration_qag(&F,0.0,afact,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&norm,&abserr);
gsl_integration_workspace_free(workspace);
#undef ABSERR
#undef RELERR
#undef WORKSPACE_NUM
return result/norm;
}
double growth_function(double a)
{
#define WORKSPACE_NUM 100000
#define ABSERR 1e-8
#define RELERR 1e-8
static int initFlag = 1;
static int currCosmoNum;
static double growth_function_norm;
static gsl_spline *cosmocalc_growth_function_spline = NULL;
static gsl_interp_accel *cosmocalc_growth_function_acc = NULL;
double growth_function_table[COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH];
double a_table[COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH];
long i;
gsl_integration_workspace *workspace;
gsl_function F;
double result,abserr,afact;
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);
F.function = &growth_function_integ_funct;
for(i=0;i<COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH;++i)
{
afact = (1e-3 + AEXPN_MAX - AEXPN_MIN)/(COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH-1.0)*((double) i) + AEXPN_MIN;
a_table[i] = afact;
F.params = &(afact);
gsl_integration_qag(&F,0.0,afact,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&result,&abserr);
growth_function_table[i] = result;
}
afact = 1.0;
F.params = &(afact);
gsl_integration_qag(&F,0.0,1.0,ABSERR,RELERR,(size_t) WORKSPACE_NUM,GSL_INTEG_GAUSS51,workspace,&growth_function_norm,&abserr);
gsl_integration_workspace_free(workspace);
//init the spline and accelerators
if(cosmocalc_growth_function_spline != NULL)
gsl_spline_free(cosmocalc_growth_function_spline);
cosmocalc_growth_function_spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH));
gsl_spline_init(cosmocalc_growth_function_spline,a_table,growth_function_table,(size_t) (COSMOCALC_GROWTH_FUNCTION_TABLE_LENGTH));
if(cosmocalc_growth_function_acc != NULL)
gsl_interp_accel_reset(cosmocalc_growth_function_acc);
else
cosmocalc_growth_function_acc = gsl_interp_accel_alloc();
}
return gsl_spline_eval(cosmocalc_growth_function_spline,a,cosmocalc_growth_function_acc)/growth_function_norm;
#undef WORKSPACE_NUM
#undef ABSERR
#undef RELERR
}
#endif
#undef ODEGROWTH
| {
"alphanum_fraction": 0.7172327331,
"avg_line_length": 29.843537415,
"ext": "c",
"hexsha": "f2d91e6bd0b19694bc22a4a1500249aa9fa50c6b",
"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/growth_function.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/growth_function.c",
"max_line_length": 136,
"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/growth_function.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2760,
"size": 8774
} |
#include <viaio/VImage.h>
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <viaio/Vlib.h>
#include "gsl_utils.h"
void prewhite(gsl_matrix_float** pinvX,gsl_matrix_float** invM,gsl_matrix_float* X,int numlags)
{
int n = X->size2;
/* preparation for whitening */
/* X^T */
gsl_matrix_float* transX = gsl_matrix_float_alloc(X->size2, X->size1);
gsl_matrix_float_transpose_memcpy(transX,X);
/* identity */
gsl_matrix_float *R = gsl_matrix_float_alloc(n,n);
gsl_matrix_float_set_identity(R);
/* pseudo inverse */
*pinvX = fmat_PseudoInv(transX,NULL);
/* temporary matrix buffer for binary matrix operations */
gsl_matrix_float *result;
gsl_matrix_float *result2;
result = fmat_x_mat(transX,*pinvX,NULL);
gsl_matrix_float_sub(R,result);
gsl_matrix_float_free(result);
/* result buffer */
gsl_matrix_float *M;
if(numlags == 1){
/* create a n-x-n matrix Diag1 where the k=1 sub- and suberdiagonals
* are 1 and the remaining entries are 0.
* Equivalent matlab code:
*
* keep = 1:n;
* indk1=((keep(2:n)-keep(1:n-1))==1);
* Diag1=diag(indk1,1)+diag(indk1,-1);
*/
gsl_matrix_float *Diag1 = gsl_matrix_float_alloc(n,n);
gsl_matrix_float_set_zero(Diag1);
/* set superdiagonal to 1 */
gsl_vector_float_view superview = gsl_matrix_float_superdiagonal(Diag1,1);
gsl_vector_float_set_all(&superview.vector,1);
/* set subdiagonal to 1 */
gsl_vector_float_view subview = gsl_matrix_float_subdiagonal(Diag1,1);
gsl_vector_float_set_all(&subview.vector,1);
float M11 = trace(R);
result = fmat_x_mat(R, Diag1, NULL);
float M12 = trace(result);
float M21 = M12/2.0;
fmat_x_mat(R,Diag1,result);
result2 = fmat_x_mat(result,R,NULL);
fmat_x_mat(result2,Diag1,result);
float M22 = trace(result)/2;
gsl_matrix_float_free(result);
gsl_matrix_float_free(result2);
M = gsl_matrix_float_alloc(2,2);
/* M=[M11 M12; M21 M22] */
gsl_matrix_float_set(M,0,0,M11);
gsl_matrix_float_set(M,0,1,M12);
gsl_matrix_float_set(M,1,0,M21);
gsl_matrix_float_set(M,1,1,M22);
gsl_matrix_float_free(Diag1);
}
else {
int i,j;
M = gsl_matrix_float_alloc(numlags+1,numlags+1);
gsl_matrix_float_set_zero(M);
gsl_matrix_float* Di = gsl_matrix_float_alloc(n,n);
gsl_matrix_float* Dj = gsl_matrix_float_alloc(n,n);
/* This double loop can be supported by a look-up-table for
* the diagonal matrixes. */
for(i=0;i<numlags+1;i++){
gsl_matrix_float_set_zero(Di);
/* set maindiagonal to 1 */
if(i==0){
gsl_vector_float_view mdiag = gsl_matrix_float_diagonal(Di);
gsl_vector_float_set_all(&mdiag.vector,1);
}
/* set i. super- and subdiagonal to 1 */
else {
/* set superdiagonal to 1 */
gsl_vector_float_view superview = gsl_matrix_float_superdiagonal(Di,i);
gsl_vector_float_set_all(&superview.vector,1);
/* set subdiagonal to 1 */
gsl_vector_float_view subview = gsl_matrix_float_subdiagonal(Di,i);
gsl_vector_float_set_all(&subview.vector,1);
}
for(j=0;j<numlags+1;j++){
gsl_matrix_float_set_zero(Dj);
/* set maindiagonal to 1 */
if(j==0){
gsl_vector_float_view mdiag = gsl_matrix_float_diagonal(Dj);
gsl_vector_float_set_all(&mdiag.vector,1);
}
/* set j. super- and subdiagonal to 1 */
else {
/* set superdiagonal to 1 */
gsl_vector_float_view superview = gsl_matrix_float_superdiagonal(Dj,j);
gsl_vector_float_set_all(&superview.vector,1);
/* set subdiagonal to 1 */
gsl_vector_float_view subview = gsl_matrix_float_subdiagonal(Dj,j);
gsl_vector_float_set_all(&subview.vector,1);
}
result = fmat_x_mat(R,Di,NULL);
result2 = fmat_x_mat(result,R,NULL);
fmat_x_mat(result2,Dj,result);
gsl_matrix_float_free(result2);
gsl_matrix_float_set(M,i,j,trace(result)/(1+(i>0)));
gsl_matrix_float_free(result);
}
}
gsl_matrix_float_free(Di);
gsl_matrix_float_free(Dj);
}
/* calculation of the return values */
*invM = fInv(M,NULL);
/* pinvX has already been initialized */
/* free memory */
gsl_matrix_float_free(transX);
gsl_matrix_float_free(R);
gsl_matrix_float_free(M);
}
| {
"alphanum_fraction": 0.692745377,
"avg_line_length": 29.0896551724,
"ext": "c",
"hexsha": "da4a7d996cf414ea6da6c3187db4a7dde389eeac",
"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_prewhitening/prewhite.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_prewhitening/prewhite.c",
"max_line_length": 96,
"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_prewhitening/prewhite.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": 1225,
"size": 4218
} |
////////////////////////////////////////////////////////////
//
// Copyright (c) 2018 Jan Filipowicz, Filip Turobos
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
////////////////////////////////////////////////////////////
#ifndef SALESMAN_EXAMPLE_PATH_MERGER_H
#define SALESMAN_EXAMPLE_PATH_MERGER_H
#include <algorithm>
#include <functional>
#include <iterator>
#include <stack>
#include <utility>
#include <vector>
#include <gsl/gsl_util>
#include <gsl/span>
#include <repeat.h>
#include "disjoint_set_data_structure.h"
#include "permutation.h"
template<class UniformRandomBitGenerator>
class path_merger {
public:
explicit path_merger(UniformRandomBitGenerator& g) noexcept;
permutation operator()(const permutation& lhs, const permutation& rhs);
private:
using edge_type = std::pair<unsigned, unsigned>;
using edge_vector = std::vector<edge_type>;
edge_vector to_edges(const permutation& perm) const;
permutation to_permutation(const edge_vector& edges) const;
UniformRandomBitGenerator& rand;
};
template<class UniformRandomBitGenerator>
path_merger<UniformRandomBitGenerator>::path_merger(UniformRandomBitGenerator& g) noexcept
: rand(g) {}
template<class UniformRandomBitGenerator>
permutation path_merger<UniformRandomBitGenerator>::operator()(const permutation& lhs, const permutation& rhs) {
Expects(lhs.size() == rhs.size());
Expects(lhs.size() > 0);
const std::size_t size = lhs.size();
edge_vector lhs_edges = to_edges(lhs);
edge_vector rhs_edges = to_edges(rhs);
edge_vector result_edges;
result_edges.reserve(size);
std::set_intersection(lhs_edges.begin(), lhs_edges.end(), rhs_edges.begin(), rhs_edges.end(), std::back_inserter(result_edges));
disjoint_set_data_structure components(size);
std::vector<unsigned> missing_edges(size, 2);
for (const auto& [left, right] : result_edges) {
components.merge(left, right);
gsl::at(missing_edges, left)--;
gsl::at(missing_edges, right)--;
}
std::shuffle(lhs_edges.begin(), lhs_edges.end(), rand);
std::shuffle(rhs_edges.begin(), rhs_edges.end(), rand);
gsl::span<edge_type> spans[2] {lhs_edges, rhs_edges};
while (!std::all_of(std::begin(spans), std::end(spans), std::mem_fn(&gsl::span<edge_type>::empty))) {
for (auto&& span : spans) {
auto it = std::find_if(span.begin(), span.end(), [&](const edge_type& edge) {
const auto& [lhs, rhs] = edge;
return gsl::at(missing_edges, lhs) && gsl::at(missing_edges, rhs) && components.find(lhs) != components.find(rhs);
});
if (it != span.end()) {
const auto& [left, right] = *it;
result_edges.emplace_back(left, right);
components.merge(left, right);
gsl::at(missing_edges, left)--;
gsl::at(missing_edges, right)--;
}
span = span.subspan(it - span.begin());
}
}
std::stack<unsigned, std::vector<unsigned>> s;
for (unsigned i = 0; i < size; i++) {
repeat(gsl::at(missing_edges, i), [&] {
if (!s.empty() && components.find(s.top()) != components.find(i)) {
const unsigned& left = s.top();
const unsigned& right = i;
result_edges.emplace_back(left, right);
components.merge(left, right);
gsl::at(missing_edges, left)--;
gsl::at(missing_edges, right)--;
s.pop();
} else {
s.push(i);
}
});
}
if (!s.empty()) {
const unsigned left = s.top();
s.pop();
const unsigned& right = s.top();
result_edges.emplace_back(left, right);
}
Ensures(result_edges.size() == lhs.size());
return to_permutation(result_edges);
}
template<class UniformRandomBitGenerator>
auto path_merger<UniformRandomBitGenerator>::to_edges(const permutation& perm) const -> edge_vector {
Expects(perm.size() > 0);
edge_vector result {std::minmax({perm.front(), perm.back()})};
result.reserve(perm.size());
std::transform(std::next(perm.begin()), perm.end(), perm.begin(), std::inserter(result, result.end()), [](unsigned lhs, unsigned rhs) {
return std::minmax({lhs, rhs});
});
std::sort(result.begin(), result.end());
Ensures(result.size() == perm.size());
return result;
}
template<class UniformRandomBitGenerator>
permutation path_merger<UniformRandomBitGenerator>::to_permutation(const edge_vector& edges) const {
Expects(edges.size() > 0);
const std::size_t size = edges.size();
std::vector<std::vector<unsigned>> graph(size);
for (auto&& node : graph) {
node.reserve(2);
}
for (const auto& [lhs, rhs] : edges) {
gsl::at(graph, lhs).push_back(rhs);
gsl::at(graph, rhs).push_back(lhs);
}
permutation result(size);
unsigned prev = 0;
unsigned cur = graph.front().front();
std::for_each(std::next(result.begin()), result.end(), [&](unsigned& element) {
element = cur;
const auto& node = gsl::at(graph, cur);
unsigned next = node.front() == prev ? node.back() : node.front();
prev = cur;
cur = next;
});
Ensures(result.size() == edges.size());
return result;
}
#endif
| {
"alphanum_fraction": 0.695622435,
"avg_line_length": 36.55,
"ext": "h",
"hexsha": "d221aad4e9f641e6ce0691dc1d2315898ddc47a3",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SirEmentaler/Eugenics-Wars",
"max_forks_repo_path": "SalesmanExample/path_merger.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SirEmentaler/Eugenics-Wars",
"max_issues_repo_path": "SalesmanExample/path_merger.h",
"max_line_length": 136,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SirEmentaler/Eugenics-Wars",
"max_stars_repo_path": "SalesmanExample/path_merger.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1451,
"size": 5848
} |
/*
* 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 utility_77d83a8d_bf54_4fbe_ab3c_b06d0be9e40e_h
#define utility_77d83a8d_bf54_4fbe_ab3c_b06d0be9e40e_h
#include <gslib/std.h>
#include <gslib/type.h>
/*
* This file include a series of intersection operations.
* Here are all the details:
* point ratio
* linear - linear: available available
* linear - quad: none available
* linear - cubic: none available
* quad - quad: none available
* quad - cubic: available none
* cubic - cubic: available none
* To convert from ratio to point was quite simple, this was why I suggest ratio first.
* other cases limited by the algorithm where the point was the first result, I hope you
* notice this and use certain methods to get your result, so I didn't offer an altered
* way, but you can simply achieve that by calling the reparameterize functions.
* Caution that the precision of intersection may cause loss of roots,
* set tolerance around 0.2 - 0.3 might be good.
*/
__gslib_begin__
gs_export extern void linear_interpolate(vec2 c[], const vec2& p1, const vec2& p2, int step);
gs_export extern void quadratic_interpolate(vec2 c[], const vec2& p1, const vec2& p2, const vec2& p3, int step);
gs_export extern void cubic_interpolate(vec2 c[], const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4, int step);
gs_export extern void hermite_interpolate(vec2 c[], const vec2& p1, const vec2& p2, const vec2& t1, const vec2& t2, int step);
gs_export extern float linear_reparameterize(const vec2& p1, const vec2& p2, const vec2& p);
gs_export extern float quad_reparameterize(const vec3 para[2], const vec2& p);
gs_export extern float cubic_reparameterize(const vec4 para[2], const vec2& p);
gs_export extern float best_quad_reparameterize(const vec3 para[2], const vec2& p);
gs_export extern float best_cubic_reparameterize(const vec4 para[2], const vec2& p);
gs_export extern bool is_concave_angle(const vec2& p1, const vec2& p2, const vec2& p3);
gs_export extern bool is_concave_angle(const vec2& p1, const vec2& p2, const vec2& p3, bool cw);
gs_export extern bool is_approx_line(const vec2& p1, const vec2& p2, const vec2& p3, float tolerance);
gs_export extern void get_linear_coefficient(vec3& coef, const vec2& p, const vec2& d);
gs_export extern void get_linear_parameter_equation(vec2 para[2], const vec2& a, const vec2& b);
gs_export extern void get_quad_parameter_equation(vec3 para[2], const vec2& a, const vec2& b, const vec2& c);
gs_export extern void get_cubic_parameter_equation(vec4 para[2], const vec2& a, const vec2& b, const vec2& c, const vec2& d);
gs_export extern void get_first_derivate_factor(vec2 df1[2], const vec3 para[2]);
gs_export extern void get_first_derivate_factor(vec3 df1[2], const vec4 para[2]);
gs_export extern void get_second_derivate_factor(vec2 df2[2], const vec4 para[2]);
gs_export extern void get_first_derivate_factor(vec3 df1[2], const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4);
gs_export extern void get_second_derivate_factor(vec2 df2[2], const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4);
gs_export extern void get_first_derivate(vec2& d, const vec3 df1[2], float t);
gs_export extern void get_second_derivate(vec2& d, const vec2 df2[2], float t);
gs_export extern float get_cubic_curvature(const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4, float t);
gs_export extern int solve_univariate_quadratic(float t[2], const vec3& coef);
gs_export extern int solve_univariate_cubic(float t[3], const vec4& coef);
gs_export extern int solve_univariate_quartic(float t[4], const float coef[5]);
gs_export extern int get_cubic_inflection(float t[2], const vec2& a, const vec2& b, const vec2& c, const vec2& d);
gs_export extern int get_cubic_inflection(float t[2], const vec3 ff[2], const vec2 sf[2]);
gs_export extern int get_quad_extrema(float t[], const vec2& ff);
gs_export extern int get_cubic_extrema(float t[2], const vec3& ff);
gs_export extern void get_quad_bound_box(rectf& rc, const vec2& p1, const vec2& p2, const vec2& p3);
gs_export extern void get_cubic_bound_box(rectf& rc, const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4);
gs_export extern int intersection_quad_linear(float t[2], const vec3 quad[2], const vec3& linear);
gs_export extern int intersection_cubic_linear(float t[3], const vec4 cubic[2], const vec3& linear);
gs_export extern int intersection_quad_quad(float ts[4][2], const vec3 quad1[2], const vec3 quad2[2]);
gs_export extern void intersectp_linear_linear(vec2& ip, const vec2& p1, const vec2& p2, const vec2& d1, const vec2& d2);
gs_export extern int intersectp_cubic_quad(vec2 ip[6], const vec2 cp1[4], const vec2 cp2[3], float tolerance);
gs_export extern int intersectp_cubic_cubic(vec2 ip[9], const vec2 cp1[4], const vec2 cp2[4], float tolerance);
gs_export extern bool get_self_intersection(float ts[2], const vec2& a, const vec2& b, const vec2& c, const vec2& d);
gs_export extern void split_quad_bezier(vec2 c[5], const vec2 p[3], float t);
gs_export extern void split_quad_bezier(vec2 c[7], const vec2 p[3], float t1, float t2);
gs_export extern void split_cubic_bezier(vec2 c[7], const vec2 p[4], float t);
gs_export extern void split_cubic_bezier(vec2 c[10], const vec2 p[4], float t1, float t2);
gs_export extern void offset_cubic_bezier(vec2 c[4], const vec2 p[4], float d);
gs_export extern float quad_bezier_length(const vec2 cp[3]);
gs_export extern float cubic_bezier_length(const vec2 cp[4], float tolerance);
gs_export extern int cubic_to_quad_bezier(vector<vec2>& quadctl, const vec2 cp[4], float tolerance);
gs_export extern float quad_control_length(const vec2& a, const vec2& b, const vec2& c);
gs_export extern float cubic_control_length(const vec2& a, const vec2& b, const vec2& c, const vec2& d);
gs_export extern float point_line_distance(const vec2& p, const vec2& p1, const vec2& p2);
gs_export extern int get_interpolate_step(const vec2& a, const vec2& b, const vec2& c, float step_len = -1.f);
gs_export extern int get_interpolate_step(const vec2& a, const vec2& b, const vec2& c, const vec2& d, float step_len = -1.f);
gs_export extern int get_rough_interpolate_step(const vec2& a, const vec2& b, const vec2& c);
gs_export extern int get_rough_interpolate_step(const vec2& a, const vec2& b, const vec2& c, const vec2& d);
gs_export extern float get_cubic_klmcoords(vec3 m[4], const vec2& p1, const vec2& p2, const vec2& p3, const vec2& p4,
const vec2& ac1, const vec2& ac2, const vec2& ac3, const vec2& ac4 /* absolute coord for error control */
);
gs_export extern float get_include_angle(const vec2& d1, const vec2& d2);
gs_export extern float get_include_angle(const vec2& a, const vec2& b, const vec2& c);
gs_export extern float get_rotate_angle(const vec2& d1, const vec2& d2);
gs_export extern float get_rotate_angle(const vec2& a, const vec2& b, const vec2& c);
gs_export extern void get_reduce_point(vec2& p, const vec2& a, const vec2& b, const vec2& c, const vec2& d);
gs_export extern bool point_in_triangle(const vec2& p, const vec2& p1, const vec2& p2, const vec2& p3);
gs_export extern int point_in_polygon(const vec2& p, const vector<vec2>& poly); /* 0: outside; 1 : inside; -1 : coincide */
gs_export extern float get_triangle_area(const vec2& p1, const vec2& p2, const vec2& p3);
gs_export extern vec3 get_barycentric_coords(const vec2& p, const vec2& p1, const vec2& p2, const vec2& p3);
gs_export extern bool clip_line_rect(float t[2], const vec2& p1, const vec2& p2, const rect& clipbox);
gs_export extern bool clip_line_rectf(float t[2], const vec2& p1, const vec2& p2, const rectf& clipbox);
gs_export extern void trace_quad_strip(const vec2 cp[], int size);
gs_export extern void trace_cubic_strip(const vec2 cp[], int size);
inline bool is_isosigned(float a, float b) { return (int)((*(uint*)&a ^ *(uint*)&b)) >= 0; }
inline bool is_isosigned(double a, double b) { return (long long)((*(unsigned long long*)&a ^ *(unsigned long long*)&b)) >= 0; }
inline bool fuzzy_zero(float f) { return (f <= 1e-4f && f >= -1e-4f); }
inline bool fuzzy_zero(float f, float tol) { return f <= tol && f >= -tol; }
inline bool fuzzy_between(float a, float b, float c, float tol) { return b > a - tol && b < c + tol; }
inline bool fuzzy_greater_inclusive(float m, float n, float tol) { return m > (n - tol); }
inline bool fuzzy_less_inclusive(float m, float n, float tol) { return m < (n + tol); }
inline bool fuzzy_greater_exclusive(float m, float n, float tol) { return m > (n + tol); }
inline bool fuzzy_less_exclusive(float m, float n, float tol) { return m < (n - tol); }
inline bool is_parallel(const vec2& a, const vec2& b) { return fuzzy_zero(a.ccw(b)); }
inline vec2& eval_linear(vec2& v, const vec2 para[2], float t)
{
vec2 sv(t, 1.f);
v.x = para[0].dot(sv);
v.y = para[1].dot(sv);
return v;
}
inline vec2& eval_quad(vec2& v, const vec3 para[2], float t)
{
vec3 sv(t * t, t , 1.f);
v.x = para[0].dot(sv);
v.y = para[1].dot(sv);
return v;
}
inline vec2& eval_cubic(vec2& v, const vec4 para[2], float t)
{
vec4 sv(t * t * t, t * t, t, 1.f);
v.x = para[0].dot(sv);
v.y = para[1].dot(sv);
return v;
}
__gslib_end__
#endif
| {
"alphanum_fraction": 0.7273668361,
"avg_line_length": 64.7926829268,
"ext": "h",
"hexsha": "6f73fa7d5826064afb64a9e7dd55eea500d37bb6",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/gslib/utility.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/gslib/utility.h",
"max_line_length": 129,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/gslib/utility.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": 3066,
"size": 10626
} |
/* linalg/hermtd.c
*
* Copyright (C) 2001, 2007, 2009 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.
*/
/* Factorise a hermitian matrix A into
*
* A = U T U'
*
* where U is unitary and T is real symmetric tridiagonal. Only the
* diagonal and lower triangular part of A is referenced and modified.
*
* On exit, T is stored in the diagonal and first subdiagonal of
* A. Since T is symmetric the upper diagonal is not stored.
*
* U is stored as a packed set of Householder transformations in the
* lower triangular part of the input matrix below the first subdiagonal.
*
* The full matrix for U can be obtained as the product
*
* U = U_N ... U_2 U_1
*
* where
*
* U_i = (I - tau_i * v_i * v_i')
*
* and where v_i is a Householder vector
*
* v_i = [0, ..., 0, 1, A(i+2,i), A(i+3,i), ... , A(N,i)]
*
* This storage scheme is the same as in LAPACK. See LAPACK's
* chetd2.f for details.
*
* See Golub & Van Loan, "Matrix Computations" (3rd ed), Section 8.3 */
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_linalg.h>
int
gsl_linalg_hermtd_decomp (gsl_matrix_complex * A, gsl_vector_complex * tau)
{
if (A->size1 != A->size2)
{
GSL_ERROR ("hermitian tridiagonal decomposition requires square matrix",
GSL_ENOTSQR);
}
else if (tau->size + 1 != A->size1)
{
GSL_ERROR ("size of tau must be (matrix size - 1)", GSL_EBADLEN);
}
else
{
const size_t N = A->size1;
size_t i;
const gsl_complex zero = gsl_complex_rect (0.0, 0.0);
const gsl_complex one = gsl_complex_rect (1.0, 0.0);
const gsl_complex neg_one = gsl_complex_rect (-1.0, 0.0);
for (i = 0 ; i < N - 1; i++)
{
gsl_vector_complex_view c = gsl_matrix_complex_column (A, i);
gsl_vector_complex_view v = gsl_vector_complex_subvector (&c.vector, i + 1, N - (i + 1));
gsl_complex tau_i = gsl_linalg_complex_householder_transform (&v.vector);
/* Apply the transformation H^T A H to the remaining columns */
if ((i + 1) < (N - 1)
&& !(GSL_REAL(tau_i) == 0.0 && GSL_IMAG(tau_i) == 0.0))
{
gsl_matrix_complex_view m =
gsl_matrix_complex_submatrix (A, i + 1, i + 1,
N - (i+1), N - (i+1));
gsl_complex ei = gsl_vector_complex_get(&v.vector, 0);
gsl_vector_complex_view x = gsl_vector_complex_subvector (tau, i, N-(i+1));
gsl_vector_complex_set (&v.vector, 0, one);
/* x = tau * A * v */
gsl_blas_zhemv (CblasLower, tau_i, &m.matrix, &v.vector, zero, &x.vector);
/* w = x - (1/2) tau * (x' * v) * v */
{
gsl_complex xv, txv, alpha;
gsl_blas_zdotc(&x.vector, &v.vector, &xv);
txv = gsl_complex_mul(tau_i, xv);
alpha = gsl_complex_mul_real(txv, -0.5);
gsl_blas_zaxpy(alpha, &v.vector, &x.vector);
}
/* apply the transformation A = A - v w' - w v' */
gsl_blas_zher2(CblasLower, neg_one, &v.vector, &x.vector, &m.matrix);
gsl_vector_complex_set (&v.vector, 0, ei);
}
gsl_vector_complex_set (tau, i, tau_i);
}
return GSL_SUCCESS;
}
}
/* Form the orthogonal matrix U from the packed QR matrix */
int
gsl_linalg_hermtd_unpack (const gsl_matrix_complex * A,
const gsl_vector_complex * tau,
gsl_matrix_complex * U,
gsl_vector * diag,
gsl_vector * sdiag)
{
if (A->size1 != A->size2)
{
GSL_ERROR ("matrix A must be sqaure", GSL_ENOTSQR);
}
else if (tau->size + 1 != A->size1)
{
GSL_ERROR ("size of tau must be (matrix size - 1)", GSL_EBADLEN);
}
else if (U->size1 != A->size1 || U->size2 != A->size1)
{
GSL_ERROR ("size of U must match size of A", GSL_EBADLEN);
}
else if (diag->size != A->size1)
{
GSL_ERROR ("size of diagonal must match size of A", GSL_EBADLEN);
}
else if (sdiag->size + 1 != A->size1)
{
GSL_ERROR ("size of subdiagonal must be (matrix size - 1)", GSL_EBADLEN);
}
else
{
const size_t N = A->size1;
size_t i;
/* Initialize U to the identity */
gsl_matrix_complex_set_identity (U);
for (i = N - 1; i-- > 0;)
{
gsl_complex ti = gsl_vector_complex_get (tau, i);
gsl_vector_complex_const_view c = gsl_matrix_complex_const_column (A, i);
gsl_vector_complex_const_view h =
gsl_vector_complex_const_subvector (&c.vector, i + 1, N - (i+1));
gsl_matrix_complex_view m =
gsl_matrix_complex_submatrix (U, i + 1, i + 1, N-(i+1), N-(i+1));
gsl_linalg_complex_householder_hm (ti, &h.vector, &m.matrix);
}
/* Copy diagonal into diag */
for (i = 0; i < N; i++)
{
gsl_complex Aii = gsl_matrix_complex_get (A, i, i);
gsl_vector_set (diag, i, GSL_REAL(Aii));
}
/* Copy subdiagonal into sdiag */
for (i = 0; i < N - 1; i++)
{
gsl_complex Aji = gsl_matrix_complex_get (A, i+1, i);
gsl_vector_set (sdiag, i, GSL_REAL(Aji));
}
return GSL_SUCCESS;
}
}
int
gsl_linalg_hermtd_unpack_T (const gsl_matrix_complex * A,
gsl_vector * diag,
gsl_vector * sdiag)
{
if (A->size1 != A->size2)
{
GSL_ERROR ("matrix A must be sqaure", GSL_ENOTSQR);
}
else if (diag->size != A->size1)
{
GSL_ERROR ("size of diagonal must match size of A", GSL_EBADLEN);
}
else if (sdiag->size + 1 != A->size1)
{
GSL_ERROR ("size of subdiagonal must be (matrix size - 1)", GSL_EBADLEN);
}
else
{
const size_t N = A->size1;
size_t i;
/* Copy diagonal into diag */
for (i = 0; i < N; i++)
{
gsl_complex Aii = gsl_matrix_complex_get (A, i, i);
gsl_vector_set (diag, i, GSL_REAL(Aii));
}
/* Copy subdiagonal into sd */
for (i = 0; i < N - 1; i++)
{
gsl_complex Aji = gsl_matrix_complex_get (A, i+1, i);
gsl_vector_set (sdiag, i, GSL_REAL(Aji));
}
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.5685230685,
"avg_line_length": 30.398340249,
"ext": "c",
"hexsha": "3660e96a4f3d3ee3aded5b17b2d88601bf1a8c44",
"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/linalg/hermtd.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/linalg/hermtd.c",
"max_line_length": 99,
"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/linalg/hermtd.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": 2056,
"size": 7326
} |
/**
* @file piecewise_regimes.c
* @author Carl Boettiger <cboettig@gmail.com>
* @date 17 May 2010
*
* @section LICENSE
*
* GPLv3
*
* @section DESCRIPTION
*
* Code for computing the likelihood of a multitype OU process on a phylogenetic tree
*
*/
#include "likelihood.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_errno.h>
#include "optimizers.h"
#include "mvn.h"
/**
* @brief Function which wraps general format used by siman and multimin
* into the likelihood format of calc_lik
*
* @param v vector of values being optimized by the algorithm
* @param params specifies the tree and observed data
*
* @return minus log likelihood
*/
double optim_func (const gsl_vector *v, void *params)
{
tree * mytree = (tree *) params;
int i, n_regimes = mytree->n_regimes;
// Force root to match Theta of regime assigned to it, should also reduce vector size!
mytree->Xo[0] = mytree->theta[mytree->regimes[0]];
// mytree->Xo[0] = gsl_vector_get(v, 0);
for(i = 0; i < n_regimes; i++){
mytree->alpha[i] = v->data[i];
mytree->theta[i] = v->data[n_regimes+i];
mytree->sigma[i] = v->data[2*n_regimes+i];
if( (mytree->alpha[i] < 0) | (mytree->sigma[i] < 0) ){ return GSL_POSINF; }
if( mytree->theta[i] < 0 ){ return GSL_POSINF; }
}
double llik = 0;
calc_lik(mytree->Xo, mytree->alpha, mytree->theta, mytree->sigma,
mytree->regimes, mytree->ancestor, mytree->branch_length,
mytree->traits, &(mytree->n_nodes), mytree->lca_matrix, &llik);
return -llik;
}
/** Fit the model by maximum likelihood, called by R */
void fit_model(double * Xo,
double * alpha,
double * theta,
double * sigma,
int * regimes,
int * ancestor,
double * branch_length,
double * traits,
int * n_nodes,
int * n_regimes,
double * llik,
int * use_siman)
{
// Perhaps don't want to see gsl_errors once we're handling in R?
// Still want better/smarter behavior of the optimizer
gsl_set_error_handler_off ();
/** First, initialize the tree structure to facilitate passing all these elements */
int i,j;
tree * mytree = (tree *) malloc(sizeof(tree));
mytree->Xo = Xo;
mytree->alpha = alpha;
mytree->theta = theta;
mytree->sigma = sigma;
mytree->regimes = regimes;
mytree->ancestor = ancestor;
mytree->branch_length = branch_length;
mytree->traits = traits;
mytree->n_nodes = *n_nodes;
mytree->n_regimes = *n_regimes;
/** Second, save time by storing the least common ancestor matrix */
/* Save time by calculating least common ancestor ahead of time.
* Though this does the calc for all nodes, only tip ones are used.
* Current get_lca algorithm is only designed for tips anyway. */
double sep; // separation time, not actually used
mytree->lca_matrix = (int *) malloc(gsl_pow_2(*n_nodes) * sizeof(int) );
for(i=0; i < *n_nodes; i++){
for(j=0; j < *n_nodes; j++){
mytree->lca_matrix[*n_nodes*i+j] = get_lca(i,j, *n_nodes, ancestor, branch_length, &sep);
}
}
/** Then initialize the vector of parameters to be searched */
gsl_vector *x = gsl_vector_alloc(3 * *n_regimes);
// gsl_vector_set(x, 0, *Xo); /* Forces Xo to match theta (?) */
for(i = 0; i < *n_regimes; i++){
gsl_vector_set(x, i, alpha[i]);
gsl_vector_set(x, *n_regimes+i, theta[i]);
gsl_vector_set(x, 2 * *n_regimes+i, mytree->sigma[i]);
}
/** Select and call a likelihood optimization routine
* given the tree (with data) and parameters */
gsl_rng * rng = gsl_rng_alloc(gsl_rng_default);
if(*use_siman)
*llik = siman(x, mytree, rng);
else
*llik = multimin(x, mytree);
gsl_rng_free(rng);
gsl_vector_free(x);
free(mytree->lca_matrix);
free(mytree);
}
/* Externally exported function to determine LCA matrix */
/**
* @brief Determine the last common ancestor matrix of the tips,
* used in the likelihood calculation
*
* @param ancestor ancestor of the specified nide
* @param branch_length double branch lengths below each of the nodes
* @param n_nodes: integer number of nodes (including tips) in the tree
* @param lca_matrix must be an integer array of size n_nodes^2
*/
void calc_lca(int * ancestor, double * branch_length,
int * n_nodes, int * lca_matrix)
{
int i,j;
/* Save time by calculating least common ancestor ahead of time.
* Though this does the calc for all nodes, only tip ones are used.
* Current get_lca algorithm is only designed for tips anyway. */
double sep; // separation time, not actually used
for(i=0; i < *n_nodes; i++){
for(j=0; j < *n_nodes; j++){
lca_matrix[*n_nodes*i+j] = get_lca(i,j, *n_nodes, ancestor,
branch_length, &sep);
}
}
}
/** Simulate under the model. Called by R */
void simulate_model (double * Xo, double * alpha, double * theta,
double * sigma, int * regimes, int * ancestor,
double * branch_length, double * traits, int * n_nodes,
int * n_regimes, double * llik, double * seed)
{
/* Turn off likelihood calcuation on the simulated data for speed */
int return_likelihood = 0; // consider making an option at the .C level
int i,j;
tree * mytree = (tree *) malloc(sizeof(tree));
mytree->Xo = Xo;
mytree->alpha = alpha;
mytree->theta = theta;
mytree->sigma = sigma;
mytree->regimes = regimes;
mytree->ancestor = ancestor;
mytree->branch_length = branch_length;
mytree->traits = traits;
mytree->n_nodes = *n_nodes;
mytree->n_regimes = *n_regimes;
/* Save time by calculating least common ancestor ahead of time. */
double sep; // separation time, not actually used
mytree->lca_matrix = (int *) malloc(gsl_pow_2(*n_nodes) * sizeof(int) );
for(i=0; i < *n_nodes; i++){
for(j=0; j < *n_nodes; j++){
mytree->lca_matrix[*n_nodes*i+j] =
get_lca(i,j, *n_nodes, ancestor, branch_length, &sep);
}
}
/* Allocate the parameter vector */
gsl_vector *x = gsl_vector_alloc(1 + 3 * *n_regimes);
gsl_vector_set(x, 0, *Xo);
for(i = 0; i < *n_regimes; i++){
gsl_vector_set(x, 1+i, alpha[i]);
gsl_vector_set(x, 1+*n_regimes+i, theta[i]);
gsl_vector_set(x, 1+2 * *n_regimes+i, mytree->sigma[i]);
}
gsl_rng * rng = gsl_rng_alloc(gsl_rng_default);
gsl_rng_set(rng, *seed);
/* These are the only lines that differ from the fit_models wrapper */
simulate (rng, mytree);
if(return_likelihood){
calc_lik(mytree->Xo, mytree->alpha, mytree->theta, mytree->sigma,
mytree->regimes, mytree->ancestor, mytree->branch_length,
mytree->traits, &(mytree->n_nodes), mytree->lca_matrix, llik);
}
// for(i=0; i< mytree->n_regimes; i++) printf("%g %g %g\n", mytree->alpha[i], mytree->theta[i], mytree->sigma[i] );
// printf("sim llik: %g\n", *llik);
gsl_rng_free(rng);
gsl_vector_free(x);
free(mytree->lca_matrix);
free(mytree);
}
/** Test code by running in pure C */
int main(void)
{
/** Define the tree and the trait data (Anoles tree from "ouch" R package) */
int n_nodes = 45;
double branch_length[] = { 0.0, 12./38, 20./38, 2./38, 2./38, 4./38,
8./38, 5./38, 5./38, 5./38, 5./38, 10./38,
9./38, 4./38, 8./38, 2./38, 20./38, 2./38,
4./38, 2./38, 1./38, 2./38, 26./38, 4./38,
2./38, 2./38, 2./38, 2./38, 15./38, 10./38,
10./38, 10./38, 10./38, 16./38, 12./38, 4./38,
2./38, 2./38, 10./38, 8./38, 2./38, 1./38,
1./38, 2./38, 2./38};
/* Almost a star tree */
/* double branch_length[] = { 0.000, .001, .001, .001, .001,
0.001, .001, .001, .001, .001,
0.001, .001, .001, .001, .001,
0.001, .001, .001, .001, .001,
0.001, .001, .999, .999, .999,
0.999, .999, .999, .999, .999,
0.999, .999, .999, .999, .999,
0.999, .999, .999, .999, .999,
0.999, .999, .999, .999, .999 };
*/
int ancestor[] = {-1, 0, 1, 2, 3, 2, 0, 6, 7, 8, 9,
8, 7, 12, 13,14, 6, 16, 17, 18, 19, 18, 1,
3, 4, 4, 5, 5, 9, 10, 10, 11, 11, 12,
13, 14, 15, 15, 16, 17, 19, 20, 20, 21, 21};
double traits[] = {0.000000, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 0.000000, 0.000000, 0.000000,
0.000000, 0.000000, 2.602690, 2.660260, 2.660260,
2.653242, 2.674149, 2.701361, 7.161247, 13.299534,
3.328627, 3.353407, 3.360375, 3.049273, 2.906901,
2.980619, 2.933857, 3.975530, -3.104587, 3.346389,
12.928524, -12.939162, 7.990720, 8.058707, -5.068053};
/*
int regimes[] = {1, 1, 2, 2, 2,
2, 1, 1, 0, 0,
0, 0, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 2, 2, 2,
2, 2, 2, 0, 0,
0, 0, 0, 1, 1,
1, 1, 0, 1, 1,
1, 1, 1, 1, 1};
*/
int regimes[] = {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};
double Xo = 3;
double alpha[3] = {2.6, 2.6, 2.6};
double theta[3] = {3., 3.,3};
double sigma[3] = {0.2, 0.2, 0.2 };
int n_regimes = 3;
double llik = 0;
/* Initialize the lca matrix */
int * lca = (int *) calloc(n_nodes*n_nodes, sizeof(int));
/* test the pure likelihood function first */
calc_lca(ancestor, branch_length, &n_nodes, lca);
calc_lik(&Xo, alpha, theta, sigma, regimes, ancestor,
branch_length, traits, &n_nodes, lca, &llik);
printf("log likelihood: %g\n", llik);
/* We'll use the faster Nelder-Mead algorithm for the check */
int use_siman = 0;
/* Test the fitting routine */
fit_model(&Xo, alpha, theta, sigma, regimes, ancestor, branch_length,
traits, &n_nodes, &n_regimes, &llik, &use_siman);
printf("Xo = %g\n", Xo);
printf("alphas: %g %g %g\n", alpha[0], alpha[1], alpha[2]);
printf("thetas: %g %g %g\n", theta[0], theta[1], theta[2]);
printf("sigmas: %g %g %g\n", sigma[0], sigma[1], sigma[2]);
printf("log likelihood: %g\n", llik);
/* Test the simulation code */
/*
double seed = 1.0;
printf("seed: %lo\n", (unsigned long int) seed);
simulate_model(&Xo, alpha, theta, sigma, regimes, ancestor, branch_length,
traits, &n_nodes, &n_regimes, &llik, &seed);
int i;
printf("simulated traits:\n");
for(i=0; i < 45; i++)
printf("%g ", traits[i]);
printf("\n");
*/
free(lca);
return 0;
}
| {
"alphanum_fraction": 0.5735320524,
"avg_line_length": 32.284057971,
"ext": "c",
"hexsha": "de2d614c2aeb11183ed0a4de643b59fd784b767d",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "cboettig/wrightscape",
"max_forks_repo_path": "src/piecewise_regimes.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "cboettig/wrightscape",
"max_issues_repo_path": "src/piecewise_regimes.c",
"max_line_length": 116,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "cboettig/wrightscape",
"max_stars_repo_path": "src/piecewise_regimes.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3820,
"size": 11138
} |
/* Cholesky Decomposition
*
* Copyright (C) 2000 Thomas Walter
*
* 03 May 2000: Modified for GSL by Brian Gough
* 29 Jul 2005: Additions by Gerard Jungman
* Copyright (C) 2000,2001, 2002, 2003, 2005, 2007 Brian Gough, Gerard Jungman
*
* This 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, or (at your option) any
* later version.
*
* This source 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.
*/
/*
* Cholesky decomposition of a symmetrix positive definite matrix.
* This is useful to solve the matrix arising in
* periodic cubic splines
* approximating splines
*
* This algorithm does:
* A = L * L'
* with
* L := lower left triangle matrix
* L' := the transposed form of L.
*
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
static inline
double
quiet_sqrt (double x)
/* avoids runtime error, for checking matrix for positive definiteness */
{
return (x >= 0) ? sqrt(x) : GSL_NAN;
}
int
gsl_linalg_cholesky_decomp (gsl_matrix * A)
{
const size_t M = A->size1;
const size_t N = A->size2;
if (M != N)
{
GSL_ERROR("cholesky decomposition requires square matrix", GSL_ENOTSQR);
}
else
{
size_t i,j,k;
int status = 0;
/* Do the first 2 rows explicitly. It is simple, and faster. And
* one can return if the matrix has only 1 or 2 rows.
*/
double A_00 = gsl_matrix_get (A, 0, 0);
double L_00 = quiet_sqrt(A_00);
if (A_00 <= 0)
{
status = GSL_EDOM ;
}
gsl_matrix_set (A, 0, 0, L_00);
if (M > 1)
{
double A_10 = gsl_matrix_get (A, 1, 0);
double A_11 = gsl_matrix_get (A, 1, 1);
double L_10 = A_10 / L_00;
double diag = A_11 - L_10 * L_10;
double L_11 = quiet_sqrt(diag);
if (diag <= 0)
{
status = GSL_EDOM;
}
gsl_matrix_set (A, 1, 0, L_10);
gsl_matrix_set (A, 1, 1, L_11);
}
for (k = 2; k < M; k++)
{
double A_kk = gsl_matrix_get (A, k, k);
for (i = 0; i < k; i++)
{
double sum = 0;
double A_ki = gsl_matrix_get (A, k, i);
double A_ii = gsl_matrix_get (A, i, i);
gsl_vector_view ci = gsl_matrix_row (A, i);
gsl_vector_view ck = gsl_matrix_row (A, k);
if (i > 0) {
gsl_vector_view di = gsl_vector_subvector(&ci.vector, 0, i);
gsl_vector_view dk = gsl_vector_subvector(&ck.vector, 0, i);
gsl_blas_ddot (&di.vector, &dk.vector, &sum);
}
A_ki = (A_ki - sum) / A_ii;
gsl_matrix_set (A, k, i, A_ki);
}
{
gsl_vector_view ck = gsl_matrix_row (A, k);
gsl_vector_view dk = gsl_vector_subvector (&ck.vector, 0, k);
double sum = gsl_blas_dnrm2 (&dk.vector);
double diag = A_kk - sum * sum;
double L_kk = quiet_sqrt(diag);
if (diag <= 0)
{
status = GSL_EDOM;
}
gsl_matrix_set (A, k, k, L_kk);
}
}
/* Now copy the transposed lower triangle to the upper triangle,
* the diagonal is common.
*/
for (i = 1; i < M; i++)
{
for (j = 0; j < i; j++)
{
double A_ij = gsl_matrix_get (A, i, j);
gsl_matrix_set (A, j, i, A_ij);
}
}
if (status == GSL_EDOM)
{
GSL_ERROR ("matrix must be positive definite", GSL_EDOM);
}
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_solve (const gsl_matrix * LLT,
const gsl_vector * b,
gsl_vector * x)
{
if (LLT->size1 != LLT->size2)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else if (LLT->size1 != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (LLT->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
/* Copy x <- b */
gsl_vector_memcpy (x, b);
/* Solve for c using forward-substitution, L c = b */
gsl_blas_dtrsv (CblasLower, CblasNoTrans, CblasNonUnit, LLT, x);
/* Perform back-substitution, U x = c */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LLT, x);
return GSL_SUCCESS;
}
}
int
gsl_linalg_cholesky_svx (const gsl_matrix * LLT,
gsl_vector * x)
{
if (LLT->size1 != LLT->size2)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else if (LLT->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
/* Solve for c using forward-substitution, L c = b */
gsl_blas_dtrsv (CblasLower, CblasNoTrans, CblasNonUnit, LLT, x);
/* Perform back-substitution, U x = c */
gsl_blas_dtrsv (CblasUpper, CblasNoTrans, CblasNonUnit, LLT, x);
return GSL_SUCCESS;
}
}
/*
gsl_linalg_cholesky_invert()
Compute the inverse of a symmetric positive definite matrix in
Cholesky form.
Inputs: LLT - matrix in cholesky form on input
A^{-1} = L^{-t} L^{-1} on output
Return: success or error
*/
int
gsl_linalg_cholesky_invert(gsl_matrix * LLT)
{
if (LLT->size1 != LLT->size2)
{
GSL_ERROR ("cholesky matrix must be square", GSL_ENOTSQR);
}
else
{
size_t N = LLT->size1;
size_t i, j;
double sum;
gsl_vector_view v1, v2;
/* invert the lower triangle of LLT */
for (i = 0; i < N; ++i)
{
double ajj;
j = N - i - 1;
gsl_matrix_set(LLT, j, j, 1.0 / gsl_matrix_get(LLT, j, j));
ajj = -gsl_matrix_get(LLT, j, j);
if (j < N - 1)
{
gsl_matrix_view m;
m = gsl_matrix_submatrix(LLT, j + 1, j + 1,
N - j - 1, N - j - 1);
v1 = gsl_matrix_subcolumn(LLT, j, j + 1, N - j - 1);
gsl_blas_dtrmv(CblasLower, CblasNoTrans, CblasNonUnit,
&m.matrix, &v1.vector);
gsl_blas_dscal(ajj, &v1.vector);
}
} /* for (i = 0; i < N; ++i) */
/*
* The lower triangle of LLT now contains L^{-1}. Now compute
* A^{-1} = L^{-t} L^{-1}
*
* The (ij) element of A^{-1} is column i of L^{-1} dotted into
* column j of L^{-1}
*/
for (i = 0; i < N; ++i)
{
for (j = i + 1; j < N; ++j)
{
v1 = gsl_matrix_subcolumn(LLT, i, j, N - j);
v2 = gsl_matrix_subcolumn(LLT, j, j, N - j);
/* compute Ainv_{ij} = sum_k Linv_{ki} Linv_{kj} */
gsl_blas_ddot(&v1.vector, &v2.vector, &sum);
/* store in upper triangle */
gsl_matrix_set(LLT, i, j, sum);
}
/* now compute the diagonal element */
v1 = gsl_matrix_subcolumn(LLT, i, i, N - i);
gsl_blas_ddot(&v1.vector, &v1.vector, &sum);
gsl_matrix_set(LLT, i, i, sum);
}
/* copy the transposed upper triangle to the lower triangle */
for (j = 1; j < N; j++)
{
for (i = 0; i < j; i++)
{
double A_ij = gsl_matrix_get (LLT, i, j);
gsl_matrix_set (LLT, j, i, A_ij);
}
}
return GSL_SUCCESS;
}
} /* gsl_linalg_cholesky_invert() */
int
gsl_linalg_cholesky_decomp_unit(gsl_matrix * A, gsl_vector * D)
{
const size_t N = A->size1;
size_t i, j;
/* initial Cholesky */
int stat_chol = gsl_linalg_cholesky_decomp(A);
if(stat_chol == GSL_SUCCESS)
{
/* calculate D from diagonal part of initial Cholesky */
for(i = 0; i < N; ++i)
{
const double C_ii = gsl_matrix_get(A, i, i);
gsl_vector_set(D, i, C_ii*C_ii);
}
/* multiply initial Cholesky by 1/sqrt(D) on the right */
for(i = 0; i < N; ++i)
{
for(j = 0; j < N; ++j)
{
gsl_matrix_set(A, i, j, gsl_matrix_get(A, i, j) / sqrt(gsl_vector_get(D, j)));
}
}
/* Because the initial Cholesky contained both L and transpose(L),
the result of the multiplication is not symmetric anymore;
but the lower triangle _is_ correct. Therefore we reflect
it to the upper triangle and declare victory.
*/
for(i = 0; i < N; ++i)
for(j = i + 1; j < N; ++j)
gsl_matrix_set(A, i, j, gsl_matrix_get(A, j, i));
}
return stat_chol;
}
| {
"alphanum_fraction": 0.5290315631,
"avg_line_length": 25.8579387187,
"ext": "c",
"hexsha": "8519fdce77e82b952153f77923fc99bc98c3d6e2",
"lang": "C",
"max_forks_count": 173,
"max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z",
"max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_forks_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_forks_repo_name": "juandesant/astrometry.net",
"max_forks_repo_path": "gsl-an/linalg/cholesky.c",
"max_issues_count": 208,
"max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z",
"max_issues_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_issues_repo_name": "juandesant/astrometry.net",
"max_issues_repo_path": "gsl-an/linalg/cholesky.c",
"max_line_length": 86,
"max_stars_count": 460,
"max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_stars_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_stars_repo_name": "juandesant/astrometry.net",
"max_stars_repo_path": "gsl-an/linalg/cholesky.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z",
"num_tokens": 2714,
"size": 9283
} |
#ifdef HAVE_PETSC
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <mpi.h>
#include <petsc.h>
#include "common_c.h"
#include "FCMangle.h"
#define fillsparsecpetscs FortranCInterface_GLOBAL_(fillsparsecpetscs, FILLSPARSECPETSCS)
#define fillsparsecpetscc FortranCInterface_GLOBAL_(fillsparsecpetscc, FILLSPARSECPETSCC)
#define COLMAJ2D(row,col,numrow) (row-1)+(col-1)*numrow
#define COLMAJ3D(a,b,c,amax,bmax,cmax) (a-1)+amax*((b-1)+bmax*(c-1))
#define ROWMAJ2D_ONE(row,col,numcol) (row-1)*numcol+(col-1)
typedef long long int gcorp_t;
void fillsparsecpetscs(gcorp_t* ieng, double* EGmass, Mat* lhsP)
{
int npro = propar.npro;
int nshl = shpdat.nshl;
double* mb = (double*) malloc(sizeof(double)*nshl*nshl); //block to insert
int e,i,j,aa; //following along with fillsparse.f
PetscInt* locat = (PetscInt*) malloc(sizeof(PetscInt)*nshl);
for(e=0;e<npro;e++)
{
for(aa=0;aa<nshl;aa++) locat[aa]=ieng[e+npro*aa]-1;
// for(aa=0;aa<nshl;aa++) assert(locat[aa]>=0);
for (i=0; i<nshl; i++) { // fill up Ke with respective egmass
for (j=0; j<nshl; j++) {
mb[nshl*i + j] = EGmass[e + npro*(i + nshl*j)];
}
}
//MatSetValuesBlocked(*lhsP, nshl , locat, nshl, locat, mb, ADD_VALUES);
PetscInt petsc_nshl;
petsc_nshl = (PetscInt) nshl;
MatSetValues(*lhsP, petsc_nshl , locat, petsc_nshl, locat, mb, ADD_VALUES);
}
free(mb);
free(locat);
}
void fillsparsecpetscc(gcorp_t* ieng, double* EGmass, Mat* lhsP)
{
int npro = propar.npro;
int nshl = shpdat.nshl;
int nedof = conpar.nedof;
double* mb = (double*) malloc(sizeof(double)*nedof*nedof); //block to insert
int e,i,j,aa; //following along with fillsparse.f
//int* locat = (int*) malloc(sizeof(int)*nshl);
PetscInt* locat = (PetscInt*) malloc(sizeof(PetscInt)*nshl);
for(e=0;e<npro;e++)
{
for(aa=0;aa<nshl;aa++) locat[aa]=ieng[e+npro*aa]-1;
// for(aa=0;aa<nshl;aa++) assert(locat[aa]>=0);
for (i=0; i<nedof; i++) { /* fill up Ke with respective egmass */
for (j=0; j<nedof; j++) {
mb[nedof*i + j] = EGmass[e + npro*(i + nedof*j)];
}
}
//MatSetValuesBlocked(*lhsP, nshl , locat, nshl, locat, mb, ADD_VALUES);
PetscInt petsc_nshl;
petsc_nshl = (PetscInt) nshl;
MatSetValuesBlocked(*lhsP, petsc_nshl , locat, petsc_nshl, locat, mb, ADD_VALUES);
}
free(mb);
free(locat);
}
#endif
| {
"alphanum_fraction": 0.5974173946,
"avg_line_length": 36.0684931507,
"ext": "c",
"hexsha": "9ed0e764db666447f2f8337bfaf4daa625f0d58e",
"lang": "C",
"max_forks_count": 38,
"max_forks_repo_forks_event_max_datetime": "2021-11-12T19:38:00.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-04-21T12:13:40.000Z",
"max_forks_repo_head_hexsha": "a096094f33b98047de0a2e28225c4d74875a88d8",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "yangf4/phasta",
"max_forks_repo_path": "phSolver/common/fillsparse.c",
"max_issues_count": 21,
"max_issues_repo_head_hexsha": "a096094f33b98047de0a2e28225c4d74875a88d8",
"max_issues_repo_issues_event_max_datetime": "2017-12-17T03:47:51.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-10-06T19:50:43.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "yangf4/phasta",
"max_issues_repo_path": "phSolver/common/fillsparse.c",
"max_line_length": 91,
"max_stars_count": 49,
"max_stars_repo_head_hexsha": "a096094f33b98047de0a2e28225c4d74875a88d8",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "yangf4/phasta",
"max_stars_repo_path": "phSolver/common/fillsparse.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-07T01:02:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-16T13:45:34.000Z",
"num_tokens": 903,
"size": 2633
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include <iosfwd>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <gsl/gsl>
#include "onnxruntime_config.h"
namespace onnxruntime {
#ifdef __GNUC__
#pragma GCC diagnostic push
#ifdef HAS_NULL_DEREFERENCE
#pragma GCC diagnostic ignored "-Wnull-dereference"
#endif
#endif
class TensorShape {
// We use negative numbers for unknown symbolic dimension. Each negative
// number represents a unique symbolic dimension.
public:
TensorShape() = default;
TensorShape(const TensorShape& other) : TensorShape(other.GetDims()) {}
TensorShape& operator=(const TensorShape& other);
TensorShape(TensorShape&& other) { operator=(std::move(other)); }
TensorShape& operator=(TensorShape&& other);
TensorShape(gsl::span<const int64_t> dims);
TensorShape(const std::vector<int64_t>& dims) : TensorShape(gsl::make_span(dims)) {}
TensorShape(const std::initializer_list<int64_t>& dims) : TensorShape(gsl::make_span(dims)) {}
TensorShape(const int64_t* dimension_sizes, size_t dimension_count) : TensorShape(gsl::span<const int64_t>(dimension_sizes, dimension_count)) {}
TensorShape(const std::vector<int64_t>& dims, size_t start, size_t end) : TensorShape(gsl::span<const int64_t>(&dims[start], end - start)) {}
// Create a TensorShape that points to an existing buffer internally. As no copy is made, 'data' must remain valid for the life of the TensorShape
static const TensorShape FromExistingBuffer(const std::vector<int64_t>& data) {
return TensorShape(External{}, gsl::span<int64_t>(const_cast<int64_t*>(data.data()), data.size()));
}
/**
Return the dimension specified by <idx>.
*/
int64_t operator[](size_t idx) const { return values_[idx]; }
int64_t& operator[](size_t idx) { return values_[idx]; }
bool operator==(const TensorShape& other) const noexcept { return GetDims() == other.GetDims(); }
bool operator!=(const TensorShape& other) const noexcept { return GetDims() != other.GetDims(); }
size_t NumDimensions() const noexcept {
return values_.size();
}
/**
Copy dims into an array with given size
*/
void CopyDims(int64_t* dims, size_t num_dims) const {
memcpy(dims, values_.begin(), sizeof(int64_t) * std::min(num_dims, NumDimensions()));
}
/**
Copy dims from a specific start dim into an array with given size
`start_dim` is expected to be in the inclusive range [0, NumDimensions() - 1]
and this function does no checks to ensure that
*/
void CopyDims(int64_t* dims, size_t start_dim, size_t num_dims) const {
memcpy(dims, values_.begin() + start_dim, sizeof(int64_t) * std::min(num_dims, NumDimensions() - start_dim));
}
/**
Return underlying vector representation.
*/
gsl::span<const int64_t> GetDims() const { return values_; }
std::vector<int64_t> GetDimsAsVector() const { return std::vector<int64_t>(values_.begin(), values_.end()); }
/**
* Return the total number of elements. Returns 1 for an empty (rank 0) TensorShape.
*
* May return -1
*/
int64_t Size() const;
/**
Return the total number of elements up to the specified dimension.
If the dimension interval is empty (dimension == 0), return 1.
@param dimension Return size up to this dimension. Value must be between 0 and this->NumDimensions(), inclusive.
*/
int64_t SizeToDimension(size_t dimension) const;
/**
Return the total number of elements from the specified dimension to the end of the tensor shape.
If the dimension interval is empty (dimension == this->NumDimensions()), return 1.
@param dimension Return size from this dimension to the end. Value must be between 0 and this->NumDimensions(),
inclusive.
*/
int64_t SizeFromDimension(size_t dimension) const;
/**
Return a new TensorShape of the dimensions from dimstart to dimend.
*/
TensorShape Slice(size_t dimstart, size_t dimend) const;
/**
Return a new TensorShape of the dimensions from dimstart to end.
*/
TensorShape Slice(size_t dimstart) const { return Slice(dimstart, values_.size()); }
/**
output dimensions nicely formatted
*/
std::string ToString() const;
/**
Calculate size between start and end.
Assumes start and end are between 0 and this->NumDimensions(), inclusive, and that
start < end.
*/
int64_t SizeHelper(size_t start, size_t end) const;
/**
empty shape or 1D shape (1) is regarded as scalar tensor
*/
bool IsScalar() const {
size_t len = values_.size();
return len == 0 || (len == 1 && values_[0] == 1);
}
private:
struct External {};
TensorShape(External, gsl::span<int64_t> buffer) : values_{buffer} {}
void Allocate(size_t size);
gsl::span<int64_t> values_;
int64_t small_buffer_[5];
std::unique_ptr<int64_t[]> allocated_buffer_;
friend struct ProviderHostImpl; // So that the shared provider interface can access Allocate
};
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
// operator<< to nicely output to a stream
std::ostream& operator<<(std::ostream& out, const TensorShape& shape);
} // namespace onnxruntime
| {
"alphanum_fraction": 0.7072330654,
"avg_line_length": 34.84,
"ext": "h",
"hexsha": "365cbe26c58e312445f7d5b339ae3f49a89d9f6c",
"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": "21eb747a0fcad6559c4e601697e2f4fa06e2fb27",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jthelin/onnxruntime",
"max_forks_repo_path": "include/onnxruntime/core/framework/tensor_shape.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "435010ab6873974803591fa22262ed8b3e36e44d",
"max_issues_repo_issues_event_max_datetime": "2022-03-02T11:41:45.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-08-16T04:01:46.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "TingGong1/onnxruntime",
"max_issues_repo_path": "include/onnxruntime/core/framework/tensor_shape.h",
"max_line_length": 148,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "435010ab6873974803591fa22262ed8b3e36e44d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "TingGong1/onnxruntime",
"max_stars_repo_path": "include/onnxruntime/core/framework/tensor_shape.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-14T12:52:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-14T12:52:29.000Z",
"num_tokens": 1286,
"size": 5226
} |
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include "design.h"
/*This function computes the p-distance between 2 points in D dimensions:
the exponent p is tunable*/
double distance(double *x,double *y,int D,double p){
double dist = 0.0;
int i;
for(i=0;i<D;i++){
dist += pow(fabs(x[i]-y[i]),p);
}
return pow(dist,1.0/p);
}
/*This is the cost function of the problem: it is a sum of all the reciprocal of
the pairs distances, with some tunable exponent lambda; note that the final
1/lambda exponentiation is not performed here!*/
double cost(gsl_matrix *data,int Npoints,int D,double p,double lambda){
double sum = 0.0;
int i,j;
for(i=0;i<Npoints;i++){
for(j=i+1;j<Npoints;j++){
//Add the contribution of pair (i,j) to the cost function
sum += pow(pow(D,1.0/p)/distance(gsl_matrix_ptr(data,i,0),gsl_matrix_ptr(data,j,0),D,p),lambda);
}
}
return (2.0/(Npoints*(Npoints-1)))*sum;
}
/*This computes the cost function in the particular case in which all the points are
equally spaced on the diagonal of the hypercube*/
double diagonalCost(int Npoints,double lambda){
double sum = 0.0;
int i,j;
for(i=0;i<Npoints;i++){
for(j=i+1;j<Npoints;j++){
//Add the contribution of pair (i,j) to the cost function
sum += pow((Npoints-1)*1.0/(j-i),lambda);
}
}
return (2.0/(Npoints*(Npoints-1)))*sum;
}
/*This function computes the variation of the cost when a pair of coordinates is exchanged;
this function also performs an in-place swap of the coordinates. More specifically:
this function swaps coordinate d of points i1 and i2 and returns the variation of the cost
function due to this swap*/
/**/
double swap(gsl_matrix *data,int Npoints,int D,double p,double lambda,int i1,int i2, int d){
double costBefore,costAfter,temp;
int i;
//initialize to 0
costBefore = costAfter = 0.0;
/*compute the contribution of points i1 and i2 to the cost function, before swapping;
sum over all the particles except i1 and i2*/
for(i=0;i<Npoints;i++){
if(i!=i1 && i!=i2){
costBefore += pow(pow(D,1.0/p)/distance(gsl_matrix_ptr(data,i,0),gsl_matrix_ptr(data,i1,0),D,p),lambda) + pow(pow(D,1.0/p)/distance(gsl_matrix_ptr(data,i,0),gsl_matrix_ptr(data,i2,0),D,p),lambda);
}
}
//perform the coordinate swap
temp = gsl_matrix_get(data,i1,d);
gsl_matrix_set(data,i1,d,gsl_matrix_get(data,i2,d));
gsl_matrix_set(data,i2,d,temp);
/*compute the contribution of points i1 and i2 to the cost function, after swapping;
sum over all the particles except i1 and i2*/
for(i=0;i<Npoints;i++){
if(i!=i1 && i!=i2){
costAfter += pow(pow(D,1.0/p)/distance(gsl_matrix_ptr(data,i,0),gsl_matrix_ptr(data,i1,0),D,p),lambda) + pow(pow(D,1.0/p)/distance(gsl_matrix_ptr(data,i,0),gsl_matrix_ptr(data,i2,0),D,p),lambda);
}
}
//return the cost difference
return (2.0/(Npoints*(Npoints-1)))*(costAfter - costBefore);
}
/*This function swaps the particle pair back: needed if the original swap didn't improve the cost function*/
void swapBack(gsl_matrix *data,int i1,int i2,int d){
double temp;
//perform the coordinate swap
temp = gsl_matrix_get(data,i1,d);
gsl_matrix_set(data,i1,d,gsl_matrix_get(data,i2,d));
gsl_matrix_set(data,i2,d,temp);
}
/*Main design sampler*/
double sample(int Npoints,int D,double p,double lambda,int seed,int maxIterations,gsl_matrix *data,double *costValues){
int i,d,i1,i2,iterCount;
const gsl_rng_type *T;
gsl_rng *r;
gsl_permutation *perm = gsl_permutation_alloc(Npoints);
double currentCost,deltaCost,deltaPerc;
//Initialize random number generator
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
//Initialize permutation
gsl_permutation_init(perm);
//Initialize random number generator with provided seed
gsl_rng_set(r,seed);
//Initialize the point coordinates in data with random permutations of (1..Npoints) to enforce latin hypercube structure
for(d=0;d<D;d++){
//Shuffle the numbers
gsl_ran_shuffle(r,perm->data,Npoints,sizeof(size_t));
//Permute coordinates
for(i=0;i<Npoints;i++){
gsl_matrix_set(data,i,d,(double)perm->data[i]/(Npoints-1));
}
}
/*The loop does the following: it swaps a random coordinate of a random pair,
checks if the cost is lower. If so, it keeps the configuration, otherwise it
reverses it and tries a new one.*/
iterCount = 0;
currentCost = cost(data,Npoints,D,p,lambda);
deltaPerc = 0.0;
while(1){
//Decide which coordinate to swap of which pair
i1 = gsl_rng_uniform_int(r,Npoints);
while((i2=gsl_rng_uniform_int(r,Npoints))==i1);
d = gsl_rng_uniform_int(r,D);
//Compute the change in the cost function
deltaCost = swap(data,Npoints,D,p,lambda,i1,i2,d);
/*Check if gain in cost is positive or negative: if positive, revert the swap, if negative keep it;
anyway, log the result*/
if(deltaCost>=0){
swapBack(data,i1,i2,d);
} else{
currentCost += deltaCost;
deltaPerc = deltaCost/currentCost;
}
//Save the current cost to array
costValues[iterCount] = currentCost;
//Criterion to break the loop
if(++iterCount == maxIterations) break;
}
//Release resources for random number generator and permutations
gsl_rng_free(r);
gsl_permutation_free(perm);
//Return the relative cost change due to the last iteration
return deltaPerc;
} | {
"alphanum_fraction": 0.7133048803,
"avg_line_length": 25.9086538462,
"ext": "c",
"hexsha": "f99fec28cf49bce2c454c7f2beae670453f83130",
"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": "e155d6d39361e550906cec00dbbc57686a4bca5c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "asabyr/LensTools",
"max_forks_repo_path": "lenstools/extern/design.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e155d6d39361e550906cec00dbbc57686a4bca5c",
"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": "asabyr/LensTools",
"max_issues_repo_path": "lenstools/extern/design.c",
"max_line_length": 199,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e155d6d39361e550906cec00dbbc57686a4bca5c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "asabyr/LensTools",
"max_stars_repo_path": "lenstools/extern/design.c",
"max_stars_repo_stars_event_max_datetime": "2021-04-27T02:03:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-27T02:03:11.000Z",
"num_tokens": 1542,
"size": 5389
} |
#ifndef QCQP_B_H
#define QCQP_B_H
#include "Matrix.h"
#include "ALM_L_Katyusha.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
min 1/2 x^\top Q_0 x+b_0^\top x
s.t. 1/2 x^\top Q_i x+b_i^\top x -1\leq 0,\enspace \forall i=1,\dots,m
-b\leq x\leq b
using IPALM with loopless Katyusha as inner solver.
*/
template<typename L, typename D>
class QCQP_b: public ALM_L_Katyusha<L, D>
{
private:
vector<D> Lambda; // maximal eigenvalues of Q0, Q1,...Qm.
vector<D> norm_c; //||[b0;b1;...;bm] ||_2
vector<D> norm_1_c; //||[b0;b1;...;bm] ||_1
D b; // absolute bound on each variable
D nb_q_c; //number of quadratic constraints
D nb_v; //number of variables
Matrix<L,D> data_Q; // Q=[Q0;Q1;...;Qm]; b=[b0;b1;...;bm].
protected:
public:
QCQP_b(const char* Matrix_file,D val_b)
:ALM_L_Katyusha<L,D>(), data_Q(Matrix_file)
{
b= val_b;
nb_v=data_Q.nfeatures;
nb_q_c=data_Q.nsamples/data_Q.nfeatures- 1;
this->mu_g=0;
}
inline D get_n(){
return data_Q.nfeatures;
}
inline D get_m(){
return data_Q.nsamples/data_Q.nfeatures- 1;
}
void set_dimension(){
this->d= nb_v;
this->m= nb_q_c;
}
void set_is_feasibility_constraint(){
for(L i=0;i<nb_q_c;i++)
this->is_feasiblity_constraint[i]=1;
}
inline D value_of_P(vector<D> & x){
D res=0;
for(L i=0;i<this->d;i++)
{
if (fabs(x[i])> b){
cout<< "error: the variable x_"<< i<<"="<<x[i]<<". It should be in [-"<<b<<", "<<b<<" ]"<< endl;
system("pause");
return std::numeric_limits<double>::max();
}
}
return res;
}
inline void prox_of_P(D alpha,vector<D> & x, vector<D> & y){
for(L i=0;i<this->d;i++)
{
D x2=x[i];
if (x2>= b){
y[i]=b;
}
else if(x2<=-b){
y[i]=-b;
}
else{
y[i]=x2;
}
}
}
D prox_of_h_star_j(D x,D beta, L j){
if(x>=0) return x;
else return 0;
}
D value_of_h_star_j(D x,L j){
if(x>=0) return 0;
else {
cout<< "Error! x="<<x<<" should be nonnegative."<<endl;
system("pause");
return std::numeric_limits<double>::max();
}
}
void compute_gradient_f0(vector<D> & x, vector<D>& g){
for(L j=0;j<nb_v;j++){
g[j]=0;
for(L k = data_Q.ptr[j]; k < data_Q.ptr[j + 1];k++){
L kj=data_Q.row_idx[k];
g[j]+=x[kj]*data_Q.A[k];
}
g[j]+=data_Q.b[j];
}
}
D compute_gradient_and_value_f_i(vector<D> & x ,vector<D> & g, L i){
D fi=0;
for(L j=0;j<nb_v;j++){
g[j]=0;
L j2=i*nb_v+j;
for(L k = data_Q.ptr[j2]; k < data_Q.ptr[j2 + 1];k++){
L kj=data_Q.row_idx[k];
g[j]+=x[kj]*data_Q.A[k];
}
D bj=data_Q.b[j2];
fi+=x[j]*g[j]/2+x[j]*bj;
g[j]+=bj;
}
return fi-1;
}
D value_of_f0(vector<D> & x){
return my_value_of_f_i( x, 0);
}
D value_of_f_i(vector<D> & x, L i){
return my_value_of_f_i( x, i)-1;
}
D my_value_of_f_i(vector<D> & x, L i){
D fi=0;
for(L j=0;j<nb_v;j++){
D Qjx=0;
L j2=i*nb_v+j;
for(L k = data_Q.ptr[j2]; k < data_Q.ptr[j2 + 1];k++){
L kj=data_Q.row_idx[k];
Qjx+=x[kj]*data_Q.A[k];
}
fi+=x[j]*Qjx/2+x[j]*data_Q.b[j2];
}
return fi;
}
D value_of_h_j(D x, L i){
cout<< "Error! The "<<i<<"th function should be a feasibility constraint"<< endl;
system("pause");
return std::numeric_limits<double>::max();
}
D distance_to_domain_of_h_j(D x, L i){
if(x<=0)
return 0;
else
return x;
}
D compute_Qi_x(vector<D> & x ,vector<D> & g, L i){
D normg=0;
for(L j=0;j<nb_v;j++){
g[j]=0;
L j2=i*nb_v+j;
for(L k = data_Q.ptr[j2]; k < data_Q.ptr[j2 + 1];k++){
L kj=data_Q.row_idx[k];
g[j]+=x[kj]*data_Q.A[k];
}
normg+=g[j]*g[j];
}
return sqrt(normg);
}
void compute_lambda(){
D maxv=0;
D minv=std::numeric_limits<double>::max();
Lambda.resize(nb_q_c+1);
norm_c.resize(nb_q_c+1,0);
norm_1_c.resize(nb_q_c+1,0);
std::vector<D> xk(nb_v,1);
std::vector<D> yk(nb_v);
D normk;
D tmp;
for (L i= 0; i<nb_q_c+1 ; i++){
for(L kk=0;kk<20;kk++){
normk= compute_Qi_x(xk , yk ,i);
for (L j=0;j<nb_v;j++)
xk[j]=yk[j]/normk;
}
D res=0;
normk= compute_Qi_x(xk, yk ,i);
for (L j=0;j<nb_v;j++)
res+=xk[j]*yk[j];
Lambda[i]= res;
if (res> maxv){
maxv= res;
}
if (res< minv){
minv= res;
}
D res2= 0;
D res3= 0;
for (L j=0; j< nb_v; j++){
res2+= data_Q.b[i*nb_v+j]*data_Q.b[i*nb_v+j];
res3+= fabs(data_Q.b[i*nb_v+j]);
}
norm_c[i]= sqrt(res2);
norm_1_c[i]=res3;
}
cout<< "max Lambda= "<< maxv<< " min Lambda= "<< minv<< endl;
}
inline void set_Li_Lf(){
this->Li.clear();
this->Li.resize(this->nsamples,0);
this->Li[0]=this->nsamples*Lambda[0];
this->Lf=Lambda[0];
D maxLi=this->Li[0];
D minLi=this->Li[0];
for (L i=0; i< nb_q_c; i++){
D M_p_j= nb_v*Lambda[i+ 1]*b*b+ b*norm_1_c[i+1]+ 1;
D M_dp_j= sqrt(nb_v)*Lambda[i+ 1]*b+ norm_c[i+1];
D L_dp_j= Lambda[i+1];
D d_s_j= M_p_j+ this->beta_s*this->lambda_s[i];
D tmp=L_dp_j*d_s_j/this->beta_s+ M_dp_j*M_dp_j/this->beta_s;
this->Li[i+1]= this->nsamples*tmp;
this->Lf+=tmp;
if (this->Li[i+1]> maxLi){
maxLi= this->Li[i+ 1];
}
if (this->Li[i+ 1]< minLi){
minLi= this->Li[i+ 1];
}
}
this->sumLi=this->Lf*this->nsamples;
cout<<" max of Li: "<<maxLi<<" min of Li: "<<minLi<<" sumLi="<<this->sumLi<<" Lf= "<<this->Lf<<endl;
}
void ALM_QCQP_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){
compute_lambda();
this->ALM_solve_with_L_Katyusha(beta_0, epsilon_0, eta, rho,x0,y0, val_tau, max_nb_outer, p_N_1, p_N_2, filename1, filename2, time);
}
};
#endif
| {
"alphanum_fraction": 0.5386450382,
"avg_line_length": 21.8333333333,
"ext": "h",
"hexsha": "2ff602fa92517161e81974a8b0a1fdaf840f64b7",
"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/QCQP_b.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/QCQP_b.h",
"max_line_length": 178,
"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/QCQP_b.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2265,
"size": 6288
} |
#ifndef SEARCHPATTERNHEXMATCHER_HHHHH
#define SEARCHPATTERNHEXMATCHER_HHHHH
#include <gsl/string_span>
#include <vector>
#include <string>
#include <algorithm>
#include "SearchPatternBase.h"
namespace MPSig {
namespace detail {
class SearchPatternHexMatcher final : public SearchPatternBase {
private:
std::vector<std::pair<char, bool>> m_compiledPattern;
public:
SearchPatternHexMatcher(gsl::cstring_span<-1> hexPattern);
virtual SearchPatternBase::ExecFirstResult<gsl_span_cit_t> ExecFirst(const MPSig::SigScannerMemoryData& data, gsl_span_cit_t begin, gsl_span_cit_t end) const override;
virtual SearchPatternBase::ExecFirstResult<gsl_span_crit_t> ExecFirst(const MPSig::SigScannerMemoryData& data, gsl_span_crit_t begin, gsl_span_crit_t end) const override;
virtual SearchPatternBase::ExecFirstResult<gsl_span_cit_t> ExecDepend(const MPSig::SigScannerMemoryData& data, gsl_span_cit_t begin, gsl_span_cit_t end) const override;
virtual SearchPatternBase::ExecFirstResult<gsl_span_crit_t> ExecDepend(const MPSig::SigScannerMemoryData& data, gsl_span_crit_t begin, gsl_span_crit_t end) const override;
virtual std::unique_ptr<SearchPatternBase> Clone() const override;
};
}
}
#endif
| {
"alphanum_fraction": 0.7417910448,
"avg_line_length": 41.875,
"ext": "h",
"hexsha": "22ce6c5c65606e8e62c6243854a6b23c55cb8a06",
"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": "13f290ec593ddbeed3c59c7fba642c1704bfd529",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "KevinW1998/MultipassSigScanner",
"max_forks_repo_path": "src/search/detail/SearchPatternHexMatcher.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529",
"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": "KevinW1998/MultipassSigScanner",
"max_issues_repo_path": "src/search/detail/SearchPatternHexMatcher.h",
"max_line_length": 183,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "KevinW1998/MultipassSigScanner",
"max_stars_repo_path": "src/search/detail/SearchPatternHexMatcher.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 314,
"size": 1340
} |
/* AUTORIGHTS
Copyright (C) 2007 Princeton University
This file is part of Ferret Toolkit.
Ferret Toolkit is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "LSH.h"
extern int LSH_release (cass_table_t *table);
extern int LSH_dump (cass_table_t *table);
int LSH_init_private (cass_table_t *table, const char *param)
{
LSH_t *lsh;
cass_size_t D, M, L, H;
cass_size_t n;
const gsl_rng_type *T;
gsl_rng *r;
int i, j;
float w;
lsh = type_calloc(LSH_t, 1);
assert(table->parent_cfg != NULL);
D = lsh->D = table->parent_cfg->vec_dim;
M = lsh->M = param_get_int(param, "-M", 10);
assert(M <= sizeof(uint32_t) * 8);
L = lsh->L = param_get_int(param, "-L", 1);
H = lsh->H = param_get_int(param, "-H", 1017881);
lsh->W = type_calloc(float, L);
w = param_get_float(param, "-w", 1.0);
for (i = 0; i < L; i++) lsh->W[i] = w;
if (strstr(param, "-W") && strstr(param, "-recall")) debug("-W and -recall conflicts.\n");
param_get_float_array(param, "-W", &n, lsh->W);
lsh->alphas = type_matrix_alloc(float, L * M, D);
lsh->rnd = type_matrix_alloc(uint32_t, L, M);
lsh->betas = (float *)malloc(L * M * sizeof(float));
lsh->tmp = type_matrix_alloc(uint32_t, L, M);
lsh->tmp2 = type_calloc(uint32_t, L);
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
for (i = 0; i < L * M; i++)
{
for (j = 0; j < D; j++)
{
lsh->alphas[i][j] = gsl_ran_gaussian(r, 1.0);
}
}
for (i = 0; i < L * M; i++)
{
lsh->betas[i] = gsl_rng_uniform(r) * lsh->W[i / M];
}
gsl_rng_free(r);
srand(0);
for (i = 0; i < L; i++)
for (j = 0; j < M; j++)
lsh->rnd[i][j] = rand();
lsh->est = NULL;
if (strstr(param, "-recall"))
{
cass_size_t d_step, max_T;
float d_min, d_max;
d_step = param_get_int(param, "-d_step", 100);
max_T = param_get_int(param, "-T_max", 100);
d_min = param_get_float(param, "-d_min", 0.0);
d_max = param_get_float(param, "-d_max", 100);
LSH_recall_init(&lsh->recall, d_step, d_min, d_max, lsh->M, lsh->L, max_T, lsh->W[0]);
}
table->__private = lsh;
return 0;
}
int LSH_free_private (cass_table_t *table)
{
LSH_t *lsh = table->__private;
if (table->loaded) LSH_release(table);
matrix_free(lsh->rnd);
free(lsh->betas);
matrix_free(lsh->alphas);
free(lsh->W);
matrix_free(lsh->tmp);
free(lsh->tmp2);
if (lsh->recall.table != NULL) LSH_recall_cleanup(&lsh->recall);
free(lsh);
table->__private = NULL;
return 0;
}
void LSH_hash2 (LSH_t *lsh, uint32_t **hash, uint32_t *hash2)
{
int i, j;
for (i = 0; i < lsh->L; i++)
{
hash2[i] = 0;
for (j = 0; j < lsh->M; j++)
{
hash2[i] += lsh->rnd[i][j] * hash[i][j];
}
hash2[i] %= lsh->H;
}
}
void LSH_hash (LSH_t *lsh, const float *pnt, uint32_t **hash)
{
float s;
int i, j, k, l;
l = 0;
for (i = 0; i < lsh->L; i++)
{
for (j = 0; j < lsh->M; j++)
{
s = lsh->betas[l];
for (k = 0; k < lsh->D; k++)
{
s += pnt[k] * lsh->alphas[l][k];
}
s /= lsh->W[i];
hash[i][j] = floor(s);
l++;
}
}
}
static inline void LSH_hash_L (LSH_t *lsh, float *pnt, uint32_t **hash, int L)
{
float s;
int j, k, l;
l = L * lsh->M;
for (j = 0; j < lsh->M; j++)
{
s = lsh->betas[l];
for (k = 0; k < lsh->D; k++)
{
s += pnt[k] * lsh->alphas[l][k];
}
s /= lsh->W[L];
hash[L][j] = floor(s);
l++;
}
}
static inline void LSH_hash2_L (LSH_t *lsh, uint32_t **hash, uint32_t *hash2, int L)
{
int j;
hash2[L] = 0;
for (j = 0; j < lsh->M; j++)
{
hash2[L] += lsh->rnd[L][j] * hash[L][j];
}
hash2[L] %= lsh->H;
}
static void LSH_insert (LSH_t *lsh, float *pnt, int tag)
{
int l;
LSH_hash(lsh, pnt, lsh->tmp);
LSH_hash2(lsh, lsh->tmp, lsh->tmp2);
for (l = 0; l < lsh->L; l++)
{
ohash_insert(&lsh->hash[l], lsh->tmp2[l], tag);
}
lsh->count++;
}
int LSH_batch_insert(cass_table_t *table, cass_dataset_t *parent, cass_vecset_id_t start, cass_vecset_id_t end)
{
LSH_t *lsh = table->__private;
uint32_t i, j, k;
cass_vec_t *vec;
for (i = start; i <= end; i++)
{
for (j = 0; j < parent->vecset[i].num_regions; j++)
{
k = j + parent->vecset[i].start_vecid;
vec = DATASET_VEC(parent, k);
LSH_insert(lsh, vec->u.float_data, k);
lsh->count++;
}
}
return 0;
}
/*
void LSH_mass_insert_parallel (LSH_t *lsh, float **pnt, int cnt)
{
int l;
#pragma omp parallel for schedule(static, 1) shared(lsh, pnt, cnt)
for (l = 0; l < lsh->L; l++)
{
printf("#TH = %d / %d\n", omp_get_thread_num(),
omp_get_num_threads());
int i;
for (i = 0; i < cnt; i++)
{
LSH_hash_L(lsh, pnt[i], tmp, l);
LSH_hash2_L(lsh, tmp, tmp2, l);
ohash_insert(&lsh->hash[l], tmp2[l], i);
}
}
}
*/
int LSH_restore_private (cass_table_t *table, CASS_FILE *fin)
{
int ret;
cass_size_t L, M, D;
int32_t recall;
LSH_t *lsh;
lsh = type_calloc(LSH_t, 1);
ret = cass_read_size(&lsh->D, 1, fin);
ret += cass_read_size(&lsh->M, 1, fin);
ret += cass_read_size(&lsh->L, 1, fin);
ret += cass_read_size(&lsh->H, 1, fin);
ret += cass_read_size(&lsh->count, 1, fin);
assert(ret == 5);
lsh->W = type_calloc(float, lsh->L);
ret = cass_read_float(lsh->W, lsh->L, fin);
assert(ret == lsh->L);
L = lsh->L;
M = lsh->M;
D = lsh->D;
lsh->alphas = type_matrix_alloc(float, L * M, D);
lsh->betas = type_calloc(float, L * M);
lsh->hash = NULL; //(ohash_t *)malloc(L * sizeof(ohash_t));
lsh->tmp = type_matrix_alloc(uint32_t, L, M);
lsh->tmp2 = malloc(sizeof(uint32_t) *L );
ret = cass_read_float(lsh->alphas[0], L * M * D, fin);
assert(ret == L * M * D);
ret = cass_read_float(lsh->betas, L * M, fin);
assert(ret == L * M);
lsh->rnd = type_matrix_alloc(uint32_t, L, M);
ret = cass_read_uint32(lsh->rnd[0], L * M, fin);
assert(ret == L * M);
ret = cass_read_int32(&recall, 1, fin);
assert(ret == 1);
if (recall)
{
if (LSH_recall_load(&lsh->recall, fin) != 0) assert(0);
}
table->__private = lsh;
return 0;
}
int LSH_checkpoint_private (cass_table_t *table, CASS_FILE *fout)
{
LSH_t *lsh = table->__private;
int ret;
cass_size_t L, M, D;
int32_t recall;
ret = cass_write_size(&lsh->D, 1, fout);
ret += cass_write_size(&lsh->M, 1, fout);
ret += cass_write_size(&lsh->L, 1, fout);
ret += cass_write_size(&lsh->H, 1, fout);
ret += cass_write_size(&lsh->count, 1, fout);
assert(ret == 5);
L = lsh->L;
M = lsh->M;
D = lsh->D;
ret = cass_write_float(lsh->W, L, fout);
assert(ret == L);
ret = cass_write_float(lsh->alphas[0], L * M * D, fout);
assert(ret == L * M * D);
ret = cass_write_float(lsh->betas, L * M, fout);
assert(ret == L * M);
ret = cass_write_uint32(lsh->rnd[0], L * M, fout);
assert(ret == L * M);
recall = (lsh->recall.table != NULL);
ret = cass_write_int32(&recall, 1, fout);
assert(ret == 1);
if (recall)
{
if (LSH_recall_dump(&lsh->recall, fout) != 0) assert(0);
}
if (lsh->hash != NULL && table->dirty) return LSH_dump(table);
return 0;
}
int LSH_load (cass_table_t *table)
{
LSH_t *lsh = table->__private;
CASS_FILE *fin;
uint32_t i;
int ret;
assert(lsh->hash == NULL);
if (lsh->count == 0)
{
lsh->hash = type_calloc(ohash_t, lsh->L);
for (i = 0; i < lsh->L; i++)
{
ohash_init(&(lsh->hash[i]), lsh->H);
}
return 0;
}
fin = cass_open(table->filename, "r");
if (fin == NULL) return CASS_ERR_IO;
lsh->hash = type_calloc(ohash_t, lsh->L);
for (i = 0; i < lsh->L; i++)
{
ret = ohash_init_with_stream(&lsh->hash[i], fin);
assert(ret == 0);
}
cass_close(fin);
return 0;
}
int LSH_release (cass_table_t *table)
{
int err = 0;
uint32_t i;
LSH_t *lsh = table->__private;
if (table->loaded && table->dirty) err = LSH_dump(table);
if (err != 0) return err;
for (i = 0; i < lsh->L; i++)
{
ohash_cleanup(&(lsh->hash[i]));
}
free(lsh->hash);
lsh->hash = NULL;
return 0;
}
int LSH_dump (cass_table_t *table)
{
uint32_t i;
int ret;
CASS_FILE *fout;
LSH_t *lsh = table->__private;
if (lsh->count == 0) return 0;
assert(lsh->hash != NULL);
fout = cass_open(table->filename, "w");
assert(fout != NULL);
for (i = 0; i < lsh->L; i++)
{
ret = ohash_dump_stream(&lsh->hash[i], fout);
assert(ret == 0);
}
cass_close(fout);
table->dirty = 0;
return ret;
}
void LSH_stat (LSH_t *lsh)
{
int i;
for (i = 0; i < lsh->L; i++)
{
printf("%d:", i);
ohash_stat(&lsh->hash[i]);
}
}
/*
int LSH_est_dump_file (LSH_est_t *est, char *filename)
{
int ret;
CASS_FILE *fout = cass_open(filename, "wb");
assert(fout != NULL);
ret = 0;
ret += cass_write_int(&est->a_step, 1, fout);
ret += cass_write_double(&est->a_min, 1, fout);
ret += cass_write_double(&est->a_max, 1, fout);
ret += cass_write_int(&est->b_step, 1, fout);
ret += cass_write_double(&est->b_min, 1, fout);
ret += cass_write_double(&est->b_max, 1, fout);
assert(ret == 6);
est->a_delta = (est->a_max - est->a_min) / est->a_step;
est->b_delta = (est->b_max - est->b_min) / est->b_step;
type_matrix_dump_stream(double, fout, est->a_step, est->b_step, est->a_table);
type_matrix_dump_stream(double, fout, est->a_step, est->b_step, est->b_table);
cass_close(fout);
return 0;
}
int LSH_est_init_with_file (LSH_est_t *est, char *filename)
{
int ret;
cass_size_t row, col;
CASS_FILE *fin = cass_open(filename, "rb");
assert(fin != NULL);
ret = 0;
ret += cass_read_int32(&est->a_step, 1, fin);
ret += cass_read_double(&est->a_min, 1, fin);
ret += cass_read_double(&est->a_max, 1, fin);
ret += cass_read_int32(&est->b_step, 1, fin);
ret += cass_read_double(&est->b_min, 1, fin);
ret += cass_read_double(&est->b_max, 1, fin);
assert(ret == 6);
est->a_delta = (est->a_max - est->a_min) / est->a_step;
est->b_delta = (est->b_max - est->b_min) / est->b_step;
type_matrix_load_stream(double, fin, &row, &col, &est->a_table);
assert(row == est->a_step);
assert(col == est->b_step);
type_matrix_load_stream(double, fin, &row, &col, &est->b_table);
assert(row == est->a_step);
assert(col == est->b_step);
cass_close(fin);
return 0;
}
*/
void LSH_est_cleanup (LSH_est_t *est)
{
matrix_free(est->a_table);
matrix_free(est->b_table);
}
double LSH_est (LSH_est_t *est, double a, double b, int K)
{
int A, B;
double alpha, beta;
if (!(finite(a) && finite(b))) return 0.0;
A = (a - est->a_min) / est->a_delta;
B = (b - est->b_min) / est->b_delta;
if (A < 0) return 0.0;
if (B < 0) return 0.0;
if (A >= est->a_step) A = est->a_step - 1;
if (B >= est->a_step) B = est->a_step - 1;
alpha = est->a_table[A][B];
beta = est->b_table[A][B];
return alpha * pow(K, beta);
}
int __LSH_query(cass_table_t *table,
cass_query_t *query, cass_result_t *result)
{
LSH_t *lsh = (LSH_t *)table->__private;
LSH_query_t query2;
cass_table_t *parent;
cass_dataset_t *ds;
cass_vec_dist_t *vec_dist;
cass_vecset_t *vecset;
float recall;
cass_size_t K, L, T;
uint32_t i, j;
assert(table->loaded);
vec_dist = cass_reg_get(&table->env->vec_dist, query->vec_dist_id);
assert(vec_dist != NULL);
if (vec_dist->__class != &vec_dist_L2_float) debug("LSH only works for L2 distance for float.\n");
if (table->parent_id == CASS_ID_INV) debug("LSH query requires parent.\n");
parent = cass_reg_get(&table->env->table, table->parent_id);
assert(parent != NULL);
if (!parent->loaded) debug("LSH query requires parent to be loaded.\n");
if (!(parent->opr->type & CASS_DATA)) debug("LSH only works on CASS_DATA.\n");
ds = (cass_dataset_t *)parent->__private;
K = query->topk;
if (K == 0) debug("LSH only works for KNN queries.\n");
L = param_get_int(query->extra_params, "-L", 1);
T = param_get_int(query->extra_params, "-T", 0);
recall = param_get_float(query->extra_params, "-recall", 0);
LSH_query_init(&query2, lsh, ds, K, L, T);
assert((query->flags & CASS_RESULT_BITMAPS) == 0);
assert((query->flags & CASS_RESULT_BITMAP) == 0);
assert((query->flags & CASS_RESULT_LIST) == 0);
assert(query->flags & CASS_RESULT_LISTS);
assert(query->candidate == NULL);
result->flags = CASS_RESULT_LISTS;
vecset = query->dataset->vecset + query->vecset_id;
if (query->flags & CASS_RESULT_USERMEM)
{
assert(result->u.lists.len >= vecset->num_regions);
}
else
{
result->flags |= CASS_RESULT_MALLOC;
ARRAY_INIT_SIZE(result->u.lists, vecset->num_regions);
result->u.lists.len = vecset->num_regions;
}
for (i = 0; i < vecset->num_regions; i++)
{
if (query->flags & CASS_RESULT_USERMEM)
{
assert(result->u.lists.data[i].size >= query->topk);
}
else
{
ARRAY_INIT_SIZE(result->u.lists.data[i], query->topk);
}
result->u.lists.data[i].len = query->topk;
if (recall == 0)
{
LSH_query(&query2, DATASET_VEC(query->dataset, vecset->start_vecid + i)->u.float_data);
}
else
{
LSH_query_recall(&query2, DATASET_VEC(query->dataset, vecset->start_vecid + i)->u.float_data, recall);
}
for (j = 0; j < K; j++)
{
result->u.lists.data[i].data[j] = query2.topk[j];
}
}
if (query->flags & CASS_RESULT_SORT)
{
for (j = 0; j < vecset->num_regions; j++)
{
TOPK_SORT_MIN(result->u.lists.data[j].data, cass_list_entry_t, dist, query->topk);
}
result->flags |= CASS_RESULT_SORT;
}
LSH_query_cleanup(&query2);
return 0;
}
int __LSH_batch_query(cass_table_t *table,
/* the dataset of all the queries should be the same */
uint32_t count, cass_query_t **queries, cass_result_t **results)
{
LSH_t *lsh = (LSH_t *)table->__private;
cass_result_t *result;
cass_query_t *query;
LSH_query_t query2;
const float **points;
cass_list_entry_t **topks;
cass_table_t *parent;
cass_dataset_t *ds;
cass_vec_dist_t *vec_dist;
cass_vecset_t *vecset;
cass_size_t K, L, T, vec_count;
uint32_t i, j, k;
query = queries[0];
assert(table->loaded);
vec_dist = cass_reg_get(&table->env->vec_dist, query->vec_dist_id);
assert(vec_dist != NULL);
if (vec_dist->__class != &vec_dist_L2_float) debug("LSH only works for L2 distance for float.\n");
if (table->parent_id == CASS_ID_INV) debug("LSH query requires parent.\n");
parent = cass_reg_get(&table->env->table, table->parent_id);
assert(parent != NULL);
if (!parent->loaded) debug("LSH query requires parent to be loaded.\n");
if (!(parent->opr->type & CASS_DATA)) debug("LSH only works on CASS_DATA.\n");
ds = (cass_dataset_t *)parent->__private;
K = query->topk;
if (K == 0) debug("LSH only works for KNN queries.\n");
L = param_get_int(query->extra_params, "-L", 1);
T = param_get_int(query->extra_params, "-T", 0);
LSH_query_init(&query2, lsh, ds, K, L, T);
assert((query->flags & CASS_RESULT_BITMAPS) == 0);
assert((query->flags & CASS_RESULT_BITMAP) == 0);
assert((query->flags & CASS_RESULT_LIST) == 0);
assert(query->flags & CASS_RESULT_LISTS);
assert(query->candidate == NULL);
vec_count = 0;
for (i = 0; i < count; i++)
{
result = results[i];
query = queries[i];
result->flags = CASS_RESULT_LISTS;
vecset = query->dataset->vecset + query->vecset_id;
if (query->flags & CASS_RESULT_USERMEM)
{
assert(result->u.lists.len >= vecset->num_regions);
}
else
{
result->flags |= CASS_RESULT_MALLOC;
ARRAY_INIT_SIZE(result->u.lists, vecset->num_regions);
result->u.lists.len = vecset->num_regions;
}
for (j = 0; j < vecset->num_regions; j++)
{
if (query->flags & CASS_RESULT_USERMEM)
{
assert(result->u.lists.data[j].size >= query->topk);
}
else
{
ARRAY_INIT_SIZE(result->u.lists.data[j], query->topk);
}
result->u.lists.data[j].len = K;
}
vec_count += vecset->num_regions;
}
points = type_calloc(const float *, vec_count);
topks = type_calloc(cass_list_entry_t *, vec_count);
k = 0;
for (i = 0; i < count; i++)
{
result = results[i];
query = queries[i];
vecset = query->dataset->vecset + query->vecset_id;
for (j = 0; j < vecset->num_regions; j++)
{
points[k] = DATASET_VEC(query->dataset, vecset->start_vecid + j)->u.float_data;
topks[k] = result->u.lists.data[j].data;
k++;
}
}
assert(k == vec_count);
if (strstr(query->extra_params, "-ca"))
{
LSH_query_batch_ca(&query2, vec_count, points, topks);
}
else
{
LSH_query_batch(&query2, vec_count, points, topks);
}
query = queries[0];
if (query->flags & CASS_RESULT_SORT)
{
for (i = 0; i < vec_count; i++)
{
TOPK_SORT_MIN(topks[i], cass_list_entry_t, dist, K);
}
for (i = 0; i < count; i++)
{
results[i]->flags |= CASS_RESULT_SORT;
}
}
LSH_query_cleanup(&query2);
return 0;
}
cass_table_opr_t opr_lsh = {
.name = "lsh",
.type = CASS_VEC_INDEX,
.vecset_type = CASS_ANY,
.vec_type = CASS_VEC_FLOAT,
.dist_vecset = CASS_ANY,
.dist_vec = CASS_VEC_DIST_TYPE_L2,
.cfg = NULL,
.tune = NULL, //mplsh_tune,
.init_private = LSH_init_private,
.batch_insert = LSH_batch_insert,
.query = __LSH_query, //mplsh_query,
.batch_query = __LSH_batch_query,
.load = LSH_load,
.release = LSH_release,
.checkpoint_private = LSH_checkpoint_private,
.restore_private = LSH_restore_private,
.free_private = LSH_free_private
};
| {
"alphanum_fraction": 0.6347131031,
"avg_line_length": 22.7467532468,
"ext": "c",
"hexsha": "f30faad3b64ba04464ffd9374bd9d268cb681fd2",
"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/netapps/netferret/src/server/src/lsh/LSH.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/netapps/netferret/src/server/src/lsh/LSH.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/netapps/netferret/src/server/src/lsh/LSH.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": 6059,
"size": 17515
} |
/* rng/cmrg.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
/* This is a combined multiple recursive generator. The sequence is,
z_n = (x_n - y_n) mod m1
where the two underlying generators x and y are,
x_n = (a_{1} x_{n-1} + a_{2} x_{n-2} + a_{3} x_{n-3}) mod m1
y_n = (b_{1} y_{n-1} + b_{2} y_{n-2} + b_{3} y_{n-3}) mod m2
with coefficients a11 ... a23,
a_{1} = 0, a_{2} = 63308, a_{3} = -183326
b_{1} = 86098, b_{2} = 0, b_{3} = -539608
and moduli m1, m2,
m1 = 2^31 - 1 = 2147483647
m2 = 2^31 - 2000169 = 2145483479
We initialize the generator with
x_1 = s_1 MOD m1, x_2 = s_2 MOD m1, x_3 = s_3 MOD m1
y_1 = s_4 MOD m2, y_2 = s_5 MOD m2, y_3 = s_6 MOD m2
where s_n = (69069 * s_{n-1}) mod 2^32 and s_0 = s is the
user-supplied seed.
NOTE: According to the paper the initial values for x_n must lie in
the range 0 <= x_n <= (m1 - 1) and the initial values for y_n must
lie in the range 0 <= y_n <= (m2 - 1), with at least one non-zero
value -- our seeding procedure satisfies these constraints.
We then use 7 iterations of the generator to "warm up" the internal
state.
The theoretical value of z_{10008} is 719452880. The subscript 10008
means (1) seed the generator with s=1, (2) do the seven warm-up
iterations that are part of the seeding process, (3) then do 10000
actual iterations.
The period of this generator is about 2^205.
From: P. L'Ecuyer, "Combined Multiple Recursive Random Number
Generators," Operations Research, 44, 5 (1996), 816--822.
This is available on the net from L'Ecuyer's home page,
http://www.iro.umontreal.ca/~lecuyer/myftp/papers/combmrg.ps
ftp://ftp.iro.umontreal.ca/pub/simulation/lecuyer/papers/combmrg.ps */
static inline unsigned long int cmrg_get (void *vstate);
static double cmrg_get_double (void *vstate);
static void cmrg_set (void *state, unsigned long int s);
static const long int m1 = 2147483647, m2 = 2145483479;
static const long int a2 = 63308, qa2 = 33921, ra2 = 12979;
static const long int a3 = -183326, qa3 = 11714, ra3 = 2883;
static const long int b1 = 86098, qb1 = 24919, rb1 = 7417;
static const long int b3 = -539608, qb3 = 3976, rb3 = 2071;
typedef struct
{
long int x1, x2, x3; /* first component */
long int y1, y2, y3; /* second component */
}
cmrg_state_t;
static inline unsigned long int
cmrg_get (void *vstate)
{
cmrg_state_t *state = (cmrg_state_t *) vstate;
/* Component 1 */
{
long int h3 = state->x3 / qa3;
long int p3 = -a3 * (state->x3 - h3 * qa3) - h3 * ra3;
long int h2 = state->x2 / qa2;
long int p2 = a2 * (state->x2 - h2 * qa2) - h2 * ra2;
if (p3 < 0)
p3 += m1;
if (p2 < 0)
p2 += m1;
state->x3 = state->x2;
state->x2 = state->x1;
state->x1 = p2 - p3;
if (state->x1 < 0)
state->x1 += m1;
}
/* Component 2 */
{
long int h3 = state->y3 / qb3;
long int p3 = -b3 * (state->y3 - h3 * qb3) - h3 * rb3;
long int h1 = state->y1 / qb1;
long int p1 = b1 * (state->y1 - h1 * qb1) - h1 * rb1;
if (p3 < 0)
p3 += m2;
if (p1 < 0)
p1 += m2;
state->y3 = state->y2;
state->y2 = state->y1;
state->y1 = p1 - p3;
if (state->y1 < 0)
state->y1 += m2;
}
if (state->x1 < state->y1)
return (state->x1 - state->y1 + m1);
else
return (state->x1 - state->y1);
}
static double
cmrg_get_double (void *vstate)
{
return cmrg_get (vstate) / 2147483647.0 ;
}
static void
cmrg_set (void *vstate, unsigned long int s)
{
/* An entirely adhoc way of seeding! This does **not** come from
L'Ecuyer et al */
cmrg_state_t *state = (cmrg_state_t *) vstate;
if (s == 0)
s = 1; /* default seed is 1 */
#define LCG(n) ((69069 * n) & 0xffffffffUL)
s = LCG (s);
state->x1 = s % m1;
s = LCG (s);
state->x2 = s % m1;
s = LCG (s);
state->x3 = s % m1;
s = LCG (s);
state->y1 = s % m2;
s = LCG (s);
state->y2 = s % m2;
s = LCG (s);
state->y3 = s % m2;
/* "warm it up" */
cmrg_get (state);
cmrg_get (state);
cmrg_get (state);
cmrg_get (state);
cmrg_get (state);
cmrg_get (state);
cmrg_get (state);
}
static const gsl_rng_type cmrg_type =
{"cmrg", /* name */
2147483646, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (cmrg_state_t),
&cmrg_set,
&cmrg_get,
&cmrg_get_double};
const gsl_rng_type *gsl_rng_cmrg = &cmrg_type;
| {
"alphanum_fraction": 0.6226523572,
"avg_line_length": 26.3535353535,
"ext": "c",
"hexsha": "49e8544345ea6db63d97bec1497fe9f2c0055aa2",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/rng/cmrg.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/rng/cmrg.c",
"max_line_length": 73,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/rng/cmrg.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": 1881,
"size": 5218
} |
#include <math.h>
#include <stdio.h>
#include <mpfr.h>
#include <stdlib.h>
#include <string.h>
#include <petsc.h>
#include <time.h>
#undef __FUNCT__
#define __FUNCT__ "MatVecMPFR"
PetscErrorCode MatVecMPFR(PetscInt size_d, mpfr_t *Mat, mpfr_t *vec, mpfr_t *result) {
PetscErrorCode ierr;
mpfr_t temp1;
mpfr_t *res;
PetscFunctionBegin;
mpfr_init(temp1);
res = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d);
for(PetscInt k=0; k < size_d; ++k)
mpfr_init(res[k]);
for(PetscInt i=0; i<size_d; ++i) {
mpfr_set_d(res[i], 0.0, MPFR_RNDN);
for(PetscInt j=0; j<size_d; ++j) {
mpfr_mul(temp1, Mat[i*size_d+j], vec[j], MPFR_RNDN);
mpfr_add(res[i], res[i], temp1, MPFR_RNDN);
}
}
for(PetscInt k=0; k < size_d; ++k) {
mpfr_set(result[k], res[k], MPFR_RNDN);
mpfr_clear(res[k]);
}
mpfr_clear(temp1);
free(res);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "VecViewMPFR"
PetscErrorCode VecViewMPFR(PetscInt size_d, mpfr_t *vec) {
PetscErrorCode ierr;
double val;
PetscFunctionBegin;
printf("-------------------\n");
for(PetscInt k=0; k < size_d; ++k) {
val = mpfr_get_d(vec[k], MPFR_RNDN);
printf("vec[%d] = %4.4f\n", k, val);
}
printf("-------------------\n");
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "MatViewMPFR"
PetscErrorCode MatViewMPFR(PetscInt m, PetscInt n, mpfr_t *mat) {
PetscErrorCode ierr;
double val;
PetscFunctionBegin;
printf("-------------------\n");
for(PetscInt i=0; i < m; ++i) {
for(PetscInt j=0; j < n; ++j) {
val = mpfr_get_d(mat[i*n+j], MPFR_RNDN);
printf("%3.3f ", val);
}
printf("\n");
}
printf("-------------------\n");
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "Vec2NormMPFR"
PetscErrorCode Vec2NormMPFR(PetscInt size_d, mpfr_t *vec, mpfr_t *norm)
{
PetscErrorCode ierr;
mpfr_t val;
PetscFunctionBegin;
mpfr_init(val);
mpfr_set_d(*norm, 0.0, MPFR_RNDN);
for(PetscInt k=0; k < size_d; ++k) {
mpfr_mul(val, vec[k], vec[k], MPFR_RNDN);
mpfr_add(*norm, *norm, val, MPFR_RNDN);
}
mpfr_sqrt(*norm, *norm, MPFR_RNDN);
mpfr_clear(val);
PetscFunctionReturn(0);
}
//returns (lambda/|v1|^2)*v1*v1^T*vec
#undef __FUNCT__
#define __FUNCT__ "OrthogMap"
PetscErrorCode OrthogMap(PetscInt size_d, mpfr_t *x, mpfr_t *v1, mpfr_t *lambda, mpfr_t *result) {
PetscErrorCode ierr;
mpfr_t temp1, temp2, coef;
PetscFunctionBegin;
mpfr_inits(temp1, temp2, coef, NULL);
ierr = Vec2NormMPFR(size_d, v1, &temp1);CHKERRQ(ierr);
mpfr_mul(temp1, temp1, temp1, MPFR_RNDN);
mpfr_div(coef, *lambda, temp1, MPFR_RNDN);
//compute v1^T*vec
mpfr_set_d(temp2, 0.0, MPFR_RNDN);
for(PetscInt k=0; k < size_d; ++k) {
mpfr_mul(temp1, v1[k], x[k], MPFR_RNDN);
mpfr_add(temp2, temp2, temp1, MPFR_RNDN);
}
mpfr_mul(coef, coef, temp2, MPFR_RNDN);
//multiply v1 by coef and store to result
for(PetscInt k=0; k < size_d; ++k)
mpfr_mul(result[k], v1[k], coef, MPFR_RNDN);
mpfr_clears(temp1, temp2, coef, NULL);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "eigsMPFR"
PetscErrorCode eigsMPFR(PetscInt size_d, mpfr_t *mat, PetscInt prec, mpfr_t *result) {
PetscErrorCode ierr;
mpfr_t temp1;
mpfr_t norm;
mpfr_t error, error2;
mpfr_t *tempvec, *tempvec2;
mpfr_t *eigvec;
mpfr_t *prev;
mpfr_t *eigvecs;
mpfr_t *eigvals;
PetscFunctionBegin;
mpfr_inits(norm, error, error2, NULL);
eigvec = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d);
prev = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d);
eigvals = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d);
tempvec = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d);
tempvec2 = (mpfr_t*) malloc(sizeof(mpfr_t)*size_d);
for(PetscInt k=0; k < size_d; ++k) {
mpfr_inits(tempvec2[k], tempvec[k], eigvals[k], eigvec[k], prev[k], NULL);
}
for(PetscInt i=0; i < size_d; ++i) {
for(PetscInt l=0; l < size_d; ++l) {
mpfr_set_d(eigvec[l], 0.5, MPFR_RNDN);
}
mpfr_set_d(error, 1.0, MPFR_RNDN);
mpfr_set_d(error2, 1.0, MPFR_RNDN);
mpfr_log10(error, error, MPFR_RNDN);
mpfr_log10(error2, error2, MPFR_RNDN);
PetscInt j=0;
while(mpfr_get_d(error, MPFR_RNDN) > -prec && mpfr_get_d(error2, MPFR_RNDN) > -prec) {
j++;
for(PetscInt l=0; l < size_d; ++l)
mpfr_set(prev[l], eigvec[l], MPFR_RNDN);
ierr = MatVecMPFR(size_d, mat, eigvec, tempvec2);CHKERRQ(ierr);
//subtract off already found eigenvectors
for(PetscInt k=0; k<i; ++k) {
//PetscErrorCode OrthogMap(PetscInt size_d, mpfr_t *x, mpfr_t *v1, mpfr_t *lambda, mpfr_t *result) {
OrthogMap(size_d, eigvec, result+k*size_d, eigvals+k, tempvec);
for(PetscInt l=0; l<size_d; ++l) {
mpfr_sub(tempvec2[l], tempvec2[l], tempvec[l], MPFR_RNDN);
}
}
//normalize eig vector
ierr = Vec2NormMPFR(size_d, tempvec2, &norm);CHKERRQ(ierr);
for(PetscInt k=0; k < size_d; ++k)
mpfr_div(eigvec[k], tempvec2[k], norm, MPFR_RNDN);
//compute error
for(PetscInt k=0; k < size_d; ++k) {
mpfr_sub(tempvec[k], eigvec[k], prev[k], MPFR_RNDN);
mpfr_add(tempvec2[k], eigvec[k], prev[k], MPFR_RNDN);
}
ierr = Vec2NormMPFR(size_d, tempvec, &error);CHKERRQ(ierr);
ierr = Vec2NormMPFR(size_d, tempvec2, &error2);CHKERRQ(ierr);
ierr = mpfr_log10(error, error, MPFR_RNDN);
ierr = mpfr_log10(error2, error2, MPFR_RNDN);
//if(i==1) {
//printf("e: %2.2f\n", mpfr_get_d(error, MPFR_RNDN));
//printf("norm: %3.3e\n", mpfr_get_d(norm, MPFR_RNDN));
//ierr = VecViewMPFR(size_d, eigvec);CHKERRQ(ierr);
//}
}
//if(i==0) {
//ierr = VecViewMPFR(size_d, eigvec);CHKERRQ(ierr);
//}
//add newly found eigvec to eigvecss
for(PetscInt k=0; k < size_d; ++k)
mpfr_set(result[i*size_d+k], eigvec[k], MPFR_RNDN);
//add new eigval
mpfr_set(eigvals[i], norm, MPFR_RNDN);
//printf("EIGVAL IS %3.3f\n", mpfr_get_d(norm, MPFR_RNDN));
}
mpfr_clear(norm);
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.640318831,
"avg_line_length": 27.8796296296,
"ext": "c",
"hexsha": "0e79fabfc7d57c1669b1e6f6dbd37511ca7b6fd1",
"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/MPFReigs.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/MPFReigs.c",
"max_line_length": 102,
"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/MPFReigs.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": 2145,
"size": 6022
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <math.h>
#include <sys/time.h>
#include <mm_malloc.h>
#include <cblas.h>
#include <lapacke.h>
#include "random_matrix.h"
#include "driver.h"
#include "../../runtime/pcp.h"
static double compare_lower_triangular_matrices(int n, double *L1, int ldL1, double *L2, int ldL2)
{
#define L1(i,j) L1[(i) + (j) * ldL1]
#define L2(i,j) L2[(i) + (j) * ldL2]
// Clear out the upper triangular part.
for (int j = 0; j < n; ++j) {
for (int i = 0; i < j; i++) {
L1(i,j) = 0.0;
L2(i,j) = 0.0;
}
}
// Compute L1 := L1 - L2.
for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
L1(i,j) = L1(i,j) - L2(i,j);
}
}
// Compute || L1 ||_F.
double error = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', n, n, L1, ldL1);
error /= n;
return error;
#undef L1
#undef L2
}
static void usage(char *prog)
{
printf("Usage: %s n b p q\n", prog);
printf("\n");
printf("n: The size of the matrix\n");
printf("b: The tile size\n");
printf("p: The number of threads (or 0 for one per core)\n");
printf("q: The size of the reserved set (or 0 to use the regular mode)\n");
exit(EXIT_FAILURE);
}
int main(int argc, char** argv)
{
// Verify the number of command line options.
if (argc != 5 && argc != 6) {
usage(argv[0]);
}
// Parse command line.
int n = atoi(argv[1]);
int blksz = atoi(argv[2]);
int num_threads = atoi(argv[3]);
int reserved_set_size = atoi(argv[4]);
int verify = 1;
if (argc == 6) {
verify = 0;
}
// Verify options.
if (n < 1 ||
blksz < 1 ||
num_threads < 0 ||
reserved_set_size < 0 ||
(reserved_set_size >= num_threads && num_threads > 0)) {
usage(argv[0]);
}
// Initialise random number generator.
srand(time(NULL));
// Generate random SPD matrix A.
printf("Generating SPD matrix A...\n");
int ldA = n;
double *A = (double *) malloc(n * ldA * sizeof(double));
generate_dense_spd_matrix(n, A, ldA);
// Copy A to Ain.
printf("Copying A to Ain...\n");
double *Ain = (double *) malloc(n * ldA * sizeof(double));
memcpy(Ain, A, n * ldA * sizeof(double));
// Start the runtime system.
pcp_start(num_threads);
// Set the execution mode.
if (reserved_set_size == 0) {
pcp_set_mode(PCP_REGULAR);
} else {
pcp_set_mode(PCP_FIXED);
pcp_set_reserved_set_size(reserved_set_size);
}
// Call the driver.
printf("Calling the driver routine...\n");
parallel_block_chol(n, blksz, A, ldA);
if (verify) {
// Verify the solution.
printf("Verifying the solution... ");
fflush(stdout);
double tm = pcp_get_time();
LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', n, Ain, ldA);
tm = pcp_get_time() - tm;
double error = compare_lower_triangular_matrices(n, Ain, ldA, A, ldA);
if (error < 1e-14) {
printf("PASSED\n");
} else {
printf("FAILED\n");
}
printf("LAPACK_dpotrf took %.6lf seconds\n", tm);
} else {
printf("Verification disabled\n");
}
// Save the trace.
printf("Saving the trace...\n");
pcp_view_trace_tikz();
// View statistics.
printf("Printing statistics...\n");
pcp_view_statistics_stdout();
// Stop the runtime system.
pcp_stop();
// Clean up.
free(A);
free(Ain);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.5511269929,
"avg_line_length": 24.2533333333,
"ext": "c",
"hexsha": "1bc5f6c126cf6dfbf07f942d2d0de4fe9f97f1b7",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/pcp-runtime",
"max_forks_repo_path": "src/examples/dpotrf/main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/pcp-runtime",
"max_issues_repo_path": "src/examples/dpotrf/main.c",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/pcp-runtime",
"max_stars_repo_path": "src/examples/dpotrf/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1061,
"size": 3638
} |
#ifndef __GSLPRINT_H__
#define __GSLPRINT_H__
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <fstream>
#include <gsl/gsl_math.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_poly.h>
#include <gsl/gsl_integration.h>
#endif
void gsl_matrix_fprint(FILE * stream, gsl_matrix * target,int rows,int columns, char const * format);
void gsl_vector_fprint(FILE * stream, gsl_vector * target,int length, char const * format);
void gsl_matrix_printf(gsl_matrix * m, int rows, int columns, char const * format);
void gsl_vector_printf(gsl_vector * m,int length, char const * format);
void gsl_vector_complex_fprint(FILE * stream, gsl_vector_complex * target, int length, char const * format);
void gsl_matrix_complex_fprint(FILE * stream, gsl_matrix_complex * target, int rows, int columns, char const * format);
void gsl_matrix_complex_printf(gsl_matrix_complex * target, int rows, int columns, char const * format);
void gsl_vector_complex_fprint(gsl_vector_complex * target, int length, char const * format);
| {
"alphanum_fraction": 0.7782646801,
"avg_line_length": 42.2592592593,
"ext": "h",
"hexsha": "18984b08e3465fed4f2185ca72a8f888da4ac24c",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-10-16T03:11:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-03-18T13:50:13.000Z",
"max_forks_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Walter-Feng/HomebrewLib",
"max_forks_repo_path": "gslprint.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Walter-Feng/HomebrewLib",
"max_issues_repo_path": "gslprint.h",
"max_line_length": 119,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "f88625463b774b436f76fe4f9bd2f8e64e9fedee",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Walter-Feng/Hartree-Fock",
"max_stars_repo_path": "include/gslprint.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-23T18:50:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-23T21:27:21.000Z",
"num_tokens": 285,
"size": 1141
} |
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "boost_coroutine/http_client.h"
#include "callback/http_client.h"
#include "coroutine_ts/http_client.h"
#include "sync/http_client.h"
#include "task/http_client.h"
#include "threaded/http_client.h"
#include "executor.h"
#include <boost/algorithm/string.hpp>
#include <gsl/gsl_util>
#if 1
static inline auto log_msg = std::stringstream{};
#else
static inline auto& log_msg = std::cerr;
#endif
static HttpResponse request_get_impl(std::string_view uri) {
if (uri == "/file1") {
return Redirect{"/newplaceoffile1"};
}
if (uri == "/newplaceoffile1") {
return Redirect{"/file2"};
}
if (uri == "/file2") {
return Content{"content1"};
}
if (uri == "/file3") {
return Content{"content2"};
}
if (boost::algorithm::starts_with(uri, "/extremeredirect")) {
std::vector<std::string> parts;
boost::algorithm::split(parts, uri, [](char c) { return c == '/'; });
if (parts.size() == 2) {
return Redirect{std::string{uri} + "/1"};
}
if (parts.size() == 3) {
auto num = std::stol(parts[2]);
if (num < 4) {
return Redirect{"/extremeredirect/" + std::to_string(num + 1)};
}
}
return Content{"finally here"};
}
return Content{""};
}
namespace synchronous {
class ConcreteHttpClient : public HttpClient {
public:
HttpResponse request_get(std::string_view uri) override {
log_msg << "request " << uri << "..." << std::endl;
auto out
= gsl::finally([&] { log_msg << "...request " << uri << std::endl; });
return request_get_impl(uri);
}
};
}
namespace threaded {
class ConcreteHttpClient : public HttpClient {
public:
HttpResponse request_get(std::string_view uri) override {
log_msg << "request " << uri << "..." << std::endl;
auto out
= gsl::finally([&] { log_msg << "...request " << uri << std::endl; });
return request_get_impl(uri);
}
};
}
namespace callback {
class ConcreteHttpClient : public HttpClient {
public:
void request_get(const std::string& uri,
const std::function<void(HttpResponse)>& cb) override {
log_msg << "request " << uri << "..." << std::endl;
auto handle = [uri]() -> HttpResponse { return request_get_impl(uri); };
get_current_executor().add_work([=] {
log_msg << "...request " << uri << std::endl;
get_current_executor().add_work([=] { cb(handle()); });
});
}
};
}
namespace task_based {
class ConcreteHttpClient : public HttpClient {
public:
task<HttpResponse> request_get(const std::string& uri) override {
log_msg << "request " << uri << "..." << std::endl;
const auto handle
= [uri]() -> HttpResponse { return request_get_impl(uri); };
auto fut = make_task<HttpResponse>();
get_current_executor().add_work([=] {
log_msg << "...request " << uri << std::endl;
fut->set_result(handle());
});
return fut;
}
};
}
namespace boost_coroutine {
class ConcreteHttpClient : public HttpClient {
public:
task<HttpResponse> request_get(const std::string& uri) override {
log_msg << "request " << uri << "..." << std::endl;
const auto handle = [=]() -> HttpResponse { return request_get_impl(uri); };
auto fut = make_task<HttpResponse>();
get_current_executor().add_work([=] {
log_msg << "...request " << uri << std::endl;
fut->set_result(handle());
});
return fut;
}
};
}
namespace coroutines_ts {
class ConcreteHttpClient : public HttpClient {
public:
task<HttpResponse> request_get(const std::string& uri) override {
log_msg << "request " << uri << "..." << std::endl;
const auto handle = [=]() -> HttpResponse { return request_get_impl(uri); };
auto fut = make_task<HttpResponse>();
get_current_executor().add_work([=] {
log_msg << "...request " << uri << std::endl;
fut->set_result(handle());
});
return fut;
}
};
}
| {
"alphanum_fraction": 0.6134688691,
"avg_line_length": 26.5878378378,
"ext": "h",
"hexsha": "48da7f6a63e3ad0a37ad60ebe6395e6996ecc2fc",
"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": "d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "adrianimboden/cppusergroup-adynchronous-programming",
"max_forks_repo_path": "mixed/src/http_client_implementations.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4",
"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": "adrianimboden/cppusergroup-adynchronous-programming",
"max_issues_repo_path": "mixed/src/http_client_implementations.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d6fad3ff980be2e7c13ed9e3e05b62e984c9caa4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "adrianimboden/cppusergroup-adynchronous-programming",
"max_stars_repo_path": "mixed/src/http_client_implementations.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 978,
"size": 3935
} |
/**
*
* @file core_ctrtri.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Julien Langou
* @author Henricus Bouwmeester
* @author Mathieu Faverge
* @date 2010-11-15
* @generated c Tue Jan 7 11:44:46 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex32_t
*
* CORE_ctrtri - Computes the inverse of a complex upper or lower
* triangular matrix A.
*
*******************************************************************************
*
* @param[in] uplo
* = PlasmaUpper: Upper triangle of A is stored;
* = PlasmaLower: Lower triangle of A is stored.
*
* @param[in] diag
* = PlasmaNonUnit: A is non-unit triangular;
* = PlasmaUnit: A is unit triangular.
*
* @param[in] N
* The order of the matrix A. N >= 0.
*
* @param[in,out] A
* On entry, the triangular matrix A. If UPLO = 'U', the
* leading N-by-N upper triangular part of the array A
* contains the upper triangular matrix, and the strictly
* lower triangular part of A is not referenced. If UPLO =
* 'L', the leading N-by-N lower triangular part of the array
* A contains the lower triangular matrix, and the strictly
* upper triangular part of A is not referenced. If DIAG =
* 'U', the diagonal elements of A are also not referenced and
* are assumed to be 1. On exit, the (triangular) inverse of
* the original matrix.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,N).
*
* @param[out] info
* - 0 on successful exit
* - <0 if -i, the i-th argument had an illegal value
* - >0 if i, A(i,i) is exactly zero. The triangular
* matrix is singular and its inverse can not be computed.
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_ctrtri = PCORE_ctrtri
#define CORE_ctrtri PCORE_ctrtri
#endif
void CORE_ctrtri(PLASMA_enum uplo, PLASMA_enum diag, int N, PLASMA_Complex32_t *A, int LDA, int *info)
{
*info = LAPACKE_ctrtri_work(
LAPACK_COL_MAJOR,
lapack_const(uplo), lapack_const(diag),
N, A, LDA);
}
| {
"alphanum_fraction": 0.5694108152,
"avg_line_length": 33.9452054795,
"ext": "c",
"hexsha": "32365b89ebc11a2fbb0a262ad4f5d0adadb367a2",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas/core_ctrtri.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas/core_ctrtri.c",
"max_line_length": 102,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas/core_ctrtri.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 632,
"size": 2478
} |
/*
** hemodynamic modelling for single-subject LISA
**
** G.Lohmann, MPI-KYB, 2018
*/
#include <viaio/Vlib.h>
#include <viaio/VImage.h>
#include <viaio/mu.h>
#include <viaio/option.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_spline.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#define ABS(x) ((x) > 0 ? (x) : -(x))
#define SQR(x) ((x)*(x))
#define LEN 10000 /* buffer length */
#define NTRIALS 10000 /* max number of trials */
/* standard parameter values for gamma function, Glover 99 */
double a1 = 6;
double b1 = 0.9;
double a2 = 12;
double b2 = 0.9;
double cc = 0.35;
typedef struct TrialStruct {
int id;
float onset;
float duration;
float height;
} Trial;
void printmat(gsl_matrix *R,char *str)
{
int i,j;
fprintf(stderr," %s: \n",str);
for (i=0; i<R->size1; i++) {
for (j=0; j<R->size2; j++) {
fprintf(stderr," %9.6f",gsl_matrix_get(R,i,j));
}
fprintf(stderr,"\n");
}
fprintf(stderr,"\n");
}
void tprintmat(gsl_matrix *R,char *str)
{
int i,j;
fprintf(stderr," %s: \n",str);
for (i=0; i<R->size2; i++) {
for (j=0; j<R->size1; j++) {
fprintf(stderr," %9.6f",gsl_matrix_get(R,j,i));
}
fprintf(stderr,"\n");
}
fprintf(stderr,"\n");
}
void printvec(gsl_vector *x,char *str)
{
int i;
fprintf(stderr," %s: \n",str);
for (i=0; i<x->size; i++) {
fprintf(stderr," %f\n",x->data[i]);
}
fprintf(stderr,"\n");
}
/* output txt file for plotting */
void PlotDesign(gsl_matrix *X,double tr,VString filename)
{
int i,j;
double u=0;
FILE *fp = fopen(filename,"w");
if (fp == NULL) VError("err opening plot file");
double t = 0;
for (i=0; i<X->size1; i++) {
fprintf(fp," %8.2f",t);
for (j=0; j<X->size2; j++) {
u = gsl_matrix_get(X,i,j);
fprintf(fp," %10.6f",u);
}
t += tr;
fprintf(fp,"\n");
}
fclose(fp);
}
/* create design X */
gsl_matrix *VCreateDesign(int ntimesteps,int nevents,int hemomodel,VBoolean firstcol,gsl_matrix *covariates)
{
int dim = nevents;
if (hemomodel == 1) dim = nevents*2;
if (hemomodel == 2) dim = nevents*3;
if (firstcol == TRUE) dim++;
if (covariates != NULL) dim += covariates->size2; /* nuisance covariates without task labels */
gsl_matrix *X = gsl_matrix_calloc(ntimesteps,dim);
return X;
}
/* Glover kernel, gamma function */
double xgamma(double xx, double t0)
{
double x, y, scale = 20;
double y1, y2;
double d1, d2;
x = xx - t0;
if(x < 0 || x > 50)
return 0;
d1 = a1 * b1;
d2 = a2 * b2;
y1 = pow(x / d1, a1) * exp(-(x - d1) / b1);
y2 = pow(x / d2, a2) * exp(-(x - d2) / b2);
y = y1 - cc * y2;
y /= scale;
return y;
}
/* Glover kernel, gamma function, parameters changed for block designs */
double bgamma(double xx, double t0)
{
double x, y, scale = 120;
double y1, y2;
double d1, d2;
double aa1 = 6;
double bb1 = 0.9;
double aa2 = 12;
double bb2 = 0.9;
double cx = 0.1;
x = xx - t0;
if(x < 0 || x > 50)
return 0;
d1 = aa1 * bb1;
d2 = aa2 * bb2;
y1 = pow(x / d1, aa1) * exp(-(x - d1) / bb1);
y2 = pow(x / d2, aa2) * exp(-(x - d2) / bb2);
y = y1 - cx * y2;
y /= scale;
return y;
}
/* first derivative */
double deriv1_gamma(double x, double t0)
{
double d1, d2, y1, y2, y, xx;
double scale = 20.0;
xx = x - t0;
if(xx < 0 || xx > 50) return 0;
d1 = a1 * b1;
d2 = a2 * b2;
y1 = pow(d1, -a1) * a1 * pow(xx, (a1 - 1.0)) * exp(-(xx - d1) / b1)
- (pow((xx / d1), a1) * exp(-(xx - d1) / b1)) / b1;
y2 = pow(d2, -a2) * a2 * pow(xx, (a2 - 1.0)) * exp(-(xx - d2) / b2)
- (pow((xx / d2), a2) * exp(-(xx - d2) / b2)) / b2;
y = y1 - cc * y2;
y /= scale;
return y;
}
/* second derivative */
double deriv2_gamma(double x, double t0)
{
double d1, d2, y1, y2, y3, y4, y, xx;
double scale = 20.0;
xx = x - t0;
if (xx < 0 || xx > 50) return 0;
d1 = a1 * b1;
d2 = a2 * b2;
y1 = pow(d1, -a1) * a1 * (a1 - 1) * pow(xx, a1 - 2) * exp(-(xx - d1) / b1)
- pow(d1, -a1) * a1 * pow(xx, (a1 - 1)) * exp(-(xx - d1) / b1) / b1;
y2 = pow(d1, -a1) * a1 * pow(xx, a1 - 1) * exp(-(xx - d1) / b1) / b1
- pow((xx / d1), a1) * exp(-(xx - d1) / b1) / (b1 * b1);
y1 = y1 - y2;
y3 = pow(d2, -a2) * a2 * (a2 - 1) * pow(xx, a2 - 2) * exp(-(xx - d2) / b2)
- pow(d2, -a2) * a2 * pow(xx, (a2 - 1)) * exp(-(xx - d2) / b2) / b2;
y4 = pow(d2, -a2) * a2 * pow(xx, a2 - 1) * exp(-(xx - d2) / b2) / b2
- pow((xx / d2), a2) * exp(-(xx - d2) / b2) / (b2 * b2);
y2 = y3 - y4;
y = y1 - cc * y2;
y /= scale;
return y;
}
/* Gaussian function */
double xgauss(double xx, double t0)
{
double sigma=1.0;
double x, y, z, a = 2.506628273;
x = (xx - t0);
z = x / sigma;
y = exp(-0.5*z*z) / (sigma * a);
return y;
}
void XConvolve(double *src,double *dst,double *kernel,int nt,int kernelsize)
{
int i,j,jj,k;
double sum=0;
for (i=0; i<nt; i++) {
sum = 0;
k=0;
for (j=i; j<i+kernelsize; j++) {
jj = i-k;
if (jj >= 0 && jj < nt) {
sum += src[jj] * kernel[k];
}
k++;
}
dst[i] = sum;
}
}
/* hemodynamic modelling at high temporal resolution */
void VHemoModel(Trial *trial,int ntrials,int nevents,int nt,double xtr,int hemomodel,VBoolean firstcol,
gsl_matrix *X,gsl_matrix *covariates)
{
int i,j,jj,k;
double t,t0,t1,h;
/* set temporal resolution to 0.5 sec, reduce discretization artefacts */
double hfactor = floor(xtr/0.5);
if (hfactor < 1.0) hfactor = 1.0;
double tr = xtr/hfactor;
int jfactor = (int)hfactor;
int ntimesteps = jfactor*nt;
for(i = 0; i < nevents; i++) {
double xmin = VRepnMaxValue(VFloatRepn);
for(j = 0; j < ntrials; j++) {
if(trial[j].id != i) continue;
if(trial[j].duration < xmin) xmin = trial[j].duration;
}
}
/* get kernels */
t1 = 30.0; /* kernel duration = 30 secs */
int kernelsize = t1 / tr;
if (tr < 0.01) VWarning(" implausible TR (%f seconds)",tr);
/* fprintf(stderr," hf= %f, tr= %f %f, kernelsize: %d\n",hfactor,xtr,tr,kernelsize); */
double *kernel1=NULL,*kernel2=NULL;
double *bkernel = (double *)VCalloc(kernelsize,sizeof(double));
double *kernel0 = (double *)VCalloc(kernelsize,sizeof(double));
if (hemomodel == 1 || hemomodel == 2) {
kernel1 = (double *)VCalloc(kernelsize,sizeof(double));
}
if (hemomodel == 2) {
kernel2 = (double *)VCalloc(kernelsize,sizeof(double));
}
i = 0;
for (t = 0; t < t1; t += tr) {
if (i >= kernelsize) break;
bkernel[i] = xgauss(t, 5.0*tr);
kernel0[i] = xgamma(t, 0.0);
if(hemomodel == 1 || hemomodel == 2)
kernel1[i] = deriv1_gamma(t, 0);
if(hemomodel == 2)
kernel2[i] = deriv2_gamma(t, 0);
i++;
}
/* tmp storage */
double *x = (double *) VCalloc(ntimesteps,sizeof(double));
double *y = (double *) VCalloc(ntimesteps,sizeof(double));
/* constant in column 0 */
int col=0;
if (firstcol == TRUE) {
gsl_matrix_set_zero(X);
for (j=0; j<nt; j++) gsl_matrix_set(X,j,0,1.0);
col=1;
}
/* for each trial,event, do... */
for (i = 0; i < nevents; i++) {
for (k=0; k<ntimesteps; k++) x[k] = y[k] = 0;
/* read design info */
int trialcount = 0;
for (j = 0; j < ntrials; j++) {
if(trial[j].id != i+1) continue;
trialcount++;
t0 = trial[j].onset;
t1 = trial[j].onset + trial[j].duration;
h = trial[j].height;
int k0 = (int) (t0/tr + 0.5);
int k1 = (int) (t1/tr + 0.5);
int klen=0;
for (k=k0; k<=k1; k++) {
if (k < 0 || k >= ntimesteps) continue;
x[k] = h;
klen++;
}
if(trialcount < 1)
VError(" no trials in event %d, please re-number event-ids, ntrials= %d", i + 1,ntrials);
}
/* convolve */
if (hemomodel == 3) { /* block design, gaussian kernel */
XConvolve(x,y,bkernel,ntimesteps,kernelsize);
}
else { /* gamma function kernel */
XConvolve(x,y,kernel0,ntimesteps,kernelsize);
}
for (j=0; j<X->size1; j++) {
jj = j*jfactor;
if (jj >= ntimesteps) continue;
gsl_matrix_set(X,j,col,y[jj]/hfactor);
}
col++;
if (hemomodel == 1 || hemomodel == 2) { /* gamma function kernel, first derivative */
XConvolve(x,y,kernel1,ntimesteps,kernelsize);
for (j=0; j<X->size1; j++) {
jj = j*jfactor;
if (jj >= ntimesteps) continue;
gsl_matrix_set(X,j,col,y[jj]/hfactor);
}
col++;
}
if (hemomodel == 2) { /* gamma function kernel, second derivative */
XConvolve(x,y,kernel2,ntimesteps,kernelsize);
for (j=0; j<X->size1; j++) {
jj = j*jfactor;
if (jj >= ntimesteps) continue;
gsl_matrix_set(X,j,col,y[jj]/hfactor);
}
col++;
}
}
/* add further covariates that have no task labels, will not be permuted */
if (covariates != NULL) {
for (i=0; i<covariates->size2; i++) {
for (j=0; j<covariates->size1; j++) {
if (col >= X->size2) VError(" VHemoModel, column= %d %d\n",col,(int)X->size2);
gsl_matrix_set(X,j,col,gsl_matrix_get(covariates,j,i));
}
col++;
}
}
/* cleanup */
VFree(x);
VFree(y);
VFree(kernel0);
VFree(bkernel);
if (kernel1 != NULL) VFree(kernel1);
if (kernel2 != NULL) VFree(kernel2);
}
| {
"alphanum_fraction": 0.5509466071,
"avg_line_length": 24.1076923077,
"ext": "c",
"hexsha": "cd7ef5c54f31639c903ba58c8d1774cd3a2db863",
"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_prewhitening/HemoModel.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_prewhitening/HemoModel.c",
"max_line_length": 108,
"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_prewhitening/HemoModel.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": 3513,
"size": 9402
} |
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_math.h>
#include "zero_crossing.h"
/* \fn double zero_crossing(double (*model)(double, void *), void *params, double *x_lo, double *x_hi)
* \brief Find a zero crossing of the supplied model. */
double zero_crossing(double (*model)(double, void *), void *params, double *x_lo, double *x_hi)
{
int status;
int iter=0;
int max_iter = 100;
double x; //root
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
gsl_function F;
F.function = model;
F.params = params;
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc(T);
gsl_root_fsolver_set(s,&F, *x_lo, *x_hi);
do{
iter++;
status = gsl_root_fsolver_iterate(s);
x = gsl_root_fsolver_root(s);
*x_lo = gsl_root_fsolver_x_lower(s);
*x_hi = gsl_root_fsolver_x_upper(s);
status = gsl_root_test_interval(*x_lo, *x_hi,0,0.001);
//printf("iter %d x_lo %e x %e x_hi %e\n",iter,*x_lo,x,*x_hi);
}while((status==GSL_CONTINUE)&&(iter<max_iter));
gsl_root_fsolver_free(s);
return x;
}
| {
"alphanum_fraction": 0.6890756303,
"avg_line_length": 21.8571428571,
"ext": "c",
"hexsha": "5c1d5a0ee5a6ba2bc607be0d0b670b054cbb7eda",
"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": "30351e243fd1d21556acb04d0625c5110d2fb0fe",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "brantr/zero-crossing",
"max_forks_repo_path": "zero_crossing.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "30351e243fd1d21556acb04d0625c5110d2fb0fe",
"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": "brantr/zero-crossing",
"max_issues_repo_path": "zero_crossing.c",
"max_line_length": 102,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "30351e243fd1d21556acb04d0625c5110d2fb0fe",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "brantr/zero-crossing",
"max_stars_repo_path": "zero_crossing.c",
"max_stars_repo_stars_event_max_datetime": "2016-11-15T03:58:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-11-15T03:58:43.000Z",
"num_tokens": 335,
"size": 1071
} |
#include <cblas.h>
#include <clapack.h>
#ifdef NoChange
#define dgeqrf_ dgeqrf
#elif defined(UpCase)
#define dgeqrf_ DGEQRF
#endif
main(int nargs, char **args)
{
extern void dgeqrf_(F77_INTEGER*,F77_INTEGER*,double*,F77_INTEGER*,
double*,double*,F77_INTEGER*,F77_INTEGER*);
double A[1]={1.0}, b[1]={1.0}, c[1];
F77_INTEGER N=1, info;
dgeqrf_(&N, &N, A, &N, b, c, &N, &info);
}
| {
"alphanum_fraction": 0.6267942584,
"avg_line_length": 26.125,
"ext": "c",
"hexsha": "ffb3ac45c58c24f6288762ae76da681cfee05a52",
"lang": "C",
"max_forks_count": 47,
"max_forks_repo_forks_event_max_datetime": "2021-11-11T20:59:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-27T06:22:57.000Z",
"max_forks_repo_head_hexsha": "cc36aa7e0362c577739ac507378068882834825e",
"max_forks_repo_licenses": [
"BSD-3-Clause-Clear"
],
"max_forks_repo_name": "kevleyski/math-atlas",
"max_forks_repo_path": "lib/qr.c",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "cc36aa7e0362c577739ac507378068882834825e",
"max_issues_repo_issues_event_max_datetime": "2021-06-05T20:00:27.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-13T15:19:26.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-Clear"
],
"max_issues_repo_name": "kevleyski/math-atlas",
"max_issues_repo_path": "lib/qr.c",
"max_line_length": 70,
"max_stars_count": 135,
"max_stars_repo_head_hexsha": "cc36aa7e0362c577739ac507378068882834825e",
"max_stars_repo_licenses": [
"BSD-3-Clause-Clear"
],
"max_stars_repo_name": "kevleyski/math-atlas",
"max_stars_repo_path": "lib/qr.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T02:26:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-08T20:35:35.000Z",
"num_tokens": 156,
"size": 418
} |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_histogram.h>
#include "allvars.h"
#include "proto.h"
void get_cov_matrix(double *theta, int nstep, int ntheta)
{
int i, j;
double cov;
for(i=0; i<ntheta; i++)
{
cov = gsl_stats_covariance(&theta[i*nstep], 1, &theta[i*nstep], 1, nstep);
cov = cov>1.0e-6 ? cov : 1.0e-6;
cov_matrix[i*ntheta + i] = cov;
for(j=0; j<i; j++)
{
cov = gsl_stats_covariance(&theta[i*nstep], 1, &theta[j*nstep], 1, nstep);
cov = cov>0.0001?cov:0.0;
cov_matrix[i*ntheta + j] = cov_matrix[j*ntheta + i] = cov;
}
}
}
void get_cov_matrix_diag(double *theta, int nstep, int ntheta)
{
int i, j;
double cov;
for(i=0; i<ntheta; i++)
{
cov = gsl_stats_covariance(&theta[i*nstep], 1, &theta[i*nstep], 1, nstep);
cov = cov>1.0e-6 ? cov : 1.0e-6;
cov_matrix[i*ntheta + i] = cov;
for(j=0; j<i; j++)
{
cov_matrix[i*ntheta + j] = cov_matrix[j*ntheta + i] = 0.0;
}
}
}
void mcmc_stats(char * fname)
{
FILE *fp;
double **theta, tmp, err_max1, err_max2, theta_up, theta_low;
int i, nstep, istep;
theta = malloc(ntheta*sizeof(double));
for(i=0; i<ntheta; i++)
{
theta[i] = malloc((nmcmc)*sizeof(double));
}
fp = fopen(fname, "r");
if(fp==NULL)
{
strcpy(str_error_exit, fname);
error_exit(2);
}
istep = 0;
nstep = 0;
while(!feof(fp) && nstep < nmcmc)
{
fscanf(fp, "%d", &istep);
for(i=0; i<ntheta; i++)
{
fscanf(fp, "%lf", &theta[i][nstep]);
}
fscanf(fp,"%lf\n", &tmp);
nstep++;
}
printf("nstep: %d\n", nstep);
if(nstep <= nbuilt)
{
strcpy(str_error_exit, "mcmc.txt");
error_exit(10);
}
printf("Sts: ID par err1 err2\n");
for(i=0; i<ntheta; i++)
{
gsl_sort(&theta[i][nbuilt-1], 1, nstep-nbuilt);
//printf("ss:%f %f %f\n", theta[i*n_mcmc + 40000], theta[i*n_mcmc+ 40100], theta[i*n_mcmc+ 40200]);
theta_best[i] = gsl_stats_mean(&theta[i][nbuilt-1], 1, nstep-nbuilt);
//theta_best[i] = gsl_stats_quantile_from_sorted_data(&theta[i][nbuilt-1], 1, nstep-nbuilt, 0.500);
theta_low = gsl_stats_quantile_from_sorted_data(&theta[i][nbuilt-1], 1, nstep-nbuilt, 0.1585);
theta_up = gsl_stats_quantile_from_sorted_data(&theta[i][nbuilt-1], 1, nstep-nbuilt, 1.0-0.1585);
err_max1 = (theta_best[i] - theta_range[i][0])/2.35;
err_max2 = (theta_range[i][1] - theta_best[i])/2.35;
theta_best_var[i*2] = max(min( theta_best[i] - theta_low, err_max1 ), 0.0);
theta_best_var[i*2+1] = max( min( theta_up - theta_best[i], err_max2 ), 0.0);
printf("Sts: %d %f %f %f\n", i, theta_best[i], theta_best_var[i*2], theta_best_var[i*2+1]);
}
fclose(fp);
return;
} | {
"alphanum_fraction": 0.5992217899,
"avg_line_length": 25.4684684685,
"ext": "c",
"hexsha": "09c9943058d7099720024caf05e32c37536ca97c",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-04-12T11:48:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-12-29T06:04:13.000Z",
"max_forks_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/MICA",
"max_forks_repo_path": "src/mcmc_stats.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "LiyrAstroph/MICA",
"max_issues_repo_path": "src/mcmc_stats.c",
"max_line_length": 103,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/MICA",
"max_stars_repo_path": "src/mcmc_stats.c",
"max_stars_repo_stars_event_max_datetime": "2016-10-25T06:32:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-25T06:32:33.000Z",
"num_tokens": 1020,
"size": 2827
} |
/**
* @file beamformer.h
* @brief Beamforming in the subband domain.
* @author John McDonough and Kenichi Kumatani
*/
#ifndef BEAMFORMER_H
#define BEAMFORMER_H
#include <stdio.h>
#include <assert.h>
#include <float.h>
#include <gsl/gsl_block.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_fft_complex.h>
#include <common/refcount.h>
#include "common/jexception.h"
#include "stream/stream.h"
#include "beamformer/spectralinfoarray.h"
#include "modulated/modulated.h"
#define SSPEED 343740.0
class BeamformerWeights {
public:
BeamformerWeights( unsigned fftLen, unsigned chanN, bool halfBandShift, unsigned NC = 1 );
~BeamformerWeights();
void calcMainlobe( float samplerate, const gsl_vector* delays, bool isGSC );
void calcMainlobe2( float samplerate, const gsl_vector* delaysT, const gsl_vector* delaysJ, bool isGSC );
void calcMainlobeN( float samplerate, const gsl_vector* delaysT, const gsl_matrix* delaysIs, unsigned NC, bool isGSC );
void calcSidelobeCancellerP_f( unsigned fbinX, const gsl_vector* packedWeight );
void calcSidelobeCancellerU_f( unsigned fbinX, const gsl_vector_complex* wa );
void calcBlockingMatrix( unsigned fbinX );
bool write_fir_coeff(const String& fn, unsigned winType);
#ifdef ENABLE_LEGACY_BTK_API
bool writeFIRCoeff(const String& fn, unsigned winType);
#endif
void setSidelobeCanceller_f( unsigned fbinX, gsl_vector_complex* wl_f ){
gsl_vector_complex_memcpy( wl_[fbinX], wl_f );
}
void setQuiescentVector( unsigned fbinX, gsl_vector_complex *wq_f, bool isGSC=false );
void setQuiescentVectorAll( gsl_complex z, bool isGSC=false );
void setTimeAlignment();
bool isHalfBandShift() const {return(halfBandShift_);}
unsigned NC() const {return(NC_);}
unsigned fftLen() const {return(fftLen_);}
unsigned chanN() const {return(chanN_);}
gsl_vector_complex** arrayManifold() const { return (ta_); }
gsl_vector_complex* wq_f( unsigned fbinX ) const { return wq_[fbinX]; }
gsl_vector_complex* wl_f( unsigned fbinX ) const { return wl_[fbinX]; }
gsl_vector_complex** wq() const { return (wq_); }
gsl_matrix_complex** B() const { return (B_); }
gsl_vector_complex** wa() const { return (wa_); }
gsl_vector_complex** CSDs() const { return CSDs_; }
gsl_vector_complex* wp1() const { return wp1_; }
private:
void alloc_weights_();
void free_weights_();
unsigned fftLen_;
unsigned chanN_;
bool halfBandShift_;
unsigned NC_; // the numbef of constraints
gsl_vector_complex** wq_; // a quiescent weight vector for each frequency bin, wq_[fbinX][chanN]
gsl_matrix_complex** B_; // a blocking matrix for each frequency bin, B_[fbinX][chanN][chanN-NC]
gsl_vector_complex** wa_; // an active weight vector for each frequency bin, wa_[fbinX][chanN-NC]
gsl_vector_complex** wl_; // wl_[fbinX] = B_[fbinX] * wa_[fbinX]
gsl_vector_complex** ta_; // do time alignment for multi-channel waves. It is also called an array manifold. _ta[fbinX][chanN].
gsl_vector_complex* wp1_; // a weight vector of postfiltering, _wp[fbinX]
gsl_vector_complex** CSDs_; // cross spectral density for the post-filtering
};
typedef refcount_ptr<BeamformerWeights> BeamformerWeightsPtr;
// ----- definition for class `SubbandBeamformer' -----
//
class SubbandBeamformer : public VectorComplexFeatureStream {
public:
SubbandBeamformer(unsigned fftLen = 512, bool halfBandShift = false, const String& nm = "SubbandBeamformer");
~SubbandBeamformer();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
unsigned fftLen() const { return fftLen_; }
unsigned fftLen2() const { return fftLen2_; }
unsigned chanN() const { return channelList_.size(); }
virtual unsigned dim() const { return chanN();}
bool is_end() const {return is_end_;}
const gsl_vector_complex* snapshot_array_f(unsigned fbinX) const { return (snapshot_array_->snapshot(fbinX)); }
virtual SnapShotArrayPtr snapshot_array() const { return(snapshot_array_); }
void set_channel(VectorComplexFeatureStreamPtr& chan);
virtual void clear_channel();
#ifdef ENABLE_LEGACY_BTK_API
bool isEnd() { return is_end(); }
const gsl_vector_complex* snapShotArray_f(unsigned fbinX){ return snapshot_array_f(fbinX); }
virtual SnapShotArrayPtr getSnapShotArray(){ return(snapshot_array()); }
void setChannel(VectorComplexFeatureStreamPtr& chan){ set_channel(chan); }
virtual void clearChannel(){ clear_channel(); }
#endif
protected:
typedef list<VectorComplexFeatureStreamPtr> ChannelList_;
typedef ChannelList_::iterator ChannelIterator_;
SnapShotArrayPtr snapshot_array_;
unsigned fftLen_;
unsigned fftLen2_;
bool halfBandShift_;
ChannelList_ channelList_;
};
// ----- definition for class `SubbandDS' -----
//
class SubbandDS : public SubbandBeamformer {
public:
SubbandDS(unsigned fftLen = 512, bool halfBandShift = false, const String& nm = "SubbandDS");
~SubbandDS();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
virtual void clear_channel();
virtual const gsl_vector_complex *get_weights(unsigned fbinX) const { return bfweight_vec_[0]->wq_f(fbinX); }
virtual BeamformerWeights* beamformer_weight_object(unsigned srcX=0) const { return bfweight_vec_[srcX]; }
virtual void calc_array_manifold_vectors(float samplerate, const gsl_vector* delays);
virtual void calc_array_manifold_vectors_2(float samplerate, const gsl_vector* delaysT, const gsl_vector* delaysJ);
virtual void calc_array_manifold_vectors_n(float samplerate, const gsl_vector* delaysT, const gsl_matrix* delaysJ, unsigned NC=2);
#ifdef ENABLE_LEGACY_BTK_API
virtual void clearChannel(){ clear_channel(); }
virtual const gsl_vector_complex *getWeights(unsigned fbinX) const { return get_weights(fbinX); }
virtual BeamformerWeights* getBeamformerWeightObject(unsigned srcX=0) const { return beamformer_weight_object(srcX); }
virtual void calcArrayManifoldVectors(float sampleRate, const gsl_vector* delays){
calc_array_manifold_vectors(sampleRate, delays);
}
virtual void calcArrayManifoldVectors2(float sampleRate, const gsl_vector* delaysT, const gsl_vector* delaysJ){
calc_array_manifold_vectors_2(sampleRate, delaysT, delaysJ);
}
virtual void calcArrayManifoldVectorsN(float sampleRate, const gsl_vector* delaysT, const gsl_matrix* delaysJ, unsigned NC=2){
calc_array_manifold_vectors_n(sampleRate, delaysT, delaysJ, NC);
}
#endif /* #ifdef ENABLE_LEGACY_BTK_API */
protected:
void alloc_image_();
void alloc_bfweight_(int nSrc, int NC);
vector<BeamformerWeights *> bfweight_vec_; // weights of a beamformer per source.
};
#define NO_PROCESSING 0x00
#define SCALING_MDP 0x01
class SubbandGSC : public SubbandDS {
public:
SubbandGSC(unsigned fftLen = 512, bool halfBandShift = false, const String& nm = "SubbandGSC")
: SubbandDS( fftLen, halfBandShift, nm ),normalize_weight_(false){}
~SubbandGSC();
virtual const gsl_vector_complex* next(int frame_no = -5);
void normalize_weight(bool flag){ normalize_weight_ = flag; }
void set_quiescent_weights_f(unsigned fbinX, const gsl_vector_complex* srcWq);
void set_active_weights_f(unsigned fbinX, const gsl_vector* packedWeight);
void zero_active_weights();
void calc_gsc_weights(float samplerate, const gsl_vector* delaysT);
void calc_gsc_weights_2(float samplerate, const gsl_vector* delaysT, const gsl_vector* delaysJ);
void calc_gsc_weights_n(float samplerate, const gsl_vector* delaysT, const gsl_matrix* delaysJ, unsigned NC=2);
bool write_fir_coeff(const String& fn, unsigned winType=1);
gsl_matrix_complex* blocking_matrix(unsigned srcX, unsigned fbinX){
return (bfweight_vec_[srcX]->B())[fbinX];
}
#ifdef ENABLE_LEGACY_BTK_API
void normalizeWeight(bool flag){ normalize_weight(flag); }
void setQuiescentWeights_f(unsigned fbinX, const gsl_vector_complex * srcWq){ set_quiescent_weights_f(fbinX, srcWq); }
void setActiveWeights_f(unsigned fbinX, const gsl_vector* packedWeight){ set_active_weights_f(fbinX, packedWeight); }
void zeroActiveWeights(){ zero_active_weights(); }
void calcGSCWeights(float sampleRate, const gsl_vector* delaysT){ calc_gsc_weights(sampleRate, delaysT); }
void calcGSCWeights2(float sampleRate, const gsl_vector* delaysT, const gsl_vector* delaysJ){ calc_gsc_weights_2(sampleRate, delaysT, delaysJ); }
void calcGSCWeightsN(float sampleRate, const gsl_vector* delaysT, const gsl_matrix* delaysJ, unsigned NC=2){ calc_gsc_weights_n(sampleRate, delaysT, delaysJ, NC); }
bool writeFIRCoeff(const String& fn, unsigned winType=1){ return write_fir_coeff(fn, winType); }
gsl_matrix_complex* getBlockingMatrix(unsigned srcX, unsigned fbinX){ return blocking_matrix(srcX, fbinX); }
#endif /* #ifdef ENABLE_LEGACY_BTK_API */
protected:
bool normalize_weight_;
};
/**
@class SubbandGSCRLS
@brief implementation of recursive least squares of a GSC
@usage
1. calcGSCWeights()
2. initPrecisionMatrix() or setPrecisionMatrix()
3. update_sctive_weight_vecotrs( false ) if you want to stop adapting the active weight vectors.
@note notations are based on Van Trees, "Optimum Array Processing", pp. 766-767.
*/
typedef enum {
CONSTANT_NORM = 0x01,
THRESHOLD_LIMITATION = 0x02,
NO_QUADRATIC_CONSTRAINT = 0x00
} QuadraticConstraintType;
// ----- definition for class `SubbandGSCRLS' -----
//
class SubbandGSCRLS : public SubbandGSC {
public:
SubbandGSCRLS(unsigned fftLen = 512, bool halfBandShift = false, float mu = 0.9, float sigma2=0.0, const String& nm = "SubbandGSCRLS");
~SubbandGSCRLS();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
void init_precision_matrix(float sigma2 = 0.01);
void set_precision_matrix(unsigned fbinX, gsl_matrix_complex *Pz);
void update_active_weight_vecotrs(bool flag){ is_wa_updated_ = flag; }
void set_quadratic_constraint(float alpha, int qctype=1){ alpha_=alpha; qctype_=(QuadraticConstraintType)qctype; }
#ifdef ENABLE_LEGACY_BTK_API
void initPrecisionMatrix(float sigma2 = 0.01){ init_precision_matrix(sigma2); }
void setPrecisionMatrix(unsigned fbinX, gsl_matrix_complex *Pz){ set_precision_matrix(fbinX, Pz); }
void updateActiveWeightVecotrs(bool flag){ update_active_weight_vecotrs(flag); }
void setQuadraticConstraint(float alpha, int qctype=1){ set_quadratic_constraint(alpha, qctype); }
#endif /* #ifdef ENABLE_LEGACY_BTK_API */
private:
void update_active_weight_vector2_(int frame_no); /* the case of the half band shift = False */
bool alloc_subbandGSCRLS_image_();
void free_subbandGSCRLS_image_();
gsl_vector_complex** gz_; /* Gain vectors */
gsl_matrix_complex** Pz_; /* Precision matrices */
gsl_vector_complex* Zf_; /* output of the blocking matrix at each frequency */
gsl_vector_complex* wa_;
float mu_; /* Exponential factor for the covariance matrix */
float* diagonal_weights_;
float alpha_; /* Weight for the quadratic constraint*/
QuadraticConstraintType qctype_;
bool is_wa_updated_;
/* work space for updating active weight vectors */
gsl_vector_complex* PzH_Z_;
gsl_matrix_complex* _I;
gsl_matrix_complex* mat1_;
};
// ----- definition for class `SubbandMMI' -----
//
class SubbandMMI : public SubbandDS {
public:
SubbandMMI(unsigned fftLen = 512, bool halfBandShift = false, unsigned targetSourceX=0, unsigned nSource=2, int pfType=0, float alpha=0.9, const String& nm = "SubbandMMI")
: SubbandDS( fftLen, halfBandShift, nm ),
targetSourceX_(targetSourceX),
nSource_(nSource),
pftype_(pfType),
alpha_(alpha),
use_binary_mask_(false),
binary_mask_type_(0),
interference_outputs_(NULL),
avg_output_(NULL)
{}
~SubbandMMI();
virtual const gsl_vector_complex* next(int frame_no = -5);
void use_binary_mask(float avgFactor=-1.0, unsigned fwidth=1, unsigned type=0);
void calc_weights( float samplerate, const gsl_matrix* delays);
void calc_weights_n( float samplerate, const gsl_matrix* delays, unsigned NC=2);
void set_hi_active_weights_f(unsigned fbinX, const gsl_vector* pkdWa, const gsl_vector* pkdwb, int option=0);
void set_active_weights_f(unsigned fbinX, const gsl_matrix* packedWeights, int option=0);
#ifdef ENABLE_LEGACY_BTK_API
void useBinaryMask(float avgFactor=-1.0, unsigned fwidth=1, unsigned type=0){ use_binary_mask(avgFactor, fwidth, type); }
void calcWeights( float sampleRate, const gsl_matrix* delays){ calc_weights(sampleRate, delays); }
void calcWeightsN( float sampleRate, const gsl_matrix* delays, unsigned NC=2){ calc_weights_n(sampleRate, delays, NC); }
void setHiActiveWeights_f(unsigned fbinX, const gsl_vector* pkdWa, const gsl_vector* pkdwb, int option=0){
set_hi_active_weights_f(fbinX, pkdWa, pkdwb, option);
}
void setActiveWeights_f(unsigned fbinX, const gsl_matrix* packedWeights, int option=0){
set_active_weights_f(fbinX, packedWeights, option);
}
#endif /* #ifdef ENABLE_LEGACY_BTK_API */
private:
void calc_interference_outputs_();
void binary_masking_( gsl_vector_complex** interferenceOutputs, unsigned targetSourceX, gsl_vector_complex* output );
unsigned targetSourceX_; // the n-th source will be emphasized
unsigned nSource_; // the number of sound sources
int pftype_;
float alpha_;
bool use_binary_mask_; // true if you use a binary mask
unsigned binary_mask_type_;// 0:use GSC's outputs, 1:use outputs of the upper branch.
gsl_vector_complex** interference_outputs_;
gsl_vector_complex* avg_output_;
float avg_factor_;
unsigned fwidth_;
};
// ----- definition for class `SubbandMVDR' -----
//
/**
@class SubbandMVDR
@usage
1. setChannel()
2. calc_array_manifold_vectors(), calc_array_manifold_vectors2() or calc_array_manifold_vectorsN().
3. set_noise_spatial_spectral_matrix() or set_diffuse_noise_model()
4. calc_mvdr_weights()
*/
class SubbandMVDR : public SubbandDS {
public:
/**
@brief Basic MVDR beamformer implementation
@param int fftLen[in]
@param bool halfBandShift[in]
*/
SubbandMVDR(unsigned fftLen = 512, bool halfBandShift = false, const String& nm = "SubbandMVDR");
~SubbandMVDR();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void clear_channel();
bool calc_mvdr_weights(float samplerate, float dThreshold = 1.0E-8, bool calcInverseMatrix = true);
const gsl_vector_complex* mvdr_weights(unsigned fbinX) const { return wmvdr_[fbinX]; }
const gsl_matrix_complex *noise_spatial_spectral_matrix(unsigned fbinX) const { return R_[fbinX]; }
bool set_noise_spatial_spectral_matrix(unsigned fbinX, gsl_matrix_complex* Rnn);
bool set_diffuse_noise_model(const gsl_matrix* micPositions, float samplerate, float sspeed = 343740.0); /* micPositions[][x,y,z] */
void set_all_diagonal_loading(float diagonalWeight);
void set_diagonal_looading(unsigned fbinX, float diagonalWeight);
/**
@brief Divide each non-diagonal elemnt by 1 + mu instead of diagonal loading. mu can be interpreted as the ratio of the sensor noise to the ambient noise power.
@param float mu[in]
*/
void divide_all_nondiagonal_elements(float mu){
for(unsigned fbinX=0;fbinX<=fftLen_/2;fbinX++)
divide_nondiagonal_elements( fbinX, mu );
}
void divide_nondiagonal_elements(unsigned fbinX, float mu);
gsl_matrix_complex** noise_spatial_spectral_matrix() const { return R_; }
#ifdef ENABLE_LEGACY_BTK_API
void clearChannel(){ clear_channel(); }
bool calcMVDRWeights( float sampleRate, float dThreshold = 1.0E-8, bool calcInverseMatrix = true ){ return calc_mvdr_weights(sampleRate, dThreshold, calcInverseMatrix); }
const gsl_vector_complex* getMVDRWeights(unsigned fbinX){ return mvdr_weights(fbinX); }
const gsl_matrix_complex *getNoiseSpatialSpectralMatrix(unsigned fbinX){ return noise_spatial_spectral_matrix(fbinX); }
bool setNoiseSpatialSpectralMatrix(unsigned fbinX, gsl_matrix_complex* Rnn){ return set_noise_spatial_spectral_matrix(fbinX, Rnn); }
bool setDiffuseNoiseModel(const gsl_matrix* micPositions, float sampleRate, float sspeed = 343740.0){ return set_diffuse_noise_model(micPositions, sampleRate, sspeed); }
void setAllLevelsOfDiagonalLoading(float diagonalWeight){ set_all_diagonal_loading(diagonalWeight); }
void setLevelOfDiagonalLoading(unsigned fbinX, float diagonalWeight){ set_diagonal_looading(fbinX, diagonalWeight); }
void divideAllNonDiagonalElements( float mu ){ divide_all_nondiagonal_elements(mu); }
void divideNonDiagonalElements( unsigned fbinX, float mu ){ divide_nondiagonal_elements(fbinX, mu); }
gsl_matrix_complex** getNoiseSpatialSpectralMatrix(){ return noise_spatial_spectral_matrix(); }
#endif /* #ifdef ENABLE_LEGACY_BTK_API */
protected:
gsl_matrix_complex** R_; /* Noise spatial spectral matrices */
gsl_matrix_complex** invR_;
gsl_vector_complex** wmvdr_;
float* diagonal_weights_;
};
// ----- definition for class `SubbandMVDRGSC' -----
//
/**
@class SubbandMVDRGSC
@usage
1. setChannel()
2. calc_array_manifold_vectors(), calc_array_manifold_vectors2() or calc_array_manifold_vectorsN().
3. set_noise_spatial_spectral_matrix() or set_diffuse_noise_model()
4. calc_mvdr_weights()
5. calc_blocking_matrix1() or calc_blocking_matrix2()
6. set_active_weights_f()
*/
class SubbandMVDRGSC : public SubbandMVDR {
public:
/**
@brief MVDR beamforming implementation
@param int fftLen[in]
@param bool halfBandShift[in]
*/
SubbandMVDRGSC(unsigned fftLen = 512, bool halfBandShift = false, const String& nm = "SubbandMVDR");
~SubbandMVDRGSC();
virtual const gsl_vector_complex* next(int frame_no = -5);
void set_active_weights_f(unsigned fbinX, const gsl_vector* packedWeight);
void zero_active_weights();
bool calc_blocking_matrix1(float samplerate, const gsl_vector* delaysT);
bool calc_blocking_matrix2();
void upgrade_blocking_matrix();
const gsl_vector_complex* blocking_matrix_output(int outChanX=0);
#ifdef ENABLE_LEGACY_BTK_API
void setActiveWeights_f(unsigned fbinX, const gsl_vector* packedWeight){ set_active_weights_f(fbinX, packedWeight); }
void zeroActiveWeights(){ zero_active_weights(); }
bool calcBlockingMatrix1(float sampleRate, const gsl_vector* delaysT){ return calc_blocking_matrix1(sampleRate, delaysT); }
bool calcBlockingMatrix2(){ return calc_blocking_matrix2(); }
void upgradeBlockingMatrix(){ upgrade_blocking_matrix(); }
const gsl_vector_complex* blockingMatrixOutput(int outChanX=0){ return blocking_matrix_output(outChanX); }
#endif
protected:
bool normalize_weight_;
};
typedef Inherit<SubbandBeamformer, VectorComplexFeatureStreamPtr> SubbandBeamformerPtr;
typedef Inherit<SubbandDS, SubbandBeamformerPtr> SubbandDSPtr;
typedef Inherit<SubbandGSC, SubbandDSPtr> SubbandGSCPtr;
typedef Inherit<SubbandGSCRLS, SubbandGSCPtr> SubbandGSCRLSPtr;
typedef Inherit<SubbandMMI, SubbandDSPtr> SubbandMMIPtr;
typedef Inherit<SubbandMVDR, SubbandDSPtr> SubbandMVDRPtr;
typedef Inherit<SubbandMVDRGSC, SubbandMVDRPtr> SubbandMVDRGSCPtr;
// ----- members for class `SubbandOrthogonalizer' -----
//
class SubbandOrthogonalizer : public VectorComplexFeatureStream {
public:
SubbandOrthogonalizer(SubbandMVDRGSCPtr &beamformer, int outChanX=0, const String& nm = "SubbandOrthogonalizer");
~SubbandOrthogonalizer();
virtual const gsl_vector_complex* next(int frame_no = -5);
private:
SubbandMVDRGSCPtr beamformer_;
int outChanX_;
};
typedef Inherit<SubbandOrthogonalizer, VectorComplexFeatureStreamPtr> SubbandOrthogonalizerPtr;
class SubbandBlockingMatrix : public SubbandGSC {
public:
SubbandBlockingMatrix(unsigned fftLen=512, bool halfBandShift=false, const String& nm = "SubbandBlockingMatrix")
:SubbandGSC(fftLen, halfBandShift, nm ){;}
~SubbandBlockingMatrix();
virtual const gsl_vector_complex* next(int frame_no = -5);
};
// ----- definition for class DOAEstimatorSRPBase' -----
//
class DOAEstimatorSRPBase {
public:
DOAEstimatorSRPBase( unsigned nBest, unsigned fbinMax );
virtual ~DOAEstimatorSRPBase();
const gsl_vector *nbest_rps() const { return nBestRPs_; }
const gsl_matrix *nbest_doas() const { return argMaxDOAs_;}
const gsl_matrix *response_power_matrix() const { return rpMat_;}
float energy() const {return energy_;}
void final_nbest_hypotheses(){get_nbest_hypotheses_from_accrp_();}
void set_energy_threshold(float engeryThreshold){ engery_threshold_ = engeryThreshold; }
void set_frequency_range(unsigned fbinMin, unsigned fbinMax){ fbinMin_ = fbinMin; fbinMax_ = fbinMax;}
void init_accs(){ init_accs_(); }
void set_search_param(float minTheta=-M_PI/2, float maxTheta=M_PI/2,
float minPhi=-M_PI/2, float maxPhi=M_PI/2,
float widthTheta=0.1, float widthPhi=0.1);
#ifdef ENABLE_LEGACY_BTK_API
const gsl_vector *getNBestRPs(){ return nbest_rps(); }
const gsl_matrix *getNBestDOAs(){ return nbest_doas(); }
const gsl_matrix *getResponsePowerMatrix(){ return response_power_matrix(); }
float getEnergy(){return energy();}
void getFinalNBestHypotheses(){ final_nbest_hypotheses(); }
void setEnergyThreshold(float engeryThreshold){ set_energy_threshold(engeryThreshold); }
void setFrequencyRange(unsigned fbinMin, unsigned fbinMax){ set_frequency_range(fbinMin, fbinMax); }
void initAccs(){ init_accs(); }
void setSearchParam(float minTheta=-M_PI/2, float maxTheta=M_PI/2,
float minPhi=-M_PI/2, float maxPhi=M_PI/2,
float widthTheta=0.1, float widthPhi=0.1)
{
set_search_param(minTheta, maxTheta, minPhi, maxPhi, widthTheta, widthPhi);
}
#endif
protected:
void clear_table_();
virtual void get_nbest_hypotheses_from_accrp_();
virtual void init_accs_();
float widthTheta_;
float widthPhi_;
float minTheta_;
float maxTheta_;
float minPhi_;
float maxPhi_;
unsigned nTheta_;
unsigned nPhi_;
unsigned fbinMin_;
unsigned fbinMax_;
unsigned nBest_;
bool table_initialized_;
gsl_vector *accRPs_;
gsl_vector *nBestRPs_;
gsl_matrix *argMaxDOAs_;
vector<gsl_vector_complex **> svTbl_; // [][fftL2+1][_dim]
gsl_matrix *rpMat_;
float engery_threshold_;
float energy_;
#ifdef __MBDEBUG__
void allocDebugWorkSapce();
#endif /* #ifdef __MBDEBUG__ */
};
// ----- definition for class DOAEstimatorSRPDSBLA' -----
//
/**
@brief estimate the direction of arrival based on the maximum steered response power
@usage
1. construct an object
2. set the geometry of the linear array
3. call next()
*/
class DOAEstimatorSRPDSBLA :
public DOAEstimatorSRPBase, public SubbandDS {
public:
DOAEstimatorSRPDSBLA( unsigned nBest, unsigned samplerate, unsigned fftLen, const String& nm="DOAEstimatorSRPDSBLA" );
~DOAEstimatorSRPDSBLA();
const gsl_vector_complex* next(int frame_no = -5);
void reset();
void set_array_geometry(gsl_vector *positions);
#ifdef ENABLE_LEGACY_BTK_API
void setArrayGeometry(gsl_vector *positions){ set_array_geometry(positions); }
#endif
protected:
virtual void calc_steering_unit_table_();
virtual float calc_response_power_( unsigned uttX );
private:
virtual void set_look_direction_( int nChan, float theta );
unsigned samplerate_;
gsl_matrix *arraygeometry_; // [micX][x,y,z]
};
typedef refcount_ptr<DOAEstimatorSRPBase> DOAEstimatorSRPBasePtr;
typedef Inherit<DOAEstimatorSRPDSBLA, SubbandDSPtr> DOAEstimatorSRPDSBLAPtr;
// ----- definition for functions' -----
//
float calc_energy(SnapShotArrayPtr snapShotArray, unsigned fbinMin, unsigned fbinMax, unsigned fftLen2, bool halfBandShift=false);
void calc_gsc_output(const gsl_vector_complex* snapShot,
gsl_vector_complex* wl_f, gsl_vector_complex* wq_f,
gsl_complex *pYf, bool normalizeWeight=false );
bool pseudoinverse( gsl_matrix_complex *A, gsl_matrix_complex *invA, float dThreshold = 1.0E-8 );
void calc_all_delays(float x, float y, float z, const gsl_matrix* mpos, gsl_vector* delays);
void calc_product(gsl_vector_complex* synthesisSamples, gsl_matrix_complex* gs_W, gsl_vector_complex* product);
#ifdef ENABLE_LEGACY_BTK_API
inline void calcAllDelays(float x, float y, float z, const gsl_matrix* mpos, gsl_vector* delays)
{
calc_all_delays(x, y, z, mpos, delays);
}
inline void calcProduct(gsl_vector_complex* synthesisSamples, gsl_matrix_complex* gs_W, gsl_vector_complex* product)
{
calc_product(synthesisSamples, gs_W, product);
}
#endif
#endif
| {
"alphanum_fraction": 0.7464452145,
"avg_line_length": 41.9148580968,
"ext": "h",
"hexsha": "0223f214753cdd9f91fb7eedc608da37400c8ba0",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z",
"max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "musiclvme/distant_speech_recognition",
"max_forks_repo_path": "btk20_src/beamformer/beamformer.h",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "musiclvme/distant_speech_recognition",
"max_issues_repo_path": "btk20_src/beamformer/beamformer.h",
"max_line_length": 173,
"max_stars_count": 136,
"max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "musiclvme/distant_speech_recognition",
"max_stars_repo_path": "btk20_src/beamformer/beamformer.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z",
"num_tokens": 6547,
"size": 25107
} |
#include <stdio.h>
#include <gsl/gsl_sf_bessel.h>
int main( int argc, const char *argv[] ) {
double x = 5.0 ;
double y = gsl_sf_bessel_J0( x ) ;
printf("J0(%g) = % .18e\n", x, y ) ;
return 0 ;
}
| {
"alphanum_fraction": 0.46484375,
"avg_line_length": 23.2727272727,
"ext": "c",
"hexsha": "89e90ea5aa1858c68e1225613cc7e29082f4bde0",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-05-14T22:34:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-05-14T22:34:13.000Z",
"max_forks_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "subramon/qlu",
"max_forks_repo_path": "experimental/c_files/gsl_test/gsl_test.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47",
"max_issues_repo_issues_event_max_datetime": "2020-09-26T23:47:22.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-29T16:48:25.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "subramon/qlu",
"max_issues_repo_path": "experimental/c_files/gsl_test/gsl_test.c",
"max_line_length": 52,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2fb8a2b3636dd11e2dfeae2a6477bd130316da47",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "subramon/qlu",
"max_stars_repo_path": "experimental/c_files/gsl_test/gsl_test.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 81,
"size": 256
} |
/* rng/transputer.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
/* This is the INMOS Transputer Development System generator. The sequence is,
x_{n+1} = (a x_n) mod m
with a = 1664525 and m = 2^32. The seed specifies the initial
value, x_1.
The theoretical value of x_{10001} is 1244127297.
The period of this generator is 2^30. */
static inline unsigned long int transputer_get (void *vstate);
static double transputer_get_double (void *vstate);
static void transputer_set (void *state, unsigned long int s);
typedef struct
{
unsigned long int x;
}
transputer_state_t;
static unsigned long int
transputer_get (void *vstate)
{
transputer_state_t *state = (transputer_state_t *) vstate;
state->x = (1664525 * state->x) & 0xffffffffUL;
return state->x;
}
static double
transputer_get_double (void *vstate)
{
return transputer_get (vstate) / 4294967296.0 ;
}
static void
transputer_set (void *vstate, unsigned long int s)
{
transputer_state_t *state = (transputer_state_t *) vstate;
if (s == 0)
s = 1 ; /* default seed is 1. */
state->x = s;
return;
}
static const gsl_rng_type transputer_type =
{"transputer", /* name */
0xffffffffUL, /* RAND_MAX */
1, /* RAND_MIN */
sizeof (transputer_state_t),
&transputer_set,
&transputer_get,
&transputer_get_double};
const gsl_rng_type *gsl_rng_transputer = &transputer_type;
| {
"alphanum_fraction": 0.6983362522,
"avg_line_length": 27.1904761905,
"ext": "c",
"hexsha": "a2c422ab925caf874b7055e5cf5e877d5e97cd35",
"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/rng/transputer.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/rng/transputer.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/rng/transputer.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": 616,
"size": 2284
} |
/* Authors:
G. Jungman
J. Scott (james.scott@lexifi.com)
*/
/* Implementation for Sobol generator.
* See
* [Bratley+Fox, TOMS 14, 88 (1988)]
* [Antonov+Saleev, USSR Comput. Maths. Math. Phys. 19, 252 (1980)]
*/
#include <config.h>
#include <gsl/gsl_qrng.h>
#include <gsl/gsl_rng.h>
#define SOBOL_BIT_COUNT 30
/* prototypes for generator type functions */
static size_t sobol_state_size(unsigned int dimension);
static int sobol_init(void * state, unsigned int dimension);
static int sobol_get(void * state, unsigned int dimension, double * v);
/* global Sobol generator type object */
static const gsl_qrng_type sobol_type =
{
"sobol",
0,
sobol_state_size,
sobol_init,
sobol_get
};
const gsl_qrng_type * gsl_qrng_sobol = &sobol_type;
/* Sobol generator state.
* sequence_count = number of calls with this generator
* last_numerator_vec = last generated numerator vector
* last_denominator_inv = 1/denominator for last numerator vector
* v_direction = direction number table
*/
typedef struct
{
unsigned int sequence_count;
double last_denominator_inv;
int *last_numerator_vec;
int *v_direction[SOBOL_BIT_COUNT];
} sobol_state_t;
static size_t sobol_state_size(unsigned int dimension)
{
return
sizeof(sobol_state_t) + /* The struct */
sizeof(int) * dimension + /* for last_numerator_vec */
sizeof(int) * dimension * SOBOL_BIT_COUNT; /* for the direction no.s */
}
/* l is a degree number, between 1 and the degree of the polynomial
associated with the dimension being initialized */
static int sobol_init_direction(gsl_rng *r, int l)
{
/* See Peter Jaeckel, Monte Carlo Methods in Finance, Wiley 2002, p86.
*/
int wkl = gsl_rng_uniform_int(r, 1<<l) | 1;
return wkl;
}
void get_primitive_polynomials(int dimension, int *degree_table, int *primitive_polynomials);
static int sobol_init(void * state, unsigned int dimension)
{
sobol_state_t * s_state = (sobol_state_t *) state;
unsigned int i_dim;
int j, k;
int ell;
int *degree_table;
int *primitive_polynomials;
int *includ;
int max_degree;
gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
if(dimension < 1) {
return GSL_EINVAL;
}
{ /* initialize degree_table, primitive_polynomials, max_degree and includ */
degree_table = (int *) malloc(sizeof(int) * dimension);
if (degree_table==0)
GSL_ERROR_NULL ("allocation of degree table failed for sobol init", GSL_ENOMEM);
primitive_polynomials = (int *) malloc(sizeof(int) * dimension);
if (primitive_polynomials==0) {
free(degree_table);
GSL_ERROR_NULL ("allocation of primitives failed for sobol init", GSL_ENOMEM);
}
/* Generate the primitive polynomials */
get_primitive_polynomials(dimension, degree_table, primitive_polynomials);
max_degree = degree_table[dimension-1];
includ = (int *) malloc(sizeof(int) * max_degree);
if (includ==0) {
free(degree_table);
free(primitive_polynomials);
GSL_ERROR_NULL ("allocation of 'includ' failed for sobol init", GSL_ENOMEM);
}
}
s_state->last_numerator_vec = (int *) ((char *) s_state + sizeof(sobol_state_t));
/* Initialize direction table in dimension 0. */
for(k=0; k<SOBOL_BIT_COUNT; k++) {
s_state->v_direction[k] =
(int *) (((char *) s_state) +
sizeof(sobol_state_t) +
sizeof(int) * dimension +
sizeof(int) * dimension * k);
s_state->v_direction[k][0] = 1;
}
/* Initialize in remaining dimensions. */
for(i_dim=1; i_dim<dimension; i_dim++) {
const int poly_index = i_dim;
const int degree_i = degree_table[poly_index];
/* Expand the polynomial bit pattern to separate
* components of the logical array includ[].
*/
int p_i = primitive_polynomials[poly_index];
for(k = degree_i-1; k >= 0; k--) {
includ[k] = ((p_i % 2) == 1);
p_i /= 2;
}
/* Leading elements for dimension i are randomly initialized */
for(j=0; j<degree_i; j++) s_state->v_direction[j][i_dim] = sobol_init_direction(r, j+1);
/* Calculate remaining elements for this dimension,
* as explained in Bratley+Fox, section 2.
*/
for(j=degree_i; j<SOBOL_BIT_COUNT; j++) {
int newv = s_state->v_direction[j-degree_i][i_dim];
ell = 1;
for(k=0; k<degree_i; k++) {
ell *= 2;
if(includ[k]) newv ^= (ell * s_state->v_direction[j-k-1][i_dim]);
}
s_state->v_direction[j][i_dim] = newv;
}
}
/* Multiply columns of v by appropriate power of 2. */
ell = 1;
for(j=SOBOL_BIT_COUNT-1-1; j>=0; j--) {
ell *= 2;
for(i_dim=0; i_dim<dimension; i_dim++) {
s_state->v_direction[j][i_dim] *= ell;
}
}
/* 1/(common denominator of the elements in v_direction) */
s_state->last_denominator_inv = 1.0 /(2.0 * ell);
/* final setup */
s_state->sequence_count = 0;
for(i_dim=0; i_dim<dimension; i_dim++) s_state->last_numerator_vec[i_dim] = 0;
free(degree_table);
free(primitive_polynomials);
free(includ);
gsl_rng_free(r);
return GSL_SUCCESS;
}
static int sobol_get(void * state, unsigned int dimension, double * v)
{
sobol_state_t * s_state = (sobol_state_t *) state;
unsigned int i_dimension;
/* Find the position of the least-significant zero in count. */
int ell = 0;
int c = s_state->sequence_count;
while(1) {
++ell;
if((c % 2) == 1) c /= 2;
else break;
}
/* Check for exhaustion. */
if(ell > SOBOL_BIT_COUNT) return GSL_EFAILED; /* FIXME: good return code here */
for(i_dimension=0; i_dimension<dimension; i_dimension++) {
const int direction_i = s_state->v_direction[ell-1][i_dimension];
const int old_numerator_i = s_state->last_numerator_vec[i_dimension];
const int new_numerator_i = old_numerator_i ^ direction_i;
s_state->last_numerator_vec[i_dimension] = new_numerator_i;
v[i_dimension] = new_numerator_i * s_state->last_denominator_inv;
}
s_state->sequence_count++;
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.6662273476,
"avg_line_length": 29.4660194175,
"ext": "c",
"hexsha": "f70f1fd9ab5b2bca02170b27881282c257b370b2",
"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/contrib/jsqrng-sobol.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/contrib/jsqrng-sobol.c",
"max_line_length": 94,
"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/contrib/jsqrng-sobol.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": 1720,
"size": 6070
} |
/* matrixio.c */
// 8.4.13 Example programs for matrices of gsl-ref.pdf
// GNU GSL GNU Scientific Library reference book
// pp. 99,100
/*
Compiling advice:
gcc matrixio.c -lgsl -lgslcblas
*/
#include <stdio.h>
#include <gsl/gsl_matrix.h>
int main (void) {
int i, j, k = 0;
gsl_matrix * m = gsl_matrix_alloc (100, 100);
gsl_matrix * a = gsl_matrix_alloc (100, 100);
for (i = 0; i < 100; i++)
for (j = 0; j < 100; j++)
gsl_matrix_set (m, i, j, 0.23 + 100*i + j);
{
FILE * f = fopen("test.dat", "wb");
gsl_matrix_fwrite (f, m);
fclose (f);
}
{
FILE * f = fopen ("test.dat", "rb") ;
gsl_matrix_fread(f, a);
fclose (f);
}
for (i = 0; i < 100; i++)
for (j = 0; j < 100; j++)
{
double mij = gsl_matrix_get (m, i, j);
double aij = gsl_matrix_get (a, i, j);
if (mij != aij) k++;
}
gsl_matrix_free(m);
gsl_matrix_free(a);
printf("differences = %d (should be zero)\n", k);
return (k > 0);
}
| {
"alphanum_fraction": 0.5470171891,
"avg_line_length": 19.0192307692,
"ext": "c",
"hexsha": "73694071562857717ac31fda2a58e9906a0290bf",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2021-03-01T07:13:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-01-24T19:18:42.000Z",
"max_forks_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ernestyalumni/CompPhys",
"max_forks_repo_path": "gslExamples/matrixio.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855",
"max_issues_repo_issues_event_max_datetime": "2019-01-29T22:37:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-01-16T22:34:47.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ernestyalumni/CompPhys",
"max_issues_repo_path": "gslExamples/matrixio.c",
"max_line_length": 54,
"max_stars_count": 70,
"max_stars_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ernestyalumni/CompPhys",
"max_stars_repo_path": "gslExamples/matrixio.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-24T16:00:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-07-24T04:09:27.000Z",
"num_tokens": 350,
"size": 989
} |
#include "lah.h"
#ifdef HAVE_LAPACK
#include <lapacke.h>
lah_Return lah_solveLU(lah_mat *B, lah_mat const *L, lapack_int *ipiv)
{
if ( L == NULL || B == NULL || L->nR != B->nR
|| B->nR != L->nC)
{
return lahReturnParameterError;
}
/*
if (matrix_layout == LAPACK_COL_MAJOR)
{
lda = L->nR;
ldb = B->nR;
}
else
{
lda = L->nC;
ldb = B->nC;
}
*/
return (!GETRS(LAH_LAPACK_LAYOUT, 'N', B->nR, B->nC, L->data , LAH_LEADING_DIM(L), ipiv, B->data, LAH_LEADING_DIM(B))) ? lahReturnOk : lahReturnExternError;
}
#endif
| {
"alphanum_fraction": 0.5325732899,
"avg_line_length": 21.1724137931,
"ext": "c",
"hexsha": "e5d4596e2fd07d9be09e6fdb2590a06a037b5aea",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "maj0e/linear-algebra-helpers",
"max_forks_repo_path": "Source/lah_solveLU.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "maj0e/linear-algebra-helpers",
"max_issues_repo_path": "Source/lah_solveLU.c",
"max_line_length": 160,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "maj0e/linear-algebra-helpers",
"max_stars_repo_path": "Source/lah_solveLU.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 212,
"size": 614
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** 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. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#include <petsc.h>
#include <petscvec.h>
#include <petscmat.h>
#include <petscksp.h>
#include "common-driver-utils.h"
/*
Stokes output:
---------------------------------
Operator summary:
K
G
f,
h
u
p
---------------------------------
Solution summary:
max_u
min_u
average_u
|r_1|
|r_2|
---------------------------------
Solver summary:
name
---------------------------------
Petsc build summary:
*/
PetscErrorCode BSSCR_stokes_output( PetscViewer v, Mat stokes_A, Vec stokes_b, Vec stokes_x, KSP ksp, PetscInt monitor_index )
{
Mat K,G,D,C;
Vec f,h, u,p;
K = G = D = C = PETSC_NULL;
f = h = PETSC_NULL;
u = p = PETSC_NULL;
MatNestGetSubMat( stokes_A, 0,0, &K );
MatNestGetSubMat( stokes_A, 0,1, &G );
MatNestGetSubMat( stokes_A, 1,0, &D );
MatNestGetSubMat( stokes_A, 1,1, &C );
VecNestGetSubVec( stokes_x, 0, &u );
VecNestGetSubVec( stokes_x, 1, &p );
VecNestGetSubVec( stokes_b, 0, &f );
VecNestGetSubVec( stokes_b, 1, &h );
PetscViewerASCIIPrintf( v, "Stokes Output:\n");
PetscViewerASCIIPushTab( v );
/*--------------------------------------------------------------------------------------------*/
PetscViewerASCIIPrintf( v, "--------------------------------------------------\n");
PetscViewerASCIIPrintf( v, "Operator summary:\n");
PetscViewerASCIIPushTab( v );
if (K) { BSSCR_MatInfoLog(v,K, "stokes_A11"); PetscViewerASCIIPrintf( v, "\n"); }
if (G) { BSSCR_MatInfoLog(v,G, "stokes_A12"); PetscViewerASCIIPrintf( v, "\n"); }
if (D){ BSSCR_MatInfoLog(v,D, "stokes_A21"); PetscViewerASCIIPrintf( v, "\n"); }
if (C) { BSSCR_MatInfoLog(v,C, "stokes_A22"); PetscViewerASCIIPrintf( v, "\n"); }
if (f) { BSSCR_VecInfoLog(v,f,"stokes_b1"); PetscViewerASCIIPrintf( v, "\n"); }
if (h) { BSSCR_VecInfoLog(v,h,"stokes_b2"); PetscViewerASCIIPrintf( v, "\n"); }
PetscViewerASCIIPopTab( v );
/*--------------------------------------------------------------------------------------------*/
PetscViewerASCIIPrintf( v, "--------------------------------------------------\n");
PetscViewerASCIIPrintf( v, "Solution summary:\n");
PetscViewerASCIIPushTab( v );
if (u) { BSSCR_VecInfoLog(v,u,"x1"); PetscViewerASCIIPrintf( v, "\n"); }
if (p) { BSSCR_VecInfoLog(v,p,"x2"); PetscViewerASCIIPrintf( v, "\n"); }
{
PetscScalar s,sum;
PetscReal r,max,min;
PetscInt N, loc;
double r1,r2;
Vec K_d;
PetscInt loc_max, loc_min;
VecGetSize( u, &N );
VecMax( u, &loc, &r ); PetscViewerASCIIPrintf( v, "u_max: %1.12e [%d] \n", r, loc );
VecMin( u, &loc, &r ); PetscViewerASCIIPrintf( v, "u_min: %1.12e [%d] \n", r, loc );
VecDot( u,u, &s ); PetscViewerASCIIPrintf( v, "u_rms: %1.12e \n", sqrt( PetscRealPart(s) )/N );
VecDuplicate( u, &K_d );
MatGetDiagonal( K, K_d );
VecMax( K_d, &loc_max, &max );
VecMin( K_d, &loc_min, &min );
PetscViewerASCIIPrintf( v,"Algebraic contrast: max(K_d)=%.3e [%d] , min(K_d)=%.3e [%d] , max(K_d)/min(K_d) = %.8e \n", max,loc_max, min,loc_min, max/min );
MatGetRowMax( K, K_d, PETSC_NULL );
VecMax( K_d, &loc_max, &max );
MatGetRowMin( K, K_d, PETSC_NULL );
VecAbs( K_d );
VecMin( K_d, &loc_min, &min );
PetscViewerASCIIPrintf( v,"Algebraic contrast: max(K)=%.3e [%d] , |min(K)|=%.3e [%d] , max(K)/|min(K)| = %.8e \n", max,loc_max, min,loc_min, max/min );
Stg_VecDestroy(&K_d );
PetscViewerASCIIPrintf( v, "\n");
VecGetSize( p, &N );
VecMax( p, &loc, &r ); PetscViewerASCIIPrintf( v, "p_max: %1.12e [%d] \n", r, loc );
VecMin( p, &loc, &r ); PetscViewerASCIIPrintf( v, "p_min: %1.12e [%d] \n", r, loc );
VecDot( p,p, &s ); PetscViewerASCIIPrintf( v, "p_rms: %1.12e \n", sqrt( PetscRealPart(s) )/N );
VecSum( p, &sum ); PetscViewerASCIIPrintf( v, "sum(p): %1.12e \n", sum );
PetscViewerASCIIPrintf( v, "\n");
r1 = BSSCR_StokesMomentumResidual( K,G,f, u,p );
PetscViewerASCIIPrintf( v, "|r1| = %1.12e <momentum> \n", r1 );
r2 = BSSCR_StokesContinuityResidual( G,C,h, u,p );
PetscViewerASCIIPrintf( v, "|r2| = %1.12e <continuity> \n", r2 );
PetscViewerASCIIPrintf( v, "\n");
}
PetscViewerASCIIPopTab( v );
/*--------------------------------------------------------------------------------------------*/
if (ksp) {
PetscViewerASCIIPrintf( v, "--------------------------------------------------\n");
PetscViewerASCIIPrintf( v, "Solver summary:\n");
PetscViewerASCIIPushTab( v );
BSSCR_KSPLogSolve( v, monitor_index, ksp );
BSSCR_BSSCR_KSPLogSolveSummary( v, monitor_index, ksp );
PetscViewerASCIIPrintf( v, "\n");
PetscViewerASCIIPopTab( v );
}
/*--------------------------------------------------------------------------------------------*/
PetscViewerASCIIPrintf( v, "--------------------------------------------------\n");
PetscViewerASCIIPrintf( v, "Petsc build summary:\n");
PetscViewerASCIIPushTab( v );
BSSCR_GeneratePetscHeader_for_viewer( v );
PetscViewerASCIIPrintf( v, "\n");
PetscViewerASCIIPopTab( v );
/*--------------------------------------------------------------------------------------------*/
PetscViewerASCIIPopTab(v);
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.5004255319,
"avg_line_length": 33.9595375723,
"ext": "c",
"hexsha": "8966d301b60f367eea054fa596407d40faa9b195",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z",
"max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "longgangfan/underworld2",
"max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_output.c",
"max_issues_count": 561,
"max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "longgangfan/underworld2",
"max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_output.c",
"max_line_length": 158,
"max_stars_count": 116,
"max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "longgangfan/underworld2",
"max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_output.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z",
"num_tokens": 2105,
"size": 5875
} |
#ifndef CWANNIER_DOS_VALUES_H
#define CWANNIER_DOS_VALUES_H
#include <stdbool.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include "HTightBinding.h"
#include "ctetra/dos.h"
double* DosValues(HTightBinding *Hrs, gsl_matrix *R, int na, int nb, int nc, double *Es, double num_dos, bool all_Es);
double* DosEnergyDerivValues(HTightBinding *Hrs, gsl_matrix *R, int na, int nb, int nc, double *Es, int num_dos, double num_electrons, double *fermi, double *dos_fermi, double *dos_deriv_fermi);
#endif // CWANNIER_DOS_VALUES_H
| {
"alphanum_fraction": 0.77090301,
"avg_line_length": 35.1764705882,
"ext": "h",
"hexsha": "77f1b9d7802b5aa0a226609a8aaa9cc3dea457f6",
"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": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tflovorn/cwannier",
"max_forks_repo_path": "DosValues.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8",
"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": "tflovorn/cwannier",
"max_issues_repo_path": "DosValues.h",
"max_line_length": 194,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tflovorn/cwannier",
"max_stars_repo_path": "DosValues.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 191,
"size": 598
} |
/* $Id$ */
/*--------------------------------------------------------------------*/
/*; Copyright (C) 2012-2016 */
/*; Associated Universities, Inc. Washington DC, USA. */
/*; */
/*; 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 Massachusetts Ave, Cambridge, */
/*; MA 02139, USA. */
/*; */
/*;Correspondence about this software should be addressed as follows: */
/*; Internet email: bcotton@nrao.edu. */
/*; Postal address: William Cotton */
/*; National Radio Astronomy Observatory */
/*; 520 Edgemont Road */
/*; Charlottesville, VA 22903-2475 USA */
/*--------------------------------------------------------------------*/
#ifndef OBITPOLNCALFIT_H
#define OBITPOLNCALFIT_H
#include "Obit.h"
#include "ObitErr.h"
#include "ObitUV.h"
#include "ObitThread.h"
#include "ObitInfoList.h"
#include "ObitSource.h"
#include "ObitSourceList.h"
#include "ObitAntennaList.h"
#include "ObitComplex.h"
#include "ObitTableCP.h"
#include "ObitTablePD.h"
#include "ObitTableBP.h"
#ifdef HAVE_GSL
#include <gsl/gsl_multifit_nlin.h>
#endif /* HAVE_GSL */
/*-------- Obit: Merx mollis mortibus nuper ------------------*/
/**
* \file ObitPolnCalFit.h
*
* ObitPolnCalFit Class for fitting polarization calibration to UV data.
*
* This class does least squares fitting of a full nonlinear model
* To instrumental polarization and calibration terms and optionally source
* polarization parameters.
* Results are stored in a combination of AIPS PD (instrumental poln),
* AIPS CP (source poln) and AIPS BP (gain corrections including R-L phase).
*
* \section ObitPolnCalFitaccess Creators and Destructors
* An ObitPolnCalFit will usually be created using ObitPolnCalFitCreate which allows
* specifying a name for the object as well as other information.
*
* A copy of a pointer to an ObitPolnCalFit should always be made using the
* #ObitPolnCalFitRef function which updates the reference count in the object.
* Then whenever freeing an ObitPolnCalFit or changing a pointer, the function
* #ObitPolnCalFitUnref will decrement the reference count and destroy the object
* when the reference count hits 0.
* There is no explicit destructor.
*/
/*---------------Private structures----------------*/
/**
* \enum polnParmType
* enum for I/O file type.
* This specifies the type of underlying data file.
*/
enum polnParmType {
/** Unspecified */
polnParmUnspec=0,
/** Source parameter */
polnParmSou,
/** Antenna parameter */
polnParmAnt,
/** Antenna gain */
polnParmGain,
/** Phase difference */
polnParmPD
}; /* end enum polnParmType */
/** typedef for enum for polnParmType . */
typedef enum polnParmType PolnParmType;
/* Threaded function argument */
typedef struct {
/* Obit error stack object */
ObitErr *err;
/** thread */
ObitThread *thread;
/** thread number, >0 -> no threading */
olong ithread;
/** Do error analysis? */
gboolean doError;
/** First 0-rel datum in Data/Wt arrays */
olong lo;
/** Last 0-rel datum in Data/Wt arrays */
olong hi;
/** selected antenna, 0-> all */
olong selAnt;
/** selected source, 0-> all */
olong selSou;
/** Number of visibilities being fitted */
olong nvis;
/** Number of data points being fitted (nvis*4) */
olong ndata;
/** Array of input data arrays, [10 x nvis]
each row: 2*parallactic angle (rad), blank,
RR_r, RR_i, LL_r, LL_i, RL_r, RL_i, LR_r, LR_i */
ofloat *inData;
/** Array of input data weights (~ 1/var), [4 x nvis]
each row: RR, LL, RL, LR */
ofloat *inWt;
/** Source no of visibility, in range [0,nsou-1] */
olong *souNo;
/** Antenna numbers of visibility, in range [0,nant-1] */
olong *antNo;
/** Number of antennas */
olong nant;
/** Reference antenna */
olong refAnt;
/** Fit only reference antenna R-L phase */
gboolean doFitRL;
/** Fit global X & Y feed gains?: */
gboolean doFitGain;
/** Are the feeds circularly polarized? */
gboolean isCircFeed;
/** Reference frequency (Hz) */
odouble refFreq;
/** Current frequency (Hz) */
odouble curFreq;
/** R-L (or X-Y) phase difference */
odouble PD;
/** Error estimate R-L (or X-Y) phase difference */
odouble PDerr;
/** Fit Stokes I poln, per cal */
gboolean *doFitI;
/** Fit fit source linear poln, per cal */
gboolean *doFitPol;
/** Fit fit Stokes V poln, per cal */
gboolean *doFitV;
/** Antenna parameters 4 x nant,
each row: D1_r, D1_i, D2_r, D2_i */
odouble *antParm;
/** Antenna error estimates 4 x nant */
odouble *antErr;
/** Antenna parameters fit flags, 4 x nant */
gboolean **antFit;
/** Antenna parameters number, 4 x nant */
olong **antPNumb;
/** Antenna gains 2 x nant, each row: Gain_X, gain_Y */
odouble *antGain;
/** Antenna gains error estimates 2 x nant */
odouble *antGainErr;
/* Antenna parameters fit flags, 2 x nant */
gboolean **antGainFit;
/** Antenna gain parameters number, 2 x nant */
olong **antGainPNumb;
/** Number of calibrator sources */
olong nsou;
/** Source parameters 4 x nsou,
each row: I, Poln_amp, Poln_RL (rad), V */
odouble *souParm;
/** Source error estimates 4 x nsou, */
odouble *souErr;
/** Source parameters fit flags, 4 x nsou */
gboolean **souFit;
/** Source parameters number, 4 x nsou */
olong **souPNumb;
/** Source Ids in SU table, Data */
olong *souIDs;
/** Inverse Source Ids lookup, index of data source ID-1
gives calibrator number */
olong *isouIDs;
/** Number of parameters being fitted */
olong nparam;
/** Number of valid parallel observations */
olong nPobs;
/** Number of valid cross pol observations */
olong nXobs;
/** Chi squared of fit */
ofloat ChiSq;
/** Sum of parallel residuals */
odouble sumParResid;
/** Sum of cross residuals */
odouble sumXResid;
/** Parameter type */
PolnParmType paramType;
/** Parameter number */
olong paramNumber;
/** Sum of first derivatives */
odouble sumDeriv;
/** Sum of second derivatives */
odouble sumDeriv2;
/** Sum of weights */
odouble sumWt;
/** Frequency of data */
odouble freq;
/** R-L Phase of calibrators (rad) at Freq */
ofloat *RLPhase;
/** Fractional polarization of calibrators */
ofloat *PPol;
/** Derivative of PPol (GHz) of calibrators */
ofloat *dPPol;
/** Central channel (1-rel) of fit */
olong Chan;
/** IF number (1-rel) */
olong IFno;
/** complex work arrays for antenna based parameters, max 100 ant */
dcomplex RS[100], RD[100], LS[100], LD[100],
RSc[100], RDc[100], LSc[100], LDc[100],
PR[100], PRc[100], PL[100], PLc[100];
odouble SR[100], DR[100], SL[100], DL[100];
/** Max antenna number */
olong maxAnt;
/** Solution method */
gchar solnType[5];
} PolnFitArg;
/*--------------Class definitions-------------------------------------*/
/** ObitPolnCalFit Class structure. */
typedef struct {
#include "ObitPolnCalFitDef.h" /* this class definition */
} ObitPolnCalFit;
/*----------------- Macroes ---------------------------*/
/**
* Macro to unreference (and possibly destroy) an ObitPolnCalFit
* returns a ObitPolnCalFit*.
* in = object to unreference
*/
#define ObitPolnCalFitUnref(in) ObitUnref (in)
/**
* Macro to reference (update reference count) an ObitPolnCalFit.
* returns a ObitPolnCalFit*.
* in = object to reference
*/
#define ObitPolnCalFitRef(in) ObitRef (in)
/**
* Macro to determine if an object is the member of this or a
* derived class.
* Returns TRUE if a member, else FALSE
* in = object to reference
*/
#define ObitPolnCalFitIsA(in) ObitIsA (in, ObitPolnCalFitGetClass())
/*---------------Public functions---------------------------*/
/** Public: Class initializer. */
void ObitPolnCalFitClassInit (void);
/** Public: Default Constructor. */
ObitPolnCalFit* newObitPolnCalFit (gchar* name);
/** Public: Create/initialize ObitPolnCalFit structures */
ObitPolnCalFit* ObitPolnCalFitCreate (gchar* name);
/** Typedef for definition of class pointer structure */
typedef ObitPolnCalFit* (*ObitPolnCalFitCreateFP) (gchar* name);
/** Public: ClassInfo pointer */
gconstpointer ObitPolnCalFitGetClass (void);
/** Public: Copy (deep) constructor. */
ObitPolnCalFit* ObitPolnCalFitCopy (ObitPolnCalFit *in,
ObitPolnCalFit *out, ObitErr *err);
/** Public: Copy structure. */
void ObitPolnCalFitClone (ObitPolnCalFit *in, ObitPolnCalFit *out,
ObitErr *err);
/** Public: Fit a UV data */
void ObitPolnCalFitFit (ObitPolnCalFit* in, ObitUV *inUV,
ObitUV *outUV, ObitErr *err);
/** Typedef for definition of class pointer structure */
typedef void(*ObitPolnCalFitFitFP) (ObitPolnCalFit* in, ObitUV *inUV,
ObitUV *outUV, ObitErr *err);
/*----------- ClassInfo Structure -----------------------------------*/
/**
* ClassInfo Structure.
* Contains class name, a pointer to any parent class
* (NULL if none) and function pointers.
*/
typedef struct {
#include "ObitPolnCalFitClassDef.h"
} ObitPolnCalFitClassInfo;
#endif /* OBITPOLNCALFIT_H */
| {
"alphanum_fraction": 0.6161988929,
"avg_line_length": 34.67003367,
"ext": "h",
"hexsha": "60ce39bb7cbce3e25c07227615787366224491df",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z",
"max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986",
"max_forks_repo_licenses": [
"Linux-OpenIB"
],
"max_forks_repo_name": "sarrvesh/Obit",
"max_forks_repo_path": "ObitSystem/Obit/include/ObitPolnCalFit.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Linux-OpenIB"
],
"max_issues_repo_name": "sarrvesh/Obit",
"max_issues_repo_path": "ObitSystem/Obit/include/ObitPolnCalFit.h",
"max_line_length": 85,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986",
"max_stars_repo_licenses": [
"Linux-OpenIB"
],
"max_stars_repo_name": "sarrvesh/Obit",
"max_stars_repo_path": "ObitSystem/Obit/include/ObitPolnCalFit.h",
"max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z",
"num_tokens": 2766,
"size": 10297
} |
/*
* mutation.c
*
* Created on: 5.5.2017
* Author: heine
*/
#define _XOPEN_SOURCE 600
#include <math.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <mpi.h>
//static const gsl_rng_type * T; // Generator type
//static const gsl_rng * rgen; // Generator
/*void set_mutationseed( int id ) {
struct timespec spec;
clock_gettime( CLOCK_REALTIME, &spec );
gsl_rng_env_setup();
T = gsl_rng_default;
rgen = gsl_rng_alloc( T );
gsl_rng_set( rgen, ( unsigned long int ) ( round( spec.tv_nsec / 1.0e6 ) + 34 * id ) );
}*/
void
mutation(
long N,
double *x,
int state_dim,
gsl_rng * rgen )
{
for ( long i = 0; i < N; i++ )
for ( int d = 0; d < state_dim; d++ )
x[ state_dim * i + d ] = x[ state_dim * i + d ] +
gsl_ran_gaussian_ziggurat( rgen, 1.0 );
}
| {
"alphanum_fraction": 0.6097023153,
"avg_line_length": 18.8958333333,
"ext": "c",
"hexsha": "e941cccdf5b718452f59075bc4fd341eef792910",
"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": "2b7d74519289d2dac684b483a85ec2696e694c27",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "heinekmp/AIRPF",
"max_forks_repo_path": "src/mutation.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27",
"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": "heinekmp/AIRPF",
"max_issues_repo_path": "src/mutation.c",
"max_line_length": 89,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2b7d74519289d2dac684b483a85ec2696e694c27",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "heinekmp/AIRPF",
"max_stars_repo_path": "src/mutation.c",
"max_stars_repo_stars_event_max_datetime": "2020-05-21T06:38:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-21T06:38:23.000Z",
"num_tokens": 306,
"size": 907
} |
#include <math.h>
#define FORCE_OPENBLAS_COMPLEX_STRUCT
#include <cblas.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int MKL_INT;
typedef openblas_complex_double MKL_Complex16;
#define AVX512_ALIGN 64
#include "gene_bruit_rayleigh_scalaire.c"
int main(void)
{
int val;
int M, N, K;
int lda, ldb, ldc;
int kboucle;
float charge;
char *p;
FILE *fichier1;
fichier1 = fopen("../results/results_openblas_gemm_fp64.dat", "w");
int has_param_m = 0, has_param_n = 0, has_param_k = 0;
char transa = CblasNoTrans, transb = CblasNoTrans;
if ((p = getenv("MATMUL_M"))) {
M = atoi(p);
has_param_m=1;
}
if ((p = getenv("MATMUL_N"))) {
N = atoi(p);
has_param_n=1;
}
if ((p = getenv("MATMUL_K"))) {
K = atoi(p);
has_param_k=1;
}
if ((p = getenv("TRANSA"))) {
if(*p == 'T')
transa = CblasTrans;
}
if ((p = getenv("TRANSB"))) {
if(*p == 'T')
transb = CblasTrans;
}
/* Begin huge loop */
for (kboucle = 1; kboucle < 31; kboucle++) {
val = 100 * kboucle;
M = has_param_m?M:val;
N = has_param_n?N:val;
K = has_param_k?K:val;
lda = (transa == CblasNoTrans)?M:K;
ldb = (transb == CblasNoTrans)?K:N;
ldc = M;
printf(">>>>> Matrix size %dx%d (K=%d, TransA=%d TransB=%d) <<<<<<\n", M, N, K,\
transa - CblasNoTrans, transb - CblasNoTrans);
int iboucle, jboucle;
int param = 20;
float *mat_real, *mat_imag;
// Timers
struct timespec tpdeb, tpfin, tpcour;
clockid_t clock_id = CLOCK_REALTIME;
int status2;
double dureeloc, dureetot;
dureetot = 0.0;
// BLAS
MKL_Complex16 alpha, beta;
MKL_Complex16 *A, *B, *C;
alpha.real = 1.0;
alpha.imag = 0.0;
beta.real = 0.0;
beta.imag = 0.0;
mat_real = (float *)aligned_alloc(AVX512_ALIGN, val * val * sizeof(float));
mat_imag = (float *)aligned_alloc(AVX512_ALIGN, val * val * sizeof(float));
A = (MKL_Complex16 *)aligned_alloc(AVX512_ALIGN, M * K * sizeof(MKL_Complex16));
B = (MKL_Complex16 *)aligned_alloc(AVX512_ALIGN, K * N * sizeof(MKL_Complex16));
C = (MKL_Complex16 *)aligned_alloc(AVX512_ALIGN, M * N * sizeof(MKL_Complex16));
for (iboucle = 0; iboucle < val * val; iboucle++) {
gene_bruit_rayleigh_scalaire(param, mat_real + iboucle,
mat_imag + iboucle);
}
// Force hermitian matrix
for (iboucle = 0; iboucle < K; iboucle++) {
for (jboucle = 0; jboucle < N; jboucle++) {
B[(iboucle * N) + jboucle].real = (double)(*(mat_real + (jboucle * K) + iboucle));
B[(iboucle * N) + jboucle].imag =
-1.0 * (double)(*(mat_imag + (jboucle * K) + iboucle));
}
}
for (iboucle = 0; iboucle < M * K; iboucle++) {
A[iboucle].real = (double)mat_real[iboucle];
A[iboucle].imag = (double)mat_imag[iboucle];
}
status2 = clock_gettime(clock_id, &tpdeb); // start timer;
cblas_zgemm(CblasColMajor, transa, transb, \
M, N, K, \
&alpha, A, lda, \
B, ldb, &beta, C, ldc);
status2 = clock_gettime(clock_id, &tpfin); // stop timer
dureeloc = (float)(tpfin.tv_sec - tpdeb.tv_sec) +
(float)(tpfin.tv_nsec - tpdeb.tv_nsec) * 1.e-9;
dureetot = dureetot + dureeloc;
printf("execution time = %f ms\n", dureeloc * 1000);
charge = (float)M;
charge = 8.0f * charge * charge * charge;
charge = charge / dureeloc;
printf("%f GFLOPS\n", charge / 1e9);
fprintf(fichier1, "%5.2f\n", charge / 1e9);
free(mat_real);
free(mat_imag);
free(A);
free(B);
free(C);
}
fclose(fichier1);
return 0;
}
| {
"alphanum_fraction": 0.5840347543,
"avg_line_length": 24.8851351351,
"ext": "c",
"hexsha": "9b68b9f4bc7e1b6a075e1287b1f0fe75a3ae684b",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-11-19T18:13:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-07T16:47:16.000Z",
"max_forks_repo_head_hexsha": "1ec81d2475a857fbb81474036af98080b5c1875e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "JishinMaster/scientific_benchmarks",
"max_forks_repo_path": "src/mulmat/zgemm_OPENBLAS.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1ec81d2475a857fbb81474036af98080b5c1875e",
"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": "JishinMaster/scientific_benchmarks",
"max_issues_repo_path": "src/mulmat/zgemm_OPENBLAS.c",
"max_line_length": 90,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1ec81d2475a857fbb81474036af98080b5c1875e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "JishinMaster/scientific_benchmarks",
"max_stars_repo_path": "src/mulmat/zgemm_OPENBLAS.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1281,
"size": 3683
} |
/* specfunc/bessel_J0.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_mode.h>
#include "bessel.h"
#include "bessel_amp_phase.h"
#include <gsl/gsl_sf_trig.h>
#include <gsl/gsl_sf_bessel.h>
#include "cheb_eval.c"
/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/
/* based on SLATEC besj0, 1977 version, w. fullerton */
/* chebyshev expansions for Bessel functions
series for bj0 on the interval 0. to 1.60000d+01
with weighted error 7.47e-18
log weighted error 17.13
significant figures required 16.98
decimal places required 17.68
*/
static double bj0_data[13] = {
0.100254161968939137,
-0.665223007764405132,
0.248983703498281314,
-0.0332527231700357697,
0.0023114179304694015,
-0.0000991127741995080,
0.0000028916708643998,
-0.0000000612108586630,
0.0000000009838650793,
-0.0000000000124235515,
0.0000000000001265433,
-0.0000000000000010619,
0.0000000000000000074,
};
static cheb_series bj0_cs = {
bj0_data,
12,
-1, 1,
9
};
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int gsl_sf_bessel_J0_e(const double x, gsl_sf_result * result)
{
double y = fabs(x);
/* CHECK_POINTER(result) */
if(y < 2.0*GSL_SQRT_DBL_EPSILON) {
result->val = 1.0;
result->err = y*y;
return GSL_SUCCESS;
}
else if(y <= 4.0) {
return cheb_eval_e(&bj0_cs, 0.125*y*y - 1.0, result);
}
else {
const double z = 32.0/(y*y) - 1.0;
gsl_sf_result ca;
gsl_sf_result ct;
gsl_sf_result cp;
const int stat_ca = cheb_eval_e(&_gsl_sf_bessel_amp_phase_bm0_cs, z, &ca);
const int stat_ct = cheb_eval_e(&_gsl_sf_bessel_amp_phase_bth0_cs, z, &ct);
const int stat_cp = gsl_sf_bessel_cos_pi4_e(y, ct.val/y, &cp);
const double sqrty = sqrt(y);
const double ampl = (0.75 + ca.val) / sqrty;
result->val = ampl * cp.val;
result->err = fabs(cp.val) * ca.err/sqrty + fabs(ampl) * cp.err;
result->err += GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_3(stat_ca, stat_ct, stat_cp);
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_bessel_J0(const double x)
{
EVAL_RESULT(gsl_sf_bessel_J0_e(x, &result));
}
| {
"alphanum_fraction": 0.638258737,
"avg_line_length": 29.125,
"ext": "c",
"hexsha": "a0fc5810fc820bc9224e7b649ae9eefd15b38eb6",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_J0.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_J0.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/specfunc/bessel_J0.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": 1034,
"size": 3262
} |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright 2018 - Matteo Ragni, Matteo Cocetti - University of Trento
*
* 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.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <cblas.h>
#include "libeuler.h"
/**
* @brief Internal: Strut that will be passed to euler functions callbacks
*/
typedef struct euler_passthrough
{
double ts; /**< Integration steps. Taken from options struct */
double alpha; /**< Tustin coefficient. Taken from options struct */
lapack_int u_offset; /**< Input offset for \f$t+h\f$ callbacks. Taken from options struct */
euler_ode_function f; /**< Vector field to integrate. Taken from input struct */
euler_ode_jacobian df; /**< Jacobian of the vector field. Taken from options struct */
const double *xk; /**< Current state. Taken from parameters */
lapack_int x_size; /**< Ode dimension, taken from the input struct */
double *work_f; /**< Working space. Allocated in integration step */
double *work_df; /**< Working space. Allocated in integration step */
void *data; /**< User supplied data. Taken from parameters */
} euler_passtrough;
/**
* @brief Euler implicit step wrapper
*
* The vector field wrapper implements the following:
* \f{
* g(\cdot) = -x(t+h) + x(t) + (1-\alpha) h f(x(t), u_{1..u_{off}, p} +
* \alpha h f(x(t+h), u_{u_{off}..dim(u)}, p)
* \f}
* by using user supplied vector field callback. The implicit step search the root
* of \f$g(\cdot)\f$.
*/
void euler_function_wrapper(double *f, const double t, const double *x, const double *u, const double **p, void *data);
/**
* @brief Euler implicit step wrapper jacobian
*
* The vector field wrapper implements the following jacobian matrix:
* \f{
* \nabla_{x(t+h)} g(\cdot) = -I + \alpha h \nabla_{x(t+h)} f(x(t+h), u_{u_{off}..dim(u)}, p)
* \f}
* by using user supplied vector field callback
*/
void euler_jacobian_wrapper(double *f, const double t, const double *x, const double *u, const double **p, void *data);
euler_ret euler(const euler_options *opt, double *xp, const double t, const double *x, const double *u, const double **p, void *data)
{
/* EXPLICIT IMPLEMENTATION */
/* Performin a very simple step if alpha == 0 */
if (opt->alpha == 0)
{
opt->f(xp, t, x, u, p, opt->data);
cblas_dscal(opt->x_size, opt->ts, xp, 1);
cblas_daxpy(opt->x_size, 1, x, 1, xp, 1);
return EULER_SUCCESS;
}
/* IMPLICIT IMPLEMENTTION */
/* Allocating working memory */
double *work_f = (double *)calloc(2 * opt->x_size, sizeof(double));
if (!work_f)
return EULER_EMALLOC;
double *work_df = (double *)calloc(2 * opt->x_size * opt->x_size, sizeof(double));
if(!work_df) {
free(work_f);
return EULER_EMALLOC;
}
/* Setting up the identity matrix in work_df second space, once forever */
for (lapack_int i = 0; i < opt->x_size; i++)
work_df[(opt->x_size * opt->x_size) + i + i * opt->x_size] = -1.0;
/* Setting up options for Euler step */
newton_options newton_opts = {
opt->ordering, opt->x_size, opt->x_size,
opt->s_tol, opt->x_tol, opt->max_iter,
euler_function_wrapper,
euler_jacobian_wrapper
};
euler_passtrough pt = {
opt->ts, opt->alpha, opt->u_offset,
opt->f, opt->df, x, opt->x_size,
work_f, work_df,
opt->data
};
cblas_dcopy(opt->x_size, x, 1, xp, 1);
newton_ret nwt = newton_solve(&newton_opts, t, xp, u, p, ((void *)&pt));
/* Freeing space */
free(work_f);
free(work_df);
if (nwt > NEWTON_MAX_ITER)
return EULER_GENERIC;
return EULER_SUCCESS;
}
void euler_function_wrapper(double *f, const double t, const double *x, const double *u, const double **p, void *data) {
euler_passtrough *_data = ((euler_passtrough *)data);
/* Evaluating f(x(k), u(k)) and f(x(k+1), u(k+1)), storing result in work_f */
_data->f(_data->work_f, t, _data->xk, u, p, _data->data);
_data->f(_data->work_f + _data->x_size, t, x, u + _data->u_offset, p, _data->data);
/* Computing: x(k) - x(k+1) + (1-alpha) ts f(x(k), u(k)) + alpha ts f(x(k+1), u(k+1)) */
cblas_dscal(_data->x_size, (1 - _data->alpha) * _data->ts, _data->work_f, 1);
cblas_dscal(_data->x_size, _data->alpha * _data->ts, _data->work_f + _data->x_size, 1);
cblas_daxpy(_data->x_size, 1, _data->work_f + _data->x_size, 1, _data->work_f, 1);
cblas_daxpy(_data->x_size, -1, x, 1, _data->work_f, 1);
cblas_daxpy(_data->x_size, 1, _data->xk, 1, _data->work_f, 1);
/* Copying result in output */
cblas_dcopy(_data->x_size, _data->work_f, 1, f, 1);
}
void euler_jacobian_wrapper(double *df, const double t, const double *x, const double *u, const double **p, void *data) {
euler_passtrough *_data = ((euler_passtrough *)data);
/* Evaluating JAC(f)(x(k+1), u(k+1)) */
_data->df(_data->work_df, t, x, u + _data->u_offset, p, _data->data);
/* Computing: -I + alpha ts JAC(f)(x(k+1), u(k+1)) (still using level 1 Blas) */
cblas_dscal(_data->x_size * _data->x_size, _data->alpha * _data->ts, _data->work_df, 1);
cblas_daxpy(_data->x_size * _data->x_size, 1, _data->work_df + _data->x_size * _data->x_size, 1, _data->work_df, 1);
/* Copying result in output */
cblas_dcopy(_data->x_size * _data->x_size, _data->work_df, 1, df, 1);
} | {
"alphanum_fraction": 0.6358354992,
"avg_line_length": 43.6066666667,
"ext": "c",
"hexsha": "1ac2368a21a4359a65a52cb272a36338cafa33fe",
"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": "7dd73c1b383b6c32086da4880a82326ebf47b71b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MatteoRagni/libeuler",
"max_forks_repo_path": "libeuler.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7dd73c1b383b6c32086da4880a82326ebf47b71b",
"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": "MatteoRagni/libeuler",
"max_issues_repo_path": "libeuler.c",
"max_line_length": 138,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "7dd73c1b383b6c32086da4880a82326ebf47b71b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MatteoRagni/libeuler",
"max_stars_repo_path": "libeuler.c",
"max_stars_repo_stars_event_max_datetime": "2020-01-22T02:16:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-05T07:42:42.000Z",
"num_tokens": 1966,
"size": 6541
} |
#include <stdio.h>
#include <gsl/gsl_sf_bessel.h>
int main (void)
{
double x, y;
x = 5.0;
y = gsl_sf_bessel_J0 (x);
printf ("J0(%g) = %.18e\n", x, y);
return 0;
} | {
"alphanum_fraction": 0.5561797753,
"avg_line_length": 16.1818181818,
"ext": "c",
"hexsha": "6d5bcfc2ce756db844005e1c700415aa3396ae4c",
"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": "bf415f2b11cd7289b13ab900752cf1f856ce4b47",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kevintee/Predicting-Gene-Networks",
"max_forks_repo_path": "src/gpdream/modules/Merlin/src/test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bf415f2b11cd7289b13ab900752cf1f856ce4b47",
"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": "kevintee/Predicting-Gene-Networks",
"max_issues_repo_path": "src/gpdream/modules/Merlin/src/test.c",
"max_line_length": 36,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bf415f2b11cd7289b13ab900752cf1f856ce4b47",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kevintee/Predicting-Gene-Networks",
"max_stars_repo_path": "src/gpdream/modules/Merlin/src/test.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 73,
"size": 178
} |
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
*/
/*
*
*
* Filename: polar.c
*
* Description: Cartesian <-> Polar coordinates transformation
*
* Version: 1.0
* Created: 06/05/2014 14:21:40
* Revision: none
* License: BSD
*
* Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it
* Organization: Università degli Studi di Trieste
*
*
*/
#include <math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_math.h>
#include "funcs.h"
/*
* FUNCTION
* Name: bloch_vector
* Description: Return the Bloch vector corresponding to (r,theta,phi) polar coords
*
*/
int bloch_vector ( gsl_vector* v, double r, double theta, double phi )
{
/* Check the validity of coordinates */
if ( r > 1 ) /* Non physical state */
{
v = NULL ;
return -1;
}
theta = fmod (theta, M_PI ) ; /* Taking the modulo */
phi = fmod ( phi, 2*M_PI ) ;
gsl_vector_set ( v, 1, r*sin(theta)*cos(phi) ) ;
gsl_vector_set ( v, 2, r*sin(theta)*sin(phi) ) ;
gsl_vector_set ( v, 3, r*cos(theta) ) ;
return 0;
} /* ----- end of function bloch_vector ----- */
/*
* FUNCTION
* Name: polars
* Description: From the Bloch vector representation to the polar coordinates
*
*/
int polars ( double* r, double* theta, double* phi, const gsl_vector* v )
{
*r = gsl_hypot3( VECTOR(v,1), VECTOR(v,2), VECTOR(v,3) ) ;
if ( *r > 1 )
return -1 ;
*theta = acos(VECTOR(v,3)) ;
if ( gsl_fcmp(fabs(*theta),1,1e-9) )
*phi = 0 ;
else
*phi = atan2(VECTOR(v,2),VECTOR(v,1)) ;
return 0;
} /* ----- end of function polars ----- */
| {
"alphanum_fraction": 0.665783372,
"avg_line_length": 31.1237113402,
"ext": "c",
"hexsha": "f5ed9c3ffa1b1e4e08c48f1311c12046d659c645",
"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": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "j-silver/quantum_dots",
"max_forks_repo_path": "polar.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"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": "j-silver/quantum_dots",
"max_issues_repo_path": "polar.c",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "j-silver/quantum_dots",
"max_stars_repo_path": "polar.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 804,
"size": 3019
} |
//
// cngsl.h
//
// Copy Number Utilities that use gsl
//
// copyright 2017 Peter Andrews
//
#ifndef PAA_CNGSL_H_
#define PAA_CNGSL_H_
#include <gsl/gsl_cdf.h>
#include <algorithm>
#include <limits>
#include <string>
#include <vector>
#include "cn.h"
namespace paa {
class CNStateCall {
public:
CNStateCall(const std::vector<double> & state_probs_,
const unsigned int expected_state_,
const double segment_count_) :
state_probs{state_probs_},
not_state_probs(state_probs.size()),
expected_state{expected_state_},
segment_count{segment_count_} {
double loss_prob{0.0};
double not_loss_prob{0.0};
double expected_prob{0.0};
double not_expected_prob{0.0};
double gain_prob{0.0};
double not_gain_prob{0.0};
for (unsigned int s{0}; s != state_probs.size(); ++s) {
if (state_probs[s] > state_probs[best_call]) {
best_call = s;
}
if (s < expected_state) {
loss_prob += state_probs[s];
not_gain_prob += state_probs[s];
not_expected_prob += state_probs[s];
} else if (s > expected_state) {
gain_prob += state_probs[s];
not_loss_prob += state_probs[s];
not_expected_prob += state_probs[s];
} else {
expected_prob += state_probs[s];
not_loss_prob += state_probs[s];
not_gain_prob += state_probs[s];
}
}
for (unsigned int n{0}; n != state_probs.size(); ++n) {
for (unsigned int s{0}; s != state_probs.size(); ++s) {
if (n == s) continue;
not_state_probs[n] += state_probs[s];
}
}
type = best_call < expected_state ? "loss" :
(best_call > expected_state ? "gain" : "norm");
const double min_prob{std::numeric_limits<double>::min()};
score = -log10(max(best_call < expected_state ? not_loss_prob :
(best_call > expected_state ? not_gain_prob :
not_expected_prob),
min_prob));
prob_not_expected = max(not_expected_prob, min_prob);
prob_not_loss = max(not_loss_prob, min_prob);
prob_not_gain = max(not_gain_prob, min_prob);
}
std::vector<double> state_probs;
std::vector<double> not_state_probs;
unsigned int expected_state;
unsigned int best_call{0};
double segment_count{0.0};
std::string type{""};
double score{0.0};
double prob_not_expected{0.0};
double prob_not_loss{0.0};
double prob_not_gain{0.0};
};
class CNStateCaller {
public:
CNStateCaller(const Reference & ref_,
const std::vector<Bin> & bins_,
const CN_Bins & profile_) :
ref{ref_}, bins{bins_}, profile{profile_},
x_chr{ref.find_x_chromosome()},
y_chr{ref.find_y_chromosome()},
is_male{is_profile_male()},
expected_states{get_expected_states()},
average_autosome_count{get_average_autosome_count()},
zero_state_count{average_autosome_count / 10} { }
double get_average_autosome_count() const {
double count{0};
unsigned int n_count{0};
for (unsigned int b{0}; b != bins.size(); ++b) {
const unsigned int chr{bins[b].chromosome()};
if (chr == x_chr || chr == y_chr) continue;
count += profile[b].norm_count();
++n_count;
}
return count / n_count;
}
std::vector<unsigned char> get_expected_states() const {
std::vector<unsigned char> result;
for (unsigned int c{0}; c != ref.n_chromosomes(); ++c) {
const bool is_x{c == x_chr};
const bool is_y{c == y_chr};
if (is_male && (is_x || is_y)) {
result.push_back(1);
} else if (!is_male && is_y) {
result.push_back(0);
} else {
result.push_back(2);
}
}
return result;
}
bool is_profile_male() const {
double ratio{0};
unsigned int n_ratio{0};
for (unsigned int b{0}; b != bins.size(); ++b) {
const unsigned int chr{bins[b].chromosome()};
if (chr == y_chr) {
ratio += profile[b].ratio();
++n_ratio;
}
}
return ratio / n_ratio > 0.3333;
}
CNStateCall call(const unsigned int start,
const unsigned int stop) const {
const double par_fraction{fraction_par(start, stop)};
const unsigned int expected_par_copy{2};
const unsigned int expected_state{static_cast<unsigned int>(
0.5 + par_fraction * expected_par_copy +
(1 - par_fraction) * expected_states[bins[start].chromosome()])};
const double segment_count{[start, stop, this]() {
double result{0};
for (unsigned int b{start}; b != stop; ++b) {
result += profile[b].norm_count();
}
return result;
}()};
std::vector<double> state_chi_squareds(n_states);
std::vector<double> state_probs(n_states);
double total_prob{0.0};
double diff_power{2.0};
while (total_prob <= 0) {
for (unsigned int s{0}; s != n_states; ++s) {
const double expected_count{(stop - start) *
(s ? s * average_autosome_count / 2 : zero_state_count)};
const double diff{expected_count > segment_count ?
expected_count - segment_count : segment_count - expected_count};
const double chi_squared{pow(diff, diff_power) / expected_count};
state_chi_squareds[s] = chi_squared;
const double prob{gsl_cdf_chisq_Q(chi_squared, 1)};
total_prob += state_probs[s] = prob;
}
diff_power -= 0.1;
}
diff_power += 0.1;
for (unsigned int s{0}; s != n_states; ++s) {
state_probs[s] /= total_prob;
}
return CNStateCall{move(state_probs), expected_state, segment_count};
}
double fraction_par(const unsigned int start,
const unsigned int stop) const {
if (bins[start].chromosome() != x_chr) {
return 0.0;
}
const unsigned int par_coords[2][2]{{60000, 2699520},
{154931043, 155260560}};
if (bins[stop - 1].stop_position() <= par_coords[0][0] ||
bins[start].start_position() >= par_coords[1][1] ||
(bins[start].start_position() >= par_coords[0][1] &&
bins[stop - 1].stop_position() <= par_coords[1][0])) {
return 0.0;
}
double result{0.0};
for (unsigned int b{start}; b != stop; ++b) {
double frac_pos{0.0};
for (const unsigned int p : {0, 1}) {
const unsigned int par_len{par_coords[p][1] - par_coords[p][0]};
if (bins[b].start_position() <= par_coords[p][0]) {
if (bins[b].stop_position() >= par_coords[p][1]) {
frac_pos += 1.0 * par_len / bins[b].length();
} else if (bins[b].stop_position() >= par_coords[p][0]) {
frac_pos += 1.0 * (bins[b].stop_position() - par_coords[p][0]) /
bins[b].length();
}
} else if (bins[b].start_position() <= par_coords[p][1]) {
if (bins[b].stop_position() <= par_coords[p][1]) {
frac_pos += 1.0;
} else {
frac_pos += 1.0 * (par_coords[p][1] - bins[b].start_position()) /
bins[b].length();
}
}
}
result += frac_pos;
}
return result / (stop - start);
}
const Reference & ref;
const std::vector<Bin> & bins;
const CN_Bins & profile;
const unsigned int x_chr;
const unsigned int y_chr;
const bool is_male;
const std::vector<unsigned char> expected_states;
const double average_autosome_count;
const double zero_state_count;
const unsigned int n_states{20};
};
} // namespace paa
#endif // PAA_CNGSL_H_
| {
"alphanum_fraction": 0.6019171881,
"avg_line_length": 31.6919831224,
"ext": "h",
"hexsha": "28a4c30d095bc85b556bede821b329392365e815",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-11-20T15:47:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-11-20T15:47:54.000Z",
"max_forks_repo_head_hexsha": "571f2d03a457da2f51d525ac038aef455e3467c1",
"max_forks_repo_licenses": [
"Zlib",
"MIT"
],
"max_forks_repo_name": "docpaa/mumdex",
"max_forks_repo_path": "cn/cngsl.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "571f2d03a457da2f51d525ac038aef455e3467c1",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Zlib",
"MIT"
],
"max_issues_repo_name": "docpaa/mumdex",
"max_issues_repo_path": "cn/cngsl.h",
"max_line_length": 79,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "571f2d03a457da2f51d525ac038aef455e3467c1",
"max_stars_repo_licenses": [
"Zlib",
"MIT"
],
"max_stars_repo_name": "docpaa/mumdex",
"max_stars_repo_path": "cn/cngsl.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-23T00:58:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-02-07T15:58:30.000Z",
"num_tokens": 1968,
"size": 7511
} |
/**
* @file stream.h
* @brief Representation of feature streams.
* @author John McDonough.
*/
#ifndef STREAM_H
#define STREAM_H
#include <gsl/gsl_vector.h>
#include <gsl/gsl_complex.h>
#include "common/refcount.h"
// ----- interface class for 'FeatureStream' -----
//
template <typename Type, typename item_type>
class FeatureStream : public Countable {
public:
virtual ~FeatureStream();
const String& name() const { return name_; }
unsigned size() const { return size_; }
virtual const Type* next(int frame_no = -5) = 0;
const Type* current() {
if (frame_no_ < 0)
throw jconsistency_error("Frame index (%d) < 0.", frame_no_);
return next(frame_no_);
}
bool is_end(){ return is_end_; };
virtual void reset() {
frame_no_ = frame_reset_no_;
is_end_ = false;
}
virtual int frame_no() const { return frame_no_; }
size_t itemsize() { return sizeof(item_type); };
protected:
FeatureStream(unsigned sz, const String& nm);
void gsl_vector_set_(Type *vector, int index, item_type value);
void increment_() { frame_no_++; }
const int frame_reset_no_;
const unsigned size_;
int frame_no_; /*!< lapse time after reset() */
Type* vector_;
bool is_end_;
private:
const String name_;
};
// ----- declare partial specializations of 'FeatureStream' -----
//
template<> FeatureStream<gsl_vector_char, char>::FeatureStream(unsigned sz, const String& nm);
template<> FeatureStream<gsl_vector_short, short>::FeatureStream(unsigned sz, const String& nm);
template<> FeatureStream<gsl_vector_float, float>::FeatureStream(unsigned sz, const String& nm);
template<> FeatureStream<gsl_vector, double>::FeatureStream(unsigned sz, const String& nm);
template<> FeatureStream<gsl_vector_complex, gsl_complex>::FeatureStream(unsigned sz, const String& nm);
template<> FeatureStream<gsl_vector_char, char>::~FeatureStream();
template<> FeatureStream<gsl_vector_short, short>::~FeatureStream();
template<> FeatureStream<gsl_vector_float, float>::~FeatureStream();
template<> FeatureStream<gsl_vector, double>::~FeatureStream();
template<> FeatureStream<gsl_vector_complex, gsl_complex>::~FeatureStream();
template<> void FeatureStream<gsl_vector_char, char>::gsl_vector_set_(gsl_vector_char *vector, int index, char value);
template<> void FeatureStream<gsl_vector_short, short>::gsl_vector_set_(gsl_vector_short *vector, int index, short value);
template<> void FeatureStream<gsl_vector_float, float>::gsl_vector_set_(gsl_vector_float *vector, int index, float value);
template<> void FeatureStream<gsl_vector, double>::gsl_vector_set_(gsl_vector *vector, int index, double value);
template<> void FeatureStream<gsl_vector_complex, gsl_complex>::gsl_vector_set_(gsl_vector_complex *vector, int index, gsl_complex value);
typedef FeatureStream<gsl_vector_char, char> VectorCharFeatureStream;
typedef FeatureStream<gsl_vector_short, short> VectorShortFeatureStream;
typedef FeatureStream<gsl_vector_float, float> VectorFloatFeatureStream;
typedef FeatureStream<gsl_vector, double> VectorFeatureStream;
typedef FeatureStream<gsl_vector_complex, gsl_complex> VectorComplexFeatureStream;
typedef refcountable_ptr<VectorCharFeatureStream> VectorCharFeatureStreamPtr;
typedef refcountable_ptr<VectorShortFeatureStream> VectorShortFeatureStreamPtr;
typedef refcountable_ptr<VectorFloatFeatureStream> VectorFloatFeatureStreamPtr;
typedef refcountable_ptr<VectorFeatureStream> VectorFeatureStreamPtr;
typedef refcountable_ptr<VectorComplexFeatureStream> VectorComplexFeatureStreamPtr;
#endif
| {
"alphanum_fraction": 0.7642006096,
"avg_line_length": 40.5505617978,
"ext": "h",
"hexsha": "8c4dbc17479d4a2e687d057853435a9f1e817b88",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z",
"max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "musiclvme/distant_speech_recognition",
"max_forks_repo_path": "btk20_src/stream/stream.h",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "musiclvme/distant_speech_recognition",
"max_issues_repo_path": "btk20_src/stream/stream.h",
"max_line_length": 138,
"max_stars_count": 136,
"max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "musiclvme/distant_speech_recognition",
"max_stars_repo_path": "btk20_src/stream/stream.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z",
"num_tokens": 827,
"size": 3609
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include <gsl\gsl>
#include "Data\Data.h"
#include "Data\Pose.h"
#include "opencv\cv.h"
#include "MageSettings.h"
namespace mage
{
struct VOIKeyframe
{
const VolumeOfInterestSettings& VoiSettings;
cv::Vec3f WorldPosition;
cv::Vec3f Forward;
cv::Vec3f Right;
cv::Vec3f Up;
float NearDepth;
float FarDepth;
// Cached values for performance.
cv::Vec3f Centroid;
float DistanceAlphaToXi;
float ModifiedDistanceAlphaToOmega;
VOIKeyframe(const Pose& pose, const Depth& depth, const VolumeOfInterestSettings& voiSettings);
float TeardropScore(const cv::Vec3f&) const;
};
bool CalculateVolumeOfInterest(gsl::span<const VOIKeyframe> keyframes, const VolumeOfInterestSettings& voiSettings, AxisAlignedVolume& voi);
} | {
"alphanum_fraction": 0.6840390879,
"avg_line_length": 26.3142857143,
"ext": "h",
"hexsha": "0849d897434fa618f6c30f6f516d392c8deb395a",
"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": "Core/MAGESLAM/Source/VolumeOfInterest/VolumeOfInterest.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": "Core/MAGESLAM/Source/VolumeOfInterest/VolumeOfInterest.h",
"max_line_length": 144,
"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": "Core/MAGESLAM/Source/VolumeOfInterest/VolumeOfInterest.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": 226,
"size": 921
} |
#ifndef Single_Pin_Conduction_h
#define Single_Pin_Conduction_h
#include <vector>
// Trilinos includes
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_RCP.hpp"
#include "Teuchos_SerialDenseMatrix.hpp"
#include "Teuchos_SerialDenseSolver.hpp"
#include "Teuchos_SerialDenseVector.hpp"
// vendored includes
#include <gsl/gsl>
namespace enrico {
//===========================================================================//
/*!
* \class Single_Pin_Conduction
* \brief Solve thermal conduction in single fuel pin.
*
* This class implements a simple 1-D radial thermal conduction equation
* for each axial level of a fuel pin. Axial conduction is ignored and there
* is currently no gap conductance model. This model should only be used for
* very approximate qualitative behavior.
*/
//===========================================================================//
class Single_Pin_Conduction {
public:
//@{
//! Typedefs
using RCP_PL = Teuchos::RCP<Teuchos::ParameterList>;
using Matrix = Teuchos::SerialDenseMatrix<int, double>;
using Vector = Teuchos::SerialDenseVector<int, double>;
using Solver = Teuchos::SerialDenseSolver<int, double>;
//@}
private:
// >>> DATA
// Geometry
double d_fuel_radius;
double d_clad_radius;
double d_delta_r_fuel;
double d_delta_r_clad;
std::vector<double> d_delta_z;
// Thermal conductivities
double d_k_fuel;
double d_k_clad;
public:
// Constructor
Single_Pin_Conduction(RCP_PL& parameters, const std::vector<double>& delta_z);
// Set fuel radius (cm)
void set_fuel_radius(double r)
{
Expects(r > 0.0);
Expects(r < 2.0);
d_fuel_radius = r;
}
// Set clad radius (cm)
void set_clad_radius(double r)
{
Expects(r > 0.0);
Expects(r < 2.0);
d_clad_radius = r;
}
// Solve conduction equation at each axial level
void solve(const std::vector<double>& power,
const std::vector<double>& channel_temperature,
std::vector<double>& fuel_temperature);
};
//---------------------------------------------------------------------------//
} // end namespace enrico
//---------------------------------------------------------------------------//
#endif // Single_Pin_Conduction_h
//---------------------------------------------------------------------------//
// end of Single_Pin_Conduction.h
//---------------------------------------------------------------------------//
| {
"alphanum_fraction": 0.5760197775,
"avg_line_length": 27.2696629213,
"ext": "h",
"hexsha": "542c4c6c99c4b4d5beb26f0b9d4eb1f18dc7f8dc",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pshriwise/enrico",
"max_forks_repo_path": "include/smrt/Single_Pin_Conduction.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pshriwise/enrico",
"max_issues_repo_path": "include/smrt/Single_Pin_Conduction.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "72b95ca947804f672e5f1726e169ef6f4889e78e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pshriwise/enrico",
"max_stars_repo_path": "include/smrt/Single_Pin_Conduction.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 529,
"size": 2427
} |
#ifndef XYCO_RUNTIME_UTILS_SELECT_H
#define XYCO_RUNTIME_UTILS_SELECT_H
#include <gsl/pointers>
#include <utility>
#include "runtime/runtime.h"
#include "type_wrapper.h"
namespace xyco::runtime {
template <typename T1, typename T2>
class SelectFuture
: public Future<std::variant<TypeWrapper<T1>, TypeWrapper<T2>>> {
using CoOutput = std::variant<TypeWrapper<T1>, TypeWrapper<T2>>;
public:
auto poll(Handle<void> self) -> Poll<CoOutput> override {
if (!ready_) {
ready_ = true;
auto [wrapper1, wrapper2] = std::pair<Future<void>, Future<void>>(
future_wrapper<T1, 0>(std::move(futures_.first)),
future_wrapper<T2, 1>(std::move(futures_.second)));
wrappers_ = {wrapper1.get_handle(), wrapper2.get_handle()};
RuntimeCtx::get_ctx()->spawn(std::move(wrapper1));
RuntimeCtx::get_ctx()->spawn(std::move(wrapper2));
return Pending();
}
if (result_.index() == 0) {
RuntimeCtx::get_ctx()->cancel_future(wrappers_.second);
return Ready<CoOutput>{
CoOutput(std::in_place_index<0>, std::get<0>(result_))};
}
RuntimeCtx::get_ctx()->cancel_future(wrappers_.first);
return Ready<CoOutput>{
CoOutput(std::in_place_index<1>, std::get<1>(result_))};
}
SelectFuture(Future<T1> &&future1, Future<T2> &&future2)
: Future<CoOutput>(nullptr),
ready_(false),
result_(std::in_place_index<2>, true),
futures_(std::move(future1), std::move(future2)) {}
private:
template <typename T, int Index>
auto future_wrapper(Future<T> future) -> Future<void>
requires(!std::is_same_v<T, void>) {
auto result = co_await future;
if (result_.index() == 2) {
result_ = std::variant<TypeWrapper<T1>, TypeWrapper<T2>, bool>(
std::in_place_index<Index>, TypeWrapper<T>{result});
RuntimeCtx::get_ctx()->register_future(this);
}
}
template <typename T, int Index>
auto future_wrapper(Future<T> future) -> Future<void>
requires(std::is_same_v<T, void>) {
co_await future;
if (result_.index() == 2) {
result_ = std::variant<TypeWrapper<T1>, TypeWrapper<T2>, bool>(
std::in_place_index<Index>, TypeWrapper<T>());
RuntimeCtx::get_ctx()->register_future(this);
}
}
bool ready_;
std::variant<TypeWrapper<T1>, TypeWrapper<T2>, bool> result_;
std::pair<Future<T1>, Future<T2>> futures_;
std::pair<Handle<PromiseBase>, Handle<PromiseBase>> wrappers_;
};
template <typename T1, typename T2>
auto select(Future<T1> future1, Future<T2> future2)
-> Future<std::variant<TypeWrapper<T1>, TypeWrapper<T2>>> {
co_return co_await SelectFuture<T1, T2>(std::move(future1),
std::move(future2));
}
} // namespace xyco::runtime
#endif // XYCO_RUNTIME_UTILS_SELECT_H | {
"alphanum_fraction": 0.6565620542,
"avg_line_length": 33.7831325301,
"ext": "h",
"hexsha": "58f58f3afd3413e4f5ad8fbb0ad92425619eeaab",
"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": "7682652f17b82e2370fa7af17635c5d0c470efe0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ddxy18/xyco",
"max_forks_repo_path": "src/runtime/utils/select.h",
"max_issues_count": 17,
"max_issues_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0",
"max_issues_repo_issues_event_max_datetime": "2022-03-18T06:16:15.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-10-30T06:10:46.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ddxy18/xyco",
"max_issues_repo_path": "src/runtime/utils/select.h",
"max_line_length": 72,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7682652f17b82e2370fa7af17635c5d0c470efe0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ddxy18/xyco",
"max_stars_repo_path": "src/runtime/utils/select.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 752,
"size": 2804
} |
/* randist/dirichlet.c
*
* 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 <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_gamma.h>
/* The Dirichlet probability distribution of order K-1 is
p(\theta_1,...,\theta_K) d\theta_1 ... d\theta_K =
(1/Z) \prod_i=1,K \theta_i^{alpha_i - 1} \delta(1 -\sum_i=1,K \theta_i)
The normalization factor Z can be expressed in terms of gamma functions:
Z = {\prod_i=1,K \Gamma(\alpha_i)} / {\Gamma( \sum_i=1,K \alpha_i)}
The K constants, \alpha_1,...,\alpha_K, must be positive. The K parameters,
\theta_1,...,\theta_K are nonnegative and sum to 1.
The random variates are generated by sampling K values from gamma
distributions with parameters a=\alpha_i, b=1, and renormalizing.
See A.M. Law, W.D. Kelton, Simulation Modeling and Analysis (1991).
Gavin E. Crooks <gec@compbio.berkeley.edu> (2002)
*/
void
gsl_ran_dirichlet (const gsl_rng * r, const size_t K,
const double alpha[], double theta[])
{
size_t i;
double norm = 0.0;
for (i = 0; i < K; i++)
{
theta[i] = gsl_ran_gamma (r, alpha[i], 1.0);
}
for (i = 0; i < K; i++)
{
norm += theta[i];
}
for (i = 0; i < K; i++)
{
theta[i] /= norm;
}
}
double
gsl_ran_dirichlet_pdf (const size_t K,
const double alpha[], const double theta[])
{
return exp (gsl_ran_dirichlet_lnpdf (K, alpha, theta));
}
double
gsl_ran_dirichlet_lnpdf (const size_t K,
const double alpha[], const double theta[])
{
/*We calculate the log of the pdf to minimize the possibility of overflow */
size_t i;
double log_p = 0.0;
double sum_alpha = 0.0;
for (i = 0; i < K; i++)
{
log_p += (alpha[i] - 1.0) * log (theta[i]);
}
for (i = 0; i < K; i++)
{
sum_alpha += alpha[i];
}
log_p += gsl_sf_lngamma (sum_alpha);
for (i = 0; i < K; i++)
{
log_p -= gsl_sf_lngamma (alpha[i]);
}
return log_p;
}
| {
"alphanum_fraction": 0.6333333333,
"avg_line_length": 26.5384615385,
"ext": "c",
"hexsha": "ad136e1821815d89f51a883c883495465d94293c",
"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/randist/dirichlet.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/randist/dirichlet.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/randist/dirichlet.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": 817,
"size": 2760
} |
#ifndef _UI_HELPERS_H_
#define _UI_HELPERS_H_
#define OEMRESOURCE
#include <algorithm>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <vector>
#include <ppl.h>
#include <gsl/gsl>
// Included before windows.h, because pfc.h includes winsock2.h
#include "../pfc/pfc.h"
#include <windows.h>
#include <WindowsX.h>
#include <SHLWAPI.H>
#include <vssym32.h>
#include <uxtheme.h>
#include <shldisp.h>
#include <ShlObj.h>
#include <gdiplus.h>
#include <Usp10.h>
#include <CommonControls.h>
#include <wil/resource.h>
// Windows SDK headers define min and max macros, which are used by gdiplus.h.
//
// This undefines them temporarily to avoid conflicts with the C++ standard
// library. They are redefined at the end of this header.
#ifdef max
#define _UI_HELPERS_OLD_MAX_
#undef max
#endif
#ifdef min
#define _UI_HELPERS_OLD_MIN_
#undef min
#endif
#include "../mmh/stdafx.h"
#ifndef RECT_CX
#define RECT_CX(rc) (rc.right - rc.left)
#endif
#ifndef RECT_CY
#define RECT_CY(rc) (rc.bottom - rc.top)
#endif
#include "literals.h"
#include "handle.h"
#include "win32_helpers.h"
#include "ole.h"
#include "dialog.h"
#include "dpi.h"
#include "container_window.h"
#include "message_hook.h"
#include "trackbar.h"
#include "solid_fill.h"
#include "theming.h"
#include "gdi.h"
#include "text_drawing.h"
#include "list_view/list_view.h"
#include "drag_image.h"
#include "info_box.h"
#include "menu.h"
#include "ole/data_object.h"
#include "ole/enum_format_etc.h"
#ifdef _UI_HELPERS_OLD_MAX_
#define max(a, b) (((a) > (b)) ? (a) : (b))
#undef _UI_HELPERS_OLD_MAX_
#endif
#ifdef _UI_HELPERS_OLD_MIN_
#define min(a, b) (((a) < (b)) ? (a) : (b))
#undef _UI_HELPERS_OLD_MIN_
#endif
#endif
| {
"alphanum_fraction": 0.7253914989,
"avg_line_length": 18.8210526316,
"ext": "h",
"hexsha": "3f838c0d89d00df7b8962c05caaef8b68793297d",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2019-07-12T23:37:01.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-04-12T13:45:38.000Z",
"max_forks_repo_head_hexsha": "7db30d91f58116ece51e2cdaf83c4e2be819609e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "reupen/ui_helpers",
"max_forks_repo_path": "stdafx.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "7db30d91f58116ece51e2cdaf83c4e2be819609e",
"max_issues_repo_issues_event_max_datetime": "2019-07-13T08:56:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-07-12T23:39:30.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "reupen/ui_helpers",
"max_issues_repo_path": "stdafx.h",
"max_line_length": 78,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "7db30d91f58116ece51e2cdaf83c4e2be819609e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "reupen/ui_helpers",
"max_stars_repo_path": "stdafx.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-30T17:17:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-12T13:45:36.000Z",
"num_tokens": 491,
"size": 1788
} |
#ifndef __UTILS_H_INCLUDED__
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <set>
#include <tuple>
#include <math.h>
#include <Eigen/Dense>
#include <gsl/gsl>
#define __UTILS_H_INCLUDED__
#include <cosan/base/CosanBO.h>
namespace Cosan{
/**
* @brief General string to number conversion function
* @details As we allow for user-determined numeric type `NumericType`, the detailed implementation or functions needed maybe slightly
* different among each other. For instance, when we are trying to read data from `csv` file. Different data type requires different
* string-to-numeric function. For `double`, one is required `std::stod` while 'std::stof' is the candidate function if
* `float` is chosen. To take care of this variant before running time, we conside the static-i. The feature
* allows us to discard branches of an if statement at compile-time based on a constant expression condition. In the following
* code as an example, we define a template function with input requiring `NumericType` as numeric and then the implementation
* is decided via `if constexpr` statement.
**/
template<Numeric NumericType>
NumericType StringToNum(const std::string& arg, std::size_t* pos = 0) {
static_assert(std::is_arithmetic<NumericType>::value, "NumericType must be numeric");
if constexpr (std::is_same_v<NumericType, unsigned long>) {
return std::stoul(arg,pos);
}
else if constexpr (std::is_same_v<NumericType, unsigned long long>){
return std::stoull(arg,pos);
}
else if constexpr (std::is_same_v<NumericType, int>){
return std::stoi(arg,pos);
}
else if constexpr (std::is_same_v<NumericType, long>){
return std::stol(arg,pos);
}
else if constexpr (std::is_same_v<NumericType, long long>){
return std::stoll(arg,pos);
}
else if constexpr (std::is_same_v<NumericType, float>){
return std::stof(arg,pos);
}
else if constexpr (std::is_same_v<NumericType, double>){
return std::stod(arg,pos);
}
else{
return std::stold(arg,pos);
}
}
}
template<typename Matrix>
Matrix load_csv1 (const std::string & path) {
std::ifstream indata;
indata.open(path);
std::string line;
std::vector<double> values;
gsl::index rows = 0;
while (std::getline(indata, line)) {
std::stringstream lineStream(line);
std::string cell;
while (getline(lineStream, cell, ',')) {
values.push_back(stod(cell));
}
++rows;
}
return Eigen::Map<const Eigen::Matrix<typename Matrix::Scalar, Matrix::RowsAtCompileTime, Matrix::ColsAtCompileTime, Eigen::RowMajor> >(values.data(), rows, values.size()/rows);
}
template<typename Matrix>
void save_csv(const std::string & path, const Matrix & matrix){
// if (path.substr(path.size()-4)!=".csv"){
// path.append(".csv");
// }
std::ofstream file(path,std::ios::out);
if (file.is_open()){
Eigen::IOFormat csvFmt(Eigen::FullPrecision,0,",");
file<<matrix.format(csvFmt);
file.close();
}
}
#endif
| {
"alphanum_fraction": 0.6454378445,
"avg_line_length": 36.6966292135,
"ext": "h",
"hexsha": "9132621c9022adf2a3c6ffe1b7ae57e1968d5f63",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-04-13T05:56:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-13T05:56:38.000Z",
"max_forks_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zhxinyu/cosan",
"max_forks_repo_path": "cosan/io/utils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074",
"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": "zhxinyu/cosan",
"max_issues_repo_path": "cosan/io/utils.h",
"max_line_length": 181,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ea93704782e6c66f6bcf65362c957d719e25b074",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zhxinyu/cosan",
"max_stars_repo_path": "cosan/io/utils.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 781,
"size": 3266
} |
#include <complex.h>
#include <math.h>
#include <petsc.h>
#include <stdint.h>
#define LOOPY_CALL_WITH_INTEGER_TYPES(MACRO_NAME) \
MACRO_NAME(int8, char) \
MACRO_NAME(int16, short) \
MACRO_NAME(int32, int) \
MACRO_NAME(int64, long)
#define LOOPY_DEFINE_FLOOR_DIV_POS_B(SUFFIX, TYPE) \
static inline TYPE loopy_floor_div_pos_b_##SUFFIX(TYPE a, TYPE b) \
{ \
if (a<0) \
a = a - (b-1); \
return a/b; \
}
LOOPY_CALL_WITH_INTEGER_TYPES(LOOPY_DEFINE_FLOOR_DIV_POS_B)
#undef LOOPY_DEFINE_FLOOR_DIV_POS_B
#undef LOOPY_CALL_WITH_INTEGER_TYPES
#define BYTES8 (8*8)
typedef double double8 __attribute__ ((vector_size (BYTES8)));
#define BYTES4 (8*4)
typedef int int8 __attribute__ ((vector_size (BYTES4)));
void wrap_form0_cell_integral_otherwise(int const start, int const end, double *__restrict__ dat2, double const *__restrict__ dat1, double const *__restrict__ glob0, double const *__restrict__ dat0, int const *__restrict__ map0, int const *__restrict__ map1)
{
double8 form_form0_cell_integral_otherwise __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_0 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_1 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_10 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_11 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_12 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_13 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_14 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_15 __attribute__ ((aligned (64)));
double const form_form0_cell_integral_otherwise_16[4] __attribute__ ((aligned (64))) = { 0.041666666666666664, 0.041666666666666664, 0.041666666666666664, 0.041666666666666664 };
double const form_form0_cell_integral_otherwise_17[4 * 4] __attribute__ ((aligned (64))) = { 0.13819660112500914, 0.585410196624969, 0.138196601125011, 0.13819660112501098, 0.13819660112500912, 0.13819660112501092, 0.585410196624969, 0.13819660112501098, 0.13819660112500914, 0.13819660112501095, 0.138196601125011, 0.585410196624969, 0.5854101966249672, 0.13819660112501092, 0.138196601125011, 0.13819660112501098 };
double8 form_form0_cell_integral_otherwise_18 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_19 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_2 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_20 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_21 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_22[4] __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_23 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_24 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_25 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_26 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_27 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_28 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_29 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_3 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_30 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_31 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_32 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_33 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_34 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_35 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_36 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_37 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_38 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_39 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_4 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_40 __attribute__ ((aligned (64)));
double const form_form0_cell_integral_otherwise_41[4] __attribute__ ((aligned (64))) = { -1.0, 0.0, 0.0, 1.0 };
double8 form_form0_cell_integral_otherwise_42 __attribute__ ((aligned (64)));
double const form_form0_cell_integral_otherwise_43[4] __attribute__ ((aligned (64))) = { -1.0, 0.0, 1.0, 0.0 };
double8 form_form0_cell_integral_otherwise_44 __attribute__ ((aligned (64)));
double const form_form0_cell_integral_otherwise_45[4] __attribute__ ((aligned (64))) = { -1.0, 1.0, 0.0, 0.0 };
double8 form_form0_cell_integral_otherwise_5 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_6 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_7 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_8 __attribute__ ((aligned (64)));
double8 form_form0_cell_integral_otherwise_9 __attribute__ ((aligned (64)));
double8 t0[4] __attribute__ ((aligned (64)));
double8 t1[4 * 3] __attribute__ ((aligned (64)));
double8 t2[4] __attribute__ ((aligned (64)));
double8 const zero_vec_float64 = { 0.0 };
{
/* initial slab for 'n_outer' */
/* */
}
{
int const n_outer = start + -1 * ((7 + 7 * start) / 8);
if (-1 + end + -1 * start >= 0)
{
for (int i2 = 0; i2 <= 3; ++i2)
t2[i2] = zero_vec_float64;
for (int i0 = 0; i0 <= 3; ++i0)
{
for (int i1 = 0; i1 <= 2; ++i1)
for (int n_batch = start + -8 * n_outer; n_batch <= (-8 + end + -8 * n_outer >= 0 ? 7 : -1 + end + -8 * n_outer); ++n_batch)
t1[(3 * i0 + i1)][n_batch] = dat1[3 * map1[32 * n_outer + 4 * n_batch + i0] + i1];
for (int n_batch = start + -8 * n_outer; n_batch <= (-8 + end + -8 * n_outer >= 0 ? 7 : -1 + end + -8 * n_outer); ++n_batch)
t0[i0][n_batch] = dat0[map0[32 * n_outer + 4 * n_batch + i0]];
}
for (int n_batch = start + -8 * n_outer; n_batch <= (-8 + end + -8 * n_outer >= 0 ? 7 : -1 + end + -8 * n_outer); ++n_batch)
{
/* no-op (insn=form__start) */
/* */
}
form_form0_cell_integral_otherwise_20 = zero_vec_float64;
form_form0_cell_integral_otherwise = -1.0 * t1[0];
form_form0_cell_integral_otherwise_0 = form_form0_cell_integral_otherwise + t1[3];
form_form0_cell_integral_otherwise_1 = -1.0 * t1[1];
form_form0_cell_integral_otherwise_2 = form_form0_cell_integral_otherwise_1 + t1[7];
form_form0_cell_integral_otherwise_3 = -1.0 * t1[2];
form_form0_cell_integral_otherwise_4 = form_form0_cell_integral_otherwise_3 + t1[11];
form_form0_cell_integral_otherwise_5 = form_form0_cell_integral_otherwise_1 + t1[10];
form_form0_cell_integral_otherwise_6 = form_form0_cell_integral_otherwise_3 + t1[8];
form_form0_cell_integral_otherwise_7 = form_form0_cell_integral_otherwise_2 * form_form0_cell_integral_otherwise_4 + -1.0 * form_form0_cell_integral_otherwise_5 * form_form0_cell_integral_otherwise_6;
form_form0_cell_integral_otherwise_8 = form_form0_cell_integral_otherwise + t1[6];
form_form0_cell_integral_otherwise_9 = form_form0_cell_integral_otherwise_3 + t1[5];
form_form0_cell_integral_otherwise_10 = form_form0_cell_integral_otherwise_5 * form_form0_cell_integral_otherwise_9;
form_form0_cell_integral_otherwise_11 = form_form0_cell_integral_otherwise_1 + t1[4];
form_form0_cell_integral_otherwise_12 = form_form0_cell_integral_otherwise + t1[9];
form_form0_cell_integral_otherwise_13 = form_form0_cell_integral_otherwise_11 * form_form0_cell_integral_otherwise_6 + -1.0 * form_form0_cell_integral_otherwise_2 * form_form0_cell_integral_otherwise_9;
form_form0_cell_integral_otherwise_14 = form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_13 + form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_7 + form_form0_cell_integral_otherwise_8 * (form_form0_cell_integral_otherwise_10 + -1.0 * form_form0_cell_integral_otherwise_11 * form_form0_cell_integral_otherwise_4);
#pragma omp simd
for (int n_batch_simd = start + -8 * n_outer; n_batch_simd <= (-8 + end + -8 * n_outer >= 0 ? 7 : -1 + end + -8 * n_outer); ++n_batch_simd)
form_form0_cell_integral_otherwise_15[n_batch_simd] = fabs(form_form0_cell_integral_otherwise_14[n_batch_simd]);
for (int form_j = 0; form_j <= 3; ++form_j)
form_form0_cell_integral_otherwise_22[form_j] = zero_vec_float64;
for (int form_ip = 0; form_ip <= 3; ++form_ip)
{
form_form0_cell_integral_otherwise_18 = zero_vec_float64;
for (int form_i = 0; form_i <= 3; ++form_i)
form_form0_cell_integral_otherwise_18 = form_form0_cell_integral_otherwise_18 + form_form0_cell_integral_otherwise_17[4 * form_ip + form_i] * t0[form_i];
form_form0_cell_integral_otherwise_19 = form_form0_cell_integral_otherwise_16[form_ip] * form_form0_cell_integral_otherwise_15;
form_form0_cell_integral_otherwise_20 = form_form0_cell_integral_otherwise_20 + form_form0_cell_integral_otherwise_19;
form_form0_cell_integral_otherwise_21 = form_form0_cell_integral_otherwise_19 * glob0[0] * form_form0_cell_integral_otherwise_18;
for (int form_j_0 = 0; form_j_0 <= 3; ++form_j_0)
form_form0_cell_integral_otherwise_22[form_j_0] = form_form0_cell_integral_otherwise_22[form_j_0] + form_form0_cell_integral_otherwise_17[4 * form_ip + form_j_0] * form_form0_cell_integral_otherwise_21;
}
form_form0_cell_integral_otherwise_23 = 1.0 / form_form0_cell_integral_otherwise_14;
form_form0_cell_integral_otherwise_24 = form_form0_cell_integral_otherwise_7 * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_25 = -1.0 * t0[0];
form_form0_cell_integral_otherwise_26 = form_form0_cell_integral_otherwise_25 + t0[1];
form_form0_cell_integral_otherwise_27 = (form_form0_cell_integral_otherwise_10 + form_form0_cell_integral_otherwise_11 * -1.0 * form_form0_cell_integral_otherwise_4) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_28 = form_form0_cell_integral_otherwise_25 + t0[2];
form_form0_cell_integral_otherwise_29 = form_form0_cell_integral_otherwise_13 * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_30 = form_form0_cell_integral_otherwise_25 + t0[3];
form_form0_cell_integral_otherwise_31 = form_form0_cell_integral_otherwise_29 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_24 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_27 * form_form0_cell_integral_otherwise_28;
form_form0_cell_integral_otherwise_32 = (form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_6 + form_form0_cell_integral_otherwise_4 * -1.0 * form_form0_cell_integral_otherwise_8) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_33 = (form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_4 + form_form0_cell_integral_otherwise_9 * -1.0 * form_form0_cell_integral_otherwise_12) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_34 = (form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_9 + -1.0 * form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_6) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_35 = form_form0_cell_integral_otherwise_34 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_32 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_33 * form_form0_cell_integral_otherwise_28;
form_form0_cell_integral_otherwise_36 = (form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_5 + -1.0 * form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_2) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_37 = (form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_11 + -1.0 * form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_5) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_38 = (form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_2 + -1.0 * form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_11) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_39 = form_form0_cell_integral_otherwise_38 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_36 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_37 * form_form0_cell_integral_otherwise_28;
form_form0_cell_integral_otherwise_40 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_38 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_29 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_34) * form_form0_cell_integral_otherwise_20;
form_form0_cell_integral_otherwise_42 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_37 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_27 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_33) * form_form0_cell_integral_otherwise_20;
form_form0_cell_integral_otherwise_44 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_36 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_24 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_32) * form_form0_cell_integral_otherwise_20;
for (int form_j_1 = 0; form_j_1 <= 3; ++form_j_1)
t2[form_j_1] = t2[form_j_1] + form_form0_cell_integral_otherwise_41[form_j_1] * form_form0_cell_integral_otherwise_40 + form_form0_cell_integral_otherwise_43[form_j_1] * form_form0_cell_integral_otherwise_42 + form_form0_cell_integral_otherwise_22[form_j_1] + form_form0_cell_integral_otherwise_45[form_j_1] * form_form0_cell_integral_otherwise_44;
for (int n_batch = start + -8 * n_outer; n_batch <= (-8 + end + -8 * n_outer >= 0 ? 7 : -1 + end + -8 * n_outer); ++n_batch)
{
/* no-op (insn=statement4) */
/* */
}
for (int i3 = 0; i3 <= 3; ++i3)
for (int n_batch = start + -8 * n_outer; n_batch <= (-8 + end + -8 * n_outer >= 0 ? 7 : -1 + end + -8 * n_outer); ++n_batch)
dat2[map0[32 * n_outer + 4 * n_batch + i3]] = dat2[map0[32 * n_outer + 4 * n_batch + i3]] + t2[i3][n_batch];
}
}
{
/* bulk slab for 'n_outer' */
/* */
}
for (int n_outer = 1 + start + -1 * ((7 + 7 * start) / 8); n_outer <= -2 + (7 + end) / 8; ++n_outer)
{
for (int i2 = 0; i2 <= 3; ++i2)
t2[i2] = zero_vec_float64;
for (int i0 = 0; i0 <= 3; ++i0)
{
for (int i1 = 0; i1 <= 2; ++i1)
for (int n_batch = 0; n_batch <= 7; ++n_batch)
t1[(3 * i0 + i1)][n_batch] = dat1[3 * map1[32 * n_outer + 4 * n_batch + i0] + i1];
for (int n_batch = 0; n_batch <= 7; ++n_batch)
t0[i0][n_batch] = dat0[map0[32 * n_outer + 4 * n_batch + i0]];
}
for (int n_batch = 0; n_batch <= 7; ++n_batch)
{
/* no-op (insn=form__start) */
/* */
}
form_form0_cell_integral_otherwise_20 = zero_vec_float64;
form_form0_cell_integral_otherwise = -1.0 * t1[0];
form_form0_cell_integral_otherwise_0 = form_form0_cell_integral_otherwise + t1[3];
form_form0_cell_integral_otherwise_1 = -1.0 * t1[1];
form_form0_cell_integral_otherwise_2 = form_form0_cell_integral_otherwise_1 + t1[7];
form_form0_cell_integral_otherwise_3 = -1.0 * t1[2];
form_form0_cell_integral_otherwise_4 = form_form0_cell_integral_otherwise_3 + t1[11];
form_form0_cell_integral_otherwise_5 = form_form0_cell_integral_otherwise_1 + t1[10];
form_form0_cell_integral_otherwise_6 = form_form0_cell_integral_otherwise_3 + t1[8];
form_form0_cell_integral_otherwise_7 = form_form0_cell_integral_otherwise_2 * form_form0_cell_integral_otherwise_4 + -1.0 * form_form0_cell_integral_otherwise_5 * form_form0_cell_integral_otherwise_6;
form_form0_cell_integral_otherwise_8 = form_form0_cell_integral_otherwise + t1[6];
form_form0_cell_integral_otherwise_9 = form_form0_cell_integral_otherwise_3 + t1[5];
form_form0_cell_integral_otherwise_10 = form_form0_cell_integral_otherwise_5 * form_form0_cell_integral_otherwise_9;
form_form0_cell_integral_otherwise_11 = form_form0_cell_integral_otherwise_1 + t1[4];
form_form0_cell_integral_otherwise_12 = form_form0_cell_integral_otherwise + t1[9];
form_form0_cell_integral_otherwise_13 = form_form0_cell_integral_otherwise_11 * form_form0_cell_integral_otherwise_6 + -1.0 * form_form0_cell_integral_otherwise_2 * form_form0_cell_integral_otherwise_9;
form_form0_cell_integral_otherwise_14 = form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_13 + form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_7 + form_form0_cell_integral_otherwise_8 * (form_form0_cell_integral_otherwise_10 + -1.0 * form_form0_cell_integral_otherwise_11 * form_form0_cell_integral_otherwise_4);
#pragma omp simd
for (int n_batch_simd = 0; n_batch_simd <= 7; ++n_batch_simd)
form_form0_cell_integral_otherwise_15[n_batch_simd] = fabs(form_form0_cell_integral_otherwise_14[n_batch_simd]);
for (int form_j = 0; form_j <= 3; ++form_j)
form_form0_cell_integral_otherwise_22[form_j] = zero_vec_float64;
for (int form_ip = 0; form_ip <= 3; ++form_ip)
{
form_form0_cell_integral_otherwise_18 = zero_vec_float64;
for (int form_i = 0; form_i <= 3; ++form_i)
form_form0_cell_integral_otherwise_18 = form_form0_cell_integral_otherwise_18 + form_form0_cell_integral_otherwise_17[4 * form_ip + form_i] * t0[form_i];
form_form0_cell_integral_otherwise_19 = form_form0_cell_integral_otherwise_16[form_ip] * form_form0_cell_integral_otherwise_15;
form_form0_cell_integral_otherwise_20 = form_form0_cell_integral_otherwise_20 + form_form0_cell_integral_otherwise_19;
form_form0_cell_integral_otherwise_21 = form_form0_cell_integral_otherwise_19 * glob0[0] * form_form0_cell_integral_otherwise_18;
for (int form_j_0 = 0; form_j_0 <= 3; ++form_j_0)
form_form0_cell_integral_otherwise_22[form_j_0] = form_form0_cell_integral_otherwise_22[form_j_0] + form_form0_cell_integral_otherwise_17[4 * form_ip + form_j_0] * form_form0_cell_integral_otherwise_21;
}
form_form0_cell_integral_otherwise_23 = 1.0 / form_form0_cell_integral_otherwise_14;
form_form0_cell_integral_otherwise_24 = form_form0_cell_integral_otherwise_7 * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_25 = -1.0 * t0[0];
form_form0_cell_integral_otherwise_26 = form_form0_cell_integral_otherwise_25 + t0[1];
form_form0_cell_integral_otherwise_27 = (form_form0_cell_integral_otherwise_10 + form_form0_cell_integral_otherwise_11 * -1.0 * form_form0_cell_integral_otherwise_4) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_28 = form_form0_cell_integral_otherwise_25 + t0[2];
form_form0_cell_integral_otherwise_29 = form_form0_cell_integral_otherwise_13 * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_30 = form_form0_cell_integral_otherwise_25 + t0[3];
form_form0_cell_integral_otherwise_31 = form_form0_cell_integral_otherwise_29 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_24 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_27 * form_form0_cell_integral_otherwise_28;
form_form0_cell_integral_otherwise_32 = (form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_6 + form_form0_cell_integral_otherwise_4 * -1.0 * form_form0_cell_integral_otherwise_8) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_33 = (form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_4 + form_form0_cell_integral_otherwise_9 * -1.0 * form_form0_cell_integral_otherwise_12) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_34 = (form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_9 + -1.0 * form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_6) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_35 = form_form0_cell_integral_otherwise_34 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_32 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_33 * form_form0_cell_integral_otherwise_28;
form_form0_cell_integral_otherwise_36 = (form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_5 + -1.0 * form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_2) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_37 = (form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_11 + -1.0 * form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_5) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_38 = (form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_2 + -1.0 * form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_11) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_39 = form_form0_cell_integral_otherwise_38 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_36 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_37 * form_form0_cell_integral_otherwise_28;
form_form0_cell_integral_otherwise_40 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_38 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_29 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_34) * form_form0_cell_integral_otherwise_20;
form_form0_cell_integral_otherwise_42 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_37 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_27 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_33) * form_form0_cell_integral_otherwise_20;
form_form0_cell_integral_otherwise_44 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_36 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_24 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_32) * form_form0_cell_integral_otherwise_20;
for (int form_j_1 = 0; form_j_1 <= 3; ++form_j_1)
t2[form_j_1] = t2[form_j_1] + form_form0_cell_integral_otherwise_41[form_j_1] * form_form0_cell_integral_otherwise_40 + form_form0_cell_integral_otherwise_43[form_j_1] * form_form0_cell_integral_otherwise_42 + form_form0_cell_integral_otherwise_22[form_j_1] + form_form0_cell_integral_otherwise_45[form_j_1] * form_form0_cell_integral_otherwise_44;
for (int n_batch = 0; n_batch <= 7; ++n_batch)
{
/* no-op (insn=statement4) */
/* */
}
for (int i3 = 0; i3 <= 3; ++i3)
for (int n_batch = 0; n_batch <= 7; ++n_batch)
dat2[map0[32 * n_outer + 4 * n_batch + i3]] = dat2[map0[32 * n_outer + 4 * n_batch + i3]] + t2[i3][n_batch];
}
{
/* final slab for 'n_outer' */
/* */
}
{
int const n_outer = loopy_floor_div_pos_b_int32(-1 + end, 8);
if (-1 + 8 * n_outer + -1 * start >= 0)
{
for (int i2 = 0; i2 <= 3; ++i2)
t2[i2] = zero_vec_float64;
for (int i0 = 0; i0 <= 3; ++i0)
{
for (int i1 = 0; i1 <= 2; ++i1)
for (int n_batch = 0; n_batch <= -1 + end + -8 * n_outer; ++n_batch)
t1[(3 * i0 + i1)][n_batch] = dat1[3 * map1[32 * n_outer + 4 * n_batch + i0] + i1];
for (int n_batch = 0; n_batch <= -1 + end + -8 * n_outer; ++n_batch)
t0[i0][n_batch] = dat0[map0[32 * n_outer + 4 * n_batch + i0]];
}
for (int n_batch = 0; n_batch <= -1 + end + -8 * n_outer; ++n_batch)
{
/* no-op (insn=form__start) */
/* */
}
form_form0_cell_integral_otherwise_20 = zero_vec_float64;
form_form0_cell_integral_otherwise = -1.0 * t1[0];
form_form0_cell_integral_otherwise_0 = form_form0_cell_integral_otherwise + t1[3];
form_form0_cell_integral_otherwise_1 = -1.0 * t1[1];
form_form0_cell_integral_otherwise_2 = form_form0_cell_integral_otherwise_1 + t1[7];
form_form0_cell_integral_otherwise_3 = -1.0 * t1[2];
form_form0_cell_integral_otherwise_4 = form_form0_cell_integral_otherwise_3 + t1[11];
form_form0_cell_integral_otherwise_5 = form_form0_cell_integral_otherwise_1 + t1[10];
form_form0_cell_integral_otherwise_6 = form_form0_cell_integral_otherwise_3 + t1[8];
form_form0_cell_integral_otherwise_7 = form_form0_cell_integral_otherwise_2 * form_form0_cell_integral_otherwise_4 + -1.0 * form_form0_cell_integral_otherwise_5 * form_form0_cell_integral_otherwise_6;
form_form0_cell_integral_otherwise_8 = form_form0_cell_integral_otherwise + t1[6];
form_form0_cell_integral_otherwise_9 = form_form0_cell_integral_otherwise_3 + t1[5];
form_form0_cell_integral_otherwise_10 = form_form0_cell_integral_otherwise_5 * form_form0_cell_integral_otherwise_9;
form_form0_cell_integral_otherwise_11 = form_form0_cell_integral_otherwise_1 + t1[4];
form_form0_cell_integral_otherwise_12 = form_form0_cell_integral_otherwise + t1[9];
form_form0_cell_integral_otherwise_13 = form_form0_cell_integral_otherwise_11 * form_form0_cell_integral_otherwise_6 + -1.0 * form_form0_cell_integral_otherwise_2 * form_form0_cell_integral_otherwise_9;
form_form0_cell_integral_otherwise_14 = form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_13 + form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_7 + form_form0_cell_integral_otherwise_8 * (form_form0_cell_integral_otherwise_10 + -1.0 * form_form0_cell_integral_otherwise_11 * form_form0_cell_integral_otherwise_4);
#pragma omp simd
for (int n_batch_simd = 0; n_batch_simd <= -1 + end + -8 * n_outer; ++n_batch_simd)
form_form0_cell_integral_otherwise_15[n_batch_simd] = fabs(form_form0_cell_integral_otherwise_14[n_batch_simd]);
for (int form_j = 0; form_j <= 3; ++form_j)
form_form0_cell_integral_otherwise_22[form_j] = zero_vec_float64;
for (int form_ip = 0; form_ip <= 3; ++form_ip)
{
form_form0_cell_integral_otherwise_18 = zero_vec_float64;
for (int form_i = 0; form_i <= 3; ++form_i)
form_form0_cell_integral_otherwise_18 = form_form0_cell_integral_otherwise_18 + form_form0_cell_integral_otherwise_17[4 * form_ip + form_i] * t0[form_i];
form_form0_cell_integral_otherwise_19 = form_form0_cell_integral_otherwise_16[form_ip] * form_form0_cell_integral_otherwise_15;
form_form0_cell_integral_otherwise_20 = form_form0_cell_integral_otherwise_20 + form_form0_cell_integral_otherwise_19;
form_form0_cell_integral_otherwise_21 = form_form0_cell_integral_otherwise_19 * glob0[0] * form_form0_cell_integral_otherwise_18;
for (int form_j_0 = 0; form_j_0 <= 3; ++form_j_0)
form_form0_cell_integral_otherwise_22[form_j_0] = form_form0_cell_integral_otherwise_22[form_j_0] + form_form0_cell_integral_otherwise_17[4 * form_ip + form_j_0] * form_form0_cell_integral_otherwise_21;
}
form_form0_cell_integral_otherwise_23 = 1.0 / form_form0_cell_integral_otherwise_14;
form_form0_cell_integral_otherwise_24 = form_form0_cell_integral_otherwise_7 * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_25 = -1.0 * t0[0];
form_form0_cell_integral_otherwise_26 = form_form0_cell_integral_otherwise_25 + t0[1];
form_form0_cell_integral_otherwise_27 = (form_form0_cell_integral_otherwise_10 + form_form0_cell_integral_otherwise_11 * -1.0 * form_form0_cell_integral_otherwise_4) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_28 = form_form0_cell_integral_otherwise_25 + t0[2];
form_form0_cell_integral_otherwise_29 = form_form0_cell_integral_otherwise_13 * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_30 = form_form0_cell_integral_otherwise_25 + t0[3];
form_form0_cell_integral_otherwise_31 = form_form0_cell_integral_otherwise_29 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_24 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_27 * form_form0_cell_integral_otherwise_28;
form_form0_cell_integral_otherwise_32 = (form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_6 + form_form0_cell_integral_otherwise_4 * -1.0 * form_form0_cell_integral_otherwise_8) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_33 = (form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_4 + form_form0_cell_integral_otherwise_9 * -1.0 * form_form0_cell_integral_otherwise_12) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_34 = (form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_9 + -1.0 * form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_6) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_35 = form_form0_cell_integral_otherwise_34 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_32 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_33 * form_form0_cell_integral_otherwise_28;
form_form0_cell_integral_otherwise_36 = (form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_5 + -1.0 * form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_2) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_37 = (form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_11 + -1.0 * form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_5) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_38 = (form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_2 + -1.0 * form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_11) * form_form0_cell_integral_otherwise_23;
form_form0_cell_integral_otherwise_39 = form_form0_cell_integral_otherwise_38 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_36 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_37 * form_form0_cell_integral_otherwise_28;
form_form0_cell_integral_otherwise_40 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_38 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_29 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_34) * form_form0_cell_integral_otherwise_20;
form_form0_cell_integral_otherwise_42 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_37 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_27 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_33) * form_form0_cell_integral_otherwise_20;
form_form0_cell_integral_otherwise_44 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_36 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_24 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_32) * form_form0_cell_integral_otherwise_20;
for (int form_j_1 = 0; form_j_1 <= 3; ++form_j_1)
t2[form_j_1] = t2[form_j_1] + form_form0_cell_integral_otherwise_41[form_j_1] * form_form0_cell_integral_otherwise_40 + form_form0_cell_integral_otherwise_43[form_j_1] * form_form0_cell_integral_otherwise_42 + form_form0_cell_integral_otherwise_22[form_j_1] + form_form0_cell_integral_otherwise_45[form_j_1] * form_form0_cell_integral_otherwise_44;
for (int n_batch = 0; n_batch <= -1 + end + -8 * n_outer; ++n_batch)
{
/* no-op (insn=statement4) */
/* */
}
for (int i3 = 0; i3 <= 3; ++i3)
for (int n_batch = 0; n_batch <= -1 + end + -8 * n_outer; ++n_batch)
dat2[map0[32 * n_outer + 4 * n_batch + i3]] = dat2[map0[32 * n_outer + 4 * n_batch + i3]] + t2[i3][n_batch];
}
}
} | {
"alphanum_fraction": 0.7987915408,
"avg_line_length": 96.783625731,
"ext": "c",
"hexsha": "9357e02b06cfd14e0c2267158a3906e2ed043ad4",
"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": "45af935843217475f45a22f69d7f19965422c923",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sv2518/Vect-Firedrake-Likwid",
"max_forks_repo_path": "cached_kernels/0ee8f4736d289edd2859eaf7303628_p10082.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "45af935843217475f45a22f69d7f19965422c923",
"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": "sv2518/Vect-Firedrake-Likwid",
"max_issues_repo_path": "cached_kernels/0ee8f4736d289edd2859eaf7303628_p10082.c",
"max_line_length": 419,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "45af935843217475f45a22f69d7f19965422c923",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sv2518/Vect-Firedrake-Likwid",
"max_stars_repo_path": "cached_kernels/0ee8f4736d289edd2859eaf7303628_p10082.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 9673,
"size": 33100
} |
/* multifit/gsl_multifit.h
*
* Copyright (C) 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.
*/
#ifndef __GSL_MULTIFIT_H__
#define __GSL_MULTIFIT_H__
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t n; /* number of observations */
size_t p; /* number of parameters */
gsl_matrix * A;
gsl_matrix * Q;
gsl_matrix * QSI;
gsl_vector * S;
gsl_vector * t;
gsl_vector * xt;
gsl_vector * D;
}
gsl_multifit_linear_workspace;
gsl_multifit_linear_workspace *
gsl_multifit_linear_alloc (size_t n, size_t p);
void
gsl_multifit_linear_free (gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear (const gsl_matrix * X,
const gsl_vector * y,
gsl_vector * c,
gsl_matrix * cov,
double * chisq,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_svd (const gsl_matrix * X,
const gsl_vector * y,
double tol,
size_t * rank,
gsl_vector * c,
gsl_matrix * cov,
double *chisq,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_wlinear (const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_vector * c,
gsl_matrix * cov,
double * chisq,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_wlinear_svd (const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
double tol,
size_t * rank,
gsl_vector * c,
gsl_matrix * cov,
double *chisq,
gsl_multifit_linear_workspace * work);
int
gsl_multifit_linear_est (const gsl_vector * x,
const gsl_vector * c,
const gsl_matrix * cov, double *y, double *y_err);
__END_DECLS
#endif /* __GSL_MULTIFIT_H__ */
| {
"alphanum_fraction": 0.5909665193,
"avg_line_length": 29.5887850467,
"ext": "h",
"hexsha": "e408b0d01fd6e6298a21bf291206e22480e04f7a",
"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/multifit/gsl_multifit.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/multifit/gsl_multifit.h",
"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/multifit/gsl_multifit.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 716,
"size": 3166
} |
#ifndef _DRAGONCELLO_H
#define _DRAGONCELLO_H
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
#include "constants.h"
#include <gsl/gsl_integration.h>
#include <gsl/gsl_matrix.h>
using namespace std;
using namespace DRAGON;
struct diagEntry {
double upper;
double central;
double lower;
};
struct norms {
double max;
double mean;
double norm2;
};
class DRAGONCELLO {
public:
DRAGONCELLO(int,int);
~DRAGONCELLO() { cout << "I am the destructor " << endl; }
void buildXGrid();
void buildYGrid();
void buildZGrid();
void buildPGrid();
void initEmptyGrids();
void initGrids();
void initSource();
void initBfield();
void initAnisoSpatialDiffusion();
void initDriftLikeVelocities();
void initEloss();
void dumpSpectra();
void dumpSpectra_2(int counter);
void dumpProfiles();
void dumpProfiles2D();
void compute_epsilon(int counter);
void computeResidualLosses(int);
void computeResidualDiffAniso(int);
void computeSourceEnergyIntegral(int, int, int);
void computeSolutionEnergyIntegral(int, int, int);
void initCN2Daniso();
void Run2D();
void propagateInZaniso(double dt, double dtbar, int counter);
void propagateInRaniso(double dt, double dtbar, int counter);
void propagateMixedDerivatives(double dt, double dtbar, int counter);
void propagateEloss(double dt, double dtbar);
void printLocalFlux();
void dumpSolution(int counter);
inline long int index(int ix, int iy, int iz, int ip) {
return (((ix * ny + iy) * nz + iz) * np + ip);
}
inline long int indexSpatial(int ix, int iy, int iz) {
return (((ix * ny + iy) * nz + iz));
}
inline double computeVelocity(double momentum) {
return c_light*sqrt( 1. - mass*mass*c_light*c_light/(momentum*momentum) );
}
inline vector<double> getP() {
return p_vec;
}
void solveTridiagonalSystem(vector<double>& a, vector<double>& b, vector<double>& c, vector<double>& r, vector<double>& u, int n);
int gsl_linalg_solve_tridiag(const vector<double> & diag, const vector<double> & abovediag, const vector<double> & belowdiag,
const vector<double> & rhs, vector<double> & x);
int solve_tridiag_nonsym(const vector<double> & diag, const vector<double> & abovediag, const vector<double> & belowdiag,
const vector<double> & rhs, vector<double> & x, size_t N);
private:
int Z, A;
int species_id;
double deltax, deltay, deltaz, deltaLogp;
vector<double> x_vec, y_vec, z_vec, p_vec;
vector<double> deltaxUp, deltayUp, deltazUp;
vector<double> deltaxDown, deltayDown, deltazDown;
vector<double> deltaxCentral, deltayCentral, deltazCentral;
unsigned int ixsun, iysun, izsun, ipLocal;
vector<double> N; //(r,z,p) or (x,y,z,p)
vector<double> N_previous; //(r,z,p) or (x,y,z,p)
double sourceEnergyIntegral;
double totalInjectedEnergy;
double solutionEnergyIntegral;
double reaccelerationPower;
double totalReaccelerationEnergy;
vector<double> analyticalSolution;
vector<double> sourceTerm;
vector<double> b_r; // (r,z) or (r,phi,z); b_r = B_r/|B| magnetic field unit vector projected along r
vector<double> b_phi; // (r,z) or (r,phi,z);
vector<double> b_x; // b_x = B_x/|B| magnetic field unit vector projected along x
vector<double> b_y; // b_y = B_y/|B|
vector<double> b_z; // same as before, but along z
vector<double> diffusionCoefficient; //(r,z,p) or (x,y,z,p)
vector<double> diffusionCoefficient_xx; //(r,z,p) or (x,y,z,p)
vector<double> diffusionCoefficient_zz; //(r,z,p) or (x,y,z,p)
vector<double> Dpara; //(r,z,p) or (x,y,z,p)
vector<double> Dperp; //(r,z,p) or (x,y,z,p)
vector<double> D_rr; //(r,z,p) or (r,phi,z,p)
vector<double> D_rz; //(r,z,p) or (r,phi,z,p)
vector<double> D_xx; //(x,z,p) or (x,y,z,p)
vector<double> D_xz; //(x,z,p) or (x,y,z,p)
vector<double> D_zz; //(r,z,p) or (x,z,p) or ...
vector<double> u_r; //(r,z,p) or (x,y,z,p)
vector<double> u_x; //(x,z,p) or (x,y,z,p)
vector<double> u_z; //(r,z,p) or (x,z,p) or ...
vector<double> reaccelerationCoefficient; //(r,z,p) or (x,y,z,p)
vector<double> energyLossTerm; //(r,z,p) or (x,y,z,p)
vector<double> upperDiagonalZ;
vector<double> lowerDiagonalZ;
vector<double> centralDiagonalZ;
vector<double> upperDiagonalX;
vector<double> lowerDiagonalX;
vector<double> centralDiagonalX;
vector<double> upperDiagonalR;
vector<double> lowerDiagonalR;
vector<double> centralDiagonalR;
vector<double> upperDiagonalDpp;
vector<double> lowerDiagonalDpp;
vector<double> centralDiagonalDpp;
vector<double> upperDiagonalEloss;
vector<double> lowerDiagonalEloss;
vector<double> centralDiagonalEloss;
};
#endif
| {
"alphanum_fraction": 0.6680277664,
"avg_line_length": 28.476744186,
"ext": "h",
"hexsha": "1c4b035009281ad5b8b85d6f438d2b733eab1031",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-11-26T02:21:41.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-11-26T02:21:41.000Z",
"max_forks_repo_head_hexsha": "1dfa2a9bf4d6359d5a9257c10f9adf825edd4594",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sscerr/DRAGONCELLO",
"max_forks_repo_path": "dragoncello.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1dfa2a9bf4d6359d5a9257c10f9adf825edd4594",
"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": "sscerr/DRAGONCELLO",
"max_issues_repo_path": "dragoncello.h",
"max_line_length": 132,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "1dfa2a9bf4d6359d5a9257c10f9adf825edd4594",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sscerr/DRAGONCELLO",
"max_stars_repo_path": "dragoncello.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-25T07:12:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-25T22:05:46.000Z",
"num_tokens": 1451,
"size": 4898
} |
/* movstat/test_variance.c
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_movstat.h>
/* compute moving variance by explicitely constructing window and computing variance */
int
slow_movvar(const gsl_movstat_end_t etype, const gsl_vector * x, gsl_vector * y,
const int H, const int J)
{
const size_t n = x->size;
const int K = H + J + 1;
double *window = malloc(K * sizeof(double));
size_t i;
for (i = 0; i < n; ++i)
{
size_t wsize = gsl_movstat_fill(etype, x, i, H, J, window);
double variance = (wsize > 1) ? gsl_stats_variance(window, 1, wsize) : 0.0;
gsl_vector_set(y, i, variance);
}
free(window);
return GSL_SUCCESS;
}
/* compute moving variance by explicitely constructing window and computing variance */
int
slow_movsd(const gsl_movstat_end_t etype, const gsl_vector * x, gsl_vector * y,
const int H, const int J)
{
const size_t n = x->size;
const int K = H + J + 1;
double *window = malloc(K * sizeof(double));
size_t i;
for (i = 0; i < n; ++i)
{
size_t wsize = gsl_movstat_fill(etype, x, i, H, J, window);
double sd = (wsize > 1) ? gsl_stats_sd(window, 1, wsize) : 0.0;
gsl_vector_set(y, i, sd);
}
free(window);
return GSL_SUCCESS;
}
static double
func_var(const size_t n, double x[], void * params)
{
(void) params;
if (n > 1)
return gsl_stats_variance(x, 1, n);
else
return 0.0;
}
static double
func_sd(const size_t n, double x[], void * params)
{
(void) params;
if (n > 1)
return gsl_stats_sd(x, 1, n);
else
return 0.0;
}
static void
test_variance_proc(const double tol, const size_t n, const size_t H, const size_t J,
const gsl_movstat_end_t etype, gsl_rng * rng_p)
{
gsl_movstat_workspace * w = gsl_movstat_alloc2(H, J);
gsl_vector * x = gsl_vector_alloc(n);
gsl_vector * y = gsl_vector_alloc(n);
gsl_vector * z = gsl_vector_alloc(n);
gsl_movstat_function F1, F2;
char buf[2048];
F1.function = func_var;
F1.params = NULL;
F2.function = func_sd;
F2.params = NULL;
random_vector(x, rng_p);
/* test variance */
/* y = variance(x) with slow brute force method */
slow_movvar(etype, x, y, H, J);
/* y = variance(x) with fast method */
gsl_movstat_variance(etype, x, z, w);
/* test y = z */
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u variance random", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* z = variance(x) in-place */
gsl_vector_memcpy(z, x);
gsl_movstat_variance(etype, z, z, w);
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u variance random in-place", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* z = variance(x) with user-defined function */
gsl_movstat_apply(etype, &F1, x, z, w);
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u variance user", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* test standard deviation */
/* y = stddev(x) with slow brute force method */
slow_movsd(etype, x, y, H, J);
/* y = stddev(x) with fast method */
gsl_movstat_sd(etype, x, z, w);
/* test y = z */
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u stddev random", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* z = stddev(x) in-place */
gsl_vector_memcpy(z, x);
gsl_movstat_sd(etype, z, z, w);
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u stddev random in-place", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* z = stddev(x) with user-defined function */
gsl_movstat_apply(etype, &F2, x, z, w);
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u stddev user", n, H, J, etype);
compare_vectors(tol, z, y, buf);
gsl_movstat_free(w);
gsl_vector_free(x);
gsl_vector_free(y);
gsl_vector_free(z);
}
static void
test_variance(gsl_rng * rng_p)
{
const double eps = 1.0e-10;
test_variance_proc(eps, 1000, 0, 0, GSL_MOVSTAT_END_PADZERO, rng_p);
test_variance_proc(eps, 1000, 3, 3, GSL_MOVSTAT_END_PADZERO, rng_p);
test_variance_proc(eps, 1000, 0, 5, GSL_MOVSTAT_END_PADZERO, rng_p);
test_variance_proc(eps, 1000, 5, 0, GSL_MOVSTAT_END_PADZERO, rng_p);
test_variance_proc(eps, 2000, 10, 5, GSL_MOVSTAT_END_PADZERO, rng_p);
test_variance_proc(eps, 2000, 5, 10, GSL_MOVSTAT_END_PADZERO, rng_p);
test_variance_proc(eps, 20, 50, 50, GSL_MOVSTAT_END_PADZERO, rng_p);
test_variance_proc(eps, 20, 10, 50, GSL_MOVSTAT_END_PADZERO, rng_p);
test_variance_proc(eps, 20, 50, 10, GSL_MOVSTAT_END_PADZERO, rng_p);
test_variance_proc(eps, 1000, 0, 0, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_variance_proc(eps, 1000, 3, 3, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_variance_proc(eps, 1000, 1, 5, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_variance_proc(eps, 1000, 5, 1, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_variance_proc(eps, 2000, 10, 5, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_variance_proc(eps, 2000, 5, 10, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_variance_proc(eps, 20, 50, 50, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_variance_proc(eps, 20, 10, 50, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_variance_proc(eps, 20, 50, 10, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_variance_proc(eps, 1000, 0, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_variance_proc(eps, 1000, 3, 3, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_variance_proc(eps, 1000, 0, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_variance_proc(eps, 1000, 5, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_variance_proc(eps, 2000, 10, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_variance_proc(eps, 2000, 5, 10, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_variance_proc(eps, 20, 50, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_variance_proc(eps, 20, 10, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_variance_proc(eps, 20, 50, 10, GSL_MOVSTAT_END_TRUNCATE, rng_p);
}
| {
"alphanum_fraction": 0.6904071984,
"avg_line_length": 32.4603960396,
"ext": "c",
"hexsha": "eeb36705be792bf7af536d544ad1103d4bb651d4",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/movstat/test_variance.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/movstat/test_variance.c",
"max_line_length": 88,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/movstat/test_variance.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": 2124,
"size": 6557
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_roots.h>
#include "cosmocalc.h"
#include "haloprofs.h"
#include "weaklens.h"
double eps_fun(double x, void *p)
{
double *v = (double*)p;
return NFWprof_menc(x,v[0],v[1],v[2]) - v[3];
}
double solve_scale_nfw(gsl_root_fsolver *s, gsl_function F, double *p)
{
int status;
int iter,max_iter = 100;
double x_lo = 0.0,x_hi = 5.0;
double r;
iter = 0;
gsl_root_fsolver_set(s,&F,x_lo,x_hi);
do
{
iter++;
status = gsl_root_fsolver_iterate(s);
r = gsl_root_fsolver_root(s);
x_lo = gsl_root_fsolver_x_lower(s);
x_hi = gsl_root_fsolver_x_upper(s);
status = gsl_root_test_interval(x_lo, x_hi,0,0.001);
}
while (status == GSL_CONTINUE && iter < max_iter);
return r;
}
int main(int argc, char **argv)
{
//init
cosmoData.cosmoNum = 1;
cosmoData.OmegaM = 0.27;
cosmoData.OmegaL = 0.73;
cosmoData.OmegaB = 0.045;
cosmoData.OmegaNu = 0.0;
cosmoData.OmegaK = 0.0;
cosmoData.h = 0.7;
cosmoData.w0 = -1.0;
cosmoData.wa = 0.0;
cosmoData.SpectralIndex = 0.96;
cosmoData.Sigma8 = 0.8;
cosmoData.useSmoothTransFunc = 0;
//prints mass function in bins to stdout
double a = atof(argv[1]);
double mp = atof(argv[2]);
double np;
double mmin = 1e1;
double mmax = 1e18;
long Nm = 2000;
double m,dlnm = log(mmax/mmin)/Nm;
long i;
double rvir,rs,c;
cosmoData.delta = 200.0*RHO_CRIT*hubble_noscale(a)*hubble_noscale(a)/(cosmoData.OmegaM*RHO_CRIT/a/a/a);
//fprintf(stderr,"delta = %f\n",cosmoData.delta);
gsl_root_fsolver *s;
gsl_function F;
double p[4],r1,rN,rN2;
F.function = &eps_fun;
F.params = p;
s = gsl_root_fsolver_alloc(gsl_root_fsolver_brent);
fprintf(stdout,"# m rs rvir r1 rN rN2\n");
for(i=0;i<Nm;++i)
{
m = exp(dlnm*i)*mmin;
rvir = pow(m/(cosmoData.delta*RHO_CRIT*cosmoData.OmegaM*4.0/3.0*M_PI),1.0/3.0);
c = duffy2008_concNFW(m,a);
//if(c < 4.0)
//c = 4.0;
rs = rvir/c;
np = m/mp;
if(np >= 1.0)
{
p[0] = m;
p[1] = rvir;
p[2] = c;
p[3] = mp;
r1 = solve_scale_nfw(s,F,p);
}
else
r1 = -1.0;
if(np > 100)
{
p[0] = m;
p[1] = rvir;
p[2] = c;
p[3] = mp*100.0;
rN = solve_scale_nfw(s,F,p);
}
else
rN = -1.0;
if(np > 10)
{
p[0] = m;
p[1] = rvir;
p[2] = c;
p[3] = mp*10.0;
rN2 = solve_scale_nfw(s,F,p);
}
else
rN2 = -1.0;
fprintf(stdout,"%e %e %e %e %e %e\n",m,rs,rvir,r1,rN,rN2);
}
gsl_root_fsolver_free(s);
return 0;
}
| {
"alphanum_fraction": 0.5860331174,
"avg_line_length": 20.1304347826,
"ext": "c",
"hexsha": "b01fd12dd91b5b3db04107806c28f3c659a76d86",
"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": "example/main.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": "example/main.c",
"max_line_length": 105,
"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": "example/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1079,
"size": 2778
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_wavelet.h>
int
main (int argc, char **argv)
{
(void)(argc); /* avoid unused parameter warning */
int i, n = 256, nc = 20;
double *orig_data = malloc (n * sizeof (double));
double *data = malloc (n * sizeof (double));
double *abscoeff = malloc (n * sizeof (double));
size_t *p = malloc (n * sizeof (size_t));
FILE * f;
gsl_wavelet *w;
gsl_wavelet_workspace *work;
w = gsl_wavelet_alloc (gsl_wavelet_daubechies, 4);
work = gsl_wavelet_workspace_alloc (n);
f = fopen (argv[1], "r");
for (i = 0; i < n; i++)
{
fscanf (f, "%lg", &orig_data[i]);
data[i] = orig_data[i];
}
fclose (f);
gsl_wavelet_transform_forward (w, data, 1, n, work);
for (i = 0; i < n; i++)
{
abscoeff[i] = fabs (data[i]);
}
gsl_sort_index (p, abscoeff, 1, n);
for (i = 0; (i + nc) < n; i++)
data[p[i]] = 0;
gsl_wavelet_transform_inverse (w, data, 1, n, work);
for (i = 0; i < n; i++)
{
printf ("%g %g\n", orig_data[i], data[i]);
}
gsl_wavelet_free (w);
gsl_wavelet_workspace_free (work);
free (data);
free (orig_data);
free (abscoeff);
free (p);
return 0;
}
| {
"alphanum_fraction": 0.5722402597,
"avg_line_length": 20.8813559322,
"ext": "c",
"hexsha": "422c55d54ed7875b757da960a4e4b888e7cc17fc",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/dwt.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/dwt.c",
"max_line_length": 54,
"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/dwt.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": 421,
"size": 1232
} |
/**
* \brief Function Definition Library to implement Sensor Fusion Algorithm
* \author jaspalsingh@cmail.carleton.ca
* \version 1.0
* \date 2019-12-01
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
#include "sensor_fusion.h"
/**
* \brief Structure pointer for computed support degree matrix
* \details Structure pointer for calculating support degree matrix
* \param[in] sensor_readings array of sensor readings
* \return Success: pointer to the structure support_degree_matrix
* \return Failure: NULL
*/
struct support_degree_matrix *compute_support_degree_matrix(double *sensor_readings) {
struct support_degree_matrix *spd;
spd = (struct support_degree_matrix *)malloc(sizeof(struct support_degree_matrix));
// count the number of sensor readings
int length = sizeof(sensor_readings) / sizeof(sensor_readings[0]);
spd->sensor_count = length;
double **arrptr = (double **)malloc(length * sizeof(double *));
int count = 0;
for (int i = 0; i < length; i++) {
arrptr[i] = (double *)malloc(length * sizeof(double));
}
// allocate memory space for support degree matrix structure
spd->sd_matrix = (double *)malloc(sizeof(double) * length * length);
if (arrptr == NULL || spd == NULL || spd->sd_matrix == NULL) {
printf("ERROR: Failed to allocate memory at %s\n", __func__);
return NULL;
}
// compute support degree matrix
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
arrptr[i][j] = exp(-1 * fabs(sensor_readings[i] - sensor_readings[j]));
spd->sd_matrix[count] = arrptr[i][j];
count++;
}
}
printf("INFO : Computed support degree matrix\n");
for (int i = 0; i < length * length; i++) {
printf("DEBUG: Value => %f\n", spd->sd_matrix[i]);
}
free(arrptr);
return spd;
}
/**
* \brief Structure pointer calculate eigen value and eigen vector
* \details Structure pointer for calculating eigen value and eigen vector
* \param[in] support_degree_matrix pointer to structure support degree matrix
* \return Success: pointer to structure eigen_value_vector
* \return Failure: NULL
*/
struct eigen_value_vector *compute_eigen(struct support_degree_matrix *spd) {
if ((spd->sd_matrix == NULL) || (spd->sensor_count == 0)) {
printf("ERROR: Invalid param passed at %s\n", __func__);
return NULL;
}
int length = spd->sensor_count;
struct eigen_value_vector *eigen;
// allocation memory space for eigen value vector structure
eigen = (struct eigen_value_vector *)malloc(sizeof(struct eigen_value_vector));
eigen->eigen_value = (double *)malloc(sizeof(double) * length);
eigen->eigen_vector = (double **)malloc(length * sizeof(double *));
for (int i = 0; i < length; i++) {
eigen->eigen_vector[i] = (double *)malloc(length * sizeof(double));
}
if (eigen == NULL || eigen->eigen_vector == NULL || eigen->eigen_value == NULL) {
printf("ERROR: Failed to allocate memory at %s\n", __func__);
return NULL;
}
//Refer: https://www.gnu.org/software/gsl/doc/html/eigen.html
// compute eigen values
gsl_matrix_view m = gsl_matrix_view_array(spd->sd_matrix, length, length);
gsl_vector *eval = gsl_vector_alloc(length);
gsl_matrix *evec = gsl_matrix_alloc(length, length);
gsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(length);
gsl_eigen_symmv(&m.matrix, eval, evec, w);
gsl_eigen_symmv_free(w);
gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_VAL_DESC);
{
int i;
for (i = 0; i < length; i++) {
eigen->eigen_value[i] = gsl_vector_get(eval, i);
gsl_vector_view evec_i = gsl_matrix_column(evec, i);
for (int j = 0; j < length; j++) {
eigen->eigen_vector[i][j] = *(*(&evec_i.vector.data) + j * length);
}
}
}
for (int i = 0; i < length; i++) {
printf("DEBUG: Eigen Value => %g\n", eigen->eigen_value[i]);
printf("DEBUG: Eigen Vector => \n");
for (int j = 0; j < length; j++) {
printf("%g\n", eigen->eigen_vector[i][j]);
}
}
gsl_vector_free(eval);
gsl_matrix_free(evec);
return eigen;
}
/**
* \brief Function to calculate the contribution rate of principal component
* \details Compute the contribution rate of kth and mth principal components
* \param[in] eigen_value_vector pointer to structure of eigen_value_vector
* \param[in] sensor_count total count of sensors
* \return Success: pointer to contribution_rate of type double
* \return Failure: NULL
*/
double *compute_contribution_rate(struct eigen_value_vector *eigen,
int sensor_count) {
if ((sensor_count == 0) || (eigen->eigen_value == NULL) || (eigen->eigen_vector == NULL)) {
printf("ERROR: Invalid param passed at %s\n", __func__);
return NULL;
}
double *contribution_rate = (double *)malloc(sensor_count * sizeof(double));
if (contribution_rate == NULL) {
printf("ERROR: Failed to allocate memory at %s\n", __func__);
return NULL;
}
double sum = 0;
for (int i = 0; i < sensor_count; i++) {
sum += eigen->eigen_value[i];
}
printf("INFO : Compute contribution rate\n");
for (int j = 0; j < sensor_count; j++) {
contribution_rate[j] = eigen->eigen_value[j] / sum;
printf("DEBUG: Rate => %g\n", contribution_rate[j]);
}
return contribution_rate;
}
/**
* \brief Function to compute contribution rate
* \details Compute the count of contribution rates to be used for sensors
* \param[in] contribution_rate
* \param[in] threshold
* \param[in] sensor_count number of sensors to be used
* \return Success: contribution rate count,
* \return Failure: -1
*/
int compute_contrib_rate_count(double *contribution_rate,
float threshold,
int sensor_count) {
if ((contribution_rate == NULL) || (threshold == 0) || (sensor_count == 0)) {
printf("ERROR: Invalid param passed at %s\n", __func__);
return -1;
}
double sum = 0;
int m;
for (int k = 0; k < sensor_count; k++) {
for (int j = 0; j <= k; j++) {
sum += contribution_rate[j];
}
if (sum <= threshold) {
m = k - 1;
printf("DEBUG: Contribution rate to use %d\n", m);
return m;
}
}
printf("DEBUG: Count of Contribution rates => %d\n", sensor_count);
return sensor_count;
}
/**
* \brief Function to compute principal component
* \details Computed principal component for each of eigen vector
* \param[in] support_degree_matrix pointer to structure support degree matrix
* \param[in] eigen_vector pointer to pointer of eigen vector of type double
* \param[in] contrib_rate_count number of contribution rate to be used
* \return Success: principal of support degree matrix,
* \return Failure: NULL
*/
double **compute_principal_component(struct support_degree_matrix *spd,
double **eigen_vector,
int contrib_rate_count) {
if ((spd->sensor_count == 0) || (contrib_rate_count == 0) || (spd->sd_matrix == NULL) || (eigen_vector == NULL)) {
printf("ERROR: Invalid param passed at %s\n", __func__);
return NULL;
}
int n = spd->sensor_count;
int m = contrib_rate_count;
int count = 0;
double **arrptr = (double **)malloc(n * sizeof(double *));
for (int i = 0; i < n; i++) {
arrptr[i] = (double *)malloc(n * sizeof(double));
}
if (arrptr == NULL) {
printf("ERROR: Failed to allocate memory at %s\n", __func__);
return NULL;
}
printf("INFO : Compute support degree matrix\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arrptr[i][j] = spd->sd_matrix[count];
printf("%f\n", arrptr[i][j]);
count++;
}
}
double **principal_components_matrix = (double **)malloc(m * sizeof(double *));
for (int i = 0; i < n; i++) {
principal_components_matrix[i] = (double *)malloc(n * sizeof(double));
}
if (principal_components_matrix == NULL) {
printf("ERROR: Failed to allocate memory at %s\n", __func__);
return NULL;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
principal_components_matrix[i][j] = 0;
for (int k = 0; k < n; k++) {
principal_components_matrix[i][j] += eigen_vector[i][k] * arrptr[k][j];
}
}
}
free(arrptr);
return principal_components_matrix;
}
/**
* \brief Function to compute integrated support degree
* \details Computed support degree matrix for each of the sensors
* \param[in] principle_components pointer to pointer of principle component of type double
* \param[in] contribution_rate pointer to contribution rate of type double
* \param[in] contrib_rate_count number of contribution rate to be used
* \param[in] sensor_count number of sensors
* \return Success: array of support degree matrix,
* \return Failure: NULL
*/
double *compute_integrated_support_degree(double **principle_components,
double *contribution_rate,
int contrib_rate_count,
int sensor_count) {
if ((sensor_count == 0) || (contrib_rate_count == 0) || (principle_components == NULL) || (contribution_rate == NULL)) {
printf("ERROR: Invalid param passed at %s\n", __func__);
return NULL;
}
double *arr = (double *)malloc(sensor_count * sizeof(double));
if (arr == NULL) {
printf("ERROR: Failed to allocate memory at %s\n", __func__);
return NULL;
}
// Calculate integrated support degree matrix
for (int i = 0; i < sensor_count; i++) {
for (int j = 0; j < contrib_rate_count; j++) {
printf("INFO: Principal Component => %d-%f, Contribution Rate => %d-%f\n", i, principle_components[i][j], j, contribution_rate[i]);
arr[i] += principle_components[i][j] * contribution_rate[i];
}
}
return arr;
}
/**
* \brief Function to eliminate invalid sensor readings
* \details Discard the faulty sensor readings from the support degree matrix
* \param[in,out] integrated_support_degree_matrix pointer to integrated support degree matrix
* \param[in] fault_tolerance_threshold threshold value to cut off invalid readings
* \param[in] sensor_count total count of sensors
* \return Success: 0,
* \return Failure: -1
*/
int eliminate_incorrect_data(double *integrated_support_degree_matrix,
double fault_tolerance_threshold,
int sensor_count) {
int i;
double mean = 0;
double sum = 0;
double *arr = integrated_support_degree_matrix;
if ((sensor_count == 0) || (arr == NULL)) {
printf("ERROR: Invalid param passed at %s\n", __func__);
return -1;
}
for (i = 0; i < sensor_count; i++) {
sum += arr[i];
}
mean = sum / (i + 1);
for (i = 0; i < sensor_count; i++) {
if (fabs(arr[i]) < fabs(fault_tolerance_threshold * mean)) {
arr[i] = 0;
}
}
return 0;
}
/**
* \brief Function to compute weight coefficient for each sensor
* \details Compute weighted coefficients for each sensors from the support degree matrix
* \param[in] integrated_support_degree_matrix pointer to integrated support degree matrix
* \param[in] sensor_count total count of sensors
* \return Success: array of weighted coefficients,
* \return Failure: NULL
*/
double *compute_weight_coefficient(double *integrated_support_degree_matrix,
int sensor_count) {
double sum_weight_coefficient = 0;
if ((sensor_count == 0) || (integrated_support_degree_matrix == NULL)) {
printf("ERROR: Invalid param passed at %s\n", __func__);
return NULL;
}
double *arr = (double *)malloc(sensor_count * sizeof(double));
if (arr == NULL) {
printf("ERROR: Failed to allocate memory at %s\n", __func__);
return NULL;
}
memset(arr, 0, sensor_count * sizeof(double));
for (int i = 0; i < sensor_count; i++) {
sum_weight_coefficient += integrated_support_degree_matrix[i];
}
for (int i = 0; i < sensor_count; i++) {
arr[i] = integrated_support_degree_matrix[i] / sum_weight_coefficient;
}
return arr;
}
/**
* \brief Function to compute fused output
* \details Compute the aggregated value of sensors from the weighted coefficients
* \param[in] weight_coefficient pointer to weighted coefficient of sensors
* \param[in] sensor_data pointer to data of sensors
* \param[in] sensor_count total count of sensors
* \return Success: fused value of sensor data
* \return Failure: -1
*/
double compute_fused_output(double *weight_coefficient,
double *sensor_data,
int sensor_count) {
double fused_output = 0;
if ((sensor_count == 0) || (weight_coefficient == NULL) || (sensor_data == NULL)) {
printf("ERROR: Invalid param passed at %s\n", __func__);
return -1;
}
for (int i = 0; i < sensor_count; i++) {
fused_output += weight_coefficient[i] * sensor_data[i];
}
return fused_output;
} | {
"alphanum_fraction": 0.6222369097,
"avg_line_length": 39.3554913295,
"ext": "c",
"hexsha": "ff720195666c5b745497873c4ca25270bf5e9854",
"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": "25b78e48d4bc6737c61c599026e1943348b91fcc",
"max_forks_repo_licenses": [
"RSA-MD"
],
"max_forks_repo_name": "jaspal-carleton/SensorFusionAlgorithm",
"max_forks_repo_path": "src/sensor_fusion.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "25b78e48d4bc6737c61c599026e1943348b91fcc",
"max_issues_repo_issues_event_max_datetime": "2019-12-18T14:59:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-08T18:40:17.000Z",
"max_issues_repo_licenses": [
"RSA-MD"
],
"max_issues_repo_name": "jaspal-carleton/SensorFusionAlgorithm",
"max_issues_repo_path": "src/sensor_fusion.c",
"max_line_length": 143,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "25b78e48d4bc6737c61c599026e1943348b91fcc",
"max_stars_repo_licenses": [
"RSA-MD"
],
"max_stars_repo_name": "jaspal-carleton/SensorFusionAlgorithm",
"max_stars_repo_path": "src/sensor_fusion.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3299,
"size": 13617
} |
#ifndef ENTITY_H_
#define ENTITY_H_
#include <vector>
#include <memory>
#include <utility>
#include <gsl.h>
#include "Component.h"
using std::vector;
using std::unique_ptr;
using std::make_unique;
using std::move;
using std::forward;
class Entity
{
public:
static void test();
template <typename C, typename... Args>
void addComponent(Args &&... args);
template <typename C>
C * getComponent() const;
private:
Component * getComponent(Component::Id _id, Component::Id _mask) const;
vector<unique_ptr<Component>> m_components;
vector<Component::Id> m_componentIds; // invariant : m_components.size() == m_componentIds.size()
};
template<typename C, typename ...Args>
inline void Entity::addComponent(Args && ...args)
{
Expects(IdInfoOf<C>::value.isRegistered() != 0);
m_components.emplace_back(make_unique<C>(forward<Args>(args)...));
m_componentIds.emplace_back(IdInfoOf<C>::value.getId());
}
template<typename C>
inline C * Entity::getComponent() const
{
auto & idInfo = IdInfoOf<C>::value;
auto id = idInfo.getId();
auto mask = idInfo.getMaskId();
return static_cast<C*>(getComponent(id, mask));
}
#endif // ENTITY_H_
| {
"alphanum_fraction": 0.6892230576,
"avg_line_length": 22.1666666667,
"ext": "h",
"hexsha": "089b25c174dd38af5893113bf4aa75df725ac1d7",
"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": "84ad449d9e6f242d77fe4774791e5db5356b75b3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Onduril/GetComponent",
"max_forks_repo_path": "GetComponent/include/Entity.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "84ad449d9e6f242d77fe4774791e5db5356b75b3",
"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": "Onduril/GetComponent",
"max_issues_repo_path": "GetComponent/include/Entity.h",
"max_line_length": 106,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "84ad449d9e6f242d77fe4774791e5db5356b75b3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Onduril/GetComponent",
"max_stars_repo_path": "GetComponent/include/Entity.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 290,
"size": 1197
} |
/*
Simulation of a network of Izhikevich neurons, coupled by chemical synapses,
receiving uncorrelated, random input spiketrains.
The simulation was written by Ekkehard Ullner in 2013.
This is a modified version of E.U.'s original, stand-alone program,
for use e.g. via the ctypes ffi in Python.
Changelog:
- suport for networks with inhibitory synapses
- Neuron type switched from FitzHugh-Nagumo to Izhikevich
- Various simulation parameters exposed to allow arbitrary network topologies,
input patterns, neuron parameters etc.
- results are written to a provided buffer instead of text files
- the non-free, problematic[0] "Numerical Recipes" RAN1 random number generator
was replaced with a Mersenne Twister rng from the GNU scientific library.
[0 "Random Numbers in Scientific Computing: An Introduction", Katzgraber, 2010
http://arxiv.org/pdf/1005.4117.pdf]
- cosmetics and a minimum of documentation (i.e. the comments)
CK 2014-2016
The MIT License (MIT)
Copyright (c) 2013,2014 Ekkehard Ullner, Clemens Korndörfer
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 PARTICU
LAR 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.
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <time.h>
#include <assert.h>
void sagwas(){
puts("simulation version Oct 12 2016");
}
/* function simulate
* ------------------
* Runs a single network simulation with the given parameters and writes the resulting
* voltage traces into a given buffer.
*
* Parameters:
*
* N: Number of rows i in the simulated grid of neurons. (regardless of network topology,
* the network is a 'grid' where each node is adressed by an (i,j) coordinate.)
* M: number of columns j in the grid
*
* limit: number of simulation steps to run
*
* KT: maximum number of coupled neighbors of any node (degree of the network)
* connection: function pointer, where
* connection(i,j,l, '0' | '1') must return the first (second) coordinate of the l'th afferent to cell ij
* connection(i,j,l, 's') must return the strength of that connection
*
* recording_voltage: array of shape (M,N,limit) in which simulation results will be written in row first order
* recording_recov: same as recording_voltage, for the neuron's recovery variable
* recording_spikes: same as recording_voltage, for binary log of spike events
*
* inputc_exc: array of shape (M,N) in row-first order. modulates the rate of input pulses fed into
* each cell, values within [0,1]. aka "the stimulus".
* inputc_inh: same for inhibitory input pulses
* laminex: lambda_in_ex, the rate of excitatory input spikes to input-receiving nodes
* lamini: lambda_in_in, the rate of inhibitory input spikes to input-receiving nodes
* izhi_a: parameter a of the izhikevich neuron
* izhi_b: parameter b of the izhikevich neuron
* izhi_reset_c: reset constant of the neuron
* izhi_recovery_d: recovery reset constant
* con_upstr_exc: synapse conductivity of the excitatory random inputs
* con_upstr_inh: synapse conductivity of the inhibitory random inputs
* # lateral synapses:
* taus: duration of transmitter presence after spike
* alp: rising time constant of fraction of open receptors
* bet: decay time constant of fraction of open receptors
* # inhibitory synapses:
* tauni: duration of transmitter presence after spike
* ani: rising time constant of fraction of open receptors
* bni: decay time constant of fraction of open receptors
* # external excitatory synapses:
* tauna: duration of transmitter presence after spike
* ana: rising time constant of fraction of open receptors
* bna: decay time constant of fraction of open receptors
* activation_noise: scale of white noise added to each neuron's activation variable
* seed: random seed > 0
* verbose: print a lot or not
* delta_t: integration step width
*/
void simulate(int M,
int N,
int limit,
int KT,
double (*connection)(int,int,int,char),
double* recording_voltage,
double* recording_recov,
double* recording_spikes,
double* inputc_exc,
double* inputc_inh,
double laminex,
double lamini,
double izhi_a,
double izhi_b,
double izhi_reset_c,
double izhi_recovery_d,
double con_upstr_exc,
double con_upstr_inh,
double taus,
double alp,
double bet,
double tauni,
double ani,
double bni,
double tauna,
double ana,
double bna,
double activation_noise,
int seed,
int verbose,
double delta_t){
// say hello & show the current parametrisation & input pattern.
if (verbose){
printf("starting simulation (Izhikevich neuron)\n");
printf("seed: %d\nM: %d\nN: %d\nlimit: %d\nKT: %d\nlaminex: %f\nlamini: %f\nizhi_a: %f\nizhi_b: %f\nizhi_reset_c: %f\nizhi_recovery_d: %f\ncon_upstr_exc: %f\ncon_upstr_inh: %f\ntaus: %f\nalp: %f\nbet: %f\ntauni: %f\nani: %f\nbni: %f\ntauna: %f\nana: %f\nbna: %f\nactivation_noise: %f\ndelta_t: %f\n",
seed, M, N, limit, KT, laminex, lamini, izhi_a, izhi_b, izhi_reset_c, izhi_recovery_d, con_upstr_exc, con_upstr_inh, taus, alp, bet, tauni, ani, bni, tauna, ana, bna, activation_noise, delta_t);
int i1,j1;
int print_exc, print_inh;
for (j1 = 0; j1<M; j1++ ){
for (i1 = 0; i1<N; i1++ ){
print_exc = inputc_exc[i1 + N*j1] > 0;
print_inh = inputc_inh[i1 + N*j1] > 0;
if (print_exc && print_inh) printf(" ±");
else if (print_exc) printf(" +");
else if (print_inh) printf(" -");
else printf(" .");
}
printf("\n");
}
}
assert(seed>0);
gsl_rng* rng = gsl_rng_alloc(gsl_rng_mt19937);
gsl_rng_set(rng, seed);
// Initialisations & constant parameters:
// neuron model:
double xold[N][M],dx_h[N][M],xh[N][M],xnew[N][M]; // activation variable (previous value, first step, intermediate value, new value)
double yold[N][M],dy_h[N][M],yh[N][M],ynew[N][M]; // recovery variable (previous value, first step, intermediate value, new value)
double Isyn[N][M]; // collection of lateral input currents at each neuron in the current time step
double spikes[N][M]; // recording of spike events in the current time step
// lateral synapses:
double rold[N][M],rh[N][M],rnew[N][M]; // fraction of open receptors (previous value, intermediate value, new value).
// more precisely: r[i][j] is the fraction of open receptors at synapses anywhere in the network
// that are the target of neuron (i,j). Since all synapses have the same rise and decay constants
// alpha and beta, the effect of a spike at neuron i,j is the same at all of its target synapses.
// We can therefore write the fractions of open receptors of all these target synapses as a
// single variable r[i][j], associated with the source neuron i,j.
double Tl[N][M]; // spike arrival times "T_j" (indexing follows the same logic as r[][])
double Hs[N][M]; // transmitter concentrations "[T]_j" (...here, too)
double Vna = 0.0; // synaptic reversal potential (excitatory)
double Vni = -80; // synaptic reversal potential (inhibitory)
// double taus = 0.01; // duration of transmitter presence after spike
double Tm = 1.0; // maximum transmitter concentration
// double alp = 8.0; // rising time constant of fraction of open receptors
// double bet = 8.0; // decay time constant of fraction of open receptors
// activatory external input synapses:
double rnoa[N][M],rnha[N][M],rnna[N][M]; // fraction of open receptors
double Tnla[N][M],Hna[N][M]; // spike arrival times and transmitter concentrations
// double tauna = 0.01; // duration of transmitter presence after spike
double Tna = 1.0; // maximum transmitter concentration
// double ana = 8.0; // rising time constant of fraction of open receptors
// double bna = 8.0; // decay time constant of fraction of open receptors
// inhibitory external input synapses:
double rnoi[N][M],rnhi[N][M],rnni[N][M]; // fraction of open receptors (previous value, intermediate value, new value)
double Tnli[N][M],Hni[N][M]; // spike arrival times and transmitter concentrations
// double tauni = 0.01; // duration of transmitter presence after spike
double Tni = 1.0; // maximum transmitter concentration
// double ani = 8.0; // rising time constant of fraction of open receptors
// double bni = 8.0; // decay time constant of fraction of open receptors
// misc:
double izhi_reset_threshold = 30; // spike detection threshold
long step; // simulation step count
// double delta_t = 0.001; // integration step width
// double delta_t = 0.01; // integration step width
double current_time = 0.0; // simulation time
int i,j,l; // various loop variables over network nodes.
int p1[N][M][KT],p2[N][M][KT]; // lookup tables holding the first (p1) and second (p2) coordinate of the KT'th afferent to neuron N,M
float conductance_net[N][M][KT]; // lookup table: synapse conductance of the KT'th afferent to neuron N,M
double in_exc[N][M]; // excitatory stimulus strength (input noise rate modulation) for neuron N,M
double in_inh[N][M]; // inhibitory ...
// remaining initialisations:
for (j = 0;j<M;j++ ){
for (i = 0;i<N;i++ ){
in_exc[i][j] = inputc_exc[i + N * j];
in_inh[i][j] = inputc_inh[i + N * j];
xold[i][j] = 30*(gsl_rng_uniform(rng)-0.5);
yold[i][j] = 30*(gsl_rng_uniform(rng)-0.5);
rold[i][j] = 0.0;
rnoa[i][j] = 0.0;
rnoi[i][j] = 0.0;
Tl[i][j] = -2 * taus;
Hs[i][j] = 0.0;
Isyn[i][j] = 0.0;
Tnla[i][j] = -2 * tauna;
Tnli[i][j] = -2 * tauni;
Hna[i][j] = 0.0;
Hni[i][j] = 0.0;
// network connectivity lookup tables:
for (l = 0;l<KT;l++ ){
p1[i][j][l] = (int)connection(j,i,l,'0');
p2[i][j][l] = (int)connection(j,i,l,'1');
conductance_net[i][j][l] = connection(j,i,l,'s');
}}}
// // some more extreme verbosity for verification
// printf("\n connectivity structure: \n");
// for (l = 0; l<KT; l++){
// printf("\n\n%d. neighbour of each unit:\n\n", l);
// for (j = 0;j<M;j++ ){
// for (i = 0;i<N;i++ ){
// printf("(%d,%d) ", p1[i][j][l], p2[i][j][l]);
// }
// printf("\n");
// }
// }
// for (l = 0; l<KT; l++){
// printf("\n\nconductance from %d. neighbour of each unit:\n\n", l);
// for (j = 0;j<M;j++ ){
// for (i = 0;i<N;i++ ){
// printf("%05.2f ", conductance_net[i][j][l]);
// }
// printf("\n");
// }
// }
// begin stepwise integration by the implicit midpoint method
for(step = 1; step<= limit;step++ ){
if (verbose && (step % (limit/100) == 0)){
printf("\r...%d%%",(int)(100 * step/(double)limit));
fflush(stdout);
}
for (j = 0;j<M;j++ ){
for (i = 0;i<N;i++ ){
// set transmitter presence if there was a spike recently,
// ...for synapses within the network..
if (Tl[i][j] + taus>current_time) Hs[i][j] = 1.0 * Tm;
else Hs[i][j] = 0.0;
// ..for activatory external input synapses..
if (Tnla[i][j] + tauna>current_time) Hna[i][j] = 1.0 * Tna;
else Hna[i][j] = 0.0;
// ..and for inhibitory external input synapses.
if (Tnli[i][j] + tauni>current_time) Hni[i][j] = 1.0 * Tni;
else Hni[i][j] = 0.0;
}}
// first integration step
double x;
double y;
double I;
double g;
for (j = 0;j<M;j++ ){
for (i = 0;i<N;i++ ){
x = xold[i][j];
y = yold[i][j];
// collect lateral synaptic currents
Isyn[i][j] = 0.0;
for (l = 0;l<KT;l++ ){
if(p1[i][j][l]>=0 && p2[i][j][l]>=0){
// input currents to neuron (i,j) depend proportionally on
// r[ p1[i][j][l] ][ p2[i][j][l] ], that is, on the fraction of open
// receptors of all the synapses targeted by neighbour l projecting
// to neuron i,j. These synapses have a high fraction of open receptors
// if their source neuron recently fired a spike. Thus, input currents
// flow to neuron (i,j) if its neighbours have recently fired a spike.
// we use signed conductance values to encode excitatory vs inhibitory synapses.
// of course, conductance is in fact positive in both these synapses; what differs
// is the reversal potential.
g = conductance_net[i][j][l];
if (g > 0.0)
Isyn[i][j] -= g * rold[p1[i][j][l]][p2[i][j][l]] * (xold[i][j] - Vna);
else if (g < 0.0)
Isyn[i][j] -= -g * rold[p1[i][j][l]][p2[i][j][l]] * (xold[i][j] - Vni);
}
}
I = Isyn[i][j];
// collect external synaptic currents
I -= con_upstr_exc * rnoa[i][j] * (xold[i][j] - Vna);
I -= con_upstr_inh * rnoi[i][j] * (xold[i][j] - Vni);
// Izhikevich neuron:
// dv/dt = 0.04v^2 + 5v + 140 - u + I
// du/dt = a(bv - u)
dx_h[i][j] = 0.04*x*x + 5*x + 140 - y + I;
dy_h[i][j] = izhi_a * (izhi_b*x - y);
// step:
xh[i][j] = xold[i][j] + (dx_h[i][j])*delta_t;
yh[i][j] = yold[i][j] + (dy_h[i][j])*delta_t;
// fraction of open receptors.. dr/dt = alpha [T] (1 - r) - beta r
// ..of synapses within the network:
rh[i][j] = rold[i][j] + (alp * Hs[i][j] * (1 - rold[i][j]) - bet * rold[i][j]) * delta_t;
// ..of synapses receiving external noise, activatory:
rnha[i][j] = rnoa[i][j] + (ana * Hna[i][j] * (1 - rnoa[i][j]) - bna * rnoa[i][j]) * delta_t;
// ..of synapses receiving external noise, inhibitory:
rnhi[i][j] = rnoi[i][j] + (ani * Hni[i][j] * (1 - rnoi[i][j]) - bni * rnoi[i][j]) * delta_t;
}}
// second integration step
double dx;
double dy;
double Ihsyn;
for (j = 0;j<M;j++ ){
for (i = 0;i<N;i++ ){
x = xh[i][j];
y = yh[i][j];
Ihsyn = 0.0;
for (l = 0;l<KT;l++ ){
if(p1[i][j][l]>=0 && p2[i][j][l]>=0){
g = conductance_net[i][j][l];
if (g > 0)
Ihsyn -= g * rh[p1[i][j][l]][p2[i][j][l]] * (xh[i][j] - Vna);
else if (g < 0)
Ihsyn -= -g * rh[p1[i][j][l]][p2[i][j][l]] * (xh[i][j] - Vni);
}
}
I = 0.5 * (Isyn[i][j] + Ihsyn);
// input currents from external synapses
I -= 0.5 * con_upstr_exc * (rnoa[i][j] * (xold[i][j] - Vna) + rnha[i][j] * (xh[i][j] - Vna));
I -= 0.5 * con_upstr_inh * (rnoi[i][j] * (xold[i][j] - Vni) + rnhi[i][j] * (xh[i][j] - Vni));
// Izhikevich neuron:
// dv/dt = 0.04v^2 + 5v + 140 - u + I
// du/dt = a(bv -u)
dx = 0.04*x*x + 5*x + 140 - y + I;
dy = izhi_a * (izhi_b*x - y);
xnew[i][j] = xold[i][j] + 0.5*(dx_h[i][j] + dx)*delta_t;
ynew[i][j] = yold[i][j] + 0.5*(dy_h[i][j] + dy)*delta_t;
// fraction of open receptors.. dr/dt = alpha [T] (1 - r) - beta r
// ..of synapses within the network:
rnew[i][j] = rold[i][j] + 0.5 * (alp * Hs[i][j] * (1 - rold[i][j]) - bet * rold[i][j] + alp * Hs[i][j] * (1 - rh[i][j]) - bet * rh[i][j]) * delta_t;
// ..of synapses receiving external noise, activatory:
rnna[i][j] = rnoa[i][j] + 0.5 * (ana * Hna[i][j] * (1 - rnoa[i][j]) - bna * rnoa[i][j] + ana * Hna[i][j] * (1 - rnha[i][j]) - bna * rnha[i][j]) * delta_t;
// ..of synapses receiving external noise, inhibitory:
rnni[i][j] = rnoi[i][j] + 0.5 * (ani * Hni[i][j] * (1 - rnoi[i][j]) - bni * rnoi[i][j] + ani * Hni[i][j] * (1 - rnhi[i][j]) - bni * rnhi[i][j]) * delta_t;
}}
// identify spike times & prepare next step
current_time = delta_t * step;
for (j = 0;j<M;j++ ){
for (i = 0;i<N;i++ ){
// note spike times within the network
if(xnew[i][j] >= izhi_reset_threshold){
xnew[i][j] = izhi_reset_c;
ynew[i][j] += izhi_recovery_d;
spikes[i][j] = 1;
Tl[i][j] = current_time;
}
else spikes[i][j] = 0;
// sample random spike times for activatory external input
if(gsl_rng_uniform(rng) <= (laminex * (double)in_exc[i][j]) * delta_t){
Tnla[i][j] = current_time;
}
// sample random spike times for inhibitory external input
if(gsl_rng_uniform(rng)<= (lamini * (double)in_inh[i][j]) * delta_t){
Tnli[i][j] = current_time;
}
// swap
xold[i][j] = xnew[i][j];
yold[i][j] = ynew[i][j];
rold[i][j] = rnew[i][j];
rnoa[i][j] = rnna[i][j];
rnoi[i][j] = rnni[i][j];
if (activation_noise > 0)
xold[i][j] += (gsl_rng_uniform(rng)-0.5)*activation_noise;
}}
// write the current network state into the provided output buffers.
// each is a 3D array of shape (M,N,limit) in row first order,
// so it has strides proportional to (N * limit, limit, 1).
int linearind = 0;
for(int oi = 0; oi < M; oi++ ) {
for(int oj = 0; oj < N; oj++ ) {
linearind = oi * limit * N + oj * limit + step - 1;
recording_voltage[linearind] = xnew[oj][oi];
recording_recov[linearind] = ynew[oj][oi];
//recording_recov[linearind] = (double) Tnla[oj][oi] == current_time; // <-uncomment to show input spikes instead
recording_spikes[linearind] = spikes[oj][oi];
}
}
} // end of integration loop
if (verbose){
printf("\033[2K");
fflush(stdout);
}
gsl_rng_free(rng);
}
// helper function to play with the random number generator.
void rantest(long seed,int N,double * out){
gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937); // initialize a mersenne twister rng
gsl_rng_set(rng, seed); // seed it
double number = - 1;
for(int i = 0; i<N; i++ ){
number = gsl_rng_uniform(rng); // sample a number
printf("%ld %f\n",seed,number);
out[i] = number;
}
puts(" - - - ");
gsl_rng_free(rng);
}
| {
"alphanum_fraction": 0.5500597943,
"avg_line_length": 42.3178137652,
"ext": "c",
"hexsha": "3578bbad62359b2e36bd24af7731919becc586f2",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-12-21T13:40:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-06-19T14:21:23.000Z",
"max_forks_repo_head_hexsha": "1478f602211ed4bc45331c8bd0124fe1d558aca9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "cknd/synchrony",
"max_forks_repo_path": "libHC/ekkesim/src/simulation_izhikevich.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1478f602211ed4bc45331c8bd0124fe1d558aca9",
"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": "cknd/synchrony",
"max_issues_repo_path": "libHC/ekkesim/src/simulation_izhikevich.c",
"max_line_length": 308,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "1478f602211ed4bc45331c8bd0124fe1d558aca9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "cknd/synchrony",
"max_stars_repo_path": "libHC/ekkesim/src/simulation_izhikevich.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-08T20:59:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-16T11:32:03.000Z",
"num_tokens": 5914,
"size": 20905
} |
#include <bindings.cmacros.h>
#include <gsl/gsl_multimin.h>
BC_INLINE2(GSL_MULTIMIN_FN_EVAL,gsl_multimin_function*,gsl_vector*,double)
BC_INLINE2(GSL_MULTIMIN_FN_EVAL_F,gsl_multimin_function_fdf*,gsl_vector*,double)
BC_INLINE3VOID(GSL_MULTIMIN_FN_EVAL_DF,gsl_multimin_function_fdf*,gsl_vector*,gsl_vector*)
BC_INLINE4VOID(GSL_MULTIMIN_FN_EVAL_F_DF,gsl_multimin_function_fdf*,gsl_vector*,double*,gsl_vector*)
| {
"alphanum_fraction": 0.8753056235,
"avg_line_length": 51.125,
"ext": "c",
"hexsha": "8b844b96d107f49d7331c74498ada9c0414e30d3",
"lang": "C",
"max_forks_count": 19,
"max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z",
"max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "flip111/bindings-dsl",
"max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/MultidimensionalMinimization.c",
"max_issues_count": 23,
"max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb",
"max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "flip111/bindings-dsl",
"max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/MultidimensionalMinimization.c",
"max_line_length": 100,
"max_stars_count": 25,
"max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "flip111/bindings-dsl",
"max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/MultidimensionalMinimization.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z",
"num_tokens": 123,
"size": 409
} |
// Copyright 2019 John McFarlane
//
// 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 WSS_BOARD_PREMIUMS_H
#define WSS_BOARD_PREMIUMS_H
#include <gsl/string_span>
#include "board.h"
enum class premium {
normal,
dl,
tl,
dw,
tw
};
constexpr std::array<int, 5> letter_multipliers {
1,
2,
3,
1,
1
};
constexpr std::array<int, 5> word_multipliers {
1,
1,
1,
2,
3
};
auto load_board_premiums(gsl::cstring_span<> filename)
-> std::optional<board<premium>>;
#endif //WSS_BOARD_PREMIUMS_H
| {
"alphanum_fraction": 0.6702997275,
"avg_line_length": 22.02,
"ext": "h",
"hexsha": "7810b6823be2e1ca25fe7f932d5971e0cbf97401",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-02-23T18:04:41.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-23T18:04:41.000Z",
"max_forks_repo_head_hexsha": "2772e303f79360056dd9f879198e6af207397dcc",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "johnmcfarlane/wss",
"max_forks_repo_path": "src/play/board_premiums.h",
"max_issues_count": 21,
"max_issues_repo_head_hexsha": "2772e303f79360056dd9f879198e6af207397dcc",
"max_issues_repo_issues_event_max_datetime": "2022-03-18T23:55:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-10-28T22:07:55.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "johnmcfarlane/wss",
"max_issues_repo_path": "src/play/board_premiums.h",
"max_line_length": 75,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "2772e303f79360056dd9f879198e6af207397dcc",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "johnmcfarlane/wss",
"max_stars_repo_path": "src/play/board_premiums.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-03T17:23:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-02-04T09:40:23.000Z",
"num_tokens": 285,
"size": 1101
} |
/* filter/test_median.c
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_filter.h>
#include <gsl/gsl_movstat.h>
#include <gsl/gsl_statistics.h>
/* compute filtered data by explicitely constructing window, sorting it and finding median */
int
slow_movmedian(const gsl_filter_end_t etype, const gsl_vector * x, gsl_vector * y, const int K)
{
const size_t H = K / 2;
const size_t n = x->size;
double *window = malloc(K * sizeof(double));
size_t i;
for (i = 0; i < n; ++i)
{
size_t wsize = gsl_movstat_fill(etype, x, i, H, H, window);
double yi = gsl_stats_median(window, 1, wsize);
gsl_vector_set(y, i, yi);
}
free(window);
return GSL_SUCCESS;
}
static void
test_median_proc(const double tol, const size_t n, const size_t K,
const gsl_filter_end_t etype, gsl_rng *rng_p)
{
gsl_filter_median_workspace *w = gsl_filter_median_alloc(K);
gsl_vector *x = gsl_vector_alloc(n);
gsl_vector *y = gsl_vector_alloc(n);
gsl_vector *z = gsl_vector_alloc(n);
char buf[2048];
/* test moving median with random input */
random_vector(x, rng_p);
/* y = median(x) with slow brute force algorithm */
slow_movmedian(etype, x, y, K);
/* z = median(x) */
gsl_filter_median(etype, x, z, w);
/* test y = z */
sprintf(buf, "n=%zu K=%zu endtype=%u median random", n, K, etype);
compare_vectors(tol, z, y, buf);
/* z = median(x) in-place */
gsl_vector_memcpy(z, x);
gsl_filter_median(etype, z, z, w);
sprintf(buf, "n=%zu K=%zu endtype=%u median random in-place", n, K, etype);
compare_vectors(tol, z, y, buf);
gsl_vector_free(x);
gsl_vector_free(y);
gsl_vector_free(z);
gsl_filter_median_free(w);
}
static void
test_median(gsl_rng * rng_p)
{
test_median_proc(GSL_DBL_EPSILON, 1000, 1, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 3, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 5, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 100, 301, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 17, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 9, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 901, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 201, GSL_MOVSTAT_END_PADZERO, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 1, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 3, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 5, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 100, 301, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 17, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 9, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 901, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 201, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 1, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 3, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 1000, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 100, 301, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 17, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 5000, 9, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 901, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_median_proc(GSL_DBL_EPSILON, 50, 201, GSL_MOVSTAT_END_TRUNCATE, rng_p);
}
| {
"alphanum_fraction": 0.7474272931,
"avg_line_length": 38.5344827586,
"ext": "c",
"hexsha": "61c20ce1b6af623aedf66e67eb9360bdb4c53900",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/filter/test_median.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/filter/test_median.c",
"max_line_length": 95,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/filter/test_median.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": 1379,
"size": 4470
} |
/*
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 <errno.h>
#include "SIMULATION/TOOLS/sim.h"
#include "PHY/TOOLS/tools_defs.h"
#include "assertions.h"
// NEW code with lookup table for sin/cos based on delay profile (TO BE TESTED)
double **cos_lut = NULL, * *sin_lut = NULL;
//#if 1
int init_freq_channel(channel_desc_t *desc, uint16_t nb_rb, int16_t n_samples)
{
double delta_f, freq; // 90 kHz spacing
double delay;
int16_t f;
uint8_t l;
if((n_samples & 1) == 0)
{
fprintf(stderr, "freq_channel_init: n_samples has to be odd\n");
return(-1);
}
cos_lut = (double **)malloc(n_samples * sizeof(double *));
sin_lut = (double **)malloc(n_samples * sizeof(double *));
delta_f = nb_rb * 180000 / (n_samples - 1);
for(f = -(n_samples >> 1); f <= (n_samples >> 1); f++)
{
freq = delta_f * (double)f * 1e-6; // due to the fact that delays is in mus
cos_lut[f + (n_samples >> 1)] = (double *)malloc((int)desc->nb_taps * sizeof(double));
sin_lut[f + (n_samples >> 1)] = (double *)malloc((int)desc->nb_taps * sizeof(double));
for(l = 0; l < (int)desc->nb_taps; l++)
{
if(desc->nb_taps == 1)
{
delay = desc->delays[l];
}
else
{
delay = desc->delays[l] + NB_SAMPLES_CHANNEL_OFFSET / desc->sampling_rate;
}
cos_lut[f + (n_samples >> 1)][l] = cos(2 * M_PI * freq * delay);
sin_lut[f + (n_samples >> 1)][l] = sin(2 * M_PI * freq * delay);
//printf("values cos:%d, sin:%d\n", cos_lut[f][l], sin_lut[f][l]);
}
}
return(0);
}
int freq_channel(channel_desc_t *desc, uint16_t nb_rb, int16_t n_samples)
{
int16_t f, f2, d;
uint8_t aarx, aatx, l;
double *clut, *slut;
static int freq_channel_init = 0;
static int n_samples_max = 0;
// do some error checking
// n_samples has to be a odd number because we assume the spectrum is symmetric around the DC and includes the DC
if((n_samples & 1) == 0)
{
fprintf(stderr, "freq_channel: n_samples has to be odd\n");
return(-1);
}
// printf("no of taps:%d,",(int)desc->nb_taps);
if(freq_channel_init == 0)
{
// we are initializing the lut for the largets possible n_samples=12*nb_rb+1
// if called with n_samples<12*nb_rb+1, we decimate the lut
n_samples_max = 12 * nb_rb + 1;
if(init_freq_channel(desc, nb_rb, n_samples_max) == 0)
{
freq_channel_init = 1;
}
else
{
return(-1);
}
}
d = (n_samples_max - 1) / (n_samples - 1);
//printf("no_samples=%d, n_samples_max=%d, d=%d\n",n_samples,n_samples_max,d);
start_meas(&desc->interp_freq);
for(f = -n_samples_max / 2, f2 = -n_samples / 2; f < n_samples_max / 2; f += d, f2++)
{
clut = cos_lut[n_samples_max / 2 + f];
slut = sin_lut[n_samples_max / 2 + f];
for(aarx = 0; aarx < desc->nb_rx; aarx++)
{
for(aatx = 0; aatx < desc->nb_tx; aatx++)
{
desc->chF[aarx + (aatx * desc->nb_rx)][n_samples / 2 + f2].x = 0.0;
desc->chF[aarx + (aatx * desc->nb_rx)][n_samples / 2 + f2].y = 0.0;
for(l = 0; l < (int)desc->nb_taps; l++)
{
desc->chF[aarx + (aatx * desc->nb_rx)][n_samples / 2 + f2].x += (desc->a[l][aarx + (aatx * desc->nb_rx)].x * clut[l] +
desc->a[l][aarx + (aatx * desc->nb_rx)].y * slut[l]);
desc->chF[aarx + (aatx * desc->nb_rx)][n_samples / 2 + f2].y += (-desc->a[l][aarx + (aatx * desc->nb_rx)].x * slut[l] +
desc->a[l][aarx + (aatx * desc->nb_rx)].y * clut[l]);
}
}
}
}
stop_meas(&desc->interp_freq);
return(0);
}
double compute_pbch_sinr(channel_desc_t *desc,
channel_desc_t *desc_i1,
channel_desc_t *desc_i2,
double snr_dB, double snr_i1_dB,
double snr_i2_dB,
uint16_t nb_rb)
{
double avg_sinr, snr = pow(10.0, .1 * snr_dB), snr_i1 = pow(10.0, .1 * snr_i1_dB), snr_i2 = pow(10.0, .1 * snr_i2_dB);
uint16_t f;
uint8_t aarx, aatx;
double S;
struct complex S_i1;
struct complex S_i2;
avg_sinr = 0.0;
// printf("nb_rb %d\n",nb_rb);
for(f = (nb_rb - 6); f < (nb_rb + 6); f++)
{
S = 0.0;
S_i1.x = 0.0;
S_i1.y = 0.0;
S_i2.x = 0.0;
S_i2.y = 0.0;
for(aarx = 0; aarx < desc->nb_rx; aarx++)
{
for(aatx = 0; aatx < desc->nb_tx; aatx++)
{
S += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc->chF[aarx + (aatx * desc->nb_rx)][f].x +
desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc->chF[aarx + (aatx * desc->nb_rx)][f].y);
// printf("%d %d chF[%d] => (%f,%f)\n",aarx,aatx,f,desc->chF[aarx+(aatx*desc->nb_rx)][f].x,desc->chF[aarx+(aatx*desc->nb_rx)][f].y);
if(desc_i1)
{
S_i1.x += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].x +
desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].y);
S_i1.y += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].y -
desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].x);
}
if(desc_i2)
{
S_i2.x += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].x +
desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].y);
S_i2.y += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].y -
desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].x);
}
}
}
// printf("snr %f f %d : S %f, S_i1 %f, S_i2 %f\n",snr,f-nb_rb,S,snr_i1*sqrt(S_i1.x*S_i1.x + S_i1.y*S_i1.y),snr_i2*sqrt(S_i2.x*S_i2.x + S_i2.y*S_i2.y));
avg_sinr += (snr * S / (desc->nb_tx + snr_i1 * sqrt(S_i1.x * S_i1.x + S_i1.y * S_i1.y) + snr_i2 * sqrt(S_i2.x * S_i2.x + S_i2.y * S_i2.y)));
}
// printf("avg_sinr %f (%f,%f,%f)\n",avg_sinr/12.0,snr,snr_i1,snr_i2);
return(10 * log10(avg_sinr / 12.0));
}
double compute_sinr(channel_desc_t *desc,
channel_desc_t *desc_i1,
channel_desc_t *desc_i2,
double snr_dB, double snr_i1_dB,
double snr_i2_dB,
uint16_t nb_rb)
{
double avg_sinr, snr = pow(10.0, .1 * snr_dB), snr_i1 = pow(10.0, .1 * snr_i1_dB), snr_i2 = pow(10.0, .1 * snr_i2_dB);
uint16_t f;
uint8_t aarx, aatx;
double S;
struct complex S_i1;
struct complex S_i2;
DevAssert(nb_rb > 0);
avg_sinr = 0.0;
// printf("nb_rb %d\n",nb_rb);
for(f = 0; f < 2 * nb_rb; f++)
{
S = 0.0;
S_i1.x = 0.0;
S_i1.y = 0.0;
S_i2.x = 0.0;
S_i2.y = 0.0;
for(aarx = 0; aarx < desc->nb_rx; aarx++)
{
for(aatx = 0; aatx < desc->nb_tx; aatx++)
{
S += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc->chF[aarx + (aatx * desc->nb_rx)][f].x +
desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc->chF[aarx + (aatx * desc->nb_rx)][f].y);
if(desc_i1)
{
S_i1.x += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].x +
desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].y);
S_i1.y += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].y -
desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i1->chF[aarx + (aatx * desc->nb_rx)][f].x);
}
if(desc_i2)
{
S_i2.x += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].x +
desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].y);
S_i2.y += (desc->chF[aarx + (aatx * desc->nb_rx)][f].x * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].y -
desc->chF[aarx + (aatx * desc->nb_rx)][f].y * desc_i2->chF[aarx + (aatx * desc->nb_rx)][f].x);
}
}
}
// printf("f %d : S %f, S_i1 %f, S_i2 %f\n",f-nb_rb,snr*S,snr_i1*sqrt(S_i1.x*S_i1.x + S_i1.y*S_i1.y),snr_i2*sqrt(S_i2.x*S_i2.x + S_i2.y*S_i2.y));
avg_sinr += (snr * S / (desc->nb_tx + snr_i1 * sqrt(S_i1.x * S_i1.x + S_i1.y * S_i1.y) + snr_i2 * sqrt(S_i2.x * S_i2.x + S_i2.y * S_i2.y)));
}
// printf("avg_sinr %f (%f,%f,%f)\n",avg_sinr/12.0,snr,snr_i1,snr_i2);
return(10 * log10(avg_sinr / (nb_rb * 2)));
}
int pbch_polynomial_degree = 6;
double pbch_awgn_polynomial[7] = {-7.2926e-05, -2.8749e-03, -4.5064e-02, -3.5301e-01, -1.4655e+00, -3.6282e+00, -6.6907e+00};
void load_pbch_desc(FILE *pbch_file_fd)
{
int i, ret;
char dummy[25];
ret = fscanf(pbch_file_fd, "%d", &pbch_polynomial_degree);
if(ret < 0)
{
printf("fscanf failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if(pbch_polynomial_degree > 6)
{
printf("Illegal degree for pbch interpolation polynomial %d\n", pbch_polynomial_degree);
exit(-1);
}
printf("PBCH polynomial : ");
for(i = 0; i <= pbch_polynomial_degree; i++)
{
ret = fscanf(pbch_file_fd, "%24s", dummy);
if(ret < 0)
{
printf("fscanf failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
pbch_awgn_polynomial[i] = strtod(dummy, NULL);
printf("%f ", pbch_awgn_polynomial[i]);
}
printf("\n");
}
double pbch_bler(double sinr)
{
int i;
double log10_bler = pbch_awgn_polynomial[pbch_polynomial_degree];
double sinrpow = sinr;
double bler = 0.0;
// printf("log10bler %f\n",log10_bler);
if(sinr < -10.0)
{
bler = 1.0;
}
else if(sinr >= 0.0)
{
bler = 0.0;
}
else
{
for(i = 1; i <= pbch_polynomial_degree; i++)
{
// printf("sinrpow %f\n",sinrpow);
log10_bler += (pbch_awgn_polynomial[pbch_polynomial_degree - i] * sinrpow);
sinrpow *= sinr;
// printf("log10bler %f\n",log10_bler);
}
bler = pow(10.0, log10_bler);
}
//printf ("sinr %f bler %f\n",sinr,bler);
return(bler);
}
| {
"alphanum_fraction": 0.5158562368,
"avg_line_length": 36.1705882353,
"ext": "c",
"hexsha": "431960118ad431e208ee233f61398af5fac4fc5f",
"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": "93e5617d68431a477e803af2fa66290fd52470d2",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "AManTw/oai5g",
"max_forks_repo_path": "openair1/SIMULATION/TOOLS/abstraction.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2",
"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": "AManTw/oai5g",
"max_issues_repo_path": "openair1/SIMULATION/TOOLS/abstraction.c",
"max_line_length": 163,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "93e5617d68431a477e803af2fa66290fd52470d2",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "AManTw/oai5g",
"max_stars_repo_path": "openair1/SIMULATION/TOOLS/abstraction.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4112,
"size": 12298
} |
/* TODO these are parts of the tests from msprime that haven't been ported
* into the new test framework yet. Once these have all been moved across
* into the appropriate location, delete.
*/
#define _GNU_SOURCE
/*
* Unit tests for the low-level msprime API.
*/
#include "tsk_genotypes.h"
#include "tsk_convert.h"
#include "tsk_stats.h"
#include <float.h>
#include <limits.h>
#include <stdio.h>
#include <unistd.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_randist.h>
#include <CUnit/Basic.h>
/* Global variables used for test in state in the test suite */
char *_tmp_file_name;
FILE *_devnull;
#define SIMPLE_BOTTLENECK 0
#define INSTANTANEOUS_BOTTLENECK 1
typedef struct {
int type;
double time;
uint32_t population_id;
double parameter;
} bottleneck_desc_t;
/* Example tree sequences used in some of the tests. */
/* Simple single tree example. */
const char *single_tree_ex_nodes = /* 6 */
"1 0 -1 -1\n" /* / \ */
"1 0 -1 -1\n" /* / \ */
"1 0 -1 -1\n" /* / \ */
"1 0 -1 -1\n" /* / 5 */
"0 1 -1 -1\n" /* 4 / \ */
"0 2 -1 -1\n" /* / \ / \ */
"0 3 -1 -1\n"; /* 0 1 2 3 */
const char *single_tree_ex_edges = "0 1 4 0,1\n"
"0 1 5 2,3\n"
"0 1 6 4,5\n";
const char *single_tree_ex_sites = "0.1 0\n"
"0.2 0\n"
"0.3 0\n";
const char *single_tree_ex_mutations
= "0 2 1 -1\n"
"1 4 1 -1\n"
"1 0 0 1\n" /* Back mutation over 0 */
"2 0 1 -1\n" /* recurrent mutations over samples */
"2 1 1 -1\n"
"2 2 1 -1\n"
"2 3 1 -1\n";
/* Example from the PLOS paper */
const char *paper_ex_nodes = "1 0 -1 0\n"
"1 0 -1 0\n"
"1 0 -1 1\n"
"1 0 -1 1\n"
"0 0.071 -1 -1\n"
"0 0.090 -1 -1\n"
"0 0.170 -1 -1\n"
"0 0.202 -1 -1\n"
"0 0.253 -1 -1\n";
const char *paper_ex_edges = "2 10 4 2\n"
"2 10 4 3\n"
"0 10 5 1\n"
"0 2 5 3\n"
"2 10 5 4\n"
"0 7 6 0,5\n"
"7 10 7 0,5\n"
"0 2 8 2,6\n";
/* We make one mutation for each tree */
const char *paper_ex_sites = "1 0\n"
"4.5 0\n"
"8.5 0\n";
const char *paper_ex_mutations = "0 2 1\n"
"1 0 1\n"
"2 5 1\n";
/* Two (diploid) indivduals */
const char *paper_ex_individuals = "0 0.2,1.5\n"
"0 0.0,0.0\n";
/* An example of a nonbinary tree sequence */
const char *nonbinary_ex_nodes = "1 0 0 -1\n"
"1 0 0 -1\n"
"1 0 0 -1\n"
"1 0 0 -1\n"
"1 0 0 -1\n"
"1 0 0 -1\n"
"1 0 0 -1\n"
"1 0 0 -1\n"
"0 0.01 0 -1\n"
"0 0.068 0 -1\n"
"0 0.130 0 -1\n"
"0 0.279 0 -1\n"
"0 0.405 0 -1\n";
const char *nonbinary_ex_edges = "0 100 8 0,1,2,3\n"
"0 100 9 6,8\n"
"0 100 10 4\n"
"0 17 10 5\n"
"0 100 10 7\n"
"17 100 11 5,9\n"
"0 17 12 9\n"
"0 100 12 10\n"
"17 100 12 11";
const char *nonbinary_ex_sites = "1 0\n"
"18 0\n";
const char *nonbinary_ex_mutations = "0 2 1\n"
"1 11 1";
/* An example of a tree sequence with unary nodes. */
const char *unary_ex_nodes = "1 0 0 -1\n"
"1 0 0 -1\n"
"1 0 0 -1\n"
"1 0 0 -1\n"
"0 0.071 0 -1\n"
"0 0.090 0 -1\n"
"0 0.170 0 -1\n"
"0 0.202 0 -1\n"
"0 0.253 0 -1\n";
const char *unary_ex_edges = "2 10 4 2,3\n"
"0 10 5 1\n"
"0 2 5 3\n"
"2 10 5 4\n"
"0 7 6 0,5\n"
"7 10 7 0\n"
"0 2 7 2\n"
"7 10 7 5\n"
"0 7 8 6\n"
"0 2 8 7\n";
/* We make one mutation for each tree, over unary nodes if this exist */
const char *unary_ex_sites = "1.0 0\n"
"4.5 0\n"
"8.5 0\n";
const char *unary_ex_mutations = "0 2 1\n"
"1 6 1\n"
"2 5 1\n";
/* An example of a tree sequence with internally sampled nodes. */
/* TODO: find a way to draw these side-by-side */
/*
7
+-+-+
| 5
| +-++
| | 4
| | +++
| | | 3
| | |
| 1 2
|
0
8
+-+-+
| 5
| +-++
| | 4
| | +++
3 | | |
| | |
1 2 |
|
0
6
+-+-+
| 5
| +-++
| | 4
| | +++
| | | 3
| | |
| 1 2
|
0
*/
const char *internal_sample_ex_nodes = "1 0.0 0 -1\n"
"1 0.1 0 -1\n"
"1 0.1 0 -1\n"
"1 0.2 0 -1\n"
"0 0.4 0 -1\n"
"1 0.5 0 -1\n"
"0 0.7 0 -1\n"
"0 1.0 0 -1\n"
"0 1.2 0 -1\n";
const char *internal_sample_ex_edges = "2 8 4 0\n"
"0 10 4 2\n"
"0 2 4 3\n"
"8 10 4 3\n"
"0 10 5 1,4\n"
"8 10 6 0,5\n"
"0 2 7 0,5\n"
"2 8 8 3,5\n";
/* We make one mutation for each tree, some above the internal node */
const char *internal_sample_ex_sites = "1.0 0\n"
"4.5 0\n"
"8.5 0\n";
const char *internal_sample_ex_mutations = "0 2 1\n"
"1 5 1\n"
"2 5 1\n";
/* Simple utilities to parse text so we can write declaritive
* tests. This is not intended as a robust general input mechanism.
*/
static void
parse_nodes(const char *text, tsk_node_tbl_t *node_table)
{
int ret;
size_t c, k;
size_t MAX_LINE = 1024;
char line[MAX_LINE];
const char *whitespace = " \t";
char *p;
double time;
int flags, population, individual;
char *name;
c = 0;
while (text[c] != '\0') {
/* Fill in the line */
k = 0;
while (text[c] != '\n' && text[c] != '\0') {
CU_ASSERT_FATAL(k < MAX_LINE - 1);
line[k] = text[c];
c++;
k++;
}
if (text[c] == '\n') {
c++;
}
line[k] = '\0';
p = strtok(line, whitespace);
CU_ASSERT_FATAL(p != NULL);
flags = atoi(p);
p = strtok(NULL, whitespace);
CU_ASSERT_FATAL(p != NULL);
time = atof(p);
p = strtok(NULL, whitespace);
CU_ASSERT_FATAL(p != NULL);
population = atoi(p);
p = strtok(NULL, whitespace);
if (p == NULL) {
individual = -1;
} else {
individual = atoi(p);
p = strtok(NULL, whitespace);
}
if (p == NULL) {
name = "";
} else {
name = p;
}
ret = tsk_node_tbl_add_row(
node_table, flags, time, population, individual, name, strlen(name));
CU_ASSERT_FATAL(ret >= 0);
}
}
static void
parse_edges(const char *text, tsk_edge_tbl_t *edge_table)
{
int ret;
size_t c, k;
size_t MAX_LINE = 1024;
char line[MAX_LINE], sub_line[MAX_LINE];
const char *whitespace = " \t";
char *p, *q;
double left, right;
tsk_id_t parent, child;
uint32_t num_children;
c = 0;
while (text[c] != '\0') {
/* Fill in the line */
k = 0;
while (text[c] != '\n' && text[c] != '\0') {
CU_ASSERT_FATAL(k < MAX_LINE - 1);
line[k] = text[c];
c++;
k++;
}
if (text[c] == '\n') {
c++;
}
line[k] = '\0';
p = strtok(line, whitespace);
CU_ASSERT_FATAL(p != NULL);
left = atof(p);
p = strtok(NULL, whitespace);
CU_ASSERT_FATAL(p != NULL);
right = atof(p);
p = strtok(NULL, whitespace);
CU_ASSERT_FATAL(p != NULL);
parent = atoi(p);
num_children = 0;
p = strtok(NULL, whitespace);
CU_ASSERT_FATAL(p != NULL);
num_children = 1;
q = p;
while (*q != '\0') {
if (*q == ',') {
num_children++;
}
q++;
}
CU_ASSERT_FATAL(num_children >= 1);
strncpy(sub_line, p, MAX_LINE);
q = strtok(sub_line, ",");
for (k = 0; k < num_children; k++) {
CU_ASSERT_FATAL(q != NULL);
child = atoi(q);
ret = tsk_edge_tbl_add_row(edge_table, left, right, parent, child);
CU_ASSERT_FATAL(ret >= 0);
q = strtok(NULL, ",");
}
CU_ASSERT_FATAL(q == NULL);
}
}
static void
parse_sites(const char *text, tsk_site_tbl_t *site_table)
{
int ret;
size_t c, k;
size_t MAX_LINE = 1024;
char line[MAX_LINE];
double position;
char ancestral_state[MAX_LINE];
const char *whitespace = " \t";
char *p;
c = 0;
while (text[c] != '\0') {
/* Fill in the line */
k = 0;
while (text[c] != '\n' && text[c] != '\0') {
CU_ASSERT_FATAL(k < MAX_LINE - 1);
line[k] = text[c];
c++;
k++;
}
if (text[c] == '\n') {
c++;
}
line[k] = '\0';
p = strtok(line, whitespace);
CU_ASSERT_FATAL(p != NULL);
position = atof(p);
p = strtok(NULL, whitespace);
CU_ASSERT_FATAL(p != NULL);
strncpy(ancestral_state, p, MAX_LINE);
ret = tsk_site_tbl_add_row(
site_table, position, ancestral_state, strlen(ancestral_state), NULL, 0);
CU_ASSERT_FATAL(ret >= 0);
}
}
static void
parse_mutations(const char *text, tsk_mutation_tbl_t *mutation_table)
{
int ret;
size_t c, k;
size_t MAX_LINE = 1024;
char line[MAX_LINE];
const char *whitespace = " \t";
char *p;
tsk_id_t node;
tsk_id_t site;
tsk_id_t parent;
char derived_state[MAX_LINE];
c = 0;
while (text[c] != '\0') {
/* Fill in the line */
k = 0;
while (text[c] != '\n' && text[c] != '\0') {
CU_ASSERT_FATAL(k < MAX_LINE - 1);
line[k] = text[c];
c++;
k++;
}
if (text[c] == '\n') {
c++;
}
line[k] = '\0';
p = strtok(line, whitespace);
site = atoi(p);
CU_ASSERT_FATAL(p != NULL);
p = strtok(NULL, whitespace);
CU_ASSERT_FATAL(p != NULL);
node = atoi(p);
p = strtok(NULL, whitespace);
CU_ASSERT_FATAL(p != NULL);
strncpy(derived_state, p, MAX_LINE);
parent = TSK_NULL;
p = strtok(NULL, whitespace);
if (p != NULL) {
parent = atoi(p);
}
ret = tsk_mutation_tbl_add_row(mutation_table, site, node, parent, derived_state,
strlen(derived_state), NULL, 0);
CU_ASSERT_FATAL(ret >= 0);
}
}
static void
parse_individuals(const char *text, tsk_individual_tbl_t *individual_table)
{
int ret;
size_t c, k;
size_t MAX_LINE = 1024;
char line[MAX_LINE];
char sub_line[MAX_LINE];
const char *whitespace = " \t";
char *p, *q;
double location[MAX_LINE];
int location_len;
int flags;
char *name;
c = 0;
while (text[c] != '\0') {
/* Fill in the line */
k = 0;
while (text[c] != '\n' && text[c] != '\0') {
CU_ASSERT_FATAL(k < MAX_LINE - 1);
line[k] = text[c];
c++;
k++;
}
if (text[c] == '\n') {
c++;
}
line[k] = '\0';
p = strtok(line, whitespace);
CU_ASSERT_FATAL(p != NULL);
flags = atoi(p);
p = strtok(NULL, whitespace);
CU_ASSERT_FATAL(p != NULL);
// the locations are comma-separated
location_len = 1;
q = p;
while (*q != '\0') {
if (*q == ',') {
location_len++;
}
q++;
}
CU_ASSERT_FATAL(location_len >= 1);
strncpy(sub_line, p, MAX_LINE);
q = strtok(sub_line, ",");
for (k = 0; k < location_len; k++) {
CU_ASSERT_FATAL(q != NULL);
location[k] = atof(q);
q = strtok(NULL, ",");
}
CU_ASSERT_FATAL(q == NULL);
p = strtok(NULL, whitespace);
if (p == NULL) {
name = "";
} else {
name = p;
}
ret = tsk_individual_tbl_add_row(
individual_table, flags, location, location_len, name, strlen(name));
CU_ASSERT_FATAL(ret >= 0);
}
}
static void
tsk_treeseq_from_text(tsk_treeseq_t *ts, double sequence_length, const char *nodes,
const char *edges, const char *migrations, const char *sites, const char *mutations,
const char *individuals, const char *provenance)
{
int ret;
tsk_tbl_collection_t tables;
tsk_id_t max_population_id;
tsk_tbl_size_t j;
CU_ASSERT_FATAL(ts != NULL);
CU_ASSERT_FATAL(nodes != NULL);
CU_ASSERT_FATAL(edges != NULL);
/* Not supporting provenance here for now */
CU_ASSERT_FATAL(provenance == NULL);
ret = tsk_tbl_collection_init(&tables, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
tables.sequence_length = sequence_length;
parse_nodes(nodes, tables.nodes);
parse_edges(edges, tables.edges);
if (sites != NULL) {
parse_sites(sites, tables.sites);
}
if (mutations != NULL) {
parse_mutations(mutations, tables.mutations);
}
if (individuals != NULL) {
parse_individuals(individuals, tables.individuals);
}
/* We need to add in populations if they are referenced */
max_population_id = -1;
for (j = 0; j < tables.nodes->num_rows; j++) {
max_population_id = TSK_MAX(max_population_id, tables.nodes->population[j]);
}
if (max_population_id >= 0) {
for (j = 0; j <= (tsk_tbl_size_t) max_population_id; j++) {
ret = tsk_population_tbl_add_row(tables.populations, NULL, 0);
CU_ASSERT_EQUAL_FATAL(ret, j);
}
}
ret = tsk_treeseq_init(ts, &tables, TSK_BUILD_INDEXES);
/* tsk_treeseq_print_state(ts, stdout); */
/* printf("ret = %s\n", tsk_strerror(ret)); */
CU_ASSERT_EQUAL_FATAL(ret, 0);
tsk_tbl_collection_free(&tables);
}
static int
get_max_site_mutations(tsk_treeseq_t *ts)
{
int ret;
int max_mutations = 0;
size_t j;
tsk_site_t site;
for (j = 0; j < tsk_treeseq_get_num_sites(ts); j++) {
ret = tsk_treeseq_get_site(ts, j, &site);
CU_ASSERT_EQUAL_FATAL(ret, 0);
max_mutations = TSK_MAX(max_mutations, site.mutations_length);
}
return max_mutations;
}
static bool
multi_mutations_exist(tsk_treeseq_t *ts, size_t start, size_t end)
{
int ret;
size_t j;
tsk_site_t site;
for (j = 0; j < TSK_MIN(tsk_treeseq_get_num_sites(ts), end); j++) {
ret = tsk_treeseq_get_site(ts, j, &site);
CU_ASSERT_EQUAL_FATAL(ret, 0);
if (site.mutations_length > 1) {
return true;
}
}
return false;
}
static void
unsort_edges(tsk_edge_tbl_t *edges, size_t start)
{
size_t j, k;
size_t n = edges->num_rows - start;
tsk_edge_t *buff = malloc(n * sizeof(tsk_edge_t));
gsl_rng *rng = gsl_rng_init(gsl_rng_default);
CU_ASSERT_FATAL(edges != NULL);
CU_ASSERT_FATAL(rng != NULL);
gsl_rng_set(rng, 1);
for (j = 0; j < n; j++) {
k = start + j;
buff[j].left = edges->left[k];
buff[j].right = edges->right[k];
buff[j].parent = edges->parent[k];
buff[j].child = edges->child[k];
}
gsl_ran_shuffle(rng, buff, n, sizeof(tsk_edge_t));
for (j = 0; j < n; j++) {
k = start + j;
edges->left[k] = buff[j].left;
edges->right[k] = buff[j].right;
edges->parent[k] = buff[j].parent;
edges->child[k] = buff[j].child;
}
free(buff);
gsl_rng_free(rng);
}
static void
unsort_sites(tsk_site_tbl_t *sites, tsk_mutation_tbl_t *mutations)
{
double position;
char *ancestral_state = NULL;
size_t j, k, length;
if (sites->num_rows > 1) {
/* Swap the first two sites */
CU_ASSERT_EQUAL_FATAL(sites->ancestral_state_offset[0], 0);
position = sites->position[0];
length = sites->ancestral_state_offset[1];
/* Save a copy of the first ancestral state */
ancestral_state = malloc(length);
CU_ASSERT_FATAL(ancestral_state != NULL);
memcpy(ancestral_state, sites->ancestral_state, length);
/* Now write the ancestral state for the site 1 here */
k = 0;
for (j = sites->ancestral_state_offset[1]; j < sites->ancestral_state_offset[2];
j++) {
sites->ancestral_state[k] = sites->ancestral_state[j];
k++;
}
sites->ancestral_state_offset[1] = k;
memcpy(sites->ancestral_state + k, ancestral_state, length);
sites->position[0] = sites->position[1];
sites->position[1] = position;
/* Update the mutations for these sites */
j = 0;
while (j < mutations->num_rows && mutations->site[j] == 0) {
mutations->site[j] = 1;
j++;
}
while (j < mutations->num_rows && mutations->site[j] == 1) {
mutations->site[j] = 0;
j++;
}
}
tsk_safe_free(ancestral_state);
}
static void
add_individuals(tsk_treeseq_t *ts)
{
int ret;
int max_inds = 20;
tsk_id_t j;
int k = 0;
int ploidy = 2;
tsk_tbl_collection_t tables;
char *metadata = "abc";
size_t metadata_length = 3;
tsk_id_t *samples;
tsk_tbl_size_t num_samples = tsk_treeseq_get_num_samples(ts);
ret = tsk_treeseq_get_samples(ts, &samples);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_copy_tables(ts, &tables);
CU_ASSERT_EQUAL_FATAL(ret, 0);
tsk_individual_tbl_clear(tables.individuals);
memset(tables.nodes->individual, 0xff, tables.nodes->num_rows * sizeof(tsk_id_t));
k = 0;
for (j = 0; j < num_samples; j++) {
if ((k % ploidy) == 0) {
tsk_individual_tbl_add_row(
tables.individuals, (uint32_t) k, NULL, 0, metadata, metadata_length);
CU_ASSERT_TRUE(ret >= 0)
}
tables.nodes->individual[samples[j]] = k / ploidy;
k += 1;
if (k >= ploidy * max_inds) {
break;
}
}
ret = tsk_treeseq_free(ts);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_init(ts, &tables, TSK_BUILD_INDEXES);
CU_ASSERT_EQUAL_FATAL(ret, 0);
tsk_tbl_collection_free(&tables);
}
static void
verify_nodes_equal(tsk_node_t *n1, tsk_node_t *n2)
{
double eps = 1e-6;
CU_ASSERT_DOUBLE_EQUAL_FATAL(n1->time, n1->time, eps);
CU_ASSERT_EQUAL_FATAL(n1->population, n2->population);
CU_ASSERT_EQUAL_FATAL(n1->flags, n2->flags);
CU_ASSERT_FATAL(n1->metadata_length == n2->metadata_length);
CU_ASSERT_NSTRING_EQUAL_FATAL(n1->metadata, n2->metadata, n1->metadata_length);
}
static void
verify_edges_equal(tsk_edge_t *r1, tsk_edge_t *r2, double scale)
{
double eps = 1e-6;
CU_ASSERT_DOUBLE_EQUAL_FATAL(r1->left * scale, r2->left, eps);
CU_ASSERT_DOUBLE_EQUAL_FATAL(r1->right * scale, r2->right, eps);
CU_ASSERT_EQUAL_FATAL(r1->parent, r2->parent);
CU_ASSERT_EQUAL_FATAL(r1->child, r2->child);
}
static void
verify_migrations_equal(tsk_migration_t *r1, tsk_migration_t *r2, double scale)
{
double eps = 1e-6;
CU_ASSERT_DOUBLE_EQUAL_FATAL(r1->left * scale, r2->left, eps);
CU_ASSERT_DOUBLE_EQUAL_FATAL(r1->right * scale, r2->right, eps);
CU_ASSERT_DOUBLE_EQUAL_FATAL(r1->time, r2->time, eps);
CU_ASSERT_EQUAL_FATAL(r1->node, r2->node);
CU_ASSERT_EQUAL_FATAL(r1->source, r2->source);
CU_ASSERT_EQUAL_FATAL(r1->dest, r2->dest);
}
static void
verify_provenances_equal(tsk_provenance_t *p1, tsk_provenance_t *p2)
{
CU_ASSERT_FATAL(p1->timestamp_length == p2->timestamp_length);
CU_ASSERT_NSTRING_EQUAL_FATAL(p1->timestamp, p2->timestamp, p1->timestamp_length);
CU_ASSERT_FATAL(p1->record_length == p2->record_length);
CU_ASSERT_NSTRING_EQUAL_FATAL(p1->record, p2->record, p1->record_length);
}
static void
verify_individuals_equal(tsk_individual_t *i1, tsk_individual_t *i2)
{
tsk_tbl_size_t j;
CU_ASSERT_FATAL(i1->id == i2->id);
CU_ASSERT_FATAL(i1->flags == i2->flags);
CU_ASSERT_FATAL(i1->metadata_length == i2->metadata_length);
CU_ASSERT_NSTRING_EQUAL_FATAL(i1->metadata, i2->metadata, i1->metadata_length);
CU_ASSERT_FATAL(i1->location_length == i2->location_length);
for (j = 0; j < i1->location_length; j++) {
CU_ASSERT_EQUAL_FATAL(i1->location[j], i2->location[j]);
}
}
static void
verify_populations_equal(tsk_population_t *p1, tsk_population_t *p2)
{
CU_ASSERT_FATAL(p1->id == p2->id);
CU_ASSERT_FATAL(p1->metadata_length == p2->metadata_length);
CU_ASSERT_NSTRING_EQUAL_FATAL(p1->metadata, p2->metadata, p1->metadata_length);
}
static tsk_tree_t *
get_tree_list(tsk_treeseq_t *ts)
{
int ret;
tsk_tree_t t, *trees;
size_t num_trees;
num_trees = tsk_treeseq_get_num_trees(ts);
ret = tsk_tree_init(&t, ts, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
trees = malloc(num_trees * sizeof(tsk_tree_t));
CU_ASSERT_FATAL(trees != NULL);
for (ret = tsk_tree_first(&t); ret == 1; ret = tsk_tree_next(&t)) {
CU_ASSERT_FATAL(t.index < num_trees);
ret = tsk_tree_init(&trees[t.index], ts, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_tree_copy(&trees[t.index], &t);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_tree_equal(&trees[t.index], &t);
CU_ASSERT_EQUAL_FATAL(ret, 0);
/* Make sure the left and right coordinates are also OK */
CU_ASSERT_DOUBLE_EQUAL(trees[t.index].left, t.left, 1e-6);
CU_ASSERT_DOUBLE_EQUAL(trees[t.index].right, t.right, 1e-6);
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_tree_free(&t);
CU_ASSERT_EQUAL_FATAL(ret, 0);
return trees;
}
static void
verify_tree_next_prev(tsk_treeseq_t *ts)
{
int ret;
tsk_tree_t *trees, t;
size_t j;
size_t num_trees = tsk_treeseq_get_num_trees(ts);
trees = get_tree_list(ts);
ret = tsk_tree_init(&t, ts, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
/* Single forward pass */
j = 0;
for (ret = tsk_tree_first(&t); ret == 1; ret = tsk_tree_next(&t)) {
CU_ASSERT_EQUAL_FATAL(j, t.index);
ret = tsk_tree_equal(&t, &trees[t.index]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
j++;
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(j, num_trees);
/* Single reverse pass */
j = num_trees;
for (ret = tsk_tree_last(&t); ret == 1; ret = tsk_tree_prev(&t)) {
CU_ASSERT_EQUAL_FATAL(j - 1, t.index);
ret = tsk_tree_equal(&t, &trees[t.index]);
if (ret != 0) {
printf("trees differ\n");
printf("REVERSE tree::\n");
tsk_tree_print_state(&t, stdout);
printf("FORWARD tree::\n");
tsk_tree_print_state(&trees[t.index], stdout);
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
j--;
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(j, 0);
/* Full forward, then reverse */
j = 0;
for (ret = tsk_tree_first(&t); ret == 1; ret = tsk_tree_next(&t)) {
CU_ASSERT_EQUAL_FATAL(j, t.index);
ret = tsk_tree_equal(&t, &trees[t.index]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
j++;
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(j, num_trees);
j--;
while ((ret = tsk_tree_prev(&t)) == 1) {
CU_ASSERT_EQUAL_FATAL(j - 1, t.index);
ret = tsk_tree_equal(&t, &trees[t.index]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
j--;
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(j, 0);
CU_ASSERT_EQUAL_FATAL(t.index, 0);
/* Calling prev should return 0 and have no effect. */
for (j = 0; j < 10; j++) {
ret = tsk_tree_prev(&t);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(t.index, 0);
ret = tsk_tree_equal(&t, &trees[t.index]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
}
/* Full reverse then forward */
j = num_trees;
for (ret = tsk_tree_last(&t); ret == 1; ret = tsk_tree_prev(&t)) {
CU_ASSERT_EQUAL_FATAL(j - 1, t.index);
ret = tsk_tree_equal(&t, &trees[t.index]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
j--;
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(j, 0);
j++;
while ((ret = tsk_tree_next(&t)) == 1) {
CU_ASSERT_EQUAL_FATAL(j, t.index);
ret = tsk_tree_equal(&t, &trees[t.index]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
j++;
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(j, num_trees);
CU_ASSERT_EQUAL_FATAL(t.index, num_trees - 1);
/* Calling next should return 0 and have no effect. */
for (j = 0; j < 10; j++) {
ret = tsk_tree_next(&t);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(t.index, num_trees - 1);
ret = tsk_tree_equal(&t, &trees[t.index]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
}
/* Do a zigzagging traversal */
ret = tsk_tree_first(&t);
CU_ASSERT_EQUAL_FATAL(ret, 1);
for (j = 1; j < TSK_MIN(10, num_trees / 2); j++) {
while (t.index < num_trees - j) {
ret = tsk_tree_next(&t);
CU_ASSERT_EQUAL_FATAL(ret, 1);
}
CU_ASSERT_EQUAL_FATAL(t.index, num_trees - j);
ret = tsk_tree_equal(&t, &trees[t.index]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
while (t.index > j) {
ret = tsk_tree_prev(&t);
CU_ASSERT_EQUAL_FATAL(ret, 1);
}
CU_ASSERT_EQUAL_FATAL(t.index, j);
ret = tsk_tree_equal(&t, &trees[t.index]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
}
/* Free the trees. */
ret = tsk_tree_free(&t);
CU_ASSERT_EQUAL_FATAL(ret, 0);
for (j = 0; j < tsk_treeseq_get_num_trees(ts); j++) {
ret = tsk_tree_free(&trees[j]);
}
free(trees);
}
static void
verify_vargen(tsk_treeseq_t *ts)
{
int ret;
tsk_vargen_t vargen;
size_t num_samples = tsk_treeseq_get_num_samples(ts);
size_t num_sites = tsk_treeseq_get_num_sites(ts);
tsk_variant_t *var;
size_t j, k, f, s;
int flags[] = { 0, TSK_16_BIT_GENOTYPES };
tsk_id_t *samples[] = { NULL, NULL };
ret = tsk_treeseq_get_samples(ts, samples);
CU_ASSERT_EQUAL_FATAL(ret, 0);
for (s = 0; s < 2; s++) {
for (f = 0; f < sizeof(flags) / sizeof(*flags); f++) {
ret = tsk_vargen_init(&vargen, ts, samples[s], num_samples, flags[f]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
tsk_vargen_print_state(&vargen, _devnull);
j = 0;
while ((ret = tsk_vargen_next(&vargen, &var)) == 1) {
CU_ASSERT_EQUAL(var->site->id, j);
if (var->site->mutations_length == 0) {
CU_ASSERT_EQUAL(var->num_alleles, 1);
} else {
CU_ASSERT_TRUE(var->num_alleles > 1);
}
CU_ASSERT_EQUAL(
var->allele_lengths[0], var->site->ancestral_state_length);
CU_ASSERT_NSTRING_EQUAL_FATAL(
var->alleles[0], var->site->ancestral_state, var->allele_lengths[0]);
for (k = 0; k < var->num_alleles; k++) {
CU_ASSERT_TRUE(var->allele_lengths[k] >= 0);
}
for (k = 0; k < num_samples; k++) {
if (flags[f] == TSK_16_BIT_GENOTYPES) {
CU_ASSERT(var->genotypes.u16[k] <= var->num_alleles);
} else {
CU_ASSERT(var->genotypes.u8[k] <= var->num_alleles);
}
}
j++;
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL(j, num_sites);
CU_ASSERT_EQUAL_FATAL(tsk_vargen_next(&vargen, &var), 0);
ret = tsk_vargen_free(&vargen);
CU_ASSERT_EQUAL_FATAL(ret, 0);
}
}
}
static void
verify_stats(tsk_treeseq_t *ts)
{
int ret;
uint32_t num_samples = tsk_treeseq_get_num_samples(ts);
tsk_id_t *samples;
uint32_t j;
double pi;
int max_site_mutations = get_max_site_mutations(ts);
ret = tsk_treeseq_get_pairwise_diversity(ts, NULL, 0, &pi);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_PARAM_VALUE);
ret = tsk_treeseq_get_pairwise_diversity(ts, NULL, 1, &pi);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_PARAM_VALUE);
ret = tsk_treeseq_get_pairwise_diversity(ts, NULL, num_samples + 1, &pi);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_PARAM_VALUE);
ret = tsk_treeseq_get_samples(ts, &samples);
CU_ASSERT_EQUAL_FATAL(ret, 0);
for (j = 2; j < num_samples; j++) {
ret = tsk_treeseq_get_pairwise_diversity(ts, samples, j, &pi);
if (max_site_mutations <= 1) {
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_TRUE_FATAL(pi >= 0);
} else {
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);
}
}
}
/* FIXME: this test is weak and should check the return value somehow.
* We should also have simplest and single tree tests along with separate
* tests for the error conditions. This should be done as part of the general
* stats framework.
*/
static void
verify_genealogical_nearest_neighbours(tsk_treeseq_t *ts)
{
int ret;
tsk_id_t *samples;
tsk_id_t *sample_sets[2];
size_t sample_set_size[2];
size_t num_samples = tsk_treeseq_get_num_samples(ts);
double *A = malloc(2 * num_samples * sizeof(double));
CU_ASSERT_FATAL(A != NULL);
ret = tsk_treeseq_get_samples(ts, &samples);
CU_ASSERT_EQUAL_FATAL(ret, 0);
sample_sets[0] = samples;
sample_set_size[0] = num_samples / 2;
sample_sets[1] = samples + sample_set_size[0];
sample_set_size[1] = num_samples - sample_set_size[0];
ret = tsk_treeseq_genealogical_nearest_neighbours(
ts, samples, num_samples, sample_sets, sample_set_size, 2, 0, A);
CU_ASSERT_EQUAL_FATAL(ret, 0);
free(A);
}
/* FIXME: this test is weak and should check the return value somehow.
* We should also have simplest and single tree tests along with separate
* tests for the error conditions. This should be done as part of the general
* stats framework.
*/
static void
verify_mean_descendants(tsk_treeseq_t *ts)
{
int ret;
tsk_id_t *samples;
tsk_id_t *sample_sets[2];
size_t sample_set_size[2];
size_t num_samples = tsk_treeseq_get_num_samples(ts);
double *C = malloc(2 * tsk_treeseq_get_num_nodes(ts) * sizeof(double));
CU_ASSERT_FATAL(C != NULL);
ret = tsk_treeseq_get_samples(ts, &samples);
CU_ASSERT_EQUAL_FATAL(ret, 0);
sample_sets[0] = samples;
sample_set_size[0] = num_samples / 2;
sample_sets[1] = samples + sample_set_size[0];
sample_set_size[1] = num_samples - sample_set_size[0];
ret = tsk_treeseq_mean_descendants(ts, sample_sets, sample_set_size, 2, 0, C);
CU_ASSERT_EQUAL_FATAL(ret, 0);
/* Check some error conditions */
ret = tsk_treeseq_mean_descendants(ts, sample_sets, sample_set_size, 0, 0, C);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_PARAM_VALUE);
samples[0] = -1;
ret = tsk_treeseq_mean_descendants(ts, sample_sets, sample_set_size, 2, 0, C);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_OUT_OF_BOUNDS);
samples[0] = tsk_treeseq_get_num_nodes(ts) + 1;
ret = tsk_treeseq_mean_descendants(ts, sample_sets, sample_set_size, 2, 0, C);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_OUT_OF_BOUNDS);
free(C);
}
static void
verify_compute_mutation_parents(tsk_treeseq_t *ts)
{
int ret;
size_t size = tsk_treeseq_get_num_mutations(ts) * sizeof(tsk_id_t);
tsk_id_t *parent = malloc(size);
tsk_tbl_collection_t tables;
CU_ASSERT_FATAL(parent != NULL);
ret = tsk_treeseq_copy_tables(ts, &tables);
CU_ASSERT_EQUAL_FATAL(ret, 0);
memcpy(parent, tables.mutations->parent, size);
/* tsk_tbl_collection_print_state(&tables, stdout); */
/* Make sure the tables are actually updated */
memset(tables.mutations->parent, 0xff, size);
ret = tsk_tbl_collection_compute_mutation_parents(&tables, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(memcmp(parent, tables.mutations->parent, size), 0);
/* printf("after\n"); */
/* tsk_tbl_collection_print_state(&tables, stdout); */
free(parent);
tsk_tbl_collection_free(&tables);
}
static void
verify_individual_nodes(tsk_treeseq_t *ts)
{
int ret;
tsk_individual_t individual;
tsk_id_t k;
size_t num_nodes = tsk_treeseq_get_num_nodes(ts);
size_t num_individuals = tsk_treeseq_get_num_individuals(ts);
size_t j;
for (k = 0; k < (tsk_id_t) num_individuals; k++) {
ret = tsk_treeseq_get_individual(ts, k, &individual);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_FATAL(individual.nodes_length >= 0);
for (j = 0; j < individual.nodes_length; j++) {
CU_ASSERT_FATAL(individual.nodes[j] < num_nodes);
CU_ASSERT_EQUAL_FATAL(k, ts->tables->nodes->individual[individual.nodes[j]]);
}
}
}
/* When we keep all sites in simplify, the genotypes for the subset of the
* samples should be the same as the original */
static void
verify_simplify_genotypes(tsk_treeseq_t *ts, tsk_treeseq_t *subset, tsk_id_t *samples,
uint32_t num_samples, tsk_id_t *node_map)
{
int ret;
size_t m = tsk_treeseq_get_num_sites(ts);
tsk_vargen_t vargen, subset_vargen;
tsk_variant_t *variant, *subset_variant;
size_t j, k;
tsk_id_t *all_samples;
uint8_t a1, a2;
tsk_id_t *sample_index_map;
tsk_treeseq_get_sample_index_map(ts, &sample_index_map);
/* tsk_treeseq_print_state(ts, stdout); */
/* tsk_treeseq_print_state(subset, stdout); */
ret = tsk_vargen_init(&vargen, ts, NULL, 0, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_vargen_init(&subset_vargen, subset, NULL, 0, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(m, tsk_treeseq_get_num_sites(subset));
tsk_treeseq_get_samples(ts, &all_samples);
for (j = 0; j < m; j++) {
ret = tsk_vargen_next(&vargen, &variant);
CU_ASSERT_EQUAL_FATAL(ret, 1);
ret = tsk_vargen_next(&subset_vargen, &subset_variant);
CU_ASSERT_EQUAL_FATAL(ret, 1);
CU_ASSERT_EQUAL(variant->site->id, j)
CU_ASSERT_EQUAL(subset_variant->site->id, j)
CU_ASSERT_EQUAL(variant->site->position, subset_variant->site->position);
for (k = 0; k < num_samples; k++) {
CU_ASSERT_FATAL(sample_index_map[samples[k]] < ts->num_samples);
a1 = variant->genotypes.u8[sample_index_map[samples[k]]];
a2 = subset_variant->genotypes.u8[k];
/* printf("a1 = %d, a2 = %d\n", a1, a2); */
/* printf("k = %d original node = %d " */
/* "original_index = %d a1=%.*s a2=%.*s\n", */
/* (int) k, samples[k], sample_index_map[samples[k]], */
/* variant->allele_lengths[a1], variant->alleles[a1], */
/* subset_variant->allele_lengths[a2], subset_variant->alleles[a2]);
*/
CU_ASSERT_FATAL(a1 < variant->num_alleles);
CU_ASSERT_FATAL(a2 < subset_variant->num_alleles);
CU_ASSERT_EQUAL_FATAL(
variant->allele_lengths[a1], subset_variant->allele_lengths[a2]);
CU_ASSERT_NSTRING_EQUAL_FATAL(variant->alleles[a1],
subset_variant->alleles[a2], variant->allele_lengths[a1]);
}
}
tsk_vargen_free(&vargen);
tsk_vargen_free(&subset_vargen);
}
static void
verify_simplify_properties(tsk_treeseq_t *ts, tsk_treeseq_t *subset, tsk_id_t *samples,
uint32_t num_samples, tsk_id_t *node_map)
{
int ret;
tsk_node_t n1, n2;
tsk_tree_t full_tree, subset_tree;
tsk_site_t *tree_sites;
tsk_tbl_size_t tree_sites_length;
uint32_t j, k;
tsk_id_t u, mrca1, mrca2;
size_t total_sites;
CU_ASSERT_EQUAL(
tsk_treeseq_get_sequence_length(ts), tsk_treeseq_get_sequence_length(subset));
CU_ASSERT_EQUAL(tsk_treeseq_get_num_samples(subset), num_samples);
CU_ASSERT(tsk_treeseq_get_num_nodes(ts) >= tsk_treeseq_get_num_nodes(subset));
CU_ASSERT_EQUAL(tsk_treeseq_get_num_samples(subset), num_samples);
/* Check the sample properties */
for (j = 0; j < num_samples; j++) {
ret = tsk_treeseq_get_node(ts, samples[j], &n1);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL(node_map[samples[j]], j);
ret = tsk_treeseq_get_node(subset, node_map[samples[j]], &n2);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(n1.population, n2.population);
CU_ASSERT_EQUAL_FATAL(n1.time, n2.time);
CU_ASSERT_EQUAL_FATAL(n1.flags, n2.flags);
CU_ASSERT_EQUAL_FATAL(n1.metadata_length, n2.metadata_length);
CU_ASSERT_NSTRING_EQUAL(n1.metadata, n2.metadata, n2.metadata_length);
}
/* Check that node mappings are correct */
for (j = 0; j < tsk_treeseq_get_num_nodes(ts); j++) {
ret = tsk_treeseq_get_node(ts, j, &n1);
CU_ASSERT_EQUAL_FATAL(ret, 0);
if (node_map[j] != TSK_NULL) {
ret = tsk_treeseq_get_node(subset, node_map[j], &n2);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(n1.population, n2.population);
CU_ASSERT_EQUAL_FATAL(n1.time, n2.time);
CU_ASSERT_EQUAL_FATAL(n1.flags, n2.flags);
CU_ASSERT_EQUAL_FATAL(n1.metadata_length, n2.metadata_length);
CU_ASSERT_NSTRING_EQUAL(n1.metadata, n2.metadata, n2.metadata_length);
}
}
if (num_samples == 0) {
CU_ASSERT_EQUAL(tsk_treeseq_get_num_edges(subset), 0);
CU_ASSERT_EQUAL(tsk_treeseq_get_num_nodes(subset), 0);
} else if (num_samples == 1) {
CU_ASSERT_EQUAL(tsk_treeseq_get_num_edges(subset), 0);
CU_ASSERT_EQUAL(tsk_treeseq_get_num_nodes(subset), 1);
}
/* Check the pairwise MRCAs */
ret = tsk_tree_init(&full_tree, ts, 0);
CU_ASSERT_EQUAL(ret, 0);
ret = tsk_tree_init(&subset_tree, subset, 0);
CU_ASSERT_EQUAL(ret, 0);
ret = tsk_tree_first(&full_tree);
CU_ASSERT_EQUAL(ret, 1);
ret = tsk_tree_first(&subset_tree);
CU_ASSERT_EQUAL(ret, 1);
total_sites = 0;
while (1) {
while (full_tree.right <= subset_tree.right) {
for (j = 0; j < num_samples; j++) {
for (k = j + 1; k < num_samples; k++) {
ret = tsk_tree_get_mrca(&full_tree, samples[j], samples[k], &mrca1);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_tree_get_mrca(&subset_tree, node_map[samples[j]],
node_map[samples[k]], &mrca2);
CU_ASSERT_EQUAL_FATAL(ret, 0);
if (mrca1 == TSK_NULL) {
CU_ASSERT_EQUAL_FATAL(mrca2, TSK_NULL);
} else {
CU_ASSERT_EQUAL(node_map[mrca1], mrca2);
}
}
}
ret = tsk_tree_next(&full_tree);
CU_ASSERT_FATAL(ret >= 0);
if (ret != 1) {
break;
}
}
/* Check the sites in this tree */
ret = tsk_tree_get_sites(&subset_tree, &tree_sites, &tree_sites_length);
CU_ASSERT_EQUAL_FATAL(ret, 0);
for (j = 0; j < tree_sites_length; j++) {
CU_ASSERT(subset_tree.left <= tree_sites[j].position);
CU_ASSERT(tree_sites[j].position < subset_tree.right);
for (k = 0; k < tree_sites[j].mutations_length; k++) {
ret = tsk_tree_get_parent(
&subset_tree, tree_sites[j].mutations[k].node, &u);
CU_ASSERT_EQUAL(ret, 0);
}
total_sites++;
}
ret = tsk_tree_next(&subset_tree);
if (ret != 1) {
break;
}
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL(tsk_treeseq_get_num_sites(subset), total_sites);
tsk_tree_free(&subset_tree);
tsk_tree_free(&full_tree);
verify_vargen(subset);
}
static void
verify_simplify(tsk_treeseq_t *ts)
{
int ret;
uint32_t n = tsk_treeseq_get_num_samples(ts);
uint32_t num_samples[] = { 0, 1, 2, 3, n / 2, n - 1, n };
size_t j;
tsk_id_t *sample;
tsk_id_t *node_map = malloc(tsk_treeseq_get_num_nodes(ts) * sizeof(tsk_id_t));
tsk_treeseq_t subset;
int flags = TSK_FILTER_SITES;
CU_ASSERT_FATAL(node_map != NULL);
ret = tsk_treeseq_get_samples(ts, &sample);
CU_ASSERT_EQUAL_FATAL(ret, 0);
if (tsk_treeseq_get_num_migrations(ts) > 0) {
ret = tsk_treeseq_simplify(ts, sample, 2, 0, &subset, NULL);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_SIMPLIFY_MIGRATIONS_NOT_SUPPORTED);
/* Exiting early here because simplify isn't supported with migrations. */
goto out;
}
for (j = 0; j < sizeof(num_samples) / sizeof(uint32_t); j++) {
if (num_samples[j] <= n) {
ret = tsk_treeseq_simplify(
ts, sample, num_samples[j], flags, &subset, node_map);
/* printf("ret = %s\n", tsk_strerror(ret)); */
CU_ASSERT_EQUAL_FATAL(ret, 0);
verify_simplify_properties(ts, &subset, sample, num_samples[j], node_map);
tsk_treeseq_free(&subset);
/* Keep all sites */
ret = tsk_treeseq_simplify(ts, sample, num_samples[j], 0, &subset, node_map);
CU_ASSERT_EQUAL_FATAL(ret, 0);
verify_simplify_properties(ts, &subset, sample, num_samples[j], node_map);
verify_simplify_genotypes(ts, &subset, sample, num_samples[j], node_map);
tsk_treeseq_free(&subset);
}
}
out:
free(node_map);
}
static void
verify_reduce_topology(tsk_treeseq_t *ts)
{
int ret;
size_t j;
tsk_id_t *sample;
tsk_treeseq_t reduced;
tsk_edge_t edge;
double *X;
size_t num_sites;
size_t n = tsk_treeseq_get_num_samples(ts);
int flags = TSK_REDUCE_TO_SITE_TOPOLOGY;
ret = tsk_treeseq_get_samples(ts, &sample);
CU_ASSERT_EQUAL_FATAL(ret, 0);
if (tsk_treeseq_get_num_migrations(ts) > 0) {
ret = tsk_treeseq_simplify(ts, sample, 2, flags, &reduced, NULL);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_SIMPLIFY_MIGRATIONS_NOT_SUPPORTED);
return;
}
ret = tsk_treeseq_simplify(ts, sample, n, flags, &reduced, NULL);
CU_ASSERT_EQUAL_FATAL(ret, 0);
X = reduced.tables->sites->position;
num_sites = reduced.tables->sites->num_rows;
if (num_sites == 0) {
CU_ASSERT_EQUAL_FATAL(tsk_treeseq_get_num_edges(&reduced), 0);
}
for (j = 0; j < tsk_treeseq_get_num_edges(&reduced); j++) {
ret = tsk_treeseq_get_edge(&reduced, j, &edge);
CU_ASSERT_EQUAL_FATAL(ret, 0);
if (edge.left != 0) {
CU_ASSERT_EQUAL_FATAL(
edge.left, X[tsk_search_sorted(X, num_sites, edge.left)]);
}
if (edge.right != tsk_treeseq_get_sequence_length(&reduced)) {
CU_ASSERT_EQUAL_FATAL(
edge.right, X[tsk_search_sorted(X, num_sites, edge.right)]);
}
}
tsk_treeseq_free(&reduced);
}
/* Utility function to return a tree sequence for testing. It is the
* callers responsilibility to free all memory.
*/
static tsk_treeseq_t *
get_example_tree_sequence(uint32_t num_samples, uint32_t num_historical_samples,
uint32_t num_loci, double sequence_length, double recombination_rate,
double mutation_rate, uint32_t num_bottlenecks, bottleneck_desc_t *bottlenecks,
int alphabet)
{
return NULL;
}
tsk_treeseq_t **
get_example_nonbinary_tree_sequences(void)
{
return NULL;
}
tsk_treeseq_t *
make_recurrent_and_back_mutations_copy(tsk_treeseq_t *ts)
{
return NULL;
}
tsk_treeseq_t *
make_permuted_nodes_copy(tsk_treeseq_t *ts)
{
return NULL;
}
/* Insert some gaps into the specified tree sequence, i.e., positions
* that no edge covers. */
tsk_treeseq_t *
make_gappy_copy(tsk_treeseq_t *ts)
{
return NULL;
}
/* Return a copy of the tree sequence after deleting half of its edges.
*/
tsk_treeseq_t *
make_decapitated_copy(tsk_treeseq_t *ts)
{
return NULL;
}
tsk_treeseq_t *
make_multichar_mutations_copy(tsk_treeseq_t *ts)
{
return NULL;
}
tsk_treeseq_t **
get_example_tree_sequences(int include_nonbinary)
{
size_t max_examples = 1024;
tsk_treeseq_t **ret = malloc(max_examples * sizeof(tsk_treeseq_t *));
ret[0] = NULL;
return ret;
}
static void
verify_vcf_converter(tsk_treeseq_t *ts, unsigned int ploidy)
{
int ret;
char *str = NULL;
tsk_vcf_converter_t vc;
unsigned int num_variants;
ret = tsk_vcf_converter_init(&vc, ts, ploidy, "chr1234");
CU_ASSERT_FATAL(ret == 0);
tsk_vcf_converter_print_state(&vc, _devnull);
ret = tsk_vcf_converter_get_header(&vc, &str);
CU_ASSERT_EQUAL(ret, 0);
CU_ASSERT_NSTRING_EQUAL("##", str, 2);
num_variants = 0;
while ((ret = tsk_vcf_converter_next(&vc, &str)) == 1) {
CU_ASSERT_NSTRING_EQUAL("chr1234\t", str, 2);
num_variants++;
}
CU_ASSERT_EQUAL(ret, 0);
CU_ASSERT_TRUE(num_variants == tsk_treeseq_get_num_mutations(ts));
tsk_vcf_converter_free(&vc);
}
static void
test_node_metadata(void)
{
const char *nodes = "1 0 0 -1 n1\n"
"1 0 0 -1 n2\n"
"0 1 0 -1 A_much_longer_name\n"
"0 1 0 -1\n"
"0 1 0 -1 n4";
const char *edges = "0 1 2 0,1\n";
tsk_treeseq_t ts;
int ret;
tsk_node_t node;
tsk_treeseq_from_text(&ts, 1, nodes, edges, NULL, NULL, NULL, NULL, NULL);
CU_ASSERT_EQUAL(tsk_treeseq_get_num_samples(&ts), 2);
CU_ASSERT_EQUAL(tsk_treeseq_get_num_nodes(&ts), 5);
ret = tsk_treeseq_get_node(&ts, 0, &node);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_NSTRING_EQUAL(node.metadata, "n1", 2);
ret = tsk_treeseq_get_node(&ts, 1, &node);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_NSTRING_EQUAL(node.metadata, "n2", 2);
ret = tsk_treeseq_get_node(&ts, 2, &node);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_NSTRING_EQUAL(node.metadata, "A_much_longer_name", 18);
ret = tsk_treeseq_get_node(&ts, 3, &node);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_NSTRING_EQUAL(node.metadata, "", 0);
ret = tsk_treeseq_get_node(&ts, 4, &node);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_NSTRING_EQUAL(node.metadata, "n4", 2);
tsk_treeseq_free(&ts);
}
static void
verify_trees_consistent(tsk_treeseq_t *ts)
{
int ret;
size_t num_trees;
tsk_tree_t tree;
ret = tsk_tree_init(&tree, ts, 0);
CU_ASSERT_EQUAL(ret, 0);
num_trees = 0;
for (ret = tsk_tree_first(&tree); ret == 1; ret = tsk_tree_next(&tree)) {
tsk_tree_print_state(&tree, _devnull);
CU_ASSERT_EQUAL(tree.index, num_trees);
num_trees++;
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL(tsk_treeseq_get_num_trees(ts), num_trees);
tsk_tree_free(&tree);
}
static void
verify_ld(tsk_treeseq_t *ts)
{
int ret;
size_t num_sites = tsk_treeseq_get_num_sites(ts);
tsk_site_t *sites = malloc(num_sites * sizeof(tsk_site_t));
int *num_site_mutations = malloc(num_sites * sizeof(int));
tsk_ld_calc_t ld_calc;
double *r2, *r2_prime, x;
size_t j, num_r2_values;
double eps = 1e-6;
r2 = calloc(num_sites, sizeof(double));
r2_prime = calloc(num_sites, sizeof(double));
CU_ASSERT_FATAL(r2 != NULL);
CU_ASSERT_FATAL(r2_prime != NULL);
CU_ASSERT_FATAL(sites != NULL);
CU_ASSERT_FATAL(num_site_mutations != NULL);
ret = tsk_ld_calc_init(&ld_calc, ts);
CU_ASSERT_EQUAL_FATAL(ret, 0);
tsk_ld_calc_print_state(&ld_calc, _devnull);
for (j = 0; j < num_sites; j++) {
ret = tsk_treeseq_get_site(ts, j, sites + j);
CU_ASSERT_EQUAL_FATAL(ret, 0);
num_site_mutations[j] = sites[j].mutations_length;
ret = tsk_ld_calc_get_r2(&ld_calc, j, j, &x);
if (num_site_mutations[j] <= 1) {
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_DOUBLE_EQUAL_FATAL(x, 1.0, eps);
} else {
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);
}
}
if (num_sites > 0) {
/* Some checks in the forward direction */
ret = tsk_ld_calc_get_r2_array(
&ld_calc, 0, TSK_DIR_FORWARD, num_sites, DBL_MAX, r2, &num_r2_values);
if (multi_mutations_exist(ts, 0, num_sites)) {
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);
} else {
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(num_r2_values, num_sites - 1);
}
tsk_ld_calc_print_state(&ld_calc, _devnull);
ret = tsk_ld_calc_get_r2_array(&ld_calc, num_sites - 2, TSK_DIR_FORWARD,
num_sites, DBL_MAX, r2_prime, &num_r2_values);
if (multi_mutations_exist(ts, num_sites - 2, num_sites)) {
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);
} else {
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(num_r2_values, 1);
}
tsk_ld_calc_print_state(&ld_calc, _devnull);
ret = tsk_ld_calc_get_r2_array(
&ld_calc, 0, TSK_DIR_FORWARD, num_sites, DBL_MAX, r2_prime, &num_r2_values);
if (multi_mutations_exist(ts, 0, num_sites)) {
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);
} else {
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(num_r2_values, num_sites - 1);
tsk_ld_calc_print_state(&ld_calc, _devnull);
for (j = 0; j < num_r2_values; j++) {
CU_ASSERT_EQUAL_FATAL(r2[j], r2_prime[j]);
ret = tsk_ld_calc_get_r2(&ld_calc, 0, j + 1, &x);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_DOUBLE_EQUAL_FATAL(r2[j], x, eps);
}
}
/* Some checks in the reverse direction */
ret = tsk_ld_calc_get_r2_array(&ld_calc, num_sites - 1, TSK_DIR_REVERSE,
num_sites, DBL_MAX, r2, &num_r2_values);
if (multi_mutations_exist(ts, 0, num_sites)) {
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);
} else {
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(num_r2_values, num_sites - 1);
}
tsk_ld_calc_print_state(&ld_calc, _devnull);
ret = tsk_ld_calc_get_r2_array(
&ld_calc, 1, TSK_DIR_REVERSE, num_sites, DBL_MAX, r2_prime, &num_r2_values);
if (multi_mutations_exist(ts, 0, 1)) {
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);
} else {
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(num_r2_values, 1);
}
tsk_ld_calc_print_state(&ld_calc, _devnull);
ret = tsk_ld_calc_get_r2_array(&ld_calc, num_sites - 1, TSK_DIR_REVERSE,
num_sites, DBL_MAX, r2_prime, &num_r2_values);
if (multi_mutations_exist(ts, 0, num_sites)) {
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);
} else {
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(num_r2_values, num_sites - 1);
tsk_ld_calc_print_state(&ld_calc, _devnull);
for (j = 0; j < num_r2_values; j++) {
CU_ASSERT_EQUAL_FATAL(r2[j], r2_prime[j]);
ret = tsk_ld_calc_get_r2(&ld_calc, num_sites - 1, num_sites - j - 2, &x);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_DOUBLE_EQUAL_FATAL(r2[j], x, eps);
}
}
/* Check some error conditions */
ret = tsk_ld_calc_get_r2_array(
&ld_calc, 0, 0, num_sites, DBL_MAX, r2, &num_r2_values);
CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_PARAM_VALUE);
}
if (num_sites > 3) {
/* Check for some basic distance calculations */
j = num_sites / 2;
x = sites[j + 1].position - sites[j].position;
ret = tsk_ld_calc_get_r2_array(
&ld_calc, j, TSK_DIR_FORWARD, num_sites, x, r2, &num_r2_values);
if (multi_mutations_exist(ts, j, num_sites)) {
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);
} else {
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(num_r2_values, 1);
}
x = sites[j].position - sites[j - 1].position;
ret = tsk_ld_calc_get_r2_array(
&ld_calc, j, TSK_DIR_REVERSE, num_sites, x, r2, &num_r2_values);
if (multi_mutations_exist(ts, 0, j + 1)) {
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_ONLY_INFINITE_SITES);
} else {
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(num_r2_values, 1);
}
}
/* Check some error conditions */
for (j = num_sites; j < num_sites + 2; j++) {
ret = tsk_ld_calc_get_r2_array(
&ld_calc, j, TSK_DIR_FORWARD, num_sites, DBL_MAX, r2, &num_r2_values);
CU_ASSERT_EQUAL(ret, TSK_ERR_OUT_OF_BOUNDS);
ret = tsk_ld_calc_get_r2(&ld_calc, j, 0, r2);
CU_ASSERT_EQUAL(ret, TSK_ERR_OUT_OF_BOUNDS);
ret = tsk_ld_calc_get_r2(&ld_calc, 0, j, r2);
CU_ASSERT_EQUAL(ret, TSK_ERR_OUT_OF_BOUNDS);
}
tsk_ld_calc_free(&ld_calc);
free(r2);
free(r2_prime);
free(sites);
free(num_site_mutations);
}
static void
verify_empty_tree_sequence(tsk_treeseq_t *ts, double sequence_length)
{
CU_ASSERT_EQUAL(tsk_treeseq_get_num_edges(ts), 0);
CU_ASSERT_EQUAL(tsk_treeseq_get_num_mutations(ts), 0);
CU_ASSERT_EQUAL(tsk_treeseq_get_num_mutations(ts), 0);
CU_ASSERT_EQUAL(tsk_treeseq_get_num_migrations(ts), 0);
CU_ASSERT_EQUAL(tsk_treeseq_get_num_samples(ts), 0);
CU_ASSERT_EQUAL(tsk_treeseq_get_sequence_length(ts), sequence_length);
CU_ASSERT_EQUAL(tsk_treeseq_get_num_trees(ts), 1);
verify_trees_consistent(ts);
verify_ld(ts);
verify_stats(ts);
verify_vargen(ts);
verify_vcf_converter(ts, 1);
}
static void
verify_sample_sets_for_tree(tsk_tree_t *tree)
{
int ret, stack_top, j;
tsk_id_t u, v, n, num_nodes, num_samples;
size_t tmp;
tsk_id_t *stack, *samples;
tsk_treeseq_t *ts = tree->tree_sequence;
tsk_id_t *sample_index_map = ts->sample_index_map;
const tsk_id_t *list_left = tree->left_sample;
const tsk_id_t *list_right = tree->right_sample;
const tsk_id_t *list_next = tree->next_sample;
tsk_id_t stop, sample_index;
n = tsk_treeseq_get_num_samples(ts);
num_nodes = tsk_treeseq_get_num_nodes(ts);
stack = malloc(n * sizeof(tsk_id_t));
samples = malloc(n * sizeof(tsk_id_t));
CU_ASSERT_FATAL(stack != NULL);
CU_ASSERT_FATAL(samples != NULL);
for (u = 0; u < num_nodes; u++) {
if (tree->left_child[u] == TSK_NULL && !tsk_treeseq_is_sample(ts, u)) {
CU_ASSERT_EQUAL(list_left[u], TSK_NULL);
CU_ASSERT_EQUAL(list_right[u], TSK_NULL);
} else {
stack_top = 0;
num_samples = 0;
stack[stack_top] = u;
while (stack_top >= 0) {
v = stack[stack_top];
stack_top--;
if (tsk_treeseq_is_sample(ts, v)) {
samples[num_samples] = v;
num_samples++;
}
for (v = tree->right_child[v]; v != TSK_NULL; v = tree->left_sib[v]) {
stack_top++;
stack[stack_top] = v;
}
}
ret = tsk_tree_get_num_samples(tree, u, &tmp);
CU_ASSERT_EQUAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(num_samples, tmp);
j = 0;
sample_index = list_left[u];
if (sample_index != TSK_NULL) {
stop = list_right[u];
while (true) {
CU_ASSERT_TRUE_FATAL(j < n);
CU_ASSERT_EQUAL_FATAL(sample_index, sample_index_map[samples[j]]);
j++;
if (sample_index == stop) {
break;
}
sample_index = list_next[sample_index];
}
}
CU_ASSERT_EQUAL_FATAL(j, num_samples);
}
}
free(stack);
free(samples);
}
static void
verify_sample_sets(tsk_treeseq_t *ts)
{
int ret;
tsk_tree_t t;
ret = tsk_tree_init(&t, ts, TSK_SAMPLE_COUNTS | TSK_SAMPLE_LISTS);
CU_ASSERT_EQUAL(ret, 0);
for (ret = tsk_tree_first(&t); ret == 1; ret = tsk_tree_next(&t)) {
verify_sample_sets_for_tree(&t);
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
for (ret = tsk_tree_last(&t); ret == 1; ret = tsk_tree_prev(&t)) {
verify_sample_sets_for_tree(&t);
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
tsk_tree_free(&t);
}
static void
verify_tree_equals(tsk_treeseq_t *ts)
{
int ret;
tsk_tree_t *trees, t;
size_t j, k;
tsk_treeseq_t *other_ts
= get_example_tree_sequence(10, 0, 100, 100.0, 1.0, 1.0, 0, NULL, 0);
int flags[] = { 0, TSK_SAMPLE_LISTS, TSK_SAMPLE_COUNTS,
TSK_SAMPLE_LISTS | TSK_SAMPLE_COUNTS };
trees = get_tree_list(ts);
ret = tsk_tree_init(&t, other_ts, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
for (j = 0; j < tsk_treeseq_get_num_trees(ts); j++) {
ret = tsk_tree_equal(&t, &trees[j]);
CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_PARAM_VALUE);
for (k = 0; k < tsk_treeseq_get_num_trees(ts); k++) {
ret = tsk_tree_equal(&trees[j], &trees[k]);
if (j == k) {
CU_ASSERT_EQUAL_FATAL(ret, 0);
} else {
CU_ASSERT_EQUAL_FATAL(ret, 1);
}
}
}
ret = tsk_tree_free(&t);
CU_ASSERT_EQUAL_FATAL(ret, 0);
for (j = 0; j < sizeof(flags) / sizeof(int); j++) {
ret = tsk_tree_init(&t, ts, flags[j]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
for (ret = tsk_tree_first(&t); ret == 1; ret = tsk_tree_next(&t)) {
for (k = 0; k < tsk_treeseq_get_num_trees(ts); k++) {
ret = tsk_tree_equal(&t, &trees[k]);
if (t.index == k) {
CU_ASSERT_EQUAL_FATAL(ret, 0);
} else {
CU_ASSERT_EQUAL_FATAL(ret, 1);
}
}
}
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_tree_free(&t);
CU_ASSERT_EQUAL(ret, 0);
}
for (j = 0; j < tsk_treeseq_get_num_trees(ts); j++) {
ret = tsk_tree_free(&trees[j]);
}
free(trees);
tsk_treeseq_free(other_ts);
free(other_ts);
}
static void
test_individual_nodes_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_individual_nodes(examples[j]);
add_individuals(examples[j]);
verify_individual_nodes(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
test_diff_iter_from_examples(void)
{
/* tsk_treeseq_t **examples = get_example_tree_sequences(1); */
/* uint32_t j; */
/* CU_ASSERT_FATAL(examples != NULL); */
/* for (j = 0; examples[j] != NULL; j++) { */
/* verify_tree_diffs(examples[j]); */
/* tsk_treeseq_free(examples[j]); */
/* free(examples[j]); */
/* } */
/* free(examples); */
}
static void
test_tree_iter_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_trees_consistent(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
test_sample_sets_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_sample_sets(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
test_tree_equals_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_tree_equals(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
test_next_prev_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_tree_next_prev(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
test_ld_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_ld(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
test_tsk_vargen_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_vargen(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
test_stats_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_stats(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
test_genealogical_nearest_neighbours_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_genealogical_nearest_neighbours(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
test_mean_descendants_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_mean_descendants(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
test_compute_mutation_parents_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_compute_mutation_parents(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
verify_simplify_errors(tsk_treeseq_t *ts)
{
int ret;
tsk_id_t *s;
tsk_id_t u;
tsk_treeseq_t subset;
tsk_id_t sample[2];
ret = tsk_treeseq_get_samples(ts, &s);
CU_ASSERT_EQUAL_FATAL(ret, 0);
memcpy(sample, s, 2 * sizeof(tsk_id_t));
for (u = 0; u < (tsk_id_t) tsk_treeseq_get_num_nodes(ts); u++) {
if (!tsk_treeseq_is_sample(ts, u)) {
sample[1] = u;
ret = tsk_treeseq_simplify(ts, sample, 2, 0, &subset, NULL);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_SAMPLES);
}
}
sample[0] = -1;
ret = tsk_treeseq_simplify(ts, sample, 2, 0, &subset, NULL);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_NODE_OUT_OF_BOUNDS);
sample[0] = s[0];
sample[1] = s[0];
ret = tsk_treeseq_simplify(ts, sample, 2, 0, &subset, NULL);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_DUPLICATE_SAMPLE);
}
static void
test_simplify_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_simplify(examples[j]);
if (tsk_treeseq_get_num_migrations(examples[j]) == 0) {
/* Migrations are not supported at the moment, so skip these tests
* rather than complicate them */
verify_simplify_errors(examples[j]);
}
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
test_reduce_topology_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_reduce_topology(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
verify_newick(tsk_treeseq_t *ts)
{
/* int ret, err; */
/* tsk_tree_t t; */
/* tsk_id_t root; */
/* size_t precision = 4; */
/* size_t buffer_size = 1024 * 1024; */
/* char *newick = malloc(buffer_size); */
/* size_t j, size; */
/* CU_ASSERT_FATAL(newick != NULL); */
/* ret = tsk_tree_init(&t, ts, 0); */
/* CU_ASSERT_EQUAL_FATAL(ret, 0); */
/* ret = tsk_tree_first(&t); */
/* CU_ASSERT_FATAL(ret == 1); */
/* for (root = t.left_root; root != TSK_NULL; root = t.right_sib[root]) { */
/* err = tsk_tree_get_newick(&t, root, precision, 0, buffer_size, newick); */
/* CU_ASSERT_EQUAL_FATAL(err, 0); */
/* size = strlen(newick); */
/* CU_ASSERT_TRUE(size > 0); */
/* CU_ASSERT_TRUE(size < buffer_size); */
/* for (j = 0; j <= size; j++) { */
/* err = tsk_tree_get_newick(&t, root, precision, 0, j, newick); */
/* CU_ASSERT_EQUAL_FATAL(err, TSK_ERR_BUFFER_OVERFLOW); */
/* } */
/* err = tsk_tree_get_newick(&t, root, precision, 0, size + 1, newick); */
/* CU_ASSERT_EQUAL_FATAL(err, 0); */
/* } */
/* for (ret = tsk_tree_first(&t); ret == 1; ret = tsk_tree_next(&t)) { */
/* for (root = t.left_root; root != TSK_NULL; root = t.right_sib[root]) { */
/* err = tsk_tree_get_newick(&t, root, precision, 0, 0, NULL); */
/* CU_ASSERT_EQUAL_FATAL(err, TSK_ERR_BAD_PARAM_VALUE); */
/* err = tsk_tree_get_newick(&t, root, precision, 0, buffer_size, newick); */
/* CU_ASSERT_EQUAL_FATAL(err, 0); */
/* size = strlen(newick); */
/* CU_ASSERT_EQUAL(newick[size - 1], ';'); */
/* } */
/* } */
/* CU_ASSERT_EQUAL_FATAL(ret, 0); */
/* tsk_tree_free(&t); */
/* free(newick); */
}
static void
test_newick_from_examples(void)
{
tsk_treeseq_t **examples = get_example_tree_sequences(1);
uint32_t j;
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
verify_newick(examples[j]);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static void
verify_tree_sequences_equal(tsk_treeseq_t *ts1, tsk_treeseq_t *ts2,
bool check_migrations, bool check_mutations, bool check_provenance)
{
int ret, err1, err2;
size_t j;
tsk_edge_t r1, r2;
tsk_node_t n1, n2;
tsk_migration_t m1, m2;
tsk_provenance_t p1, p2;
tsk_individual_t i1, i2;
tsk_population_t pop1, pop2;
size_t num_mutations = tsk_treeseq_get_num_mutations(ts1);
tsk_site_t site_1, site_2;
tsk_mutation_t mutation_1, mutation_2;
tsk_tree_t t1, t2;
/* tsk_treeseq_print_state(ts1, stdout); */
/* tsk_treeseq_print_state(ts2, stdout); */
CU_ASSERT_EQUAL(tsk_treeseq_get_num_samples(ts1), tsk_treeseq_get_num_samples(ts2));
CU_ASSERT_EQUAL(
tsk_treeseq_get_sequence_length(ts1), tsk_treeseq_get_sequence_length(ts2));
CU_ASSERT_EQUAL(tsk_treeseq_get_num_edges(ts1), tsk_treeseq_get_num_edges(ts2));
CU_ASSERT_EQUAL(tsk_treeseq_get_num_nodes(ts1), tsk_treeseq_get_num_nodes(ts2));
CU_ASSERT_EQUAL(tsk_treeseq_get_num_trees(ts1), tsk_treeseq_get_num_trees(ts2));
for (j = 0; j < tsk_treeseq_get_num_nodes(ts1); j++) {
ret = tsk_treeseq_get_node(ts1, j, &n1);
CU_ASSERT_EQUAL(ret, 0);
ret = tsk_treeseq_get_node(ts2, j, &n2);
CU_ASSERT_EQUAL(ret, 0);
verify_nodes_equal(&n1, &n2);
}
for (j = 0; j < tsk_treeseq_get_num_edges(ts1); j++) {
ret = tsk_treeseq_get_edge(ts1, j, &r1);
CU_ASSERT_EQUAL(ret, 0);
ret = tsk_treeseq_get_edge(ts2, j, &r2);
CU_ASSERT_EQUAL(ret, 0);
verify_edges_equal(&r1, &r2, 1.0);
}
if (check_mutations) {
CU_ASSERT_EQUAL_FATAL(
tsk_treeseq_get_num_sites(ts1), tsk_treeseq_get_num_sites(ts2));
for (j = 0; j < tsk_treeseq_get_num_sites(ts1); j++) {
ret = tsk_treeseq_get_site(ts1, j, &site_1);
CU_ASSERT_EQUAL(ret, 0);
ret = tsk_treeseq_get_site(ts2, j, &site_2);
CU_ASSERT_EQUAL(ret, 0);
CU_ASSERT_EQUAL(site_1.position, site_2.position);
CU_ASSERT_EQUAL(
site_1.ancestral_state_length, site_2.ancestral_state_length);
CU_ASSERT_NSTRING_EQUAL(site_1.ancestral_state, site_2.ancestral_state,
site_1.ancestral_state_length);
CU_ASSERT_EQUAL(site_1.metadata_length, site_2.metadata_length);
CU_ASSERT_NSTRING_EQUAL(
site_1.metadata, site_2.metadata, site_1.metadata_length);
}
CU_ASSERT_EQUAL_FATAL(
tsk_treeseq_get_num_mutations(ts1), tsk_treeseq_get_num_mutations(ts2));
for (j = 0; j < num_mutations; j++) {
ret = tsk_treeseq_get_mutation(ts1, j, &mutation_1);
CU_ASSERT_EQUAL(ret, 0);
ret = tsk_treeseq_get_mutation(ts2, j, &mutation_2);
CU_ASSERT_EQUAL(ret, 0);
CU_ASSERT_EQUAL(mutation_1.id, j);
CU_ASSERT_EQUAL(mutation_1.id, mutation_2.id);
CU_ASSERT_EQUAL(mutation_1.site, mutation_2.site);
CU_ASSERT_EQUAL(mutation_1.node, mutation_2.node);
CU_ASSERT_EQUAL_FATAL(mutation_1.parent, mutation_2.parent);
CU_ASSERT_EQUAL_FATAL(
mutation_1.derived_state_length, mutation_2.derived_state_length);
CU_ASSERT_NSTRING_EQUAL(mutation_1.derived_state, mutation_2.derived_state,
mutation_1.derived_state_length);
CU_ASSERT_EQUAL_FATAL(
mutation_1.metadata_length, mutation_2.metadata_length);
CU_ASSERT_NSTRING_EQUAL(
mutation_1.metadata, mutation_2.metadata, mutation_1.metadata_length);
}
}
if (check_migrations) {
CU_ASSERT_EQUAL_FATAL(
tsk_treeseq_get_num_migrations(ts1), tsk_treeseq_get_num_migrations(ts2));
for (j = 0; j < tsk_treeseq_get_num_migrations(ts1); j++) {
ret = tsk_treeseq_get_migration(ts1, j, &m1);
CU_ASSERT_EQUAL(ret, 0);
ret = tsk_treeseq_get_migration(ts2, j, &m2);
CU_ASSERT_EQUAL(ret, 0);
verify_migrations_equal(&m1, &m2, 1.0);
}
}
if (check_provenance) {
CU_ASSERT_EQUAL_FATAL(
tsk_treeseq_get_num_provenances(ts1), tsk_treeseq_get_num_provenances(ts2));
for (j = 0; j < tsk_treeseq_get_num_provenances(ts1); j++) {
ret = tsk_treeseq_get_provenance(ts1, j, &p1);
CU_ASSERT_EQUAL(ret, 0);
ret = tsk_treeseq_get_provenance(ts2, j, &p2);
CU_ASSERT_EQUAL(ret, 0);
verify_provenances_equal(&p1, &p2);
}
}
CU_ASSERT_EQUAL_FATAL(
tsk_treeseq_get_num_individuals(ts1), tsk_treeseq_get_num_individuals(ts2));
for (j = 0; j < tsk_treeseq_get_num_individuals(ts1); j++) {
ret = tsk_treeseq_get_individual(ts1, j, &i1);
CU_ASSERT_EQUAL(ret, 0);
ret = tsk_treeseq_get_individual(ts2, j, &i2);
CU_ASSERT_EQUAL(ret, 0);
verify_individuals_equal(&i1, &i2);
}
CU_ASSERT_EQUAL_FATAL(
tsk_treeseq_get_num_populations(ts1), tsk_treeseq_get_num_populations(ts2));
for (j = 0; j < tsk_treeseq_get_num_populations(ts1); j++) {
ret = tsk_treeseq_get_population(ts1, j, &pop1);
CU_ASSERT_EQUAL(ret, 0);
ret = tsk_treeseq_get_population(ts2, j, &pop2);
CU_ASSERT_EQUAL(ret, 0);
verify_populations_equal(&pop1, &pop2);
}
ret = tsk_tree_init(&t1, ts1, 0);
CU_ASSERT_EQUAL(ret, 0);
ret = tsk_tree_init(&t2, ts2, 0);
CU_ASSERT_EQUAL(ret, 0);
ret = tsk_tree_first(&t1);
CU_ASSERT_EQUAL(ret, 1);
ret = tsk_tree_first(&t2);
CU_ASSERT_EQUAL(ret, 1);
while (1) {
err1 = tsk_tree_next(&t1);
err2 = tsk_tree_next(&t2);
CU_ASSERT_EQUAL_FATAL(err1, err2);
if (err1 != 1) {
break;
}
}
tsk_tree_free(&t1);
tsk_tree_free(&t2);
}
static void
test_save_empty_kas(void)
{
int ret;
tsk_treeseq_t ts1, ts2;
double sequence_length = 1234.00;
tsk_tbl_collection_t tables;
ret = tsk_tbl_collection_init(&tables, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
tables.sequence_length = sequence_length;
ret = tsk_treeseq_init(&ts1, &tables, TSK_BUILD_INDEXES);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_dump(&ts1, _tmp_file_name, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
verify_empty_tree_sequence(&ts1, sequence_length);
ret = tsk_treeseq_load(&ts2, _tmp_file_name, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
verify_empty_tree_sequence(&ts2, sequence_length);
tsk_treeseq_free(&ts1);
tsk_treeseq_free(&ts2);
tsk_tbl_collection_free(&tables);
}
static void
test_save_kas(void)
{
int ret;
size_t j, k;
tsk_treeseq_t **examples = get_example_tree_sequences(1);
tsk_treeseq_t ts2;
tsk_treeseq_t *ts1;
char *file_uuid;
int dump_flags[] = { 0 };
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
ts1 = examples[j];
file_uuid = tsk_treeseq_get_file_uuid(ts1);
CU_ASSERT_EQUAL_FATAL(file_uuid, NULL);
for (k = 0; k < sizeof(dump_flags) / sizeof(int); k++) {
ret = tsk_treeseq_dump(ts1, _tmp_file_name, dump_flags[k]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_load(&ts2, _tmp_file_name, TSK_LOAD_EXTENDED_CHECKS);
CU_ASSERT_EQUAL_FATAL(ret, 0);
verify_tree_sequences_equal(ts1, &ts2, true, true, true);
tsk_treeseq_print_state(&ts2, _devnull);
verify_vargen(&ts2);
file_uuid = tsk_treeseq_get_file_uuid(&ts2);
CU_ASSERT_NOT_EQUAL_FATAL(file_uuid, NULL);
CU_ASSERT_EQUAL(strlen(file_uuid), TSK_UUID_SIZE);
tsk_treeseq_free(&ts2);
}
tsk_treeseq_free(ts1);
free(ts1);
}
free(examples);
}
static void
test_save_kas_tables(void)
{
int ret;
size_t j, k;
tsk_treeseq_t **examples = get_example_tree_sequences(1);
tsk_treeseq_t *ts1;
tsk_tbl_collection_t t1, t2;
int dump_flags[] = { 0 };
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
ts1 = examples[j];
ret = tsk_tbl_collection_init(&t1, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_copy_tables(ts1, &t1);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL_FATAL(t1.file_uuid, NULL);
for (k = 0; k < sizeof(dump_flags) / sizeof(int); k++) {
ret = tsk_tbl_collection_dump(&t1, _tmp_file_name, dump_flags[k]);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_tbl_collection_init(&t2, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_tbl_collection_load(&t2, _tmp_file_name, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_TRUE(tsk_tbl_collection_equals(&t1, &t2));
CU_ASSERT_EQUAL_FATAL(t1.file_uuid, NULL);
CU_ASSERT_NOT_EQUAL_FATAL(t2.file_uuid, NULL);
CU_ASSERT_EQUAL(strlen(t2.file_uuid), TSK_UUID_SIZE);
tsk_tbl_collection_free(&t2);
}
tsk_tbl_collection_free(&t1);
tsk_treeseq_free(ts1);
free(ts1);
}
free(examples);
}
static void
test_sort_tables(void)
{
int ret;
tsk_treeseq_t **examples = get_example_tree_sequences(1);
tsk_treeseq_t ts2;
tsk_treeseq_t *ts1;
size_t j, k, start, starts[3];
tsk_tbl_collection_t tables;
int load_flags = TSK_BUILD_INDEXES;
tsk_id_t tmp_node;
ret = tsk_tbl_collection_init(&tables, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
ts1 = examples[j];
ret = tsk_treeseq_copy_tables(ts1, &tables);
CU_ASSERT_EQUAL_FATAL(ret, 0);
/* Check the input validation */
ret = tsk_tbl_collection_sort(NULL, 0, 0);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_PARAM_VALUE);
/* Check edge sorting */
if (tables.edges->num_rows == 2) {
starts[0] = 0;
starts[1] = 0;
starts[2] = 0;
} else {
starts[0] = 0;
starts[1] = tables.edges->num_rows / 2;
starts[2] = tables.edges->num_rows - 2;
}
for (k = 0; k < 3; k++) {
start = starts[k];
unsort_edges(tables.edges, start);
ret = tsk_treeseq_init(&ts2, &tables, load_flags);
CU_ASSERT_NOT_EQUAL_FATAL(ret, 0);
tsk_treeseq_free(&ts2);
ret = tsk_tbl_collection_sort(&tables, 0, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_init(&ts2, &tables, load_flags);
CU_ASSERT_EQUAL_FATAL(ret, 0);
verify_tree_sequences_equal(ts1, &ts2, true, true, false);
tsk_treeseq_free(&ts2);
}
/* A start value of num_tables.edges should have no effect */
ret = tsk_tbl_collection_sort(&tables, tables.edges->num_rows, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_init(&ts2, &tables, load_flags);
CU_ASSERT_EQUAL_FATAL(ret, 0);
verify_tree_sequences_equal(ts1, &ts2, true, true, false);
tsk_treeseq_free(&ts2);
if (tables.sites->num_rows > 1) {
/* Check site sorting */
unsort_sites(tables.sites, tables.mutations);
ret = tsk_treeseq_init(&ts2, &tables, load_flags);
CU_ASSERT_NOT_EQUAL(ret, 0);
tsk_treeseq_free(&ts2);
ret = tsk_tbl_collection_sort(&tables, 0, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_init(&ts2, &tables, load_flags);
CU_ASSERT_EQUAL_FATAL(ret, 0);
verify_tree_sequences_equal(ts1, &ts2, true, true, false);
tsk_treeseq_free(&ts2);
/* Check for site bounds error */
tables.mutations->site[0] = tables.sites->num_rows;
ret = tsk_tbl_collection_sort(&tables, 0, 0);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_SITE_OUT_OF_BOUNDS);
tables.mutations->site[0] = 0;
ret = tsk_tbl_collection_sort(&tables, 0, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
/* Check for edge node bounds error */
tmp_node = tables.edges->parent[0];
tables.edges->parent[0] = tables.nodes->num_rows;
ret = tsk_tbl_collection_sort(&tables, 0, 0);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_NODE_OUT_OF_BOUNDS);
tables.edges->parent[0] = tmp_node;
ret = tsk_tbl_collection_sort(&tables, 0, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
/* Check for mutation node bounds error */
tmp_node = tables.mutations->node[0];
tables.mutations->node[0] = tables.nodes->num_rows;
ret = tsk_tbl_collection_sort(&tables, 0, 0);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_NODE_OUT_OF_BOUNDS);
tables.mutations->node[0] = tmp_node;
/* Check for mutation parent bounds error */
tables.mutations->parent[0] = tables.mutations->num_rows;
ret = tsk_tbl_collection_sort(&tables, 0, 0);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_MUTATION_OUT_OF_BOUNDS);
tables.mutations->parent[0] = TSK_NULL;
ret = tsk_tbl_collection_sort(&tables, 0, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
}
tsk_treeseq_free(ts1);
free(ts1);
}
free(examples);
tsk_tbl_collection_free(&tables);
}
static void
test_dump_tables(void)
{
int ret;
tsk_treeseq_t **examples = get_example_tree_sequences(1);
tsk_treeseq_t ts2;
tsk_treeseq_t *ts1;
tsk_tbl_collection_t tables;
size_t j;
int load_flags = TSK_BUILD_INDEXES;
ret = tsk_tbl_collection_init(&tables, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
ts1 = examples[j];
ret = tsk_treeseq_copy_tables(ts1, NULL);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_PARAM_VALUE);
ret = tsk_treeseq_copy_tables(ts1, &tables);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_init(&ts2, &tables, load_flags);
CU_ASSERT_EQUAL_FATAL(ret, 0);
verify_tree_sequences_equal(ts1, &ts2, true, true, true);
tsk_treeseq_print_state(&ts2, _devnull);
tsk_treeseq_free(&ts2);
tsk_treeseq_free(ts1);
free(ts1);
}
free(examples);
tsk_tbl_collection_free(&tables);
}
static void
test_dump_tables_kas(void)
{
int ret;
size_t k;
tsk_treeseq_t *ts1, ts2, ts3, **examples;
tsk_tbl_collection_t tables;
int load_flags = TSK_BUILD_INDEXES;
ret = tsk_tbl_collection_init(&tables, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
examples = get_example_tree_sequences(1);
for (k = 0; examples[k] != NULL; k++) {
ts1 = examples[k];
CU_ASSERT_FATAL(ts1 != NULL);
ret = tsk_treeseq_copy_tables(ts1, &tables);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_init(&ts2, &tables, load_flags);
ret = tsk_treeseq_dump(&ts2, _tmp_file_name, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_load(&ts3, _tmp_file_name, TSK_LOAD_EXTENDED_CHECKS);
CU_ASSERT_EQUAL_FATAL(ret, 0);
verify_tree_sequences_equal(ts1, &ts3, true, true, true);
tsk_treeseq_print_state(&ts2, _devnull);
tsk_treeseq_free(&ts2);
tsk_treeseq_free(&ts3);
tsk_treeseq_free(ts1);
free(ts1);
}
free(examples);
tsk_tbl_collection_free(&tables);
}
void
test_tsk_tbl_collection_simplify_errors(void)
{
int ret;
tsk_tbl_collection_t tables;
tsk_id_t samples[] = { 0, 1 };
ret = tsk_tbl_collection_init(&tables, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
tables.sequence_length = 1;
ret = tsk_site_tbl_add_row(tables.sites, 0, "A", 1, NULL, 0);
CU_ASSERT_FATAL(ret >= 0);
ret = tsk_site_tbl_add_row(tables.sites, 0, "A", 1, NULL, 0);
CU_ASSERT_FATAL(ret >= 0);
ret = tsk_tbl_collection_simplify(&tables, samples, 0, 0, NULL);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_DUPLICATE_SITE_POSITION);
/* Out of order positions */
tables.sites->position[0] = 0.5;
ret = tsk_tbl_collection_simplify(&tables, samples, 0, 0, NULL);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_UNSORTED_SITES);
/* Position out of bounds */
tables.sites->position[0] = 1.5;
ret = tsk_tbl_collection_simplify(&tables, samples, 0, 0, NULL);
CU_ASSERT_EQUAL_FATAL(ret, TSK_ERR_BAD_SITE_POSITION);
/* TODO More tests for this: see
* https://github.com/tskit-dev/msprime/issues/517 */
tsk_tbl_collection_free(&tables);
}
void
test_tsk_tbl_collection_position_errors(void)
{
int ret;
int j;
tsk_tbl_collection_t t1, t2;
tsk_tbl_collection_position_t pos1, pos2;
tsk_treeseq_t **examples = get_example_tree_sequences(1);
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
// set-up
ret = tsk_tbl_collection_init(&t1, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_tbl_collection_init(&t2, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_copy_tables(examples[j], &t1);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_tbl_collection_copy(&t1, &t2);
CU_ASSERT_EQUAL_FATAL(ret, 0);
tsk_tbl_collection_record_position(&t1, &pos1);
// for each table, add a new row to t2, bookmark that location,
// then try to reset t1 to this illegal location
// individuals
tsk_individual_tbl_add_row(t2.individuals, 0, NULL, 0, NULL, 0);
tsk_tbl_collection_record_position(&t2, &pos2);
ret = tsk_tbl_collection_reset_position(&t1, &pos2);
CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);
ret = tsk_tbl_collection_reset_position(&t2, &pos1);
CU_ASSERT_EQUAL(ret, 0);
// nodes
tsk_node_tbl_add_row(t2.nodes, 0, 1.2, 0, -1, NULL, 0);
tsk_tbl_collection_record_position(&t2, &pos2);
ret = tsk_tbl_collection_reset_position(&t1, &pos2);
CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);
ret = tsk_tbl_collection_reset_position(&t2, &pos1);
CU_ASSERT_EQUAL(ret, 0);
// edges
tsk_edge_tbl_add_row(t2.edges, 0.1, 0.4, 0, 3);
tsk_tbl_collection_record_position(&t2, &pos2);
ret = tsk_tbl_collection_reset_position(&t1, &pos2);
CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);
ret = tsk_tbl_collection_reset_position(&t2, &pos1);
CU_ASSERT_EQUAL(ret, 0);
// migrations
tsk_migration_tbl_add_row(t2.migrations, 0.1, 0.2, 2, 1, 2, 1.2);
tsk_tbl_collection_record_position(&t2, &pos2);
ret = tsk_tbl_collection_reset_position(&t1, &pos2);
CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);
ret = tsk_tbl_collection_reset_position(&t2, &pos1);
CU_ASSERT_EQUAL(ret, 0);
// sites
tsk_site_tbl_add_row(t2.sites, 0.3, "A", 1, NULL, 0);
tsk_tbl_collection_record_position(&t2, &pos2);
ret = tsk_tbl_collection_reset_position(&t1, &pos2);
CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);
ret = tsk_tbl_collection_reset_position(&t2, &pos1);
CU_ASSERT_EQUAL(ret, 0);
// mutations
tsk_mutation_tbl_add_row(t2.mutations, 0, 1, -1, "X", 1, NULL, 0);
tsk_tbl_collection_record_position(&t2, &pos2);
ret = tsk_tbl_collection_reset_position(&t1, &pos2);
CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);
ret = tsk_tbl_collection_reset_position(&t2, &pos1);
CU_ASSERT_EQUAL(ret, 0);
// populations
tsk_population_tbl_add_row(t2.populations, NULL, 0);
tsk_tbl_collection_record_position(&t2, &pos2);
ret = tsk_tbl_collection_reset_position(&t1, &pos2);
CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);
ret = tsk_tbl_collection_reset_position(&t2, &pos1);
CU_ASSERT_EQUAL(ret, 0);
// provenance
tsk_provenance_tbl_add_row(t2.provenances, "abc", 3, NULL, 0);
tsk_tbl_collection_record_position(&t2, &pos2);
ret = tsk_tbl_collection_reset_position(&t1, &pos2);
CU_ASSERT_EQUAL(ret, TSK_ERR_BAD_TABLE_POSITION);
ret = tsk_tbl_collection_reset_position(&t2, &pos1);
CU_ASSERT_EQUAL(ret, 0);
tsk_tbl_collection_free(&t1);
tsk_tbl_collection_free(&t2);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
void
test_tsk_tbl_collection_position(void)
{
int ret;
int j, k;
tsk_treeseq_t **examples;
tsk_tbl_collection_t t1, t2, t3;
tsk_tbl_collection_position_t pos1, pos2;
examples = get_example_tree_sequences(1);
CU_ASSERT_FATAL(examples != NULL);
for (j = 0; examples[j] != NULL; j++) {
ret = tsk_tbl_collection_init(&t1, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_tbl_collection_init(&t2, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_tbl_collection_init(&t3, 0);
CU_ASSERT_EQUAL_FATAL(ret, 0);
ret = tsk_treeseq_copy_tables(examples[j], &t1);
// bookmark at pos1
tsk_tbl_collection_record_position(&t1, &pos1);
// copy to t2
ret = tsk_tbl_collection_copy(&t1, &t2);
CU_ASSERT_EQUAL_FATAL(ret, 0);
// resetting position should do nothing
ret = tsk_tbl_collection_reset_position(&t2, &pos1);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_TRUE(tsk_tbl_collection_equals(&t1, &t2));
// add more rows to t2
// (they don't have to make sense for this test)
for (k = 0; k < 3; k++) {
tsk_node_tbl_add_row(t2.nodes, 0, 1.2, 0, -1, NULL, 0);
tsk_node_tbl_add_row(t2.nodes, 0, 1.2, k, -1, NULL, 0);
tsk_edge_tbl_add_row(t2.edges, 0.1, 0.5, k, k + 1);
tsk_edge_tbl_add_row(t2.edges, 0.3, 0.8, k, k + 2);
}
// bookmark at pos2
tsk_tbl_collection_record_position(&t2, &pos2);
// copy to t3
ret = tsk_tbl_collection_copy(&t2, &t3);
CU_ASSERT_EQUAL_FATAL(ret, 0);
// add more rows to t3
for (k = 0; k < 3; k++) {
tsk_node_tbl_add_row(t3.nodes, 0, 1.2, k + 5, -1, NULL, 0);
tsk_site_tbl_add_row(t3.sites, 0.2, "A", 1, NULL, 0);
tsk_site_tbl_add_row(t3.sites, 0.2, "C", 1, NULL, 0);
tsk_mutation_tbl_add_row(t3.mutations, 0, k, -1, "T", 1, NULL, 0);
tsk_migration_tbl_add_row(t3.migrations, 0.0, 0.5, 1, 0, 1, 1.2);
tsk_individual_tbl_add_row(t3.individuals, k, NULL, 0, NULL, 0);
tsk_population_tbl_add_row(t3.populations, "X", 1);
tsk_provenance_tbl_add_row(t3.provenances, "abc", 3, NULL, 0);
}
// now resetting t3 to pos2 should equal t2
ret = tsk_tbl_collection_reset_position(&t3, &pos2);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_TRUE(tsk_tbl_collection_equals(&t2, &t3));
// and resetting to pos1 should equal t1
ret = tsk_tbl_collection_reset_position(&t3, &pos1);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_TRUE(tsk_tbl_collection_equals(&t1, &t3));
ret = tsk_tbl_collection_clear(&t1);
CU_ASSERT_EQUAL_FATAL(ret, 0);
CU_ASSERT_EQUAL(t1.individuals->num_rows, 0);
CU_ASSERT_EQUAL(t1.populations->num_rows, 0);
CU_ASSERT_EQUAL(t1.nodes->num_rows, 0);
CU_ASSERT_EQUAL(t1.edges->num_rows, 0);
CU_ASSERT_EQUAL(t1.migrations->num_rows, 0);
CU_ASSERT_EQUAL(t1.sites->num_rows, 0);
CU_ASSERT_EQUAL(t1.mutations->num_rows, 0);
CU_ASSERT_EQUAL(t1.provenances->num_rows, 0);
tsk_tbl_collection_free(&t1);
tsk_tbl_collection_free(&t2);
tsk_tbl_collection_free(&t3);
tsk_treeseq_free(examples[j]);
free(examples[j]);
}
free(examples);
}
static int
msprime_suite_init(void)
{
int fd;
static char template[] = "/tmp/tsk_c_test_XXXXXX";
_tmp_file_name = NULL;
_devnull = NULL;
_tmp_file_name = malloc(sizeof(template));
if (_tmp_file_name == NULL) {
return CUE_NOMEMORY;
}
strcpy(_tmp_file_name, template);
fd = mkstemp(_tmp_file_name);
if (fd == -1) {
return CUE_SINIT_FAILED;
}
close(fd);
_devnull = fopen("/dev/null", "w");
if (_devnull == NULL) {
return CUE_SINIT_FAILED;
}
return CUE_SUCCESS;
}
static int
msprime_suite_cleanup(void)
{
if (_tmp_file_name != NULL) {
unlink(_tmp_file_name);
free(_tmp_file_name);
}
if (_devnull != NULL) {
fclose(_devnull);
}
return CUE_SUCCESS;
}
static void
handle_cunit_error()
{
fprintf(stderr, "CUnit error occured: %d: %s\n", CU_get_error(), CU_get_error_msg());
exit(EXIT_FAILURE);
}
int
main(int argc, char **argv)
{
int ret;
CU_pTest test;
CU_pSuite suite;
CU_TestInfo tests[] = {
{ "test_node_metadata", test_node_metadata },
{ "test_diff_iter_from_examples", test_diff_iter_from_examples },
{ "test_tree_iter_from_examples", test_tree_iter_from_examples },
{ "test_tree_equals_from_examples", test_tree_equals_from_examples },
{ "test_next_prev_from_examples", test_next_prev_from_examples },
{ "test_sample_sets_from_examples", test_sample_sets_from_examples },
{ "test_tsk_vargen_from_examples", test_tsk_vargen_from_examples },
{ "test_newick_from_examples", test_newick_from_examples },
{ "test_stats_from_examples", test_stats_from_examples },
{ "test_compute_mutation_parents_from_examples",
test_compute_mutation_parents_from_examples },
{ "test_individual_nodes_from_examples", test_individual_nodes_from_examples },
{ "test_ld_from_examples", test_ld_from_examples },
{ "test_simplify_from_examples", test_simplify_from_examples },
{ "test_reduce_topology_from_examples", test_reduce_topology_from_examples },
{ "test_save_empty_kas", test_save_empty_kas },
{ "test_save_kas", test_save_kas },
{ "test_save_kas_tables", test_save_kas_tables },
{ "test_dump_tables", test_dump_tables },
{ "test_sort_tables", test_sort_tables },
{ "test_dump_tables_kas", test_dump_tables_kas },
{ "test_tsk_tbl_collection_position", test_tsk_tbl_collection_position },
{ "test_tsk_tbl_collection_position_errors",
test_tsk_tbl_collection_position_errors },
{ "test_genealogical_nearest_neighbours_from_examples",
test_genealogical_nearest_neighbours_from_examples },
{ "test_mean_descendants_from_examples", test_mean_descendants_from_examples },
CU_TEST_INFO_NULL,
};
/* We use initialisers here as the struct definitions change between
* versions of CUnit */
CU_SuiteInfo suites[] = {
{ .pName = "msprime",
.pInitFunc = msprime_suite_init,
.pCleanupFunc = msprime_suite_cleanup,
.pTests = tests },
CU_SUITE_INFO_NULL,
};
if (CUE_SUCCESS != CU_initialize_registry()) {
handle_cunit_error();
}
if (CUE_SUCCESS != CU_register_suites(suites)) {
handle_cunit_error();
}
CU_basic_set_mode(CU_BRM_VERBOSE);
if (argc == 1) {
CU_basic_run_tests();
} else if (argc == 2) {
suite = CU_get_suite_by_name("msprime", CU_get_registry());
if (suite == NULL) {
printf("Suite not found\n");
return EXIT_FAILURE;
}
test = CU_get_test_by_name(argv[1], suite);
if (test == NULL) {
printf("Test '%s' not found\n", argv[1]);
return EXIT_FAILURE;
}
CU_basic_run_test(suite, test);
} else {
printf("usage: ./tests <test_name>\n");
return EXIT_FAILURE;
}
ret = EXIT_SUCCESS;
if (CU_get_number_of_tests_failed() != 0) {
printf("Test failed!\n");
ret = EXIT_FAILURE;
}
CU_cleanup_registry();
return ret;
}
| {
"alphanum_fraction": 0.591940268,
"avg_line_length": 33.4943473792,
"ext": "c",
"hexsha": "4f61515a434f8b8da5f2a249049535cd7183611d",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-12-07T10:09:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-12-07T10:09:40.000Z",
"max_forks_repo_head_hexsha": "5fd0e3774283fa7e634c48f0f6314f6352c3ee8a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "grahamgower/tskit",
"max_forks_repo_path": "c/tests/old_tests.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5fd0e3774283fa7e634c48f0f6314f6352c3ee8a",
"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": "grahamgower/tskit",
"max_issues_repo_path": "c/tests/old_tests.c",
"max_line_length": 89,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5fd0e3774283fa7e634c48f0f6314f6352c3ee8a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "grahamgower/tskit",
"max_stars_repo_path": "c/tests/old_tests.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 27880,
"size": 97770
} |
//Gets line spectral frequencies (LSFs).
//from the linear prediction (LP) polynomial coefficients along cols or rows of X.
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include <cblas.h>
#include <lapacke.h>
#include "cmp_ascend.c"
#ifdef __cplusplus
namespace ov {
extern "C" {
#endif
int poly2lsf_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim);
int poly2lsf_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim);
int poly2lsf_c (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim);
int poly2lsf_z (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim);
int poly2lsf_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim)
{
const float z = 0.0f, o = 1.0f;
const int P = (dim==0) ? R-1 : C-1;
const int job = 'E', compz = 'N'; //eigenvalues only
const lapack_int ldh = P+1, n = P+1, ldz = 1;
const lapack_int ilo = 1, ihi = n; //avoids balancing
lapack_int info;
float *poly, *prev, *omegas, *compan, *wr, *wi, zz[1];
int r, c;
//Checks
if (R<1) { fprintf(stderr,"error in poly2lsf_s: nrows X must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in poly2lsf_s: ncols X must be positive\n"); return 1; }
if (P<1) { fprintf(stderr,"error in poly2lsf_s: P (length of polynomial coeffs including a0=1) must be positive\n"); return 1; }
//Allocate
if (!(poly=(float *)malloc((size_t)(n+1)*sizeof(float)))) { fprintf(stderr,"error in poly2lsf_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(prev=(float *)malloc((size_t)(n+1)*sizeof(float)))) { fprintf(stderr,"error in poly2lsf_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(omegas=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,"error in poly2lsf_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(wr=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,"error in poly2lsf_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(wi=(float *)malloc((size_t)(n)*sizeof(float)))) { fprintf(stderr,"error in poly2lsf_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(compan=(float *)malloc((size_t)(n*n)*sizeof(float)))) { fprintf(stderr,"error in poly2lsf_s: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0)
{
for (c=0; c<C; c++)
{
if (iscolmajor) { cblas_scopy(n,&X[c*R],1,poly,1); }
else { cblas_scopy(n,&X[c],C,poly,1); }
cblas_sscal(n,-1.0f/poly[0],poly,1); poly[n] = z;
for (r=1; r<=n; r++) { prev[r] = poly[n-r]; }
for (r=1; r<=n; r++) { poly[r] -= prev[r]; }
cblas_scopy(n*n,&z,0,compan,1); cblas_scopy(n-1,&o,0,&compan[1],n+1); cblas_scopy(n,&poly[1],1,compan,n);
//fprintf(stderr,"compan = \n"); for (r=0; r<n; r++) { for (c2=0; c2<n; c2++) { fprintf(stderr,"%f ",compan[r+c2*n]); } fprintf(stderr,"\n"); }
info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in poly2lsf_s: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[r] = (wi[r]>10.0f*FLT_EPSILON) ? atan2f(wi[r],wr[r]) : 0.0f; }
for (r=1; r<=n; r++) { poly[r] += prev[r] + prev[r]; }
cblas_scopy(n*n,&z,0,compan,1); cblas_scopy(n-1,&o,0,&compan[1],n+1); cblas_scopy(n,&poly[1],1,compan,n);
//fprintf(stderr,"compan = \n"); for (r=0; r<n; r++) { for (c2=0; c2<n; c2++) { fprintf(stderr,"%f ",compan[r+c2*n]); } fprintf(stderr,"\n"); }
info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in poly2lsf_s: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[n+r] = (wi[r]>10.0f*FLT_EPSILON) ? atan2f(wi[r],wr[r]) : 0.0f; }
qsort(omegas,(size_t)(2*n),sizeof(float),cmp_ascend_s);
if (iscolmajor) { cblas_scopy(n-1,&omegas[n+1],1,&Y[c*(n-1)],1); } //cblas_scopy(2*n,omegas,1,&Y[2*c*n],1);
else { cblas_scopy(n-1,&omegas[n+1],1,&Y[c],C); } //cblas_scopy(2*n,omegas,1,&Y[c],C);
}
}
else if (dim==1)
{
for (r=0; r<R; r++)
{
if (iscolmajor) { cblas_scopy(n,&X[r],R,poly,1); }
else { cblas_scopy(n,&X[r*C],1,poly,1); }
cblas_sscal(n,-1.0f/poly[0],poly,1); poly[n] = z;
for (c=1; c<=n; c++) { prev[c] = poly[n-c]; }
for (c=1; c<=n; c++) { poly[c] -= prev[c]; }
cblas_scopy(n*n,&z,0,compan,1); cblas_scopy(n-1,&o,0,&compan[1],n+1); cblas_scopy(n,&poly[1],1,compan,n);
info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in poly2lsf_s: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[c] = (wi[c]>10.0f*FLT_EPSILON) ? atan2f(wi[c],wr[c]) : 0.0f; }
for (c=1; c<=n; c++) { poly[c] += prev[c] + prev[c]; }
cblas_scopy(n*n,&z,0,compan,1); cblas_scopy(n-1,&o,0,&compan[1],n+1); cblas_scopy(n,&poly[1],1,compan,n);
info = LAPACKE_shseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in poly2lsf_s: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[n+c] = (wi[c]>10.0f*FLT_EPSILON) ? atan2f(wi[c],wr[c]) : 0.0f; }
qsort(omegas,(size_t)(2*n),sizeof(float),cmp_ascend_s);
if (iscolmajor) { cblas_scopy(n-1,&omegas[n+1],1,&Y[r],R); } //cblas_scopy(2*n,omegas,1,&Y[r],R);
else { cblas_scopy(n-1,&omegas[n+1],1,&Y[r*(n-1)],1); } //cblas_scopy(2*n,omegas,1,&Y[2*r*n],1);
}
}
else
{
fprintf(stderr,"error in poly2lsf_s: dim must be 0 or 1.\n"); return 1;
}
//Exit
free(compan); free(wr); free(wi); free(poly); free(prev); free(omegas);
return 0;
}
int poly2lsf_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim)
{
const double z = 0.0, o = 1.0;
const int P = (dim==0) ? R-1 : C-1;
const int job = 'E', compz = 'N'; //eigenvalues only
const lapack_int ldh = P+1, n = P+1, ldz = 1;
const lapack_int ilo = 1, ihi = n; //avoids balancing
lapack_int info;
double *poly, *prev, *omegas, *compan, *wr, *wi, zz[1];
int r, c;
//Checks
if (R<1) { fprintf(stderr,"error in poly2lsf_d: nrows X must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in poly2lsf_d: ncols X must be positive\n"); return 1; }
if (P<1) { fprintf(stderr,"error in poly2lsf_d: P (length of polynomial coeffs including a0=1) must be positive\n"); return 1; }
//Allocate
if (!(poly=(double *)malloc((size_t)(n+1)*sizeof(double)))) { fprintf(stderr,"error in poly2lsf_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(prev=(double *)malloc((size_t)(n+1)*sizeof(double)))) { fprintf(stderr,"error in poly2lsf_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(omegas=(double *)malloc((size_t)(2*n)*sizeof(double)))) { fprintf(stderr,"error in poly2lsf_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(wr=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,"error in poly2lsf_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(wi=(double *)malloc((size_t)(n)*sizeof(double)))) { fprintf(stderr,"error in poly2lsf_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(compan=(double *)malloc((size_t)(n*n)*sizeof(double)))) { fprintf(stderr,"error in poly2lsf_d: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0)
{
for (c=0; c<C; c++)
{
if (iscolmajor) { cblas_dcopy(n,&X[c*R],1,poly,1); }
else { cblas_dcopy(n,&X[c],C,poly,1); }
cblas_dscal(n,-1.0/poly[0],poly,1); poly[n] = z;
for (r=1; r<=n; r++) { prev[r] = poly[n-r]; }
for (r=1; r<=n; r++) { poly[r] -= prev[r]; }
cblas_dcopy(n*n,&z,0,compan,1); cblas_dcopy(n-1,&o,0,&compan[1],n+1); cblas_dcopy(n,&poly[1],1,compan,n);
info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in poly2lsf_d: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[r] = (wi[r]>10.0*DBL_EPSILON) ? atan2(wi[r],wr[r]) : 0.0; }
for (r=1; r<=n; r++) { poly[r] += prev[r] + prev[r]; }
cblas_dcopy(n*n,&z,0,compan,1); cblas_dcopy(n-1,&o,0,&compan[1],n+1); cblas_dcopy(n,&poly[1],1,compan,n);
info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in poly2lsf_d: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[n+r] = (wi[r]>10.0*DBL_EPSILON) ? atan2(wi[r],wr[r]) : 0.0; }
qsort(omegas,(size_t)(2*n),sizeof(double),cmp_ascend_d);
if (iscolmajor) { cblas_dcopy(n-1,&omegas[n+1],1,&Y[c*(n-1)],1); } //cblas_dcopy(2*n,omegas,1,&Y[2*c*n],1);
else { cblas_dcopy(n-1,&omegas[n+1],1,&Y[c],C); } //cblas_dcopy(2*n,omegas,1,&Y[c],C);
}
}
else if (dim==1)
{
for (r=0; r<R; r++)
{
if (iscolmajor) { cblas_dcopy(n,&X[r],R,poly,1); }
else { cblas_dcopy(n,&X[r*C],1,poly,1); }
cblas_dscal(n,-1.0/poly[0],poly,1); poly[n] = z;
for (c=1; c<=n; c++) { prev[c] = poly[n-c]; }
for (c=1; c<=n; c++) { poly[c] -= prev[c]; }
cblas_dcopy(n*n,&z,0,compan,1); cblas_dcopy(n-1,&o,0,&compan[1],n+1); cblas_dcopy(n,&poly[1],1,compan,n);
info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in poly2lsf_d: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[c] = (wi[c]>10.0*DBL_EPSILON) ? atan2(wi[c],wr[c]) : 0.0; }
for (c=1; c<=n; c++) { poly[c] += prev[c] + prev[c]; }
cblas_dcopy(n*n,&z,0,compan,1); cblas_dcopy(n-1,&o,0,&compan[1],n+1); cblas_dcopy(n,&poly[1],1,compan,n);
info = LAPACKE_dhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,compan,ldh,wr,wi,zz,ldz); //eig
if (info) { fprintf(stderr,"error in poly2lsf_d: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[n+c] = (wi[c]>10.0*DBL_EPSILON) ? atan2(wi[c],wr[c]) : 0.0; }
qsort(omegas,(size_t)(2*n),sizeof(double),cmp_ascend_d);
if (iscolmajor) { cblas_dcopy(n-1,&omegas[n+1],1,&Y[r],R); } //cblas_dcopy(2*n,omegas,1,&Y[r],R);
else { cblas_dcopy(n-1,&omegas[n+1],1,&Y[r*(n-1)],1); }
}
}
else
{
fprintf(stderr,"error in poly2lsf_d: dim must be 0 or 1.\n"); return 1;
}
//Exit
free(compan); free(wr); free(wi); free(poly); free(prev); free(omegas);
return 0;
}
int poly2lsf_c (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim)
{
const float z[2] = {0.0f,0.0f}, o[2] = {1.0f,0.0f};
const int P = (dim==0) ? R-1 : C-1;
const int job = 'E', compz = 'N'; //eigenvalues only
const lapack_int ldh = P+1, n = P+1, ldz = 1;
const lapack_int ilo = 1, ihi = n; //avoids balancing
lapack_int info;
float *poly, *prev, *omegas, *compan, *wc, zz[2], sc[2];
int r, c;
//Checks
if (R<1) { fprintf(stderr,"error in poly2lsf_c: nrows X must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in poly2lsf_c: ncols X must be positive\n"); return 1; }
if (P<1) { fprintf(stderr,"error in poly2lsf_c: P (length of polynomial coeffs including a0=1) must be positive\n"); return 1; }
//Allocate
if (!(poly=(float *)malloc((size_t)(2*n+2)*sizeof(float)))) { fprintf(stderr,"error in poly2lsf_c: problem with malloc. "); perror("malloc"); return 1; }
if (!(prev=(float *)malloc((size_t)(2*n+2)*sizeof(float)))) { fprintf(stderr,"error in poly2lsf_c: problem with malloc. "); perror("malloc"); return 1; }
if (!(wc=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,"error in poly2lsf_c: problem with malloc. "); perror("malloc"); return 1; }
if (!(omegas=(float *)malloc((size_t)(2*n)*sizeof(float)))) { fprintf(stderr,"error in poly2lsf_c: problem with malloc. "); perror("malloc"); return 1; }
if (!(compan=(float *)malloc((size_t)(4*n*n)*sizeof(float)))) { fprintf(stderr,"error in poly2lsf_c: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0)
{
for (c=0; c<C; c++)
{
if (iscolmajor) { cblas_ccopy(n,&X[2*c*R],1,poly,1); }
else { cblas_ccopy(n,&X[2*c],C,poly,1); }
sc[0] = 1.0f/(poly[0]*poly[0]+poly[1]*poly[1]); sc[1] = poly[1]*sc[0]; sc[0] *= -poly[0];
cblas_cscal(n,sc,poly,1); poly[2*n] = poly[2*n+1] = 0.0f;
for (r=1; r<=n; r++) { prev[2*r] = poly[2*(n-r)]; prev[2*r+1] = poly[2*(n-r)+1]; }
for (r=1; r<=n; r++) { poly[2*r] -= prev[2*r]; poly[2*r+1] -= prev[2*r+1]; }
cblas_ccopy(n*n,z,0,compan,1); cblas_ccopy(n-1,o,0,&compan[2],n+1); cblas_ccopy(n,&poly[2],1,compan,n);
info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)wc,(lapack_complex_float *)zz,ldz);
if (info) { fprintf(stderr,"error in poly2lsf_c: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[r] = atan2f(wc[2*r+1],wc[2*r]); }
//for (r=0; r<n; r++) { omegas[r] = (wc[2*r+1]>10.0f*FLT_EPSILON) ? atan2f(wc[2*r+1],wc[2*r]) : 0.0f; }
for (r=1; r<=n; r++) { poly[2*r] += prev[2*r] + prev[2*r]; poly[2*r+1] += prev[2*r+1] + prev[2*r+1]; }
cblas_ccopy(n*n,z,0,compan,1); cblas_ccopy(n-1,o,0,&compan[2],n+1); cblas_ccopy(n,&poly[2],1,compan,n);
info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)wc,(lapack_complex_float *)zz,ldz);
if (info) { fprintf(stderr,"error in poly2lsf_c: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[n+r] = atan2f(wc[2*r+1],wc[2*r]); }
//for (r=0; r<n; r++) { omegas[n+r] = (wc[2*r+1]>10.0f*FLT_EPSILON) ? atan2f(wc[2*r+1],wc[2*r]) : 0.0f; }
qsort(omegas,(size_t)(2*n),sizeof(float),cmp_ascend_s);
if (iscolmajor) { cblas_scopy(2*n,omegas,1,&Y[2*c*n],1); }
else { cblas_scopy(2*n,omegas,1,&Y[c],C); }
}
}
else if (dim==1)
{
for (r=0; r<R; r++)
{
if (iscolmajor) { cblas_ccopy(n,&X[2*r],R,poly,1); }
else { cblas_ccopy(n,&X[2*r*C],1,poly,1); }
sc[0] = 1.0f/(poly[0]*poly[0]+poly[1]*poly[1]); sc[1] = poly[1]*sc[0]; sc[0] *= -poly[0];
cblas_cscal(n,sc,poly,1); poly[2*n] = poly[2*n+1] = 0.0f;
for (c=1; c<=n; c++) { prev[2*c] = poly[2*(n-c)]; prev[2*c+1] = poly[2*(n-c)+1]; }
for (c=1; c<=n; c++) { poly[2*c] -= prev[2*c]; poly[2*c+1] -= prev[2*c+1]; }
cblas_ccopy(n*n,z,0,compan,1); cblas_ccopy(n-1,o,0,&compan[2],n+1); cblas_ccopy(n,&poly[2],1,compan,n);
info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)wc,(lapack_complex_float *)zz,ldz);
if (info) { fprintf(stderr,"error in poly2lsf_c: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[c] = atan2f(wc[2*c+1],wc[2*c]); }
//for (c=0; c<n; c++) { omegas[c] = (wc[2*r+1]>10.0f*FLT_EPSILON) ? atan2f(wc[2*r+1],wc[2*r]) : 0.0f; }
for (c=1; c<=n; c++) { poly[2*c] += prev[2*c] + prev[2*c]; poly[2*c+1] += prev[2*c+1] + prev[2*c+1]; }
cblas_ccopy(n*n,z,0,compan,1); cblas_ccopy(n-1,o,0,&compan[2],n+1); cblas_ccopy(n,&poly[2],1,compan,n);
info = LAPACKE_chseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_float *)compan,ldh,(lapack_complex_float *)wc,(lapack_complex_float *)zz,ldz);
if (info) { fprintf(stderr,"error in poly2lsf_c: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[n+c] = atan2f(wc[2*c+1],wc[2*c]); }
//for (c=0; c<n; c++) { omegas[n+c] = (wc[2*r+1]>10.0f*FLT_EPSILON) ? atan2f(wc[2*r+1],wc[2*r]) : 0.0f; }
qsort(omegas,(size_t)(2*n),sizeof(float),cmp_ascend_s);
if (iscolmajor) { cblas_scopy(2*n,omegas,1,&Y[r],R); }
else { cblas_scopy(2*n,omegas,1,&Y[2*r*n],1); }
}
}
else
{
fprintf(stderr,"error in poly2lsf_c: dim must be 0 or 1.\n"); return 1;
}
//Exit
free(compan); free(wc); free(poly); free(prev); free(omegas);
return 0;
}
int poly2lsf_z (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim)
{
const double z[2] = {0.0,0.0}, o[2] = {1.0,0.0};
const int P = (dim==0) ? R-1 : C-1;
const int job = 'E', compz = 'N'; //eigenvalues only
const lapack_int ldh = P+1, n = P+1, ldz = 1;
const lapack_int ilo = 1, ihi = n; //avoids balancing
lapack_int info;
double *poly, *prev, *omegas, *compan, *wc, zz[2], sc[2];
int r, c;
//Checks
if (R<1) { fprintf(stderr,"error in poly2lsf_z: nrows X must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in poly2lsf_z: ncols X must be positive\n"); return 1; }
if (P<1) { fprintf(stderr,"error in poly2lsf_z: P (length of polynomial coeffs including a0=1) must be positive\n"); return 1; }
//Allocate
if (!(poly=(double *)malloc((size_t)(2*n+2)*sizeof(double)))) { fprintf(stderr,"error in poly2lsf_z: problem with malloc. "); perror("malloc"); return 1; }
if (!(prev=(double *)malloc((size_t)(2*n+2)*sizeof(double)))) { fprintf(stderr,"error in poly2lsf_z: problem with malloc. "); perror("malloc"); return 1; }
if (!(wc=(double *)malloc((size_t)(2*n)*sizeof(double)))) { fprintf(stderr,"error in poly2lsf_z: problem with malloc. "); perror("malloc"); return 1; }
if (!(omegas=(double *)malloc((size_t)(2*n)*sizeof(double)))) { fprintf(stderr,"error in poly2lsf_z: problem with malloc. "); perror("malloc"); return 1; }
if (!(compan=(double *)malloc((size_t)(4*n*n)*sizeof(double)))) { fprintf(stderr,"error in poly2lsf_z: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0)
{
for (c=0; c<C; c++)
{
if (iscolmajor) { cblas_zcopy(n,&X[2*c*R],1,poly,1); }
else { cblas_zcopy(n,&X[2*c],C,poly,1); }
sc[0] = 1.0/(poly[0]*poly[0]+poly[1]*poly[1]); sc[1] = poly[1]*sc[0]; sc[0] *= -poly[0];
cblas_zscal(n,sc,poly,1); poly[2*n] = poly[2*n+1] = 0.0;
for (r=1; r<=n; r++) { prev[2*r] = poly[2*(n-r)]; prev[2*r+1] = poly[2*(n-r)+1]; }
for (r=1; r<=n; r++) { poly[2*r] -= prev[2*r]; poly[2*r+1] -= prev[2*r+1]; }
cblas_zcopy(n*n,z,0,compan,1); cblas_zcopy(n-1,o,0,&compan[2],n+1); cblas_zcopy(n,&poly[2],1,compan,n);
info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)wc,(lapack_complex_double *)zz,ldz);
if (info) { fprintf(stderr,"error in poly2lsf_z: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[r] = atan2(wc[2*r+1],wc[2*r]); }
//for (r=0; r<n; r++) { omegas[r] = (wc[2*r+1]>10.0*DBL_EPSILON) ? atan2(wc[2*r+1],wc[2*r]) : 0.0; }
for (r=1; r<=n; r++) { poly[2*r] += prev[2*r] + prev[2*r]; poly[2*r+1] += prev[2*r+1] + prev[2*r+1]; }
cblas_zcopy(n*n,z,0,compan,1); cblas_zcopy(n-1,o,0,&compan[2],n+1); cblas_zcopy(n,&poly[2],1,compan,n);
info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)wc,(lapack_complex_double *)zz,ldz);
if (info) { fprintf(stderr,"error in poly2lsf_z: lapacke decomposition failed\n"); return 1; }
for (r=0; r<n; r++) { omegas[n+r] = atan2(wc[2*r+1],wc[2*r]); }
qsort(omegas,(size_t)(2*n),sizeof(double),cmp_ascend_d);
if (iscolmajor) { cblas_dcopy(2*n,omegas,1,&Y[2*c*n],1); }
else { cblas_dcopy(2*n,omegas,1,&Y[c],C); }
}
}
else if (dim==1)
{
for (r=0; r<R; r++)
{
if (iscolmajor) { cblas_zcopy(n,&X[2*r],R,poly,1); }
else { cblas_zcopy(n,&X[2*r*C],1,poly,1); }
sc[0] = 1.0/(poly[0]*poly[0]+poly[1]*poly[1]); sc[1] = poly[1]*sc[0]; sc[0] *= -poly[0];
cblas_zscal(n,sc,poly,1); poly[2*n] = poly[2*n+1] = 0.0;
for (c=1; c<=n; c++) { prev[2*c] = poly[2*(n-c)]; prev[2*c+1] = poly[2*(n-c)+1]; }
for (c=1; c<=n; c++) { poly[2*c] -= prev[2*c]; poly[2*c+1] -= prev[2*c+1]; }
cblas_zcopy(n*n,z,0,compan,1); cblas_zcopy(n-1,o,0,&compan[2],n+1); cblas_zcopy(n,&poly[2],1,compan,n);
info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)wc,(lapack_complex_double *)zz,ldz);
if (info) { fprintf(stderr,"error in poly2lsf_z: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[c] = atan2(wc[2*c+1],wc[2*c]); }
//for (c=0; c<n; c++) { omegas[n+c] = (wc[2*r+1]>10.0*DBL_EPSILON) ? atan2(wc[2*r+1],wc[2*r]) : 0.0; }
for (c=1; c<=n; c++) { poly[2*c] += prev[2*c] + prev[2*c]; poly[2*c+1] += prev[2*c+1] + prev[2*c+1]; }
cblas_zcopy(n*n,z,0,compan,1); cblas_zcopy(n-1,o,0,&compan[2],n+1); cblas_zcopy(n,&poly[2],1,compan,n);
info = LAPACKE_zhseqr(LAPACK_COL_MAJOR,job,compz,n,ilo,ihi,(lapack_complex_double *)compan,ldh,(lapack_complex_double *)wc,(lapack_complex_double *)zz,ldz);
if (info) { fprintf(stderr,"error in poly2lsf_z: lapacke decomposition failed\n"); return 1; }
for (c=0; c<n; c++) { omegas[n+c] = atan2(wc[2*c+1],wc[2*c]); }
//for (c=0; c<n; c++) { omegas[n+c] = (wc[2*r+1]>10.0*DBL_EPSILON) ? atan2(wc[2*r+1],wc[2*r]) : 0.0; }
qsort(omegas,(size_t)(2*n),sizeof(double),cmp_ascend_d);
if (iscolmajor) { cblas_dcopy(2*n,omegas,1,&Y[r],R); }
else { cblas_dcopy(2*n,omegas,1,&Y[2*r*n],1); }
}
}
else
{
fprintf(stderr,"error in poly2lsf_z: dim must be 0 or 1.\n"); return 1;
}
//Exit
free(compan); free(wc); free(poly); free(prev); free(omegas);
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.5672728859,
"avg_line_length": 63.1652892562,
"ext": "c",
"hexsha": "9c08ef09227ffb83f01d9d67c40c2f28b9ffca89",
"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": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/aud",
"max_forks_repo_path": "c/poly2lsf.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "erikedwards4/aud",
"max_issues_repo_path": "c/poly2lsf.c",
"max_line_length": 168,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/aud",
"max_stars_repo_path": "c/poly2lsf.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8536,
"size": 22929
} |
// Copyright Jean Pierre Cimalando 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include "player/instrument.h"
#include "synth/synth.h"
#include <fmidi/fmidi.h>
#include <gsl/gsl>
#include <memory>
class Midi_Synth_Instrument : public Midi_Instrument {
public:
Midi_Synth_Instrument();
~Midi_Synth_Instrument();
void flush_events() override;
void open_midi_output(gsl::cstring_span id) override;
void close_midi_output() override;
bool is_synth() const override { return true; }
void configure_audio(double audio_rate, double audio_latency);
void generate_audio(float *output, unsigned nframes);
void preload(const fmidi_smf_t &smf);
protected:
void handle_send_message(const uint8_t *data, unsigned len, double ts, uint8_t flags) override;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
| {
"alphanum_fraction": 0.7244488978,
"avg_line_length": 26.972972973,
"ext": "h",
"hexsha": "d9da6d43f4074a4cf725595cb72fc681c332347c",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-11-22T08:05:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-07-10T18:48:10.000Z",
"max_forks_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "jpcima/smf-dsp",
"max_forks_repo_path": "sources/player/instruments/synth.h",
"max_issues_count": 19,
"max_issues_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb",
"max_issues_repo_issues_event_max_datetime": "2022-01-16T20:44:07.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-05T23:59:33.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "jpcima/smf-dsp",
"max_issues_repo_path": "sources/player/instruments/synth.h",
"max_line_length": 99,
"max_stars_count": 22,
"max_stars_repo_head_hexsha": "9978db5c9fa8b6eebe558eee212a2c0ed5c9e1bb",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "jpcima/smf-dsp",
"max_stars_repo_path": "sources/player/instruments/synth.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-26T23:08:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-08T15:23:44.000Z",
"num_tokens": 244,
"size": 998
} |
static const char help[] =
"Solves elasto-plastic torsion problem in 2D using SNESVI. Option prefix -el_.\n"
"Equation is - grad^2 u = f(x,y) where f(x,y) = 2 C. Zero Dirichlet\n"
"boundary conditions. Domain Omega = (0,1)x(0,1). Constraint is upper bound\n"
" u(x,y) <= dist((x,y), bdry Omega) = psi(x,y).\n"
"At locations where the constraint is active, the material experiences plastic\n"
"failure. Where inactive, the equation represents the elasticity. As with\n"
"related codes ../obstacle.c and dam.c the code reuses the residual and\n"
"Jacobian evaluation code from ch6/.\n"
"Reference: R. Kornhuber (1994) 'Monotone multigrid methods for elliptic\n"
"variational inequalities I', Numerische Mathematik, 69(2), 167-184.\n\n";
#include <petsc.h>
#include "../../ch6/poissonfunctions.h"
// z = psi(x,y) = dist((x,y), bdry Omega) is the upper obstacle
double psi(double x, double y) {
if (y <= x)
if (y <= 1.0 - x)
return y;
else
return 1.0 - x;
else
if (y <= 1.0 - x)
return x;
else
return 1.0 - y;
}
double zero(double x, double y, double z, void *ctx) {
return 0.0;
}
static double C = 2.5;
double f_fcn(double x, double y, double z, void *ctx) {
return 2.0 * C;
}
extern PetscErrorCode FormBounds(SNES, Vec, Vec);
int main(int argc,char **argv) {
PetscErrorCode ierr;
DM da, da_after;
SNES snes;
Vec u_initial, u;
PoissonCtx user;
SNESConvergedReason reason;
int snesits;
double lflops,flops;
DMDALocalInfo info;
PetscInitialize(&argc,&argv,NULL,help);
ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"el_",
"elasto-plastic torsion solver options",""); CHKERRQ(ierr);
ierr = PetscOptionsReal("-C","f(x,y)=2C is source term",
"elasto.c",C,&C,NULL); CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
ierr = DMDACreate2d(PETSC_COMM_WORLD,
DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_STAR,
3,3, // override with -da_grid_x,_y
PETSC_DECIDE,PETSC_DECIDE, // num of procs in each dim
1,1,NULL,NULL, // dof = 1 and stencil width = 1
&da);CHKERRQ(ierr);
ierr = DMSetFromOptions(da); CHKERRQ(ierr);
ierr = DMSetUp(da); CHKERRQ(ierr);
ierr = DMDASetUniformCoordinates(da,0.0,1.0,0.0,1.0,-1.0,-1.0);CHKERRQ(ierr);
user.cx = 1.0;
user.cy = 1.0;
user.cz = 1.0;
user.g_bdry = &zero;
user.f_rhs = &f_fcn;
user.addctx = NULL;
ierr = DMSetApplicationContext(da,&user);CHKERRQ(ierr);
ierr = SNESCreate(PETSC_COMM_WORLD,&snes);CHKERRQ(ierr);
ierr = SNESSetDM(snes,da);CHKERRQ(ierr);
ierr = SNESSetApplicationContext(snes,&user);CHKERRQ(ierr);
ierr = SNESSetType(snes,SNESVINEWTONRSLS);CHKERRQ(ierr);
ierr = SNESVISetComputeVariableBounds(snes,&FormBounds);CHKERRQ(ierr);
// reuse residual and jacobian from ch6/
ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,
(DMDASNESFunction)Poisson2DFunctionLocal,&user); CHKERRQ(ierr);
ierr = DMDASNESSetJacobianLocal(da,
(DMDASNESJacobian)Poisson2DJacobianLocal,&user); CHKERRQ(ierr);
ierr = SNESSetFromOptions(snes);CHKERRQ(ierr);
// initial iterate is zero
ierr = DMCreateGlobalVector(da,&u_initial);CHKERRQ(ierr);
ierr = VecSet(u_initial,0.0); CHKERRQ(ierr);
/* solve; then get solution and DM after solution*/
ierr = SNESSolve(snes,NULL,u_initial);CHKERRQ(ierr);
ierr = VecDestroy(&u_initial); CHKERRQ(ierr);
ierr = DMDestroy(&da); CHKERRQ(ierr);
ierr = SNESGetDM(snes,&da_after); CHKERRQ(ierr);
ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr); /* do not destroy u */
/* performance measures */
ierr = SNESGetConvergedReason(snes,&reason); CHKERRQ(ierr);
if (reason <= 0) {
ierr = PetscPrintf(PETSC_COMM_WORLD,
"WARNING: SNES not converged ... use -snes_converged_reason to check\n"); CHKERRQ(ierr);
}
ierr = SNESGetIterationNumber(snes,&snesits); CHKERRQ(ierr);
ierr = PetscGetFlops(&lflops); CHKERRQ(ierr);
ierr = MPI_Allreduce(&lflops,&flops,1,MPI_DOUBLE,MPI_SUM,PETSC_COMM_WORLD); CHKERRQ(ierr);
ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"done on %4d x %4d grid; total flops = %.3e; SNES iterations %d\n",
info.mx,info.my,flops,snesits); CHKERRQ(ierr);
SNESDestroy(&snes);
return PetscFinalize();
}
// for call-back: tell SNESVI we want -infty < u <= psi
PetscErrorCode FormBounds(SNES snes, Vec Xl, Vec Xu) {
PetscErrorCode ierr;
DM da;
DMDALocalInfo info;
int i, j;
double **aXu, dx, dy, x, y;
ierr = VecSet(Xu,PETSC_NINFINITY);CHKERRQ(ierr);
ierr = SNESGetDM(snes,&da);CHKERRQ(ierr);
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
dx = 1.0 / (PetscReal)(info.mx-1);
dy = 1.0 / (PetscReal)(info.my-1);
ierr = DMDAVecGetArray(da, Xu, &aXu);CHKERRQ(ierr);
for (j=info.ys; j<info.ys+info.ym; j++) {
y = j * dy;
for (i=info.xs; i<info.xs+info.xm; i++) {
x = i * dx;
aXu[j][i] = psi(x,y);
}
}
ierr = DMDAVecRestoreArray(da, Xu, &aXu);CHKERRQ(ierr);
return 0;
}
| {
"alphanum_fraction": 0.6467986926,
"avg_line_length": 35.380952381,
"ext": "c",
"hexsha": "1bd1a06711cb3389fdc8ab77ea2840808c67c327",
"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": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mapengfei-nwpu/p4pdes",
"max_forks_repo_path": "c/ch12/solns/elasto.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"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": "mapengfei-nwpu/p4pdes",
"max_issues_repo_path": "c/ch12/solns/elasto.c",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mapengfei-nwpu/p4pdes",
"max_stars_repo_path": "c/ch12/solns/elasto.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1633,
"size": 5201
} |
#include <gsl/gsl_complex.h>
#define RVEC(A) int A##n, double*A##p
#define RMAT(A) int A##r, int A##c, double* A##p
#define KRVEC(A) int A##n, const double*A##p
#define KRMAT(A) int A##r, int A##c, const double* A##p
#define CVEC(A) int A##n, gsl_complex*A##p
#define CMAT(A) int A##r, int A##c, gsl_complex* A##p
#define KCVEC(A) int A##n, const gsl_complex*A##p
#define KCMAT(A) int A##r, int A##c, const gsl_complex* A##p
#define FVEC(A) int A##n, float*A##p
#define FMAT(A) int A##r, int A##c, float* A##p
#define KFVEC(A) int A##n, const float*A##p
#define KFMAT(A) int A##r, int A##c, const float* A##p
#define QVEC(A) int A##n, gsl_complex_float*A##p
#define QMAT(A) int A##r, int A##c, gsl_complex_float* A##p
#define KQVEC(A) int A##n, const gsl_complex_float*A##p
#define KQMAT(A) int A##r, int A##c, const gsl_complex_float* A##p
#include <gsl/gsl_blas.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_fft_complex.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_poly.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_multiroots.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_multifit_nlin.h>
#include <string.h>
#include <stdio.h>
#define MACRO(B) do {B} while (0)
#define ERROR(CODE) MACRO(return CODE;)
#define REQUIRES(COND, CODE) MACRO(if(!(COND)) {ERROR(CODE);})
#define OK return 0;
#define MIN(A,B) ((A)<(B)?(A):(B))
#define MAX(A,B) ((A)>(B)?(A):(B))
#ifdef DBG
#define DEBUGMSG(M) printf("*** calling aux C function: %s\n",M);
#else
#define DEBUGMSG(M)
#endif
#define CHECK(RES,CODE) MACRO(if(RES) return CODE;)
#ifdef DBG
#define DEBUGMAT(MSG,X) printf(MSG" = \n"); gsl_matrix_fprintf(stdout,X,"%f"); printf("\n");
#else
#define DEBUGMAT(MSG,X)
#endif
#ifdef DBG
#define DEBUGVEC(MSG,X) printf(MSG" = \n"); gsl_vector_fprintf(stdout,X,"%f"); printf("\n");
#else
#define DEBUGVEC(MSG,X)
#endif
#define DVVIEW(A) gsl_vector_view A = gsl_vector_view_array(A##p,A##n)
#define DMVIEW(A) gsl_matrix_view A = gsl_matrix_view_array(A##p,A##r,A##c)
#define CVVIEW(A) gsl_vector_complex_view A = gsl_vector_complex_view_array((double*)A##p,A##n)
#define CMVIEW(A) gsl_matrix_complex_view A = gsl_matrix_complex_view_array((double*)A##p,A##r,A##c)
#define KDVVIEW(A) gsl_vector_const_view A = gsl_vector_const_view_array(A##p,A##n)
#define KDMVIEW(A) gsl_matrix_const_view A = gsl_matrix_const_view_array(A##p,A##r,A##c)
#define KCVVIEW(A) gsl_vector_complex_const_view A = gsl_vector_complex_const_view_array((double*)A##p,A##n)
#define KCMVIEW(A) gsl_matrix_complex_const_view A = gsl_matrix_complex_const_view_array((double*)A##p,A##r,A##c)
#define FVVIEW(A) gsl_vector_float_view A = gsl_vector_float_view_array(A##p,A##n)
#define FMVIEW(A) gsl_matrix_float_view A = gsl_matrix_float_view_array(A##p,A##r,A##c)
#define QVVIEW(A) gsl_vector_complex_float_view A = gsl_vector_float_complex_view_array((float*)A##p,A##n)
#define QMVIEW(A) gsl_matrix_complex_float_view A = gsl_matrix_float_complex_view_array((float*)A##p,A##r,A##c)
#define KFVVIEW(A) gsl_vector_float_const_view A = gsl_vector_float_const_view_array(A##p,A##n)
#define KFMVIEW(A) gsl_matrix_float_const_view A = gsl_matrix_float_const_view_array(A##p,A##r,A##c)
#define KQVVIEW(A) gsl_vector_complex_float_const_view A = gsl_vector_complex_float_const_view_array((float*)A##p,A##n)
#define KQMVIEW(A) gsl_matrix_complex_float_const_view A = gsl_matrix_complex_float_const_view_array((float*)A##p,A##r,A##c)
#define V(a) (&a.vector)
#define M(a) (&a.matrix)
#define GCVEC(A) int A##n, gsl_complex*A##p
#define KGCVEC(A) int A##n, const gsl_complex*A##p
#define GQVEC(A) int A##n, gsl_complex_float*A##p
#define KGQVEC(A) int A##n, const gsl_complex_float*A##p
#define BAD_SIZE 2000
#define BAD_CODE 2001
#define MEM 2002
#define BAD_FILE 2003
void no_abort_on_error() {
gsl_set_error_handler_off();
}
int sumF(KFVEC(x),FVEC(r)) {
DEBUGMSG("sumF");
REQUIRES(rn==1,BAD_SIZE);
int i;
float res = 0;
for (i = 0; i < xn; i++) res += xp[i];
rp[0] = res;
OK
}
int sumR(KRVEC(x),RVEC(r)) {
DEBUGMSG("sumR");
REQUIRES(rn==1,BAD_SIZE);
int i;
double res = 0;
for (i = 0; i < xn; i++) res += xp[i];
rp[0] = res;
OK
}
int sumQ(KQVEC(x),QVEC(r)) {
DEBUGMSG("sumQ");
REQUIRES(rn==1,BAD_SIZE);
int i;
gsl_complex_float res;
res.dat[0] = 0;
res.dat[1] = 0;
for (i = 0; i < xn; i++) {
res.dat[0] += xp[i].dat[0];
res.dat[1] += xp[i].dat[1];
}
rp[0] = res;
OK
}
int sumC(KCVEC(x),CVEC(r)) {
DEBUGMSG("sumC");
REQUIRES(rn==1,BAD_SIZE);
int i;
gsl_complex res;
res.dat[0] = 0;
res.dat[1] = 0;
for (i = 0; i < xn; i++) {
res.dat[0] += xp[i].dat[0];
res.dat[1] += xp[i].dat[1];
}
rp[0] = res;
OK
}
int prodF(KFVEC(x),FVEC(r)) {
DEBUGMSG("prodF");
REQUIRES(rn==1,BAD_SIZE);
int i;
float res = 1;
for (i = 0; i < xn; i++) res *= xp[i];
rp[0] = res;
OK
}
int prodR(KRVEC(x),RVEC(r)) {
DEBUGMSG("prodR");
REQUIRES(rn==1,BAD_SIZE);
int i;
double res = 1;
for (i = 0; i < xn; i++) res *= xp[i];
rp[0] = res;
OK
}
int prodQ(KQVEC(x),QVEC(r)) {
DEBUGMSG("prodQ");
REQUIRES(rn==1,BAD_SIZE);
int i;
gsl_complex_float res;
float temp;
res.dat[0] = 1;
res.dat[1] = 0;
for (i = 0; i < xn; i++) {
temp = res.dat[0] * xp[i].dat[0] - res.dat[1] * xp[i].dat[1];
res.dat[1] = res.dat[0] * xp[i].dat[1] + res.dat[1] * xp[i].dat[0];
res.dat[0] = temp;
}
rp[0] = res;
OK
}
int prodC(KCVEC(x),CVEC(r)) {
DEBUGMSG("prodC");
REQUIRES(rn==1,BAD_SIZE);
int i;
gsl_complex res;
double temp;
res.dat[0] = 1;
res.dat[1] = 0;
for (i = 0; i < xn; i++) {
temp = res.dat[0] * xp[i].dat[0] - res.dat[1] * xp[i].dat[1];
res.dat[1] = res.dat[0] * xp[i].dat[1] + res.dat[1] * xp[i].dat[0];
res.dat[0] = temp;
}
rp[0] = res;
OK
}
int dotF(KFVEC(x), KFVEC(y), FVEC(r)) {
DEBUGMSG("dotF");
REQUIRES(xn==yn,BAD_SIZE);
REQUIRES(rn==1,BAD_SIZE);
DEBUGMSG("dotF");
KFVVIEW(x);
KFVVIEW(y);
gsl_blas_sdot(V(x),V(y),rp);
OK
}
int dotR(KRVEC(x), KRVEC(y), RVEC(r)) {
DEBUGMSG("dotR");
REQUIRES(xn==yn,BAD_SIZE);
REQUIRES(rn==1,BAD_SIZE);
DEBUGMSG("dotR");
KDVVIEW(x);
KDVVIEW(y);
gsl_blas_ddot(V(x),V(y),rp);
OK
}
int dotQ(KQVEC(x), KQVEC(y), QVEC(r)) {
DEBUGMSG("dotQ");
REQUIRES(xn==yn,BAD_SIZE);
REQUIRES(rn==1,BAD_SIZE);
DEBUGMSG("dotQ");
KQVVIEW(x);
KQVVIEW(y);
gsl_blas_cdotu(V(x),V(y),rp);
OK
}
int dotC(KCVEC(x), KCVEC(y), CVEC(r)) {
DEBUGMSG("dotC");
REQUIRES(xn==yn,BAD_SIZE);
REQUIRES(rn==1,BAD_SIZE);
DEBUGMSG("dotC");
KCVVIEW(x);
KCVVIEW(y);
gsl_blas_zdotu(V(x),V(y),rp);
OK
}
int toScalarR(int code, KRVEC(x), RVEC(r)) {
REQUIRES(rn==1,BAD_SIZE);
DEBUGMSG("toScalarR");
KDVVIEW(x);
double res;
switch(code) {
case 0: { res = gsl_blas_dnrm2(V(x)); break; }
case 1: { res = gsl_blas_dasum(V(x)); break; }
case 2: { res = gsl_vector_max_index(V(x)); break; }
case 3: { res = gsl_vector_max(V(x)); break; }
case 4: { res = gsl_vector_min_index(V(x)); break; }
case 5: { res = gsl_vector_min(V(x)); break; }
default: ERROR(BAD_CODE);
}
rp[0] = res;
OK
}
int toScalarF(int code, KFVEC(x), FVEC(r)) {
REQUIRES(rn==1,BAD_SIZE);
DEBUGMSG("toScalarF");
KFVVIEW(x);
float res;
switch(code) {
case 0: { res = gsl_blas_snrm2(V(x)); break; }
case 1: { res = gsl_blas_sasum(V(x)); break; }
case 2: { res = gsl_vector_float_max_index(V(x)); break; }
case 3: { res = gsl_vector_float_max(V(x)); break; }
case 4: { res = gsl_vector_float_min_index(V(x)); break; }
case 5: { res = gsl_vector_float_min(V(x)); break; }
default: ERROR(BAD_CODE);
}
rp[0] = res;
OK
}
int toScalarC(int code, KCVEC(x), RVEC(r)) {
REQUIRES(rn==1,BAD_SIZE);
DEBUGMSG("toScalarC");
KCVVIEW(x);
double res;
switch(code) {
case 0: { res = gsl_blas_dznrm2(V(x)); break; }
case 1: { res = gsl_blas_dzasum(V(x)); break; }
default: ERROR(BAD_CODE);
}
rp[0] = res;
OK
}
int toScalarQ(int code, KQVEC(x), FVEC(r)) {
REQUIRES(rn==1,BAD_SIZE);
DEBUGMSG("toScalarQ");
KQVVIEW(x);
float res;
switch(code) {
case 0: { res = gsl_blas_scnrm2(V(x)); break; }
case 1: { res = gsl_blas_scasum(V(x)); break; }
default: ERROR(BAD_CODE);
}
rp[0] = res;
OK
}
inline double sign(double x) {
if(x>0) {
return +1.0;
} else if (x<0) {
return -1.0;
} else {
return 0.0;
}
}
inline float float_sign(float x) {
if(x>0) {
return +1.0;
} else if (x<0) {
return -1.0;
} else {
return 0.0;
}
}
inline gsl_complex complex_abs(gsl_complex z) {
gsl_complex r;
r.dat[0] = gsl_complex_abs(z);
r.dat[1] = 0;
return r;
}
inline gsl_complex complex_signum(gsl_complex z) {
gsl_complex r;
double mag;
if (z.dat[0] == 0 && z.dat[1] == 0) {
r.dat[0] = 0;
r.dat[1] = 0;
} else {
mag = gsl_complex_abs(z);
r.dat[0] = z.dat[0]/mag;
r.dat[1] = z.dat[1]/mag;
}
return r;
}
#define OP(C,F) case C: { for(k=0;k<xn;k++) rp[k] = F(xp[k]); OK }
#define OPV(C,E) case C: { for(k=0;k<xn;k++) rp[k] = E; OK }
int mapR(int code, KRVEC(x), RVEC(r)) {
int k;
REQUIRES(xn == rn,BAD_SIZE);
DEBUGMSG("mapR");
switch (code) {
OP(0,sin)
OP(1,cos)
OP(2,tan)
OP(3,fabs)
OP(4,asin)
OP(5,acos)
OP(6,atan) /* atan2 mediante vectorZip */
OP(7,sinh)
OP(8,cosh)
OP(9,tanh)
OP(10,gsl_asinh)
OP(11,gsl_acosh)
OP(12,gsl_atanh)
OP(13,exp)
OP(14,log)
OP(15,sign)
OP(16,sqrt)
default: ERROR(BAD_CODE);
}
}
int mapF(int code, KFVEC(x), FVEC(r)) {
int k;
REQUIRES(xn == rn,BAD_SIZE);
DEBUGMSG("mapF");
switch (code) {
OP(0,sin)
OP(1,cos)
OP(2,tan)
OP(3,fabs)
OP(4,asin)
OP(5,acos)
OP(6,atan) /* atan2 mediante vectorZip */
OP(7,sinh)
OP(8,cosh)
OP(9,tanh)
OP(10,gsl_asinh)
OP(11,gsl_acosh)
OP(12,gsl_atanh)
OP(13,exp)
OP(14,log)
OP(15,sign)
OP(16,sqrt)
default: ERROR(BAD_CODE);
}
}
int mapCAux(int code, KGCVEC(x), GCVEC(r)) {
int k;
REQUIRES(xn == rn,BAD_SIZE);
DEBUGMSG("mapC");
switch (code) {
OP(0,gsl_complex_sin)
OP(1,gsl_complex_cos)
OP(2,gsl_complex_tan)
OP(3,complex_abs)
OP(4,gsl_complex_arcsin)
OP(5,gsl_complex_arccos)
OP(6,gsl_complex_arctan)
OP(7,gsl_complex_sinh)
OP(8,gsl_complex_cosh)
OP(9,gsl_complex_tanh)
OP(10,gsl_complex_arcsinh)
OP(11,gsl_complex_arccosh)
OP(12,gsl_complex_arctanh)
OP(13,gsl_complex_exp)
OP(14,gsl_complex_log)
OP(15,complex_signum)
OP(16,gsl_complex_sqrt)
// gsl_complex_arg
// gsl_complex_abs
default: ERROR(BAD_CODE);
}
}
int mapC(int code, KCVEC(x), CVEC(r)) {
return mapCAux(code, xn, (gsl_complex*)xp, rn, (gsl_complex*)rp);
}
gsl_complex_float complex_float_math_fun(gsl_complex (*cf)(gsl_complex), gsl_complex_float a)
{
gsl_complex c;
gsl_complex r;
gsl_complex_float float_r;
c.dat[0] = a.dat[0];
c.dat[1] = a.dat[1];
r = (*cf)(c);
float_r.dat[0] = r.dat[0];
float_r.dat[1] = r.dat[1];
return float_r;
}
gsl_complex_float complex_float_math_op(gsl_complex (*cf)(gsl_complex,gsl_complex),
gsl_complex_float a,gsl_complex_float b)
{
gsl_complex c1;
gsl_complex c2;
gsl_complex r;
gsl_complex_float float_r;
c1.dat[0] = a.dat[0];
c1.dat[1] = a.dat[1];
c2.dat[0] = b.dat[0];
c2.dat[1] = b.dat[1];
r = (*cf)(c1,c2);
float_r.dat[0] = r.dat[0];
float_r.dat[1] = r.dat[1];
return float_r;
}
#define OPC(C,F) case C: { for(k=0;k<xn;k++) rp[k] = complex_float_math_fun(&F,xp[k]); OK }
#define OPCA(C,F,A,B) case C: { for(k=0;k<xn;k++) rp[k] = complex_float_math_op(&F,A,B); OK }
int mapQAux(int code, KGQVEC(x), GQVEC(r)) {
int k;
REQUIRES(xn == rn,BAD_SIZE);
DEBUGMSG("mapQ");
switch (code) {
OPC(0,gsl_complex_sin)
OPC(1,gsl_complex_cos)
OPC(2,gsl_complex_tan)
OPC(3,complex_abs)
OPC(4,gsl_complex_arcsin)
OPC(5,gsl_complex_arccos)
OPC(6,gsl_complex_arctan)
OPC(7,gsl_complex_sinh)
OPC(8,gsl_complex_cosh)
OPC(9,gsl_complex_tanh)
OPC(10,gsl_complex_arcsinh)
OPC(11,gsl_complex_arccosh)
OPC(12,gsl_complex_arctanh)
OPC(13,gsl_complex_exp)
OPC(14,gsl_complex_log)
OPC(15,complex_signum)
OPC(16,gsl_complex_sqrt)
// gsl_complex_arg
// gsl_complex_abs
default: ERROR(BAD_CODE);
}
}
int mapQ(int code, KQVEC(x), QVEC(r)) {
return mapQAux(code, xn, (gsl_complex_float*)xp, rn, (gsl_complex_float*)rp);
}
int mapValR(int code, double* pval, KRVEC(x), RVEC(r)) {
int k;
double val = *pval;
REQUIRES(xn == rn,BAD_SIZE);
DEBUGMSG("mapValR");
switch (code) {
OPV(0,val*xp[k])
OPV(1,val/xp[k])
OPV(2,val+xp[k])
OPV(3,val-xp[k])
OPV(4,pow(val,xp[k]))
OPV(5,pow(xp[k],val))
default: ERROR(BAD_CODE);
}
}
int mapValF(int code, float* pval, KFVEC(x), FVEC(r)) {
int k;
float val = *pval;
REQUIRES(xn == rn,BAD_SIZE);
DEBUGMSG("mapValF");
switch (code) {
OPV(0,val*xp[k])
OPV(1,val/xp[k])
OPV(2,val+xp[k])
OPV(3,val-xp[k])
OPV(4,pow(val,xp[k]))
OPV(5,pow(xp[k],val))
default: ERROR(BAD_CODE);
}
}
int mapValCAux(int code, gsl_complex* pval, KGCVEC(x), GCVEC(r)) {
int k;
gsl_complex val = *pval;
REQUIRES(xn == rn,BAD_SIZE);
DEBUGMSG("mapValC");
switch (code) {
OPV(0,gsl_complex_mul(val,xp[k]))
OPV(1,gsl_complex_div(val,xp[k]))
OPV(2,gsl_complex_add(val,xp[k]))
OPV(3,gsl_complex_sub(val,xp[k]))
OPV(4,gsl_complex_pow(val,xp[k]))
OPV(5,gsl_complex_pow(xp[k],val))
default: ERROR(BAD_CODE);
}
}
int mapValC(int code, gsl_complex* val, KCVEC(x), CVEC(r)) {
return mapValCAux(code, val, xn, (gsl_complex*)xp, rn, (gsl_complex*)rp);
}
int mapValQAux(int code, gsl_complex_float* pval, KQVEC(x), GQVEC(r)) {
int k;
gsl_complex_float val = *pval;
REQUIRES(xn == rn,BAD_SIZE);
DEBUGMSG("mapValQ");
switch (code) {
OPCA(0,gsl_complex_mul,val,xp[k])
OPCA(1,gsl_complex_div,val,xp[k])
OPCA(2,gsl_complex_add,val,xp[k])
OPCA(3,gsl_complex_sub,val,xp[k])
OPCA(4,gsl_complex_pow,val,xp[k])
OPCA(5,gsl_complex_pow,xp[k],val)
default: ERROR(BAD_CODE);
}
}
int mapValQ(int code, gsl_complex_float* val, KQVEC(x), QVEC(r)) {
return mapValQAux(code, val, xn, (gsl_complex_float*)xp, rn, (gsl_complex_float*)rp);
}
#define OPZE(C,msg,E) case C: {DEBUGMSG(msg) for(k=0;k<an;k++) rp[k] = E(ap[k],bp[k]); OK }
#define OPZV(C,msg,E) case C: {DEBUGMSG(msg) res = E(V(r),V(b)); CHECK(res,res); OK }
int zipR(int code, KRVEC(a), KRVEC(b), RVEC(r)) {
REQUIRES(an == bn && an == rn, BAD_SIZE);
int k;
switch(code) {
OPZE(4,"zipR Pow",pow)
OPZE(5,"zipR ATan2",atan2)
}
KDVVIEW(a);
KDVVIEW(b);
DVVIEW(r);
gsl_vector_memcpy(V(r),V(a));
int res;
switch(code) {
OPZV(0,"zipR Add",gsl_vector_add)
OPZV(1,"zipR Sub",gsl_vector_sub)
OPZV(2,"zipR Mul",gsl_vector_mul)
OPZV(3,"zipR Div",gsl_vector_div)
default: ERROR(BAD_CODE);
}
}
int zipF(int code, KFVEC(a), KFVEC(b), FVEC(r)) {
REQUIRES(an == bn && an == rn, BAD_SIZE);
int k;
switch(code) {
OPZE(4,"zipF Pow",pow)
OPZE(5,"zipF ATan2",atan2)
}
KFVVIEW(a);
KFVVIEW(b);
FVVIEW(r);
gsl_vector_float_memcpy(V(r),V(a));
int res;
switch(code) {
OPZV(0,"zipF Add",gsl_vector_float_add)
OPZV(1,"zipF Sub",gsl_vector_float_sub)
OPZV(2,"zipF Mul",gsl_vector_float_mul)
OPZV(3,"zipF Div",gsl_vector_float_div)
default: ERROR(BAD_CODE);
}
}
int zipCAux(int code, KGCVEC(a), KGCVEC(b), GCVEC(r)) {
REQUIRES(an == bn && an == rn, BAD_SIZE);
int k;
switch(code) {
OPZE(0,"zipC Add",gsl_complex_add)
OPZE(1,"zipC Sub",gsl_complex_sub)
OPZE(2,"zipC Mul",gsl_complex_mul)
OPZE(3,"zipC Div",gsl_complex_div)
OPZE(4,"zipC Pow",gsl_complex_pow)
//OPZE(5,"zipR ATan2",atan2)
}
//KCVVIEW(a);
//KCVVIEW(b);
//CVVIEW(r);
//gsl_vector_memcpy(V(r),V(a));
//int res;
switch(code) {
default: ERROR(BAD_CODE);
}
}
int zipC(int code, KCVEC(a), KCVEC(b), CVEC(r)) {
return zipCAux(code, an, (gsl_complex*)ap, bn, (gsl_complex*)bp, rn, (gsl_complex*)rp);
}
#define OPCZE(C,msg,E) case C: {DEBUGMSG(msg) for(k=0;k<an;k++) rp[k] = complex_float_math_op(&E,ap[k],bp[k]); OK }
int zipQAux(int code, KGQVEC(a), KGQVEC(b), GQVEC(r)) {
REQUIRES(an == bn && an == rn, BAD_SIZE);
int k;
switch(code) {
OPCZE(0,"zipQ Add",gsl_complex_add)
OPCZE(1,"zipQ Sub",gsl_complex_sub)
OPCZE(2,"zipQ Mul",gsl_complex_mul)
OPCZE(3,"zipQ Div",gsl_complex_div)
OPCZE(4,"zipQ Pow",gsl_complex_pow)
//OPZE(5,"zipR ATan2",atan2)
}
//KCVVIEW(a);
//KCVVIEW(b);
//CVVIEW(r);
//gsl_vector_memcpy(V(r),V(a));
//int res;
switch(code) {
default: ERROR(BAD_CODE);
}
}
int zipQ(int code, KQVEC(a), KQVEC(b), QVEC(r)) {
return zipQAux(code, an, (gsl_complex_float*)ap, bn, (gsl_complex_float*)bp, rn, (gsl_complex_float*)rp);
}
int fft(int code, KCVEC(X), CVEC(R)) {
REQUIRES(Xn == Rn,BAD_SIZE);
DEBUGMSG("fft");
int s = Xn;
gsl_fft_complex_wavetable * wavetable = gsl_fft_complex_wavetable_alloc (s);
gsl_fft_complex_workspace * workspace = gsl_fft_complex_workspace_alloc (s);
gsl_vector_const_view X = gsl_vector_const_view_array((double*)Xp, 2*Xn);
gsl_vector_view R = gsl_vector_view_array((double*)Rp, 2*Rn);
gsl_blas_dcopy(&X.vector,&R.vector);
if(code==0) {
gsl_fft_complex_forward ((double*)Rp, 1, s, wavetable, workspace);
} else {
gsl_fft_complex_inverse ((double*)Rp, 1, s, wavetable, workspace);
}
gsl_fft_complex_wavetable_free (wavetable);
gsl_fft_complex_workspace_free (workspace);
OK
}
int deriv(int code, double f(double, void*), double x, double h, double * result, double * abserr)
{
gsl_function F;
F.function = f;
F.params = 0;
if(code==0) return gsl_deriv_central (&F, x, h, result, abserr);
if(code==1) return gsl_deriv_forward (&F, x, h, result, abserr);
if(code==2) return gsl_deriv_backward (&F, x, h, result, abserr);
return 0;
}
int integrate_qng(double f(double, void*), double a, double b, double prec,
double *result, double*error) {
DEBUGMSG("integrate_qng");
gsl_function F;
F.function = f;
F.params = NULL;
size_t neval;
int res = gsl_integration_qng (&F, a,b, 0, prec, result, error, &neval);
CHECK(res,res);
OK
}
int integrate_qags(double f(double,void*), double a, double b, double prec, int w,
double *result, double* error) {
DEBUGMSG("integrate_qags");
gsl_integration_workspace * wk = gsl_integration_workspace_alloc (w);
gsl_function F;
F.function = f;
F.params = NULL;
int res = gsl_integration_qags (&F, a,b, 0, prec, w,wk, result, error);
CHECK(res,res);
gsl_integration_workspace_free (wk);
OK
}
int integrate_qagi(double f(double,void*), double prec, int w,
double *result, double* error) {
DEBUGMSG("integrate_qagi");
gsl_integration_workspace * wk = gsl_integration_workspace_alloc (w);
gsl_function F;
F.function = f;
F.params = NULL;
int res = gsl_integration_qagi (&F, 0, prec, w,wk, result, error);
CHECK(res,res);
gsl_integration_workspace_free (wk);
OK
}
int integrate_qagiu(double f(double,void*), double a, double prec, int w,
double *result, double* error) {
DEBUGMSG("integrate_qagiu");
gsl_integration_workspace * wk = gsl_integration_workspace_alloc (w);
gsl_function F;
F.function = f;
F.params = NULL;
int res = gsl_integration_qagiu (&F, a, 0, prec, w,wk, result, error);
CHECK(res,res);
gsl_integration_workspace_free (wk);
OK
}
int integrate_qagil(double f(double,void*), double b, double prec, int w,
double *result, double* error) {
DEBUGMSG("integrate_qagil");
gsl_integration_workspace * wk = gsl_integration_workspace_alloc (w);
gsl_function F;
F.function = f;
F.params = NULL;
int res = gsl_integration_qagil (&F, b, 0, prec, w,wk, result, error);
CHECK(res,res);
gsl_integration_workspace_free (wk);
OK
}
int polySolve(KRVEC(a), CVEC(z)) {
DEBUGMSG("polySolve");
REQUIRES(an>1,BAD_SIZE);
gsl_poly_complex_workspace * w = gsl_poly_complex_workspace_alloc (an);
int res = gsl_poly_complex_solve ((double*)ap, an, w, (double*)zp);
CHECK(res,res);
gsl_poly_complex_workspace_free (w);
OK;
}
int vector_fscanf(char*filename, RVEC(a)) {
DEBUGMSG("gsl_vector_fscanf");
DVVIEW(a);
FILE * f = fopen(filename,"r");
CHECK(!f,BAD_FILE);
int res = gsl_vector_fscanf(f,V(a));
CHECK(res,res);
fclose (f);
OK
}
int vector_fprintf(char*filename, char*fmt, RVEC(a)) {
DEBUGMSG("gsl_vector_fprintf");
DVVIEW(a);
FILE * f = fopen(filename,"w");
CHECK(!f,BAD_FILE);
int res = gsl_vector_fprintf(f,V(a),fmt);
CHECK(res,res);
fclose (f);
OK
}
int vector_fread(char*filename, RVEC(a)) {
DEBUGMSG("gsl_vector_fread");
DVVIEW(a);
FILE * f = fopen(filename,"r");
CHECK(!f,BAD_FILE);
int res = gsl_vector_fread(f,V(a));
CHECK(res,res);
fclose (f);
OK
}
int vector_fwrite(char*filename, RVEC(a)) {
DEBUGMSG("gsl_vector_fwrite");
DVVIEW(a);
FILE * f = fopen(filename,"w");
CHECK(!f,BAD_FILE);
int res = gsl_vector_fwrite(f,V(a));
CHECK(res,res);
fclose (f);
OK
}
int matrix_fprintf(char*filename, char*fmt, int ro, RMAT(m)) {
DEBUGMSG("matrix_fprintf");
FILE * f = fopen(filename,"w");
CHECK(!f,BAD_FILE);
int i,j,sr,sc;
if (ro==1) { sr = mc; sc = 1;} else { sr = 1; sc = mr;}
#define AT(M,r,c) (M##p[(r)*sr+(c)*sc])
for (i=0; i<mr; i++) {
for (j=0; j<mc-1; j++) {
fprintf(f,fmt,AT(m,i,j));
fprintf(f," ");
}
fprintf(f,fmt,AT(m,i,j));
fprintf(f,"\n");
}
fclose (f);
OK
}
//---------------------------------------------------------------
typedef double Trawfun(int, double*);
double only_f_aux_min(const gsl_vector*x, void *pars) {
Trawfun * f = (Trawfun*) pars;
double* p = (double*)calloc(x->size,sizeof(double));
int k;
for(k=0;k<x->size;k++) {
p[k] = gsl_vector_get(x,k);
}
double res = f(x->size,p);
free(p);
return res;
}
// this version returns info about intermediate steps
int minimize(int method, double f(int, double*), double tolsize, int maxit,
KRVEC(xi), KRVEC(sz), RMAT(sol)) {
REQUIRES(xin==szn && solr == maxit && solc == 3+xin,BAD_SIZE);
DEBUGMSG("minimizeList (nmsimplex)");
gsl_multimin_function my_func;
// extract function from pars
my_func.f = only_f_aux_min;
my_func.n = xin;
my_func.params = f;
size_t iter = 0;
int status;
double size;
const gsl_multimin_fminimizer_type *T;
gsl_multimin_fminimizer *s = NULL;
// Initial vertex size vector
KDVVIEW(sz);
// Starting point
KDVVIEW(xi);
// Minimizer nmsimplex, without derivatives
switch(method) {
case 0 : {T = gsl_multimin_fminimizer_nmsimplex; break; }
#ifdef GSL110
case 1 : {T = gsl_multimin_fminimizer_nmsimplex; break; }
#else
case 1 : {T = gsl_multimin_fminimizer_nmsimplex2; break; }
#endif
default: ERROR(BAD_CODE);
}
s = gsl_multimin_fminimizer_alloc (T, my_func.n);
gsl_multimin_fminimizer_set (s, &my_func, V(xi), V(sz));
do {
status = gsl_multimin_fminimizer_iterate (s);
size = gsl_multimin_fminimizer_size (s);
solp[iter*solc+0] = iter+1;
solp[iter*solc+1] = s->fval;
solp[iter*solc+2] = size;
int k;
for(k=0;k<xin;k++) {
solp[iter*solc+k+3] = gsl_vector_get(s->x,k);
}
iter++;
if (status) break;
status = gsl_multimin_test_size (size, tolsize);
} while (status == GSL_CONTINUE && iter < maxit);
int i,j;
for (i=iter; i<solr; i++) {
solp[i*solc+0] = iter;
for(j=1;j<solc;j++) {
solp[i*solc+j]=0.;
}
}
gsl_multimin_fminimizer_free(s);
OK
}
// working with the gradient
typedef struct {double (*f)(int, double*); int (*df)(int, double*, int, double*);} Tfdf;
double f_aux_min(const gsl_vector*x, void *pars) {
Tfdf * fdf = ((Tfdf*) pars);
double* p = (double*)calloc(x->size,sizeof(double));
int k;
for(k=0;k<x->size;k++) {
p[k] = gsl_vector_get(x,k);
}
double res = fdf->f(x->size,p);
free(p);
return res;
}
void df_aux_min(const gsl_vector * x, void * pars, gsl_vector * g) {
Tfdf * fdf = ((Tfdf*) pars);
double* p = (double*)calloc(x->size,sizeof(double));
double* q = (double*)calloc(g->size,sizeof(double));
int k;
for(k=0;k<x->size;k++) {
p[k] = gsl_vector_get(x,k);
}
fdf->df(x->size,p,g->size,q);
for(k=0;k<x->size;k++) {
gsl_vector_set(g,k,q[k]);
}
free(p);
free(q);
}
void fdf_aux_min(const gsl_vector * x, void * pars, double * f, gsl_vector * g) {
*f = f_aux_min(x,pars);
df_aux_min(x,pars,g);
}
int minimizeD(int method, double f(int, double*), int df(int, double*, int, double*),
double initstep, double minimpar, double tolgrad, int maxit,
KRVEC(xi), RMAT(sol)) {
REQUIRES(solr == maxit && solc == 2+xin,BAD_SIZE);
DEBUGMSG("minimizeWithDeriv (conjugate_fr)");
gsl_multimin_function_fdf my_func;
// extract function from pars
my_func.f = f_aux_min;
my_func.df = df_aux_min;
my_func.fdf = fdf_aux_min;
my_func.n = xin;
Tfdf stfdf;
stfdf.f = f;
stfdf.df = df;
my_func.params = &stfdf;
size_t iter = 0;
int status;
const gsl_multimin_fdfminimizer_type *T;
gsl_multimin_fdfminimizer *s = NULL;
// Starting point
KDVVIEW(xi);
// conjugate gradient fr
switch(method) {
case 0 : {T = gsl_multimin_fdfminimizer_conjugate_fr; break; }
case 1 : {T = gsl_multimin_fdfminimizer_conjugate_pr; break; }
case 2 : {T = gsl_multimin_fdfminimizer_vector_bfgs; break; }
case 3 : {T = gsl_multimin_fdfminimizer_vector_bfgs2; break; }
case 4 : {T = gsl_multimin_fdfminimizer_steepest_descent; break; }
default: ERROR(BAD_CODE);
}
s = gsl_multimin_fdfminimizer_alloc (T, my_func.n);
gsl_multimin_fdfminimizer_set (s, &my_func, V(xi), initstep, minimpar);
do {
status = gsl_multimin_fdfminimizer_iterate (s);
solp[iter*solc+0] = iter+1;
solp[iter*solc+1] = s->f;
int k;
for(k=0;k<xin;k++) {
solp[iter*solc+k+2] = gsl_vector_get(s->x,k);
}
iter++;
if (status) break;
status = gsl_multimin_test_gradient (s->gradient, tolgrad);
} while (status == GSL_CONTINUE && iter < maxit);
int i,j;
for (i=iter; i<solr; i++) {
solp[i*solc+0] = iter;
for(j=1;j<solc;j++) {
solp[i*solc+j]=0.;
}
}
gsl_multimin_fdfminimizer_free(s);
OK
}
//---------------------------------------------------------------
double only_f_aux_root(double x, void *pars) {
double (*f)(double) = (double (*)(double)) pars;
return f(x);
}
int root(int method, double f(double),
double epsrel, int maxit,
double xl, double xu, RMAT(sol)) {
REQUIRES(solr == maxit && solc == 4,BAD_SIZE);
DEBUGMSG("root_only_f");
gsl_function my_func;
// extract function from pars
my_func.function = only_f_aux_root;
my_func.params = f;
size_t iter = 0;
int status;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
// Starting point
switch(method) {
case 0 : {T = gsl_root_fsolver_bisection; printf("7\n"); break; }
case 1 : {T = gsl_root_fsolver_falsepos; break; }
case 2 : {T = gsl_root_fsolver_brent; break; }
default: ERROR(BAD_CODE);
}
s = gsl_root_fsolver_alloc (T);
gsl_root_fsolver_set (s, &my_func, xl, xu);
do {
double best, current_lo, current_hi;
status = gsl_root_fsolver_iterate (s);
best = gsl_root_fsolver_root (s);
current_lo = gsl_root_fsolver_x_lower (s);
current_hi = gsl_root_fsolver_x_upper (s);
solp[iter*solc] = iter + 1;
solp[iter*solc+1] = best;
solp[iter*solc+2] = current_lo;
solp[iter*solc+3] = current_hi;
iter++;
if (status) /* check if solver is stuck */
break;
status =
gsl_root_test_interval (current_lo, current_hi, 0, epsrel);
}
while (status == GSL_CONTINUE && iter < maxit);
int i;
for (i=iter; i<solr; i++) {
solp[i*solc+0] = iter;
solp[i*solc+1]=0.;
solp[i*solc+2]=0.;
solp[i*solc+3]=0.;
}
gsl_root_fsolver_free(s);
OK
}
typedef struct {
double (*f)(double);
double (*jf)(double);
} uniTfjf;
double f_aux_uni(double x, void *pars) {
uniTfjf * fjf = ((uniTfjf*) pars);
return (fjf->f)(x);
}
double jf_aux_uni(double x, void * pars) {
uniTfjf * fjf = ((uniTfjf*) pars);
return (fjf->jf)(x);
}
void fjf_aux_uni(double x, void * pars, double * f, double * g) {
*f = f_aux_uni(x,pars);
*g = jf_aux_uni(x,pars);
}
int rootj(int method, double f(double),
double df(double),
double epsrel, int maxit,
double x, RMAT(sol)) {
REQUIRES(solr == maxit && solc == 2,BAD_SIZE);
DEBUGMSG("root_fjf");
gsl_function_fdf my_func;
// extract function from pars
my_func.f = f_aux_uni;
my_func.df = jf_aux_uni;
my_func.fdf = fjf_aux_uni;
uniTfjf stfjf;
stfjf.f = f;
stfjf.jf = df;
my_func.params = &stfjf;
size_t iter = 0;
int status;
const gsl_root_fdfsolver_type *T;
gsl_root_fdfsolver *s;
// Starting point
switch(method) {
case 0 : {T = gsl_root_fdfsolver_newton;; break; }
case 1 : {T = gsl_root_fdfsolver_secant; break; }
case 2 : {T = gsl_root_fdfsolver_steffenson; break; }
default: ERROR(BAD_CODE);
}
s = gsl_root_fdfsolver_alloc (T);
gsl_root_fdfsolver_set (s, &my_func, x);
do {
double x0;
status = gsl_root_fdfsolver_iterate (s);
x0 = x;
x = gsl_root_fdfsolver_root(s);
solp[iter*solc+0] = iter+1;
solp[iter*solc+1] = x;
iter++;
if (status) /* check if solver is stuck */
break;
status =
gsl_root_test_delta (x, x0, 0, epsrel);
}
while (status == GSL_CONTINUE && iter < maxit);
int i;
for (i=iter; i<solr; i++) {
solp[i*solc+0] = iter;
solp[i*solc+1]=0.;
}
gsl_root_fdfsolver_free(s);
OK
}
//---------------------------------------------------------------
typedef void TrawfunV(int, double*, int, double*);
int only_f_aux_multiroot(const gsl_vector*x, void *pars, gsl_vector*y) {
TrawfunV * f = (TrawfunV*) pars;
double* p = (double*)calloc(x->size,sizeof(double));
double* q = (double*)calloc(y->size,sizeof(double));
int k;
for(k=0;k<x->size;k++) {
p[k] = gsl_vector_get(x,k);
}
f(x->size,p,y->size,q);
for(k=0;k<y->size;k++) {
gsl_vector_set(y,k,q[k]);
}
free(p);
free(q);
return 0; //hmmm
}
int multiroot(int method, void f(int, double*, int, double*),
double epsabs, int maxit,
KRVEC(xi), RMAT(sol)) {
REQUIRES(solr == maxit && solc == 1+2*xin,BAD_SIZE);
DEBUGMSG("root_only_f");
gsl_multiroot_function my_func;
// extract function from pars
my_func.f = only_f_aux_multiroot;
my_func.n = xin;
my_func.params = f;
size_t iter = 0;
int status;
const gsl_multiroot_fsolver_type *T;
gsl_multiroot_fsolver *s;
// Starting point
KDVVIEW(xi);
switch(method) {
case 0 : {T = gsl_multiroot_fsolver_hybrids;; break; }
case 1 : {T = gsl_multiroot_fsolver_hybrid; break; }
case 2 : {T = gsl_multiroot_fsolver_dnewton; break; }
case 3 : {T = gsl_multiroot_fsolver_broyden; break; }
default: ERROR(BAD_CODE);
}
s = gsl_multiroot_fsolver_alloc (T, my_func.n);
gsl_multiroot_fsolver_set (s, &my_func, V(xi));
do {
status = gsl_multiroot_fsolver_iterate (s);
solp[iter*solc+0] = iter+1;
int k;
for(k=0;k<xin;k++) {
solp[iter*solc+k+1] = gsl_vector_get(s->x,k);
}
for(k=xin;k<2*xin;k++) {
solp[iter*solc+k+1] = gsl_vector_get(s->f,k-xin);
}
iter++;
if (status) /* check if solver is stuck */
break;
status =
gsl_multiroot_test_residual (s->f, epsabs);
}
while (status == GSL_CONTINUE && iter < maxit);
int i,j;
for (i=iter; i<solr; i++) {
solp[i*solc+0] = iter;
for(j=1;j<solc;j++) {
solp[i*solc+j]=0.;
}
}
gsl_multiroot_fsolver_free(s);
OK
}
// working with the jacobian
typedef struct {int (*f)(int, double*, int, double *);
int (*jf)(int, double*, int, int, double*);} Tfjf;
int f_aux(const gsl_vector*x, void *pars, gsl_vector*y) {
Tfjf * fjf = ((Tfjf*) pars);
double* p = (double*)calloc(x->size,sizeof(double));
double* q = (double*)calloc(y->size,sizeof(double));
int k;
for(k=0;k<x->size;k++) {
p[k] = gsl_vector_get(x,k);
}
(fjf->f)(x->size,p,y->size,q);
for(k=0;k<y->size;k++) {
gsl_vector_set(y,k,q[k]);
}
free(p);
free(q);
return 0;
}
int jf_aux(const gsl_vector * x, void * pars, gsl_matrix * jac) {
Tfjf * fjf = ((Tfjf*) pars);
double* p = (double*)calloc(x->size,sizeof(double));
double* q = (double*)calloc((jac->size1)*(jac->size2),sizeof(double));
int i,j,k;
for(k=0;k<x->size;k++) {
p[k] = gsl_vector_get(x,k);
}
(fjf->jf)(x->size,p,jac->size1,jac->size2,q);
k=0;
for(i=0;i<jac->size1;i++) {
for(j=0;j<jac->size2;j++){
gsl_matrix_set(jac,i,j,q[k++]);
}
}
free(p);
free(q);
return 0;
}
int fjf_aux(const gsl_vector * x, void * pars, gsl_vector * f, gsl_matrix * g) {
f_aux(x,pars,f);
jf_aux(x,pars,g);
return 0;
}
int multirootj(int method, int f(int, double*, int, double*),
int jac(int, double*, int, int, double*),
double epsabs, int maxit,
KRVEC(xi), RMAT(sol)) {
REQUIRES(solr == maxit && solc == 1+2*xin,BAD_SIZE);
DEBUGMSG("root_fjf");
gsl_multiroot_function_fdf my_func;
// extract function from pars
my_func.f = f_aux;
my_func.df = jf_aux;
my_func.fdf = fjf_aux;
my_func.n = xin;
Tfjf stfjf;
stfjf.f = f;
stfjf.jf = jac;
my_func.params = &stfjf;
size_t iter = 0;
int status;
const gsl_multiroot_fdfsolver_type *T;
gsl_multiroot_fdfsolver *s;
// Starting point
KDVVIEW(xi);
switch(method) {
case 0 : {T = gsl_multiroot_fdfsolver_hybridsj;; break; }
case 1 : {T = gsl_multiroot_fdfsolver_hybridj; break; }
case 2 : {T = gsl_multiroot_fdfsolver_newton; break; }
case 3 : {T = gsl_multiroot_fdfsolver_gnewton; break; }
default: ERROR(BAD_CODE);
}
s = gsl_multiroot_fdfsolver_alloc (T, my_func.n);
gsl_multiroot_fdfsolver_set (s, &my_func, V(xi));
do {
status = gsl_multiroot_fdfsolver_iterate (s);
solp[iter*solc+0] = iter+1;
int k;
for(k=0;k<xin;k++) {
solp[iter*solc+k+1] = gsl_vector_get(s->x,k);
}
for(k=xin;k<2*xin;k++) {
solp[iter*solc+k+1] = gsl_vector_get(s->f,k-xin);
}
iter++;
if (status) /* check if solver is stuck */
break;
status =
gsl_multiroot_test_residual (s->f, epsabs);
}
while (status == GSL_CONTINUE && iter < maxit);
int i,j;
for (i=iter; i<solr; i++) {
solp[i*solc+0] = iter;
for(j=1;j<solc;j++) {
solp[i*solc+j]=0.;
}
}
gsl_multiroot_fdfsolver_free(s);
OK
}
//-------------- non linear least squares fitting -------------------
int nlfit(int method, int f(int, double*, int, double*),
int jac(int, double*, int, int, double*),
double epsabs, double epsrel, int maxit, int p,
KRVEC(xi), RMAT(sol)) {
REQUIRES(solr == maxit && solc == 2+xin,BAD_SIZE);
DEBUGMSG("nlfit");
const gsl_multifit_fdfsolver_type *T;
gsl_multifit_fdfsolver *s;
gsl_multifit_function_fdf my_f;
// extract function from pars
my_f.f = f_aux;
my_f.df = jf_aux;
my_f.fdf = fjf_aux;
my_f.n = p;
my_f.p = xin; // !!!!
Tfjf stfjf;
stfjf.f = f;
stfjf.jf = jac;
my_f.params = &stfjf;
size_t iter = 0;
int status;
KDVVIEW(xi);
//DMVIEW(cov);
switch(method) {
case 0 : { T = gsl_multifit_fdfsolver_lmsder; break; }
case 1 : { T = gsl_multifit_fdfsolver_lmder; break; }
default: ERROR(BAD_CODE);
}
s = gsl_multifit_fdfsolver_alloc (T, my_f.n, my_f.p);
gsl_multifit_fdfsolver_set (s, &my_f, V(xi));
do { status = gsl_multifit_fdfsolver_iterate (s);
solp[iter*solc+0] = iter+1;
solp[iter*solc+1] = gsl_blas_dnrm2 (s->f);
int k;
for(k=0;k<xin;k++) {
solp[iter*solc+k+2] = gsl_vector_get(s->x,k);
}
iter++;
if (status) /* check if solver is stuck */
break;
status = gsl_multifit_test_delta (s->dx, s->x, epsabs, epsrel);
}
while (status == GSL_CONTINUE && iter < maxit);
int i,j;
for (i=iter; i<solr; i++) {
solp[i*solc+0] = iter;
for(j=1;j<solc;j++) {
solp[i*solc+j]=0.;
}
}
//gsl_multifit_covar (s->J, 0.0, M(cov));
gsl_multifit_fdfsolver_free (s);
OK
}
//////////////////////////////////////////////////////
#define RAN(C,F) case C: { for(k=0;k<rn;k++) { rp[k]= F(gen); }; OK }
int random_vector(int seed, int code, RVEC(r)) {
DEBUGMSG("random_vector")
static gsl_rng * gen = NULL;
if (!gen) { gen = gsl_rng_alloc (gsl_rng_mt19937);}
gsl_rng_set (gen, seed);
int k;
switch (code) {
RAN(0,gsl_rng_uniform)
RAN(1,gsl_ran_ugaussian)
default: ERROR(BAD_CODE);
}
}
#undef RAN
//////////////////////////////////////////////////////
#include "gsl-ode.c"
//////////////////////////////////////////////////////
| {
"alphanum_fraction": 0.5769211577,
"avg_line_length": 27.2097759674,
"ext": "c",
"hexsha": "e727c91e48132042283bbea30869aa5b664ff3c7",
"lang": "C",
"max_forks_count": 145,
"max_forks_repo_forks_event_max_datetime": "2022-03-17T02:29:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-12T08:34:57.000Z",
"max_forks_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c",
"max_forks_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_forks_repo_name": "curiousleo/liquidhaskell",
"max_forks_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/gsl-aux.c",
"max_issues_count": 1300,
"max_issues_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T18:11:03.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-01T05:41:07.000Z",
"max_issues_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_issues_repo_name": "curiousleo/liquidhaskell",
"max_issues_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/gsl-aux.c",
"max_line_length": 124,
"max_stars_count": 941,
"max_stars_repo_head_hexsha": "a265c044159480b3ddedbbf4982736a33ec8872c",
"max_stars_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_stars_repo_name": "curiousleo/liquidhaskell",
"max_stars_repo_path": "benchmarks/hmatrix-0.15.0.1/lib/Numeric/GSL/gsl-aux.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-26T10:32:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-13T10:51:40.000Z",
"num_tokens": 12911,
"size": 40080
} |
#include "scf.h"
#include "scf_decompose.h"
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_sf_gegenbauer.h>
/* computes a!/b! = a(a-1)(a-2)...(b+1) */
double factorial_frac(int a, int b)
{
if(a<0 || b<0)
{
perror("factorial_frac: either a or b is negative!!\n");
exit(1);
}
int recip = 0;
if(a==b)
return 1.0;
else if(a<b)
{
int temp = b;
b = a;
a = temp;
recip = 1;
}
double val = 1;
while(a > b)
{
val = val * a;
a--;
}
if(recip)
val = 1.0/val;
return val;
}
void scf_integral(double* mat_cos, double* mat_sin)
{
long long k;
double* rr = (double*)malloc(NumPart*sizeof(double));
double* cos_tt = (double*)malloc(NumPart*sizeof(double));
double* pp = (double*)malloc(NumPart*sizeof(double));
#ifdef USE_GSL_GEGENBAUER_HOST
double* xxi = (double*)malloc(NumPart*sizeof(double));
double this_Cna;
#endif
/* cos_tt is calculated directly by cos(theta)=z/r because
we never need theta by itself, but only cos(theta) in the
legendre polynomials. Also, notice that cos_tt must be
calculated in double precision because with single precision
zz[k] can be greater than rr[k] by a tiny bit, which
the plgndr routine will complain later on */
for(k=0; k<NumPart; k++)
{
rr[k] = sqrt((double)xx[k]*(double)xx[k] +
(double)yy[k]*(double)yy[k] +
(double)zz[k]*(double)zz[k]);
cos_tt[k] = (double)zz[k]/rr[k];
pp[k] = atan2(yy[k], xx[k]);
#ifdef USE_GSL_GEGENBAUER_HOST
xxi[k] = (rr[k]-1.0) / (rr[k]+1.0);
#endif
}
double N_lm;
double K_nl, I_nl, A_nl;
double gamm1, gamm2;
float this_Phi_nl;
double* P_lm_k = (double*)malloc(NumPart*sizeof(double));
double m_Phinlk_Plm, Nlm_Anl;
double sum_cos = 0.0;
double sum_sin = 0.0;
int n, l, m;
for(l=0; l<=decompose_lmax; l++)
{
for(m=0; m<=l; m++)
{
N_lm = (2*l+1)/4.0/PI * 2.0 * factorial_frac(l-m,l+m);
if(m==0)
N_lm = 0.5*N_lm;
for (k=0; k<NumPart; k++)
{
P_lm_k[k] = gsl_sf_legendre_Plm(l,m, cos_tt[k]);
/* Note: This can be computed more efficiently using gsl_sf_legendre_Plm_array
which computes a list of legendre polynomials at constant m with varying l.
but this changes the code and I don't have time to deal with that for now.
Numerical Recipes's plgndr is actually faster, but single precision. */
}
for(n=0; n<=decompose_nmax; n++)
{
K_nl = 0.5*n*(n+4*l+3)+(l+1)*(2*l+1);
gamm1 = factorial_frac(n+4*l+2,n);
gamm2 = factorial_frac(2*l+1, 2*(2*l+1));
I_nl = -K_nl/(n+2*l+1.5) * gamm1 * gamm2 * gamm2;
A_nl = 1.0/I_nl;
sum_cos = 0.0;
sum_sin = 0.0;
for(k=0; k<NumPart; k++)
{
#ifdef USE_GSL_GEGENBAUER_HOST
this_Cna = gsl_sf_gegenpoly_n(n, 2*l+1.5, xxi[k]);
this_Phi_nl = Phi_nl(this_Cna, l, rr[k]);
#else
this_Phi_nl = Phi_nl(n, l, rr[k]);
#endif
m_Phinlk_Plm = mm[k] * this_Phi_nl * P_lm_k[k];
sum_cos += m_Phinlk_Plm * cos(m*pp[k]);
sum_sin += m_Phinlk_Plm * sin(m*pp[k]);
}
Nlm_Anl = N_lm * A_nl;
mat_cos[ind(n,l,m)] = sum_cos * Nlm_Anl;
mat_sin[ind(n,l,m)] = sum_sin * Nlm_Anl;
} // n loop
} // m loop
} // l loop
free(rr);
free(pp);
free(cos_tt);
free(P_lm_k);
}
void scf_integral_spherical(float* mat_cos)
{
long long k;
float* rr = (float*)malloc(NumPart*sizeof(float));
double temp_r;
for(k=0; k<NumPart; k++)
{
temp_r = sqrt(xx[k]*xx[k] + yy[k]*yy[k] + zz[k]*zz[k]);
rr[k] = (float)temp_r;
}
double N00 = 0.07957747154; /* = 1/(4*pi) */
double K_n0, I_n0, A_n0;
float this_Phi_n0;
double sum_cos = 0.0;
int n;
for(n=0; n<=decompose_nmax; n++)
{
K_n0 = 0.5*n*(n+3)+1;
I_n0 = -K_n0/(n+1.5)/4.0 * (n+2) * (n+1);
A_n0 = 1.0/I_n0;
sum_cos = 0.0;
for(k=0; k<NumPart; k++)
{
this_Phi_n0 = Phi_n0(n, rr[k]);
sum_cos += mm[k] * this_Phi_n0;
}
mat_cos[n] = (float) (sum_cos * A_n0 * N00);
} // n loop
free(rr);
}
| {
"alphanum_fraction": 0.481595092,
"avg_line_length": 25.206185567,
"ext": "c",
"hexsha": "fe990a07f6f5c08b74bc8a802f1f8f630feccfb3",
"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": "e04d8738e92333f546ec6ef4b4f61c7e87456aba",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "wayne927/vl2-scf",
"max_forks_repo_path": "scf_integral.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e04d8738e92333f546ec6ef4b4f61c7e87456aba",
"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": "wayne927/vl2-scf",
"max_issues_repo_path": "scf_integral.c",
"max_line_length": 94,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "e04d8738e92333f546ec6ef4b4f61c7e87456aba",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "wayne927/vl2-scf",
"max_stars_repo_path": "scf_integral.c",
"max_stars_repo_stars_event_max_datetime": "2017-03-08T23:45:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-07T19:05:02.000Z",
"num_tokens": 1500,
"size": 4890
} |
/* multifit_nlinear/dogleg.c
*
* Copyright (C) 2016 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_multifit_nlinear.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
/*
* This module contains an implementation of the Powell dogleg
* algorithm for nonlinear optimization problems. This implementation
* closely follows the following works:
*
* [1] H. B. Nielsen, K. Madsen, Introduction to Optimization and
* Data Fitting, Informatics and Mathematical Modeling,
* Technical University of Denmark (DTU), 2010.
*
* [2] J. E. Dennis and H. H. W. Mei, Two new unconstrained optimization
* algorithms which use function and gradient values, J. Opt. Theory and
* Appl., 28(4), 1979.
*/
typedef struct
{
size_t n; /* number of observations */
size_t p; /* number of parameters */
gsl_vector *dx_gn; /* Gauss-Newton step, size p */
gsl_vector *dx_sd; /* steepest descent step, size p */
double norm_Dgn; /* || D dx_gn || */
double norm_Dsd; /* || D dx_sd || */
double norm_Dinvg; /* || D^{-1} g || */
double norm_JDinv2g; /* || J D^{-2} g || */
gsl_vector *workp; /* workspace, length p */
gsl_vector *workn; /* workspace, length n */
/* tunable parameters */
gsl_multifit_nlinear_parameters params;
} dogleg_state_t;
#include "common.c"
static void * dogleg_alloc (const void * params, const size_t n, const size_t p);
static void dogleg_free(void *vstate);
static int dogleg_init(const void *vtrust_state, void *vstate);
static int dogleg_preloop(const void * vtrust_state, void * vstate);
static int dogleg_step(const void * vtrust_state, const double delta,
gsl_vector * dx, void * vstate);
static int dogleg_double_step(const void * vtrust_state, const double delta,
gsl_vector * dx, void * vstate);
static int dogleg_preduction(const void * vtrust_state, const gsl_vector * dx,
double * pred, void * vstate);
static int dogleg_calc_gn(const gsl_multifit_nlinear_trust_state * trust_state, gsl_vector * dx);
static double dogleg_beta(const double t, const double delta,
const gsl_vector * diag, dogleg_state_t * state);
static void *
dogleg_alloc (const void * params, const size_t n, const size_t p)
{
const gsl_multifit_nlinear_parameters *mparams = (const gsl_multifit_nlinear_parameters *) params;
dogleg_state_t *state;
state = calloc(1, sizeof(dogleg_state_t));
if (state == NULL)
{
GSL_ERROR_NULL ("failed to allocate dogleg state", GSL_ENOMEM);
}
state->dx_gn = gsl_vector_alloc(p);
if (state->dx_gn == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for dx_gn", GSL_ENOMEM);
}
state->dx_sd = gsl_vector_alloc(p);
if (state->dx_sd == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for dx_sd", GSL_ENOMEM);
}
state->workp = gsl_vector_alloc(p);
if (state->workp == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for workp", GSL_ENOMEM);
}
state->workn = gsl_vector_alloc(n);
if (state->workn == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for workn", GSL_ENOMEM);
}
state->n = n;
state->p = p;
state->params = *mparams;
return state;
}
static void
dogleg_free(void *vstate)
{
dogleg_state_t *state = (dogleg_state_t *) vstate;
if (state->dx_gn)
gsl_vector_free(state->dx_gn);
if (state->dx_sd)
gsl_vector_free(state->dx_sd);
if (state->workp)
gsl_vector_free(state->workp);
if (state->workn)
gsl_vector_free(state->workn);
free(state);
}
/*
dogleg_init()
Initialize dogleg solver
Inputs: vtrust_state - trust state
vstate - workspace
Return: success/error
*/
static int
dogleg_init(const void *vtrust_state, void *vstate)
{
(void)vtrust_state;
(void)vstate;
return GSL_SUCCESS;
}
/*
dogleg_preloop()
Initialize dogleg method prior to iteration loop.
This involves computing the steepest descent step. The
Gauss-Newton step is computed if needed in the _step()
routines.
Notes: on output,
1) state->dx_sd contains steepest descent step
2) state->norm_Dinvg contains || D^{-1} g ||
3) state->norm_JDinv2g contains || J D^{-2} g ||
*/
static int
dogleg_preloop(const void * vtrust_state, void * vstate)
{
const gsl_multifit_nlinear_trust_state *trust_state =
(const gsl_multifit_nlinear_trust_state *) vtrust_state;
dogleg_state_t *state = (dogleg_state_t *) vstate;
double u;
double alpha; /* ||g||^2 / ||Jg||^2 */
/* calculate the steepest descent step */
/* compute workp = D^{-1} g and its norm */
gsl_vector_memcpy(state->workp, trust_state->g);
gsl_vector_div(state->workp, trust_state->diag);
state->norm_Dinvg = gsl_blas_dnrm2(state->workp);
/* compute workp = D^{-2} g */
gsl_vector_div(state->workp, trust_state->diag);
/* compute: workn = J D^{-2} g */
gsl_blas_dgemv(CblasNoTrans, 1.0, trust_state->J, state->workp, 0.0, state->workn);
state->norm_JDinv2g = gsl_blas_dnrm2(state->workn);
u = state->norm_Dinvg / state->norm_JDinv2g;
alpha = u * u;
/* dx_sd = -alpha D^{-2} g */
gsl_vector_memcpy(state->dx_sd, state->workp);
gsl_vector_scale(state->dx_sd, -alpha);
state->norm_Dsd = scaled_enorm(trust_state->diag, state->dx_sd);
state->norm_Dgn = -1.0; /* computed later if needed */
return GSL_SUCCESS;
}
/*
dogleg_step()
Calculate a new step vector
*/
static int
dogleg_step(const void * vtrust_state, const double delta,
gsl_vector * dx, void * vstate)
{
const gsl_multifit_nlinear_trust_state *trust_state =
(const gsl_multifit_nlinear_trust_state *) vtrust_state;
dogleg_state_t *state = (dogleg_state_t *) vstate;
if (state->norm_Dsd >= delta)
{
/* steepest descent step is outside trust region;
* truncate steepest descent step to trust region boundary */
gsl_vector_memcpy(dx, state->dx_sd);
gsl_vector_scale(dx, delta / state->norm_Dsd);
}
else
{
/* compute Gauss-Newton step if needed */
if (state->norm_Dgn < 0.0)
{
int status = dogleg_calc_gn(trust_state, state->dx_gn);
if (status)
return status;
/* compute || D dx_gn || */
state->norm_Dgn = scaled_enorm(trust_state->diag, state->dx_gn);
}
if (state->norm_Dgn <= delta)
{
/* Gauss-Newton step is inside trust region, use it as final step
* since it is the global minimizer of the quadratic model function */
gsl_vector_memcpy(dx, state->dx_gn);
}
else
{
/* Gauss-Newton step is outside trust region, but steepest
* descent is inside; use dogleg step */
double beta = dogleg_beta(1.0, delta, trust_state->diag, state);
/* compute: workp = dx_gn - dx_sd */
scaled_addition(1.0, state->dx_gn, -1.0, state->dx_sd, state->workp);
/* dx = dx_sd + beta*(dx_gn - dx_sd) */
scaled_addition(beta, state->workp, 1.0, state->dx_sd, dx);
}
}
return GSL_SUCCESS;
}
/*
dogleg_double_step()
Calculate a new step with double dogleg method. Based on
section 3 of [2]
*/
static int
dogleg_double_step(const void * vtrust_state, const double delta,
gsl_vector * dx, void * vstate)
{
const double alpha_fac = 0.8; /* recommended value from Dennis and Mei */
const gsl_multifit_nlinear_trust_state *trust_state =
(const gsl_multifit_nlinear_trust_state *) vtrust_state;
dogleg_state_t *state = (dogleg_state_t *) vstate;
if (state->norm_Dsd >= delta)
{
/* steepest descent step is outside trust region;
* truncate steepest descent step to trust region boundary */
gsl_vector_memcpy(dx, state->dx_sd);
gsl_vector_scale(dx, delta / state->norm_Dsd);
}
else
{
/* compute Gauss-Newton step if needed */
if (state->norm_Dgn < 0.0)
{
int status = dogleg_calc_gn(trust_state, state->dx_gn);
if (status)
return status;
/* compute || D dx_gn || */
state->norm_Dgn = scaled_enorm(trust_state->diag, state->dx_gn);
}
if (state->norm_Dgn <= delta)
{
/* Gauss-Newton step is inside trust region, use it as final step
* since it is the global minimizer of the quadratic model function */
gsl_vector_memcpy(dx, state->dx_gn);
}
else
{
double t, u, v, c;
/* compute: u = ||D^{-1} g||^2 / ||J D^{-2} g||^2 */
v = state->norm_Dinvg / state->norm_JDinv2g;
u = v * v;
/* compute: v = g^T dx_gn */
gsl_blas_ddot(trust_state->g, state->dx_gn, &v);
/* compute: c = ||D^{-1} g||^4 / (||J D^{-2} g||^2 * |g^T dx_gn|) */
c = u * (state->norm_Dinvg / fabs(v)) * state->norm_Dinvg;
/* compute: t = 1 - alpha_fac*(1-c) */
t = 1.0 - alpha_fac*(1.0 - c);
if (t * state->norm_Dgn <= delta)
{
/* set dx = (delta / ||D dx_gn||) dx_gn */
gsl_vector_memcpy(dx, state->dx_gn);
gsl_vector_scale(dx, delta / state->norm_Dgn);
}
else
{
/* Cauchy point is inside, Gauss-Newton is outside trust region;
* use double dogleg step */
double beta = dogleg_beta(t, delta, trust_state->diag, state);
/* compute: workp = t*dx_gn - dx_sd */
scaled_addition(t, state->dx_gn, -1.0, state->dx_sd, state->workp);
/* dx = dx_sd + beta*(t*dx_gn - dx_sd) */
scaled_addition(beta, state->workp, 1.0, state->dx_sd, dx);
}
}
}
return GSL_SUCCESS;
}
static int
dogleg_preduction(const void * vtrust_state, const gsl_vector * dx,
double * pred, void * vstate)
{
const gsl_multifit_nlinear_trust_state *trust_state =
(const gsl_multifit_nlinear_trust_state *) vtrust_state;
dogleg_state_t *state = (dogleg_state_t *) vstate;
*pred = quadratic_preduction(trust_state->f, trust_state->J, dx, state->workn);
return GSL_SUCCESS;
}
/*
dogleg_calc_gn()
Calculate Gauss-Newton step which satisfies:
J dx_gn = -f
Inputs: trust_state - trust state variables
dx - (output) Gauss-Newton step
Return: success/error
*/
static int
dogleg_calc_gn(const gsl_multifit_nlinear_trust_state * trust_state, gsl_vector * dx)
{
int status;
const gsl_multifit_nlinear_parameters *params = trust_state->params;
/* initialize linear least squares solver */
status = (params->solver->init)(trust_state, trust_state->solver_state);
if (status)
return status;
/* prepare the linear solver to compute Gauss-Newton step */
status = (params->solver->presolve)(0.0, trust_state, trust_state->solver_state);
if (status)
return status;
/* solve: J dx_gn = -f for Gauss-Newton step */
status = (params->solver->solve)(trust_state->f,
dx,
trust_state,
trust_state->solver_state);
if (status)
return status;
return GSL_SUCCESS;
}
/*
dogleg_beta()
This function finds beta in [0,1] such that the step
dx = dx_sd + beta*(t*dx_gn - dx_sd)
has norm
||D dx|| = delta
beta is the positive root of the quadratic:
a beta^2 + b beta + c = 0
with
a = ||D(t*dx_gn - dx_sd)||^2
b = 2 dx_sd^T D^T D (t*dx_gn - dx_sd)
c = ||D dx_sd||^2 - delta^2
Inputs: t - amount of Gauss-Newton step to use for dogleg
(= 1 for classical dogleg, <= 1 for double dogleg)
delta - trust region radius
diag - diag(D) scaling matrix
state - workspace
*/
static double
dogleg_beta(const double t, const double delta,
const gsl_vector * diag, dogleg_state_t * state)
{
double beta;
double a, b, c;
/* compute: workp = t*dx_gn - dx_sd */
scaled_addition(t, state->dx_gn, -1.0, state->dx_sd, state->workp);
/* a = || D (t*dx_gn - dx_sd) ||^2 */
a = scaled_enorm(diag, state->workp);
a *= a;
/* workp = D^T D (t*dx_gn - dx_sd) */
gsl_vector_mul(state->workp, diag);
gsl_vector_mul(state->workp, diag);
/* b = 2 dx_sd^T D^T D (t*dx_gn - dx-sd) */
gsl_blas_ddot(state->dx_sd, state->workp, &b);
b *= 2.0;
/* c = || D dx_sd ||^2 - delta^2 = (||D dx_sd|| + delta) (||D dx_sd|| - delta) */
c = (state->norm_Dsd + delta) * (state->norm_Dsd - delta);
if (b > 0.0)
{
beta = (-2.0 * c) / (b + sqrt(b*b - 4.0*a*c));
}
else
{
beta = (-b + sqrt(b*b - 4.0*a*c)) / (2.0 * a);
}
return beta;
}
static const gsl_multifit_nlinear_trs dogleg_type =
{
"dogleg",
dogleg_alloc,
dogleg_init,
dogleg_preloop,
dogleg_step,
dogleg_preduction,
dogleg_free
};
const gsl_multifit_nlinear_trs *gsl_multifit_nlinear_trs_dogleg = &dogleg_type;
static const gsl_multifit_nlinear_trs ddogleg_type =
{
"double-dogleg",
dogleg_alloc,
dogleg_init,
dogleg_preloop,
dogleg_double_step,
dogleg_preduction,
dogleg_free
};
const gsl_multifit_nlinear_trs *gsl_multifit_nlinear_trs_ddogleg = &ddogleg_type;
| {
"alphanum_fraction": 0.6340978485,
"avg_line_length": 28.7408163265,
"ext": "c",
"hexsha": "f006cdae4b57f5212e5fad53c3291a9082ca178c",
"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/multifit_nlinear/dogleg.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/multifit_nlinear/dogleg.c",
"max_line_length": 100,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/multifit_nlinear/dogleg.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": 3973,
"size": 14083
} |
/* min/gsl_min.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 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_MIN_H__
#define __GSL_MIN_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_math.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
{
const char *name;
size_t size;
int (*set) (void *state, gsl_function * f, double x_minimum, double f_minimum, double x_lower, double f_lower, double x_upper, double f_upper);
int (*iterate) (void *state, gsl_function * f, double * x_minimum, double * f_minimum, double * x_lower, double * f_lower, double * x_upper, double * f_upper);
}
gsl_min_fminimizer_type;
typedef struct
{
const gsl_min_fminimizer_type * type;
gsl_function * function ;
double x_minimum ;
double x_lower ;
double x_upper ;
double f_minimum, f_lower, f_upper;
void *state;
}
gsl_min_fminimizer;
gsl_min_fminimizer *
gsl_min_fminimizer_alloc (const gsl_min_fminimizer_type * T) ;
void gsl_min_fminimizer_free (gsl_min_fminimizer * s);
int gsl_min_fminimizer_set (gsl_min_fminimizer * s,
gsl_function * f, double x_minimum,
double x_lower, double x_upper);
int gsl_min_fminimizer_set_with_values (gsl_min_fminimizer * s,
gsl_function * f,
double x_minimum, double f_minimum,
double x_lower, double f_lower,
double x_upper, double f_upper);
int gsl_min_fminimizer_iterate (gsl_min_fminimizer * s);
const char * gsl_min_fminimizer_name (const gsl_min_fminimizer * s);
double gsl_min_fminimizer_x_minimum (const gsl_min_fminimizer * s);
double gsl_min_fminimizer_x_lower (const gsl_min_fminimizer * s);
double gsl_min_fminimizer_x_upper (const gsl_min_fminimizer * s);
double gsl_min_fminimizer_f_minimum (const gsl_min_fminimizer * s);
double gsl_min_fminimizer_f_lower (const gsl_min_fminimizer * s);
double gsl_min_fminimizer_f_upper (const gsl_min_fminimizer * s);
/* Deprecated, use x_minimum instead */
double gsl_min_fminimizer_minimum (const gsl_min_fminimizer * s);
int
gsl_min_test_interval (double x_lower, double x_upper, double epsabs, double epsrel);
GSL_VAR const gsl_min_fminimizer_type * gsl_min_fminimizer_goldensection;
GSL_VAR const gsl_min_fminimizer_type * gsl_min_fminimizer_brent;
GSL_VAR const gsl_min_fminimizer_type * gsl_min_fminimizer_quad_golden;
typedef
int (*gsl_min_bracketing_function)(gsl_function *f,
double *x_minimum,double * f_minimum,
double *x_lower, double * f_lower,
double *x_upper, double * f_upper,
size_t eval_max);
int
gsl_min_find_bracket(gsl_function *f,double *x_minimum,double * f_minimum,
double *x_lower, double * f_lower,
double *x_upper, double * f_upper,
size_t eval_max);
__END_DECLS
#endif /* __GSL_MIN_H__ */
| {
"alphanum_fraction": 0.684822976,
"avg_line_length": 36.0625,
"ext": "h",
"hexsha": "2cfa8023be99f1448cd22b68b3316223081c8720",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z",
"max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "snipekill/FPGen",
"max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_min.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"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": "snipekill/FPGen",
"max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_min.h",
"max_line_length": 163,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "snipekill/FPGen",
"max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_min.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z",
"num_tokens": 987,
"size": 4039
} |
//
// Created by agibsonccc on 2/6/16.
//
#ifndef NATIVEOPERATIONS_CBLAS_ENUM_CONVERSION_H_H
#define NATIVEOPERATIONS_CBLAS_ENUM_CONVERSION_H_H
#include <cblas.h>
/*
enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102 };
enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113,
AtlasConj=114};
enum CBLAS_UPLO {CblasUpper=121, CblasLower=122};
enum CBLAS_DIAG {CblasNonUnit=131, CblasUnit=132};
enum CBLAS_SIDE {CblasLeft=141, CblasRight=142};
*/
#include <dll.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Converts a character
* to its proper enum
* for row (c) or column (f) ordering
* default is row major
*/
CBLAS_ORDER convertOrder(int from);
/**
* Converts a character to its proper enum
* t -> transpose
* n -> no transpose
* c -> conj
*/
CBLAS_TRANSPOSE convertTranspose(int from);
/**
* Upper or lower
* U/u -> upper
* L/l -> lower
*
* Default is upper
*/
CBLAS_UPLO convertUplo(int from);
/**
* For diagonals:
* u/U -> unit
* n/N -> non unit
*
* Default: unit
*/
CBLAS_DIAG convertDiag(int from);
/**
* Side of a matrix, left or right
* l /L -> left
* r/R -> right
* default: left
*/
CBLAS_SIDE convertSide(int from);
#ifdef __cplusplus
}
#endif
#endif //NATIVEOPERATIONS_CBLAS_ENUM_CONVERSION_H_H
| {
"alphanum_fraction": 0.7038491752,
"avg_line_length": 19,
"ext": "h",
"hexsha": "496baf71b87cee2f1b09f1f76b677a1e5c904e19",
"lang": "C",
"max_forks_count": 108,
"max_forks_repo_forks_event_max_datetime": "2021-03-29T05:25:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-01-19T15:11:03.000Z",
"max_forks_repo_head_hexsha": "96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "rexwong/deeplearning4j",
"max_forks_repo_path": "libnd4j/include/cblas_enum_conversion.h",
"max_issues_count": 331,
"max_issues_repo_head_hexsha": "96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38",
"max_issues_repo_issues_event_max_datetime": "2018-06-08T07:16:15.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-03-07T21:26:26.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "rexwong/deeplearning4j",
"max_issues_repo_path": "libnd4j/include/cblas_enum_conversion.h",
"max_line_length": 75,
"max_stars_count": 97,
"max_stars_repo_head_hexsha": "96a12b3b0ee7282f245c8a0af1c90b0ce2c2ed38",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "rexwong/deeplearning4j",
"max_stars_repo_path": "libnd4j/include/cblas_enum_conversion.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-09T17:36:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-02-15T07:08:45.000Z",
"num_tokens": 394,
"size": 1273
} |
/* ieee-utils/fp-os2.c
*
* Copyright (C) 2001 Henry Sobotka <sobotka@axess.com>
*
* 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 <float.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_errno.h>
int
gsl_ieee_set_mode (int precision, int rounding, int exception_mask)
{
unsigned mode = 0;
switch (precision)
{
case GSL_IEEE_SINGLE_PRECISION:
_control87(PC_24, MCW_PC);
break ;
case GSL_IEEE_DOUBLE_PRECISION:
_control87(PC_53, MCW_PC);
break ;
case GSL_IEEE_EXTENDED_PRECISION:
_control87(PC_64, MCW_PC);
break ;
}
switch (rounding)
{
case GSL_IEEE_ROUND_TO_NEAREST:
_control87(RC_NEAR, MCW_RC);
break ;
case GSL_IEEE_ROUND_DOWN:
_control87(RC_DOWN, MCW_RC);
break ;
case GSL_IEEE_ROUND_UP:
_control87(RC_UP, MCW_RC);
break ;
case GSL_IEEE_ROUND_TO_ZERO:
_control87(RC_CHOP, MCW_RC);
break ;
default:
_control87(RC_NEAR, MCW_RC);
}
/* Turn on all the exceptions apart from 'inexact' */
mode = EM_INVALID | EM_DENORMAL | EM_ZERODIVIDE | EM_OVERFLOW | EM_UNDERFLOW;
if (exception_mask & GSL_IEEE_MASK_INVALID)
mode &= ~ EM_INVALID;
if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)
mode &= ~ EM_DENORMAL;
if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)
mode &= ~ EM_ZERODIVIDE;
if (exception_mask & GSL_IEEE_MASK_OVERFLOW)
mode &= ~ EM_OVERFLOW;
if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)
mode &= ~ EM_UNDERFLOW;
if (exception_mask & GSL_IEEE_TRAP_INEXACT)
{
mode |= EM_INEXACT;
}
else
{
mode &= ~ EM_INEXACT;
}
_control87(mode, MCW_EM);
return GSL_SUCCESS ;
}
| {
"alphanum_fraction": 0.6896695943,
"avg_line_length": 25.9891304348,
"ext": "c",
"hexsha": "8c41a50aff9ac15a22bd8b7c6775b2e27f120f0b",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-os2emx.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ieee-utils/fp-os2emx.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/ieee-utils/fp-os2emx.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": 657,
"size": 2391
} |
/* randist/weibull.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* The Weibull distribution has the form,
p(x) dx = (b/a) (x/a)^(b-1) exp(-(x/a)^b) dx
*/
double
gsl_ran_weibull (const gsl_rng * r, const double a, const double b)
{
double x = gsl_rng_uniform_pos (r);
double z = pow (-log (x), 1 / b);
return a * z;
}
double
gsl_ran_weibull_pdf (const double x, const double a, const double b)
{
if (x < 0)
{
return 0 ;
}
else if (x == 0)
{
if (b == 1)
return 1/a ;
else
return 0 ;
}
else if (b == 1)
{
return exp(-x/a)/a ;
}
else
{
double p = (b/a) * exp (-pow (x/a, b) + (b - 1) * log (x/a));
return p;
}
}
| {
"alphanum_fraction": 0.6324461343,
"avg_line_length": 24.2769230769,
"ext": "c",
"hexsha": "b1494ef3656faf7e01189e66e14df6e8f20d9751",
"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/randist/weibull.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/weibull.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/randist/weibull.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": 480,
"size": 1578
} |
#pragma once
/*
* (C) Copyright 2020-2021 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
/*! \addtogroup ioda_cxx_attribute
*
* @{
* \file Has_Attributes.h
* \brief Interfaces for ioda::Has_Attributes and related classes.
*/
#include <gsl/gsl-lite.hpp>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "ioda/Attributes/Attribute.h"
#include "ioda/Exception.h"
#include "ioda/Misc/Dimensions.h"
#include "ioda/Misc/Eigen_Compat.h"
#include "ioda/Types/Type.h"
#include "ioda/defs.h"
namespace ioda {
class Has_Attributes;
namespace detail {
class Has_Attributes_Backend;
class Has_Attributes_Base;
class Variable_Backend;
class Group_Backend;
/// \brief Describes the functions that can add attributes
/// \ingroup ioda_cxx_attribute
/// \details Using the (Curiously Recurring Template
/// Pattern)[https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern] to implement this
/// since we want to use the same functions for placeholder attribute construction.
/// \see Has_Attributes
/// \see Attribute_Creator
template <class DerivedHasAtts>
class CanAddAttributes {
public:
/// @name Convenience functions for adding attributes
/// @{
/// \brief Create and write an Attribute, for arbitrary dimensions.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param attrname is the name of the Attribute to be created.
/// \param data is a gsl::span (a pointer-length pair) that contains the data to be written.
/// \param dimensions is an initializer list representing the size of the metadata. Each element
/// is a dimension with a certain size.
/// \returns Another instance of this Has_Attribute. Used for operation chaining.
/// \throws jedi::xError if data.size() does not match the number of total elements
/// described by dimensions.
/// \see gsl::span for details of how to make a span.
template <class DataType>
DerivedHasAtts add(const std::string& attrname, ::gsl::span<const DataType> data,
const ::std::vector<Dimensions_t>& dimensions) {
auto derivedThis = static_cast<DerivedHasAtts*>(this);
auto att = derivedThis->template create<DataType>(attrname, dimensions);
att.template write<DataType>(data);
return *derivedThis;
}
/// \brief Create and write an Attribute, for arbitrary dimensions.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param attrname is the name of the Attribute to be created.
/// \param data is an initializer list that contains the data to be written.
/// \param dimensions is an initializer list representing the size of the metadata. Each
/// element is a dimension with a certain size.
/// \returns Another instance of this Has_Attribute. Used for operation chaining.
/// \throws jedi::xError if data.size() does not match the number of total
/// elements described by dimensions.
template <class DataType>
DerivedHasAtts add(const std::string& attrname, ::std::initializer_list<DataType> data,
const ::std::vector<Dimensions_t>& dimensions) {
auto derivedThis = static_cast<DerivedHasAtts*>(this);
auto att = derivedThis->template create<DataType>(attrname, dimensions);
att.template write<DataType>(data);
return *derivedThis;
}
/// \brief Create and write an Attribute, for a single-dimensional span of 1-D data.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param attrname is the name of the Attribute to be created.
/// \param data is a gsl::span (a pointer-length pair) that contains the data to be written.
/// The new Attribute will be one-dimensional and the length of the overall span.
/// \returns Another instance of this Has_Attribute. Used for operation chaining.
/// \see gsl::span for details of how to make a span.
/// \see gsl::make_span
template <class DataType>
DerivedHasAtts add(const std::string& attrname, ::gsl::span<const DataType> data) {
return add(attrname, data, {gsl::narrow<Dimensions_t>(data.size())});
}
/// \brief Create and write an Attribute, for a 1-D initializer list.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param attrname is the name of the Attribute to be created.
/// \param data is an initializer list that contains the data to be written.
/// The new Attribute will be one-dimensional and the length of the overall span.
/// \returns Another instance of this Has_Attribute. Used for operation chaining.
template <class DataType>
DerivedHasAtts add(const std::string& attrname, ::std::initializer_list<DataType> data) {
return add(attrname, data, {gsl::narrow<Dimensions_t>(data.size())});
}
/// \brief Create and write a single datum of an Attribute.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param attrname is the name of the Attribute to be created.
/// \param data is the data to be written. The new Attribute will be zero-dimensional and will
/// contain only this datum.
/// \note Even 0-dimensional data have a type, which may be a compound
/// array (i.e. a single string of variable length).
/// \returns Another instance of this Has_Attribute. Used for operation chaining.
template <class DataType>
DerivedHasAtts add(const std::string& attrname, const DataType& data) {
return add(attrname, gsl::make_span(&data, 1), {1});
}
template <class EigenClass>
DerivedHasAtts addWithEigenRegular(const std::string& attrname, const EigenClass& data,
bool is2D = true) {
#if 1 //__has_include("Eigen/Dense")
typedef typename EigenClass::Scalar ScalarType;
// If d is already in Row Major form, then this is optimized out.
Eigen::Array<ScalarType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> dout;
dout.resize(data.rows(), data.cols());
dout = data;
const auto& dconst = dout; // To make some compilers happy.
auto sp = gsl::make_span(dconst.data(), static_cast<int>(data.rows() * data.cols()));
if (is2D)
return add(attrname, sp,
{gsl::narrow<Dimensions_t>(data.rows()), gsl::narrow<Dimensions_t>(data.cols())});
else
return add(attrname, sp);
#else
static_assert(false, "The Eigen headers cannot be found, so this function cannot be used.");
#endif
}
template <class EigenClass>
DerivedHasAtts addWithEigenTensor(const std::string& attrname, const EigenClass& data) {
#if 1 //__has_include("unsupported/Eigen/CXX11/Tensor")
typedef typename EigenClass::Scalar ScalarType;
ioda::Dimensions dims = detail::EigenCompat::getTensorDimensions(data);
auto derived_this = static_cast<DerivedHasAtts*>(this);
Attribute att = derived_this->template create<ScalarType>(attrname, dims.dimsCur);
att.writeWithEigenTensor(data);
return *derived_this;
#else
static_assert(
false, "The Eigen unsupported/ headers cannot be found, so this function cannot be used.");
#endif
}
/// @}
};
/// \brief Describes the functions that can read attributes
/// \ingroup ioda_cxx_attribute
/// \details Uses the (CRTP)[https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern]
/// to implement this as we use the same functions for placeholder attribute construction.
/// \see Has_Attributes
template <class DerivedHasAtts>
class CanReadAttributes {
protected:
CanReadAttributes() {}
public:
virtual ~CanReadAttributes() {}
/// @name Convenience functions for reading attributes
/// @{
/// \brief Open and read an Attribute, for expected dimensions.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param attrname is the name of the Attribute to be read.
/// \param data is a pointer-size pair to the data buffer that is filled with the metadata's
/// contents. It should be pre-sized to accomodate all of the matadata. See
/// getDimensions().numElements. Data will be filled in row-major order.
/// \throws jedi::xError on a size mismatch between Attribute dimensions and data.size().
template <class DataType>
const DerivedHasAtts read(const std::string& attrname, gsl::span<DataType> data) const {
// Attribute att = this->open(attrname);
Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);
att.read(data);
return *(static_cast<const DerivedHasAtts*>(this));
}
/// \brief Open and read an Attribute, with unknown dimensions.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param attrname is the name of the Attribute to be read.
/// \param data is a vector acting as a data buffer that is filled with the metadata's
/// contents. It gets resized as needed. data will be filled in row-major order.
template <class DataType>
const DerivedHasAtts read(const std::string& attrname, std::vector<DataType>& data) const {
Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);
att.read(data);
return *(static_cast<const DerivedHasAtts*>(this));
}
/// \brief Open and read an Attribute, with unknown dimensions.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param attrname is the name of the Attribute to be read.
/// \param data is a valarray acting as a data buffer that is filled with the metadata's
/// contents. It gets resized as needed. data will be filled in row-major order.
template <class DataType>
const DerivedHasAtts read(const std::string& attrname, std::valarray<DataType>& data) const {
Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);
att.read(data);
return *(static_cast<const DerivedHasAtts*>(this));
}
/// \brief Read a datum of an Attribute.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param attrname is the name of the Attribute to be read.
/// \param data is a datum of type DataType.
/// \throws jedi::xError if the underlying data have size > 1.
template <class DataType>
const DerivedHasAtts read(const std::string& attrname, DataType& data) const {
Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);
att.read<DataType>(data);
return *(static_cast<const DerivedHasAtts*>(this));
}
/// \brief Read a datum of an Attribute.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param attrname is the name of the Attribute to be read.
/// \returns A datum of type DataType.
/// \throws jedi::xError if the underlying data have size > 1.
template <class DataType>
DataType read(const std::string& attrname) const {
Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);
return att.read<DataType>();
}
template <class EigenClass, bool Resize = detail::EigenCompat::CanResize<EigenClass>::value>
DerivedHasAtts readWithEigenRegular(const std::string& attrname, EigenClass& data) {
#if 1 // __has_include("Eigen/Dense")
Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);
att.readWithEigenRegular<EigenClass, Resize>(data);
return *(static_cast<const DerivedHasAtts*>(this));
#else
static_assert(false, "The Eigen headers cannot be found, so this function cannot be used.")
#endif
}
template <class EigenClass>
DerivedHasAtts readWithEigenTensor(const std::string& attrname, EigenClass& data) {
#if 1 //__has_include("unsupported/Eigen/CXX11/Tensor")
Attribute att = static_cast<const DerivedHasAtts*>(this)->open(attrname);
att.readWithEigenTensor<EigenClass>(data);
return *(static_cast<const DerivedHasAtts*>(this));
#else
static_assert(
false, "The Eigen unsupported/ headers cannot be found, so this function cannot be used.");
#endif
}
/// @}
};
/// \ingroup ioda_cxx_attribute
class IODA_DL Has_Attributes_Base {
private:
/// Using an opaque object to implement the backend.
std::shared_ptr<Has_Attributes_Backend> backend_;
// Backend classes do occasionally need access to the Attribute_Backend object.
friend class Group_Backend;
friend class Variable_Backend;
protected:
Has_Attributes_Base(std::shared_ptr<Has_Attributes_Backend>);
public:
virtual ~Has_Attributes_Base();
/// Query the backend and get the type provider.
virtual detail::Type_Provider* getTypeProvider() const;
/// @name General Functions
/// @{
///
/// List all attributes
/// \returns an unordered vector of attribute names for an object.
virtual std::vector<std::string> list() const;
/// List all attributes
/// \returns an unordered vector of attribute names for an object.
inline std::vector<std::string> operator()() const { return list(); }
/// \brief Does an Attribute with the specified name exist?
/// \param attname is the name of the Attribute that we are looking for.
/// \returns true if it exists.
/// \returns false otherwise.
virtual bool exists(const std::string& attname) const;
/// \brief Delete an Attribute with the specified name.
/// \param attname is the name of the Attribute that we are deleting.
/// \throws jedi::xError if no such attribute exists.
virtual void remove(const std::string& attname);
/// \brief Open an Attribute by name
/// \param name is the name of the Attribute to be opened.
/// \returns An instance of an Attribute that can be queried (with getDimensions()) and read.
virtual Attribute open(const std::string& name) const;
/// \brief Open Attribute by name
/// \param name is the name of the Attribute to be opened.
/// \returns An instance of Attribute that can be queried (with getDimensions()) and read.
inline Attribute operator[](const std::string& name) const { return open(name); }
/// \brief Open all attributes in an object.
/// \details This is a collective call, optimized for performance.
/// \return A sequence of (name, Attribute) pairs.
virtual std::vector<std::pair<std::string, Attribute>> openAll() const;
/// \brief Create an Attribute without setting its data.
/// \param attrname is the name of the Attribute.
/// \param dimensions is a vector representing the size of the metadata.
/// Each element of the vector is a dimension with a certain size.
/// \param in_memory_datatype is the runtime description of the Attribute's data type.
/// \returns An instance of Attribute that can be written to.
virtual Attribute create(const std::string& attrname, const Type& in_memory_dataType,
const std::vector<Dimensions_t>& dimensions = {1});
/// Python compatability function
inline Attribute _create_py(const std::string& attrname, BasicTypes dataType,
const std::vector<Dimensions_t>& dimensions = {1}) {
return create(attrname, ::ioda::Type(dataType, getTypeProvider()), dimensions);
}
/// \brief Create an Attribute without setting its data.
/// \tparam DataType is the type of the data. I.e. float, int, uint16_t, std::string, etc.
/// \param attrname is the name of the Attribute.
/// \param dimensions is a vector representing the size of the metadata. Each element of the
/// vector is a dimension with a certain size.
/// \returns An instance of Attribute that can be written to.
template <class DataType, class TypeWrapper = Types::GetType_Wrapper<DataType>>
Attribute create(const std::string& attrname,
const std::vector<Dimensions_t>& dimensions = {1}) {
try {
Type in_memory_dataType = TypeWrapper::GetType(getTypeProvider());
auto att = create(attrname, in_memory_dataType, dimensions);
return att;
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
}
/// \brief Rename an Attribute
/// \param oldName is the name of the Attribute to be changed.
/// \param newName is the new name of the Attribute.
/// \throws jedi::xError if oldName is not found.
/// \throws jedi::xError if newName already exists.
virtual void rename(const std::string& oldName, const std::string& newName);
/// @}
};
class IODA_DL Has_Attributes_Backend : public Has_Attributes_Base {
protected:
Has_Attributes_Backend();
public:
virtual ~Has_Attributes_Backend();
/// \brief Default implementation of Has_Attributes_Base::openAll.
/// \see Has_Attributes_Base::openAll.
std::vector<std::pair<std::string, Attribute>> openAll() const override;
};
} // namespace detail
/** \brief This class exists inside of ioda::Group or ioda::Variable and provides
* the interface to manipulating Attributes.
* \ingroup ioda_cxx_attribute
*
* \note It should only be constructed inside of a Group or Variable.
* It has no meaning elsewhere.
* \see Attribute for the class that represents individual attributes.
* \throws jedi::xError on all exceptions.
**/
class IODA_DL Has_Attributes : public detail::CanAddAttributes<Has_Attributes>,
public detail::CanReadAttributes<Has_Attributes>,
public detail::Has_Attributes_Base {
public:
Has_Attributes();
Has_Attributes(std::shared_ptr<detail::Has_Attributes_Backend>);
virtual ~Has_Attributes();
};
} // namespace ioda
/// @} // End Doxygen block
| {
"alphanum_fraction": 0.7084272195,
"avg_line_length": 44.38,
"ext": "h",
"hexsha": "9785a8515685b7010bdd96d26adc8217b94bde89",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-11-14T09:19:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-09T16:12:02.000Z",
"max_forks_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Gibies/ioda",
"max_forks_repo_path": "src/engines/ioda/include/ioda/Attributes/Has_Attributes.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75",
"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": "Gibies/ioda",
"max_issues_repo_path": "src/engines/ioda/include/ioda/Attributes/Has_Attributes.h",
"max_line_length": 101,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Gibies/ioda",
"max_stars_repo_path": "src/engines/ioda/include/ioda/Attributes/Has_Attributes.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-09T16:11:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-09T16:11:50.000Z",
"num_tokens": 4299,
"size": 17752
} |
/* rng/zuf.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
/* It is crucial that m == n-273 mod 607 at all times;
For speed of execution, however, this is never enforced.
Instead is is set in the initializer: note 607-273=334
Note also that the state.u[607] is not initialized */
static inline unsigned long int zuf_get (void *vstate);
static double zuf_get_double (void *vstate);
static void zuf_set (void *state, unsigned long int s);
static const unsigned long int zuf_randmax = 16777216; /* 2^24 */
typedef struct
{
int n;
unsigned long int u[607];
}
zuf_state_t;
/* The zufall package was implemented with float's, which is to say 24
bits of precision. Since I'm using long's instead, my RANDMAX
reflects this. */
static inline unsigned long int
zuf_get (void *vstate)
{
zuf_state_t *state = (zuf_state_t *) vstate;
const int n = state->n;
const int m = (n - 273 + 607) % 607;
unsigned long int t = state->u[n] + state->u[m];
while (t > zuf_randmax)
t -= zuf_randmax;
state->u[n] = t;
if (n == 606)
{
state->n = 0;
}
else
{
state->n = n + 1;
}
return t;
}
static double
zuf_get_double (void *vstate)
{
return zuf_get (vstate) / 16777216.0 ;
}
static void
zuf_set (void *vstate, unsigned long int s)
{
/* A very elaborate seeding procedure is provided with the
zufall package; this is virtually a copy of that procedure */
/* Initialized data */
long int kl = 9373;
long int ij = 1802;
/* Local variables */
long int i, j, k, l, m;
double x, y;
long int ii, jj;
zuf_state_t *state = (zuf_state_t *) vstate;
state->n = 0;
/* generates initial seed buffer by linear congruential */
/* method. Taken from Marsaglia, FSU report FSU-SCRI-87-50 */
/* variable seed should be 0 < seed <31328 */
if (s == 0)
s = 1802; /* default seed is 1802 */
ij = s;
i = ij / 177 % 177 + 2;
j = ij % 177 + 2;
k = kl / 169 % 178 + 1;
l = kl % 169;
for (ii = 0; ii < 607; ++ii)
{
x = 0.0;
y = 0.5;
/* 24 bits?? */
for (jj = 1; jj <= 24; ++jj)
{
m = i * j % 179 * k % 179;
i = j;
j = k;
k = m;
l = (l * 53 + 1) % 169;
if (l * m % 64 >= 32)
{
x += y;
}
y *= 0.5;
}
state->u[ii] = (unsigned long int) (x * zuf_randmax);
}
}
static const gsl_rng_type zuf_type =
{"zuf", /* name */
0x00ffffffUL, /* RAND_MAX */
0, /* RAND_MIN */
sizeof (zuf_state_t),
&zuf_set,
&zuf_get,
&zuf_get_double};
const gsl_rng_type *gsl_rng_zuf = &zuf_type;
| {
"alphanum_fraction": 0.6270125224,
"avg_line_length": 23.6197183099,
"ext": "c",
"hexsha": "c5c93bcdb0ab7fef0897a1998bff3baabeabd504",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/rng/zuf.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/rng/zuf.c",
"max_line_length": 72,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/rng/zuf.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": 1075,
"size": 3354
} |
#pragma once
#include <gsl/gsl>
#include "exception.h"
#include <fmt/format.h>
#include "mathutil.h"
#include "stringutil.h"
#include "version.h"
#include "stopwatch.h"
#include "logging.h"
| {
"alphanum_fraction": 0.7150259067,
"avg_line_length": 14.8461538462,
"ext": "h",
"hexsha": "6a6f32d3d6bf38f882acda17e29846606acdabbb",
"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/infrastructure.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/infrastructure.h",
"max_line_length": 23,
"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/infrastructure.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": 50,
"size": 193
} |
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include "norm.h"
#include "constants.h"
int readFileVector( gsl_vector *vector, char *filePath, char *fileName ) //read file vals into vector
{
char tmpFilepath[120] = "\0";
char tmpReading[20];
char *tmp2;
double reading; //WARNING this is similar to global var $readings, consider renaming
strcat( tmpFilepath, filePath ); //TODO replace this and the first instance of strcat into strcpy, that should work
strcat( tmpFilepath, fileName ); //combines the filepath and name into one searchable /path/file
FILE *file = fopen( tmpFilepath, "rt");
printf("%s\n", tmpFilepath); //TODO DELETE THIS
if ( file == NULL ) { //check if file exists
fprintf( stderr, "Error, unable to locate the Mu data file\n");
exit(100);
}
for ( int i = 0; i < skip; i++) //move past header of read files
{
fgets( tmpReading, 19, file );
}
for ( int i = 0; i < readings; i++ )
{
fgets( tmpReading, 19, file );
tmp2 = strrchr( tmpReading, '\t' );
tmp2 = tmp2 + 1;
reading = atof(tmp2);
gsl_vector_set( vector, i, reading);
}
fclose(file);
return 0;
}
int readFileMatrix( gsl_matrix *matrix, char *filePath, int argc, char *argv[] )
{
char *tmp2;
double reading;
for ( int j = 2; j < argc; j++ )
{
gsl_vector_view column;
char tmpFilepath[120] = "\0"; //TODO replace this and the first instance of strcat into strcpy, that should work
char tmpReading[20];
strcat( tmpFilepath, filePath );
strcat( tmpFilepath, argv[j] ); //combines the filepath and name into one searchable /path/file
FILE *file = fopen( tmpFilepath, "rt");
printf("%s\n", tmpFilepath); //TODO DELETE THIS
if ( file == NULL ) { //check if file exists
fprintf( stderr, "Error, unable to locate a reference data file\n");
exit(100);
}
for ( int i = 0; i < skip; i++) //move past header of read files
{
fgets( tmpReading, 20, file);
}
for ( int i = 0; i < readings; i++ ) //fill the ith element of the jth column
{
fgets( tmpReading, 19, file );
tmp2 = strrchr( tmpReading, '\t' );
tmp2 = tmp2 + 1;
reading = atof(tmp2);
gsl_matrix_set( matrix, i, j-2, reading );
}
fclose(file);
column = gsl_matrix_column( matrix, j-2 ); //NORMALISE EACH REFERENCE VECOTR.
normalizeVector( &column.vector );
}
return 0;
}
| {
"alphanum_fraction": 0.6028528529,
"avg_line_length": 31.3411764706,
"ext": "c",
"hexsha": "146256f83aa9091fa81125af48d17b08a629a1a6",
"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": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jakeinater/spectralILU",
"max_forks_repo_path": "src/utils.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d",
"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": "jakeinater/spectralILU",
"max_issues_repo_path": "src/utils.c",
"max_line_length": 140,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "825dbd5c5495b0ce0a0d14a5bed865b9bfdda98d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jakeinater/spectralILU",
"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": 748,
"size": 2664
} |
/* specfunc/hyperg_2F1.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman
* Copyright (C) 2009 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_exp.h>
#include <gsl/gsl_sf_pow_int.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_psi.h>
#include <gsl/gsl_sf_hyperg.h>
#include "error.h"
#define locEPS (1000.0*GSL_DBL_EPSILON)
/* Assumes c != negative integer.
*/
static int
hyperg_2F1_series(const double a, const double b, const double c,
const double x,
gsl_sf_result * result
)
{
double sum_pos = 1.0;
double sum_neg = 0.0;
double del_pos = 1.0;
double del_neg = 0.0;
double del = 1.0;
double k = 0.0;
int i = 0;
if(fabs(c) < GSL_DBL_EPSILON) {
result->val = 0.0; /* FIXME: ?? */
result->err = 1.0;
GSL_ERROR ("error", GSL_EDOM);
}
do {
if(++i > 30000) {
result->val = sum_pos - sum_neg;
result->err = del_pos + del_neg;
result->err += 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);
result->err += 2.0 * GSL_DBL_EPSILON * (2.0*sqrt(k)+1.0) * fabs(result->val);
GSL_ERROR ("error", GSL_EMAXITER);
}
del *= (a+k)*(b+k) * x / ((c+k) * (k+1.0)); /* Gauss series */
if(del > 0.0) {
del_pos = del;
sum_pos += del;
}
else if(del == 0.0) {
/* Exact termination (a or b was a negative integer).
*/
del_pos = 0.0;
del_neg = 0.0;
break;
}
else {
del_neg = -del;
sum_neg -= del;
}
k += 1.0;
} while(fabs((del_pos + del_neg)/(sum_pos-sum_neg)) > GSL_DBL_EPSILON);
result->val = sum_pos - sum_neg;
result->err = del_pos + del_neg;
result->err += 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);
result->err += 2.0 * GSL_DBL_EPSILON * (2.0*sqrt(k) + 1.0) * fabs(result->val);
return GSL_SUCCESS;
}
/* a = aR + i aI, b = aR - i aI */
static
int
hyperg_2F1_conj_series(const double aR, const double aI, const double c,
double x,
gsl_sf_result * result)
{
if(c == 0.0) {
result->val = 0.0; /* FIXME: should be Inf */
result->err = 0.0;
GSL_ERROR ("error", GSL_EDOM);
}
else {
double sum_pos = 1.0;
double sum_neg = 0.0;
double del_pos = 1.0;
double del_neg = 0.0;
double del = 1.0;
double k = 0.0;
do {
del *= ((aR+k)*(aR+k) + aI*aI)/((k+1.0)*(c+k)) * x;
if(del >= 0.0) {
del_pos = del;
sum_pos += del;
}
else {
del_neg = -del;
sum_neg -= del;
}
if(k > 30000) {
result->val = sum_pos - sum_neg;
result->err = del_pos + del_neg;
result->err += 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);
result->err += 2.0 * GSL_DBL_EPSILON * (2.0*sqrt(k)+1.0) * fabs(result->val);
GSL_ERROR ("error", GSL_EMAXITER);
}
k += 1.0;
} while(fabs((del_pos + del_neg)/(sum_pos - sum_neg)) > GSL_DBL_EPSILON);
result->val = sum_pos - sum_neg;
result->err = del_pos + del_neg;
result->err += 2.0 * GSL_DBL_EPSILON * (sum_pos + sum_neg);
result->err += 2.0 * GSL_DBL_EPSILON * (2.0*sqrt(k) + 1.0) * fabs(result->val);
return GSL_SUCCESS;
}
}
/* Luke's rational approximation. The most accesible
* discussion is in [Kolbig, CPC 23, 51 (1981)].
* The convergence is supposedly guaranteed for x < 0.
* You have to read Luke's books to see this and other
* results. Unfortunately, the stability is not so
* clear to me, although it seems very efficient when
* it works.
*/
static
int
hyperg_2F1_luke(const double a, const double b, const double c,
const double xin,
gsl_sf_result * result)
{
int stat_iter;
const double RECUR_BIG = 1.0e+50;
const int nmax = 20000;
int n = 3;
const double x = -xin;
const double x3 = x*x*x;
const double t0 = a*b/c;
const double t1 = (a+1.0)*(b+1.0)/(2.0*c);
const double t2 = (a+2.0)*(b+2.0)/(2.0*(c+1.0));
double F = 1.0;
double prec;
double Bnm3 = 1.0; /* B0 */
double Bnm2 = 1.0 + t1 * x; /* B1 */
double Bnm1 = 1.0 + t2 * x * (1.0 + t1/3.0 * x); /* B2 */
double Anm3 = 1.0; /* A0 */
double Anm2 = Bnm2 - t0 * x; /* A1 */
double Anm1 = Bnm1 - t0*(1.0 + t2*x)*x + t0 * t1 * (c/(c+1.0)) * x*x; /* A2 */
while(1) {
double npam1 = n + a - 1;
double npbm1 = n + b - 1;
double npcm1 = n + c - 1;
double npam2 = n + a - 2;
double npbm2 = n + b - 2;
double npcm2 = n + c - 2;
double tnm1 = 2*n - 1;
double tnm3 = 2*n - 3;
double tnm5 = 2*n - 5;
double n2 = n*n;
double F1 = (3.0*n2 + (a+b-6)*n + 2 - a*b - 2*(a+b)) / (2*tnm3*npcm1);
double F2 = -(3.0*n2 - (a+b+6)*n + 2 - a*b)*npam1*npbm1/(4*tnm1*tnm3*npcm2*npcm1);
double F3 = (npam2*npam1*npbm2*npbm1*(n-a-2)*(n-b-2)) / (8*tnm3*tnm3*tnm5*(n+c-3)*npcm2*npcm1);
double E = -npam1*npbm1*(n-c-1) / (2*tnm3*npcm2*npcm1);
double An = (1.0+F1*x)*Anm1 + (E + F2*x)*x*Anm2 + F3*x3*Anm3;
double Bn = (1.0+F1*x)*Bnm1 + (E + F2*x)*x*Bnm2 + F3*x3*Bnm3;
double r = An/Bn;
prec = fabs((F - r)/F);
F = r;
if(prec < GSL_DBL_EPSILON || n > nmax) break;
if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) {
An /= RECUR_BIG;
Bn /= RECUR_BIG;
Anm1 /= RECUR_BIG;
Bnm1 /= RECUR_BIG;
Anm2 /= RECUR_BIG;
Bnm2 /= RECUR_BIG;
Anm3 /= RECUR_BIG;
Bnm3 /= RECUR_BIG;
}
else if(fabs(An) < 1.0/RECUR_BIG || fabs(Bn) < 1.0/RECUR_BIG) {
An *= RECUR_BIG;
Bn *= RECUR_BIG;
Anm1 *= RECUR_BIG;
Bnm1 *= RECUR_BIG;
Anm2 *= RECUR_BIG;
Bnm2 *= RECUR_BIG;
Anm3 *= RECUR_BIG;
Bnm3 *= RECUR_BIG;
}
n++;
Bnm3 = Bnm2;
Bnm2 = Bnm1;
Bnm1 = Bn;
Anm3 = Anm2;
Anm2 = Anm1;
Anm1 = An;
}
result->val = F;
result->err = 2.0 * fabs(prec * F);
result->err += 2.0 * GSL_DBL_EPSILON * (n+1.0) * fabs(F);
/* FIXME: just a hack: there's a lot of shit going on here */
result->err *= 8.0 * (fabs(a) + fabs(b) + 1.0);
stat_iter = (n >= nmax ? GSL_EMAXITER : GSL_SUCCESS );
return stat_iter;
}
/* Luke's rational approximation for the
* case a = aR + i aI, b = aR - i aI.
*/
static
int
hyperg_2F1_conj_luke(const double aR, const double aI, const double c,
const double xin,
gsl_sf_result * result)
{
int stat_iter;
const double RECUR_BIG = 1.0e+50;
const int nmax = 10000;
int n = 3;
const double x = -xin;
const double x3 = x*x*x;
const double atimesb = aR*aR + aI*aI;
const double apb = 2.0*aR;
const double t0 = atimesb/c;
const double t1 = (atimesb + apb + 1.0)/(2.0*c);
const double t2 = (atimesb + 2.0*apb + 4.0)/(2.0*(c+1.0));
double F = 1.0;
double prec;
double Bnm3 = 1.0; /* B0 */
double Bnm2 = 1.0 + t1 * x; /* B1 */
double Bnm1 = 1.0 + t2 * x * (1.0 + t1/3.0 * x); /* B2 */
double Anm3 = 1.0; /* A0 */
double Anm2 = Bnm2 - t0 * x; /* A1 */
double Anm1 = Bnm1 - t0*(1.0 + t2*x)*x + t0 * t1 * (c/(c+1.0)) * x*x; /* A2 */
while(1) {
double nm1 = n - 1;
double nm2 = n - 2;
double npam1_npbm1 = atimesb + nm1*apb + nm1*nm1;
double npam2_npbm2 = atimesb + nm2*apb + nm2*nm2;
double npcm1 = nm1 + c;
double npcm2 = nm2 + c;
double tnm1 = 2*n - 1;
double tnm3 = 2*n - 3;
double tnm5 = 2*n - 5;
double n2 = n*n;
double F1 = (3.0*n2 + (apb-6)*n + 2 - atimesb - 2*apb) / (2*tnm3*npcm1);
double F2 = -(3.0*n2 - (apb+6)*n + 2 - atimesb)*npam1_npbm1/(4*tnm1*tnm3*npcm2*npcm1);
double F3 = (npam2_npbm2*npam1_npbm1*(nm2*nm2 - nm2*apb + atimesb)) / (8*tnm3*tnm3*tnm5*(n+c-3)*npcm2*npcm1);
double E = -npam1_npbm1*(n-c-1) / (2*tnm3*npcm2*npcm1);
double An = (1.0+F1*x)*Anm1 + (E + F2*x)*x*Anm2 + F3*x3*Anm3;
double Bn = (1.0+F1*x)*Bnm1 + (E + F2*x)*x*Bnm2 + F3*x3*Bnm3;
double r = An/Bn;
prec = fabs(F - r)/fabs(F);
F = r;
if(prec < GSL_DBL_EPSILON || n > nmax) break;
if(fabs(An) > RECUR_BIG || fabs(Bn) > RECUR_BIG) {
An /= RECUR_BIG;
Bn /= RECUR_BIG;
Anm1 /= RECUR_BIG;
Bnm1 /= RECUR_BIG;
Anm2 /= RECUR_BIG;
Bnm2 /= RECUR_BIG;
Anm3 /= RECUR_BIG;
Bnm3 /= RECUR_BIG;
}
else if(fabs(An) < 1.0/RECUR_BIG || fabs(Bn) < 1.0/RECUR_BIG) {
An *= RECUR_BIG;
Bn *= RECUR_BIG;
Anm1 *= RECUR_BIG;
Bnm1 *= RECUR_BIG;
Anm2 *= RECUR_BIG;
Bnm2 *= RECUR_BIG;
Anm3 *= RECUR_BIG;
Bnm3 *= RECUR_BIG;
}
n++;
Bnm3 = Bnm2;
Bnm2 = Bnm1;
Bnm1 = Bn;
Anm3 = Anm2;
Anm2 = Anm1;
Anm1 = An;
}
result->val = F;
result->err = 2.0 * fabs(prec * F);
result->err += 2.0 * GSL_DBL_EPSILON * (n+1.0) * fabs(F);
/* FIXME: see above */
result->err *= 8.0 * (fabs(aR) + fabs(aI) + 1.0);
stat_iter = (n >= nmax ? GSL_EMAXITER : GSL_SUCCESS );
return stat_iter;
}
/* Do the reflection described in [Moshier, p. 334].
* Assumes a,b,c != neg integer.
*/
static
int
hyperg_2F1_reflect(const double a, const double b, const double c,
const double x, gsl_sf_result * result)
{
const double d = c - a - b;
const int intd = floor(d+0.5);
const int d_integer = ( fabs(d - intd) < locEPS );
if(d_integer) {
const double ln_omx = log(1.0 - x);
const double ad = fabs(d);
int stat_F2 = GSL_SUCCESS;
double sgn_2;
gsl_sf_result F1;
gsl_sf_result F2;
double d1, d2;
gsl_sf_result lng_c;
gsl_sf_result lng_ad2;
gsl_sf_result lng_bd2;
int stat_c;
int stat_ad2;
int stat_bd2;
if(d >= 0.0) {
d1 = d;
d2 = 0.0;
}
else {
d1 = 0.0;
d2 = d;
}
stat_ad2 = gsl_sf_lngamma_e(a+d2, &lng_ad2);
stat_bd2 = gsl_sf_lngamma_e(b+d2, &lng_bd2);
stat_c = gsl_sf_lngamma_e(c, &lng_c);
/* Evaluate F1.
*/
if(ad < GSL_DBL_EPSILON) {
/* d = 0 */
F1.val = 0.0;
F1.err = 0.0;
}
else {
gsl_sf_result lng_ad;
gsl_sf_result lng_ad1;
gsl_sf_result lng_bd1;
int stat_ad = gsl_sf_lngamma_e(ad, &lng_ad);
int stat_ad1 = gsl_sf_lngamma_e(a+d1, &lng_ad1);
int stat_bd1 = gsl_sf_lngamma_e(b+d1, &lng_bd1);
if(stat_ad1 == GSL_SUCCESS && stat_bd1 == GSL_SUCCESS && stat_ad == GSL_SUCCESS) {
/* Gamma functions in the denominator are ok.
* Proceed with evaluation.
*/
int i;
double sum1 = 1.0;
double term = 1.0;
double ln_pre1_val = lng_ad.val + lng_c.val + d2*ln_omx - lng_ad1.val - lng_bd1.val;
double ln_pre1_err = lng_ad.err + lng_c.err + lng_ad1.err + lng_bd1.err + GSL_DBL_EPSILON * fabs(ln_pre1_val);
int stat_e;
/* Do F1 sum.
*/
for(i=1; i<ad; i++) {
int j = i-1;
term *= (a + d2 + j) * (b + d2 + j) / (1.0 + d2 + j) / i * (1.0-x);
sum1 += term;
}
stat_e = gsl_sf_exp_mult_err_e(ln_pre1_val, ln_pre1_err,
sum1, GSL_DBL_EPSILON*fabs(sum1),
&F1);
if(stat_e == GSL_EOVRFLW) {
OVERFLOW_ERROR(result);
}
}
else {
/* Gamma functions in the denominator were not ok.
* So the F1 term is zero.
*/
F1.val = 0.0;
F1.err = 0.0;
}
} /* end F1 evaluation */
/* Evaluate F2.
*/
if(stat_ad2 == GSL_SUCCESS && stat_bd2 == GSL_SUCCESS) {
/* Gamma functions in the denominator are ok.
* Proceed with evaluation.
*/
const int maxiter = 2000;
double psi_1 = -M_EULER;
gsl_sf_result psi_1pd;
gsl_sf_result psi_apd1;
gsl_sf_result psi_bpd1;
int stat_1pd = gsl_sf_psi_e(1.0 + ad, &psi_1pd);
int stat_apd1 = gsl_sf_psi_e(a + d1, &psi_apd1);
int stat_bpd1 = gsl_sf_psi_e(b + d1, &psi_bpd1);
int stat_dall = GSL_ERROR_SELECT_3(stat_1pd, stat_apd1, stat_bpd1);
double psi_val = psi_1 + psi_1pd.val - psi_apd1.val - psi_bpd1.val - ln_omx;
double psi_err = psi_1pd.err + psi_apd1.err + psi_bpd1.err + GSL_DBL_EPSILON*fabs(psi_val);
double fact = 1.0;
double sum2_val = psi_val;
double sum2_err = psi_err;
double ln_pre2_val = lng_c.val + d1*ln_omx - lng_ad2.val - lng_bd2.val;
double ln_pre2_err = lng_c.err + lng_ad2.err + lng_bd2.err + GSL_DBL_EPSILON * fabs(ln_pre2_val);
int stat_e;
int j;
/* Do F2 sum.
*/
for(j=1; j<maxiter; j++) {
/* values for psi functions use recurrence; Abramowitz+Stegun 6.3.5 */
double term1 = 1.0/(double)j + 1.0/(ad+j);
double term2 = 1.0/(a+d1+j-1.0) + 1.0/(b+d1+j-1.0);
double delta = 0.0;
psi_val += term1 - term2;
psi_err += GSL_DBL_EPSILON * (fabs(term1) + fabs(term2));
fact *= (a+d1+j-1.0)*(b+d1+j-1.0)/((ad+j)*j) * (1.0-x);
delta = fact * psi_val;
sum2_val += delta;
sum2_err += fabs(fact * psi_err) + GSL_DBL_EPSILON*fabs(delta);
if(fabs(delta) < GSL_DBL_EPSILON * fabs(sum2_val)) break;
}
if(j == maxiter) stat_F2 = GSL_EMAXITER;
if(sum2_val == 0.0) {
F2.val = 0.0;
F2.err = 0.0;
}
else {
stat_e = gsl_sf_exp_mult_err_e(ln_pre2_val, ln_pre2_err,
sum2_val, sum2_err,
&F2);
if(stat_e == GSL_EOVRFLW) {
result->val = 0.0;
result->err = 0.0;
GSL_ERROR ("error", GSL_EOVRFLW);
}
}
stat_F2 = GSL_ERROR_SELECT_2(stat_F2, stat_dall);
}
else {
/* Gamma functions in the denominator not ok.
* So the F2 term is zero.
*/
F2.val = 0.0;
F2.err = 0.0;
} /* end F2 evaluation */
sgn_2 = ( GSL_IS_ODD(intd) ? -1.0 : 1.0 );
result->val = F1.val + sgn_2 * F2.val;
result->err = F1.err + F2. err;
result->err += 2.0 * GSL_DBL_EPSILON * (fabs(F1.val) + fabs(F2.val));
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_F2;
}
else {
/* d not an integer */
gsl_sf_result pre1, pre2;
double sgn1, sgn2;
gsl_sf_result F1, F2;
int status_F1, status_F2;
/* These gamma functions appear in the denominator, so we
* catch their harmless domain errors and set the terms to zero.
*/
gsl_sf_result ln_g1ca, ln_g1cb, ln_g2a, ln_g2b;
double sgn_g1ca, sgn_g1cb, sgn_g2a, sgn_g2b;
int stat_1ca = gsl_sf_lngamma_sgn_e(c-a, &ln_g1ca, &sgn_g1ca);
int stat_1cb = gsl_sf_lngamma_sgn_e(c-b, &ln_g1cb, &sgn_g1cb);
int stat_2a = gsl_sf_lngamma_sgn_e(a, &ln_g2a, &sgn_g2a);
int stat_2b = gsl_sf_lngamma_sgn_e(b, &ln_g2b, &sgn_g2b);
int ok1 = (stat_1ca == GSL_SUCCESS && stat_1cb == GSL_SUCCESS);
int ok2 = (stat_2a == GSL_SUCCESS && stat_2b == GSL_SUCCESS);
gsl_sf_result ln_gc, ln_gd, ln_gmd;
double sgn_gc, sgn_gd, sgn_gmd;
gsl_sf_lngamma_sgn_e( c, &ln_gc, &sgn_gc);
gsl_sf_lngamma_sgn_e( d, &ln_gd, &sgn_gd);
gsl_sf_lngamma_sgn_e(-d, &ln_gmd, &sgn_gmd);
sgn1 = sgn_gc * sgn_gd * sgn_g1ca * sgn_g1cb;
sgn2 = sgn_gc * sgn_gmd * sgn_g2a * sgn_g2b;
if(ok1 && ok2) {
double ln_pre1_val = ln_gc.val + ln_gd.val - ln_g1ca.val - ln_g1cb.val;
double ln_pre2_val = ln_gc.val + ln_gmd.val - ln_g2a.val - ln_g2b.val + d*log(1.0-x);
double ln_pre1_err = ln_gc.err + ln_gd.err + ln_g1ca.err + ln_g1cb.err;
double ln_pre2_err = ln_gc.err + ln_gmd.err + ln_g2a.err + ln_g2b.err;
if(ln_pre1_val < GSL_LOG_DBL_MAX && ln_pre2_val < GSL_LOG_DBL_MAX) {
gsl_sf_exp_err_e(ln_pre1_val, ln_pre1_err, &pre1);
gsl_sf_exp_err_e(ln_pre2_val, ln_pre2_err, &pre2);
pre1.val *= sgn1;
pre2.val *= sgn2;
}
else {
OVERFLOW_ERROR(result);
}
}
else if(ok1 && !ok2) {
double ln_pre1_val = ln_gc.val + ln_gd.val - ln_g1ca.val - ln_g1cb.val;
double ln_pre1_err = ln_gc.err + ln_gd.err + ln_g1ca.err + ln_g1cb.err;
if(ln_pre1_val < GSL_LOG_DBL_MAX) {
gsl_sf_exp_err_e(ln_pre1_val, ln_pre1_err, &pre1);
pre1.val *= sgn1;
pre2.val = 0.0;
pre2.err = 0.0;
}
else {
OVERFLOW_ERROR(result);
}
}
else if(!ok1 && ok2) {
double ln_pre2_val = ln_gc.val + ln_gmd.val - ln_g2a.val - ln_g2b.val + d*log(1.0-x);
double ln_pre2_err = ln_gc.err + ln_gmd.err + ln_g2a.err + ln_g2b.err;
if(ln_pre2_val < GSL_LOG_DBL_MAX) {
pre1.val = 0.0;
pre1.err = 0.0;
gsl_sf_exp_err_e(ln_pre2_val, ln_pre2_err, &pre2);
pre2.val *= sgn2;
}
else {
OVERFLOW_ERROR(result);
}
}
else {
pre1.val = 0.0;
pre2.val = 0.0;
UNDERFLOW_ERROR(result);
}
status_F1 = hyperg_2F1_series( a, b, 1.0-d, 1.0-x, &F1);
status_F2 = hyperg_2F1_series(c-a, c-b, 1.0+d, 1.0-x, &F2);
result->val = pre1.val*F1.val + pre2.val*F2.val;
result->err = fabs(pre1.val*F1.err) + fabs(pre2.val*F2.err);
result->err += fabs(pre1.err*F1.val) + fabs(pre2.err*F2.val);
result->err += 2.0 * GSL_DBL_EPSILON * (fabs(pre1.val*F1.val) + fabs(pre2.val*F2.val));
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
}
static int pow_omx(const double x, const double p, gsl_sf_result * result)
{
double ln_omx;
double ln_result;
if(fabs(x) < GSL_ROOT5_DBL_EPSILON) {
ln_omx = -x*(1.0 + x*(1.0/2.0 + x*(1.0/3.0 + x/4.0 + x*x/5.0)));
}
else {
ln_omx = log(1.0-x);
}
ln_result = p * ln_omx;
return gsl_sf_exp_err_e(ln_result, GSL_DBL_EPSILON * fabs(ln_result), result);
}
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int
gsl_sf_hyperg_2F1_e(double a, double b, const double c,
const double x,
gsl_sf_result * result)
{
const double d = c - a - b;
const double rinta = floor(a + 0.5);
const double rintb = floor(b + 0.5);
const double rintc = floor(c + 0.5);
const int a_neg_integer = ( a < 0.0 && fabs(a - rinta) < locEPS );
const int b_neg_integer = ( b < 0.0 && fabs(b - rintb) < locEPS );
const int c_neg_integer = ( c < 0.0 && fabs(c - rintc) < locEPS );
result->val = 0.0;
result->err = 0.0;
/* Handle x == 1.0 RJM */
if (fabs (x - 1.0) < locEPS && (c - a - b) > 0 && c != 0 && !c_neg_integer) {
gsl_sf_result lngamc, lngamcab, lngamca, lngamcb;
double lngamc_sgn, lngamca_sgn, lngamcb_sgn;
int status;
int stat1 = gsl_sf_lngamma_sgn_e (c, &lngamc, &lngamc_sgn);
int stat2 = gsl_sf_lngamma_e (c - a - b, &lngamcab);
int stat3 = gsl_sf_lngamma_sgn_e (c - a, &lngamca, &lngamca_sgn);
int stat4 = gsl_sf_lngamma_sgn_e (c - b, &lngamcb, &lngamcb_sgn);
if (stat1 != GSL_SUCCESS || stat2 != GSL_SUCCESS
|| stat3 != GSL_SUCCESS || stat4 != GSL_SUCCESS)
{
DOMAIN_ERROR (result);
}
status =
gsl_sf_exp_err_e (lngamc.val + lngamcab.val - lngamca.val - lngamcb.val,
lngamc.err + lngamcab.err + lngamca.err + lngamcb.err,
result);
result->val *= lngamc_sgn / (lngamca_sgn * lngamcb_sgn);
return status;
}
if(x < -1.0 || 1.0 <= x) {
DOMAIN_ERROR(result);
}
if(c_neg_integer) {
/* If c is a negative integer, then either a or b must be a
negative integer of smaller magnitude than c to ensure
cancellation of the series. */
if(! (a_neg_integer && a > c + 0.1) && ! (b_neg_integer && b > c + 0.1)) {
DOMAIN_ERROR(result);
}
}
if(fabs(c-b) < locEPS || fabs(c-a) < locEPS) {
return pow_omx(x, d, result); /* (1-x)^(c-a-b) */
}
if(a >= 0.0 && b >= 0.0 && c >=0.0 && x >= 0.0 && x < 0.995) {
/* Series has all positive definite
* terms and x is not close to 1.
*/
return hyperg_2F1_series(a, b, c, x, result);
}
if(fabs(a) < 10.0 && fabs(b) < 10.0) {
/* a and b are not too large, so we attempt
* variations on the series summation.
*/
if(a_neg_integer) {
return hyperg_2F1_series(rinta, b, c, x, result);
}
if(b_neg_integer) {
return hyperg_2F1_series(a, rintb, c, x, result);
}
if(x < -0.25) {
return hyperg_2F1_luke(a, b, c, x, result);
}
else if(x < 0.5) {
return hyperg_2F1_series(a, b, c, x, result);
}
else {
if(fabs(c) > 10.0) {
return hyperg_2F1_series(a, b, c, x, result);
}
else {
return hyperg_2F1_reflect(a, b, c, x, result);
}
}
}
else {
/* Either a or b or both large.
* Introduce some new variables ap,bp so that bp is
* the larger in magnitude.
*/
double ap, bp;
if(fabs(a) > fabs(b)) {
bp = a;
ap = b;
}
else {
bp = b;
ap = a;
}
if(x < 0.0) {
/* What the hell, maybe Luke will converge.
*/
return hyperg_2F1_luke(a, b, c, x, result);
}
if(GSL_MAX_DBL(fabs(ap),1.0)*fabs(bp)*fabs(x) < 2.0*fabs(c)) {
/* If c is large enough or x is small enough,
* we can attempt the series anyway.
*/
return hyperg_2F1_series(a, b, c, x, result);
}
if(fabs(bp*bp*x*x) < 0.001*fabs(bp) && fabs(ap) < 10.0) {
/* The famous but nearly worthless "large b" asymptotic.
*/
int stat = gsl_sf_hyperg_1F1_e(ap, c, bp*x, result);
result->err = 0.001 * fabs(result->val);
return stat;
}
/* We give up. */
result->val = 0.0;
result->err = 0.0;
GSL_ERROR ("error", GSL_EUNIMPL);
}
}
int
gsl_sf_hyperg_2F1_conj_e(const double aR, const double aI, const double c,
const double x,
gsl_sf_result * result)
{
const double ax = fabs(x);
const double rintc = floor(c + 0.5);
const int c_neg_integer = ( c < 0.0 && fabs(c - rintc) < locEPS );
result->val = 0.0;
result->err = 0.0;
if(ax >= 1.0 || c_neg_integer || c == 0.0) {
DOMAIN_ERROR(result);
}
if( (ax < 0.25 && fabs(aR) < 20.0 && fabs(aI) < 20.0)
|| (c > 0.0 && x > 0.0)
) {
return hyperg_2F1_conj_series(aR, aI, c, x, result);
}
else if(fabs(aR) < 10.0 && fabs(aI) < 10.0) {
if(x < -0.25) {
return hyperg_2F1_conj_luke(aR, aI, c, x, result);
}
else {
return hyperg_2F1_conj_series(aR, aI, c, x, result);
}
}
else {
if(x < 0.0) {
/* What the hell, maybe Luke will converge.
*/
return hyperg_2F1_conj_luke(aR, aI, c, x, result);
}
/* Give up. */
result->val = 0.0;
result->err = 0.0;
GSL_ERROR ("error", GSL_EUNIMPL);
}
}
int
gsl_sf_hyperg_2F1_renorm_e(const double a, const double b, const double c,
const double x,
gsl_sf_result * result
)
{
const double rinta = floor(a + 0.5);
const double rintb = floor(b + 0.5);
const double rintc = floor(c + 0.5);
const int a_neg_integer = ( a < 0.0 && fabs(a - rinta) < locEPS );
const int b_neg_integer = ( b < 0.0 && fabs(b - rintb) < locEPS );
const int c_neg_integer = ( c < 0.0 && fabs(c - rintc) < locEPS );
if(c_neg_integer) {
if((a_neg_integer && a > c+0.1) || (b_neg_integer && b > c+0.1)) {
/* 2F1 terminates early */
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else {
/* 2F1 does not terminate early enough, so something survives */
/* [Abramowitz+Stegun, 15.1.2] */
gsl_sf_result g1, g2, g3, g4, g5;
double s1, s2, s3, s4, s5;
int stat = 0;
stat += gsl_sf_lngamma_sgn_e(a-c+1, &g1, &s1);
stat += gsl_sf_lngamma_sgn_e(b-c+1, &g2, &s2);
stat += gsl_sf_lngamma_sgn_e(a, &g3, &s3);
stat += gsl_sf_lngamma_sgn_e(b, &g4, &s4);
stat += gsl_sf_lngamma_sgn_e(-c+2, &g5, &s5);
if(stat != 0) {
DOMAIN_ERROR(result);
}
else {
gsl_sf_result F;
int stat_F = gsl_sf_hyperg_2F1_e(a-c+1, b-c+1, -c+2, x, &F);
double ln_pre_val = g1.val + g2.val - g3.val - g4.val - g5.val;
double ln_pre_err = g1.err + g2.err + g3.err + g4.err + g5.err;
double sg = s1 * s2 * s3 * s4 * s5;
int stat_e = gsl_sf_exp_mult_err_e(ln_pre_val, ln_pre_err,
sg * F.val, F.err,
result);
return GSL_ERROR_SELECT_2(stat_e, stat_F);
}
}
}
else {
/* generic c */
gsl_sf_result F;
gsl_sf_result lng;
double sgn;
int stat_g = gsl_sf_lngamma_sgn_e(c, &lng, &sgn);
int stat_F = gsl_sf_hyperg_2F1_e(a, b, c, x, &F);
int stat_e = gsl_sf_exp_mult_err_e(-lng.val, lng.err,
sgn*F.val, F.err,
result);
return GSL_ERROR_SELECT_3(stat_e, stat_F, stat_g);
}
}
int
gsl_sf_hyperg_2F1_conj_renorm_e(const double aR, const double aI, const double c,
const double x,
gsl_sf_result * result
)
{
const double rintc = floor(c + 0.5);
const double rinta = floor(aR + 0.5);
const int a_neg_integer = ( aR < 0.0 && fabs(aR-rinta) < locEPS && aI == 0.0);
const int c_neg_integer = ( c < 0.0 && fabs(c - rintc) < locEPS );
if(c_neg_integer) {
if(a_neg_integer && aR > c+0.1) {
/* 2F1 terminates early */
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else {
/* 2F1 does not terminate early enough, so something survives */
/* [Abramowitz+Stegun, 15.1.2] */
gsl_sf_result g1, g2;
gsl_sf_result g3;
gsl_sf_result a1, a2;
int stat = 0;
stat += gsl_sf_lngamma_complex_e(aR-c+1, aI, &g1, &a1);
stat += gsl_sf_lngamma_complex_e(aR, aI, &g2, &a2);
stat += gsl_sf_lngamma_e(-c+2.0, &g3);
if(stat != 0) {
DOMAIN_ERROR(result);
}
else {
gsl_sf_result F;
int stat_F = gsl_sf_hyperg_2F1_conj_e(aR-c+1, aI, -c+2, x, &F);
double ln_pre_val = 2.0*(g1.val - g2.val) - g3.val;
double ln_pre_err = 2.0 * (g1.err + g2.err) + g3.err;
int stat_e = gsl_sf_exp_mult_err_e(ln_pre_val, ln_pre_err,
F.val, F.err,
result);
return GSL_ERROR_SELECT_2(stat_e, stat_F);
}
}
}
else {
/* generic c */
gsl_sf_result F;
gsl_sf_result lng;
double sgn;
int stat_g = gsl_sf_lngamma_sgn_e(c, &lng, &sgn);
int stat_F = gsl_sf_hyperg_2F1_conj_e(aR, aI, c, x, &F);
int stat_e = gsl_sf_exp_mult_err_e(-lng.val, lng.err,
sgn*F.val, F.err,
result);
return GSL_ERROR_SELECT_3(stat_e, stat_F, stat_g);
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_hyperg_2F1(double a, double b, double c, double x)
{
EVAL_RESULT(gsl_sf_hyperg_2F1_e(a, b, c, x, &result));
}
double gsl_sf_hyperg_2F1_conj(double aR, double aI, double c, double x)
{
EVAL_RESULT(gsl_sf_hyperg_2F1_conj_e(aR, aI, c, x, &result));
}
double gsl_sf_hyperg_2F1_renorm(double a, double b, double c, double x)
{
EVAL_RESULT(gsl_sf_hyperg_2F1_renorm_e(a, b, c, x, &result));
}
double gsl_sf_hyperg_2F1_conj_renorm(double aR, double aI, double c, double x)
{
EVAL_RESULT(gsl_sf_hyperg_2F1_conj_renorm_e(aR, aI, c, x, &result));
}
| {
"alphanum_fraction": 0.5482952573,
"avg_line_length": 30.413938754,
"ext": "c",
"hexsha": "65683ec8debb07e81ed394f4d2060a69900a4569",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z",
"max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ruslankuzmin/julia",
"max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/specfunc/hyperg_2F1.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "ruslankuzmin/julia",
"max_issues_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/specfunc/hyperg_2F1.c",
"max_line_length": 118,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/specfunc/hyperg_2F1.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": 10170,
"size": 28802
} |
/* monte/vegas.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: MJB */
/* Modified by: Brian Gough, 12/2000 */
/* This is an implementation of the adaptive Monte-Carlo algorithm
of G. P. Lepage, originally described in J. Comp. Phys. 27, 192(1978).
The current version of the algorithm was described in the Cornell
preprint CLNS-80/447 of March, 1980.
This code follows most closely the c version by D.R.Yennie, coded
in 1984.
The input coordinates are x[j], with upper and lower limits xu[j]
and xl[j]. The integration length in the j-th direction is
delx[j]. Each coordinate x[j] is rescaled to a variable y[j] in
the range 0 to 1. The range is divided into bins with boundaries
xi[i][j], where i=0 corresponds to y=0 and i=bins to y=1. The grid
is refined (ie, bins are adjusted) using d[i][j] which is some
variation on the squared sum. A third parameter used in defining
the real coordinate using random numbers is called z. It ranges
from 0 to bins. Its integer part gives the lower index of the bin
into which a call is to be placed, and the remainder gives the
location inside the bin.
When stratified sampling is used the bins are grouped into boxes,
and the algorithm allocates an equal number of function calls to
each box.
The variable alpha controls how "stiff" the rebinning algorithm is.
alpha = 0 means never change the grid. Alpha is typically set between
1 and 2.
*/
/* configuration headers */
#include <config.h>
/* standard headers */
#include <math.h>
#include <stdio.h>
/* gsl headers */
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_monte_vegas.h>
/* lib-specific headers */
#define BINS_MAX 50 /* even integer, will be divided by two */
/* A separable grid with coordinates and values */
#define COORD(s,i,j) ((s)->xi[(i)*(s)->dim + (j)])
#define NEW_COORD(s,i) ((s)->xin[(i)])
#define VALUE(s,i,j) ((s)->d[(i)*(s)->dim + (j)])
/* predeclare functions */
typedef int coord;
static void init_grid (gsl_monte_vegas_state * s, double xl[], double xu[],
size_t dim);
static void reset_grid_values (gsl_monte_vegas_state * s);
static void init_box_coord (gsl_monte_vegas_state * s, coord box[]);
static int change_box_coord (gsl_monte_vegas_state * s, coord box[]);
static void accumulate_distribution (gsl_monte_vegas_state * s, coord bin[],
double y);
static void random_point (double x[], coord bin[], double *bin_vol,
const coord box[],
const double xl[], const double xu[],
gsl_monte_vegas_state * s, gsl_rng * r);
static void resize_grid (gsl_monte_vegas_state * s, unsigned int bins);
static void refine_grid (gsl_monte_vegas_state * s);
static void print_lim (gsl_monte_vegas_state * state,
double xl[], double xu[], unsigned long dim);
static void print_head (gsl_monte_vegas_state * state,
unsigned long num_dim, unsigned long calls,
unsigned int it_num,
unsigned int bins, unsigned int boxes);
static void print_res (gsl_monte_vegas_state * state,
unsigned int itr, double res, double err,
double cum_res, double cum_err,
double chi_sq);
static void print_dist (gsl_monte_vegas_state * state, unsigned long dim);
static void print_grid (gsl_monte_vegas_state * state, unsigned long dim);
int
gsl_monte_vegas_integrate (gsl_monte_function * f,
double xl[], double xu[],
size_t dim, size_t calls,
gsl_rng * r,
gsl_monte_vegas_state * state,
double *result, double *abserr)
{
double cum_int, cum_sig;
size_t i, k, it;
if (dim != state->dim)
{
GSL_ERROR ("number of dimensions must match allocated size", GSL_EINVAL);
}
for (i = 0; i < dim; i++)
{
if (xu[i] <= xl[i])
{
GSL_ERROR ("xu must be greater than xl", GSL_EINVAL);
}
if (xu[i] - xl[i] > GSL_DBL_MAX)
{
GSL_ERROR ("Range of integration is too large, please rescale",
GSL_EINVAL);
}
}
if (state->stage == 0)
{
init_grid (state, xl, xu, dim);
if (state->verbose >= 0)
{
print_lim (state, xl, xu, dim);
}
}
if (state->stage <= 1)
{
state->wtd_int_sum = 0;
state->sum_wgts = 0;
state->chi_sum = 0;
state->it_num = 1;
state->samples = 0;
}
if (state->stage <= 2)
{
unsigned int bins = state->bins_max;
unsigned int boxes = 1;
if (state->mode != GSL_VEGAS_MODE_IMPORTANCE_ONLY)
{
/* shooting for 2 calls/box */
boxes = floor (pow (calls / 2.0, 1.0 / dim));
state->mode = GSL_VEGAS_MODE_IMPORTANCE;
if (2 * boxes >= state->bins_max)
{
/* if bins/box < 2 */
int box_per_bin = GSL_MAX (boxes / state->bins_max, 1);
bins = GSL_MIN(boxes / box_per_bin, state->bins_max);
boxes = box_per_bin * bins;
state->mode = GSL_VEGAS_MODE_STRATIFIED;
}
}
{
double tot_boxes = pow ((double) boxes, (double) dim);
state->calls_per_box = GSL_MAX (calls / tot_boxes, 2);
calls = state->calls_per_box * tot_boxes;
}
/* total volume of x-space/(avg num of calls/bin) */
state->jac = state->vol * pow ((double) bins, (double) dim) / calls;
state->boxes = boxes;
/* If the number of bins changes from the previous invocation, bins
are expanded or contracted accordingly, while preserving bin
density */
if (bins != state->bins)
{
resize_grid (state, bins);
if (state->verbose > 1)
{
print_grid (state, dim);
}
}
if (state->verbose >= 0)
{
print_head (state,
dim, calls, state->it_num, state->bins, state->boxes);
}
}
state->it_start = state->it_num;
cum_int = 0.0;
cum_sig = 0.0;
state->chisq = 0.0;
for (it = 0; it < state->iterations; it++)
{
double intgrl = 0.0, intgrl_sq = 0.0;
double sig = 0.0;
double wgt;
size_t calls_per_box = state->calls_per_box;
double jacbin = state->jac;
double *x = state->x;
coord *bin = state->bin;
state->it_num = state->it_start + it;
reset_grid_values (state);
init_box_coord (state, state->box);
do
{
double m = 0, q = 0;
double f_sq_sum = 0.0;
for (k = 0; k < calls_per_box; k++)
{
double fval, bin_vol;
random_point (x, bin, &bin_vol, state->box, xl, xu, state, r);
fval = jacbin * bin_vol * GSL_MONTE_FN_EVAL (f, x);
/* recurrence for mean and variance */
{
double d = fval - m;
m += d / (k + 1.0);
q += d * d * (k / (k + 1.0));
}
if (state->mode != GSL_VEGAS_MODE_STRATIFIED)
{
double f_sq = fval * fval;
accumulate_distribution (state, bin, f_sq);
}
}
intgrl += m * calls_per_box;
f_sq_sum = q * calls_per_box ;
sig += f_sq_sum ;
if (state->mode == GSL_VEGAS_MODE_STRATIFIED)
{
accumulate_distribution (state, bin, f_sq_sum);
}
}
while (change_box_coord (state, state->box));
/* Compute final results for this iteration */
sig = sig / (calls_per_box - 1.0) ;
if (sig > 0)
{
wgt = 1.0 / sig;
}
else if (state->sum_wgts > 0)
{
wgt = state->sum_wgts / state->samples;
}
else
{
wgt = 0.0;
}
intgrl_sq = intgrl * intgrl;
state->result = intgrl;
state->sigma = sqrt(sig);
if (wgt > 0.0)
{
state->samples++ ;
state->sum_wgts += wgt;
state->wtd_int_sum += intgrl * wgt;
state->chi_sum += intgrl_sq * wgt;
cum_int = state->wtd_int_sum / state->sum_wgts;
cum_sig = sqrt (1 / state->sum_wgts);
if (state->samples > 1)
{
state->chisq = (state->chi_sum - state->wtd_int_sum * cum_int) /
(state->samples - 1.0);
}
}
else
{
cum_int += (intgrl - cum_int) / (it + 1.0);
cum_sig = 0.0;
}
if (state->verbose >= 0)
{
print_res (state,
state->it_num, intgrl, sqrt (sig), cum_int, cum_sig,
state->chisq);
if (it + 1 == state->iterations && state->verbose > 0)
{
print_grid (state, dim);
}
}
if (state->verbose > 1)
{
print_dist (state, dim);
}
refine_grid (state);
if (state->verbose > 1)
{
print_grid (state, dim);
}
}
/* By setting stage to 1 further calls will generate independent
estimates based on the same grid, although it may be rebinned. */
state->stage = 1;
*result = cum_int;
*abserr = cum_sig;
return GSL_SUCCESS;
}
gsl_monte_vegas_state *
gsl_monte_vegas_alloc (size_t dim)
{
gsl_monte_vegas_state *s =
(gsl_monte_vegas_state *) malloc (sizeof (gsl_monte_vegas_state));
if (s == 0)
{
GSL_ERROR_VAL ("failed to allocate space for vegas state struct",
GSL_ENOMEM, 0);
}
s->delx = (double *) malloc (dim * sizeof (double));
if (s->delx == 0)
{
free (s);
GSL_ERROR_VAL ("failed to allocate space for delx", GSL_ENOMEM, 0);
}
s->d = (double *) malloc (BINS_MAX * dim * sizeof (double));
if (s->d == 0)
{
free (s->delx);
free (s);
GSL_ERROR_VAL ("failed to allocate space for d", GSL_ENOMEM, 0);
}
s->xi = (double *) malloc ((BINS_MAX + 1) * dim * sizeof (double));
if (s->xi == 0)
{
free (s->d);
free (s->delx);
free (s);
GSL_ERROR_VAL ("failed to allocate space for xi", GSL_ENOMEM, 0);
}
s->xin = (double *) malloc ((BINS_MAX + 1) * sizeof (double));
if (s->xin == 0)
{
free (s->xi);
free (s->d);
free (s->delx);
free (s);
GSL_ERROR_VAL ("failed to allocate space for xin", GSL_ENOMEM, 0);
}
s->weight = (double *) malloc (BINS_MAX * sizeof (double));
if (s->weight == 0)
{
free (s->xin);
free (s->xi);
free (s->d);
free (s->delx);
free (s);
GSL_ERROR_VAL ("failed to allocate space for xin", GSL_ENOMEM, 0);
}
s->box = (coord *) malloc (dim * sizeof (coord));
if (s->box == 0)
{
free (s->weight);
free (s->xin);
free (s->xi);
free (s->d);
free (s->delx);
free (s);
GSL_ERROR_VAL ("failed to allocate space for box", GSL_ENOMEM, 0);
}
s->bin = (coord *) malloc (dim * sizeof (coord));
if (s->bin == 0)
{
free (s->box);
free (s->weight);
free (s->xin);
free (s->xi);
free (s->d);
free (s->delx);
free (s);
GSL_ERROR_VAL ("failed to allocate space for bin", GSL_ENOMEM, 0);
}
s->x = (double *) malloc (dim * sizeof (double));
if (s->x == 0)
{
free (s->bin);
free (s->box);
free (s->weight);
free (s->xin);
free (s->xi);
free (s->d);
free (s->delx);
free (s);
GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
}
s->dim = dim;
s->bins_max = BINS_MAX;
gsl_monte_vegas_init (s);
return s;
}
/* Set some default values and whatever */
int
gsl_monte_vegas_init (gsl_monte_vegas_state * state)
{
state->stage = 0;
state->alpha = 1.5;
state->verbose = -1;
state->iterations = 5;
state->mode = GSL_VEGAS_MODE_IMPORTANCE;
state->chisq = 0;
state->bins = state->bins_max;
state->ostream = stdout;
return GSL_SUCCESS;
}
void
gsl_monte_vegas_free (gsl_monte_vegas_state * s)
{
free (s->x);
free (s->delx);
free (s->d);
free (s->xi);
free (s->xin);
free (s->weight);
free (s->box);
free (s->bin);
free (s);
}
static void
init_box_coord (gsl_monte_vegas_state * s, coord box[])
{
size_t i;
size_t dim = s->dim;
for (i = 0; i < dim; i++)
{
box[i] = 0;
}
}
/* change_box_coord steps through the box coord like
{0,0}, {0, 1}, {0, 2}, {0, 3}, {1, 0}, {1, 1}, {1, 2}, ...
*/
static int
change_box_coord (gsl_monte_vegas_state * s, coord box[])
{
int j = s->dim - 1;
int ng = s->boxes;
while (j >= 0)
{
box[j] = (box[j] + 1) % ng;
if (box[j] != 0)
{
return 1;
}
j--;
}
return 0;
}
static void
init_grid (gsl_monte_vegas_state * s, double xl[], double xu[], size_t dim)
{
size_t j;
double vol = 1.0;
s->bins = 1;
for (j = 0; j < dim; j++)
{
double dx = xu[j] - xl[j];
s->delx[j] = dx;
vol *= dx;
COORD (s, 0, j) = 0.0;
COORD (s, 1, j) = 1.0;
}
s->vol = vol;
}
static void
reset_grid_values (gsl_monte_vegas_state * s)
{
size_t i, j;
size_t dim = s->dim;
size_t bins = s->bins;
for (i = 0; i < bins; i++)
{
for (j = 0; j < dim; j++)
{
VALUE (s, i, j) = 0.0;
}
}
}
static void
accumulate_distribution (gsl_monte_vegas_state * s, coord bin[], double y)
{
size_t j;
size_t dim = s->dim;
for (j = 0; j < dim; j++)
{
int i = bin[j];
VALUE (s, i, j) += y;
}
}
static void
random_point (double x[], coord bin[], double *bin_vol,
const coord box[], const double xl[], const double xu[],
gsl_monte_vegas_state * s, gsl_rng * r)
{
/* Use the random number generator r to return a random position x
in a given box. The value of bin gives the bin location of the
random position (there may be several bins within a given box) */
double vol = 1.0;
size_t j;
size_t dim = s->dim;
size_t bins = s->bins;
size_t boxes = s->boxes;
DISCARD_POINTER(xu); /* prevent warning about unused parameter */
for (j = 0; j < dim; ++j)
{
/* box[j] + ran gives the position in the box units, while z
is the position in bin units. */
double z = ((box[j] + gsl_rng_uniform_pos (r)) / boxes) * bins;
int k = z;
double y, bin_width;
bin[j] = k;
if (k == 0)
{
bin_width = COORD (s, 1, j);
y = z * bin_width;
}
else
{
bin_width = COORD (s, k + 1, j) - COORD (s, k, j);
y = COORD (s, k, j) + (z - k) * bin_width;
}
x[j] = xl[j] + y * s->delx[j];
vol *= bin_width;
}
*bin_vol = vol;
}
static void
resize_grid (gsl_monte_vegas_state * s, unsigned int bins)
{
size_t j, k;
size_t dim = s->dim;
/* weight is ratio of bin sizes */
double pts_per_bin = (double) s->bins / (double) bins;
for (j = 0; j < dim; j++)
{
double xold;
double xnew = 0;
double dw = 0;
int i = 1;
for (k = 1; k <= s->bins; k++)
{
dw += 1.0;
xold = xnew;
xnew = COORD (s, k, j);
for (; dw > pts_per_bin; i++)
{
dw -= pts_per_bin;
NEW_COORD (s, i) = xnew - (xnew - xold) * dw;
}
}
for (k = 1 ; k < bins; k++)
{
COORD(s, k, j) = NEW_COORD(s, k);
}
COORD (s, bins, j) = 1;
}
s->bins = bins;
}
static void
refine_grid (gsl_monte_vegas_state * s)
{
size_t i, j, k;
size_t dim = s->dim;
size_t bins = s->bins;
for (j = 0; j < dim; j++)
{
double grid_tot_j, tot_weight;
double * weight = s->weight;
double oldg = VALUE (s, 0, j);
double newg = VALUE (s, 1, j);
VALUE (s, 0, j) = (oldg + newg) / 2;
grid_tot_j = VALUE (s, 0, j);
/* This implements gs[i][j] = (gs[i-1][j]+gs[i][j]+gs[i+1][j])/3 */
for (i = 1; i < bins - 1; i++)
{
double rc = oldg + newg;
oldg = newg;
newg = VALUE (s, i + 1, j);
VALUE (s, i, j) = (rc + newg) / 3;
grid_tot_j += VALUE (s, i, j);
}
VALUE (s, bins - 1, j) = (newg + oldg) / 2;
grid_tot_j += VALUE (s, bins - 1, j);
tot_weight = 0;
for (i = 0; i < bins; i++)
{
weight[i] = 0;
if (VALUE (s, i, j) > 0)
{
oldg = grid_tot_j / VALUE (s, i, j);
/* damped change */
weight[i] = pow (((oldg - 1) / oldg / log (oldg)), s->alpha);
}
tot_weight += weight[i];
#ifdef DEBUG
printf("weight[%d] = %g\n", i, weight[i]);
#endif
}
{
double pts_per_bin = tot_weight / bins;
double xold;
double xnew = 0;
double dw = 0;
i = 1;
for (k = 0; k < bins; k++)
{
dw += weight[k];
xold = xnew;
xnew = COORD (s, k + 1, j);
for (; dw > pts_per_bin; i++)
{
dw -= pts_per_bin;
NEW_COORD (s, i) = xnew - (xnew - xold) * dw / weight[k];
}
}
for (k = 1 ; k < bins ; k++)
{
COORD(s, k, j) = NEW_COORD(s, k);
}
COORD (s, bins, j) = 1;
}
}
}
static void
print_lim (gsl_monte_vegas_state * state,
double xl[], double xu[], unsigned long dim)
{
unsigned long j;
fprintf (state->ostream, "The limits of integration are:\n");
for (j = 0; j < dim; ++j)
fprintf (state->ostream, "\nxl[%lu]=%f xu[%lu]=%f", j, xl[j], j, xu[j]);
fprintf (state->ostream, "\n");
fflush (state->ostream);
}
static void
print_head (gsl_monte_vegas_state * state,
unsigned long num_dim, unsigned long calls,
unsigned int it_num, unsigned int bins, unsigned int boxes)
{
fprintf (state->ostream,
"\nnum_dim=%lu, calls=%lu, it_num=%d, max_it_num=%d ",
num_dim, calls, it_num, state->iterations);
fprintf (state->ostream,
"verb=%d, alph=%.2f,\nmode=%d, bins=%d, boxes=%d\n",
state->verbose, state->alpha, state->mode, bins, boxes);
fprintf (state->ostream,
"\n single.......iteration ");
fprintf (state->ostream, "accumulated......results \n");
fprintf (state->ostream,
"iteration integral sigma integral ");
fprintf (state->ostream, " sigma chi-sq/it\n\n");
fflush (state->ostream);
}
static void
print_res (gsl_monte_vegas_state * state,
unsigned int itr,
double res, double err,
double cum_res, double cum_err,
double chi_sq)
{
fprintf (state->ostream,
"%4d %6.4e %10.2e %6.4e %8.2e %10.2e\n",
itr, res, err, cum_res, cum_err, chi_sq);
fflush (state->ostream);
}
static void
print_dist (gsl_monte_vegas_state * state, unsigned long dim)
{
unsigned long i, j;
int p = state->verbose;
if (p < 1)
return;
for (j = 0; j < dim; ++j)
{
fprintf (state->ostream, "\n axis %lu \n", j);
fprintf (state->ostream, " x g\n");
for (i = 0; i < state->bins; i++)
{
fprintf (state->ostream, "weight [%11.2e , %11.2e] = ",
COORD (state, i, j), COORD(state,i+1,j));
fprintf (state->ostream, " %11.2e\n", VALUE (state, i, j));
}
fprintf (state->ostream, "\n");
}
fprintf (state->ostream, "\n");
fflush (state->ostream);
}
static void
print_grid (gsl_monte_vegas_state * state, unsigned long dim)
{
unsigned long i, j;
int p = state->verbose;
if (p < 1)
return;
for (j = 0; j < dim; ++j)
{
fprintf (state->ostream, "\n axis %lu \n", j);
fprintf (state->ostream, " x \n");
for (i = 0; i <= state->bins; i++)
{
fprintf (state->ostream, "%11.2e", COORD (state, i, j));
if (i % 5 == 4)
fprintf (state->ostream, "\n");
}
fprintf (state->ostream, "\n");
}
fprintf (state->ostream, "\n");
fflush (state->ostream);
}
| {
"alphanum_fraction": 0.5593152866,
"avg_line_length": 23.2323699422,
"ext": "c",
"hexsha": "cbc792db222588de0d60465dfd06752847398b0f",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/monte/vegas.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/monte/vegas.c",
"max_line_length": 79,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/monte/vegas.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": 6261,
"size": 20096
} |
/* These tests are based on the NIST Statistical Reference Datasets
See http://www.nist.gov/itl/div898/strd/index.html for more
information. */
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_ieee_utils.h>
size_t norris_n = 36;
double norris_x[] = { 0.2, 337.4, 118.2, 884.6, 10.1, 226.5, 666.3, 996.3,
448.6, 777.0, 558.2, 0.4, 0.6, 775.5, 666.9, 338.0,
447.5, 11.6, 556.0, 228.1, 995.8, 887.6, 120.2, 0.3,
0.3, 556.8, 339.1, 887.2, 999.0, 779.0, 11.1, 118.3,
229.2, 669.1, 448.9, 0.5 } ;
double norris_y[] = { 0.1, 338.8, 118.1, 888.0, 9.2, 228.1, 668.5, 998.5,
449.1, 778.9, 559.2, 0.3, 0.1, 778.1, 668.8, 339.3,
448.9, 10.8, 557.7, 228.3, 998.0, 888.8, 119.6, 0.3,
0.6, 557.6, 339.3, 888.0, 998.5, 778.9, 10.2, 117.6,
228.9, 668.4, 449.2, 0.2};
size_t noint1_n = 11;
double noint1_x[] = { 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70 };
double noint1_y[] = { 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140};
size_t noint2_n = 3;
double noint2_x[] = { 4, 5, 6 } ;
double noint2_y[] = { 3, 4, 4 } ;
int
main (void)
{
double x[1000], y[1000], w[1000];
size_t xstride = 2, wstride = 3, ystride = 5;
size_t i;
for (i = 0; i < norris_n; i++)
{
x[i*xstride] = norris_x[i];
w[i*wstride] = 1.0;
y[i*ystride] = norris_y[i];
}
gsl_ieee_env_setup();
{
double c0, c1, cov00, cov01, cov11, sumsq;
double expected_c0 = -0.262323073774029;
double expected_c1 = 1.00211681802045;
double expected_cov00 = pow(0.232818234301152, 2.0);
double expected_cov01 = -7.74327536339570e-05; /* computed from octave */
double expected_cov11 = pow(0.429796848199937E-03, 2.0);
double expected_sumsq = 26.6173985294224;
gsl_fit_linear (x, xstride, y, ystride, norris_n,
&c0, &c1, &cov00, &cov01, &cov11, &sumsq);
/* gsl_fit_wlinear (x, xstride, w, wstride, y, ystride, norris_n,
&c0, &c1, &cov00, &cov01, &cov11, &sumsq); */
gsl_test_rel (c0, expected_c0, 1e-10, "norris gsl_fit_linear c0") ;
gsl_test_rel (c1, expected_c1, 1e-10, "norris gsl_fit_linear c1") ;
gsl_test_rel (cov00, expected_cov00, 1e-10, "norris gsl_fit_linear cov00") ;
gsl_test_rel (cov01, expected_cov01, 1e-10, "norris gsl_fit_linear cov01") ;
gsl_test_rel (cov11, expected_cov11, 1e-10, "norris gsl_fit_linear cov11") ;
gsl_test_rel (sumsq, expected_sumsq, 1e-10, "norris gsl_fit_linear sumsq") ;
}
{
double c0, c1, cov00, cov01, cov11, sumsq;
double expected_c0 = -0.262323073774029;
double expected_c1 = 1.00211681802045;
double expected_cov00 = 6.92384428759429e-02; /* computed from octave */
double expected_cov01 = -9.89095016390515e-05; /* computed from octave */
double expected_cov11 = 2.35960747164148e-07; /* computed from octave */
double expected_sumsq = 26.6173985294224;
gsl_fit_wlinear (x, xstride, w, wstride, y, ystride, norris_n,
&c0, &c1, &cov00, &cov01, &cov11, &sumsq);
gsl_test_rel (c0, expected_c0, 1e-10, "norris gsl_fit_wlinear c0") ;
gsl_test_rel (c1, expected_c1, 1e-10, "norris gsl_fit_wlinear c1") ;
gsl_test_rel (cov00, expected_cov00, 1e-10, "norris gsl_fit_wlinear cov00") ;
gsl_test_rel (cov01, expected_cov01, 1e-10, "norris gsl_fit_wlinear cov01") ;
gsl_test_rel (cov11, expected_cov11, 1e-10, "norris gsl_fit_wlinear cov11") ;
gsl_test_rel (sumsq, expected_sumsq, 1e-10, "norris gsl_fit_wlinear sumsq") ;
}
for (i = 0; i < noint1_n; i++)
{
x[i*xstride] = noint1_x[i];
w[i*wstride] = 1.0;
y[i*ystride] = noint1_y[i];
}
{
double c1, cov11, sumsq;
double expected_c1 = 2.07438016528926;
double expected_cov11 = pow(0.165289256198347E-01, 2.0);
double expected_sumsq = 127.272727272727;
gsl_fit_mul (x, xstride, y, ystride, noint1_n, &c1, &cov11, &sumsq);
gsl_test_rel (c1, expected_c1, 1e-10, "noint1 gsl_fit_mul c1") ;
gsl_test_rel (cov11, expected_cov11, 1e-10, "noint1 gsl_fit_mul cov11") ;
gsl_test_rel (sumsq, expected_sumsq, 1e-10, "noint1 gsl_fit_mul sumsq") ;
}
{
double c1, cov11, sumsq;
double expected_c1 = 2.07438016528926;
double expected_cov11 = 2.14661371686165e-05; /* computed from octave */
double expected_sumsq = 127.272727272727;
gsl_fit_wmul (x, xstride, w, wstride, y, ystride, noint1_n, &c1, &cov11, &sumsq);
gsl_test_rel (c1, expected_c1, 1e-10, "noint1 gsl_fit_wmul c1") ;
gsl_test_rel (cov11, expected_cov11, 1e-10, "noint1 gsl_fit_wmul cov11") ;
gsl_test_rel (sumsq, expected_sumsq, 1e-10, "noint1 gsl_fit_wmul sumsq") ;
}
for (i = 0; i < noint2_n; i++)
{
x[i*xstride] = noint2_x[i];
w[i*wstride] = 1.0;
y[i*ystride] = noint2_y[i];
}
{
double c1, cov11, sumsq;
double expected_c1 = 0.727272727272727;
double expected_cov11 = pow(0.420827318078432E-01, 2.0);
double expected_sumsq = 0.272727272727273;
gsl_fit_mul (x, xstride, y, ystride, noint2_n, &c1, &cov11, &sumsq);
gsl_test_rel (c1, expected_c1, 1e-10, "noint2 gsl_fit_mul c1") ;
gsl_test_rel (cov11, expected_cov11, 1e-10, "noint2 gsl_fit_mul cov11") ;
gsl_test_rel (sumsq, expected_sumsq, 1e-10, "noint2 gsl_fit_mul sumsq") ;
}
{
double c1, cov11, sumsq;
double expected_c1 = 0.727272727272727;
double expected_cov11 = 1.29870129870130e-02 ; /* computed from octave */
double expected_sumsq = 0.272727272727273;
gsl_fit_wmul (x, xstride, w, wstride, y, ystride, noint2_n, &c1, &cov11, &sumsq);
gsl_test_rel (c1, expected_c1, 1e-10, "noint2 gsl_fit_wmul c1") ;
gsl_test_rel (cov11, expected_cov11, 1e-10, "noint2 gsl_fit_wmul cov11") ;
gsl_test_rel (sumsq, expected_sumsq, 1e-10, "noint2 gsl_fit_wmul sumsq") ;
}
/* now summarize the results */
exit (gsl_test_summary ());
}
| {
"alphanum_fraction": 0.6228978008,
"avg_line_length": 35.5402298851,
"ext": "c",
"hexsha": "255552201c78758173b5721c182d98cede62025c",
"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/fit/test.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/fit/test.c",
"max_line_length": 85,
"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/fit/test.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": 2445,
"size": 6184
} |
#pragma once
#include <string_view>
#include <gsl/span>
#include <spirv_cross.hpp>
namespace babylon
{
class ShaderCompiler
{
public:
ShaderCompiler();
~ShaderCompiler();
struct ShaderInfo
{
std::unique_ptr<const spirv_cross::Compiler> Compiler;
gsl::span<uint8_t> Bytes;
};
void Compile(std::string_view vertexSource, std::string_view fragmentSource, std::function<void (ShaderInfo, ShaderInfo)> onCompiled);
};
}
| {
"alphanum_fraction": 0.6351084813,
"avg_line_length": 21.125,
"ext": "h",
"hexsha": "cdb8eb013dc3cfcc37e75c40dd132147bd4b168b",
"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": "548684984126ee6cd242f2d73ecff8c6f5614b02",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ryantrem/BabylonNative",
"max_forks_repo_path": "Library/Source/ShaderCompiler.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "6d15ec5d418f7f723eba574665233049c785cc72",
"max_issues_repo_issues_event_max_datetime": "2021-10-13T00:01:39.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-04-03T22:56:41.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "TrevorDev/BabylonNative",
"max_issues_repo_path": "Library/Source/ShaderCompiler.h",
"max_line_length": 142,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "6d15ec5d418f7f723eba574665233049c785cc72",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "TrevorDev/BabylonNative",
"max_stars_repo_path": "Library/Source/ShaderCompiler.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-09T11:42:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-02-18T22:03:11.000Z",
"num_tokens": 112,
"size": 507
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef _libmatrixmult_h
#define _libmatrixmult_h
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
// *****************************************************************
// We support Intel MKL (recommended) or OpenBLAS.
// These flags are used for conditional compilation with mkl and openblas
// #define USE_INTEL_MKL
// #define USE_GNU_THREADING
// #define USE_OPEN_BLAS
// *****************************************************************
//#ifdef __cplusplus
//extern "C" {
//#endif
//#ifdef __cplusplus
//}
//#endif
// Since we call cblas_dgemm in openmp for loop,
// we call "extension" APIs for setting number of threads of the given API.
// For example: for OpenBLAS we use openblas_set_num_threads and
// for MKL we use mkl_set_num_threads. This avoids performance degradation due to overprovisioning.
#ifdef USE_OPEN_BLAS
#include <cblas.h>
// extern "C" void openblas_set_num_threads(int numThreads);
#elif defined USE_INTEL_MKL
#include <mkl.h>
#include <mkl_service.h>
#endif
void setNumThreadsForBLAS(int numThreads);
// Multiplies two matrices m1Ptr and m2Ptr in row-major format of shape
// (m1rlen, m1clen) and (m1clen, m2clen)
void matmult(double* m1Ptr, double* m2Ptr, double* retPtr, int m1rlen,
int m1clen, int m2clen, int numThreads);
void tsmm(double* m1Ptr, double* retPtr, int m1rlen, int m1clen, bool isLeftTranspose, int numThreads);
#endif
| {
"alphanum_fraction": 0.6835834069,
"avg_line_length": 35.9682539683,
"ext": "h",
"hexsha": "d39242e7b00ef33ee4e987e626077b147e42bb72",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-09-21T13:09:44.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-21T13:09:44.000Z",
"max_forks_repo_head_hexsha": "1f508911052f035580c2b9120912dc63c47804d2",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "frreiss/fred-systemml",
"max_forks_repo_path": "src/main/cpp/libmatrixmult.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1f508911052f035580c2b9120912dc63c47804d2",
"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": "frreiss/fred-systemml",
"max_issues_repo_path": "src/main/cpp/libmatrixmult.h",
"max_line_length": 104,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "1f508911052f035580c2b9120912dc63c47804d2",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "frreiss/fred-systemml",
"max_stars_repo_path": "src/main/cpp/libmatrixmult.h",
"max_stars_repo_stars_event_max_datetime": "2018-09-21T13:09:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-09-21T13:09:43.000Z",
"num_tokens": 574,
"size": 2266
} |
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_plain.h>
#include <gsl/gsl_monte_miser.h>
#include <gsl/gsl_monte_vegas.h>
/* Computation of the integral,
I = int (dx dy dz)/(2pi)^3 1/(1-cos(x)cos(y)cos(z))
over (-pi,-pi,-pi) to (+pi, +pi, +pi). The exact answer
is Gamma(1/4)^4/(4 pi^3). This example is taken from
C.Itzykson, J.M.Drouffe, "Statistical Field Theory -
Volume 1", Section 1.1, p21, which cites the original
paper M.L.Glasser, I.J.Zucker, Proc.Natl.Acad.Sci.USA 74
1800 (1977) */
/* For simplicity we compute the integral over the region
(0,0,0) -> (pi,pi,pi) and multiply by 8 */
double exact = 1.3932039296856768591842462603255;
double
g (double *k, size_t dim, void *params)
{
double A = 1.0 / (M_PI * M_PI * M_PI);
return A / (1.0 - cos (k[0]) * cos (k[1]) * cos (k[2]));
}
void
display_results (char *title, double result, double error)
{
printf ("%s ==================\n", title);
printf ("result = % .6f\n", result);
printf ("sigma = % .6f\n", error);
printf ("exact = % .6f\n", exact);
printf ("error = % .6f = %.2g sigma\n", result - exact,
fabs (result - exact) / error);
}
int
main (void)
{
double res, err;
double xl[3] = { 0, 0, 0 };
double xu[3] = { M_PI, M_PI, M_PI };
const gsl_rng_type *T;
gsl_rng *r;
gsl_monte_function G = { &g, 3, 0 };
size_t calls = 500000;
gsl_rng_env_setup ();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
{
gsl_monte_plain_state *s = gsl_monte_plain_alloc (3);
gsl_monte_plain_integrate (&G, xl, xu, 3, calls, r, s,
&res, &err);
gsl_monte_plain_free (s);
display_results ("plain", res, err);
}
{
gsl_monte_miser_state *s = gsl_monte_miser_alloc (3);
gsl_monte_miser_integrate (&G, xl, xu, 3, calls, r, s,
&res, &err);
gsl_monte_miser_free (s);
display_results ("miser", res, err);
}
{
gsl_monte_vegas_state *s = gsl_monte_vegas_alloc (3);
gsl_monte_vegas_integrate (&G, xl, xu, 3, 10000, r, s,
&res, &err);
display_results ("vegas warm-up", res, err);
printf ("converging...\n");
do
{
gsl_monte_vegas_integrate (&G, xl, xu, 3, calls/5, r, s,
&res, &err);
printf ("result = % .6f sigma = % .6f "
"chisq/dof = %.1f\n", res, err, gsl_monte_vegas_chisq (s));
}
while (fabs (gsl_monte_vegas_chisq (s) - 1.0) > 0.5);
display_results ("vegas final", res, err);
gsl_monte_vegas_free (s);
}
gsl_rng_free (r);
return 0;
}
| {
"alphanum_fraction": 0.5746352413,
"avg_line_length": 24.9813084112,
"ext": "c",
"hexsha": "a2b95fcf974e9e2fde88e54f11481b7b1b0ae1d0",
"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/doc/examples/monte.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/doc/examples/monte.c",
"max_line_length": 75,
"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/doc/examples/monte.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": 909,
"size": 2673
} |
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_multifit_nlinear.h>
/* number of data points to fit */
#define N 40
struct data {
size_t n;
double * y;
};
int
expb_f (const gsl_vector * x, void *data,
gsl_vector * f)
{
size_t n = ((struct data *)data)->n;
double *y = ((struct data *)data)->y;
double A = gsl_vector_get (x, 0);
double lambda = gsl_vector_get (x, 1);
double b = gsl_vector_get (x, 2);
size_t i;
for (i = 0; i < n; i++)
{
/* Model Yi = A * exp(-lambda * i) + b */
double t = i;
double Yi = A * exp (-lambda * t) + b;
gsl_vector_set (f, i, Yi - y[i]);
}
return GSL_SUCCESS;
}
int
expb_df (const gsl_vector * x, void *data,
gsl_matrix * J)
{
size_t n = ((struct data *)data)->n;
double A = gsl_vector_get (x, 0);
double lambda = gsl_vector_get (x, 1);
size_t i;
for (i = 0; i < n; i++)
{
/* Jacobian matrix J(i,j) = dfi / dxj, */
/* where fi = (Yi - yi)/sigma[i], */
/* Yi = A * exp(-lambda * i) + b */
/* and the xj are the parameters (A,lambda,b) */
double t = i;
double e = exp(-lambda * t);
gsl_matrix_set (J, i, 0, e);
gsl_matrix_set (J, i, 1, -t * A * e);
gsl_matrix_set (J, i, 2, 1.0);
}
return GSL_SUCCESS;
}
void
callback(const size_t iter, void *params,
const gsl_multifit_nlinear_workspace *w)
{
gsl_vector *f = gsl_multifit_nlinear_residual(w);
gsl_vector *x = gsl_multifit_nlinear_position(w);
double rcond;
/* compute reciprocal condition number of J(x) */
gsl_multifit_nlinear_rcond(&rcond, w);
fprintf(stderr, "iter %2zu: A = %.4f, lambda = %.4f, b = %.4f, cond(J) = %8.4f, |f(x)| = %.4f\n",
iter,
gsl_vector_get(x, 0),
gsl_vector_get(x, 1),
gsl_vector_get(x, 2),
1.0 / rcond,
gsl_blas_dnrm2(f));
}
int
main (void)
{
const gsl_multifit_nlinear_type *T = gsl_multifit_nlinear_trust;
gsl_multifit_nlinear_workspace *w;
gsl_multifit_nlinear_fdf fdf;
gsl_multifit_nlinear_parameters fdf_params =
gsl_multifit_nlinear_default_parameters();
const size_t n = N;
const size_t p = 3;
gsl_vector *f;
gsl_matrix *J;
gsl_matrix *covar = gsl_matrix_alloc (p, p);
double y[N], weights[N];
struct data d = { n, y };
double x_init[3] = { 1.0, 1.0, 0.0 }; /* starting values */
gsl_vector_view x = gsl_vector_view_array (x_init, p);
gsl_vector_view wts = gsl_vector_view_array(weights, n);
gsl_rng * r;
double chisq, chisq0;
int status, info;
size_t i;
const double xtol = 1e-8;
const double gtol = 1e-8;
const double ftol = 0.0;
gsl_rng_env_setup();
r = gsl_rng_alloc(gsl_rng_default);
/* define the function to be minimized */
fdf.f = expb_f;
fdf.df = expb_df; /* set to NULL for finite-difference Jacobian */
fdf.fvv = NULL; /* not using geodesic acceleration */
fdf.n = n;
fdf.p = p;
fdf.params = &d;
/* this is the data to be fitted */
for (i = 0; i < n; i++)
{
double t = i;
double yi = 1.0 + 5 * exp (-0.1 * t);
double si = 0.1 * yi;
double dy = gsl_ran_gaussian(r, si);
weights[i] = 1.0 / (si * si);
y[i] = yi + dy;
printf ("data: %zu %g %g\n", i, y[i], si);
};
/* allocate workspace with default parameters */
w = gsl_multifit_nlinear_alloc (T, &fdf_params, n, p);
/* initialize solver with starting point and weights */
gsl_multifit_nlinear_winit (&x.vector, &wts.vector, &fdf, w);
/* compute initial cost function */
f = gsl_multifit_nlinear_residual(w);
gsl_blas_ddot(f, f, &chisq0);
/* solve the system with a maximum of 20 iterations */
status = gsl_multifit_nlinear_driver(20, xtol, gtol, ftol,
callback, NULL, &info, w);
/* compute covariance of best fit parameters */
J = gsl_multifit_nlinear_jac(w);
gsl_multifit_nlinear_covar (J, 0.0, covar);
/* compute final cost */
gsl_blas_ddot(f, f, &chisq);
#define FIT(i) gsl_vector_get(w->x, i)
#define ERR(i) sqrt(gsl_matrix_get(covar,i,i))
fprintf(stderr, "summary from method '%s/%s'\n",
gsl_multifit_nlinear_name(w),
gsl_multifit_nlinear_trs_name(w));
fprintf(stderr, "number of iterations: %zu\n",
gsl_multifit_nlinear_niter(w));
fprintf(stderr, "function evaluations: %zu\n", fdf.nevalf);
fprintf(stderr, "Jacobian evaluations: %zu\n", fdf.nevaldf);
fprintf(stderr, "reason for stopping: %s\n",
(info == 1) ? "small step size" : "small gradient");
fprintf(stderr, "initial |f(x)| = %f\n", sqrt(chisq0));
fprintf(stderr, "final |f(x)| = %f\n", sqrt(chisq));
{
double dof = n - p;
double c = GSL_MAX_DBL(1, sqrt(chisq / dof));
fprintf(stderr, "chisq/dof = %g\n", chisq / dof);
fprintf (stderr, "A = %.5f +/- %.5f\n", FIT(0), c*ERR(0));
fprintf (stderr, "lambda = %.5f +/- %.5f\n", FIT(1), c*ERR(1));
fprintf (stderr, "b = %.5f +/- %.5f\n", FIT(2), c*ERR(2));
}
fprintf (stderr, "status = %s\n", gsl_strerror (status));
gsl_multifit_nlinear_free (w);
gsl_matrix_free (covar);
gsl_rng_free (r);
return 0;
}
| {
"alphanum_fraction": 0.6025302115,
"avg_line_length": 27.158974359,
"ext": "c",
"hexsha": "370ad8f74d26f990c53c3969f4883c79c4fd3da0",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/nlfit.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/doc/examples/nlfit.c",
"max_line_length": 99,
"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/doc_texinfo/examples/nlfit.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": 1736,
"size": 5296
} |
/*
C code for Binney (2012)'s Staeckel approximation code
*/
#ifdef _WIN32
#include <Python.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_integration.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#define CHUNKSIZE 10
//Potentials
#include <galpy_potentials.h>
#include <integrateFullOrbit.h>
#include <actionAngle.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
//Macros to export functions in DLL on different OS
#if defined(_WIN32)
#define EXPORT __declspec(dllexport)
#elif defined(__GNUC__)
#define EXPORT __attribute__((visibility("default")))
#else
// Just do nothing?
#define EXPORT
#endif
/*
Structure Declarations
*/
struct JRStaeckelArg{
double E;
double Lz22delta;
double I3U;
double delta;
double u0;
double sinh2u0;
double v0;
double sin2v0;
double potu0v0;
int nargs;
struct potentialArg * actionAngleArgs;
};
struct JzStaeckelArg{
double E;
double Lz22delta;
double I3V;
double delta;
double u0;
double cosh2u0;
double sinh2u0;
double potupi2;
int nargs;
struct potentialArg * actionAngleArgs;
};
struct dJRStaeckelArg{
double E;
double Lz22delta;
double I3U;
double delta;
double u0;
double sinh2u0;
double v0;
double sin2v0;
double potu0v0;
double umin;
double umax;
int nargs;
struct potentialArg * actionAngleArgs;
};
struct dJzStaeckelArg{
double E;
double Lz22delta;
double I3V;
double delta;
double u0;
double cosh2u0;
double sinh2u0;
double potupi2;
double vmin;
int nargs;
struct potentialArg * actionAngleArgs;
};
struct u0EqArg{
double E;
double Lz22delta;
double delta;
int nargs;
struct potentialArg * actionAngleArgs;
};
/*
Function Declarations
*/
EXPORT void calcu0(int,double *,double *,int,int *,double *,int,double*,
double *,int *);
EXPORT void actionAngleStaeckel_uminUmaxVmin(int,double *,double *,double *,double *,
double *,double *,int,int *,double *,
int,double *,double *,
double *,double *,int *);
EXPORT void actionAngleStaeckel_actions(int,double *,double *,double *,double *,
double *,double *,int,int *,double *,int,
double *,int,double *,double *,int *);
EXPORT void actionAngleStaeckel_actionsFreqsAngles(int,double *,double *,double *,
double *,double *,double *,
int,int *,double *,
int,double *,int,double *,double *,
double *,double *,double *,
double *,double *,double *,int *);
EXPORT void actionAngleStaeckel_actionsFreqs(int,double *,double *,double *,double *,
double *,double *,int,int *,double *,
int,double *,int,double *,double *,
double *,double *,double *,int *);
void calcAnglesStaeckel(int,double *,double *,double *,double *,double *,
double *,double *,double *,double *,double *,double *,
double *,double *,double *,double *,double *,double *,
double *,double *,double *,double *,double *,double *,
double *,int,double *,double *,double *,double *,
double *,double *,double *,double *,double *,double *,
int,struct potentialArg *,int);
void calcFreqsFromDerivsStaeckel(int,double *,double *,double *,
double *,double *,double *,
double *,double *,double *,double *);
void calcdI3dJFromDerivsStaeckel(int,double *,double *,double *,double *,
double *,double *,double *,double *);
void calcJRStaeckel(int,double *,double *,double *,double *,double *,double *,
int,double *,double *,double *,double *,double *,double *,
int,struct potentialArg *,int);
void calcJzStaeckel(int,double *,double *,double *,double *,double *,int,
double *,double *,double *,double *,double *,int,
struct potentialArg *,int);
void calcdJRStaeckel(int,double *,double *,double *,double *,double *,
double *,double *,double *,int,
double *,double *,double *,double *,double *,double *,int,
struct potentialArg *,int);
void calcdJzStaeckel(int,double *,double *,double *,double *,double *,
double *,double *,int,double *,double *,double *,double *,
double *,int,
struct potentialArg *,int);
void calcUminUmax(int,double *,double *,double *,double *,double *,double *,
double *,int,double *,double *,double *,double *,double *,
double *,int,struct potentialArg *);
void calcVmin(int,double *,double *,double *,double *,double *,double *,int,
double *,double *,double *,double *,double *,int,
struct potentialArg *);
double JRStaeckelIntegrandSquared(double,void *);
double JRStaeckelIntegrand(double,void *);
double JzStaeckelIntegrandSquared(double,void *);
double JzStaeckelIntegrand(double,void *);
double dJRdEStaeckelIntegrand(double,void *);
double dJRdELowStaeckelIntegrand(double,void *);
double dJRdEHighStaeckelIntegrand(double,void *);
double dJRdLzStaeckelIntegrand(double,void *);
double dJRdLzLowStaeckelIntegrand(double,void *);
double dJRdLzHighStaeckelIntegrand(double,void *);
double dJRdI3StaeckelIntegrand(double,void *);
double dJRdI3LowStaeckelIntegrand(double,void *);
double dJRdI3HighStaeckelIntegrand(double,void *);
double dJzdEStaeckelIntegrand(double,void *);
double dJzdELowStaeckelIntegrand(double,void *);
double dJzdEHighStaeckelIntegrand(double,void *);
double dJzdLzStaeckelIntegrand(double,void *);
double dJzdLzLowStaeckelIntegrand(double,void *);
double dJzdLzHighStaeckelIntegrand(double,void *);
double dJzdI3StaeckelIntegrand(double,void *);
double dJzdI3LowStaeckelIntegrand(double,void *);
double dJzdI3HighStaeckelIntegrand(double,void *);
double u0Equation(double,void *);
double evaluatePotentials(double,double,int, struct potentialArg *);
double evaluatePotentialsUV(double,double,double,int,struct potentialArg *);
/*
Actual functions, inlines first
*/
static inline void uv_to_Rz(double u, double v, double * R, double *z,
double delta){
*R= delta * sinh(u) * sin(v);
*z= delta * cosh(u) * cos(v);
}
static inline void Rz_to_uv_vec(int ndata,
double *R,
double *z,
double *u,
double *v,
int ndelta,
double * delta){
int ii;
double d12, d22, coshu, cosv,tdelta;
int delta_stride= ndelta == 1 ? 0 : 1;
for (ii=0; ii < ndata; ii++) {
tdelta= *(delta+ii*delta_stride);
d12= (*(z+ii)+tdelta)*(*(z+ii)+tdelta)+(*(R+ii))*(*(R+ii));
d22= (*(z+ii)-tdelta)*(*(z+ii)-tdelta)+(*(R+ii))*(*(R+ii));
coshu= 0.5/tdelta*(sqrt(d12)+sqrt(d22));
cosv= 0.5/tdelta*(sqrt(d12)-sqrt(d22));
*u++= acosh(coshu);
*v++= acos(cosv);
}
u-= ndata;
v-= ndata;
}
static inline void calcEL(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *E,
double *Lz,
int nargs,
struct potentialArg * actionAngleArgs){
int ii;
for (ii=0; ii < ndata; ii++){
*(E+ii)= evaluatePotentials(*(R+ii),*(z+ii),
nargs,actionAngleArgs)
+ 0.5 * *(vR+ii) * *(vR+ii)
+ 0.5 * *(vT+ii) * *(vT+ii)
+ 0.5 * *(vz+ii) * *(vz+ii);
*(Lz+ii)= *(R+ii) * *(vT+ii);
}
}
/*
MAIN FUNCTIONS
*/
void calcu0(int ndata,
double *E,
double *Lz,
int npot,
int * pot_type,
double * pot_args,
int ndelta,
double * delta,
double *u0,
int * err){
int ii;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_leapFuncArgs_Full(npot,actionAngleArgs,&pot_type,&pot_args);
//setup the function to be minimized
gsl_function u0Eq;
struct u0EqArg * params= (struct u0EqArg *) malloc ( sizeof (struct u0EqArg) );
params->nargs= npot;
params->actionAngleArgs= actionAngleArgs;
//Setup solver
int status;
int iter, max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double u_guess, u_lo, u_hi;
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc (T);
u0Eq.function = &u0Equation;
int delta_stride= ndelta == 1 ? 0 : 1;
for (ii=0; ii < ndata; ii++){
//Setup function
params->delta= *(delta+ii*delta_stride);
params->E= *(E+ii);
params->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
u0Eq.params = params;
//Find starting points for minimum
u_guess= 1.;
u_lo= 0.001;
u_hi= 100.;
gsl_set_error_handler_off();
status = gsl_min_fminimizer_set (s, &u0Eq, u_guess, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(u0+ii)= u_hi;
gsl_set_error_handler (NULL);
continue;
}
gsl_set_error_handler (NULL);
iter= 0;
do
{
iter++;
status = gsl_min_fminimizer_iterate (s);
u_guess = gsl_min_fminimizer_x_minimum (s);
u_lo = gsl_min_fminimizer_x_lower (s);
u_hi = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
*(u0+ii)= gsl_min_fminimizer_x_minimum (s);
}
gsl_min_fminimizer_free (s);
free(params);
free_potentialArgs(npot,actionAngleArgs);
free(actionAngleArgs);
*err= status;
}
void actionAngleStaeckel_uminUmaxVmin(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *u0,
int npot,
int * pot_type,
double * pot_args,
int ndelta,
double * delta,
double *umin,
double *umax,
double *vmin,
int * err){
// Just copied this over from actionAngleStaeckel_actions below, not elegant
// but does the job...
int ii;
double tdelta;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_leapFuncArgs_Full(npot,actionAngleArgs,&pot_type,&pot_args);
//E,Lz
double *E= (double *) malloc ( ndata * sizeof(double) );
double *Lz= (double *) malloc ( ndata * sizeof(double) );
calcEL(ndata,R,vR,vT,z,vz,E,Lz,npot,actionAngleArgs);
//Calculate all necessary parameters
double *ux= (double *) malloc ( ndata * sizeof(double) );
double *vx= (double *) malloc ( ndata * sizeof(double) );
Rz_to_uv_vec(ndata,R,z,ux,vx,ndelta,delta);
double *coshux= (double *) malloc ( ndata * sizeof(double) );
double *sinhux= (double *) malloc ( ndata * sizeof(double) );
double *sinvx= (double *) malloc ( ndata * sizeof(double) );
double *cosvx= (double *) malloc ( ndata * sizeof(double) );
double *pux= (double *) malloc ( ndata * sizeof(double) );
double *pvx= (double *) malloc ( ndata * sizeof(double) );
double *sinh2u0= (double *) malloc ( ndata * sizeof(double) );
double *cosh2u0= (double *) malloc ( ndata * sizeof(double) );
double *v0= (double *) malloc ( ndata * sizeof(double) );
double *sin2v0= (double *) malloc ( ndata * sizeof(double) );
double *potu0v0= (double *) malloc ( ndata * sizeof(double) );
double *potupi2= (double *) malloc ( ndata * sizeof(double) );
double *I3U= (double *) malloc ( ndata * sizeof(double) );
double *I3V= (double *) malloc ( ndata * sizeof(double) );
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) private(ii,tdelta)
for (ii=0; ii < ndata; ii++){
tdelta= *(delta+ii*delta_stride);
*(coshux+ii)= cosh(*(ux+ii));
*(sinhux+ii)= sinh(*(ux+ii));
*(cosvx+ii)= cos(*(vx+ii));
*(sinvx+ii)= sin(*(vx+ii));
*(pux+ii)= tdelta * (*(vR+ii) * *(coshux+ii) * *(sinvx+ii)
+ *(vz+ii) * *(sinhux+ii) * *(cosvx+ii));
*(pvx+ii)= tdelta * (*(vR+ii) * *(sinhux+ii) * *(cosvx+ii)
- *(vz+ii) * *(coshux+ii) * *(sinvx+ii));
*(sinh2u0+ii)= sinh(*(u0+ii)) * sinh(*(u0+ii));
*(cosh2u0+ii)= cosh(*(u0+ii)) * cosh(*(u0+ii));
*(v0+ii)= 0.5 * M_PI; //*(vx+ii);
*(sin2v0+ii)= sin(*(v0+ii)) * sin(*(v0+ii));
*(potu0v0+ii)= evaluatePotentialsUV(*(u0+ii),*(v0+ii),tdelta,
npot,actionAngleArgs);
*(I3U+ii)= *(E+ii) * *(sinhux+ii) * *(sinhux+ii)
- 0.5 * *(pux+ii) * *(pux+ii) / tdelta / tdelta
- 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinhux+ii) / *(sinhux+ii)
- ( *(sinhux+ii) * *(sinhux+ii) + *(sin2v0+ii))
*evaluatePotentialsUV(*(ux+ii),*(v0+ii),tdelta,
npot,actionAngleArgs)
+ ( *(sinh2u0+ii) + *(sin2v0+ii) )* *(potu0v0+ii);
*(potupi2+ii)= evaluatePotentialsUV(*(u0+ii),0.5 * M_PI,tdelta,
npot,actionAngleArgs);
*(I3V+ii)= - *(E+ii) * *(sinvx+ii) * *(sinvx+ii)
+ 0.5 * *(pvx+ii) * *(pvx+ii) / tdelta / tdelta
+ 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinvx+ii) / *(sinvx+ii)
- *(cosh2u0+ii) * *(potupi2+ii)
+ ( *(sinh2u0+ii) + *(sinvx+ii) * *(sinvx+ii))
* evaluatePotentialsUV(*(u0+ii),*(vx+ii),tdelta,
npot,actionAngleArgs);
}
//Calculate 'peri' and 'apo'centers
calcUminUmax(ndata,umin,umax,ux,pux,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,
sin2v0,potu0v0,npot,actionAngleArgs);
calcVmin(ndata,vmin,vx,pvx,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs);
//Free
free_potentialArgs(npot,actionAngleArgs);
free(actionAngleArgs);
free(E);
free(Lz);
free(ux);
free(vx);
free(coshux);
free(sinhux);
free(sinvx);
free(cosvx);
free(pux);
free(pvx);
free(sinh2u0);
free(cosh2u0);
free(v0);
free(sin2v0);
free(potu0v0);
free(potupi2);
free(I3U);
free(I3V);
}
void actionAngleStaeckel_actions(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *u0,
int npot,
int * pot_type,
double * pot_args,
int ndelta,
double * delta,
int order,
double *jr,
double *jz,
int * err){
int ii;
double tdelta;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_leapFuncArgs_Full(npot,actionAngleArgs,&pot_type,&pot_args);
//E,Lz
double *E= (double *) malloc ( ndata * sizeof(double) );
double *Lz= (double *) malloc ( ndata * sizeof(double) );
calcEL(ndata,R,vR,vT,z,vz,E,Lz,npot,actionAngleArgs);
//Calculate all necessary parameters
double *ux= (double *) malloc ( ndata * sizeof(double) );
double *vx= (double *) malloc ( ndata * sizeof(double) );
Rz_to_uv_vec(ndata,R,z,ux,vx,ndelta,delta);
double *coshux= (double *) malloc ( ndata * sizeof(double) );
double *sinhux= (double *) malloc ( ndata * sizeof(double) );
double *sinvx= (double *) malloc ( ndata * sizeof(double) );
double *cosvx= (double *) malloc ( ndata * sizeof(double) );
double *pux= (double *) malloc ( ndata * sizeof(double) );
double *pvx= (double *) malloc ( ndata * sizeof(double) );
double *sinh2u0= (double *) malloc ( ndata * sizeof(double) );
double *cosh2u0= (double *) malloc ( ndata * sizeof(double) );
double *v0= (double *) malloc ( ndata * sizeof(double) );
double *sin2v0= (double *) malloc ( ndata * sizeof(double) );
double *potu0v0= (double *) malloc ( ndata * sizeof(double) );
double *potupi2= (double *) malloc ( ndata * sizeof(double) );
double *I3U= (double *) malloc ( ndata * sizeof(double) );
double *I3V= (double *) malloc ( ndata * sizeof(double) );
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) private(ii,tdelta)
for (ii=0; ii < ndata; ii++){
tdelta= *(delta+ii*delta_stride);
*(coshux+ii)= cosh(*(ux+ii));
*(sinhux+ii)= sinh(*(ux+ii));
*(cosvx+ii)= cos(*(vx+ii));
*(sinvx+ii)= sin(*(vx+ii));
*(pux+ii)= tdelta * (*(vR+ii) * *(coshux+ii) * *(sinvx+ii)
+ *(vz+ii) * *(sinhux+ii) * *(cosvx+ii));
*(pvx+ii)= tdelta * (*(vR+ii) * *(sinhux+ii) * *(cosvx+ii)
- *(vz+ii) * *(coshux+ii) * *(sinvx+ii));
*(sinh2u0+ii)= sinh(*(u0+ii)) * sinh(*(u0+ii));
*(cosh2u0+ii)= cosh(*(u0+ii)) * cosh(*(u0+ii));
*(v0+ii)= 0.5 * M_PI; //*(vx+ii);
*(sin2v0+ii)= sin(*(v0+ii)) * sin(*(v0+ii));
*(potu0v0+ii)= evaluatePotentialsUV(*(u0+ii),*(v0+ii),tdelta,
npot,actionAngleArgs);
*(I3U+ii)= *(E+ii) * *(sinhux+ii) * *(sinhux+ii)
- 0.5 * *(pux+ii) * *(pux+ii) / tdelta / tdelta
- 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinhux+ii) / *(sinhux+ii)
- ( *(sinhux+ii) * *(sinhux+ii) + *(sin2v0+ii))
*evaluatePotentialsUV(*(ux+ii),*(v0+ii),tdelta,
npot,actionAngleArgs)
+ ( *(sinh2u0+ii) + *(sin2v0+ii) )* *(potu0v0+ii);
*(potupi2+ii)= evaluatePotentialsUV(*(u0+ii),0.5 * M_PI,tdelta,
npot,actionAngleArgs);
*(I3V+ii)= - *(E+ii) * *(sinvx+ii) * *(sinvx+ii)
+ 0.5 * *(pvx+ii) * *(pvx+ii) / tdelta / tdelta
+ 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinvx+ii) / *(sinvx+ii)
- *(cosh2u0+ii) * *(potupi2+ii)
+ ( *(sinh2u0+ii) + *(sinvx+ii) * *(sinvx+ii))
* evaluatePotentialsUV(*(u0+ii),*(vx+ii),tdelta,
npot,actionAngleArgs);
}
//Calculate 'peri' and 'apo'centers
double *umin= (double *) malloc ( ndata * sizeof(double) );
double *umax= (double *) malloc ( ndata * sizeof(double) );
double *vmin= (double *) malloc ( ndata * sizeof(double) );
calcUminUmax(ndata,umin,umax,ux,pux,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,
sin2v0,potu0v0,npot,actionAngleArgs);
calcVmin(ndata,vmin,vx,pvx,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs);
//Calculate the actions
calcJRStaeckel(ndata,jr,umin,umax,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,order);
calcJzStaeckel(ndata,jz,vmin,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,
potupi2,npot,actionAngleArgs,order);
//Free
free_potentialArgs(npot,actionAngleArgs);
free(actionAngleArgs);
free(E);
free(Lz);
free(ux);
free(vx);
free(coshux);
free(sinhux);
free(sinvx);
free(cosvx);
free(pux);
free(pvx);
free(sinh2u0);
free(cosh2u0);
free(v0);
free(sin2v0);
free(potu0v0);
free(potupi2);
free(I3U);
free(I3V);
free(umin);
free(umax);
free(vmin);
}
void calcJRStaeckel(int ndata,
double * jr,
double * umin,
double * umax,
double * E,
double * Lz,
double * I3U,
int ndelta,
double * delta,
double * u0,
double * sinh2u0,
double * v0,
double * sin2v0,
double * potu0v0,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * JRInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct JRStaeckelArg * params= (struct JRStaeckelArg *) malloc ( nthreads * sizeof (struct JRStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii) \
shared(jr,umin,umax,JRInt,params,T,delta,E,Lz,I3U,u0,sinh2u0,v0,sin2v0,potu0v0)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(umin+ii) == -9999.99 || *(umax+ii) == -9999.99 ){
*(jr+ii)= 9999.99;
continue;
}
if ( (*(umax+ii) - *(umin+ii)) / *(umax+ii) < 0.000001 ){//circular
*(jr+ii) = 0.;
continue;
}
//Setup function
(params+tid)->delta= *(delta+ii*delta_stride);
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(params+tid)->I3U= *(I3U+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->v0= *(v0+ii);
(params+tid)->sin2v0= *(sin2v0+ii);
(params+tid)->potu0v0= *(potu0v0+ii);
(JRInt+tid)->function = &JRStaeckelIntegrand;
(JRInt+tid)->params = params+tid;
//Integrate
*(jr+ii)= gsl_integration_glfixed (JRInt+tid,*(umin+ii),*(umax+ii),T)
* sqrt(2.) * *(delta+ii*delta_stride) / M_PI;
}
free(JRInt);
free(params);
gsl_integration_glfixed_table_free ( T );
}
void calcJzStaeckel(int ndata,
double * jz,
double * vmin,
double * E,
double * Lz,
double * I3V,
int ndelta,
double * delta,
double * u0,
double * cosh2u0,
double * sinh2u0,
double * potupi2,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * JzInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct JzStaeckelArg * params= (struct JzStaeckelArg *) malloc ( nthreads * sizeof (struct JzStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii) \
shared(jz,vmin,JzInt,params,T,delta,E,Lz,I3V,u0,cosh2u0,sinh2u0,potupi2)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(vmin+ii) == -9999.99 ){
*(jz+ii)= 9999.99;
continue;
}
if ( (0.5 * M_PI - *(vmin+ii)) / M_PI * 2. < 0.000001 ){//circular
*(jz+ii) = 0.;
continue;
}
//Setup function
(params+tid)->delta= *(delta+ii*delta_stride);
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(params+tid)->I3V= *(I3V+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->cosh2u0= *(cosh2u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->potupi2= *(potupi2+ii);
(JzInt+tid)->function = &JzStaeckelIntegrand;
(JzInt+tid)->params = params+tid;
//Integrate
*(jz+ii)= gsl_integration_glfixed (JzInt+tid,*(vmin+ii),M_PI/2.,T)
* 2 * sqrt(2.) * *(delta+ii*delta_stride) / M_PI;
}
free(JzInt);
free(params);
gsl_integration_glfixed_table_free ( T );
}
void actionAngleStaeckel_actionsFreqs(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *u0,
int npot,
int * pot_type,
double * pot_args,
int ndelta,
double * delta,
int order,
double *jr,
double *jz,
double *Omegar,
double *Omegaphi,
double *Omegaz,
int * err){
int ii;
double tdelta;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_leapFuncArgs_Full(npot,actionAngleArgs,&pot_type,&pot_args);
//E,Lz
double *E= (double *) malloc ( ndata * sizeof(double) );
double *Lz= (double *) malloc ( ndata * sizeof(double) );
calcEL(ndata,R,vR,vT,z,vz,E,Lz,npot,actionAngleArgs);
//Calculate all necessary parameters
double *ux= (double *) malloc ( ndata * sizeof(double) );
double *vx= (double *) malloc ( ndata * sizeof(double) );
Rz_to_uv_vec(ndata,R,z,ux,vx,ndelta,delta);
double *coshux= (double *) malloc ( ndata * sizeof(double) );
double *sinhux= (double *) malloc ( ndata * sizeof(double) );
double *sinvx= (double *) malloc ( ndata * sizeof(double) );
double *cosvx= (double *) malloc ( ndata * sizeof(double) );
double *pux= (double *) malloc ( ndata * sizeof(double) );
double *pvx= (double *) malloc ( ndata * sizeof(double) );
double *sinh2u0= (double *) malloc ( ndata * sizeof(double) );
double *cosh2u0= (double *) malloc ( ndata * sizeof(double) );
double *v0= (double *) malloc ( ndata * sizeof(double) );
double *sin2v0= (double *) malloc ( ndata * sizeof(double) );
double *potu0v0= (double *) malloc ( ndata * sizeof(double) );
double *potupi2= (double *) malloc ( ndata * sizeof(double) );
double *I3U= (double *) malloc ( ndata * sizeof(double) );
double *I3V= (double *) malloc ( ndata * sizeof(double) );
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) private(ii,tdelta)
for (ii=0; ii < ndata; ii++){
tdelta= *(delta+ii*delta_stride);
*(coshux+ii)= cosh(*(ux+ii));
*(sinhux+ii)= sinh(*(ux+ii));
*(cosvx+ii)= cos(*(vx+ii));
*(sinvx+ii)= sin(*(vx+ii));
*(pux+ii)= tdelta * (*(vR+ii) * *(coshux+ii) * *(sinvx+ii)
+ *(vz+ii) * *(sinhux+ii) * *(cosvx+ii));
*(pvx+ii)= tdelta * (*(vR+ii) * *(sinhux+ii) * *(cosvx+ii)
- *(vz+ii) * *(coshux+ii) * *(sinvx+ii));
*(sinh2u0+ii)= sinh(*(u0+ii)) * sinh(*(u0+ii));
*(cosh2u0+ii)= cosh(*(u0+ii)) * cosh(*(u0+ii));
*(v0+ii)= 0.5 * M_PI; //*(vx+ii);
*(sin2v0+ii)= sin(*(v0+ii)) * sin(*(v0+ii));
*(potu0v0+ii)= evaluatePotentialsUV(*(u0+ii),*(v0+ii),tdelta,
npot,actionAngleArgs);
*(I3U+ii)= *(E+ii) * *(sinhux+ii) * *(sinhux+ii)
- 0.5 * *(pux+ii) * *(pux+ii) / tdelta / tdelta
- 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinhux+ii) / *(sinhux+ii)
- ( *(sinhux+ii) * *(sinhux+ii) + *(sin2v0+ii))
*evaluatePotentialsUV(*(ux+ii),*(v0+ii),tdelta,
npot,actionAngleArgs)
+ ( *(sinh2u0+ii) + *(sin2v0+ii) )* *(potu0v0+ii);
*(potupi2+ii)= evaluatePotentialsUV(*(u0+ii),0.5 * M_PI,tdelta,
npot,actionAngleArgs);
*(I3V+ii)= - *(E+ii) * *(sinvx+ii) * *(sinvx+ii)
+ 0.5 * *(pvx+ii) * *(pvx+ii) / tdelta / tdelta
+ 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinvx+ii) / *(sinvx+ii)
- *(cosh2u0+ii) * *(potupi2+ii)
+ ( *(sinh2u0+ii) + *(sinvx+ii) * *(sinvx+ii))
* evaluatePotentialsUV(*(u0+ii),*(vx+ii),tdelta,
npot,actionAngleArgs);
}
//Calculate 'peri' and 'apo'centers
double *umin= (double *) malloc ( ndata * sizeof(double) );
double *umax= (double *) malloc ( ndata * sizeof(double) );
double *vmin= (double *) malloc ( ndata * sizeof(double) );
calcUminUmax(ndata,umin,umax,ux,pux,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,
sin2v0,potu0v0,npot,actionAngleArgs);
calcVmin(ndata,vmin,vx,pvx,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs);
//Calculate the actions
calcJRStaeckel(ndata,jr,umin,umax,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,order);
calcJzStaeckel(ndata,jz,vmin,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,
potupi2,npot,actionAngleArgs,order);
//Calculate the derivatives of the actions wrt the integrals of motion
double *dJRdE= (double *) malloc ( ndata * sizeof(double) );
double *dJRdLz= (double *) malloc ( ndata * sizeof(double) );
double *dJRdI3= (double *) malloc ( ndata * sizeof(double) );
double *dJzdE= (double *) malloc ( ndata * sizeof(double) );
double *dJzdLz= (double *) malloc ( ndata * sizeof(double) );
double *dJzdI3= (double *) malloc ( ndata * sizeof(double) );
double *detA= (double *) malloc ( ndata * sizeof(double) );
calcdJRStaeckel(ndata,dJRdE,dJRdLz,dJRdI3,
umin,umax,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,order);
calcdJzStaeckel(ndata,dJzdE,dJzdLz,dJzdI3,
vmin,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,
potupi2,npot,actionAngleArgs,order);
calcFreqsFromDerivsStaeckel(ndata,Omegar,Omegaphi,Omegaz,detA,
dJRdE,dJRdLz,dJRdI3,
dJzdE,dJzdLz,dJzdI3);
//Free
free_potentialArgs(npot,actionAngleArgs);
free(actionAngleArgs);
free(E);
free(Lz);
free(ux);
free(vx);
free(coshux);
free(sinhux);
free(sinvx);
free(cosvx);
free(pux);
free(pvx);
free(sinh2u0);
free(cosh2u0);
free(v0);
free(sin2v0);
free(potu0v0);
free(potupi2);
free(I3U);
free(I3V);
free(umin);
free(umax);
free(vmin);
free(dJRdE);
free(dJRdLz);
free(dJRdI3);
free(dJzdE);
free(detA);
free(dJzdLz);
free(dJzdI3);
}
void actionAngleStaeckel_actionsFreqsAngles(int ndata,
double *R,
double *vR,
double *vT,
double *z,
double *vz,
double *u0,
int npot,
int * pot_type,
double * pot_args,
int ndelta,
double * delta,
int order,
double *jr,
double *jz,
double *Omegar,
double *Omegaphi,
double *Omegaz,
double *Angler,
double *Anglephi,
double *Anglez,
int * err){
int ii;
double tdelta;
//Set up the potentials
struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );
parse_leapFuncArgs_Full(npot,actionAngleArgs,&pot_type,&pot_args);
//E,Lz
double *E= (double *) malloc ( ndata * sizeof(double) );
double *Lz= (double *) malloc ( ndata * sizeof(double) );
calcEL(ndata,R,vR,vT,z,vz,E,Lz,npot,actionAngleArgs);
//Calculate all necessary parameters
double *ux= (double *) malloc ( ndata * sizeof(double) );
double *vx= (double *) malloc ( ndata * sizeof(double) );
Rz_to_uv_vec(ndata,R,z,ux,vx,ndelta,delta);
double *coshux= (double *) malloc ( ndata * sizeof(double) );
double *sinhux= (double *) malloc ( ndata * sizeof(double) );
double *sinvx= (double *) malloc ( ndata * sizeof(double) );
double *cosvx= (double *) malloc ( ndata * sizeof(double) );
double *pux= (double *) malloc ( ndata * sizeof(double) );
double *pvx= (double *) malloc ( ndata * sizeof(double) );
double *sinh2u0= (double *) malloc ( ndata * sizeof(double) );
double *cosh2u0= (double *) malloc ( ndata * sizeof(double) );
double *v0= (double *) malloc ( ndata * sizeof(double) );
double *sin2v0= (double *) malloc ( ndata * sizeof(double) );
double *potu0v0= (double *) malloc ( ndata * sizeof(double) );
double *potupi2= (double *) malloc ( ndata * sizeof(double) );
double *I3U= (double *) malloc ( ndata * sizeof(double) );
double *I3V= (double *) malloc ( ndata * sizeof(double) );
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) private(ii,tdelta)
for (ii=0; ii < ndata; ii++){
tdelta= *(delta+ii*delta_stride);
*(coshux+ii)= cosh(*(ux+ii));
*(sinhux+ii)= sinh(*(ux+ii));
*(cosvx+ii)= cos(*(vx+ii));
*(sinvx+ii)= sin(*(vx+ii));
*(pux+ii)= tdelta * (*(vR+ii) * *(coshux+ii) * *(sinvx+ii)
+ *(vz+ii) * *(sinhux+ii) * *(cosvx+ii));
*(pvx+ii)= tdelta * (*(vR+ii) * *(sinhux+ii) * *(cosvx+ii)
- *(vz+ii) * *(coshux+ii) * *(sinvx+ii));
*(sinh2u0+ii)= sinh(*(u0+ii)) * sinh(*(u0+ii));
*(cosh2u0+ii)= cosh(*(u0+ii)) * cosh(*(u0+ii));
*(v0+ii)= 0.5 * M_PI; //*(vx+ii);
*(sin2v0+ii)= sin(*(v0+ii)) * sin(*(v0+ii));
*(potu0v0+ii)= evaluatePotentialsUV(*(u0+ii),*(v0+ii),tdelta,
npot,actionAngleArgs);
*(I3U+ii)= *(E+ii) * *(sinhux+ii) * *(sinhux+ii)
- 0.5 * *(pux+ii) * *(pux+ii) / tdelta / tdelta
- 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinhux+ii) / *(sinhux+ii)
- ( *(sinhux+ii) * *(sinhux+ii) + *(sin2v0+ii))
*evaluatePotentialsUV(*(ux+ii),*(v0+ii),tdelta,
npot,actionAngleArgs)
+ ( *(sinh2u0+ii) + *(sin2v0+ii) )* *(potu0v0+ii);
*(potupi2+ii)= evaluatePotentialsUV(*(u0+ii),0.5 * M_PI,tdelta,
npot,actionAngleArgs);
*(I3V+ii)= - *(E+ii) * *(sinvx+ii) * *(sinvx+ii)
+ 0.5 * *(pvx+ii) * *(pvx+ii) / tdelta / tdelta
+ 0.5 * *(Lz+ii) * *(Lz+ii) / tdelta / tdelta / *(sinvx+ii) / *(sinvx+ii)
- *(cosh2u0+ii) * *(potupi2+ii)
+ ( *(sinh2u0+ii) + *(sinvx+ii) * *(sinvx+ii))
* evaluatePotentialsUV(*(u0+ii),*(vx+ii),tdelta,
npot,actionAngleArgs);
}
//Calculate 'peri' and 'apo'centers
double *umin= (double *) malloc ( ndata * sizeof(double) );
double *umax= (double *) malloc ( ndata * sizeof(double) );
double *vmin= (double *) malloc ( ndata * sizeof(double) );
calcUminUmax(ndata,umin,umax,ux,pux,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,
sin2v0,potu0v0,npot,actionAngleArgs);
calcVmin(ndata,vmin,vx,pvx,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,potupi2,
npot,actionAngleArgs);
//Calculate the actions
calcJRStaeckel(ndata,jr,umin,umax,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,order);
calcJzStaeckel(ndata,jz,vmin,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,
potupi2,npot,actionAngleArgs,order);
//Calculate the derivatives of the actions wrt the integrals of motion
double *dJRdE= (double *) malloc ( ndata * sizeof(double) );
double *dJRdLz= (double *) malloc ( ndata * sizeof(double) );
double *dJRdI3= (double *) malloc ( ndata * sizeof(double) );
double *dJzdE= (double *) malloc ( ndata * sizeof(double) );
double *dJzdLz= (double *) malloc ( ndata * sizeof(double) );
double *dJzdI3= (double *) malloc ( ndata * sizeof(double) );
double *detA= (double *) malloc ( ndata * sizeof(double) );
calcdJRStaeckel(ndata,dJRdE,dJRdLz,dJRdI3,
umin,umax,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,npot,actionAngleArgs,order);
calcdJzStaeckel(ndata,dJzdE,dJzdLz,dJzdI3,
vmin,E,Lz,I3V,ndelta,delta,u0,cosh2u0,sinh2u0,
potupi2,npot,actionAngleArgs,order);
calcFreqsFromDerivsStaeckel(ndata,Omegar,Omegaphi,Omegaz,detA,
dJRdE,dJRdLz,dJRdI3,
dJzdE,dJzdLz,dJzdI3);
double *dI3dJR= (double *) malloc ( ndata * sizeof(double) );
double *dI3dJz= (double *) malloc ( ndata * sizeof(double) );
double *dI3dLz= (double *) malloc ( ndata * sizeof(double) );
calcdI3dJFromDerivsStaeckel(ndata,dI3dJR,dI3dJz,dI3dLz,detA,
dJRdE,dJzdE,dJRdLz,dJzdLz);
calcAnglesStaeckel(ndata,Angler,Anglephi,Anglez,
Omegar,Omegaphi,Omegaz,dI3dJR,dI3dJz,dI3dLz,
dJRdE,dJRdLz,dJRdI3,
dJzdE,dJzdLz,dJzdI3,
ux,vx,pux,pvx,
umin,umax,E,Lz,I3U,ndelta,delta,u0,sinh2u0,v0,sin2v0,
potu0v0,
vmin,I3V,cosh2u0,potupi2,
npot,actionAngleArgs,order);
//Free
free_potentialArgs(npot,actionAngleArgs);
free(actionAngleArgs);
free(E);
free(Lz);
free(ux);
free(vx);
free(coshux);
free(sinhux);
free(sinvx);
free(cosvx);
free(pux);
free(pvx);
free(sinh2u0);
free(cosh2u0);
free(v0);
free(sin2v0);
free(potu0v0);
free(potupi2);
free(I3U);
free(I3V);
free(umin);
free(umax);
free(vmin);
free(dJRdE);
free(dJRdLz);
free(dJRdI3);
free(dJzdE);
free(dJzdLz);
free(dJzdI3);
free(detA);
free(dI3dJR);
free(dI3dJz);
free(dI3dLz);
}
void calcFreqsFromDerivsStaeckel(int ndata,
double * Omegar,
double * Omegaphi,
double * Omegaz,
double * detA,
double * djrdE,
double * djrdLz,
double * djrdI3,
double * djzdE,
double * djzdLz,
double * djzdI3){
int ii;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(ii) \
shared(Omegar,Omegaphi,Omegaz,djrdE,djrdLz,djrdI3,djzdE,djzdLz,djzdI3,detA)
for (ii=0; ii < ndata; ii++){
if ( *(djrdE+ii) == 9999.99 || *(djzdE+ii) == 9999.99 ) {
*(Omegar+ii)= 9999.99;
*(Omegaz+ii)= 9999.99;
*(Omegaphi+ii)= 9999.99;
} else {
//First calculate the determinant of the relevant matrix
*(detA+ii)= *(djrdE+ii) * *(djzdI3+ii) - *(djzdE+ii) * *(djrdI3+ii);
//Then calculate the frequencies
*(Omegar+ii)= *(djzdI3+ii) / *(detA+ii);
*(Omegaz+ii)= - *(djrdI3+ii) / *(detA+ii);
*(Omegaphi+ii)= ( *(djrdI3+ii) * *(djzdLz+ii) - *(djzdI3+ii) * *(djrdLz+ii)) / *(detA+ii);
}
}
}
void calcdI3dJFromDerivsStaeckel(int ndata,
double * dI3dJR,
double * dI3dJz,
double * dI3dLz,
double * detA,
double * djrdE,
double * djzdE,
double * djrdLz,
double * djzdLz){
int ii;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(ii) \
shared(djrdE,djzdE,djrdLz,djzdLz,dI3dJR,dI3dJz,dI3dLz,detA)
for (ii=0; ii < ndata; ii++){
*(dI3dJR+ii)= - *(djzdE+ii) / *(detA+ii);
*(dI3dJz+ii)= *(djrdE+ii) / *(detA+ii);
*(dI3dLz+ii)= -( *(djrdE+ii) * *(djzdLz+ii) - *(djzdE+ii) * *(djrdLz+ii) ) / *(detA+ii);
}
}
void calcdJRStaeckel(int ndata,
double * djrdE,
double * djrdLz,
double * djrdI3,
double * umin,
double * umax,
double * E,
double * Lz,
double * I3U,
int ndelta,
double * delta,
double * u0,
double * sinh2u0,
double * v0,
double * sin2v0,
double * potu0v0,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
double mid;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * dJRInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) malloc ( nthreads * sizeof (struct dJRStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,mid) \
shared(djrdE,djrdLz,djrdI3,umin,umax,dJRInt,params,T,delta,E,Lz,I3U,u0,sinh2u0,v0,sin2v0,potu0v0)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(umin+ii) == -9999.99 || *(umax+ii) == -9999.99 ){
*(djrdE+ii)= 9999.99;
*(djrdLz+ii)= 9999.99;
*(djrdI3+ii)= 9999.99;
continue;
}
if ( (*(umax+ii) - *(umin+ii)) / *(umax+ii) < 0.000001 ){//circular
*(djrdE+ii) = 0.;
*(djrdLz+ii) = 0.;
*(djrdI3+ii) = 0.;
continue;
}
//Setup function
(params+tid)->delta= *(delta+ii*delta_stride);
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(params+tid)->I3U= *(I3U+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->v0= *(v0+ii);
(params+tid)->sin2v0= *(sin2v0+ii);
(params+tid)->potu0v0= *(potu0v0+ii);
(params+tid)->umin= *(umin+ii);
(params+tid)->umax= *(umax+ii);
(dJRInt+tid)->function = &dJRdELowStaeckelIntegrand;
(dJRInt+tid)->params = params+tid;
mid= sqrt( 0.5 * ( *(umax+ii) - *(umin+ii) ) );
//Integrate to get djrdE
*(djrdE+ii)= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
(dJRInt+tid)->function = &dJRdEHighStaeckelIntegrand;
*(djrdE+ii)+= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
*(djrdE+ii)*= *(delta+ii*delta_stride) / M_PI / sqrt(2.);
//then calculate djrdLz
(dJRInt+tid)->function = &dJRdLzLowStaeckelIntegrand;
*(djrdLz+ii)= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
(dJRInt+tid)->function = &dJRdLzHighStaeckelIntegrand;
*(djrdLz+ii)+= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
*(djrdLz+ii)*= - *(Lz+ii) / M_PI / sqrt(2.) / *(delta+ii*delta_stride);
//then calculate djrdI3
(dJRInt+tid)->function = &dJRdI3LowStaeckelIntegrand;
*(djrdI3+ii)= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
(dJRInt+tid)->function = &dJRdI3HighStaeckelIntegrand;
*(djrdI3+ii)+= gsl_integration_glfixed (dJRInt+tid,0.,mid,T);
*(djrdI3+ii)*= - *(delta+ii*delta_stride) / M_PI / sqrt(2.);
}
free(dJRInt);
free(params);
gsl_integration_glfixed_table_free ( T );
}
void calcdJzStaeckel(int ndata,
double * djzdE,
double * djzdLz,
double * djzdI3,
double * vmin,
double * E,
double * Lz,
double * I3V,
int ndelta,
double * delta,
double * u0,
double * cosh2u0,
double * sinh2u0,
double * potupi2,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
double mid;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * dJzInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) malloc ( nthreads * sizeof (struct dJzStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,mid) \
shared(djzdE,djzdLz,djzdI3,vmin,dJzInt,params,T,delta,E,Lz,I3V,u0,cosh2u0,sinh2u0,potupi2)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(vmin+ii) == -9999.99 ){
*(djzdE+ii)= 9999.99;
*(djzdLz+ii)= 9999.99;
*(djzdI3+ii)= 9999.99;
continue;
}
if ( (0.5 * M_PI - *(vmin+ii)) / M_PI * 2. < 0.000001 ){//circular
*(djzdE+ii) = 0.;
*(djzdLz+ii) = 0.;
*(djzdI3+ii) = 0.;
continue;
}
//Setup function
(params+tid)->delta= *(delta+ii*delta_stride);
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(params+tid)->I3V= *(I3V+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->cosh2u0= *(cosh2u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->potupi2= *(potupi2+ii);
(params+tid)->vmin= *(vmin+ii);
//First calculate dJzdE
(dJzInt+tid)->function = &dJzdELowStaeckelIntegrand;
(dJzInt+tid)->params = params+tid;
mid= sqrt( 0.5 * (M_PI/2. - *(vmin+ii) ) );
//BOVY: pv does not vanish at pi/2, so no need to break up the integral
//Integrate
*(djzdE+ii)= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
(dJzInt+tid)->function = &dJzdEHighStaeckelIntegrand;
*(djzdE+ii)+= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
*(djzdE+ii)*= sqrt(2.) * *(delta+ii*delta_stride) / M_PI;
//Then calculate dJzdLz
(dJzInt+tid)->function = &dJzdLzLowStaeckelIntegrand;
//Integrate
*(djzdLz+ii)= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
(dJzInt+tid)->function = &dJzdLzHighStaeckelIntegrand;
*(djzdLz+ii)+= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
*(djzdLz+ii)*= - *(Lz+ii) * sqrt(2.) / M_PI / *(delta+ii*delta_stride);
//Then calculate dJzdI3
(dJzInt+tid)->function = &dJzdI3LowStaeckelIntegrand;
//Integrate
*(djzdI3+ii)= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
(dJzInt+tid)->function = &dJzdI3HighStaeckelIntegrand;
*(djzdI3+ii)+= gsl_integration_glfixed (dJzInt+tid,0.,mid,T);
*(djzdI3+ii)*= sqrt(2.) * *(delta+ii*delta_stride) / M_PI;
}
free(dJzInt);
free(params);
gsl_integration_glfixed_table_free ( T );
}
void calcAnglesStaeckel(int ndata,
double * Angler,
double * Anglephi,
double * Anglez,
double * Omegar,
double * Omegaphi,
double * Omegaz,
double * dI3dJR,
double * dI3dJz,
double * dI3dLz,
double * dJRdE,
double * dJRdLz,
double * dJRdI3,
double * dJzdE,
double * dJzdLz,
double * dJzdI3,
double * ux,
double * vx,
double * pux,
double * pvx,
double * umin,
double * umax,
double * E,
double * Lz,
double * I3U,
int ndelta,
double * delta,
double * u0,
double * sinh2u0,
double * v0,
double * sin2v0,
double * potu0v0,
double * vmin,
double * I3V,
double * cosh2u0,
double * potupi2,
int nargs,
struct potentialArg * actionAngleArgs,
int order){
int ii, tid, nthreads;
double Or1, Or2, I3r1, I3r2,phitmp;
double mid, midpoint;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * AngleuInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
gsl_function * AnglevInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct dJRStaeckelArg * paramsu= (struct dJRStaeckelArg *) malloc ( nthreads * sizeof (struct dJRStaeckelArg) );
struct dJzStaeckelArg * paramsv= (struct dJzStaeckelArg *) malloc ( nthreads * sizeof (struct dJzStaeckelArg) );
for (tid=0; tid < nthreads; tid++){
(paramsu+tid)->nargs= nargs;
(paramsu+tid)->actionAngleArgs= actionAngleArgs;
(paramsv+tid)->nargs= nargs;
(paramsv+tid)->actionAngleArgs= actionAngleArgs;
}
//Setup integrator
gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,mid,midpoint,Or1,Or2,I3r1,I3r2,phitmp) \
shared(Angler,Anglephi,Anglez,Omegar,Omegaz,dI3dJR,dI3dJz,umin,umax,AngleuInt,AnglevInt,paramsu,paramsv,T,delta,E,Lz,I3U,u0,sinh2u0,v0,sin2v0,potu0v0,vmin,I3V,cosh2u0,potupi2)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
if ( *(umin+ii) == -9999.99 || *(umax+ii) == -9999.99 ){
*(Angler+ii)= 9999.99;
*(Anglephi+ii)= 9999.99;
*(Anglez+ii)= 9999.99;
continue;
}
if ( (*(umax+ii) - *(umin+ii)) / *(umax+ii) < 0.000001 ){//circular
*(Angler+ii) = 0.;
*(Anglephi+ii) = 0.;
*(Anglez+ii) = 0.;
continue;
}
//Setup u function
(paramsu+tid)->delta= *(delta+ii*delta_stride);
(paramsu+tid)->E= *(E+ii);
(paramsu+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(paramsu+tid)->I3U= *(I3U+ii);
(paramsu+tid)->u0= *(u0+ii);
(paramsu+tid)->sinh2u0= *(sinh2u0+ii);
(paramsu+tid)->v0= *(v0+ii);
(paramsu+tid)->sin2v0= *(sin2v0+ii);
(paramsu+tid)->potu0v0= *(potu0v0+ii);
(paramsu+tid)->umin= *(umin+ii);
(paramsu+tid)->umax= *(umax+ii);
(AngleuInt+tid)->params = paramsu+tid;
midpoint= *(umin+ii)+ 0.5 * ( *(umax+ii) - *(umin+ii) );
if ( *(pux+ii) > 0. ) {
if ( *(ux+ii) > midpoint ) {
mid= sqrt( ( *(umax+ii) - *(ux+ii) ) );
(AngleuInt+tid)->function = &dJRdEHighStaeckelIntegrand;
Or1= gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
(AngleuInt+tid)->function = &dJRdI3HighStaeckelIntegrand;
I3r1= -gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
(AngleuInt+tid)->function = &dJRdLzHighStaeckelIntegrand;
*(Anglephi+ii)= M_PI * *(dJRdLz+ii) + *(Lz+ii) * gsl_integration_glfixed (AngleuInt+tid,0.,mid,T) / *(delta+ii*delta_stride) / sqrt(2.);
Or1*= *(delta+ii*delta_stride) / sqrt(2.);
I3r1*= *(delta+ii*delta_stride) / sqrt(2.);
Or1= M_PI * *(dJRdE+ii) - Or1;
I3r1= M_PI * *(dJRdI3+ii) - I3r1;
}
else {
mid= sqrt( ( *(ux+ii) - *(umin+ii) ) );
(AngleuInt+tid)->function = &dJRdELowStaeckelIntegrand;
Or1= gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
(AngleuInt+tid)->function = &dJRdI3LowStaeckelIntegrand;
I3r1= -gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
(AngleuInt+tid)->function = &dJRdLzLowStaeckelIntegrand;
*(Anglephi+ii)= - *(Lz+ii) * gsl_integration_glfixed (AngleuInt+tid,0.,mid,T) / *(delta+ii*delta_stride) / sqrt(2.);
Or1*= *(delta+ii*delta_stride) / sqrt(2.);
I3r1*= *(delta+ii*delta_stride) / sqrt(2.);
}
}
else {
if ( *(ux+ii) > midpoint ) {
mid= sqrt( ( *(umax+ii) - *(ux+ii) ) );
(AngleuInt+tid)->function = &dJRdEHighStaeckelIntegrand;
Or1= gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
Or1*= *(delta+ii*delta_stride) / sqrt(2.);
Or1= M_PI * *(dJRdE+ii) + Or1;
(AngleuInt+tid)->function = &dJRdI3HighStaeckelIntegrand;
I3r1= -gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
I3r1*= *(delta+ii*delta_stride) / sqrt(2.);
I3r1= M_PI * *(dJRdI3+ii) + I3r1;
(AngleuInt+tid)->function = &dJRdLzHighStaeckelIntegrand;
*(Anglephi+ii)= M_PI * *(dJRdLz+ii) - *(Lz+ii) * gsl_integration_glfixed (AngleuInt+tid,0.,mid,T) / *(delta+ii*delta_stride) / sqrt(2.);
}
else {
mid= sqrt( ( *(ux+ii) - *(umin+ii) ) );
(AngleuInt+tid)->function = &dJRdELowStaeckelIntegrand;
Or1= gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
Or1*= *(delta+ii*delta_stride) / sqrt(2.);
Or1= 2. * M_PI * *(dJRdE+ii) - Or1;
(AngleuInt+tid)->function = &dJRdI3LowStaeckelIntegrand;
I3r1= -gsl_integration_glfixed (AngleuInt+tid,0.,mid,T);
I3r1*= *(delta+ii*delta_stride) / sqrt(2.);
I3r1= 2. * M_PI * *(dJRdI3+ii) - I3r1;
(AngleuInt+tid)->function = &dJRdLzLowStaeckelIntegrand;
*(Anglephi+ii)= 2. * M_PI * *(dJRdLz+ii) + *(Lz+ii) * gsl_integration_glfixed (AngleuInt+tid,0.,mid,T) / *(delta+ii*delta_stride) / sqrt(2.);
}
}
//Setup v function
(paramsv+tid)->delta= *(delta+ii*delta_stride);
(paramsv+tid)->E= *(E+ii);
(paramsv+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(paramsv+tid)->I3V= *(I3V+ii);
(paramsv+tid)->u0= *(u0+ii);
(paramsv+tid)->cosh2u0= *(cosh2u0+ii);
(paramsv+tid)->sinh2u0= *(sinh2u0+ii);
(paramsv+tid)->potupi2= *(potupi2+ii);
(paramsv+tid)->vmin= *(vmin+ii);
(AnglevInt+tid)->params = paramsv+tid;
midpoint= *(vmin+ii)+ 0.5 * ( 0.5 * M_PI - *(vmin+ii) );
if ( *(pvx+ii) > 0. ) {
if ( *(vx+ii) < midpoint || *(vx+ii) > (M_PI - midpoint) ) {
mid = ( *(vx+ii) > 0.5 * M_PI ) ? sqrt( (M_PI - *(vx+ii) - *(vmin+ii))): sqrt( *(vx+ii) - *(vmin+ii));
(AnglevInt+tid)->function = &dJzdELowStaeckelIntegrand;
Or2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
Or2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdI3LowStaeckelIntegrand;
I3r2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
I3r2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdLzLowStaeckelIntegrand;
phitmp= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
phitmp*= - *(Lz+ii) / *(delta+ii*delta_stride) / sqrt(2.);
if ( *(vx+ii) > 0.5 * M_PI ) {
Or2= M_PI * *(dJzdE+ii) - Or2;
I3r2= M_PI * *(dJzdI3+ii) - I3r2;
phitmp= M_PI * *(dJzdLz+ii) - phitmp;
}
}
else {
mid= sqrt( fabs ( 0.5 * M_PI - *(vx+ii) ) );
(AnglevInt+tid)->function = &dJzdEHighStaeckelIntegrand;
Or2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
Or2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdI3HighStaeckelIntegrand;
I3r2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
I3r2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdLzHighStaeckelIntegrand;
phitmp= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
phitmp*= - *(Lz+ii) / *(delta+ii*delta_stride) / sqrt(2.);
if ( *(vx+ii) > 0.5 * M_PI ) {
Or2= 0.5 * M_PI * *(dJzdE+ii) + Or2;
I3r2= 0.5 * M_PI * *(dJzdI3+ii) + I3r2;
phitmp= 0.5 * M_PI * *(dJzdLz+ii) + phitmp;
}
else {
Or2= 0.5 * M_PI * *(dJzdE+ii) - Or2;
I3r2= 0.5 * M_PI * *(dJzdI3+ii) - I3r2;
phitmp= 0.5 * M_PI * *(dJzdLz+ii) - phitmp;
}
}
}
else {
if ( *(vx+ii) < midpoint || *(vx+ii) > (M_PI - midpoint)) {
mid = ( *(vx+ii) > 0.5 * M_PI ) ? sqrt( (M_PI - *(vx+ii) - *(vmin+ii))): sqrt( *(vx+ii) - *(vmin+ii));
(AnglevInt+tid)->function = &dJzdELowStaeckelIntegrand;
Or2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
Or2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdI3LowStaeckelIntegrand;
I3r2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
I3r2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdLzLowStaeckelIntegrand;
phitmp= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
phitmp*= - *(Lz+ii) / *(delta+ii*delta_stride) / sqrt(2.);
if ( *(vx+ii) < 0.5 * M_PI ) {
Or2= 2. * M_PI * *(dJzdE+ii) - Or2;
I3r2= 2. * M_PI * *(dJzdI3+ii) - I3r2;
phitmp= 2. * M_PI * *(dJzdLz+ii) - phitmp;
}
else {
Or2= M_PI * *(dJzdE+ii) + Or2;
I3r2= M_PI * *(dJzdI3+ii) + I3r2;
phitmp= M_PI * *(dJzdLz+ii) + phitmp;
}
}
else {
mid= sqrt( fabs ( 0.5 * M_PI - *(vx+ii) ) );
(AnglevInt+tid)->function = &dJzdEHighStaeckelIntegrand;
Or2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
Or2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdI3HighStaeckelIntegrand;
I3r2= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
I3r2*= *(delta+ii*delta_stride) / sqrt(2.);
(AnglevInt+tid)->function = &dJzdLzHighStaeckelIntegrand;
phitmp= gsl_integration_glfixed (AnglevInt+tid,0.,mid,T);
phitmp*= - *(Lz+ii) / *(delta+ii*delta_stride) / sqrt(2.);
if ( *(vx+ii) < 0.5 * M_PI ) {
Or2= 1.5 * M_PI * *(dJzdE+ii) + Or2;
I3r2= 1.5 * M_PI * *(dJzdI3+ii) + I3r2;
phitmp= 1.5 * M_PI * *(dJzdLz+ii) + phitmp;
}
else {
Or2= 1.5 * M_PI * *(dJzdE+ii) - Or2;
I3r2= 1.5 * M_PI * *(dJzdI3+ii) - I3r2;
phitmp= 1.5 * M_PI * *(dJzdLz+ii) - phitmp;
}
}
}
*(Angler+ii)= *(Omegar+ii) * ( Or1 + Or2 )
+ *(dI3dJR+ii) * ( I3r1 + I3r2 );
// In Binney (2012) Anglez starts at zmax/vmin and v_z < 0 / v_v > 0;
// Put this on the same system as Isochrone and Spherical angles +pi/2
*(Anglez+ii)= *(Omegaz+ii) * ( Or1 + Or2 )
+ *(dI3dJz+ii) * ( I3r1 + I3r2 ) + 0.5 * M_PI;
*(Anglephi+ii)+= phitmp;
*(Anglephi+ii)+= *(Omegaphi+ii) * ( Or1 + Or2 )
+ *(dI3dLz+ii) * ( I3r1 + I3r2 );
*(Angler+ii)= fmod(*(Angler+ii),2. * M_PI);
*(Anglez+ii)= fmod(*(Anglez+ii),2. * M_PI);
while ( *(Angler+ii) < 0. )
*(Angler+ii)+= 2. * M_PI;
while ( *(Anglez+ii) < 0. )
*(Anglez+ii)+= 2. * M_PI;
while ( *(Angler+ii) > 2. * M_PI )
*(Angler+ii)-= 2. * M_PI;
while ( *(Anglez+ii) > 2. * M_PI )
*(Anglez+ii)-= 2. * M_PI;
}
free(AngleuInt);
free(AnglevInt);
free(paramsu);
free(paramsv);
gsl_integration_glfixed_table_free ( T );
}
void calcUminUmax(int ndata,
double * umin,
double * umax,
double * ux,
double * pux,
double * E,
double * Lz,
double * I3U,
int ndelta,
double * delta,
double * u0,
double * sinh2u0,
double * v0,
double * sin2v0,
double * potu0v0,
int nargs,
struct potentialArg * actionAngleArgs){
int ii, tid, nthreads;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
double peps, meps;
gsl_function * JRRoot= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct JRStaeckelArg * params= (struct JRStaeckelArg *) malloc ( nthreads * sizeof (struct JRStaeckelArg) );
//Setup solver
int status;
int iter, max_iter = 100;
const gsl_root_fsolver_type *T;
struct pragmasolver *s= (struct pragmasolver *) malloc ( nthreads * sizeof (struct pragmasolver) );;
double u_lo, u_hi;
T = gsl_root_fsolver_brent;
for (tid=0; tid < nthreads; tid++){
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
(s+tid)->s= gsl_root_fsolver_alloc (T);
}
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
gsl_set_error_handler_off();
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,iter,status,u_lo,u_hi,meps,peps) \
shared(umin,umax,JRRoot,params,s,ux,delta,E,Lz,I3U,u0,sinh2u0,v0,sin2v0,potu0v0,max_iter)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
//Setup function
(params+tid)->delta= *(delta+ii*delta_stride);
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(params+tid)->I3U= *(I3U+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->v0= *(v0+ii);
(params+tid)->sin2v0= *(sin2v0+ii);
(params+tid)->potu0v0= *(potu0v0+ii);
(JRRoot+tid)->function = &JRStaeckelIntegrandSquared;
(JRRoot+tid)->params = params+tid;
//Find starting points for minimum
peps= GSL_FN_EVAL(JRRoot+tid,*(ux+ii)+0.000001);
meps= GSL_FN_EVAL(JRRoot+tid,*(ux+ii)-0.000001);
if ( fabs(GSL_FN_EVAL(JRRoot+tid,*(ux+ii))) < 0.0000001 && peps*meps < 0. ){ //we are at umin or umax
if ( peps < 0. && meps > 0. ) {//umax
*(umax+ii)= *(ux+ii);
u_lo= 0.9 * (*(ux+ii) - 0.000001);
u_hi= *(ux+ii) - 0.0000001;
while ( GSL_FN_EVAL(JRRoot+tid,u_lo) >= 0. && u_lo > 0.000000001){
u_hi= u_lo; //this makes sure that brent evaluates using previous
u_lo*= 0.9;
}
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(umin+ii) = 0.;//Assume zero if below 0.000000001
} else {
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
u_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
u_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(umin+ii) = gsl_root_fsolver_root ((s+tid)->s);
}
}
else {// JB: Should catch all: if ( peps > 0. && meps < 0. ){//umin
*(umin+ii)= *(ux+ii);
u_lo= *(ux+ii) + 0.000001;
u_hi= 1.1 * (*(ux+ii) + 0.000001);
while ( GSL_FN_EVAL(JRRoot+tid,u_hi) >= 0. && u_hi < asinh(37.5/ *(delta+ii*delta_stride))) {
u_lo= u_hi; //this makes sure that brent evaluates using previous
u_hi*= 1.1;
}
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
u_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
u_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(umax+ii) = gsl_root_fsolver_root ((s+tid)->s);
}
}
else if ( fabs(peps) < 0.00000001 && fabs(meps) < 0.00000001 && peps <= 0 && meps <= 0 ) {//circular
*(umin+ii) = *(ux+ii);
*(umax+ii) = *(ux+ii);
}
else {
u_lo= 0.9 * *(ux+ii);
u_hi= *(ux+ii);
while ( GSL_FN_EVAL(JRRoot+tid,u_lo) >= 0. && u_lo > 0.000000001){
u_hi= u_lo; //this makes sure that brent evaluates using previous
u_lo*= 0.9;
}
u_hi= (u_lo < 0.9 * *(ux+ii)) ? u_lo / 0.9 / 0.9: *(ux+ii);
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(umin+ii) = 0.;//Assume zero if below 0.000000001
} else {
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
u_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
u_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(umin+ii) = gsl_root_fsolver_root ((s+tid)->s);
}
//Find starting points for maximum
u_lo= *(ux+ii);
u_hi= 1.1 * *(ux+ii);
while ( GSL_FN_EVAL(JRRoot+tid,u_hi) > 0. && u_hi < asinh(37.5/ *(delta+ii*delta_stride))) {
u_lo= u_hi; //this makes sure that brent evaluates using previous
u_hi*= 1.1;
}
u_lo= (u_hi > 1.1 * *(ux+ii)) ? u_hi / 1.1 / 1.1: *(ux+ii);
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, u_lo, u_hi);
if (status == GSL_EINVAL) {
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
u_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
u_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (u_lo, u_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(umin+ii) = -9999.99;
*(umax+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(umax+ii) = gsl_root_fsolver_root ((s+tid)->s);
}
}
gsl_set_error_handler (NULL);
for (tid=0; tid < nthreads; tid++)
gsl_root_fsolver_free( (s+tid)->s);
free(s);
free(JRRoot);
free(params);
}
void calcVmin(int ndata,
double * vmin,
double * vx,
double * pvx,
double * E,
double * Lz,
double * I3V,
int ndelta,
double * delta,
double * u0,
double * cosh2u0,
double * sinh2u0,
double * potupi2,
int nargs,
struct potentialArg * actionAngleArgs){
int ii, tid, nthreads;
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
gsl_function * JzRoot= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );
struct JzStaeckelArg * params= (struct JzStaeckelArg *) malloc ( nthreads * sizeof (struct JzStaeckelArg) );
//Setup solver
int status;
int iter, max_iter = 100;
const gsl_root_fsolver_type *T;
struct pragmasolver *s= (struct pragmasolver *) malloc ( nthreads * sizeof (struct pragmasolver) );;
double v_lo, v_hi;
T = gsl_root_fsolver_brent;
for (tid=0; tid < nthreads; tid++){
(params+tid)->nargs= nargs;
(params+tid)->actionAngleArgs= actionAngleArgs;
(s+tid)->s= gsl_root_fsolver_alloc (T);
}
int delta_stride= ndelta == 1 ? 0 : 1;
UNUSED int chunk= CHUNKSIZE;
gsl_set_error_handler_off();
#pragma omp parallel for schedule(static,chunk) \
private(tid,ii,iter,status,v_lo,v_hi) \
shared(vmin,JzRoot,params,s,vx,delta,E,Lz,I3V,u0,cosh2u0,sinh2u0,potupi2,max_iter)
for (ii=0; ii < ndata; ii++){
#ifdef _OPENMP
tid= omp_get_thread_num();
#else
tid = 0;
#endif
//Setup function
(params+tid)->delta= *(delta+ii*delta_stride);
(params+tid)->E= *(E+ii);
(params+tid)->Lz22delta= 0.5 * *(Lz+ii) * *(Lz+ii) / *(delta+ii*delta_stride) / *(delta+ii*delta_stride);
(params+tid)->I3V= *(I3V+ii);
(params+tid)->u0= *(u0+ii);
(params+tid)->cosh2u0= *(cosh2u0+ii);
(params+tid)->sinh2u0= *(sinh2u0+ii);
(params+tid)->potupi2= *(potupi2+ii);
(JzRoot+tid)->function = &JzStaeckelIntegrandSquared;
(JzRoot+tid)->params = params+tid;
//Find starting points for minimum
if ( fabs(GSL_FN_EVAL(JzRoot+tid,*(vx+ii))) < 0.0000001) //we are at vmin
*(vmin+ii)= ( *(vx+ii) > 0.5 * M_PI ) ? M_PI - *(vx+ii): *(vx+ii);
else {
if ( *(vx+ii) > 0.5 * M_PI ){
v_lo= 0.9 * ( M_PI - *(vx+ii) );
v_hi= M_PI - *(vx+ii);
}
else {
v_lo= 0.9 * *(vx+ii);
v_hi= *(vx+ii);
}
while ( GSL_FN_EVAL(JzRoot+tid,v_lo) >= 0. && v_lo > 0.000000001){
v_hi= v_lo; //this makes sure that brent evaluates using previous
v_lo*= 0.9;
}
//Find root
status = gsl_root_fsolver_set ((s+tid)->s, JzRoot+tid, v_lo, v_hi);
if (status == GSL_EINVAL) {
*(vmin+ii) = -9999.99;
continue;
}
iter= 0;
do
{
iter++;
status = gsl_root_fsolver_iterate ((s+tid)->s);
v_lo = gsl_root_fsolver_x_lower ((s+tid)->s);
v_hi = gsl_root_fsolver_x_upper ((s+tid)->s);
status = gsl_root_test_interval (v_lo, v_hi,
9.9999999999999998e-13,
4.4408920985006262e-16);
}
while (status == GSL_CONTINUE && iter < max_iter);
// LCOV_EXCL_START
if (status == GSL_EINVAL) {//Shouldn't ever get here
*(vmin+ii) = -9999.99;
continue;
}
// LCOV_EXCL_STOP
*(vmin+ii) = gsl_root_fsolver_root ((s+tid)->s);
fflush(stdout);
}
}
gsl_set_error_handler (NULL);
for (tid=0; tid < nthreads; tid++)
gsl_root_fsolver_free( (s+tid)->s);
free(s);
free(JzRoot);
free(params);
}
double JRStaeckelIntegrand(double u,
void * p){
double out= JRStaeckelIntegrandSquared(u,p);
if ( out <= 0.) return 0.;
else return sqrt(out);
}
double JRStaeckelIntegrandSquared(double u,
void * p){
struct JRStaeckelArg * params= (struct JRStaeckelArg *) p;
double sinh2u= sinh(u) * sinh(u);
double dU= (sinh2u+params->sin2v0)
*evaluatePotentialsUV(u,params->v0,params->delta,
params->nargs,params->actionAngleArgs)
- (params->sinh2u0+params->sin2v0)*params->potu0v0;
return params->E * sinh2u - params->I3U - dU - params->Lz22delta / sinh2u;
}
double JRStaeckelIntegrandSquared4dJR(double u,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double sinh2u= sinh(u) * sinh(u);
double dU= (sinh2u+params->sin2v0)
*evaluatePotentialsUV(u,params->v0,params->delta,
params->nargs,params->actionAngleArgs)
- (params->sinh2u0+params->sin2v0)*params->potu0v0;
return params->E * sinh2u - params->I3U - dU - params->Lz22delta / sinh2u;
}
double JzStaeckelIntegrand(double v,
void * p){
double out= JzStaeckelIntegrandSquared(v,p);
if ( out <= 0. ) return 0.;
else return sqrt(out);
}
double JzStaeckelIntegrandSquared(double v,
void * p){
struct JzStaeckelArg * params= (struct JzStaeckelArg *) p;
double sin2v= sin(v) * sin(v);
double dV= params->cosh2u0 * params->potupi2
- (params->sinh2u0+sin2v)
*evaluatePotentialsUV(params->u0,v,params->delta,
params->nargs,params->actionAngleArgs);
return params->E * sin2v + params->I3V + dV - params->Lz22delta / sin2v;
}
double JzStaeckelIntegrandSquared4dJz(double v,
void * p){
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) p;
double sin2v= sin(v) * sin(v);
double dV= params->cosh2u0 * params->potupi2
- (params->sinh2u0+sin2v)
*evaluatePotentialsUV(params->u0,v,params->delta,
params->nargs,params->actionAngleArgs);
return params->E * sin2v + params->I3V + dV - params->Lz22delta / sin2v;
}
double dJRdELowStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umin + t * t;
return 2. * t * dJRdEStaeckelIntegrand(u,p);
}
double dJRdEHighStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umax - t * t;
return 2. * t * dJRdEStaeckelIntegrand(u,p);
}
double dJRdEStaeckelIntegrand(double u,
void * p){
double out= JRStaeckelIntegrandSquared4dJR(u,p);
if ( out <= 0. ) return 0.;
else return sinh(u)*sinh(u)/sqrt(out);
}
double dJRdLzLowStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umin + t * t;
return 2. * t * dJRdLzStaeckelIntegrand(u,p);
}
double dJRdLzHighStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umax - t * t;
return 2. * t * dJRdLzStaeckelIntegrand(u,p);
}
double dJRdLzStaeckelIntegrand(double u,
void * p){
double out= JRStaeckelIntegrandSquared4dJR(u,p);
if ( out <= 0. ) return 0.;
else return 1./sinh(u)/sinh(u)/sqrt(out);
}
double dJRdI3LowStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umin + t * t;
return 2. * t * dJRdI3StaeckelIntegrand(u,p);
}
double dJRdI3HighStaeckelIntegrand(double t,
void * p){
struct dJRStaeckelArg * params= (struct dJRStaeckelArg *) p;
double u= params->umax - t * t;
return 2. * t * dJRdI3StaeckelIntegrand(u,p);
}
double dJRdI3StaeckelIntegrand(double u,
void * p){
double out= JRStaeckelIntegrandSquared4dJR(u,p);
if ( out <= 0. ) return 0.;
else return 1./sqrt(out);
}
double dJzdELowStaeckelIntegrand(double t,
void * p){
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) p;
double v= params->vmin + t * t;
return 2. * t * dJzdEStaeckelIntegrand(v,p);
}
double dJzdEHighStaeckelIntegrand(double t,
void * p){
double v= M_PI/2. - t * t;
return 2. * t * dJzdEStaeckelIntegrand(v,p);
}
double dJzdEStaeckelIntegrand(double v,
void * p){
double out= JzStaeckelIntegrandSquared4dJz(v,p);
if ( out <= 0. ) return 0.;
else return sin(v)*sin(v)/sqrt(out);
}
double dJzdLzLowStaeckelIntegrand(double t,
void * p){
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) p;
double v= params->vmin + t * t;
return 2. * t * dJzdLzStaeckelIntegrand(v,p);
}
double dJzdLzHighStaeckelIntegrand(double t,
void * p){
double v= M_PI/2. - t * t;
return 2. * t * dJzdLzStaeckelIntegrand(v,p);
}
double dJzdLzStaeckelIntegrand(double v,
void * p){
double out= JzStaeckelIntegrandSquared4dJz(v,p);
if ( out <= 0. ) return 0.;
else return 1./sin(v)/sin(v)/sqrt(out);
}
double dJzdI3LowStaeckelIntegrand(double t,
void * p){
struct dJzStaeckelArg * params= (struct dJzStaeckelArg *) p;
double v= params->vmin + t * t;
return 2. * t * dJzdI3StaeckelIntegrand(v,p);
}
double dJzdI3HighStaeckelIntegrand(double t,
void * p){
double v= M_PI/2. - t * t;
return 2. * t * dJzdI3StaeckelIntegrand(v,p);
}
double dJzdI3StaeckelIntegrand(double v,
void * p){
double out= JzStaeckelIntegrandSquared4dJz(v,p);
if ( out <= 0. ) return 0.;
else return 1./sqrt(out);
}
double u0Equation(double u, void * p){
struct u0EqArg * params= (struct u0EqArg *) p;
double sinh2u= sinh(u) * sinh(u);
double cosh2u= cosh(u) * cosh(u);
double dU= cosh2u * evaluatePotentialsUV(u,0.5*M_PI,params->delta,
params->nargs,params->actionAngleArgs);
return -(params->E*sinh2u-dU-params->Lz22delta/sinh2u);
}
double evaluatePotentialsUV(double u, double v, double delta,
int nargs,
struct potentialArg * actionAngleArgs){
double R,z;
uv_to_Rz(u,v,&R,&z,delta);
return evaluatePotentials(R,z,nargs,actionAngleArgs);
}
| {
"alphanum_fraction": 0.6226157262,
"avg_line_length": 35.3558127831,
"ext": "c",
"hexsha": "4d08d84213bb03b0898f2eeec7bd965aa4c02b91",
"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": "d6db971285f163456c81775fc2fdc7d75189762c",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "gusbeane/galpy",
"max_forks_repo_path": "galpy/actionAngle/actionAngle_c_ext/actionAngleStaeckel.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c",
"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": "gusbeane/galpy",
"max_issues_repo_path": "galpy/actionAngle/actionAngle_c_ext/actionAngleStaeckel.c",
"max_line_length": 177,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "gusbeane/galpy",
"max_stars_repo_path": "galpy/actionAngle/actionAngle_c_ext/actionAngleStaeckel.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 26231,
"size": 70252
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.