Search is not available for this dataset
text string | meta dict |
|---|---|
/* specfunc/bessel_Jn.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_sf_pow_int.h>
#include "bessel.h"
#include "bessel_amp_phase.h"
#include "bessel_olver.h"
#include <gsl/gsl_sf_bessel.h>
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int gsl_sf_bessel_Jn_e(int n, double x, gsl_sf_result * result)
{
int sign = 1;
if(n < 0) {
/* reduce to case n >= 0 */
n = -n;
if(GSL_IS_ODD(n)) sign = -sign;
}
if(x < 0.0) {
/* reduce to case x >= 0. */
x = -x;
if(GSL_IS_ODD(n)) sign = -sign;
}
/* CHECK_POINTER(result) */
if(n == 0) {
gsl_sf_result b0;
int stat_J0 = gsl_sf_bessel_J0_e(x, &b0);
result->val = sign * b0.val;
result->err = b0.err;
return stat_J0;
}
else if(n == 1) {
gsl_sf_result b1;
int stat_J1 = gsl_sf_bessel_J1_e(x, &b1);
result->val = sign * b1.val;
result->err = b1.err;
return stat_J1;
}
else {
if(x == 0.0) {
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else if(x*x < 10.0*(n+1.0)*GSL_ROOT5_DBL_EPSILON) {
gsl_sf_result b;
int status = gsl_sf_bessel_IJ_taylor_e((double)n, x, -1, 50, GSL_DBL_EPSILON, &b);
result->val = sign * b.val;
result->err = b.err;
result->err += GSL_DBL_EPSILON * fabs(result->val);
return status;
}
else if(GSL_ROOT4_DBL_EPSILON * x > (n*n+1.0)) {
int status = gsl_sf_bessel_Jnu_asympx_e((double)n, x, result);
result->val *= sign;
return status;
}
else if(n > 50) {
int status = gsl_sf_bessel_Jnu_asymp_Olver_e((double)n, x, result);
result->val *= sign;
return status;
}
else if(x > 1000.0)
{
/* We need this to avoid feeding large x to CF1; note that
* due to the above check, we know that n <= 50.
*/
int status = gsl_sf_bessel_Jnu_asympx_e((double)n, x, result);
result->val *= sign;
return status;
}
else {
double ans;
double err;
double ratio;
double sgn;
int stat_b;
int stat_CF1 = gsl_sf_bessel_J_CF1((double)n, x, &ratio, &sgn);
/* backward recurrence */
double Jkp1 = GSL_SQRT_DBL_MIN * ratio;
double Jk = GSL_SQRT_DBL_MIN;
double Jkm1;
int k;
for(k=n; k>0; k--) {
Jkm1 = 2.0*k/x * Jk - Jkp1;
Jkp1 = Jk;
Jk = Jkm1;
}
if(fabs(Jkp1) > fabs(Jk)) {
gsl_sf_result b1;
stat_b = gsl_sf_bessel_J1_e(x, &b1);
ans = b1.val/Jkp1 * GSL_SQRT_DBL_MIN;
err = b1.err/Jkp1 * GSL_SQRT_DBL_MIN;
}
else {
gsl_sf_result b0;
stat_b = gsl_sf_bessel_J0_e(x, &b0);
ans = b0.val/Jk * GSL_SQRT_DBL_MIN;
err = b0.err/Jk * GSL_SQRT_DBL_MIN;
}
result->val = sign * ans;
result->err = fabs(err);
return GSL_ERROR_SELECT_2(stat_CF1, stat_b);
}
}
}
int
gsl_sf_bessel_Jn_array(int nmin, int nmax, double x, double * result_array)
{
/* CHECK_POINTER(result_array) */
if(nmin < 0 || nmax < nmin) {
int n;
for(n=nmax; n>=nmin; n--) {
result_array[n-nmin] = 0.0;
}
GSL_ERROR ("domain error", GSL_EDOM);
}
else if(x == 0.0) {
int n;
for(n=nmax; n>=nmin; n--) {
result_array[n-nmin] = 0.0;
}
if(nmin == 0) result_array[0] = 1.0;
return GSL_SUCCESS;
}
else {
gsl_sf_result r_Jnp1;
gsl_sf_result r_Jn;
int stat_np1 = gsl_sf_bessel_Jn_e(nmax+1, x, &r_Jnp1);
int stat_n = gsl_sf_bessel_Jn_e(nmax, x, &r_Jn);
int stat = GSL_ERROR_SELECT_2(stat_np1, stat_n);
double Jnp1 = r_Jnp1.val;
double Jn = r_Jn.val;
double Jnm1;
int n;
if(stat == GSL_SUCCESS) {
for(n=nmax; n>=nmin; n--) {
result_array[n-nmin] = Jn;
Jnm1 = -Jnp1 + 2.0*n/x * Jn;
Jnp1 = Jn;
Jn = Jnm1;
}
}
else {
for(n=nmax; n>=nmin; n--) {
result_array[n-nmin] = 0.0;
}
}
return stat;
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_bessel_Jn(const int n, const double x)
{
EVAL_RESULT(gsl_sf_bessel_Jn_e(n, x, &result));
}
| {
"alphanum_fraction": 0.5817212791,
"avg_line_length": 25.33,
"ext": "c",
"hexsha": "3d5c9581566427aa2aa277597e8ad9b4c440ae33",
"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_Jn.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_Jn.c",
"max_line_length": 88,
"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_Jn.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": 1681,
"size": 5066
} |
#include "../EngineTest.h"
#include <Catch2>
#include <gsl/gsl_math.h>
TEST_CASE("kurtosis Function Evaluation Tests", "[kurtosis]") {
// SECTION("Empty Test"){
// requireIsEqual("kurtosis()", "Insufficient Number of Arguments for Function: kurtosis");
// }
SECTION("`kurtosis` Test 1"){
requireIsEqual("kurtosis(-9.75, -6.89, 8.71, 9.56)", -2.4054875147);
}
SECTION("`kurtosis` Test 2"){
requireIsEqual("kurtosis(-0.03, -0.66, 8.08, 7.46, -9.47, 5.48)", -1.3867096466);
}
SECTION("`kurt` Test 3"){
requireIsEqual("kurt(6.88, 2.73, 0.91, 7.03)", -2.3097016758);
}
SECTION("`kurt` Test 4"){
requireIsEqual("kurt(8.51, 4.35)", -2.75);
}
SECTION("`kurtosis` Test 5"){
requireIsEqual("kurtosis(9.24, -5.27, 8.46, 8.69, 3.49, 7.69)", -0.7621422371);
}
SECTION("`kurt` Test 6"){
requireIsEqual("kurt(0.94, 2.67, -0.5, -4.74)", -1.8915463404);
}
SECTION("`kurt` Test 7"){
requireIsEqual("kurt(-3.29, -3.04, 2.81, 6.5, -2.0)", -1.8864498289);
}
SECTION("`kurtosis` Test 8"){
requireIsEqual("kurtosis(-9.95, -8.32, 3.62, -9.95)", -1.7095361309);
}
SECTION("`kurtosis` Test 9"){
requireIsEqual("kurtosis(-2.47, 7.98, 7.08, 5.36, -0.13, 0.57, -5.41, -6.09, -4.31)", -1.7566598859);
}
SECTION("`kurtosis` Test 10"){
requireIsEqual("kurtosis(-3.21, -8.75, 6.86, 9.35, -3.09, 4.99)", -1.932477903);
}
}
| {
"alphanum_fraction": 0.5543551654,
"avg_line_length": 26.9272727273,
"ext": "h",
"hexsha": "6c88708943224b103dc6cd3199bac0c3b3c623cc",
"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": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "antoniojkim/CalcPlusPlus",
"max_forks_repo_path": "Tests/Tests/StatisticsTests/kurtosisTests.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"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": "antoniojkim/CalcPlusPlus",
"max_issues_repo_path": "Tests/Tests/StatisticsTests/kurtosisTests.h",
"max_line_length": 109,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "antoniojkim/CalcPlusPlus",
"max_stars_repo_path": "Tests/Tests/StatisticsTests/kurtosisTests.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 600,
"size": 1481
} |
/**
*
* @file qwrapper_sgemm.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @author Mathieu Faverge
* @author Jakub Kurzak
* @date 2010-11-15
* @generated s Tue Jan 7 11:44:56 2014
*
**/
#include <cblas.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_sgemm(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum transA, int transB,
int m, int n, int k, int nb,
float alpha, const float *A, int lda,
const float *B, int ldb,
float beta, float *C, int ldc)
{
DAG_CORE_GEMM;
QUARK_Insert_Task(quark, CORE_sgemm_quark, task_flags,
sizeof(PLASMA_enum), &transA, VALUE,
sizeof(PLASMA_enum), &transB, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(int), &k, VALUE,
sizeof(float), &alpha, VALUE,
sizeof(float)*nb*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(float)*nb*nb, B, INPUT,
sizeof(int), &ldb, VALUE,
sizeof(float), &beta, VALUE,
sizeof(float)*nb*nb, C, INOUT,
sizeof(int), &ldc, VALUE,
0);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_sgemm2( Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum transA, int transB,
int m, int n, int k, int nb,
float alpha, const float *A, int lda,
const float *B, int ldb,
float beta, float *C, int ldc)
{
DAG_CORE_GEMM;
QUARK_Insert_Task(quark, CORE_sgemm_quark, task_flags,
sizeof(PLASMA_enum), &transA, VALUE,
sizeof(PLASMA_enum), &transB, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(int), &k, VALUE,
sizeof(float), &alpha, VALUE,
sizeof(float)*nb*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(float)*nb*nb, B, INPUT,
sizeof(int), &ldb, VALUE,
sizeof(float), &beta, VALUE,
sizeof(float)*nb*nb, C, INOUT | LOCALITY | GATHERV,
sizeof(int), &ldc, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_sgemm_quark = PCORE_sgemm_quark
#define CORE_sgemm_quark PCORE_sgemm_quark
#endif
void CORE_sgemm_quark(Quark *quark)
{
PLASMA_enum transA;
PLASMA_enum transB;
int m;
int n;
int k;
float alpha;
float *A;
int lda;
float *B;
int ldb;
float beta;
float *C;
int ldc;
quark_unpack_args_13(quark, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
cblas_sgemm(
CblasColMajor,
(CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,
m, n, k,
(alpha), A, lda,
B, ldb,
(beta), C, ldc);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_sgemm_f2(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum transA, int transB,
int m, int n, int k, int nb,
float alpha, const float *A, int lda,
const float *B, int ldb,
float beta, float *C, int ldc,
float *fake1, int szefake1, int flag1,
float *fake2, int szefake2, int flag2)
{
DAG_CORE_GEMM;
QUARK_Insert_Task(quark, CORE_sgemm_f2_quark, task_flags,
sizeof(PLASMA_enum), &transA, VALUE,
sizeof(PLASMA_enum), &transB, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(int), &k, VALUE,
sizeof(float), &alpha, VALUE,
sizeof(float)*nb*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(float)*nb*nb, B, INPUT,
sizeof(int), &ldb, VALUE,
sizeof(float), &beta, VALUE,
sizeof(float)*nb*nb, C, INOUT | LOCALITY,
sizeof(int), &ldc, VALUE,
sizeof(float)*szefake1, fake1, flag1,
sizeof(float)*szefake2, fake2, flag2,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_sgemm_f2_quark = PCORE_sgemm_f2_quark
#define CORE_sgemm_f2_quark PCORE_sgemm_f2_quark
#endif
void CORE_sgemm_f2_quark(Quark* quark)
{
PLASMA_enum transA;
PLASMA_enum transB;
int M;
int N;
int K;
float alpha;
float *A;
int LDA;
float *B;
int LDB;
float beta;
float *C;
int LDC;
void *fake1, *fake2;
quark_unpack_args_15(quark, transA, transB, M, N, K, alpha,
A, LDA, B, LDB, beta, C, LDC, fake1, fake2);
cblas_sgemm(
CblasColMajor,
(CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,
M, N, K,
(alpha), A, LDA,
B, LDB,
(beta), C, LDC);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_sgemm_p2(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum transA, int transB,
int m, int n, int k, int nb,
float alpha, const float *A, int lda,
const float **B, int ldb,
float beta, float *C, int ldc)
{
DAG_CORE_GEMM;
QUARK_Insert_Task(quark, CORE_sgemm_p2_quark, task_flags,
sizeof(PLASMA_enum), &transA, VALUE,
sizeof(PLASMA_enum), &transB, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(int), &k, VALUE,
sizeof(float), &alpha, VALUE,
sizeof(float)*lda*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(float*), B, INPUT,
sizeof(int), &ldb, VALUE,
sizeof(float), &beta, VALUE,
sizeof(float)*ldc*nb, C, INOUT | LOCALITY,
sizeof(int), &ldc, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_sgemm_p2_quark = PCORE_sgemm_p2_quark
#define CORE_sgemm_p2_quark PCORE_sgemm_p2_quark
#endif
void CORE_sgemm_p2_quark(Quark* quark)
{
PLASMA_enum transA;
PLASMA_enum transB;
int M;
int N;
int K;
float alpha;
float *A;
int LDA;
float **B;
int LDB;
float beta;
float *C;
int LDC;
quark_unpack_args_13(quark, transA, transB, M, N, K, alpha,
A, LDA, B, LDB, beta, C, LDC);
cblas_sgemm(
CblasColMajor,
(CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,
M, N, K,
(alpha), A, LDA,
*B, LDB,
(beta), C, LDC);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_sgemm_p3(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum transA, int transB,
int m, int n, int k, int nb,
float alpha, const float *A, int lda,
const float *B, int ldb,
float beta, float **C, int ldc)
{
DAG_CORE_GEMM;
QUARK_Insert_Task(quark, CORE_sgemm_p3_quark, task_flags,
sizeof(PLASMA_enum), &transA, VALUE,
sizeof(PLASMA_enum), &transB, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(int), &k, VALUE,
sizeof(float), &alpha, VALUE,
sizeof(float)*lda*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(float)*ldb*nb, B, INPUT,
sizeof(int), &ldb, VALUE,
sizeof(float), &beta, VALUE,
sizeof(float*), C, INOUT | LOCALITY,
sizeof(int), &ldc, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_sgemm_p3_quark = PCORE_sgemm_p3_quark
#define CORE_sgemm_p3_quark PCORE_sgemm_p3_quark
#endif
void CORE_sgemm_p3_quark(Quark* quark)
{
PLASMA_enum transA;
PLASMA_enum transB;
int M;
int N;
int K;
float alpha;
float *A;
int LDA;
float *B;
int LDB;
float beta;
float **C;
int LDC;
quark_unpack_args_13(quark, transA, transB, M, N, K, alpha,
A, LDA, B, LDB, beta, C, LDC);
cblas_sgemm(
CblasColMajor,
(CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,
M, N, K,
(alpha), A, LDA,
B, LDB,
(beta), *C, LDC);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_sgemm_p2f1(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum transA, int transB,
int m, int n, int k, int nb,
float alpha, const float *A, int lda,
const float **B, int ldb,
float beta, float *C, int ldc,
float *fake1, int szefake1, int flag1)
{
DAG_CORE_GEMM;
QUARK_Insert_Task(quark, CORE_sgemm_p2f1_quark, task_flags,
sizeof(PLASMA_enum), &transA, VALUE,
sizeof(PLASMA_enum), &transB, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(int), &k, VALUE,
sizeof(float), &alpha, VALUE,
sizeof(float)*lda*nb, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(float*), B, INPUT,
sizeof(int), &ldb, VALUE,
sizeof(float), &beta, VALUE,
sizeof(float)*ldc*nb, C, INOUT | LOCALITY,
sizeof(int), &ldc, VALUE,
sizeof(float)*szefake1, fake1, flag1,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_sgemm_p2f1_quark = PCORE_sgemm_p2f1_quark
#define CORE_sgemm_p2f1_quark PCORE_sgemm_p2f1_quark
#endif
void CORE_sgemm_p2f1_quark(Quark* quark)
{
PLASMA_enum transA;
PLASMA_enum transB;
int M;
int N;
int K;
float alpha;
float *A;
int LDA;
float **B;
int LDB;
float beta;
float *C;
int LDC;
void *fake1;
quark_unpack_args_14(quark, transA, transB, M, N, K, alpha,
A, LDA, B, LDB, beta, C, LDC, fake1);
cblas_sgemm(
CblasColMajor,
(CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,
M, N, K,
(alpha), A, LDA,
*B, LDB,
(beta), C, LDC);
}
| {
"alphanum_fraction": 0.4330254953,
"avg_line_length": 34.8049450549,
"ext": "c",
"hexsha": "f9fe5e9f635baf06f6d20d89d8a1544d321debeb",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas-qwrapper/qwrapper_sgemm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas-qwrapper/qwrapper_sgemm.c",
"max_line_length": 94,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas-qwrapper/qwrapper_sgemm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3203,
"size": 12669
} |
/*
Copyright (c) 2015, Patrick Weltevrede
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_statistics_double.h>
#include "psrsalsa.h"
#define KSTEST 1
#define KSFLAT 2
#define KSSIN 3
#define KSFLAT_WITH_MINMAX 4
#define CORREL 20
#define PEARSON 21
#define MOMENTS 30
#define MEDIAN 31
#define CHI2TEST_HIST 50
#define CHI2TEST_CDF 51
int main(int argc, char **argv)
{
psrsalsaApplication application;
long i, j;
int file1_column1, file1_column2, file1_column3, file2_column1, file2_column2, file2_column3, typetest, read_log, output_idx, skiplines;
double threshold1, threshold2, threshold3, ksflat_min, ksflat_max;
initApplication(&application, "pstat", "[options] inputfile(s)");
application.switch_libversions = 1;
application.switch_verbose = 1;
application.switch_debug = 1;
file1_column1 = 0;
file1_column2 = 0;
file1_column3 = 0;
file2_column1 = 0;
file2_column2 = 0;
file2_column3 = 0;
typetest = 0;
read_log = 0;
threshold1 = 0;
threshold2 = 0;
threshold3 = 0;
output_idx = 0;
skiplines = 0;
if(argc < 2) {
printf("Program to perform various statistical tests on input data. One or two input\n");
printf("files are required depending on the statistical test to be performed. The input\n");
printf("files should be ascii files with each line having an equal number of columns.\n");
printf("Lines starting with a # will be ignored. Usage:\n\n");
printApplicationHelp(&application);
printf("Input/Output options:\n");
printf("-col \"c1 c2 c3\" Specify one, two or three column numbers (counting from 1) to\n");
printf(" be read in from the first input file. Some statistical tests\n");
printf(" require only one input column, others two or more.\n");
printf("-col1 Equivalent to -col\n");
printf("-col2 Like -col1, but for second input file.\n");
printf("-log The base 10 log of the input values is used.\n");
printf("-output Specify output filename to use rather than the stdout.\n");
printf("-skiplines nr Specify number of lines that should be skipped from start file(s).\n");
printf("\nStatistical tests:\n");
printf("-chi2hist \"t1 t2 t3\" Input should be two files, each being a histogram and\n");
printf(" having two (or three, see below) columns: bin location and\n");
printf(" the height. The histograms should have equal bin widths,\n");
printf(" overlap at least partially and have aligned bins. Only bins\n");
printf(" in the 1st input file with a height >= t1 are considered (so if\n");
printf(" negative, everything should be included. t2 is the theshold for\n");
printf(" the 2nd file, while t3 is that for the sum of heights of the\n");
printf(" two histograms. Specifying t2 and t3 is optional. The optional\n");
printf(" 3rd column is the std. dev. on each bin, which is set to zero\n");
printf(" for bins outside the covered range of the histograms, and the\n");
printf(" height is set to zero as well. With only two columns, the\n");
printf(" chi-square test is unweighted, i.e. each bin has an equal\n");
printf(" weight (set to 1) regardless of the height of the bin(s).\n");
printf(" Examples: \n");
printf(" pstat -chi2hist \"-1 -1 0.1\" -col1 \"1 2\" -col2 \"1 2\" file1 file2\n");
printf(" pstat -chi2hist -1 -col1 \"1 2 3\" -col2 \"1 2 3\" file1 file2\n");
printf("-chi2cdf This test is similar to -chi2hist, except that the inputs are\n");
printf(" not histograms, but the distribution of points itself (i.e. one\n");
printf(" column). This test therefore does not depend on binning. The\n");
printf(" vertical difference in their CDF is quantified with an non-\n");
printf(" weighted chi-square test (weights are set to 1). This is done\n");
printf(" for each point in the CDF of the shortest distribution and\n");
printf(" using a linear interpolation of the other. This test can be\n");
printf(" useful to decide which model distribution fits an observed\n");
printf(" distribution best, but the chi square itself is not immediately\n");
printf(" meaningful. Example: pstat -chi2cdf file1 file2\n");
printf("-correl Produces the cross correlation function (as function of lag)\n");
printf(" calculated in the Fourier domain assuming equal sampling.\n");
printf(" Examples: pstat -correl -col1 1 -col2 1 file1 file2\n");
printf(" or: pstat -correl -col \"1 2\" file1\n");
printf("-ks Kolmogorov-Smirnov test: Assess difference between two\n");
printf(" distributions of points. The made approximations are similar to\n");
printf(" the implementation in Numerical Recipes in C, 2nd edition and.\n");
printf(" does not depend on any binning.\n");
printf(" Examples: pstat -ks -col1 1 -col2 1 file1 file2\n");
printf(" or: pstat -ks -col \"1 2\" file1\n");
printf("-ksflat Like -ks, but compare single input distribution with a flat\n");
printf(" distribution covering the range of input values.\n");
printf(" Example: pstat -ksflat -col 1 file1\n");
printf("-ksflat2 \"min max\" Like -ksflat, but set the range to the specified values.\n");
printf(" Example: pstat -ksflat2 \"0 1\" -col 1 file1\n");
printf("-kssin Like -ks, but compare single input distribution with a\n");
printf(" sinusoidal distribution between 0 and 90 deg.\n");
printf(" Example: pstat -kssin -col 1 file1\n");
printf("-median Compute the median of the distribution.\n");
printf(" Example: pstat -median -col 1 file1\n");
printf("-moments Compute different moments of the distribution (mean, variance\n");
printf(" etc.)\n");
printf(" Example: pstat -moments -col 1 file1\n");
printf("-pearson Pearson product-moment correlation coefficient:\n");
printf(" Measures the linear correlation between two variables.\n");
printf(" Examples: pstat -pearson -col1 1 -col2 1 file1 file2\n");
printf(" or: pstat -pearson -col \"1 2\" file1\n");
printf("\n");
printCitationInfo();
terminateApplication(&application);
return 0;
}else {
for(i = 1; i < argc; i++) {
int index;
index = i;
if(processCommandLine(&application, argc, argv, &index)) {
i = index;
}else if(strcmp(argv[i], "-col") == 0 || strcmp(argv[i], "-col1") == 0) {
int ret;
ret = parse_command_string(application.verbose_state, argc, argv, i+1, 0, 1, "%d %d %d", &file1_column1, &file1_column2, &file1_column3, NULL);
if(ret == 1) {
file1_column2 = 0;
file1_column3 = 0;
}else if(ret == 2) {
file1_column3 = 0;
}else if(ret != 3) {
printerror(application.verbose_state.debug, "ERROR pstat: Cannot parse '%s' option, 1, 2 or 3 values.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-col2") == 0) {
int ret;
ret = parse_command_string(application.verbose_state, argc, argv, i+1, 0, 1, "%d %d %d", &file2_column1, &file2_column2, &file2_column3, NULL);
if(ret == 1) {
file2_column2 = 0;
file2_column3 = 0;
}else if(ret == 2) {
file2_column3 = 0;
}else if(ret != 3) {
printerror(application.verbose_state.debug, "ERROR pstat: Cannot parse '%s' option, 1, 2 or 3 values.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-skiplines") == 0) {
int ret;
ret = parse_command_string(application.verbose_state, argc, argv, i+1, 0, 1, "%d", &skiplines, NULL);
if(ret != 1) {
printerror(application.verbose_state.debug, "ERROR pstat: Cannot parse '%s' option, 1 integer value was expected.", argv[i]);
return 0;
}
i++;
}else if(strcmp(argv[i], "-output") == 0) {
output_idx = i+1;
i++;
}else if(strcmp(argv[i], "-correl") == 0) {
if(typetest != 0) {
printerror(application.verbose_state.debug, "pstat: Cannot specify more than one type of statistical test at the time");
return 0;
}
typetest = CORREL;
}else if(strcasecmp(argv[i], "-pearson") == 0) {
if(typetest != 0) {
printerror(application.verbose_state.debug, "pstat: Cannot specify more than one type of statistical test at the time");
return 0;
}
typetest = PEARSON;
}else if(strcmp(argv[i], "-ks") == 0) {
if(typetest != 0) {
printerror(application.verbose_state.debug, "pstat: Cannot specify more than one type of statistical test at the time");
return 0;
}
typetest = KSTEST;
}else if(strcmp(argv[i], "-ksflat") == 0) {
if(typetest != 0) {
printerror(application.verbose_state.debug, "pstat: Cannot specify more than one type of statistical test at the time");
return 0;
}
typetest = KSFLAT;
}else if(strcmp(argv[i], "-ksflat2") == 0) {
if(typetest != 0) {
printerror(application.verbose_state.debug, "pstat: Cannot specify more than one type of statistical test at the time");
return 0;
}
int ret;
ret = parse_command_string(application.verbose_state, argc, argv, i+1, 0, 1, "%lf %lf", &ksflat_min, &ksflat_max, NULL);
if(ret != 2) {
printerror(application.verbose_state.debug, "ERROR pstat: Cannot parse '%s' option, 2 values were expected.", argv[i]);
return 0;
}
typetest = KSFLAT_WITH_MINMAX;
i++;
}else if(strcmp(argv[i], "-moments") == 0) {
if(typetest != 0) {
printerror(application.verbose_state.debug, "pstat: Cannot specify more than one type of statistical test at the time");
return 0;
}
typetest = MOMENTS;
}else if(strcmp(argv[i], "-median") == 0) {
if(typetest != 0) {
printerror(application.verbose_state.debug, "pstat: Cannot specify more than one type of statistical test at the time");
return 0;
}
typetest = MEDIAN;
}else if(strcmp(argv[i], "-kssin") == 0) {
if(typetest != 0) {
printerror(application.verbose_state.debug, "pstat: Cannot specify more than one type of statistical test at the time");
return 0;
}
typetest = KSSIN;
}else if(strcmp(argv[i], "-chi2hist") == 0) {
int ret;
ret = parse_command_string(application.verbose_state, argc, argv, i+1, 0, 1, "%lf %lf %lf", &threshold1, &threshold2, &threshold3, NULL);
if(ret == 1) {
threshold2 = threshold3 = -1;
}else if(ret == 2) {
threshold3 = -1;
}else if(ret != 3) {
printerror(application.verbose_state.debug, "ERROR pstat: Cannot parse '%s' option, 1, 2 or 3 values.", argv[i]);
return 0;
}
if(typetest != 0) {
printerror(application.verbose_state.debug, "pstat: Cannot specify more than one type of statistical test at the time");
return 0;
}
typetest = CHI2TEST_HIST;
i++;
}else if(strcmp(argv[i], "-chi2cdf") == 0) {
if(typetest != 0) {
printerror(application.verbose_state.debug, "pstat: Cannot specify more than one type of statistical test at the time");
return 0;
}
typetest = CHI2TEST_CDF;
}else if(strcmp(argv[i], "-log") == 0) {
read_log = 1;
}else {
if(argv[i][0] == '-') {
printerror(application.verbose_state.debug, "pstat: Unknown option: %s\n\nRun pstat without command line arguments to show help", argv[i]);
terminateApplication(&application);
return 0;
}else {
if(applicationAddFilename(i, application.verbose_state) == 0)
return 0;
}
}
}
}
if(applicationFilenameList_checkConsecutive(argv, application.verbose_state) == 0) {
return 0;
}
{
int nrInputFiles;
int nrInputColumns;
nrInputFiles = numberInApplicationFilenameList(&application, argv, application.verbose_state);
if(nrInputFiles < 1) {
printerror(application.verbose_state.debug, "ERROR pstat: No files specified");
return 0;
}
if(nrInputFiles > 2) {
printerror(application.verbose_state.debug, "ERROR pstat: Cannot specify more than two input files. %d input files are currently specified.", nrInputFiles);
if(application.verbose_state.debug) {
printerror(0, " These are:");
char *filename_ptr;
for(i = 0; i < nrInputFiles; i++) {
filename_ptr = getNextFilenameFromList(&application, argv, application.verbose_state);
if(filename_ptr != NULL) {
printerror(0, " %s", filename_ptr);
}
}
}
return 0;
}
if(file1_column1 == 0) {
{
printwarning(application.verbose_state.debug, "WARNING pstat: No -col1 option. Using the default (-col1 1).");
file1_column1 = 1;
file1_column2 = 0;
file1_column3 = 0;
}
}
if(nrInputFiles == 2 && file2_column1 == 0) {
{
printwarning(application.verbose_state.debug, "WARNING pstat: No -col2 option, while there are two input files. Default is -col2 1.");
file2_column1 = 1;
file2_column2 = 0;
file2_column3 = 0;
}
}
if(file2_column1 && nrInputFiles != 2) {
printerror(application.verbose_state.debug, "ERROR pstat: -col2 option suggest that there should be two input files, but there is only %d defined on command line.", nrInputFiles);
return 0;
}
nrInputColumns = 0;
if(file1_column1)
nrInputColumns++;
if(file1_column2)
nrInputColumns++;
if(file1_column3)
nrInputColumns++;
if(file2_column1)
nrInputColumns++;
if(file2_column2)
nrInputColumns++;
if(file2_column3)
nrInputColumns++;
if(typetest == KSTEST) {
if(nrInputColumns != 2) {
printerror(application.verbose_state.debug, "ERROR pstat: KS-test requires two columns of data to be read in. Example: pstat -ks -col1 1 -col2 1 file1 file2 or pstat -ks -col \"1 2\" file1");
return 0;
}
}else if(typetest == CORREL) {
if(nrInputColumns != 2) {
printerror(application.verbose_state.debug, "ERROR pstat: Correlation requires two columns of data to be read in. Example: pstat -correl -col1 1 -col2 1 file1 file2 or pstat -correl -col \"1 2\" file1");
return 0;
}
}else if(typetest == PEARSON) {
if(nrInputColumns != 2) {
printerror(application.verbose_state.debug, "ERROR pstat: Correlation requires two columns of data to be read in. Example: pstat -pearson -col1 1 -col2 1 file1 file2 or pstat -pearson -col \"1 2\" file1");
return 0;
}
}else if(typetest == MOMENTS) {
if(nrInputColumns != 1) {
printerror(application.verbose_state.debug, "ERROR pstat: Computation of the moments of a distribution requires one columns of data to be read in. Example: pstat -moments -col 1 file1");
return 0;
}
}else if(typetest == MEDIAN) {
if(nrInputColumns != 1) {
printerror(application.verbose_state.debug, "ERROR pstat: Computation of the median of a distribution requires one columns of data to be read in. Example: pstat -median -col 1 file1");
return 0;
}
}else if(typetest == KSFLAT) {
if(nrInputColumns != 1) {
printerror(application.verbose_state.debug, "ERROR pstat: KS-test comparison with a flat distribution requires one columns of data to be read in. Example: pstat -ksflat -col 1 file1");
return 0;
}
}else if(typetest == KSFLAT_WITH_MINMAX) {
if(nrInputColumns != 1) {
printerror(application.verbose_state.debug, "ERROR pstat: KS-test comparison with a flat distribution requires one columns of data to be read in. Example: pstat -ksflat2 \"0 1\" -col 1 file1");
return 0;
}
}else if(typetest == KSSIN) {
if(nrInputColumns != 1) {
printerror(application.verbose_state.debug, "ERROR pstat: KS-test comparison with a sinusoidal distribution requires one columns of data to be read in. Example: pstat -kssin -col 1 file1");
return 0;
}
}else if(typetest == CHI2TEST_HIST) {
if(nrInputColumns != 4 && nrInputColumns != 6) {
printerror(application.verbose_state.debug, "ERROR pstat: The chi-square histogram test requires four or six columns of data to be read in. Examples: pstat -chi2hist -1 -col1 \"1 2\" -col2 \"1 2\" file1 file2 or pstat -chi2hist -1 -col1 \"1 2 3\" -col2 \"1 2 3\" file1 file2");
return 0;
}
}else if(typetest == CHI2TEST_CDF) {
if(nrInputColumns != 2) {
printerror(application.verbose_state.debug, "ERROR pstat: The chi-square CDF test requires two columns of data to be read in. Examples: pstat -chi2cdf -col1 1 -col2 1 file1 file2 or pstat -chi2cdf -col1 \"1 2\" file1");
return 0;
}
}else {
printerror(application.verbose_state.debug, "ERROR pstat: No statistical test has been specified, nothing to do.");
return 0;
}
}
char *filename_ptr;
double *input_array[6];
long number_values[6];
int number_input_arrays;
number_input_arrays = 0;
number_values[0] = 0;
filename_ptr = getNextFilenameFromList(&application, argv, application.verbose_state);
if(filename_ptr == NULL) {
printerror(application.verbose_state.debug, "ERROR pstat: Bug!");
return 0;
}
if(file1_column1) {
double min_x, max_x, avrg;
if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &number_values[number_input_arrays], file1_column1, 1.0, read_log, &input_array[number_input_arrays], &min_x, &max_x, &avrg, application.verbose_state, 0) == 0) {
printerror(application.verbose_state.debug, "ERROR pstat: cannot load file.\n");
return 0;
}
number_input_arrays++;
}
if(file1_column2) {
double min_x, max_x, avrg;
if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &number_values[number_input_arrays], file1_column2, 1.0, read_log, &input_array[number_input_arrays], &min_x, &max_x, &avrg, application.verbose_state, 0) == 0) {
printerror(application.verbose_state.debug, "ERROR pstat: cannot load file.\n");
return 0;
}
number_input_arrays++;
}
if(file1_column3) {
double min_x, max_x, avrg;
if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &number_values[number_input_arrays], file1_column3, 1.0, read_log, &input_array[number_input_arrays], &min_x, &max_x, &avrg, application.verbose_state, 0) == 0) {
printerror(application.verbose_state.debug, "ERROR pstat: cannot load file.\n");
return 0;
}
number_input_arrays++;
}
if(file2_column1 || file2_column2 || file2_column3) {
filename_ptr = getNextFilenameFromList(&application, argv, application.verbose_state);
if(filename_ptr == NULL) {
printerror(application.verbose_state.debug, "ERROR pstat: Bug!");
return 0;
}
}
if(file2_column1) {
double min_x, max_x, avrg;
if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &number_values[number_input_arrays], file2_column1, 1.0, read_log, &input_array[number_input_arrays], &min_x, &max_x, &avrg, application.verbose_state, 0) == 0) {
printerror(application.verbose_state.debug, "ERROR pstat: cannot load file.\n");
return 0;
}
number_input_arrays++;
}
if(file2_column2) {
double min_x, max_x, avrg;
if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &number_values[number_input_arrays], file2_column2, 1.0, read_log, &input_array[number_input_arrays], &min_x, &max_x, &avrg, application.verbose_state, 0) == 0) {
printerror(application.verbose_state.debug, "ERROR pstat: cannot load file.\n");
return 0;
}
number_input_arrays++;
}
if(file2_column3) {
double min_x, max_x, avrg;
if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &number_values[number_input_arrays], file2_column3, 1.0, read_log, &input_array[number_input_arrays], &min_x, &max_x, &avrg, application.verbose_state, 0) == 0) {
printerror(application.verbose_state.debug, "ERROR pstat: cannot load file.\n");
return 0;
}
number_input_arrays++;
}
FILE *fout;
if(output_idx) {
fout = fopen(argv[output_idx], "w");
if(fout == NULL) {
printerror(application.verbose_state.debug, "ERROR pstat: Cannot open %s", argv[output_idx]);
return 0;
}
}else {
fout = stdout;
}
if(typetest == KSTEST) {
double max_diff, prob;
if(number_input_arrays != 2) {
printerror(application.verbose_state.debug, "ERROR pstat: KS-test requires two input arrays to be specified");
return 0;
}
kstest(input_array[0], number_values[0], input_array[1], number_values[1], 0, 0, 0, NULL, &max_diff, &prob, application.verbose_state);
if(application.verbose_state.verbose == 0) {
fprintf(fout, "probability = %e\n", prob);
}
}else if(typetest == KSFLAT) {
double max_diff, prob;
if(number_input_arrays != 1) {
printerror(application.verbose_state.debug, "ERROR pstat: KS-test comparison with a flat distribution requires one input array to be specified");
return 0;
}
kstest(input_array[0], number_values[0], NULL, 0, 1, 0, 0, NULL, &max_diff, &prob, application.verbose_state);
if(application.verbose_state.verbose == 0) {
fprintf(fout, "probability = %e\n", prob);
}
}else if(typetest == KSFLAT_WITH_MINMAX) {
double max_diff, prob;
if(number_input_arrays != 1) {
printerror(application.verbose_state.debug, "ERROR pstat: KS-test comparison with a flat distribution requires one input array to be specified");
return 0;
}
kstest(input_array[0], number_values[0], NULL, 0, 3, ksflat_min, ksflat_max, NULL, &max_diff, &prob, application.verbose_state);
if(application.verbose_state.verbose == 0) {
fprintf(fout, "probability = %e\n", prob);
}
}else if(typetest == KSSIN) {
double max_diff, prob;
if(number_input_arrays != 1) {
printerror(application.verbose_state.debug, "ERROR pstat: KS-test comparison with a sinusoidal distribution requires one input array to be specified");
return 0;
}
kstest(input_array[0], number_values[0], NULL, 0, 2, 0, 0, NULL, &max_diff, &prob, application.verbose_state);
if(application.verbose_state.verbose == 0) {
fprintf(fout, "probability = %e\n", prob);
}
}else if(typetest == MOMENTS) {
double mean, variance, skew, kurt;
if(number_input_arrays != 1) {
printerror(application.verbose_state.debug, "ERROR pstat: Computation of the moments of a distribution requires one columns of data to be read in.");
return 0;
}
mean = gsl_stats_mean(input_array[0], 1, number_values[0]);
fprintf(fout, "Mean = %e\n", mean);
variance = gsl_stats_variance_m(input_array[0], 1, number_values[0], mean);
fprintf(fout, "Variance = %e (unbiased, normalised by 1/(N-1))\n", variance);
fprintf(fout, "Standard deviation = %e (unbiased, normalised by 1/(N-1))\n", sqrt(variance));
variance *= (number_values[0]-1.0)/(double)number_values[0];
fprintf(fout, "Variance = %e (normalised by 1/N)\n", variance);
fprintf(fout, "Standard deviation = %e (normalised by 1/N)\n", sqrt(variance));
skew = gsl_stats_skew(input_array[0], 1, number_values[0]);
fprintf(fout, "Skewness = %e\n", skew);
kurt = gsl_stats_kurtosis(input_array[0], 1, number_values[0]);
fprintf(fout, "Kurtosis = %e\n", kurt);
}else if(typetest == MEDIAN) {
double median;
if(number_input_arrays != 1) {
printerror(application.verbose_state.debug, "ERROR pstat: Computation of the moments of a distribution requires one columns of data to be read in.");
return 0;
}
gsl_sort(input_array[0], 1, number_values[0]);
median = gsl_stats_median_from_sorted_data(input_array[0], 1, number_values[0]);
fprintf(fout, "Median = %e\n", median);
}else if(typetest == PEARSON) {
double cc;
if(number_input_arrays != 2) {
printerror(application.verbose_state.debug, "ERROR pstat: Correlation requires two input arrays to be specified");
return 0;
}
if(number_values[0] != number_values[1]) {
printerror(application.verbose_state.debug, "ERROR pstat: Correlation requires two input arrays of equal length");
return 0;
}
#if GSL_VERSION_NUMBER >= 110
cc = gsl_stats_correlation(input_array[0], 1, input_array[1], 1, number_values[0]);
fprintf(fout, "Pearson correlation coefficient = %e\n", cc);
#else
printerror(application.verbose_state.debug, "ERROR pstat: Pearson correlation coefficient cannot be calculated if GSL < 1.10");
return 0;
#endif
}else if(typetest == CORREL) {
if(number_input_arrays != 2) {
printerror(application.verbose_state.debug, "ERROR pstat: Correlation requires two input arrays to be specified");
return 0;
}
if(number_values[0] != number_values[1]) {
printerror(application.verbose_state.debug, "ERROR pstat: Correlation requires two input arrays of equal length");
return 0;
}
if(number_values[0] > 2147483646) {
printerror(application.verbose_state.debug, "ERROR pstat: Input array too long.");
return 0;
}
float *x1, *y1;
x1 = malloc(number_values[0]*sizeof(float));
y1 = malloc(number_values[1]*sizeof(float));
if(x1 == NULL || y1 == NULL) {
printerror(application.verbose_state.debug, "ERROR pstat: Memory allocation error");
return 0;
}
for(i = 0; i < number_values[0]; i++)
x1[i] = (input_array[0])[i];
for(i = 0; i < number_values[1]; i++)
y1[i] = (input_array[1])[i];
int extrazeropad, cc_length;
float *ans;
extrazeropad = 0;
if(crosscorrelation_fft_padding(x1, y1, number_values[0], extrazeropad, &ans, &cc_length, application.verbose_state) == 0) {
printerror(application.verbose_state.debug, "ERROR pstat: Cross correlation failed.");
return 0;
}
free(x1);
free(y1);
int lagoutput;
lagoutput = 1;
if(lagoutput == 0) {
for(i = 0; i < cc_length; i++)
fprintf(fout, "%ld %e\n", i, ans[i]);
}else {
for(i = cc_length/2; i <= cc_length-1; i++)
fprintf(fout, "%ld %e\n", i-cc_length, ans[i]);
for(i = 0; i < cc_length/2; i++)
fprintf(fout, "%ld %e\n", i, ans[i]);
}
free(ans);
}else if(typetest == CHI2TEST_HIST) {
double binwidth, ratio, offset, chi2;
long offset_binnr, file2_x_col, dof, i2, nr_overlapping_bins;
if(number_input_arrays != 4 && number_input_arrays != 6) {
printerror(application.verbose_state.debug, "ERROR pstat: The chi-square histogram test requires four or six columns of data to be specified.");
return 0;
}
if(number_input_arrays == 4) {
file2_x_col = 2;
printwarning(application.verbose_state.debug, "WARNING pstat: Since no column numbers with error-bars are provided, uniform weighting of the different bins is assumed with sigma=1. This is unlikely to be correct.");
}else {
file2_x_col = 3;
}
binwidth = (input_array[0])[1] - (input_array[0])[0];
ratio = binwidth/((input_array[file2_x_col])[1] - (input_array[file2_x_col])[0]);
if(application.verbose_state.verbose) {
printf("Ratio bin widths of two histograms is %lf (should be very close to 1)\n", binwidth);
}
if(ratio < 0.999 || ratio > 1.001) {
printerror(application.verbose_state.debug, "ERROR pstat: The binwidths of the two histograms appear to be different (%e != %e).", (input_array[0])[1] - (input_array[0])[0], (input_array[file2_x_col])[1] - (input_array[file2_x_col])[0]);
return 0;
}
offset = (input_array[file2_x_col])[0];
offset -= (input_array[0])[0];
offset /= binwidth;
if(application.verbose_state.verbose) {
printf("Offset between two histograms is %lf bins (should be very close to an integer value)\n", offset);
}
offset_binnr = round(offset);
offset = fabs(offset - offset_binnr);
if(offset > 0.001) {
printerror(application.verbose_state.debug, "ERROR pstat: The bins of the two histograms do not appear to be aligned, but have an offset of %lf.", offset);
return 0;
}
double height1, height2;
height1 = 0;
height2 = 0;
for(i = 0; i < number_values[0]; i++)
height1 += (input_array[1])[i];
for(i = 0; i < number_values[file2_x_col]; i++)
height2 += (input_array[file2_x_col+1])[i];
if(application.verbose_state.verbose) {
printf("Ratio of integrals of two histograms is %lf (should be very close to 1)\n", height1/height2);
}
if(height1/height2 > 1.001 || height2/height1 > 1.001) {
printwarning(application.verbose_state.debug, "WARNING pstat: The two histograms appear to be normalised differently, so the derived numbers are unlikely to give useful results.");
}
chi2 = 0;
dof = 0;
nr_overlapping_bins = 0;
for(i = -labs(offset_binnr)-10; i < number_values[0]+labs(offset_binnr)+10; i++) {
int hist1_exist, hist2_exist;
hist1_exist = hist2_exist = 0;
if(i >= 0 && i < number_values[0]) {
height1 = (input_array[1])[i];
hist1_exist = 1;
}else {
height1 = 0;
}
i2 = i - offset_binnr;
if(i2 >= 0 && i2 < number_values[file2_x_col]) {
height2 = (input_array[file2_x_col+1])[i2];
hist2_exist = 1;
if(hist1_exist) {
offset = (input_array[file2_x_col])[i2];
offset -= (input_array[0])[i];
offset /= binwidth;
if(fabs(offset) > 0.001) {
printerror(application.verbose_state.debug, "ERROR pstat: The bins of the two histograms do not appear to be aligned, but bins %ld and %ld have an offset of %lf.", i+1, i2+1, offset);
return 0;
}
nr_overlapping_bins++;
}
}else {
height2 = 0;
}
if(hist1_exist || hist2_exist) {
if(height1 >= threshold1 && height2 >= threshold2 && (height1+height2) >= threshold3) {
double delta_y, var;
delta_y = height2 - height1;
if(number_input_arrays == 4) {
chi2 += delta_y*delta_y;
dof++;
}else {
var = 0;
if(hist1_exist)
var += (input_array[2])[i] * (input_array[2])[i];
if(hist2_exist)
var += (input_array[file2_x_col+2])[i2] * (input_array[file2_x_col+2])[i2];
chi2 += delta_y*delta_y/var;
dof++;
}
}
}
}
if(nr_overlapping_bins == 0) {
printerror(application.verbose_state.debug, "ERROR pstat: There appears to be no overlap between the two histograms.");
return 0;
}
if(application.verbose_state.verbose) {
printf("Number of overlapping bins between two distributions: %ld\n", nr_overlapping_bins);
printf("Total number of bins considered with specified threshold: %ld\n", dof);
}
if(number_input_arrays != 6)
fprintf(fout, "Total non-weighted chi square: %f = %e\n", chi2, chi2);
else if(application.verbose_state.verbose)
fprintf(fout, "Total chi square: %f = %e\n", chi2, chi2);
if(number_input_arrays == 6) {
fprintf(fout, "Reduced chi square: %f = %e\n", chi2/(double)dof, chi2/(double)dof);
}
}else if(typetest == CHI2TEST_CDF) {
double x1, cdf1, cdf2, chi2;
long start2, dof;
if(number_input_arrays != 2) {
printerror(application.verbose_state.debug, "ERROR pstat: The chi-square CDF test requires two columns of data to be specified.");
return 0;
}
if(number_values[0] > number_values[1]) {
i = number_values[0];
number_values[0] = number_values[1];
number_values[1] = i;
input_array[2] = input_array[0];
input_array[0] = input_array[1];
input_array[1] = input_array[2];
}
gsl_sort(input_array[0], 1, number_values[0]);
gsl_sort(input_array[1], 1, number_values[1]);
start2 = 0;
chi2 = 0;
dof = 0;
for(i = 0; i < number_values[0] - 1; i++) {
cdf1 = (i+1)/(double)number_values[0];
x1 = (input_array[0])[i] + 0.5*((input_array[0])[i+1]-(input_array[0])[i]);
if(application.verbose_state.debug)
printf("Going to find chi2 of observation distribution cdf point: (%e, %e)\n", x1, cdf1);
if(x1 <= (input_array[1])[0]) {
if(application.verbose_state.debug)
printf(" model cdf starts after point of interest\n");
cdf2 = 0;
if(x1 == (input_array[1])[0]) {
cdf2 = (j+0.5)/(double)number_values[1];
}
}else if(x1 >= (input_array[1])[number_values[1]-1]) {
if(application.verbose_state.debug)
printf(" model cdf ends before point of interest\n");
cdf2 = 1;
if(x1 == (input_array[1])[number_values[1]-1]) {
cdf2 = (number_values[1]-1 +0.5)/(double)number_values[1];
}
}else {
for(j = start2; j < number_values[1]; j++) {
if((input_array[1])[j] >= x1) {
if(application.verbose_state.debug)
printf(" First model cdf point after point of interest: (%e %e)\n", (input_array[1])[j], (j+1)/(double)number_values[1]);
long index1, index2;
index1 = j-1;
index2 = j;
if(j == 0) {
printerror(application.verbose_state.debug, "ERROR pstat: Bug!\n");
return 0;
}
while((input_array[1])[index2] == (input_array[1])[index1]) {
if(index2 < number_values[1] - 1) {
index2++;
}else if(index1 > 1) {
index1--;
}else {
printerror(application.verbose_state.debug, "ERROR pstat: Something is wrong with the second input distribution, as all input values appear to be identical.\n");
return 0;
}
}
if(application.verbose_state.debug)
printf(" Going to interpolate following model points: (%e %e) and (%e %e)\n", (input_array[1])[index1], (index1+1-0.5)/(double)number_values[1], (input_array[1])[index2], (index2+1-0.5)/(double)number_values[1]);
if(index1 < 0 || index2 >= number_values[1]) {
printerror(application.verbose_state.debug, "ERROR pstat: Interpolation failed - trying to access second array out of limits (index1=%ld, index2=%ld).\n", index1, index2);
return 0;
}
cdf2 = ((index2+1-0.5)/(double)number_values[1] - (index1+1-0.5)/(double)number_values[1]) * (x1 - (input_array[1])[index1]) / ((input_array[1])[index2] - (input_array[1])[index1]) + (index1+1-0.5)/(double)number_values[1];
if(!isfinite(cdf2)) {
printerror(application.verbose_state.debug, "ERROR pstat: Interpolation failed: i=%ld, j=%ld (array2=[%e, %e, %e]), \n", i, j, (input_array[1])[j-1], (input_array[1])[j], (input_array[1])[j+1]);
return 0;
}
start2 = j - 2;
if(start2 < 0)
start2 = 0;
break;
}
}
}
chi2 += (cdf2-cdf1)*(cdf2-cdf1);
dof++;
if(application.verbose_state.debug) {
printf(" cdf2=%e, cdf1=%e, diff=%e\n", cdf2, cdf1, (cdf2-cdf1));
printf(" new chi2 = %e\n", chi2);
}
}
if(application.verbose_state.verbose) {
printf("\nTotal number of bins considered: %ld\n", dof);
}
fprintf(fout, "Non-weighted total chi square = %f = %e\n", chi2, chi2);
}else {
printerror(application.verbose_state.debug, "ERROR pstat: Bug!");
return 0;
}
if(output_idx) {
fclose(fout);
}
for(i = 0; i < number_input_arrays; i++) {
free(input_array[i]);
}
terminateApplication(&application);
return 0;
}
| {
"alphanum_fraction": 0.6525587602,
"avg_line_length": 46.2430730479,
"ext": "c",
"hexsha": "e9b2fa25a05b1083c2d649bf7e63b97b95b48e83",
"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": "e5074b552d1c404123dee058d5cee79ea230b5a9",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "David-McKenna/psrsalsa",
"max_forks_repo_path": "src/prog/pstat.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9",
"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": "David-McKenna/psrsalsa",
"max_issues_repo_path": "src/prog/pstat.c",
"max_line_length": 755,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "David-McKenna/psrsalsa",
"max_stars_repo_path": "src/prog/pstat.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 10155,
"size": 36717
} |
/*************************************************************************
description:
This file contains the class that can do the actual radiative transport,
including routines for grid calculation, physics and the actual transport
Copyright Jan-Pieter Paardekooper and Chael Kruip October 2011
This file is part of SimpleX.
SimpleX 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.
SimpleX 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 SimpleX. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#ifndef SIMPLEX_H
#define SIMPLEX_H
#ifndef NOMPI
#include "mpi.h"
#endif
#include "rates.h"
#include "Common.h"
#include "Structs.h"
#include <gsl/gsl_rng.h> //random number generator
#include "configfile.h" //keyvalue input file
#ifdef HEAL_PIX
#include "healpix_base.h" //healpix header
#endif
#include "tree_structures.h" //octree
#include "hilbert.h" //hilbert curve
#include "h5w_serial.h" //hdf5 header
#include <algorithm>
#if defined(__cplusplus)
extern "C"
{
#endif
#include <stdio.h>
#include <stdlib.h>
#include <libqhull.h>
#include <mem.h>
#include <qset.h>
#include <geom.h>
#include <merge.h>
#include <poly.h>
#include <io.h>
#include <stat.h>
#if defined(__cplusplus)
}
#endif
using namespace std;
#define VERTEX_ITERATOR vector< Vertex >::iterator
#define SITE_ITERATOR vector< Site >::iterator
#define SIMPL_ITERATOR vector< Simpl >::iterator
//! Class in which all functions that work on the SimpleX grid are stored
//! This is the main class of the simulation!
class SimpleX{
public:
//! constructor
SimpleX(const string& output_path = ".", const string& data_path = ".");
//! destructor
~SimpleX();
//================ Grid Initilisation Functions ==================================//
//! Create triangulation
//! Initialize the simulation by creating/reading the vertex list and compute the triangulation
//! Result is a list of Sites and a list of Simplices
void init_triangulation(char* inputName);
//TEST
void reinit_triangulation();
//END TEST
//! Read in parameter file
void read_parameters( char* inputName );
//! Create orientations and mappings from correct header file
void set_direction_bins();
//! Create a simple homogeneous point distribution
//! Points are placed using the gsl randoom number generator
void poisson_square();
//! Read in hdf5 file with site information
void read_vertex_list();
//! Compute the largest index of all the vertices
unsigned long long int computeMaxId();
//! Create boundary around computational domain
//! Width of the boundary is variable borderBox.
//! Number of points in the boundary is variable borderSites.
void create_boundary();
//!Create octree containing all vertices
//!Size of the tree depends on the number of subboxes used, which
//!is determined by the hilbert order m
void create_vertex_tree();
//! Decompose the domain
//! Count the number of sites contained in one subbox and add those until
//! number of points is approximately equal per processor
void decompose_domain();
//! Assign the correct process to vertices
void assign_process();
//! Check if site is in unit domain
bool inDomain(const float& x, const float& y, const float& z, const unsigned int& rank);
//! Compute the triangulation
//! Call to QHull to perform the triangulation of vertices in one subbox
//! The result is a vector of simplices
//! Also, a check is done whether the subbox and domain boundaries are
//! sufficiently large. If not, subbox boundaries are extended. If the
//! boundary around the unity domain is too small, the code exits,
//! to avoid memory issues when this number would be increased
void compute_triangulation();
//! Create the sites array on which radiative transfer is performed
//! From the list of simplices the vertices relevant for this proc are selected and
//! put in the sites vector
void create_sites();
//! Give each site an id corresponding to place in local sites vector
void assign_site_ids();
//! Determine which sites use ballistic transport and which sites
//! should use direction conserving transport at the start of the
//! simulation.
void initiate_ballistic_sites();
//! Shuffle list of sites
//! This is necessary since the sites list is created from the simplices returned by QHull,
//! so they are ordered.
void shuffle_sites();
//================ Site Properties Functions ==================================//
//! Compute properties of the sites from the triangulation
//! Important properties like the neighbours, the volumes and
//! the most straight paths are computed
void compute_site_properties();
//! Compute the neighbours of vertex
//! Generate the neighbour vectors for each vertex from the simplex vector
//! Care should be taken so that no vertex is put twice in the neighbour list.
//! Also get rid of vertices in the sub box boundary that are not connected to a site
//! in the computational domain
void compute_neighbours();
//! Compute the volume of the Voronoi cell
//! Use the volumes of the simplices that the vertex is part of to compute
//! the volume of the Voronoi cell around the vertex
void compute_volumes();
//! Calculate the most straight paths for every incoming direction
//! Needed for fast radiative transport
void calculate_straight();
//! Identify the place of every ballistic site in neighbour array
//! of neighbouring site
void match_neighbours();
//! Compute the solid angles into which the intensity is distributed
void compute_solid_angles( const bool& rotate );
//! Check for cyclic connections in the grid and remove them if possible
void check_cyclic_connections();
//! Calculate mean distance to neighbours
void calculate_line_lengths();
//! Create list without border simplicesc
void remove_border_simplices();
//================ Grid Update Routines ============================//
//! Rotate the solid angles of the unit sphere
//! to avoid preferential directions
void rotate_solid_angles();
//! calculate normal distributed random numbers using the Box-Muller transformation
void randGauss( float& y1, float& y2 );
//! Store the intensities for use in later run, directions are kept.
void store_intensities();
//! Get the ballistic sites that have intensity to be stored
const vector< unsigned long int > get_ballistic_sites_to_store();
//! Store ballistic intensities in unit sphere tesselation
void store_ballistic_intensities( const vector< unsigned long int >& sites_to_store );
//! Return the intensities from the previous run
void return_intensities();
//! Return the intensities to ballistic sites
void return_ballistic_intensities();
//! Check which sites are ballistic and which not
//! according to user specified switch
//! Only used is case of combined transport
void check_ballistic_sites();
//! Create new sites array without the removed sites
void store_site_properties();
//! Create updated vertex list from site_properties vector
void create_new_vertex_list();
//================ Send Routines ===================================//
//! Send vertices to processors
void send_vertices();
//! Send the domain decomposition to all procs
void send_dom_dec();
//! Fill the list of indices of sites that contain information to be send
//! to other procs
void fill_send_list();
//! Give every vertex its correct process (needed for vertices in boundary between procs)
void send_site_properties();
//! Give every ballistic site its correct neighbour information
//! This is only needed for ballistic sites in boundary between procs, and is necessary because
//! the order of the neighbours in the neighbour vector is not the same among procs.
void send_neighbour_properties();
//! Send teh updated ballistic sites to all procs
void send_site_ballistics( const vector< unsigned long int >& sites_to_send );
//! Send the intensities among procs
void send_intensities();
//! Send site physics to all procs
//! In case sites change from proc send physics
void send_site_physics();
//! In case sites change from proc send intensities
void send_site_intensities();
//! Send stored intensities among procs
void send_stored_intensities();
//! Send the updated vertex list to all procs
void send_new_vertex_list();
//================ Physics Functions ==================================//
//! Compute all the physics needed to do radiative transport
void compute_physics( const unsigned int& run );
//! Initialize physical parameters
void initialise_physics_params();
//! Read metal line cooling data and initialize vectors
void read_metals();
//! set homogeneous number density.
//! Use only in combination with Poisson_Square()
void set_homogeneous_number_density( const float& nH );
//! Give the masses and fluxes that were read in to the sites
//! Use only in combination with read_vertex_list()
void assign_read_properties();
//! Give the updates sites their correct physical quantities from stored values
void return_physics();
//! Calculate the bounds of the frequency bins
vector<double> calc_freq_bounds( const double& lowerBound, const double& upperBound );
//! calculate effective cross section and spectrum of black body source
void black_body_source( const double& tempSource );
//! Compute the total number of atoms on this proc, used for output
void output_number_of_atoms();
//! Return mean optical depth of total grid
double output_optical_depth();
//! output relevant physical parameters to screen
void parameter_output( const unsigned int& run );
//! Add more neighbours to vertices that have a flux, by adding the neighbours
//! of neighbours.
void make_source_isotropic();
//! calculate recombination
double recombine();
//! Rate of energy loss in cell
double cooling_rate( Site& site );
//! Rate of energy gain in cell
double heating_rate( const vector<double>& N_ion, const double& t_end );
//! compute mean molecular weight
double compute_mu( Site& );
//!Convert internal energy to temperature
double u_to_T( const double& u, const double& mu );
//!Convert temperature to internal energy
double T_to_u( const double& T, const double& mu );
//! update the temperature by including heating and cooling processes
double update_temperature( Site& site, const vector<double>& N_ion, const double& t_end );
//================= Radiative Transfer Functions ======================//
//! Solve the rate equation to determine ionisations and recombinations
vector<double> solve_rate_equation( Site& site );
//! Send source photons
void source_transport( Site& site );
//! Transport photons diffusely
void diffuse_transport( Site& site, vector<double>& N_out_total );
//! Redistribute intensity: actual radiative transport
void non_diffuse_transport( Site& site, vector<double>& N_out_total );
//! Call to do radiative transfer
void radiation_transport( const unsigned int& run );
//================== Output Functions ================================//
//! Call the output routines
void generate_output( const unsigned int& run );
//! Write hdf5 output file
void write_hdf5_output(char* name, const unsigned int& run);
//! calculate position of the I-Front for source in centre
double calc_IFront( const unsigned int& run );
//! calculate escape fraction
double calc_escape_fraction( const unsigned int& run, const unsigned int& times );
//================ Generic Functions ==============================//
//! clear all temporary structures for the next run
void clear_temporary();
//! Function to give diagnostic output about total number of photons in simulation
double count_photons();
//! return number of runs
const unsigned int& get_numRuns() const{ return numRuns; }
//! Return number of outputs
const unsigned int& get_numOutputs() const{ return numOutputs; }
// ================ Public lists and variables ===================//
//! List of vertices that will be used to perform triangulation
vector< Vertex > vertices;
//! List of sites for doing radiative transfer
vector< Site > sites;
//! Vector holding the domain decomposition
vector< unsigned int > dom_dec;
//! List of sites from the previous run, whose properties are still needed
vector< Site_Update > site_properties;
//! List of entries in site_intensities array of every site
vector<unsigned long int> intens_ids;
//! List of site intensities from previous run, that are still needed
vector<float> site_intensities;
//! List of indices of sites needed for transport along procs
vector< unsigned long int > send_list;
//! List of site indices that might be removed
vector< unsigned long int > sites_marked_for_removal;
//! List of sites and properties to be updated
vector< Site_Remove > total_sites_marked_for_removal;
//! List of simplices that results from the QHull call
vector< Simpl > simplices;
//! Temporary list of neutral number densities that are read in
vector< float > temp_n_HI_list;
//! Temporary list of ionised number densities that are read in
vector< float > temp_n_HII_list;
//! Temporary list of fluxes that are read in
vector< float > temp_flux_list;
//! Temporary list of internalEnergies that are read in
vector< float > temp_u_list;
//! Temporary list of dudt that are read in
vector< float > temp_dudt_list;
//! Temporary list of clumping factors that are read in
vector< float > temp_clumping_list;
//! Temporary list of metallicity
vector<float> temp_metallicity_list;
//! Cross section of hydrogen
vector<double> cross_H;
//! The photon excess energy used to heat the gas
vector<double> photon_excess_energy;
//! The elemental abundances of metals (and Helium)
vector<double> abundances;
//! Vector of cooling curves
vector< cooling_curve > curves;
//! Variable used by random number generator
gsl_rng * ran;
//! Output to logfile
ofstream simpleXlog;
protected:
unsigned long int numSites; //!< Total number of sites in the simulation
unsigned long int origNumSites; //!< Original number of sites
unsigned int borderSites; //!< Number of sites in the boundary around computational domain
unsigned int hilbert_order; //!< Hilbert order that determines the number of subboxes
unsigned int numSweeps; //!< Number of grid sweeps during simulation
unsigned int numRuns; //!< Number of runs of the simulation
unsigned int numOutputs; //!< Number of outputs of the simulation
unsigned int numPixels; //!< Number of pixels in HEALPix calculation
unsigned int numStraight; //!< Number of straight directions
int randomSeed; //!< Seed for random number generator
short dimension; //!< Dimension of the simulation (default = 3)
string inputFileName; //!< File which holds densities and fluxes to be read in
string dataPath; //!< Path where the metal line cooling tables are
bool blackBody; //!< Use blackbody for source spectrum?
bool recombination; //!< Include recombination or not
bool rec_rad; //!< Include recombination radiation or not
bool coll_ion; //!< Include collisional ionisations?
bool heat_cool; //!< Include heating and cooling?
bool metal_cooling; //!< Include metal line cooling?
short int numFreq; //!< Number of frequencies
short int freq_spacing; //!< Spacing of the frequency bins
short RTmethod; //!< Method for RT
bool diffuseTransport; //!< Set this to 1 to do only ballistic transport
bool ballisticTransport; //!< Set this to 1 to do only ballistic transport
bool dirConsTransport; //!< Set this to 1 to do only direction conserving transport
bool combinedTransport; //!< Set this to 1 to do combined transport
bool photon_conservation; //!< Use temporal photon conservation scheme or not?
double subcycle_frac; //!< Fraction of the characteristic time scale at which subcycling is done
double sizeBox; //!< Size of the box in parsec
float borderBox; //!< Size of boundary around computational domain
float padding_subbox; //!< Subbox boundary in which extra points are triangulated
double simTime; //!< Total simulation time in Myr
double time_conversion; //!< Time conversion for output
double sourceTeff; //!< Effective temperature of the sources in K
double gasIonTemp; //!< Temperature of the ionised gas in K
double gasNeutralTemp; //!< Temperature of the neutral gas in K
double switchTau; //!< Optical depth below which ballistic transport is no longer trusted
double totalVolume; //!< Total volume of all Voronoi cells added up
double totalAtoms; //!< Total number of atoms in the simulation domain
int localMaxRes; //!< Maximum resolution on the local processor
unsigned int COMM_RANK; //!< Rank of this proc
unsigned int COMM_SIZE; //!< Total number of procs
unsigned int chunk_size; //!< Maximum size of chunks written in one piece to hdf5 file
unsigned int max_msg_to_send; //!< Maximum number of messages to send in MPI call
unsigned long int vertex_id_max; //!< Maximum vertex index
short int orientation_index; //!< Orientation of the unit sphere tesselation
short int orientation_index_old; //!< Orientation of the unit sphere tesselation in previous run
float euler_phi; //!< Euler angle phi for random rotation of coordinate system
float euler_theta; //!< Euler angle theta for random rotation of coordinate system
float euler_psi; //!< Euler angle psi for random rotation of coordinate system
bool heal_pix; //!< Use heal_pix for associating directions and neighbours or not?
int num_ref_pix_HP; //!< Number of pixels to use for associating neighbours in compute_solid_angles()
float straightAngle; //!< Maximum angle allowed between straight direction and Delaunay direction.
bool straight_from_tess; //!< In DCT, calculate straightest neighbours wrt Delaunay edge or direction bin?
double UNIT_L; //!< Unit length in box
double UNIT_M; //!< Unit mass in box, converts number density into number of atoms
double UNIT_I; //!< Unit number of ionising photons in box
double UNIT_T; //!< Time of 1 sweep in seconds
double UNIT_T_MYR; //!< Time of 1 sweep in Myr
double UNIT_D; //!< Unit number density
double UNIT_V; //!< Unit volume
float straight_correction_factor; //!< Correction factor to correct for the fact that no straight lines exist on the grid
vertex_tree vert_tree; //!< Octree that will contain the vertices
bool give_IFront; //!< Calculate IFront position for a source in centre?
ofstream IFront_output; //!< Output of IFront data to file
float*** orient; //!< Array to hold the direction bins
unsigned int*** maps; //!< Array to hold the mappings between direction bins
unsigned int number_of_directions; //!< Number of discretizations of the unit sphere for DCT
unsigned int number_of_orientations;//!< Number of random rotations of the DCT discretization
};
#endif
| {
"alphanum_fraction": 0.6711671024,
"avg_line_length": 38.3151183971,
"ext": "h",
"hexsha": "97cba342ca031f998462c166ae25bcf6b40b29b2",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z",
"max_forks_repo_head_hexsha": "c2034074ee76c08057c4faa96c32044ab40952e9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "joshuawall/amuse",
"max_forks_repo_path": "src/amuse/community/simplex/src/src/SimpleX.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c2034074ee76c08057c4faa96c32044ab40952e9",
"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": "joshuawall/amuse",
"max_issues_repo_path": "src/amuse/community/simplex/src/src/SimpleX.h",
"max_line_length": 125,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c2034074ee76c08057c4faa96c32044ab40952e9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "joshuawall/amuse",
"max_stars_repo_path": "src/amuse/community/simplex/src/src/SimpleX.h",
"max_stars_repo_stars_event_max_datetime": "2019-04-09T09:06:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-04-09T09:06:08.000Z",
"num_tokens": 4359,
"size": 21035
} |
#include <stdio.h>
#include <gsl/gsl_blas.h>
int main()
{
double a[] = { 0.11, 0.12, 0.13,
0.21, 0.22, 0.23 };
double b[] = { 1011, 1012,
1021, 1022,
1031, 1032 };
double c[] = { 0.00, 0.00,
0.00, 0.00 };
gsl_matrix_view A = gsl_matrix_view_array(a, 2, 3);
gsl_matrix_view B = gsl_matrix_view_array(b, 3, 2);
gsl_matrix_view C = gsl_matrix_view_array(c, 2, 2);
gsl_matrix *D = gsl_matrix_alloc(2, 3);
int i, j;
for (i=1; i<3; i++)
for (j=1; j<4; j++)
gsl_matrix_set (D, i-1, j-1, ((float) i)/10 + ((float) j)/100);
for (i=0; i<2; i++)
for (j=0; j<3; j++)
printf("D(%d,%d) = %f\n", i, j, gsl_matrix_get(D, i, j));
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans,
1.0, D, &B.matrix,
0.0, &C.matrix);
printf ("[ %g, %g\n", c[0], c[1]);
printf (" %g, %g ]\n", c[2], c[3]);
return 0;
}
| {
"alphanum_fraction": 0.4861407249,
"avg_line_length": 24.0512820513,
"ext": "c",
"hexsha": "58ff15383212cedf0ce62763b73c3ad0e1fa7b83",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-02-25T06:53:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-04-21T08:25:26.000Z",
"max_forks_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tcrundall/chronostar",
"max_forks_repo_path": "benchmarks/matrix_library_tests/gslProduct.c",
"max_issues_count": 13,
"max_issues_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_issues_repo_issues_event_max_datetime": "2021-11-08T23:44:29.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-08-14T07:30:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tcrundall/chronostar",
"max_issues_repo_path": "benchmarks/matrix_library_tests/gslProduct.c",
"max_line_length": 69,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tcrundall/chronostar",
"max_stars_repo_path": "benchmarks/matrix_library_tests/gslProduct.c",
"max_stars_repo_stars_event_max_datetime": "2021-05-14T01:13:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-05-28T11:05:42.000Z",
"num_tokens": 385,
"size": 938
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <builtin_types.h>
#include "intT.h"
#include <fenv.h>
#include <signal.h>
//electron mass squared
double m2 = 1.0;
//electron charge
double e = 0.30282212;
//double m2=1.0;
//double e=1.0;
double EV(double T, void * p, int* WLlist);
double Exact(double T, double B, int fermion)
//Return the exact integrand for constant fields
{
double TB = e*T*B;
double Exact;
if( B < 1.0e-40)
Exact = 0.0;
else
if(fermion == 1)
Exact = exp(-m2*T)/(T*T*T)*(TB/tanh(TB)-1.0-1.0/3.0*TB*TB);
else
if (TB < 50.0)
Exact = exp(-m2*T)/(T*T*T)*(TB/sinh(TB)-1.0+1.0/6.0*TB*TB);
else
Exact = exp(-m2*T)/(T*T*T)*(1.0/6.0*TB*TB-1.0);
//printf("%f %e\n",T, exp(-T));
return Exact;
}
double bumpd(double x)
//The bump function
{
if (abs(x) < 1.0)
return exp(-1.0/(1.0-x*x));
else
return 0.0;
}
double fixfluxB(double rho2, double lambda2)
//Magnetic field strength for the fixflux profile
{
float l = sqrt(lambda2);
float lmlmin = (l - lmin)/(tubedist - lmin);
if(sqrt(rho2) > tubedist/2.0) printf("Warning: inappropriate magnetic field being used. rho=%f\n", sqrt(rho2));
return 2.0/(lambda2*q2)*(1.0-0.75*lmlmin)*bumpd(2.0*sqrt(rho2/lambda2))
+ 3.0/(tubedist*tubedist)*lmlmin;
}
double periodicB(double rho2, double lambda2)
//magnetic field for the periodic flux tube profile
{
double expr, rho, lambda, flraf, f, ceilraf;
double expral, exprapl;
rho = sqrt(rho2);
lambda = sqrt(lambda2);
expr = exp(-rho/lambda);
flraf = floor(rho/tubedist);
ceilraf = ceil(rho/tubedist);
if(rho < tubedist)
{
expral = 0.0;
if((tubedist-rho)/lambda < 10.0)
expral = exp(-(rho-tubedist)/lambda);
f = expr/(tubedist*(1.0 + expr)*(1.0 + expr));
if(rho > 0.0)
f += expral/(rho*(1.0+expral)*(1.0+expral));
}
else
{
if(abs(fmod(rho,tubedist)) < 1.0e-6)
{
f = flraf/(4.0*rho);
}
else
{
expral = exp(-(rho-flraf*tubedist)/lambda);
exprapl = exp(-(rho-ceilraf*tubedist)/lambda);
f = flraf*expral/(rho*(1.0+expral)*(1.0+expral)) +
ceilraf*exprapl/(rho*(1.0+exprapl)*(1.0+exprapl));
}
}
//f=1.0f/lambda2*exp(-1.0f*rho2/lambda2);
//f=lambda2/8.0f;
f=tubedist/(2.0*log(2.0)*lambda2)*f;
//f=1.0;
return f;
}
double MagField(double rho2, void* p)
//Compute the magnetic field.
{
double B;
double sinrho;
struct Wparams *params = (struct Wparams *) p;
switch(profile){
case step:
if(rho2<params->l2)
B=1.0/params->l2;
else
B=0.0;
break;
case smooth:
B=params->l2/((params->l2+rho2)*(params->l2+rho2));
break;
case quadratic:
if(rho2<params->l2)
B=2.0/params->l2*(1.0-rho2/params->l2);
else
B=0.0;
break;
case gaussian:
if(rho2<100.0*params->l2)
B=1.0/(params->l2*exp(rho2/params->l2));
else
B=0.0;
break;
case periodic:
B=periodicB(rho2,params->l2);
break;
case spline:
sinrho=sin(pi*sqrt(rho2)/tubedist);
B=1.0/(params->l2*exp(sinrho*sinrho/params->l2));
break;
case fixflux:
B = fixfluxB(rho2,params->l2);
break;
}
B=2.0*params->F/e*B;
return B;
}
double smTscal(double B, double T)
//Effective action for T<<1.0 for scalar QED
{
double B2=e*e*B*B;
double B4=B2*B2;
double B6=B2*B4;
double T2=T*T;
double T3=T2*T;
double T4=T3*T;
double result;
result = 7.0/360.0*B4*T*(1.0-m2*T)+(147.0*B4*m2*m2-31.0*B6)/15120.0*T3
+(31.0*B6*m2-49.0*B4*m2*m2*m2)/15120.0*T4;
return result;
}
double smTferm(double B, double T)
//Effective action for T<<1.0 for fermionic QED
{
double B2=e*e*B*B;
double B4=B2*B2;
double B6=B2*B4;
double T2=T*T;
double T3=T2*T;
double T4=T3*T;
double result;
result = 1.0/45.0*B4*T*(m2*T-1.0) + (2.0*B6/945.0 - B4*m2*m2/90.0)*T3
+(7.0*B4*m2*m2*m2-4.0*B6*m2)/1890.0*T4;
//result = 1.0/45.0*B4*T*(T-1.0) + (2.0*B6/945.0 - B4/90.0)*T3
// +(7.0*B4-4.0*B6)/1890.0*T4;
return result;
}
double meanigrand(double* igrand, int ngroups, double* igranderr)
//compute the mean and std. err. for igrand
{
double meanig=0.0;
int i;
*igranderr=0.0;
for(i=0;i<ngroups;i++)
{
meanig+=igrand[i];
}
meanig/=ngroups;
for(i=0; i < ngroups; i++)
{
*igranderr+=(igrand[i]-meanig)*(igrand[i]-meanig);
}
*igranderr = sqrt(*igranderr);
*igranderr /= ngroups;
return meanig;
}
double* Tfunc(double T, void* p, int* order)
//The integrand of the proper time, T, integral
{
struct Wparams *params = (struct Wparams *) p;
double rho2 = params->xcm.x*params->xcm.x + params->xcm.y*params->xcm.y;
double smallT;
double B;
double TB;
double* igrand = malloc(params->ng*sizeof(*igrand));
int groupsize = 128; //loops per group
int* WLlist = malloc(groupsize*sizeof(*WLlist));
int i, j;
double rho = params->xcm.x;
double l2 = params->l2;
double sin2rho = sin(2.0*pi*rho/tubedist);
double denominator;
double igmean; double igerr;
if(!igrand || !WLlist) printf("error Tfunc(): malloc failed\n");
//printf("func: T=%f\n",T);
B=MagField(rho2,p);
TB=e*T*B;
//printf("T=%f f'/f''=%f\n",T,(params->l2+params->xcm.x*params->xcm.x));
//determine a suitable definition for small T
switch(profile)
{
case step:
smallT=abs(rho*rho-l2);
break;
case smooth:
smallT= 0.5*(l2+rho*rho);
break;
case quadratic:
smallT= 0.5*(l2+rho*rho);
break;
case gaussian:
smallT=l2;
break;
case periodic:
smallT=0.5*(l2+rho*rho);
break;
case spline:
if(rho/tubedist>1.0e-8)
smallT=tubedist*tubedist*l2/(pi*pi*sin2rho*sin2rho);
else
smallT=1.0e12;
break;
case fixflux:
//small if T << l2, or if the loop is far from any bump functions.
if(rho*rho<l2/4.0)
smallT = 0.25*l2;
else
smallT = 0.25*l2+(rho-sqrt(l2)/2.0)*(rho-sqrt(l2)/2.0);
}
for(i = 0; i < params->ng; i++)
{
//printf("func igrand[%d]=%f\n",i,igrand[i]);
if(T < 0.1 && T < 0.01*smallT)
//if(T<0.7)
{
if(verbosity >= 2)
printf("using small T expression: %f %f %f\n", rho2, T, smallT);
if(params->fermion == 1)
igrand[i] = smTferm(B, T);
else
igrand[i] = smTscal(B, T);
}
else if(T < 0.01*smallT)
//use the exact expression
{
if(verbosity >= 2)
printf("using const. field expression %f %f %f\n", rho2, T, smallT);
if(TB > 1.0e-6)
igrand[i] = Exact(T, B, params->fermion);
else
igrand[i] = 0.0;
}
else if(T > 49.0)
//for large T, the contribution is exponentially supressed.
{
if(verbosity >= 2)
printf("using large T expression %f %f %f\n", rho2, T);
if(params->fermion==1)
{
igrand[i]=-1.0*exp(-m2*T)/(3.0*T)*e*e*B*B;
//if(B>1e-6)
// igrand[i]=exp(-m2*T)/(T*T*T)*(TB/tanh(TB)-1.0-1.0/3.0*TB*TB);
//else
// igrand[i]=0.0;
//printf("igrand(%f)=%f\n",T,igrand[i]);
}
else
igrand[i]=exp(-m2*T)/(6.0*T)*e*e*B*B;
}
else
{
for(j=0;j<groupsize;j++)
{
//printf("func j=%d\n",j);
WLlist[j]=order[j + i*groupsize];
}
if(verbosity >= 3)
printf("EV= %e Exact = %e\n",EV(T,p, WLlist),T/sinh(T));
if(params->fermion==1)
igrand[i]= exp(-m2*T)/(T*T*T)*(EV(T, p, WLlist)-1.0-1.0/3.0*TB*TB);
else
igrand[i]= exp(-m2*T)/(T*T*T)*(EV(T, p, WLlist)-1.0+1.0/6.0*TB*TB);
//igrand[i]=Exact(T,1.0);
//return Exact(T,1.0);
}
}
if(T > 0.0f && verbosity >= 2){
igmean = meanigrand(igrand, params->ng, &igerr);
printf("WLvconstExpression: ");
printf("%e %e %e %e %e %e\n",
rho2, T, Exact(T, B, params->fermion), smTscal(B, T), igmean, igerr);
}
free(WLlist);
return igrand;
}
void signal_handler(int sig)
//Floating point signal handler
{
printf( "Error: Floating point signal detected.\n");
exit(1);
}
void EVMean(double *EV, float4 *Wsscal_h, float4 *Wsferm_h, int n, int *WL, double T, int fermion)
//Compute the expectation value and error of the Wilson loops
//WL is a list representing a group of wordline indices
//to compute the expectation value of
{
int i, WLi;
double EVWlNb2, EVWlN, EVWlNb4;
double SEWlNb2, SEWlN, SEWlNb4;
double *EVpart1;
double *EVpart2;
double *EVpart4;
double Nby4part;
//Turn on floating point exceptions:
feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW | FE_UNDERFLOW);
// Set the signal handler:
signal(SIGFPE, signal_handler);
*EV = 0.0;
EVWlNb2 = 0.0; EVWlN = 0.0; EVWlNb4 = 0.0;
//allocate arrays to store the wilson loop of each worldline
EVpart1 = (double *) malloc(n*sizeof(*EVpart1));
EVpart2 = (double *) malloc(n*sizeof(*EVpart2));
EVpart4 = (double *) malloc(n*sizeof(*EVpart4));
if(!EVpart1 || !EVpart2 || !EVpart4) printf("EVonly(): malloc failed\n");
//determine the sum of the contributions
for(i = 0; i < n; i++){
WLi=WL[i];
//Compute the scalar part
Nby4part = Wsscal_h[WLi].y + Wsscal_h[WLi].z;
EVpart1[i] = cos(0.5*Wsscal_h[WLi].x+0.25*(Nby4part));
EVpart2[i] = cos(Wsscal_h[WLi].x);
EVpart4[i] = cos(0.5*(Nby4part));
if(fermion == 1)
{
if(isinf(Wsferm_h[WLi].x) !=0 ||isinf(Wsferm_h[WLi].y) !=0 ||isinf(Wsferm_h[WLi].z) !=0
|| isnan(Wsferm_h[WLi].x) !=0 || isnan(Wsferm_h[WLi].y) !=0 ||isnan(Wsferm_h[WLi].z) !=0 )
{
printf("Warning: WSferm is infinite. Worldline=%d\n",WLi);
}
//Compute the fermion part
//printf("Wsferm_h[%d].x=%f\n",WLi,Wsferm_h[WLi].x);
//printf("Wsferm_h[%d].y=%f\n",WLi,Wsferm_h[WLi].y);
//printf("Wsferm_h[%d].z=%f\n",WLi,Wsferm_h[WLi].z);
Nby4part = Wsferm_h[WLi].y+Wsferm_h[WLi].z;
if(abs(Nby4part) > 600.0 | abs(Wsferm_h[WLi].x) > 600.0)
{
printf("Warning: Large cosh argument. T=%f, WLi=%d\n",T,WLi);
EVpart1[i] *= 1.0e10;
EVpart2[i] *= 1.0e10;
EVpart4[i] *= 1.0e10;
}
else
{
EVpart1[i] *= cosh(0.5*(double)Wsferm_h[WLi].x+0.25*((double)Nby4part));
EVpart2[i] *= cosh((double)Wsferm_h[WLi].x);
EVpart4[i] *= cosh(0.5*((double)Nby4part));
//EVpart1[i]*=cosh(T);
//EVpart2[i]*=cosh(T);
//EVpart4[i]*=cosh(T);
}
if(isnan(EVpart1[i]) != 0 || isnan(EVpart2[i]) != 0 || isnan(EVpart4[i]) != 0
|| isinf(EVpart1[i]) != 0 || isinf(EVpart2[i]) != 0 || isinf(EVpart4[i]) != 0)
printf("Warning: Infinity detected: WL# %d\n",WLi);
}
EVWlNb4 += EVpart4[i];
EVWlNb2 += EVpart2[i];
EVWlN += EVpart1[i];
//printf("EVpart1[%d]=%f\n",i,EVpart1[i]);
}
EVWlNb4 /=n;
EVWlNb2 /=n;
EVWlN /=n;
//Extrapolate to N=infinity
*EV=8.0/3.0*EVWlN - 2.0*EVWlNb2 + 1.0/3.0*EVWlNb4;
free(EVpart1);
free(EVpart2);
free(EVpart4);
}
| {
"alphanum_fraction": 0.5912857276,
"avg_line_length": 26.1975609756,
"ext": "c",
"hexsha": "a4e2a0b0e5fac134a1eb53df5be4acec9da03243",
"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": "81cdf2bbb91e50cfe60e0ed81e6c93079a176cc8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "QEDan/Worldline-Flux-Tube-Lattice",
"max_forks_repo_path": "Integrand.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "81cdf2bbb91e50cfe60e0ed81e6c93079a176cc8",
"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": "QEDan/Worldline-Flux-Tube-Lattice",
"max_issues_repo_path": "Integrand.c",
"max_line_length": 157,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "81cdf2bbb91e50cfe60e0ed81e6c93079a176cc8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "QEDan/Worldline-Flux-Tube-Lattice",
"max_stars_repo_path": "Integrand.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4316,
"size": 10741
} |
#ifndef CTETRA_NUMSTATES_H
#define CTETRA_NUMSTATES_H
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_vector.h>
#include "input.h"
#include "submesh.h"
#include "ecache.h"
#include "tetra.h"
double NumStates(double E, EnergyCache *Ecache);
double NumStatesContrib(double E, double E1, double E2, double E3, double E4, double num_tetra);
#endif // CTETRA_NUMSTATES_H
| {
"alphanum_fraction": 0.7619047619,
"avg_line_length": 22.2352941176,
"ext": "h",
"hexsha": "f58841333521df7d463a6f7a2a8f178882fed210",
"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": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tflovorn/ctetra",
"max_forks_repo_path": "numstates.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tflovorn/ctetra",
"max_issues_repo_path": "numstates.h",
"max_line_length": 96,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tflovorn/ctetra",
"max_stars_repo_path": "numstates.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 111,
"size": 378
} |
#ifndef OPENMC_TALLIES_FILTER_ENERGY_H
#define OPENMC_TALLIES_FILTER_ENERGY_H
#include <gsl/gsl>
#include "openmc/tallies/filter.h"
#include "openmc/vector.h"
namespace openmc {
//==============================================================================
//! Bins the incident neutron energy.
//==============================================================================
class EnergyFilter : public Filter {
public:
//----------------------------------------------------------------------------
// Constructors, destructors
~EnergyFilter() = default;
//----------------------------------------------------------------------------
// Methods
std::string type() const override { return "energy"; }
void from_xml(pugi::xml_node node) override;
void get_all_bins(const Particle& p, TallyEstimator estimator,
FilterMatch& match) const override;
void to_statepoint(hid_t filter_group) const override;
std::string text_label(int bin) const override;
//----------------------------------------------------------------------------
// Accessors
const vector<double>& bins() const { return bins_; }
void set_bins(gsl::span<const double> bins);
bool matches_transport_groups() const { return matches_transport_groups_; }
protected:
//----------------------------------------------------------------------------
// Data members
vector<double> bins_;
//! True if transport group number can be used directly to get bin number
bool matches_transport_groups_ {false};
};
//==============================================================================
//! Bins the outgoing neutron energy.
//!
//! Only scattering events use the get_all_bins functionality. Nu-fission
//! tallies manually iterate over the filter bins.
//==============================================================================
class EnergyoutFilter : public EnergyFilter {
public:
//----------------------------------------------------------------------------
// Methods
std::string type() const override { return "energyout"; }
void get_all_bins(const Particle& p, TallyEstimator estimator,
FilterMatch& match) const override;
std::string text_label(int bin) const override;
};
} // namespace openmc
#endif // OPENMC_TALLIES_FILTER_ENERGY_H
| {
"alphanum_fraction": 0.5074300699,
"avg_line_length": 30.1052631579,
"ext": "h",
"hexsha": "c820f28fb4b9632044ffbb187293867002049a44",
"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": "922f688978693761f82c4a3764ab05dd96cc8cff",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "huak95/openmc",
"max_forks_repo_path": "include/openmc/tallies/filter_energy.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "922f688978693761f82c4a3764ab05dd96cc8cff",
"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": "huak95/openmc",
"max_issues_repo_path": "include/openmc/tallies/filter_energy.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2efe223404680099f9a77214e743ab78e37cd08c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "stu314159/openmc",
"max_stars_repo_path": "include/openmc/tallies/filter_energy.h",
"max_stars_repo_stars_event_max_datetime": "2021-10-09T17:55:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-10-09T17:55:14.000Z",
"num_tokens": 399,
"size": 2288
} |
///
/// @file
///
/// @author Angelika Schwarz (angies@cs.umu.se), Umeå University
/// @author Mirko Myllykoski (mirkom@cs.umu.se), Umeå University
///
/// @internal LICENSE
///
/// Copyright (c) 2019-2020, Umeå Universitet
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
///
/// 1. Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
///
/// 2. Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// 3. Neither the name of the copyright holder nor the names of its
/// contributors may be used to endorse or promote products derived from this
/// software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
///
#include <starneig_config.h>
#include <starneig/configuration.h>
#include <starneig/error.h>
#include "core.h"
#include "typedefs.h"
#include "robust.h"
#include "cpu.h"
#include "partition.h"
#include "../../common/common.h"
#include "../../common/node_internal.h"
#include "../../common/matrix.h"
#include <starneig/sep_sm.h>
#include <cblas.h>
#include <stdlib.h>
#include <starpu.h>
#include <math.h>
#include <float.h>
static int search_multiplicities(int n, double *lambda, int *lambda_type)
{
int multiplicity = 0;
for (int i = 0; i < n; i++) {
if (lambda_type[i] == 0) { // REAL
double real = lambda[i];
for (int j = i+1; j < n; j++) {
if (lambda_type[j] == 0 && lambda[j] == real) {
multiplicity = 1;
break;
}
}
}
else { // CMPLX
double real = lambda[i];
double imag = lambda[i+1];
for (int j = i+2; j < n; j++) {
if (lambda_type[j] == 1 && lambda_type[j+1]) {
if (lambda[j] == real && lambda[j+1] == imag) {
multiplicity = 1;
break;
}
j++;
}
}
i++;
}
}
return multiplicity;
}
static starneig_error_t eigenvectors(
struct starneig_eigenvectors_conf const *_conf,
int n, int *selected,
double *S, int ldS,
double *Q, int ldQ,
double *Y, int ldY)
{
#define S(i,j) S[(i) + (j) * (size_t)ldS]
#define Q(i,j) Q[(i) + (j) * (size_t)ldQ]
#define X(i,j) X[(i) + (j) * (size_t)ldX]
#define Y(i,j) Y[(i) + (j) * (size_t)ldY]
// use default configuration if necessary
struct starneig_eigenvectors_conf *conf;
struct starneig_eigenvectors_conf local_conf;
if (_conf == NULL)
starneig_eigenvectors_init_conf(&local_conf);
else
local_conf = *_conf;
conf = &local_conf;
//
// check mandatory arguments
//
if (selected == NULL) {
starneig_error("Eigenvalue selection bitmap is NULL. Exiting...");
return STARNEIG_INVALID_ARGUMENTS;
}
int num_selected = starneig_eigvec_std_count_selected(n, selected);
if (num_selected == 0) {
starneig_error("Eigenvalue selection bitmap does not have any "
"selected eigenvalues. Exiting...");
return STARNEIG_INVALID_ARGUMENTS;
}
if (S == NULL) {
starneig_error("Matrix S is NULL. Exiting...");
return STARNEIG_INVALID_ARGUMENTS;
}
if (Q == NULL) {
starneig_error("Matrix Q is NULL. Exiting...");
return STARNEIG_INVALID_ARGUMENTS;
}
if (Y == NULL) {
starneig_error("Eigenvector matrix is NULL. Exiting...");
return STARNEIG_INVALID_ARGUMENTS;
}
//
// check configuration
//
if (conf->tile_size == STARNEIG_EIGENVECTORS_DEFAULT_TILE_SIZE) {
double select_ratio = (double) num_selected/n;
conf->tile_size = MIN(MAX(240, sqrt(n)/sqrt(select_ratio)), 936);
starneig_message("Setting tile size to %d.", conf->tile_size);
}
if (conf->tile_size <= 0) {
starneig_error("Tile size is %d. Exiting...", conf->tile_size);
return STARNEIG_INVALID_CONFIGURATION;
}
//
// preprocess
//
// extract the eigenvalues and their type (1-by-1 or 2-by-2 block)
double *lambda = (double *) malloc((size_t)n * sizeof(double));
int *lambda_type = (int *) malloc((size_t)n * sizeof(int));
lambda[n-1] = S(n-1,n-1);
lambda_type[n-1] = 0;
for (int i = 0; i < n - 1; i++) {
if (S(i+1,i) != 0.0) {
// A 2-by-2 block in canonical Schur form has the shape
// [ S(i,i) S(i,i+1) ] = [ a b ] or [ a -b ]
// [ S(i+1,i) S(i+1,i+1) ] [-c a ] [ c a ].
lambda_type[i] = 1;
lambda_type[i+1] = 1;
double real = S(i+1,i+1);
double imag = sqrt(fabs(S(i+1,i)))*sqrt(fabs(S(i,i+1)));
lambda[i] = real;
lambda[i+1] = imag;
i++;
}
else {
// 1-by-1 block
lambda_type[i] = 0;
lambda[i] = S(i,i);
}
}
//
// sanity check
//
starneig_error_t ret = STARNEIG_SUCCESS;
int illposed = search_multiplicities(n, lambda, lambda_type);
if (illposed) {
starneig_warning("Multiple eigenvalues detected.\n");
ret = STARNEIG_CLOSE_EIGENVALUES;
}
//
// overflow control
//
const double eps = DBL_EPSILON/2;
const double smlnum = MAX(2*DBL_MIN, DBL_MIN*((double)n/eps));
//
// partition
//
int num_tiles = (n+conf->tile_size-1)/conf->tile_size;
int *first_row = (int *) malloc((num_tiles+1)*sizeof(int));
int *first_col = (int *) malloc((num_tiles+1)*sizeof(int));
starneig_eigvec_std_partition(n, lambda_type, conf->tile_size, first_row);
starneig_eigvec_std_partition_selected(n, first_row, selected, num_tiles, first_col);
//
// workspace
//
int ldX = ldY;
double *X = (double *) malloc((size_t)ldX*num_selected*sizeof(double));
size_t num_segments = (size_t) num_tiles*num_selected;
double *Xnorms = (double *) malloc(num_segments*sizeof(double));
#define Xnorms(col, tilerow) Xnorms[(col) + (tilerow) * (size_t)num_selected]
scaling_t *scales = (scaling_t*) malloc(num_segments*sizeof(scaling_t));
#define scales(col, tilerow) scales[(col) + (tilerow) * (size_t)num_selected]
starneig_eigvec_std_init_scaling_factor(num_tiles*num_selected, scales);
double *Snorms =
(double *) malloc((size_t)num_tiles*num_tiles*sizeof(double));
#define Snorms(i,j) Snorms[(i) + (j) * (size_t)num_tiles]
int *info = (int *) malloc((size_t)num_selected*sizeof(int));
// Copy all selected eigenvalue types to a compact memory representation.
int *selected_lambda_type = (int *) malloc((size_t)num_selected*sizeof(int));
int idx = 0;
for (int i = 0; i < n; i++) {
if (selected[i]) {
selected_lambda_type[idx] = lambda_type[i];
idx++;
}
}
//
// register
//
starpu_data_handle_t **S_tiles;
starpu_data_handle_t **Q_tiles;
starpu_data_handle_t **X_tiles;
starpu_data_handle_t **Y_tiles;
starpu_data_handle_t *selected_tiles;
starpu_data_handle_t *lambda_tiles;
starpu_data_handle_t *lambda_type_tiles;
starpu_data_handle_t *selected_lambda_type_tiles;
starpu_data_handle_t **Xnorms_tiles;
starpu_data_handle_t **scales_tiles;
starpu_data_handle_t **S_tiles_norms;
starpu_data_handle_t *info_tiles;
S_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t *));
Q_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t *));
X_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t *));
Y_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t *));
selected_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t));
lambda_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t));
lambda_type_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t));
selected_lambda_type_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t));
Xnorms_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t *));
scales_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t *));
S_tiles_norms = malloc(num_tiles*sizeof(starpu_data_handle_t *));
info_tiles = malloc(num_tiles*sizeof(starpu_data_handle_t));
for (int i = 0; i < num_tiles; i++) {
S_tiles[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));
Q_tiles[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));
X_tiles[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));
Y_tiles[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));
Xnorms_tiles[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));
scales_tiles[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));
S_tiles_norms[i] = malloc(num_tiles*sizeof(starpu_data_handle_t));
starpu_vector_data_register(
&selected_tiles[i],
STARPU_MAIN_RAM,
(uintptr_t)(&selected[first_row[i]]),
first_row[i+1]-first_row[i],
sizeof(int));
starpu_vector_data_register(
&lambda_tiles[i],
STARPU_MAIN_RAM,
(uintptr_t)(&lambda[first_row[i]]),
first_row[i+1]-first_row[i],
sizeof(double));
starpu_vector_data_register(
&lambda_type_tiles[i],
STARPU_MAIN_RAM,
(uintptr_t)(&lambda_type[first_row[i]]),
first_row[i+1]-first_row[i],
sizeof(int));
starpu_vector_data_register(
&selected_lambda_type_tiles[i],
STARPU_MAIN_RAM,
(uintptr_t)(&selected_lambda_type[first_col[i]]),
first_col[i+1]-first_col[i],
sizeof(int));
starpu_vector_data_register(
&info_tiles[i],
STARPU_MAIN_RAM,
(uintptr_t)(&info[first_col[i]]),
first_col[i+1]-first_col[i],
sizeof(int));
for (int j = 0; j < num_tiles; j++) {
if (i <= j) {
starpu_matrix_data_register(
&S_tiles[i][j],
STARPU_MAIN_RAM,
(uintptr_t)(&S(first_row[i], first_row[j])),
ldS,
first_row[i+1]-first_row[i],
first_row[j+1]-first_row[j],
sizeof(double));
starpu_variable_data_register(
&S_tiles_norms[i][j],
STARPU_MAIN_RAM,
(uintptr_t)(&Snorms(i,j)),
sizeof(double));
starpu_matrix_data_register(
&X_tiles[i][j],
STARPU_MAIN_RAM,
(uintptr_t)(&X(first_row[i], first_col[j])),
ldX,
first_row[i+1]-first_row[i],
first_col[j+1]-first_col[j],
sizeof(double));
starpu_vector_data_register(
&Xnorms_tiles[i][j],
STARPU_MAIN_RAM,
(uintptr_t)(&Xnorms(first_col[j],i)),
first_col[j+1]-first_col[j],
sizeof(double));
starpu_vector_data_register(
&scales_tiles[i][j],
STARPU_MAIN_RAM,
(uintptr_t)(&scales(first_col[j],i)),
first_col[j+1]-first_col[j],
sizeof(scaling_t));
}
starpu_matrix_data_register(
&Q_tiles[i][j],
STARPU_MAIN_RAM,
(uintptr_t)(&Q(first_row[i], first_row[j])),
ldQ,
first_row[i+1]-first_row[i],
first_row[j+1]-first_row[j],
sizeof(double));
starpu_matrix_data_register(
&Y_tiles[i][j],
STARPU_MAIN_RAM,
(uintptr_t)(&Y(first_row[i], first_col[j])),
ldY,
first_row[i+1]-first_row[i],
first_col[j+1]-first_col[j],
sizeof(double));
}
}
//
// insert tasks
//
starneig_eigvec_std_insert_backsolve_tasks(num_tiles,
S_tiles, S_tiles_norms, lambda_tiles, lambda_type_tiles,
X_tiles, scales_tiles, Xnorms_tiles, selected_tiles,
selected_lambda_type_tiles, info_tiles, smlnum,
STARPU_MAX_PRIO, STARPU_DEFAULT_PRIO);
starpu_task_wait_for_all();
starneig_eigvec_std_unify_scaling(num_tiles, first_row, first_col, scales, X, ldX,
lambda_type, selected);
starneig_eigvec_std_insert_backtransform_tasks(first_row, num_tiles,
Q_tiles, X_tiles, Y_tiles);
//
// evaluate reliability
//
for (int i = 0; i < num_selected; i++) {
if (info[i] != STARNEIG_SUCCESS) {
starneig_warning("Eigenvector column X(:,%d) was perturbed and "
"cannot be trusted.", i);
ret = STARNEIG_CLOSE_EIGENVALUES;
}
}
starpu_task_wait_for_all();
//
// clean up
//
for (int i = 0; i < num_tiles; i++) {
starpu_data_unregister(selected_tiles[i]);
starpu_data_unregister(lambda_tiles[i]);
starpu_data_unregister(lambda_type_tiles[i]);
starpu_data_unregister(selected_lambda_type_tiles[i]);
starpu_data_unregister(info_tiles[i]);
for (int j = 0; j < num_tiles; j++) {
if (i <= j) {
starpu_data_unregister(S_tiles[i][j]);
starpu_data_unregister(S_tiles_norms[i][j]);
starpu_data_unregister(X_tiles[i][j]);
starpu_data_unregister(Xnorms_tiles[i][j]);
starpu_data_unregister(scales_tiles[i][j]);
}
starpu_data_unregister(Q_tiles[i][j]);
starpu_data_unregister(Y_tiles[i][j]);
}
free(S_tiles[i]);
free(Q_tiles[i]);
free(X_tiles[i]);
free(Y_tiles[i]);
free(Xnorms_tiles[i]);
free(scales_tiles[i]);
free(S_tiles_norms[i]);
}
free(S_tiles);
free(Q_tiles);
free(X_tiles);
free(Y_tiles);
free(Xnorms_tiles);
free(scales_tiles);
free(selected_tiles);
free(lambda_tiles);
free(lambda_type_tiles);
free(selected_lambda_type_tiles);
free(info_tiles);
free(X);
free(Xnorms);
free(Snorms);
free(info);
free(scales);
free(lambda_type);
free(selected_lambda_type);
free(lambda);
free(first_row);
free(first_col);
#undef Xnorms
#undef Snorms
#undef scales
#undef S
#undef Q
#undef X
#undef Y
return ret;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
__attribute__ ((visibility ("default")))
void starneig_eigenvectors_init_conf(struct starneig_eigenvectors_conf *conf) {
conf->tile_size = STARNEIG_EIGENVECTORS_DEFAULT_TILE_SIZE;
}
__attribute__ ((visibility ("default")))
int starneig_SEP_SM_Eigenvectors_expert(
struct starneig_eigenvectors_conf *conf,
int n,
int selected[],
double S[], int ldS,
double Q[], int ldQ,
double X[], int ldX)
{
CHECK_INIT();
starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_SEQUENTIAL);
starneig_node_set_mode(STARNEIG_MODE_SM);
starneig_node_resume_starpu();
starneig_error_t ret = eigenvectors(
conf, n, selected, S, ldS, Q, ldQ, X, ldX);
starpu_task_wait_for_all();
starneig_node_pause_starpu();
starneig_node_set_mode(STARNEIG_MODE_OFF);
starneig_node_set_blas_mode(STARNEIG_BLAS_MODE_ORIGINAL);
return ret;
}
__attribute__ ((visibility ("default")))
int starneig_SEP_SM_Eigenvectors(
int n,
int selected[],
double S[], int ldS,
double Q[], int ldQ,
double X[], int ldX)
{
CHECK_INIT();
return starneig_SEP_SM_Eigenvectors_expert(
NULL, n, selected, S, ldS, Q, ldQ, X, ldX);
}
| {
"alphanum_fraction": 0.591299772,
"avg_line_length": 31.8491620112,
"ext": "c",
"hexsha": "df42b5f13a8d5456f1b294564150b8a90011c8d6",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z",
"max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/StarNEig",
"max_forks_repo_path": "src/eigenvectors/standard/interface.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/StarNEig",
"max_issues_repo_path": "src/eigenvectors/standard/interface.c",
"max_line_length": 89,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/StarNEig",
"max_stars_repo_path": "src/eigenvectors/standard/interface.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z",
"num_tokens": 4209,
"size": 17103
} |
/*****************************************************************\
__
/ /
/ / __ __
/ /______ _______ / / / / ________ __ __
/ ______ \ /_____ \ / / / / / _____ | / / / /
/ / | / _______| / / / / / / /____/ / / / / /
/ / / / / _____ / / / / / / _______/ / / / /
/ / / / / /____/ / / / / / / |______ / |______/ /
/_/ /_/ |________/ / / / / \_______/ \_______ /
/_/ /_/ / /
/ /
High Level Game Framework /_/
---------------------------------------------------------------
Copyright (c) 2007-2011 - Rodrigo Braz Monteiro.
This file is subject to the terms of halley_license.txt.
\*****************************************************************/
#pragma once
#include <string>
#include <sstream>
#include <halley/data_structures/vector.h>
#include <gsl/gsl_assert>
#include <iomanip>
#include <cstdint>
namespace Halley {
typedef char Character;
typedef wchar_t utf16type;
typedef char32_t utf32type;
typedef std::wstring StringUTF16;
typedef std::u32string StringUTF32;
// String class
class String {
public:
const static size_t npos = size_t(-1);
String();
String(const char* utf8);
String(const char* utf8,size_t bytes);
String(const std::basic_string<Character>& str);
String(const String& str) noexcept;
String(String&& str) noexcept;
explicit String(const wchar_t* utf16);
explicit String(const StringUTF32 &utf32);
explicit String(char character);
explicit String(wchar_t character);
explicit String(int character);
explicit String(float number);
explicit String(double number);
String& operator=(const char* utf8);
String& operator=(const std::basic_string<Character>& str);
String& operator=(String&& str) noexcept;
String& operator=(const String& str);
operator std::string() const;
bool isEmpty() const;
size_t length() const;
void setSize(size_t size);
void truncate(size_t size);
String& trim(bool fromRight);
String& trimBoth();
bool contains(const String& string) const;
size_t find(String str) const;
String replaceAll(const String& before, const String& after) const;
String replaceOne(const String& before, const String& after) const;
void shrink();
String left(size_t n) const;
String right(size_t n) const;
String mid(size_t start,size_t count=npos) const;
bool startsWith(const String& string,bool caseSensitive=true) const;
bool endsWith(const String& string,bool caseSensitive=true) const;
void writeText(const Character* src,size_t len,size_t &pos);
void writeChar(const Character &src,size_t &pos);
void writeNumber(Character *temp,int number,int pad,size_t &pos);
bool isNumber() const;
bool isInteger() const;
String asciiLower() const;
String asciiUpper() const;
void asciiMakeUpper();
void asciiMakeLower();
bool asciiCompareNoCase(const Character *src) const;
void appendCharacter(int unicode);
// Convert a string to a number
int toInteger() const;
long long toInteger64() const;
float toFloat() const;
int subToInteger(size_t start,size_t end) const;
// std::string methods
const char* c_str() const;
String substr(size_t pos, size_t len=npos) const;
size_t find(Character character, size_t pos=0) const;
size_t find(const char* str, size_t pos=0) const;
size_t find_last_of(char character) const;
size_t size() const;
const char& operator[](size_t pos) const;
char& operator[](size_t pos);
static const Character* stringPtrTrim(Character *chr,size_t len,size_t startPos);
static const Character* stringTrim(String &str,size_t startPos);
// Number tidy up functions
static String prettyFloat(String src);
static String prettySize(long long bytes);
// Unicode routines
StringUTF16 getUTF16() const;
StringUTF32 getUTF32() const;
size_t getUTF32Len() const;
// Static unicode routines
static size_t getUTF8Len(const wchar_t *utf16);
static size_t getUTF8Len(const StringUTF32 &utf32);
static size_t getUTF16Len(const StringUTF32 &utf32);
inline std::string& cppStr() { return str; }
inline const std::string& cppStr() const { return str; }
Vector<String> split(char delimiter) const;
Vector<String> split(String delimiter) const;
static String concatList(const Vector<String>& list, String separator);
//////////
String operator += (const String &p);
String operator += (const char* p);
String operator += (const wchar_t* p);
String operator += (const double &p);
String operator += (const int &p);
String operator += (const Character &p);
bool operator== (const String& rhp) const;
bool operator!= (const String& rhp) const;
bool operator< (const String& rhp) const;
bool operator> (const String& rhp) const;
bool operator<= (const String& rhp) const;
bool operator>= (const String& rhp) const;
private:
Character* getCharPointer(size_t pos);
static size_t UTF8toUTF16(const char *utf8,wchar_t *utf16);
static size_t UTF16toUTF8(const wchar_t *utf16,char *utf8);
static size_t UTF32toUTF8(const utf32type *utf32,char *utf8);
std::string str;
};
String operator+ (const String& lhp, const String& rhp);
std::ostream& operator<< (std::ostream& os, const String& rhp);
std::istream& operator>> (std::istream& is, String& rhp);
using StringArray = Vector<String>;
}
namespace std {
template<>
struct hash<Halley::String>
{
size_t operator()(const Halley::String& s) const
{
return std::hash<std::string>()(s.cppStr());
}
};
}
| {
"alphanum_fraction": 0.6475061903,
"avg_line_length": 29.9153439153,
"ext": "h",
"hexsha": "4e299ec984f5c7c085a768d9a3c1db96eabf7fe8",
"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": "aa58e1abe22cda9e80637922721c03574779cd81",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Healthire/halley",
"max_forks_repo_path": "src/engine/utils/include/halley/text/halleystring.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81",
"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": "Healthire/halley",
"max_issues_repo_path": "src/engine/utils/include/halley/text/halleystring.h",
"max_line_length": 83,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa58e1abe22cda9e80637922721c03574779cd81",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Healthire/halley",
"max_stars_repo_path": "src/engine/utils/include/halley/text/halleystring.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1440,
"size": 5654
} |
/**
* Last modified: Tue Aug 30 16:29:05 CST 2016
* @author: Lie Yan
* @email: robin.lie.yan@outlook.com
*
*/
#pragma once
#include <gsl.h>
#include <iostream>
namespace grund {
template<int TypeTag, typename ValueType>
class Unit {
public:
using intrinsic_type = ValueType;
Unit() = default;
Unit(const Unit &rhs) = default;
Unit(Unit &&rhs) = default;
Unit &operator=(const Unit &rhs) = default;
Unit &operator=(Unit &&rhs) = default;
constexpr explicit Unit(const ValueType &v) : _value(v) {}
constexpr explicit operator ValueType() const { return _value; }
constexpr ValueType value() const { return _value; }
// unary minus
constexpr Unit operator-() const { return Unit(-_value); }
constexpr Unit &operator+=(const Unit &rhs) {
_value += rhs._value;
return *this;
}
constexpr Unit operator+(const Unit &rhs) const {
Unit ret(*this);
return ret += rhs;
}
constexpr Unit &operator-=(const Unit &rhs) {
_value -= rhs._value;
return *this;
}
constexpr Unit operator-(const Unit &rhs) const {
Unit ret(*this);
return ret -= rhs;
}
constexpr bool operator==(const Unit &rhs) const {
return _value == rhs._value;
}
// derived operator
constexpr bool operator!=(const Unit &rhs) const {
return not(*this == rhs);
}
constexpr bool operator<(const Unit &rhs) const {
return _value < rhs._value;
}
// derived operator
constexpr bool operator<=(const Unit &rhs) const {
return not(rhs < *this);
}
// derived operator
constexpr bool operator>(const Unit &rhs) const { return rhs < *this; }
// derived operator
constexpr bool operator>=(const Unit &rhs) const {
return not(*this < rhs);
}
friend std::ostream &operator<<(std::ostream &out, const Unit &m) {
out << ValueType(m);
return out;
}
template<typename T>
friend constexpr Unit operator*(const Unit &u, const T &v) {
return Unit{u.value() * v};
}
// derived operator
template<typename T>
friend constexpr Unit operator*(const T &v, const Unit &u) {
return operator*(u, v);
}
template<typename T>
friend constexpr Unit operator/(const Unit &u, const T &v) {
return Unit{u.value() / v};
}
template <typename U>
U to() const { return U(_value); }
private:
ValueType _value;
};
}
| {
"alphanum_fraction": 0.6446067899,
"avg_line_length": 21.9528301887,
"ext": "h",
"hexsha": "a0076d67d7127a8787bb635f3cf0be11ff742b2e",
"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": "4b691e515b30508fb5e29c68426bad51d9629e72",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "robin33n/formulae-cxx",
"max_forks_repo_path": "include/general/unit.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72",
"max_issues_repo_issues_event_max_datetime": "2019-09-26T11:32:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-25T11:10:39.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "robin33n/formulae-cxx",
"max_issues_repo_path": "include/general/unit.h",
"max_line_length": 73,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "robin33n/formulae-cxx",
"max_stars_repo_path": "include/general/unit.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-25T04:00:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-25T04:00:03.000Z",
"num_tokens": 613,
"size": 2327
} |
/* population genetics tools- mainly for working with site frequency spectrum
/
/
/ Andrew Kern
*/
#include "stdio.h"
#include "math.h"
#include "popGenTools.h"
#include "numerical.h"
#include "assert.h"
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_sf.h>
/* function for sfs generation */
double my_f(double q, void * p){
struct my_f_params * params = (struct my_f_params *) p;
double beta = params->beta;
int i = params->i;
int n = params->n;
return ((1.0 - exp(-2.0 * beta * (1.0 - q))) / (1.0 - exp(-2.0 * beta))) * (2.0 / (q * (1.0 - q))) * gsl_ran_binomial_pdf(i, q, n);
}
/* integral of f over allele freq */
double my_F(double beta, void * p){
struct my_F_params * params = (struct my_F_params *) p;
struct my_f_params fParams;
gsl_function f;
gsl_integration_workspace * w = gsl_integration_workspace_alloc (100000);
double result,error;
if (beta == 0){
gsl_integration_workspace_free(w);
return 1.0 / params->i;
}
else{
fParams.beta = beta;
fParams.i = params->i;
fParams.n = params->n;
f.function = &(my_f);
f.params = &fParams;
gsl_integration_qags(&f,0.0,1.0,1e-5,1e-5, 100000,w, &result,&error);
gsl_integration_workspace_free(w);
return result;
}
}
/* integral of f over allele freq using numerical recipes integration */
double my_F2(double beta, void * p){
struct my_F_params * params = (struct my_F_params *) p;
struct my_f_params fParams;
double result;
if (beta == 0){
return 1.0 / params->i;
}
else{
fParams.beta = beta;
fParams.i = params->i;
fParams.n = params->n;
result = d_qromb2(&my_f, 0.0, 1.0, &fParams);
return result;
}
}
/* this returns the prob of SNP freq i given n and beta */
double snpProb(double beta, void * p){
struct my_F_params * params = (struct my_F_params *) p;
struct my_F_params tempParams;
long double tot;
int i;
gsl_function F;
/* add up total prob space */
tot = 0.0;
tempParams.n = params->n;
for(i = 1; i < params->n ; i++){
tempParams.i = i;
F.function = &my_F;
F.params = &tempParams;
tot += GSL_FN_EVAL(&F, beta);
}
/* reset parameters */
F.function = &my_F;
F.params = params;
return GSL_FN_EVAL(&F, beta) / tot ;
}
/* trying to speedup the snpProb routine with a lookup of the denominators (in snpProb_params) */
double snpProbDenomLookup(double beta, void * p){
struct my_snpProb_params * params = (struct my_snpProb_params *) p;
struct my_F_params tempParams;
gsl_function F;
/* set parameters */
tempParams.n = params->n;
tempParams.i = params->i;
F.function = &my_F;
F.params = &tempParams;
return GSL_FN_EVAL(&F, beta) / params->denom ;
}
/* sampleSize vector - returns a vector of 1s or 0s depending on sample sizes in the data */
gsl_vector *sampleSizeVector(struct snp data[], int snpNumber, int maxSampleSize){
gsl_vector *bools;
int i;
//alloc and initialize bools vector
bools = gsl_vector_alloc(maxSampleSize + 1);
gsl_vector_set_zero(bools);
//go through data, set each sampleSize value to 1
for(i = 0; i < snpNumber; i++){
gsl_vector_set(bools,data[i].n, 1);
}
return(bools);
}
/* returns a vector of snpProbDenominators from i = 2 to n, 1 indexed */
gsl_vector *makeSnpProbDenomVector(double beta, int maxSampleSize, gsl_vector *sampleSizeVector){
gsl_vector *probs;
int i, j, test;
double tot;
struct my_F_params tempParams;
gsl_function F;
probs = gsl_vector_alloc(maxSampleSize + 1);
/* go from n = 2 to maxSampleSize, calc total prob space for each, put in vector probs */
for(j = 2; j < maxSampleSize + 1; j++){
//check if sampleSize is included
test = gsl_vector_get(sampleSizeVector,j);
if (test){
tot = 0.0;
tempParams.n = j;
for(i = 1; i < j ; i++){
tempParams.i = i;
F.function = &my_F;
F.params = &tempParams;
tot += GSL_FN_EVAL(&F, beta);
}
gsl_vector_set(probs, j, tot);
}
}
return probs;
}
/* snpProbDenom - returns denom for snpProb */
double snpProbDenom(double beta, int sampleSize){
int i;
double tot;
struct my_F_params tempParams;
gsl_function F;
tot = 0.0;
tempParams.n = sampleSize;
for(i = 1; i < sampleSize ; i++){
tempParams.i = i;
F.function = &my_F;
F.params = &tempParams;
tot += GSL_FN_EVAL(&F, beta);
}
return(tot);
}
/* snpProbMatrix- returns a matrix of log snpProbs. matrix is maxSampleSize+1 by maxSampleSize. rows represent
variable sampleSizes (2 to max), columns represent freqs (1 to max -1) */
gsl_matrix *snpProbMatrix(double beta, int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools){
gsl_vector *denoms;
gsl_matrix *probs;
struct my_snpProb_params FParams;
gsl_function f;
int i, j;
//alloc probs
probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);
gsl_matrix_set_zero(probs);
//get denoms
denoms = makeSnpProbDenomVector(beta,maxSampleSize, sampleSizeVector);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//have sample size i?
if (gsl_vector_get(sampleSizeVector, i)){
//go through freqs
for(j = 1; j < maxSampleSize; j++){
//have freq j?
if(gsl_matrix_get(sfsBools, i, j)){
//calc prob
FParams.i = j;
FParams.n = i;
FParams.denom = gsl_vector_get(denoms,i);
f.function = &snpProbDenomLookup;
f.params = &FParams;
gsl_matrix_set(probs, i, j, log(GSL_FN_EVAL(&f, beta)));
}
}
}
}
gsl_vector_free(denoms);
return(probs);
}
/* snpProbMatrix- returns a matrix of snpProbs. matrix is maxSampleSize+1 by maxSampleSize. rows represent
variable sampleSizes (2 to max), columns represent freqs (1 to max -1) */
gsl_matrix *snpProbMatrixNotLog(double beta, int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools){
gsl_vector *denoms;
gsl_matrix *probs;
struct my_snpProb_params FParams;
gsl_function f;
int i, j;
//alloc probs
probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);
gsl_matrix_set_zero(probs);
//get denoms
denoms = makeSnpProbDenomVector(beta,maxSampleSize, sampleSizeVector);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//have sample size i?
if (gsl_vector_get(sampleSizeVector, i)){
//go through freqs
for(j = 1; j < maxSampleSize; j++){
//have freq j?
if(gsl_matrix_get(sfsBools, i, j)){
//calc prob
FParams.i = j;
FParams.n = i;
FParams.denom = gsl_vector_get(denoms,i);
f.function = &snpProbDenomLookup;
f.params = &FParams;
gsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, beta));
}
}
}
}
gsl_vector_free(denoms);
return(probs);
}
/* snpProbMatrixNotLogFull- returns a matrix of snpProbs. matrix is maxSampleSize+1 by maxSampleSize. rows represent
variable sampleSizes (2 to max), columns represent freqs (1 to max -1). All freqs/samplesizes included */
gsl_matrix *snpProbMatrixNotLogFull(double beta, int maxSampleSize, gsl_vector *sampleSizeVector){
gsl_vector *denoms;
gsl_matrix *probs;
struct my_snpProb_params FParams;
gsl_function f;
int i, j;
//alloc probs
probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);
gsl_matrix_set_zero(probs);
//get denoms
denoms = makeSnpProbDenomVector(beta,maxSampleSize, sampleSizeVector);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//check for sampleSize
if (gsl_vector_get(sampleSizeVector,i)){
//go through freqs
for(j = 1; j < maxSampleSize; j++){
//calc prob
FParams.i = j;
FParams.n = i;
FParams.denom = gsl_vector_get(denoms,i);
f.function = &snpProbDenomLookup;
f.params = &FParams;
gsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, beta));
}
}
}
gsl_vector_free(denoms);
return(probs);
}
/* snpProbVectorNotLog- returns a vector of log snpProbs at specified sampleSize columns represent freqs (1 to max -1) */
gsl_vector *snpProbVectorNotLog(double beta, int sampleSize){
double denom;
gsl_vector *probs;
struct my_snpProb_params FParams;
gsl_function f;
int i;
//alloc probs
probs = gsl_vector_alloc(sampleSize);
gsl_vector_set_zero(probs);
//get denoms
denom = snpProbDenom(beta, sampleSize);
//go through freqs
for(i = 1; i < sampleSize; i++){
FParams.i = i;
FParams.n = sampleSize;
FParams.denom = denom;
f.function = &snpProbDenomLookup;
f.params = &FParams;
gsl_vector_set(probs, i, GSL_FN_EVAL(&f, beta));
}
return(probs);
}
/* likelihood function for SFS given the data; p here contains the data and the weights */
double my_lik(double beta, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
struct my_F_params FParams;
gsl_function f;
double lik;
int i;
lik = 0;
for(i = 0; i < params->snpNumber; i++){
FParams.i = params->data[i].i;
FParams.n = params->data[i].n;
f.function = &snpProb;
f.params = &FParams;
lik += log(GSL_FN_EVAL(&f, beta));
}
return -lik;
}
/* likelihood function for SFS where each SNP has independent selection coeff */
double sfsLikBetaVector(gsl_vector *betas, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
struct my_F_params FParams;
gsl_function f;
double lik;
int i;
lik = 0;
for(i = 0; i < params->snpNumber; i++){
FParams.i = params->data[i].i;
FParams.n = params->data[i].n;
f.function = &snpProb;
f.params = &FParams;
lik += log(GSL_FN_EVAL(&f, gsl_vector_get(betas, i)));
}
return -lik;
}
/* weighted likelihood function for SFS given the data; here contains the data and the weights */
double weightedLik(double beta, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
struct my_F_params FParams;
gsl_function f;
double lik;
int i;
lik = 0;
for(i = 0; i < params->snpNumber; i++){
FParams.i = params->data[i].i;
FParams.n = params->data[i].n;
f.function = &snpProb;
f.params = &FParams;
lik += gsl_vector_get(params->weights, i) * log(GSL_FN_EVAL(&f, beta));
}
return -lik;
}
/* weighted likelihood function for SFS given the data; here contains the data and the weights and uses the snpProbLookup routine */
double weightedLikLook(double beta, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
double lik;
int i;
gsl_matrix *probs;
//make prob matrix (note this is in logs)
probs = snpProbMatrix(beta, params->maxSampleSize, params->sampleSizeVector, params->sfsBools);
//now go and tally likelihood
lik = 0;
for(i = 0; i < params->snpNumber; i++){
lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_vector_get(params->weights,i);
}
gsl_matrix_free(probs);
return -lik;
}
double weightedLikLookCI(double beta, void * p){
struct my_likCI_params *params = (struct my_likCI_params *) p;
struct my_lik_params likParams;
gsl_function l;
double result;
likParams.data = params->data;
likParams.snpNumber = params->snpNumber;
likParams.sampleSizeVector = params->sampleSizeVector;
likParams.maxSampleSize = params->maxSampleSize;
likParams.weights = params->weights;
likParams.sfsBools = params->sfsBools;
l.function = &weightedLikLook;
l.params = &likParams;
result = GSL_FN_EVAL(&l, beta) - (params->lMax) - (params->logUnits) ;
// printf("%f\t%f\t%f\n",params->lMax,GSL_FN_EVAL(&l, beta),result);
return result;
}
/* wrapper for my_lik for use in mnbrak */
double likWrap(double beta){
gsl_function f;
f.function = &my_lik;
f.params = NULL;
return GSL_FN_EVAL(&f, beta);
}
/* wrapper for my_lik for use in mnbrak */
double wlikWrap(double beta, void * p){
gsl_function f;
struct my_lik_params * params = (struct my_lik_params *) p;
f.function = &weightedLik;
f.params = params;
return GSL_FN_EVAL(&f, beta);
}
/* wrapper for my_lik for use in mnbrak */
double wlikWrapLook(double beta, void * p){
gsl_function f;
struct my_lik_params * params = (struct my_lik_params *) p;
f.function = &weightedLikLook;
f.params = params;
return GSL_FN_EVAL(&f, beta);
}
double wlikCIWrapLook(double beta, void * p){
gsl_function f;
struct my_likCI_params * params = (struct my_likCI_params *) p;
f.function = &weightedLikLookCI;
f.params = params;
return GSL_FN_EVAL(&f, beta);
}
/*error checking function for likelihood function */
void printProfile(double min, double max, void * p){
gsl_function f;
struct my_lik_params *params = (struct my_lik_params *) p;
int i;
f.function = &weightedLikLook;
f.params = params;
for(i = min; i < max; i++){
printf("%d\t%f\n",i, GSL_FN_EVAL(&f, i));
}
}
/* get ML estimate of beta using likelihood function; BRENT method for gsl */
double ml_est(double * lik_beta_hat){
int status;
int iter = 0;
int max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc;
gsl_function L;
/* get minimum bracket */
ax = -10.0;
bx = 0.0;
cx = 10.0;
mnbrak(&ax, &bx, &cx, &fa, &fb, &fc, &my_lik);
/* check if there is a minimum, if not return inf */
if (fa == fb || fc == fb || ax > cx){
*lik_beta_hat = fa;
return 666.0;
}
else{
/* do mimization */
L.function = &my_lik;
//should have param line here but no params....
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &L, bx, ax, cx);
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_min_fminimizer_free(s);
return m;
}
}
/* get weighted ML estimate of beta using likelihood function; BRENT method for gsl */
double weighted_ml_est(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc, min;
gsl_function L;
struct my_lik_params * params = (struct my_lik_params *) p;
// get minimum bracket
ax = -10.0;
bx = 1.0;
cx = 10;
L.function = &weightedLik;
L.params = params;
mnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrap, bx, params);
//check if there is a minimum, if not return 666
if (fa == fb || fc == fb || ax > cx){
min = fa;
if(fb < min){
min = fb;
}
if(fc < min){
min = fc;
}
*lik_beta_hat = min;
return 666.0;
}
else{
// do mimization
//initialize lik function
L.function = &weightedLik;
L.params = params;
//min routine
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &L, bx, ax, cx);
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);
gsl_min_fminimizer_free(s);
return m;
}
}
double weighted_ml_est_lookup(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc, dummy;
gsl_function L;
struct my_lik_params * params = (struct my_lik_params *) p;
// get minimum bracket
ax = -20.0;
bx = -1.0;
cx = 20;
L.function = &weightedLikLook;
L.params = params;
mnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLook, bx, params);
//swap bounds if needed
if (cx < ax){
dummy = cx;
cx = ax;
ax = dummy;
}
// do mimization
//initialize lik function
L.function = &weightedLikLook;
L.params = params;
//min routine
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &L, bx, ax, cx);
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);
gsl_min_fminimizer_free(s);
return m;
}
/* same as above but outputs 666 on minimization error */
double weighted_ml_est_lookup_errReport(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc, dummy;
gsl_function L;
struct my_lik_params * params = (struct my_lik_params *) p;
// get minimum bracket
ax = -20.0;
bx = -1.0;
cx = 20;
L.function = &weightedLikLook;
L.params = params;
mnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLook, bx, params);
//swap bounds if needed
if (cx < ax){
dummy = cx;
cx = ax;
ax = dummy;
}
//check for error
if (fb >= fc || fb >= fa){
return(666.0);
}
// do mimization
//initialize lik function
L.function = &weightedLikLook;
L.params = params;
//min routine
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_set_error_handler_off ();
status = gsl_min_fminimizer_set(s, &L, bx, ax, cx);
if (status == GSL_EINVAL){
return(666);
}
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);
gsl_min_fminimizer_free(s);
return m;
}
/* get weighted ML lower CI beta using weightedLikLookCI method; BRENT method for gsl */
double weighted_ml_CILower_lookup(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
double m, a, b, ax, cx;
gsl_function L;
struct my_likCI_params * params = (struct my_likCI_params *) p;
// get minimum bracket
ax = -50.0;
cx = params->beta_hat;
// do root finding
//initialize lik function
L.function = &weightedLikLookCI;
L.params = params;
//min routine
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc(T);
gsl_root_fsolver_set(s, &L, ax, cx);
do{
iter++;
status = gsl_root_fsolver_iterate(s);
m = gsl_root_fsolver_root(s);
a = gsl_root_fsolver_x_lower(s);
b = gsl_root_fsolver_x_upper(s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_root_fsolver_free(s);
return m;
}
/* get weighted ML upper CI beta using weightedLikLookCI method; BRENT method for gsl */
double weighted_ml_CIUpper_lookup(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
double m, a, b, ax, cx;
gsl_function L;
struct my_likCI_params * params = (struct my_likCI_params *) p;
// get minimum bracket
cx = 100.0;
ax = params->beta_hat;
// do root finding
//initialize lik function
L.function = &weightedLikLookCI;
L.params = params;
//min routine
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc(T);
gsl_root_fsolver_set(s, &L, ax, cx);
do{
iter++;
status = gsl_root_fsolver_iterate(s);
m = gsl_root_fsolver_root(s);
a = gsl_root_fsolver_x_lower(s);
b = gsl_root_fsolver_x_upper(s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_root_fsolver_free(s);
return m;
}
/* summarizeSFS- returns a matrix of counts which summarize the SFS conditional
upon sampleSize. rows = sampleSize, column = freqs */
gsl_matrix *summarizeSFS(int maxSampleSize, struct snp data[], int snpNumber){
gsl_matrix *counts;
int i;
//alloc matrix of size maxSampleSize by maxSampleSize
counts = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize + 1);
gsl_matrix_set_zero(counts);
assert(counts != NULL);
gsl_matrix_set_zero(counts);
//go through data, fill up matrix
for(i = 0; i < snpNumber; i++){
gsl_matrix_set(counts, data[i].n, data[i].i, gsl_matrix_get(counts, data[i].n, data[i].i) + 1);
}
return(counts);
}
/* summarizeSFS- returns a matrix of booleans which summarize the SFS conditional
upon sampleSize. rows = sampleSize, column = freqs */
gsl_matrix *summarizeSFSBool(int maxSampleSize, struct snp data[], int snpNumber){
gsl_matrix *counts;
int i;
//alloc matrix of size maxSampleSize by maxSampleSize
counts = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize + 1);
gsl_matrix_set_zero(counts);
assert(counts != NULL);
gsl_matrix_set_zero(counts);
//go through data, fill up matrix
for(i = 0; i < snpNumber; i++){
gsl_matrix_set(counts, data[i].n, data[i].i, 1);
}
return(counts);
}
/* simulateSiteFreq- returns an int representing the frequency of
of a site (unfolded), i, in sampleSize n, conditional on sel.
coeff. beta , also needs a pointer to a gsl random number generator */
int simulateSiteFreq(int sampleSize, double alpha, void *r){
int i;
double sum, probs[sampleSize - 1], rand;
gsl_function p;
struct my_F_params simParams;
gsl_rng * rn = (gsl_rng *) r;
simParams.n = sampleSize;
/* put probs in vector */
for(i = 0; i < sampleSize - 1; i++){
simParams.i = i + 1;
p.function = &snpProb;
p.params = &simParams;
probs[i] = GSL_FN_EVAL(&p, alpha);
}
/* choose frequency */
rand = gsl_rng_uniform(rn);
sum = 0;
for(i = 0; i < sampleSize - 1; i++){
sum += probs[i];
if (rand <= sum){
return(i+1);
}
}
return(666);
}
/* ascertainment stuff -- following Nielsen et al. 2004 */
/* simpleAscertain-- Nielsen et al. 2004 eqn 2 *, returns the prob of ascertainment
given a sample freq */
double simpleAscertain(double sampleFreq, void * p){
struct my_F_params * params = (struct my_F_params *) p;
double sampleSize, ascSize,tmpSampleFreq;
double num1 = 0.0;
double num2 = 0.0;
sampleSize = params->n;
ascSize = params->ascSize;
tmpSampleFreq = (int) sampleFreq;
//test for weirdness
if (sampleFreq < ascSize){
num1 = 0;
}
else{
num1 = gsl_sf_choose(sampleFreq, ascSize);
}
if ((sampleSize -sampleFreq) < ascSize){
num2 = 0;
}
else{
num2 = gsl_sf_choose(sampleSize - sampleFreq, ascSize);
}
return(1.0 - ((num1 + num2) / gsl_sf_choose(sampleSize, ascSize)));
}
/* outgroupAscertain-- equivalent to Nielsen et al. 2004 eqn 2,
returns the prob of ascertainment given a sample freq, but
is for use when ascertainment was based on single outgroup comparisons
(e.g. divergence between reference genomes). specifically this
calculates the prob of sampling only ancestral alleles.
IMPORTANT- sampleFreq here is derived allele freq */
double outgroupAscertain(double sampleFreq, void * p){
struct my_F_params * params = (struct my_F_params *) p;
double sampleSize, ascSize;
double num = 0.0;
sampleSize = params->n;
ascSize = params->ascSize;
//test for weirdness
if ((sampleSize - sampleFreq) < ascSize){
num = 0;
}
else{
num = gsl_sf_choose((sampleSize - sampleFreq), ascSize);
}
return(num / gsl_sf_choose(sampleSize, ascSize));
}
/* probAscertainmentGivenModel-- Nielsen et al. 2005 eqn 8
returns the prob of ascertainment given the model */
double probAscertainmentGivenModel(double beta, void *p){
struct my_F_params * params = (struct my_F_params *) p;
struct my_F_params tempParams;
long double tot, tmpres, tmpres2;
int i=1;
gsl_function F, G;
/* add up total prob space */
tot = 0.0;
tempParams.n = params->n;
tempParams.ascSize = params->ascSize;
for(i = 1; i < params->n ; i++){
tempParams.i = i;
F.function = &(snpProb);
F.params = &tempParams;
tmpres = 0.0;
tmpres = GSL_FN_EVAL(&F, beta);
G.function = &simpleAscertain;
G.params = &tempParams;
tmpres2 = GSL_FN_EVAL(&G, i) ;
tot += tmpres * tmpres2;
}
return(tot) ;
}
/* probAscertainmentGivenModel-- Nielsen et al. 2005 eqn 8
returns the prob of ascertainment given the model */
double probOutgroupAscertainmentGivenModel(double beta, void *p){
struct my_F_params * params = (struct my_F_params *) p;
struct my_F_params tempParams;
long double tot, tmpres, tmpres2;
int i=1;
gsl_function F, G;
/* add up total prob space */
tot = 0.0;
tempParams.n = params->n;
tempParams.ascSize = params->ascSize;
for(i = 1; i < params->n ; i++){
tempParams.i = i;
F.function = &(snpProb);
F.params = &tempParams;
tmpres = 0.0;
tmpres = GSL_FN_EVAL(&F, beta);
G.function = &outgroupAscertain;
G.params = &tempParams;
tmpres2 = GSL_FN_EVAL(&G, i) ;
tot += tmpres * tmpres2;
}
return(tot) ;
}
/* probAscertainmentGivenModelLookup-- Nielsen et al. 2005 eqn 8
returns the prob of ascertainment given the model, lookup version
requires snpProb matrix and ascProb matrix */
double probAscertainmentGivenModelLookup(double beta, int sampSize, gsl_matrix *snpProbs, gsl_matrix *ascProbs){
long double tot;
int i=1;
/* add up total prob space */
tot = 0.0;
for(i = 1; i < sampSize ; i++){
tot += gsl_matrix_get(snpProbs, sampSize, i) * gsl_matrix_get(ascProbs, sampSize, i);
}
return(tot) ;
}
/* probAscertainmentGivenModelHemiLookup-- same
as above but expects vector not matrix of snpProbs */
double probAscertainmentGivenModelHemiLookup(double beta, int sampSize, gsl_vector *snpProbs, gsl_matrix *ascProbs){
long double tot;
int i=1;
/* add up total prob space */
tot = 0.0;
for(i = 1; i < sampSize ; i++){
tot += gsl_vector_get(snpProbs, i) * gsl_matrix_get(ascProbs, sampSize, i);
}
return(tot) ;
}
/* ascSize vector - returns a vector of 1s or 0s depending on ascertainment sample sizes in the data */
gsl_vector *ascSizeVector(struct snp data[], int snpNumber, int maxSampleSize){
gsl_vector *bools;
int i;
//alloc and initialize bools vector
bools = gsl_vector_alloc(maxSampleSize + 1);
gsl_vector_set_zero(bools);
//go through data, set each sampleSize value to 1
for(i = 0; i < snpNumber; i++){
gsl_vector_set(bools,data[i].ascSize, 1);
}
return(bools);
}
/* snpAscMatrix- returns a matrix of simpleAscertainment probs. matrix is maxSampleSize+1 by maxSampleSize. rows represent
variable sampleSizes (2 to max), columns represent freqs (1 to max -1). Currently this only supports a single ascertainment size */
gsl_matrix *snpAscMatrix(int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools, \
int ascSize){
gsl_matrix *probs;
struct my_F_params FParams;
gsl_function f;
int i, j;
//alloc probs
probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);
gsl_matrix_set_zero(probs);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//have sample size i?
if (gsl_vector_get(sampleSizeVector, i)){
//go through freqs
for(j = 1; j < maxSampleSize; j++){
//have freq j?
if(gsl_matrix_get(sfsBools, i, j)){
//calc prob
FParams.i = j;
FParams.n = i;
FParams.ascSize = ascSize;
f.function = &simpleAscertain;
f.params = &FParams;
gsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, j));
}
}
}
}
return(probs);
}
/* snpOutgroupAscMatrix- returns a matrix of outgroupAscertainment probs. matrix is maxSampleSize+1 by maxSampleSize. rows represent
variable sampleSizes (2 to max), columns represent freqs (1 to max -1). Currently this only supports a single ascertainment size */
gsl_matrix *snpOutgroupAscMatrix(int maxSampleSize, gsl_vector *sampleSizeVector, int ascSize){
gsl_matrix *probs;
struct my_F_params FParams;
gsl_function f;
int i, j;
//alloc probs
probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);
gsl_matrix_set_zero(probs);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//have sample size i?
if (gsl_vector_get(sampleSizeVector, i)){
//go through freqs
for(j = 1; j < i; j++){
//calc prob
FParams.i = j;
FParams.n = i;
FParams.ascSize = ascSize;
f.function = &outgroupAscertain;
f.params = &FParams;
gsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, j));
}
}
}
return(probs);
}
/*estimateAscSFS-- ML estimates of SFS, given ascertainment. returns
a matrix of probs. matrix is maxSampleSize+1 by maxSampleSize. rows represent
variable sampleSizes (2 to max), columns represent freqs (1 to max -1). Currently this only supports a single ascertainment size */
gsl_matrix *estimateAscSFS(int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools, \
int ascSize, gsl_matrix *sfsSummary){
gsl_matrix *probs, *ascProbs;
int i, j;
double ssTmp, p_hat;
double xij;
//alloc probs
probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);
gsl_matrix_set_zero(probs);
//calculate ascProbs
ascProbs = snpAscMatrix(maxSampleSize, sampleSizeVector, sfsBools, \
ascSize);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//have sample size i?
if (gsl_vector_get(sampleSizeVector, i)){
//go through freqs to tally up denom at sampleSize
ssTmp = 0.0;
for(j = 1; j < maxSampleSize; j++){
xij = gsl_matrix_get(sfsSummary, i, j);
if (xij > 0){
ssTmp += xij / gsl_matrix_get(ascProbs, i, j);
}
}
//go back through freqs to assign p_hats at sampleSize
for(j = 1; j < maxSampleSize; j++){
xij = gsl_matrix_get(sfsSummary, i, j);
p_hat = (double) xij / gsl_matrix_get(ascProbs, i, j);
gsl_matrix_set(probs, i, j, p_hat / ssTmp);
}
}
}
return(probs);
}
/* weighted likelihood function for SFS given the data and ascertainment; here contains the data and the weights and uses the snpProbLookup routine */
double weightedLikLookAsc(double beta, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
double lik, num;
int i;
gsl_matrix *probs, *ascProbs;
gsl_vector *ascDenoms;
//make prob matrix (note this is in logs)
probs = snpProbMatrix(beta, params->maxSampleSize, params->sampleSizeVector, params->sfsBools);
//make ascProb matrix (NOT in logs!)
ascProbs = snpAscMatrix(params->maxSampleSize, params->sampleSizeVector, params->sfsBools, params->ascSize);
//make vector of denoms
ascDenoms = gsl_vector_alloc(params->maxSampleSize + 1);
gsl_vector_set_zero(ascDenoms);
for(i = params->ascSize; i <= params->maxSampleSize; i++){
gsl_vector_set(ascDenoms,i,probAscertainmentGivenModelLookup(beta, i, probs, ascProbs));
}
//now go and tally likelihood
lik = 0;
num = 0;
for(i = 0; i < params->snpNumber; i++){
lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) \
+ log(gsl_matrix_get(ascProbs,params->data[i].n,params->data[i].i)) \
- log(gsl_vector_get(ascDenoms, params->data[i].n));
}
gsl_matrix_free(probs);
gsl_matrix_free(ascProbs);
gsl_vector_free(ascDenoms);
return -lik;
}
/* weighted likelihood function for SFS given the data and outgroup ascertainment; here contains the data and the weights and uses the snpProbLookup routine */
double weightedLikLookOutgroupAsc(double beta, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
double lik, num;
int i;
gsl_matrix *probs, *ascProbs;
gsl_vector *ascDenoms;
//make prob matrix
probs = snpProbMatrixNotLogFull(beta, params->maxSampleSize, params->sampleSizeVector);
//make ascProb matrix
ascProbs = snpOutgroupAscMatrix(params->maxSampleSize, params->sampleSizeVector, params->ascSize);
//make vector of denoms
ascDenoms = gsl_vector_alloc(params->maxSampleSize + 1);
gsl_vector_set_zero(ascDenoms);
for(i = params->ascSize; i <= params->maxSampleSize; i++){
gsl_vector_set(ascDenoms,i,probAscertainmentGivenModelLookup(beta, i, probs, ascProbs));
}
//now go and tally likelihood
lik = 0;
num = 0;
for(i = 0; i < params->snpNumber; i++){
num = (gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_matrix_get(ascProbs,params->data[i].n,params->data[i].i)) \
/ gsl_vector_get(ascDenoms, params->data[i].n);
lik += log(num);
//printf("first: %f\t second: %f\t third: %f\n",gsl_matrix_get(probs,params->data[i].n,params->data[i].i),gsl_matrix_get(ascProbs,params->data[i].n,params->data[i].i),gsl_vector_get(ascDenoms, params->data[i].n));
}
gsl_matrix_free(probs);
gsl_matrix_free(ascProbs);
gsl_vector_free(ascDenoms);
return -lik;
}
/* wrapper for my_lik for use in mnbrak */
double wlikWrapLookAsc(double beta, void * p){
gsl_function f;
struct my_lik_params * params = (struct my_lik_params *) p;
f.function = &weightedLikLookAsc;
f.params = params;
return GSL_FN_EVAL(&f, beta);
}
/* wrapper for my_lik for use in mnbrak */
double wlikWrapLookOutgroupAsc(double beta, void * p){
gsl_function f;
struct my_lik_params * params = (struct my_lik_params *) p;
f.function = &weightedLikLookOutgroupAsc;
f.params = params;
return GSL_FN_EVAL(&f, beta);
}
/* get weighted ML estimate of beta using likelihood function (lookup) conditional on ascertainment
; BRENT method for gsl */
double weighted_ml_est_lookup_asc(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc, dummy;
gsl_function L;
struct my_lik_params * params = (struct my_lik_params *) p;
// get minimum bracket
ax = -20.0;
bx = -1.0;
cx = 20;
L.function = &weightedLikLookAsc;
L.params = params;
mnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLookAsc, bx, params);
//swap bounds if needed
if (cx < ax){
dummy = cx;
cx = ax;
ax = dummy;
}
// do mimization
//initialize lik function
L.function = &weightedLikLookAsc;
L.params = params;
//min routine
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &L, bx, ax, cx);
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);
gsl_min_fminimizer_free(s);
return m;
}
/* get weighted ML estimate of beta using likelihood function (lookup) conditional on outgroup ascertainment
; BRENT method for gsl */
double weighted_ml_est_lookup_outgroup_asc(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc, dummy;
gsl_function L;
struct my_lik_params * params = (struct my_lik_params *) p;
// get minimum bracket
ax = -20.0;
bx = -1.0;
cx = 20;
L.function = &weightedLikLookOutgroupAsc;
L.params = params;
mnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLookOutgroupAsc, bx, params);
//swap bounds if needed
if (cx < ax){
dummy = cx;
cx = ax;
ax = dummy;
}
// do mimization
//initialize lik function
L.function = &weightedLikLookOutgroupAsc;
L.params = params;
//min routine
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &L, bx, ax, cx);
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);
gsl_min_fminimizer_free(s);
return m;
}
/* likelihood function for SFS where each SNP has
independent selection coeff and outgroup ascertainment */
double sfsLikBetaVectorOutgroupAsc(gsl_vector *betas, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
double pSNP, pAsc, pAscModel,lik, tmp;
int i;
gsl_matrix *ascProbs;
gsl_vector *snpProbs;
lik = 0;
//make ascProb matrix
ascProbs = snpOutgroupAscMatrix(params->maxSampleSize, params->sampleSizeVector, \
params->ascSize);
//go through snps
for(i = 0; i < params->snpNumber; i++){
//create vector of snpProbs, find pSNP_i
snpProbs = snpProbVectorNotLog(gsl_vector_get(betas, i), params->data[i].n);
pSNP = gsl_vector_get(snpProbs, params->data[i].i);
//lookup pAsc_i
pAsc = gsl_matrix_get(ascProbs, params->data[i].n, params->data[i].i);
//get pAscModel
pAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \
snpProbs, ascProbs);
tmp = pSNP * pAsc / pAscModel;
lik += log(tmp);
gsl_vector_free(snpProbs);
}
gsl_matrix_free(ascProbs);
return -lik;
}
| {
"alphanum_fraction": 0.6796950499,
"avg_line_length": 27.5328898744,
"ext": "c",
"hexsha": "71b0bcff1d74893f69ca40a52abebccddb298536",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "andrewkern/segSiteHMM",
"max_forks_repo_path": "hmm/popGenTools.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "andrewkern/segSiteHMM",
"max_issues_repo_path": "hmm/popGenTools.c",
"max_line_length": 217,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "andrewkern/segSiteHMM",
"max_stars_repo_path": "hmm/popGenTools.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 11352,
"size": 37252
} |
/* linalg/balance.c
*
* Copyright (C) 2001 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.
*/
/* Balance a general matrix by scaling the columns
*
* B = A D
*
* where D is a diagonal matrix
*/
#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_linalg.h"
int
gsl_linalg_balance_columns (gsl_matrix * A, gsl_vector * D)
{
const size_t N = A->size2;
size_t j;
if (D->size != A->size2)
{
GSL_ERROR("length of D must match second dimension of A", GSL_EINVAL);
}
gsl_vector_set_all (D, 1.0);
for (j = 0; j < N; j++)
{
gsl_vector_view A_j = gsl_matrix_column (A, j);
double s = gsl_blas_dasum(&A_j.vector);
double f = 1.0;
if (s == 0.0)
{
gsl_vector_set (D, j, f);
continue;
}
while (s > 1.0)
{
s /= 2.0;
f *= 2.0;
}
while (s < 0.5)
{
s *= 2.0;
f /= 2.0;
}
gsl_vector_set (D, j, f);
if (f != 1.0)
{
gsl_blas_dscal(1.0/f, &A_j.vector);
}
}
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.5921259843,
"avg_line_length": 22.4117647059,
"ext": "c",
"hexsha": "3257095cf06b92af32692b1657c232c0580162c7",
"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/linalg/balance.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/linalg/balance.c",
"max_line_length": 76,
"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/linalg/balance.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": 548,
"size": 1905
} |
/*
+---------------------------------------------------------------------------+
| Juzhen: C++ library for linear algebra |
+---------------------------------------------------------------------------+
| |
| Copyright 2011 Hui Chen |
| |
| 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 SRC_ADAPTOR_BLAS_H_
#define SRC_ADAPTOR_BLAS_H_
#include <assert.h>
#include <cblas.h>
namespace juzhen {
template<typename T>
void gemm(
const int M, const int N,
const int K, const T *A, const int lda, const T *B,
const int ldb, T *c, const int ldc) {
assert(0); // always fails
}
template<> inline
void gemm<float>(
const int M, const int N,
const int K, const float *A, const int lda, const float *B,
const int ldb, float *c, const int ldc) {
cblas_sgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1.,
A, lda, B, ldb, 0., c, ldc);
}
template<> inline
void gemm<double>(
const int M, const int N,
const int K, const double *A, const int lda, const double *B,
const int ldb, double *c, const int ldc) {
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1.,
A, lda, B, ldb, 0., c, ldc);
}
template<> inline
void gemm<CS>(
const int M, const int N,
const int K, const CS *A, const int lda, const CS *B,
const int ldb, CS *c, const int ldc) {
CS alpha(1., 0.);
CS beta(0., 0.);
cblas_cgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, &alpha,
A, lda, B, ldb, &beta, c, ldc);
}
template<> inline
void gemm<CD>(
const int M, const int N,
const int K, const CD *A, const int lda, const CD *B,
const int ldb, CD *c, const int ldc) {
CD alpha(1., 0.);
CD beta(0., 0.);
cblas_zgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, M, N, K, &alpha,
A, lda, B, ldb, &beta, c, ldc);
}
template<typename T>
int geev(
char nl, char nr, const int n,
T *a, const int lda, CD * w, T *vl, const int ldvl,
T *vr, const int ldvr) {
assert(0); // always fails
}
/*
* Linear solver
*/
template<typename T>
int gesv(
const int n, const int nrhs,
T *a, const int lda, T *b, const int ldb) {
assert(0); // always fails
}
/*
* Matrix inversion
*/
template<typename T>
int matrix_inverse(
const int m, const int n, T *a, const int lda) {
assert(0); // always fails
}
/*
* Matrix determinant
*/
template<typename T>
T matrix_determinant(const int m, T *a) {
assert(0); // always fails
}
}
#endif // SRC_ADAPTOR_BLAS_H_
| {
"alphanum_fraction": 0.4955537591,
"avg_line_length": 31.9913793103,
"ext": "h",
"hexsha": "98c5e45fc66c5717f61cab36f3957ef38336f9cd",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-01-30T20:18:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-04-07T10:42:06.000Z",
"max_forks_repo_head_hexsha": "5af4308e683f79ab98081739c4a7a567757532b8",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "huichen/juzhen",
"max_forks_repo_path": "src/adaptor/blas.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5af4308e683f79ab98081739c4a7a567757532b8",
"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": "huichen/juzhen",
"max_issues_repo_path": "src/adaptor/blas.h",
"max_line_length": 77,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "5af4308e683f79ab98081739c4a7a567757532b8",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "huichen/juzhen",
"max_stars_repo_path": "src/adaptor/blas.h",
"max_stars_repo_stars_event_max_datetime": "2019-01-30T20:17:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-09T10:00:27.000Z",
"num_tokens": 928,
"size": 3711
} |
#include <nlopt.h>
#include <stdio.h>
#include <math.h>
/****************************************************************************/
/* test function from M. J. Box, "A new method of constrained optimization
and a comparison with other methods," Computer J. 8 (1), 42-52 (1965) */
int testfuncs_verbose = 1;
int testfuncs_counter = 0;
static double testfuncs_status(int n, const double *x, double f)
{
++testfuncs_counter;
if (testfuncs_verbose) {
int i;
printf("f_%d (%g", testfuncs_counter, x[0]);
for (i = 1; i < n; ++i)
printf(", %g", x[i]);
printf(") = %g\n", f);
}
return f;
}
#define RETURN(f) return testfuncs_status(n, x, f);
static const double k1 = -145421.402, k2 = 2931.1506, k3 = -40.427932, k4 = 5106.192,
k5 = 15711.36, k6 = -161622.577, k7 = 4176.15328, k8 = 2.8260078,
k9 = 9200.476, k10 = 13160.295, k11 = -21686.9194, k12 = 123.56928,
k13 = -21.1188894, k14 = 706.834, k15 = 2898.573, k16 = 28298.388,
k17 = 60.81096, k18 = 31.242116, k19 = 329.574, k20 = -2882.082,
k21 = 74095.3845, k22 = -306.262544, k23 = 16.243649, k24 = -3094.252,
k25 = -5566.2628, k26 = -26237, k27 = 99, k28 = -0.42, k29 = 1300, k30 = 2100, k31 = 925548.252, k32 = -61968.8432, k33 = 23.3088196, k34 = -27096.648, k35 = -50843.766;
static double box(int n, const double *x, double *grad, void *data)
{
double x1 = x[0], x2 = x[1], x3 = x[2], x4 = x[3], x5 = x[4];
double b, x6, y1, y2, y3, y4, u;
const double a0 = 9, a1 = 15, a2 = 50, a3 = 9.583, a4 = 20, a5 = 15, a6 = 6, a7 = 0.75;
b = x2 + 0.01 * x3;
x6 = (k1 + k2 * x2 + k3 * x3 + k4 * x4 + k5 * x5) * x1;
y1 = k6 + k7 * x2 + k8 * x3 + k9 * x4 + k10 * x5;
y2 = k11 + k12 * x2 + k13 * x3 + k14 * x4 + k15 * x5;
y3 = k16 + k17 * x2 + k18 * x3 + k19 * x4 + k20 * x5;
y4 = k21 + k22 * x2 + k23 * x3 + k24 * x4 + k25 * x5;
u = a2 * y1 + a3 * y2 + a4 * y3 + a5 * y4 + 7840 * a6 - 100000 * a0 - 50800 * b * a7 + k31 + k32 * x2 + k33 * x3 + k34 * x4 + k35 * x5;
if (grad) {
int i;
grad[0] = u + a1 * (k1 + k2 * x2 + k3 * x3 + k4 * x4 + k5 * x5);
grad[1] = x1 * (a2 * k7 + a3 * k12 + a4 * k17 + a5 * k22 - 50800 * a7 + k32) + a1 * (k2 * x1);
grad[2] = x1 * (a2 * k8 + a3 * k13 + a4 * k18 + a5 * k23 - 50800 * a7 * 0.01) + a1 * x1 * k3;
grad[3] = x1 * (a2 * k9 + a3 * k14 + a4 * k19 + a5 * k24) + a1 * x1 * k4;
grad[4] = x1 * (a2 * k10 + a3 * k15 + a4 * k20 + a5 * k25) + a1 * x1 * k5;
for (i = 0; i < 5; ++i)
grad[i] = -grad[i];
}
RETURN(-(u * x1 - 24345 + a1 * x6));
}
static double box_constraint(int n, const double *x, double *grad, void *data)
{
int which_constraint = *((int *) data);
double x1 = x[0], x2 = x[1], x3 = x[2], x4 = x[3], x5 = x[4];
double x6, y1, y2, y3, x7, x8;
int i;
x6 = (k1 + k2 * x2 + k3 * x3 + k4 * x4 + k5 * x5) * x1;
y1 = k6 + k7 * x2 + k8 * x3 + k9 * x4 + k10 * x5;
y2 = k11 + k12 * x2 + k13 * x3 + k14 * x4 + k15 * x5;
y3 = k16 + k17 * x2 + k18 * x3 + k19 * x4 + k20 * x5;
x7 = (y1 + y2 + y3) * x1;
x8 = (k26 + k27 * x2 + k28 * x3 + k29 * x4 + k30 * x5) * x1 + x6 + x7;
if (grad) {
grad[0] = grad[1] = grad[2] = grad[3] = grad[4] = 0;
if (which_constraint != 2 && which_constraint != -2) {
/* grad x6 */
grad[0] += (k1 + k2 * x2 + k3 * x3 + k4 * x4 + k5 * x5);
grad[1] += x1 * k2;
grad[2] += x1 * k3;
grad[3] += x1 * k4;
grad[4] += x1 * k5;
}
if (which_constraint != 1 && which_constraint != -1) {
/* grad x7 */
grad[0] += (y1 + y2 + y3);
grad[1] += x1 * (k7 + k12 + k17);
grad[2] += x1 * (k8 + k13 + k18);
grad[3] += x1 * (k9 + k14 + k19);
grad[4] += x1 * (k10 + k15 + k20);
}
if (which_constraint == 3 || which_constraint == -3) {
/* grad (x8 - x6 - x7) */
grad[0] += k26 + k27 * x2 + k28 * x3 + k29 * x4 + k30 * x5;
grad[1] += x1 * k27;
grad[2] += x1 * k28;
grad[3] += x1 * k29;
grad[4] += x1 * k30;
}
}
if (which_constraint == -1) {
if (grad)
for (i = 0; i < 5; ++i)
grad[i] = -grad[i];
return -x6;
} else if (which_constraint == 1) {
return x6 - 294000;
} else if (which_constraint == -2) {
if (grad)
for (i = 0; i < 5; ++i)
grad[i] = -grad[i];
return -x7;
} else if (which_constraint == 2) {
return x7 - 294000;
} else if (which_constraint == -3) {
if (grad)
for (i = 0; i < 5; ++i)
grad[i] = -grad[i];
return -x8;
} else if (which_constraint == 3) {
return x8 - 277200;
}
return 0;
}
int main(void)
{
const double box_lb[5] = { 0, 1.2, 20, 9, 6.5 };
const double box_ub[5] = { HUGE_VAL, 2.4, 60, 9.3, 7.0 };
const double box_xmin[5] = { 4.53743, 2.4, 60, 9.3, 7.0 };
int cdata[6] = { -1, 1, -2, 2, -3, 3 };
double x[5] = { 2.52, 2, 37.5, 9.25, 6.8 };
double minf;
nlopt_minimize_constrained(NLOPT_LN_COBYLA, 5, box, NULL, 6, box_constraint, cdata, sizeof(int), box_lb, box_ub, x, &minf, -HUGE_VAL, 1e-10, 0, 0, NULL, 0, 0);
printf("found f(%g,%g,%g,%g,%g) = %0.8f after %d iters\n", x[0], x[1], x[2], x[3], x[4], minf, testfuncs_counter);
return 0;
}
| {
"alphanum_fraction": 0.4609090909,
"avg_line_length": 38.4615384615,
"ext": "c",
"hexsha": "3f92320779b872b96d1e78b3fff9ad534f4be5c6",
"lang": "C",
"max_forks_count": 1126,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T16:43:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-04T11:57:46.000Z",
"max_forks_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "rockandsalt/conan-center-index",
"max_forks_repo_path": "recipes/nlopt/all/test_package/test_package.c",
"max_issues_count": 9799,
"max_issues_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:45.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-04T12:02:11.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "rockandsalt/conan-center-index",
"max_issues_repo_path": "recipes/nlopt/all/test_package/test_package.c",
"max_line_length": 173,
"max_stars_count": 562,
"max_stars_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "rockandsalt/conan-center-index",
"max_stars_repo_path": "recipes/nlopt/all/test_package/test_package.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T16:41:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-04T12:23:43.000Z",
"num_tokens": 2348,
"size": 5500
} |
/*********************************************************************************/
/* Matrix product program with MPI on a virtual ring of processors */
/* S. Vialle - October 2014 */
/*********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mpi.h>
#include <omp.h>
#include <cblas.h>
#include "main.h"
#include "Calcul.h"
/*-------------------------------------------------------------------------------*/
/* Sequential product of local matrixes (optimized seq product). */
/*-------------------------------------------------------------------------------*/
void OneLocalProduct(int step)
{
int OffsetStepLigC;
int i, j, k;
// Set the number of OpenMP threads inside parallel regions
omp_set_num_threads(NbThreads);
// Compute the current step offset, in the MPI program, to access right C lines
OffsetStepLigC = (Me * LOCAL_SIZE + step * LOCAL_SIZE) % SIZE;
switch (KernelId) {
// Kernel 0 : Optimized code implemented by an application developer
case 0 :
for (i = 0; i < LOCAL_SIZE; i++) {
for (j = 0; j < LOCAL_SIZE; j++) {
double accu[8];
accu[0] = accu[1] = accu[2] = accu[3] = accu[4] = accu[5] = accu[6] = accu[7] = 0.0;
for (k = 0; k < (SIZE/8)*8; k += 8) {
accu[0] += A_Slice[i][k+0] * TB_Slice[j][k+0];
accu[1] += A_Slice[i][k+1] * TB_Slice[j][k+1];
accu[2] += A_Slice[i][k+2] * TB_Slice[j][k+2];
accu[3] += A_Slice[i][k+3] * TB_Slice[j][k+3];
accu[4] += A_Slice[i][k+4] * TB_Slice[j][k+4];
accu[5] += A_Slice[i][k+5] * TB_Slice[j][k+5];
accu[6] += A_Slice[i][k+6] * TB_Slice[j][k+6];
accu[7] += A_Slice[i][k+7] * TB_Slice[j][k+7];
}
for (k = (SIZE/8)*8; k < SIZE; k++) {
accu[0] += A_Slice[i][k] * TB_Slice[j][k];
}
C_Slice[i+OffsetStepLigC][j] = accu[0] + accu[1] + accu[2] + accu[3] +
accu[4] + accu[5] + accu[6] + accu[7];
}
}
break;
// Kernel 1 : Very optimized computing kernel implemented in a HPC library
case 1 :
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
LOCAL_SIZE, LOCAL_SIZE, SIZE,
1.0, &A_Slice[0][0], SIZE,
&B_Slice[0][0], LOCAL_SIZE,
0.0, &C_Slice[OffsetStepLigC][0], LOCAL_SIZE);
break;
default :
fprintf(stderr,"Error: kernel %d not implemented!\n",KernelId);
exit(EXIT_FAILURE);
break;
}
}
| {
"alphanum_fraction": 0.4503116978,
"avg_line_length": 37.3561643836,
"ext": "c",
"hexsha": "5db53b6d78e359cf5694e41b78470772757d6304",
"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": "ac5573cefc4c307c1a9f16a2c4e016a201dabece",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "pallamidessi/Courses",
"max_forks_repo_path": "MPI/SendRecvReplaceVersion/Calcul.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ac5573cefc4c307c1a9f16a2c4e016a201dabece",
"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": "pallamidessi/Courses",
"max_issues_repo_path": "MPI/SendRecvReplaceVersion/Calcul.c",
"max_line_length": 97,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ac5573cefc4c307c1a9f16a2c4e016a201dabece",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "pallamidessi/Courses",
"max_stars_repo_path": "MPI/SendRecvReplaceVersion/Calcul.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 789,
"size": 2727
} |
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_blas.h>
static int
hilbert_matrix(gsl_matrix * m)
{
const size_t N = m->size1;
const size_t M = m->size2;
size_t i, j;
for (i = 0; i < N; i++)
{
for (j = 0; j < M; j++)
{
gsl_matrix_set(m, i, j, 1.0/(i+j+1.0));
}
}
return GSL_SUCCESS;
}
int
main()
{
const size_t n = 10; /* number of observations */
const size_t p = 8; /* number of model parameters */
size_t i;
gsl_matrix *X = gsl_matrix_alloc(n, p);
gsl_vector *y = gsl_vector_alloc(n);
/* construct Hilbert matrix and rhs vector */
hilbert_matrix(X);
{
double val = 1.0;
for (i = 0; i < n; ++i)
{
gsl_vector_set(y, i, val);
val *= -1.0;
}
}
{
const size_t npoints = 200; /* number of points on L-curve and GCV curve */
gsl_multifit_linear_workspace *w =
gsl_multifit_linear_alloc(n, p);
gsl_vector *c = gsl_vector_alloc(p); /* OLS solution */
gsl_vector *c_lcurve = gsl_vector_alloc(p); /* regularized solution (L-curve) */
gsl_vector *c_gcv = gsl_vector_alloc(p); /* regularized solution (GCV) */
gsl_vector *reg_param = gsl_vector_alloc(npoints);
gsl_vector *rho = gsl_vector_alloc(npoints); /* residual norms */
gsl_vector *eta = gsl_vector_alloc(npoints); /* solution norms */
gsl_vector *G = gsl_vector_alloc(npoints); /* GCV function values */
double lambda_l; /* optimal regularization parameter (L-curve) */
double lambda_gcv; /* optimal regularization parameter (GCV) */
double G_gcv; /* G(lambda_gcv) */
size_t reg_idx; /* index of optimal lambda */
double rcond; /* reciprocal condition number of X */
double chisq, rnorm, snorm;
/* compute SVD of X */
gsl_multifit_linear_svd(X, w);
rcond = gsl_multifit_linear_rcond(w);
fprintf(stderr, "matrix condition number = %e\n", 1.0 / rcond);
/* unregularized (standard) least squares fit, lambda = 0 */
gsl_multifit_linear_solve(0.0, X, y, c, &rnorm, &snorm, w);
chisq = pow(rnorm, 2.0);
fprintf(stderr, "\n=== Unregularized fit ===\n");
fprintf(stderr, "residual norm = %g\n", rnorm);
fprintf(stderr, "solution norm = %g\n", snorm);
fprintf(stderr, "chisq/dof = %g\n", chisq / (n - p));
/* calculate L-curve and find its corner */
gsl_multifit_linear_lcurve(y, reg_param, rho, eta, w);
gsl_multifit_linear_lcorner(rho, eta, ®_idx);
/* store optimal regularization parameter */
lambda_l = gsl_vector_get(reg_param, reg_idx);
/* regularize with lambda_l */
gsl_multifit_linear_solve(lambda_l, X, y, c_lcurve, &rnorm, &snorm, w);
chisq = pow(rnorm, 2.0) + pow(lambda_l * snorm, 2.0);
fprintf(stderr, "\n=== Regularized fit (L-curve) ===\n");
fprintf(stderr, "optimal lambda: %g\n", lambda_l);
fprintf(stderr, "residual norm = %g\n", rnorm);
fprintf(stderr, "solution norm = %g\n", snorm);
fprintf(stderr, "chisq/dof = %g\n", chisq / (n - p));
/* calculate GCV curve and find its minimum */
gsl_multifit_linear_gcv(y, reg_param, G, &lambda_gcv, &G_gcv, w);
/* regularize with lambda_gcv */
gsl_multifit_linear_solve(lambda_gcv, X, y, c_gcv, &rnorm, &snorm, w);
chisq = pow(rnorm, 2.0) + pow(lambda_gcv * snorm, 2.0);
fprintf(stderr, "\n=== Regularized fit (GCV) ===\n");
fprintf(stderr, "optimal lambda: %g\n", lambda_gcv);
fprintf(stderr, "residual norm = %g\n", rnorm);
fprintf(stderr, "solution norm = %g\n", snorm);
fprintf(stderr, "chisq/dof = %g\n", chisq / (n - p));
/* output L-curve and GCV curve */
for (i = 0; i < npoints; ++i)
{
printf("%e %e %e %e\n",
gsl_vector_get(reg_param, i),
gsl_vector_get(rho, i),
gsl_vector_get(eta, i),
gsl_vector_get(G, i));
}
/* output L-curve corner point */
printf("\n\n%f %f\n",
gsl_vector_get(rho, reg_idx),
gsl_vector_get(eta, reg_idx));
/* output GCV curve corner minimum */
printf("\n\n%e %e\n",
lambda_gcv,
G_gcv);
gsl_multifit_linear_free(w);
gsl_vector_free(c);
gsl_vector_free(c_lcurve);
gsl_vector_free(reg_param);
gsl_vector_free(rho);
gsl_vector_free(eta);
gsl_vector_free(G);
}
gsl_matrix_free(X);
gsl_vector_free(y);
return 0;
}
| {
"alphanum_fraction": 0.5902417962,
"avg_line_length": 32.3916083916,
"ext": "c",
"hexsha": "8f448d67371fb546e42c058ec245f37ff9ced79e",
"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/fitreg2.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/fitreg2.c",
"max_line_length": 98,
"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/fitreg2.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": 1359,
"size": 4632
} |
#include <config.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_fft_complex.h>
#include <gsl/gsl_fft_complex_float.h>
#define BASE_DOUBLE
#include "templates_on.h"
#include "bitreverse.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "bitreverse.c"
#include "templates_off.h"
#undef BASE_FLOAT
#include "factorize.c"
#define BASE_DOUBLE
#include "templates_on.h"
#include "c_init.c"
#include "c_main.c"
#include "c_pass_2.c"
#include "c_pass_3.c"
#include "c_pass_4.c"
#include "c_pass_5.c"
#include "c_pass_6.c"
#include "c_pass_7.c"
#include "c_pass_n.c"
#include "c_radix2.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "c_init.c"
#include "c_main.c"
#include "c_pass_2.c"
#include "c_pass_3.c"
#include "c_pass_4.c"
#include "c_pass_5.c"
#include "c_pass_6.c"
#include "c_pass_7.c"
#include "c_pass_n.c"
#include "c_radix2.c"
#include "templates_off.h"
#undef BASE_FLOAT
#include <gsl/gsl_fft_halfcomplex.h>
#include <gsl/gsl_fft_halfcomplex_float.h>
#define BASE_DOUBLE
#include "templates_on.h"
#include "hc_init.c"
#include "hc_main.c"
#include "hc_pass_2.c"
#include "hc_pass_3.c"
#include "hc_pass_4.c"
#include "hc_pass_5.c"
#include "hc_pass_n.c"
#include "hc_radix2.c"
#include "hc_unpack.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "hc_init.c"
#include "hc_main.c"
#include "hc_pass_2.c"
#include "hc_pass_3.c"
#include "hc_pass_4.c"
#include "hc_pass_5.c"
#include "hc_pass_n.c"
#include "hc_radix2.c"
#include "hc_unpack.c"
#include "templates_off.h"
#undef BASE_FLOAT
#include <gsl/gsl_fft_real.h>
#include <gsl/gsl_fft_real_float.h>
#define BASE_DOUBLE
#include "templates_on.h"
#include "real_init.c"
#include "real_main.c"
#include "real_pass_2.c"
#include "real_pass_3.c"
#include "real_pass_4.c"
#include "real_pass_5.c"
#include "real_pass_n.c"
#include "real_radix2.c"
#include "real_unpack.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "real_init.c"
#include "real_main.c"
#include "real_pass_2.c"
#include "real_pass_3.c"
#include "real_pass_4.c"
#include "real_pass_5.c"
#include "real_pass_n.c"
#include "real_radix2.c"
#include "real_unpack.c"
#include "templates_off.h"
#undef BASE_FLOAT
| {
"alphanum_fraction": 0.7552588997,
"avg_line_length": 20.9491525424,
"ext": "c",
"hexsha": "9aa0da77b10e56473f5de226b97a573aae771eaa",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/fft/fft.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/fft/fft.c",
"max_line_length": 42,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/fft/fft.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": 704,
"size": 2472
} |
#ifndef L_1_LASSO_D_H
#define L_1_LASSO_D_H
#include "Matrix.h"
#include "APPROX2.h"
#include "ALM_APG.h"
#include <string>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <stdio.h> /* printf */
#include <time.h>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <ctime>
#include <math.h>
//This class solves problem of the form f(x)+g(x)+ h(Mx) by ASGARD_DL;
// where f(x)= 0
//and g(x)=frac{lambda2}{2}|x|_2+lambda1|x|_1,
// h(x)= lambda3|x- b|_1.
template<typename L, typename D>
class L_1_Lasso_d: public ALM_APG<L, D>
{
private:
D lambda1;
D lambda2;
D lambda3;
Matrix<L,D> my_M;
D val_lambda_f;
protected:
public:
L_1_Lasso_d(const char* Matrix_file,D val_lambda1, D val_lambda2, D val_lambda3)
:ALM_APG<L,D>(),my_M(Matrix_file)
{
lambda1=val_lambda1;
lambda2=val_lambda2;
lambda3=val_lambda3;
val_lambda_f=0;
this->val_mu_f=0;
this->val_mu_g=lambda2;
}
L get_n(){return my_M.nfeatures;}
L get_m(){return my_M.nsamples;}
inline D gradient_of_phi_j(D x1, L i){
return 0;
}
inline D value_of_g_i(D x, L i){
return lambda2*x*x/2+lambda1*fabs(x);
}
inline D value_of_phi_j(D x1, L i){return 0;}
inline D value_of_h_j(D x, L i){
return lambda3*fabs(x- my_M.b[i]);
}
inline D value_of_h_star_j(D x, L j){
if (x<= lambda3 && x>= -lambda3){
return my_M.b[j]*x;
}
else{
cout<< "error in h*(x)"<< endl;
return std::numeric_limits<double>::max();
}
}
inline D prox_of_g_i(D x1,D x2,D x3, L i){
return compute_one_step(1.0/x2, x1, x3)-x3;
}
D compute_one_step(D tau, D u, D x){
D new_x;
if(x>tau*(lambda1+u))
new_x=(x-tau*(lambda1+u))/(1+lambda2*tau);
else if(x<tau*(u-lambda1))
new_x=(x-tau*(u-lambda1))/(1+lambda2*tau);
else
new_x=0;
return new_x;
}
// compute min_x h^*(x)+ x2/2*(x- x1)*(x- x1)
inline D prox_of_h_star_j(D x1, D x2, L j){
if (x1- my_M.b[j]/x2> lambda3){
return lambda3;
}
else if (x1- my_M.b[j]/x2< -lambda3){
return -lambda3;
}
else{
return x1- my_M.b[j]/x2;
}
}
inline D feasible_dual(vector<D> & x, vector<D> & y){
if(lambda2>0)
{
return 1;
}
else
{
D scal=1;
L l=x.size();
for(L i=0;i<l;i++)
if(fabs(x[i]+y[i])>lambda1)
scal=min(lambda1/fabs(x[i]+y[i]),scal);
return scal;
}
}
inline D value_of_phistar_i(D x,L i) {return 0;}
inline D value_of_g_tilde_star(D scal,vector<D> & x, vector<D> & y){
return 0;
}
inline void set_matrix_M(){
this->data_M=my_M;
}
inline void set_matrix_A(){
this->data_A.nsamples=0;
this->data_A.nfeatures=this->data_M.nfeatures;
this->data_A.nnz=0;
this->data_A.ptr.resize(1,0);
this->data_A.ptr_t.resize(this->data_M.nfeatures+1,0);
}
inline D distance_to_subgradient_of_g(){
D res=0;
D tmp;
D xv;
for(L i=0;i<this->n;i++){
tmp=-this->gradient_of_f[i]-this->M_tlambda_s[i];
xv=this->x_s[i];
if(xv>0) res+=(tmp-lambda2*xv-lambda1)*(tmp-lambda2*xv-lambda1);
else if(xv<0) res+=(tmp-lambda2*xv+lambda1)*(tmp-lambda2*xv+lambda1);
else if(tmp-lambda2*xv>lambda1) res+=(tmp-lambda2*xv-lambda1)*(tmp-lambda2*xv-lambda1);
else if(tmp-lambda2*xv<-lambda1) res+=(tmp-lambda2*xv+lambda1)*(tmp-lambda2*xv+lambda1);
else res+=0;
}
return sqrt(res);
}
void ALM_APG_solver(D beta_0, D epsilon_0, D omega, vector<D> & x0,vector<D> & y0,L val_tau, L max_nb_outer, L p_N_1, L p_N_2,string filename1, string filename2, D time){
this->ALM_APG_solve_with_APPROX(beta_0, epsilon_0, omega,x0,y0, val_tau, max_nb_outer, p_N_1, p_N_2, val_lambda_f, filename1, filename2, time);
}
};
#endif
| {
"alphanum_fraction": 0.5891375409,
"avg_line_length": 21.6141304348,
"ext": "h",
"hexsha": "a2f7abe7a11cabc2709039cf1e6035a959b897fc",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_forks_repo_licenses": [
"BSD-Source-Code"
],
"max_forks_repo_name": "lifei16/supplementary_code",
"max_forks_repo_path": "IPALM_OPENMP/L_1_Lasso_d.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-Source-Code"
],
"max_issues_repo_name": "lifei16/supplementary_code",
"max_issues_repo_path": "IPALM_OPENMP/L_1_Lasso_d.h",
"max_line_length": 174,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_stars_repo_licenses": [
"BSD-Source-Code"
],
"max_stars_repo_name": "lifei16/supplementary_code",
"max_stars_repo_path": "IPALM_OPENMP/L_1_Lasso_d.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1338,
"size": 3977
} |
#include <mpi.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#include <signal.h>
#include <gsl/gsl_rng.h>
#include "allvars.h"
#include "proto.h"
#define TAG_DATAIN 100
#define TAG_DATAOUT 101
static void serial_sort(char *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *));
static void msort_serial_with_tmp(char *base, size_t n, size_t s, int (*compar) (const void *, const void *),
char *t);
static void parallel_merge(int master, int ncpu, size_t * nlist, size_t nmax, char *base, size_t nmemb,
size_t size, int (*compar) (const void *, const void *));
void parallel_sort(void *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *))
{
int i, ncpu_in_group, master, groupnr;
size_t nmax, *nlist;
serial_sort((char *) base, nmemb, size, compar);
nlist = (size_t *) mymalloc(NTask * sizeof(size_t));
MPI_Allgather(&nmemb, sizeof(size_t), MPI_BYTE, nlist, sizeof(size_t), MPI_BYTE, MPI_COMM_WORLD);
for(i = 0, nmax = 0; i < NTask; i++)
if(nlist[i] > nmax)
nmax = nlist[i];
for(ncpu_in_group = 2; ncpu_in_group <= (1 << PTask); ncpu_in_group *= 2)
{
groupnr = ThisTask / ncpu_in_group;
master = ncpu_in_group * groupnr;
parallel_merge(master, ncpu_in_group, nlist, nmax, (char *) base, nmemb, size, compar);
}
myfree(nlist);
}
void parallel_merge(int master, int ncpu, size_t * nlist, size_t nmax,
char *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *))
{
size_t na, nb, nr;
int cpua, cpub, cpur;
char *list_a, *list_b, *list_r;
if(master + ncpu / 2 >= NTask) /* nothing to do */
return;
if(ThisTask != master)
{
if(nmemb)
{
list_r = (char *) mymalloc(nmemb * size);
MPI_Request requests[2];
MPI_Isend(base, nmemb * size, MPI_BYTE, master, TAG_DATAIN, MPI_COMM_WORLD, &requests[0]);
MPI_Irecv(list_r, nmemb * size, MPI_BYTE, master, TAG_DATAOUT, MPI_COMM_WORLD, &requests[1]);
MPI_Waitall(2, requests, MPI_STATUSES_IGNORE);
memcpy(base, list_r, nmemb * size);
myfree(list_r);
}
}
else
{
list_a = (char *) mymalloc(nmax * size);
list_b = (char *) mymalloc(nmax * size);
list_r = (char *) mymalloc(nmax * size);
cpua = master;
cpub = master + ncpu / 2;
cpur = master;
na = 0;
nb = 0;
nr = 0;
memcpy(list_a, base, nmemb * size);
if(nlist[cpub])
MPI_Recv(list_b, nlist[cpub] * size, MPI_BYTE, cpub, TAG_DATAIN, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
while(cpur < master + ncpu && cpur < NTask)
{
while(na >= nlist[cpua] && cpua < master + ncpu / 2 - 1)
{
cpua++;
if(nlist[cpua])
MPI_Recv(list_a, nlist[cpua] * size, MPI_BYTE, cpua, TAG_DATAIN, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
na = 0;
}
while(nb >= nlist[cpub] && cpub < master + ncpu - 1 && cpub < NTask - 1)
{
cpub++;
if(nlist[cpub])
MPI_Recv(list_b, nlist[cpub] * size, MPI_BYTE, cpub, TAG_DATAIN, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
nb = 0;
}
while(nr >= nlist[cpur])
{
if(cpur == master)
memcpy(base, list_r, nr * size);
else
{
if(nlist[cpur])
MPI_Send(list_r, nlist[cpur] * size, MPI_BYTE, cpur, TAG_DATAOUT, MPI_COMM_WORLD);
}
nr = 0;
cpur++;
}
if(na < nlist[cpua] && nb < nlist[cpub])
{
if(compar(list_a + na * size, list_b + nb * size) < 0)
{
memcpy(list_r + nr * size, list_a + na * size, size);
na++;
nr++;
}
else
{
memcpy(list_r + nr * size, list_b + nb * size, size);
nb++;
nr++;
}
}
else if(na < nlist[cpua])
{
memcpy(list_r + nr * size, list_a + na * size, size);
na++;
nr++;
}
else if(nb < nlist[cpub])
{
memcpy(list_r + nr * size, list_b + nb * size, size);
nb++;
nr++;
}
}
myfree(list_r);
myfree(list_b);
myfree(list_a);
}
}
static void serial_sort(char *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *))
{
const size_t storage = nmemb * size;
char *tmp = (char *) mymalloc(storage);
msort_serial_with_tmp(base, nmemb, size, compar, tmp);
myfree(tmp);
}
static void msort_serial_with_tmp(char *base, size_t n, size_t s, int (*compar) (const void *, const void *),
char *t)
{
char *tmp;
char *b1, *b2;
size_t n1, n2;
if(n <= 1)
return;
n1 = n / 2;
n2 = n - n1;
b1 = base;
b2 = base + n1 * s;
msort_serial_with_tmp(b1, n1, s, compar, t);
msort_serial_with_tmp(b2, n2, s, compar, t);
tmp = t;
while(n1 > 0 && n2 > 0)
{
if(compar(b1, b2) < 0)
{
--n1;
memcpy(tmp, b1, s);
tmp += s;
b1 += s;
}
else
{
--n2;
memcpy(tmp, b2, s);
tmp += s;
b2 += s;
}
}
if(n1 > 0)
memcpy(tmp, b1, n1 * s);
memcpy(base, t, (n - n2) * s);
}
| {
"alphanum_fraction": 0.5816367265,
"avg_line_length": 22.466367713,
"ext": "c",
"hexsha": "803686b65732557e9d72421082dd295454c36c83",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "egpbos/egp",
"max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/parallel_sort.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "egpbos/egp",
"max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/parallel_sort.c",
"max_line_length": 109,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "egpbos/egp",
"max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/parallel_sort.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1666,
"size": 5010
} |
/* Initialize topic and POV assignments uniformly at random, and set
various hyper-parameters needed for inference. Assignments must be
initialized before doing inference for the first time. */
#include <assert.h>
#include <gsl/gsl_rng.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "index.h"
#include "parse_mmaps.h"
#include "sample.h"
int main(int argc, char **argv) {
if (argc != 11) {
printf("Usage: %s mmap_directory num_topics pov_per_topic num_threads psi_alpha "
"psi_beta gamma_alpha gamma_beta beta alpha\n",
argv[0]);
exit(1);
}
int num_threads = atoi(argv[4]);
char *endptr;
create_indexes(argv[1],
strtod(argv[5], &endptr),
strtod(argv[6], &endptr),
strtod(argv[7], &endptr),
strtod(argv[8], &endptr),
strtod(argv[9], &endptr),
strtod(argv[10], &endptr),
atoi(argv[2]),
atoi(argv[3]),
num_threads);
struct mmap_info mmap_info = open_mmaps_mmap(argv[1]);
// If revisions are numbered from zero, make sure the first
// revision gets assigned a null topic/POV
struct revision_assignment* first_assignment
= get_revision_assignment(&mmap_info, 0);
first_assignment->topic = -1;
first_assignment->pov = -1;
struct sample_threads sample_threads;
initialize_threads(&sample_threads, num_threads, &mmap_info);
resample_null(&sample_threads);
resample_uniform(&sample_threads);
destroy_threads(&sample_threads);
close_mmaps(mmap_info);
}
| {
"alphanum_fraction": 0.7085324232,
"avg_line_length": 28.7254901961,
"ext": "c",
"hexsha": "afbe147ebf1d0f72378278986f5d6f5c9de164fc",
"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": "c727087d0ac2d440d4e70fbea0c3342c3c734073",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "allenlavoie/topic-pov",
"max_forks_repo_path": "src/initialize.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073",
"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": "allenlavoie/topic-pov",
"max_issues_repo_path": "src/initialize.c",
"max_line_length": 85,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c727087d0ac2d440d4e70fbea0c3342c3c734073",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "allenlavoie/topic-pov",
"max_stars_repo_path": "src/initialize.c",
"max_stars_repo_stars_event_max_datetime": "2015-01-05T17:04:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-05T17:04:56.000Z",
"num_tokens": 387,
"size": 1465
} |
/*
* GaussianMixtureModel.h
* Provides implementation of Gaussian Mixture Model return type.
*
Copyright 2017 Michal Gallus
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <vector>
#include <gsl.h>
namespace spectre::unsupervised::gmm
{
/// <summary>
/// Represents a single component of a Gaussian Mixture.
/// </summary>
struct GaussianComponent
{
/// <summary>
/// Mean value of the component or peak's location.
/// </summary>
double mean;
/// <summary>
/// Standard deviation of the component or peak's width.
/// </summary>
double deviation;
/// <summary>
/// Weight of the component or peak's height.
/// </summary>
double weight;
};
/// <summary>
/// Represents a composite of gaussian distribution components
/// that build up a Gaussian Mixture Model.
/// </summary>
struct GaussianMixtureModel
{
/// <summary>
/// Constructor used for initialization of m/z, intesities and gaussian components
/// collections.
/// </summary>
/// <param name="mzArray">M/z data shared by all spectra.</param>
/// <param name="intensities">Mean intensities at each point.</param>
/// <param name="numberOfComponents">Number of Gaussian Components to be set.</param>
GaussianMixtureModel(const gsl::span<double> &mzArray,
const gsl::span<double> &intensities,
const std::vector<GaussianComponent> &&components) :
originalMzArray(mzArray.begin(), mzArray.end()),
originalMeanSpectrum(intensities.begin(), intensities.end()),
components(std::move(components)),
isMerged(), isNoiseReduced(), mzMergingThreshold() // will be used in future.
{ }
/// <summary>
/// Collection of Gaussian components.
/// </summary>
const std::vector<GaussianComponent> components;
/// <summary>
/// Collection of initially supplied mz values.
/// </summary>
const std::vector<double> originalMzArray;
/// <summary>
/// Collection of average supplied spectra.
/// </summary>
const std::vector<double> originalMeanSpectrum;
/// <summary>
/// M/z threshold used in components merging.
/// </summary>
const double mzMergingThreshold;
/// <summary>
/// Value indicating whether this instance is merged.
/// </summary>
const bool isMerged;
/// <summary>
/// Gets a value indicating whether this instance is noise components reduced.
/// </summary>
const bool isNoiseReduced;
};
}
| {
"alphanum_fraction": 0.6636125654,
"avg_line_length": 30.56,
"ext": "h",
"hexsha": "7ef2eedcb322dcfd6ce0888377f4ac60517c3a03",
"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": "e5e4a65b52d44bc6c0efe68743eae83a08871664",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "spectre-team/native-algorithms",
"max_forks_repo_path": "src/Spectre.libGaussianMixtureModelling/GaussianMixtureModel.h",
"max_issues_count": 36,
"max_issues_repo_head_hexsha": "e5e4a65b52d44bc6c0efe68743eae83a08871664",
"max_issues_repo_issues_event_max_datetime": "2018-08-03T21:18:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-31T16:44:51.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "spectre-team/native-algorithms",
"max_issues_repo_path": "src/Spectre.libGaussianMixtureModelling/GaussianMixtureModel.h",
"max_line_length": 89,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e5e4a65b52d44bc6c0efe68743eae83a08871664",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "spectre-team/native-algorithms",
"max_stars_repo_path": "src/Spectre.libGaussianMixtureModelling/GaussianMixtureModel.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 676,
"size": 3056
} |
#ifndef FIT_GSL_H
#define FIT_GSL_H
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
class Fit;
//! Structure for fitting data
struct FitData {
size_t n;// number of points to be fitted (size of X, Y and sigma arrays)
size_t p;// number of fit parameters
double * X;// the data to be fitted (abscissae)
double * Y; // the data to be fitted (ordinates)
double * sigma; // the weighting data
Fit *fitter; //pointer to the fitter object (used only for the NonLinearFit class)
};
int expd3_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
int expd3_df (const gsl_vector * x, void *params, gsl_matrix * J);
int expd3_f (const gsl_vector * x, void *params, gsl_vector * f);
double expd3_d (const gsl_vector * x, void *params);
int expd2_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
int expd2_df (const gsl_vector * x, void *params, gsl_matrix * J);
int expd2_f (const gsl_vector * x, void *params, gsl_vector * f);
double expd2_d (const gsl_vector * x, void *params);
int exp_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
int exp_df (const gsl_vector * x, void *params, gsl_matrix * J);
int exp_f (const gsl_vector * x, void *params, gsl_vector * f);
double exp_d (const gsl_vector * x, void *params);
int boltzmann_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
int boltzmann_df (const gsl_vector * x, void *params, gsl_matrix * J);
int boltzmann_f (const gsl_vector * x, void *params, gsl_vector * f);
double boltzmann_d (const gsl_vector * x, void *params);
int logistic_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
int logistic_df (const gsl_vector * x, void *params, gsl_matrix * J);
int logistic_f (const gsl_vector * x, void *params, gsl_vector * f);
double logistic_d (const gsl_vector * x, void *params);
int gauss_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
int gauss_df (const gsl_vector * x, void *params, gsl_matrix * J);
int gauss_f (const gsl_vector * x, void *params,gsl_vector * f);
double gauss_d (const gsl_vector * x, void *params);
int gauss_multi_peak_f (const gsl_vector * x, void *params, gsl_vector * f);
double gauss_multi_peak_d (const gsl_vector * x, void *params);
int gauss_multi_peak_df (const gsl_vector * x, void *params, gsl_matrix * J);
int gauss_multi_peak_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
int lorentz_multi_peak_f (const gsl_vector * x, void *params, gsl_vector * f);
double lorentz_multi_peak_d (const gsl_vector * x, void *params);
int lorentz_multi_peak_df (const gsl_vector * x, void *params, gsl_matrix * J);
int lorentz_multi_peak_fdf (const gsl_vector * x, void *params, gsl_vector * f, gsl_matrix * J);
int user_f(const gsl_vector * x, void *params, gsl_vector * f);
double user_d(const gsl_vector * x, void *params);
int user_df(const gsl_vector * x, void *params,gsl_matrix * J);
int user_fdf(const gsl_vector * x, void *params,gsl_vector * f, gsl_matrix * J);
#endif
| {
"alphanum_fraction": 0.7252208047,
"avg_line_length": 47.0307692308,
"ext": "h",
"hexsha": "9d3b4d22a10251a0899bae7ce687812b26326f21",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z",
"max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca",
"max_forks_repo_licenses": [
"IJG"
],
"max_forks_repo_name": "hoehnp/SpaceDesignTool",
"max_forks_repo_path": "thirdparty/qtiplot/qtiplot/src/analysis/fit_gsl.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca",
"max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z",
"max_issues_repo_licenses": [
"IJG"
],
"max_issues_repo_name": "hoehnp/SpaceDesignTool",
"max_issues_repo_path": "thirdparty/qtiplot/qtiplot/src/analysis/fit_gsl.h",
"max_line_length": 96,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca",
"max_stars_repo_licenses": [
"IJG"
],
"max_stars_repo_name": "hoehnp/SpaceDesignTool",
"max_stars_repo_path": "thirdparty/qtiplot/qtiplot/src/analysis/fit_gsl.h",
"max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z",
"num_tokens": 881,
"size": 3057
} |
/*
** 1st level statistical inference using LISA
** GLM (general linear modeling) using precoloring
**
** G.Lohmann, MPI-KYB, 2018
*/
#include <viaio/Vlib.h>
#include <viaio/VImage.h>
#include <viaio/mu.h>
#include <viaio/option.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_math.h>
extern gsl_matrix *PseudoInv(gsl_matrix *A,gsl_matrix *B);
extern void printmat(gsl_matrix *R,char *str);
extern void printvec(gsl_vector *x,char *str);
/*
** general linear model (GLM) using pecoloring
*/
void VGLM(gsl_matrix *Data,gsl_matrix *X,gsl_matrix *XInv,gsl_vector *con,VImage map,VImage zmap)
{
int i;
int m = Data->size2;
int n = con->size;
gsl_set_error_handler_off();
gsl_vector *y = gsl_vector_calloc (m);
gsl_vector *beta = gsl_vector_calloc (n);
/* compute pseudoinverse */
XInv = PseudoInv(X,XInv);
/* main loop */
VFillImage(zmap,VAllBands,0);
size_t nvox=0;
for (nvox=0; nvox < Data->size1; nvox++) {
y->data = gsl_matrix_ptr(Data,nvox,0);
gsl_blas_dgemv(CblasNoTrans,1.0,XInv,y,0.0,beta);
/* contrast image */
double sum=0;
for (i=0; i<beta->size; i++) {
sum += (beta->data[i]*con->data[i]);
}
if (gsl_isnan(sum) || gsl_isinf(sum)) continue;
int b = VPixel(map,0,0,nvox,VShort);
int r = VPixel(map,0,1,nvox,VShort);
int c = VPixel(map,0,2,nvox,VShort);
VPixel(zmap,b,r,c,VFloat) = sum;
}
gsl_vector_free(beta);
gsl_vector_free(y);
}
| {
"alphanum_fraction": 0.6660280971,
"avg_line_length": 22.6956521739,
"ext": "c",
"hexsha": "b478e8befafca063c9eb16bc1a13ae778709aa9b",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/stats/vlisa_precoloring/GLM.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/stats/vlisa_precoloring/GLM.c",
"max_line_length": 97,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/stats/vlisa_precoloring/GLM.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": 519,
"size": 1566
} |
#ifndef STRUCTS_H
#define STRUCTS_H
#include <gsl/gsl_randist.h>
#include <stdint.h>
#define N_FEATURES 32
#define BOARD_WIDTH 10
#define BOARD_HEIGHT 20
struct genotype {
float * feature_weights;
int * feature_enabled;
};
struct phenotype {
int fitness;
int has_fitness;
struct genotype* genotype;
};
struct population {
int size;
struct phenotype** individuals;
};
struct board {
uint16_t lines[BOARD_HEIGHT];
};
struct tetromino {
int p_top;
int p_left;
int p_right;
int p_bottom;
uint16_t lines[4];
};
struct tetromino tetrominos[19];
struct t_last_placement {
struct tetromino * tetromino;
int x;
int y;
int n_lines_removed;
int * lines_removed;
};
enum selection {
TOURNAMENT,
SUS,
SIGMA,
};
struct feature {
char * name;
int weights;
float (* function) (struct board *, struct board *, struct t_last_placement *);
};
struct feature features[N_FEATURES];
struct options {
int feature_enabled[N_FEATURES];
int enabled_f_indices[N_FEATURES];
int n_features_enabled;
int n_weights_enabled;
int verbose;
int population_size;
int tournament_group_size;
int max_n_generations;
int crossover_points;
int elitism;
int no_log;
int no_change_duration;
int reset_volume;
int n_trials;
int print_board;
int n_piece_lookahead;
int randomization_range;
int mutation_range;
float feature_enable_rate;
float mutation_rate;
float crossover_rate;
float tournament_group_random_selection;
enum selection selection;
char* log_directory;
gsl_rng * rng;
};
#endif | {
"alphanum_fraction": 0.6899038462,
"avg_line_length": 16.9795918367,
"ext": "h",
"hexsha": "81027ba8c9544d1c8d5779b7628877234ec8886c",
"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": "7b5b2480dd7672855822188bdee63f608720bee8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "badeball/tetris-ea",
"max_forks_repo_path": "code/include/structs.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7b5b2480dd7672855822188bdee63f608720bee8",
"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": "badeball/tetris-ea",
"max_issues_repo_path": "code/include/structs.h",
"max_line_length": 83,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "7b5b2480dd7672855822188bdee63f608720bee8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "badeball/tetris-ea",
"max_stars_repo_path": "code/include/structs.h",
"max_stars_repo_stars_event_max_datetime": "2017-05-13T13:53:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-13T13:53:07.000Z",
"num_tokens": 389,
"size": 1664
} |
#ifndef __HCORE__
#define __HCORE__
#ifdef MKL
#include <mkl.h>
#include <mkl_lapack.h>
//#pragma message("MKL is used")
#else
#ifdef ARMPL
#include <armpl.h>
#else
#include <cblas.h>
#endif
#ifdef LAPACKE_UTILS
#include <lapacke_utils.h>
#endif
#include <lapacke.h>
//#pragma message("MKL is NOT used")
#endif
#ifndef hcore_min
#define hcore_min(a, b) ((a) < (b) ? (a) : (b))
#endif
#ifndef hcore_max
#define hcore_max(a, b) ((a) < (b) ? (b) : (a))
#endif
#define HCORE_NoTrans 111
#define HCORE_Trans 112
#define HCORE_ConjTrans 113
#define HCORE_Upper 121
#define HCORE_Lower 122
#define HCORE_UpperLower 123
#define HCORE_NonUnit 131
#define HCORE_Unit 132
#define HCORE_Left 141
#define HCORE_Right 142
typedef int HCORE_enum;
#endif
| {
"alphanum_fraction": 0.6264367816,
"avg_line_length": 18.9130434783,
"ext": "h",
"hexsha": "ea4033365ed26f9f3f6740bc8402c85f77855df9",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-03-01T14:44:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-01T14:44:20.000Z",
"max_forks_repo_head_hexsha": "0b1c6d659e56d10795fc1838c1e2959e2afad8ad",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ecrc/hcore",
"max_forks_repo_path": "src/include/hcore.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0b1c6d659e56d10795fc1838c1e2959e2afad8ad",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "ecrc/hcore",
"max_issues_repo_path": "src/include/hcore.h",
"max_line_length": 47,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0b1c6d659e56d10795fc1838c1e2959e2afad8ad",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ecrc/hcore",
"max_stars_repo_path": "src/include/hcore.h",
"max_stars_repo_stars_event_max_datetime": "2021-04-04T19:12:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-04T19:12:33.000Z",
"num_tokens": 277,
"size": 870
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#define COMPEARTH_PRIVATE_DET3X3 1
#define COMPEARTH_PRIVATE_CROSS3 1
#define COMPEARTH_PRIVATE_NORM3 1
#define COMPEARTH_PRIVATE_GEM3 1
#define COMPEARTH_PRIVATE_GEMT3 1
#include "compearth.h"
#ifdef COMPEARTH_USE_MKL
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wstrict-prototypes"
#endif
#include <mkl_lapacke.h>
//#include <mkl_cblas.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#else
#include <lapacke.h>
//#include <cblas.h>
#endif
#define LWORK 15
/*!
* @brief Converts a nearly orthogonal matrix into a numerically orthogonal
* matrix.
*
* @param[in] n Number of bases.
* @param[in] itype Orthogonalization strategy. \n
* CE_ORTH_SVD orthgonalizes with the SVD. \n
* CE_ORTH_TAPE2012 orthogalizes with Tape 2012c
* Appendix E. \n
* CE_ORTH_QUAT orthogonalizes with quaternions.
* @param[in] Uin [3 x 3 x n] set of bases where each [3 x 3] basis is
* in column major order.
*
* @param[out] Uout [3 x 3 x n] set of re-orthgonalized bases where
* each [3 x 3] bais is in column major order.
* @param[out] dtUin If NULL then this will be ignored. \n
* Otherwise, this is an array of dimension [n] holding
* the determinants of the input basis.
* @param[out] dtUout If NULL then this will be ignored. \n
* Otherwise, this is an array of dimension [n] holding
* the determinants of the output basis.
*
* @result 0 indicates success.
*
* @author Carl Tape and converted to C by Ben Baker.
*
*/
int compearth_Uorth(const int n,
const enum ceOrthoType_enum itype,
const double *__restrict__ Uin,
double *__restrict__ Uout,
double *__restrict__ dtUin,
double *__restrict__ dtUout)
{
double Ut[9] __attribute__((aligned(64)));
double U[9] __attribute__((aligned(64)));
double Vt[9] __attribute__((aligned(64)));
double work[LWORK], s[3], p[3], det, normb, normp;
int i, ierr;
bool lwantDetIn;
const double tol = DBL_EPSILON*100.0;
// Check inputs
if (n < 1 || Uin == NULL || Uout == NULL)
{
if (n < 1){fprintf(stderr, "%s: No matrices\n", __func__);}
if (Uin == NULL){fprintf(stderr, "%s: Uin is NULL\n", __func__);}
if (Uout == NULL){fprintf(stderr, "%s: Uout is NULL\n", __func__);}
return -1;
}
lwantDetIn = false;
if (dtUin != NULL){lwantDetIn = true;}
// Orthogonalize basis with SVD
if (itype == CE_ORTH_SVD)
{
for (i=0; i<n; i++)
{
// This will frequently be called with matrices that may already
// be sufficiently orthonormal.
det = det3x3ColumnMajor(&Uin[9*i]);
if (fabs(det - 1.0) > 1.e-12)
{
// Compute SVD
memcpy(Ut, &Uin[9*i], 9*sizeof(double));
ierr = LAPACKE_dgesvd_work(LAPACK_COL_MAJOR, 'A', 'A',
3, 3, Ut, 3, s, U, 3,
Vt, 3, work, LWORK);
if (ierr != 0)
{
fprintf(stderr, "%s: Error computing Ut\n", __func__);
return -1;
}
// Compute U*V' - note Vt is already computed by SVD
gemm3_colMajorNoTransNoTrans(U, Vt, &Uout[9*i]);
// N.B. I could get the determinant here from the singular
// values but i'll wait
}
else
{
memcpy(&Uout[9*i], &Uin[9*i], 9*sizeof(double));
}
if (lwantDetIn){dtUin[i] = det;}
}
}
// Orthgonalize with suggestion in TapeTape2012c Appendix E
else if (itype == CE_ORTH_TAPE2012)
{
for (i=0; i<n; i++)
{
// This will frequently be called with matrices that may already
// be sufficiently orthonormal.
det = det3x3ColumnMajor(&Uin[9*i]);
if (fabs(det - 1.0) > tol)
{
cross3(&Uin[9*i], &Uin[9*i+3], p);
normb = norm3(&Uin[9*i+3]);
normp = norm3(p);
Uout[9*i] = Uin[9*i];
Uout[9*i+1] = Uin[9*i+1];
Uout[9*i+2] = Uin[9*i+2];
Uout[9*i+3] = Uin[9*i+3]/normb;
Uout[9*i+4] = Uin[9*i+4]/normb;
Uout[9*i+5] = Uin[9*i+5]/normb;
Uout[9*i+6] = Uin[9*i+6]/normp;
Uout[9*i+7] = Uin[9*i+7]/normp;
Uout[9*i+8] = Uin[9*i+8]/normp;
}
else
{
memcpy(&Uout[9*i], &Uin[9*i], 9*sizeof(double));
}
if (lwantDetIn){dtUin[i] = det;}
}
}
else if (itype == CE_ORTH_QUAT)
{
fprintf(stderr, "%s: Error quaternions not yet programmed\n",
__func__);
return -1;
}
else if (itype == CE_NO_ORTH)
{
memcpy(Uout, Uin, 9*(size_t) n*sizeof(double));
//cblas_dcopy(9*n, Uin, 1, Uout, 1);
}
else
{
fprintf(stderr, "%s: Only itype=1 is programmed\n", __func__);
return -1;
}
//if (dtUin != NULL)
//{
// for (i=0; i<n; i++)
// {
// dtUin[i] = det3x3ColumnMajor(&Uin[9*i]);
// }
//}
if (dtUout != NULL)
{
for (i=0; i<n; i++)
{
dtUout[i] = det3x3ColumnMajor(&Uout[9*i]);
}
}
return 0;
}
| {
"alphanum_fraction": 0.5101207688,
"avg_line_length": 33.5942857143,
"ext": "c",
"hexsha": "184e22a232b6a8a23ab9768b171b66a56cf9acf0",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z",
"max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "carltape/mtbeach",
"max_forks_repo_path": "c_src/Uorth.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "carltape/mtbeach",
"max_issues_repo_path": "c_src/Uorth.c",
"max_line_length": 76,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "OUCyf/mtbeach",
"max_stars_repo_path": "c_src/Uorth.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z",
"num_tokens": 1696,
"size": 5879
} |
/* ieee-utils/make_rep.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_ieee_utils.h>
#include "endian.c"
#include "standardize.c"
static void sprint_nybble(int i, char *s) ;
static void sprint_byte(int i, char *s) ;
static int determine_ieee_type (int non_zero, int exponent, int max_exponent);
/* For the IEEE float format the bits are found from the following
masks,
sign = 0x80000000
exponent = 0x7f800000
mantisssa = 0x007fffff
For the IEEE double format the masks are,
sign = 0x8000000000000000
exponent = 0x7ff0000000000000
mantissa = 0x000fffffffffffff
*/
void
gsl_ieee_float_to_rep (const float * x, gsl_ieee_float_rep * r)
{
int e, non_zero;
union {
float f;
struct {
unsigned char byte[4] ;
} ieee ;
} u;
u.f = *x ;
if (little_endian_p())
make_float_bigendian(&(u.f)) ;
/* note that r->sign is signed, u.ieee.byte is unsigned */
if (u.ieee.byte[3]>>7)
{
r->sign = 1 ;
}
else
{
r->sign = 0 ;
}
e = (u.ieee.byte[3] & 0x7f) << 1 | (u.ieee.byte[2] & 0x80)>>7 ;
r->exponent = e - 127 ;
sprint_byte((u.ieee.byte[2] & 0x7f) << 1,r->mantissa) ;
sprint_byte(u.ieee.byte[1],r->mantissa + 7) ;
sprint_byte(u.ieee.byte[0],r->mantissa + 15) ;
r->mantissa[23] = '\0' ;
non_zero = u.ieee.byte[0] || u.ieee.byte[1] || (u.ieee.byte[2] & 0x7f);
r->type = determine_ieee_type (non_zero, e, 255) ;
}
void
gsl_ieee_double_to_rep (const double * x, gsl_ieee_double_rep * r)
{
int e, non_zero;
union
{
double d;
struct {
unsigned char byte[8];
} ieee ;
} u;
u.d= *x ;
if (little_endian_p())
make_double_bigendian(&(u.d)) ;
/* note that r->sign is signed, u.ieee.byte is unsigned */
if (u.ieee.byte[7]>>7)
{
r->sign = 1 ;
}
else
{
r->sign = 0 ;
}
e =(u.ieee.byte[7] & 0x7f)<<4 ^ (u.ieee.byte[6] & 0xf0)>>4 ;
r->exponent = e - 1023 ;
sprint_nybble(u.ieee.byte[6],r->mantissa) ;
sprint_byte(u.ieee.byte[5],r->mantissa + 4) ;
sprint_byte(u.ieee.byte[4],r->mantissa + 12) ;
sprint_byte(u.ieee.byte[3],r->mantissa + 20) ;
sprint_byte(u.ieee.byte[2],r->mantissa + 28) ;
sprint_byte(u.ieee.byte[1],r->mantissa + 36) ;
sprint_byte(u.ieee.byte[0],r->mantissa + 44) ;
r->mantissa[52] = '\0' ;
non_zero = (u.ieee.byte[0] || u.ieee.byte[1] || u.ieee.byte[2]
|| u.ieee.byte[3] || u.ieee.byte[4] || u.ieee.byte[5]
|| (u.ieee.byte[6] & 0x0f)) ;
r->type = determine_ieee_type (non_zero, e, 2047) ;
}
/* A table of character representations of nybbles */
static char nybble[16][5]={ /* include space for the \0 */
"0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"
} ;
static void
sprint_nybble(int i, char *s)
{
char *c ;
c=nybble[i & 0x0f ];
*s=c[0] ; *(s+1)=c[1] ; *(s+2)=c[2] ; *(s+3)=c[3] ;
}
static void
sprint_byte(int i, char *s)
{
char *c ;
c=nybble[(i & 0xf0)>>4];
*s=c[0] ; *(s+1)=c[1] ; *(s+2)=c[2] ; *(s+3)=c[3] ;
c=nybble[i & 0x0f];
*(s+4)=c[0] ; *(s+5)=c[1] ; *(s+6)=c[2] ; *(s+7)=c[3] ;
}
static int
determine_ieee_type (int non_zero, int exponent, int max_exponent)
{
if (exponent == max_exponent)
{
if (non_zero)
{
return GSL_IEEE_TYPE_NAN ;
}
else
{
return GSL_IEEE_TYPE_INF ;
}
}
else if (exponent == 0)
{
if (non_zero)
{
return GSL_IEEE_TYPE_DENORMAL ;
}
else
{
return GSL_IEEE_TYPE_ZERO ;
}
}
else
{
return GSL_IEEE_TYPE_NORMAL ;
}
}
| {
"alphanum_fraction": 0.585198316,
"avg_line_length": 22.7929292929,
"ext": "c",
"hexsha": "59bf861243bec0fb5f8608cc489f9910ebfe60ca",
"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/ieee-utils/make_rep.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/ieee-utils/make_rep.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/ieee-utils/make_rep.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": 1590,
"size": 4513
} |
/*
** centrality maps using spectral coherence
**
** get cross-periodogram via multiplication of FFTs
**
** Ref: T. Subba Rao,
** On the Cross Periodogram of a Stationary Gaussian Vector Process,
** The Annals of Mathematical Statistics, Vol. 38, No. 2 (Apr., 1967),
** pp. 593-597. (2239172.pdf)
**
** Implementation follows SAS, see
** http://www.tau.ac.il/cc/pages/docs/sas8/ets/chap17/
**
** G.Lohmann, September 2009
*/
#include <viaio/Vlib.h>
#include <viaio/VImage.h>
#include <viaio/mu.h>
#include <viaio/option.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_math.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265
#define SQR(x) ((x) * (x))
#define ABS(x) ((x) > 0 ? (x) : -(x))
#ifdef _OPENMP
#include <omp.h>
#endif /*_OPENMP*/
/* re-implementation of cblas_sspmv, cblas_sspmv causes problems */
void my_sspmv(float *A,float *x,float *y,int n)
{
size_t i,j,k,kk;
float tmp1=0,tmp2=0;
for (j=0; j<n; j++) y[j] = 0;
kk = k = 0;
for (j=0; j<n; j++) {
tmp1 = x[j];
tmp2 = 0;
k = kk;
for (i=0; i<j; i++) {
y[i] += tmp1 * A[k];
tmp2 += A[k] * x[i];
k++;
}
y[j] += tmp1*A[kk+j] + tmp2;
kk += (j+1);
}
}
double Normalize(double *data,int n)
{
int i;
double sum,nx=(double)n;
sum = 0;
for (i=0; i<n; i++) sum += data[i];
sum /= nx;
for (i=0; i<n; i++) data[i] -= sum;
return sum;
}
double Tukey(double x,double wx)
{
if (ABS(x) >= wx) return 0;
else return 0.5*(1.0 + cos((PI*x)/wx));
}
int GetFFtIndex(int n,double tr,double wavelength)
{
int k0;
double nx,cycle;
nx = (double)n;
cycle = wavelength / tr;
k0 = (int)(nx/cycle + 0.5);
return k0;
}
double *Weights(int n,int k0,int p)
{
int k;
double *w=NULL;
double kx,wx,sum;
w = (double *) VCalloc(n,sizeof(double));
wx = (double) p;
kx = 0;
for (k=0; k<p; k++) {
w[k] = Tukey(kx,wx);
kx++;
}
sum = 0;
for (k=0; k<p; k++) sum += w[k];
sum *= (2.0*PI);
for (k=0; k<p; k++) w[k] /= sum;
return w;
}
void Tables(gsl_matrix *tablecos,gsl_matrix *tablesin)
{
int i,k,n;
double kx,ix,nx,w;
n = tablecos->size1;
nx = (double)n;
kx = 0;
for (k=0; k<n; k++) {
w = 2.0*PI*kx/nx;
ix = 0;
for (i=1; i<n; i++) {
gsl_matrix_set(tablecos,k,i,cos(w*ix));
gsl_matrix_set(tablesin,k,i,sin(w*ix));
ix++;
}
kx++;
}
}
void FFT(double *in,double *xcos,double *xsin,gsl_matrix *tablecos,gsl_matrix *tablesin)
{
int i,k,n;
double sum1,sum2,kx,ix,nx;
n = tablecos->size1;
nx = 1;
kx = 0;
for (k=0; k<n; k++) {
if (k >= tablecos->size1) VError(" k= %d",k);
if (k >= tablesin->size1) VError(" k= %d",k);
sum1 = sum2 = 0;
/* w = 2.0*PI*kx/nx; */
ix = 0;
for (i=0; i<n; i++) {
sum1 += in[i]*gsl_matrix_get(tablecos,k,i);
sum2 += in[i]*gsl_matrix_get(tablesin,k,i);
ix++;
}
xcos[k] = 2.0*sum1/nx;
xsin[k] = 2.0*sum2/nx;
kx++;
}
}
void DegreeCentrality(float *A,float *ev,size_t n)
{
size_t i,j,k;
double sum=0,nx=(double)n;
fprintf(stderr," degree centrality, n= %lu\n",n);
for (i=0; i<n; i++) {
sum=0;
for (j=0; j<n; j++) {
if (i==j) continue;
if (j < i) k=j+i*(i+1)/2;
else k=i+j*(j+1)/2;
sum += A[k];
}
ev[i] = (float)(100.0*sum/nx);
}
}
void EigenvectorCentrality(float *A,float *ev,size_t n)
{
size_t i,iter,maxiter;
float sum,d,nx;
static float *y=NULL;
fprintf(stderr," power iteration, n= %lu\n",n);
if (y==NULL) y = (float *) VCalloc(n,sizeof(float));
if (!y) VError(" err allocating vector ");
nx = sqrt((double)n);
for (i=0; i<n; i++) ev[i] = y[i] = 1.0/nx;
maxiter=50;
for (iter=0; iter < maxiter; iter++) {
/* y = Ax, A symmetric and lower-triangular */
/* cblas_sspmv(CblasRowMajor,CblasLower,(int)n,1.0f,A,ev,1,1.0f,y,1); */
my_sspmv(A,ev,y,n);
sum = 0;
for (i=0; i<n; i++) sum += y[i]*y[i];
sum = sqrt(sum);
d = 0;
for (i=0; i<n; i++) {
d += SQR(ev[i] - y[i]/sum);
ev[i] = y[i]/sum;
}
fprintf(stderr," %5lu %f\n",iter,d);
if (d < 1.0e-6) break;
}
for (i=0; i<n; i++) ev[i] *= 100.0;
fprintf(stderr," ecm done..\n");
}
VImage WriteOutput(VImage src,VImage map,int nslices,int nrows, int ncols, float *ev, size_t n)
{
size_t i,b,r,c;
VImage dest = VCreateImage(nslices,nrows,ncols,VFloatRepn);
VFillImage(dest,VAllBands,0);
VCopyImageAttrs (src, dest);
for (i=0; i<n; i++) {
b = VPixel(map,0,0,i,VInteger);
r = VPixel(map,0,1,i,VInteger);
c = VPixel(map,0,2,i,VInteger);
/* if (ev[i] > 0) fprintf(stderr," %6d %3d %3d %3d %f\n",i,c,r,b,ev[i]); */
VPixel(dest,b,r,c,VFloat) = ev[i];
}
return dest;
}
VAttrList VSpectralECM(VAttrList list,VImage mask,VDouble wavelength,VShort nlags,
VShort first,VShort length,VShort type)
{
int b,r,c,j,k,kk,k0,n,p;
size_t i;
size_t m,nvox;
int last;
gsl_matrix *matcos=NULL,*matsin=NULL;
float *A=NULL,*ev=NULL;
float tr=-1,xtr=-1;
double *in,*xsin=NULL,*xcos=NULL,*w=NULL;
double nx,u,sumx,freq=0;
gsl_matrix *tablecos=NULL,*tablesin=NULL;
double pi = 2.0*acos(0);
/* get image dimensions */
int nrows=0,ncols=0,nt=0;
int nslices = VAttrListNumImages(list);
VImage *src = VAttrListGetImages(list,nslices);
VImageDimensions(src,nslices,&nt,&nrows,&ncols);
size_t ntimesteps = nt;
if (VImageNRows(mask) != nrows)
VError(" inconsistent image dims, mask has %d rows, image has %d rows",VImageNRows(mask),nrows);
if (VImageNColumns(mask) != ncols)
VError(" inconsistent image dims, mask has %d columns, image has %d columns",VImageNColumns(mask),ncols);
if (VImageNBands(mask) != nslices)
VError(" inconsistent image dims, mask has %d slices, image has %d slices",VImageNBands(mask),nslices);
/* get time steps to include */
if (first < 0) first = 0;
if (length <= 0) length = ntimesteps;
last = first + length -1;
if (last >= ntimesteps) last = ntimesteps-1;
n = last - first + 1;
if (n < 2) VError(" not enough timesteps, nt= %d",n);
nx = (double)n;
/*
** get freq range
*/
if (VGetAttr (VImageAttrList (src[0]), "repetition_time", NULL,
VFloatRepn, (VPointer) & xtr) == VAttrFound) {
tr = (xtr/1000.0);
}
if (tr <= 0) VError(" illegal tr: %f",tr);
k0 = GetFFtIndex((int)n,tr,wavelength);
freq = 1.0/wavelength;
fprintf(stderr," TR= %g secs, wavelength= %g secs, freq= %.3f Hz, k0= %d\n",
tr,wavelength,freq,k0);
if (k0 < 1 || k0 >= n/2) VError(" illegal freq, index must be in [1,%d]\n",n/2);
/* weights */
if (nlags < 0)
p = n/15; /* default */
else
p = (int)nlags;
if (p < 3) VError(" nlags too small, %d",p);
w = Weights((int)n,k0,p);
/* count number of voxels */
nvox = 0;
for (b=0; b<nslices; b++) {
if (VImageNRows(src[b]) < 2) continue;
for (r=0; r<nrows; r++) {
for (c=0; c<ncols; c++) {
if (fabs(VGetPixel(mask,b,r,c)) < TINY) continue;
nvox++;
}
}
}
fprintf(stderr," nvoxels: %ld, n= %d, nlags= %d\n",(long)nvox, (int)n, (int)p);
/*
** voxel maps
*/
VImage map = VCreateImage(1,4,nvox,VIntegerRepn);
if (map == NULL) VError(" error allocating addr map");
VFillImage(map,VAllBands,0);
VPixel(map,0,3,0,VInteger) = nslices;
VPixel(map,0,3,1,VInteger) = nrows;
VPixel(map,0,3,2,VInteger) = ncols;
double *xmap = (double *)VCalloc(nvox,sizeof(double));
i = 0;
for (b=0; b<nslices; b++) {
if (VImageNRows(src[b]) < 2) continue;
for (r=0; r<nrows; r++) {
for (c=0; c<ncols; c++) {
if (fabs(VGetPixel(mask,b,r,c)) < TINY) continue;
VPixel(map,0,0,i,VInteger) = b;
VPixel(map,0,1,i,VInteger) = r;
VPixel(map,0,2,i,VInteger) = c;
i++;
}
}
}
/* alloc memory */
in = (double *)VCalloc(n,sizeof(double));
xsin = (double *)VCalloc(n,sizeof(double));
xcos = (double *)VCalloc(n,sizeof(double));
tablecos = gsl_matrix_calloc((int)n,(int)n);
if (tablecos == NULL) VError(" err alloc cos");
tablesin = gsl_matrix_calloc((int)n,(int)n);
if (tablesin == NULL) VError(" err alloc sin");
Tables(tablecos,tablesin);
/*
** precompute FFT
*/
matcos = gsl_matrix_calloc(nvox,(int)n);
if (!matcos) VError(" err alloc matcos");
matsin = gsl_matrix_calloc(nvox,(int)n);
if (!matsin) VError(" err alloc matsin");
Tables(tablecos,tablesin);
for (i=0; i<nvox; i++) {
b = VPixel(map,0,0,i,VInteger);
r = VPixel(map,0,1,i,VInteger);
c = VPixel(map,0,2,i,VInteger);
j = 0;
for (k=first; k<=last; k++) {
in[j++] = (double) VGetPixel(src[b],k-first,r,c);
}
double q = Normalize(in,n);
if (fabs(q) < TINY) continue;
FFT(in,xcos,xsin,tablecos,tablesin);
nx = (double)n;
sumx = 0;
for (k=-p; k<=p; k++) {
kk = k+k0;
if (kk < 0) kk = -k;
if (kk >= n) kk = n-k;
u = 2.0*(xcos[kk]*xcos[kk] + xsin[kk]*xsin[kk])/nx;
sumx += w[ABS(k)]*u;
}
xmap[i] = sumx;
for (k=0; k<n; k++) {
gsl_matrix_set(matcos,i,k,xcos[k]);
gsl_matrix_set(matsin,i,k,xsin[k]);
}
}
/*
** compute spectral coherence matrix
*/
m = (nvox*(nvox+1))/2;
fprintf(stderr," matrix computation, n= %ld...\n",(long)nvox);
A = (float *) VCalloc(m,sizeof(float));
if (!A) VError(" err allocating matrix");
memset(A,0,m*sizeof(float));
size_t progress=0;
#pragma omp parallel for shared(progress) schedule(guided) firstprivate(A,xmap)
for (i=0; i<nvox; i++) {
if (i%1000 == 0) fprintf(stderr," %d000 of %ld\r",(int)(++progress),(long)nvox);
size_t j=0,kij=0;
int k=0,kk=0;
double v=0,x=0,y=0,cs=0,qs=0,c1,s1,c2,s2,re,im;
x = xmap[i];
for (j=0; j<i; j++) {
y = xmap[j];
cs = qs = 0;
for (k=-p; k<=p; k++) {
kk = k+k0;
if (kk < 0) kk = -k;
if (kk >= n) kk = n-k;
c1 = gsl_matrix_get(matcos,i,kk);
s1 = gsl_matrix_get(matsin,i,kk);
c2 = gsl_matrix_get(matcos,j,kk);
s2 = gsl_matrix_get(matsin,j,kk);
re = 2.0*(c1*c2 + s1*s2)/nx;
im = 2.0*(c1*s2 - s1*c2)/nx;
cs += w[ABS(k)] * re;
qs += w[ABS(k)] * im;
}
if (type == 0) { /* spectral coherence */
if (x*y > TINY) {
v = (cs*cs + qs*qs) / (x*y);
v = sqrt(v);
}
else v = -1;
}
else { /* phase sync */
v = atan2(qs,cs)/pi;
/* v = 1.0 - ABS(v); */
v = cos(v);
}
if (v < TINY) v = TINY; /* make matrix irreducible */
kij=j+i*(i+1)/2;
A[kij] = v;
}
}
/* free space */
gsl_matrix_free(matcos);
gsl_matrix_free(matsin);
/*
** eigenvector centrality
*/
ev = (float *) VCalloc(nvox,sizeof(float));
EigenvectorCentrality(A,ev,nvox);
/* DegreeCentrality(A,ev,nvox); */
VImage dest0 = WriteOutput(src[0],map,nslices,nrows,ncols,ev,nvox);
VSetAttr(VImageAttrList(dest0),"name",NULL,VStringRepn,"eigenvector_centrality");
VAttrList out_list = VCreateAttrList();
VAppendAttr(out_list,"image",NULL,VImageRepn,dest0);
return out_list;
}
VDictEntry TYPDict[] = {
{ "freq", 0 },
{ "sync", 1 },
{ NULL }
};
int main (int argc,char *argv[])
{
static VDouble wavelength = 10;
static VShort nlags = 10;
static VShort first = 0;
static VShort length = 0;
static VShort type = 0;
static VString mask_filename = "";
static VShort nproc = 0;
static VOptionDescRec options[] = {
{"wavelength", VDoubleRepn,1,(VPointer) &wavelength,VRequiredOpt,NULL,"wavelength in secs"},
{"first",VShortRepn,1,(VPointer) &first,VOptionalOpt,NULL,"first timestep to use"},
{"length",VShortRepn,1,(VPointer) &length,VOptionalOpt,NULL,"length of time series to use"},
{"mask",VStringRepn,1,(VPointer) &mask_filename,VRequiredOpt,NULL,"mask"},
{"nlags",VShortRepn,1,(VPointer) &nlags,VOptionalOpt,NULL,
"num lags in cross-corr, use 0 to get default value"},
{"type",VShortRepn,1,(VPointer) &type,VOptionalOpt,TYPDict,"frequency or phase coherence"},
{"j",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,"Number of processors to use, '0' to use all"}
};
FILE *in_file,*out_file;
VString in_filename=NULL;
char *prg = "vspectralecm";
/* parse command line */
VParseFilterCmdZ (VNumber (options),options,argc,argv,&in_file,&out_file,&in_filename);
if (type > 2) VError(" illegal type");
/* omp-stuff */
#ifdef _OPENMP
int num_procs=omp_get_num_procs();
if (nproc > 0 && nproc < num_procs) num_procs = nproc;
fprintf(stderr,"using %d cores\n",(int)num_procs);
omp_set_num_threads(num_procs);
#endif /* _OPENMP */
/* read mask */
VAttrList listm = VReadAttrList(mask_filename,0L,TRUE,FALSE);
VImage mask = VReadImage(listm);
if (mask == NULL) VError(" no ROI mask found");
/* read functional data */
VAttrList list = VReadAttrListZ(in_file,in_filename,0L,TRUE,FALSE);
if (list == NULL) VError(" error reading input file %s",in_file);
VAttrList geolist = VGetGeoInfo(list);
/*
** process
*/
VAttrList out_list = VSpectralECM(list,mask,wavelength,nlags,first,length,type);
/* update geoinfo, 4D to 3D */
if (geolist != NULL) {
double *D = VGetGeoDim(geolist,NULL);
D[0] = 3; /* 3D */
D[4] = 1; /* just one timestep */
VSetGeoDim(geolist,D);
VSetGeoInfo(geolist,out_list);
}
VHistory(VNumber(options),options,prg,&list,&out_list);
if (! VWriteFile (out_file, out_list)) exit (1);
fprintf (stderr, "%s: done.\n", argv[0]);
return 0;
}
| {
"alphanum_fraction": 0.5814501288,
"avg_line_length": 24.0442477876,
"ext": "c",
"hexsha": "0e4a6d0dea077dcff91ee782914aa14f17207c7c",
"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/nets/vspectralecm/vspectralecm.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/nets/vspectralecm/vspectralecm.c",
"max_line_length": 109,
"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/nets/vspectralecm/vspectralecm.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": 4916,
"size": 13585
} |
#pragma once
#include <mylibs/container.hpp> // pl::Vector
#include <initializer_list> // std::initializer_list
#include "FoodImpl.h" // fa::FoodWithAmount
#include "NoteImpl.h" // fa::NoteImpl
#include "PlanEntry.h" // fa::PlanEntryDynamicDelegator
#include "Date.h" // fa::Date
#include "GlobalHeader.h" // fa::OStream
#include <utility> // std::forward
#include <mylibs/utility.hpp> // pl::forEachArgument
#include <gsl.h> // gsl::not_null
namespace fa {
namespace daily_plan_detail {
template <class Type>
using Container = pl::Vector<Type>;
} // END of namespace daily_plan_detail
class DailyPlanImpl final {
public:
using this_type = DailyPlanImpl;
using DailyPlanFood = FoodWithAmount;
using DailyPlanNote = NoteImpl;
using Interface = PlanEntryInterface;
using FoodUniqueOwner = pl::PolymorphicUniqueOwner<Interface, PlanEntryDynamicDelegator>;
using NoteUniqueOwner = pl::PolymorphicUniqueOwner<Interface, PlanEntryDynamicDelegator>;
using FoodCont = daily_plan_detail::Container<FoodUniqueOwner>;
using NoteCont = daily_plan_detail::Container<NoteUniqueOwner>;
//! put FoodWithAmounts and NoteImpls in here.
template <class ...Args>
explicit DailyPlanImpl(Args &&...args) : date_{ Date::today() } {
pl::forEachArgument([this](auto &&e) {
initCont(std::forward<decltype(e)>(e));
}, std::forward<Args>(args)...);
}
Date getDate() const;
void setDate(Date const &);
void setDate(Date &&);
NutrientTable getAllNutrients() const;
NutrientTable getMacroNutrients() const;
NutrientTable getMicroNutrients() const;
double getMacroPercentage() const;
double getMicroPercentage() const;
double getKcalPercentage() const;
double getOverallPercentage() const;
void addEntry(FoodWithAmount const &);
void addEntry(FoodWithAmount &&);
void addEntry(NoteImpl const &);
void addEntry(NoteImpl &&);
pl::View<FoodCont const> getFoods() const;
pl::View<FoodCont> getFoods();
pl::View<NoteCont const> getNotes() const;
pl::View<NoteCont> getNotes();
daily_plan_detail::Container<gsl::not_null<Interface const *>> getEntries() const;
daily_plan_detail::Container<gsl::not_null<Interface *>> getEntries();
daily_plan_detail::Container<gsl::not_null<DailyPlanFood *>> getFoodsDownCasted();
daily_plan_detail::Container<gsl::not_null<DailyPlanFood const *>> getFoodsDownCasted() const;
daily_plan_detail::Container<gsl::not_null<DailyPlanNote *>> getNotesDownCasted();
daily_plan_detail::Container<gsl::not_null<DailyPlanNote const *>> getNotesDownCasted() const;
friend OStream &operator<<(OStream &, this_type const &);
private:
void initCont(DailyPlanFood const &dpf);
void initCont(DailyPlanFood &&dpf);
void initCont(DailyPlanNote const ¬e);
void initCont(DailyPlanNote &¬e);
NutrientTable getNutrients(FoodCont::const_iterator b,
FoodCont::const_iterator e,
NutrientTable accu) const;
FoodCont foodCont_;
NoteCont noteCont_;
Date date_;
}; // END of class DailyPlanImpl
} // END of namespace fa
| {
"alphanum_fraction": 0.6365178067,
"avg_line_length": 42.119047619,
"ext": "h",
"hexsha": "0aa8c4ef17c2037beccc95b902e40bcf7723bdcd",
"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": "0ed9964fc0470f4ad9e7164af3da7be85c0caf68",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "CppPhil/SE2P_FoodAssistant",
"max_forks_repo_path": "Source/DailyPlanImpl.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0ed9964fc0470f4ad9e7164af3da7be85c0caf68",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "CppPhil/SE2P_FoodAssistant",
"max_issues_repo_path": "Source/DailyPlanImpl.h",
"max_line_length": 103,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0ed9964fc0470f4ad9e7164af3da7be85c0caf68",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "CppPhil/SE2P_FoodAssistant",
"max_stars_repo_path": "Source/DailyPlanImpl.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 803,
"size": 3538
} |
//This gets polynomial coeffs for each row/col of X using the Burg method.
//An opt mean0 is added to zero the mean of each row/col of X first.
//In this case, this is mean0 -> autocov_fft -> sig2ar_burg.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
#ifdef __cplusplus
namespace codee {
extern "C" {
#endif
int sig2ar_burg_s (float *Y, float *V, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t P, const int mean0);
int sig2ar_burg_d (double *Y, double *V, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t P, const int mean0);
int sig2ar_burg_s (float *Y, float *V, const float *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t P, const int mean0)
{
if (dim>3) { fprintf(stderr,"error in sig2ar_burg_s: dim must be in [0 3]\n"); return 1; }
const float o = 1.0f;
const int N = (dim==0) ? R : C;
int r, c, p, q;
float m, g, b2, f2;
float *b, *f, *oldf, *AStmp;
//Checks
if (R<1) { fprintf(stderr,"error in sig2ar_burg_s: nrows X must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in sig2ar_burg_s: ncols X must be positive\n"); return 1; }
if (dim==0 && P>=R) { fprintf(stderr,"error in sig2ar_burg_s: P must be < nrows X for dim==0\n"); return 1; }
if (dim==1 && P>=C) { fprintf(stderr,"error in sig2ar_burg_s: P must be < ncols X for dim==1\n"); return 1; }
//Allocate
if (!(b=(float *)malloc((size_t)(N)*sizeof(float)))) { fprintf(stderr,"error in sig2ar_burg_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(f=(float *)malloc((size_t)(N)*sizeof(float)))) { fprintf(stderr,"error in sig2ar_burg_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(oldf=(float *)malloc((size_t)(N)*sizeof(float)))) { fprintf(stderr,"error in sig2ar_burg_s: problem with malloc. "); perror("malloc"); return 1; }
if (!(AStmp=(float *)malloc((size_t)(P)*sizeof(float)))) { fprintf(stderr,"error in sig2ar_burg_s: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0)
{
if (iscolmajor)
{
for (size_t c=0; c<C; c++)
{
cblas_scopy((int)R,&X[c*R],1,b,1);
if (mean0)
{
m = cblas_sdot((int)R,b,1,&o,0) / R;
cblas_saxpy((int)R,-m,&o,0,b,1);
}
cblas_scopy((int)R,b,1,f,1);
V[c] = cblas_sdot((int)R,b,1,f,1) / R;
for (p=1; p<=P; p++)
{
b2 = cblas_sdot(R-p,b,1,b,1);
f2 = cblas_sdot(R-p,&f[p],1,&f[p],1);
Y[c*P+p-1] = g = (-2.0f/(b2+f2)) * cblas_sdot(R-p,b,1,&f[p],1);
V[c] *= fmaf(g,-g,1.0f);
if (p>1) { for (q=0; q<p; q++) { Y[c*P+q] += g * AStmp[p-q-2]; } }
if (p<P)
{
cblas_scopy(p,&Y[c*P],1,AStmp,1);
cblas_scopy(N-p,&f[p],1,&oldf[p],1);
cblas_saxpy(N-p,g,b,1,&f[p],1);
cblas_saxpy(N-p,g,&oldf[p],1,b,1);
}
}
}
}
else
{
for (size_t c=0; c<C; c++)
{
cblas_scopy((int)R,&X[c],(int)C,b,1);
if (mean0)
{
m = cblas_sdot((int)R,b,1,&o,0) / R;
cblas_saxpy((int)R,-m,&o,0,b,1);
}
cblas_scopy((int)R,b,1,f,1);
V[c] = cblas_sdot((int)R,b,1,f,1) / R;
for (p=1; p<=P; p++)
{
b2 = cblas_sdot(R-p,b,1,b,1);
f2 = cblas_sdot(R-p,&f[p],1,&f[p],1);
Y[c+(p-1)*C] = g = (-2.0f/(b2+f2)) * cblas_sdot(R-p,b,1,&f[p],1);
V[c] *= fmaf(g,-g,1.0f);
if (p>1) { for (q=0; q<p; q++) { Y[c+q*C] += g * AStmp[p-q-2]; } }
if (p<P)
{
cblas_scopy(p,&Y[c],(int)C,AStmp,1);
cblas_scopy(N-p,&f[p],1,&oldf[p],1);
cblas_saxpy(N-p,g,b,1,&f[p],1);
cblas_saxpy(N-p,g,&oldf[p],1,b,1);
}
}
}
}
cblas_sscal(P*C,-1.0f,Y,1);
}
else if (dim==1)
{
if (iscolmajor)
{
for (size_t r=0; r<R; r++)
{
cblas_scopy((int)C,&X[r],(int)R,b,1);
if (mean0)
{
m = cblas_sdot((int)C,b,1,&o,0) / C;
cblas_saxpy((int)C,-m,&o,0,b,1);
}
cblas_scopy((int)C,b,1,f,1);
V[r] = cblas_sdot((int)C,b,1,f,1) / C;
for (p=1; p<=P; p++)
{
b2 = cblas_sdot(C-p,b,1,b,1);
f2 = cblas_sdot(C-p,&f[p],1,&f[p],1);
Y[r+(p-1)*R] = g = (-2.0f/(b2+f2)) * cblas_sdot(C-p,b,1,&f[p],1);
V[r] *= fmaf(g,-g,1.0f);
if (p>1) { for (q=0; q<p; q++) { Y[r+q*R] += g * AStmp[p-q-2]; } }
if (p<P)
{
cblas_scopy(p,&Y[r],(int)R,AStmp,1);
cblas_scopy(N-p,&f[p],1,&oldf[p],1);
cblas_saxpy(N-p,g,b,1,&f[p],1);
cblas_saxpy(N-p,g,&oldf[p],1,b,1);
}
}
}
}
else
{
for (size_t r=0; r<R; r++)
{
cblas_scopy((int)C,&X[r*C],1,b,1);
if (mean0)
{
m = cblas_sdot((int)C,b,1,&o,0) / C;
cblas_saxpy((int)C,-m,&o,0,b,1);
}
cblas_scopy((int)C,b,1,f,1);
V[r] = cblas_sdot((int)C,b,1,f,1) / C;
for (p=1; p<=P; p++)
{
b2 = cblas_sdot(C-p,b,1,b,1);
f2 = cblas_sdot(C-p,&f[p],1,&f[p],1);
Y[r*P+p-1] = g = (-2.0f/(b2+f2)) * cblas_sdot(C-p,b,1,&f[p],1);
V[r] *= fmaf(g,-g,1.0f);
if (p>1) { for (q=0; q<p; q++) { Y[r*P+q] += g * AStmp[p-q-2]; } }
if (p<P)
{
cblas_scopy(p,&Y[r*P],1,AStmp,1);
cblas_scopy(N-p,&f[p],1,&oldf[p],1);
cblas_saxpy(N-p,g,b,1,&f[p],1);
cblas_saxpy(N-p,g,&oldf[p],1,b,1);
}
}
}
}
cblas_sscal(R*P,-1.0f,Y,1);
}
else
{
fprintf(stderr,"error in sig2ar_burg_s: dim must be 0 or 1.\n"); return 1;
}
//Exit
free(b); free(f); free(oldf); free(AStmp);
return 0;
}
int sig2ar_burg_d (double *Y, double *V, const double *X, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t dim, const size_t P, const int mean0)
{
if (dim>3) { fprintf(stderr,"error in sig2ar_burg_d: dim must be in [0 3]\n"); return 1; }
const double o = 1.0;
const int N = (dim==0) ? R : C;
int r, c, p, q;
double m, g, b2, f2;
double *b, *f, *oldf, *AStmp;
//Checks
if (R<1) { fprintf(stderr,"error in sig2ar_burg_d: nrows X must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in sig2ar_burg_d: ncols X must be positive\n"); return 1; }
if (dim==0 && P>=R) { fprintf(stderr,"error in sig2ar_burg_d: P must be < nrows X for dim==0\n"); return 1; }
if (dim==1 && P>=C) { fprintf(stderr,"error in sig2ar_burg_d: P must be < ncols X for dim==1\n"); return 1; }
//Allocate
if (!(b=(double *)malloc((size_t)(N)*sizeof(double)))) { fprintf(stderr,"error in sig2ar_burg_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(f=(double *)malloc((size_t)(N)*sizeof(double)))) { fprintf(stderr,"error in sig2ar_burg_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(oldf=(double *)malloc((size_t)(N)*sizeof(double)))) { fprintf(stderr,"error in sig2ar_burg_d: problem with malloc. "); perror("malloc"); return 1; }
if (!(AStmp=(double *)malloc((size_t)(P)*sizeof(double)))) { fprintf(stderr,"error in sig2ar_burg_d: problem with malloc. "); perror("malloc"); return 1; }
if (dim==0)
{
if (iscolmajor)
{
for (size_t c=0; c<C; c++)
{
cblas_dcopy((int)R,&X[c*R],1,b,1);
if (mean0)
{
m = cblas_ddot((int)R,b,1,&o,0) / R;
cblas_daxpy((int)R,-m,&o,0,b,1);
}
cblas_dcopy((int)R,b,1,f,1);
V[c] = cblas_ddot((int)R,b,1,f,1) / R;
for (p=1; p<=P; p++)
{
b2 = cblas_ddot(R-p,b,1,b,1);
f2 = cblas_ddot(R-p,&f[p],1,&f[p],1);
Y[c*P+p-1] = g = (-2.0/(b2+f2)) * cblas_ddot(R-p,b,1,&f[p],1);
V[c] *= fma(g,-g,1.0);
if (p>1) { for (q=0; q<p; q++) { Y[c*P+q] += g * AStmp[p-q-2]; } }
if (p<P)
{
cblas_dcopy(p,&Y[c*P],1,AStmp,1);
cblas_dcopy(N-p,&f[p],1,&oldf[p],1);
cblas_daxpy(N-p,g,b,1,&f[p],1);
cblas_daxpy(N-p,g,&oldf[p],1,b,1);
}
}
}
}
else
{
for (size_t c=0; c<C; c++)
{
cblas_dcopy((int)R,&X[c],(int)C,b,1);
if (mean0)
{
m = cblas_ddot((int)R,b,1,&o,0) / R;
cblas_daxpy((int)R,-m,&o,0,b,1);
}
cblas_dcopy((int)R,b,1,f,1);
V[c] = cblas_ddot((int)R,b,1,f,1) / R;
for (p=1; p<=P; p++)
{
b2 = cblas_ddot(R-p,b,1,b,1);
f2 = cblas_ddot(R-p,&f[p],1,&f[p],1);
Y[c+(p-1)*C] = g = (-2.0/(b2+f2)) * cblas_ddot(R-p,b,1,&f[p],1);
V[c] *= fma(g,-g,1.0);
if (p>1) { for (q=0; q<p; q++) { Y[c+q*C] += g * AStmp[p-q-2]; } }
if (p<P)
{
cblas_dcopy(p,&Y[c],(int)C,AStmp,1);
cblas_dcopy(N-p,&f[p],1,&oldf[p],1);
cblas_daxpy(N-p,g,b,1,&f[p],1);
cblas_daxpy(N-p,g,&oldf[p],1,b,1);
}
}
}
}
cblas_dscal(P*C,-1.0,Y,1);
}
else if (dim==1)
{
if (iscolmajor)
{
for (size_t r=0; r<R; r++)
{
cblas_dcopy((int)C,&X[r],(int)R,b,1);
if (mean0)
{
m = cblas_ddot((int)C,b,1,&o,0) / C;
cblas_daxpy((int)C,-m,&o,0,b,1);
}
cblas_dcopy((int)C,b,1,f,1);
V[r] = cblas_ddot((int)C,b,1,f,1) / C;
for (p=1; p<=P; p++)
{
b2 = cblas_ddot(C-p,b,1,b,1);
f2 = cblas_ddot(C-p,&f[p],1,&f[p],1);
Y[r+(p-1)*R] = g = (-2.0/(b2+f2)) * cblas_ddot(C-p,b,1,&f[p],1);
V[r] *= fma(g,-g,1.0);
if (p>1) { for (q=0; q<p; q++) { Y[r+q*R] += g * AStmp[p-q-2]; } }
if (p<P)
{
cblas_dcopy(p,&Y[r],(int)R,AStmp,1);
cblas_dcopy(N-p,&f[p],1,&oldf[p],1);
cblas_daxpy(N-p,g,b,1,&f[p],1);
cblas_daxpy(N-p,g,&oldf[p],1,b,1);
}
}
}
}
else
{
for (size_t r=0; r<R; r++)
{
cblas_dcopy((int)C,&X[r*C],1,b,1);
if (mean0)
{
m = cblas_ddot((int)C,b,1,&o,0) / C;
cblas_daxpy((int)C,-m,&o,0,b,1);
}
cblas_dcopy((int)C,b,1,f,1);
V[r] = cblas_ddot((int)C,b,1,f,1) / C;
for (p=1; p<=P; p++)
{
b2 = cblas_ddot(C-p,b,1,b,1);
f2 = cblas_ddot(C-p,&f[p],1,&f[p],1);
Y[r*P+p-1] = g = (-2.0/(b2+f2)) * cblas_ddot(C-p,b,1,&f[p],1);
V[r] *= fma(g,-g,1.0);
if (p>1) { for (q=0; q<p; q++) { Y[r*P+q] += g * AStmp[p-q-2]; } }
if (p<P)
{
cblas_dcopy(p,&Y[r*P],1,AStmp,1);
cblas_dcopy(N-p,&f[p],1,&oldf[p],1);
cblas_daxpy(N-p,g,b,1,&f[p],1);
cblas_daxpy(N-p,g,&oldf[p],1,b,1);
}
}
}
}
cblas_dscal(R*P,-1.0,Y,1);
}
else
{
fprintf(stderr,"error in sig2ar_burg_d: dim must be 0 or 1.\n"); return 1;
}
//Exit
free(b); free(f); free(oldf); free(AStmp);
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.4026666667,
"avg_line_length": 39.9408284024,
"ext": "c",
"hexsha": "15ea179538e0bec94f453f07d1c3fff860a9c23e",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-10-05T13:50:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-10-05T13:50:32.000Z",
"max_forks_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/dsp",
"max_forks_repo_path": "c/sig2ar_burg.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e",
"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/dsp",
"max_issues_repo_path": "c/sig2ar_burg.c",
"max_line_length": 195,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/dsp",
"max_stars_repo_path": "c/sig2ar_burg.c",
"max_stars_repo_stars_event_max_datetime": "2020-08-26T09:22:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-26T09:22:40.000Z",
"num_tokens": 4430,
"size": 13500
} |
#include <cblas.h>
#include <stdio.h>
#include <assert.h>
/*
* y = alpha*A*x + beta*y,
* where alpha and beta are scalars, x and y are vectors and A is an
* m by n matrix.
*/
void cblas_dgemv(const enum CBLAS_ORDER order,
const enum CBLAS_TRANSPOSE TransA, const int M, const int N,
const double alpha, const double *A, const int lda,
const double *X, const int incX, const double beta,
double *Y, const int incY)
{
assert(order == CblasColMajor);
assert(TransA == CblasNoTrans);
int i;
for (i = 0; i < N; ++i)
{
Y[i*incY] += beta* Y[i*incY] + alpha* cblas_ddot(N, A[i] , lda , X , incX);
}
}
| {
"alphanum_fraction": 0.5856515373,
"avg_line_length": 25.2962962963,
"ext": "c",
"hexsha": "cb773e4694758e9a16daa9feb5bd7ed3fa410af4",
"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": "c2d0eac5808394b5061efafc2d072551e631647d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ethiery/HPCassignments",
"max_forks_repo_path": "1_funWithBLAS/src/dgemv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c2d0eac5808394b5061efafc2d072551e631647d",
"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": "ethiery/HPCassignments",
"max_issues_repo_path": "1_funWithBLAS/src/dgemv.c",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c2d0eac5808394b5061efafc2d072551e631647d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ethiery/HPCassignments",
"max_stars_repo_path": "1_funWithBLAS/src/dgemv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 209,
"size": 683
} |
#ifndef OPENMC_TALLIES_FILTER_COLLISIONS_H
#define OPENMC_TALLIES_FILTER_COLLISIONS_H
#include <vector>
#include <unordered_map>
#include <gsl/gsl>
#include "openmc/tallies/filter.h"
namespace openmc {
//==============================================================================
//! Bins the incident neutron energy.
//==============================================================================
class CollisionFilter : public Filter {
public:
//----------------------------------------------------------------------------
// Constructors, destructors
~CollisionFilter() = default;
//----------------------------------------------------------------------------
// Methods
std::string type() const override { return "collision"; }
void from_xml(pugi::xml_node node) override;
void get_all_bins(const Particle& p, TallyEstimator estimator,
FilterMatch& match) const override;
void to_statepoint(hid_t filter_group) const override;
std::string text_label(int bin) const override;
//----------------------------------------------------------------------------
// Accessors
const std::vector<int>& bins() const { return bins_; }
void set_bins(gsl::span<const int> bins);
protected:
//----------------------------------------------------------------------------
// Data members
std::vector<int> bins_;
std::unordered_map<int,int> map_;
};
} // namespace openmc
#endif // OPENMC_TALLIES_FILTER_COLLISIONS_H
| {
"alphanum_fraction": 0.4938608458,
"avg_line_length": 26.6545454545,
"ext": "h",
"hexsha": "45e6d940546529b513cbce55b37e52221c273a2a",
"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": "7f7977091df7552449cff6c3b96a1166e4b43e45",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "HunterBelanger/openmc",
"max_forks_repo_path": "include/openmc/tallies/filter_collision.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7f7977091df7552449cff6c3b96a1166e4b43e45",
"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": "HunterBelanger/openmc",
"max_issues_repo_path": "include/openmc/tallies/filter_collision.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "7f7977091df7552449cff6c3b96a1166e4b43e45",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "HunterBelanger/openmc",
"max_stars_repo_path": "include/openmc/tallies/filter_collision.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-18T16:09:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-18T16:09:59.000Z",
"num_tokens": 268,
"size": 1466
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2018 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include <gsl/gsl>
#include <list>
#include <string>
class Module;
class Event;
/**
* Is this build for enterprise edition?
*
* @return true when building EE, false for CE
*/
bool is_enterprise_edition();
/**
* In order to allow making unit tests we want to be able to mock the
* enterprise edition settings dynamically
*/
void set_enterprise_edition(bool enable);
/**
* Load the requested file and parse it as JSON
*
* @param fname the name of the file
* @return the json representation of the file
* @throws std::system_error if we fail to read the file
* std::runtime_error if we fail to parse the content of the file
*/
nlohmann::json load_file(const std::string& fname);
/**
* Iterate over the module descriptor json and populate each entry
* in the modules array into the provided modules list.
*
* @param ptr The JSON representation of the module description. See
* ../README.md for a description of the syntax
* @param modules Where to store the list of all of the entries found
* @param srcroot The source root to prepend to all of the paths in the spec
* @param objroot The object root to prepend to all of the paths in the spec
* @throws std::invalid_argument if the provided JSON is of an unexpected format
*/
void parse_module_descriptors(const nlohmann::json&,
std::list<std::unique_ptr<Module>>& modules,
const std::string& srcroot,
const std::string& objroot);
/**
* Build the master event file
*
* @param modules The modules to include
* @param output_file Where to store the result
* @throws std::system_error if we fail to write the file
*/
void create_master_file(const std::list<std::unique_ptr<Module>>& modules,
const std::string& output_file);
| {
"alphanum_fraction": 0.6883217324,
"avg_line_length": 34.0263157895,
"ext": "h",
"hexsha": "b87926b177e497f8ffc9937bf0e219d315dc4cc2",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-04-06T09:20:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-10-11T14:00:49.000Z",
"max_forks_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "rohansuri/kv_engine",
"max_forks_repo_path": "auditd/generator/generator_utilities.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328",
"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": "rohansuri/kv_engine",
"max_issues_repo_path": "auditd/generator/generator_utilities.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "6d377448a787ce5dc268c95def2850e36f5f1328",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "rohansuri/kv_engine",
"max_stars_repo_path": "auditd/generator/generator_utilities.h",
"max_stars_repo_stars_event_max_datetime": "2019-06-13T07:33:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-06-13T07:33:09.000Z",
"num_tokens": 582,
"size": 2586
} |
// This matrix class is a C++ wrapper for the GNU Scientific Library
// Copyright (C) ULP-IPB Strasbourg
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#ifndef _vector_double_h
#define _vector_double_h
#ifdef __HP_aCC
#include <iostream.h>
#else
#include <iostream>
#endif
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gslwrap/vector_double.h>
//#define NDEBUG 0
#include <assert.h>
namespace gsl
{
#ifndef __HP_aCC
using std::ostream;
//using std::string;
//using std::runtime_error;
#endif
class vector_view;
class vector
{
protected:
gsl_vector *gsldata;
void free(){if(gsldata) gsl_vector_free(gsldata);gsldata=NULL;}
void alloc(size_t n) {gsldata=gsl_vector_alloc(n);}
void calloc(size_t n){gsldata=gsl_vector_calloc(n);}
public:
typedef double value_type;
vector() : gsldata(NULL) {;}
vector( const vector &other ):gsldata(NULL) {copy(other);}
template<class oclass>
vector( const oclass &other ):gsldata(NULL) {copy(other);}
~vector(){free();}
vector(const size_t& n,bool clear=true)
{
if(clear){this->calloc(n);}
else {this->alloc(n);}
}
vector(const int& n,bool clear=true)
{
if(clear){this->calloc(n);}
else {this->alloc(n);}
}
void resize(size_t n);
template <class oclass>
void copy(const oclass &other)
{
if ( static_cast<const void *>( this ) == static_cast<const void *>( &other ) )
return;
if (!other.is_set())
{
gsldata=NULL;
return;
}
resize(other.size());
for (size_t i=0;i<size();i++)
{
gsl_vector_set(gsldata, i, (double)other[i]);
}
}
void copy(const vector& other);
bool is_set() const{if (gsldata) return true; else return false;}
// void clone(vector& other);
// size_t size() const {if (!gsldata) {cout << "vector::size vector not initialized" << endl; exit(-1);}return gsldata->size;}
size_t size() const {assert (gsldata); return gsldata->size;}
/** for interfacing with gsl c */
/* gsl_vector *gslobj() {if (!gsldata){cout << "vector::gslobj ERROR, data not initialized!! " << endl; exit(-1);}return gsldata;} */
/* const gsl_vector *gslobj() const {if (!gsldata){cout << "vector::gslobj ERROR, data not initialized!! " << endl; exit(-1);}return gsldata;} */
gsl_vector *gslobj() {assert(gsldata);return gsldata;}
const gsl_vector *gslobj() const {assert(gsldata);return gsldata;}
static vector_view create_vector_view( const gsl_vector_view &other );
// ********Accessing vector elements
// Unlike FORTRAN compilers, C compilers do not usually provide support for range checking of vectors and matrices (2). However, the functions gsl_vector_get and gsl_vector_set can perform range checking for you and report an error if you attempt to access elements outside the allowed range.
// The functions for accessing the elements of a vector or matrix are defined in `gsl_vector.h' and declared extern inline to eliminate function-call overhead. If necessary you can turn off range checking completely without modifying any source files by recompiling your program with the preprocessor definition GSL_RANGE_CHECK_OFF. Provided your compiler supports inline functions the effect of turning off range checking is to replace calls to gsl_vector_get(v,i) by v->data[i*v->stride] and and calls to gsl_vector_set(v,i,x) by v->data[i*v->stride]=x. Thus there should be no performance penalty for using the range checking functions when range checking is turned off.
// This function returns the i-th element of a vector v. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked and 0 is returned.
double get(size_t i) const {return gsl_vector_get(gsldata,i);}
// This function sets the value of the i-th element of a vector v to x. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked.
void set(size_t i,double x){gsl_vector_set(gsldata,i,x);}
// These functions return a pointer to the i-th element of a vector v. If i lies outside the allowed range of 0 to n-1 then the error handler is invoked
double &operator[](size_t i) { return *gsl_vector_ptr(gsldata,i);}
const double &operator[](size_t i) const { return *gsl_vector_ptr(gsldata,i);}
double &operator()(size_t i) { return *gsl_vector_ptr(gsldata,i);}
const double &operator()(size_t i) const { return *gsl_vector_ptr(gsldata,i);}
// ***** Initializing vector elements
// This function sets all the elements of the vector v to the value x.
void set_all(double x){gsl_vector_set_all (gsldata,x);}
// This function sets all the elements of the vector v to zero.
void set_zero(){gsl_vector_set_zero (gsldata);}
// This function makes a basis vector by setting all the elements of the vector v to zero except for the i-th element which is set to one.
int set_basis (size_t i) {return gsl_vector_set_basis (gsldata,i);}
// **** Reading and writing vectors
// The library provides functions for reading and writing vectors to a file as binary data or formatted text.
// This function writes the elements of the vector v to the stream stream in binary format. The return value is 0 for success and GSL_EFAILED if there was a problem writing to the file. Since the data is written in the native binary format it may not be portable between different architectures.
int fwrite (FILE * stream) const {return gsl_vector_fwrite (stream, gsldata);}
// This function reads into the vector v from the open stream stream in binary format. The vector v must be preallocated with the correct length since the function uses the size of v to determine how many bytes to read. The return value is 0 for success and GSL_EFAILED if there was a problem reading from the file. The data is assumed to have been written in the native binary format on the same architecture.
int fread (FILE * stream) {return gsl_vector_fread (stream, gsldata);}
void load( const char *filename );
///
void save( const char *filename ) const;
// This function writes the elements of the vector v line-by-line to the stream stream using the format specifier format, which should be one of the %g, %e or %f formats for floating point numbers and %d for integers. The function returns 0 for success and GSL_EFAILED if there was a problem writing to the file.
int fprintf (FILE * stream, const char * format) const {return gsl_vector_fprintf (stream, gsldata,format) ;}
// This function reads formatted data from the stream stream into the vector v. The vector v must be preallocated with the correct length since the function uses the size of v to determine how many numbers to read. The function returns 0 for success and GSL_EFAILED if there was a problem reading from the file.
int fscanf (FILE * stream) {return gsl_vector_fscanf (stream, gsldata); }
// ******* Vector views
// In addition to creating vectors from slices of blocks it is also possible to slice vectors and create vector views. For example, a subvector of another vector can be described with a view, or two views can be made which provide access to the even and odd elements of a vector.
// A vector view is a temporary object, stored on the stack, which can be used to operate on a subset of vector elements. Vector views can be defined for both constant and non-constant vectors, using separate types that preserve constness. A vector view has the type gsl_vector_view and a constant vector view has the type gsl_vector_const_view. In both cases the elements of the view can be accessed as a gsl_vector using the vector component of the view object. A pointer to a vector of type gsl_vector * or const gsl_vector * can be obtained by taking the address of this component with the & operator.
// These functions return a vector view of a subvector of another vector v. The start of the new vector is offset by offset elements from the start of the original
// vector. The new vector has n elements. Mathematically, the i-th element of the new vector v' is given by,
// v'(i) = v->data[(offset + i)*v->stride]
// where the index i runs from 0 to n-1.
// The data pointer of the returned vector struct is set to null if the combined parameters (offset,n) overrun the end of the original vector.
// The new vector is only a view of the block underlying the original vector, v. The block containing the elements of v is not owned by the new vector. When the
// new vector goes out of scope the original vector v and its block will continue to exist. The original memory can only be deallocated by freeing the original vector.
// Of course, the original vector should not be deallocated while the new vector is still in use.
// The function gsl_vector_const_subvector is equivalent to gsl_vector_subvector but can be used for vectors which are declared const.
vector_view subvector (size_t offset, size_t n);
const vector_view subvector (size_t offset, size_t n) const;
// vector_const_view subvector (size_t offset, size_t n) const;
// class view
// {
// gsl_vector_view *gsldata;
// public:
// view();
// };
// view subvector(size_t offset, size_t n)
// {
// return view(gsl_vector_subvector(gsldata,offset,n);
// }
// const view subvector(size_t offset, size_t n) const
// {
// return view(gsl_vector_const_subvector(gsldata,offset,n);
// }
// Function: gsl_vector gsl_vector_subvector_with_stride (gsl_vector *v, size_t offset, size_t stride, size_t n)
// Function: gsl_vector_const_view gsl_vector_const_subvector_with_stride (const gsl_vector * v, size_t offset, size_t stride, size_t n)
// These functions return a vector view of a subvector of another vector v with an additional stride argument. The subvector is formed in the same way as for
// gsl_vector_subvector but the new vector has n elements with a step-size of stride from one element to the next in the original vector. Mathematically,
// the i-th element of the new vector v' is given by,
// v'(i) = v->data[(offset + i*stride)*v->stride]
// where the index i runs from 0 to n-1.
// Note that subvector views give direct access to the underlying elements of the original vector. For example, the following code will zero the even elements of the
// vector v of length n, while leaving the odd elements untouched,
// gsl_vector_view v_even = gsl_vector_subvector_with_stride (v, 0, 2, n/2);
// gsl_vector_set_zero (&v_even.vector);
// A vector view can be passed to any subroutine which takes a vector argument just as a directly allocated vector would be, using &view.vector. For example, the
// following code computes the norm of odd elements of v using the BLAS routine DNRM2,
// gsl_vector_view v_odd = gsl_vector_subvector_with_stride (v, 1, 2, n/2);
// double r = gsl_blas_dnrm2 (&v_odd.vector);
// The function gsl_vector_const_subvector_with_stride is equivalent to gsl_vector_subvector_with_stride but can be used for
// vectors which are declared const.
// Function: gsl_vector_view gsl_vector_complex_real (gsl_vector_complex *v)
// Function: gsl_vector_const_view gsl_vector_complex_const_real (const gsl_vector_complex *v)
// These functions return a vector view of the real parts of the complex vector v.
// The function gsl_vector_complex_const_real is equivalent to gsl_vector_complex_real but can be used for vectors which are declared
// const.
// Function: gsl_vector_view gsl_vector_complex_imag (gsl_vector_complex *v)
// Function: gsl_vector_const_view gsl_vector_complex_const_imag (const gsl_vector_complex *v)
// These functions return a vector view of the imaginary parts of the complex vector v.
// The function gsl_vector_complex_const_imag is equivalent to gsl_vector_complex_imag but can be used for vectors which are declared
// const.
// Function: gsl_vector_view gsl_vector_view_array (double *base, size_t n)
// Function: gsl_vector_const_view gsl_vector_const_view_array (const double *base, size_t n)
// These functions return a vector view of an array. The start of the new vector is given by base and has n elements. Mathematically, the i-th element of the new
// vector v' is given by,
// v'(i) = base[i]
// where the index i runs from 0 to n-1.
// The array containing the elements of v is not owned by the new vector view. When the view goes out of scope the original array will continue to exist. The
// original memory can only be deallocated by freeing the original pointer base. Of course, the original array should not be deallocated while the view is still in use.
// The function gsl_vector_const_view_array is equivalent to gsl_vector_view_array but can be used for vectors which are declared const.
// Function: gsl_vector_view gsl_vector_view_array_with_stride (double * base, size_t stride, size_t n)
// Function: gsl_vector_const_view gsl_vector_const_view_array_with_stride (const double * base, size_t stride, size_t n)
// These functions return a vector view of an array base with an additional stride argument. The subvector is formed in the same way as for
// gsl_vector_view_array but the new vector has n elements with a step-size of stride from one element to the next in the original array. Mathematically,
// the i-th element of the new vector v' is given by,
// v'(i) = base[i*stride]
// where the index i runs from 0 to n-1.
// Note that the view gives direct access to the underlying elements of the original array. A vector view can be passed to any subroutine which takes a vector
// argument just as a directly allocated vector would be, using &view.vector.
// The function gsl_vector_const_view_array_with_stride is equivalent to gsl_vector_view_array_with_stride but can be used for
// arrays which are declared const.
// ************* Copying vectors
// Common operations on vectors such as addition and multiplication are available in the BLAS part of the library (see section BLAS Support). However, it is useful to have a small number of utility functions which do not require the full BLAS code. The following functions fall into this category.
// This function copies the elements of the vector src into the vector dest.
vector& operator=(const vector& other){copy(other);return (*this);}
// Function: int gsl_vector_swap (gsl_vector * v, gsl_vector * w)
// This function exchanges the elements of the vectors v and w by copying. The two vectors must have the same length.
// ***** Exchanging elements
// The following function can be used to exchange, or permute, the elements of a vector.
// Function: int gsl_vector_swap_elements (gsl_vector * v, size_t i, size_t j)
// This function exchanges the i-th and j-th elements of the vector v in-place.
int swap_elements (size_t i, size_t j) {return gsl_vector_swap_elements (gsldata, i,j);}
// Function: int gsl_vector_reverse (gsl_vector * v)
// This function reverses the order of the elements of the vector v.
int reverse () {return gsl_vector_reverse (gsldata) ;}
// ******* Vector operations
// The following operations are only defined for real vectors.
// This function adds the elements of vector b to the elements of vector a, a'_i = a_i + b_i. The two vectors must have the same length.
int operator+=(const vector &other) {return gsl_vector_add (gsldata, other.gsldata);}
// This function subtracts the elements of vector b from the elements of vector a, a'_i = a_i - b_i. The two vectors must have the same length.
int operator-=(const vector &other) {return gsl_vector_sub (gsldata, other.gsldata);}
// Function: int gsl_vector_mul (gsl_vector * a, const gsl_vector * b)
// This function multiplies the elements of vector a by the elements of vector b, a'_i = a_i * b_i. The two vectors must have the same length.
int operator*=(const vector &other) {return gsl_vector_mul (gsldata, other.gsldata);}
// This function divides the elements of vector a by the elements of vector b, a'_i = a_i / b_i. The two vectors must have the same length.
int operator/=(const vector &other) {return gsl_vector_div (gsldata, other.gsldata);}
// This function multiplies the elements of vector a by the constant factor x, a'_i = x a_i.
int operator*=(double x) {return gsl_vector_scale (gsldata, x);}
// Function: int gsl_vector_add_constant (gsl_vector * a, const double x)
// This function adds the constant value x to the elements of the vector a, a'_i = a_i + x.
int operator+=(double x) {return gsl_vector_add_constant (gsldata,x);}
// This function multiplies the elements of vector a by the constant factor x, a'_i = x a_i.
int operator/=(double x) {return gsl_vector_scale (gsldata, 1/x);}
// bool operators:
bool operator==(const vector& other) const;
bool operator!=(const vector& other) const { return (!((*this)==other));}
// stream output:
// friend ostream& operator<< ( ostream& os, const vector& vect );
/** returns sum of all the vector elements. */
double sum() const;
// returns sqrt(v.t*v);
double norm2() const;
// **** Finding maximum and minimum elements of vectors
// This function returns the maximum value in the vector v.
double max() const{return gsl_vector_max (gsldata) ;}
// Function: double gsl_vector_min (const gsl_vector * v)
// This function returns the minimum value in the vector v.
double min() const{return gsl_vector_min (gsldata) ;}
// Function: void gsl_vector_minmax (const gsl_vector * v, double * min_out, double * max_out)
// This function returns the minimum and maximum values in the vector v, storing them in min_out and max_out.
// This function returns the index of the maximum value in the vector v. When there are several equal maximum elements then the lowest index is returned.
size_t max_index(){return gsl_vector_max_index (gsldata);}
// Function: size_t gsl_vector_min_index (const gsl_vector * v)
// This function returns the index of the minimum value in the vector v. When there are several equal minimum elements then the lowest index is returned.
size_t min_index(){return gsl_vector_min_index (gsldata);}
// Function: void gsl_vector_minmax_index (const gsl_vector * v, size_t * imin, size_t * imax)
// This function returns the indices of the minimum and maximum values in the vector v, storing them in imin and imax. When there are several equal minimum
// or maximum elements then the lowest indices are returned.
// Vector properties
// Function: int gsl_vector_isnull (const gsl_vector * v)
// This function returns 1 if all the elements of the vector v are zero, and 0 otherwise. };
bool isnull(){return gsl_vector_isnull (gsldata);}
};
// When you add create a view it will stick to its with the view until you call change_view
// ex:
// matrix_float m(5,5);
// vector_float v(5);
// // ...
// m.column(3) = v; //the 3rd column of the matrix m will equal v.
class vector_view : public vector
{
public:
vector_view(const vector& other) :vector(){init(other);}
vector_view(const vector_view& other):vector(){init(other);}
vector_view(const gsl_vector& gsl_other) : vector() {init_with_gsl_vector(gsl_other);}
void init(const vector& other);
void init_with_gsl_vector(const gsl_vector& gsl_other);
void change_view(const vector& other){init(other);}
private:
};
ostream& operator<< ( ostream& os, const vector & vect );
// vector_type<>::type is a template interface to vector_?
// it is usefull for in templated situations for getting the correct vector type
#define tmp_type_is
#ifdef tmp_type_is
typedef vector vector_double;
template<class T>
struct vector_type {typedef vector_double type;};
template<class T>
struct value_type {typedef double type;};
#else
template<> struct vector_type<double> {typedef vector type;};
#endif
#undef tmp_type_is
}
#endif// _vector_double_h
| {
"alphanum_fraction": 0.7337768778,
"avg_line_length": 51.5970149254,
"ext": "h",
"hexsha": "6858c596f0b71945fad8b23b07a5b328e29a5041",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "boomsbloom/dtm-fmri",
"max_forks_repo_path": "DTM/dtm-master/gslwrap/include/gslwrap/vector_double.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"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": "boomsbloom/dtm-fmri",
"max_issues_repo_path": "DTM/dtm-master/gslwrap/include/gslwrap/vector_double.h",
"max_line_length": 675,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "boomsbloom/dtm-fmri",
"max_stars_repo_path": "DTM/dtm-master/gslwrap/include/gslwrap/vector_double.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z",
"num_tokens": 4965,
"size": 20742
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#pragma once
#if SEAL_COMPILER == SEAL_COMPILER_GCC
// We require GCC >= 6
#if (__GNUC__ < 6) || not defined(__cplusplus)
#pragma GCC error "SEAL requires __GNUC__ >= 6"
#endif
// Read in config.h
#include "seal/util/config.h"
#if (__GNUC__ == 6) && defined(SEAL_USE_IF_CONSTEXPR)
#pragma GCC error "g++-6 cannot compile Microsoft SEAL as C++17; set CMake build option `SEAL_USE_CXX17' to OFF"
#endif
// Are we using MSGSL?
#ifdef SEAL_USE_MSGSL
#include <gsl/gsl>
#endif
// Are intrinsics enabled?
#ifdef SEAL_USE_INTRIN
#include <x86intrin.h>
#ifdef SEAL_USE___BUILTIN_CLZLL
#define SEAL_MSB_INDEX_UINT64(result, value) { \
*result = 63UL - static_cast<unsigned long>(__builtin_clzll(value)); \
}
#endif
#ifdef SEAL_USE___INT128
#define SEAL_MULTIPLY_UINT64_HW64(operand1, operand2, hw64) { \
*hw64 = static_cast<unsigned long long>( \
((static_cast<unsigned __int128>(operand1) \
* static_cast<unsigned __int128>(operand2)) >> 64)); \
}
#define SEAL_MULTIPLY_UINT64(operand1, operand2, result128) { \
unsigned __int128 product = static_cast<unsigned __int128>(operand1) * operand2;\
result128[0] = static_cast<unsigned long long>(product); \
result128[1] = static_cast<unsigned long long>(product >> 64); \
}
#define SEAL_DIVIDE_UINT128_UINT64(numerator, denominator, result) { \
unsigned __int128 n, q; \
n = (static_cast<unsigned __int128>(numerator[1]) << 64) | \
(static_cast<unsigned __int128>(numerator[0])); \
q = n / denominator; \
n -= q * denominator; \
numerator[0] = static_cast<std::uint64_t>(n); \
numerator[1] = static_cast<std::uint64_t>(n >> 64); \
quotient[0] = static_cast<std::uint64_t>(q); \
quotient[1] = static_cast<std::uint64_t>(q >> 64); \
}
#endif
#ifdef SEAL_USE__ADDCARRY_U64
#define SEAL_ADD_CARRY_UINT64(operand1, operand2, carry, result) _addcarry_u64( \
carry, operand1, operand2, result)
#endif
#ifdef SEAL_USE__SUBBORROW_U64
#if ((__GNUC__ == 7) && (__GNUC_MINOR__ >= 2)) || (__GNUC__ >= 8)
// The inverted arguments problem was fixed in GCC-7.2
// (https://patchwork.ozlabs.org/patch/784309/)
#define SEAL_SUB_BORROW_UINT64(operand1, operand2, borrow, result) _subborrow_u64( \
borrow, operand1, operand2, result)
#else
// Warning: Note the inverted order of operand1 and operand2
#define SEAL_SUB_BORROW_UINT64(operand1, operand2, borrow, result) _subborrow_u64( \
borrow, operand2, operand1, result)
#endif //(__GNUC__ == 7) && (__GNUC_MINOR__ >= 2)
#endif
#endif //SEAL_USE_INTRIN
#endif
| {
"alphanum_fraction": 0.5799752015,
"avg_line_length": 39.3414634146,
"ext": "h",
"hexsha": "c41873770f49f7735f0c31a8a3032a97d02001df",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-09T08:38:44.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-09T08:38:44.000Z",
"max_forks_repo_head_hexsha": "1d5c8169aa5aca9deb75c4079e53ea8d5e94007d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "KoizumiRuby/SEAL",
"max_forks_repo_path": "native/src/seal/util/gcc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1d5c8169aa5aca9deb75c4079e53ea8d5e94007d",
"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": "KoizumiRuby/SEAL",
"max_issues_repo_path": "native/src/seal/util/gcc.h",
"max_line_length": 112,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4a019473ad90b066b593f5714d6bf07d3a3ed671",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "deisler134/SEAL",
"max_stars_repo_path": "native/src/seal/util/gcc.h",
"max_stars_repo_stars_event_max_datetime": "2020-05-13T17:40:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-12-24T07:08:33.000Z",
"num_tokens": 781,
"size": 3226
} |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Inspired by Chromium video capture interface
// Simplified and stripped from internal base code
#ifndef S3D_VIDEO_CAPTURE_VIDEO_CAPTURE_DEVICE_DECKLINK_H
#define S3D_VIDEO_CAPTURE_VIDEO_CAPTURE_DEVICE_DECKLINK_H
#include <s3d/video/capture/video_capture_device.h>
#include <s3d/video/capture/video_capture_device_factory.h>
#include <gsl/gsl>
#include <chrono>
namespace s3d {
class DecklinkCaptureDelegate;
class VideoCaptureDeviceDecklink : public VideoCaptureDevice {
public:
explicit VideoCaptureDeviceDecklink(const VideoCaptureDeviceDescriptor& deviceDescriptor);
gsl::owner<VideoCaptureDevice*> clone() const override;
~VideoCaptureDeviceDecklink() override;
void AllocateAndStart(const VideoCaptureFormat& format,
VideoCaptureDevice::Client* client) override;
void StopAndDeAllocate() override;
// called from delegate
void OnIncomingCapturedData(const VideoCaptureDevice::Client::Images& images,
const VideoCaptureFormat& frameFormat,
std::chrono::microseconds /*timestamp*/);
VideoCaptureFormat DefaultFormat() override;
private:
VideoCaptureDevice::Client* client_{};
std::unique_ptr<DecklinkCaptureDelegate> captureDelegate_;
};
} // namespace s3d
#endif // S3D_VIDEO_CAPTURE_VIDEO_CAPTURE_DEVICE_DECKLINK_H
| {
"alphanum_fraction": 0.7670454545,
"avg_line_length": 29.9574468085,
"ext": "h",
"hexsha": "84081849e7b785cd0d3a88ccdf70f22bab5cec45",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z",
"max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "hugbed/OpenS3D",
"max_forks_repo_path": "src/core/decklink/include/s3d/video/capture/video_capture_device_decklink.h",
"max_issues_count": 40,
"max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "hugbed/OpenS3D",
"max_issues_repo_path": "src/core/decklink/include/s3d/video/capture/video_capture_device_decklink.h",
"max_line_length": 92,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "hugbed/OpenS3D",
"max_stars_repo_path": "src/core/decklink/include/s3d/video/capture/video_capture_device_decklink.h",
"max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z",
"num_tokens": 298,
"size": 1408
} |
/* linalg/test_ql.c
*
* Copyright (C) 2019 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_permute_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_permutation.h>
static int
test_QL_decomp_eps(const gsl_matrix * m, const double eps, const char * desc)
{
int s = 0;
const size_t M = m->size1;
const size_t N = m->size2;
size_t i, j;
gsl_matrix * QL = gsl_matrix_alloc(M, N);
gsl_vector * tau = gsl_vector_alloc(N);
gsl_matrix * A = gsl_matrix_alloc(M, N);
gsl_matrix * L = gsl_matrix_alloc(M, N);
gsl_matrix * Q = gsl_matrix_alloc(M, M);
gsl_matrix_memcpy(QL, m);
s += gsl_linalg_QL_decomp(QL, tau);
s += gsl_linalg_QL_unpack(QL, tau, Q, L);
/* compute A = Q L */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, Q, L, 0.0, A);
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
double aij = gsl_matrix_get(A, i, j);
double mij = gsl_matrix_get(m, i, j);
gsl_test_rel(aij, mij, eps, "%s (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, M, N, i,j, aij, mij);
}
}
gsl_matrix_free(QL);
gsl_vector_free(tau);
gsl_matrix_free(A);
gsl_matrix_free(Q);
gsl_matrix_free(L);
return s;
}
static int
test_QL_decomp(gsl_rng * r)
{
int s = 0;
size_t M, N;
for (M = 1; M <= 30; ++M)
{
for (N = 1; N <= M; ++N)
{
gsl_matrix * A = gsl_matrix_alloc(M, N);
create_random_matrix(A, r);
s += test_QL_decomp_eps(A, 1.0e5 * GSL_MAX(M, N) * GSL_DBL_EPSILON, "QL_decomp random");
gsl_matrix_free(A);
}
}
s += test_QL_decomp_eps(m53, 1.0e2 * GSL_DBL_EPSILON, "QL_decomp m(5,3)");
s += test_QL_decomp_eps(hilb2, 1.0e2 * GSL_DBL_EPSILON, "QL_decomp hilbert(2)");
s += test_QL_decomp_eps(hilb3, 1.0e2 * GSL_DBL_EPSILON, "QL_decomp hilbert(3)");
s += test_QL_decomp_eps(hilb4, 1.0e2 * GSL_DBL_EPSILON, "QL_decomp hilbert(4)");
s += test_QL_decomp_eps(hilb12, 1.0e2 * GSL_DBL_EPSILON, "QL_decomp hilbert(12)");
s += test_QL_decomp_eps(vander2, 1.0e1 * GSL_DBL_EPSILON, "QL_decomp vander(2)");
s += test_QL_decomp_eps(vander3, 1.0e1 * GSL_DBL_EPSILON, "QL_decomp vander(3)");
s += test_QL_decomp_eps(vander4, 1.0e2 * GSL_DBL_EPSILON, "QL_decomp vander(4)");
return s;
}
| {
"alphanum_fraction": 0.6529133858,
"avg_line_length": 30.5288461538,
"ext": "c",
"hexsha": "cab793e87f601aacafe7383abdc30209d390c547",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_ql.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_ql.c",
"max_line_length": 98,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_ql.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": 1060,
"size": 3175
} |
//cmc_stateSpace.c --
// this program creates and outputs a coalescent markov chain's complete state space
// given a particular model
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include "AFS.h"
int n1, n2;
void getParameters(int argc,const char **argv);
void usage();
int main(int argc, const char * argv[]){
int i;
afsObject *A;
afsStateSpace *stateSpace;
getParameters(argc,argv);
stateSpace = afsStateSpaceNew();
A = afsObjectNew(n1,n2);
afsObjectInit(A,n1,n2);
//
// printf("%s\n",A->matString );
// // exit(1);
stateSpace->states[0] = A;
stateSpace->nstates=1;
// stateSpace->tmpStorage[A->nalleles][n1][0] = A;
// stateSpace->nstateArray[A->nalleles][n1] =1;
g_hash_table_insert(stateSpace->stateHash, A->matString, "TRUE");
preorderEvolveState(stateSpace, A, n1, n2);
//qsort(stateSpace->states,stateSpace->nstates, sizeof(stateSpace->states[0]), afsObjectQsortCompare);
printf("n1: %d n2: %d nstates: %d\n",n1,n2,stateSpace->nstates);
for(i=0;i<stateSpace->nstates;i++){
afsObjectPrint(stateSpace->states[i]);
printf("-----------\n");
}
afsStateSpaceFree(stateSpace);
return(0);
}
void getParameters(int argc,const char **argv){
// int args;
// int i;
if( argc < 2){
usage();
}
n1 = atoi(argv[1]);
n2 = atoi(argv[2]);
}
void usage(){
fprintf(stderr,"usage: cmc_stateSpace n1 n2\n");
// fprintf(stderr,"parameters: \n");
exit(1);
} | {
"alphanum_fraction": 0.6659850034,
"avg_line_length": 19.56,
"ext": "c",
"hexsha": "998eb74ac2993b89ce5557f8368c90e05afcab40",
"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": "e1643d7489106d5e040329bd0b7db75d80ce21d6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kern-lab/im_clam",
"max_forks_repo_path": "cmc_stateSpace.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec",
"max_issues_repo_issues_event_max_datetime": "2018-04-08T17:04:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-01-17T09:15:17.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dortegadelv/IMaDNA",
"max_issues_repo_path": "cmc_stateSpace.c",
"max_line_length": 103,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dortegadelv/IMaDNA",
"max_stars_repo_path": "cmc_stateSpace.c",
"max_stars_repo_stars_event_max_datetime": "2020-04-17T17:22:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-07-22T13:06:07.000Z",
"num_tokens": 448,
"size": 1467
} |
/*
Excited States software: KGS
Contributors: See CONTRIBUTORS.txt
Contact: kgs-contact@simtk.org
Copyright (C) 2009-2017 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 CONFIGURATION_H
#define CONFIGURATION_H
#include <list>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <vector>
#include <tuple>
#include "math/Nullspace.h"
#include "math/Eigenvalue.h"
#include "core/graph/KinGraph.h"
class Molecule;
class Selection;
/**
* A configuration holds all DOF-values necessary to update a molecules atom-positions.
* DOF-values are relative to whatever is stored in the Atom::reference_positions, so calling
* Configuration* conf = new Configuration(m_protein);
* will create a configuration where all DOF-values are 0 and which represents whatever is in
* the reference positions of m_protein. Modifying for example
* conf->m_dofs[2] += 0.1
* will add 0.1 units (often radians) to the third DOF. To see the resulting structure call either
* m_protein->setConfiguration(conf);
* or
* conf->updatedProtein();
* and then access Atom::position (not Atom::m_referencePosition).
*
* As new configurations are generated from older ones, the field m_children and m_parent store the
* connectivity information.
*/
class Configuration
{
public:
double *m_dofs; ///< DOF-values (relative to Atom::m_referencePosition)
//double *m_sumProjSteps; //TODO: What is this?
/** Construct a configuration with all DOF-values set to 0 and no m_parent. */
Configuration(Molecule * mol);
/** Construct a configuration with all DOF-values set to 0 and the specified m_parent. */
Configuration(Configuration* parent);
~Configuration();
double getGlobalTorsion( int i ) ; ///< Get a global DOF-value
double* getGlobalTorsions() ; ///< Get global DOF-value array
unsigned int getNumDOFs() const;
/** Set the specified dof to the global torsion value. Convenient function for
* calculating difference between reference torsion and val. */
void setGlobalTorsion(int i, double val);
Configuration* clone() const; ///< Copy this configuration
void Print(); // TODO: Remove or rename to printDOFs
// Molecule* collapseRigidBonds();
// void identifyBiggerRigidBodies(); ///< Identify clusters
// void readBiggerSet(); ///< read the set of clusters, related to identifying clusters
void projectOnCycleNullSpace (gsl_vector *to_project, gsl_vector *after_project);
void convertAllDofsToCycleDofs( gsl_vector *cycleDofs, gsl_vector *allDofs);
void convertCycleDofsToAllDofs( gsl_vector *allDofsAfter, gsl_vector *cycleDofs, gsl_vector *allDofsBefore = nullptr);
// static bool compareSize(std::pair<int, unsigned int> firstEntry, std::pair<int, unsigned int> secondEntry);//TODO: What is this?
void writeQToBfactor();
// When the samples are generated as an expanding tree, the m_children and m_parent store the connectivity information of these nodes
const int m_treeDepth; ///< Depth in the exploration tree
int m_id; ///< ID of configuration
double m_vdwEnergy; ///< van der Waals energy of configuration
double m_deltaH; ///< change in enthalpy due to clash constraints
double m_distanceToTarget; ///< Distance to target configuration
double m_distanceToParent; ///< Distance to m_parent configuration
double m_distanceToIni; ///< Distance to initial configuration
double m_paretoFrontDistance;
double m_maxConstraintViolation; //Maximum detected distance violation of h-bond constraints, Todo: maybe not necessary to keep
double m_minCollisionFactor; //minimum necessary clash-factor for configuration to be clash free, Todo: maybe not necessary to keep
double m_usedClashPrevention;
// std::map<unsigned int, Rigidbody*> m_biggerRBMap; // <Cluster-idx, Pointer-to-cluster>
// std::vector< std::pair<int, unsigned int> > m_sortedRBs; // < cluster-idx, cluster size>
int m_numClusters; ///< Number of rigid clusters (super rigid bodies)
int m_maxIndex; ///< Index of largest cluster
int m_maxSize; ///< Size of largest cluster
int m_clashFreeDofs; ///< Number of clash-free dofs (for post-processing)
Molecule * updatedMolecule(); ///< Update the atom-positions to reflect this configuration and return the molecule
Molecule * getMolecule() const;///< Return the associated molecule
void updateMolecule(); ///< Update the atom-positions to reflect this configuration
/** Return the cycle jacobian. Calls computeJacobians if CycleJacobian is not up to date */
gsl_matrix* getCycleJacobian();
Nullspace* getNullspace(); ///< Compute the nullspace (if it wasn't already) and return it
//Nullspace* getNullspaceligand(); ///< Compute the nullspace for ligand (if it wasn't already) and return it
Nullspace* getNullspacenocoupling();
void Hessianmatrixentropy(double cutoff=20.0, double coefficientvalue=1.0, double vdwenergyvalue=10000.0, Nullspace* Nu=nullptr, Molecule* mol=nullptr, bool proteinonly=false, std::string nocoupling="true"); ///< Compute the nullspace for vibrational entropy (if it wasn't already) and return it
Eigenvalue* geteigenvalue();
gsl_matrix* getHydrophobicJacobian();
gsl_matrix* getHydrogenJacobian();
gsl_matrix* getDistanceJacobian();
void rigidityAnalysis();
void deleteNullspace(); ///if not needed anymore, save memory
Configuration* getParent(); ///< Access configuration that spawned this one
std::list<Configuration*>& getChildren(); ///< Access child configurations
double siteDOFTransfer(Selection& source, Selection& sink,gsl_matrix* baseMatrix); //
void sortFreeEnergyModes(gsl_matrix* baseMatrix, gsl_vector* singVals, gsl_vector* returnIDs); //return index list of modes sorted by free energy
int getNumRigidDihedralsligand();
bool checknocoupling();
static Nullspace* ClashAvoidingNullSpace; //TODO: Make private (or even better put in ClashAvoidingMove).
void setrigiddofid();
protected:
int numligandRigidDihedrals=0; ///< Rigid dihedrals in ligand
void updateGlobalTorsions(); ///< Update the global DOF-values (m_dofs_global field)
double *m_dofs_global; ///< DOF-values in a global system (not relative to Atom::reference_position)
Molecule * const m_molecule; ///< The molecule related to the configuration
Configuration * m_parent; ///< The parent-configuration this configuration was generated from
std::list<Configuration*> m_children; ///< List of child-configurations
void computeCycleJacobianAndNullSpace();
void computeCycleJacobianentropyforall();
void computeCycleJacobianentropy(Nullspace* Nu,std::string nocoupling);
void computeMassmatrix();
void computedistancematrix(Molecule* mol);
void computeHessiancartesian(double cutoff, double coefficientvalue, double vdwenergyvalue,Molecule* mol);
void computeJacobians(); ///< Compute non-redundant cycle jacobian and hbond-jacobian // and also HydrophobicBond-jacobian
// Jacobian matrix of all the cycles of rigid bodies
void computeJacobiansnocoupling();
static gsl_matrix* CycleJacobian; // column dimension is the number of DOFs; row dimension is 5 times the number of cycles because 2 atoms on each cycle-closing edge
//static gsl_matrix* CycleJacobianligand;// column dimension is the number of DOFS; row dimension is the number of cycles\//
//static gsl_matrix* ClashAvoidingJacobian;
//Nullspace* nullspaceligand;
//static SVD* JacobianSVDligand;
static gsl_matrix* CycleJacobiannocoupling;
gsl_matrix* CycleJacobianentropy;// column dimension is the number of DOFS; row dimension is the number of cycles\//
gsl_matrix* CycleJacobianentropycoupling;
gsl_matrix* CycleJacobianentropynocoupling;
gsl_matrix* Hessianmatrix_cartesian;
static gsl_matrix* Massmatrix;
static gsl_matrix* distancematrix;
static gsl_matrix* coefficientmatrix;
Eigenvalue* Entropyeigen;
static gsl_matrix* HBondJacobian; // column dimension is the number of DOFS; row dimension is the number of cycles\//
static gsl_matrix* HydrophobicBondJacobian; //column dimension is the number of DOFs; row dimension is the 5 times the number of Hydrophobic bond
static gsl_matrix* DBondJacobian; //column dimension is the number of DOFs; row dimension is the 5 times the number of Hydrophobic bond
static Configuration* CycleJacobianOwner;
static SVD* JacobianSVD;
static SVD* JacobianSVDnocoupling;
Nullspace* nullspace; ///< Nullspace of hbond of this configuration
Nullspace* nullspacenocoupling;
Nullspace* nullspaceHydro;
};
#endif
| {
"alphanum_fraction": 0.7447435246,
"avg_line_length": 49.225,
"ext": "h",
"hexsha": "32e36b11ee5a7a586dca6e4d74edac69d18a8ad8",
"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/core/Configuration.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"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": "XiyuChenFAU/kgs_vibration_entropy",
"max_issues_repo_path": "src/core/Configuration.h",
"max_line_length": 298,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_stars_repo_path": "src/core/Configuration.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2330,
"size": 9845
} |
/* Copyright 2017. The Regents of the University of California.
* Copyright 2016. Martin Uecker.
* All rights reserved. Use of this source code is governed by
* a BSD-style license which can be found in the LICENSE file.
*
* Authors:
* 2016 Martin Uecker <martin.uecker@med.uni-goettingen.de>
* 2017 Jon Tamir <jtamir@eecs.berkeley.edu>
*/
#include <complex.h>
#include "misc/misc.h"
#ifdef NOLAPACKE
#include "lapacke/lapacke.h"
#elif USE_MKL
#include <mkl.h>
#else
#include <lapacke.h>
#endif
#include "lapack.h"
#define LAPACKE(x, ...) \
if (0 != LAPACKE_##x(LAPACK_COL_MAJOR, __VA_ARGS__)) \
error("LAPACK: " # x " failed.");
/* ATTENTION: blas and lapack use column-major matrices
* while native C uses row-major. All matrices are
* transposed to what one would expect.
*
* LAPACK svd destroys its input matrix
**/
void lapack_eig(long N, float eigenval[N], complex float matrix[N][N])
{
LAPACKE(cheev, 'V', 'U', N, &matrix[0][0], N, eigenval);
}
void lapack_svd(long M, long N, complex float U[M][M], complex float VH[N][N], float S[(N > M) ? M : N], complex float A[N][M])
{
LAPACKE(cgesdd, 'A', M, N, &A[0][0], M, S, &U[0][0], M, &VH[0][0], N);
}
void lapack_svd_econ(long M, long N,
complex float U[M][(N > M) ? M : N],
complex float VH[(N > M) ? M : N][N],
float S[(N > M) ? M : N],
complex float A[N][M])
{
PTR_ALLOC(float[MIN(M, N) - 1], superb);
LAPACKE(cgesvd, 'S', 'S', M, N, &A[0][0], M, S, &U[0][0], M, &VH[0][0], MIN(M, N), *superb);
PTR_FREE(superb);
}
void lapack_eig_double(long N, double eigenval[N], complex double matrix[N][N])
{
LAPACKE(zheev, 'V', 'U', N, &matrix[0][0], N, eigenval);
}
void lapack_svd_double(long M, long N, complex double U[M][M], complex double VH[N][N], double S[(N > M) ? M : N], complex double A[N][M])
{
LAPACKE(zgesdd, 'A', M, N, &A[0][0], M, S, &U[0][0], M, &VH[0][0], N);
}
static void lapack_cholesky_UL(long N, char UL, complex float A[N][N])
{
LAPACKE(cpotrf, UL, N, &A[0][0], N);
}
void lapack_cholesky(long N, complex float A[N][N])
{
lapack_cholesky_UL(N, 'U', A);
}
void lapack_cholesky_lower(long N, complex float A[N][N])
{
lapack_cholesky_UL(N, 'L', A);
}
static void lapack_trimat_inverse_UL(long N, char UL, complex float A[N][N])
{
LAPACKE(ctrtri, UL, 'N', N, &A[0][0], N);
}
void lapack_trimat_inverse(long N, complex float A[N][N])
{
lapack_trimat_inverse_UL(N, 'U', A);
}
void lapack_trimat_inverse_lower(long N, complex float A[N][N])
{
lapack_trimat_inverse_UL(N, 'L', A);
}
| {
"alphanum_fraction": 0.6373713381,
"avg_line_length": 24.7647058824,
"ext": "c",
"hexsha": "04e864f99e17d77f46e450e563b4ee6e8fe6cd19",
"lang": "C",
"max_forks_count": 153,
"max_forks_repo_forks_event_max_datetime": "2022-03-28T07:03:34.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-25T02:30:45.000Z",
"max_forks_repo_head_hexsha": "4c97d5a2ada80bfa266a1b4b97d0a4aa023cec5a",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "MartinK84/bart",
"max_forks_repo_path": "src/num/lapack.c",
"max_issues_count": 158,
"max_issues_repo_head_hexsha": "4c97d5a2ada80bfa266a1b4b97d0a4aa023cec5a",
"max_issues_repo_issues_event_max_datetime": "2022-02-15T15:36:44.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-17T18:55:08.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "MartinK84/bart",
"max_issues_repo_path": "src/num/lapack.c",
"max_line_length": 138,
"max_stars_count": 189,
"max_stars_repo_head_hexsha": "4c97d5a2ada80bfa266a1b4b97d0a4aa023cec5a",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "MartinK84/bart",
"max_stars_repo_path": "src/num/lapack.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T10:30:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-28T15:36:23.000Z",
"num_tokens": 898,
"size": 2526
} |
#include "ccv.h"
#include "ccv_internal.h"
#include <sys/time.h>
#ifdef HAVE_GSL
#include <gsl/gsl_rng.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_randist.h>
#endif
#ifdef USE_OPENMP
#include <omp.h>
#endif
#ifdef HAVE_LIBLINEAR
#include <linear.h>
#endif
const ccv_dpm_param_t ccv_dpm_default_params = {
.interval = 8,
.min_neighbors = 1,
.flags = 0,
.threshold = 0.6, // 0.8
};
#define CCV_DPM_WINDOW_SIZE (8)
static int _ccv_dpm_scale_upto(ccv_dense_matrix_t* a, ccv_dpm_mixture_model_t** _model, int count, int interval)
{
int c, i;
ccv_size_t size = ccv_size(a->cols, a->rows);
for (c = 0; c < count; c++)
{
ccv_dpm_mixture_model_t* model = _model[c];
for (i = 0; i < model->count; i++)
{
size.width = ccv_min(model->root[i].root.w->cols * CCV_DPM_WINDOW_SIZE, size.width);
size.height = ccv_min(model->root[i].root.w->rows * CCV_DPM_WINDOW_SIZE, size.height);
}
}
int hr = a->rows / size.height;
int wr = a->cols / size.width;
double scale = pow(2.0, 1.0 / (interval + 1.0));
int next = interval + 1;
return (int)(log((double)ccv_min(hr, wr)) / log(scale)) - next;
}
static void _ccv_dpm_feature_pyramid(ccv_dense_matrix_t* a, ccv_dense_matrix_t** pyr, int scale_upto, int interval)
{
int next = interval + 1;
double scale = pow(2.0, 1.0 / (interval + 1.0));
memset(pyr, 0, (scale_upto + next * 2) * sizeof(ccv_dense_matrix_t*));
pyr[next] = a;
int i;
for (i = 1; i <= interval; i++)
ccv_resample(pyr[next], &pyr[next + i], 0, (int)(pyr[next]->rows / pow(scale, i)), (int)(pyr[next]->cols / pow(scale, i)), CCV_INTER_AREA);
for (i = next; i < scale_upto + next; i++)
ccv_sample_down(pyr[i], &pyr[i + next], 0, 0, 0);
ccv_dense_matrix_t* hog;
/* a more efficient way to generate up-scaled hog (using smaller size) */
for (i = 0; i < next; i++)
{
hog = 0;
ccv_hog(pyr[i + next], &hog, 0, 9, CCV_DPM_WINDOW_SIZE / 2 /* this is */);
pyr[i] = hog;
}
hog = 0;
ccv_hog(pyr[next], &hog, 0, 9, CCV_DPM_WINDOW_SIZE);
pyr[next] = hog;
for (i = next + 1; i < scale_upto + next * 2; i++)
{
hog = 0;
ccv_hog(pyr[i], &hog, 0, 9, CCV_DPM_WINDOW_SIZE);
ccv_matrix_free(pyr[i]);
pyr[i] = hog;
}
}
static void _ccv_dpm_compute_score(ccv_dpm_root_classifier_t* root_classifier, ccv_dense_matrix_t* hog, ccv_dense_matrix_t* hog2x, ccv_dense_matrix_t** _response, ccv_dense_matrix_t** part_feature, ccv_dense_matrix_t** dx, ccv_dense_matrix_t** dy)
{
ccv_dense_matrix_t* response = 0;
ccv_filter(hog, root_classifier->root.w, &response, 0, CCV_NO_PADDING);
ccv_dense_matrix_t* root_feature = 0;
ccv_flatten(response, (ccv_matrix_t**)&root_feature, 0, 0);
ccv_matrix_free(response);
*_response = root_feature;
if (hog2x == 0)
return;
ccv_make_matrix_mutable(root_feature);
int rwh = (root_classifier->root.w->rows - 1) / 2, rww = (root_classifier->root.w->cols - 1) / 2;
int rwh_1 = root_classifier->root.w->rows / 2, rww_1 = root_classifier->root.w->cols / 2;
int i, x, y;
for (i = 0; i < root_classifier->count; i++)
{
ccv_dpm_part_classifier_t* part = root_classifier->part + i;
ccv_dense_matrix_t* response = 0;
ccv_filter(hog2x, part->w, &response, 0, CCV_NO_PADDING);
ccv_dense_matrix_t* feature = 0;
ccv_flatten(response, (ccv_matrix_t**)&feature, 0, 0);
ccv_matrix_free(response);
part_feature[i] = dx[i] = dy[i] = 0;
ccv_distance_transform(feature, &part_feature[i], 0, &dx[i], 0, &dy[i], 0, part->dx, part->dy, part->dxx, part->dyy, CCV_NEGATIVE | CCV_GSEDT);
ccv_matrix_free(feature);
int pwh = (part->w->rows - 1) / 2, pww = (part->w->cols - 1) / 2;
int offy = part->y + pwh - rwh * 2;
int miny = pwh, maxy = part_feature[i]->rows - part->w->rows + pwh;
int offx = part->x + pww - rww * 2;
int minx = pww, maxx = part_feature[i]->cols - part->w->cols + pww;
float* f_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | CCV_C1, root_feature, rwh, 0, 0);
for (y = rwh; y < root_feature->rows - rwh_1; y++)
{
int iy = ccv_clamp(y * 2 + offy, miny, maxy);
for (x = rww; x < root_feature->cols - rww_1; x++)
{
int ix = ccv_clamp(x * 2 + offx, minx, maxx);
f_ptr[x] -= ccv_get_dense_matrix_cell_value_by(CCV_32F | CCV_C1, part_feature[i], iy, ix, 0);
}
f_ptr += root_feature->cols;
}
}
}
#ifdef HAVE_LIBLINEAR
#ifdef HAVE_GSL
static uint64_t _ccv_dpm_time_measure()
{
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec * 1000000 + tv.tv_usec;
}
#define less_than(fn1, fn2, aux) ((fn1).value >= (fn2).value)
static CCV_IMPLEMENT_QSORT(_ccv_dpm_aspect_qsort, struct feature_node, less_than)
#undef less_than
#define less_than(a1, a2, aux) ((a1) < (a2))
static CCV_IMPLEMENT_QSORT(_ccv_dpm_area_qsort, int, less_than)
#undef less_than
#define less_than(s1, s2, aux) ((s1) < (s2))
static CCV_IMPLEMENT_QSORT(_ccv_dpm_score_qsort, double, less_than)
#undef less_than
static ccv_dpm_mixture_model_t* _ccv_dpm_model_copy(ccv_dpm_mixture_model_t* _model)
{
ccv_dpm_mixture_model_t* model = (ccv_dpm_mixture_model_t*)ccmalloc(sizeof(ccv_dpm_mixture_model_t));
model->count = _model->count;
model->root = (ccv_dpm_root_classifier_t*)ccmalloc(sizeof(ccv_dpm_root_classifier_t) * model->count);
int i, j;
memcpy(model->root, _model->root, sizeof(ccv_dpm_root_classifier_t) * model->count);
for (i = 0; i < model->count; i++)
{
ccv_dpm_root_classifier_t* _root = _model->root + i;
ccv_dpm_root_classifier_t* root = model->root + i;
root->root.w = ccv_dense_matrix_new(_root->root.w->rows, _root->root.w->cols, CCV_32F | 31, 0, 0);
memcpy(root->root.w->data.u8, _root->root.w->data.u8, _root->root.w->rows * _root->root.w->step);
ccv_make_matrix_immutable(root->root.w);
ccv_dpm_part_classifier_t* _part = _root->part;
ccv_dpm_part_classifier_t* part = root->part = (ccv_dpm_part_classifier_t*)ccmalloc(sizeof(ccv_dpm_part_classifier_t) * root->count);
memcpy(part, _part, sizeof(ccv_dpm_part_classifier_t) * root->count);
for (j = 0; j < root->count; j++)
{
part[j].w = ccv_dense_matrix_new(_part[j].w->rows, _part[j].w->cols, CCV_32F | 31, 0, 0);
memcpy(part[j].w->data.u8, _part[j].w->data.u8, _part[j].w->rows * _part[j].w->step);
ccv_make_matrix_immutable(part[j].w);
}
}
return model;
}
static void _ccv_dpm_write_checkpoint(ccv_dpm_mixture_model_t* model, int done, const char* dir)
{
char swpfile[1024];
sprintf(swpfile, "%s.swp", dir);
FILE* w = fopen(swpfile, "w+");
if (!w)
return;
if (done)
fprintf(w, ".\n");
else
fprintf(w, ",\n");
int i, j, x, y, ch, count = 0;
for (i = 0; i < model->count; i++)
{
if (model->root[i].root.w == 0)
break;
count++;
}
if (done)
fprintf(w, "%d\n", model->count);
else
fprintf(w, "%d %d\n", model->count, count);
for (i = 0; i < count; i++)
{
ccv_dpm_root_classifier_t* root_classifier = model->root + i;
fprintf(w, "%d %d\n", root_classifier->root.w->rows, root_classifier->root.w->cols);
fprintf(w, "%a %a %a %a\n", root_classifier->beta, root_classifier->alpha[0], root_classifier->alpha[1], root_classifier->alpha[2]);
ch = CCV_GET_CHANNEL(root_classifier->root.w->type);
for (y = 0; y < root_classifier->root.w->rows; y++)
{
for (x = 0; x < root_classifier->root.w->cols * ch; x++)
fprintf(w, "%a ", root_classifier->root.w->data.f32[y * root_classifier->root.w->cols * ch + x]);
fprintf(w, "\n");
}
fprintf(w, "%d\n", root_classifier->count);
for (j = 0; j < root_classifier->count; j++)
{
ccv_dpm_part_classifier_t* part_classifier = root_classifier->part + j;
fprintf(w, "%d %d %d\n", part_classifier->x, part_classifier->y, part_classifier->z);
fprintf(w, "%la %la %la %la\n", part_classifier->dx, part_classifier->dy, part_classifier->dxx, part_classifier->dyy);
fprintf(w, "%a %a %a %a %a %a\n", part_classifier->alpha[0], part_classifier->alpha[1], part_classifier->alpha[2], part_classifier->alpha[3], part_classifier->alpha[4], part_classifier->alpha[5]);
fprintf(w, "%d %d %d\n", part_classifier->w->rows, part_classifier->w->cols, part_classifier->counterpart);
ch = CCV_GET_CHANNEL(part_classifier->w->type);
for (y = 0; y < part_classifier->w->rows; y++)
{
for (x = 0; x < part_classifier->w->cols * ch; x++)
fprintf(w, "%a ", part_classifier->w->data.f32[y * part_classifier->w->cols * ch + x]);
fprintf(w, "\n");
}
}
}
fclose(w);
rename(swpfile, dir);
}
static void _ccv_dpm_read_checkpoint(ccv_dpm_mixture_model_t* model, const char* dir)
{
FILE* r = fopen(dir, "r");
if (!r)
return;
int count;
char flag;
fscanf(r, "%c", &flag);
assert(flag == ',');
fscanf(r, "%d %d", &model->count, &count);
ccv_dpm_root_classifier_t* root_classifier = (ccv_dpm_root_classifier_t*)ccmalloc(sizeof(ccv_dpm_root_classifier_t) * count);
memset(root_classifier, 0, sizeof(ccv_dpm_root_classifier_t) * count);
int i, j, k;
for (i = 0; i < count; i++)
{
int rows, cols;
fscanf(r, "%d %d", &rows, &cols);
fscanf(r, "%f %f %f %f", &root_classifier[i].beta, &root_classifier[i].alpha[0], &root_classifier[i].alpha[1], &root_classifier[i].alpha[2]);
root_classifier[i].root.w = ccv_dense_matrix_new(rows, cols, CCV_32F | 31, 0, 0);
for (j = 0; j < rows * cols * 31; j++)
fscanf(r, "%f", &root_classifier[i].root.w->data.f32[j]);
ccv_make_matrix_immutable(root_classifier[i].root.w);
fscanf(r, "%d", &root_classifier[i].count);
if (root_classifier[i].count <= 0)
{
root_classifier[i].part = 0;
continue;
}
ccv_dpm_part_classifier_t* part_classifier = (ccv_dpm_part_classifier_t*)ccmalloc(sizeof(ccv_dpm_part_classifier_t) * root_classifier[i].count);
for (j = 0; j < root_classifier[i].count; j++)
{
fscanf(r, "%d %d %d", &part_classifier[j].x, &part_classifier[j].y, &part_classifier[j].z);
fscanf(r, "%lf %lf %lf %lf", &part_classifier[j].dx, &part_classifier[j].dy, &part_classifier[j].dxx, &part_classifier[j].dyy);
fscanf(r, "%f %f %f %f %f %f", &part_classifier[j].alpha[0], &part_classifier[j].alpha[1], &part_classifier[j].alpha[2], &part_classifier[j].alpha[3], &part_classifier[j].alpha[4], &part_classifier[j].alpha[5]);
fscanf(r, "%d %d %d", &rows, &cols, &part_classifier[j].counterpart);
part_classifier[j].w = ccv_dense_matrix_new(rows, cols, CCV_32F | 31, 0, 0);
for (k = 0; k < rows * cols * 31; k++)
fscanf(r, "%f", &part_classifier[j].w->data.f32[k]);
ccv_make_matrix_immutable(part_classifier[j].w);
}
root_classifier[i].part = part_classifier;
}
model->root = root_classifier;
fclose(r);
}
static void _ccv_dpm_mixture_model_cleanup(ccv_dpm_mixture_model_t* model)
{
/* this is different because it doesn't compress to a continuous memory region */
int i, j;
for (i = 0; i < model->count; i++)
{
ccv_dpm_root_classifier_t* root_classifier = model->root + i;
for (j = 0; j < root_classifier->count; j++)
{
ccv_dpm_part_classifier_t* part_classifier = root_classifier->part + j;
ccv_matrix_free(part_classifier->w);
}
if (root_classifier->count > 0)
ccfree(root_classifier->part);
if (root_classifier->root.w != 0)
ccv_matrix_free(root_classifier->root.w);
}
ccfree(model->root);
model->count = 0;
model->root = 0;
}
static const int _ccv_dpm_sym_lut[] = { 2, 3, 0, 1,
4 + 0, 4 + 8, 4 + 7, 4 + 6, 4 + 5, 4 + 4, 4 + 3, 4 + 2, 4 + 1,
13 + 9, 13 + 8, 13 + 7, 13 + 6, 13 + 5, 13 + 4, 13 + 3, 13 + 2, 13 + 1, 13, 13 + 17, 13 + 16, 13 + 15, 13 + 14, 13 + 13, 13 + 12, 13 + 11, 13 + 10 };
static void _ccv_dpm_check_root_classifier_symmetry(ccv_dense_matrix_t* w)
{
assert(CCV_GET_CHANNEL(w->type) == 31 && CCV_GET_DATA_TYPE(w->type) == CCV_32F);
float *w_ptr = w->data.f32;
int i, j, k;
for (i = 0; i < w->rows; i++)
{
for (j = 0; j < w->cols; j++)
{
for (k = 0; k < 31; k++)
{
double v = fabs(w_ptr[j * 31 + k] - w_ptr[(w->cols - 1 - j) * 31 + _ccv_dpm_sym_lut[k]]);
if (v > 0.002)
printf("symmetric violation at (%d, %d, %d), off by: %f\n", i, j, k, v);
}
}
w_ptr += w->cols * 31;
}
}
typedef struct {
int id;
int count;
float score;
int x, y;
float scale_x, scale_y;
ccv_dpm_part_classifier_t root;
ccv_dpm_part_classifier_t* part;
} ccv_dpm_feature_vector_t;
static void _ccv_dpm_collect_examples_randomly(gsl_rng* rng, ccv_array_t** negex, char** bgfiles, int bgnum, int negnum, int components, int* rows, int* cols, int grayscale)
{
int i, j;
for (i = 0; i < components; i++)
negex[i] = ccv_array_new(sizeof(ccv_dpm_feature_vector_t), negnum, 0);
int mrows = rows[0], mcols = cols[0];
for (i = 1; i < components; i++)
{
mrows = ccv_max(mrows, rows[i]);
mcols = ccv_max(mcols, cols[i]);
}
FLUSH(" - generating negative examples for all models : 0 / %d", negnum);
while (negex[0]->rnum < negnum)
{
double p = (double)negnum / (double)bgnum;
for (i = 0; i < bgnum; i++)
if (gsl_rng_uniform(rng) < p)
{
ccv_dense_matrix_t* image = 0;
ccv_read(bgfiles[i], &image, (grayscale ? CCV_IO_GRAY : 0) | CCV_IO_ANY_FILE);
assert(image != 0);
if (image->rows - mrows * CCV_DPM_WINDOW_SIZE < 0 ||
image->cols - mcols * CCV_DPM_WINDOW_SIZE < 0)
{
ccv_matrix_free(image);
continue;
}
int y = gsl_rng_uniform_int(rng, image->rows - mrows * CCV_DPM_WINDOW_SIZE + 1);
int x = gsl_rng_uniform_int(rng, image->cols - mcols * CCV_DPM_WINDOW_SIZE + 1);
for (j = 0; j < components; j++)
{
ccv_dense_matrix_t* slice = 0;
ccv_slice(image, (ccv_matrix_t**)&slice, 0, y + ((mrows - rows[j]) * CCV_DPM_WINDOW_SIZE + 1) / 2, x + ((mcols - cols[j]) * CCV_DPM_WINDOW_SIZE + 1) / 2, rows[j] * CCV_DPM_WINDOW_SIZE, cols[j] * CCV_DPM_WINDOW_SIZE);
assert(y + ((mrows - rows[j]) * CCV_DPM_WINDOW_SIZE + 1) / 2 >= 0 &&
y + ((mrows - rows[j]) * CCV_DPM_WINDOW_SIZE + 1) / 2 + rows[j] * CCV_DPM_WINDOW_SIZE <= image->rows &&
x + ((mcols - cols[j]) * CCV_DPM_WINDOW_SIZE + 1) / 2 >= 0 &&
x + ((mcols - cols[j]) * CCV_DPM_WINDOW_SIZE + 1) / 2 + cols[j] * CCV_DPM_WINDOW_SIZE <= image->cols);
ccv_dense_matrix_t* hog = 0;
ccv_hog(slice, &hog, 0, 9, CCV_DPM_WINDOW_SIZE);
ccv_matrix_free(slice);
ccv_dpm_feature_vector_t vector = {
.id = j,
.count = 0,
.part = 0,
};
ccv_make_matrix_mutable(hog);
assert(hog->rows == rows[j] && hog->cols == cols[j] && CCV_GET_CHANNEL(hog->type) == 31 && CCV_GET_DATA_TYPE(hog->type) == CCV_32F);
vector.root.w = hog;
ccv_array_push(negex[j], &vector);
}
ccv_matrix_free(image);
FLUSH(" - generating negative examples for all models : %d / %d", negex[0]->rnum, negnum);
if (negex[0]->rnum >= negnum)
break;
}
}
}
static ccv_array_t* _ccv_dpm_summon_examples_by_rectangle(char** posfiles, ccv_rect_t* bboxes, int posnum, int id, int rows, int cols, int grayscale)
{
int i;
FLUSH(" - generating positive examples for model %d : 0 / %d", id, posnum);
ccv_array_t* posv = ccv_array_new(sizeof(ccv_dpm_feature_vector_t), posnum, 0);
for (i = 0; i < posnum; i++)
{
ccv_rect_t bbox = bboxes[i];
int mcols = (int)(sqrtf(bbox.width * bbox.height * cols / (float)rows) + 0.5);
int mrows = (int)(sqrtf(bbox.width * bbox.height * rows / (float)cols) + 0.5);
bbox.x = bbox.x + (bbox.width - mcols) / 2;
bbox.y = bbox.y + (bbox.height - mrows) / 2;
bbox.width = mcols;
bbox.height = mrows;
ccv_dpm_feature_vector_t vector = {
.id = id,
.count = 0,
.part = 0,
};
// resolution is too low to be useful
if (mcols * 2 < cols * CCV_DPM_WINDOW_SIZE || mrows * 2 < rows * CCV_DPM_WINDOW_SIZE)
{
vector.root.w = 0;
ccv_array_push(posv, &vector);
continue;
}
ccv_dense_matrix_t* image = 0;
ccv_read(posfiles[i], &image, (grayscale ? CCV_IO_GRAY : 0) | CCV_IO_ANY_FILE);
assert(image != 0);
ccv_dense_matrix_t* up2x = 0;
ccv_sample_up(image, &up2x, 0, 0, 0);
ccv_matrix_free(image);
ccv_dense_matrix_t* slice = 0;
ccv_slice(up2x, (ccv_matrix_t**)&slice, 0, bbox.y * 2, bbox.x * 2, bbox.height * 2, bbox.width * 2);
ccv_matrix_free(up2x);
ccv_dense_matrix_t* resize = 0;
ccv_resample(slice, &resize, 0, rows * CCV_DPM_WINDOW_SIZE, cols * CCV_DPM_WINDOW_SIZE, CCV_INTER_AREA);
ccv_matrix_free(slice);
ccv_dense_matrix_t* hog = 0;
ccv_hog(resize, &hog, 0, 9, CCV_DPM_WINDOW_SIZE);
ccv_matrix_free(resize);
ccv_make_matrix_mutable(hog);
assert(hog->rows == rows && hog->cols == cols && CCV_GET_CHANNEL(hog->type) == 31 && CCV_GET_DATA_TYPE(hog->type) == CCV_32F);
vector.root.w = hog;
ccv_array_push(posv, &vector);
FLUSH(" - generating positive examples for model %d : %d / %d", id, i + 1, posnum);
}
return posv;
}
static void _ccv_dpm_initialize_root_classifier(gsl_rng* rng, ccv_dpm_root_classifier_t* root_classifier, int label, int cnum, int* poslabels, ccv_array_t* posex, int* neglabels, ccv_array_t* negex, double C, int symmetric, int grayscale)
{
int i, j, x, y, k, l;
int cols = root_classifier->root.w->cols;
int cols2c = (cols + 1) / 2;
int rows = root_classifier->root.w->rows;
printf(" - creating initial model %d at %dx%d\n", label + 1, cols, rows);
struct problem prob;
prob.n = symmetric ? 31 * cols2c * rows + 1 : 31 * cols * rows + 1;
prob.bias = symmetric ? 0.5 : 1.0; // for symmetric, since we only pass half features in, need to set bias to be half too
// new version (1.91) of liblinear uses double instead of int (1.8) for prob.y, cannot cast for that.
prob.y = malloc(sizeof(prob.y[0]) * (cnum + negex->rnum) * (!!symmetric + 1));
prob.x = (struct feature_node**)malloc(sizeof(struct feature_node*) * (cnum + negex->rnum) * (!!symmetric + 1));
FLUSH(" - converting examples to liblinear format: %d / %d", 0, (cnum + negex->rnum) * (!!symmetric + 1));
l = 0;
for (i = 0; i < posex->rnum; i++)
if (poslabels[i] == label)
{
ccv_dense_matrix_t* hog = ((ccv_dpm_feature_vector_t*)ccv_array_get(posex, i))->root.w;
if (!hog)
continue;
struct feature_node* features;
if (symmetric)
{
features = (struct feature_node*)malloc(sizeof(struct feature_node) * (31 * cols2c * rows + 2));
float* hptr = hog->data.f32;
j = 0;
for (y = 0; y < rows; y++)
{
for (x = 0; x < cols2c; x++)
for (k = 0; k < 31; k++)
{
features[j].index = j + 1;
features[j].value = hptr[x * 31 + k];
++j;
}
hptr += hog->cols * 31;
}
features[j].index = j + 1;
features[j].value = prob.bias;
features[j + 1].index = -1;
prob.x[l] = features;
prob.y[l] = 1;
++l;
features = (struct feature_node*)malloc(sizeof(struct feature_node) * (31 * cols2c * rows + 2));
hptr = hog->data.f32;
j = 0;
for (y = 0; y < rows; y++)
{
for (x = 0; x < cols2c; x++)
for (k = 0; k < 31; k++)
{
features[j].index = j + 1;
features[j].value = hptr[(cols - 1 - x) * 31 + _ccv_dpm_sym_lut[k]];
++j;
}
hptr += hog->cols * 31;
}
features[j].index = j + 1;
features[j].value = prob.bias;
features[j + 1].index = -1;
prob.x[l] = features;
prob.y[l] = 1;
++l;
} else {
features = (struct feature_node*)malloc(sizeof(struct feature_node) * (31 * cols * rows + 2));
for (j = 0; j < rows * cols * 31; j++)
{
features[j].index = j + 1;
features[j].value = hog->data.f32[j];
}
features[31 * rows * cols].index = 31 * rows * cols + 1;
features[31 * rows * cols].value = prob.bias;
features[31 * rows * cols + 1].index = -1;
prob.x[l] = features;
prob.y[l] = 1;
++l;
}
FLUSH(" - converting examples to liblinear format: %d / %d", l, (cnum + negex->rnum) * (!!symmetric + 1));
}
for (i = 0; i < negex->rnum; i++)
if (neglabels[i] == label)
{
ccv_dense_matrix_t* hog = ((ccv_dpm_feature_vector_t*)ccv_array_get(negex, i))->root.w;
struct feature_node* features;
if (symmetric)
{
features = (struct feature_node*)malloc(sizeof(struct feature_node) * (31 * cols2c * rows + 2));
float* hptr = hog->data.f32;
j = 0;
for (y = 0; y < rows; y++)
{
for (x = 0; x < cols2c; x++)
for (k = 0; k < 31; k++)
{
features[j].index = j + 1;
features[j].value = hptr[x * 31 + k];
++j;
}
hptr += hog->cols * 31;
}
features[j].index = j + 1;
features[j].value = prob.bias;
features[j + 1].index = -1;
prob.x[l] = features;
prob.y[l] = -1;
++l;
features = (struct feature_node*)malloc(sizeof(struct feature_node) * (31 * cols2c * rows + 2));
hptr = hog->data.f32;
j = 0;
for (y = 0; y < rows; y++)
{
for (x = 0; x < cols2c; x++)
for (k = 0; k < 31; k++)
{
features[j].index = j + 1;
features[j].value = hptr[(cols - 1 - x) * 31 + _ccv_dpm_sym_lut[k]];
++j;
}
hptr += hog->cols * 31;
}
features[j].index = j + 1;
features[j].value = prob.bias;
features[j + 1].index = -1;
prob.x[l] = features;
prob.y[l] = -1;
++l;
} else {
features = (struct feature_node*)malloc(sizeof(struct feature_node) * (31 * cols * rows + 2));
for (j = 0; j < 31 * rows * cols; j++)
{
features[j].index = j + 1;
features[j].value = hog->data.f32[j];
}
features[31 * rows * cols].index = 31 * rows * cols + 1;
features[31 * rows * cols].value = prob.bias;
features[31 * rows * cols + 1].index = -1;
prob.x[l] = features;
prob.y[l] = -1;
++l;
}
FLUSH(" - converting examples to liblinear format: %d / %d", l, (cnum + negex->rnum) * (!!symmetric + 1));
}
prob.l = l;
printf("\n - generated %d examples with %d dimensions each\n"
" - running liblinear for initial linear SVM model (L2-regularized, L1-loss)\n", prob.l, prob.n);
struct parameter linear_parameters = { .solver_type = L2R_L1LOSS_SVC_DUAL,
.eps = 1e-1,
.C = C,
.nr_weight = 0,
.weight_label = 0,
.weight = 0 };
const char* err = check_parameter(&prob, &linear_parameters);
if (err)
{
printf(" - ERROR: cannot pass check parameter: %s\n", err);
exit(-1);
}
struct model* linear = train(&prob, &linear_parameters);
assert(linear != 0);
printf(" - model->label[0]: %d, model->nr_class: %d, model->nr_feature: %d\n", linear->label[0], linear->nr_class, linear->nr_feature);
if (symmetric)
{
float* wptr = root_classifier->root.w->data.f32;
for (y = 0; y < rows; y++)
{
for (x = 0; x < cols2c; x++)
for (k = 0; k < 31; k++)
wptr[(cols - 1 - x) * 31 + _ccv_dpm_sym_lut[k]] = wptr[x * 31 + k] = linear->w[(y * cols2c + x) * 31 + k];
wptr += cols * 31;
}
// since for symmetric, lsvm only computed half features, to compensate that, we doubled the constant.
root_classifier->beta = linear->w[31 * rows * cols2c] * 2.0;
} else {
for (j = 0; j < 31 * rows * cols; j++)
root_classifier->root.w->data.f32[j] = linear->w[j];
root_classifier->beta = linear->w[31 * rows * cols];
}
free_and_destroy_model(&linear);
free(prob.y);
for (j = 0; j < prob.l; j++)
free(prob.x[j]);
free(prob.x);
ccv_make_matrix_immutable(root_classifier->root.w);
}
static void _ccv_dpm_initialize_part_classifiers(ccv_dpm_root_classifier_t* root_classifier, int parts, int symmetric)
{
int i, j, k, x, y;
ccv_dense_matrix_t* w = 0;
ccv_sample_up(root_classifier->root.w, &w, 0, 0, 0);
ccv_make_matrix_mutable(w);
root_classifier->count = parts;
root_classifier->part = (ccv_dpm_part_classifier_t*)ccmalloc(sizeof(ccv_dpm_part_classifier_t) * parts);
memset(root_classifier->part, 0, sizeof(ccv_dpm_part_classifier_t) * parts);
double area = w->rows * w->cols / (double)parts;
for (i = 0; i < parts;)
{
ccv_dpm_part_classifier_t* part_classifier = root_classifier->part + i;
int dx = 0, dy = 0, dw = 0, dh = 0, sym = 0;
double dsum = -1.0; // absolute value, thus, -1.0 is enough
#define slice_and_update_if_needed(y, x, l, n, s) \
{ \
ccv_dense_matrix_t* slice = 0; \
ccv_slice(w, (ccv_matrix_t**)&slice, 0, y, x, l, n); \
double sum = ccv_sum(slice, CCV_UNSIGNED) / (double)(l * n); \
if (sum > dsum) \
{ \
dsum = sum; \
dx = x; \
dy = y; \
dw = n; \
dh = l; \
sym = s; \
} \
ccv_matrix_free(slice); \
}
for (j = 1; (j < area + 1) && (j * 3 <= w->rows * 2); j++)
{
k = (int)(area / j + 0.5);
if (k < 1 || k * 3 > w->cols * 2)
continue;
if (j > k * 2 || k > j * 2)
continue;
if (symmetric)
{
if (k % 2 == w->cols % 2) // can be symmetric in horizontal center
{
x = (w->cols - k) / 2;
for (y = 0; y < w->rows - j + 1; y++)
slice_and_update_if_needed(y, x, j, k, 0);
}
if (i < parts - 1) // have 2 locations
{
for (y = 0; y < w->rows - j + 1; y++)
for (x = 0; x <= w->cols / 2 - k /* to avoid overlapping */; x++)
slice_and_update_if_needed(y, x, j, k, 1);
}
} else {
for (y = 0; y < w->rows - j + 1; y++)
for (x = 0; x < w->cols - k + 1; x++)
slice_and_update_if_needed(y, x, j, k, 0);
}
}
printf(" ---- part %d(%d) %dx%d at (%d,%d), entropy: %lf\n", i + 1, parts, dw, dh, dx, dy, dsum);
part_classifier->dx = 0;
part_classifier->dy = 0;
part_classifier->dxx = 0.1f;
part_classifier->dyy = 0.1f;
part_classifier->x = dx;
part_classifier->y = dy;
part_classifier->z = 1;
part_classifier->w = 0;
ccv_slice(w, (ccv_matrix_t**)&part_classifier->w, 0, dy, dx, dh, dw);
ccv_make_matrix_immutable(part_classifier->w);
/* clean up the region we selected */
float* w_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | 31, w, dy, dx, 0);
for (y = 0; y < dh; y++)
{
for (x = 0; x < dw * 31; x++)
w_ptr[x] = 0;
w_ptr += w->cols * 31;
}
i++;
if (symmetric && sym) // add counter-part
{
dx = w->cols - (dx + dw);
printf(" ---- part %d(%d) %dx%d at (%d,%d), entropy: %lf\n", i + 1, parts, dw, dh, dx, dy, dsum);
part_classifier[1].dx = 0;
part_classifier[1].dy = 0;
part_classifier[1].dxx = 0.1f;
part_classifier[1].dyy = 0.1f;
part_classifier[1].x = dx;
part_classifier[1].y = dy;
part_classifier[1].z = 1;
part_classifier[1].w = 0;
ccv_slice(w, (ccv_matrix_t**)&part_classifier[1].w, 0, dy, dx, dh, dw);
ccv_make_matrix_immutable(part_classifier[1].w);
/* clean up the region we selected */
float* w_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | 31, w, dy, dx, 0);
for (y = 0; y < dh; y++)
{
for (x = 0; x < dw * 31; x++)
w_ptr[x] = 0;
w_ptr += w->cols * 31;
}
part_classifier[0].counterpart = i;
part_classifier[1].counterpart = i - 1;
i++;
} else {
part_classifier->counterpart = -1;
}
}
ccv_matrix_free(w);
}
static void _ccv_dpm_initialize_feature_vector_on_pattern(ccv_dpm_feature_vector_t* vector, ccv_dpm_root_classifier_t* root, int id)
{
int i;
vector->id = id;
vector->count = root->count;
vector->part = (ccv_dpm_part_classifier_t*)ccmalloc(sizeof(ccv_dpm_part_classifier_t) * root->count);
vector->root.w = ccv_dense_matrix_new(root->root.w->rows, root->root.w->cols, CCV_32F | 31, 0, 0);
for (i = 0; i < vector->count; i++)
{
vector->part[i].x = root->part[i].x;
vector->part[i].y = root->part[i].y;
vector->part[i].z = root->part[i].z;
vector->part[i].w = ccv_dense_matrix_new(root->part[i].w->rows, root->part[i].w->cols, CCV_32F | 31, 0, 0);
}
}
static void _ccv_dpm_feature_vector_cleanup(ccv_dpm_feature_vector_t* vector)
{
int i;
if (vector->root.w)
ccv_matrix_free(vector->root.w);
for (i = 0; i < vector->count; i++)
ccv_matrix_free(vector->part[i].w);
if (vector->part)
ccfree(vector->part);
}
static void _ccv_dpm_feature_vector_free(ccv_dpm_feature_vector_t* vector)
{
_ccv_dpm_feature_vector_cleanup(vector);
ccfree(vector);
}
static double _ccv_dpm_vector_score(ccv_dpm_mixture_model_t* model, ccv_dpm_feature_vector_t* v)
{
if (v->id < 0 || v->id >= model->count)
return 0;
ccv_dpm_root_classifier_t* root_classifier = model->root + v->id;
double score = root_classifier->beta;
int i, k, ch = CCV_GET_CHANNEL(v->root.w->type);
assert(ch == 31);
float *vptr = v->root.w->data.f32;
float *wptr = root_classifier->root.w->data.f32;
for (i = 0; i < v->root.w->rows * v->root.w->cols * ch; i++)
score += wptr[i] * vptr[i];
assert(v->count == root_classifier->count || (v->count == 0 && v->part == 0));
for (k = 0; k < v->count; k++)
{
ccv_dpm_part_classifier_t* part_classifier = root_classifier->part + k;
ccv_dpm_part_classifier_t* part_vector = v->part + k;
score -= part_classifier->dx * part_vector->dx;
score -= part_classifier->dxx * part_vector->dxx;
score -= part_classifier->dy * part_vector->dy;
score -= part_classifier->dyy * part_vector->dyy;
vptr = part_vector->w->data.f32;
wptr = part_classifier->w->data.f32;
for (i = 0; i < part_vector->w->rows * part_vector->w->cols * ch; i++)
score += wptr[i] * vptr[i];
}
return score;
}
static void _ccv_dpm_collect_feature_vector(ccv_dpm_feature_vector_t* v, float score, int x, int y, ccv_dense_matrix_t* pyr, ccv_dense_matrix_t* detail, ccv_dense_matrix_t** dx, ccv_dense_matrix_t** dy)
{
v->score = score;
v->x = x;
v->y = y;
ccv_zero(v->root.w);
int rwh = (v->root.w->rows - 1) / 2, rww = (v->root.w->cols - 1) / 2;
int i, ix, iy, ch = CCV_GET_CHANNEL(v->root.w->type);
float* h_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | ch, pyr, y - rwh, x - rww, 0);
float* w_ptr = v->root.w->data.f32;
for (iy = 0; iy < v->root.w->rows; iy++)
{
memcpy(w_ptr, h_ptr, v->root.w->cols * ch * sizeof(float));
h_ptr += pyr->cols * ch;
w_ptr += v->root.w->cols * ch;
}
for (i = 0; i < v->count; i++)
{
ccv_dpm_part_classifier_t* part = v->part + i;
int pww = (part->w->cols - 1) / 2, pwh = (part->w->rows - 1) / 2;
int offy = part->y + pwh - rwh * 2;
int offx = part->x + pww - rww * 2;
iy = ccv_clamp(y * 2 + offy, pwh, detail->rows - part->w->rows + pwh);
ix = ccv_clamp(x * 2 + offx, pww, detail->cols - part->w->cols + pww);
int ry = ccv_get_dense_matrix_cell_value_by(CCV_32S | CCV_C1, dy[i], iy, ix, 0);
int rx = ccv_get_dense_matrix_cell_value_by(CCV_32S | CCV_C1, dx[i], iy, ix, 0);
part->dx = rx; // I am not sure if I need to flip the sign or not (confirmed, it should be this way)
part->dy = ry;
part->dxx = rx * rx;
part->dyy = ry * ry;
// deal with out-of-bound error
int start_y = ccv_max(0, iy - ry - pwh);
assert(start_y < detail->rows);
int start_x = ccv_max(0, ix - rx - pww);
assert(start_x < detail->cols);
int end_y = ccv_min(detail->rows, iy - ry - pwh + part->w->rows);
assert(end_y >= 0);
int end_x = ccv_min(detail->cols, ix - rx - pww + part->w->cols);
assert(end_x >= 0);
h_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | ch, detail, start_y, start_x, 0);
ccv_zero(v->part[i].w);
w_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | ch, part->w, start_y - (iy - ry - pwh), start_x - (ix - rx - pww), 0);
for (iy = start_y; iy < end_y; iy++)
{
memcpy(w_ptr, h_ptr, (end_x - start_x) * ch * sizeof(float));
h_ptr += detail->cols * ch;
w_ptr += part->w->cols * ch;
}
}
}
static ccv_dpm_feature_vector_t* _ccv_dpm_collect_best(ccv_dense_matrix_t* image, ccv_dpm_mixture_model_t* model, ccv_rect_t bbox, double overlap, ccv_dpm_param_t params)
{
int i, j, k, x, y;
double scale = pow(2.0, 1.0 / (params.interval + 1.0));
int next = params.interval + 1;
int scale_upto = _ccv_dpm_scale_upto(image, &model, 1, params.interval);
if (scale_upto < 0)
return 0;
ccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)alloca((scale_upto + next * 2) * sizeof(ccv_dense_matrix_t*));
_ccv_dpm_feature_pyramid(image, pyr, scale_upto, params.interval);
float best = -FLT_MAX;
ccv_dpm_feature_vector_t* v = 0;
for (i = 0; i < model->count; i++)
{
ccv_dpm_root_classifier_t* root_classifier = model->root + i;
double scale_x = 1.0;
double scale_y = 1.0;
for (j = next; j < scale_upto + next * 2; j++)
{
ccv_size_t size = ccv_size((int)(root_classifier->root.w->cols * CCV_DPM_WINDOW_SIZE * scale_x + 0.5), (int)(root_classifier->root.w->rows * CCV_DPM_WINDOW_SIZE * scale_y + 0.5));
if (ccv_min((double)(size.width * size.height), (double)(bbox.width * bbox.height)) /
ccv_max((double)(bbox.width * bbox.height), (double)(size.width * size.height)) < overlap)
{
scale_x *= scale;
scale_y *= scale;
continue;
}
ccv_dense_matrix_t* root_feature = 0;
ccv_dense_matrix_t* part_feature[CCV_DPM_PART_MAX];
ccv_dense_matrix_t* dx[CCV_DPM_PART_MAX];
ccv_dense_matrix_t* dy[CCV_DPM_PART_MAX];
_ccv_dpm_compute_score(root_classifier, pyr[j], pyr[j - next], &root_feature, part_feature, dx, dy);
int rwh = (root_classifier->root.w->rows - 1) / 2, rww = (root_classifier->root.w->cols - 1) / 2;
int rwh_1 = root_classifier->root.w->rows / 2, rww_1 = root_classifier->root.w->cols / 2;
float* f_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | CCV_C1, root_feature, rwh, 0, 0);
for (y = rwh; y < root_feature->rows - rwh_1; y++)
{
for (x = rww; x < root_feature->cols - rww_1; x++)
{
ccv_rect_t rect = ccv_rect((int)((x - rww) * CCV_DPM_WINDOW_SIZE * scale_x + 0.5), (int)((y - rwh) * CCV_DPM_WINDOW_SIZE * scale_y + 0.5), (int)(root_classifier->root.w->cols * CCV_DPM_WINDOW_SIZE * scale_x + 0.5), (int)(root_classifier->root.w->rows * CCV_DPM_WINDOW_SIZE * scale_y + 0.5));
if ((double)(ccv_max(0, ccv_min(rect.x + rect.width, bbox.x + bbox.width) - ccv_max(rect.x, bbox.x)) *
ccv_max(0, ccv_min(rect.y + rect.height, bbox.y + bbox.height) - ccv_max(rect.y, bbox.y))) /
(double)ccv_max(rect.width * rect.height, bbox.width * bbox.height) >= overlap && f_ptr[x] > best)
{
// initialize v
if (v == 0)
{
v = (ccv_dpm_feature_vector_t*)ccmalloc(sizeof(ccv_dpm_feature_vector_t));
_ccv_dpm_initialize_feature_vector_on_pattern(v, root_classifier, i);
}
// if it is another kind, cleanup and reinitialize
if (v->id != i)
{
_ccv_dpm_feature_vector_cleanup(v);
_ccv_dpm_initialize_feature_vector_on_pattern(v, root_classifier, i);
}
_ccv_dpm_collect_feature_vector(v, f_ptr[x] + root_classifier->beta, x, y, pyr[j], pyr[j - next], dx, dy);
v->scale_x = scale_x;
v->scale_y = scale_y;
best = f_ptr[x];
}
}
f_ptr += root_feature->cols;
}
for (k = 0; k < root_classifier->count; k++)
{
ccv_matrix_free(part_feature[k]);
ccv_matrix_free(dx[k]);
ccv_matrix_free(dy[k]);
}
ccv_matrix_free(root_feature);
scale_x *= scale;
scale_y *= scale;
}
}
for (i = 0; i < scale_upto + next * 2; i++)
ccv_matrix_free(pyr[i]);
return v;
}
static ccv_array_t* _ccv_dpm_collect_all(gsl_rng* rng, ccv_dense_matrix_t* image, ccv_dpm_mixture_model_t* model, ccv_dpm_param_t params, float threshold)
{
int i, j, k, x, y;
double scale = pow(2.0, 1.0 / (params.interval + 1.0));
int next = params.interval + 1;
int scale_upto = _ccv_dpm_scale_upto(image, &model, 1, params.interval);
if (scale_upto < 0)
return 0;
ccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)alloca((scale_upto + next * 2) * sizeof(ccv_dense_matrix_t*));
_ccv_dpm_feature_pyramid(image, pyr, scale_upto, params.interval);
ccv_array_t* av = ccv_array_new(sizeof(ccv_dpm_feature_vector_t*), 64, 0);
int enough = 64 / model->count;
int* order = (int*)alloca(sizeof(int) * model->count);
for (i = 0; i < model->count; i++)
order[i] = i;
gsl_ran_shuffle(rng, order, model->count, sizeof(int));
for (i = 0; i < model->count; i++)
{
ccv_dpm_root_classifier_t* root_classifier = model->root + order[i];
double scale_x = 1.0;
double scale_y = 1.0;
for (j = next; j < scale_upto + next * 2; j++)
{
ccv_dense_matrix_t* root_feature = 0;
ccv_dense_matrix_t* part_feature[CCV_DPM_PART_MAX];
ccv_dense_matrix_t* dx[CCV_DPM_PART_MAX];
ccv_dense_matrix_t* dy[CCV_DPM_PART_MAX];
_ccv_dpm_compute_score(root_classifier, pyr[j], pyr[j - next], &root_feature, part_feature, dx, dy);
int rwh = (root_classifier->root.w->rows - 1) / 2, rww = (root_classifier->root.w->cols - 1) / 2;
int rwh_1 = root_classifier->root.w->rows / 2, rww_1 = root_classifier->root.w->cols / 2;
float* f_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | CCV_C1, root_feature, rwh, 0, 0);
for (y = rwh; y < root_feature->rows - rwh_1; y++)
{
for (x = rww; x < root_feature->cols - rww_1; x++)
if (f_ptr[x] + root_classifier->beta > threshold)
{
// initialize v
ccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccmalloc(sizeof(ccv_dpm_feature_vector_t));
_ccv_dpm_initialize_feature_vector_on_pattern(v, root_classifier, order[i]);
_ccv_dpm_collect_feature_vector(v, f_ptr[x] + root_classifier->beta, x, y, pyr[j], pyr[j - next], dx, dy);
v->scale_x = scale_x;
v->scale_y = scale_y;
ccv_array_push(av, &v);
if (av->rnum >= enough * (i + 1))
break;
}
f_ptr += root_feature->cols;
if (av->rnum >= enough * (i + 1))
break;
}
for (k = 0; k < root_classifier->count; k++)
{
ccv_matrix_free(part_feature[k]);
ccv_matrix_free(dx[k]);
ccv_matrix_free(dy[k]);
}
ccv_matrix_free(root_feature);
scale_x *= scale;
scale_y *= scale;
if (av->rnum >= enough * (i + 1))
break;
}
}
for (i = 0; i < scale_upto + next * 2; i++)
ccv_matrix_free(pyr[i]);
return av;
}
static void _ccv_dpm_collect_from_background(ccv_array_t* av, gsl_rng* rng, char** bgfiles, int bgnum, ccv_dpm_mixture_model_t* model, ccv_dpm_new_param_t params, float threshold)
{
int i, j;
int* order = (int*)ccmalloc(sizeof(int) * bgnum);
for (i = 0; i < bgnum; i++)
order[i] = i;
gsl_ran_shuffle(rng, order, bgnum, sizeof(int));
for (i = 0; i < bgnum; i++)
{
FLUSH(" - collecting negative examples -- (%d%%)", av->rnum * 100 / params.negative_cache_size);
ccv_dense_matrix_t* image = 0;
ccv_read(bgfiles[order[i]], &image, (params.grayscale ? CCV_IO_GRAY : 0) | CCV_IO_ANY_FILE);
ccv_array_t* at = _ccv_dpm_collect_all(rng, image, model, params.detector, threshold);
if (at)
{
for (j = 0; j < at->rnum; j++)
ccv_array_push(av, ccv_array_get(at, j));
ccv_array_free(at);
}
ccv_matrix_free(image);
if (av->rnum >= params.negative_cache_size)
break;
}
ccfree(order);
}
static void _ccv_dpm_initialize_root_rectangle_estimator(ccv_dpm_mixture_model_t* model, char** posfiles, ccv_rect_t* bboxes, int posnum, ccv_dpm_new_param_t params)
{
int i, j, k, c;
ccv_dpm_feature_vector_t** posv = (ccv_dpm_feature_vector_t**)ccmalloc(sizeof(ccv_dpm_feature_vector_t*) * posnum);
int* num_per_model = (int*)alloca(sizeof(int) * model->count);
memset(num_per_model, 0, sizeof(int) * model->count);
FLUSH(" - collecting responses from positive examples : 0%%");
for (i = 0; i < posnum; i++)
{
FLUSH(" - collecting responses from positive examples : %d%%", i * 100 / posnum);
ccv_dense_matrix_t* image = 0;
ccv_read(posfiles[i], &image, (params.grayscale ? CCV_IO_GRAY : 0) | CCV_IO_ANY_FILE);
posv[i] = _ccv_dpm_collect_best(image, model, bboxes[i], params.include_overlap, params.detector);
if (posv[i])
++num_per_model[posv[i]->id];
ccv_matrix_free(image);
}
// this will estimate new x, y, and scale
printf("\n - linear regression for x, y, and scale drifting\n");
for (i = 0; i < model->count; i++)
{
ccv_dpm_root_classifier_t* root_classifier = model->root + i;
gsl_matrix* X = gsl_matrix_alloc(num_per_model[i], root_classifier->count * 2 + 1);
gsl_vector* y[3];
y[0] = gsl_vector_alloc(num_per_model[i]);
y[1] = gsl_vector_alloc(num_per_model[i]);
y[2] = gsl_vector_alloc(num_per_model[i]);
gsl_vector* z = gsl_vector_alloc(root_classifier->count * 2 + 1);
gsl_matrix* cov = gsl_matrix_alloc(root_classifier->count * 2 + 1, root_classifier->count * 2 + 1);;
c = 0;
for (j = 0; j < posnum; j++)
{
ccv_dpm_feature_vector_t* v = posv[j];
if (v && v->id == i)
{
gsl_matrix_set(X, c, 0, 1.0);
for (k = 0; k < v->count; k++)
{
gsl_matrix_set(X, c, k * 2 + 1, v->part[k].dx);
gsl_matrix_set(X, c, k * 2 + 2, v->part[k].dy);
}
ccv_rect_t bbox = bboxes[j];
gsl_vector_set(y[0], c, (bbox.x + bbox.width * 0.5) / (v->scale_x * CCV_DPM_WINDOW_SIZE) - v->x);
gsl_vector_set(y[1], c, (bbox.y + bbox.height * 0.5) / (v->scale_y * CCV_DPM_WINDOW_SIZE) - v->y);
gsl_vector_set(y[2], c, sqrt((bbox.width * bbox.height) / (root_classifier->root.w->rows * v->scale_x * CCV_DPM_WINDOW_SIZE * root_classifier->root.w->cols * v->scale_y * CCV_DPM_WINDOW_SIZE)) - 1.0);
++c;
}
}
gsl_multifit_linear_workspace* workspace = gsl_multifit_linear_alloc(num_per_model[i], root_classifier->count * 2 + 1);
double chisq;
for (j = 0; j < 3; j++)
{
gsl_multifit_linear(X, y[j], z, cov, &chisq, workspace);
root_classifier->alpha[j] = params.discard_estimating_constant ? 0 : gsl_vector_get(z, 0);
for (k = 0; k < root_classifier->count; k++)
{
ccv_dpm_part_classifier_t* part_classifier = root_classifier->part + k;
part_classifier->alpha[j * 2] = gsl_vector_get(z, k * 2 + 1);
part_classifier->alpha[j * 2 + 1] = gsl_vector_get(z, k * 2 + 2);
}
}
gsl_multifit_linear_free(workspace);
gsl_matrix_free(cov);
gsl_vector_free(z);
gsl_vector_free(y[0]);
gsl_vector_free(y[1]);
gsl_vector_free(y[2]);
gsl_matrix_free(X);
}
for (i = 0; i < posnum; i++)
if (posv[i])
_ccv_dpm_feature_vector_free(posv[i]);
ccfree(posv);
}
static void _ccv_dpm_regularize_mixture_model(ccv_dpm_mixture_model_t* model, int i, double regz)
{
int k;
ccv_dpm_root_classifier_t* root_classifier = model->root + i;
int ch = CCV_GET_CHANNEL(root_classifier->root.w->type);
ccv_make_matrix_mutable(root_classifier->root.w);
float *wptr = root_classifier->root.w->data.f32;
for (i = 0; i < root_classifier->root.w->rows * root_classifier->root.w->cols * ch; i++)
wptr[i] -= regz * wptr[i];
ccv_make_matrix_immutable(root_classifier->root.w);
root_classifier->beta -= regz * root_classifier->beta;
for (k = 0; k < root_classifier->count; k++)
{
ccv_dpm_part_classifier_t* part_classifier = root_classifier->part + k;
ccv_make_matrix_mutable(part_classifier->w);
wptr = part_classifier->w->data.f32;
for (i = 0; i < part_classifier->w->rows * part_classifier->w->cols * ch; i++)
wptr[i] -= regz * wptr[i];
ccv_make_matrix_immutable(part_classifier->w);
part_classifier->dx -= regz * part_classifier->dx;
part_classifier->dxx -= regz * part_classifier->dxx;
part_classifier->dy -= regz * part_classifier->dy;
part_classifier->dyy -= regz * part_classifier->dyy;
part_classifier->dxx = ccv_max(0.01, part_classifier->dxx);
part_classifier->dyy = ccv_max(0.01, part_classifier->dyy);
}
}
static void _ccv_dpm_stochastic_gradient_descent(ccv_dpm_mixture_model_t* model, ccv_dpm_feature_vector_t* v, double y, double alpha, double Cn, int symmetric)
{
if (v->id < 0 || v->id >= model->count)
return;
ccv_dpm_root_classifier_t* root_classifier = model->root + v->id;
int i, j, k, c, ch = CCV_GET_CHANNEL(v->root.w->type);
assert(ch == 31);
assert(v->root.w->rows == root_classifier->root.w->rows && v->root.w->cols == root_classifier->root.w->cols);
float *vptr = v->root.w->data.f32;
ccv_make_matrix_mutable(root_classifier->root.w);
float *wptr = root_classifier->root.w->data.f32;
if (symmetric)
{
for (i = 0; i < v->root.w->rows; i++)
{
for (j = 0; j < v->root.w->cols; j++)
for (c = 0; c < ch; c++)
{
wptr[j * ch + c] += alpha * y * Cn * vptr[j * ch + c];
wptr[j * ch + c] += alpha * y * Cn * vptr[(v->root.w->cols - 1 - j) * ch + _ccv_dpm_sym_lut[c]];
}
vptr += v->root.w->cols * ch;
wptr += root_classifier->root.w->cols * ch;
}
root_classifier->beta += alpha * y * Cn * 2.0;
} else {
for (i = 0; i < v->root.w->rows * v->root.w->cols * ch; i++)
wptr[i] += alpha * y * Cn * vptr[i];
root_classifier->beta += alpha * y * Cn;
}
ccv_make_matrix_immutable(root_classifier->root.w);
assert(v->count == root_classifier->count);
for (k = 0; k < v->count; k++)
{
ccv_dpm_part_classifier_t* part_classifier = root_classifier->part + k;
ccv_make_matrix_mutable(part_classifier->w);
ccv_dpm_part_classifier_t* part_vector = v->part + k;
assert(part_vector->w->rows == part_classifier->w->rows && part_vector->w->cols == part_classifier->w->cols);
part_classifier->dx -= alpha * y * Cn * part_vector->dx;
part_classifier->dxx -= alpha * y * Cn * part_vector->dxx;
part_classifier->dxx = ccv_max(part_classifier->dxx, 0.01);
part_classifier->dy -= alpha * y * Cn * part_vector->dy;
part_classifier->dyy -= alpha * y * Cn * part_vector->dyy;
part_classifier->dyy = ccv_max(part_classifier->dyy, 0.01);
vptr = part_vector->w->data.f32;
wptr = part_classifier->w->data.f32;
if (symmetric)
{
// 2x converge on everything for symmetric feature
if (part_classifier->counterpart == -1)
{
part_classifier->dx += /* flip the sign on x-axis (symmetric) */ alpha * y * Cn * part_vector->dx;
part_classifier->dxx -= alpha * y * Cn * part_vector->dxx;
part_classifier->dxx = ccv_max(part_classifier->dxx, 0.01);
part_classifier->dy -= alpha * y * Cn * part_vector->dy;
part_classifier->dyy -= alpha * y * Cn * part_vector->dyy;
part_classifier->dyy = ccv_max(part_classifier->dyy, 0.01);
for (i = 0; i < part_vector->w->rows; i++)
{
for (j = 0; j < part_vector->w->cols; j++)
for (c = 0; c < ch; c++)
{
wptr[j * ch + c] += alpha * y * Cn * vptr[j * ch + c];
wptr[j * ch + c] += alpha * y * Cn * vptr[(part_vector->w->cols - 1 - j) * ch + _ccv_dpm_sym_lut[c]];
}
vptr += part_vector->w->cols * ch;
wptr += part_classifier->w->cols * ch;
}
} else {
ccv_dpm_part_classifier_t* other_part_classifier = root_classifier->part + part_classifier->counterpart;
assert(part_vector->w->rows == other_part_classifier->w->rows && part_vector->w->cols == other_part_classifier->w->cols);
other_part_classifier->dx += /* flip the sign on x-axis (symmetric) */ alpha * y * Cn * part_vector->dx;
other_part_classifier->dxx -= alpha * y * Cn * part_vector->dxx;
other_part_classifier->dxx = ccv_max(other_part_classifier->dxx, 0.01);
other_part_classifier->dy -= alpha * y * Cn * part_vector->dy;
other_part_classifier->dyy -= alpha * y * Cn * part_vector->dyy;
other_part_classifier->dyy = ccv_max(other_part_classifier->dyy, 0.01);
for (i = 0; i < part_vector->w->rows; i++)
{
for (j = 0; j < part_vector->w->cols * ch; j++)
wptr[j] += alpha * y * Cn * vptr[j];
vptr += part_vector->w->cols * ch;
wptr += part_classifier->w->cols * ch;
}
vptr = part_vector->w->data.f32;
wptr = other_part_classifier->w->data.f32;
for (i = 0; i < part_vector->w->rows; i++)
{
for (j = 0; j < part_vector->w->cols; j++)
for (c = 0; c < ch; c++)
wptr[j * ch + c] += alpha * y * Cn * vptr[(part_vector->w->cols - 1 - j) * ch + _ccv_dpm_sym_lut[c]];
vptr += part_vector->w->cols * ch;
wptr += other_part_classifier->w->cols * ch;
}
}
} else {
for (i = 0; i < part_vector->w->rows * part_vector->w->cols * ch; i++)
wptr[i] += alpha * y * Cn * vptr[i];
}
ccv_make_matrix_immutable(part_classifier->w);
}
}
static void _ccv_dpm_write_gradient_descent_progress(int i, int j, const char* dir)
{
char swpfile[1024];
sprintf(swpfile, "%s.swp", dir);
FILE* w = fopen(swpfile, "w+");
if (!w)
return;
fprintf(w, "%d %d\n", i, j);
fclose(w);
rename(swpfile, dir);
}
static void _ccv_dpm_read_gradient_descent_progress(int* i, int* j, const char* dir)
{
FILE* r = fopen(dir, "r");
if (!r)
return;
fscanf(r, "%d %d", i, j);
fclose(r);
}
static void _ccv_dpm_write_feature_vector(FILE* w, ccv_dpm_feature_vector_t* v)
{
int j, x, y, ch;
if (v)
{
fprintf(w, "%d %d %d\n", v->id, v->root.w->rows, v->root.w->cols);
ch = CCV_GET_CHANNEL(v->root.w->type);
for (y = 0; y < v->root.w->rows; y++)
{
for (x = 0; x < v->root.w->cols * ch; x++)
fprintf(w, "%a ", v->root.w->data.f32[y * v->root.w->cols * ch + x]);
fprintf(w, "\n");
}
fprintf(w, "%d %a\n", v->count, v->score);
for (j = 0; j < v->count; j++)
{
ccv_dpm_part_classifier_t* part_classifier = v->part + j;
fprintf(w, "%la %la %la %la\n", part_classifier->dx, part_classifier->dy, part_classifier->dxx, part_classifier->dyy);
fprintf(w, "%d %d %d\n", part_classifier->x, part_classifier->y, part_classifier->z);
fprintf(w, "%d %d\n", part_classifier->w->rows, part_classifier->w->cols);
ch = CCV_GET_CHANNEL(part_classifier->w->type);
for (y = 0; y < part_classifier->w->rows; y++)
{
for (x = 0; x < part_classifier->w->cols * ch; x++)
fprintf(w, "%a ", part_classifier->w->data.f32[y * part_classifier->w->cols * ch + x]);
fprintf(w, "\n");
}
}
} else {
fprintf(w, "0 0 0\n");
}
}
static ccv_dpm_feature_vector_t* _ccv_dpm_read_feature_vector(FILE* r)
{
int id, rows, cols, j, k;
fscanf(r, "%d %d %d", &id, &rows, &cols);
if (rows == 0 && cols == 0)
return 0;
ccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccmalloc(sizeof(ccv_dpm_feature_vector_t));
v->id = id;
v->root.w = ccv_dense_matrix_new(rows, cols, CCV_32F | 31, 0, 0);
for (j = 0; j < rows * cols * 31; j++)
fscanf(r, "%f", &v->root.w->data.f32[j]);
fscanf(r, "%d %f", &v->count, &v->score);
v->part = (ccv_dpm_part_classifier_t*)ccmalloc(sizeof(ccv_dpm_part_classifier_t) * v->count);
for (j = 0; j < v->count; j++)
{
ccv_dpm_part_classifier_t* part_classifier = v->part + j;
fscanf(r, "%lf %lf %lf %lf", &part_classifier->dx, &part_classifier->dy, &part_classifier->dxx, &part_classifier->dyy);
fscanf(r, "%d %d %d", &part_classifier->x, &part_classifier->y, &part_classifier->z);
fscanf(r, "%d %d", &rows, &cols);
part_classifier->w = ccv_dense_matrix_new(rows, cols, CCV_32F | 31, 0, 0);
for (k = 0; k < rows * cols * 31; k++)
fscanf(r, "%f", &part_classifier->w->data.f32[k]);
}
return v;
}
static void _ccv_dpm_write_positive_feature_vectors(ccv_dpm_feature_vector_t** vs, int n, const char* dir)
{
FILE* w = fopen(dir, "w+");
if (!w)
return;
fprintf(w, "%d\n", n);
int i;
for (i = 0; i < n; i++)
_ccv_dpm_write_feature_vector(w, vs[i]);
fclose(w);
}
static int _ccv_dpm_read_positive_feature_vectors(ccv_dpm_feature_vector_t** vs, int _n, const char* dir)
{
FILE* r = fopen(dir, "r");
if (!r)
return -1;
int n;
fscanf(r, "%d", &n);
assert(n == _n);
int i;
for (i = 0; i < n; i++)
vs[i] = _ccv_dpm_read_feature_vector(r);
fclose(r);
return 0;
}
static void _ccv_dpm_write_negative_feature_vectors(ccv_array_t* negv, int negative_cache_size, const char* dir)
{
FILE* w = fopen(dir, "w+");
if (!w)
return;
fprintf(w, "%d %d\n", negative_cache_size, negv->rnum);
int i;
for (i = 0; i < negv->rnum; i++)
{
ccv_dpm_feature_vector_t* v = *(ccv_dpm_feature_vector_t**)ccv_array_get(negv, i);
_ccv_dpm_write_feature_vector(w, v);
}
fclose(w);
}
static int _ccv_dpm_read_negative_feature_vectors(ccv_array_t** _negv, int _negative_cache_size, const char* dir)
{
FILE* r = fopen(dir, "r");
if (!r)
return -1;
int negative_cache_size, negnum;
fscanf(r, "%d %d", &negative_cache_size, &negnum);
assert(negative_cache_size == _negative_cache_size);
ccv_array_t* negv = *_negv = ccv_array_new(sizeof(ccv_dpm_feature_vector_t*), negnum, 0);
int i;
for (i = 0; i < negnum; i++)
{
ccv_dpm_feature_vector_t* v = _ccv_dpm_read_feature_vector(r);
assert(v);
ccv_array_push(negv, &v);
}
fclose(r);
return 0;
}
static void _ccv_dpm_adjust_model_constant(ccv_dpm_mixture_model_t* model, int k, ccv_dpm_feature_vector_t** posv, int posnum, double percentile)
{
int i, j;
double* scores = (double*)ccmalloc(posnum * sizeof(double));
j = 0;
for (i = 0; i < posnum; i++)
if (posv[i] && posv[i]->id == k)
{
scores[j] = _ccv_dpm_vector_score(model, posv[i]);
j++;
}
_ccv_dpm_score_qsort(scores, j, 0);
float adjust = scores[ccv_clamp((int)(percentile * j), 0, j - 1)];
// adjust to percentile
model->root[k].beta -= adjust;
printf(" - tune model %d constant for %f\n", k + 1, -adjust);
ccfree(scores);
}
static void _ccv_dpm_check_params(ccv_dpm_new_param_t params)
{
assert(params.components > 0);
assert(params.parts > 0);
assert(params.grayscale == 0 || params.grayscale == 1);
assert(params.symmetric == 0 || params.symmetric == 1);
assert(params.min_area > 100);
assert(params.max_area > params.min_area);
assert(params.iterations >= 0);
assert(params.data_minings >= 0);
assert(params.relabels >= 0);
assert(params.negative_cache_size > 0);
assert(params.include_overlap > 0.1);
assert(params.alpha > 0 && params.alpha < 1);
assert(params.alpha_ratio > 0 && params.alpha_ratio < 1);
assert(params.C > 0);
assert(params.balance > 0);
assert(params.percentile_breakdown > 0 && params.percentile_breakdown <= 1);
assert(params.detector.interval > 0);
}
#define MINI_BATCH (10)
#define REGQ (100)
static ccv_dpm_mixture_model_t* _ccv_dpm_optimize_root_mixture_model(gsl_rng* rng, ccv_dpm_mixture_model_t* model, ccv_array_t** posex, ccv_array_t** negex, int relabels, double balance, double C, double previous_alpha, double alpha_ratio, int iterations, int symmetric)
{
int i, j, k, t, c;
for (i = 0; i < model->count - 1; i++)
assert(posex[i]->rnum == posex[i + 1]->rnum && negex[i]->rnum == negex[i + 1]->rnum);
int posnum = posex[0]->rnum;
int negnum = negex[0]->rnum;
int* label = (int*)ccmalloc(sizeof(int) * (posnum + negnum));
int* order = (int*)ccmalloc(sizeof(int) * (posnum + negnum));
double previous_positive_loss = 0, previous_negative_loss = 0, positive_loss = 0, negative_loss = 0, loss = 0;
double regz_rate = C;
for (c = 0; c < relabels; c++)
{
int* pos_prog = (int*)alloca(sizeof(int) * model->count);
memset(pos_prog, 0, sizeof(int) * model->count);
for (i = 0; i < posnum; i++)
{
int best = -1;
double best_score = -DBL_MAX;
for (k = 0; k < model->count; k++)
{
ccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccv_array_get(posex[k], i);
if (v->root.w == 0)
continue;
double score = _ccv_dpm_vector_score(model, v); // the loss for mini-batch method (computed on model)
if (score > best_score)
{
best = k;
best_score = score;
}
}
label[i] = best;
if (best >= 0)
++pos_prog[best];
}
printf(" - positive examples divided by components for root model optimizing : %d", pos_prog[0]);
for (i = 1; i < model->count; i++)
printf(", %d", pos_prog[i]);
printf("\n");
int* neg_prog = (int*)alloca(sizeof(int) * model->count);
memset(neg_prog, 0, sizeof(int) * model->count);
for (i = 0; i < negnum; i++)
{
int best = gsl_rng_uniform_int(rng, model->count);
label[i + posnum] = best;
++neg_prog[best];
}
printf(" - negative examples divided by components for root model optimizing : %d", neg_prog[0]);
for (i = 1; i < model->count; i++)
printf(", %d", neg_prog[i]);
printf("\n");
ccv_dpm_mixture_model_t* _model;
double alpha = previous_alpha;
previous_positive_loss = previous_negative_loss = 0;
for (t = 0; t < iterations; t++)
{
for (i = 0; i < posnum + negnum; i++)
order[i] = i;
gsl_ran_shuffle(rng, order, posnum + negnum, sizeof(int));
for (j = 0; j < model->count; j++)
{
double pos_weight = sqrt((double)neg_prog[j] / pos_prog[j] * balance); // positive weight
double neg_weight = sqrt((double)pos_prog[j] / neg_prog[j] / balance); // negative weight
_model = _ccv_dpm_model_copy(model);
int l = 0;
for (i = 0; i < posnum + negnum; i++)
{
k = order[i];
if (label[k] == j)
{
assert(label[k] < model->count);
if (k < posnum)
{
ccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccv_array_get(posex[label[k]], k);
assert(v->root.w);
double score = _ccv_dpm_vector_score(model, v); // the loss for mini-batch method (computed on model)
assert(!isnan(score));
assert(v->id == j);
if (score <= 1)
_ccv_dpm_stochastic_gradient_descent(_model, v, 1, alpha * pos_weight, regz_rate, symmetric);
} else {
ccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccv_array_get(negex[label[k]], k - posnum);
double score = _ccv_dpm_vector_score(model, v);
assert(!isnan(score));
assert(v->id == j);
if (score >= -1)
_ccv_dpm_stochastic_gradient_descent(_model, v, -1, alpha * neg_weight, regz_rate, symmetric);
}
++l;
if (l % REGQ == REGQ - 1)
_ccv_dpm_regularize_mixture_model(_model, j, 1.0 - pow(1.0 - alpha / (double)((pos_prog[j] + neg_prog[j]) * (!!symmetric + 1)), REGQ));
if (l % MINI_BATCH == MINI_BATCH - 1)
{
// mimicking mini-batch way of doing things
_ccv_dpm_mixture_model_cleanup(model);
ccfree(model);
model = _model;
_model = _ccv_dpm_model_copy(model);
}
}
}
_ccv_dpm_regularize_mixture_model(_model, j, 1.0 - pow(1.0 - alpha / (double)((pos_prog[j] + neg_prog[j]) * (!!symmetric + 1)), (((pos_prog[j] + neg_prog[j]) % REGQ) + 1) % (REGQ + 1)));
_ccv_dpm_mixture_model_cleanup(model);
ccfree(model);
model = _model;
}
// compute the loss
positive_loss = negative_loss = loss = 0;
int posvn = 0;
for (i = 0; i < posnum; i++)
{
if (label[i] < 0)
continue;
assert(label[i] < model->count);
ccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccv_array_get(posex[label[i]], i);
if (v->root.w)
{
double score = _ccv_dpm_vector_score(model, v);
assert(!isnan(score));
double hinge_loss = ccv_max(0, 1.0 - score);
positive_loss += hinge_loss;
double pos_weight = sqrt((double)neg_prog[v->id] / pos_prog[v->id] * balance); // positive weight
loss += pos_weight * hinge_loss;
++posvn;
}
}
for (i = 0; i < negnum; i++)
{
if (label[i + posnum] < 0)
continue;
assert(label[i + posnum] < model->count);
ccv_dpm_feature_vector_t* v = (ccv_dpm_feature_vector_t*)ccv_array_get(negex[label[i + posnum]], i);
double score = _ccv_dpm_vector_score(model, v);
assert(!isnan(score));
double hinge_loss = ccv_max(0, 1.0 + score);
negative_loss += hinge_loss;
double neg_weight = sqrt((double)pos_prog[v->id] / neg_prog[v->id] / balance); // negative weight
loss += neg_weight * hinge_loss;
}
loss = loss / (posvn + negnum);
positive_loss = positive_loss / posvn;
negative_loss = negative_loss / negnum;
FLUSH(" - with loss %.5lf (positive %.5lf, negative %.5f) at rate %.5lf %d | %d -- %d%%", loss, positive_loss, negative_loss, alpha, posvn, negnum, (t + 1) * 100 / iterations);
// check symmetric property of generated root feature
if (symmetric)
for (i = 0; i < model->count; i++)
{
ccv_dpm_root_classifier_t* root_classifier = model->root + i;
_ccv_dpm_check_root_classifier_symmetry(root_classifier->root.w);
}
if (fabs(previous_positive_loss - positive_loss) < 1e-5 &&
fabs(previous_negative_loss - negative_loss) < 1e-5)
{
printf("\n - aborting iteration at %d because we didn't gain much", t + 1);
break;
}
previous_positive_loss = positive_loss;
previous_negative_loss = negative_loss;
alpha *= alpha_ratio; // it will decrease with each iteration
}
printf("\n");
}
ccfree(order);
ccfree(label);
return model;
}
void ccv_dpm_mixture_model_new(char** posfiles, ccv_rect_t* bboxes, int posnum, char** bgfiles, int bgnum, int negnum, const char* dir, ccv_dpm_new_param_t params)
{
int t, d, c, i, j, k, p;
_ccv_dpm_check_params(params);
assert(params.negative_cache_size <= negnum && params.negative_cache_size > REGQ && params.negative_cache_size > MINI_BATCH);
printf("with %d positive examples and %d negative examples\n"
"negative examples are are going to be collected from %d background images\n",
posnum, negnum, bgnum);
printf("use symmetric property? %s\n", params.symmetric ? "yes" : "no");
printf("use color? %s\n", params.grayscale ? "no" : "yes");
printf("negative examples cache size : %d\n", params.negative_cache_size);
printf("%d components and %d parts\n", params.components, params.parts);
printf("expected %d root relabels, %d relabels, %d data minings and %d iterations\n", params.root_relabels, params.relabels, params.data_minings, params.iterations);
printf("include overlap : %lf\n"
"alpha : %lf\n"
"alpha decreasing ratio : %lf\n"
"C : %lf\n"
"balance ratio : %lf\n"
"------------------------\n",
params.include_overlap, params.alpha, params.alpha_ratio, params.C, params.balance);
gsl_rng_env_setup();
gsl_rng* rng = gsl_rng_alloc(gsl_rng_default);
gsl_rng_set(rng, *(unsigned long int*)¶ms);
ccv_dpm_mixture_model_t* model = (ccv_dpm_mixture_model_t*)ccmalloc(sizeof(ccv_dpm_mixture_model_t));
memset(model, 0, sizeof(ccv_dpm_mixture_model_t));
struct feature_node* fn = (struct feature_node*)ccmalloc(sizeof(struct feature_node) * posnum);
for (i = 0; i < posnum; i++)
{
assert(bboxes[i].width > 0 && bboxes[i].height > 0);
fn[i].value = (float)bboxes[i].width / (float)bboxes[i].height;
fn[i].index = i;
}
char checkpoint[512];
char initcheckpoint[512];
sprintf(checkpoint, "%s/model", dir);
sprintf(initcheckpoint, "%s/init.model", dir);
_ccv_dpm_aspect_qsort(fn, posnum, 0);
double mean = 0;
for (i = 0; i < posnum; i++)
mean += fn[i].value;
mean /= posnum;
double variance = 0;
for (i = 0; i < posnum; i++)
variance += (fn[i].value - mean) * (fn[i].value - mean);
variance /= posnum;
printf("global mean: %lf, & variance: %lf\ninterclass mean(variance):", mean, variance);
int* mnum = (int*)alloca(sizeof(int) * params.components);
int outnum = posnum, innum = 0;
for (i = 0; i < params.components; i++)
{
mnum[i] = (int)((double)outnum / (double)(params.components - i) + 0.5);
double mean = 0;
for (j = innum; j < innum + mnum[i]; j++)
mean += fn[j].value;
mean /= mnum[i];
double variance = 0;
for (j = innum; j < innum + mnum[i]; j++)
variance += (fn[j].value - mean) * (fn[j].value - mean);
variance /= mnum[i];
printf(" %lf(%lf)", mean, variance);
outnum -= mnum[i];
innum += mnum[i];
}
printf("\n");
int* areas = (int*)ccmalloc(sizeof(int) * posnum);
for (i = 0; i < posnum; i++)
areas[i] = bboxes[i].width * bboxes[i].height;
_ccv_dpm_area_qsort(areas, posnum, 0);
// so even the object is 1/4 in size, we can still detect them (in detection phase, we start at 2x image)
int area = ccv_clamp(areas[(int)(posnum * 0.2 + 0.5)], params.min_area, params.max_area);
ccfree(areas);
innum = 0;
_ccv_dpm_read_checkpoint(model, checkpoint);
if (model->count <= 0)
{
/* initialize root mixture model with liblinear */
model->count = params.components;
model->root = (ccv_dpm_root_classifier_t*)ccmalloc(sizeof(ccv_dpm_root_classifier_t) * model->count);
memset(model->root, 0, sizeof(ccv_dpm_root_classifier_t) * model->count);
}
printf("computing root mixture model dimensions: ");
fflush(stdout);
int* poslabels = (int*)ccmalloc(sizeof(int) * posnum);
int* rows = (int*)alloca(sizeof(int) * params.components);
int* cols = (int*)alloca(sizeof(int) * params.components);
for (i = 0; i < params.components; i++)
{
double aspect = 0;
for (j = innum; j < innum + mnum[i]; j++)
{
aspect += fn[j].value;
poslabels[fn[j].index] = i; // setup labels
}
aspect /= mnum[i];
cols[i] = ccv_max((int)(sqrtf(area / aspect) * aspect / CCV_DPM_WINDOW_SIZE + 0.5), 1);
rows[i] = ccv_max((int)(sqrtf(area / aspect) / CCV_DPM_WINDOW_SIZE + 0.5), 1);
if (i < params.components - 1)
printf("%dx%d, ", cols[i], rows[i]);
else
printf("%dx%d\n", cols[i], rows[i]);
fflush(stdout);
innum += mnum[i];
}
ccfree(fn);
int corrupted = 1;
for (i = 0; i < params.components; i++)
if (model->root[i].root.w)
{
printf("skipping root mixture model initialization for model %d(%d)\n", i + 1, params.components);
corrupted = 0;
} else
break;
if (corrupted)
{
printf("root mixture model initialization corrupted, reboot\n");
ccv_array_t** posex = (ccv_array_t**)alloca(sizeof(ccv_array_t*) * params.components);
for (i = 0; i < params.components; i++)
posex[i] = _ccv_dpm_summon_examples_by_rectangle(posfiles, bboxes, posnum, i, rows[i], cols[i], params.grayscale);
printf("\n");
ccv_array_t** negex = (ccv_array_t**)alloca(sizeof(ccv_array_t*) * params.components);
_ccv_dpm_collect_examples_randomly(rng, negex, bgfiles, bgnum, negnum, params.components, rows, cols, params.grayscale);
printf("\n");
int* neglabels = (int*)ccmalloc(sizeof(int) * negex[0]->rnum);
for (i = 0; i < negex[0]->rnum; i++)
neglabels[i] = gsl_rng_uniform_int(rng, params.components);
for (i = 0; i < params.components; i++)
{
ccv_dpm_root_classifier_t* root_classifier = model->root + i;
root_classifier->root.w = ccv_dense_matrix_new(rows[i], cols[i], CCV_32F | 31, 0, 0);
printf("initializing root mixture model for model %d(%d)\n", i + 1, params.components);
_ccv_dpm_initialize_root_classifier(rng, root_classifier, i, mnum[i], poslabels, posex[i], neglabels, negex[i], params.C, params.symmetric, params.grayscale);
}
ccfree(neglabels);
ccfree(poslabels);
// check symmetric property of generated root feature
if (params.symmetric)
for (i = 0; i < params.components; i++)
{
ccv_dpm_root_classifier_t* root_classifier = model->root + i;
_ccv_dpm_check_root_classifier_symmetry(root_classifier->root.w);
}
if (params.components > 1)
{
/* TODO: coordinate-descent for lsvm */
printf("optimizing root mixture model with coordinate-descent approach\n");
model = _ccv_dpm_optimize_root_mixture_model(rng, model, posex, negex, params.root_relabels, params.balance, params.C, params.alpha, params.alpha_ratio, params.iterations, params.symmetric);
} else {
printf("components == 1, skipped coordinate-descent to optimize root mixture model\n");
}
for (i = 0; i < params.components; i++)
{
for (j = 0; j < posex[i]->rnum; j++)
_ccv_dpm_feature_vector_cleanup((ccv_dpm_feature_vector_t*)ccv_array_get(posex[i], j));
ccv_array_free(posex[i]);
for (j = 0; j < negex[i]->rnum; j++)
_ccv_dpm_feature_vector_cleanup((ccv_dpm_feature_vector_t*)ccv_array_get(negex[i], j));
ccv_array_free(negex[i]);
}
} else {
ccfree(poslabels);
}
_ccv_dpm_write_checkpoint(model, 0, checkpoint);
/* initialize part filter */
printf("initializing part filters\n");
for (i = 0; i < params.components; i++)
{
if (model->root[i].count > 0)
{
printf(" - skipping part filters initialization for model %d(%d)\n", i + 1, params.components);
} else {
printf(" - initializing part filters for model %d(%d)\n", i + 1, params.components);
_ccv_dpm_initialize_part_classifiers(model->root + i, params.parts, params.symmetric);
_ccv_dpm_write_checkpoint(model, 0, checkpoint);
_ccv_dpm_write_checkpoint(model, 0, initcheckpoint);
}
}
_ccv_dpm_write_checkpoint(model, 0, checkpoint);
/* optimize both root filter and part filters with stochastic gradient descent */
printf("optimizing root filter & part filters with stochastic gradient descent\n");
char gradient_progress_checkpoint[512];
sprintf(gradient_progress_checkpoint, "%s/gradient_descent_progress", dir);
char feature_vector_checkpoint[512];
sprintf(feature_vector_checkpoint, "%s/positive_vectors", dir);
char neg_vector_checkpoint[512];
sprintf(neg_vector_checkpoint, "%s/negative_vectors", dir);
ccv_dpm_feature_vector_t** posv = (ccv_dpm_feature_vector_t**)ccmalloc(posnum * sizeof(ccv_dpm_feature_vector_t*));
int* order = (int*)ccmalloc(sizeof(int) * (posnum + params.negative_cache_size + 64 /* the magical number for maximum negative examples collected per image */));
double previous_positive_loss = 0, previous_negative_loss = 0, positive_loss = 0, negative_loss = 0, loss = 0;
// need to re-weight for each examples
c = d = t = 0;
ccv_array_t* negv = 0;
if (0 == _ccv_dpm_read_negative_feature_vectors(&negv, params.negative_cache_size, neg_vector_checkpoint))
printf(" - read collected negative responses from last interrupted process\n");
_ccv_dpm_read_gradient_descent_progress(&c, &d, gradient_progress_checkpoint);
for (; c < params.relabels; c++)
{
double regz_rate = params.C;
ccv_dpm_mixture_model_t* _model;
if (0 == _ccv_dpm_read_positive_feature_vectors(posv, posnum, feature_vector_checkpoint))
{
printf(" - read collected positive responses from last interrupted process\n");
} else {
FLUSH(" - collecting responses from positive examples : 0%%");
for (i = 0; i < posnum; i++)
{
FLUSH(" - collecting responses from positive examples : %d%%", i * 100 / posnum);
ccv_dense_matrix_t* image = 0;
ccv_read(posfiles[i], &image, (params.grayscale ? CCV_IO_GRAY : 0) | CCV_IO_ANY_FILE);
posv[i] = _ccv_dpm_collect_best(image, model, bboxes[i], params.include_overlap, params.detector);
ccv_matrix_free(image);
}
FLUSH(" - collecting responses from positive examples : 100%%\n");
_ccv_dpm_write_positive_feature_vectors(posv, posnum, feature_vector_checkpoint);
}
int* posvnum = (int*)alloca(sizeof(int) * model->count);
memset(posvnum, 0, sizeof(int) * model->count);
for (i = 0; i < posnum; i++)
if (posv[i])
{
assert(posv[i]->id >= 0 && posv[i]->id < model->count);
++posvnum[posv[i]->id];
}
printf(" - positive examples divided by components : %d", posvnum[0]);
for (i = 1; i < model->count; i++)
printf(", %d", posvnum[i]);
printf("\n");
params.detector.threshold = 0;
for (; d < params.data_minings; d++)
{
// the cache is used up now, collect again
_ccv_dpm_write_gradient_descent_progress(c, d, gradient_progress_checkpoint);
double alpha = params.alpha;
if (negv)
{
ccv_array_t* av = ccv_array_new(sizeof(ccv_dpm_feature_vector_t*), 64, 0);
for (j = 0; j < negv->rnum; j++)
{
ccv_dpm_feature_vector_t* v = *(ccv_dpm_feature_vector_t**)ccv_array_get(negv, j);
double score = _ccv_dpm_vector_score(model, v);
assert(!isnan(score));
if (score >= -1)
ccv_array_push(av, &v);
else
_ccv_dpm_feature_vector_free(v);
}
ccv_array_free(negv);
negv = av;
} else {
negv = ccv_array_new(sizeof(ccv_dpm_feature_vector_t*), 64, 0);
}
FLUSH(" - collecting negative examples -- (0%%)");
if (negv->rnum < params.negative_cache_size)
_ccv_dpm_collect_from_background(negv, rng, bgfiles, bgnum, model, params, 0);
_ccv_dpm_write_negative_feature_vectors(negv, params.negative_cache_size, neg_vector_checkpoint);
FLUSH(" - collecting negative examples -- (100%%)\n");
int* negvnum = (int*)alloca(sizeof(int) * model->count);
memset(negvnum, 0, sizeof(int) * model->count);
for (i = 0; i < negv->rnum; i++)
{
ccv_dpm_feature_vector_t* v = *(ccv_dpm_feature_vector_t**)ccv_array_get(negv, i);
assert(v->id >= 0 && v->id < model->count);
++negvnum[v->id];
}
if (negv->rnum <= ccv_max(params.negative_cache_size / 2, ccv_max(REGQ, MINI_BATCH)))
{
for (i = 0; i < model->count; i++)
// we cannot get sufficient negatives, adjust constant and abort for next round
_ccv_dpm_adjust_model_constant(model, i, posv, posnum, params.percentile_breakdown);
continue;
}
printf(" - negative examples divided by components : %d", negvnum[0]);
for (i = 1; i < model->count; i++)
printf(", %d", negvnum[i]);
printf("\n");
previous_positive_loss = previous_negative_loss = 0;
uint64_t elapsed_time = _ccv_dpm_time_measure();
assert(negv->rnum < params.negative_cache_size + 64);
for (t = 0; t < params.iterations; t++)
{
for (p = 0; p < model->count; p++)
{
// if don't have enough negnum or posnum, aborting
if (negvnum[p] <= ccv_max(params.negative_cache_size / (model->count * 3), ccv_max(REGQ, MINI_BATCH)) ||
posvnum[p] <= ccv_max(REGQ, MINI_BATCH))
continue;
double pos_weight = sqrt((double)negvnum[p] / posvnum[p] * params.balance); // positive weight
double neg_weight = sqrt((double)posvnum[p] / negvnum[p] / params.balance); // negative weight
_model = _ccv_dpm_model_copy(model);
for (i = 0; i < posnum + negv->rnum; i++)
order[i] = i;
gsl_ran_shuffle(rng, order, posnum + negv->rnum, sizeof(int));
int l = 0;
for (i = 0; i < posnum + negv->rnum; i++)
{
k = order[i];
if (k < posnum)
{
if (posv[k] == 0 || posv[k]->id != p)
continue;
double score = _ccv_dpm_vector_score(model, posv[k]); // the loss for mini-batch method (computed on model)
assert(!isnan(score));
if (score <= 1)
_ccv_dpm_stochastic_gradient_descent(_model, posv[k], 1, alpha * pos_weight, regz_rate, params.symmetric);
} else {
ccv_dpm_feature_vector_t* v = *(ccv_dpm_feature_vector_t**)ccv_array_get(negv, k - posnum);
if (v->id != p)
continue;
double score = _ccv_dpm_vector_score(model, v);
assert(!isnan(score));
if (score >= -1)
_ccv_dpm_stochastic_gradient_descent(_model, v, -1, alpha * neg_weight, regz_rate, params.symmetric);
}
++l;
if (l % REGQ == REGQ - 1)
_ccv_dpm_regularize_mixture_model(_model, p, 1.0 - pow(1.0 - alpha / (double)((posvnum[p] + negvnum[p]) * (!!params.symmetric + 1)), REGQ));
if (l % MINI_BATCH == MINI_BATCH - 1)
{
// mimicking mini-batch way of doing things
_ccv_dpm_mixture_model_cleanup(model);
ccfree(model);
model = _model;
_model = _ccv_dpm_model_copy(model);
}
}
_ccv_dpm_regularize_mixture_model(_model, p, 1.0 - pow(1.0 - alpha / (double)((posvnum[p] + negvnum[p]) * (!!params.symmetric + 1)), (((posvnum[p] + negvnum[p]) % REGQ) + 1) % (REGQ + 1)));
_ccv_dpm_mixture_model_cleanup(model);
ccfree(model);
model = _model;
}
// compute the loss
int posvn = 0;
positive_loss = negative_loss = loss = 0;
for (i = 0; i < posnum; i++)
if (posv[i] != 0)
{
double score = _ccv_dpm_vector_score(model, posv[i]);
assert(!isnan(score));
double hinge_loss = ccv_max(0, 1.0 - score);
positive_loss += hinge_loss;
double pos_weight = sqrt((double)negvnum[posv[i]->id] / posvnum[posv[i]->id] * params.balance); // positive weight
loss += pos_weight * hinge_loss;
++posvn;
}
for (i = 0; i < negv->rnum; i++)
{
ccv_dpm_feature_vector_t* v = *(ccv_dpm_feature_vector_t**)ccv_array_get(negv, i);
double score = _ccv_dpm_vector_score(model, v);
assert(!isnan(score));
double hinge_loss = ccv_max(0, 1.0 + score);
negative_loss += hinge_loss;
double neg_weight = sqrt((double)posvnum[v->id] / negvnum[v->id] / params.balance); // negative weight
loss += neg_weight * hinge_loss;
}
loss = loss / (posvn + negv->rnum);
positive_loss = positive_loss / posvn;
negative_loss = negative_loss / negv->rnum;
FLUSH(" - with loss %.5lf (positive %.5lf, negative %.5f) at rate %.5lf %d | %d -- %d%%", loss, positive_loss, negative_loss, alpha, posvn, negv->rnum, (t + 1) * 100 / params.iterations);
// check symmetric property of generated root feature
if (params.symmetric)
for (i = 0; i < params.components; i++)
{
ccv_dpm_root_classifier_t* root_classifier = model->root + i;
_ccv_dpm_check_root_classifier_symmetry(root_classifier->root.w);
}
if (fabs(previous_positive_loss - positive_loss) < 1e-5 &&
fabs(previous_negative_loss - negative_loss) < 1e-5)
{
printf("\n - aborting iteration at %d because we didn't gain much", t + 1);
break;
}
previous_positive_loss = positive_loss;
previous_negative_loss = negative_loss;
alpha *= params.alpha_ratio; // it will decrease with each iteration
}
_ccv_dpm_write_checkpoint(model, 0, checkpoint);
printf("\n - data mining %d takes %.2lf seconds at loss %.5lf, %d more to go (%d of %d)\n", d + 1, (double)(_ccv_dpm_time_measure() - elapsed_time) / 1000000.0, loss, params.data_minings - d - 1, c + 1, params.relabels);
j = 0;
double* scores = (double*)ccmalloc(posnum * sizeof(double));
for (i = 0; i < posnum; i++)
if (posv[i])
{
scores[j] = _ccv_dpm_vector_score(model, posv[i]);
assert(!isnan(scores[j]));
j++;
}
_ccv_dpm_score_qsort(scores, j, 0);
ccfree(scores);
double breakdown;
printf(" - threshold breakdown by percentile");
for (breakdown = params.percentile_breakdown; breakdown < 1.0; breakdown += params.percentile_breakdown)
printf(" %0.2lf(%.1f%%)", scores[ccv_clamp((int)(breakdown * j), 0, j - 1)], (1.0 - breakdown) * 100);
printf("\n");
char persist[512];
sprintf(persist, "%s/model.%d.%d", dir, c, d);
_ccv_dpm_write_checkpoint(model, 0, persist);
}
d = 0;
// if abort, means that we cannot find enough negative examples, try to adjust constant
for (i = 0; i < posnum; i++)
if (posv[i])
_ccv_dpm_feature_vector_free(posv[i]);
remove(feature_vector_checkpoint);
}
if (negv)
{
for (i = 0; i < negv->rnum; i++)
{
ccv_dpm_feature_vector_t* v = *(ccv_dpm_feature_vector_t**)ccv_array_get(negv, i);
_ccv_dpm_feature_vector_free(v);
}
ccv_array_free(negv);
}
remove(neg_vector_checkpoint);
ccfree(order);
ccfree(posv);
printf("root rectangle prediction with linear regression\n");
_ccv_dpm_initialize_root_rectangle_estimator(model, posfiles, bboxes, posnum, params);
_ccv_dpm_write_checkpoint(model, 1, checkpoint);
printf("done\n");
remove(gradient_progress_checkpoint);
_ccv_dpm_mixture_model_cleanup(model);
ccfree(model);
gsl_rng_free(rng);
}
#else
void ccv_dpm_mixture_model_new(char** posfiles, ccv_rect_t* bboxes, int posnum, char** bgfiles, int bgnum, int negnum, const char* dir, ccv_dpm_new_param_t params)
{
fprintf(stderr, " ccv_dpm_classifier_cascade_new requires libgsl and liblinear support, please compile ccv with them.\n");
}
#endif
#else
void ccv_dpm_mixture_model_new(char** posfiles, ccv_rect_t* bboxes, int posnum, char** bgfiles, int bgnum, int negnum, const char* dir, ccv_dpm_new_param_t params)
{
fprintf(stderr, " ccv_dpm_classifier_cascade_new requires libgsl and liblinear support, please compile ccv with them.\n");
}
#endif
static int _ccv_is_equal(const void* _r1, const void* _r2, void* data)
{
const ccv_root_comp_t* r1 = (const ccv_root_comp_t*)_r1;
const ccv_root_comp_t* r2 = (const ccv_root_comp_t*)_r2;
int distance = (int)(ccv_min(r1->rect.width, r1->rect.height) * 0.25 + 0.5);
return r2->rect.x <= r1->rect.x + distance &&
r2->rect.x >= r1->rect.x - distance &&
r2->rect.y <= r1->rect.y + distance &&
r2->rect.y >= r1->rect.y - distance &&
r2->rect.width <= (int)(r1->rect.width * 1.5 + 0.5) &&
(int)(r2->rect.width * 1.5 + 0.5) >= r1->rect.width &&
r2->rect.height <= (int)(r1->rect.height * 1.5 + 0.5) &&
(int)(r2->rect.height * 1.5 + 0.5) >= r1->rect.height;
}
static int _ccv_is_equal_same_class(const void* _r1, const void* _r2, void* data)
{
const ccv_root_comp_t* r1 = (const ccv_root_comp_t*)_r1;
const ccv_root_comp_t* r2 = (const ccv_root_comp_t*)_r2;
int distance = (int)(ccv_min(r1->rect.width, r1->rect.height) * 0.25 + 0.5);
return r2->classification.id == r1->classification.id &&
r2->rect.x <= r1->rect.x + distance &&
r2->rect.x >= r1->rect.x - distance &&
r2->rect.y <= r1->rect.y + distance &&
r2->rect.y >= r1->rect.y - distance &&
r2->rect.width <= (int)(r1->rect.width * 1.5 + 0.5) &&
(int)(r2->rect.width * 1.5 + 0.5) >= r1->rect.width &&
r2->rect.height <= (int)(r1->rect.height * 1.5 + 0.5) &&
(int)(r2->rect.height * 1.5 + 0.5) >= r1->rect.height;
}
ccv_array_t* ccv_dpm_detect_objects(ccv_dense_matrix_t* a, ccv_dpm_mixture_model_t** _model, int count, ccv_dpm_param_t params)
{
int c, i, j, k, x, y;
double scale = pow(2.0, 1.0 / (params.interval + 1.0));
int next = params.interval + 1;
int scale_upto = _ccv_dpm_scale_upto(a, _model, count, params.interval);
if (scale_upto < 0) // image is too small to be interesting
return 0;
ccv_dense_matrix_t** pyr = (ccv_dense_matrix_t**)alloca((scale_upto + next * 2) * sizeof(ccv_dense_matrix_t*));
_ccv_dpm_feature_pyramid(a, pyr, scale_upto, params.interval);
ccv_array_t* idx_seq;
ccv_array_t* seq = ccv_array_new(sizeof(ccv_root_comp_t), 64, 0);
ccv_array_t* seq2 = ccv_array_new(sizeof(ccv_root_comp_t), 64, 0);
ccv_array_t* result_seq = ccv_array_new(sizeof(ccv_root_comp_t), 64, 0);
for (c = 0; c < count; c++)
{
ccv_dpm_mixture_model_t* model = _model[c];
double scale_x = 1.0;
double scale_y = 1.0;
for (i = next; i < scale_upto + next * 2; i++)
{
for (j = 0; j < model->count; j++)
{
ccv_dpm_root_classifier_t* root = model->root + j;
ccv_dense_matrix_t* root_feature = 0;
ccv_dense_matrix_t* part_feature[CCV_DPM_PART_MAX];
ccv_dense_matrix_t* dx[CCV_DPM_PART_MAX];
ccv_dense_matrix_t* dy[CCV_DPM_PART_MAX];
_ccv_dpm_compute_score(root, pyr[i], pyr[i - next], &root_feature, part_feature, dx, dy);
int rwh = (root->root.w->rows - 1) / 2, rww = (root->root.w->cols - 1) / 2;
int rwh_1 = root->root.w->rows / 2, rww_1 = root->root.w->cols / 2;
/* these values are designed to make sure works with odd/even number of rows/cols
* of the root classifier:
* suppose the image is 6x6, and the root classifier is 6x6, the scan area should starts
* at (2,2) and end at (2,2), thus, it is capped by (rwh, rww) to (6 - rwh_1 - 1, 6 - rww_1 - 1)
* this computation works for odd root classifier too (i.e. 5x5) */
float* f_ptr = (float*)ccv_get_dense_matrix_cell_by(CCV_32F | CCV_C1, root_feature, rwh, 0, 0);
for (y = rwh; y < root_feature->rows - rwh_1; y++)
{
for (x = rww; x < root_feature->cols - rww_1; x++)
if (f_ptr[x] + root->beta > params.threshold)
{
ccv_root_comp_t comp;
comp.neighbors = 1;
comp.classification.id = c + 1;
comp.classification.confidence = f_ptr[x] + root->beta;
comp.pnum = root->count;
float drift_x = root->alpha[0],
drift_y = root->alpha[1],
drift_scale = root->alpha[2];
for (k = 0; k < root->count; k++)
{
ccv_dpm_part_classifier_t* part = root->part + k;
comp.part[k].neighbors = 1;
comp.part[k].classification.id = c;
int pww = (part->w->cols - 1) / 2, pwh = (part->w->rows - 1) / 2;
int offy = part->y + pwh - rwh * 2;
int offx = part->x + pww - rww * 2;
int iy = ccv_clamp(y * 2 + offy, pwh, part_feature[k]->rows - part->w->rows + pwh);
int ix = ccv_clamp(x * 2 + offx, pww, part_feature[k]->cols - part->w->cols + pww);
int ry = ccv_get_dense_matrix_cell_value_by(CCV_32S | CCV_C1, dy[k], iy, ix, 0);
int rx = ccv_get_dense_matrix_cell_value_by(CCV_32S | CCV_C1, dx[k], iy, ix, 0);
drift_x += part->alpha[0] * rx + part->alpha[1] * ry;
drift_y += part->alpha[2] * rx + part->alpha[3] * ry;
drift_scale += part->alpha[4] * rx + part->alpha[5] * ry;
ry = iy - ry;
rx = ix - rx;
comp.part[k].rect = ccv_rect((int)((rx - pww) * CCV_DPM_WINDOW_SIZE / 2 * scale_x + 0.5), (int)((ry - pwh) * CCV_DPM_WINDOW_SIZE / 2 * scale_y + 0.5), (int)(part->w->cols * CCV_DPM_WINDOW_SIZE / 2 * scale_x + 0.5), (int)(part->w->rows * CCV_DPM_WINDOW_SIZE / 2 * scale_y + 0.5));
comp.part[k].classification.confidence = -ccv_get_dense_matrix_cell_value_by(CCV_32F | CCV_C1, part_feature[k], iy, ix, 0);
}
comp.rect = ccv_rect((int)((x + drift_x) * CCV_DPM_WINDOW_SIZE * scale_x - rww * CCV_DPM_WINDOW_SIZE * scale_x * (1.0 + drift_scale) + 0.5), (int)((y + drift_y) * CCV_DPM_WINDOW_SIZE * scale_y - rwh * CCV_DPM_WINDOW_SIZE * scale_y * (1.0 + drift_scale) + 0.5), (int)(root->root.w->cols * CCV_DPM_WINDOW_SIZE * scale_x * (1.0 + drift_scale) + 0.5), (int)(root->root.w->rows * CCV_DPM_WINDOW_SIZE * scale_y * (1.0 + drift_scale) + 0.5));
ccv_array_push(seq, &comp);
}
f_ptr += root_feature->cols;
}
for (k = 0; k < root->count; k++)
{
ccv_matrix_free(part_feature[k]);
ccv_matrix_free(dx[k]);
ccv_matrix_free(dy[k]);
}
ccv_matrix_free(root_feature);
}
scale_x *= scale;
scale_y *= scale;
}
/* the following code from OpenCV's haar feature implementation */
if (params.min_neighbors == 0)
{
for (i = 0; i < seq->rnum; i++)
{
ccv_root_comp_t* comp = (ccv_root_comp_t*)ccv_array_get(seq, i);
ccv_array_push(result_seq, comp);
}
} else {
idx_seq = 0;
ccv_array_clear(seq2);
// group retrieved rectangles in order to filter out noise
int ncomp = ccv_array_group(seq, &idx_seq, _ccv_is_equal_same_class, 0);
ccv_root_comp_t* comps = (ccv_root_comp_t*)ccmalloc((ncomp + 1) * sizeof(ccv_root_comp_t));
memset(comps, 0, (ncomp + 1) * sizeof(ccv_root_comp_t));
// count number of neighbors
for (i = 0; i < seq->rnum; i++)
{
ccv_root_comp_t r1 = *(ccv_root_comp_t*)ccv_array_get(seq, i);
int idx = *(int*)ccv_array_get(idx_seq, i);
comps[idx].classification.id = r1.classification.id;
comps[idx].pnum = r1.pnum;
if (r1.classification.confidence > comps[idx].classification.confidence || comps[idx].neighbors == 0)
{
comps[idx].rect = r1.rect;
comps[idx].classification.confidence = r1.classification.confidence;
memcpy(comps[idx].part, r1.part, sizeof(ccv_comp_t) * CCV_DPM_PART_MAX);
}
++comps[idx].neighbors;
}
// calculate average bounding box
for (i = 0; i < ncomp; i++)
{
int n = comps[i].neighbors;
if (n >= params.min_neighbors)
ccv_array_push(seq2, comps + i);
}
// filter out large object rectangles contains small object rectangles
for (i = 0; i < seq2->rnum; i++)
{
ccv_root_comp_t* r2 = (ccv_root_comp_t*)ccv_array_get(seq2, i);
int distance = (int)(ccv_min(r2->rect.width, r2->rect.height) * 0.25 + 0.5);
for (j = 0; j < seq2->rnum; j++)
{
ccv_root_comp_t r1 = *(ccv_root_comp_t*)ccv_array_get(seq2, j);
if (i != j &&
abs(r1.classification.id) == r2->classification.id &&
r1.rect.x >= r2->rect.x - distance &&
r1.rect.y >= r2->rect.y - distance &&
r1.rect.x + r1.rect.width <= r2->rect.x + r2->rect.width + distance &&
r1.rect.y + r1.rect.height <= r2->rect.y + r2->rect.height + distance &&
// if r1 (the smaller one) is better, mute r2
(r2->classification.confidence <= r1.classification.confidence && r2->neighbors < r1.neighbors))
{
r2->classification.id = -r2->classification.id;
break;
}
}
}
// filter out small object rectangles inside large object rectangles
for (i = 0; i < seq2->rnum; i++)
{
ccv_root_comp_t r1 = *(ccv_root_comp_t*)ccv_array_get(seq2, i);
if (r1.classification.id > 0)
{
int flag = 1;
for (j = 0; j < seq2->rnum; j++)
{
ccv_root_comp_t r2 = *(ccv_root_comp_t*)ccv_array_get(seq2, j);
int distance = (int)(ccv_min(r2.rect.width, r2.rect.height) * 0.25 + 0.5);
if (i != j &&
r1.classification.id == abs(r2.classification.id) &&
r1.rect.x >= r2.rect.x - distance &&
r1.rect.y >= r2.rect.y - distance &&
r1.rect.x + r1.rect.width <= r2.rect.x + r2.rect.width + distance &&
r1.rect.y + r1.rect.height <= r2.rect.y + r2.rect.height + distance &&
(r2.classification.confidence > r1.classification.confidence || r2.neighbors >= r1.neighbors))
{
flag = 0;
break;
}
}
if (flag)
ccv_array_push(result_seq, &r1);
}
}
ccv_array_free(idx_seq);
ccfree(comps);
}
}
for (i = 0; i < scale_upto + next * 2; i++)
ccv_matrix_free(pyr[i]);
ccv_array_free(seq);
ccv_array_free(seq2);
ccv_array_t* result_seq2;
/* the following code from OpenCV's haar feature implementation */
if (params.flags & CCV_DPM_NO_NESTED)
{
result_seq2 = ccv_array_new(sizeof(ccv_root_comp_t), 64, 0);
idx_seq = 0;
// group retrieved rectangles in order to filter out noise
int ncomp = ccv_array_group(result_seq, &idx_seq, _ccv_is_equal, 0);
ccv_root_comp_t* comps = (ccv_root_comp_t*)ccmalloc((ncomp + 1) * sizeof(ccv_root_comp_t));
memset(comps, 0, (ncomp + 1) * sizeof(ccv_root_comp_t));
// count number of neighbors
for(i = 0; i < result_seq->rnum; i++)
{
ccv_root_comp_t r1 = *(ccv_root_comp_t*)ccv_array_get(result_seq, i);
int idx = *(int*)ccv_array_get(idx_seq, i);
if (comps[idx].neighbors == 0 || comps[idx].classification.confidence < r1.classification.confidence)
{
comps[idx].classification.confidence = r1.classification.confidence;
comps[idx].neighbors = 1;
comps[idx].rect = r1.rect;
comps[idx].classification.id = r1.classification.id;
comps[idx].pnum = r1.pnum;
memcpy(comps[idx].part, r1.part, sizeof(ccv_comp_t) * CCV_DPM_PART_MAX);
}
}
// calculate average bounding box
for(i = 0; i < ncomp; i++)
if(comps[i].neighbors)
ccv_array_push(result_seq2, &comps[i]);
ccv_array_free(result_seq);
ccfree(comps);
} else {
result_seq2 = result_seq;
}
return result_seq2;
}
ccv_dpm_mixture_model_t* ccv_dpm_read_mixture_model(const char* directory)
{
FILE* r = fopen(directory, "r");
if (r == 0)
return 0;
int count;
char flag;
fscanf(r, "%c", &flag);
assert(flag == '.');
fscanf(r, "%d", &count);
ccv_dpm_root_classifier_t* root_classifier = (ccv_dpm_root_classifier_t*)ccmalloc(sizeof(ccv_dpm_root_classifier_t) * count);
memset(root_classifier, 0, sizeof(ccv_dpm_root_classifier_t) * count);
int i, j, k;
size_t size = sizeof(ccv_dpm_mixture_model_t) + sizeof(ccv_dpm_root_classifier_t) * count;
/* the format is easy, but I tried to copy all data into one memory region */
for (i = 0; i < count; i++)
{
int rows, cols;
fscanf(r, "%d %d", &rows, &cols);
fscanf(r, "%f %f %f %f", &root_classifier[i].beta, &root_classifier[i].alpha[0], &root_classifier[i].alpha[1], &root_classifier[i].alpha[2]);
root_classifier[i].root.w = ccv_dense_matrix_new(rows, cols, CCV_32F | 31, ccmalloc(ccv_compute_dense_matrix_size(rows, cols, CCV_32F | 31)), 0);
size += ccv_compute_dense_matrix_size(rows, cols, CCV_32F | 31);
for (j = 0; j < rows * cols * 31; j++)
fscanf(r, "%f", &root_classifier[i].root.w->data.f32[j]);
ccv_make_matrix_immutable(root_classifier[i].root.w);
fscanf(r, "%d", &root_classifier[i].count);
ccv_dpm_part_classifier_t* part_classifier = (ccv_dpm_part_classifier_t*)ccmalloc(sizeof(ccv_dpm_part_classifier_t) * root_classifier[i].count);
size += sizeof(ccv_dpm_part_classifier_t) * root_classifier[i].count;
for (j = 0; j < root_classifier[i].count; j++)
{
fscanf(r, "%d %d %d", &part_classifier[j].x, &part_classifier[j].y, &part_classifier[j].z);
fscanf(r, "%lf %lf %lf %lf", &part_classifier[j].dx, &part_classifier[j].dy, &part_classifier[j].dxx, &part_classifier[j].dyy);
fscanf(r, "%f %f %f %f %f %f", &part_classifier[j].alpha[0], &part_classifier[j].alpha[1], &part_classifier[j].alpha[2], &part_classifier[j].alpha[3], &part_classifier[j].alpha[4], &part_classifier[j].alpha[5]);
fscanf(r, "%d %d %d", &rows, &cols, &part_classifier[j].counterpart);
part_classifier[j].w = ccv_dense_matrix_new(rows, cols, CCV_32F | 31, ccmalloc(ccv_compute_dense_matrix_size(rows, cols, CCV_32F | 31)), 0);
size += ccv_compute_dense_matrix_size(rows, cols, CCV_32F | 31);
for (k = 0; k < rows * cols * 31; k++)
fscanf(r, "%f", &part_classifier[j].w->data.f32[k]);
ccv_make_matrix_immutable(part_classifier[j].w);
}
root_classifier[i].part = part_classifier;
}
fclose(r);
unsigned char* m = (unsigned char*)ccmalloc(size);
ccv_dpm_mixture_model_t* model = (ccv_dpm_mixture_model_t*)m;
m += sizeof(ccv_dpm_mixture_model_t);
model->count = count;
model->root = (ccv_dpm_root_classifier_t*)m;
m += sizeof(ccv_dpm_root_classifier_t) * model->count;
memcpy(model->root, root_classifier, sizeof(ccv_dpm_root_classifier_t) * model->count);
ccfree(root_classifier);
for (i = 0; i < model->count; i++)
{
ccv_dpm_part_classifier_t* part_classifier = model->root[i].part;
model->root[i].part = (ccv_dpm_part_classifier_t*)m;
m += sizeof(ccv_dpm_part_classifier_t) * model->root[i].count;
memcpy(model->root[i].part, part_classifier, sizeof(ccv_dpm_part_classifier_t) * model->root[i].count);
ccfree(part_classifier);
}
for (i = 0; i < model->count; i++)
{
ccv_dense_matrix_t* w = model->root[i].root.w;
model->root[i].root.w = (ccv_dense_matrix_t*)m;
m += ccv_compute_dense_matrix_size(w->rows, w->cols, w->type);
memcpy(model->root[i].root.w, w, ccv_compute_dense_matrix_size(w->rows, w->cols, w->type));
model->root[i].root.w->data.u8 = (unsigned char*)(model->root[i].root.w + 1);
ccfree(w);
for (j = 0; j < model->root[i].count; j++)
{
w = model->root[i].part[j].w;
model->root[i].part[j].w = (ccv_dense_matrix_t*)m;
m += ccv_compute_dense_matrix_size(w->rows, w->cols, w->type);
memcpy(model->root[i].part[j].w, w, ccv_compute_dense_matrix_size(w->rows, w->cols, w->type));
model->root[i].part[j].w->data.u8 = (unsigned char*)(model->root[i].part[j].w + 1);
ccfree(w);
}
}
return model;
}
void ccv_dpm_mixture_model_free(ccv_dpm_mixture_model_t* model)
{
ccfree(model);
}
| {
"alphanum_fraction": 0.6445675348,
"avg_line_length": 39.4993652137,
"ext": "c",
"hexsha": "33aac11bb7e2029ce73fb6ee038494b9512a3d86",
"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": "bedf2c1ab39f99664067f346986bf07f1c8bd188",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "r3gis3r/ccv",
"max_forks_repo_path": "lib/ccv_dpm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bedf2c1ab39f99664067f346986bf07f1c8bd188",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "r3gis3r/ccv",
"max_issues_repo_path": "lib/ccv_dpm.c",
"max_line_length": 442,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "bedf2c1ab39f99664067f346986bf07f1c8bd188",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "r3gis3r/ccv",
"max_stars_repo_path": "lib/ccv_dpm.c",
"max_stars_repo_stars_event_max_datetime": "2020-12-27T13:51:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-27T13:51:53.000Z",
"num_tokens": 31431,
"size": 93337
} |
/* poly.c - Polynomial (de)compression routines
*
* Copyright (c) 2015 Maurizio Tomasi
*
* 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 "libpolycomp.h"
#include <assert.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_block_double.h>
#include <gsl/gsl_vector_double.h>
#include <gsl/gsl_matrix_double.h>
#include <gsl/gsl_multifit.h>
#include <fftw3.h>
#ifdef WITH_OPENMP
#include <omp.h>
#else
static int omp_get_thread_num(void) { return 0; }
static int omp_get_max_threads(void) { return 1; }
#endif
/**********************************************************************/
/** \defgroup poly Polynomial compression functions
*
* Polynomial compression relies on a simple idea, that is to divide
* the input data stream into subsets of consecutive samples (called
* "chunks"), and to approximate each chunk by means of a polynomial.
* Such compression is inherently lossy, as the residuals of the
* fitting procedure are usually discarded. If the polynomial used for
* the fitting produces residuals that are too large, usually the
* samples in the chunk are saved in uncompressed form.
*
* This idea has been widely applied in the literature. Libpolycomp
* implements an improvement over it, because if the fit residuals are
* too large, the library saves a chopped sequence of the Chebyshev
* transform of the residuals. This allows to achieve better
* compression ratios in those cases where polynomial fitting is not
* always enough to keep compression errors below the desired
* threshold. This kind of compression works quite well for smooth
* data series, where changes between consecutive samples are well
* described by slowly varying continuous functions. It is not
* suitable if the signal contains noise, unless this noise is
* significantly smaller than the signal and than the error threshold.
*
* Libpolycomp allows to avoid the usage of Chebyshev transforms. In
* this case, if no polynomial of the desired degree are able to fit
* the data with the given error threshold, the data for that chunk is
* saved uncompressed.
*
* The typical workflow for applying polynomial compression is the
* following:
*
* 1. Allocate a new \ref pcomp_polycomp_t object via a call to \ref
* pcomp_init_polycomp. Such object contains the parameters to be
* used for the compression, e.g., the size of each chunk, the
* degree of the fitting polynomial, whether to apply or not the
* Chebyshev transform to the residuals, etc.
*
* 2. Split the data into chunks and compress each of them using the
* function \ref pcomp_compress_polycomp.
*
* 3. Convert the list of chunks into a byte sequence using \ref
* pcomp_encode_chunks, typically with the purpose of saving it
* into a file or sending it through a pipe/socket/etc.
*
* The decompression workflow is specular:
*
* 1. Process the byte sequence containing the compressed data using
* \ref pcomp_decode_chunks. This will produce a list of chunks
* that are still compressed.
*
* 2. Decompress the chunks using the function \ref
* pcomp_decompress_polycomp.
*
* The compression functions described in this page use the \ref
* pcomp_polycomp_t structure to determine which parameters to use for
* the compression. The functions that allow to allocate/free/manage
* this structure are the following:
*
* - \ref pcomp_init_polycomp and \ref pcomp_free_polycomp
* - \ref pcomp_polycomp_samples_per_chunk
* - \ref pcomp_polycomp_num_of_poly_coeffs
* - \ref pcomp_polycomp_max_error
* - \ref pcomp_polycomp_algorithm
* - \ref pcomp_polycomp_period and \ref pcomp_polycomp_set_period
*
* It is possible to use a set of more low-level functions to use
* polynomial compression. Refer to \ref poly_lowlevel for further
* information.
*/
/** \defgroup poly_lowlevel Polynomial compression (low-level functions)
*/
/**********************************************************************/
static double integer_power(int x, int y)
{
double dbl_x = (double)x;
if (y < 0)
abort();
if (y == 0)
return 1.0;
else if (y == 1)
return dbl_x;
else {
double result = dbl_x * dbl_x;
int cur_power = 2;
while (2 * cur_power < y) {
result *= result;
cur_power *= 2;
}
if (y > cur_power)
result *= integer_power(x, y - cur_power);
return result;
}
}
/***********************************************************************
* Types and functions used for polynomial least-square fitting
*/
struct __pcomp_poly_fit_data_t {
size_t num_of_samples;
size_t num_of_coeffs;
gsl_multifit_linear_workspace* workspace;
gsl_matrix* matrix;
gsl_vector* y;
gsl_vector* c;
gsl_matrix* cov_matrix;
};
/** \ingroup polyfit
*
* \brief Allocate a new instance of the \ref pcomp_poly_fit_data_t
* structure on the heap
*
* \param[in] num_of_samples Number of floating-point numbers that
* must fit the polynomial
*
* \param[in] num_of_coeffs Number of coefficients of the
* least-squares fitting polynomial \f$p(x)\f$. This is equal to
* \f$\deg p(x) + 1\f$, where \f$\deg p(x)\f$ is the degree of the
* polynomial. Thus, for a parabolic polynomial of the form \f$p(x) =
* a x^2 + b x + c\f$, \a num_of_coeffs = 3.
*
* \returns A newly created instance of \ref pcomp_poly_fit_data_t
* structure. This must be freed using \ref pcomp_free_poly_fit, once
* it is no longer used.
*/
pcomp_poly_fit_data_t* pcomp_init_poly_fit(size_t num_of_samples,
size_t num_of_coeffs)
{
size_t i, j;
pcomp_poly_fit_data_t* poly_fit
= malloc(sizeof(pcomp_poly_fit_data_t));
if (poly_fit == NULL)
abort();
poly_fit->num_of_samples = num_of_samples;
poly_fit->num_of_coeffs = num_of_coeffs;
poly_fit->workspace
= gsl_multifit_linear_alloc(num_of_samples, num_of_coeffs);
poly_fit->matrix = gsl_matrix_alloc(num_of_samples, num_of_coeffs);
poly_fit->y = gsl_vector_alloc(num_of_samples);
poly_fit->c = gsl_vector_alloc(num_of_coeffs);
poly_fit->cov_matrix
= gsl_matrix_alloc(num_of_coeffs, num_of_coeffs);
for (i = 0; i < num_of_samples; ++i) {
for (j = 0; j < num_of_coeffs; ++j) {
gsl_matrix_set(poly_fit->matrix, i, j,
integer_power(i + 1, j));
}
}
return poly_fit;
}
/** \ingroup polyfit
*
* \brief Free an instance of the \ref pcomp_poly_fit_data_t that has
* been allocated via a call to \ref pcomp_init_poly_fit.
*
* \param[in] poly_fit Pointer to the structure to be freed
*/
void pcomp_free_poly_fit(pcomp_poly_fit_data_t* poly_fit)
{
if (poly_fit == NULL)
return;
gsl_matrix_free(poly_fit->matrix);
gsl_vector_free(poly_fit->y);
gsl_vector_free(poly_fit->c);
gsl_matrix_free(poly_fit->cov_matrix);
gsl_multifit_linear_free(poly_fit->workspace);
free(poly_fit);
}
/** \ingroup polyfit
*
* \brief Return the number of samples to be used in a polynomial fit
*
* \param[in] poly_fit Pointer to the structure detailing the fit
*
* \returns The number of samples that should be passed to a call to
* \ref pcomp_run_poly_fit.
*/
size_t
pcomp_poly_fit_num_of_samples(const pcomp_poly_fit_data_t* poly_fit)
{
if (poly_fit == NULL)
abort();
return poly_fit->num_of_samples;
}
/** \ingroup polyfit
*
* \brief Return the number of coefficients of the least-squares
* fitting polynomial
*
* \param[in] poly_fit Pointer to the structure detailing the fit
*
* \returns The number of coefficients for the fitting polynomial (one
* plus the polynomial degree)
*/
size_t
pcomp_poly_fit_num_of_coeffs(const pcomp_poly_fit_data_t* poly_fit)
{
if (poly_fit == NULL)
abort();
return poly_fit->num_of_coeffs;
}
/** \ingroup polyfit
*
* \brief Calculates a polynomial least-squares fit.
*
* Compute a least-squares fit between the numbers \f$x_i\f$ (with
* \f$i = 1 \ldots N\f$) and the polynomial \f$p(x)\f$ through the
* points \f$(i, x_i)_{i=1}^N\f$. The coefficients of \f$p(x)\f$ are
* saved in \a coeffs, from the least to the greatest degree.
*
* Here is an example of the usage of this function:
*
* \code{.c}
* double points[] = { 1.0, 3.0, 5.0 };
* double coeffs[2];
* const size_t num_of_points = sizeof(points) / sizeof(points[0]);
* const size_t num_of_coeffs = sizeof(coeffs) / sizeof(coeffs[0]);
* pcomp_poly_fit_data_t* poly_fit;
*
* poly_fit = pcomp_init_poly_fit(num_of_points, num_of_coeffs);
* pcomp_run_poly_fit(poly_fit, coeffs, points);
* printf("The data are fitted by the polynomial y = %f + %f x\n",
* coeffs[0], coeffs[1]);
* \endcode
*
* \param[in] poly_fit Pointer to a \ref pcomp_poly_fit_data_t
* structure, created using the \ref pcomp_init_poly_fit function.
*
* \param[out] coeffs Pointer to an array where the coefficients of
* the polynomial will be stored on exit. The array must have room for
* a number of elements greater or equal than the value returned by
* \ref pcomp_poly_fit_num_of_coeffs.
*
* \param[in] points Array of numbers \f$x_i\f$ to use in the fit. The
* number of elements considered in the fit is equal to the return
* value of \ref pcomp_poly_fit_num_of_samples.
*
* \returns \ref PCOMP_STAT_SUCCESS if the fit was computed
* successfully, \ref PCOMP_STAT_INVALID_FIT if the data are incorrect
* (e.g., there are fewer samples than unknowns).
*/
int pcomp_run_poly_fit(pcomp_poly_fit_data_t* poly_fit, double* coeffs,
const double* points)
{
size_t idx;
double chisq;
if (poly_fit == NULL || coeffs == NULL || points == NULL)
abort();
for (idx = 0; idx < poly_fit->num_of_samples; ++idx) {
gsl_vector_set(poly_fit->y, idx, points[idx]);
}
if (gsl_multifit_linear(poly_fit->matrix, poly_fit->y, poly_fit->c,
poly_fit->cov_matrix, &chisq,
poly_fit->workspace) != 0) {
return PCOMP_STAT_INVALID_FIT;
}
for (idx = 0; idx < poly_fit->num_of_coeffs; ++idx) {
coeffs[idx] = gsl_vector_get(poly_fit->c, idx);
}
return PCOMP_STAT_SUCCESS;
}
/***********************************************************************
* Types and functions used for computing Chebyshev transforms
*/
struct __pcomp_chebyshev_t {
double* input;
double* output;
size_t num_of_samples;
fftw_plan fftw_plan_ptr;
pcomp_transform_direction_t dir;
};
/** \ingroup cheby
*
* \brief Allocate a new instance of the \ref pcomp_chebyshev_t
* structure on the heap
*
* Despite the fact that this function takes the parameter \a dir, the
* function which actually computes the Chebyshev transform (\ref
* pcomp_run_chebyshev) allow to specify the desired direction. The
* purpose of having \a dir encoded in \ref pcomp_chebyshev_t is that
* sometimes it is useful to keep it memorized in the structure
* itself.
*
* \param[in] num_of_samples Number of floating-point numbers that
* will be transformed
*
* \param[in] dir Direction of the transform (either forward or
* backward). This is used to determine the normalization constant of
* the transform:
* - If computing a forward transform, the normalization is \f$1 / (N
* - 1)\f$, with \f$N\f$ the number of samples.
* - If computing a backward transform, the normalization is 1.
*
* \returns A newly created instance of \ref pcomp_poly_fit_data_t
* structure. This must be freed using \ref pcomp_free_poly_fit, once
* it is no longer used.
*/
pcomp_chebyshev_t* pcomp_init_chebyshev(size_t num_of_samples,
pcomp_transform_direction_t dir)
{
pcomp_chebyshev_t* chebyshev = malloc(sizeof(pcomp_chebyshev_t));
if (chebyshev == NULL)
abort();
chebyshev->input = fftw_alloc_real(num_of_samples);
chebyshev->output = fftw_alloc_real(num_of_samples);
chebyshev->num_of_samples = num_of_samples;
chebyshev->fftw_plan_ptr = fftw_plan_r2r_1d(
num_of_samples, chebyshev->input, chebyshev->output,
FFTW_REDFT00, FFTW_ESTIMATE);
chebyshev->dir = dir;
return chebyshev;
}
/** \ingroup cheby
*
* \brief Free the memory allocated by a previous call to \ref
* pcomp_init_chebyshev.
*
* \param[in] plan Pointer to the structure to be freed.
*/
void pcomp_free_chebyshev(pcomp_chebyshev_t* plan)
{
if (plan == NULL)
return;
if (plan->input != NULL)
fftw_free(plan->input);
if (plan->output != NULL)
fftw_free(plan->output);
if (plan->fftw_plan_ptr != NULL)
fftw_destroy_plan(plan->fftw_plan_ptr);
free(plan);
}
/** \ingroup cheby
*
* \brief Return the number of samples in a Chebyshev transform
*
* \param[in] plan Pointer to the Chebyshev plan.
*
* \returns The number of elements that are used in the Chebyshev
* transform specified by \a plan.
*/
size_t pcomp_chebyshev_num_of_samples(const pcomp_chebyshev_t* plan)
{
if (plan == NULL)
abort();
return plan->num_of_samples;
}
/** \ingroup cheby
*
* \brief Return the direction of a Chebyshev transform
*
* \param[in] plan Pointer to the Chebyshev plan.
*
* \returns A \ref pcomp_transform_direction_t value specifying the
* normalization used for the Chebyshev transform specified by \a
* plan.
*/
pcomp_transform_direction_t
pcomp_chebyshev_direction(const pcomp_chebyshev_t* plan)
{
if (plan == NULL)
abort();
return plan->dir;
}
static double chebyshev_normalization(pcomp_transform_direction_t dir,
size_t num_of_samples)
{
if (dir == PCOMP_TD_DIRECT)
return 1.0 / (((double)num_of_samples) - 1.0);
else
return 0.5;
}
/** \ingroup cheby
*
* \brief Compute a forward/backward Chebyshev discrete transform
*
* \code{.c}
* #define NUM_OF_POINTS 3
* double points[NUM_OF_POINTS] = { 0.0, 1.0, 3.0 };
* double transform[NUM_OF_POINTS];
* pcomp_chebyshev_t* chebyshev;
* size_t idx;
*
* chebyshev = pcomp_init_chebyshev(NUM_OF_POINTS, PCOMP_TD_DIRECT);
* pcomp_run_chebyshev(chebyshev, PCOMP_TD_DIRECT, transform, points);
*
* puts("Transform:");
* for (idx = 0; idx < NUM_OF_POINTS; ++idx) {
* printf("%f\t", transform[idx]);
* }
* puts("");
* \endcode
*
* \param[in] plan Pointer to a Chebyshev plan created by \ref
* pcomp_init_chebyshev
*
* \param[in] dir Direction of the transform. This parameter overrides
* the internal direction of \a plan (returned by \ref
* pcomp_chebyshev_direction).
*
* \param[out] output Pointer to an array of \c double values that will
* contain the Chebyshev transform of \a input. It must have room for
* a number of elements at least equal to the return value of \ref
* pcomp_num_of_samples.
*
* \param[in] input Array of \c double values to be transformed. The
* function will use the first N elements, where N is the return value
* of \ref pcomp_num_of_samples.
*
* \returns \ref PCOMP_STAT_SUCCESS when successful.
*/
int pcomp_run_chebyshev(pcomp_chebyshev_t* plan,
pcomp_transform_direction_t dir, double* output,
const double* input)
{
double norm;
size_t idx;
if (plan == NULL)
abort();
if (input != NULL) {
for (idx = 0; idx < plan->num_of_samples; ++idx) {
plan->input[idx] = input[idx];
}
}
fftw_execute(plan->fftw_plan_ptr);
norm = chebyshev_normalization(dir, plan->num_of_samples);
for (idx = 0; idx < plan->num_of_samples; ++idx) {
plan->output[idx] *= norm;
}
if (output != NULL && output != plan->output) {
for (idx = 0; idx < plan->num_of_samples; ++idx) {
output[idx] = plan->output[idx];
}
}
return PCOMP_STAT_SUCCESS;
}
/** \ingroup cheby
*
* \brief Return the input data used in the last call to \ref
*pcomp_run_chebyshev
*
* If \ref pcomp_run_chebyshev was never called, the array returned by
* this function contains garbage.
*
* \param[in] plan Pointer to a Chebyshev plan created by \ref
* pcomp_init_chebyshev
*
* \return A pointer to the first element of the array of elements
* used as input by the last call to \ref pcomp_run_chebyshev.
*/
const double* pcomp_chebyshev_input(const pcomp_chebyshev_t* plan)
{
if (plan == NULL)
abort();
return plan->input;
}
/** \ingroup cheby
*
* \brief Return the output (Chebyshev transform) of the last call to
*\ref pcomp_run_chebyshev
*
* If \ref pcomp_run_chebyshev was never called, the array returned by
* this function contains garbage.
*
* \param[in] plan Pointer to a Chebyshev plan created by \ref
* pcomp_init_chebyshev
*
* \return A pointer to the first element of the array of elements
* containing the output of the last call to \ref pcomp_run_chebyshev.
*/
const double* pcomp_chebyshev_output(const pcomp_chebyshev_t* plan)
{
if (plan == NULL)
abort();
return plan->output;
}
/***********************************************************************
* Types and functions used for applying the combined
* fitting/Chebyshev transforms
*/
struct __pcomp_polycomp_t {
size_t samples_per_chunk;
pcomp_poly_fit_data_t* poly_fit;
pcomp_chebyshev_t* chebyshev;
pcomp_chebyshev_t* inv_chebyshev;
double max_allowable_error;
pcomp_polycomp_algorithm_t algorithm;
double period;
};
/** \ingroup poly
*
* \brief Allocate space for a \ref pcomp_polycomp_t structure
*
* \param[in] samples_per_chunk Number of samples in each chunk
*
* \param[in] num_of_coeffs Number of polynomial coefficients to use
*
* \param[in] max_allowable_error Upper bound for the compression
* error (positive value)
*
* \param[in] algorithm Kind of compression algorithm to use
*
* \returns A pointer to the newly allocate \ref pcomp_polycomp_t
* structure. This must be freed using \ref pcomp_free_polycomp, once
* it is no longer used.
*/
pcomp_polycomp_t*
pcomp_init_polycomp(pcomp_chunk_size_t samples_per_chunk,
pcomp_poly_size_t num_of_coeffs,
double max_allowable_error,
pcomp_polycomp_algorithm_t algorithm)
{
pcomp_polycomp_t* params = malloc(sizeof(pcomp_polycomp_t));
if (params == NULL)
abort();
params->samples_per_chunk = samples_per_chunk;
params->poly_fit
= pcomp_init_poly_fit(samples_per_chunk, num_of_coeffs);
params->chebyshev
= pcomp_init_chebyshev(samples_per_chunk, PCOMP_TD_DIRECT);
params->inv_chebyshev
= pcomp_init_chebyshev(samples_per_chunk, PCOMP_TD_INVERSE);
params->max_allowable_error = max_allowable_error;
params->algorithm = algorithm;
params->period = 0.0;
return params;
}
/** \ingroup poly
*
* \brief Free the memory allocated by \ref pcomp_init_polycomp for a
* \ref pcomp_polycomp_t structure.
*
* \param[in] params Pointer to the structure to be freed
*/
void pcomp_free_polycomp(pcomp_polycomp_t* params)
{
if (params == NULL)
return;
pcomp_free_poly_fit(params->poly_fit);
pcomp_free_chebyshev(params->chebyshev);
pcomp_free_chebyshev(params->inv_chebyshev);
free(params);
}
/** \ingroup poly
*
* \brief Return the number of samples per chunk
*
* This function returns the size of each chunk but the last one in
* the input data for a polynomial compression. Such chunks contain a
* set of consecutive values in the input array passed to routines as
* \ref pcomp_compress_polycomp.
*
* \param[in] params Pointer to a \ref pcomp_polycomp_t structure
* containing the compression parameters
*
* \returns The number of samples in each chunk.
*/
pcomp_chunk_size_t
pcomp_polycomp_samples_per_chunk(const pcomp_polycomp_t* params)
{
if (params == NULL)
abort();
return params->samples_per_chunk;
}
/** \ingroup poly
*
* \brief Return the number of coefficients for the fitting polynomial
* used in the polynomial compression.
*
* The return value has the same meaning as the value returned by the
* \ref pcomp_poly_fit_num_of_coeffs.
*
* \param[in] params Pointer to a \ref pcomp_polycomp_t structure
* containing the compression parameters
*
* \returns The number of coefficients of the fitting polynomial.
*/
pcomp_poly_size_t
pcomp_polycomp_num_of_poly_coeffs(const pcomp_polycomp_t* params)
{
if (params == NULL || params->poly_fit == NULL)
abort();
return params->poly_fit->num_of_coeffs;
}
/** \ingroup poly
*
* \brief Return the upper bound on the error of the polynomial
*compression.
*
* \param[in] params Pointer to a \ref pcomp_polycomp_t structure
* containing the compression parameters
*
* \returns The maximum allowable error for the polynomial compression.
*/
double pcomp_polycomp_max_error(const pcomp_polycomp_t* params)
{
if (params == NULL)
abort();
return params->max_allowable_error;
}
/** \ingroup poly
*
* \brief Return the kind of algorithm used for a polynomial
*compression.
*
* \param[in] params Pointer to a \ref pcomp_polycomp_t structure
* containing the compression parameters
*
* \returns The algorithm to be used by the compressor.
*/
pcomp_polycomp_algorithm_t
pcomp_polycomp_algorithm(const pcomp_polycomp_t* params)
{
if (params == NULL)
abort();
return params->algorithm;
}
/** \ingroup poly_lowlevel
*
* \brief Return a pointer to a \ref pcomp_chebyshev_t structure
* representing the forward Chebyshev transform.
*
* \param[in] params Pointer to a \ref pcomp_polycomp_t structure
* containing the compression parameters
*
* \returns The algorithm to be used by the compressor.
*/
pcomp_chebyshev_t*
pcomp_polycomp_forward_cheby(const pcomp_polycomp_t* params)
{
if (params == NULL)
abort();
return params->chebyshev;
}
/** \ingroup poly_lowlevel
*
* \brief Return a pointer to a \ref pcomp_chebyshev_t structure
* representing the forward Chebyshev transform.
*
* \param[in] params Pointer to a \ref pcomp_polycomp_t structure
* containing the compression parameters
*
* \returns The algorithm to be used by the compressor.
*/
pcomp_chebyshev_t*
pcomp_polycomp_backward_cheby(const pcomp_polycomp_t* params)
{
if (params == NULL)
abort();
return params->inv_chebyshev;
}
/** \ingroup poly
*
* \brief Return the period of the input data, or a number
* less than or equal to 0 if the data have no periodicity.
*
* See also \ref pcomp_polycomp_set_period.
*
* \param[in] params Pointer to a \ref pcomp_polycomp_t structure
* containing the compression parameters
*
* \returns The periodicity. If zero or negative, no periodicity is
* assumed in the data to be compressed.
*/
double pcomp_polycomp_period(const pcomp_polycomp_t* params)
{
if (params == NULL)
abort();
return params->period;
}
/** \ingroup poly
*
* \brief Set the periodicity of the data to be compressed
*
* If \a period is a value greater than zero, this is assumed to be
* the periodicity of the input data: the value \a x is therefore
* assumed equivalent to \a x + \a period and to \a x - \a period. It
* is typically a multiple of Pi = 3.14159...
*
* The polynomial compressor can improve the compression ratio for
* data if they have some form of periodicity.
*
* \param[in] params Pointer to a \ref pcomp_polycomp_t structure
* containing the compression parameters
*
* \param[in] period The periodicity of the data, or a zero/negative
* value if no periodicity should be assumed by the compressor.
*/
void pcomp_polycomp_set_period(pcomp_polycomp_t* params, double period)
{
if (params == NULL)
abort();
params->period = period;
}
/***********************************************************************
* Evaluate the value of a polynomial at a point using Horner's formula
*/
static double eval_poly(double* coeffs, size_t num_of_coeffs, double x)
{
if (coeffs == NULL)
abort();
if (num_of_coeffs >= 1) {
int idx = num_of_coeffs - 1;
double result = coeffs[idx];
if (num_of_coeffs == 1)
return result;
for (idx = num_of_coeffs - 2; idx >= 0; --idx)
result = result * x + coeffs[idx];
return result;
}
else
return 0.0;
}
/***********************************************************************/
/** \ingroup poly_lowlevel
*
* \brief Remove sudden jumps from \a input
*
* Assuming that the data in the array \a input have a periodicity
* equal to \a period, the function copies them to \a output while
* applying a positive/negative offset equal to a multiple of \a
* period.
*
* It is ok for \a input and \a output to point to the same memory
* location.
*
* \param[out] output Pointer to the array that will contain the
* result. It must have room for at least \a num_of_samples values.
*
* \param[in] input Array of \a num_of_samples values to process.
*
* \param[in] num_of_samples Number of samples to process in \a input
*
* \param[in] period Periodicity of the data. If less or equal to
* zero, \a input is copied verbatim to \a output.
*/
void pcomp_straighten(double* output, const double* input,
size_t num_of_samples, double period)
{
size_t idx;
if (input == NULL || output == NULL)
abort();
if (period > 0) {
double half_period = period * 0.5;
double offset = 0.0;
output[0] = input[0];
for (idx = 1; idx < num_of_samples; ++idx) {
double diff_with_previous = input[idx] - input[idx - 1];
if (diff_with_previous > half_period)
offset -= period;
else if (diff_with_previous < -half_period)
offset += period;
output[idx] = input[idx] + offset;
}
}
else {
for (idx = 0; idx < num_of_samples; ++idx)
output[idx] = input[idx];
}
}
/***********************************************************************
* Chunk initialization/destruction
*/
/* Information about a chunk of data compressed using the polynomial
* compression */
struct __pcomp_polycomp_chunk_t {
/* Number of samples in this chunk */
size_t num_of_samples;
/* Is this chunk compressed using polynomial/Chebyshev
* coefficients? */
int is_compressed;
/* If the chunk is not compressed (is_compressed == 0), this
* points to a buffer which holds "num_of_samples" uncompressed
* samples */
double* uncompressed;
/* Polynomial coefficients, from the lowest-order to the
* highest-order */
size_t num_of_poly_coeffs;
double* poly_coeffs;
/* Chebyshev coefficients */
uint8_t* cheby_mask;
size_t num_of_cheby_coeffs; /* This is always less than
* num_of_samples, as the Chebyshev
* series is chopped. */
double* cheby_coeffs;
};
/** \ingroup poly_lowlevel
*
* \brief Allocate memory for a \ref pcomp_polycomp_chunk_t object
*
* \param[in] num_of_samples Number of samples that the chunk will be
* capable to hold.
*
* \return A pointer to the newly allocated object. Use \ref
* pcomp_free_chunk to free the memory once is no longer needed.
*/
pcomp_polycomp_chunk_t*
pcomp_init_chunk(pcomp_chunk_size_t num_of_samples)
{
pcomp_polycomp_chunk_t* chunk
= malloc(sizeof(pcomp_polycomp_chunk_t));
if (chunk == NULL)
abort();
chunk->num_of_samples = num_of_samples;
chunk->is_compressed = 0;
chunk->uncompressed
= malloc(sizeof(double) * sizeof(chunk->num_of_samples));
chunk->num_of_poly_coeffs = 0;
chunk->poly_coeffs = NULL;
chunk->num_of_cheby_coeffs = 0;
chunk->cheby_coeffs = NULL;
chunk->cheby_mask = NULL;
return chunk;
}
/** \ingroup poly_lowlevel
*
* \brief Allocate memory for a \ref pcomp_polycomp_chunk_t object and
* fill it with data in uncompressed form.
*
* \param[in] num_of_samples Number of samples that the chunk will be
* capable to hold.
*
* \param[in] samples The (uncompressed) samples to copy into the
* chunk. After the call, \a input is no longer needed and can be
* freed without invalidating the pointer returned by the function.
*
* \return A pointer to the newly allocated object. Use \ref
* pcomp_free_chunk to free the memory once is no longer needed.
*/
pcomp_polycomp_chunk_t*
pcomp_init_uncompressed_chunk(pcomp_chunk_size_t num_of_samples,
const double* samples)
{
pcomp_polycomp_chunk_t* chunk
= malloc(sizeof(pcomp_polycomp_chunk_t));
const size_t num_of_bytes = sizeof(double) * num_of_samples;
if (chunk == NULL)
abort();
chunk->num_of_samples = num_of_samples;
chunk->is_compressed = 0;
chunk->uncompressed = malloc(num_of_bytes);
if (chunk->uncompressed == NULL)
abort();
memcpy(chunk->uncompressed, samples, num_of_bytes);
chunk->num_of_poly_coeffs = 0;
chunk->poly_coeffs = NULL;
chunk->num_of_cheby_coeffs = 0;
chunk->cheby_coeffs = NULL;
chunk->cheby_mask = NULL;
return chunk;
}
/** \ingroup poly_lowlevel
*
* \brief Allocate memory for a \ref pcomp_polycomp_chunk_t object and
* fill it with data compressed using the polynomial compression
* algorithm.
*
* \param[in] num_of_samples Number of samples that the chunk will be
* capable to hold.
*
* \param[in] num_of_poly_coeffs Number of coefficients of the
* interpolating polynomial.
*
* \param[in] poly_coeffs Pointer to the coefficients of the
* interpolating polynomial. Their number must be equal to the
* parameter \a num_of_poly_coeffs.
*
* \param[in] num_of_cheby_coeffs Number of nonzero Chebyshev
* coefficients associated with the polynomial fit. This number is
* always less than \a num_of_samples. Zero is allowed.
*
* \param[in] cheby_mask Bitmask representing the position of the
* nonzero coefficients in \a cheby_coeffs within the full sequence.
* (Use \ref pcomp_mask_get_bit and \ref pcomp_mask_set_bit to
* read/write bits in the sequence.)
*
* \param[in] cheby_coeffs Array of nonzero Chebyshev coefficients.
* Their number must be equal to \a num_of_cheby_coeffs.
*
* \return A pointer to the newly allocated object. Use \ref
* pcomp_free_chunk to free the memory once is no longer needed.
*/
pcomp_polycomp_chunk_t* pcomp_init_compressed_chunk(
pcomp_chunk_size_t num_of_samples,
pcomp_poly_size_t num_of_poly_coeffs, const double* poly_coeffs,
pcomp_chunk_size_t num_of_cheby_coeffs, const uint8_t* cheby_mask,
const double* cheby_coeffs)
{
size_t size;
pcomp_polycomp_chunk_t* chunk;
if (num_of_samples == 0 || poly_coeffs == NULL)
abort();
chunk = malloc(sizeof(pcomp_polycomp_chunk_t));
if (chunk == NULL)
abort();
chunk->num_of_samples = num_of_samples;
chunk->is_compressed = 1;
chunk->uncompressed = NULL;
chunk->num_of_poly_coeffs = num_of_poly_coeffs;
size = num_of_poly_coeffs * sizeof(double);
chunk->poly_coeffs = malloc(size);
if (chunk->poly_coeffs == NULL)
abort();
memcpy(chunk->poly_coeffs, poly_coeffs, size);
chunk->num_of_cheby_coeffs = num_of_cheby_coeffs;
if (num_of_cheby_coeffs > 0) {
size = num_of_cheby_coeffs * sizeof(double);
chunk->cheby_coeffs = malloc(size);
if (chunk->cheby_coeffs == NULL)
abort();
memcpy(chunk->cheby_coeffs, cheby_coeffs, size);
size = pcomp_chunk_cheby_mask_size(num_of_samples)
* sizeof(uint8_t);
chunk->cheby_mask = malloc(size);
if (chunk->cheby_mask == NULL)
abort();
memcpy(chunk->cheby_mask, cheby_mask, size);
}
else {
chunk->cheby_mask = NULL;
chunk->cheby_coeffs = NULL;
}
return chunk;
}
/** \ingroup poly_lowlevel
*
* \brief Free memory associated with a \ref pcomp_poly_chunk_t
*
* This function releases the memory allocated by one of the following
* functions:
* - \ref pcomp_init_chunk
* - \ref pcomp_init_uncompressed_chunk
* - \ref pcomp_init_compressed_chunk
*
* \param[in] chunk Pointer to the object to be freed.
*/
void pcomp_free_chunk(pcomp_polycomp_chunk_t* chunk)
{
if (chunk == NULL)
return;
if (chunk->uncompressed != NULL)
free(chunk->uncompressed);
if (chunk->poly_coeffs != NULL)
free(chunk->poly_coeffs);
if (chunk->cheby_coeffs != NULL)
free(chunk->cheby_coeffs);
if (chunk->cheby_mask != NULL)
free(chunk->cheby_mask);
free(chunk);
}
/** \ingroup poly_lowlevel
*
* \brief Return the number of samples in a chunk
*
* \param[in] chunk Pointer to the chunk data
*
* \returns The number of samples
*/
pcomp_chunk_size_t
pcomp_chunk_num_of_samples(const pcomp_polycomp_chunk_t* chunk)
{
if (chunk == NULL)
abort();
return chunk->num_of_samples;
}
/** \ingroup poly_lowlevel
*
* \brief Return the number of bytes necessary to encode a chunk
*
* Refer to \ref pcomp_encode_chunks and \ref pcomp_decode_chunks for
* further details.
*
* \param[in] chunk Pointer to the chunk data
*
* \returns The number of bytes
*/
size_t pcomp_chunk_num_of_bytes(const pcomp_polycomp_chunk_t* chunk)
{
if (chunk == NULL)
abort();
if (chunk->is_compressed) {
/* The size is calculated as follows:
* - the "compressed" flag (int8_t)
* - the number of samples (pcomp_chunk_size_t)
* - the number N of polynomial coefficients (pcomp_poly_size_t)
* - the size of the Chebyshev mask
* - the number M of Chebyshev coefficients (pcomp_chunk_size_t)
* - Nx8 bytes for the polynomial (only if M > 0)
* - Mx8 bytes for the Chebyshev coefficients (only if M > 0)
*/
size_t result = sizeof(int8_t) + sizeof(pcomp_chunk_size_t)
+ sizeof(pcomp_poly_size_t)
+ (chunk->num_of_poly_coeffs) * sizeof(double)
+ sizeof(pcomp_chunk_size_t);
if (chunk->num_of_cheby_coeffs > 0) {
result += pcomp_chunk_cheby_mask_size(chunk->num_of_samples)
+ chunk->num_of_cheby_coeffs * sizeof(double);
}
return result;
}
else {
/* The size is calculated as follows:
* - 1 byte for the "uncompressed" flag
* - 4 bytes for the number of samples
* - Nx8 bytes for the samples
*/
return sizeof(int8_t) + sizeof(pcomp_chunk_size_t)
+ chunk->num_of_samples * sizeof(double);
}
}
/** \ingroup poly_lowlevel
*
* \brief Return nonzero if the chunk holds data in uncompressed form.
*/
int pcomp_chunk_is_compressed(const pcomp_polycomp_chunk_t* chunk)
{
if (chunk == NULL)
abort();
return chunk->is_compressed;
}
/** \ingroup poly_lowlevel
*
* \brief If the chunks contain uncompressed data, returns a pointer
* to the first element. Otherwise, return \c NULL.
*/
const double*
pcomp_chunk_uncompressed_data(const pcomp_polycomp_chunk_t* chunk)
{
if (chunk == NULL)
abort();
if (chunk->is_compressed)
return NULL;
return chunk->uncompressed;
}
/** \ingroup poly_lowlevel
*
* \brief If the chunks contain compressed data, returns the number of
* polynomial coefficients used in the compression. Otherwise, return
* zero.
*/
pcomp_poly_size_t
pcomp_chunk_num_of_poly_coeffs(const pcomp_polycomp_chunk_t* chunk)
{
if (chunk == NULL)
abort();
if (!chunk->is_compressed)
return 0;
return chunk->num_of_poly_coeffs;
}
/** \ingroup poly_lowlevel
*
* \brief If the chunks contain compressed data, returns a pointer to
* the first element of the array of coefficients of the interpolating
* polynomial. Otherwise, return \c NULL.
*/
const double*
pcomp_chunk_poly_coeffs(const pcomp_polycomp_chunk_t* chunk)
{
if (chunk == NULL)
abort();
if (!chunk->is_compressed || chunk->num_of_poly_coeffs == 0)
return NULL;
return chunk->poly_coeffs;
}
/** \ingroup poly_lowlevel
*
* \brief If the chunks contain compressed data, returns the number of
* nonzero Chebyshev coefficients held in the chunk. Otherwise, return
* zero.
*/
pcomp_chunk_size_t
pcomp_chunk_num_of_cheby_coeffs(const pcomp_polycomp_chunk_t* chunk)
{
if (chunk == NULL)
abort();
if (!chunk->is_compressed)
return 0;
return chunk->num_of_cheby_coeffs;
}
/** \ingroup poly_lowlevel
*
* \brief If the chunks contain compressed data, returns a pointer to
* the first element of the Chebyshev transform of the fit residuals.
* Otherwise, return \c NULL.
*/
const double*
pcomp_chunk_cheby_coeffs(const pcomp_polycomp_chunk_t* chunk)
{
if (chunk == NULL)
abort();
if (!chunk->is_compressed || chunk->num_of_cheby_coeffs == 0)
return NULL;
return chunk->cheby_coeffs;
}
/** \ingroup poly_lowlevel
*
* \brief Return the number of bytes required for the bitmask of
* nonzero Chebyshev coefficients.
*
* The polynomial compression compresses Chebyshev transforms by
* saving only those coefficients that are significantly different
* from zero. In order to keep track of the position of such
* coefficients in the full array, a bit mask is used. This function
* determines how many bytes are required for such mask, which is
* internally represented by Libpolycomp as an array of \c uint8_t
* values.
*
* \param[in] chunk_size Number of samples in the chunk
*
* \returns The number of bytes (\c uint8_t values) required for the
* mask.
*/
size_t pcomp_chunk_cheby_mask_size(pcomp_chunk_size_t chunk_size)
{
return chunk_size / CHAR_BIT
+ ((chunk_size % CHAR_BIT) > 0 ? 1 : 0);
}
/** \ingroup poly_lowlevel
*
* \brief Return a pointer to the bitmask of nonzero Chebyshev
* coefficients for a chunk
*
* \param[in] chunk Pointer to the chunk
*
* \returns A pointer to the array of bytes which make up the mask.
* Use \ref pcomp_mask_get_bit to access the values of each bit.
*/
const uint8_t*
pcomp_chunk_cheby_mask(const pcomp_polycomp_chunk_t* chunk)
{
if (chunk == NULL)
abort();
return chunk->cheby_mask;
}
/**********************************************************************/
/** \ingroup poly_lowlevel
*
* \brief Compute a polynomial fit of the data in \a input and a
* Chebyshev transform of the residuals
*
* Note that this function *always* computes the Chebyshev transform
* of the data, even if there is a perfect fit between the polynomial
* and the input data.
*
* \param[in] params Pointer to a \ref pcomp_polycomp_t structure
* initialized by \ref pcomp_init_polycomp.
*
* \param[out] coeffs Pointer to the array that on exit will hold the
* coefficients of the best-fit polynomial. It must have enough room
* for a number of elements equal to the return value of \ref
* pcomp_polycomp_num_of_poly_coeffs.
*
* \param[out] cheby_residuals Pointer to an array that on exit will
* contain the Chebyshev transform of the residuals of the fit. It can
* be \c NULL; in any case, these numbers can be obtained by the use
* of a call to \ref pcomp_polycomp_forward_cheby and \ref
* pcomp_chebyshev_output.
*
* \param[in] input Pointer to the array of values to be transformed.
* The number of values used is equal to the return value of the
* function \ref pcomp_polycomp_samples_per_chunk.
*
* \param[out] max_residual Pointer to a variable that will hold the
* maximum absolute value of the discrepancy between each sample in \a
* input and the polynomial fit. It can be \c NULL.
*
* \returns If no errors occurred, \ref PCOMP_STAT_SUCCESS. Otherwise,
* the function returns the code of the error.
*/
int pcomp_polyfit_and_chebyshev(pcomp_polycomp_t* params,
double* coeffs, double* cheby_residuals,
const double* input,
double* max_residual)
{
size_t idx;
int status;
double running_max = -1.0; /* Negative stands for "uninitialized" */
status = pcomp_run_poly_fit(params->poly_fit, coeffs, input);
if (status != PCOMP_STAT_SUCCESS)
return status;
for (idx = 0; idx < params->samples_per_chunk; ++idx) {
double abs_residual;
params->chebyshev->input[idx]
= input[idx]
- eval_poly(coeffs, params->poly_fit->num_of_coeffs,
idx + 1.0);
abs_residual = fabs(params->chebyshev->input[idx]);
if (abs_residual > running_max || running_max < 0.0)
running_max = abs_residual;
}
if (max_residual != NULL)
*max_residual = running_max;
if (params->algorithm != PCOMP_ALG_NO_CHEBYSHEV) {
status = pcomp_run_chebyshev(
params->chebyshev, params->chebyshev->dir, NULL, NULL);
if (cheby_residuals != NULL
&& cheby_residuals != params->chebyshev->output) {
memcpy(cheby_residuals, params->chebyshev->output,
sizeof(params->chebyshev->output[0])
* params->chebyshev->num_of_samples);
}
}
return status;
}
/***********************************************************************
* Sort the array "positions" according to the absolute values of
* "coeffs", in *descending* order. The function uses the merge sort
* algorithm. */
static void sort_positions(pcomp_chunk_size_t positions[],
const double coeffs[], size_t num)
{
size_t front, back;
double pivot;
pcomp_chunk_size_t temp;
if (num < 2)
return;
pivot = fabs(coeffs[positions[num / 2]]);
for (front = 0, back = num - 1;; front++, back--) {
while (fabs(coeffs[positions[front]]) > pivot) {
front++;
}
while (pivot > fabs(coeffs[positions[back]])) {
if (back == 0)
break;
back--;
}
if (front >= back)
break;
temp = positions[front];
positions[front] = positions[back];
positions[back] = temp;
}
sort_positions(positions, coeffs, front);
sort_positions(positions + front, coeffs, num - front);
}
/** \ingroup poly_lowlevel
*
* \brief Return the value of the bit at the position \a pos in the
* bitmask \a mask.
*
* \param[in] mask Pointer to the first byte of the mask
*
* \param[in] pos Zero-based index of the bit in the mask
*
* \returns Either 0 or 1, depending on the value of the bit.
*/
int pcomp_mask_get_bit(const uint8_t* mask, size_t pos)
{
return (mask[pos / CHAR_BIT] & (1 << (pos % CHAR_BIT))) != 0;
}
/** \ingroup poly_lowlevel
*
* \brief Set the value of the bit at position \a pos in the bitmask \a
*
* \param[inout] mask The bitmask to modify
*
* \param[in] pos Zero-based index of the byte to set
*
* \param[in] value Value of the bit (either 0 or 1; any value
* different from zero is treated as equal to 1)
*/
void pcomp_mask_set_bit(uint8_t* mask, size_t pos, int value)
{
if (value != 0) {
mask[pos / CHAR_BIT] |= (1 << (pos % CHAR_BIT));
}
else {
mask[pos / CHAR_BIT] &= ~(((uint8_t)1) << (pos % CHAR_BIT));
}
}
static double compute_discrepancy(double a[], double b[], size_t num)
{
size_t idx;
double err = 0.0;
for (idx = 0; idx < num; ++idx) {
double cur_err = fabs(a[idx] - b[idx]);
if (cur_err > err)
err = cur_err;
}
return err;
}
/** \ingroup poly_lowlevel
*
* \brief Find the smallest subset of Chebyshev coefficients that can
* approximate a Chebyshev transform with an error less than \a
* max_allowable_error.
*
* On exit, the bits in \a bitmask will be set to 1 in correspondence
* of every Chebyshev coefficient that must be retained. The function
* returns the number of Chebyshev coefficients to retain (i.e., the
* number of bits in \a mask that have been set to 1).
*
* \param[in] chebyshev Pointer to a \ref pcomp_chebyshev_t structure
* used to compute the forward Chebyshev transform (from the space of
* the fit residuals to the Chebyshev space)
*
* \param[in] inv_chebyshev Pointer to a \ref pcomp_chebyshev_t
* structure representing the inverse transform of \a chebyshev.
*
* \param[in] max_allowable_error The maximum allowed discrepancy for
* the chopped Chebyshev, as measured in the space of the fit
* residuals.
*
* \param[out] mask Bitmask that will contain the position of the
* unchopped Chebyshev terms of the transform of the fit residuals.
* Use \ref pcomp_mask_get_bit to access each element.
*
* \param[out] max_error If not \c NULL, it will be set to the maximum
* error due to the chopping of the Chebyshev transform represented by
* \a mask.
*
* \returns The number of bits equal to one in \a mask, i.e., the
* number of unchopped Chebyshev coefficients.
*/
size_t pcomp_find_chebyshev_mask(pcomp_chebyshev_t* chebyshev,
pcomp_chebyshev_t* inv_chebyshev,
double max_allowable_error,
uint8_t* mask, double* max_error)
{
size_t idx;
size_t cur_coeff = 0;
pcomp_chunk_size_t* positions;
double err;
if (chebyshev == NULL || inv_chebyshev == NULL || mask == NULL
|| chebyshev->num_of_samples != inv_chebyshev->num_of_samples)
abort();
if (max_allowable_error <= 0.0)
return 0;
/* The "positions" array contains the indexes to the
* chebyshev->output array, i.e., the list of Chebyshev
* coefficients to sort in decreasing order. At the beginning each
* entry is set to its own index:
*
* +---+---+---+-----+
* positions: | 0 | 1 | 2 | ... |
* +---+---+---+-----+
*
* After the call to "sort_positions", the "positions" array
* contains the indexes to "chebyshev->output" ordered according
* to the decreasing absolute value of the latters, e.g.:
*
* +---+---+---+-----+
* positions: | 7 | 2 | 5 | ... |
* +---+---+---+-----+
*/
positions = malloc(chebyshev->num_of_samples
* sizeof(pcomp_chunk_size_t));
if (positions == NULL)
abort();
for (idx = 0; idx < chebyshev->num_of_samples; ++idx) {
positions[idx] = idx;
}
sort_positions(positions, chebyshev->output,
chebyshev->num_of_samples);
/* Start by setting all the coefficients to zero */
memset(&inv_chebyshev->input[0], 0,
chebyshev->num_of_samples * sizeof(inv_chebyshev->input[0]));
memset(&mask[0], 0,
pcomp_chunk_cheby_mask_size(chebyshev->num_of_samples));
/* Add the coefficients one by one until the error is below
* "max_allowable_error" */
cur_coeff = 0;
while (cur_coeff < chebyshev->num_of_samples) {
inv_chebyshev->input[positions[cur_coeff]]
= chebyshev->output[positions[cur_coeff]];
pcomp_mask_set_bit(mask, positions[cur_coeff], 1);
++cur_coeff;
pcomp_run_chebyshev(inv_chebyshev, inv_chebyshev->dir, NULL,
NULL);
err = compute_discrepancy(chebyshev->input,
inv_chebyshev->output,
chebyshev->num_of_samples);
if (err < max_allowable_error)
break;
}
free(positions);
if (max_error != NULL)
*max_error = err;
return cur_coeff;
}
/* This function is used internally by "pcomp_run_polycomp_on_chunk"
* and "pcomp_decompress_poly_chunk" to make sure there is no memory
* leak on the chunk passed as argument. */
static void clear_chunk(pcomp_polycomp_chunk_t* chunk)
{
/* Leave chunk->uncompressed as it is, as it never changes
*/
chunk->num_of_poly_coeffs = 0;
if (chunk->poly_coeffs != NULL)
free(chunk->poly_coeffs);
chunk->num_of_cheby_coeffs = 0;
if (chunk->cheby_coeffs != NULL)
free(chunk->cheby_coeffs);
}
/** \ingroup poly_lowlevel
*
* \brief Compress the first \a num_of_samples elements in \a input
* and store them in \a chunk.
*
* The function determines if the data in \a input can be efficiently
* compressed using polynomial compression with the parameters
* described by \a params. If it is so, it stores the compressed data
* in \a chunk. If the compression ratio is small or equal to one, or
* if the compression error is too large, the function copies the data
* in \a input into \a chunk in uncompressed format.
*
* The following example shows how to use this function together with
* \ref pcomp_init_chunk:
*
* \code{.c}
* double input[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0,
* 7.0, 8.0, 9.0, 11.0 };
* size_t input_size = sizeof(input) / sizeof(input[0]);
* pcomp_polycomp_chunk_t* chunk;
* pcomp_polycomp_t* polycomp;
* double max_error;
* size_t idx;
*
* polycomp = pcomp_init_polycomp(input_size, 2, 1.0e-5,
* PCOMP_ALG_USE_CHEBYSHEV);
* chunk = pcomp_init_chunk(input_size);
*
* pcomp_run_polycomp_on_chunk(polycomp, input, input_size, chunk,
* &max_error);
* \endcode
*
* \param[in] params Pointer to a \a pcomp_polycomp_t structure
* (created using \ref pcomp_init_polycomp) which provides the
* parameters of the compression.
*
* \param[in] input The sequence of numbers to compress. Their number
* is equal to the parameter \a num_of_samples
*
* \param[in] num_of_samples Number of values in \a input to compress
*
* \param[inout] chunk The chunk that will contain the data, either in
* compressed or uncompressed format. It must have already been
* initialized via a call to \ref pcomp_init_chunk.
*
* \param[out] max_error On exit, the function writes the compression
* error here. It can be \c NULL.
*
* \returns Either \ref PCOMP_STAT_SUCCESS (if no errors occurred), or
* the error code.
*/
int pcomp_run_polycomp_on_chunk(pcomp_polycomp_t* params,
const double* input,
pcomp_chunk_size_t num_of_samples,
pcomp_polycomp_chunk_t* chunk,
double* max_error)
{
uint8_t* mask = NULL;
double* coeffs = NULL;
size_t cheby_coeffs_to_retain = 0;
int apply_chebyshev = 1;
double* buf = NULL;
const double* straightened_input;
if (chunk == NULL || input == NULL || params == NULL
|| params->poly_fit == NULL || params->chebyshev == NULL
|| params->inv_chebyshev == NULL)
abort();
clear_chunk(chunk);
if (num_of_samples != params->samples_per_chunk)
return PCOMP_STAT_INVALID_BUFFER;
if (params->period > 0.0) {
buf = malloc(num_of_samples * sizeof(input[0]));
if (buf == NULL)
abort();
pcomp_straighten(buf, input, num_of_samples, params->period);
straightened_input = buf; /* This preserve const-correctness */
}
else {
straightened_input = input;
}
if (num_of_samples <= params->poly_fit->num_of_coeffs) {
/* The number of element is so small that is better to store
* them uncompressed */
chunk->is_compressed = 0;
}
else {
double max_residual;
/* Compute the polynomial fit and the full Chebyshev
* transform */
coeffs
= malloc(sizeof(double) * params->poly_fit->num_of_coeffs);
if (coeffs == NULL)
abort();
pcomp_polyfit_and_chebyshev(params, coeffs, NULL,
straightened_input, &max_residual);
apply_chebyshev
= (max_residual >= params->max_allowable_error)
&& (params->algorithm != PCOMP_ALG_NO_CHEBYSHEV);
/* If the Chebyshev transform is needed, chop it as much as
* possible */
if (apply_chebyshev) {
mask = malloc(pcomp_chunk_cheby_mask_size(num_of_samples));
if (mask == NULL)
abort();
cheby_coeffs_to_retain = pcomp_find_chebyshev_mask(
params->chebyshev, params->inv_chebyshev,
params->max_allowable_error, mask, max_error);
chunk->is_compressed = (cheby_coeffs_to_retain
+ params->poly_fit->num_of_coeffs)
< num_of_samples;
if (!chunk->is_compressed) {
free(mask);
mask = NULL;
}
}
else {
/* Assume that num_of_samples > deg(p) + 1 */
chunk->is_compressed
= (max_residual <= params->max_allowable_error);
}
}
chunk->num_of_samples = num_of_samples;
if (chunk->is_compressed) {
size_t idx;
chunk->num_of_poly_coeffs = params->poly_fit->num_of_coeffs;
chunk->poly_coeffs = coeffs;
if (apply_chebyshev) {
size_t cheby_idx;
chunk->num_of_cheby_coeffs = cheby_coeffs_to_retain;
chunk->cheby_mask = mask;
chunk->cheby_coeffs
= malloc(sizeof(double) * cheby_coeffs_to_retain);
if (chunk->cheby_coeffs == NULL)
abort();
cheby_idx = 0;
for (idx = 0; idx < params->chebyshev->num_of_samples;
++idx) {
if (pcomp_mask_get_bit(mask, idx)) {
chunk->cheby_coeffs[cheby_idx++]
= params->chebyshev->output[idx];
}
}
}
else {
chunk->num_of_cheby_coeffs = 0;
chunk->cheby_mask = NULL;
chunk->cheby_coeffs = NULL;
}
}
else {
size_t idx;
if (coeffs != NULL)
free(coeffs);
chunk->uncompressed = malloc(sizeof(double) * num_of_samples);
if (chunk->uncompressed == NULL)
abort();
for (idx = 0; idx < num_of_samples; ++idx)
chunk->uncompressed[idx] = input[idx];
if (max_error != NULL)
*max_error = 0.0;
}
if (buf != NULL) {
free(buf);
}
return PCOMP_STAT_SUCCESS;
}
/** \ingroup poly_lowlevel
*
* \brief Decompress the data in a chunk
*
* This function performs the decompression of a chunk, and it is the
* counterpart of \ref pcomp_run_polycomp_on_chunk. Here is an
* example:
*
* \code{.c}
* double* decompr;
* pcomp_chebyshev_t* inv_chebyshev;
*
* // We assume that "chunk" has already been initialized somewhere
* decompr = malloc(sizeof(double) *
* pcomp_chunk_num_of_samples(chunk));
*
* inv_chebyshev = pcomp_init_chebyshev(input_size,
* PCOMP_TD_INVERSE);
* pcomp_decompress_polycomp_chunk(decompr, chunk, inv_chebyshev);
* \endcode
*
* \param[out] output Pointer to the array that will contain the
* uncompressed data
*
* \param[in] chunk The chunk to decompress
*
* \param[in] inv_chebyshev Pointer to a \ref pcomp_chebyshev_t object
* that performs the inverse Chebyshev transform. The function does
* not allocate an object of this kind because in this way such
* objects can be reused on subsequent calls to \ref
* pcomp_decompress_polycomp_chunk.
*
* \returns Either \ref PCOMP_STAT_SUCCESS if no error occurred, or
* the error code.
*/
int pcomp_decompress_polycomp_chunk(double* output,
const pcomp_polycomp_chunk_t* chunk,
pcomp_chebyshev_t* inv_chebyshev)
{
if (output == NULL || chunk == NULL || inv_chebyshev == NULL)
abort();
if (chunk->is_compressed) {
size_t idx;
/* Compute the values of the polynomial at the points 1,
* 2, ...
*/
for (idx = 0; idx < chunk->num_of_samples; ++idx) {
output[idx] = eval_poly(chunk->poly_coeffs,
chunk->num_of_poly_coeffs, idx + 1);
}
/* If present, add the contribution of the Chebyshev
* transform
*/
if (chunk->num_of_cheby_coeffs > 0) {
size_t cur_cheby_idx = 0;
if (chunk->cheby_coeffs == NULL)
abort();
for (idx = 0; idx < chunk->num_of_samples; ++idx) {
if (pcomp_mask_get_bit(chunk->cheby_mask, idx)) {
if (cur_cheby_idx >= chunk->num_of_cheby_coeffs) {
abort();
}
inv_chebyshev->input[idx]
= chunk->cheby_coeffs[cur_cheby_idx++];
}
else {
inv_chebyshev->input[idx] = 0.0;
}
}
pcomp_run_chebyshev(inv_chebyshev, inv_chebyshev->dir, NULL,
NULL);
for (idx = 0; idx < chunk->num_of_samples; ++idx) {
output[idx] += inv_chebyshev->output[idx];
}
}
}
else {
memcpy(output, chunk->uncompressed,
sizeof(chunk->uncompressed[0]) * chunk->num_of_samples);
}
return PCOMP_STAT_SUCCESS;
}
/** \ingroup poly
*
* \brief Compress the array \a input_buf using polynomial compression
*
* This function compresses the first \a input_size elements of the
* array \a input_buf using the polynomial compression scheme. The
* output is an array of chunks saved in \a output_buf (the number of
* elements of this array is saved in \a num_of_chunks). The \a params
* variable specifies the parameters used by the compression
* algorithm.
*
* Here is an example showing how to compress a sequence of numbers in
* the variable \a input:
*
* \code{.c}
* double input[] = { 1.0, 2.0, 3.0, 4.0, 3.0, 2.0,
* 1.0, 2.0, 6.0, 7.0, 9.0 };
* size_t input_size = sizeof(input) / sizeof(input[0]);
* double* decompr;
* size_t decompr_size;
* pcomp_polycomp_chunk_t** chunks;
* size_t num_of_chunks;
* pcomp_polycomp_t* params;
* size_t idx;
*
* params = pcomp_init_polycomp(4, 2, 1.0e-5, PCOMP_ALG_USE_CHEBYSHEV);
* pcomp_compress_polycomp(&chunks, &num_of_chunks, input, input_size,
* params);
*
* // Print some information for each chunk
* for(idx = 0; idx < num_of_chunks; ++idx) {
* printf("Chunk %lu of %lu: %s\n", idx + 1, num_of_chunks,
* pcomp_chunk_is_compressed(chunks[idx]) ?
* "compressed" : "uncompressed");
* }
* \endcode
*
* Once the sequence \a input_buf is compressed, the array of chunks
* can either be analyzed (e.g., using a \c for loop as in the example
* above) or encoded using the \ref pcomp_encode_chunks. Once the
* variable \a output_buf is no longer used, it should be freed via a
* call to \ref pcomp_free_chunks.
*
* \param[out] output_buf Pointer to a variable that will receive the
* address of an array of \ref pcomp_polycomp_chunk_t variables
* created by the function. Such array contains the whole set of data
* in \a input in compressed format. The array can be freed via a call
* to \ref pcomp_free_chunks.
*
* \param[out] num_of_chunks On output, the variable will contain the
* number of chunks saved in \a output_buf.
*
* \param[in] input_buf Pointer to the array of numbers to compress.
*
* \param[in] input_size Number of elements in \a input_buf to
* compress.
*
* \param[in] params Parameters used for the compression. The variable
* must have been created via a call to \ref pcomp_init_polycomp.
*
* \returns Either \ref PCOMP_STAT_SUCCESS if no error occurred, or
* the error code.
*/
int pcomp_compress_polycomp(pcomp_polycomp_chunk_t** output_buf[],
size_t* num_of_chunks,
const double* input_buf, size_t input_size,
const pcomp_polycomp_t* params)
{
size_t idx;
pcomp_polycomp_t** chunk_params;
pcomp_polycomp_t* last_chunk_params;
size_t samples_in_last_chunk = 0;
if (output_buf == NULL || num_of_chunks == NULL || input_buf == NULL
|| params == NULL || params->poly_fit == NULL)
abort();
/* Calculate how many chunks we'll create */
*num_of_chunks = input_size / params->samples_per_chunk;
samples_in_last_chunk = input_size % params->samples_per_chunk;
if (samples_in_last_chunk != 0)
++(*num_of_chunks);
*output_buf
= malloc(sizeof(pcomp_polycomp_chunk_t*) * (*num_of_chunks));
if (*output_buf == NULL)
abort();
/* Allocate a pcomp_polycomp_t structure for each of the OpenMP
* threads */
chunk_params
= malloc(sizeof(pcomp_polycomp_t*) * omp_get_max_threads());
for (idx = 0; idx < omp_get_max_threads(); ++idx) {
chunk_params[idx] = pcomp_init_polycomp(
params->samples_per_chunk, params->poly_fit->num_of_coeffs,
params->max_allowable_error, params->algorithm);
}
if (samples_in_last_chunk != 0) {
/* This is going to be used by just *one* OpenMP process */
last_chunk_params = pcomp_init_polycomp(
samples_in_last_chunk, params->poly_fit->num_of_coeffs,
params->max_allowable_error, params->algorithm);
}
else {
last_chunk_params = NULL;
}
#pragma omp parallel for
for (idx = 0; idx < *num_of_chunks; ++idx) {
const double* cur_input = input_buf
+ params->samples_per_chunk * idx;
pcomp_polycomp_t* cur_params;
size_t cur_chunk_size;
if (idx + 1 < *num_of_chunks || last_chunk_params == NULL) {
cur_params = chunk_params[omp_get_thread_num()];
cur_chunk_size = params->samples_per_chunk;
}
else {
cur_params = last_chunk_params;
cur_chunk_size = samples_in_last_chunk;
}
if (cur_params == NULL)
abort();
(*output_buf)[idx] = pcomp_init_chunk(cur_chunk_size);
pcomp_run_polycomp_on_chunk(cur_params, cur_input,
cur_chunk_size, (*output_buf)[idx],
NULL);
}
for (idx = 0; idx < omp_get_max_threads(); ++idx)
pcomp_free_polycomp(chunk_params[idx]);
free(chunk_params);
pcomp_free_polycomp(last_chunk_params);
return PCOMP_STAT_SUCCESS;
}
/** \ingroup poly
*
* \brief Compute the sum of the number of samples encoded in \a
*chunk_array
*
* \param[in] chunk_array Array of \ref pcomp_polycomp_chunk_t
* variables. Typically, such array is created via a call to \ref
* pcomp_compress_polycomp.
*
* \param[in] num_of_chunks Number of elements in \a chunk_array
*
* \returns The overall number of samples encoded in the sequence of
* chunks
*/
size_t
pcomp_total_num_of_samples(pcomp_polycomp_chunk_t* const chunk_array[],
size_t num_of_chunks)
{
size_t total = 0;
size_t idx;
if (chunk_array == NULL)
abort();
for (idx = 0; idx < num_of_chunks; ++idx) {
if (chunk_array[idx] == NULL)
abort();
total += chunk_array[idx]->num_of_samples;
}
return total;
}
/** \ingroup poly
*
* \brief Decompress a sequence of chunks
*
* This function is the counterpart for \ref pcomp_compress_polycomp.
*
* \param[out] output_buf Pointer to the variable that will hold the
* uncompressed data. It must have room for a number of elements at
* least equal to the return value of \ref pcomp_total_num_of_samples.
*
* \param[in] chunk_array Array of chunks holding the data in
* compressed format.
*
* \param[in] num_of_chunks Number of elements in the array \a
* chunk_array.
*
* \returns Either \ref PCOMP_STAT_SUCCESS if no error occurred, or
* the error code.
*/
int pcomp_decompress_polycomp(
double* output_buf, pcomp_polycomp_chunk_t* const chunk_array[],
size_t num_of_chunks)
{
size_t idx;
size_t* start_pos_list;
pcomp_chebyshev_t** inv_cheby_list = NULL;
pcomp_chebyshev_t* last_inv_cheby = NULL;
if (output_buf == NULL || chunk_array == NULL || num_of_chunks == 0)
abort();
/* Precompute the position in the output buffer where the
* decompressed data from each chunk will be written: in this way,
* we prevent data races in the parallel for loop below. */
start_pos_list = malloc(sizeof(size_t) * num_of_chunks);
if (start_pos_list == NULL)
abort();
start_pos_list[0] = 0;
for (idx = 0; idx < num_of_chunks - 1; ++idx) {
/* The algorithm heavy relies on the fact that *all the
* chunks* but the last one have the same number of
* elements! */
if (chunk_array[idx]->num_of_samples
!= chunk_array[0]->num_of_samples)
abort();
start_pos_list[idx + 1] = start_pos_list[idx]
+ chunk_array[idx]->num_of_samples;
}
/* Since FFTW's plan allocation functions are not reentrant, we
* must initialize them outside the parallel loop. */
inv_cheby_list
= malloc(sizeof(pcomp_chebyshev_t*) * omp_get_max_threads());
if (inv_cheby_list == NULL)
abort();
for (idx = 0; idx < omp_get_max_threads(); ++idx) {
if (idx < num_of_chunks) {
inv_cheby_list[idx] = pcomp_init_chebyshev(
chunk_array[idx]->num_of_samples, PCOMP_TD_INVERSE);
}
else {
inv_cheby_list[idx] = NULL;
}
}
if (chunk_array[num_of_chunks - 1]->num_of_samples
!= chunk_array[0]->num_of_samples) {
last_inv_cheby = pcomp_init_chebyshev(
chunk_array[num_of_chunks - 1]->num_of_samples,
PCOMP_TD_INVERSE);
}
else
last_inv_cheby = NULL;
#pragma omp parallel for
for (idx = 0; idx < num_of_chunks; ++idx) {
pcomp_chebyshev_t* cur_inv_cheby;
if (chunk_array[idx] == NULL)
abort();
if (idx + 1 < num_of_chunks || last_inv_cheby == NULL) {
cur_inv_cheby = inv_cheby_list[omp_get_thread_num()];
}
else {
cur_inv_cheby = last_inv_cheby;
}
pcomp_decompress_polycomp_chunk(
output_buf + start_pos_list[idx], chunk_array[idx],
cur_inv_cheby);
}
free(start_pos_list);
for (idx = 0; idx < omp_get_max_threads(); ++idx) {
pcomp_free_chebyshev(inv_cheby_list[idx]);
}
free(inv_cheby_list);
pcomp_free_chebyshev(last_inv_cheby);
return PCOMP_STAT_SUCCESS;
}
/** \ingroup poly
*
* \brief Free an array of chunks
*
* \param[in] chunk_array An array of chunks. This variable must have
* been allocated by a call to \ref pcomp_compress_polycomp.
*
* \param[in] num_of_chunks Number of elements in the array \a
* chunk_array
*/
void pcomp_free_chunks(pcomp_polycomp_chunk_t* chunk_array[],
size_t num_of_chunks)
{
size_t idx;
if (chunk_array == NULL)
return;
for (idx = 0; idx < num_of_chunks; ++idx) {
pcomp_free_chunk(chunk_array[idx]);
}
free(chunk_array);
}
/** \ingroup poly
*
* \brief Number of bytes required by \ref pcomp_encode_chunks
*
* This function computes the number of bytes required to encode the
* array of chunks in the variable \a chunks. Unlike functions like
* \ref pcomp_rle_bufsize, this function provides an exact estimate,
* not an upper bound.
*
* \param[in] chunks Array of chunks to encode. This should have been
* initialized via a call to \ref pcomp_compress_polycomp.
*
* \param[in] num_of_chunks Number of elements in \a chunks.
*
* \returns The number of bytes required for the output buffer used by
* \ref pcomp_encode_chunks.
*/
size_t pcomp_chunks_num_of_bytes(pcomp_polycomp_chunk_t* const chunks[],
size_t num_of_chunks)
{
size_t result = sizeof(size_t); /* Room for the number of chunks */
size_t idx;
for (idx = 0; idx < num_of_chunks; ++idx) {
result += pcomp_chunk_num_of_bytes(chunks[idx]);
}
return result;
}
/***********************************************************************
* Encode/decode a list of chunks into a raw stream of bytes (suitable
* for I/O).
*/
#define SAVE_TO_PTR_AND_INCREMENT(buf, value, type) \
{ \
*((type*)buf) = value; \
buf = ((type*)buf) + 1; \
}
/** \ingroup poly
*
* \brief Encode a list of chunks into a sequence of raw bytes
*
* This function transforms an array of instances to \ref
* pcomp_polycomp_chunk_t variables into a sequence of raw bytes,
* suitable for I/O. It can be used together with \ref
* pcomp_compress_polycomp to compress a dataset and save it into a
* binary file.
*
* To decode byte sequences produced by this function, use \ref
* pcomp_decode_chunks.
*
* \param[out] buf Pointer to a memory buffer that will receive the
* result of the encoding. It must have room for a number of bytes (\c
* uint8_t) at least equal to the return value of \ref
* pcomp_chunks_num_of_bytes.
*
* \param[out] buf_size On exit, it will contain the number of bytes
* actually written in \a buf. The latter number is equal to the value
* returned by \ref pcomp_chunks_num_of_bytes.
*
* \param[in] chunk_array Array of chunks to encode
*
* \param[in] num_of_chunks Number of elements in the array \a
* chunk_array.
*
* \returns Either \ref PCOMP_STAT_SUCCESS if no error occurred, or
* the error code.
*/
int pcomp_encode_chunks(void* buf, size_t* buf_size,
pcomp_polycomp_chunk_t* const chunk_array[],
size_t num_of_chunks)
{
void* buf_ptr = buf;
size_t chunk_idx;
uint64_t num_of_chunks_uint64 = (uint64_t)num_of_chunks;
if (chunk_array == NULL || num_of_chunks == 0)
abort();
SAVE_TO_PTR_AND_INCREMENT(buf_ptr, num_of_chunks_uint64, uint64_t);
num_of_chunks = num_of_chunks_uint64;
for (chunk_idx = 0; chunk_idx < num_of_chunks; ++chunk_idx) {
const pcomp_polycomp_chunk_t* cur_chunk
= chunk_array[chunk_idx];
size_t idx; /* Used for inner loops */
SAVE_TO_PTR_AND_INCREMENT(buf_ptr, cur_chunk->is_compressed,
uint8_t);
SAVE_TO_PTR_AND_INCREMENT(buf_ptr, cur_chunk->num_of_samples,
pcomp_chunk_size_t);
if (cur_chunk->is_compressed) {
size_t cheby_mask_size = pcomp_chunk_cheby_mask_size(
cur_chunk->num_of_samples);
SAVE_TO_PTR_AND_INCREMENT(buf_ptr,
cur_chunk->num_of_poly_coeffs,
pcomp_poly_size_t);
for (idx = 0; idx < cur_chunk->num_of_poly_coeffs; idx++) {
SAVE_TO_PTR_AND_INCREMENT(
buf_ptr, cur_chunk->poly_coeffs[idx], double);
}
SAVE_TO_PTR_AND_INCREMENT(buf_ptr,
cur_chunk->num_of_cheby_coeffs,
pcomp_chunk_size_t);
if (cur_chunk->num_of_cheby_coeffs > 0) {
/* Mask */
for (idx = 0; idx < cheby_mask_size; ++idx) {
SAVE_TO_PTR_AND_INCREMENT(
buf_ptr, cur_chunk->cheby_mask[idx], uint8_t);
}
/* Chebyshev coefficients */
for (idx = 0; idx < cur_chunk->num_of_cheby_coeffs;
idx++) {
SAVE_TO_PTR_AND_INCREMENT(
buf_ptr, cur_chunk->cheby_coeffs[idx], double);
}
}
}
else {
for (idx = 0; idx < cur_chunk->num_of_samples; idx++) {
SAVE_TO_PTR_AND_INCREMENT(
buf_ptr, cur_chunk->uncompressed[idx], double);
}
}
}
*buf_size = ((uint8_t*)buf_ptr) - ((uint8_t*)buf);
return PCOMP_STAT_SUCCESS;
}
#define READ_FROM_PTR_AND_INCREMENT(var, pointer, type) \
{ \
var = *((type*)(pointer)); \
pointer = ((type*)(pointer)) + 1; \
}
/** \ingroup poly
*
* \brief Decode a byte sequence created by \ref pcomp_encode_chunks
* into an array of chunks.
*
* This function can be used to read from a binary file or a socket a
* sequence of chunks encoded by \ref pcomp_encode_chunks. The
* function allocates memory for an array of \ref
* pcomp_polycomp_chunk_t structures and returns it in the variable \a
* chunk_array. The latter variable must be freed using \ref
* pcomp_free_chunks once it is no longer needed.
*
* This function is the counterpart for \ref pcomp_encode_chunks.
*
* \param[out] chunk_array Pointer to an array that will contain the
* chunks decoded from \a buf.
*
* \param[out] num_of_chunks On exit, this variable will hold the
* number of chunks saved in \a chunk_array.
*
* \param[in] Pointer to the byte sequence to decode.
*
* \returns Either \ref PCOMP_STAT_SUCCESS if no error occurred, or
* the error code.
*/
int pcomp_decode_chunks(pcomp_polycomp_chunk_t** chunk_array[],
size_t* num_of_chunks, const void* buf)
{
const void* cur_ptr = buf;
size_t chunk_idx;
double* poly_buf = NULL;
size_t poly_buf_size = 0;
double* cheby_buf = NULL;
size_t cheby_buf_size = 0;
uint8_t* cheby_mask_buf = NULL;
size_t cheby_mask_buf_size = 0;
double* uncompr_buf = NULL;
size_t uncompr_buf_size = 0;
uint64_t num_of_chunks_uint64;
if (buf == NULL || chunk_array == NULL || num_of_chunks == NULL)
abort();
READ_FROM_PTR_AND_INCREMENT(num_of_chunks_uint64, cur_ptr,
uint64_t);
*num_of_chunks = num_of_chunks_uint64;
*chunk_array
= malloc(sizeof(pcomp_polycomp_chunk_t*) * (*num_of_chunks));
if (*chunk_array == NULL)
abort();
for (chunk_idx = 0; chunk_idx < *num_of_chunks; ++chunk_idx) {
uint8_t is_compressed;
size_t num_of_samples;
size_t idx; /* Used for inner loops */
READ_FROM_PTR_AND_INCREMENT(is_compressed, cur_ptr, uint8_t);
READ_FROM_PTR_AND_INCREMENT(num_of_samples, cur_ptr,
pcomp_chunk_size_t);
if (is_compressed) {
size_t num_of_poly_coeffs;
size_t num_of_cheby_coeffs;
size_t cheby_mask_size
= pcomp_chunk_cheby_mask_size(num_of_samples);
READ_FROM_PTR_AND_INCREMENT(num_of_poly_coeffs, cur_ptr,
pcomp_poly_size_t);
if (num_of_poly_coeffs > poly_buf_size) {
poly_buf_size = num_of_poly_coeffs;
poly_buf
= realloc(poly_buf, poly_buf_size * sizeof(double));
}
for (idx = 0; idx < num_of_poly_coeffs; ++idx) {
READ_FROM_PTR_AND_INCREMENT(poly_buf[idx], cur_ptr,
double);
}
READ_FROM_PTR_AND_INCREMENT(num_of_cheby_coeffs, cur_ptr,
pcomp_chunk_size_t);
if (num_of_cheby_coeffs > 0) {
if (cheby_mask_size > cheby_mask_buf_size) {
cheby_mask_buf_size = cheby_mask_size;
cheby_mask_buf = realloc(cheby_mask_buf,
cheby_mask_buf_size
* sizeof(uint8_t));
}
for (idx = 0; idx < cheby_mask_size; ++idx) {
READ_FROM_PTR_AND_INCREMENT(cheby_mask_buf[idx],
cur_ptr, uint8_t);
}
if (num_of_cheby_coeffs > cheby_buf_size) {
cheby_buf_size = num_of_cheby_coeffs;
cheby_buf = realloc(
cheby_buf, cheby_buf_size * sizeof(double));
}
for (idx = 0; idx < num_of_cheby_coeffs; ++idx) {
READ_FROM_PTR_AND_INCREMENT(cheby_buf[idx], cur_ptr,
double);
}
}
(*chunk_array)[chunk_idx] = pcomp_init_compressed_chunk(
num_of_samples, num_of_poly_coeffs, poly_buf,
num_of_cheby_coeffs, cheby_mask_buf, cheby_buf);
}
else {
if (num_of_samples > uncompr_buf_size) {
uncompr_buf_size = num_of_samples;
uncompr_buf = realloc(
uncompr_buf, uncompr_buf_size * sizeof(double));
}
for (idx = 0; idx < num_of_samples; ++idx) {
READ_FROM_PTR_AND_INCREMENT(uncompr_buf[idx], cur_ptr,
double);
}
(*chunk_array)[chunk_idx] = pcomp_init_uncompressed_chunk(
num_of_samples, uncompr_buf);
}
}
if (poly_buf != NULL)
free(poly_buf);
if (cheby_buf != NULL)
free(cheby_buf);
if (uncompr_buf != NULL)
free(uncompr_buf);
return PCOMP_STAT_SUCCESS;
}
| {
"alphanum_fraction": 0.6414807109,
"avg_line_length": 31.79790238,
"ext": "c",
"hexsha": "f0f526dd28f3d39f7bf6bb79a5cb454407ebc67c",
"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": "5b292411a7f9b692d4d5225713d7987199b5478f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ziotom78/libpolycomp",
"max_forks_repo_path": "poly.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5b292411a7f9b692d4d5225713d7987199b5478f",
"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": "ziotom78/libpolycomp",
"max_issues_repo_path": "poly.c",
"max_line_length": 73,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "5b292411a7f9b692d4d5225713d7987199b5478f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ziotom78/libpolycomp",
"max_stars_repo_path": "poly.c",
"max_stars_repo_stars_event_max_datetime": "2018-12-31T05:43:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-02T21:41:11.000Z",
"num_tokens": 19349,
"size": 78827
} |
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
#include <point2d.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_multimin.h>
#include <QVector>
#define PI 3.1415926535
#define R2 33000
#define PARAM_COUNT 6
struct param_struct {
QVector<Point2D> *data;
int resi;
int aresi;
double f_min;
double f_max;
double RmU,LmU,CmU,C0U,UU,R0U;
double Rm,Lm,Cm,C0,U,R0;
};
double If(const gsl_vector *v, void *params, double f); //I(f)
double StDev(const gsl_vector *v, void *params); //sum from 0 to N-1 (I_exp(f)-I(f))**2
Point2D find_extremum(QVector<Point2D> dat, bool max, int* index=0);
#endif // FUNCTIONS_H
| {
"alphanum_fraction": 0.6952380952,
"avg_line_length": 21,
"ext": "h",
"hexsha": "5191a89e72257d39143d4cabe97faa431bf1fd3e",
"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": "e08dd73e8c1a373b0f33da71779400a584902ef1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lierdakil/masec-2",
"max_forks_repo_path": "asec_simplex/functions.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e08dd73e8c1a373b0f33da71779400a584902ef1",
"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": "lierdakil/masec-2",
"max_issues_repo_path": "asec_simplex/functions.h",
"max_line_length": 87,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e08dd73e8c1a373b0f33da71779400a584902ef1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lierdakil/masec-2",
"max_stars_repo_path": "asec_simplex/functions.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 212,
"size": 630
} |
#pragma once
#ifndef __GREEK_LETTERS_H__
#define __GREEK_LETTERS_H__
#include <cstring>
#include <string>
#include <gsl/gsl_math.h>
#include "../../Utils/BinarySearch.h"
constexpr const int numGreekLetters = 49;
constexpr const char* greekLetterNames[numGreekLetters] = {
"Alpha", "Beta", "Chi", "Delta", "Epsilon", "Eta", "Gamma", "Iota", "Kappa", "Lambda",
"Mu", "Nu", "Omega", "Omicron", "Phi", "Pi", "Psi", "Rho", "Sigma", "Tau", "Theta",
"Upsilon", "Xi", "Zeta", "alpha", "beta", "chi", "delta", "epsilon", "eta", "gamma",
"iota", "kappa", "lambda", "mu", "nu", "omega", "omicron", "phi", "pi", "psi", "rho",
"sigma", "tau", "theta", "upsilon", "vphi", "xi", "zeta"
};
constexpr const int shortestGreekLetterName = 2;
constexpr const int longestGreekLetterName = 7;
constexpr const int greekLetterLength = 2;
const std::string greekLetters[numGreekLetters] = {
u8"\u0391", u8"\u0392", u8"\u03A7", u8"\u0394", u8"\u0395", u8"\u0397", u8"\u0393",
u8"\u0399", u8"\u039A", u8"\u039B", u8"\u039C", u8"\u039D", u8"\u03A9", u8"\u039F",
u8"\u03A6", u8"\u03A0", u8"\u03A8", u8"\u03A1", u8"\u03A3", u8"\u03A4", u8"\u0398",
u8"\u03A5", u8"\u039E", u8"\u0396", u8"\u03B1", u8"\u03B2", u8"\u03C7", u8"\u03B4",
u8"\u03B5", u8"\u03B7", u8"\u03B3", u8"\u03B9", u8"\u03BA", u8"\u03BB", u8"\u03BC",
u8"\u03BD", u8"\u03C9", u8"\u03BF", u8"\u03C6", u8"\u03C0", u8"\u03C8", u8"\u03C1",
u8"\u03C3", u8"\u03C4", u8"\u03B8", u8"\u03C5", u8"\u03d5", u8"\u03BE", u8"\u03B6"
};
/*
Returns index of the constant in the constants array.
Uses binary search under the hood to search for the index.
Parameters
----------
name: The name of the constantaddMissingRParens
The index or -1 if the provided name is not a constant.
*/
CONSTEXPR_BINARY_SEARCH(getGreekLetterNameIndex, greekLetterNames, numGreekLetters)
static int getGreekLetterIndex(const std::string& name){
if (name.size() <= greekLetterLength){
for (int i = 0; i < numGreekLetters; ++i){
if (name == greekLetters[i]){
return i;
}
}
}
return getGreekLetterNameIndex(name.c_str());
}
#endif // __GREEK_LETTERS_H__
| {
"alphanum_fraction": 0.6384471469,
"avg_line_length": 36.8620689655,
"ext": "h",
"hexsha": "1717bfe0670ab81ace43f2fd2a39ef934f027738",
"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": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "antoniojkim/CalcPlusPlus",
"max_forks_repo_path": "MathEngine/Expressions/VariableExpressions/GreekLetters.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"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": "antoniojkim/CalcPlusPlus",
"max_issues_repo_path": "MathEngine/Expressions/VariableExpressions/GreekLetters.h",
"max_line_length": 87,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "antoniojkim/CalcPlusPlus",
"max_stars_repo_path": "MathEngine/Expressions/VariableExpressions/GreekLetters.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 813,
"size": 2138
} |
/* Copyright (c) 2020 Felix Kutzner (github.com/fkutzner)
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.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
*/
#pragma once
#include <libincmonk/verifier/Traits.h>
#include <cstdint>
#include <gsl/span>
#include <iterator>
#include <limits>
#include <memory>
#include <optional>
#include <ostream>
#include <unordered_map>
#include <vector>
namespace incmonk::verifier {
class Var {
public:
constexpr explicit Var(uint32_t id);
constexpr Var();
constexpr auto getRawValue() const -> uint32_t;
constexpr auto operator==(Var rhs) const -> bool;
constexpr auto operator!=(Var rhs) const -> bool;
constexpr auto operator<(Var rhs) const -> bool;
constexpr auto operator<=(Var rhs) const -> bool;
constexpr auto operator>(Var rhs) const -> bool;
constexpr auto operator>=(Var rhs) const -> bool;
private:
uint32_t m_rawValue;
};
template <>
struct Key<Var> {
constexpr static auto get(Var const& item) -> std::size_t;
};
auto operator""_Var(unsigned long long cnfValue) -> Var;
auto operator<<(std::ostream& stream, Var var) -> std::ostream&;
class Lit {
public:
constexpr explicit Lit(Var v, bool positive);
constexpr Lit();
constexpr auto getRawValue() const -> uint32_t;
constexpr auto getVar() const -> Var;
constexpr auto isPositive() const -> bool;
constexpr auto operator-() const -> Lit;
constexpr auto operator==(Lit rhs) const -> bool;
constexpr auto operator!=(Lit rhs) const -> bool;
constexpr auto operator<(Lit rhs) const -> bool;
constexpr auto operator<=(Lit rhs) const -> bool;
constexpr auto operator>(Lit rhs) const -> bool;
constexpr auto operator>=(Lit rhs) const -> bool;
private:
uint32_t m_rawValue;
};
auto operator""_Lit(unsigned long long cnfValue) -> Lit;
auto operator<<(std::ostream& stream, Lit lit) -> std::ostream&;
template <>
struct Key<Lit> {
constexpr static auto get(Lit const& item) -> std::size_t;
};
auto maxLit(Var var) noexcept -> Lit;
enum class ClauseVerificationState : uint8_t {
/// The clause is part of the problem instance, no verification required
Irredundant = 0,
/// The clause is a lemma and has not yet been determined to be relevant for the proof
Passive = 1,
/// The clause is a lemma and has been determinined relevant for the proof. RAT property
/// verification is pending
VerificationPending = 2,
/// The clause is a lemma and its RAT property has been verified.
Verified = 3
};
using ProofSequenceIdx = uint32_t;
class Clause final {
public:
using size_type = uint32_t;
using iterator = Lit*; // TODO: write proper iterator
using const_iterator = Lit const*; // TODO: write proper const_iterator
auto operator[](size_type idx) noexcept -> Lit&;
auto operator[](size_type idx) const noexcept -> Lit const&;
auto getLiterals() noexcept -> gsl::span<Lit>;
auto getLiterals() const noexcept -> gsl::span<Lit const>;
auto size() const noexcept -> size_type;
auto empty() const noexcept -> bool;
void setState(ClauseVerificationState state) noexcept;
auto getState() const noexcept -> ClauseVerificationState;
auto getAddIdx() const noexcept -> ProofSequenceIdx;
private:
friend class ClauseCollection;
Clause(size_type size, ClauseVerificationState initialState, ProofSequenceIdx addIdx) noexcept;
size_type m_size;
uint32_t m_flags;
ProofSequenceIdx m_pointOfAdd;
Lit m_firstLit;
};
auto operator<<(std::ostream& stream, Clause const& clause) -> std::ostream&;
class ClauseFinder;
class ClauseOccurrences;
class ClauseCollection final {
public:
ClauseCollection();
~ClauseCollection();
class Ref {
public:
auto operator==(Ref rhs) const noexcept -> bool;
auto operator!=(Ref rhs) const noexcept -> bool;
private:
std::size_t m_offset = 0;
friend class ClauseCollection;
friend class RefIterator;
friend struct std::hash<Ref>;
};
class RefIterator {
public:
using value_type = Ref;
using reference = Ref&;
using pointer = Ref*;
using difference_type = intptr_t;
using iterator_category = std::input_iterator_tag;
RefIterator(char const* m_allocatorMemory, std::size_t highWaterMark) noexcept;
RefIterator() noexcept;
auto operator*() const noexcept -> Ref const&;
auto operator->() const noexcept -> Ref const*;
auto operator++(int) noexcept -> RefIterator;
auto operator++() noexcept -> RefIterator&;
auto operator==(RefIterator const& rhs) const noexcept -> bool;
auto operator!=(RefIterator const& rhs) const noexcept -> bool;
RefIterator(RefIterator const& rhs) noexcept = default;
RefIterator(RefIterator&& rhs) noexcept = default;
auto operator=(RefIterator const& rhs) noexcept -> RefIterator& = default;
auto operator=(RefIterator&& rhs) noexcept -> RefIterator& = default;
private:
char const* m_clausePtr;
std::size_t m_distanceToEnd;
Ref m_currentRef;
};
using LitSpan = gsl::span<Lit const>;
using OccRng = gsl::span<Ref const>;
auto add(LitSpan lits, ClauseVerificationState initialState, ProofSequenceIdx addIdx) -> Ref;
auto resolve(Ref cref) noexcept -> Clause&;
auto resolve(Ref cref) const noexcept -> Clause const&;
auto find(LitSpan lits) const noexcept -> std::optional<Ref>;
auto getOccurrences(Lit lit) const noexcept -> OccRng;
auto begin() const noexcept -> RefIterator;
auto end() const noexcept -> RefIterator;
auto getMaxVar() const noexcept -> Var;
ClauseCollection(ClauseCollection&&) noexcept;
auto operator=(ClauseCollection &&) -> ClauseCollection&;
ClauseCollection(ClauseCollection const&) = delete;
auto operator=(ClauseCollection const&) -> ClauseCollection& = delete;
private:
void resize(std::size_t newSize);
auto isValidRef(Ref cref) const noexcept -> bool;
char* m_memory = nullptr;
std::size_t m_currentSize = 0;
std::size_t m_highWaterMark = 0;
Var m_maxVar = 0_Var;
std::vector<Ref> m_deletedClauses;
mutable std::unique_ptr<ClauseFinder> m_clauseFinder;
mutable std::unique_ptr<ClauseOccurrences> m_clauseOccurrences;
};
using CRef = ClauseCollection::Ref;
using OptCRef = std::optional<CRef>;
}
#include "ClauseImpl.h"
| {
"alphanum_fraction": 0.7283448556,
"avg_line_length": 30.3580246914,
"ext": "h",
"hexsha": "600be576742e1351c1c5055856fbfb9e060af7d9",
"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": "fc87d8b408cd57a69f0c1bf3579ccbdfd60d7c13",
"max_forks_repo_licenses": [
"X11",
"MIT"
],
"max_forks_repo_name": "fkutzner/IncrementalMonkey",
"max_forks_repo_path": "lib/libincmonk/verifier/Clause.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fc87d8b408cd57a69f0c1bf3579ccbdfd60d7c13",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"X11",
"MIT"
],
"max_issues_repo_name": "fkutzner/IncrementalMonkey",
"max_issues_repo_path": "lib/libincmonk/verifier/Clause.h",
"max_line_length": 97,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fc87d8b408cd57a69f0c1bf3579ccbdfd60d7c13",
"max_stars_repo_licenses": [
"X11",
"MIT"
],
"max_stars_repo_name": "fkutzner/IncrementalMonkey",
"max_stars_repo_path": "lib/libincmonk/verifier/Clause.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-12T17:58:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-02-12T17:58:09.000Z",
"num_tokens": 1735,
"size": 7377
} |
#pragma once
#include "ShaderCompiler.h"
#include <gsl/gsl>
#include <spirv_cross.hpp>
#include <spirv_parser.hpp>
#include <unordered_map>
#include <string>
namespace Babylon::ShaderCompilerCommon
{
template<typename AppendageT>
inline void AppendBytes(std::vector<uint8_t>& bytes, const AppendageT appendage)
{
auto ptr = reinterpret_cast<const uint8_t*>(&appendage);
auto stride = static_cast<std::ptrdiff_t>(sizeof(AppendageT));
bytes.insert(bytes.end(), ptr, ptr + stride);
}
template<typename AppendageT = std::string&>
inline void AppendBytes(std::vector<uint8_t>& bytes, const std::string& string)
{
auto ptr = reinterpret_cast<const uint8_t*>(string.data());
auto stride = static_cast<std::ptrdiff_t>(string.length());
bytes.insert(bytes.end(), ptr, ptr + stride);
}
template<typename ElementT>
inline void AppendBytes(std::vector<uint8_t>& bytes, const gsl::span<ElementT>& data)
{
auto ptr = reinterpret_cast<const uint8_t*>(data.data());
auto stride = static_cast<std::ptrdiff_t>(data.size() * sizeof(ElementT));
bytes.insert(bytes.end(), ptr, ptr + stride);
}
struct NonSamplerUniformsInfo
{
struct Uniform
{
enum class TypeEnum
{
Vec4,
Mat4
};
std::string Name{};
uint32_t Offset{};
uint16_t RegisterSize{};
TypeEnum Type{};
};
uint16_t ByteSize{};
std::vector<Uniform> Uniforms{};
};
void AppendUniformBuffer(std::vector<uint8_t>& bytes, const NonSamplerUniformsInfo& uniformBuffer, bool isFragment);
void AppendSamplers(std::vector<uint8_t>& bytes, const spirv_cross::Compiler& compiler, const spirv_cross::SmallVector<spirv_cross::Resource>& samplers, std::unordered_map<std::string, uint8_t>& stages);
NonSamplerUniformsInfo CollectNonSamplerUniforms(spirv_cross::Parser& parser, const spirv_cross::Compiler& compiler);
struct ShaderInfo
{
std::unique_ptr<spirv_cross::Parser> Parser;
std::unique_ptr<const spirv_cross::Compiler> Compiler;
gsl::span<uint8_t> Bytes;
std::unordered_map<std::string, std::string> AttributeRenaming;
};
ShaderCompiler::BgfxShaderInfo CreateBgfxShader(ShaderInfo vertexShaderInfo, ShaderInfo fragmentShaderInfo);
}
| {
"alphanum_fraction": 0.6621230896,
"avg_line_length": 34.0985915493,
"ext": "h",
"hexsha": "1242354a995c9c9f4140e42e5b91aee9d5359a56",
"lang": "C",
"max_forks_count": 114,
"max_forks_repo_forks_event_max_datetime": "2022-03-11T21:13:27.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-10T18:07:19.000Z",
"max_forks_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "chiamaka-123/BabylonNative",
"max_forks_repo_path": "Plugins/NativeEngine/Source/ShaderCompilerCommon.h",
"max_issues_count": 593,
"max_issues_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T19:25:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-05-31T23:56:36.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "chiamaka-123/BabylonNative",
"max_issues_repo_path": "Plugins/NativeEngine/Source/ShaderCompilerCommon.h",
"max_line_length": 207,
"max_stars_count": 474,
"max_stars_repo_head_hexsha": "7f1f9fd23bf649c9c8a1260f2b93752145b0c024",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "chiamaka-123/BabylonNative",
"max_stars_repo_path": "Plugins/NativeEngine/Source/ShaderCompilerCommon.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T12:09:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-29T09:41:22.000Z",
"num_tokens": 557,
"size": 2421
} |
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "allvars.h"
#include "proto.h"
#include "domain.h"
#include <gsl/gsl_heapsort.h>
static struct peano_hilbert_data
{
peanokey key;
int index;
}
*mp;
static int *Id;
void peano_hilbert_order(void)
{
int i;
if(ThisTask == 0)
printf("begin Peano-Hilbert order...\n");
if(N_gas)
{
mp = (struct peano_hilbert_data *) mymalloc(sizeof(struct peano_hilbert_data) * N_gas);
Id = (int *) mymalloc(sizeof(int) * N_gas);
for(i = 0; i < N_gas; i++)
{
mp[i].index = i;
mp[i].key = Key[i];
}
#ifdef MYSORT
mysort_peano(mp, N_gas, sizeof(struct peano_hilbert_data), peano_compare_key);
#else
qsort(mp, N_gas, sizeof(struct peano_hilbert_data), peano_compare_key);
#endif
for(i = 0; i < N_gas; i++)
Id[mp[i].index] = i;
reorder_gas();
myfree(Id);
myfree(mp);
}
if(NumPart - N_gas > 0)
{
mp = (struct peano_hilbert_data *) mymalloc(sizeof(struct peano_hilbert_data) * (NumPart - N_gas));
mp -= (N_gas);
Id = (int *) mymalloc(sizeof(int) * (NumPart - N_gas));
Id -= (N_gas);
for(i = N_gas; i < NumPart; i++)
{
mp[i].index = i;
mp[i].key = Key[i];
}
#ifdef MYSORT
mysort_peano(mp + N_gas, NumPart - N_gas, sizeof(struct peano_hilbert_data), peano_compare_key);
#else
qsort(mp + N_gas, NumPart - N_gas, sizeof(struct peano_hilbert_data), peano_compare_key);
#endif
for(i = N_gas; i < NumPart; i++)
Id[mp[i].index] = i;
reorder_particles();
Id += N_gas;
myfree(Id);
mp += N_gas;
myfree(mp);
}
if(ThisTask == 0)
printf("Peano-Hilbert done.\n");
}
int peano_compare_key(const void *a, const void *b)
{
if(((struct peano_hilbert_data *) a)->key < (((struct peano_hilbert_data *) b)->key))
return -1;
if(((struct peano_hilbert_data *) a)->key > (((struct peano_hilbert_data *) b)->key))
return +1;
return 0;
}
void reorder_gas(void)
{
int i;
struct particle_data Psave, Psource;
struct sph_particle_data SphPsave, SphPsource;
int idsource, idsave, dest;
for(i = 0; i < N_gas; i++)
{
if(Id[i] != i)
{
Psource = P[i];
SphPsource = SphP[i];
idsource = Id[i];
dest = Id[i];
do
{
Psave = P[dest];
SphPsave = SphP[dest];
idsave = Id[dest];
P[dest] = Psource;
SphP[dest] = SphPsource;
Id[dest] = idsource;
if(dest == i)
break;
Psource = Psave;
SphPsource = SphPsave;
idsource = idsave;
dest = idsource;
}
while(1);
}
}
}
void reorder_particles(void)
{
int i;
struct particle_data Psave, Psource;
int idsource, idsave, dest;
for(i = N_gas; i < NumPart; i++)
{
if(Id[i] != i)
{
Psource = P[i];
idsource = Id[i];
dest = Id[i];
do
{
Psave = P[dest];
idsave = Id[dest];
P[dest] = Psource;
Id[dest] = idsource;
#ifdef LT_STELLAREVOLUTION
if(P[dest].Type == 4)
MetP[P[dest].MetID].PID = dest;
#endif
if(dest == i)
break;
Psource = Psave;
idsource = idsave;
dest = idsource;
}
while(1);
}
}
}
/* The following rewrite of the original function
* peano_hilbert_key_old() has been written by MARTIN REINECKE.
* It is about a factor 2.3 - 2.5 faster than Volker's old routine!
*/
const unsigned char rottable3[48][8] = {
{36, 28, 25, 27, 10, 10, 25, 27},
{29, 11, 24, 24, 37, 11, 26, 26},
{8, 8, 25, 27, 30, 38, 25, 27},
{9, 39, 24, 24, 9, 31, 26, 26},
{40, 24, 44, 32, 40, 6, 44, 6},
{25, 7, 33, 7, 41, 41, 45, 45},
{4, 42, 4, 46, 26, 42, 34, 46},
{43, 43, 47, 47, 5, 27, 5, 35},
{33, 35, 36, 28, 33, 35, 2, 2},
{32, 32, 29, 3, 34, 34, 37, 3},
{33, 35, 0, 0, 33, 35, 30, 38},
{32, 32, 1, 39, 34, 34, 1, 31},
{24, 42, 32, 46, 14, 42, 14, 46},
{43, 43, 47, 47, 25, 15, 33, 15},
{40, 12, 44, 12, 40, 26, 44, 34},
{13, 27, 13, 35, 41, 41, 45, 45},
{28, 41, 28, 22, 38, 43, 38, 22},
{42, 40, 23, 23, 29, 39, 29, 39},
{41, 36, 20, 36, 43, 30, 20, 30},
{37, 31, 37, 31, 42, 40, 21, 21},
{28, 18, 28, 45, 38, 18, 38, 47},
{19, 19, 46, 44, 29, 39, 29, 39},
{16, 36, 45, 36, 16, 30, 47, 30},
{37, 31, 37, 31, 17, 17, 46, 44},
{12, 4, 1, 3, 34, 34, 1, 3},
{5, 35, 0, 0, 13, 35, 2, 2},
{32, 32, 1, 3, 6, 14, 1, 3},
{33, 15, 0, 0, 33, 7, 2, 2},
{16, 0, 20, 8, 16, 30, 20, 30},
{1, 31, 9, 31, 17, 17, 21, 21},
{28, 18, 28, 22, 2, 18, 10, 22},
{19, 19, 23, 23, 29, 3, 29, 11},
{9, 11, 12, 4, 9, 11, 26, 26},
{8, 8, 5, 27, 10, 10, 13, 27},
{9, 11, 24, 24, 9, 11, 6, 14},
{8, 8, 25, 15, 10, 10, 25, 7},
{0, 18, 8, 22, 38, 18, 38, 22},
{19, 19, 23, 23, 1, 39, 9, 39},
{16, 36, 20, 36, 16, 2, 20, 10},
{37, 3, 37, 11, 17, 17, 21, 21},
{4, 17, 4, 46, 14, 19, 14, 46},
{18, 16, 47, 47, 5, 15, 5, 15},
{17, 12, 44, 12, 19, 6, 44, 6},
{13, 7, 13, 7, 18, 16, 45, 45},
{4, 42, 4, 21, 14, 42, 14, 23},
{43, 43, 22, 20, 5, 15, 5, 15},
{40, 12, 21, 12, 40, 6, 23, 6},
{13, 7, 13, 7, 41, 41, 22, 20}
};
const unsigned char subpix3[48][8] = {
{0, 7, 1, 6, 3, 4, 2, 5},
{7, 4, 6, 5, 0, 3, 1, 2},
{4, 3, 5, 2, 7, 0, 6, 1},
{3, 0, 2, 1, 4, 7, 5, 6},
{1, 0, 6, 7, 2, 3, 5, 4},
{0, 3, 7, 4, 1, 2, 6, 5},
{3, 2, 4, 5, 0, 1, 7, 6},
{2, 1, 5, 6, 3, 0, 4, 7},
{6, 1, 7, 0, 5, 2, 4, 3},
{1, 2, 0, 3, 6, 5, 7, 4},
{2, 5, 3, 4, 1, 6, 0, 7},
{5, 6, 4, 7, 2, 1, 3, 0},
{7, 6, 0, 1, 4, 5, 3, 2},
{6, 5, 1, 2, 7, 4, 0, 3},
{5, 4, 2, 3, 6, 7, 1, 0},
{4, 7, 3, 0, 5, 6, 2, 1},
{6, 7, 5, 4, 1, 0, 2, 3},
{7, 0, 4, 3, 6, 1, 5, 2},
{0, 1, 3, 2, 7, 6, 4, 5},
{1, 6, 2, 5, 0, 7, 3, 4},
{2, 3, 1, 0, 5, 4, 6, 7},
{3, 4, 0, 7, 2, 5, 1, 6},
{4, 5, 7, 6, 3, 2, 0, 1},
{5, 2, 6, 1, 4, 3, 7, 0},
{7, 0, 6, 1, 4, 3, 5, 2},
{0, 3, 1, 2, 7, 4, 6, 5},
{3, 4, 2, 5, 0, 7, 1, 6},
{4, 7, 5, 6, 3, 0, 2, 1},
{6, 7, 1, 0, 5, 4, 2, 3},
{7, 4, 0, 3, 6, 5, 1, 2},
{4, 5, 3, 2, 7, 6, 0, 1},
{5, 6, 2, 1, 4, 7, 3, 0},
{1, 6, 0, 7, 2, 5, 3, 4},
{6, 5, 7, 4, 1, 2, 0, 3},
{5, 2, 4, 3, 6, 1, 7, 0},
{2, 1, 3, 0, 5, 6, 4, 7},
{0, 1, 7, 6, 3, 2, 4, 5},
{1, 2, 6, 5, 0, 3, 7, 4},
{2, 3, 5, 4, 1, 0, 6, 7},
{3, 0, 4, 7, 2, 1, 5, 6},
{1, 0, 2, 3, 6, 7, 5, 4},
{0, 7, 3, 4, 1, 6, 2, 5},
{7, 6, 4, 5, 0, 1, 3, 2},
{6, 1, 5, 2, 7, 0, 4, 3},
{5, 4, 6, 7, 2, 3, 1, 0},
{4, 3, 7, 0, 5, 2, 6, 1},
{3, 2, 0, 1, 4, 5, 7, 6},
{2, 5, 1, 6, 3, 4, 0, 7}
};
/*! This function computes a Peano-Hilbert key for an integer triplet (x,y,z),
* with x,y,z in the range between 0 and 2^bits-1.
*/
peanokey peano_hilbert_key(int x, int y, int z, int bits)
{
int mask;
unsigned char rotation = 0;
peanokey key = 0;
for(mask = 1 << (bits - 1); mask > 0; mask >>= 1)
{
unsigned char pix = ((x & mask) ? 4 : 0) | ((y & mask) ? 2 : 0) | ((z & mask) ? 1 : 0);
key <<= 3;
key |= subpix3[rotation][pix];
rotation = rottable3[rotation][pix];
}
return key;
}
peanokey morton_key(int x, int y, int z, int bits)
{
int mask;
peanokey morton = 0;
for(mask = 1 << (bits - 1); mask > 0; mask >>= 1)
{
morton <<= 3;
morton += ((z & mask) ? 4 : 0) + ((y & mask) ? 2 : 0) + ((x & mask) ? 1 : 0);
}
return morton;
}
peanokey peano_and_morton_key(int x, int y, int z, int bits, peanokey * morton_key)
{
int mask;
unsigned char rotation = 0;
peanokey key = 0;
peanokey morton = 0;
for(mask = 1 << (bits - 1); mask > 0; mask >>= 1)
{
unsigned char pix = ((x & mask) ? 4 : 0) | ((y & mask) ? 2 : 0) | ((z & mask) ? 1 : 0);
key <<= 3;
key |= subpix3[rotation][pix];
rotation = rottable3[rotation][pix];
morton <<= 3;
morton += ((z & mask) ? 4 : 0) + ((y & mask) ? 2 : 0) + ((x & mask) ? 1 : 0);
}
*morton_key = morton;
return key;
}
static int quadrants[24][2][2][2] = {
/* rotx=0, roty=0-3 */
{{{0, 7}, {1, 6}}, {{3, 4}, {2, 5}}},
{{{7, 4}, {6, 5}}, {{0, 3}, {1, 2}}},
{{{4, 3}, {5, 2}}, {{7, 0}, {6, 1}}},
{{{3, 0}, {2, 1}}, {{4, 7}, {5, 6}}},
/* rotx=1, roty=0-3 */
{{{1, 0}, {6, 7}}, {{2, 3}, {5, 4}}},
{{{0, 3}, {7, 4}}, {{1, 2}, {6, 5}}},
{{{3, 2}, {4, 5}}, {{0, 1}, {7, 6}}},
{{{2, 1}, {5, 6}}, {{3, 0}, {4, 7}}},
/* rotx=2, roty=0-3 */
{{{6, 1}, {7, 0}}, {{5, 2}, {4, 3}}},
{{{1, 2}, {0, 3}}, {{6, 5}, {7, 4}}},
{{{2, 5}, {3, 4}}, {{1, 6}, {0, 7}}},
{{{5, 6}, {4, 7}}, {{2, 1}, {3, 0}}},
/* rotx=3, roty=0-3 */
{{{7, 6}, {0, 1}}, {{4, 5}, {3, 2}}},
{{{6, 5}, {1, 2}}, {{7, 4}, {0, 3}}},
{{{5, 4}, {2, 3}}, {{6, 7}, {1, 0}}},
{{{4, 7}, {3, 0}}, {{5, 6}, {2, 1}}},
/* rotx=4, roty=0-3 */
{{{6, 7}, {5, 4}}, {{1, 0}, {2, 3}}},
{{{7, 0}, {4, 3}}, {{6, 1}, {5, 2}}},
{{{0, 1}, {3, 2}}, {{7, 6}, {4, 5}}},
{{{1, 6}, {2, 5}}, {{0, 7}, {3, 4}}},
/* rotx=5, roty=0-3 */
{{{2, 3}, {1, 0}}, {{5, 4}, {6, 7}}},
{{{3, 4}, {0, 7}}, {{2, 5}, {1, 6}}},
{{{4, 5}, {7, 6}}, {{3, 2}, {0, 1}}},
{{{5, 2}, {6, 1}}, {{4, 3}, {7, 0}}}
};
static int rotxmap_table[24] = { 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 0, 1, 2, 3, 17, 18, 19, 16, 23, 20, 21, 22
};
static int rotymap_table[24] = { 1, 2, 3, 0, 16, 17, 18, 19,
11, 8, 9, 10, 22, 23, 20, 21, 14, 15, 12, 13, 4, 5, 6, 7
};
static int rotx_table[8] = { 3, 0, 0, 2, 2, 0, 0, 1 };
static int roty_table[8] = { 0, 1, 1, 2, 2, 3, 3, 0 };
static int sense_table[8] = { -1, -1, -1, +1, +1, -1, -1, -1 };
peanokey peano_hilbert_key_old(int x, int y, int z, int bits)
{
int i, quad, bitx, bity, bitz;
int mask, rotation, rotx, roty, sense;
peanokey key;
mask = 1 << (bits - 1);
key = 0;
rotation = 0;
sense = 1;
for(i = 0; i < bits; i++, mask >>= 1)
{
bitx = (x & mask) ? 1 : 0;
bity = (y & mask) ? 1 : 0;
bitz = (z & mask) ? 1 : 0;
quad = quadrants[rotation][bitx][bity][bitz];
key <<= 3;
key += (sense == 1) ? (quad) : (7 - quad);
rotx = rotx_table[quad];
roty = roty_table[quad];
sense *= sense_table[quad];
while(rotx > 0)
{
rotation = rotxmap_table[rotation];
rotx--;
}
while(roty > 0)
{
rotation = rotymap_table[rotation];
roty--;
}
}
return key;
}
peanokey peano_and_morton_key_old(int x, int y, int z, int bits, peanokey * morton_key)
{
int i, quad, bitx, bity, bitz;
int mask, rotation, rotx, roty, sense;
peanokey key, morton;
mask = 1 << (bits - 1);
key = 0;
rotation = 0;
sense = 1;
morton = 0;
for(i = 0; i < bits; i++, mask >>= 1)
{
bitx = (x & mask) ? 1 : 0;
bity = (y & mask) ? 1 : 0;
bitz = (z & mask) ? 1 : 0;
quad = quadrants[rotation][bitx][bity][bitz];
key <<= 3;
key += (sense == 1) ? (quad) : (7 - quad);
rotx = rotx_table[quad];
roty = roty_table[quad];
sense *= sense_table[quad];
while(rotx > 0)
{
rotation = rotxmap_table[rotation];
rotx--;
}
while(roty > 0)
{
rotation = rotymap_table[rotation];
roty--;
}
morton <<= 3;
morton += (bitz << 2) + (bity << 1) + bitx;
}
*morton_key = morton;
return key;
}
peanokey morton_key_old(int x, int y, int z, int bits)
{
int i, bitx, bity, bitz;
int mask;
peanokey morton;
mask = 1 << (bits - 1);
morton = 0;
for(i = 0; i < bits; i++, mask >>= 1)
{
bitx = (x & mask) ? 1 : 0;
bity = (y & mask) ? 1 : 0;
bitz = (z & mask) ? 1 : 0;
morton <<= 3;
morton += (bitz << 2) + (bity << 1) + bitx;
}
return morton;
}
static void msort_peano_with_tmp(struct peano_hilbert_data *b, size_t n, struct peano_hilbert_data *t)
{
struct peano_hilbert_data *tmp;
struct peano_hilbert_data *b1, *b2;
size_t n1, n2;
if(n <= 1)
return;
n1 = n / 2;
n2 = n - n1;
b1 = b;
b2 = b + n1;
msort_peano_with_tmp(b1, n1, t);
msort_peano_with_tmp(b2, n2, t);
tmp = t;
while(n1 > 0 && n2 > 0)
{
if(b1->key <= b2->key)
{
--n1;
*tmp++ = *b1++;
}
else
{
--n2;
*tmp++ = *b2++;
}
}
if(n1 > 0)
memcpy(tmp, b1, n1 * sizeof(struct peano_hilbert_data));
memcpy(b, t, (n - n2) * sizeof(struct peano_hilbert_data));
}
void mysort_peano(void *b, size_t n, size_t s, int (*cmp) (const void *, const void *))
{
const size_t size = n * s;
struct peano_hilbert_data *tmp = (struct peano_hilbert_data *) mymalloc(size);
msort_peano_with_tmp((struct peano_hilbert_data *) b, n, tmp);
myfree(tmp);
}
| {
"alphanum_fraction": 0.474176527,
"avg_line_length": 21.6401384083,
"ext": "c",
"hexsha": "903be2b2dc2dcb4b97a382d7ed7dc510b1ae554c",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "egpbos/egp",
"max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/peano.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "egpbos/egp",
"max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/peano.c",
"max_line_length": 105,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "egpbos/egp",
"max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/peano.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6184,
"size": 12508
} |
/* randist/lognormal.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* The lognormal distribution has the form
p(x) dx = 1/(x * sqrt(2 pi sigma^2)) exp(-(ln(x) - zeta)^2/2 sigma^2) dx
for x > 0. Lognormal random numbers are the exponentials of
gaussian random numbers */
double
gsl_ran_lognormal (const gsl_rng * r, const double zeta, const double sigma)
{
double u, v, r2, normal, z;
do
{
/* choose x,y in uniform square (-1,-1) to (+1,+1) */
u = -1 + 2 * gsl_rng_uniform (r);
v = -1 + 2 * gsl_rng_uniform (r);
/* see if it is in the unit circle */
r2 = u * u + v * v;
}
while (r2 > 1.0 || r2 == 0);
normal = u * sqrt (-2.0 * log (r2) / r2);
z = exp (sigma * normal + zeta);
return z;
}
double
gsl_ran_lognormal_pdf (const double x, const double zeta, const double sigma)
{
if (x <= 0)
{
return 0 ;
}
else
{
double u = (log (x) - zeta)/sigma;
double p = 1 / (x * fabs(sigma) * sqrt (2 * M_PI)) * exp (-(u * u) /2);
return p;
}
}
| {
"alphanum_fraction": 0.6358441558,
"avg_line_length": 27.1126760563,
"ext": "c",
"hexsha": "2dc215ae96c729144138383aba6c27510ef56436",
"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/lognormal.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/lognormal.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/lognormal.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": 587,
"size": 1925
} |
/*
* Copyright (c) 2010-2018 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2013 Inria. All rights reserved.
*
* @precisions normal z -> c d s
*
*/
#include <lapacke.h>
#include "dplasma.h"
#include "dplasmatypes.h"
#include "map2.h"
static int
dplasma_zlacpy_trim_operator( parsec_execution_stream_t *es,
const parsec_tiled_matrix_dc_t *descA,
const parsec_tiled_matrix_dc_t *descB,
const void *_A, void *_B,
PLASMA_enum uplo, int m, int n,
void *args )
{
int tempmm, tempnn, ldam, ldbm;
const parsec_complex64_t *A = (const parsec_complex64_t*)_A;
parsec_complex64_t *B = (parsec_complex64_t*)_B;
(void)es;
(void)args;
(void)uplo;
tempmm = ((m)==((descB->mt)-1)) ? ((descB->m)-(m*(descB->mb))) : (descB->mb);
tempnn = ((n)==((descB->nt)-1)) ? ((descB->n)-(n*(descB->nb))) : (descB->nb);
ldam = BLKLDD( descA, m );
ldbm = BLKLDD( descB, m );
LAPACKE_zlacpy_work(
LAPACK_COL_MAJOR, lapack_const( PlasmaUpperLower ), tempmm, tempnn, A, ldam, B, ldbm);
return 0;
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zlacpy_New - Generates an object that performs a copy of the matrix A
* into the matrix B.
*
* See dplasma_map2_New() for further information.
*
* WARNING: The computations are not done by this call.
*
*******************************************************************************
*
* @param[in] uplo
* Specifies which part of matrix A is copied:
* = PlasmaUpperLower: All matrix is referenced.
* = PlasmaUpper: Only upper part is refrenced.
* = PlasmaLower: Only lower part is referenced.
*
* @param[in] A
* Descriptor of the distributed original matrix A. Any tiled matrix
* descriptor can be used. However, if the data is stored in column
* major, the tile distribution must match the one of the matrix B.
*
* @param[in,out] B
* Descriptor of the distributed destination matrix B. Any tiled matrix
* descriptor can be used, with no specific storage.
*
*******************************************************************************
*
* @return
* \retval NULL if incorrect parameters are given.
* \retval The PaRSEC object describing the operation that can be
* enqueued in the runtime. It, then, needs to be
* destroy with the corresponding _destruct function.
*
*******************************************************************************
*
* @sa dplasma_zlacpy
* @sa dplasma_zlacpy_Destruct
* @sa dplasma_clacpy_New
* @sa dplasma_dlacpy_New
* @sa dplasma_slacpy_New
*
******************************************************************************/
parsec_taskpool_t*
dplasma_zlacpy_trim_New( PLASMA_enum uplo,
const parsec_tiled_matrix_dc_t *A,
parsec_tiled_matrix_dc_t *B)
{
parsec_taskpool_t* tp;
tp = dplasma_map2_New(uplo, PlasmaNoTrans, A, B,
dplasma_zlacpy_trim_operator, NULL );
return tp;
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zlacpy_Destruct - Free the data structure associated to an object
* created with dplasma_zlacpy_New().
*
*******************************************************************************
*
* @param[in,out] o
* On entry, the object to destroy.
* On exit, the object cannot be used anymore.
*
*******************************************************************************
*
* @sa dplasma_zlacpy_New
* @sa dplasma_zlacpy
*
******************************************************************************/
void
dplasma_zlacpy_trim_Destruct( parsec_taskpool_t *tp )
{
parsec_taskpool_free(tp);
}
/**
*******************************************************************************
*
* @ingroup dplasma_complex64
*
* dplasma_zlacpy - Generates an object that performs a copy of the matrix A
* into the matrix B.
*
* See dplasma_map2() for further information.
*
*******************************************************************************
*
* @param[in,out] dague
* The dague context of the application that will run the operation.
*
* @param[in] uplo
* Specifies which part of matrix A is copied:
* = PlasmaUpperLower: All matrix is referenced.
* = PlasmaUpper: Only upper part is refrenced.
* = PlasmaLower: Only lower part is referenced.
*
* @param[in] A
* Descriptor of the distributed original matrix A. Any tiled matrix
* descriptor can be used. However, if the data is stored in column
* major, the tile distribution must match the one of the matrix B.
*
* @param[in,out] B
* Descriptor of the distributed destination matrix B. Any tiled matrix
* descriptor can be used, with no specific storage.
*
*******************************************************************************
*
* @return
* \retval -i if the ith parameters is incorrect.
* \retval 0 on success.
*
*******************************************************************************
*
* @sa dplasma_zlacpy_New
* @sa dplasma_zlacpy_Destruct
* @sa dplasma_clacpy
* @sa dplasma_dlacpy
* @sa dplasma_slacpy
*
******************************************************************************/
int
dplasma_zlacpy_trim( parsec_context_t *parsec,
PLASMA_enum uplo,
const parsec_tiled_matrix_dc_t *A,
parsec_tiled_matrix_dc_t *B)
{
parsec_taskpool_t *parsec_zlacpy_trim = NULL;
if ((uplo != PlasmaUpperLower) &&
(uplo != PlasmaUpper) &&
(uplo != PlasmaLower))
{
dplasma_error("dplasma_zlacpy_trim", "illegal value of uplo");
return -2;
}
parsec_zlacpy_trim = dplasma_zlacpy_trim_New(uplo, A, B);
if ( parsec_zlacpy_trim != NULL )
{
parsec_context_add_taskpool(parsec, parsec_zlacpy_trim);
dplasma_wait_until_completion(parsec);
dplasma_zlacpy_trim_Destruct( parsec_zlacpy_trim );
}
return 0;
}
| {
"alphanum_fraction": 0.5146386093,
"avg_line_length": 32.9547738693,
"ext": "c",
"hexsha": "e951bc25eb5ba2111c94df4baa6e46ed895b9765",
"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": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "NLAFET/ABFT",
"max_forks_repo_path": "dplasma/lib/zlacpy_trim_wrapper.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "NLAFET/ABFT",
"max_issues_repo_path": "dplasma/lib/zlacpy_trim_wrapper.c",
"max_line_length": 94,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "NLAFET/ABFT",
"max_stars_repo_path": "dplasma/lib/zlacpy_trim_wrapper.c",
"max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z",
"num_tokens": 1492,
"size": 6558
} |
/***************************************************************************
* Copyright (C) 2008 by Regis Behmo,,, *
* regis.behmo@ecp.fr *
* *
* 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. *
***************************************************************************/
#ifndef _MPLSH_FIT_TUNE_H_INCLUDED_
#define _MPLSH_FIT_TUNE_H_INCLUDED_
#include <lshkit.h>
#include <lshkit/matrix.h>
#include <lshkit/tune.h>
#include <cstdlib>
#include <gsl/gsl_multifit.h>
#include <boost/program_options.hpp>
#include <boost/progress.hpp>
bool is_good_value (double v);
bool constraint (const lshkit::tune::Input &x);
double mplsh_tune(const double& param_M, const double& param_G,
const double& param_a_M, const double& param_b_M, const double& param_c_M,
const double& param_a_G, const double& param_b_G, const double& param_c_G,
int N, int K, int L, int T, int& M, float& W, float R );
template<class DATA, class METRIC>
void mplsh_fit( const DATA& data, const METRIC& metric, int NN, double& param_M, double& param_G,
double& param_a_M, double& param_b_M, double& param_c_M,
double& param_a_G, double& param_b_G, double& param_c_G )
{
// Parameters
unsigned N, P, Q, K, F;
N = 0;// # points
P = 50000;// number of pairs to sample
Q = 1000;// number of queries to sample
K = NN;// search for K nearest neighbors
F = 10;// divide the sample to F folds
std::vector<unsigned> idx(data.getSize());
for (unsigned i = 0; i < idx.size(); ++i) idx[i] = i;
random_shuffle(idx.begin(), idx.end());
if (N > 0 && N < data.getSize()) idx.resize(N);
lshkit::DefaultRng rng;
rng.seed(0);//plant the same seed, always
boost::variate_generator<lshkit::DefaultRng &, lshkit::UniformUnsigned> gen(rng, lshkit::UniformUnsigned(0, idx.size()-1));
double gM = 0.0;
double gG = 0.0;
{
// sample P pairs of points
for (unsigned k = 0; k < P; ++k)
{
double dist, logdist;
for (;;)
{
unsigned i = gen();
unsigned j = gen();
if (i == j) continue;
dist = metric( data[idx[i]], data[idx[j]] );
logdist = log(dist);
if (is_good_value(logdist)) break;
}
gM += dist;
gG += logdist;
}
gM /= P;
gG /= P;
gG = exp(gG);
}
// TODO check that
// Custom
Q = (idx.size() > 1000)? 1000 : idx.size();// Added
// TODO check that
// Supprime
//if (Q > idx.size()) Q = idx.size();
//if (K > idx.size() - Q) K = idx.size() - Q;
/* sample query */
std::vector<unsigned> qry(Q);
lshkit::SampleQueries(&qry, idx.size(), rng);
/* do the queries */
std::vector<lshkit::Topk<unsigned> > topks(Q);
for (unsigned i = 0; i < Q; ++i) topks[i].reset(K);
/* ... */
gsl_matrix *X = gsl_matrix_alloc(F * K, 3);
gsl_vector *yM = gsl_vector_alloc(F * K);
gsl_vector *yG = gsl_vector_alloc(F * K);
gsl_vector *pM = gsl_vector_alloc(3);
gsl_vector *pG = gsl_vector_alloc(3);
gsl_matrix *cov = gsl_matrix_alloc(3,3);
std::vector<double> M(K);
std::vector<double> G(K);
boost::progress_display progress(F, std::cerr);
unsigned m = 0;
for (unsigned l = 0; l < F; l++)
{
// Scan
for (unsigned i = l; i< idx.size(); i += F)
{
for (unsigned j = 0; j < Q; j++)
{
int id = qry[j];
if (i != id)
{
float d = metric( data[idx[id]], data[idx[i]] );
if (is_good_value(log(double(d)))) topks[j] << lshkit::Topk<unsigned>::Element(i, d);
}
}
}
std::fill(M.begin(), M.end(), 0.0);
std::fill(G.begin(), G.end(), 0.0);
for (unsigned i = 0; i < Q; i++)
{
for (unsigned k = 0; k < K; k++)
{
M[k] += topks[i][k].dist;
G[k] += log(topks[i][k].dist);
}
}
for (unsigned k = 0; k < K; k++)
{
M[k] = log(M[k]/Q);
G[k] /= Q;
gsl_matrix_set(X, m, 0, 1.0);
gsl_matrix_set(X, m, 1, log(double(data.getSize() * (l + 1)) / double(F)));
gsl_matrix_set(X, m, 2, log(double(k + 1)));
gsl_vector_set(yM, m, M[k]);
gsl_vector_set(yG, m, G[k]);
++m;
}
++progress;
}
gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc(F * K, 3);
double chisq;
gsl_multifit_linear(X, yM, pM, cov, &chisq, work);
gsl_multifit_linear(X, yG, pG, cov, &chisq, work);
param_M = gM;
param_G = gG;
param_a_M = gsl_vector_get(pM, 0);
param_b_M = gsl_vector_get(pM, 1);
param_c_M = gsl_vector_get(pM, 2);
param_a_G = gsl_vector_get(pG, 0);
param_b_G = gsl_vector_get(pG, 1);
param_c_G = gsl_vector_get(pG, 2);
gsl_matrix_free(X);
gsl_matrix_free(cov);
gsl_vector_free(pM);
gsl_vector_free(pG);
gsl_vector_free(yM);
gsl_vector_free(yG);
}
template<class DATA, class METRIC>
double mplsh_fit_tune( const DATA& data, const METRIC& metric, const int& L, const int& T, int& M, float& W, float R = 0.8, int K = 1 )
{
/** ***************************/
/** ********** FIT ***********/
/** ***************************/
std::cout << "Fitting..." << std::endl;
double param_M, param_G, param_a_M, param_b_M, param_c_M, param_a_G, param_b_G, param_c_G;
mplsh_fit( data, metric, K, param_M, param_G, param_a_M, param_b_M, param_c_M, param_a_G, param_b_G, param_c_G );
std::cout << param_M << " " << param_G << std::endl;
std::cout << param_a_M << " " << param_b_M << " " << param_c_M << std::endl;
std::cout << param_a_G << " " << param_b_G << " " << param_c_G << std::endl;
/** ***************************/
/** ********** TUNE ***********/
/** ***************************/
std::cout << "Tuning..." << std::endl;
double cost = mplsh_tune(param_M, param_G, param_a_M, param_b_M, param_c_M, param_a_G, param_b_G, param_c_G,
data.getSize(), K, L, T, M, W, R );
std::cout << "L = " << L;
std::cout << " " << "T = " << T;
std::cout << " " << "M = " << M;
std::cout << " " << "W = " << W;
std::cout << " " << "R = " << R;
std::cout << " " << "M = " << M;
std::cout << std::endl;
return cost;
}
#endif
| {
"alphanum_fraction": 0.5537677234,
"avg_line_length": 30.033492823,
"ext": "h",
"hexsha": "f148348df34e5c2f2be8e9d2144330627aa35de4",
"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": "c77186ef123505c7e2065dcde05d8b699d6a93d9",
"max_forks_repo_licenses": [
"Naumen",
"Condor-1.1",
"MS-PL"
],
"max_forks_repo_name": "ocallaco/LuaSHkit",
"max_forks_repo_path": "lshkit/mplsh-fit-tune.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c77186ef123505c7e2065dcde05d8b699d6a93d9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Naumen",
"Condor-1.1",
"MS-PL"
],
"max_issues_repo_name": "ocallaco/LuaSHkit",
"max_issues_repo_path": "lshkit/mplsh-fit-tune.h",
"max_line_length": 135,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "c77186ef123505c7e2065dcde05d8b699d6a93d9",
"max_stars_repo_licenses": [
"Naumen",
"Condor-1.1",
"MS-PL"
],
"max_stars_repo_name": "ocallaco/LuaSHkit",
"max_stars_repo_path": "lshkit/mplsh-fit-tune.h",
"max_stars_repo_stars_event_max_datetime": "2019-06-09T21:48:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-02T21:07:37.000Z",
"num_tokens": 1992,
"size": 6277
} |
/*
* Copyright 2017 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 the ATLAS headers */
extern "C"
{
#include <cblas.h>
}
/* choose precision to train and classify. Only float and double are
* currently suppored
*/
typedef float floatType_t;
/* macro to convert 2d coords to 1d offset */
#define INDX(row,col,ld) (((col) * (ld)) + (row))
inline float sigmoid_f( float z )
{
return 1.0f / ( 1.0f + expf( -z ) );
} /* end sigmoid_f */
inline double sigmoid( double z )
{
return 1.0 / ( 1.0 + exp( -z ) );
} /* end sigmoid */
inline float sigmoidGradient_f( float z )
{
float temp = sigmoid_f( z );
return temp * ( 1.0f - temp );
} /* end sigGrad_f */
inline double sigmoidGradient( double z )
{
double temp = sigmoid( z );
return temp * ( 1.0 - temp );
} /* end sigGrad_f */
/* hardcoded constants for training and test set size and feature
* vector size
*/
#define FEATURE_VECTOR_SIZE (784)
#define TRAINING_SET_SIZE (60000)
#define TEST_SET_SIZE (10000)
#define HIDDEN_LAYER_SIZE (25)
#define NUM_OUTPUT_CLASSES (10)
/* CUDA debugging */
#ifdef DEBUG
#define CUDA_CALL(F) if( (F) != cudaSuccess ) \
{printf("Error %s at %s:%d\n", cudaGetErrorString(cudaGetLastError()), \
__FILE__,__LINE__); exit(-1);}
#define CUDA_CHECK() if( (cudaPeekAtLastError()) != cudaSuccess ) \
{printf("Error %s at %s:%d\n", cudaGetErrorString(cudaGetLastError()), \
__FILE__,__LINE__-1); exit(-1);}
#else
#define CUDA_CALL(F) (F)
#define CUDA_CHECK()
#endif
/* function defs */
void readMatrixFromFile( char *, float *, const int, const int, const int );
void readCommandLineArgs( int, char *[], float *, int *, int *, int *);
void calcGradient( floatType_t *X,
int const XRows,
int const XCols,
floatType_t const *theta1,
int const theta1Rows,
int const theta1Cols,
floatType_t const *theta2,
int const theta2Rows,
int const theta2Cols,
floatType_t const *Y,
floatType_t *cost,
floatType_t *theta1Grad,
floatType_t *theta2Grad,
floatType_t *tempMatrix );
void predict( floatType_t *X,
int const XRows,
int const XCols,
floatType_t const *theta1,
int const theta1Rows,
int const theta1Cols,
floatType_t const *theta2,
int const theta2Rows,
int const theta2Cols,
int *predictVector);
void trainNetwork( floatType_t *X,
int const XRows,
int const XCols,
floatType_t *theta1,
int const theta1Rows,
int const theta1Cols,
floatType_t *theta2,
int const theta2Rows,
int const theta2Cols,
floatType_t const *Y,
float const learningRate,
int const iterations,
int const batchSize );
| {
"alphanum_fraction": 0.5608438384,
"avg_line_length": 31.6016260163,
"ext": "h",
"hexsha": "86bb75b5bf349e13d171a8926fee898a36b092a7",
"lang": "C",
"max_forks_count": 22,
"max_forks_repo_forks_event_max_datetime": "2021-05-08T13:45:44.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-04-23T20:20:50.000Z",
"max_forks_repo_head_hexsha": "5f53bff53d8ed39e9b7100a2e73a243f0a181af6",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "syzeng999/gpu-edu-workshops",
"max_forks_repo_path": "exercises/cuda/nn/cpu/headers.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "5f53bff53d8ed39e9b7100a2e73a243f0a181af6",
"max_issues_repo_issues_event_max_datetime": "2017-02-22T21:46:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-02-22T21:46:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "syzeng999/gpu-edu-workshops",
"max_issues_repo_path": "exercises/cuda/nn/cpu/headers.h",
"max_line_length": 76,
"max_stars_count": 39,
"max_stars_repo_head_hexsha": "5f53bff53d8ed39e9b7100a2e73a243f0a181af6",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "jnbntz/gpu-edu-workshops",
"max_stars_repo_path": "exercises/cuda/nn/cpu/headers.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-08T07:41:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-16T21:15:49.000Z",
"num_tokens": 881,
"size": 3887
} |
/*
ODE: a program to get optime Runge-Kutta and multi-steps methods.
Copyright 2011-2019, Javier Burguete Tolosa.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file utils.c
* \brief Source file with util functions.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2011-2019.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <math.h>
#include <libxml/parser.h>
#include <glib.h>
#include <libintl.h>
#include <gsl/gsl_rng.h>
#include "config.h"
#include "utils.h"
gchar *error_message = NULL; ///< error message string.
/**
* Function to print an error message.
*/
void
show_error (const char *message) ///< error message string.
{
printf ("%s\n%s\n", _("ERROR!"), message);
}
/**
* Function to get an integer number of a XML node property.
*
* \return Integer number value.
*/
int
xml_node_get_int (xmlNode * node, ///< XML node.
const xmlChar * prop, ///< XML property.
int *error_code) ///< Error code.
{
int i = 0;
xmlChar *buffer;
buffer = xmlGetProp (node, prop);
if (!buffer)
*error_code = 1;
else
{
if (sscanf ((char *) buffer, "%d", &i) != 1)
*error_code = 2;
else
*error_code = 0;
xmlFree (buffer);
}
return i;
}
/**
* Function to get an unsigned integer number of a XML node property.
*
* \return Unsigned integer number value.
*/
unsigned int
xml_node_get_uint (xmlNode * node, ///< XML node.
const xmlChar * prop, ///< XML property.
int *error_code) ///< Error code.
{
unsigned int i = 0;
xmlChar *buffer;
buffer = xmlGetProp (node, prop);
if (!buffer)
*error_code = 1;
else
{
if (sscanf ((char *) buffer, "%u", &i) != 1)
*error_code = 2;
else
*error_code = 0;
xmlFree (buffer);
}
return i;
}
/**
* Function to get an unsigned integer number of a XML node property with a
* default value.
*
* \return Unsigned integer number value.
*/
unsigned int
xml_node_get_uint_with_default (xmlNode * node, ///< XML node.
const xmlChar * prop, ///< XML property.
unsigned int default_value,
///< default value.
int *error_code) ///< Error code.
{
unsigned int i;
if (xmlHasProp (node, prop))
i = xml_node_get_uint (node, prop, error_code);
else
{
i = default_value;
*error_code = 0;
}
return i;
}
/**
* Function to get an long double number of a XML node property.
*
* \return Long double number value.
*/
long double
xml_node_get_float (xmlNode * node, ///< XML node.
const xmlChar * prop, ///< XML property.
int *error_code) ///< Error code.
{
long double x = 0.L;
xmlChar *buffer;
buffer = xmlGetProp (node, prop);
if (!buffer)
*error_code = 1;
else
{
if (sscanf ((char *) buffer, "%Lg", &x) != 1)
*error_code = 2;
else
*error_code = 0;
xmlFree (buffer);
}
return x;
}
/**
* Function to read the minimum, the interval and the random function type of a
* variable on a XML node.
*
* \return 1 on success, 0 on error.
*/
int
read_variable (xmlNode * node, ///< XML node.
long double *minimum, ///< minimum value.
long double *interval, ///< interval value.
unsigned int *type, ///< random function type.
unsigned int n) ///< variable number.
{
char number[16];
gchar *buffer;
xmlChar *prop;
int code;
if (!node)
{
error_message = g_strdup (_("No XML node"));
goto exit_on_error;
}
if (xmlStrcmp (node->name, XML_VARIABLE))
{
error_message = g_strdup (_("Bad XML node"));
goto exit_on_error;
}
minimum[n] = xml_node_get_float (node, XML_MINIMUM, &code);
if (code)
{
error_message = g_strdup (_("Bad minimum"));
goto exit_on_error;
}
interval[n] = xml_node_get_float (node, XML_INTERVAL, &code);
if (code)
{
error_message = g_strdup (_("Bad interval"));
goto exit_on_error;
}
prop = xmlGetProp (node, XML_TYPE);
if (!prop || !xmlStrcmp (prop, XML_RANDOM))
type[n] = RANDOM_TYPE_UNIFORM;
else if (!xmlStrcmp (prop, XML_BOTTOM))
type[n] = RANDOM_TYPE_BOTTOM;
else if (!xmlStrcmp (prop, XML_EXTREME))
type[n] = RANDOM_TYPE_EXTREME;
else if (!xmlStrcmp (prop, XML_TOP))
type[n] = RANDOM_TYPE_TOP;
else if (!xmlStrcmp (prop, XML_REGULAR))
type[n] = RANDOM_TYPE_REGULAR;
else if (!xmlStrcmp (prop, XML_ORTHOGONAL))
type[n] = RANDOM_TYPE_ORTHOGONAL;
else
{
xmlFree (prop);
error_message = g_strdup (_("Bad random type function"));
goto exit_on_error;
}
xmlFree (prop);
return 1;
exit_on_error:
snprintf (number, 16, "%u", n + 1);
buffer = error_message;
error_message
= g_strconcat (_("Variable"), " ", number, ":\n", error_message, NULL);
g_free (buffer);
return 0;
}
/**
* Function to set the precision in a maxima program file.
*/
void
print_maxima_precision (FILE * file) ///< maxima program file.
{
fprintf (file, "fpprec:%u;\nfpprintprec:fpprec;\n", MAXIMA_PRECISION);
}
| {
"alphanum_fraction": 0.6281577326,
"avg_line_length": 27.5084745763,
"ext": "c",
"hexsha": "94e2fc5d13dbc0950cb3267527be911308039fe8",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/ode",
"max_forks_repo_path": "utils.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "jburguete/ode",
"max_issues_repo_path": "utils.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/ode",
"max_stars_repo_path": "utils.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1659,
"size": 6492
} |
// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-
/*
* Copyright (C) 2009 RobotCub Consortium
* Author: Alessandro Scalzo alessandro.scalzo@iit.it
* CopyPolicy: Released under the terms of the GNU GPL v2.0.
*
*/
#include <gsl/gsl_math.h>
#include <memory.h>
#include <stdio.h>
#ifndef __ALE_TOUCHSENSOR_H__
#define __ALE_TOUCHSENSOR_H__
#define MAX_TAXELS 128
class TouchSensor
{
bool calibrated_skin;
public:
void setColor(unsigned char r, unsigned char g, unsigned char b)
{
R_MAX = r;
G_MAX = g;
B_MAX = b;
}
void setCalibrationFlag (bool use_calibrated_skin)
{
calibrated_skin=use_calibrated_skin;
}
void resize(int width,int height,int margin)
{
if (3*margin>=width || 3*margin>=height) margin=0;
double scaleX=double(width -2*margin)/(dXmax-dXmin);
double scaleY=double(height-2*margin)/(dYmax-dYmin);
double scale=scaleX<scaleY?scaleX:scaleY;
m_Radius=m_RadiusOrig*scale;
m_maxRangeLight=int(m_Radius);
double dXmid=0.5*(dXmin+dXmax);
double dYmid=0.5*(dYmin+dYmax);
int w2=width /2;
int h2=height/2;
for (int i=0; i<nTaxels; ++i)
{
x[i]=w2+int(scale*(dX[i]-dXmid));
y[i]=h2+int(scale*(dY[i]-dYmid));
}
for (int i=0; i<nVerts; ++i)
{
xv[i]=w2+int(scale*(dXv[i]-dXmid));
yv[i]=h2+int(scale*(dYv[i]-dYmid));
}
double sigma=0.5*5.55*scale;
int maxRange=int(2.5*sigma);
if (maxRange!=m_maxRange)
{
m_maxRange=maxRange;
delete [] Exponential;
Exponential=new double[maxRange];
double k=-0.5/(sigma*sigma);
for (int x=0; x<maxRange; ++x)
{
Exponential[x]=exp(k*double(x*x));
}
}
xMin=w2+int(scale*(dXc-dXmid-15.0))-maxRange;
xMax=w2+int(scale*(dXc-dXmid+15.0))+maxRange;
yMin=h2+int(scale*(dYc-dYmid-15.0))-maxRange;
yMax=h2+int(scale*(dYc-dYmid+15.0))+maxRange;
if (xMin<0) xMin=0;
if (xMax>width) xMax=width;
if (yMin<0) yMin=0;
if (yMax>height) yMax=height;
m_Width=width;
m_Height=height;
}
virtual ~TouchSensor()
{
if (Exponential)
{
delete [] Exponential;
Exponential=0;
}
}
int Abs(int x)
{
return x>=0?x:-x;
}
int get_nTaxels ()
{
return nTaxels;
}
void eval_light(unsigned char *image)
{
int act;
int dx,dy;
int Y0,Y1;
int dya,dyb,dxa,dxb;
double remapped_activation[MAX_TAXELS];
switch (ilayoutNum)
{
case 0:
for (int i=0; i<nTaxels; ++i) remapped_activation[i]=activation[i];
break;
case 1:
for (int i=0; i<nTaxels; ++i) remapped_activation[nTaxels-1-i]=activation[i];
break;
default:
for (int i=0; i<nTaxels; ++i) remapped_activation[i]=activation[i];
printf("WARN: unkwnown layout number.\n");
break;
}
int maxRange2=m_maxRangeLight*m_maxRangeLight;
for (int i=0; i<nTaxels; ++i) if (remapped_activation[i]>0.0)
{
act=int(dGain*remapped_activation[i]);
Y0=(m_Height-y[i]-1)*m_Width+x[i];
dya=(y[i]>=m_maxRangeLight)?-m_maxRangeLight:-y[i];
dyb=(y[i]+m_maxRangeLight<m_Height)?m_maxRangeLight:m_Height-y[i]-1;
dxa=(x[i]>=m_maxRangeLight)?-m_maxRangeLight:-x[i];
dxb=(x[i]+m_maxRangeLight<m_Width)?m_maxRangeLight:m_Width-x[i]-1;
for (dy=dya; dy<=dyb; ++dy)
{
Y1=Y0-dy*m_Width;
for (dx=dxa; dx<=dxb; ++dx)
{
if (dx*dx+dy*dy<=maxRange2)
{
image[(dx+Y1)*3]=act<255?act:255;
}
}
}
}
}
void eval(unsigned char *image)
{
int act;
int dx,dy;
int Y0,Y1;
int index;
double k0,k1;
int dya,dyb,dxa,dxb;
double remapped_activation[MAX_TAXELS];
switch (ilayoutNum)
{
case 0:
for (int i=0; i<nTaxels; ++i) remapped_activation[i]=activation[i];
break;
case 1:
for (int i=0; i<nTaxels; ++i) remapped_activation[nTaxels-1-i]=activation[i];
break;
default:
for (int i=0; i<nTaxels; ++i) remapped_activation[i]=activation[i];
printf("WARN: unkwnown layout number.\n");
break;
}
for (int i=0; i<nTaxels; ++i) if (remapped_activation[i]>0.0)
{
k0=dGain*remapped_activation[i];
Y0=(m_Height-y[i]-1)*m_Width+x[i];
dya=(y[i]>=m_maxRange)?-m_maxRange:-y[i];
dyb=(y[i]+m_maxRange<m_Height)?m_maxRange:m_Height-y[i]-1;
dxa=(x[i]>=m_maxRange)?-m_maxRange:-x[i];
dxb=(x[i]+m_maxRange<m_Width)?m_maxRange:m_Width-x[i]-1;
for (dy=dya; dy<=dyb; ++dy)
{
k1=k0*Exponential[Abs(dy)];
Y1=Y0-dy*m_Width;
for (dx=dxa; dx<=dxb; ++dx)
{
index=(dx+Y1)*3;
if (image[index]<R_MAX || image[index+1]<G_MAX || image[index+2]<B_MAX)
{
act=int(k1*Exponential[Abs(dx)]);
int actR=image[index ]+(act*R_MAX)/255;
int actG=image[index+1]+(act*G_MAX)/255;
int actB=image[index+2]+(act*B_MAX)/255;
image[index ]=actR<R_MAX?actR:R_MAX;
image[index+1]=actG<G_MAX?actG:G_MAX;
image[index+2]=actB<B_MAX?actB:B_MAX;
}
}
}
}
}
void setActivationFirst7(unsigned char* data)
{
for (int i=0; i<7; ++i)
{
activation[i]=data[i+1]<=244?double(244-data[i+1]):0.0;
}
}
void setActivationLast5(unsigned char* data)
{
for (int i=1; i<=5; ++i)
{
activation[i+6]=data[i]<=244?double(244-data[i]):0.0;
}
}
void setActivationFromPortData(double val, int id)
{
if (calibrated_skin)
{
if (val>244.0)
{
activation[id]=244.0;
}
else if (val<0.0)
{
activation[id]=0.0;
}
else
{
activation[id]=val;
}
}
else
{
activation[id]=val<=244?double(244-val):0.0;
}
}
virtual void draw(unsigned char *image)
{
for (int i=0; i<nVerts; ++i)
{
drawLine(image,xv[i],yv[i],xv[(i+1)%nVerts],yv[(i+1)%nVerts]);
}
for (int i=0; i<nTaxels; ++i)
{
drawCircle(image,x[i],y[i],m_Radius);
}
}
protected:
void dither(int x,int y,unsigned char *image)
{
static const unsigned char R1=0x80,G1=0x50,B1=0x00;
static const unsigned char R2=3*R1/4,G2=3*G1/4,B2=3*B1/4;
static const unsigned char R4=3*R2/4,G4=3*G2/4,B4=3*B2/4;
//y=m_Width-y-1;
//int bytePos=(x+(y-1)*m_Width)*3;
int bytePos=(x+(m_Height-y-2)*m_Width)*3;
if (image[bytePos-3]<R4) image[bytePos-3]=R4;
if (image[bytePos-2]<G4) image[bytePos-2]=G4;
//if (image[bytePos-1]<B4) image[bytePos-1]=B4;
if (image[bytePos ]<R2) image[bytePos ]=R2;
if (image[bytePos+1]<G2) image[bytePos+1]=G2;
//if (image[bytePos+2]<B2) image[bytePos+2]=B2;
if (image[bytePos+3]<R4) image[bytePos+3]=R4;
if (image[bytePos+4]<G4) image[bytePos+4]=G4;
//if (image[bytePos+5]<B4) image[bytePos+5]=B4;
bytePos+=m_Width*3;
if (image[bytePos-3]<R2) image[bytePos-3]=R2;
if (image[bytePos-2]<G2) image[bytePos-2]=G2;
//if (image[bytePos-1]<B2) image[bytePos-1]=B2;
if (image[bytePos ]<R1) image[bytePos ]=R1;
if (image[bytePos+1]<G1) image[bytePos+1]=G1;
//if (image[bytePos+2]<B1) image[bytePos+2]=B1;
if (image[bytePos+3]<R2) image[bytePos+3]=R2;
if (image[bytePos+4]<G2) image[bytePos+4]=G2;
//if (image[bytePos+5]<B2) image[bytePos+5]=B2;
bytePos+=m_Width*3;
if (image[bytePos-3]<R4) image[bytePos-3]=R4;
if (image[bytePos-2]<G4) image[bytePos-2]=G4;
//if (image[bytePos-1]<B4) image[bytePos-1]=B4;
if (image[bytePos ]<R2) image[bytePos ]=R2;
if (image[bytePos+1]<G2) image[bytePos+1]=G2;
//if (image[bytePos+2]<B2) image[bytePos+2]=B2;
if (image[bytePos+3]<R4) image[bytePos+3]=R4;
if (image[bytePos+4]<G4) image[bytePos+4]=G4;
//if (image[bytePos+5]<B4) image[bytePos+5]=B4;
}
void drawLine(unsigned char *image,int x0,int y0,int x1,int y1)
{
if (x1==x0 && y1==y0) return;
double Vx=double(x1-x0);
double Vy=double(y1-y0);
double dt=1.0/sqrt(Vx*Vx+Vy*Vy);
for (double t=0.0; t<=1.0; t+=dt)
{
dither(x0+int(t*Vx),y0+int(t*Vy),image);
}
}
void drawCircle(unsigned char *image,int cx,int cy,double radius)
{
double dt=1.0/(2*M_PI*radius);
int dx,dy;
double cs,sn;
for (double t=0.0; t<=M_PI_4; t+=dt)
{
cs=cos(t);
sn=sin(t);
dx=int(radius*cs);
dy=int(radius*sn);
dither(cx+dx,cy+dy,image);
dither(cx+dx,cy-dy,image);
dither(cx-dx,cy-dy,image);
dither(cx-dx,cy+dy,image);
dither(cx+dy,cy+dx,image);
dither(cx+dy,cy-dx,image);
dither(cx-dy,cy-dx,image);
dither(cx-dy,cy+dx,image);
}
}
// original
double dX[MAX_TAXELS],dY[MAX_TAXELS];
static double dXmin,dXmax,dYmin,dYmax;
double dXv[8],dYv[8];
double dXc,dYc;
double dGain;
int ilayoutNum;
int ilrMirror;
double m_Radius,m_RadiusOrig;
double activation[MAX_TAXELS];
unsigned char R_MAX, G_MAX, B_MAX;
int m_maxRangeLight;
static int m_maxRange;
static double *Exponential;
// scaled
int x[MAX_TAXELS],y[MAX_TAXELS];
int xv[8],yv[8];
int nVerts;
int nTaxels;
int xMin,xMax,yMin,yMax;
int m_Width,m_Height;
public:
int min_tax;
int max_tax;
};
#endif
| {
"alphanum_fraction": 0.5049687155,
"avg_line_length": 26.7027027027,
"ext": "h",
"hexsha": "167fef0bd8dd71d1e3a82060986eff521aa71e28",
"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": "10b1d645b4a9818b0cb002b0d2d015e13ad32168",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "robotology-legacy/icub-gtk-modules",
"max_forks_repo_path": "iCubSkinGui-gtk/src/include/TouchSensor.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "10b1d645b4a9818b0cb002b0d2d015e13ad32168",
"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": "robotology-legacy/icub-gtk-modules",
"max_issues_repo_path": "iCubSkinGui-gtk/src/include/TouchSensor.h",
"max_line_length": 94,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "10b1d645b4a9818b0cb002b0d2d015e13ad32168",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "robotology-legacy/icub-gtk-modules",
"max_stars_repo_path": "iCubSkinGui-gtk/src/include/TouchSensor.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3401,
"size": 10868
} |
#ifndef OPS_REDUCERS_H
#define OPS_REDUCERS_H
#include <fundamental/tensor.h>
#include <nn/container.h>
#ifdef TENSOR_USE_CUBLAS
#include <cublas_v2.h>
#endif
#ifdef TENSOR_USE_OPENBLAS
#include <cblas.h>
#endif
#include <ops/transform.h>
namespace operators{
template<typename xpu, index_t stream_id, typename T>
void asum_backward(nn::TensorContainer<xpu, stream_id, T>& x,
nn::TensorContainer<xpu, stream_id, T>& y,
int offset, int inc, int n){
auto bwd = [](nn::TensorContainer<xpu, stream_id, float> x,
nn::TensorContainer<xpu, stream_id, float> y,
int offset, int inc, int n)
{
auto strided_x = expression::transform::stride(x, offset, inc, n);
core::Shape shape = strided_x.self().shape();
//auto repeated_y = expression::transform::repeat(shape.size(), yexp);
core::Constant<xpu, T, stream_id> repeated_y(y.gradient().scalar(),
core::Shape(x.shape().size()));
expression::Exceturer<xpu>::backward(repeated_y, strided_x);
};
STREAM_BACKWARD(xpu, stream_id).put(bwd, x, y, offset, inc, n);
}
template<index_t stream_id>
void asum(nn::TensorContainer<cpu, stream_id, float>& x,
nn::TensorContainer<cpu, stream_id, float>& y,
int offset, int inc, int n){
//y.conditional_override(core::Shape(1));
ASSERT_ERROR( ((n+offset) - (x.data().shape().size())) <= 0 , " Out of bound ");
auto fwd = [](nn::TensorContainer<cpu, stream_id, float> x,
nn::TensorContainer<cpu, stream_id, float> y,
int offset, int inc, int n)
{
float* ptr_offseted = x.data().ptr() + offset;
float result = cblas_sasum(n, ptr_offseted, inc);
y.data().set(0, result);
};
STREAM_FORWARD(cpu, stream_id).put(fwd, x, y, offset, inc, n);
if (x.require_grad() && y.require_grad())
asum_backward(x, y, offset, inc, n);
}
#ifdef TENSOR_USE_CUBLAS
template<index_t stream_id>
void asum(nn::TensorContainer<gpu, stream_id, float>& x,
nn::TensorContainer<gpu, stream_id, float>& y,
int offset, int inc, int n){
DEBUG_ASSERT(y.data().shape().size() == 1);
ASSERT_ERROR( ((n+offset) - (x.data().shape().size())) <= 0 , " Out of bound ");
auto fwd = [](nn::TensorContainer<gpu, stream_id, float> x,
nn::TensorContainer<gpu, stream_id, float> y,
int offset, int inc, int n)
{
auto cublasHandle = STREAM_FORWARD(gpu, stream_id).cublasHandle();
float result;
float* ptr_offseted = x.data().ptr() + offset;
CUDBLAS_CHECK_ERROR_ENFORCE(cublasSasum(cublasHandle, n,
ptr_offseted, inc,
&result));
y.data().set(0, result);
};
STREAM_FORWARD(gpu, stream_id).put(fwd, x, y, offset, inc, n);
if (x.require_grad() && y.require_grad())
asum_backward(x, y, offset, inc, n);
}
#endif
}
#ifdef TENSOR_USE_CUDNN
namespace cudnn {
template<cudnnReduceTensorOp_t OPERATION, index_t stream_id>
void reduce_cudnn_i(core::Tensor<gpu, stream_id, float>& tensorA,
core::Tensor<gpu, stream_id, float>& tensorB,
core::Tensor<gpu, stream_id, indices_t>& indicies,
float alpha = 1, float beta = 0){
DEBUG_ASSERT( indicies.shape() == tensorB.shape() );
cudnnReduceTensorDescriptor_t reduce;
cudnnCreateReduceTensorDescriptor(&reduce);
CHECK_CUDNN( cudnnSetReduceTensorDescriptor(
reduce,
OPERATION,
CUDNN_DATA_FLOAT,
CUDNN_NOT_PROPAGATE_NAN,
CUDNN_REDUCE_TENSOR_FLATTENED_INDICES,
CUDNN_32BIT_INDICES) );
size_t workspaces_sz;
auto cudnnhandle = STREAM_FORWARD(gpu, stream_id).cudnnHandle();
CHECK_CUDNN( cudnnGetReductionWorkspaceSize(cudnnhandle,
reduce,
tensorA.descriptor(),
tensorB.descriptor(),
&workspaces_sz) );
auto workspace_ptr = cuda::generate_workspace<void>(workspaces_sz);
CHECK_CUDNN( cudnnReduceTensor(
cudnnhandle,
reduce, // reduceTensorDesc
indicies.ptr(), // indicies
sizeof(indices_t) * indicies.shape().size(), // indicesSizeInBytes,
workspace_ptr, // workspace,
workspaces_sz, //workspaceSizeInBytes,
(void*) &alpha,
tensorA.descriptor(),
(void*) tensorA.ptr(),
(void*) &beta,
tensorB.descriptor(),
(void*) tensorB.ptr()) ) ;
for (int i = 0; i < indicies.shape()[0]; ++i)
printf(" %f\n", tensorB.at(i) );
}
template<cudnnReduceTensorOp_t OPERATION, index_t stream_id>
void reduce_cudnn(core::Tensor<gpu, stream_id, float>& tensorA,
core::Tensor<gpu, stream_id, float>& tensorB,
float alpha = 1, float beta = 0){
cudnnReduceTensorDescriptor_t reduce;
cudnnCreateReduceTensorDescriptor(&reduce);
CHECK_CUDNN( cudnnSetReduceTensorDescriptor(
reduce,
OPERATION,
CUDNN_DATA_FLOAT,
CUDNN_NOT_PROPAGATE_NAN,
CUDNN_REDUCE_TENSOR_NO_INDICES,
CUDNN_32BIT_INDICES) );
size_t workspaces_sz;
auto cudnnhandle = STREAM_FORWARD(gpu, stream_id).cudnnHandle();
CHECK_CUDNN( cudnnGetReductionWorkspaceSize(cudnnhandle,
reduce,
tensorA.descriptor(),
tensorB.descriptor(),
&workspaces_sz) );
auto workspace_ptr = cuda::generate_workspace<void>(workspaces_sz);
float dummy;
CHECK_CUDNN( cudnnReduceTensor(
cudnnhandle,
reduce, // reduceTensorDesc
&dummy, // indicies
0, // indicesSizeInBytes,
workspace_ptr, // workspace,
workspaces_sz, //workspaceSizeInBytes,
(void*) &alpha,
tensorA.descriptor(),
(void*) tensorA.ptr(),
(void*) &beta,
tensorB.descriptor(),
(void*) tensorB.ptr()) ) ;
}
}
#endif
namespace operators{
#ifdef TENSOR_USE_CUDNN
template<index_t stream_id>
void reduce_sum(core::Tensor<gpu, stream_id, float>& tensorA,
core::Tensor<gpu, stream_id, float>& tensorB,
float alpha = 1, float beta = 0){
cudnn::reduce_cudnn<CUDNN_REDUCE_TENSOR_ADD, stream_id>
(tensorA, tensorB, alpha, beta);
}
template<index_t stream_id>
void reduce_max(core::Tensor<gpu, stream_id, float>& tensorA,
core::Tensor<gpu, stream_id, float>& tensorB,
float alpha = 1, float beta = 0){
cudnn::reduce_cudnn<CUDNN_REDUCE_TENSOR_MAX, stream_id>
(tensorA, tensorB, alpha, beta);
}
template<index_t stream_id>
void reduce_min(core::Tensor<gpu, stream_id, float>& tensorA,
core::Tensor<gpu, stream_id, float>& tensorB,
float alpha = 1, float beta = 0){
cudnn::reduce_cudnn<CUDNN_REDUCE_TENSOR_MIN, stream_id>
(tensorA, tensorB, alpha, beta);
}
template<index_t stream_id>
void reduce_max_i(core::Tensor<gpu, stream_id, float>& tensorA,
core::Tensor<gpu, stream_id, float>& tensorB,
core::Tensor<gpu, stream_id, indices_t>& indices,
float alpha = 1, float beta = 0){
cudnn::reduce_cudnn_i<CUDNN_REDUCE_TENSOR_MAX, stream_id>
(tensorA, tensorB, indices, alpha, beta);
}
template<index_t stream_id>
void reduce_min_i(core::Tensor<gpu, stream_id, float>& tensorA,
core::Tensor<gpu, stream_id, float>& tensorB,
core::Tensor<gpu, stream_id, indices_t>& indices,
float alpha = 1, float beta = 0){
cudnn::reduce_cudnn_i<CUDNN_REDUCE_TENSOR_MIN, stream_id>
(tensorA, tensorB, indices, alpha, beta);
}
template<index_t stream_id>
TENSOR_INLINE_HOST void reduce_min(
std::shared_ptr<nn::TensorContainer<gpu, stream_id, float>> A,
std::shared_ptr<nn::TensorContainer<gpu, stream_id, float>> B,
index_t axis){
B->conditional_override(A->shape().reduce_axis(axis));
if (B->require_grad()){
// Create tensor for incicies
core::Tensor<gpu, stream_id, float> I(B->shape()); I.allocate();
auto fwd = [](core::Tensor<gpu, stream_id, float> A,
core::Tensor<gpu, stream_id, float> B,
core::Tensor<gpu, stream_id, float> I){
reduce_min_i(A, B, I);
};
STREAM_FORWARD(gpu, stream_id).put(fwd, A->data(), B->data(), I);
}else{
auto fwd = [](core::Tensor<gpu, stream_id, float> A,
core::Tensor<gpu, stream_id, float> B){
reduce_min(A, B);
};
STREAM_FORWARD(gpu, stream_id).put(fwd, A->data(), B->data());
}
}
#endif
}
#endif //OPS_REDUCERS_H
| {
"alphanum_fraction": 0.5229162638,
"avg_line_length": 34.7046979866,
"ext": "h",
"hexsha": "33ccb85a9c0f95a657d304ccd72b8c1c4c0346fb",
"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": "1490af758078c61caacc16f3445403df3595b33c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jsk89/projectx",
"max_forks_repo_path": "internal/nn/ops/reducers.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1490af758078c61caacc16f3445403df3595b33c",
"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": "jsk89/projectx",
"max_issues_repo_path": "internal/nn/ops/reducers.h",
"max_line_length": 105,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "1490af758078c61caacc16f3445403df3595b33c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jsk89/projectx",
"max_stars_repo_path": "internal/nn/ops/reducers.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-29T17:12:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-29T17:12:23.000Z",
"num_tokens": 2344,
"size": 10342
} |
#include <bindings.cmacros.h>
#include <gsl/gsl_sf.h>
BC_INLINE1(GSL_MODE_PREC,gsl_mode_t,unsigned)
| {
"alphanum_fraction": 0.801980198,
"avg_line_length": 20.2,
"ext": "c",
"hexsha": "a6740f437e4b9709c4e200fceb2bae528032593d",
"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/SpecialFunctions.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/SpecialFunctions.c",
"max_line_length": 45,
"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/SpecialFunctions.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": 30,
"size": 101
} |
#ifndef __GSL_BLOCK_H__
#define __GSL_BLOCK_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <gsl/gsl_block_complex_long_double.h>
#include <gsl/gsl_block_complex_double.h>
#include <gsl/gsl_block_complex_float.h>
#include <gsl/gsl_block_long_double.h>
#include <gsl/gsl_block_double.h>
#include <gsl/gsl_block_float.h>
#include <gsl/gsl_block_ulong.h>
#include <gsl/gsl_block_long.h>
#include <gsl/gsl_block_uint.h>
#include <gsl/gsl_block_int.h>
#include <gsl/gsl_block_ushort.h>
#include <gsl/gsl_block_short.h>
#include <gsl/gsl_block_uchar.h>
#include <gsl/gsl_block_char.h>
#endif /* __GSL_BLOCK_H__ */
| {
"alphanum_fraction": 0.7378984652,
"avg_line_length": 24.2,
"ext": "h",
"hexsha": "cb9752d48510e051148e5bc93c79de4d98b51361",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "deps/include/gsl/gsl_block.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "berkus/music-cs",
"max_issues_repo_path": "deps/include/gsl/gsl_block.h",
"max_line_length": 49,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "berkus/music-cs",
"max_stars_repo_path": "deps/include/gsl/gsl_block.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z",
"num_tokens": 236,
"size": 847
} |
#ifndef DATA_H
#define DATA_H
#include <gsl/gsl_vector.h>
typedef struct {
int imageIdx;
int labelerId;
int workflowId;
int workerPoolId;
int label;
double trueLabel;
double trueDifficulty;
} Label;
typedef struct {
Label *labels;
int numLabels;
int numLabelers;
int numImages;
int numWorkflows;
int numWorkerPools;
double *priorAlpha;
double *priorBeta;
double *probZ1, *probZ0;
double *alpha, *beta;
double *priorZ1;
} Dataset;
void packX (gsl_vector *x, Dataset *data);
void unpackX (const gsl_vector *x, Dataset *data);
void readData (char *filename, Dataset *data, double*, double);
void outputResults (Dataset *data);
#endif
| {
"alphanum_fraction": 0.7202380952,
"avg_line_length": 18.6666666667,
"ext": "h",
"hexsha": "a6d190696c01a4ee5a364f586e51b12a901d991b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-02-25T18:59:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-25T18:59:03.000Z",
"max_forks_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ShreyaR/WorkerPoolSelection",
"max_forks_repo_path": "EM/data.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002",
"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": "ShreyaR/WorkerPoolSelection",
"max_issues_repo_path": "EM/data.h",
"max_line_length": 63,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ShreyaR/WorkerPoolSelection",
"max_stars_repo_path": "EM/data.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 192,
"size": 672
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C header for structures for EOBNRv2HM reduced order model (non-spinning version).
* See CQG 31 195010, 2014, arXiv:1402.4146 for details on the reduced order method.
* See arXiv:1106.1021 for the EOBNRv2HM model.
*
* Borrows from the SEOBNR ROM LAL code written by Michael Puerrer and John Veitch.
*
* Put the untared data in the directory designated by the environment variable ROM_DATA_PATH.
*
* Parameter range:
* q = 1-12 (almost)
* No spin
* Mtot >= 10Msun for fstart=8Hz
*
*/
#ifndef _EOBNRV2HMROMSTRUCT_H
#define _EOBNRV2HMROMSTRUCT_H
#define _XOPEN_SOURCE 500
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#if defined(__cplusplus)
extern "C" {
#elif 0
} /* so that editors will match preceding brace */
#endif
/***************************************************/
/*************** Type definitions ******************/
typedef struct tagSplineList {
gsl_spline* spline; /* The gsl spline */
gsl_interp_accel* accel; /* The gsl accelerator */
int i; /* Index in the list */
struct tagSplineList* next; /* Pointer to the next list element */
} SplineList;
typedef struct tagEOBNRHMROMdata
{
gsl_vector* q;
gsl_vector* freq;
gsl_matrix* Camp;
gsl_matrix* Cphi;
gsl_matrix* Bamp;
gsl_matrix* Bphi;
gsl_vector* shifttime;
gsl_vector* shiftphase;
} EOBNRHMROMdata;
typedef struct tagEOBNRHMROMdata_interp
{
SplineList* Camp_interp; /* List of splines for the amp coefficients - SplineList, index of reduced basis */
SplineList* Cphi_interp; /* List of splines for the phase coefficients - SplineList, index of reduced basis */
SplineList* shifttime_interp; /* interpolated shift in time - SplineList with one element */
SplineList* shiftphase_interp; /* interpolated shift in phase - SplineList with one element */
} EOBNRHMROMdata_interp;
typedef struct tagEOBNRHMROMdata_coeff
{
gsl_vector* Camp_coeff;
gsl_vector* Cphi_coeff;
double* shifttime_coeff;
double* shiftphase_coeff;
} EOBNRHMROMdata_coeff;
typedef struct tagListmodesEOBNRHMROMdata
{
EOBNRHMROMdata* data; /* The ROM data. */
int l; /* Node mode l */
int m; /* Node submode m */
struct tagListmodesEOBNRHMROMdata* next; /* next pointer */
} ListmodesEOBNRHMROMdata;
typedef struct tagListmodesEOBNRHMROMdata_interp
{
EOBNRHMROMdata_interp* data_interp; /* The splines built from the coefficients. */
int l; /* Node mode l */
int m; /* Node submode m */
struct tagListmodesEOBNRHMROMdata_interp* next; /* next pointer */
} ListmodesEOBNRHMROMdata_interp;
typedef struct tagListmodesEOBNRHMROMdata_coeff
{
EOBNRHMROMdata_coeff* data_coeff; /* The data of coefficients. */
int l; /* Node mode l */
int m; /* Node submode m */
struct tagListmodesEOBNRHMROMdata_coeff* next; /* next pointer */
} ListmodesEOBNRHMROMdata_coeff;
/**********************************************************/
/**************** Internal functions **********************/
/* Functions associated to list manipulations */
SplineList* SplineList_AddElementNoCopy(
SplineList* appended, /* List structure to prepend to */
gsl_spline* spline, /* spline to contain */
gsl_interp_accel* accel, /* accelerator to contain */
int i /* index in the list */
);
SplineList* SplineList_GetElement(
SplineList* const splinelist, /* List structure to get a particular mode from */
const int i /* index in the list */
);
void SplineList_Destroy(
SplineList* list /* List structure to destroy; notice that the content is destroyed too */
);
ListmodesEOBNRHMROMdata* ListmodesEOBNRHMROMdata_AddModeNoCopy(
ListmodesEOBNRHMROMdata* appended, /* List structure to prepend to */
EOBNRHMROMdata* indata, /* data to contain */
int l, /*< major mode number */
int m /*< minor mode number */
);
ListmodesEOBNRHMROMdata* ListmodesEOBNRHMROMdata_GetMode(
ListmodesEOBNRHMROMdata* const list, /* List structure to get a particular mode from */
int l, /*< major mode number */
int m /*< minor mode number */
);
void ListmodesEOBNRHMROMdata_Destroy(
ListmodesEOBNRHMROMdata* list /* List structure to destroy; notice that the data is destroyed too */
);
ListmodesEOBNRHMROMdata_interp* ListmodesEOBNRHMROMdata_interp_AddModeNoCopy(
ListmodesEOBNRHMROMdata_interp* appended, /* List structure to prepend to */
EOBNRHMROMdata_interp* data, /* data to contain */
int l, /* major mode number */
int m /* minor mode number */
);
ListmodesEOBNRHMROMdata_interp* ListmodesEOBNRHMROMdata_interp_GetMode(
ListmodesEOBNRHMROMdata_interp* const list, /* List structure to get a particular mode from */
int l, /*< major mode number */
int m /*< minor mode number */
);
void ListmodesEOBNRHMROMdata_interp_Destroy(
ListmodesEOBNRHMROMdata_interp* list /* List structure to destroy; notice that the data is destroyed too */
);
ListmodesEOBNRHMROMdata_coeff* ListmodesEOBNRHMROMdata_coeff_AddModeNoCopy(
ListmodesEOBNRHMROMdata_coeff* appended, /* List structure to prepend to */
EOBNRHMROMdata_coeff* data, /* data to contain */
int l, /* major mode number */
int m /* minor mode number */
);
ListmodesEOBNRHMROMdata_coeff* ListmodesEOBNRHMROMdata_coeff_GetMode(
ListmodesEOBNRHMROMdata_coeff* const list, /* List structure to get a particular mode from */
int l, /*< major mode number */
int m /*< minor mode number */
);
void ListmodesEOBNRHMROMdata_coeff_Destroy(
ListmodesEOBNRHMROMdata_coeff* list /* List structure to destroy; notice that the data is destroyed too */
);
#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif
#endif /* _EOBNRV2HMROMSTRUCT_H */
| {
"alphanum_fraction": 0.6703936284,
"avg_line_length": 35.1021505376,
"ext": "h",
"hexsha": "1fbb2f13689e693b9157c798fe9722a1df7a7f4e",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "EOBNRv2HMROM/EOBNRv2HMROMstruct.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "titodalcanton/flare",
"max_issues_repo_path": "EOBNRv2HMROM/EOBNRv2HMROMstruct.h",
"max_line_length": 112,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "EOBNRv2HMROM/EOBNRv2HMROMstruct.h",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 1696,
"size": 6529
} |
/* movstat/test_mean.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 mean by explicitely constructing window and computing mean */
int
slow_movmean(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 mean = gsl_stats_mean(window, 1, wsize);
gsl_vector_set(y, i, mean);
}
free(window);
return GSL_SUCCESS;
}
static double
func_mean(const size_t n, double x[], void * params)
{
(void) params;
return gsl_stats_mean(x, 1, n);
}
static void
test_mean_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 F;
char buf[2048];
F.function = func_mean;
F.params = NULL;
random_vector(x, rng_p);
/* y = mean(x) with slow brute force method */
slow_movmean(etype, x, y, H, J);
/* y = mean(x) with fast method */
gsl_movstat_mean(etype, x, z, w);
/* test y = z */
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u mean random", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* z = mean(x) in-place */
gsl_vector_memcpy(z, x);
gsl_movstat_mean(etype, z, z, w);
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u mean random in-place", n, H, J, etype);
compare_vectors(tol, z, y, buf);
/* z = mean(x) with user-defined function */
gsl_movstat_apply(etype, &F, x, z, w);
sprintf(buf, "n=%zu H=%zu J=%zu endtype=%u mean 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_mean(gsl_rng * rng_p)
{
const double eps = 1.0e-10;
test_mean_proc(eps, 1000, 0, 0, GSL_MOVSTAT_END_PADZERO, rng_p);
test_mean_proc(eps, 1000, 3, 3, GSL_MOVSTAT_END_PADZERO, rng_p);
test_mean_proc(eps, 1000, 0, 5, GSL_MOVSTAT_END_PADZERO, rng_p);
test_mean_proc(eps, 1000, 5, 0, GSL_MOVSTAT_END_PADZERO, rng_p);
test_mean_proc(eps, 2000, 10, 5, GSL_MOVSTAT_END_PADZERO, rng_p);
test_mean_proc(eps, 2000, 5, 10, GSL_MOVSTAT_END_PADZERO, rng_p);
test_mean_proc(eps, 20, 50, 50, GSL_MOVSTAT_END_PADZERO, rng_p);
test_mean_proc(eps, 20, 10, 50, GSL_MOVSTAT_END_PADZERO, rng_p);
test_mean_proc(eps, 20, 50, 10, GSL_MOVSTAT_END_PADZERO, rng_p);
test_mean_proc(eps, 1000, 0, 0, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_mean_proc(eps, 1000, 3, 3, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_mean_proc(eps, 1000, 0, 5, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_mean_proc(eps, 1000, 5, 0, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_mean_proc(eps, 2000, 10, 5, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_mean_proc(eps, 2000, 5, 10, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_mean_proc(eps, 20, 50, 50, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_mean_proc(eps, 20, 10, 50, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_mean_proc(eps, 20, 50, 10, GSL_MOVSTAT_END_PADVALUE, rng_p);
test_mean_proc(eps, 1000, 0, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_mean_proc(eps, 1000, 3, 3, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_mean_proc(eps, 1000, 0, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_mean_proc(eps, 1000, 5, 0, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_mean_proc(eps, 2000, 10, 5, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_mean_proc(eps, 2000, 5, 10, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_mean_proc(eps, 20, 50, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_mean_proc(eps, 20, 10, 50, GSL_MOVSTAT_END_TRUNCATE, rng_p);
test_mean_proc(eps, 20, 50, 10, GSL_MOVSTAT_END_TRUNCATE, rng_p);
}
| {
"alphanum_fraction": 0.7082896118,
"avg_line_length": 35.0367647059,
"ext": "c",
"hexsha": "dbb5c6da7113b7e816e4d906405aa62241c764da",
"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_mean.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_mean.c",
"max_line_length": 84,
"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_mean.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": 1580,
"size": 4765
} |
/* histogram/add2d.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_histogram2d.h>
#include "find2d.c"
int
gsl_histogram2d_increment (gsl_histogram2d * h, double x, double y)
{
int status = gsl_histogram2d_accumulate (h, x, y, 1.0);
return status;
}
int
gsl_histogram2d_accumulate (gsl_histogram2d * h,
double x, double y, double weight)
{
const size_t nx = h->nx;
const size_t ny = h->ny;
size_t i = 0, j = 0;
int status = find2d (h->nx, h->xrange, h->ny, h->yrange, x, y, &i, &j);
if (status)
{
return GSL_EDOM;
}
if (i >= nx)
{
GSL_ERROR ("index lies outside valid range of 0 .. nx - 1",
GSL_ESANITY);
}
if (j >= ny)
{
GSL_ERROR ("index lies outside valid range of 0 .. ny - 1",
GSL_ESANITY);
}
h->bin[i * ny + j] += weight;
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.6523972603,
"avg_line_length": 26.1492537313,
"ext": "c",
"hexsha": "3d77c5c4ed657c2d019a8c111c02f7e635e8c0b3",
"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/histogram/add2d.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/histogram/add2d.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/histogram/add2d.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": 507,
"size": 1752
} |
/* rng/types.c
*
* Copyright (C) 2001, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#define N 100
const gsl_rng_type * gsl_rng_generator_types[N];
#define ADD(t) {if (i==N) abort(); gsl_rng_generator_types[i] = (t); i++; };
const gsl_rng_type **
gsl_rng_types_setup (void)
{
int i = 0;
ADD(gsl_rng_borosh13);
ADD(gsl_rng_cmrg);
ADD(gsl_rng_coveyou);
ADD(gsl_rng_fishman18);
ADD(gsl_rng_fishman20);
ADD(gsl_rng_fishman2x);
ADD(gsl_rng_gfsr4);
ADD(gsl_rng_knuthran);
ADD(gsl_rng_knuthran2);
ADD(gsl_rng_knuthran2002);
ADD(gsl_rng_lecuyer21);
ADD(gsl_rng_minstd);
ADD(gsl_rng_mrg);
ADD(gsl_rng_mt19937);
ADD(gsl_rng_mt19937_1999);
ADD(gsl_rng_mt19937_1998);
ADD(gsl_rng_r250);
ADD(gsl_rng_ran0);
ADD(gsl_rng_ran1);
ADD(gsl_rng_ran2);
ADD(gsl_rng_ran3);
ADD(gsl_rng_rand);
ADD(gsl_rng_rand48);
ADD(gsl_rng_random128_bsd);
ADD(gsl_rng_random128_glibc2);
ADD(gsl_rng_random128_libc5);
ADD(gsl_rng_random256_bsd);
ADD(gsl_rng_random256_glibc2);
ADD(gsl_rng_random256_libc5);
ADD(gsl_rng_random32_bsd);
ADD(gsl_rng_random32_glibc2);
ADD(gsl_rng_random32_libc5);
ADD(gsl_rng_random64_bsd);
ADD(gsl_rng_random64_glibc2);
ADD(gsl_rng_random64_libc5);
ADD(gsl_rng_random8_bsd);
ADD(gsl_rng_random8_glibc2);
ADD(gsl_rng_random8_libc5);
ADD(gsl_rng_random_bsd);
ADD(gsl_rng_random_glibc2);
ADD(gsl_rng_random_libc5);
ADD(gsl_rng_randu);
ADD(gsl_rng_ranf);
ADD(gsl_rng_ranlux);
ADD(gsl_rng_ranlux389);
ADD(gsl_rng_ranlxd1);
ADD(gsl_rng_ranlxd2);
ADD(gsl_rng_ranlxs0);
ADD(gsl_rng_ranlxs1);
ADD(gsl_rng_ranlxs2);
ADD(gsl_rng_ranmar);
ADD(gsl_rng_slatec);
ADD(gsl_rng_taus);
ADD(gsl_rng_taus2);
ADD(gsl_rng_taus113);
ADD(gsl_rng_transputer);
ADD(gsl_rng_tt800);
ADD(gsl_rng_uni);
ADD(gsl_rng_uni32);
ADD(gsl_rng_vax);
ADD(gsl_rng_waterman14);
ADD(gsl_rng_zuf);
ADD(0);
return gsl_rng_generator_types;
}
| {
"alphanum_fraction": 0.7466567608,
"avg_line_length": 26.3921568627,
"ext": "c",
"hexsha": "071edcf635a9937597742111c219973e4fcd7ac2",
"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/types.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/types.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/types.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": 886,
"size": 2692
} |
#include <gsl/gsl_math.h>
#include "gsl_cblas.h"
#include "cblas.h"
void
cblas_dscal (const int N, const double alpha, double *X, const int incX)
{
#define BASE double
#include "source_scal_r.h"
#undef BASE
}
| {
"alphanum_fraction": 0.7333333333,
"avg_line_length": 17.5,
"ext": "c",
"hexsha": "eab8367842264b0137d1df81ea23bad40937357f",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/dscal.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/dscal.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/cblas/dscal.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": 63,
"size": 210
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "Data/Data.h"
#include <gsl/gsl>
// forward declare cv::KeyPoint
namespace cv
{
class KeyPoint;
}
namespace mage
{
struct InitializationData;
struct FrameData;
class AnalyzedImage;
class Introspector
{
public:
virtual ~Introspector() = default;
virtual void Introspect(const InitializationData& /*data*/) {}
virtual void IntrospectEstimatedPose(const mage::FrameId& /*frameId*/, const mage::Matrix& /*viewMatrix*/) {}
virtual void IntrospectAnalyzedImage(const mage::FrameData& /*frame*/, const mage::AnalyzedImage& /* image */) {}
};
}
| {
"alphanum_fraction": 0.6742209632,
"avg_line_length": 21.3939393939,
"ext": "h",
"hexsha": "d58fbb642c8c9ba2c9e6dd3c83b10726751094f4",
"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/Debugging/Introspector.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/Debugging/Introspector.h",
"max_line_length": 121,
"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/Debugging/Introspector.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": 164,
"size": 706
} |
/**
*
* @file core_zgessm.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @author Mathieu Faverge
* @author Jakub Kurzak
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <cblas.h>
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex64_t
*
* CORE_zgessm applies the factors L computed by CORE_zgetrf_incpiv to
* a complex M-by-N tile A.
*
*******************************************************************************
*
* @param[in] M
* The number of rows of the tile A. M >= 0.
*
* @param[in] N
* The number of columns of the tile A. N >= 0.
*
* @param[in] K
* The number of columns of the tile L. K >= 0.
*
* @param[in] IB
* The inner-blocking size. IB >= 0.
*
* @param[in] IPIV
* The pivot indices array of size K as returned by
* CORE_zgetrf_incpiv.
*
* @param[in] L
* The M-by-K lower triangular tile.
*
* @param[in] LDL
* The leading dimension of the array L. LDL >= max(1,M).
*
* @param[in,out] A
* On entry, the M-by-N tile A.
* On exit, updated by the application of L.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,M).
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if INFO = -k, the k-th argument had an illegal value
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zgessm = PCORE_zgessm
#define CORE_zgessm PCORE_zgessm
#endif
int CORE_zgessm(int M, int N, int K, int IB,
const int *IPIV,
const PLASMA_Complex64_t *L, int LDL,
PLASMA_Complex64_t *A, int LDA)
{
static PLASMA_Complex64_t zone = 1.0;
static PLASMA_Complex64_t mzone = -1.0;
static int ione = 1;
int i, sb;
int tmp, tmp2;
/* Check input arguments */
if (M < 0) {
coreblas_error(1, "Illegal value of M");
return -1;
}
if (N < 0) {
coreblas_error(2, "Illegal value of N");
return -2;
}
if (K < 0) {
coreblas_error(3, "Illegal value of K");
return -3;
}
if (IB < 0) {
coreblas_error(4, "Illegal value of IB");
return -4;
}
if ((LDL < max(1,M)) && (M > 0)) {
coreblas_error(7, "Illegal value of LDL");
return -7;
}
if ((LDA < max(1,M)) && (M > 0)) {
coreblas_error(9, "Illegal value of LDA");
return -9;
}
/* Quick return */
if ((M == 0) || (N == 0) || (K == 0) || (IB == 0))
return PLASMA_SUCCESS;
for(i = 0; i < K; i += IB) {
sb = min(IB, K-i);
/*
* Apply interchanges to columns I*IB+1:IB*( I+1 )+1.
*/
tmp = i+1;
tmp2 = i+sb;
LAPACKE_zlaswp_work(LAPACK_COL_MAJOR, N, A, LDA, tmp, tmp2, IPIV, ione);
/*
* Compute block row of U.
*/
cblas_ztrsm(
CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasUnit,
sb, N, CBLAS_SADDR(zone),
&L[LDL*i+i], LDL,
&A[i], LDA );
if (i+sb < M) {
/*
* Update trailing submatrix.
*/
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans,
M-(i+sb), N, sb,
CBLAS_SADDR(mzone), &L[LDL*i+(i+sb)], LDL,
&A[i], LDA,
CBLAS_SADDR(zone), &A[i+sb], LDA );
}
}
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.4846912299,
"avg_line_length": 26.951048951,
"ext": "c",
"hexsha": "08a840da304653867360d4ab596b46ffe99c9584",
"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_zgessm.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_zgessm.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas/core_zgessm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1146,
"size": 3854
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C header for functions windowing and computing FFT/IFFT of time/frequency series.
*
*/
#ifndef __COMPUTELISASNR_H__
#define __COMPUTELISASNR_H__ 1
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#include "struct.h"
#include "waveform.h"
#include "fft.h"
#include "LISAgeometry.h"
#include "LISAFDresponse.h"
#include "LISAutils.h"
/********************************** Structures ******************************************/
/* Parameters for the generation of a LISA waveform (in the form of a list of modes) */
typedef struct tagComputeLISASNRparams {
double tRef; /* reference time (s) - GPS time at the frequency representing coalescence */
double phiRef; /* reference phase (rad) - phase at the frequency representing coalescence (or at fRef if specified) */
double fRef; /* reference frequency at which phiRef is set (Hz, default 0 which is interpreted as Mf=0.14) */
double m1; /* mass of companion 1 (solar masses, default 2e6) */
double m2; /* mass of companion 2 (solar masses, default 1e6) */
double distance; /* distance of source (Mpc, default 1e3) */
double inclination; /* inclination of source (rad, default pi/3) */
double lambda; /* first angle for the position in the sky (rad, default 0) */
double beta; /* second angle for the position in the sky (rad, default 0) */
double polarization; /* polarization angle (rad, default 0) */
int nbmode; /* number of modes to generate (starting with 22) - defaults to 5 (all modes) */
double deltatobs; /* Observation duration (years, default=2) */
double minf; /* Minimal frequency (Hz, default=0) - when set to 0, use the lowest frequency where the detector noise model is trusted __LISASimFD_Noise_fLow (set somewhat arbitrarily)*/
double maxf; /* Maximal frequency (Hz, default=0) - when set to 0, use the highest frequency where the detector noise model is trusted __LISASimFD_Noise_fHigh (set somewhat arbitrarily)*/
int tagextpn; /* Tag to allow PN extension of the waveform at low frequencies */
double Mfmatch; /* When PN extension allowed, geometric matching frequency: will use ROM above this value. If <=0, use ROM down to the lowest covered frequency */
int tagtdi; /* Tag selecting the desired TDI observables */
int tagint; /* Tag choosing the integrator: 0 for Fresnel (default), 1 for linear integration */
int nbptsoverlap; /* Number of points to use in loglinear overlaps (default 32768) */
LISAconstellation *variant; /* A structure defining the LISA constellation features */
int frozenLISA; /* Freeze the orbital configuration to the time of peak of the injection (default 0) */
ResponseApproxtag responseapprox; /* Approximation in the GAB and orb response - choices are full (full response, default), lowfL (keep orbital delay frequency-dependence but simplify constellation response) and lowf (simplify constellation and orbital response) - WARNING : at the moment noises are not consistent, and TDI combinations from the GAB are unchanged */
int fromtditdfile; /* Option for loading time series for TDI observables and FFTing */
int nlinesinfile; /* Number of lines of input file */
char indir[256]; /* Input directory */
char infile[256]; /* Input file */
int loadparamsfile; /* Option to load physical parameters from file and to output result to file (default 0) */
int nlinesparams; /* Number of lines in params file */
char paramsdir[256]; /* Directory for the input/output file */
char paramsfile[256]; /* Input file with the parameters */
char outputfile[256]; /* Output file */
} ComputeLISASNRparams;
#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif
#endif /* _COMPUTELISASNR_H */
| {
"alphanum_fraction": 0.6716847465,
"avg_line_length": 50.1888888889,
"ext": "h",
"hexsha": "9589158303fbd220a84fdbee0d7bce502f344a26",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "JohnGBaker/flare",
"max_forks_repo_path": "LISAinference/ComputeLISASNR.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "JohnGBaker/flare",
"max_issues_repo_path": "LISAinference/ComputeLISASNR.h",
"max_line_length": 371,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "JohnGBaker/flare",
"max_stars_repo_path": "LISAinference/ComputeLISASNR.h",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 1088,
"size": 4517
} |
#include <vector>
#include <string>
#include <math.h>
#include <cmath>
#include <memory>
#include <iostream>
#include "hdf5.h"
#include "hdf5_hl.h"
#include "H5Gpublic.h"
#include "H5Fpublic.h"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_integration.h>
#ifndef NUFATE_H
#define NUFATE_H
namespace nufate{
/// \struct Square_matrix_double
/// \brief Very simple matrix struct used for pybinding.
/// vec_ is the front address of a chank of double data,
/// which will be shaped in NxN 2dim matrix in python.
struct Square_matrix_double {
public :
unsigned int n_;
std::shared_ptr<double> vec_;
};
///\class Result
///\brief Simple class to hold the results.
class Result {
public :
std::vector<double> eval; // eigen values
std::shared_ptr<double> evec; // pointer to top address of eigen vectors
std::vector<double> ci; // coefficients
std::vector<double> energy_nodes_; // energy nodes in GeV
std::vector<double> phi_0_; // initial flux * E^(pedestal_gamma)
//
// functions below are not used by main nuFATE program,
// but may be used for pybinding.
//
/// \brief getter for eigenvalues
/// @return 1D vector
std::vector<double> get_eigenvalues() { return eval; }
/// \brief getter for coefficients
/// @return 1D vector
std::vector<double> get_coefficients() { return ci; }
/// \brief getter for energy nodes
/// @return 1D vector
std::vector<double> get_energy_nodes() { return energy_nodes_; }
/// \brief getter for initial flux * E^(pedestal_gamma)
/// @return 1D vector
std::vector<double> get_phi_0() { return phi_0_; }
/// \brief converter from pointer of double to Square_matrix_double object
/// @return Square_matrix_double
Square_matrix_double get_eigenvec_matrix() {
unsigned int n = energy_nodes_.size();
Square_matrix_double smatrix;
// evec is n x n data
smatrix.n_ = n;
smatrix.vec_ = evec;
return smatrix;
}
/// \brief debug print function
void Print(unsigned int target_index = 0) {
unsigned int dim = energy_nodes_.size();
std::cout << "***** Result print *****" << std::endl;
std::cout << "eigenvectors at row " << target_index << " ---" << std::endl;
for (unsigned int i=target_index; i<target_index+1; ++i) {
for (unsigned int j=0; j<dim; ++j) {
std::cout << *(evec.get() + i*dim + j) << " " ;
}
std::cout << std::endl;
}
std::cout << std::endl;
std::cout << "eigenvalue at i = " << target_index << " ---" << std::endl;
std::cout << eval[target_index] << std::endl;
std::cout << std::endl;
std::cout << "coefficient at i = " << target_index << " ---" << std::endl;
std::cout << ci[target_index] << std::endl;
std::cout << std::endl;
std::cout << "energy_node at i = " << target_index << " ---" << std::endl;
std::cout << energy_nodes_[target_index] << std::endl;
}
};
///\class nuFATE
///\brief nuFATE main class
class nuFATE {
private:
const double GF = 1.16e-5;
const double hbarc = 1.97e-14;
const double GW = 2.085;
const double MW = 80.385e0;
const double mmu = 0.106e0;
const double me = 511.e-6;
const double pi = M_PI;
const double MZ = 91.18;
const double s2t = 0.23;
const double gL = s2t-0.5;
const double REarth = 6371.;
const double gR = s2t;
private:
int newflavor_;
double newgamma_;
std::string newh5_filename_;
public:
/// \brief Constructor
/// @param flavor position ID of the system (1:NuE, -1:NuEBar, 2:NuMu, -2:NuMuBar, 3:NuTau, -3:NuTauBar)
/// @param gamma spectral index of input flux.
/// @param h5_filename name of hdf5 file containing the cross sections.
/// @param include_secondaries if true secondaries are added to the flux propagation.
nuFATE(int flv, double gamma, std::string h5_filename, bool include_secondaries);
/// \brief Constructor
/// @param flavor position ID of the system (1:NuE, -1:NuEBar, 2:NuMu, -2:NuMuBar, 3:NuTau, -3:NuTauBar)
/// @param gamma spectral index of input flux.
/// @param energy_nodes energy nodes in GeV.
/// @param sigma_array total cross section(CC+NC) at each energy node in cm^2.
/// @param dsigma_dE square array of differential cross section (NC only) in cm^2/GeV.
/// @param include_secondaries if true secondaries are added to the flux propagation.
nuFATE(int flv, double gamma, std::vector<double> energy_nodes, std::vector<double> sigma_array, std::vector<std::vector<double>> dsigma_dE, bool include_secondaries);
/// \brief Constructor
/// @param flavor position ID of the system (1:NuE, -1:NuEBar, 2:NuMu, -2:NuMuBar, 3:NuTau, -3:NuTauBar)
/// @param gamma spectral index of input flux.
/// @param cc_sigma_file file path for charge current(CC) total cross section in input format of nuSQuIDS
/// @param nc_sigma_file file path for neutral current(NC) total cross section in input format of nuSQuIDS
/// @param nc_dsigma_file file path to NC dSigma/dE differential cross section in input format of nuSQuIDS
/// @param include_secondaries if true secondaries are added to the flux propagation.
nuFATE(int flv, double gamma, std::string cc_sigma_file, std::string nc_sigma_file, std::string nc_dsigma_file, bool include_secondaries);
/// \brief Eigensystem calculator
Result getEigensystem();
/// \brief Function to get Earth column density
/// @param theta Zenith angle in radians.
double getEarthColumnDensity(double theta);
/// \brief Function to get flavor
int getFlavor() const;
/// \brief Function to get input spectral index
double getGamma() const;
/// \brief Function to get input filename
std::string getFilename() const;
/// \brief Function to get number of energy nodes
double getNumNodes() const;
/// \brief Function to toggle secondaries
void setAddSecondaries(bool opt) { add_secondary_term_ = opt;}
/// \brief Function to get energy nodes
std::vector<double> getEnergyNodes() { return energy_nodes_; }
/// \brief Function to get total crosssections (CC + NC)
std::vector<double> getTotalCrossSections() { return sigma_array_; }
/// \brief Function to get dsigma_dE differential crossection (for neutral-current only)
Square_matrix_double getNCDifferentialCrossSections() {
Square_matrix_double smatrix;
smatrix.n_ = NumNodes_;
smatrix.vec_ = dxs_array_;
return smatrix;
}
/// \brief Calculate Relative Attenuation
/// @param total number of targets, X[g/cm^2]*Na(Avogadro number) for example
/// @return attenuation factor (arrival_flux / initial_flux), 1D array in energy bins
std::vector<double> getRelativeAttenuation(double number_of_targets);
protected:
void Init(double gamma, const std::vector<double> &enodes, const std::vector<double> &sigmas, const std::vector<std::vector<double> > &dsigma);
void AddAdditionalTerms();
void LoadCrossSectionFromHDF5();
void SetCrossSectionsFromInput(const std::vector<double> &sigma, const std::vector<std::vector<double>> &dsigma_dE);
void SetInitialFlux();
void set_glashow_total();
void set_glashow_partial();
void set_RHS_matrices(std::shared_ptr<double> RMatrix_, std::shared_ptr<double> dxs_array);
static double rho_earth(double theta, void * p); //returns density for a given angle in radians along x distance
double readDoubleAttribute(hid_t, std::string) const;
unsigned int readUIntAttribute(hid_t, std::string) const;
std::vector<double> logspace(double min,double max,unsigned int samples) const;
private:
void AllocateMemoryForMembers(unsigned int num_nodes);
void SetEnergyBinWidths();
std::string grpdiff_;
std::string grptot_;
hid_t file_id_;
hid_t root_id_;
unsigned int NumNodes_;
unsigned int rsize_;
double Emax_;
double Emin_;
int dxsdim_[2];
std::vector<double> energy_nodes_;
std::vector<double> sigma_array_;
std::vector<double> sigma_array_orig_;
std::vector<double> DeltaE_;
std::vector<double> phi_0_;
std::vector<double> glashow_total_;
std::vector<double> sig3_array_;
std::shared_ptr<double> glashow_partial_;
std::shared_ptr<double> dxs_array_;
std::shared_ptr<double> tau_array_;
std::shared_ptr<double> sec_array_;
std::shared_ptr<double> regen_array_;
std::shared_ptr<double> RHSMatrix_;
std::shared_ptr<double> RHSMatrix1_;
std::shared_ptr<double> RHSMatrix2_;
std::shared_ptr<double> RHSMatrix3_;
std::shared_ptr<double> RHSMatrix4_;
std::shared_ptr<double> RHregen_;
std::shared_ptr<double> Enuin_;
std::shared_ptr<double> Enu_;
std::shared_ptr<double> selectron_;
std::shared_ptr<double> den_;
std::shared_ptr<double> t1_;
std::shared_ptr<double> t2_;
std::shared_ptr<double> t3_;
private:
bool include_secondaries_ = false;
bool memory_allocated_ = false;
bool initial_flux_set_ = false;
bool total_cross_section_set_ = false;
bool differential_cross_section_set_ = false;
bool RHS_set_ = false;
bool add_tau_regeneration_ = true;
bool add_glashow_term_= true;
bool add_secondary_term_ = true;
};
}
#endif
| {
"alphanum_fraction": 0.664462978,
"avg_line_length": 39.171314741,
"ext": "h",
"hexsha": "e8ab574449a11a00286c8fbcdb430400d8abe866",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2021-01-18T18:14:34.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-06-21T22:22:52.000Z",
"max_forks_repo_head_hexsha": "349338fdbb99edd5e0075038e65bb4da870ab8b4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kotoyo/nuFATE",
"max_forks_repo_path": "include/nuFATE/nuFATE.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "349338fdbb99edd5e0075038e65bb4da870ab8b4",
"max_issues_repo_issues_event_max_datetime": "2019-03-05T21:30:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-03-05T21:30:20.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "kotoyo/nuFATE",
"max_issues_repo_path": "include/nuFATE/nuFATE.h",
"max_line_length": 172,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "349338fdbb99edd5e0075038e65bb4da870ab8b4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kotoyo/nuFATE",
"max_stars_repo_path": "include/nuFATE/nuFATE.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-12T14:16:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-04-10T01:43:15.000Z",
"num_tokens": 2584,
"size": 9832
} |
#pragma once
#include "halley/support/logger.h"
#include "halley/net/connection/network_message.h"
#include <gsl/gsl>
namespace Halley
{
class Serializer;
class String;
class MessageQueue;
namespace DevCon
{
void setupMessageQueue(MessageQueue& queue);
enum class MessageType
{
Log,
ReloadAssets
};
class DevConMessage : public NetworkMessage
{
public:
virtual ~DevConMessage() = default;
virtual MessageType getMessageType() const = 0;
};
class LogMsg : public DevConMessage
{
public:
LogMsg(gsl::span<const gsl::byte> data);
LogMsg(LoggerLevel level, const String& msg);
void serialize(Serializer& s) const override;
LoggerLevel getLevel() const;
const String& getMessage() const;
MessageType getMessageType() const override;
private:
LoggerLevel level;
String msg;
};
class ReloadAssetsMsg : public DevConMessage
{
public:
ReloadAssetsMsg(gsl::span<const gsl::byte> data);
ReloadAssetsMsg(std::vector<String> ids);
void serialize(Serializer& s) const override;
std::vector<String> getIds() const;
MessageType getMessageType() const override;
private:
std::vector<String> ids;
};
}
}
| {
"alphanum_fraction": 0.7064220183,
"avg_line_length": 18.4461538462,
"ext": "h",
"hexsha": "5316df2566bc3bf86ac828c1e6e8f38d59abe27e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sunhay/halley",
"max_forks_repo_path": "src/engine/core/include/halley/core/devcon/devcon_messages.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "sunhay/halley",
"max_issues_repo_path": "src/engine/core/include/halley/core/devcon/devcon_messages.h",
"max_line_length": 52,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sunhay/halley",
"max_stars_repo_path": "src/engine/core/include/halley/core/devcon/devcon_messages.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z",
"num_tokens": 305,
"size": 1199
} |
#include <stdlib.h>
#include <assert.h>
#include <stdarg.h>
#include <string.h>
#include <float.h>
#include <math.h>
#include "kautodiff.h"
typedef struct {
uint64_t s[2];
double n_gset;
int n_iset;
volatile int lock;
} kad_rng_t;
/**********************
* Graph construction *
**********************/
static inline kad_node_t *kad_new_core(int n_d, int op, int n_child)
{
kad_node_t *s;
if (n_d >= KAD_MAX_DIM) return 0;
s = (kad_node_t*)calloc(1, sizeof(kad_node_t));
s->n_d = n_d, s->op = op, s->n_child = n_child;
if (s->n_child) s->child = (kad_node_t**)calloc(s->n_child, sizeof(kad_node_t*));
return s;
}
static inline kad_node_t *kad_vleaf(uint8_t flag, float *x, float *g, int n_d, va_list ap)
{
int i;
kad_node_t *p;
if (n_d > KAD_MAX_DIM) return 0;
p = (kad_node_t*)calloc(1, sizeof(kad_node_t));
p->n_d = n_d;
for (i = 0; i < n_d; ++i)
p->d[i] = va_arg(ap, int32_t);
p->x = x, p->g = g, p->flag = flag;
return p;
}
kad_node_t *kad_const(float *x, int n_d, ...)
{
kad_node_t *p;
va_list ap;
va_start(ap, n_d); p = kad_vleaf(KAD_CONST, x, 0, n_d, ap); va_end(ap);
return p;
}
kad_node_t *kad_feed(int n_d, ...)
{
kad_node_t *p;
va_list ap;
va_start(ap, n_d); p = kad_vleaf(0, 0, 0, n_d, ap); va_end(ap);
return p;
}
kad_node_t *kad_var(float *x, float *g, int n_d, ...)
{
kad_node_t *p;
va_list ap;
va_start(ap, n_d); p = kad_vleaf(KAD_VAR, x, g, n_d, ap); va_end(ap);
return p;
}
static inline kad_node_t *kad_finalize_node(kad_node_t *s) /* a helper function */
{
int i;
if (kad_op_list[s->op](s, KAD_SYNC_DIM) < 0) { /* check dimension */
if (s->ptr) free(s->ptr);
free(s->child); free(s);
return 0;
}
for (i = 0; i < s->n_child; ++i)
if (kad_is_back(s->child[i]))
break;
if (i < s->n_child) s->flag |= KAD_VAR;
return s;
}
/********** Simple arithmetic **********/
static inline kad_node_t *kad_op2_core(int op, kad_node_t *x, kad_node_t *y)
{
kad_node_t *s;
s = kad_new_core(0, op, 2);
s->child[0] = x, s->child[1] = y;
return kad_finalize_node(s);
}
static inline kad_node_t *kad_op1_core(int op, kad_node_t *x)
{
kad_node_t *s;
s = kad_new_core(0, op, 1);
s->child[0] = x;
return kad_finalize_node(s);
}
#define KAD_FUNC_OP2(fname, op) kad_node_t *fname(kad_node_t *x, kad_node_t *y) { return kad_op2_core((op), x, y); }
KAD_FUNC_OP2(kad_add, 1)
KAD_FUNC_OP2(kad_sub, 23)
KAD_FUNC_OP2(kad_mul, 2)
KAD_FUNC_OP2(kad_cmul, 3)
KAD_FUNC_OP2(kad_matmul, 9)
KAD_FUNC_OP2(kad_ce_multi, 13)
KAD_FUNC_OP2(kad_ce_bin, 22)
KAD_FUNC_OP2(kad_ce_bin_neg, 4)
KAD_FUNC_OP2(kad_mse, 29)
#define KAD_FUNC_OP1(fname, op) kad_node_t *fname(kad_node_t *x) { return kad_op1_core((op), x); }
KAD_FUNC_OP1(kad_log, 27)
KAD_FUNC_OP1(kad_exp, 33)
KAD_FUNC_OP1(kad_sin, 34)
KAD_FUNC_OP1(kad_square, 5)
KAD_FUNC_OP1(kad_sigm, 6)
KAD_FUNC_OP1(kad_tanh, 7)
KAD_FUNC_OP1(kad_relu, 8)
KAD_FUNC_OP1(kad_1minus, 11)
KAD_FUNC_OP1(kad_softmax, 14)
KAD_FUNC_OP1(kad_stdnorm, 32)
kad_node_t *kad_ce_multi_weighted(kad_node_t *pred, kad_node_t *truth, kad_node_t *weight)
{
kad_node_t *s;
s = kad_new_core(0, 13, 3);
s->child[0] = pred, s->child[1] = truth, s->child[2] = weight;
return kad_finalize_node(s);
}
/********** Convolution **********/
/* compute output dimension and padding sizes on both sides */
static inline int conv_find_par(int in_size, int kernel_size, int stride, int pad0, int *new_pad0, int *new_pad1)
{
int out_size, pad_both;
/* key equation: out_size = (in_size - kernel_size + pad_both) / stride + 1 */
if (pad0 == KAD_PAD_SAME && stride == 1) out_size = in_size;
else out_size = (in_size - kernel_size + (pad0 > 0? pad0 : 0) + stride - 1) / stride + 1;
pad_both = (out_size - 1) * stride + kernel_size - in_size;
*new_pad0 = pad_both / 2;
*new_pad1 = pad_both - *new_pad0;
return out_size;
}
typedef struct {
int kernel_size, stride, pad[2];
} conv_conf_t;
static inline conv_conf_t *conv2d_gen_aux(int in_row, int in_col, int kernel_r, int kernel_c, int stride_r, int stride_c, int top_pad, int left_pad)
{
conv_conf_t *cnn;
cnn = (conv_conf_t*)calloc(2, sizeof(conv_conf_t));
cnn[0].kernel_size = kernel_r, cnn[0].stride = stride_r;
cnn[1].kernel_size = kernel_c, cnn[1].stride = stride_c;
conv_find_par(in_row, kernel_r, stride_r, top_pad, &cnn[0].pad[0], &cnn[0].pad[1]);
conv_find_par(in_col, kernel_c, stride_c, left_pad, &cnn[1].pad[0], &cnn[1].pad[1]);
return cnn;
}
kad_node_t *kad_conv2d(kad_node_t *x, kad_node_t *w, int stride_r, int stride_c, int top_pad, int left_pad)
{
kad_node_t *s;
if (x->n_d != 4 || w->n_d != 4) return 0;
s = kad_new_core(0, 16, 2);
s->child[0] = x, s->child[1] = w;
s->ptr = conv2d_gen_aux(x->d[2], x->d[3], w->d[2], w->d[3], stride_r, stride_c, top_pad, left_pad);
s->ptr_size = sizeof(conv_conf_t) * 2;
return kad_finalize_node(s);
}
kad_node_t *kad_max2d(kad_node_t *x, int kernel_r, int kernel_c, int stride_r, int stride_c, int top_pad, int left_pad)
{
kad_node_t *s;
if (x->n_d != 4) return 0;
s = kad_new_core(0, 17, 1);
s->child[0] = x;
s->ptr = conv2d_gen_aux(x->d[2], x->d[3], kernel_r, kernel_c, stride_r, stride_c, top_pad, left_pad);
s->ptr_size = sizeof(conv_conf_t) * 2;
return kad_finalize_node(s);
}
static inline conv_conf_t *conv1d_gen_aux(int in_col, int kernel_c, int stride_c, int left_pad)
{
conv_conf_t *cnn;
cnn = (conv_conf_t*)calloc(1, sizeof(conv_conf_t));
cnn->kernel_size = kernel_c, cnn->stride = stride_c;
conv_find_par(in_col, kernel_c, stride_c, left_pad, &cnn->pad[0], &cnn->pad[1]);
return cnn;
}
kad_node_t *kad_conv1d(kad_node_t *x, kad_node_t *w, int stride, int left_pad)
{
kad_node_t *s;
if (x->n_d != 3 || w->n_d != 3) return 0;
s = kad_new_core(0, 18, 2);
s->child[0] = x, s->child[1] = w;
s->ptr = conv1d_gen_aux(x->d[2], w->d[2], stride, left_pad);
s->ptr_size = sizeof(conv_conf_t);
return kad_finalize_node(s);
}
kad_node_t *kad_max1d(kad_node_t *x, int kernel_size, int stride, int left_pad)
{
kad_node_t *s;
if (x->n_d != 3) return 0;
s = kad_new_core(0, 19, 1);
s->child[0] = x;
s->ptr = conv1d_gen_aux(x->d[2], kernel_size, stride, left_pad);
s->ptr_size = sizeof(conv_conf_t);
return kad_finalize_node(s);
}
kad_node_t *kad_avg1d(kad_node_t *x, int kernel_size, int stride, int left_pad)
{
kad_node_t *s;
if (x->n_d != 3) return 0;
s = kad_new_core(0, 28, 1);
s->child[0] = x;
s->ptr = conv1d_gen_aux(x->d[2], kernel_size, stride, left_pad);
s->ptr_size = sizeof(conv_conf_t);
return kad_finalize_node(s);
}
/********** Multi-node pooling **********/
static kad_node_t *kad_pooling_general(int op, int n, kad_node_t **x)
{
int i;
kad_node_t *s;
s = kad_new_core(0, op, n);
s->flag |= KAD_POOL;
for (i = 0; i < n; ++i)
s->child[i] = x[i];
return kad_finalize_node(s);
}
kad_node_t *kad_avg(int n, kad_node_t **x) { return kad_pooling_general(10, n, x); }
kad_node_t *kad_max(int n, kad_node_t **x) { return kad_pooling_general(21, n, x); }
kad_node_t *kad_stack(int n, kad_node_t **x) { return kad_pooling_general(35, n, x); }
kad_node_t *kad_select(int n, kad_node_t **x, int which)
{
kad_node_t *s;
int32_t i, *aux;
aux = (int32_t*)calloc(1, 4);
*aux = which;
s = kad_new_core(0, 12, n);
for (i = 0; i < n; ++i) s->child[i] = x[i];
s->flag |= KAD_POOL, s->ptr = aux, s->ptr_size = 4;
return kad_finalize_node(s);
}
/********** Dimension reduction **********/
static kad_node_t *kad_reduce_general(int op, kad_node_t *x, int axis)
{
kad_node_t *s;
int32_t *aux;
aux = (int32_t*)malloc(4);
aux[0] = axis;
s = kad_new_core(0, op, 1);
s->child[0] = x;
s->ptr = aux, s->ptr_size = 4;
return kad_finalize_node(s);
}
kad_node_t *kad_reduce_sum(kad_node_t *x, int axis) { return kad_reduce_general(25, x, axis); }
kad_node_t *kad_reduce_mean(kad_node_t *x, int axis) { return kad_reduce_general(26, x, axis); }
/********** Sampling related **********/
kad_node_t *kad_dropout(kad_node_t *x, kad_node_t *y)
{
kad_node_t *z;
z = kad_op2_core(15, x, y);
z->ptr = kad_rng(), z->ptr_size = sizeof(kad_rng_t);
return z;
}
kad_node_t *kad_sample_normal(kad_node_t *x)
{
kad_node_t *z;
z = kad_op1_core(24, x);
z->ptr = kad_rng(), z->ptr_size = sizeof(kad_rng_t);
return z;
}
/********** Miscellaneous **********/
kad_node_t *kad_slice(kad_node_t *x, int axis, int start, int end)
{
kad_node_t *s;
int32_t *aux;
if (end < start || start < 0) return 0;
aux = (int32_t*)malloc(3 * 4);
aux[0] = axis, aux[1] = start, aux[2] = end;
s = kad_new_core(0, 20, 1);
s->child[0] = x;
s->ptr = aux, s->ptr_size = 3 * 4;
return kad_finalize_node(s);
}
kad_node_t *kad_concat_array(int axis, int n, kad_node_t **p)
{
kad_node_t *s;
int32_t i, *aux;
aux = (int32_t*)malloc(4);
aux[0] = axis;
s = kad_new_core(0, 31, n);
for (i = 0; i < n; ++i)
s->child[i] = p[i];
s->ptr = aux, s->ptr_size = 4;
return kad_finalize_node(s);
}
kad_node_t *kad_concat(int axis, int n, ...)
{
int i;
kad_node_t **p, *s;
va_list ap;
p = (kad_node_t**)malloc(n * sizeof(kad_node_t*));
va_start(ap, n);
for (i = 0; i < n; ++i) p[i] = va_arg(ap, kad_node_p);
va_end(ap);
s = kad_concat_array(axis, n, p);
free(p);
return s;
}
kad_node_t *kad_reshape(kad_node_t *x, int n_d, int *d)
{
kad_node_t *s;
int32_t i, *aux = 0;
if (n_d > 0) {
aux = (int32_t*)malloc(n_d * 4);
for (i = 0; i < n_d; ++i) aux[i] = d? d[i] : -1;
}
s = kad_new_core(0, 30, 1);
s->child[0] = x, s->ptr = aux, s->ptr_size = n_d * 4;
return kad_finalize_node(s);
}
kad_node_t *kad_reverse(kad_node_t *x, int axis)
{
kad_node_t *s;
int32_t *aux;
aux = (int32_t*)malloc(4);
*aux = axis;
s = kad_new_core(0, 36, 1);
s->child[0] = x, s->ptr = aux, s->ptr_size = 4;
return kad_finalize_node(s);
}
kad_node_t *kad_switch(int n, kad_node_t **p)
{
kad_node_t *s;
int32_t i, *aux;
aux = (int32_t*)calloc(1, 4);
s = kad_new_core(0, 12, n);
for (i = 0; i < n; ++i)
s->child[i] = p[i];
s->ptr = aux, s->ptr_size = 4;
return kad_finalize_node(s);
}
/***********************
* Graph linearization *
***********************/
static void kad_mark_back(int n, kad_node_t **v)
{
int i, j;
for (i = 0; i < n; ++i) {
if (v[i]->n_child == 0) continue;
for (j = 0; j < v[i]->n_child; ++j)
if (kad_is_back(v[i]->child[j]))
break;
if (j < v[i]->n_child) v[i]->flag |= KAD_VAR;
else v[i]->flag &= ~KAD_VAR;
}
}
static void kad_allocate_internal(int n, kad_node_t **v)
{
int i;
kad_mark_back(n, v);
for (i = 0; i < n; ++i) {
kad_node_t *p = v[i];
if (p->n_child == 0) continue;
p->x = (float*)realloc(p->x, kad_len(p) * sizeof(float));
if (kad_is_back(p)) {
p->g = (float*)realloc(p->g, kad_len(p) * sizeof(float));
kad_op_list[p->op](p, KAD_ALLOC);
}
}
}
int kad_sync_dim(int n, kad_node_t **v, int batch_size)
{
int i, req_alloc = 0, req_sync = 0, old_size = 0;
for (i = 0; i < n; ++i) {
if (kad_is_feed(v[i])) {
old_size = v[i]->d[0]; /* TODO: check if all feeds have the same batch size */
if (batch_size > 0 && v[i]->d[0] != batch_size)
v[i]->d[0] = batch_size, req_sync = 1;
} else if (v[i]->n_child > 0 && req_sync)
kad_op_list[v[i]->op](v[i], KAD_SYNC_DIM);
}
if (old_size < batch_size) req_alloc = 1;
for (i = 0; i < n; ++i)
if (v[i]->n_child > 0 && v[i]->x == 0) req_alloc = 1;
if (req_alloc) kad_allocate_internal(n, v);
return batch_size > 0? batch_size : old_size;
}
#define kvec_t(type) struct { size_t n, m; type *a; }
#define kv_pop(v) ((v).a[--(v).n])
#define kv_push(type, v, x) do { \
if ((v).n == (v).m) { \
(v).m = (v).m? (v).m<<1 : 2; \
(v).a = (type*)realloc((v).a, sizeof(type) * (v).m); \
} \
(v).a[(v).n++] = (x); \
} while (0)
/* IMPORTANT: kad_node_t::tmp MUST BE set to zero before calling this function */
kad_node_t **kad_compile_array(int *n_node, int n_roots, kad_node_t **roots)
{
int i;
kvec_t(kad_node_p) stack = {0,0,0}, a = {0,0,0};
/* generate kad_node_t::tmp, the count of the parent nodes; shifted by 1; lowest bit to detect fake roots */
for (i = 0; i < n_roots; ++i) {
roots[i]->tmp = 1; /* mark the root */
kv_push(kad_node_p, stack, roots[i]);
}
while (stack.n) {
kad_node_t *p = kv_pop(stack);
for (i = 0; i < p->n_child; ++i) {
kad_node_t *q = p->child[i];
if (q->tmp == 0) kv_push(kad_node_p, stack, q);
q->tmp += 1<<1;
}
}
/* topological sorting (Kahn's algorithm) */
for (i = 0; i < n_roots; ++i)
if (roots[i]->tmp>>1 == 0) /* if roots[i]->tmp>>1 != 0, it is not a real root */
kv_push(kad_node_p, stack, roots[i]);
while (stack.n) {
kad_node_t *p = kv_pop(stack);
kv_push(kad_node_p, a, p);
for (i = 0; i < p->n_child; ++i) {
p->child[i]->tmp -= 1<<1;
if (p->child[i]->tmp>>1 == 0)
kv_push(kad_node_p, stack, p->child[i]);
}
}
free(stack.a);
for (i = 0; i < (int)a.n; ++i) { /* check cycles; no cycles if constructed with kad_add() etc */
assert(a.a[i]->tmp>>1 == 0);
a.a[i]->tmp = 0;
}
/* reverse */
for (i = 0; i < (int)a.n>>1; ++i) { /* reverse a.a[] */
kad_node_p t;
t = a.a[i], a.a[i] = a.a[a.n-1-i], a.a[a.n-1-i] = t;
}
kad_allocate_internal(a.n, a.a);
*n_node = a.n;
return a.a;
}
kad_node_t **kad_compile(int *n_node, int n_roots, ...)
{
int i;
kad_node_t **roots, **ret;
va_list ap;
roots = (kad_node_t**)malloc(n_roots * sizeof(kad_node_t*));
va_start(ap, n_roots);
for (i = 0; i < n_roots; ++i) roots[i] = va_arg(ap, kad_node_p);
va_end(ap);
ret = kad_compile_array(n_node, n_roots, roots);
free(roots);
return ret;
}
/************************************
* Miscellaneous on compiled graphs *
************************************/
void kad_delete(int n, kad_node_t **a)
{
int i;
for (i = 0; i < n; ++i) {
kad_node_t *p = a[i];
if (p->n_child) {
free(p->x); free(p->g);
}
free(p->child); free(p->ptr); free(p->gtmp); free(p);
}
free(a);
}
int kad_size_var(int n, kad_node_t *const* v)
{
int c, i;
for (i = c = 0; i < n; ++i)
if (kad_is_var(v[i]))
c += kad_len(v[i]);
return c;
}
int kad_size_const(int n, kad_node_t *const* v)
{
int c, i;
for (i = c = 0; i < n; ++i)
if (kad_is_const(v[i]))
c += kad_len(v[i]);
return c;
}
/**********************************
* Computate values and gradients *
**********************************/
static void kad_propagate_marks(int n, kad_node_t **a)
{
int i, j;
for (i = n - 1; i >= 0; --i) {
kad_node_t *p = a[i];
if (p->tmp > 0) {
if (kad_is_switch(p)) {
int32_t *aux = (int32_t*)p->ptr;
if (p->child[*aux]->tmp == 0)
p->child[*aux]->tmp = 1;
} else {
for (j = 0; j < p->n_child; ++j)
if (p->child[j]->tmp == 0)
p->child[j]->tmp = 1;
}
}
}
}
void kad_eval_marked(int n, kad_node_t **a)
{
int i;
kad_propagate_marks(n, a);
for (i = 0; i < n; ++i)
if (a[i]->n_child && a[i]->tmp > 0)
kad_op_list[a[i]->op](a[i], KAD_FORWARD);
for (i = 0; i < n; ++i) a[i]->tmp = 0;
}
const float *kad_eval_at(int n, kad_node_t **a, int from)
{
int i;
if (from < 0 || from >= n) from = n - 1;
for (i = 0; i < n; ++i) a[i]->tmp = (i == from);
kad_eval_marked(n, a);
return a[from]->x;
}
void kad_grad(int n, kad_node_t **a, int from)
{
int i;
if (from < 0 || from >= n) from = n - 1;
assert(a[from]->n_d == 0);
for (i = 0; i < n; ++i) a[i]->tmp = (i == from);
kad_propagate_marks(n, a);
for (i = 0; i <= from; ++i) /* set all grandients to zero */
if (a[i]->g && a[i]->tmp > 0)
memset(a[i]->g, 0, kad_len(a[i]) * sizeof(float));
for (i = from, a[i]->g[0] = 1.0f; i >= 0; --i) /* backprop */
if (a[i]->n_child && a[i]->tmp > 0)
kad_op_list[a[i]->op](a[i], KAD_BACKWARD);
for (i = 0; i <= from; ++i) a[i]->tmp = 0;
}
/***********************
* Load and save graph *
***********************/
static void kad_save1(FILE *fp, const kad_node_t *p)
{
fwrite(&p->ext_label, 4, 1, fp);
fwrite(&p->ext_flag, 4, 1, fp);
fwrite(&p->flag, 1, 1, fp);
fwrite(&p->n_child, 4, 1, fp);
if (p->n_child) {
int32_t j, pre = p->pre? p->pre->tmp : -1;
fwrite(&p->op, 2, 1, fp);
for (j = 0; j < p->n_child; ++j)
fwrite(&p->child[j]->tmp, 4, 1, fp);
fwrite(&pre, 4, 1, fp);
fwrite(&p->ptr_size, 4, 1, fp);
if (p->ptr_size > 0 && p->ptr)
fwrite(p->ptr, p->ptr_size, 1, fp);
} else {
fwrite(&p->n_d, 1, 1, fp);
if (p->n_d) fwrite(p->d, 4, p->n_d, fp);
}
}
static kad_node_t *kad_load1(FILE *fp, kad_node_t **node)
{
kad_node_t *p;
p = (kad_node_t*)calloc(1, sizeof(kad_node_t));
fread(&p->ext_label, 4, 1, fp);
fread(&p->ext_flag, 4, 1, fp);
fread(&p->flag, 1, 1, fp);
fread(&p->n_child, 4, 1, fp);
if (p->n_child) {
int32_t j, k;
p->child = (kad_node_t**)calloc(p->n_child, sizeof(kad_node_t*));
fread(&p->op, 2, 1, fp);
for (j = 0; j < p->n_child; ++j) {
fread(&k, 4, 1, fp);
p->child[j] = node? node[k] : 0;
}
fread(&k, 4, 1, fp);
if (k >= 0) p->pre = node[k];
fread(&p->ptr_size, 4, 1, fp);
if (p->ptr_size > 0) {
p->ptr = malloc(p->ptr_size);
fread(p->ptr, p->ptr_size, 1, fp);
}
} else {
fread(&p->n_d, 1, 1, fp);
if (p->n_d) fread(p->d, 4, p->n_d, fp);
}
return p;
}
int kad_save(FILE *fp, int n_node, kad_node_t **node)
{
int32_t i, k = n_node;
fwrite(&k, 4, 1, fp);
for (i = 0; i < n_node; ++i) node[i]->tmp = i;
for (i = 0; i < n_node; ++i) kad_save1(fp, node[i]);
for (i = 0; i < n_node; ++i) node[i]->tmp = 0;
return 0;
}
kad_node_t **kad_load(FILE *fp, int *_n_node)
{
int32_t i, n_node;
kad_node_t **node;
fread(&n_node, 4, 1, fp);
node = (kad_node_t**)malloc(n_node * sizeof(kad_node_t*));
for (i = 0; i < n_node; ++i) {
kad_node_t *p;
p = node[i] = kad_load1(fp, node);
if (p->n_child) {
kad_op_list[p->op](p, KAD_ALLOC);
kad_op_list[p->op](p, KAD_SYNC_DIM);
}
}
*_n_node = n_node;
kad_mark_back(n_node, node);
return node;
}
/***************
* Graph clone *
***************/
static inline kad_node_t *kad_dup1(const kad_node_t *p)
{
kad_node_t *q;
q = (kad_node_t*)malloc(sizeof(kad_node_t));
memcpy(q, p, sizeof(kad_node_t));
q->pre = 0, q->tmp = 0, q->gtmp = 0;
if (p->ptr && p->ptr_size > 0) {
if (kad_use_rng(p) && !(p->flag & KAD_SHARE_RNG) && p->ptr_size == sizeof(kad_rng_t)) {
q->ptr = kad_rng(); /* each time step uses a different RNG */
} else {
q->ptr = malloc(p->ptr_size);
memcpy(q->ptr, p->ptr, p->ptr_size);
}
}
if (q->n_child) {
q->x = q->g = 0;
q->child = (kad_node_t**)calloc(q->n_child, sizeof(kad_node_t*));
}
return q;
}
kad_node_t **kad_clone(int n, kad_node_t **v, int batch_size)
{
int i, j;
kad_node_t **u;
u = (kad_node_t**)calloc(n, sizeof(kad_node_t*));
for (i = 0; i < n; ++i) v[i]->tmp = i;
for (i = 0; i < n; ++i) {
kad_node_t *p = v[i], *q;
q = u[i] = kad_dup1(p);
if (p->pre) q->pre = u[p->pre->tmp];
if (p->n_child) {
for (j = 0; j < p->n_child; ++j)
q->child[j] = u[p->child[j]->tmp];
} else if (!kad_is_feed(p)) {
q->x = (float*)malloc(kad_len(p) * sizeof(float));
memcpy(q->x, p->x, kad_len(p) * sizeof(float));
q->g = 0;
}
}
for (i = 0; i < n; ++i) v[i]->tmp = 0;
kad_sync_dim(n, u, batch_size); /* this will allocate x[] and g[] at internal nodes */
return u;
}
/**************
* Unroll RNN *
**************/
typedef struct {
int32_t n, m;
kad_node_t **v;
} nodes_t;
static inline void push_nodes(nodes_t *w, kad_node_t *p)
{
if (w->n == w->m) {
w->m = w->m? w->m<<1 : 16;
w->v = (kad_node_t**)realloc(w->v, w->m * sizeof(kad_node_t*));
}
w->v[w->n++] = p;
}
static void kad_unroll_helper(int n_v, kad_node_t **v, int i_pivot, kad_node_t **t, int len, nodes_t *w)
{
int i, j, l;
uint8_t *flag;
kad_node_t **aux;
assert(kad_is_pivot(v[i_pivot]) && t[i_pivot] == 0);
t[i_pivot] = kad_dup1(v[i_pivot]);
t[i_pivot]->n_child = len;
t[i_pivot]->child = (kad_node_t**)realloc(t[i_pivot]->child, len * sizeof(kad_node_t*));
flag = (uint8_t*)calloc(n_v, 1);
for (i = i_pivot, flag[i] = 16; i >= 0; --i) {
if (i < i_pivot && kad_is_pivot(v[i])) continue; /* don't trespass other pivots */
if (flag[i]&16) /* flag 16: nodes to unroll */
for (j = 0; j < v[i]->n_child; ++j)
flag[v[i]->child[j]->tmp] = 16;
}
for (i = 0; i < i_pivot; ++i) {
if (!(flag[i]&16)) continue;
if (kad_is_var(v[i]) || kad_is_const(v[i]) || kad_is_pivot(v[i])) flag[i] |= 1; /* external nodes that should not be duplicated */
if (v[i]->pre) flag[v[i]->pre->tmp] |= 2;
}
flag[v[i_pivot]->child[0]->tmp] |= 4;
aux = (kad_node_t**)calloc(n_v, sizeof(kad_node_t*));
for (l = 0; l < len; ++l) {
for (i = 0; i < i_pivot; ++i) {
if (!(flag[i]&16) || ((flag[i]&3) && t[i])) continue;
t[i] = kad_dup1(v[i]);
if (v[i]->n_child)
for (j = 0; j < v[i]->n_child; ++j)
t[i]->child[j] = t[v[i]->child[j]->tmp];
if (flag[i]&4) t[i_pivot]->child[l] = t[i];
if (l == 0 && (flag[i]&2)) aux[i] = t[i];
if (v[i]->pre) {
t[v[i]->pre->tmp] = t[i];
if (l == len - 1) t[i]->pre = aux[v[i]->pre->tmp]; /* this forms a cycle! */
}
push_nodes(w, t[i]);
}
}
push_nodes(w, t[i_pivot]);
free(aux); free(flag);
}
int kad_n_pivots(int n_v, kad_node_t **v)
{
int i, n_pivots = 0;
for (i = 0; i < n_v; ++i)
if (kad_is_pivot(v[i])) ++n_pivots;
return n_pivots;
}
kad_node_t **kad_unroll(int n_v, kad_node_t **v, int *new_n, int *len)
{
int i, j, n_pivots = 0;
kad_node_t **t;
nodes_t w = {0,0,0};
t = (kad_node_t**)calloc(n_v, sizeof(kad_node_t*));
n_pivots = kad_n_pivots(n_v, v);
for (i = 0; i < n_v; ++i) v[i]->tmp = i;
if (n_pivots) {
int k, *i_pivots;
i_pivots = (int*)calloc(n_pivots, sizeof(int));
for (i = k = 0; i < n_v; ++i) /* collect pivots */
if (kad_is_pivot(v[i])) i_pivots[k++] = i;
for (i = 0; i < n_pivots; ++i) /* unroll each pivot, from the lowest to the highest */
kad_unroll_helper(n_v, v, i_pivots[i], t, len[i], &w);
free(i_pivots);
}
for (i = 0; i < n_v; ++i) { /* copy over the rest of nodes */
if (t[i]) continue;
t[i] = kad_dup1(v[i]);
if (v[i]->n_child)
for (j = 0; j < v[i]->n_child; ++j)
t[i]->child[j] = t[v[i]->child[j]->tmp];
push_nodes(&w, t[i]);
}
free(t);
for (i = 0; i < n_v; ++i) v[i]->tmp = 0;
for (i = 0; i < w.n; ++i) /* stack may change the output dimension */
if (w.v[i]->n_child > 0)
kad_op_list[w.v[i]->op](w.v[i], KAD_SYNC_DIM);
kad_allocate_internal(w.n, w.v);
*new_n = w.n;
return w.v;
}
/********************************
* Vector and matrix operations *
********************************/
#ifdef __SSE__
#include <xmmintrin.h>
static inline float kad_sdot(int n, const float *x, const float *y) /* BLAS sdot using SSE */
{
int i, n8 = n>>3<<3;
__m128 vs1, vs2;
float s, t[4];
vs1 = _mm_setzero_ps();
vs2 = _mm_setzero_ps();
for (i = 0; i < n8; i += 8) {
__m128 vx1, vx2, vy1, vy2;
vx1 = _mm_loadu_ps(&x[i]);
vx2 = _mm_loadu_ps(&x[i+4]);
vy1 = _mm_loadu_ps(&y[i]);
vy2 = _mm_loadu_ps(&y[i+4]);
vs1 = _mm_add_ps(vs1, _mm_mul_ps(vx1, vy1));
vs2 = _mm_add_ps(vs2, _mm_mul_ps(vx2, vy2));
}
for (s = 0.; i < n; ++i) s += x[i] * y[i];
_mm_storeu_ps(t, vs1);
s += t[0] + t[1] + t[2] + t[3];
_mm_storeu_ps(t, vs2);
s += t[0] + t[1] + t[2] + t[3];
return s;
}
static inline void kad_saxpy_inlined(int n, float a, const float *x, float *y) /* BLAS saxpy using SSE */
{
int i, n8 = n>>3<<3;
__m128 va;
va = _mm_set1_ps(a);
for (i = 0; i < n8; i += 8) {
__m128 vx1, vx2, vy1, vy2, vt1, vt2;
vx1 = _mm_loadu_ps(&x[i]);
vx2 = _mm_loadu_ps(&x[i+4]);
vy1 = _mm_loadu_ps(&y[i]);
vy2 = _mm_loadu_ps(&y[i+4]);
vt1 = _mm_add_ps(_mm_mul_ps(va, vx1), vy1);
vt2 = _mm_add_ps(_mm_mul_ps(va, vx2), vy2);
_mm_storeu_ps(&y[i], vt1);
_mm_storeu_ps(&y[i+4], vt2);
}
for (; i < n; ++i) y[i] += a * x[i];
}
#else
static inline float kad_sdot(int n, const float *x, const float *y) /* BLAS sdot */
{
int i;
float s = 0.;
for (i = 0; i < n; ++i) s += x[i] * y[i];
return s;
}
static inline void kad_saxpy_inlined(int n, float a, const float *x, float *y) // BLAS saxpy
{
int i;
for (i = 0; i < n; ++i) y[i] += a * x[i];
}
#endif
void kad_vec_mul_sum(int n, float *a, const float *b, const float *c)
{
int i;
for (i = 0; i < n; ++i) a[i] += b[i] * c[i];
}
void kad_saxpy(int n, float a, const float *x, float *y) { kad_saxpy_inlined(n, a, x, y); }
#ifdef HAVE_CBLAS
#include <cblas.h>
void kad_sgemm_simple(int trans_A, int trans_B, int M, int N, int K, const float *A, const float *B, float *C)
{
cblas_sgemm(CblasRowMajor, trans_A? CblasTrans : CblasNoTrans, trans_B? CblasTrans : CblasNoTrans, M, N, K, 1.0f, A, trans_A? M : K, B, trans_B? K : N, 1.0f, C, N);
}
#else
void kad_sgemm_simple(int trans_A, int trans_B, int M, int N, int K, const float *A, const float *B, float *C) /* simplified BLAS sgemm */
{
static const int x = 16;
int i, j, k;
if (!trans_A && trans_B) {
for (i = 0; i < M; i += x)
for (j = 0; j < N; j += x) {
int ii, ie = M < i + x? M : i + x;
int jj, je = N < j + x? N : j + x;
for (ii = i; ii < ie; ++ii) { /* loop tiling */
const float *aii = A + ii * K, *bjj;
float *cii = C + ii * N;
for (jj = j, bjj = B + j * K; jj < je; ++jj, bjj += K)
cii[jj] += kad_sdot(K, aii, bjj);
}
}
} else if (!trans_A && !trans_B) {
for (i = 0; i < M; ++i)
for (k = 0; k < K; ++k)
kad_saxpy_inlined(N, A[i*K+k], &B[k*N], &C[i*N]);
} else if (trans_A && !trans_B) {
for (k = 0; k < K; ++k)
for (i = 0; i < M; ++i)
kad_saxpy_inlined(N, A[k*M+i], &B[k*N], &C[i*N]);
} else abort(); /* not implemented for (trans_A && trans_B) */
}
#endif
/***************************
* Random number generator *
***************************/
static kad_rng_t kad_rng_dat = { {0x50f5647d2380309dULL, 0x91ffa96fc4c62cceULL}, 0.0, 0, 0 };
static inline uint64_t kad_splitmix64(uint64_t x)
{
uint64_t z = (x += 0x9E3779B97F4A7C15ULL);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
return z ^ (z >> 31);
}
static inline uint64_t kad_xoroshiro128plus_next(kad_rng_t *r)
{
const uint64_t s0 = r->s[0];
uint64_t s1 = r->s[1];
const uint64_t result = s0 + s1;
s1 ^= s0;
r->s[0] = (s0 << 55 | s0 >> 9) ^ s1 ^ (s1 << 14);
r->s[1] = s0 << 36 | s0 >> 28;
return result;
}
static inline void kad_xoroshiro128plus_jump(kad_rng_t *r)
{
static const uint64_t JUMP[] = { 0xbeac0467eba5facbULL, 0xd86b048b86aa9922ULL };
uint64_t s0 = 0, s1 = 0;
int i, b;
for (i = 0; i < 2; ++i)
for (b = 0; b < 64; b++) {
if (JUMP[i] & 1ULL << b)
s0 ^= r->s[0], s1 ^= r->s[1];
kad_xoroshiro128plus_next(r);
}
r->s[0] = s0, r->s[1] = s1;
}
void kad_srand(void *d, uint64_t seed)
{
kad_rng_t *r = d? (kad_rng_t*)d : &kad_rng_dat;
r->n_gset = 0.0, r->n_iset = 0;
r->s[0] = kad_splitmix64(seed);
r->s[1] = kad_splitmix64(r->s[0]);
}
void *kad_rng(void)
{
kad_rng_t *r;
r = (kad_rng_t*)calloc(1, sizeof(kad_rng_t));
kad_xoroshiro128plus_jump(&kad_rng_dat);
r->s[0] = kad_rng_dat.s[0], r->s[1] = kad_rng_dat.s[1];
return r;
}
uint64_t kad_rand(void *d) { return kad_xoroshiro128plus_next(d? (kad_rng_t*)d : &kad_rng_dat); }
double kad_drand(void *d)
{
union { uint64_t i; double d; } u;
u.i = 0x3FFULL << 52 | kad_xoroshiro128plus_next(d? (kad_rng_t*)d : &kad_rng_dat) >> 12;
return u.d - 1.0;
}
double kad_drand_normal(void *d)
{
kad_rng_t *r = d? (kad_rng_t*)d : &kad_rng_dat;
if (r->n_iset == 0) {
double fac, rsq, v1, v2;
do {
v1 = 2.0 * kad_drand(d) - 1.0;
v2 = 2.0 * kad_drand(d) - 1.0;
rsq = v1 * v1 + v2 * v2;
} while (rsq >= 1.0 || rsq == 0.0);
fac = sqrt(-2.0 * log(rsq) / rsq);
r->n_gset = v1 * fac;
r->n_iset = 1;
return v2 * fac;
} else {
r->n_iset = 0;
return r->n_gset;
}
}
/*************
* Operators *
*************/
static inline void kad_copy_dim1(kad_node_t *dst, const kad_node_t *src) /* set the dimension/shape of dst to src */
{
dst->n_d = src->n_d;
if (src->n_d) memcpy(dst->d, src->d, src->n_d * sizeof(int));
}
/********** Arithmetic operations **********/
int kad_op_add(kad_node_t *p, int action)
{
int i, n0, n1;
kad_node_t *q[2];
q[0] = p->child[0], n0 = kad_len(q[0]);
q[1] = p->child[1], n1 = kad_len(q[1]);
if (action == KAD_SYNC_DIM) {
if (n0 % n1 != 0) return -1;
kad_copy_dim1(p, q[0]);
} else if (action == KAD_FORWARD) {
assert(n0 >= n1);
memcpy(p->x, q[0]->x, n0 * sizeof(float));
for (i = 0; i < n0; i += n1)
kad_saxpy(n1, 1.0f, q[1]->x, p->x + i);
} else if (action == KAD_BACKWARD) {
if (kad_is_back(q[0])) kad_saxpy(n0, 1.0f, p->g, q[0]->g);
if (kad_is_back(q[1]))
for (i = 0; i < n0; i += n1)
kad_saxpy(n1, 1.0f, p->g + i, q[1]->g);
}
return 0;
}
int kad_op_sub(kad_node_t *p, int action)
{
int i, n0, n1;
kad_node_t *q[2];
q[0] = p->child[0], n0 = kad_len(q[0]);
q[1] = p->child[1], n1 = kad_len(q[1]);
if (action == KAD_SYNC_DIM) {
if (n0 % n1 != 0) return -1;
kad_copy_dim1(p, q[0]);
} else if (action == KAD_FORWARD) {
assert(n0 >= n1);
memcpy(p->x, q[0]->x, n0 * sizeof(float));
for (i = 0; i < n0; i += n1)
kad_saxpy(n1, -1.0f, q[1]->x, p->x + i);
} else if (action == KAD_BACKWARD) {
if (kad_is_back(q[0])) kad_saxpy(n0, 1.0f, p->g, q[0]->g);
if (kad_is_back(q[1]))
for (i = 0; i < n0; i += n1)
kad_saxpy(n1, -1.0f, p->g + i, q[1]->g);
}
return 0;
}
int kad_op_mul(kad_node_t *p, int action)
{
int i, n0, n1;
kad_node_t *q[2];
q[0] = p->child[0], n0 = kad_len(q[0]);
q[1] = p->child[1], n1 = kad_len(q[1]);
if (action == KAD_SYNC_DIM) {
if (n0 % n1 != 0) return -1;
kad_copy_dim1(p, q[0]);
} else if (action == KAD_FORWARD) {
assert(n0 >= n1);
memset(p->x, 0, n0 * sizeof(float));
if (q[0]->x != 0 && q[1]->x != 0)
for (i = 0; i < n0; i += n1) /* TODO: optimize when n1==1 */
kad_vec_mul_sum(n1, p->x + i, q[0]->x + i, q[1]->x);
} else if (action == KAD_BACKWARD) {
if (kad_is_back(q[0]) && q[1]->x)
for (i = 0; i < n0; i += n1)
kad_vec_mul_sum(n1, q[0]->g + i, p->g + i, q[1]->x);
if (kad_is_back(q[1]) && q[0]->x)
for (i = 0; i < n0; i += n1)
kad_vec_mul_sum(n1, q[1]->g, p->g + i, q[0]->x + i);
}
return 0;
}
int kad_op_cmul(kad_node_t *p, int action)
{
int i, n_a_row, n_b_row, n_col, n_a_col = 1, n_b_col = 1;
kad_node_t *q[2];
q[0] = p->child[0], q[1] = p->child[1];
n_col = q[0]->d[q[0]->n_d - 1] > q[1]->d[q[1]->n_d - 1]? q[0]->d[q[0]->n_d - 1] : q[1]->d[q[1]->n_d - 1];
for (i = q[0]->n_d - 1; i >= 0; --i) if (n_a_col < n_col) n_a_col *= q[0]->d[i];
for (i = q[1]->n_d - 1; i >= 0; --i) if (n_b_col < n_col) n_b_col *= q[1]->d[i];
n_a_row = kad_len(q[0]) / n_a_col, n_b_row = kad_len(q[1]) / n_b_col;
if (action == KAD_SYNC_DIM) {
if (n_a_col != n_b_col) return -1;
p->n_d = 2, p->d[0] = n_a_row, p->d[1] = n_b_row;
} else if (action == KAD_FORWARD) {
memset(p->x, 0, n_a_row * n_b_row * sizeof(float));
if (q[0]->x && q[1]->x)
kad_sgemm_simple(0, 1, n_a_row, n_b_row, n_col, q[0]->x, q[1]->x, p->x); /* Y = X * trans(W) */
} else if (action == KAD_BACKWARD) {
if (kad_is_back(q[0]) && q[1]->x)
kad_sgemm_simple(0, 0, n_a_row, n_col, n_b_row, p->g, q[1]->x, q[0]->g); /* G_x <- G_y * W */
if (kad_is_back(q[1]) && q[0]->x)
kad_sgemm_simple(1, 0, n_b_row, n_col, n_a_row, p->g, q[0]->x, q[1]->g); /* G_w <- trans(G_y) * X */
}
return 0;
}
int kad_op_matmul(kad_node_t *p, int action) /* TODO: matmul and cmul have different broadcasting rules */
{
int n_a_row, n_b_row, n_a_col, n_b_col;
kad_node_t *q[2];
q[0] = p->child[0];
q[1] = p->child[1];
n_a_row = q[0]->n_d == 1? 1 : q[0]->d[0];
n_b_row = q[1]->n_d == 1? 1 : q[1]->d[0];
n_a_col = kad_len(q[0]) / n_a_row;
n_b_col = kad_len(q[1]) / n_b_row;
if (action == KAD_SYNC_DIM) {
if (n_a_col != n_b_row) return -1;
p->n_d = 2, p->d[0] = n_a_row, p->d[1] = n_b_col;
} else if (action == KAD_FORWARD) {
memset(p->x, 0, n_a_row * n_b_col * sizeof(float));
if (q[0]->x && q[1]->x)
kad_sgemm_simple(0, 0, n_a_row, n_b_col, n_a_col, q[0]->x, q[1]->x, p->x); /* Y = X * W */
} else if (action == KAD_BACKWARD) {
if (kad_is_back(q[0]) && q[1]->x)
kad_sgemm_simple(0, 1, n_a_row, n_a_col, n_b_col, p->g, q[1]->x, q[0]->g); /* G_x <- G_y * trans(W) */
if (kad_is_back(q[1]) && q[0]->x)
kad_sgemm_simple(1, 0, n_b_row, n_b_col, n_a_row, q[0]->x, p->g, q[1]->g); /* G_y <- trans(A) * G_y */
}
return 0;
}
int kad_op_square(kad_node_t *p, int action)
{
int i, n;
kad_node_t *q = p->child[0];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
for (i = 0; i < n; ++i)
p->x[i] = q->x[i] * q->x[i];
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
for (i = 0; i < n; ++i)
q->g[i] += p->g[i] * (q->x[i] + q->x[i]);
}
return 0;
}
int kad_op_1minus(kad_node_t *p, int action)
{
int i, n;
kad_node_t *q = p->child[0];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
for (i = 0; i < n; ++i) p->x[i] = 1.0f - q->x[i];
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
kad_saxpy(n, -1.0f, p->g, q->g);
}
return 0;
}
int kad_op_exp(kad_node_t *p, int action)
{
int i, n;
kad_node_t *q = p->child[0];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
for (i = 0; i < n; ++i) p->x[i] = expf(q->x[i]);
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
for (i = 0; i < n; ++i)
q->g[i] += p->g[i] * p->x[i];
}
return 0;
}
int kad_op_log(kad_node_t *p, int action)
{
int i, n;
kad_node_t *q = p->child[0];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
for (i = 0; i < n; ++i) p->x[i] = logf(q->x[i]);
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
for (i = 0; i < n; ++i)
q->g[i] += p->g[i] / q->x[i];
}
return 0;
}
int kad_op_reduce_sum(kad_node_t *p, int action)
{
kad_node_t *q = p->child[0];
int i, j, k, axis, d0, d1;
assert(p->ptr);
axis = *(int32_t*)p->ptr;
if (axis < 0 || axis >= q->n_d) return -1;
for (i = 0, d0 = 1; i < axis; ++i) d0 *= q->d[i];
for (i = axis + 1, d1 = 1; i < q->n_d; ++i) d1 *= q->d[i];
if (action == KAD_SYNC_DIM) {
p->n_d = q->n_d - 1;
for (i = j = 0; i < q->n_d; ++i)
if (i != axis) p->d[j++] = q->d[i];
} else if (action == KAD_FORWARD) {
memset(p->x, 0, kad_len(p) * sizeof(float));
for (i = 0; i < d0; ++i)
for (j = 0; j < q->d[axis]; ++j)
for (k = 0; k < d1; ++k)
p->x[i * d1 + k] += q->x[(i * q->d[axis] + j) * d1 + k];
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
for (i = 0; i < d0; ++i)
for (j = 0; j < q->d[axis]; ++j)
for (k = 0; k < d1; ++k)
q->g[(i * q->d[axis] + j) * d1 + k] += p->g[i * d1 + k];
}
return 0;
}
int kad_op_reduce_mean(kad_node_t *p, int action)
{
kad_node_t *q = p->child[0];
int i, j, k, axis, d0, d1;
assert(p->ptr);
axis = *(int32_t*)p->ptr;
if (axis < 0 || axis >= q->n_d) return -1;
for (i = 0, d0 = 1; i < axis; ++i) d0 *= q->d[i];
for (i = axis + 1, d1 = 1; i < q->n_d; ++i) d1 *= q->d[i];
if (action == KAD_SYNC_DIM) {
p->n_d = q->n_d - 1;
for (i = j = 0; i < q->n_d; ++i)
if (i != axis) p->d[j++] = q->d[i];
} else if (action == KAD_FORWARD) {
float t = 1.0f / q->d[axis];
memset(p->x, 0, kad_len(p) * sizeof(float));
for (i = 0; i < d0; ++i)
for (j = 0; j < q->d[axis]; ++j)
for (k = 0; k < d1; ++k)
p->x[i * d1 + k] += t * q->x[(i * q->d[axis] + j) * d1 + k];
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
float t = 1.0f / q->d[axis];
for (i = 0; i < d0; ++i)
for (j = 0; j < q->d[axis]; ++j)
for (k = 0; k < d1; ++k)
q->g[(i * q->d[axis] + j) * d1 + k] += t * p->g[i * d1 + k];
}
return 0;
}
/********** Miscellaneous **********/
int kad_op_dropout(kad_node_t *p, int action)
{
int i, n;
kad_node_t *q = p->child[0];
assert(p->child[1]->n_d == 0);
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_ALLOC) {
if (kad_is_back(p->child[0]))
p->gtmp = realloc(p->gtmp, n);
} else if (action == KAD_FORWARD) {
float r = kad_is_const(q) || kad_is_var(q)? 0.0f : *p->child[1]->x, z = 1.0f / (1.0f - r);
uint8_t *flag = (uint8_t*)p->gtmp;
for (i = 0; i < n; ++i) {
int kept = (kad_drand(p->ptr) >= r);
p->x[i] = kept? q->x[i] * z : 0.0f;
if (flag) flag[i] = kept;
}
} else if (action == KAD_BACKWARD && kad_is_back(p->child[0])) {
float r = kad_is_const(q) || kad_is_var(q)? 0.0f : *p->child[1]->x, z = 1.0f / (1.0f - r);
uint8_t *flag = (uint8_t*)p->gtmp;
for (i = 0; i < n; ++i)
if (flag[i]) q->g[i] += z * p->g[i];
}
return 0;
}
int kad_op_sample_normal(kad_node_t *p, int action) /* not tested */
{
int i, n;
kad_node_t *q = p->child[0];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_ALLOC) {
if (kad_is_back(p->child[0]))
p->gtmp = realloc(p->gtmp, n * sizeof(float));
} else if (action == KAD_FORWARD) {
float *r = (float*)p->gtmp;
for (i = 0; i < n; ++i) {
float z;
z = (float)kad_drand_normal(p->ptr);
p->x[i] = q->x[i] * z;
if (r) r[i] = z;
}
} else if (action == KAD_BACKWARD && kad_is_back(p->child[0])) {
float *r = (float*)p->gtmp;
for (i = 0; i < n; ++i)
q->g[i] += p->g[i] * r[i];
}
return 0;
}
int kad_op_slice(kad_node_t *p, int action)
{
kad_node_t *q = p->child[0];
int32_t *aux, *range;
int i, axis, d0, d1;
assert(p->ptr);
aux = (int32_t*)p->ptr, axis = aux[0], range = aux + 1;
if (axis < 0 || axis >= q->n_d) return -1;
for (i = 0, d0 = 1; i < axis; ++i) d0 *= q->d[i];
for (i = axis + 1, d1 = 1; i < q->n_d; ++i) d1 *= q->d[i];
if (action == KAD_SYNC_DIM) {
if (range[0] >= range[1] || range[0] < 0 || range[1] > q->d[axis]) return -1;
kad_copy_dim1(p, q);
p->d[axis] = range[1] - range[0];
} else if (action == KAD_FORWARD) {
for (i = 0; i < d0; ++i)
memcpy(&p->x[i * p->d[axis] * d1], &q->x[(i * q->d[axis] + range[0]) * d1], (range[1] - range[0]) * d1 * sizeof(float));
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
for (i = 0; i < d0; ++i)
kad_saxpy((range[1] - range[0]) * d1, 1.0f, &p->g[i * p->d[axis] * d1], &q->g[(i * q->d[axis] + range[0]) * d1]);
}
return 0;
}
int kad_op_concat(kad_node_t *p, int action)
{
kad_node_t *q = p->child[0];
int32_t *aux;
int i, j, k, axis, d0, d1;
assert(p->ptr);
aux = (int32_t*)p->ptr, axis = aux[0];
for (i = 0, d0 = 1; i < axis; ++i) d0 *= q->d[i];
for (i = axis + 1, d1 = 1; i < q->n_d; ++i) d1 *= q->d[i];
if (action == KAD_SYNC_DIM) {
for (i = 1; i < p->n_child; ++i) {
if (p->child[i]->n_d != q->n_d) return -1;
for (j = 0; j < q->n_d; ++j)
if (j != axis && q->d[j] != p->child[i]->d[j]) return -1;
}
kad_copy_dim1(p, q);
for (i = 1; i < p->n_child; ++i)
p->d[axis] += p->child[i]->d[axis];
} else if (action == KAD_FORWARD) {
for (i = 0; i < d0; ++i)
for (j = k = 0; j < p->n_child; ++j) {
q = p->child[j];
memcpy(&p->x[(i * p->d[axis] + k) * d1], &q->x[i * q->d[axis] * d1], q->d[axis] * d1 * sizeof(float));
k += q->d[axis];
}
} else if (action == KAD_BACKWARD) {
for (i = 0; i < d0; ++i)
for (j = k = 0; j < p->n_child; ++j) {
q = p->child[j];
if (!kad_is_back(q)) continue;
kad_saxpy(q->d[axis] * d1, 1.0f, &p->g[(i * p->d[axis] + k) * d1], &q->g[i * q->d[axis] * d1]);
k += q->d[axis];
}
}
return 0;
}
int kad_op_reshape(kad_node_t *p, int action)
{
kad_node_t *q = p->child[0];
if (action == KAD_SYNC_DIM) {
if (p->ptr) {
int32_t *aux = (int32_t*)p->ptr;
int i, len = 1, n_missing = 0;
p->n_d = p->ptr_size / 4;
for (i = 0; i < p->n_d; ++i) p->d[i] = aux[i];
for (i = 0; i < p->n_d; ++i)
if (p->d[i] <= 0) ++n_missing;
else len *= p->d[i];
if (n_missing == 0 && len != kad_len(q)) return -1;
if (n_missing > 1) { /* attempt to infer missing dimensions except the last one */
for (i = 0; i < p->n_d; ++i)
if (p->d[i] <= 0 && i < q->n_d) {
p->d[i] = q->d[i], len *= p->d[i];
if (--n_missing == 1) break;
}
if (n_missing > 1) return -1;
}
if (n_missing == 1) { /* infer the last missing dimension */
if (kad_len(q) % len != 0) return -1;
for (i = 0; i < p->n_d; ++i)
if (p->d[i] <= 0) p->d[i] = kad_len(q) / len;
}
} else kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
memcpy(p->x, q->x, kad_len(p) * sizeof(float));
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
kad_saxpy(kad_len(p), 1.0f, p->g, q->g);
}
return 0;
}
int kad_op_reverse(kad_node_t *p, int action)
{
kad_node_t *q = p->child[0];
int axis, i, j, n, d0, d1;
axis = p->ptr? *(int32_t*)p->ptr : 0;
if (axis < 0) axis += q->n_d;
assert(axis >= 0 && axis < q->n_d);
for (i = 0, d0 = 1; i < axis; ++i) d0 *= q->d[i];
n = q->d[axis];
for (i = axis + 1, d1 = 1; i < q->n_d; ++i) d1 *= q->d[i];
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
for (i = 0; i < d0; ++i)
for (j = 0; j < n; ++j)
memcpy(&p->x[(i * n + n - 1 - j) * d1], &q->x[(i * n + j) * d1], d1 * sizeof(float));
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
for (i = 0; i < d0; ++i)
for (j = 0; j < n; ++j)
kad_saxpy(d1, 1.0f, &p->g[(i * n + n - 1 - j) * d1], &q->g[(i * n + j) * d1]);
}
return 0;
}
/********** Cost functions **********/
int kad_op_mse(kad_node_t *p, int action)
{
kad_node_t *y1 = p->child[0]; /* test */
kad_node_t *y0 = p->child[1]; /* truth */
int i, n;
n = kad_len(y0);
if (action == KAD_SYNC_DIM) {
if (n != kad_len(y1)) return -1;
p->n_d = 0;
} else if (action == KAD_FORWARD) {
double cost = 0.0;
for (i = 0; i < n; ++i)
cost += (y1->x[i] - y0->x[i]) * (y1->x[i] - y0->x[i]);
p->x[0] = (float)(cost / n);
} else if (action == KAD_BACKWARD && kad_is_back(y1)) {
float t = 2.0f * p->g[0] / n;
for (i = 0; i < n; ++i)
y1->g[i] += t * (y1->x[i] - y0->x[i]);
}
return 0;
}
int kad_op_ce_bin(kad_node_t *p, int action)
{
static const float tiny = 1e-9f;
kad_node_t *y1 = p->child[0]; /* test */
kad_node_t *y0 = p->child[1]; /* truth */
int i, n;
n = kad_len(y0);
if (action == KAD_SYNC_DIM) {
if (n != kad_len(y1)) return -1;
p->n_d = 0;
} else if (action == KAD_FORWARD) {
double cost = 0.0;
for (i = 0; i < n; ++i) {
if (y0->x[i] > 0.0f)
cost += y0->x[i] * log(y0->x[i] / (y1->x[i] > tiny? y1->x[i] : tiny));
if (1.0f - y0->x[i] > 0.0f)
cost += (1.0f - y0->x[i]) * log((1.0f - y0->x[i]) / (1.0f - y1->x[i] > tiny? 1.0f - y1->x[i] : tiny));
}
p->x[0] = (float)(cost / n);
} else if (action == KAD_BACKWARD && kad_is_back(y1)) {
float t = p->g[0] / n;
for (i = 0; i < n; ++i) {
if (y0->x[i] > 0.0f)
y1->g[i] -= t * y0->x[i] / (y1->x[i] > tiny? y1->x[i] : tiny);
if (1.0f - y0->x[i] > 0.0f)
y1->g[i] += t * (1.0f - y0->x[i]) / (1.0f - y1->x[i] > tiny? 1.0f - y1->x[i] : tiny);
}
}
return 0;
}
int kad_op_ce_bin_neg(kad_node_t *p, int action)
{
static const float tiny = 1e-9f;
kad_node_t *y1 = p->child[0]; /* test */
kad_node_t *y0 = p->child[1]; /* truth */
int i, n;
n = kad_len(y0);
if (action == KAD_SYNC_DIM) {
if (n != kad_len(y1)) return -1;
p->n_d = 0;
} else if (action == KAD_FORWARD) {
double cost = 0.0;
for (i = 0; i < n; ++i) {
if (1.0f + y0->x[i] > 0.0f)
cost += .5f * (1.0f + y0->x[i]) * log((1.0f + y0->x[i]) / (1.0f + y1->x[i] > tiny? 1.0f + y1->x[i] : tiny));
if (1.0f - y0->x[i] > 0.0f)
cost += .5f * (1.0f - y0->x[i]) * log((1.0f - y0->x[i]) / (1.0f - y1->x[i] > tiny? 1.0f - y1->x[i] : tiny));
}
p->x[0] = (float)(cost / n);
} else if (action == KAD_BACKWARD && kad_is_back(y1)) {
float t = p->g[0] / n;
for (i = 0; i < n; ++i) {
if (1.0f + y0->x[i] > 0.0f)
y1->g[i] -= .5f * t * (1.0f + y0->x[i]) / (1.0f + y1->x[i] > tiny? 1.0f + y1->x[i] : tiny);
if (1.0f - y0->x[i] > 0.0f)
y1->g[i] += .5f * t * (1.0f - y0->x[i]) / (1.0f - y1->x[i] > tiny? 1.0f - y1->x[i] : tiny);
}
}
return 0;
}
int kad_op_ce_multi(kad_node_t *p, int action)
{
static const float tiny = 1e-9f;
kad_node_t *y1 = p->child[0]; /* test */
kad_node_t *y0 = p->child[1]; /* truth */
kad_node_t *c = 0;
int i, j, n1, d0;
n1 = y0->d[y0->n_d - 1];
d0 = kad_len(y0) / n1;
if (p->n_child == 3) {
c = p->child[2];
assert(c->n_d == 1 && c->d[0] == n1);
}
if (action == KAD_SYNC_DIM) {
if (kad_len(y0) != kad_len(y1) || y0->d[y0->n_d - 1] != y1->d[y1->n_d - 1]) return -1;
p->n_d = 0;
} else if (action == KAD_FORWARD) {
double cost = 0.0;
if (c == 0) {
for (j = 0; j < d0; ++j) {
float *x1 = &y1->x[j * n1], *x0 = &y0->x[j * n1];
for (i = 0; i < n1; ++i)
if (x0[i] > 0.0f)
cost += x0[i] * log(x0[i] / (x1[i] > tiny? x1[i] : tiny));
}
} else {
for (j = 0; j < d0; ++j) {
float *x1 = &y1->x[j * n1], *x0 = &y0->x[j * n1];
for (i = 0; i < n1; ++i)
if (x0[i] > 0.0f)
cost += c->x[i] * x0[i] * log(x0[i] / (x1[i] > tiny? x1[i] : tiny));
}
}
p->x[0] = (float)(cost / d0);
} else if (action == KAD_BACKWARD && kad_is_back(y1)) {
float t = p->g[0] / d0;
if (c == 0) {
for (j = 0; j < d0; ++j) {
float *g = &y1->g[j * n1], *x1 = &y1->x[j * n1], *x0 = &y0->x[j * n1];
for (i = 0; i < n1; ++i)
g[i] -= t * x0[i] / (x1[i] > tiny? x1[i] : tiny);
}
} else {
for (j = 0; j < d0; ++j) {
float *g = &y1->g[j * n1], *x1 = &y1->x[j * n1], *x0 = &y0->x[j * n1];
for (i = 0; i < n1; ++i)
g[i] -= t * c->x[i] * x0[i] / (x1[i] > tiny? x1[i] : tiny);
}
}
}
return 0;
}
/********** Normalization **********/
int kad_op_stdnorm(kad_node_t *p, int action)
{
int i, j, n, m;
kad_node_t *q = p->child[0];
assert(q->n_d > 0);
n = q->d[q->n_d - 1];
m = kad_len(q) / n;
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_ALLOC) {
p->gtmp = realloc(p->gtmp, m * sizeof(float));
} else if (action == KAD_FORWARD) {
float *si = (float*)p->gtmp;
for (j = 0; j < m; ++j) {
float *px = &p->x[j * n], *qx = &q->x[j * n];
float avg, std_inv;
double s;
for (i = 0, s = 0.0; i < n; ++i) s += qx[i];
avg = (float)(s / n);
for (i = 0; i < n; ++i) px[i] = qx[i] - avg;
for (i = 0, s = 0.0; i < n; ++i) s += px[i] * px[i];
std_inv = s == 0.0? 1.0f : (float)(1.0 / sqrt(s / n));
for (i = 0; i < n; ++i) px[i] *= std_inv;
si[j] = std_inv;
}
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
float *si = (float*)p->gtmp;
for (j = 0; j < m; ++j) {
float *pg = &p->g[j * n], *qg = &q->g[j * n], *px = &p->x[j * n], std_inv = si[j];
double s, t;
for (i = 0, s = t = 0.0; i < n; ++i)
s += pg[i], t += px[i] * pg[i];
s /= n, t /= n;
for (i = 0; i < n; ++i)
qg[i] += std_inv * (pg[i] - s - px[i] * t);
}
}
return 0;
}
/********** Activation functions **********/
int kad_op_sigm(kad_node_t *p, int action)
{
int i, n;
kad_node_t *q = p->child[0];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
for (i = 0; i < n; ++i)
p->x[i] = 1.0f / (1.0f + expf(-q->x[i]));
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
for (i = 0; i < n; ++i)
q->g[i] += p->g[i] * (p->x[i] * (1.0f - p->x[i]));
}
return 0;
}
int kad_op_tanh(kad_node_t *p, int action)
{
int i, n;
kad_node_t *q = p->child[0];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
for (i = 0; i < n; ++i) {
if (q->x[i] < -20.0f) p->x[i] = -1.0f;
else {
float y;
y = expf(-2.0f * q->x[i]);
p->x[i] = (1.0f - y) / (1.0f + y);
}
}
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
for (i = 0; i < n; ++i)
q->g[i] += p->g[i] * (1.0f - p->x[i] * p->x[i]);
}
return 0;
}
int kad_op_relu(kad_node_t *p, int action)
{
int i, n;
kad_node_t *q = p->child[0];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
for (i = 0; i < n; ++i)
p->x[i] = q->x[i] > 0.0f? q->x[i] : 0.0f;
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
for (i = 0; i < n; ++i)
if (q->x[i] > 0.0f)
q->g[i] += p->g[i];
}
return 0;
}
int kad_op_sin(kad_node_t *p, int action)
{
int i, n;
kad_node_t *q = p->child[0];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
for (i = 0; i < n; ++i) p->x[i] = sinf(q->x[i]);
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
for (i = 0; i < n; ++i)
q->g[i] += p->g[i] * cosf(q->x[i]);
}
return 0;
}
int kad_op_softmax(kad_node_t *p, int action)
{
int i, j, n1, d0;
kad_node_t *q = p->child[0];
n1 = q->d[q->n_d - 1];
d0 = kad_len(q) / n1;
if (action == KAD_SYNC_DIM) {
kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
for (j = 0; j < d0; ++j) {
float s, max, *x = &q->x[j * n1], *y = &p->x[j * n1];
for (i = 0, max = -FLT_MAX; i < n1; ++i)
max = max > x[i]? max : x[i];
for (i = 0, s = 0.0f; i < n1; ++i) {
y[i] = expf(x[i] - max);
s += y[i];
}
for (i = 0, s = 1.0f / s; i < n1; ++i) y[i] *= s;
}
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
for (j = 0; j < d0; ++j) {
float s, *g = &p->g[j * n1], *y = &p->x[j * n1], *h = &q->g[j * n1];
for (i = 0, s = 0.0f; i < n1; ++i)
s += g[i] * y[i];
for (i = 0; i < n1; ++i)
h[i] += y[i] * (g[i] - s);
}
}
return 0;
}
/********** Multi-node pooling **********/
int kad_op_avg(kad_node_t *p, int action)
{
int i, n;
float tmp;
kad_node_t *q;
assert(p->n_child > 0);
tmp = 1.0f / p->n_child;
q = p->child[0];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
for (i = 1; i < p->n_child; ++i)
if (kad_len(p->child[i]) != n) return -1;
kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
memcpy(p->x, q->x, n * sizeof(float));
for (i = 1; i < p->n_child; ++i)
kad_saxpy(n, 1.0f, p->child[i]->x, p->x);
for (i = 0; i < n; ++i) p->x[i] *= tmp;
} else if (action == KAD_BACKWARD) {
for (i = 0; i < p->n_child; ++i)
if (kad_is_back(p->child[i]))
kad_saxpy(n, tmp, p->g, p->child[i]->g);
}
return 0;
}
int kad_op_max(kad_node_t *p, int action)
{
int i, n;
kad_node_t *q = p->child[0];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
int *max_j;
for (i = 1; i < p->n_child; ++i)
if (kad_len(p->child[i]) != n) return -1;
kad_copy_dim1(p, q);
max_j = (int*)calloc(n, sizeof(int));
p->gtmp = max_j;
} else if (action == KAD_FORWARD) {
int j, *max_j = (int*)p->gtmp;
memset(max_j, 0, n * sizeof(int));
memcpy(p->x, q->x, n * sizeof(float));
for (j = 1; j < p->n_child; ++j)
for (i = 0, q = p->child[j]; i < n; ++i)
if (q->x[i] > p->x[i]) p->x[i] = q->x[i], max_j[i] = j;
} else if (action == KAD_BACKWARD) {
int *max_j = (int*)p->gtmp;
for (i = 0; i < n; ++i)
p->child[max_j[i]]->g[i] += p->g[i];
}
return 0;
}
int kad_op_stack(kad_node_t *p, int action) /* TODO: allow axis, as in TensorFlow */
{
int i, n, axis = 0;
kad_node_t *q;
assert(p->n_child > 0);
q = p->child[0];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
for (i = 1; i < p->n_child; ++i)
if (kad_len(p->child[i]) != n) return -1;
p->n_d = q->n_d + 1;
for (i = 0; i < axis; ++i) p->d[i] = q->d[i];
p->d[axis] = p->n_child;
for (; i < q->n_d; ++i) p->d[i+1] = q->d[i];
} else if (action == KAD_FORWARD) { /* TODO: doesn't work when axis != 0 */
for (i = 0; i < p->n_child; ++i)
memcpy(&p->x[i * n], p->child[i]->x, n * sizeof(float));
} else if (action == KAD_BACKWARD) {
for (i = 0; i < p->n_child; ++i)
if (kad_is_back(p->child[i]))
kad_saxpy(n, 1.0f, &p->g[i * n], p->child[i]->g);
}
return 0;
}
int kad_op_select(kad_node_t *p, int action)
{
kad_node_t *q;
int i, n, which;
which = *(int32_t*)p->ptr;
if (which < 0) which += p->n_child;
assert(which >= 0 && which < p->n_child);
q = p->child[which];
n = kad_len(q);
if (action == KAD_SYNC_DIM) {
for (i = 0; i < p->n_child; ++i)
if (p->child[i]->n_d != q->n_d || kad_len(p->child[i]) != n)
break;
if (i < p->n_child) return -1;
kad_copy_dim1(p, q);
} else if (action == KAD_FORWARD) {
memcpy(p->x, q->x, n * sizeof(float));
} else if (action == KAD_BACKWARD && kad_is_back(q)) {
kad_saxpy(n, 1.0f, p->g, q->g);
}
return 0;
}
/********** 2D convolution **********/
static void conv_rot180(int d0, int d1, float *x) /* rotate/reverse a weight martix */
{
int i, j;
for (i = 0; i < d0; ++i) {
float tmp, *xi = &x[i * d1];
for (j = 0; j < d1>>1; ++j)
tmp = xi[j], xi[j] = xi[d1-1-j], xi[d1-1-j] = tmp;
}
}
static void conv2d_move_1to3(int d[4], const float *x, float *y) /* convert the NCHW shape to the NHWC shape */
{
int i, j, k, l;
for (i = 0; i < d[0]; ++i)
for (j = 0; j < d[1]; ++j)
for (k = 0; k < d[2]; ++k) {
int ik = (i * d[2] + k) * d[3], ijk = ((i * d[1] + j) * d[2] + k) * d[3];
for (l = 0; l < d[3]; ++l)
y[(ik + l) * d[1] + j] = x[ijk + l];
}
}
static void conv2d_add_3to1(int d[4], const float *y, float *x) /* convert the NHWC shape back to NCHW and add to another NCHW-shaped array */
{
int i, j, k, l;
for (i = 0; i < d[0]; ++i)
for (j = 0; j < d[1]; ++j)
for (k = 0; k < d[2]; ++k) {
int ik = (i * d[2] + k) * d[3], ijk = ((i * d[1] + j) * d[2] + k) * d[3];
for (l = 0; l < d[3]; ++l)
x[ijk + l] += y[(ik + l) * d[1] + j];
}
}
#define conv_out_size(in_size, aux) (((in_size) - (aux)->kernel_size + (aux)->pad[0] + (aux)->pad[1]) / (aux)->stride + 1)
#define process_row_for(_xx, _ww, _yy, _wn, _pn, _stride, _pad, _t) do { \
int j, l; \
if (_stride > 1) { \
for (l = 0; l < _wn; ++l) { \
const float *xl = &_xx[l - _pad]; \
for (j = 0; j < _pn; ++j, xl += _stride) _t[j] = *xl; \
kad_saxpy(_pn, _ww[l], _t, _yy); \
} \
} else for (l = 0; l < _wn; ++l) kad_saxpy(_pn, _ww[l], &_xx[l - _pad], _yy); \
} while (0)
#define process_row_back_x(_xx, _ww, _yy, _wn, _pn, _stride, _pad, _t) do { \
int j, l; \
if (_stride > 1) { \
for (l = 0; l < _wn; ++l) { \
float *xl = &_xx[l - _pad]; \
memset(_t, 0, _pn * sizeof(float)); \
kad_saxpy(_pn, _ww[l], _yy, _t); \
for (j = 0; j < _pn; ++j, xl += _stride) *xl += _t[j]; \
} \
} else for (l = 0; l < _wn; ++l) kad_saxpy(_pn, _ww[l], _yy, &_xx[l - _pad]); \
} while (0)
#define process_row_back_w(_xx, _ww, _yy, _wn, _pn, _stride, _pad, _t) do { \
int j, l; \
if (_stride > 1) { \
for (l = 0; l < _wn; ++l) { \
const float *xl = &_xx[l - _pad]; \
for (j = 0; j < _pn; ++j, xl += _stride) _t[j] = *xl; \
_ww[l] += kad_sdot(_pn, _yy, _t); \
} \
} else for (l = 0; l < _wn; ++l) _ww[l] += kad_sdot(_pn, _yy, &_xx[l - _pad]); \
} while (0)
/* Forward and backward passes are implemented with two different algorithms.
* The first is faster for small kernels with few input channels; otherwise the
* second algorithm is faster. Both algorithms should produce identical
* results, up to the precision of "float".
*/
int kad_op_conv2d(kad_node_t *p, int action) /* in the number-channel-height-width (NCHW) shape */
{
#define conv2d_loop1(_x, _w, _y, _tmp, _row_func) do { /* for the NCHW shape */ \
int n, c1, c0, i, k, ii; \
for (n = 0; n < q->d[0]; ++n) /* mini-batch */ \
for (c1 = 0; c1 < w->d[0]; ++c1) /* output channel */ \
for (c0 = 0; c0 < w->d[1]; ++c0) /* input channel */ \
for (k = 0; k < w->d[2]; ++k) { /* kernel row */ \
float *_ww = &(_w)[((c1 * w->d[1] + c0) * w->d[2] + k) * w->d[3]]; \
for (i = 0, ii = k - aux[0].pad[0]; i < p->d[2] && ii >= 0 && ii < q->d[2]; ++i, ii += aux[0].stride) { /* output row */ \
float *_xx = &(_x)[((n * q->d[1] + c0) * q->d[2] + ii) * q->d[3]]; \
float *_yy = &(_y)[((n * p->d[1] + c1) * p->d[2] + i) * p->d[3]]; \
if (x_padded) { \
memcpy(x_padded + aux[1].pad[0], _xx, q->d[3] * sizeof(float)); \
_xx = x_padded + aux[1].pad[0]; \
} \
_row_func(_xx, _ww, _yy, w->d[3], p->d[3], aux[1].stride, aux[1].pad[0], (_tmp)); \
} /* ~i */ \
} /* ~k, c0, c1, n */ \
} while (0)
#define conv2d_loop2(_x, _w, _y, _code) do { /* for the NHWC shape */ \
int n, c1, i, j, k, ii, j_skip = aux[1].stride * q->d[1], m = w->d[3] * w->d[1]; \
for (n = 0; n < q->d[0]; ++n) /* mini-batch */ \
for (c1 = 0; c1 < w->d[0]; ++c1) /* output channel */ \
for (k = 0; k < w->d[2]; ++k) { /* kernel row */ \
float *_ww = &(_w)[(c1 * w->d[2] + k) * m]; \
for (i = 0, ii = k - aux[0].pad[0]; i < p->d[2] && ii >= 0 && ii < q->d[2]; ++i, ii += aux[0].stride) { /* output and input row */ \
float *_xx = &(_x)[(n * q->d[2] + ii) * q->d[3] * q->d[1]]; \
float *_yy = &(_y)[((n * p->d[1] + c1) * p->d[2] + i) * p->d[3]]; \
if (x_padded) { \
memcpy(x_padded + aux[1].pad[0] * q->d[1], _xx, q->d[3] * q->d[1] * sizeof(float)); \
_xx = x_padded; \
} \
for (j = 0; j < p->d[3]; ++j, _xx += j_skip, ++_yy) _code; /* output and input column */ \
} /* ~i */ \
} /* ~k, c1, n */ \
} while (0)
conv_conf_t *aux = (conv_conf_t*)p->ptr;
kad_node_t *q = p->child[0], *w = p->child[1];
float *t = 0, *q1 = 0, *w1 = 0, *x_padded = 0;
int algo_switch = 0;
if (action == KAD_FORWARD || action == KAD_BACKWARD) { /* allocate working space */
if (w->d[3] * w->d[1] < 16) {
t = (float*)malloc(p->d[3] * sizeof(float));
x_padded = aux[1].pad[0] + aux[1].pad[1] > 0? (float*)calloc(q->d[3] + aux[1].pad[0] + aux[1].pad[1], sizeof(float)) : 0;
} else {
q1 = (float*)malloc(kad_len(q) * sizeof(float));
w1 = (float*)malloc(kad_len(w) * sizeof(float));
x_padded = aux[1].pad[0] + aux[1].pad[1] > 0? (float*)calloc((q->d[3] + aux[1].pad[0] + aux[1].pad[1]) * q->d[1], sizeof(float)) : 0;
algo_switch = 1;
}
}
if (action == KAD_SYNC_DIM) {
if (q->n_d != 4 || w->n_d != 4) return -1;
if (q->d[1] != w->d[1]) return -1; /* unmatched input channels */
p->n_d = 4;
p->d[0] = q->d[0], p->d[1] = w->d[0], p->d[2] = conv_out_size(q->d[2], &aux[0]), p->d[3] = conv_out_size(q->d[3], &aux[1]);
} else if (action == KAD_FORWARD) {
conv_rot180(w->d[0] * w->d[1], w->d[2] * w->d[3], w->x);
memset(p->x, 0, kad_len(p) * sizeof(float));
if (!algo_switch) { /* this is the first algorithm */
conv2d_loop1(q->x, w->x, p->x, t, process_row_for);
} else { /* this is the second algorithm */
conv2d_move_1to3(q->d, q->x, q1);
conv2d_move_1to3(w->d, w->x, w1);
conv2d_loop2(q1, w1, p->x, (*_yy += kad_sdot(m, _ww, _xx)));
}
conv_rot180(w->d[0] * w->d[1], w->d[2] * w->d[3], w->x);
} else if (action == KAD_BACKWARD) {
if (kad_is_back(p->child[0])) { /* backprop to the input array */
conv_rot180(w->d[0] * w->d[1], w->d[2] * w->d[3], w->x);
if (!algo_switch) {
conv2d_loop1(q->g, w->x, p->g, t, process_row_back_x);
} else {
memset(q1, 0, kad_len(q) * sizeof(float));
conv2d_move_1to3(w->d, w->x, w1);
conv2d_loop2(q1, w1, p->g, kad_saxpy(m, *_yy, _ww, _xx));
conv2d_add_3to1(q->d, q1, q->g);
}
conv_rot180(w->d[0] * w->d[1], w->d[2] * w->d[3], w->x);
}
if (kad_is_back(p->child[1])) { /* backprop to the weight matrix */
conv_rot180(w->d[0] * w->d[1], w->d[2] * w->d[3], w->g);
if (!algo_switch) {
conv2d_loop1(q->x, w->g, p->g, t, process_row_back_w);
} else {
conv2d_move_1to3(q->d, q->x, q1);
memset(w1, 0, kad_len(w) * sizeof(float));
conv2d_loop2(q1, w1, p->g, kad_saxpy(m, *_yy, _xx, _ww));
conv2d_add_3to1(w->d, w1, w->g);
}
conv_rot180(w->d[0] * w->d[1], w->d[2] * w->d[3], w->g);
}
}
free(t); free(q1); free(w1); free(x_padded);
return 0;
}
int kad_op_max2d(kad_node_t *p, int action)
{
conv_conf_t *aux = (conv_conf_t*)p->ptr;
kad_node_t *q = p->child[0];
if (action == KAD_SYNC_DIM) {
if (q->n_d != 4) return -1;
p->n_d = 4;
p->d[0] = q->d[0], p->d[1] = q->d[1], p->d[2] = conv_out_size(q->d[2], &aux[0]), p->d[3] = conv_out_size(q->d[3], &aux[1]);
} else if (action == KAD_ALLOC) {
p->gtmp = realloc(p->gtmp, kad_len(p) * sizeof(int));
} else if (action == KAD_FORWARD) {
int rest = 1, len, t, i;
int *f = (int*)p->gtmp;
len = kad_len(p);
for (i = 0; i < len; ++i) p->x[i] = -FLT_MAX;
for (i = 0; i < p->n_d - 2; ++i) rest *= p->d[i];
for (t = 0; t < rest; ++t) {
int i, j, k, l, p_row = p->d[p->n_d - 2], p_col = p->d[p->n_d - 1];
for (i = 0; i < p_row; ++i) {
int u = (t * p_row + i) * p_col;
for (k = 0; k < aux[0].kernel_size; ++k) {
int v, v0, v_end, ii = i * aux[0].stride + k - aux[0].pad[0];
if (ii < 0 || ii >= q->d[p->n_d - 2]) continue;
v0 = (t * q->d[p->n_d - 2] + ii) * q->d[p->n_d - 1];
v_end = v0 + q->d[p->n_d - 1];
for (l = 0; l < aux[1].kernel_size; ++l)
for (j = 0, v = v0 + (l > aux[1].pad[0]? l - aux[1].pad[0] : 0); j < p_col && v < v_end; ++j, v += aux[1].stride)
if (p->x[u + j] < q->x[v])
p->x[u + j] = q->x[v], f[u + j] = v;
} /* ~k */
} /* ~i */
}
} else if (action == KAD_BACKWARD) {
int i, len, *f = (int*)p->gtmp;
len = kad_len(p);
for (i = 0; i < len; ++i) q->g[f[i]] += p->g[i];
}
return 0;
}
/********** 1D convolution **********/
static void conv1d_move_1to2(int d[3], const float *x, float *y)
{
int i, j, k;
for (k = 0; k < d[0]; ++k)
for (j = 0; j < d[1]; ++j)
for (i = 0; i < d[2]; ++i)
y[(k * d[2] + i) * d[1] + j] = x[(k * d[1] + j) * d[2] + i];
}
static void conv1d_add_2to1(int d[3], const float *y, float *x)
{
int i, j, k;
for (k = 0; k < d[0]; ++k)
for (j = 0; j < d[1]; ++j)
for (i = 0; i < d[2]; ++i)
x[(k * d[1] + j) * d[2] + i] += y[(k * d[2] + i) * d[1] + j];
}
int kad_op_conv1d(kad_node_t *p, int action) /* in the number-channel-width (NCW) shape */
{
#define conv1d_loop1(_x, _w, _y, _tmp, _row_func) do { /* for the NCW shape */ \
int n, c1, c0; \
for (n = 0; n < q->d[0]; ++n) /* mini-batch */ \
for (c1 = 0; c1 < w->d[0]; ++c1) /* output channel */ \
for (c0 = 0; c0 < w->d[1]; ++c0) { /* input channel */ \
float *_ww = &(_w)[(c1 * w->d[1] + c0) * w->d[2]]; \
float *_xx = &(_x)[(n * q->d[1] + c0) * q->d[2]]; \
float *_yy = &(_y)[(n * p->d[1] + c1) * p->d[2]]; \
if (x_padded) { \
memcpy(x_padded + aux->pad[0], _xx, q->d[2] * sizeof(float)); \
_xx = x_padded + aux->pad[0]; \
} \
_row_func(_xx, _ww, _yy, w->d[2], p->d[2], aux->stride, aux->pad[0], (_tmp)); \
} /* ~c0, c1, n */ \
} while (0)
#define conv1d_loop2(_x, _w, _y, _code) do { /* for the NWC shape */ \
int n, c1, j, j_skip = aux->stride * q->d[1], m = w->d[2] * w->d[1]; \
for (n = 0; n < q->d[0]; ++n) /* mini-batch */ \
for (c1 = 0; c1 < w->d[0]; ++c1) { /* output channel */ \
float *_ww = &(_w)[c1 * m]; \
float *_xx = &(_x)[n * q->d[1] * q->d[2]]; \
float *_yy = &(_y)[(n * p->d[1] + c1) * p->d[2]]; \
if (x_padded) { \
memcpy(x_padded + aux->pad[0] * q->d[1], _xx, q->d[2] * q->d[1] * sizeof(float)); \
_xx = x_padded; \
} \
for (j = 0; j < p->d[2]; ++j, _xx += j_skip, ++_yy) _code; \
} /* ~c1, n */ \
} while (0)
conv_conf_t *aux = (conv_conf_t*)p->ptr;
kad_node_t *q = p->child[0], *w = p->child[1];
float *t = 0, *q1 = 0, *w1 = 0, *x_padded = 0;
int algo_switch = 0;
if (action == KAD_FORWARD || action == KAD_BACKWARD) { /* allocate working space */
if (w->d[2] * w->d[1] < 32) {
t = (float*)malloc(p->d[2] * sizeof(float));
x_padded = aux->pad[0] + aux->pad[1] > 0? (float*)calloc(q->d[2] + aux->pad[0] + aux->pad[1], sizeof(float)) : 0;
} else {
q1 = (float*)malloc(kad_len(q) * sizeof(float));
w1 = (float*)malloc(kad_len(w) * sizeof(float));
x_padded = aux->pad[0] + aux->pad[1] > 0? (float*)calloc((q->d[2] + aux->pad[0] + aux->pad[1]) * q->d[1], sizeof(float)) : 0;
algo_switch = 1;
}
}
if (action == KAD_SYNC_DIM) {
if (q->n_d != 3 || w->n_d != 3) return -1;
if (q->d[1] != w->d[1]) return -1; /* unmatched input channels */
p->n_d = 3;
p->d[0] = q->d[0], p->d[1] = w->d[0], p->d[2] = conv_out_size(q->d[2], aux);
} else if (action == KAD_FORWARD) {
conv_rot180(w->d[0] * w->d[1], w->d[2], w->x);
memset(p->x, 0, kad_len(p) * sizeof(float));
if (!algo_switch) { /* this is the first algorithm */
conv1d_loop1(q->x, w->x, p->x, t, process_row_for);
} else { /* this is the second algorithm */
conv1d_move_1to2(q->d, q->x, q1);
conv1d_move_1to2(w->d, w->x, w1);
conv1d_loop2(q1, w1, p->x, (*_yy += kad_sdot(m, _ww, _xx)));
}
conv_rot180(w->d[0] * w->d[1], w->d[2], w->x);
} else if (action == KAD_BACKWARD) {
if (kad_is_back(p->child[0])) { /* backprop to the input array */
conv_rot180(w->d[0] * w->d[1], w->d[2], w->x);
if (!algo_switch) {
conv1d_loop1(q->g, w->x, p->g, t, process_row_back_x);
} else {
memset(q1, 0, kad_len(q) * sizeof(float));
conv1d_move_1to2(w->d, w->x, w1);
conv1d_loop2(q1, w1, p->g, kad_saxpy(m, *_yy, _ww, _xx));
conv1d_add_2to1(q->d, q1, q->g);
}
conv_rot180(w->d[0] * w->d[1], w->d[2], w->x);
}
if (kad_is_back(p->child[1])) { /* backprop to the weight matrix */
conv_rot180(w->d[0] * w->d[1], w->d[2], w->g);
if (!algo_switch) {
conv1d_loop1(q->x, w->g, p->g, t, process_row_back_w);
} else {
conv1d_move_1to2(q->d, q->x, q1);
memset(w1, 0, kad_len(w) * sizeof(float));
conv1d_loop2(q1, w1, p->g, kad_saxpy(m, *_yy, _xx, _ww));
conv1d_add_2to1(w->d, w1, w->g);
}
conv_rot180(w->d[0] * w->d[1], w->d[2], w->g);
}
}
free(t); free(q1); free(w1); free(x_padded);
return 0;
}
int kad_op_max1d(kad_node_t *p, int action)
{
conv_conf_t *aux = (conv_conf_t*)p->ptr;
kad_node_t *q = p->child[0];
if (action == KAD_SYNC_DIM) {
if (q->n_d != 3) return -1;
p->n_d = 3;
p->d[0] = q->d[0], p->d[1] = q->d[1], p->d[2] = conv_out_size(q->d[2], aux);
} else if (action == KAD_ALLOC) {
p->gtmp = realloc(p->gtmp, kad_len(p) * sizeof(int));
} else if (action == KAD_FORWARD) {
int rest = 1, len, t, i;
int *f = (int*)p->gtmp;
len = kad_len(p);
for (i = 0; i < len; ++i) p->x[i] = -FLT_MAX;
for (i = 0; i < p->n_d - 1; ++i) rest *= p->d[i];
for (t = 0; t < rest; ++t) {
int j, l, p_width = p->d[p->n_d - 1];
int u = t * p_width, v, v0 = t * q->d[p->n_d - 1], v_end = v0 + q->d[p->n_d - 1];
for (l = 0; l < aux->kernel_size; ++l)
for (j = 0, v = v0 + (l > aux->pad[0]? l - aux->pad[0] : 0); j < p_width && v < v_end; ++j, v += aux->stride)
if (p->x[u + j] < q->x[v])
p->x[u + j] = q->x[v], f[u + j] = v;
}
} else if (action == KAD_BACKWARD) {
int i, len, *f = (int*)p->gtmp;
len = kad_len(p);
for (i = 0; i < len; ++i) q->g[f[i]] += p->g[i];
}
return 0;
}
int kad_op_avg1d(kad_node_t *p, int action)
{
conv_conf_t *aux = (conv_conf_t*)p->ptr;
kad_node_t *q = p->child[0];
if (action == KAD_SYNC_DIM) {
if (q->n_d != 3) return -1;
p->n_d = 3;
p->d[0] = q->d[0], p->d[1] = q->d[1], p->d[2] = conv_out_size(q->d[2], aux);
} else if (action == KAD_ALLOC) {
p->gtmp = realloc(p->gtmp, kad_len(p) * sizeof(int));
} else if (action == KAD_FORWARD) {
int rest = 1, len, t, i;
int *f = (int*)p->gtmp;
len = kad_len(p);
for (i = 0; i < len; ++i) p->x[i] = 0.0f, f[i] = 0;
for (i = 0; i < p->n_d - 1; ++i) rest *= p->d[i];
for (t = 0; t < rest; ++t) {
int j, l, p_width = p->d[p->n_d - 1];
int u = t * p_width, v, v0 = t * q->d[p->n_d - 1], v_end = v0 + q->d[p->n_d - 1];
for (l = 0; l < aux->kernel_size; ++l)
for (j = 0, v = v0 + (l > aux->pad[0]? l - aux->pad[0] : 0); j < p_width && v < v_end; ++j, v += aux->stride)
p->x[u + j] += q->x[v], ++f[u + j];
}
for (i = 0; i < len; ++i) p->x[i] /= f[i];
} else if (action == KAD_BACKWARD) {
int rest = 1, t, i;
int *f = (int*)p->gtmp;
for (i = 0; i < p->n_d - 1; ++i) rest *= p->d[i];
for (t = 0; t < rest; ++t) {
int j, l, p_width = p->d[p->n_d - 1];
int u = t * p_width, v, v0 = t * q->d[p->n_d - 1], v_end = v0 + q->d[p->n_d - 1];
for (l = 0; l < aux->kernel_size; ++l)
for (j = 0, v = v0 + (l > aux->pad[0]? l - aux->pad[0] : 0); j < p_width && v < v_end; ++j, v += aux->stride)
q->g[v] += p->g[u + j] / f[u + j];
}
}
return 0;
}
/********** List of operators **********/
kad_op_f kad_op_list[KAD_MAX_OP] = {
0,
kad_op_add, /* 1: element-wise addition */
kad_op_mul, /* 2: element-wise multiplication */
kad_op_cmul, /* 3: column multiplication */
kad_op_ce_bin_neg, /* 4: binary cross-entropy for (-1,1) */
kad_op_square, /* 5: square */
kad_op_sigm, /* 6: sigmoid */
kad_op_tanh, /* 7: tanh */
kad_op_relu, /* 8: ReLU */
kad_op_matmul, /* 9: matrix multiplication */
kad_op_avg, /* 10: general average pooling (not for ConvNet) */
kad_op_1minus, /* 11: 1-x */
kad_op_select, /* 12: choose between one of the children */
kad_op_ce_multi, /* 13: multi-class cross-entropy */
kad_op_softmax, /* 14: softmax */
kad_op_dropout, /* 15: dropout */
kad_op_conv2d, /* 16: 2D convolution */
kad_op_max2d, /* 17: 2D max pooling (for 2D ConvNet) */
kad_op_conv1d, /* 18: 1D convolution */
kad_op_max1d, /* 19: 1D max pooling (for 1D ConvNet) */
kad_op_slice, /* 20: slice data at a dimension */
kad_op_max, /* 21: general max pooling */
kad_op_ce_bin, /* 22: binary cross-entropy for (0,1) */
kad_op_sub, /* 23: element-wise subtraction */
kad_op_sample_normal, /* 24: sample from a normal distribution */
kad_op_reduce_sum, /* 25 */
kad_op_reduce_mean, /* 26 */
kad_op_log, /* 27: log() */
kad_op_avg1d, /* 28: 1D average pooling (for 1D ConvNet) */
kad_op_mse, /* 29: mean square error */
kad_op_reshape, /* 30 */
kad_op_concat, /* 31 */
kad_op_stdnorm, /* 32: layer normalization */
kad_op_exp, /* 33: exp() */
kad_op_sin, /* 34: sin() */
kad_op_stack, /* 35: tf.stack, but on the first axis only */
kad_op_reverse /* 36: tf.reverse, but on one axis only */
};
char *kad_op_name[KAD_MAX_OP] = {
0, "add", "mul", "cmul", "ce_bin_neg", "square", "sigm", "tanh", "relu", "matmul", "avg", "1minus", "select", "ce_multi", "softmax",
"dropout", "conv2d", "max2d", "conv1d", "max1d", "slice", "max", "ce_bin", "sub", "sample_normal", "reduce_sum", "reduce_mean", "log",
"avg1d", "mse", "reshape", "concat", "stdnorm", "exp", "sin", "stack", "reverse"
};
/**************************
*** Debugging routines ***
**************************/
void kad_trap_fe(void)
{
#ifdef __SSE__
_MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~(_MM_MASK_INVALID | _MM_MASK_DIV_ZERO));
#endif
}
void kad_print_graph(FILE *fp, int n, kad_node_t **v)
{
int i, j;
for (i = 0; i < n; ++i) v[i]->tmp = i;
for (i = 0; i < n; ++i) {
kad_node_t *p = v[i];
fprintf(fp, "%d\t%x:%x\t%d\t", i, p->flag, p->ext_flag, p->ext_label);
if (p->pre) fprintf(fp, "%d\t", p->pre->tmp);
else fprintf(fp, ".\t");
fputs("[", fp);
for (j = 0; j < p->n_d; ++j) {
if (j) fputc(',', fp);
fprintf(fp, "%d", p->d[j]);
}
fprintf(fp, "]\t");
if (p->n_child) {
fprintf(fp, "%s(", kad_op_name[p->op]);
for (j = 0; j < p->n_child; ++j) {
if (j) fputc(',', fp);
fprintf(fp, "$%d", p->child[j]->tmp);
}
fprintf(fp, ")");
} else fprintf(fp, "%s", kad_is_feed(p)? "feed" : kad_is_var(p)? "var" : kad_is_const(p)? "const" : "N/A");
fputc('\n', fp);
}
for (i = 0; i < n; ++i) v[i]->tmp = 0;
}
static void kad_add_delta(int n, kad_node_t **a, float c, float *delta)
{
int i, k;
for (i = k = 0; i < n; ++i)
if (kad_is_var(a[i])) {
kad_saxpy(kad_len(a[i]), c, &delta[k], a[i]->x);
k += kad_len(a[i]);
}
}
void kad_check_grad(int n, kad_node_t **a, int from)
{
const float eps = 1e-5f, rel = 1e-7f / eps;
int i, k, n_var;
float *g0, *delta, f0, f_minus, f_plus, s0, s1, rel_err, p_m_err;
n_var = kad_size_var(n, a);
g0 = (float*)calloc(n_var, sizeof(float));
f0 = *kad_eval_at(n, a, from);
kad_grad(n, a, from);
for (i = k = 0; i < n; ++i)
if (kad_is_var(a[i])) {
memcpy(&g0[k], a[i]->g, kad_len(a[i]) * sizeof(float));
k += kad_len(a[i]);
}
delta = (float*)calloc(n_var, sizeof(float));
for (k = 0; k < n_var; ++k) delta[k] = (float)kad_drand(0) * eps;
kad_add_delta(n, a, 1.0f, delta);
f_plus = *kad_eval_at(n, a, from);
kad_add_delta(n, a, -2.0f, delta);
f_minus = *kad_eval_at(n, a, from);
kad_add_delta(n, a, 1.0f, delta);
s0 = kad_sdot(n_var, g0, delta);
s1 = .5f * (f_plus - f_minus);
fprintf(stderr, "Gradient check -- %g <=> %g @ %g -- ", s0/eps, s1/eps, f0);
if (fabs(s1) >= rel * eps) {
rel_err = fabsf(fabsf(s0) - fabsf(s1)) / (fabsf(s0) + fabsf(s1));
p_m_err = fabsf(f_plus + f_minus - 2.0f * f0) / fabsf(f_plus - f_minus);
fprintf(stderr, "rel_err:%g p_m_err:%g -- ", rel_err, p_m_err);
if (rel_err >= rel && rel_err > p_m_err) fprintf(stderr, "failed\n");
else fprintf(stderr, "passed\n");
} else fprintf(stderr, "skipped\n");
free(delta); free(g0);
}
// ======== BEGIN JAVARY CHANGES ========
// Helper functions to load from memory instead of disk
static int fread_mem(void* target, size_t size, size_t length, int *offset, const unsigned char src[]) {
memcpy(target, &(src[*offset]), size * length);
*offset += length * size;
return *offset;
}
static kad_node_t *kad_load1_mem(const unsigned char mem[], kad_node_t **node, int *offset)
{
kad_node_t *p;
p = (kad_node_t*)calloc(1, sizeof(kad_node_t));
fread_mem(&p->ext_label, 4, 1, offset, mem);
fread_mem(&p->ext_flag, 4, 1, offset, mem);
fread_mem(&p->flag, 1, 1, offset, mem);
fread_mem(&p->n_child, 4, 1, offset, mem);
if (p->n_child) {
int32_t j, k;
p->child = (kad_node_t**)calloc(p->n_child, sizeof(kad_node_t*));
fread_mem(&p->op, 2, 1, offset, mem);
for (j = 0; j < p->n_child; ++j) {
fread_mem(&k, 4, 1, offset, mem);
p->child[j] = node? node[k] : 0;
}
fread_mem(&k, 4, 1, offset, mem);
if (k >= 0) p->pre = node[k];
fread_mem(&p->ptr_size, 4, 1, offset, mem);
if (p->ptr_size > 0) {
p->ptr = malloc(p->ptr_size);
fread_mem(p->ptr, p->ptr_size, 1, offset, mem);
}
} else {
fread_mem(&p->n_d, 1, 1, offset, mem);
if (p->n_d) fread_mem(p->d, 4, p->n_d, offset, mem);
}
return p;
}
kad_node_t **kad_load_mem(const unsigned char mem[], int *_n_node, int *offset)
{
int32_t i, n_node;
kad_node_t **node;
fread_mem(&n_node, 4, 1, offset, mem);
node = (kad_node_t**)malloc(n_node * sizeof(kad_node_t*));
for (i = 0; i < n_node; ++i) {
kad_node_t *p;
p = node[i] = kad_load1_mem(mem, node, offset);
if (p->n_child) {
kad_op_list[p->op](p, KAD_ALLOC);
kad_op_list[p->op](p, KAD_SYNC_DIM);
}
}
*_n_node = n_node;
kad_mark_back(n_node, node);
return node;
}
// ======== END JAVARY CHANGES ========
| {
"alphanum_fraction": 0.5365121662,
"avg_line_length": 30.2417582418,
"ext": "c",
"hexsha": "9e578fe6973361e4d28654ea336a0adeb5c07464",
"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": "3b9acfb49860abef1920c4c35c289be5764f9f27",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JavaryGames/digit_recognition",
"max_forks_repo_path": "kann/kautodiff.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3b9acfb49860abef1920c4c35c289be5764f9f27",
"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": "JavaryGames/digit_recognition",
"max_issues_repo_path": "kann/kautodiff.c",
"max_line_length": 165,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "3b9acfb49860abef1920c4c35c289be5764f9f27",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JavaryGames/digit_recognition",
"max_stars_repo_path": "kann/kautodiff.c",
"max_stars_repo_stars_event_max_datetime": "2020-09-09T18:57:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-15T02:57:20.000Z",
"num_tokens": 31154,
"size": 74304
} |
#include <math.h>
#include <petsc.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mpfr.h>
#include "ellipsoid/ellipsoid.h"
int main() {
EllipsoidalSystem e;
initEllipsoidalSystem(&e, 3.0, 2.0, 1.0);
ellipsoidInitToOrderN(&e, 10);
int n = 6;
//double *coefs = (double*) malloc(sizeof(double)*(n/2+1));
//printf("the value is: %15.15f\n", calcLame2(&e, 3, 1, .5));
double val;
calcLame (&e, 1, 2, 2.1, 1, 1, &val);
printf("the value is: %15.15f\n", val);
//printf("the value is: %15.15f\n", calcLame2(&e, 3, 1, 2.1));
}
| {
"alphanum_fraction": 0.614973262,
"avg_line_length": 26.7142857143,
"ext": "c",
"hexsha": "5be9a5447d65e1a72e9fa4fbb41990980f8ea9b0",
"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/testDassios.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/testDassios.c",
"max_line_length": 64,
"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/testDassios.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": 228,
"size": 561
} |
/* histogram/ntuple.c
*
* Copyright (C) 2000 Simone Piccardi
*
* 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.
*/
/* Jan/2001 Modified by Brian Gough. Minor changes for GSL */
#include <config.h>
#include <errno.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_ntuple.h>
/*
* gsl_ntuple_open:
* Initialize an ntuple structure and create the related file
*/
gsl_ntuple *
gsl_ntuple_create (char *filename, void *ntuple_data, size_t size)
{
gsl_ntuple *ntuple = malloc (sizeof (gsl_ntuple));
if (ntuple == 0)
{
GSL_ERROR_VAL ("failed to allocate space for ntuple struct",
GSL_ENOMEM, 0);
}
ntuple->ntuple_data = ntuple_data;
ntuple->size = size;
ntuple->file = fopen (filename, "wb");
if (ntuple->file == 0)
{
free (ntuple);
GSL_ERROR_VAL ("unable to create ntuple file", GSL_EFAILED, 0);
}
return ntuple;
}
/*
* gsl_ntuple_open:
* Initialize an ntuple structure and open the related file
*/
gsl_ntuple *
gsl_ntuple_open (char *filename, void *ntuple_data, size_t size)
{
gsl_ntuple *ntuple = malloc (sizeof (gsl_ntuple));
if (ntuple == 0)
{
GSL_ERROR_VAL ("failed to allocate space for ntuple struct",
GSL_ENOMEM, 0);
}
ntuple->ntuple_data = ntuple_data;
ntuple->size = size;
ntuple->file = fopen (filename, "rb");
if (ntuple->file == 0)
{
free (ntuple);
GSL_ERROR_VAL ("unable to open ntuple file for reading",
GSL_EFAILED, 0);
}
return ntuple;
}
/*
* gsl_ntuple_write:
* write to file a data row, must be used in a loop!
*/
int
gsl_ntuple_write (gsl_ntuple * ntuple)
{
size_t nwrite;
nwrite = fwrite (ntuple->ntuple_data, ntuple->size,
1, ntuple->file);
if (nwrite != 1)
{
GSL_ERROR ("failed to write ntuple entry to file", GSL_EFAILED);
}
return GSL_SUCCESS;
}
/* the following function is a synonym for gsl_ntuple_write */
int
gsl_ntuple_bookdata (gsl_ntuple * ntuple)
{
return gsl_ntuple_write (ntuple);
}
/*
* gsl_ntuple_read:
* read form file a data row, must be used in a loop!
*/
int
gsl_ntuple_read (gsl_ntuple * ntuple)
{
size_t nread;
nread = fread (ntuple->ntuple_data, ntuple->size, 1, ntuple->file);
if (nread == 0 && feof(ntuple->file))
{
return GSL_EOF;
}
if (nread != 1)
{
GSL_ERROR ("failed to read ntuple entry from file", GSL_EFAILED);
}
return GSL_SUCCESS;
}
/*
* gsl_ntuple_project:
* fill an histogram with an ntuple file contents, use
* SelVal and SelFunc user defined functions to get
* the value to book and the selection funtion
*/
#define EVAL(f,x) ((*((f)->function))(x,(f)->params))
int
gsl_ntuple_project (gsl_histogram * h, gsl_ntuple * ntuple,
gsl_ntuple_value_fn * value_func,
gsl_ntuple_select_fn * select_func)
{
size_t nread;
do
{
nread = fread (ntuple->ntuple_data, ntuple->size,
1, ntuple->file);
if (nread == 0 && feof(ntuple->file))
{
break ;
}
if (nread != 1)
{
GSL_ERROR ("failed to read ntuple for projection", GSL_EFAILED);
}
if (EVAL(select_func, ntuple->ntuple_data))
{
gsl_histogram_increment (h, EVAL(value_func, ntuple->ntuple_data));
}
}
while (1);
return GSL_SUCCESS;
}
/*
* gsl_ntuple_close:
* close the ntuple file and free the memory
*/
int
gsl_ntuple_close (gsl_ntuple * ntuple)
{
int status = fclose (ntuple->file);
if (status)
{
GSL_ERROR ("failed to close ntuple file", GSL_EFAILED);
}
free (ntuple);
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.6493112304,
"avg_line_length": 21.0985221675,
"ext": "c",
"hexsha": "cf7b2f5ea9283b2105a2327f73c9730134b2c2b0",
"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/ntuple/ntuple.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/ntuple/ntuple.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/ntuple/ntuple.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": 1206,
"size": 4283
} |
#include <math.h>
#include <stdlib.h>
#if !defined(__APPLE__)
#include <malloc.h>
#endif
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <string.h>
#include <fftw3.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_sf_expint.h>
#include <gsl/gsl_deriv.h>
#include "../cosmolike_core/theory/basics.c"
#include "../cosmolike_core/theory/structs.c"
#include "../cosmolike_core/theory/parameters.c"
#include "../cosmolike_core/emu17/P_cb/emu.c"
#include "../cosmolike_core/theory/recompute.c"
#include "../cosmolike_core/theory/cosmo3D.c"
#include "../cosmolike_core/theory/redshift.c"
#include "../cosmolike_core/theory/halo.c"
#include "../cosmolike_core/theory/HOD.c"
#include "../cosmolike_core/theory/cosmo2D_fourier.c"
#include "../cosmolike_core/theory/IA.c"
#include "../cosmolike_core/theory/cluster.c"
#include "../cosmolike_core/theory/BAO.c"
#include "../cosmolike_core/theory/external_prior.c"
#include "../cosmolike_core/theory/covariances_3D.c"
#include "../cosmolike_core/theory/covariances_fourier.c"
#include "../cosmolike_core/theory/covariances_cluster.c"
#include "init_SRD.c"
double C_shear_tomo_sys(double ell,int z1,int z2);
double C_cgl_tomo_sys(double ell_Cluster,int zl,int nN, int zs);
double C_gl_tomo_sys(double ell,int zl,int zs);
void set_data_shear(int Ncl, double *ell, double *data, int start);
void set_data_ggl(int Ncl, double *ell, double *data, int start);
void set_data_clustering(int Ncl, double *ell, double *data, int start);
void set_data_cluster_N(double *data, int start);
void set_data_cgl(double *ell_Cluster, double *data, int start);
void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope);
double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope);
double write_vector_wrapper(char *details, input_cosmo_params ic, input_nuisance_params in);
double log_like_wrapper(input_cosmo_params ic, input_nuisance_params in);
int get_N_tomo_shear(void);
int get_N_tomo_clustering(void);
int get_N_ggl(void);
int get_N_ell(void);
int get_N_tomo_shear(void){
return tomo.shear_Nbin;
}
int get_N_tomo_clustering(void){
return tomo.clustering_Nbin;
}
int get_N_ggl(void){
return tomo.ggl_Npowerspectra;
}
int get_N_ell(void){
return like.Ncl;
}
double C_shear_tomo_sys(double ell, int z1, int z2)
{
double C;
// C= C_shear_tomo_nointerp(ell,z1,z2);
// if(like.IA==1) C+=C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2);
if(like.IA!=1) C= C_shear_tomo_nointerp(ell,z1,z2);
if(like.IA==1) C= C_shear_shear_IA(ell,z1,z2);
//if(like.IA==1) C = C_shear_tomo_nointerp(ell,z1,z2)+C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2);
if(like.IA==2) C += C_II_lin_nointerp(ell,z1,z2)+C_GI_lin_nointerp(ell,z1,z2);
if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[z1])*(1.0+nuisance.shear_calibration_m[z2]);
//printf("%le %d %d %le\n",ell,z1,z2,C_shear_tomo_nointerp(ell,z1,z2)+C_II_JB_nointerp(ell,z1,z2)+C_GI_JB_nointerp(ell,z1,z2));
return C;
}
double C_gl_tomo_sys(double ell,int zl,int zs)
{
double C;
// C=C_gl_tomo_nointerp(ell,zl,zs);
// if(like.IA==1) C += C_gI_nointerp(ell,zl,zs);
if(like.IA!=1) C=C_gl_tomo_nointerp(ell,zl,zs);
if(like.IA==1) C = C_ggl_IA(ell,zl,zs);
if(like.IA==2) C += C_gI_lin_nointerp(ell,zl,zs);
if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);
return C;
}
double C_cgl_tomo_sys(double ell_Cluster, int zl,int nN, int zs)
{
double C;
C=C_cgl_tomo_nointerp(ell_Cluster,zl,nN,zs);
//if(like.IA!=0) C +=
if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);
return C;
}
void set_data_shear(int Ncl, double *ell, double *data, int start)
{
int i,z1,z2,nz;
double a;
for (nz = 0; nz < tomo.shear_Npowerspectra; nz++){
z1 = Z1(nz); z2 = Z2(nz);
for (i = 0; i < Ncl; i++){
if (ell[i]<like.lmax_shear){ data[Ncl*nz+i] = C_shear_tomo_sys(ell[i],z1,z2);}
else {data[Ncl*nz+i] = 0.;}
}
}
}
void set_data_ggl(int Ncl, double *ell, double *data, int start)
{
int i, zl,zs,nz;
for (nz = 0; nz < tomo.ggl_Npowerspectra; nz++){
zl = ZL(nz); zs = ZS(nz);
for (i = 0; i < Ncl; i++){
if (test_kmax(ell[i],zl)){
data[start+(Ncl*nz)+i] = C_gl_tomo_sys(ell[i],zl,zs);
}
else{
data[start+(Ncl*nz)+i] = 0.;
}
}
}
}
void set_data_clustering(int Ncl, double *ell, double *data, int start){
int i, nz;
for (nz = 0; nz < tomo.clustering_Npowerspectra; nz++){
//printf("%d %e %e\n",nz, gbias.b[nz][1],pf_photoz(gbias.b[nz][1],nz));
for (i = 0; i < Ncl; i++){
if (test_kmax(ell[i],nz)){data[start+(Ncl*nz)+i] = C_cl_tomo_nointerp(ell[i],nz,nz);}
else{data[start+(Ncl*nz)+i] = 0.;}
//printf("%d %d %le %le\n",nz,nz,ell[i],data[Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra + nz)+i]);
}
}
}
void set_data_cluster_N(double *data, int start){
int nN, nz;
for (nz = 0; nz < tomo.cluster_Nbin; nz++){
for (nN = 0; nN < Cluster.N200_Nbin; nN++){
data[start+Cluster.N200_Nbin*nz+nN] = N_N200(nz, nN);
}
}
}
void set_data_cgl(double *ell_Cluster, double *data, int start)
{
int zl,zs,nN,nz,i,j;
for(nN = 0; nN < Cluster.N200_Nbin; nN++){
for (nz = 0; nz < tomo.cgl_Npowerspectra; nz++){
zl = ZC(nz); zs = ZSC(nz);
for (i = 0; i < Cluster.lbin; i++){
j = start;
j += (nz*Cluster.N200_Nbin+nN)*Cluster.lbin +i;
data[j] = C_cgl_tomo_sys(ell_Cluster[i],zl,nN,zs);
}
}
}
}
int set_cosmology_params(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu)
{
cosmology.Omega_m=OMM;
cosmology.Omega_v= 1.0-cosmology.Omega_m;
cosmology.sigma_8=S8;
cosmology.n_spec= NS;
cosmology.w0=W0;
cosmology.wa=WA;
cosmology.omb=OMB;
cosmology.h0=H0;
cosmology.MGSigma=MGSigma;
cosmology.MGmu=MGmu;
if (cosmology.Omega_m < 0.05 || cosmology.Omega_m > 0.6) return 0;
if (cosmology.omb < 0.04 || cosmology.omb > 0.055) return 0;
if (cosmology.sigma_8 < 0.5 || cosmology.sigma_8 > 1.1) return 0;
if (cosmology.n_spec < 0.84 || cosmology.n_spec > 1.06) return 0;
if (cosmology.w0 < -2.1 || cosmology.w0 > -0.0) return 0;
if (cosmology.wa < -2.6 || cosmology.wa > 2.6) return 0;
if (cosmology.h0 < 0.4 || cosmology.h0 > 0.9) return 0;
return 1;
}
void set_nuisance_shear_calib(double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10)
{
nuisance.shear_calibration_m[0] = M1;
nuisance.shear_calibration_m[1] = M2;
nuisance.shear_calibration_m[2] = M3;
nuisance.shear_calibration_m[3] = M4;
nuisance.shear_calibration_m[4] = M5;
nuisance.shear_calibration_m[5] = M6;
nuisance.shear_calibration_m[6] = M7;
nuisance.shear_calibration_m[7] = M8;
nuisance.shear_calibration_m[8] = M9;
nuisance.shear_calibration_m[9] = M10;
}
int set_nuisance_shear_photoz(double SP1,double SP2,double SP3,double SP4,double SP5,double SP6,double SP7,double SP8,double SP9,double SP10,double SPS1)
{
int i;
nuisance.bias_zphot_shear[0]=SP1;
nuisance.bias_zphot_shear[1]=SP2;
nuisance.bias_zphot_shear[2]=SP3;
nuisance.bias_zphot_shear[3]=SP4;
nuisance.bias_zphot_shear[4]=SP5;
nuisance.bias_zphot_shear[5]=SP6;
nuisance.bias_zphot_shear[6]=SP7;
nuisance.bias_zphot_shear[7]=SP8;
nuisance.bias_zphot_shear[8]=SP9;
nuisance.bias_zphot_shear[9]=SP10;
for (i=0;i<tomo.shear_Nbin; i++){
nuisance.sigma_zphot_shear[i]=SPS1;
if (nuisance.sigma_zphot_shear[i]<0.001) return 0;
}
return 1;
}
int set_nuisance_clustering_photoz(double CP1,double CP2,double CP3,double CP4,double CP5,double CP6,double CP7,double CP8,double CP9,double CP10,double CPS1)
{
int i;
nuisance.bias_zphot_clustering[0]=CP1;
nuisance.bias_zphot_clustering[1]=CP2;
nuisance.bias_zphot_clustering[2]=CP3;
nuisance.bias_zphot_clustering[3]=CP4;
nuisance.bias_zphot_clustering[4]=CP5;
nuisance.bias_zphot_clustering[5]=CP6;
nuisance.bias_zphot_clustering[6]=CP7;
nuisance.bias_zphot_clustering[7]=CP8;
nuisance.bias_zphot_clustering[8]=CP9;
nuisance.bias_zphot_clustering[9]=CP10;
for (i=0;i<tomo.clustering_Nbin; i++){
nuisance.sigma_zphot_clustering[i]=CPS1;
if (nuisance.sigma_zphot_clustering[i]<0.001) return 0;
}
return 1;
}
int set_nuisance_ia(double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q)
{
nuisance.A_ia=A_ia;
nuisance.beta_ia=beta_ia;
nuisance.eta_ia=eta_ia;
nuisance.eta_ia_highz=eta_ia_highz;
nuisance.LF_alpha=LF_alpha;
nuisance.LF_P=LF_P;
nuisance.LF_Q=LF_Q;
nuisance.LF_red_alpha=LF_red_alpha;
nuisance.LF_red_P=LF_red_P;
nuisance.LF_red_Q=LF_red_Q;
if (nuisance.A_ia < 0.0 || nuisance.A_ia > 10.0) return 0;
if (nuisance.beta_ia < -1.0 || nuisance.beta_ia > 3.0) return 0;
if (nuisance.eta_ia < -3.0 || nuisance.eta_ia> 3.0) return 0;
if (nuisance.eta_ia_highz < -1.0 || nuisance.eta_ia_highz> 1.0) return 0;
// printf("%le %le %le %le %le %le %le %le %le %le\n",nuisance.A_ia,nuisance.beta_ia,nuisance.eta_ia,nuisance.eta_ia_highz,nuisance.LF_alpha,nuisance.LF_P, nuisance.LF_Q,nuisance.LF_red_alpha,nuisance.LF_red_P,nuisance.LF_red_Q);
// if(like.IA!=0){
// if (check_LF()) return 0;
// }
return 1;
}
int set_nuisance_cluster_Mobs(double cluster_Mobs_lgN0, double cluster_Mobs_alpha, double cluster_Mobs_beta, double cluster_Mobs_sigma0, double cluster_Mobs_sigma_qm, double cluster_Mobs_sigma_qz)
{
// nuisance.cluster_Mobs_lgM0 = mass_obs_norm; //fiducial : 1.72+log(1.e+14*0.7); could use e.g. sigma = 0.2 Gaussian prior
// nuisance.cluster_Mobs_alpha = mass_obs_slope; //fiducial: 1.08; e.g. sigma = 0.1 Gaussian prior
// nuisance.cluster_Mobs_beta = mass_z_slope; //fiducial: 0.0; e.g. sigma = 0.1 Gaussian prior
// nuisance.cluster_Mobs_sigma = mass_obs_scatter; //fiducial 0.25; e.g. sigma = 0.05 Gaussian prior
// fiducial values and priors from Murata et al. (2018) except for redshift-related parameters
nuisance.cluster_Mobs_lgN0 = cluster_Mobs_lgN0; //fiducial: 3.207, flat prior [0.5, 5.0]
nuisance.cluster_Mobs_alpha = cluster_Mobs_alpha; //fiducial: 0.993, flat prior [0.0, 2.0]
nuisance.cluster_Mobs_beta = cluster_Mobs_beta; //fiducial: 0.0, flat prior [-1.5, 1.5]
nuisance.cluster_Mobs_sigma0 = cluster_Mobs_sigma0; //fiducial: 0.456, flat prior [0.0, 1.5]
nuisance.cluster_Mobs_sigma_qm = cluster_Mobs_sigma_qm; //fiducial: -0.169, flat prior [-1.5, 1.5]
nuisance.cluster_Mobs_sigma_qz = cluster_Mobs_sigma_qz; //fiducial: 0.0, flat prior [-1.5, 1.5]
if (nuisance.cluster_Mobs_lgN0 < 0.5 || nuisance.cluster_Mobs_lgN0 > 5.0) return 0;
if (nuisance.cluster_Mobs_alpha < 0.0 || nuisance.cluster_Mobs_alpha > 2.0) return 0;
if (nuisance.cluster_Mobs_beta < -1.5 || nuisance.cluster_Mobs_beta > 1.5) return 0;
if (nuisance.cluster_Mobs_sigma0 < 0.0|| nuisance.cluster_Mobs_sigma0 > 1.5) return 0;
if (nuisance.cluster_Mobs_sigma_qm < -1.5 && nuisance.cluster_Mobs_sigma_qm > 1.5) return 0;
if (nuisance.cluster_Mobs_sigma_qz < -1.5 && nuisance.cluster_Mobs_sigma_qz > 1.5)return 0;
return 1;
}
int set_nuisance_gbias(double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8,double B9, double B10)
{
int i;
gbias.b[0] = B1;
gbias.b[1] = B2;
gbias.b[2] = B3;
gbias.b[3] = B4;
gbias.b[4] = B5;
gbias.b[5] = B6;
gbias.b[6] = B7;
gbias.b[7] = B8;
gbias.b[8] = B9;
gbias.b[9] = B10;
if(like.bias==1){
for (i = 0; i < 10; i++){
if (gbias.b[i] < 0.8 || gbias.b[i] > 3.0) return 0;
}
}
return 1;
}
double log_L_SRD_SN_Y1_RENEE() // computed from /Users/teifler/Dropbox/cosmolike_store/LSSTawakens/ReneeSNChains/lsst_y1_jan29_nostarts_varyM_oldomb_rand.txt
{
double log_L = 0.;
double param_diff[4];
//double inv[4][4]={{3.79965832e+03,-1.67422234e+01, 1.49107053e+03, 2.03605752e+02},{ -1.67422234e+01, 4.73633438e+02,-2.97547647e+00,-2.21008677e-01},{1.49107053e+03,-2.97547647e+00, 7.06767724e+02, 7.78147349e+01},{2.03605752e+02,-2.21008677e-01, 7.78147349e+01, 1.20866157e+01}};
// double inv[4][4]={{2.54176679e+03,2.52990975e+01,8.90935426e+02,1.36402504e+02},{2.52990975e+01,4.81470268e+02,1.01904094e+01,6.95186662e-01},{8.90935426e+02,1.01904094e+01,4.02864434e+02,4.60275519e+01},{1.36402504e+02,6.95186662e-01,4.60275519e+01,8.41721305e+00}};
double inv[4][4]={{2.92724944e+03,-2.18583441e+01, 1.31758412e+03, 1.57579361e+02},
{-2.18583441e+01, 4.63427974e+02,-1.59603150e+01,-8.00922379e-01},
{1.31758412e+03,-1.59603150e+01, 7.22127857e+02, 6.67792329e+01},
{1.57579361e+02,-8.00922379e-01, 6.67792329e+01, 9.71021170e+00}};
param_diff[0] = cosmology.Omega_m-0.3156;
param_diff[1] = cosmology.h0-0.6727;
param_diff[2] = cosmology.w0+1.0;
param_diff[3] = cosmology.wa;
log_L = -0.5*do_matrix_mult_invcov(4,inv,param_diff);
return log_L;
}
double log_L_SRD_SN_Y10_RENEE() // computed from /Users/teifler/Dropbox/cosmolike_store/LSSTawakens/ReneeSNChains/lsst_y10_jan29_nostarts_varyM_oldomb_rand.txt
{
double log_L = 0.;
double param_diff[4];
double inv[4][4]={{1.13549508e+04,-7.56474778e+01,7.30717358e+03,5.90184798e+02},
{ -7.56474778e+01,4.91930625e+02,-4.39988764e+01,-7.28574193e+00},
{7.30717358e+03,-4.39988764e+01,5.38324084e+03,3.24899498e+02},
{5.90184798e+02,-7.28574193e+00,3.24899498e+02,3.84274454e+01}};
param_diff[0] = cosmology.Omega_m-0.3156;
param_diff[1] = cosmology.h0-0.6727;
param_diff[2] = cosmology.w0+1.0;
param_diff[3] = cosmology.wa;
log_L = -0.5*do_matrix_mult_invcov(4,inv, param_diff);
return log_L;
}
double log_L_SRD_SL_Y1_TOM() // computed from /Users/teifler/Dropbox/cosmolike_store/LSSTawakens/TomSLChains/SL_LSSTY1.txt
{
double log_L = 0.;
double param_diff[4];
double inv[4][4]={{9.57953440e+01,1.90114212e+01,1.13561665e+00,2.33866782e+02},{1.90114212e+01,1.31631828e+01,-1.88534652e-02,1.45671419e+02},{1.13561665e+00,-1.88534652e-02,6.29296427e-01,-6.10433226e+00},{2.33866782e+02,1.45671419e+02,-6.10433226e+00,2.71769694e+03}};
param_diff[0] = cosmology.Omega_m-0.3156;
param_diff[1] = cosmology.w0+1.0;
param_diff[2] = cosmology.wa;
param_diff[3] = cosmology.h0-0.6727;
log_L = -0.5*do_matrix_mult_invcov(4,inv, param_diff);
return log_L;
}
double log_L_SRD_SL_Y10_TOM() // computed from /Users/teifler/Dropbox/cosmolike_store/LSSTawakens/TomSLChains/SL_LSSTY10.txt
{
double log_L = 0.;
double param_diff[4];
double inv[4][4]={{2.44407663e+02,1.31525702e+02,1.62494864e+01,1.03889766e+03},{1.31525702e+02,1.90748959e+02,8.03881315e+00,1.99392208e+03},{1.62494864e+01,8.03881315e+00,2.23917868e+00,-6.64709076e+00},{1.03889766e+03,1.99392208e+03,-6.64709076e+00,3.31389425e+04}};
param_diff[0] = cosmology.Omega_m-0.3156;
param_diff[1] = cosmology.w0+1.0;
param_diff[2] = cosmology.wa;
param_diff[3] = cosmology.h0-0.6727;
log_L = -0.5*do_matrix_mult_invcov(4,inv, param_diff);
return log_L;
}
double log_L_SRD_LSST_Y1_clusters() // // including MOR for Y1, see fisher.py
{
double log_L = 0.;
double param_diff[7];
double inv[7][7]={{3.858101e+04, 3.588867e+04, 2.231543e+03, -9.737292e+02, -2.076847e+02, -1.567836e+03, 5.165868e+02},{3.588867e+04, 4.046241e+04, 2.204910e+03, -4.306084e+02, -1.921012e+02, -1.153062e+03, 4.146891e+02},{2.231543e+03, 2.204910e+03, 4.640472e+02, -3.849041e+01, -1.164098e+01, -2.997845e+02, 8.606974e+01},{-9.737292e+02, -4.306084e+02, -3.849041e+01, 1.057829e+02, 1.234460e+01, 3.159550e+01, -1.021792e+01},{-2.076847e+02, -1.921012e+02, -1.164098e+01, 1.234460e+01, 3.965104e+00, 6.461167e+00, -2.324549e+00},{-1.567836e+03, -1.153062e+03, -2.997845e+02, 3.159550e+01, 6.461167e+00, 9.845550e+04, -2.104350e+02},{5.165868e+02, 4.146891e+02, 8.606974e+01, -1.021792e+01, -2.324549e+00, -2.104350e+02, 2.121782e+02}};
param_diff[0] = cosmology.Omega_m-0.3156;
param_diff[1] = cosmology.sigma_8-0.831;
param_diff[2] = cosmology.n_spec-0.9645;
param_diff[3] = cosmology.w0+1.0;
param_diff[4] = cosmology.wa;
param_diff[5] = cosmology.omb-0.0491685;
param_diff[6] = cosmology.h0-0.6727;
log_L = -0.5*do_matrix_mult_invcov(7,inv, param_diff);
return log_L;
}
double log_L_SRD_LSST_Y10_clusters() // including MOR for Y10, see fisher.py
{
double log_L = 0.;
double param_diff[7];
double inv[7][7]={{8.011883e+04, 7.501415e+04, 4.972257e+03, -1.009514e+03, -2.332928e+02, -4.035026e+03, 1.280726e+03},{7.501415e+04, 9.212235e+04, 5.029562e+03, 1.256229e+03, -8.904458e+00, -3.884022e+03, 1.236633e+03},{4.972257e+03, 5.029562e+03, 8.996244e+02, -1.335280e+01, -1.271912e+01, -9.151661e+02, 2.624954e+02},{-1.009514e+03, 1.256229e+03, -1.335280e+01, 3.943470e+02, 5.659304e+01, -3.776163e+01, 7.168167e+00},{-2.332928e+02, -8.904458e+00, -1.271912e+01, 5.659304e+01, 1.167193e+01, 4.161086e+00, -1.872393e+00},{-4.035026e+03, -3.884022e+03, -9.151661e+02, -3.776163e+01, 4.161086e+00, 1.000908e+05, -6.424232e+02},{1.280726e+03, 1.236633e+03, 2.624954e+02, 7.168167e+00, -1.872393e+00, -6.424232e+02, 3.273443e+02}};
param_diff[0] = cosmology.Omega_m-0.3156;
param_diff[1] = cosmology.sigma_8-0.831;
param_diff[2] = cosmology.n_spec-0.9645;
param_diff[3] = cosmology.w0+1.0;
param_diff[4] = cosmology.wa;
param_diff[5] = cosmology.omb-0.0491685;
param_diff[6] = cosmology.h0-0.6727;
log_L = -0.5*do_matrix_mult_invcov(7,inv, param_diff);
return log_L;
}
double log_L_SRD_stage3_exceptw0wa()
{
double log_L = 0.;
double param_diff[7];
double inv[7][7]={{8.52388933e+03,-2.38254882e-03,4.32405053e+00,0.00000000e+00,0.00000000e+00,1.22554260e+02,5.48470403e+01},{-2.38254882e-03,3.34465215e+01,3.86664237e-01,0.00000000e+00,0.00000000e+00,-8.71498515e+01,-7.09315084e+00},{4.32405053e+00,3.86664237e-01,2.47843770e+02,0.00000000e+00,0.00000000e+00,-1.21079947e+02,4.07696833e+00},{0.00000000e+00,0.00000000e+00,0.00000000e+00,0.00000000e+00,0.00000000e+00,0.00000000e+00,0.00000000e+00},{0.00000000e+00,0.00000000e+00,0.00000000e+00,0.00000000e+00,0.00000000e+00,0.00000000e+00,0.00000000e+00},{1.22554260e+02,-8.71498515e+01,-1.21079947e+02,-0.00000000e+00,-0.00000000e+00,7.17126110e+04,3.07891510e+03},{5.48470403e+01,-7.09315084e+00,4.07696833e+00,0.00000000e+00,0.00000000e+00,3.07891510e+03,5.31816639e+02}};
param_diff[0] = cosmology.Omega_m-0.3156;
param_diff[1] = cosmology.sigma_8-0.831;
param_diff[2] = cosmology.n_spec-0.9645;
param_diff[3] = cosmology.w0+1.0;
param_diff[4] = cosmology.wa;
param_diff[5] = cosmology.omb-0.0491685;
param_diff[6] = cosmology.h0-0.6727;
log_L = -0.5*do_matrix_mult_invcov(7,inv, param_diff);
return log_L;
}
double log_L_SRD_stage3()
{
double log_L = 0.;
double param_diff[7];
double inv[7][7]={{8.52889541e+03,9.34266060e-03,2.21513407e+00,1.85008170e+01,6.12185662e+00,1.17720010e+02,5.30670581e+01},{9.34266060e-03,3.34475078e+01,3.79135616e-01,-8.02192934e-02,5.88736315e-02,-8.69202865e+01,-7.08029577e+00},{2.21513407e+00,3.79135616e-01,2.48739187e+02,-7.46022981e+00,-2.69922217e+00,-1.19693897e+02,4.78085262e+00},{1.85008170e+01,-8.02192934e-02,-7.46022981e+00,8.42937127e+01,1.68856256e+01,-4.89063661e+01,-8.77194357e+00},{6.12185662e+00,5.88736315e-02,-2.69922217e+00,1.68856256e+01,9.55489400e+00,5.27704214e+00,-1.38597499e+00},{1.17720010e+02,-8.69202865e+01,-1.19693897e+02,-4.89063661e+01,5.27704214e+00,7.17777988e+04,3.08491105e+03},{5.30670581e+01,-7.08029577e+00,4.78085262e+00,-8.77194357e+00,-1.38597499e+00,3.08491105e+03,5.32751808e+02}};
param_diff[0] = cosmology.Omega_m-0.3156;
param_diff[1] = cosmology.sigma_8-0.831;
param_diff[2] = cosmology.n_spec-0.9645;
param_diff[3] = cosmology.w0+1.0;
param_diff[4] = cosmology.wa;
param_diff[5] = cosmology.omb-0.0491685;
param_diff[6] = cosmology.h0-0.6727;
log_L = -0.5*do_matrix_mult_invcov(7,inv, param_diff);
return log_L;
}
double log_L_SRD_LSST_Y1_3x2pt()
{
double log_L = 0.;
double param_diff[7];
double inv[7][7]={{6.461019e+05, 4.105098e+05, 9.063469e+04, -2.968463e+04, -6.656297e+03, -3.266829e+05, 7.947019e+04},{4.105098e+05, 3.102396e+05, 4.061214e+04, -2.051833e+04, -5.069455e+03, -1.156574e+05, 2.911602e+04},{9.063469e+04, 4.061214e+04, 3.652491e+04, -1.033492e+03, -1.571074e+02, -9.436089e+04, 2.396154e+04},{-2.968463e+04, -2.051833e+04, -1.033492e+03, 2.081364e+03, 4.721662e+02, 7.414854e+03, -1.864708e+03},{-6.656297e+03, -5.069455e+03, -1.571074e+02, 4.721662e+02, 1.200287e+02, 1.340576e+03, -3.293614e+02},{-3.266829e+05, -1.156574e+05, -9.436089e+04, 7.414854e+03, 1.340576e+03, 5.388793e+05, -9.884641e+04},{7.947019e+04, 2.911602e+04, 2.396154e+04, -1.864708e+03, -3.293614e+02, -9.884641e+04, 2.373400e+04}};
param_diff[0] = cosmology.Omega_m-0.3156;
param_diff[1] = cosmology.sigma_8-0.831;
param_diff[2] = cosmology.n_spec-0.9645;
param_diff[3] = cosmology.w0+1.0;
param_diff[4] = cosmology.wa;
param_diff[5] = cosmology.omb-0.0491685;
param_diff[6] = cosmology.h0-0.6727;
log_L = -0.5*do_matrix_mult_invcov(7,inv, param_diff);
return log_L;
}
double log_L_SRD_LSST_Y10_3x2pt()
{
double log_L = 0.;
double param_diff[7];
double inv[7][7]={{1.732125e+06, 1.363116e+06, 2.420885e+05, -6.384395e+04, -1.991510e+04, -7.567872e+05, 1.858361e+05},{1.363116e+06, 1.196537e+06, 1.469326e+05, -5.148233e+04, -1.796618e+04, -4.526364e+05, 1.126267e+05},{2.420885e+05, 1.469326e+05, 1.011204e+05, -1.370858e+03, -4.391526e+02, -2.001808e+05, 5.228884e+04},{-6.384395e+04, -5.148233e+04, -1.370858e+03, 4.153843e+03, 1.137490e+03, 1.286287e+04, -3.253747e+03},{-1.991510e+04, -1.796618e+04, -4.391526e+02, 1.137490e+03, 3.720224e+02, 4.198170e+03, -1.020253e+03},{-7.567872e+05, -4.526364e+05, -2.001808e+05, 1.286287e+04, 4.198170e+03, 8.507285e+05, -1.685201e+05},{1.858361e+05, 1.126267e+05, 5.228884e+04, -3.253747e+03, -1.020253e+03, -1.685201e+05, 4.064231e+04}};
param_diff[0] = cosmology.Omega_m-0.3156;
param_diff[1] = cosmology.sigma_8-0.831;
param_diff[2] = cosmology.n_spec-0.9645;
param_diff[3] = cosmology.w0+1.0;
param_diff[4] = cosmology.wa;
param_diff[5] = cosmology.omb-0.0491685;
param_diff[6] = cosmology.h0-0.6727;
log_L = -0.5*do_matrix_mult_invcov(7,inv, param_diff);
return log_L;
}
double log_L_DESI()
{
double log_L = 0.;
double param_diff[2];
double inv[2][2]={{1411.40888852,449.46652105},{449.46652105, 291.94320759}};
param_diff[0] = cosmology.w0+1.0;
param_diff[1] = cosmology.wa;
log_L = -0.5*do_matrix_mult_invcov(2,inv, param_diff);
return log_L;
}
double scatter(double N200, double z)
{
double lnM, M, a;
lnM = 1./nuisance.cluster_Mobs_alpha*(log(N200)-nuisance.cluster_Mobs_lgN0-nuisance.cluster_Mobs_beta*log(1.+z));
M = exp(lnM)*3.e14;
a = 1./(1.+z);
return scatter_lgN200_model_mz(M, a);
}
double scatter_fid(double N200, double z)
{
double cluster_Mobs_lgN0 = 3.207;
double cluster_Mobs_alpha = 0.993;
double cluster_Mobs_beta = 0.0;
double cluster_Mobs_sigma0 = 0.456;
double cluster_Mobs_sigma_qm = 0.0; // SRD suggestion from Eduardo
// double cluster_Mobs_sigma_qm = -0.169;
double cluster_Mobs_sigma_qz = 0.0;
double lnM, M, a;
lnM = 1./cluster_Mobs_alpha*(log(N200)-cluster_Mobs_lgN0-cluster_Mobs_beta*log(1.+z));
M = exp(lnM)*3.e14;
a = 1./(1.+z);
return cluster_Mobs_sigma0 + log(M/(3.e+14))*cluster_Mobs_sigma_qm + log(1./a)*cluster_Mobs_sigma_qz;
}
double log_L_SRD_LSST_CL_EDUARDO() // values for scatter function are "arbitrary" but based on some experience (Hironao/Eduarod)
{
double log_L = 0.;
double s_100_0p2 = scatter(100., 0.2);
double s_30_0p2 = scatter(30., 0.2);
double s_100_0p8 = scatter(100., 0.8); // remove if redshift dependent scatter is excluded in analysis
double f_100_0p2 = scatter_fid(100., 0.2);
double f_30_0p2 = scatter_fid(30., 0.2);
double f_100_0p8 = scatter_fid(100., 0.8); // remove if redshift dependent scatter is excluded in analysis
double sig = 0.1; // 0.05 weighting the giants
log_L = -0.5*(exp(pow((s_100_0p2-f_100_0p2)/sig, 2.0))+ exp(pow((s_30_0p2-f_30_0p2)/sig, 2.0)) + exp(pow((s_100_0p8-f_100_0p8)/sig, 2.0)));
return log_L;
}
double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope)
{
int i,j,k,m=0,l;
static double *pred;
static double *ell;
static double *ell_Cluster;
static double darg;
double chisqr,a,log_L_prior=0.0, log_L_GRS=0.0;
if(ell==0){
pred= create_double_vector(0, like.Ndata-1);
ell= create_double_vector(0, like.Ncl-1);
darg=(log(like.lmax)-log(like.lmin))/like.Ncl;
for (l=0;l<like.Ncl;l++){
ell[l]=exp(log(like.lmin)+(l+0.5)*darg);
}
ell_Cluster= create_double_vector(0, Cluster.lbin-1);
darg=(log(Cluster.l_max)-log(Cluster.l_min))/Cluster.lbin;
for (l=0;l<Cluster.lbin;l++){
ell_Cluster[l]=exp(log(Cluster.l_min)+(l+0.5)*darg);
}
}
if (set_cosmology_params(OMM,S8,NS,W0,WA,OMB,H0,MGSigma,MGmu)==0){
printf("Cosmology out of bounds\n");
return -1.0e8;
}
set_nuisance_shear_calib(M1,M2,M3,M4,M5,M6,M7,M8,M9,M10);
if (set_nuisance_shear_photoz(SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8,SP9,SP10,SPS1)==0){
printf("Shear photo-z sigma too small\n");
return -1.0e8;
}
if (set_nuisance_clustering_photoz(CP1,CP2,CP3,CP4,CP5,CP6,CP7,CP8,CP9,CP10,CPS1)==0){
printf("Clustering photo-z sigma too small\n");
return -1.0e8;
}
if (set_nuisance_ia(A_ia,beta_ia,eta_ia,eta_ia_highz,LF_alpha,LF_P,LF_Q,LF_red_alpha,LF_red_P,LF_red_Q)==0){
printf("IA parameters out of bounds\n");
return -1.0e8;
}
if (set_nuisance_gbias(B1,B2,B3,B4,B5,B6,B7,B8,B9,B10)==0){
printf("Bias out of bounds\n");
return -1.0e8;
}
if (set_nuisance_cluster_Mobs(mass_obs_norm, mass_obs_slope, mass_z_slope, mass_obs_scatter_norm, mass_obs_scatter_mass_slope, mass_obs_scatter_z_slope)==0){
printf("Mobs out of bounds\n");
return -1.0e8;
}
//printf("like %le %le %le %le %le %le %le %le\n",cosmology.Omega_m, cosmology.Omega_v,cosmology.sigma_8,cosmology.n_spec,cosmology.w0,cosmology.wa,cosmology.omb,cosmology.h0);
// printf("like %le %le %le %le\n",gbias.b[0][0], gbias.b[1][0], gbias.b[2][0], gbias.b[3][0]);
// for (i=0; i<10; i++){
// printf("nuisance %le %le %le\n",nuisance.shear_calibration_m[i],nuisance.bias_zphot_shear[i],nuisance.sigma_zphot_shear[i]);
// }
log_L_prior=0.0;
// if(like.Aubourg_Planck_BAO_SN==1) log_L_prior+=log_L_Planck_BAO_SN();
// if(like.SN==1) log_L_prior+=log_L_SN();
// if(like.BAO==1) log_L_prior+=log_L_BAO();
// if(like.Planck==1) log_L_prior+=log_L_Planck();
// if(like.IA!=0) log_L_prior+=log_L_ia();
// if(like.IA!=0) log_L_prior+=log_like_f_red();
// if(like.wlphotoz!=0) log_L_prior+=log_L_wlphotoz();
// if(like.clphotoz!=0) log_L_prior+=log_L_clphotoz();
// if(like.shearcalib==1) log_L_prior+=log_L_shear_calib();
// if(like.clusterMobs==1) log_L_prior+=log_L_clusterMobs();
// if(like.SRD_SN_Y10==1) log_L_prior+=log_L_SRD_SN_Y10_RENEE();
// if(like.SRD_SN_Y1==1) log_L_prior+=log_L_SRD_SN_Y1_RENEE();
// if(like.SRD_SL_Y10==1) log_L_prior+=log_L_SRD_SL_Y10_TOM();
// if(like.SRD_SL_Y1==1) log_L_prior+=log_L_SRD_SL_Y1_TOM();
// log_L_prior+=log_L_DESI();
if(like.SRD==1 || like.SRD==6 || like.SRD==11) log_L_prior+=log_L_SRD_stage3();
if(like.SRD==2 || like.SRD==6) log_L_prior+=1/(1+0.7*0.7)*log_L_SRD_SN_Y10_RENEE();
if(like.SRD==3 || like.SRD==6) log_L_prior+=1/(1+0.62*0.62)*log_L_SRD_SL_Y10_TOM();
if(like.SRD==4 || like.SRD==6) log_L_prior+=14202.63/18000.0*1/(1+0.62*0.62)*log_L_SRD_LSST_Y10_3x2pt();
if(like.SRD==5 || like.SRD==6) log_L_prior+=14202.63/18000.0*1/(1+0.62*0.62)*log_L_SRD_LSST_Y10_clusters();
if(like.SRD==7 || like.SRD==11) log_L_prior+=1/(1+0.7*0.7)*log_L_SRD_SN_Y1_RENEE();
if(like.SRD==8 || like.SRD==11) log_L_prior+=1/(1+0.62*0.62)*log_L_SRD_SL_Y1_TOM();
if(like.SRD==9 || like.SRD==11) log_L_prior+=11808.28/18000.0*1/(1+0.62*0.62)*log_L_SRD_LSST_Y1_3x2pt();
if(like.SRD==10 || like.SRD==11) log_L_prior+=11808.28/18000.0*1/(1+0.62*0.62)*log_L_SRD_LSST_Y1_clusters();
// printf("%d %d %d %d\n",like.BAO,like.wlphotoz,like.clphotoz,like.shearcalib);
// printf("logl %le %le %le %le\n",log_L_shear_calib(),log_L_wlphotoz(),log_L_clphotoz(),log_L_clusterMobs());
// int start=0;
// if(like.shear_shear==1) {
// set_data_shear(like.Ncl, ell, pred, start);
// start=start+like.Ncl*tomo.shear_Npowerspectra;
// }
// if(like.shear_pos==1){
// set_data_ggl(like.Ncl, ell, pred, start);
// start=start+like.Ncl*tomo.ggl_Npowerspectra;
// }
// if(like.pos_pos==1){
// set_data_clustering(like.Ncl,ell,pred, start);
// start=start+like.Ncl*tomo.clustering_Npowerspectra;
// }
// if(like.clusterN==1){
// set_data_cluster_N(pred,start);
// start=start+tomo.cluster_Nbin*Cluster.N200_Nbin;
// }
// if(like.clusterWL==1){
// set_data_cgl(ell_Cluster,pred, start);
// }
chisqr=0.0;
// for (i=0; i<like.Ndata; i++){
// for (j=0; j<like.Ndata; j++){
// a=(pred[i]-data_read(1,i))*invcov_read(1,i,j)*(pred[j]-data_read(1,j));
// chisqr=chisqr+a;
// }
// // if (fabs(data_read(1,i)/pred[i]-1.0) >1.e-4){
// // printf("%d %le %le %le\n",i,data_read(1,i),pred[i],data_read(1,i)/pred[i]);
// // }
// }
// if (chisqr<0.0){
// printf("errror: chisqr < 0\n");
// }
// if (chisqr<-1.0) exit(EXIT_FAILURE);
return -0.5*chisqr+log_L_prior;
}
void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope)
{
int i,j,k,m=0,l;
static double *pred;
static double *ell;
static double *ell_Cluster;
static double darg;
double chisqr,a,log_L_prior=0.0;
if(ell==0){
pred= create_double_vector(0, like.Ndata-1);
ell= create_double_vector(0, like.Ncl-1);
darg=(log(like.lmax)-log(like.lmin))/like.Ncl;
for (l=0;l<like.Ncl;l++){
ell[l]=exp(log(like.lmin)+(l+0.5)*darg);
}
ell_Cluster= create_double_vector(0, Cluster.lbin-1);
darg=(log(Cluster.l_max)-log(Cluster.l_min))/Cluster.lbin;
for (l=0;l<Cluster.lbin;l++){
ell_Cluster[l]=exp(log(Cluster.l_min)+(l+0.5)*darg);
}
}
// for (l=0;l<like.Ncl;l++){
// printf("%d %le\n",i,ell[l]);
// }
set_cosmology_params(OMM,S8,NS,W0,WA,OMB,H0,MGSigma,MGmu);
set_nuisance_shear_calib(M1,M2,M3,M4,M5,M6,M7,M8,M9,M10);
set_nuisance_shear_photoz(SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8,SP9,SP10,SPS1);
set_nuisance_clustering_photoz(CP1,CP2,CP3,CP4,CP5,CP6,CP7,CP8,CP9,CP10,CPS1);
set_nuisance_ia(A_ia,beta_ia,eta_ia,eta_ia_highz,LF_alpha,LF_P,LF_Q,LF_red_alpha,LF_red_P,LF_red_Q);
set_nuisance_gbias(B1,B2,B3,B4,B5,B6,B7,B8,B9,B10);
set_nuisance_cluster_Mobs(mass_obs_norm, mass_obs_slope, mass_z_slope, mass_obs_scatter_norm, mass_obs_scatter_mass_slope, mass_obs_scatter_z_slope);
int start=0;
if(like.shear_shear==1) {
set_data_shear(like.Ncl, ell, pred, start);
start=start+like.Ncl*tomo.shear_Npowerspectra;
}
if(like.shear_pos==1){
//printf("ggl\n");
set_data_ggl(like.Ncl, ell, pred, start);
start=start+like.Ncl*tomo.ggl_Npowerspectra;
}
if(like.pos_pos==1){
//printf("clustering\n");
set_data_clustering(like.Ncl,ell,pred, start);
start=start+like.Ncl*tomo.clustering_Npowerspectra;
}
if(like.clusterN==1){
set_data_cluster_N(pred,start);
start= start+tomo.cluster_Nbin*Cluster.N200_Nbin;
}
if(like.clusterWL==1){
set_data_cgl(ell_Cluster,pred, start);
}
FILE *F;
char filename[300];
if (strstr(details,"FM") != NULL){
sprintf(filename,"%s",details);
}
else {sprintf(filename,"datav/%s_%s",like.probes,details);}
F=fopen(filename,"w");
for (i=0;i<like.Ndata; i++){
fprintf(F,"%d %le\n",i,pred[i]);
//printf("%d %le\n",i,pred[i]);
}
fclose(F);
}
double write_vector_wrapper(char *details, input_cosmo_params ic, input_nuisance_params in)
{
compute_data_vector(details, ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu,
in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9],
in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4],
in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9],
in.source_z_s,
in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4],
in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9],
in.lens_z_s,
in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4],
in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9],
in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz,
in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5],
in.m_lambda[0], in.m_lambda[1], in.m_lambda[2], in.m_lambda[3],
in.m_lambda[4], in.m_lambda[5]);
return 0;
}
double log_like_wrapper(input_cosmo_params ic, input_nuisance_params in)
{
double like = log_multi_like(ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu,
in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9],
in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4],
in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9],
in.source_z_s,
in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4],
in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9],
in.lens_z_s,
in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4],
in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9],
in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz,
in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5],
in.m_lambda[0], in.m_lambda[1], in.m_lambda[2], in.m_lambda[3],
in.m_lambda[4], in.m_lambda[5]);
return like;
}
int main(int argc, char** argv)
{
int hit=atoi(argv[1]);
char filename[500],arg1[400],arg2[400];
int t;
t=hit;
double area_table[12]={7500.0,13000.0,16000.0,10000.0,15000.0,20000.0,10000.0,15000.0,20000.0,10000.0,15000.0,20000.0};
double nsource_table[12]={9.8,12.1,15.1,15.1,18.9,23.5,20.3,23.5,26.9,26.9,30.8,35.0};
double nlens_table[12]={15.0,20.0,25.0,25.0,32.0,41.0,35.0,41.0,48.0,48.0,57.0,67.0};
char survey_designation[12][200]={"LSST_Y1","LSST_Y1","LSST_Y1","LSST_Y3","LSST_Y3","LSST_Y3","LSST_Y6","LSST_Y6","LSST_Y6","LSST_Y10","LSST_Y10","LSST_Y10"};
char source_zfile[12][400]={"WL_zdistri_model0_z0=1.940000e-01_alpha=8.830000e-01","WL_zdistri_model1_z0=1.900000e-01_alpha=8.620000e-01","WL_zdistri_model2_z0=1.860000e-01_alpha=8.410000e-01","WL_zdistri_model3_z0=1.860000e-01_alpha=8.410000e-01","WL_zdistri_model4_z0=1.830000e-01_alpha=8.210000e-01","WL_zdistri_model5_z0=1.790000e-01_alpha=8.000000e-01","WL_zdistri_model6_z0=1.810000e-01_alpha=8.140000e-01","WL_zdistri_model7_z0=1.790000e-01_alpha=8.000000e-01","WL_zdistri_model8_z0=1.760000e-01_alpha=7.860000e-01","WL_zdistri_model9_z0=1.760000e-01_alpha=7.860000e-01","WL_zdistri_model10_z0=1.740000e-01_alpha=7.720000e-01","WL_zdistri_model11_z0=1.710000e-01_alpha=7.590000e-01"};
char lens_zfile[12][400]={"LSS_zdistri_model0_z0=2.590000e-01_alpha=9.520000e-01","LSS_zdistri_model1_z0=2.610000e-01_alpha=9.370000e-01","LSS_zdistri_model2_z0=2.640000e-01_alpha=9.250000e-01","LSS_zdistri_model3_z0=2.640000e-01_alpha=9.250000e-01","LSS_zdistri_model4_z0=2.680000e-01_alpha=9.150000e-01","LSS_zdistri_model5_z0=2.740000e-01_alpha=9.070000e-01","LSS_zdistri_model6_z0=2.700000e-01_alpha=9.120000e-01","LSS_zdistri_model7_z0=2.740000e-01_alpha=9.070000e-01","LSS_zdistri_model8_z0=2.780000e-01_alpha=9.030000e-01","LSS_zdistri_model9_z0=2.780000e-01_alpha=9.030000e-01","LSS_zdistri_model10_z0=2.830000e-01_alpha=9.000000e-01","LSS_zdistri_model11_z0=2.880000e-01_alpha=8.980000e-01"};
int Ntomo_lens[12]={5,5,5,7,7,7,9,9,9,10,10,10};
init_cosmo();
init_fisher_precision();
init_binning_fourier(20,20.0,15000.0,3000.0,21.0,5,Ntomo_lens[t]);
init_survey(survey_designation[t]);
sprintf(arg1,"zdistris/%s",source_zfile[t]);
sprintf(arg2,"zdistris/%s",lens_zfile[t]);
init_galaxies(arg1,arg2,"gaussian","gaussian","SRD");
init_clusters();
init_IA("NLA_HF", "GAMA");
init_probes("3x2pt_clusterN_clusterWL");
init_priors("none","none","none","none");
sprintf(filename,"%s_area%le_ng%le_nl%le",survey_designation[t],area_table[t],nsource_table[t],nlens_table[t]);
if(strstr(survey_designation[t],"LSST_Y1") != NULL) compute_data_vector(filename,0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,1.413566e+00,1.567919e+00,1.731037e+00,1.900583e+00,2.074809e+00,1.413566e+00,1.567919e+00,1.731037e+00,1.900583e+00,2.074809e+00,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.03,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0);
if(strstr(survey_designation[t],"LSST_Y3") != NULL) compute_data_vector(filename,0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,1.392398e+00,1.500535e+00,1.613747e+00,1.731037e+00,1.851600e+00,1.974761e+00,2.100003e+00,1.731037e+00,1.900583e+00,2.074809e+00,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.03,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0);
if(strstr(survey_designation[t],"LSST_Y6") != NULL) compute_data_vector(filename,0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,1.380752e+00,1.463865e+00,1.550281e+00,1.639495e+00,1.731037e+00,1.824565e+00,1.919738e+00,2.016299e+00,2.114025e+00,2.074809e+00,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.03,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0);
if(strstr(survey_designation[t],"LSST_Y10") != NULL) compute_data_vector(filename,0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,1.376695e+00,1.451179e+00,1.528404e+00,1.607983e+00,1.689579e+00,1.772899e+00,1.857700e+00,1.943754e+00,2.030887e+00,2.118943e+00,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.03,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0);
return 0;
}
| {
"alphanum_fraction": 0.7032421884,
"avg_line_length": 49.8044496487,
"ext": "c",
"hexsha": "b822bfccb1eb180dd7e98cdd699c753db321a8a5",
"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": "a4a470b01fb85cd0f461a3a82a407e84b30dd5d1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "CosmoLike/LSSTC_obsstrat",
"max_forks_repo_path": "like_fourier.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a4a470b01fb85cd0f461a3a82a407e84b30dd5d1",
"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": "CosmoLike/LSSTC_obsstrat",
"max_issues_repo_path": "like_fourier.c",
"max_line_length": 964,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a4a470b01fb85cd0f461a3a82a407e84b30dd5d1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "CosmoLike/LSSTC_obsstrat",
"max_stars_repo_path": "like_fourier.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 18025,
"size": 42533
} |
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_histogram.h>
#include"mpi.h"
const double PI = 3.14159;
double rz(double red);
struct galaxy {
double x, y, z, d, w;
};
void N2divide( int * n, int N, int Ntot);
int main (int argc, char **argv) {
FILE * DD;
FILE * PP;
const int Nr = 150;
const int Nm = 100;
const double RSTEP = 1.0;
const double MSTEP = 0.01;
const int maxNgal = 40000000;
const double RMIN = 0.0;
const double RMAX = 150.0;
int *n;
char DDname[400];
char PPname[400];
int bit;
int bittot;
sprintf(DDname,argv[1]);
MPI_Init (&argc, &argv);
int numproc;
int totproc;
MPI_Comm_rank (MPI_COMM_WORLD, &numproc);
MPI_Comm_size (MPI_COMM_WORLD, &totproc);
n = (int *) calloc(totproc + 1, sizeof(int));
sprintf(PPname,"%s.RR",argv[2]);
DD = fopen(DDname,"r");
printf("%s %d\n",DDname,numproc);
struct galaxy * gal;
double * DDcount;
double * DDcount_in_place;
gal = (struct galaxy*)malloc(maxNgal*sizeof(struct galaxy));
DDcount = (double*)calloc(Nr*Nm,sizeof(double));
DDcount_in_place = (double*)calloc(Nr*Nm,sizeof(double));
struct galaxy * galp;
galp = gal;
int N = 0;
int Ntest = 0;
double sumW = 0;
double sumW_in_place = 0;
double ra, dec, red, dist;
double weight = 1.0;
double weight1;
double weight2;
double weight3;
double weight4;
double weightFKP;
int indexFKP;
double ddummy;
char line[2000];
for (int i = 0; i < 0; i ++) {
fgets (line, 2000, DD);
printf("%s\n", line);
}
int counter = 0;
while (fscanf(DD,"%le %le %le\n",&ra,&dec,&red) != EOF) {
counter ++;
if (counter%3 != 0) {
continue;
}
ra *= PI/180.0;
dec *= PI/180.0;
dist = rz(red);
galp->x = dist*cos(dec)*cos(ra);
galp->y = dist*cos(dec)*sin(ra);
galp->z = dist*sin(dec);
galp->d = dist;
// galp->w = weight1 * weight2;
galp++;
N++;
}
fclose(DD);
n[0] = 1;
N2divide(n, totproc, N);
n[totproc] = N;
n[0] = 0;
bit = n[numproc];
bittot = n[numproc + 1];
for (int i = 0; i < totproc + 1; i++) {
printf("n[%d] = %d\n", i, n[i]);
}
double mu;
double d1, d2, d3;
double x1, y1, z1, x2, y2, z2, gd1, gd2, gw1, gw2;
double r2, rat;
double rr;
double xb, yb, zb, db2;
struct galaxy * galp1, * galp2;
galp1 = gal;
galp1 += bit;
for (int i = bit; i < bittot; i++) {
x1 = galp1->x; y1 = galp1->y; z1 = galp1->z; gd1 = galp1->d; //gw1 = galp1->w;
galp2 = gal + i + 1;
for (int j = i + 1; j < N; j++) {
x2 = galp2->x; y2 = galp2->y; z2 = galp2->z; gd2 = galp2->d; //gw2 = galp2->w;
//sumW += gw1*gw2;
sumW += 1.0;
d1 = x1 - x2;
d2 = y1 - y2;
d3 = z1 - z2;
r2 = d1*d1 + d2*d2 + d3*d3;
if (r2 > RMAX*RMAX || r2 < RMIN*RMIN) {
galp2++;
continue;
}
rat = gd1/gd2;
xb = x1 + x2*rat;
yb = y1 + y2*rat;
zb = z1 + z2*rat;
db2 = xb*xb + yb*yb + zb*zb;
mu = fabs((xb*d1 + yb*d2 + zb*d3)/sqrt(r2)/sqrt(db2));
rr = sqrt(r2);
int binr = (int)((rr - RMIN)/RSTEP);
int binm = (int)(mu/MSTEP);
if (binr >= 0 && binm >= 0 && binr < Nr && binm < Nm){
int ind = binr + Nr*binm;
// DDcount[ind] += gw1*gw2;
DDcount[ind] += 1.0;
}
galp2++;
}
galp1++;
}
free(gal);
MPI_Reduce(DDcount, DDcount_in_place, Nr*Nm, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(&sumW, &sumW_in_place, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (numproc == 0) {
PP = fopen(PPname,"w");
printf("%s\n", PPname);
fprintf(PP,"# weighted number: %lf\n",sumW_in_place);
fprintf(PP,"# RBINS: %d\n",Nr);
fprintf(PP,"# MBINS: %d\n",Nm);
int k, l;
for (k = 0; k < Nm; k++) {
for (l = 0; l < Nr; l++) {
fprintf(PP,"%lf ",DDcount_in_place[k*Nr + l]);
}
fprintf(PP,"\n");
}
fclose(PP);
}
free(DDcount);
free(DDcount_in_place);
free(n);
MPI_Finalize ();
return 0;
}
double f (double x, void * p) {
double Om = 0.310;
double ff = 2997.92458/sqrt(Om*(1.0 + x)*(1.0 + x)*(1.0 + x) + 1.0 - Om);
return ff;
}
double rz (double red) {
gsl_integration_workspace * w = gsl_integration_workspace_alloc(1000);
double result, error;
gsl_function F;
F.function = &f;
gsl_integration_qags(&F, 0, red, 0, 1e-7, 1000, w, &result, &error);
gsl_integration_workspace_free (w);
return result;
}
void N2divide( int * n, int N, int Ntot) {
double dummy;
for (int i = 1; i < N; i++) {
dummy = double(Ntot) - 0.5;
dummy -=
sqrt((2*double(Ntot)-1)*(2*double(Ntot)-1)-4*((2*double(Ntot)-n[i-1])*(n[i-1]-1)+double(Ntot)*(double(Ntot)-1)/N))/2.0;
n[i] = int(dummy);
}
return;
}
| {
"alphanum_fraction": 0.5531780994,
"avg_line_length": 22.8086124402,
"ext": "c",
"hexsha": "7779a5d92387eefd21378b1b47b033afdd423ba6",
"lang": "C",
"max_forks_count": 13,
"max_forks_repo_forks_event_max_datetime": "2022-02-22T09:24:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-26T17:30:10.000Z",
"max_forks_repo_head_hexsha": "205ce48a288acacbd41358e6d0215f4aff355049",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "echaussidon/LSS",
"max_forks_repo_path": "backup/RRpar.c",
"max_issues_count": 13,
"max_issues_repo_head_hexsha": "205ce48a288acacbd41358e6d0215f4aff355049",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T15:29:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-26T22:06:24.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "echaussidon/LSS",
"max_issues_repo_path": "backup/RRpar.c",
"max_line_length": 119,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "205ce48a288acacbd41358e6d0215f4aff355049",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "echaussidon/LSS",
"max_stars_repo_path": "backup/RRpar.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-04T08:54:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-12T14:52:26.000Z",
"num_tokens": 1826,
"size": 4767
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C code headers for the implementation of the Fourier domain response for LIGO-VIRGO detectors
*
*
*/
#ifndef _LLVFDRESPONSE_H
#define _LLVFDRESPONSE_H
#define _XOPEN_SOURCE 500
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#include "LLVgeometry.h"
#include "struct.h"
#include "waveform.h"
#include "timeconversion.h"
/**************************************************/
/**************** Prototypes **********************/
/* Function to convert string input network string to Networktag */
Networktag ParseNetworktag(char* string);
/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LLV response (for a given detector), for given values of the inclination, position in the sky and polarization angle */
int LLVSimFDResponse(
struct tagListmodesCAmpPhaseFrequencySeries **listhlm, /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */
struct tagListmodesCAmpPhaseFrequencySeries **lists, /* Output: list of contribution of each mode in the detector signal, in Frequency-domain amplitude and phase form, for the given detector and sky position */
const double gpstime, /* GPS time (s) when the signal at coalescence reaches geocenter */
const double ra, /* Position in the sky: J2000.0 right ascension (rad) */
const double dec, /* Position in the sky: J2000.0 declination (rad) */
const double inclination, /* Inclination of the source (rad) */
const double psi, /* Polarization angle (rad) */
const Detectortag tag); /* Tag identifying the detector */
/* Core function processing a signal (in the form of a list of modes) through the Fourier-domain LLV response, for given values of the inclination, position in the sky and polarization angle */
int LLVSimFDResponse3Det(
struct tagListmodesCAmpPhaseFrequencySeries **listDet1, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the detector 1 */
struct tagListmodesCAmpPhaseFrequencySeries **listDet2, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the detector 2 */
struct tagListmodesCAmpPhaseFrequencySeries **listDet3, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the detector 3 */
struct tagListmodesCAmpPhaseFrequencySeries **list, /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */
const double gpstime, /* GPS time (s) when the signal at coalescence reaches geocenter */
const double ra, /* First angle for the position in the sky */
const double dec, /* Second angle for the position in the sky */
const double inclination, /* Inclination of the source */
const double psi, /* Polarization angle */
const Networktag tag); /* Selector for the detector network */
/* Function setting the response matrix of a given detector, in cartesian coordinates */
void SetMatrixD(
gsl_matrix* D, /* Output: matrix of the detector response Dij */
const Detectortag tag); /* Tag identifying the detector */
/* Function setting the position of a detector, in cartesian coordinates */
void SetVectorXd(
gsl_vector* Xd, /* Output: position vector of the detector */
const Detectortag tag); /* Tag identifying the detector */
/* Function setting the cartesian coordinates of the wave frame vectors (X,Y,Z), given the position in the sky and polarization */
void SetVectorsXYZ(
gsl_vector* X, /* Output: cartesian vector of the wave frame unit vector X */
gsl_vector* Y, /* Output: cartesian vector of the wave frame unit vector Y */
gsl_vector* Z, /* Output: cartesian vector of the wave frame unit vector Z */
const double theta, /* First angle for the position in the sky (Earth-based spherical angle) */
const double phi, /* Second angle for the position in the sky (Earth-based spherical angle) */
const double psi); /* Polarization angle */
#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif
#endif /* _LLVFDRESPONSE_H */
| {
"alphanum_fraction": 0.6423076923,
"avg_line_length": 52.5252525253,
"ext": "h",
"hexsha": "19219f44074ce48b49cca1649f35bc3ce93fcf3a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "LLVsim/LLVFDresponse.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "titodalcanton/flare",
"max_issues_repo_path": "LLVsim/LLVFDresponse.h",
"max_line_length": 216,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "LLVsim/LLVFDresponse.h",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 1068,
"size": 5200
} |
#ifndef __DIRECT_KNN_H__
#define __DIRECT_KNN_H__
#include <mpi.h>
#include <utility>
#include <cmath>
#include <vector>
#include <string>
#include <blas.h>
#include <omp.h>
#include <utility>
#define KNN_MAX_BLOCK_SIZE 512
#define KNN_MAX_MATRIX_SIZE 2e7L
// MPI message tags
enum {
TAG_R,
TAG_Q,
TAG_KMIN,
TAG_ID,
TAG_SIZE
};
enum {
VERTICAL,
HORIZONTAL
};
/**
* Options struct used to specify how a rectangular-partitioned query should be performed.
*/
struct directQueryParams
{
char queryType; ///< Perform a k-nearest ('K') or r-near ('R') search.
int k; ///< Number of neighbors to find (if queryType is 'K').
double r; ///< Radius for r-near search (if queryType is 'R').
int refParts; ///< Partition reference points into this many approximately equal parts.
int queryParts; ///< Partition query points into this many approximately equal parts.
};
struct directQueryResults
{
std::pair<double, long> *neighbors;
long *neighborCounts;
};
class maxheap_comp {
public:
bool operator() (const std::pair<double, long> &a, const std::pair<double, long> &b) {
double diff = fabs(a.first-b.first)/a.first;
if( std::isinf(diff) || std::isnan(diff) ) { // 0/0 or x/0
return a.first < b.first;
}
if( diff < 1.0e-8 ) {
return a.second < b.second;
}
return a.first < b.first;
}
};
namespace knn {
/**
* Compute the k nearest neighbors of each query point (OBSOLETE: For debugging purposes only; use directKQueryLowMem instead)..
* \param ref an n*dim-length array of data points.
* \param query an m*dim-length array of query points.
* \param n number of local reference point
* \param m number of local query points
* \param k number of neighbors to find for each query point.
* \param dim dimensionality of reference/query points
* \return An array of pairs containing the *squared* distance to each point and its
* index in the local array. Note that this is the index of the /point/ rather
* than the index of its location in the actual array of doubles. To access the
* point, use (point index)*dim to index ref.
*/
std::pair<double, long> *directKQuery
( double *ref, double *query, long n, long m, long k, int dim);
/**
* Compute the k nearest neighbors of each query point (OBSOLETE: For debugging purposes only; use directKQueryLowMem instead)..
* \param ref an n*dim-length array of data points.
* \param query an m*dim-length array of query points.
* \param n number of local reference point
* \param m number of local query points
* \param k number of neighbors to find for each query point.
* \param dim dimensionality of reference/query points
* \param result [out] An array of m*k pairs (allocated by caller) containing the
* *squared* distance to each point and its index in the local array.
* Note that this is the index of the /point/ rather than the index of its location
* in the actual array of doubles. To access the point, use (point index)*dim to index ref.
* Results for query point i begin at result[i*k].
* \param dist An array used for calculating inter-point distances. If NULL or unspecified,
* the function allocates and deallocates this array internally. Otherwise, it must be
* allocated size at least n*B, where B is the value returned by getBlockSize, and
* deallocated at some point after the function returns.
* \param sqnormr An array used for calculating inter-point distances. If NULL or unspecified,
* the function allocates and deallocates this array internally. Otherwise, it must be
* allocated size at least n and deallocated at some point after the function returns.
* \param sqnormq An array used for calculating inter-point distances. If NULL or unspecified,
* the function allocates and deallocates this array internally. Otherwise, it must be
* allocated size at least B, where B is the value returned by getBlockSize, and
* deallocated at some point after the function returns.
*/
void directKQuery_small_a2a( double *ref, long n, int dim, int k,
std::pair<double, long> *result,
double *dist = NULL, double *sqnormr = NULL, double *sqnormq = NULL);
/**
* Compute the k nearest neighbors of each query point with a smaller memory footprint and usually better performance.
* \param ref an n*dim-length array of data points.
* \param query an m*dim-length array of query points.
* \param n number of local reference point
* \param m number of local query points
* \param k number of neighbors to find for each query point.
* \param dim dimensionality of reference/query points
* \param result [out] An array of m*k pairs (allocated by caller) containing the
* *squared* distance to each point and its
* index in the local array. Note that this is the index of the /point/ rather
* than the index of its location in the actual array of doubles. To access the
* point, use (point index)*dim to index ref. Results for query point i begin at result[i*k].
* \param dist An array used for calculating inter-point distances. If NULL or unspecified,
* the function allocates and deallocates this array internally. Otherwise, it must be
* allocated size at least n*B, where B is the value returned by getBlockSize, and
* deallocated at some point after the function returns.
* \param sqnormr An array used for calculating inter-point distances. If NULL or unspecified,
* the function allocates and deallocates this array internally. Otherwise, it must be
* allocated size at least n and deallocated at some point after the function returns.
* \param sqnormq An array used for calculating inter-point distances. If NULL or unspecified,
* the function allocates and deallocates this array internally. Otherwise, it must be
* allocated size at least B, where B is the value returned by getBlockSize, and
* deallocated at some point after the function returns.
*/
void directKQueryLowMem
( double *ref, double *query, long n, long m, long k, int dim, std::pair<double, long> *result,
double *dist = NULL, double* sqnormr = NULL, double* sqnormq = NULL );
/**
* Find all points in ref that lie within distance sqrt(R) of each
* point in query.
* \param ref an n*dim-length array of data points.
* \param query an m*dim-length array of query points.
* \param n number of local reference point
* \param m number of local query points
* \param R The *square* of the search radius.
* \param dim dimensionality of reference/query points
* \param glob_ids An array of length n containing the global id of each ref point.
* \param neighbor_count [out] An array of length m containing the number of
* neighbors found for the corresponding query point (allocated internally).
* \param neighbors [out] An array of length sum(neighbor_count) containing
* pairs of ids and squared distances for each neighbor found (allocated
* internally).
*/
void directRQuery
( double *ref, double *query, long n, long m, double R, int dim, long* glob_ids,
int **neighbor_count, std::pair<double, long> **neighbors );
/**
* Find all points in ref that lie within distance sqrt(R[i]) of query point i.
* \param ref an n*dim-length array of data points.
* \param query an m*dim-length array of query points.
* \param n number of local reference point
* \param m number of local query points
* \param R Array of length m, the *square* of the search radius for each point.
* \param dim dimensionality of reference/query points
* \param glob_ids An array of length n containing the global id of each ref point.
* \param neighbor_count [out] An array of length m containing the number of
* neighbors found for the corresponding query point (allocated internally).
* \param neighbors [out] An array of length sum(neighbor_count) containing
* pairs of ids and squared distances for each neighbor found (allocated
* internally).
*/
void directRQueryIndividual
( double *ref, double *query, long n, long m, double *R, int dim, long* glob_ids,
int **neighbor_count, std::pair<double, long> **neighbors );
/**
* Find all points in ref that lie within distance sqrt(R[i]) of query point i.
* \param ref an n*dim-length array of data points.
* \param query an m*dim-length array of query points.
* \param n number of local reference point
* \param m number of local query points
* \param R Array of length m, the *square* of the search radius for each point.
* \param dim dimensionality of reference/query points
* \param glob_ids An array of length n containing the global id of each ref point.
* \param neighbor_count [out] An array of length m containing the number of
* neighbors found for the corresponding query point (allocated internally).
* \param neighbors [out] An array of length sum(neighbor_count) containing
* pairs of ids and squared distances for each neighbor found (allocated
* internally).
*/
void directRQueryIndividualK
( double *ref, double *query, long n, long m, int k, double *R, int dim, long *glob_ids,
int **neighbor_count, std::pair<double, long> **neighbors );
/**
* Computes the distances between all query points and all reference points.
* \param ref an n*dim-length array of data points.
* \param query an m*dim-length array of query points.
* \param n number of reference point
* \param m number of query points
* \param dim dimensionality of reference/query points
* \param dist [out] m*n matrix of the *squared* distances from query points to reference points.
* \param sqnormr An array of length n used for storing the squared norm of each reference point.
* If NULL or omitted, allocated and deallocated internally.
* \param sqnromq An array of length m used for storing the squared norm of each reference point.
* If NULL or omitted, allocated and deallocated internally.
* \param useSqnormrInput If true, use precomputed squared norm values contained in sqnormr when
* this function is called; if false, compute squared norms internally.
*/
void compute_distances
( double *ref, double *query, long n, long m, int dim, double *dist,
double* sqnormr = NULL, double* sqnormq = NULL, bool useSqnormrInput = false );
/**
* Computes the square of the norm of each row of a matrix.
* \param a The input matrix (row-major).
* \param n The number of rows of a.
* \param dim The number of columns of a.
* \param b [out] The output array (length n).
*/
void sqnorm ( double *a, long n, int dim, double *b);
/**
* Find the k-nearest neighbors of each query point using distributed cyclic-shift algorithm.
* \param ref an nlocal*dim-length array of data points.
* \param query an mlocal*dim-length array of query points.
* \param glob_ids An array of length nlocal containing the unique ID of each reference point stored locally.
* \param nlocal Number of local reference points.
* \param mlocal Number of local query points.
* \param k Number of neighbors to find for each query point.
* \param dim Dimensionality of reference/query points.
* \param comm The MPI communicator to use.
* \return An array of pairs containing the distance to each neighbor and its index;
* neighbors for point i begin at location i*k.
* \note All input arrays MUST be allocated with malloc (or equivalent) and deallocated with free;
* new and delete[] may result in a segmentation fault.
*/
std::pair<double, long> * dist_directKQuery( double* &ref, double *query,
long* &glob_ids,
int nlocal, int mlocal,
int k,
int dim,
MPI_Comm comm );
/**
* Find all reference points lying within distance sqrt(R) of each query point.
* \param ref an nlocal*dim-length array of data points.
* \param query an mlocal*dim-length array of query points.
* \param n Number of global reference points
* \param m Number of global query points
* \param nlocal Number of local reference points
* \param mlocal Number of local query points
* \param R The *square* of the search radius.
* \param dim Dimensionality of reference/query points
* \param glob_ids An array of length nlocal containing the unique ID of each reference point stored locally.
* \param rneighbors [out] An externally allocated array of mlocal vectors, used to store the neighbors of each
* query point.
* \param comm The MPI communicator to use.
*/
void dist_directRQuery
( double* &ref, double *query, long n, long m, int nlocal, int mlocal, double R,
int dim, long* &glob_ids, std::vector< std::pair<double, long> >* rneighbors,
MPI_Comm comm );
/**
* Find all reference points lying within distance sqrt(R) of each query point,
* up to a maximum of max_neighbors (not necessarily the nearest).
* \param ref an nlocal*dim-length array of data points.
* \param query an mlocal*dim-length array of query points.
* \param n Number of global reference points
* \param m Number of global query points
* \param nlocal Number of local reference points
* \param mlocal Number of local query points
* \param R The *square* of the search radius.
* \param dim Dimensionality of reference/query points
* \param glob_ids An array of length nlocal containing the unique ID of each reference point stored locally.
* \param rneighbors [out] An externally allocated array of mlocal vectors, used to store the neighbors of each
* query point.
* \param max_neighbors The maximum number of neighbors returned for any given query point.
* \param comm The MPI communicator to use.
*/
void dist_directRQuery
( double* &ref, double *query, long n, long m, int nlocal, int mlocal, double R,
int dim, long* &glob_ids, std::vector< std::pair<double, long> >* rneighbors, int max_neighbors,
MPI_Comm comm );
/**
* Find all reference points lying within distance sqrt(R[i]) of query point i.
* \param ref an nlocal*dim-length array of data points.
* \param query an mlocal*dim-length array of query points.
* \param n Number of global reference points
* \param m Number of global query points
* \param nlocal Number of local reference points
* \param mlocal Number of local query points
* \param R Array of length m, the *square* of the search radius for each query point.
* \param dim Dimensionality of reference/query points
* \param glob_ids An array of length nlocal containing the unique ID of each reference point stored locally.
* \param rneighbors [out] An externally allocated array of mlocal vectors, used to store the neighbors of each
* query point.
* \param comm The MPI communicator to use.
*/
void dist_directRQueryIndividual
( double* &ref, double *query, long n, long m, int nlocal, int mlocal, double *R,
int dim, long* &glob_ids, std::vector< std::pair<double, long> >* rneighbors,
MPI_Comm comm );
/**
* Find all reference points lying within distance sqrt(R[i]) of query point i.
* \param ref an nlocal*dim-length array of data points.
* \param query an mlocal*dim-length array of query points.
* \param n Number of global reference points
* \param m Number of global query points
* \param nlocal Number of local reference points
* \param mlocal Number of local query points
* \param R Array of length m, the *square* of the search radius for each query point.
* \param dim Dimensionality of reference/query points
* \param glob_ids An array of length nlocal containing the unique ID of each reference point stored locally.
* \param rneighbors [out] An externally allocated array of mlocal vectors, used to store the neighbors of each
* query point.
* \param comm The MPI communicator to use.
*/
void dist_directRQueryIndividualK
( double* &ref, double *query, long n, long m, int nlocal, int mlocal, double *R, int k,
int dim, long* &glob_ids, std::vector< std::pair<double, long> >* rneighbors,
MPI_Comm comm );
/**
* Find all reference points lying within distance sqrt(R[i]) of query point i,
* up to a maximum of max_neighbors points (not necessarily the nearest).
* \param ref an nlocal*dim-length array of data points.
* \param query an mlocal*dim-length array of query points.
* \param n Number of global reference points
* \param m Number of global query points
* \param nlocal Number of local reference points
* \param mlocal Number of local query points
* \param R Array of length m, the *square* of the search radius for each query point.
* \param dim Dimensionality of reference/query points
* \param glob_ids An array of length nlocal containing the unique ID of each reference point stored locally.
* \param rneighbors [out] An externally allocated array of mlocal vectors, used to store the neighbors of each
* query point.
* \param max_neighbors The maximum number of neighbors to return for any single query point.
* \param comm The MPI communicator to use.
*/
void dist_directRQueryIndividual
( double* &ref, double *query, long n, long m, int nlocal, int mlocal, double *R,
int dim, long* &glob_ids, std::vector< std::pair<double, long> >* rneighbors, int max_neighbors,
MPI_Comm comm );
/**
* Merges a and b and keeps only the k smallest from each of the m sets of distance/index pairs.
* \param a one array of m*k distance+index pairs
* \param b the other array of m*k distance+index pairs
* \param m the number sets of size k
* \param k k
* \return A newly allocated array of size m*k
*/
std::pair<double, long> *kmin_merge( std::pair<double, long> *a, std::pair<double, long> *b, long m, long k );
/**
* Reads reference and query points from files in parallel and partitions them for a query with the rectangular algorithm..
* \param refFile The name of the file which contains the reference points.
* \param queryFile The name of the file which contains the query points.
* \param ref [out] an n*dim array of data points.
* \param query [out] an m*dim array of query points.
* \param n number of reference points.
* \param m number of query points.
* \param dim dimensionality of reference/query points.
* \param refParts number of parts to split reference points into (refParts * queryParts = processes).
* \param queryParts number of parts to split query points into (refParts * queryParts = processes).
* \param comm The MPI communicator to use.
* \return A pair object containing the number of reference points (first) and query points (second) stored at this process.
*/
std::pair<int, int> partitionPoints(std::string refFile, std::string queryFile, double *& ref, double *& query, long n, long m, int dim, int refParts, int queryParts, MPI_Comm comm);
/**
* Returns the number of local elements in the partitioning used by dist_directKQuery.
* \param rank This process's MPI rank.
* \param size The size of the MPI communicator used.
* \param num The global number of elements.
* \return The number of elements this process stores locally.
*/
inline int getNumLocal( int rank, int size, long num ) {
if( rank < num%size)
return std::ceil( (double)num / (double)size );
else
return num / size;
}
/**
* Returns the offset of the locally stored elements in the global array.
* \param rank This process's MPI rank.
* \param size The size of the MPI communicator used.
* \param num The global number of elements.
* \return The global array offset.
*/
inline long getGlobalArrayOffset( int rank, int size, long num ) {
if( rank < num%size )
return std::ceil( (double)num / (double)size ) * rank;
else
return std::ceil( (double)num / (double)size ) * (num%size) + (rank-(num%size)) * (num/size);
}
/**
* Repartitions points with replication.
* \param points The points to repartition (modified).
* \param localPointCount The number of points the process has.
* \param dim The dimensionality of the points.
* \param globalIDs The global ID associated with each point (modified).
* \param partitionCount The number of pieces to partition the points into (the number of replications is implicitly given by size / partitionCount)
* \param comm The communicator to use.
* \return The new number of points the process has.
*/
int directRectRepartition(double *&points, int localPointCount, int dim, int *&globalIDs, int partitionCount, int direction, MPI_Comm comm);
/**
* Performs a direct kNN or rNN query using the rectangular-partitioned algorithm, automatically repartitioning points..
* \param refPts The reference points (modified).
* \param queryPts The query points (modified).
* \param localRefCount The number of reference points the process has (modified).
* \param localQueryCount The number of query points the process has (modified).
* \param dim The dimensionality of the points.
* \param refIDs The global IDS of the reference points the process has (modified).
* \param queryIDs The global IDs of the query points the process has (modified).
* \param params The parameters of the direct kNN or rNN query.
* \param comm The communicator to use.
* \return The result of the query.
*/
directQueryResults directRectRepartitionAndQuery(double *&refPts, double *&queryPts, long& localRefCount, long& localQueryCount, int dim, int *&refIDs, int *&queryIDs, directQueryParams params, MPI_Comm comm);
/**
* Performs a rNN query on a rectangularly partitioned set of points.
* \param refPoints The reference points.
* \param queryPoints The query points.
* \param localRefCount The number of reference points the process has.
* \param localQueryCount The number of query points the process has.
* \param dim The dimensionality of the points.
* \param r The search radius of the query.
* \param queryComm The communicator to use (all processes within this comm should have the same query points).
* \return The result of the query.
*/
directQueryResults directQueryRectR(double *refPoints, double *queryPoints, int localRefCount, int localQueryCount, int dim, double r, MPI_Comm queryComm);
/**
* Performs a kNN query on a rectangularly partitioned set of points.
* \param refPoints The reference points.
* \param queryPoints The query points.
* \param localRefCount The number of reference points the process has.
* \param localQueryCount The number of query points the process has.
* \param dim The dimensionality of the points.
* \param k The number of neighbors to find for each query point.
* \param queryComm The communicator to use (all processes within this comm should have the same query points).
* \return The result of the query.
*/
directQueryResults directQueryRectK(double *refPoints, double *queryPoints, int localRefCount, int localQueryCount, int dim, int k, MPI_Comm queryComm);
/**
* Determine the number of query points that will be handled by each iteration of the LowMem queries.
* \param n The number of reference points.
* \param m The number of query points.
* \return The block size the query will use. Can be multiplied by n to determine size of distance matrix.
*/
inline int getBlockSize(long n, long m) {
int blocksize;
if( m > KNN_MAX_BLOCK_SIZE || n > 10000L) {
blocksize = std::min((long)KNN_MAX_BLOCK_SIZE, m); //number of query points handled in a given iteration
if(n * (long)blocksize > KNN_MAX_MATRIX_SIZE) blocksize = std::min((long)(KNN_MAX_MATRIX_SIZE/n), (long)blocksize); //Shrink block size if n is huge.
blocksize = std::max(blocksize, omp_get_max_threads()); //Make sure each thread has some work.
} else {
blocksize = m;
}
return blocksize;
}
}
#endif
| {
"alphanum_fraction": 0.6970719805,
"avg_line_length": 48.7896825397,
"ext": "h",
"hexsha": "44c57ab57ce35712378cb7b2c735d4bdd118bf7e",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-10-08T20:02:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-08-11T22:29:45.000Z",
"max_forks_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "maumueller/rehashing",
"max_forks_repo_path": "benchmark/askit_release/rkdtsrc/include/direct_knn/direct_knn.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad",
"max_issues_repo_issues_event_max_datetime": "2020-10-09T04:27:39.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-10-06T09:47:52.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "maumueller/rehashing",
"max_issues_repo_path": "benchmark/askit_release/rkdtsrc/include/direct_knn/direct_knn.h",
"max_line_length": 212,
"max_stars_count": 20,
"max_stars_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "maumueller/rehashing",
"max_stars_repo_path": "benchmark/askit_release/rkdtsrc/include/direct_knn/direct_knn.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-22T20:48:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-14T20:08:08.000Z",
"num_tokens": 5958,
"size": 24590
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_errno.h>
#include "ccl.h"
/*----- ROUTINE: dc_NakamuraSuto -----
INPUT: cosmology, scale factor
TASK: Computes the peak threshold: delta_c(z) assuming LCDM.
Cosmology dependence of the critical linear density according to the spherical-collapse model.
Fitting function from Nakamura & Suto (1997; arXiv:astro-ph/9710107).
*/
double dc_NakamuraSuto(ccl_cosmology *cosmo, double a, int *status){
double Om_mz = ccl_omega_x(cosmo, a, ccl_species_m_label, status);
double dc0 = (3./20.)*pow(12.*M_PI,2./3.);
double dc = dc0*(1.+0.012299*log10(Om_mz));
return dc;
}
/*----- ROUTINE: Dv_BryanNorman -----
INPUT: cosmology, scale factor
TASK: Computes the virial collapse density contrast with respect to the matter density assuming LCDM.
Cosmology dependence of the virial collapse density according to the spherical-collapse model
Fitting function from Bryan & Norman (1998; arXiv:astro-ph/9710107)
*/
double Dv_BryanNorman(ccl_cosmology *cosmo, double a, int *status){
double Om_mz = ccl_omega_x(cosmo, a, ccl_species_m_label, status);
double x = Om_mz-1.;
double Dv0 = 18.*pow(M_PI,2);
double Dv = (Dv0+82.*x-39.*pow(x,2))/Om_mz;
return Dv;
}
static double sigmaM_m2r(ccl_cosmology *cosmo, double halomass, int *status)
{
double rho_m, smooth_radius;
// Comoving matter density
//rho_m = ccl_constants.RHO_CRITICAL*cosmo->params.Omega_m*cosmo->params.h*cosmo->params.h;
rho_m = ccl_rho_x(cosmo, 1., ccl_species_m_label, 1, status);
smooth_radius = pow((3.0*halomass) / (4*M_PI*rho_m), (1.0/3.0));
return smooth_radius;
}
void ccl_cosmology_compute_sigma(ccl_cosmology *cosmo, int *status)
{
if(cosmo->computed_sigma)
return;
// create linearly-spaced values of the mass.
int nm = cosmo->spline_params.LOGM_SPLINE_NM;
double *m = NULL;
double *y = NULL;
double smooth_radius;
double na, nb;
m = ccl_linear_spacing(cosmo->spline_params.LOGM_SPLINE_MIN, cosmo->spline_params.LOGM_SPLINE_MAX, nm);
if (m == NULL ||
(fabs(m[0]-cosmo->spline_params.LOGM_SPLINE_MIN)>1e-5) ||
(fabs(m[nm-1]-cosmo->spline_params.LOGM_SPLINE_MAX)>1e-5) ||
(m[nm-1]>10E17)) {
*status = CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo,"ccl_cosmology_compute_sigmas(): Error creating linear spacing in m\n");
}
if (*status == 0) {
// create space for y, to be filled with sigma and dlnsigma_dlogm
y = malloc(sizeof(double)*nm);
if (y == NULL) {
*status = CCL_ERROR_MEMORY;
}
}
// start up of GSL pointers
int gslstatus = 0;
gsl_spline *logsigma = NULL;
gsl_spline *dlnsigma_dlogm = NULL;
// fill in sigma, if no errors have been triggered at this time.
if (*status == 0) {
for (int i=0; i<nm; i++) {
smooth_radius = sigmaM_m2r(cosmo, pow(10,m[i]), status);
y[i] = log(ccl_sigmaR(cosmo, smooth_radius, 1., status));
}
logsigma = gsl_spline_alloc(cosmo->spline_params.M_SPLINE_TYPE, nm);
if (logsigma == NULL) {
*status = CCL_ERROR_MEMORY;
}
}
if (*status == 0) {
gslstatus = gsl_spline_init(logsigma, m, y, nm);
if (gslstatus != GSL_SUCCESS) {
*status = CCL_ERROR_SPLINE ;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_sigma(): Error creating sigma(M) spline\n");
}
}
// again, making splines assuming nothing bad has happened to this point
if (*status == 0 ) {
for (int i=0; i<nm; i++) {
if(i==0) {
gslstatus |= gsl_spline_eval_e(logsigma, m[i], NULL,&na);
gslstatus |= gsl_spline_eval_e(logsigma, m[i]+cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&nb);
y[i] = 2.*(na-nb)*y[i] / cosmo->spline_params.LOGM_SPLINE_DELTA;
}
else if (i==nm-1) {
gslstatus |= gsl_spline_eval_e(logsigma, m[i]-cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&na);
gslstatus |= gsl_spline_eval_e(logsigma, m[i], NULL,&nb);
y[i] = 2.*(na-nb)*y[i] / cosmo->spline_params.LOGM_SPLINE_DELTA;
}
else {
gslstatus |= gsl_spline_eval_e(logsigma, m[i]-cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&na);
gslstatus |= gsl_spline_eval_e(logsigma, m[i]+cosmo->spline_params.LOGM_SPLINE_DELTA/2., NULL,&nb);
y[i] = (na-nb) / cosmo->spline_params.LOGM_SPLINE_DELTA;
}
}
if(gslstatus != GSL_SUCCESS ) {
ccl_raise_gsl_warning(
gslstatus, "ccl_massfunc.c: ccl_cosmology_compute_sigma():");
*status = CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_sigma(): "
"Error evaluating grid points for dlnsigma/dlogM spline\n");
}
}
if (*status == 0) {
dlnsigma_dlogm = gsl_spline_alloc(cosmo->spline_params.M_SPLINE_TYPE, nm);
if (dlnsigma_dlogm == NULL) {
*status = CCL_ERROR_MEMORY;
}
}
if (*status == 0) {
gslstatus = gsl_spline_init(dlnsigma_dlogm, m, y, nm);
if (gslstatus != GSL_SUCCESS) {
*status = CCL_ERROR_SPLINE ;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_cosmology_compute_sigma(): Error creating dlnsigma/dlogM spline\n");
}
}
if (*status == 0) {
cosmo->data.logsigma = logsigma;
cosmo->data.dlnsigma_dlogm = dlnsigma_dlogm;
cosmo->computed_sigma = true;
} else {
gsl_spline_free(logsigma);
gsl_spline_free(dlnsigma_dlogm);
}
free(m);
free(y);
}
/*----- ROUTINE: ccl_sigma_M -----
INPUT: ccl_cosmology * cosmo, double halo mass in units of Msun, double scale factor
TASK: returns sigma from the sigmaM interpolation. Also computes the sigma interpolation if
necessary.
*/
double ccl_sigmaM(ccl_cosmology *cosmo, double log_halomass, double a, int *status)
{
double sigmaM;
// Check if sigma has already been calculated
if (!cosmo->computed_sigma) {
*status = CCL_ERROR_SIGMA_INIT;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_sigmaM(): linear power spctrum has not been computed!");
return NAN;
}
double lgsigmaM;
int gslstatus = gsl_spline_eval_e(cosmo->data.logsigma, log_halomass, NULL, &lgsigmaM);
if(gslstatus != GSL_SUCCESS) {
ccl_raise_gsl_warning(gslstatus, "ccl_massfunc.c: ccl_sigmaM():");
*status |= gslstatus;
}
// Interpolate to get sigma
sigmaM = exp(lgsigmaM)*ccl_growth_factor(cosmo, a, status);
return sigmaM;
}
/*----- ROUTINE: ccl_dlnsigM_dlogM -----
INPUT: ccl_cosmology *cosmo, double halo mass in units of Msun
TASK: returns the value of the derivative of ln(sigma^-1) with respect to log10 in halo mass.
*/
double ccl_dlnsigM_dlogM(ccl_cosmology *cosmo, double log_halomass, int *status)
{
// Check if sigma has already been calculated
if (!cosmo->computed_sigma) {
*status = CCL_ERROR_SIGMA_INIT;
ccl_cosmology_set_status_message(
cosmo,
"ccl_massfunc.c: ccl_sigmaM(): linear power spctrum has not been computed!");
return NAN;
}
double dlsdlgm;
int gslstatus = gsl_spline_eval_e(cosmo->data.dlnsigma_dlogm,
log_halomass, NULL, &dlsdlgm);
if(gslstatus) {
ccl_raise_gsl_warning(gslstatus, "ccl_massfunc.c: ccl_dlnsigM_dlogM():");
*status |= gslstatus;
}
return dlsdlgm;
}
| {
"alphanum_fraction": 0.6832180166,
"avg_line_length": 31.9090909091,
"ext": "c",
"hexsha": "f121d77326dfc7c5ac0a0fc7b0e08f8d507bd5ad",
"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": "46692a38afd249946ac004cec391f47fd7c34f63",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "timothydmorton/CCL",
"max_forks_repo_path": "src/ccl_massfunc.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63",
"max_issues_repo_issues_event_max_datetime": "2020-07-28T12:22:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-28T12:22:35.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "timothydmorton/CCL",
"max_issues_repo_path": "src/ccl_massfunc.c",
"max_line_length": 115,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "timothydmorton/CCL",
"max_stars_repo_path": "src/ccl_massfunc.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2302,
"size": 7371
} |
#pragma once
#include <string>
#include <type_traits>
#include <tuple>
#include <gsl.h>
#include "roster.h"
#include "timestamp.h"
#include <boost/multi_index/sequenced_index.hpp>
class Grade
{
public:
class Key
{
private:
Roster const& roster_;
std::string grader_email_;
std::string student_name_;
private:
friend bool operator==(const Key lhs, const Key rhs)
{
const auto result{ lhs.grader_email_ == rhs.grader_email_ && lhs.student_name_ == rhs.student_name_ };
return result;
}
public:
explicit Key(Roster const& roster);
std::string getGraderEmail() const
{
Expects(!grader_email_.empty() && roster_.is_email_good(grader_email_));
return grader_email_;
}
void setGraderEmail(const std::string grader_email)
{
Expects(!grader_email.empty() && roster_.is_email_good(grader_email));
grader_email_ = grader_email;
}
std::string getStudentName() const
{
Expects(!student_name_.empty());
return student_name_;
}
void setStudentName(const std::string student_name)
{
Expects(!student_name.empty());
student_name_ = student_name;
}
bool is_good() const;
};
private:
Roster const& roster_;
Key key_;
Timestamp timestamp_{};
unsigned score_{ 0 };
public:
bool is_good() const;
Key getKey() const
{
return key_;
}
Timestamp getTimestamp() const
{
return timestamp_;
}
unsigned getScore() const
{
return score_;
}
private:
void setTimestamp(const Timestamp timestamp)
{
Expects(timestamp.is_good());
timestamp_ = timestamp;
}
friend std::istream& operator>>(std::istream& is, Grade& grade)
{
Timestamp timestamp;
is >> timestamp;
Ensures(timestamp.is_good());
grade.setTimestamp(timestamp);
char grader_email_cstr[256]{};
constexpr auto max_grader_len{ std::extent<decltype(grader_email_cstr)>::value };
is.getline(grader_email_cstr, max_grader_len, ',');
auto const grader_len{ strlen(grader_email_cstr) };
Ensures(grader_len > 0 && grader_len < max_grader_len);
grade.key_.setGraderEmail(grader_email_cstr);
is.ignore(std::numeric_limits<std::streamsize>::max(), ',');
char student_name_cstr[256]{};
constexpr auto max_student_name_len{ std::extent<decltype(student_name_cstr)>::value };
is.getline(student_name_cstr, max_student_name_len, ',');
auto const student_len{ strlen(student_name_cstr) };
Ensures(student_len > 0 && student_len < max_student_name_len);
grade.key_.setStudentName(student_name_cstr);
Ensures(grade.is_good());
is.seekg(-2, std::ios_base::end);
auto const is_comma{ is.peek()==',' };
if (is_comma)
{
is.ignore();
}
auto grade_value{ std::numeric_limits<int>::max() };
is >> grade_value;
Ensures(grade_value >= 0 && grade_value<(10+1) && is.eof());
grade.score_ = 10 * grade_value;
Ensures(grade.score_ >= 0 && grade.score_ < (100+1));
return is;
}
public:
explicit Grade(Roster const& roster);
};
| {
"alphanum_fraction": 0.7010238908,
"avg_line_length": 20.6338028169,
"ext": "h",
"hexsha": "9be8018ecbd3dc25662204aa25d89df931283bd1",
"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": "2e5f274dbaba950a9ec406b77544be2ca210a8ac",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "labermt/SRSGrade",
"max_forks_repo_path": "SRSGrade/grade.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2e5f274dbaba950a9ec406b77544be2ca210a8ac",
"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": "labermt/SRSGrade",
"max_issues_repo_path": "SRSGrade/grade.h",
"max_line_length": 105,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2e5f274dbaba950a9ec406b77544be2ca210a8ac",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "labermt/SRSGrade",
"max_stars_repo_path": "SRSGrade/grade.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 808,
"size": 2930
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "parmt_utils.h"
#ifdef PARMT_USE_INTEL
#include <mkl_lapacke.h>
#include <mkl_cblas.h>
#else
#include <lapacke.h>
#include <cblas.h>
#endif
#include "iscl/array/array.h"
#include "iscl/memory/memory.h"
#include "iscl/random/random.h"
#include "iscl/signal/convolve.h"
int parmt_utils_getEffectiveRank(const double relError,
const struct parmtNoiseBasis_struct basis)
{
double frac;
int i, rank;
rank = 1;
for (i=1; i<basis.nvals; i++)
{
// Modification of Demmel 3.9.3 to deal with sqrt(eig)
if (100.0*pow(basis.sqrtEvals[i], 2)/pow(basis.sqrtEvals[0], 2) < relError)
{
rank = i;
break;
}
}
return rank;
}
int parmt_utils_makeKLNoise(const int rank,
const int npts,
const struct parmtNoiseBasis_struct basis,
double *__restrict__ xn)
{
double *r, xscal;
int ir, ierr, ldz, rankUse;
if (rank < 1 || npts < 1 || basis.npts != npts || xn == NULL)
{
if (rank < 1){fprintf(stderr, "%s: rank is too small\n", __func__);}
if (npts < 1){fprintf(stderr, "%s: no points\n", __func__);}
if (basis.npts != npts)
{
fprintf(stderr, "%s: npts != basis.npts\n", __func__);
}
if (xn == NULL){fprintf(stderr, "%s: error x is NULL\n", __func__);}
return -1;
}
rankUse = MAX(1, MIN(basis.nvals, rank));
ldz = basis.lde;
r = random_rand64f(rankUse, &ierr);
array_zeros64f_work(npts, xn);
for (ir=0; ir<rank; ir++)
{
xscal = r[ir]*basis.sqrtEvals[ir];
printf("%f %f\n", r[ir], basis.sqrtEvals[ir]);
cblas_daxpy(npts, xscal, &basis.evects[ir*ldz], 1, xn, 1);
}
memory_free64f(&r);
return 0;
}
//============================================================================//
/*!
* @brief Releases memory on the noise basis struture
*
* @param[out] basis on exit all memory has been released and all variables
* set to NULL or 0.
*
* @author Ben Baker
*
* @copyright ISTI distributed under Apache 2
*
*/
int parmt_utils_freeNoiseBasis(struct parmtNoiseBasis_struct *basis)
{
memory_free64f(&basis->sqrtEvals);
memory_free64f(&basis->evects);
memset(basis, 0, sizeof(struct parmtNoiseBasis_struct));
return 0;
}
//============================================================================//
/*!
* @brief Computes the eigenvectors and eigenvalues of the noise
* autocorrelation matrix which will be further used in the
* Karhunen-Loeve expansion.
*
* @param[in] npts number of data points
* @param[in] data noise signal from which to compute noise basis.
*
* @param[out] basis on successful exit contains the eigendecomposition
* of the autocorrelation noise matrix for use in the KL
* expansion.
*
* @result 0 indicates success
*
* @author Ben Baker
*
* @copyright ISTI distributed under Apache 2
*
*/
int parmt_utils_getNoiseBasis64f(const int npts,
const double *__restrict__ data,
struct parmtNoiseBasis_struct *basis)
{
double *C, *CtC, *s, xnorm;
int i, ierr, j, ldc, ldctc, m, n, nrows;
const enum corrMatrixType_enum type = CORRMTX_AUTOCORRELATION;
//------------------------------------------------------------------------//
//
// error checking
ierr = 0;
memset(basis, 0, sizeof(struct parmtNoiseBasis_struct));
if (npts < 1 || data == NULL)
{
if (npts < 1)
{
fprintf(stderr, "%s: No points in noise signal\n", __func__);
}
if (data == NULL)
{
fprintf(stderr, "%s; Noise signal is NULL\n", __func__);
}
return -1;
}
C = NULL;
CtC = NULL;
// Normalize the noise energy in the noise signal
xnorm = cblas_dnrm2(npts, data, 1);
if (fabs(xnorm) < 1.e-15)
{
fprintf(stderr, "%s: Error division by zero\n", __func__);
return -1;
}
xnorm = 1.0/xnorm;
s = array_copy64f(npts, data, &ierr);
cblas_dscal(npts, xnorm, s, 1);
// Figure out the size of the noise correlation matrix
n = npts;
m = npts - 1;
ldc = n;
if (type == CORRMTX_AUTOCORRELATION)
{
nrows = n + m;
C = memory_calloc64f(ldc*nrows);
}
else
{
fprintf(stderr, "%s: Invalid correlation matrix type\n", __func__);
return -1;
}
ldctc = n;
CtC = memory_calloc64f(n*n);
// Compute the correlation matrix and C'C
ierr = convolve_corrmtx64f_work(npts, s,
m, ldc, C,
type, true, ldctc, CtC);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to compute correlation matrix\n", __func__);
goto ERROR;
}
ierr = parmt_utils_getNoiseBasisFromCtC64f(npts, ldctc, CtC, basis);
if (ierr != 0)
{
fprintf(stderr, "%s: Failed to compute noise basis\n", __func__);
}
ERROR:;
memory_free64f(&C);
memory_free64f(&CtC);
return ierr;
}
int parmt_utils_getNoiseBasisFromCtC64f(const int npts, const int ldctc,
const double *__restrict__ CtC,
struct parmtNoiseBasis_struct *basis)
{
double *CtCw, *w;
int ierr, i, info, j;
ierr = 0;
memset(basis, 0, sizeof(struct parmtNoiseBasis_struct));
CtCw = memory_calloc64f(npts*ldctc);
for (i=0; i<npts; i++)
{
cblas_dcopy(npts, &CtC[i*ldctc], 1, &CtCw[i*ldctc], 1);
}
// Compute the eigendecompsition of the symmetric matrix
w = memory_calloc64f(npts);
info = LAPACKE_dsyev(LAPACK_ROW_MAJOR, 'V', 'U', npts, CtCw, ldctc, w);
if (info != 0)
{
ierr = 1;
if (info > 0)
{
fprintf(stderr, "%s: Failure to converge on %d'th element\n",
__func__, info);
}
else
{
fprintf(stderr, "%s: %d'th parameter is invalid\n", __func__, info);
}
goto ERROR;
}
// Set the basis
basis->lde = npts;
basis->nvals = npts;
basis->npts = npts;
basis->sqrtEvals = memory_calloc64f(basis->nvals);
basis->evects = memory_calloc64f(basis->lde*basis->nvals);
// Put into descending order
for (i=0; i<npts; i++)
{
basis->sqrtEvals[i] = sqrt(w[npts-1-i]);
}
// Copy corresponding eigenvectors in descending order
for (j=0; j<npts; j++)
{
for (i=0; i<npts; i++)
{
basis->evects[j*basis->lde+i] = CtCw[i*ldctc+(npts-1-j)];
}
}
ERROR:;
memory_free64f(&w);
memory_free64f(&CtCw);
return ierr;
}
| {
"alphanum_fraction": 0.544584602,
"avg_line_length": 29.7284482759,
"ext": "c",
"hexsha": "ec678c1f495efc56311121a7fa066308a08ee90b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_forks_repo_licenses": [
"Intel"
],
"max_forks_repo_name": "bakerb845/parmt",
"max_forks_repo_path": "utils/getNoiseBasis.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Intel"
],
"max_issues_repo_name": "bakerb845/parmt",
"max_issues_repo_path": "utils/getNoiseBasis.c",
"max_line_length": 83,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416",
"max_stars_repo_licenses": [
"Intel"
],
"max_stars_repo_name": "bakerb845/parmt",
"max_stars_repo_path": "utils/getNoiseBasis.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1964,
"size": 6897
} |
#include <math.h>
#include <float.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <cblas.h>
#include "funcsfa.h"
#define min(x, y) ((x)>(y)?(y):(x))
#define max(x, y) ((x)>(y)?(x):(y))
#define DEBUG 0
#define debug_print(fmt, ...) \
do { if (DEBUG) fprintf(stderr, "%s:%4d:%25s(): " fmt, __FILE__, \
__LINE__, __func__, __VA_ARGS__); } while (0)
double eps_ev = 1e-20;
// **************************************
// Lapack
// **************************************
// Lapack Fortran DGESV interface
void
dgesv_(int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb,
int *info);
// DGESV wrapper, for solving linear equations.
static int
dgesv(int n, int nrhs, double *a, int lda, int *ipiv, double *b, int ldb)
{
int info = -1;
dgesv_(&n, &nrhs, a, &lda, ipiv, b, &ldb, &info);
return info;
}
// Lapack Fortran DGESVD interface
void
dgesvd_(char *jobu, char *jobvt, int *m, int *n, double *a, int *lda,
double *s, double *u, int *ldu, double *vt, int *ldvt, double *work,
int *lwork, int *info);
// DGESVD wrapper, for Singular Value Decomposition.
static int
dgesvd(char jobu, char jobvt, int m, int n, double *a, int lda, double *s,
double *u, int ldu, double *vt, int ldvt)
{
int info = -1;
int lwork = -1;
double optimal_lwork;
double *work;
// Query optimal work size
dgesvd_(&jobu, &jobvt, &m, &n, a, &lda,
s, u, &ldu, vt, &ldvt, &optimal_lwork,
&lwork, &info);
if (info != 0) {
return info;
}
lwork = (int) optimal_lwork;
work = malloc(sizeof(double)*lwork);
dgesvd_(&jobu, &jobvt, &m, &n, a, &lda,
s, u, &ldu, vt, &ldvt, work,
&lwork, &info);
free(work);
return info;
}
// **************************************
// Objects
// **************************************
funcsfa_Factorization*
funcsfa_Factorization_alloc(size_t n_features, size_t n_factors,
size_t n_samples, size_t n_datatypes,
size_t *n_features_split, double *data)
{
size_t i;
funcsfa_Factorization *m;
size_t sum_n_features_split = 0;
debug_print("%s\n", "Allocating SFA object");
m = malloc(sizeof(funcsfa_Factorization));
m->n_features = n_features;
m->n_factors = n_factors;
m->n_samples = n_samples;
m->n_datatypes = n_datatypes;
m->n_features_split = malloc(sizeof(size_t)*n_datatypes);
for(i=0; i<n_datatypes; i++)
{
m->n_features_split[i] = n_features_split[i];
sum_n_features_split += n_features_split[i];
}
if (sum_n_features_split != n_features)
{
debug_print("Total number of features (%zd) does not match sum (%zd)\n",
n_features, sum_n_features_split);
free(m->n_features_split);
free(m);
return NULL;
}
m->data = data;
m->coefficients = malloc(sizeof(double)*n_features*n_factors);
m->factors = malloc(sizeof(double)*n_factors*n_samples);
m->factor_cov = malloc(sizeof(double)*n_factors*n_factors);
m->residual_var = malloc(sizeof(double)*n_features);
return(m);
}
void
funcsfa_Factorization_free(funcsfa_Factorization *m)
{
debug_print("%s\n", "Freeing SFA object");
if (m != NULL)
{
free(m->n_features_split);
free(m->coefficients);
free(m->factors);
free(m->factor_cov);
free(m->residual_var);
}
free(m);
}
funcsfa_Monitor*
funcsfa_Monitor_alloc(int max_iter)
{
funcsfa_Monitor *mon;
int i;
debug_print("%s\n", "Allocating Monitor object");
mon = malloc(sizeof(funcsfa_Monitor));
if (mon == NULL) {
return NULL;
}
mon->n_iter = 0;
mon->reconstruction_error = malloc(sizeof(double)*(max_iter+1));
mon->max_diff_factors = malloc(sizeof(double)*(max_iter+1));
mon->max_diff_coefficients = malloc(sizeof(double)*(max_iter+1));
if ((mon->reconstruction_error == NULL) ||
(mon->max_diff_factors == NULL) ||
(mon->max_diff_coefficients == NULL))
{
funcsfa_Monitor_free(mon);
return NULL;
}
for (i = 0; i < max_iter+1; i++)
{
mon->reconstruction_error[i] = NAN;
mon->max_diff_factors[i] = NAN;
mon->max_diff_coefficients[i] = NAN;
}
return mon;
}
void
funcsfa_Monitor_free(funcsfa_Monitor *mon)
{
debug_print("%s\n", "Freeing Monitor object");
if (mon != NULL)
{
free(mon->reconstruction_error);
free(mon->max_diff_factors);
free(mon->max_diff_coefficients);
}
free(mon);
}
/** Bunch of memory for temporary matrices.
* @private
*/
typedef struct
{
/** Integer vector n_factors long */
int *factors_int;
/** Double vector n_features long */
double *features_double;
/** Double matrix n_features x n_factors 1 */
double *features_factors_double_a;
/** Double matrix n_features x n_factors 2 */
double *features_factors_double_b;
/** Double matrix n_factors x n_factors 1 */
double *factors_factors_double_a;
/** Double matrix n_factors x n_factors 2 */
double *factors_factors_double_b;
/** Precomputed value of diag(data * t(data)) */
double *diag_data_square;
/** Precomputed value of sum(diag(data * t(data))) per data type */
double *dt_var;
/** Factors of previous iteration */
double *prev_factors;
/** Coefficients of previous iteration */
double *prev_coefficients;
} Workspace;
static Workspace*
ws_alloc(funcsfa_Factorization *m)
{
Workspace *ws;
debug_print("%s\n", "Allocating Workspace");
ws = malloc(sizeof(Workspace));
ws->factors_int = malloc(sizeof(int)*m->n_factors);
ws->features_double = malloc(sizeof(double)*m->n_features);
ws->features_factors_double_a = malloc(sizeof(double)*m->n_features*m->n_factors);
ws->features_factors_double_b = malloc(sizeof(double)*m->n_features*m->n_factors);
ws->factors_factors_double_a = malloc(sizeof(double)*m->n_factors*m->n_factors);
ws->factors_factors_double_b = malloc(sizeof(double)*m->n_factors*m->n_factors);
ws->diag_data_square = malloc(sizeof(double)*m->n_features);
ws->dt_var = malloc(sizeof(double)*m->n_factors);
ws->prev_factors = malloc(sizeof(double)*m->n_factors*m->n_samples);
ws->prev_coefficients = malloc(sizeof(double)*m->n_features*m->n_factors);
return ws;
}
static void
ws_init(Workspace *ws, funcsfa_Factorization *m)
{
double *d_d;
size_t dt_i, feature_start, n_features, i;
debug_print("%s\n", "Initializing Workspace");
d_d = malloc(sizeof(double)*m->n_features*m->n_features);
cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans,
m->n_features, m->n_features, m->n_samples, 1,
m->data, m->n_samples,
m->data, m->n_samples,
0, d_d, m->n_features);
for (i = 0; i < m->n_features; i++)
{
ws->diag_data_square[i] = d_d[i*m->n_features + i];
}
feature_start = 0;
for(dt_i = 0; dt_i < m->n_datatypes; dt_i++)
{
ws->dt_var[dt_i] = 0;
n_features = m->n_features_split[dt_i];
for(i = feature_start; i < (feature_start + n_features); i++)
{
ws->dt_var[dt_i] += ws->diag_data_square[i];
}
ws->dt_var[dt_i] /= n_features;
feature_start = feature_start + n_features;
}
free(d_d);
}
static void
ws_free(Workspace *ws)
{
debug_print("%s\n", "Freeing Workspace");
free(ws->factors_int);
free(ws->features_double);
free(ws->features_factors_double_a);
free(ws->features_factors_double_b);
free(ws->factors_factors_double_a);
free(ws->factors_factors_double_b);
free(ws->diag_data_square);
free(ws->dt_var);
free(ws->prev_factors);
free(ws->prev_coefficients);
free(ws);
}
// **************************************
// Utility Functions
// **************************************
static double
max_diff(double *a, double *b, size_t length)
{
size_t i;
double md, d;
md = 0;
for (i = 0; i < length; i++)
{
d = fabs(a[i] - b[i]);
if (d > md)
{
md = d;
}
}
return md;
}
static bool
finite_array(double *a, size_t length)
{
for (size_t i=0; i<length; i++)
{
if (!isfinite(a[i]))
{
return false;
}
}
return true;
}
static bool
positive_array(double *a, size_t length)
{
for (size_t i=0; i<length; i++)
{
if (!(a[i] > 0.0))
{
return false;
}
}
return true;
}
#define check_finite(a, length) \
if (DEBUG && !finite_array(a, length)) {\
debug_print("%s\n", "Error, non-finite values in matrix");}
#define check_positive(a, length) \
if (DEBUG && !positive_array(a, length)) {\
debug_print("%s\n", "Error, non-positive values in matrix");}
// **************************************
// Algorithm
// **************************************
static int
expectation_factors(funcsfa_Factorization *m, Workspace *ws)
{
size_t i, j;
double *r_c, *c_r_c, *c_r_c_i, *o, *c_o;
double factor_mean, factor_var, factor_sd, deviance;
int *ipiv;
int info;
debug_print("%s\n", "Computing Expectation and Covariance of Factors");
check_finite(m->coefficients, m->n_features*m->n_factors);
check_finite(m->residual_var, m->n_features);
check_positive(m->residual_var, m->n_features);
/* Compute $\Psi^{-1} B$
* r_c = diag(1/residual_var) * coefficients */
r_c = ws->features_factors_double_a;
for (i=0; i < m->n_features; i++)
{
for (j=0; j < m->n_factors; j++)
{
r_c[j * m->n_features + i] =
m->coefficients[j * m->n_features + i] / m->residual_var[i];
}
}
/* Compute $B^T \Psi^{-1} B + I$
* c_r_c = t(coefficients) * r_c + I */
c_r_c = ws->factors_factors_double_a;
cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans,
m->n_factors, m->n_factors, m->n_features, 1,
m->coefficients, m->n_features,
r_c, m->n_features,
0, c_r_c, m->n_factors);
for (i = 0; i < m->n_factors; i++)
{
c_r_c[i*m->n_factors + i] += 1;
}
/* Compute $O = \Psi^{-1}B(B^T \Psi^{-1} B + I)^{-1}$
* o = r_c*solve(c_r_c) */
c_r_c_i = ws->factors_factors_double_b;
ipiv = ws->factors_int;
for (i = 0; i < m->n_factors; i++)
{
for (j = 0; j < m->n_factors; j++)
{
c_r_c_i[j * m->n_factors + i] = (i == j);
}
}
info = dgesv(m->n_factors, m->n_factors,
c_r_c, m->n_factors, ipiv,
c_r_c_i, m->n_factors);
if (info != 0) {
debug_print("Lapack error: %d\n", info);
return -1;
}
c_r_c = NULL;
o = ws->features_factors_double_b;
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
m->n_features, m->n_factors, m->n_factors, 1,
r_c, m->n_features,
c_r_c_i, m->n_factors,
0, o, m->n_features);
/* Compute $E[Z|X] = (\Psi^{-1}B(B^T\Psi^{-1}B+I)^{-1})^TX$
* factors = t(o) * t(X)
*/
cblas_dgemm(CblasColMajor, CblasTrans, CblasTrans,
m->n_factors, m->n_samples, m->n_features, 1,
o, m->n_features,
m->data, m->n_samples,
0, m->factors, m->n_factors);
/* Compute $B^T\Psi^{-1}B(B^T\Psi^{-1}B+I)^{-1}$
* c_o = t(coefficients) * o
*/
c_o = ws->factors_factors_double_a;
cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans,
m->n_factors, m->n_factors, m->n_features, 1,
m->coefficients, m->n_features,
o, m->n_features,
0, c_o, m->n_factors);
/*
* Compute $E[ZZ^T|X] = I - (B^T\Psi^{-1}B(B^T\Psi^{-1}B+I)^{-1})^T + E[Z|X]E[Z|X]^T$
* factor_cov = factors * t(factors) + I - c_o
*/
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,
m->n_factors, m->n_factors, m->n_samples, 1,
m->factors, m->n_factors,
m->factors, m->n_factors,
0, m->factor_cov, m->n_factors);
for (i = 0; i < m->n_factors; i++)
{
for (j = 0; j < m->n_factors; j++)
{
m->factor_cov[j * m->n_factors + i] += (i==j) - c_o[j * m->n_factors + i];
}
}
debug_print("Factor value: %g\n", m->factors[0]);
// Rescale factors
for (i = 0; i < m->n_factors; i++)
{
factor_mean = 0;
for (j = 0; j < m->n_samples; j++)
{
factor_mean += m->factors[i + j*m->n_factors];
}
factor_mean /= m->n_samples;
debug_print(" Factor mean %zd: %g\n", i, factor_mean);
factor_var = 0;
for (j = 0; j < m->n_samples; j++)
{
deviance = m->factors[i + j*m->n_factors] - factor_mean;
factor_var += deviance*deviance;
}
factor_var /= m->n_samples;
debug_print(" Factor variation %zd: %g\n", i, factor_var);
for (j = 0; j < m->n_factors; j++)
{
m->factor_cov[i + j*m->n_factors] /= factor_var;
}
factor_sd = sqrt(factor_var);
for (j = 0; j < m->n_samples; j++)
{
m->factors[i + j * m->n_factors] /= factor_sd;
}
}
return 0;
}
static int
maximize(funcsfa_Factorization *m, double *lambdas, Workspace *ws)
{
const size_t n_lambda = 2;
size_t dt_i, f_i, lambda_i, k;
double *ZXt, *BZZt;
double unpenalized_coeff, l1, l2, dt_var;
size_t n_features, feature_start;
debug_print("%s\n", "Estimating Coefficients");
check_finite(m->factor_cov, m->n_factors*m->n_factors);
check_finite(m->factors, m->n_factors*m->n_samples);
ZXt = ws->features_factors_double_a;
BZZt = ws->features_double;
// Compute E[Z|X]X^T
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
m->n_factors, m->n_features, m->n_samples, 1,
m->factors, m->n_factors,
m->data, m->n_samples,
0, ZXt, m->n_factors);
// Coordinate Descent over factors
for(k = 0; k < m->n_factors; k++)
{
debug_print("\tCoordinate descent for factor: %zd\n", k);
// Compute $BE[ZZ^T|X]_(\cdot k)$
cblas_dgemv(CblasColMajor, CblasNoTrans,
m->n_features, m->n_factors, 1.0,
m->coefficients, m->n_features,
m->factor_cov+(k*m->n_factors), 1,
0.0, BZZt, 1);
lambda_i = 0;
feature_start = 0;
for(dt_i = 0; dt_i < m->n_datatypes; dt_i++)
{
n_features = m->n_features_split[dt_i];
l1 = lambdas[lambda_i];
l2 = lambdas[lambda_i+1];
for(f_i = feature_start; f_i < (feature_start + n_features); f_i++)
{
// Compute: $$
// \hat B_{(ij)} \leftarrow \frac
// {\operatorname{S}(
// \hat B_{(ij)} + E[Z|X]_{(j \cdot)} X_{(i \cdot)}^T -
// \hat B_{(i\cdot)} \operatorname{E}[ZZ^T|X]_{(\cdot j)},
// l_1)}
// {1+l_2}
// $$
unpenalized_coeff = m->coefficients[f_i + (k * m->n_features)] +
((ZXt[k + (f_i * m->n_factors)] - BZZt[f_i])
/ m->n_samples);
m->coefficients[f_i + (k * m->n_features)] =
copysign(fmax(0.0, fabs(unpenalized_coeff) - l1),
unpenalized_coeff) /
(1 + l2);
}
feature_start = feature_start + n_features;
lambda_i = lambda_i + n_lambda;
}
}
debug_print("%s\n", "Estimating Residual Variance");
// Residual variance per data type
feature_start = 0;
for(dt_i = 0; dt_i < m->n_datatypes; dt_i++)
{
dt_var = 0;
n_features = m->n_features_split[dt_i];
for(f_i = feature_start; f_i < (feature_start + n_features); f_i++)
{
for(k = 0; k < m->n_factors; k++)
{
dt_var += (ZXt[k + (f_i * m->n_factors)] *
m->coefficients[f_i + (k * m->n_features)]);
}
}
dt_var = (ws->dt_var[dt_i] - (dt_var / n_features)) / m->n_samples;
for(f_i = feature_start; f_i < (feature_start + n_features); f_i++)
{
if (dt_var > eps_ev) {
m->residual_var[f_i] = dt_var;
} else {
m->residual_var[f_i] = eps_ev;
}
}
debug_print("\tResidual Variance %zd: %g\n", dt_i, dt_var);
feature_start = feature_start + n_features;
}
return 0;
}
static int
init_svd(funcsfa_Factorization *m, Workspace *ws)
{
int info;
size_t i, j;
double *x, *s, *vt, *u;
double scale, f, explained_var, data_var;
size_t total_n_factors;
debug_print("%s\n", "Initializing with SVD");
total_n_factors = min(m->n_features, m->n_samples);
x = malloc(sizeof(double) * m->n_features * m->n_samples);
s = malloc(sizeof(double) * total_n_factors);
vt = malloc(sizeof(double) * total_n_factors * m->n_features);
u = malloc(sizeof(double) * total_n_factors * m->n_samples);
if (x == NULL || s == NULL || vt == NULL)
{
free(x);
free(vt);
free(s);
free(u);
return -1;
}
for (i=0; i < m->n_features * m->n_samples; i++)
{
x[i] = m->data[i];
}
/* vt = svd(X).V.t */
debug_print("%s\n", "\tStarting Lapack SVD");
info = dgesvd('S', 'S',
m->n_samples, m->n_features,
x, m->n_samples,
s, u, m->n_samples,
vt, total_n_factors);
if (info != 0) {
debug_print("Lapack error: %d\n", info);
free(x);
free(vt);
free(u);
free(s);
return -1;
}
debug_print("%s\n", "\tDone Lapack SVD");
scale = 0;
for (i=0; i < m->n_factors; i++)
{
for (j=0; j < m->n_samples; j++)
{
f = u[j + i*m->n_samples] * s[i];
m->factors[i + j*m->n_factors] = f;
scale += f*f;
}
}
scale /= m->n_factors * m->n_samples;
scale = sqrt(scale);
for (i=0; i < m->n_factors; i++)
{
for (j=0; j < m->n_features; j++)
{
m->coefficients[j + i*m->n_features] = vt[i + j*total_n_factors] * scale;
}
}
for (i=0; i < m->n_factors; i++)
{
for (j=0; j < m->n_samples; j++)
{
m->factors[i + j*m->n_factors] /= scale;
}
}
explained_var = 0;
for (i=0; i < m->n_factors; i++)
{
explained_var += s[i]*s[i];
}
explained_var /= m->n_samples * m->n_features;
data_var = 0;
for (i=0; i < m->n_features; i++)
{
data_var += ws->diag_data_square[i];
}
data_var /= m->n_samples * m->n_features;
debug_print("\tData Var: %g\n", data_var);
explained_var = data_var - explained_var;
explained_var = fmax(0, explained_var) + eps_ev;
for (i = 0; i < m->n_features; i++) {
m->residual_var[i] = explained_var;
}
debug_print("\tResidual Variance: %g\n", explained_var);
free(x);
free(vt);
free(u);
free(s);
return 0;
}
double
calc_reconstruction_error(funcsfa_Factorization *m, Workspace *ws)
{
int i, j;
double error, e;
double *prediction;
error = 0.0;
for (i = 0; i < m->n_samples; i++)
{
prediction = ws->features_double;
cblas_dgemv(CblasColMajor, CblasNoTrans,
m->n_features, m->n_factors,
1.0, m->coefficients, m->n_features,
m->factors + (i*m->n_factors), 1,
0.0, prediction, 1);
for (j = 0; j < m->n_features; j++)
{
e = m->data[i + (j * m->n_samples)] - prediction[j];
error += e*e;
}
}
return error;
}
int
funcsfa(funcsfa_Factorization *m, double eps, int max_iter,
char regularizations[], double *lambdas, funcsfa_Monitor *mon)
{
int iter = 0;
int err = 0;
size_t i;
double diff = DBL_MAX;
double diff_f, diff_c;
double rec_error;
int const LEN_PREV_REC_ERROR = 10;
double prev_rec_error[LEN_PREV_REC_ERROR];
int prev_rec_error_i=0;
Workspace *ws;
for (i=0; i<m->n_datatypes; i++)
{
if (regularizations[i] != 'e')
{
debug_print("%s\n", "Only elastic net regularization is supported");
return -4;
}
}
ws = ws_alloc(m);
ws_init(ws, m);
debug_print("%s\n", "Starting Factorization");
err = init_svd(m, ws);
if (err != 0)
{
return(1);
}
rec_error = calc_reconstruction_error(m, ws);
if (mon != NULL)
{
mon->reconstruction_error[0] = rec_error;
mon->max_diff_factors[0] = 0;
mon->max_diff_coefficients[0] = 0;
}
for (i=0; i<LEN_PREV_REC_ERROR; i++) {
prev_rec_error[i] = 0.0;
}
/* EM Loop */
while (iter < max_iter && diff > eps) {
debug_print("Iteration %d\n", iter);
memcpy(ws->prev_factors, m->factors,
sizeof(double)*m->n_factors*m->n_samples);
memcpy(ws->prev_coefficients, m->coefficients,
sizeof(double)*m->n_features*m->n_factors);
err = expectation_factors(m, ws);
if (err != 0)
{
debug_print("Error in computing expectation of factors: %d\n", err);
ws_free(ws);
return(2);
}
err = maximize(m, lambdas, ws);
if (err != 0)
{
debug_print("Error in maximization: %d\n", err);
ws_free(ws);
return(3);
}
diff_f = max_diff(m->factors,
ws->prev_factors, m->n_factors*m->n_samples);
diff_c = max_diff(m->coefficients, ws->prev_coefficients,
m->n_features*m->n_factors);
debug_print("Diff (factor/coefficients): %g; %g\n", diff_f, diff_c);
prev_rec_error[prev_rec_error_i] = rec_error;
prev_rec_error_i += 1;
if (prev_rec_error_i > LEN_PREV_REC_ERROR) {
prev_rec_error_i = 0;
}
rec_error = calc_reconstruction_error(m, ws);
debug_print("Reconstruction Error: %g\n", rec_error);
diff = 0.0;
for (i=0; i<LEN_PREV_REC_ERROR; i++) {
diff += fabs(prev_rec_error[i] - rec_error);
}
diff /= LEN_PREV_REC_ERROR;
debug_print("Diff (Reconstruction Error): %g\n", diff);
if (mon != NULL)
{
mon->reconstruction_error[iter+1] = rec_error;
mon->max_diff_factors[iter+1] = diff_f;
mon->max_diff_coefficients[iter+1] = diff_c;
mon->n_iter = iter;
}
iter = iter + 1;
}
ws_free(ws);
return 0;
}
| {
"alphanum_fraction": 0.5956525875,
"avg_line_length": 26.0843672457,
"ext": "c",
"hexsha": "b71e9da8c2d226c9e7f0e9fe1afc3c9fab547a4a",
"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": "336655531f08aeec0077a443eeb76b92d6677b3a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "NKI-CCB/funcsfa",
"max_forks_repo_path": "funcsfa-c/src/funcsfa.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "336655531f08aeec0077a443eeb76b92d6677b3a",
"max_issues_repo_issues_event_max_datetime": "2018-11-21T15:39:27.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-11-21T09:37:45.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "NKI-CCB/funcsfa",
"max_issues_repo_path": "funcsfa-c/src/funcsfa.c",
"max_line_length": 87,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "336655531f08aeec0077a443eeb76b92d6677b3a",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "NKI-CCB/funcsfa",
"max_stars_repo_path": "funcsfa-c/src/funcsfa.c",
"max_stars_repo_stars_event_max_datetime": "2019-01-28T11:47:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-01-28T11:47:21.000Z",
"num_tokens": 6732,
"size": 21024
} |
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2013.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Stephan Aiche$
// $Authors: Stephan Aiche, Marc Sturm $
// --------------------------------------------------------------------------
#ifndef OPENMS_TRANSFORMATIONS_FEATUREFINDER_TRACEFITTER_H
#define OPENMS_TRANSFORMATIONS_FEATUREFINDER_TRACEFITTER_H
#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/FeatureFinderAlgorithmPickedHelperStructs.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multifit_nlin.h>
#include <gsl/gsl_blas.h>
namespace OpenMS
{
/**
* @brief Abstract fitter for RT profile fitting
*
* This class provides the basic interface and some functionality to fit multiple mass traces to
* a given RT shape model using the Levenberg-Marquardt algorithm.
*
* @todo docu needs update
*
*/
template <class PeakType>
class TraceFitter :
public DefaultParamHandler
{
public:
/// default constructor.
TraceFitter() :
DefaultParamHandler("TraceFitter")
{
defaults_.setValue("max_iteration", 500, "Maximum number of iterations used by the Levenberg-Marquardt algorithm.", ListUtils::create<String>("advanced"));
defaults_.setValue("epsilon_abs", 0.0001, "Absolute error used by the Levenberg-Marquardt algorithm.", ListUtils::create<String>("advanced"));
defaults_.setValue("epsilon_rel", 0.0001, "Relative error used by the Levenberg-Marquardt algorithm.", ListUtils::create<String>("advanced"));
defaults_.setValue("weighted", "false", "Weight mass traces according to their theoretical intensities.", ListUtils::create<String>("advanced"));
defaults_.setValidStrings("weighted", ListUtils::create<String>("true,false"));
defaultsToParam_();
}
/// copy constructor
TraceFitter(const TraceFitter& source) :
DefaultParamHandler(source),
epsilon_abs_(source.epsilon_abs_),
epsilon_rel_(source.epsilon_rel_),
max_iterations_(source.max_iterations_),
weighted_(source.weighted_)
{
updateMembers_();
}
/// assignment operator
virtual TraceFitter& operator=(const TraceFitter& source)
{
DefaultParamHandler::operator=(source);
max_iterations_ = source.max_iterations_;
epsilon_abs_ = source.epsilon_abs_;
epsilon_rel_ = source.epsilon_rel_;
weighted_ = source.weighted_;
updateMembers_();
return *this;
}
/// destructor
virtual ~TraceFitter()
{
}
/**
* Main method of the TraceFitter which triggers the actual fitting.
*/
virtual void fit(FeatureFinderAlgorithmPickedHelperStructs::MassTraces<PeakType>& traces) = 0;
/**
* Returns the lower bound of the fitted RT model
*/
virtual DoubleReal getLowerRTBound() const = 0;
/**
* Returns the upper bound of the fitted RT model
*/
virtual DoubleReal getUpperRTBound() const = 0;
/**
* Returns the height of the fitted model
*/
virtual DoubleReal getHeight() const = 0;
/**
* Returns the center position of the fitted model
*/
virtual DoubleReal getCenter() const = 0;
/**
* Returns the mass trace width at half max (FWHM)
*/
virtual DoubleReal getFWHM() const = 0;
/**
* Evaluate the fitted model at a time point
*/
virtual DoubleReal getValue(DoubleReal rt) const = 0;
/**
* Returns the theoretical value of the fitted model at position k in the passed mass trace
*
* @param trace the mass trace for which the value should be computed
* @param k use the position of the k-th peak to compute the value
*/
DoubleReal computeTheoretical(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace<PeakType>& trace, Size k)
{
double rt = trace.peaks[k].first;
return trace.theoretical_int * getValue(rt);
}
/**
* Checks if the fitted model fills out at least 'min_rt_span' of the RT span
*
* @param rt_bounds RT boundaries of the fitted model
* @param min_rt_span Minimum RT span in relation to extended area that has to remain after model fitting
*/
virtual bool checkMinimalRTSpan(const std::pair<DoubleReal, DoubleReal>& rt_bounds, const DoubleReal min_rt_span) = 0;
/**
* Checks if the fitted model is not to big
*
* @param max_rt_span Maximum RT span in relation to extended area that the model is allowed to have
*/
virtual bool checkMaximalRTSpan(const DoubleReal max_rt_span) = 0;
/**
* Returns the peak area of the fitted model
*/
virtual DoubleReal getArea() = 0;
/**
* Returns a textual representation of the fitted model function, that can be plotted using Gnuplot
*
* @param trace The mass trace that should be plotted
* @param function_name The name of the function (e.g. f(x) -> function_name = f)
* @param baseline The intensity of the baseline
* @param rt_shift A shift value, that allows to plot all RT profiles side by side, even if they would overlap in reality.
* This should be 0 for the first mass trace and increase by a fixed value for each mass trace.
*/
virtual String getGnuplotFormula(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace<PeakType>& trace, const char function_name, const DoubleReal baseline, const DoubleReal rt_shift) = 0;
protected:
/// Structure for passing data to GSL functions
struct ModelData
{
FeatureFinderAlgorithmPickedHelperStructs::MassTraces<PeakType>* traces_ptr;
bool weighted;
};
/**
* Prints the state of the current iteration (e.g., values of the parameters)
*
* @param iter Number of current iteration.
* @param s The solver that also contains all the parameters.
*/
virtual void printState_(SignedSize iter, gsl_multifit_fdfsolver* s) = 0;
virtual void updateMembers_()
{
max_iterations_ = this->param_.getValue("max_iteration");
epsilon_abs_ = this->param_.getValue("epsilon_abs");
epsilon_rel_ = this->param_.getValue("epsilon_rel");
weighted_ = this->param_.getValue("weighted") == "true";
}
/**
* Updates all member variables to the fitted values stored in the solver.
*
* @param s The solver containing the fitted parameter values.
*/
virtual void getOptimizedParameters_(gsl_multifit_fdfsolver* s) = 0;
/**
* Optimize the given parameters using the Levenberg-Marquardt algorithm.
*/
void optimize_(FeatureFinderAlgorithmPickedHelperStructs::MassTraces<PeakType> & traces, const Size num_params, double x_init[],
Int (* residual)(const gsl_vector* x, void* params, gsl_vector* f),
Int (* jacobian)(const gsl_vector* x, void* params, gsl_matrix* J),
Int (* evaluate)(const gsl_vector* x, void* params, gsl_vector* f, gsl_matrix * J))
{
const gsl_multifit_fdfsolver_type* T;
gsl_multifit_fdfsolver* s;
const size_t data_count = traces.getPeakCount();
// gsl always expects N>=p or default gsl error handler invoked,
// cause Jacobian be rectangular M x N with M>=N
if (data_count < num_params) throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__, "UnableToFit-FinalSet", "Skipping feature, gsl always expects N>=p");
gsl_multifit_function_fdf func;
gsl_vector_view x = gsl_vector_view_array(x_init, num_params);
gsl_rng_env_setup();
func.f = (residual);
func.df = (jacobian);
func.fdf = (evaluate);
func.n = data_count;
func.p = num_params;
ModelData params = {&traces, weighted_};
func.params = ¶ms;
T = gsl_multifit_fdfsolver_lmsder;
s = gsl_multifit_fdfsolver_alloc(T, data_count, num_params);
gsl_multifit_fdfsolver_set(s, &func, &x.vector);
SignedSize iter = 0;
Int gsl_status_;
do
{
iter++;
gsl_status_ = gsl_multifit_fdfsolver_iterate(s);
printState_(iter, s);
if (gsl_status_) break;
gsl_status_ = gsl_multifit_test_delta(s->dx, s->x, epsilon_abs_, epsilon_rel_);
}
while (gsl_status_ == GSL_CONTINUE && iter < max_iterations_);
// get the parameters out of the fdfsolver
getOptimizedParameters_(s);
gsl_multifit_fdfsolver_free(s);
}
/** Test for the convergence of the sequence by comparing the last iteration step dx with the absolute error epsabs and relative error epsrel to the current position x */
/// Absolute error
DoubleReal epsilon_abs_;
/// Relative error
DoubleReal epsilon_rel_;
/// Maximum number of iterations
SignedSize max_iterations_;
/// Whether to weight mass traces by theoretical intensity during the optimization
bool weighted_;
};
}
#endif // #ifndef OPENMS_TRANSFORMATIONS_FEATUREFINDER_FEATUREFINDERALGORITHMPICKED_RTFITTING_H
| {
"alphanum_fraction": 0.6748768473,
"avg_line_length": 39.0106761566,
"ext": "h",
"hexsha": "0c337f129259a259f7099fd852c0dfd7e6144a4d",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6",
"max_forks_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_forks_repo_name": "kreinert/OpenMS",
"max_forks_repo_path": "src/openms/include/OpenMS/TRANSFORMATIONS/FEATUREFINDER/TraceFitter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_issues_repo_name": "kreinert/OpenMS",
"max_issues_repo_path": "src/openms/include/OpenMS/TRANSFORMATIONS/FEATUREFINDER/TraceFitter.h",
"max_line_length": 198,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6",
"max_stars_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_stars_repo_name": "kreinert/OpenMS",
"max_stars_repo_path": "src/openms/include/OpenMS/TRANSFORMATIONS/FEATUREFINDER/TraceFitter.h",
"max_stars_repo_stars_event_max_datetime": "2016-12-09T01:45:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-12-09T01:45:03.000Z",
"num_tokens": 2475,
"size": 10962
} |
// Copyright (c) 2021. Pfizer Inc. All rights reserved.
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include "numpy/arrayobject.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_movstat.h>
#include <gsl/gsl_vector.h>
PyObject * moving_median(PyObject *NPY_UNUSED(self), PyObject *args){
PyObject *x_;
long wlen;
if (!PyArg_ParseTuple(args, "Ol:moving_median", &x_, &wlen)) return NULL;
PyArrayObject *data = (PyArrayObject *)PyArray_FromAny(
x_, PyArray_DescrFromType(NPY_DOUBLE), 1, 0,
NPY_ARRAY_ENSUREARRAY | NPY_ARRAY_CARRAY_RO, NULL
);
if (!data) return NULL;
// get the number of dimensions, and the shape
int ndim = PyArray_NDIM(data);
npy_intp *ddims = PyArray_DIMS(data);
// data pointers
double *dptr = (double *)PyArray_DATA(data);
gsl_movstat_workspace *w = gsl_movstat_alloc2(0, (size_t)wlen - 1);
gsl_vector x;
x.size = ddims[ndim-1];
x.stride = 1;
// x.data = dptr; // set this later
x.block = NULL;
x.owner = 0;
// RETURN
PyArrayObject *rmed = (PyArrayObject *)PyArray_EMPTY(ndim, ddims, NPY_DOUBLE, 0);
if (!rmed){
Py_XDECREF(data);
Py_XDECREF(rmed);
gsl_movstat_free(w);
return NULL;
}
double *rptr = (double *)PyArray_DATA(rmed);
gsl_vector xmean;
xmean.size = ddims[ndim-1];
xmean.stride = 1;
// xmean.data = rptr; // set this later
xmean.block = NULL;
xmean.owner = 0;
// for iterating over the data
long stride = ddims[ndim - 1];
int nrepeats = PyArray_SIZE(data) / stride;
for (int i = 0; i < nrepeats; ++i){
x.data = dptr;
xmean.data = rptr;
gsl_movstat_median(GSL_MOVSTAT_END_PADZERO, &x, &xmean, w);
dptr += stride;
rptr += stride;
}
gsl_movstat_free(w);
Py_XDECREF(data);
return (PyObject *)rmed;
}
static struct PyMethodDef methods[] = {
{"moving_median", moving_median, 1, NULL}, // last is the docstring
{NULL, NULL, 0, NULL} /* sentinel */
};
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"moving_median",
NULL,
-1,
methods,
NULL,
NULL,
NULL,
NULL
};
/* Initialization function for the module */
PyMODINIT_FUNC PyInit_moving_median(void)
{
PyObject *m;
m = PyModule_Create(&moduledef);
if (m == NULL) {
return NULL;
}
/* Import the array object */
import_array();
/* XXXX Add constants here */
return m;
}
| {
"alphanum_fraction": 0.60951285,
"avg_line_length": 23.2767857143,
"ext": "c",
"hexsha": "4be4206c98e89dadfbfeea433601c3d9eda5d198",
"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": "f834a82d750d9e3cdd35f4f5692a0a388210b821",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "PfizerRD/scikit-digital-health",
"max_forks_repo_path": "src/skdh/utility/_extensions/moving_median.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f834a82d750d9e3cdd35f4f5692a0a388210b821",
"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": "PfizerRD/scikit-digital-health",
"max_issues_repo_path": "src/skdh/utility/_extensions/moving_median.c",
"max_line_length": 85,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "f834a82d750d9e3cdd35f4f5692a0a388210b821",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "PfizerRD/scikit-digital-health",
"max_stars_repo_path": "src/skdh/utility/_extensions/moving_median.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T20:56:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-31T20:56:49.000Z",
"num_tokens": 749,
"size": 2607
} |
#ifndef LIC_TYPE_DEFINITION
#define LIC_TYPE_DEFINITION
#include <gsl/gsl>
#include "Metadata.h"
namespace lic
{
class MethodDefinition;
class TypeDefinition : Metadata
{
public:
TypeDefinition(Assembly& assembly, MetadataTable table, size_t rid, gsl::byte* row);
~TypeDefinition();
const char* Name() const;
const char* Namespace() const;
const gsl::span<MethodDefinition> Methods();
private:
size_t FirstMethodRid();
};
}
#endif // !LIC_TYPE_DEFINITION
| {
"alphanum_fraction": 0.7233606557,
"avg_line_length": 16.2666666667,
"ext": "h",
"hexsha": "a80d199beac4d5f9b586e435767870b4df451078",
"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": "5ad4a7014673bb60b748390856e0c7cb11eaca09",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "roberthusak/lic",
"max_forks_repo_path": "src/loader/TypeDefinition.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09",
"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": "roberthusak/lic",
"max_issues_repo_path": "src/loader/TypeDefinition.h",
"max_line_length": 88,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5ad4a7014673bb60b748390856e0c7cb11eaca09",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "roberthusak/lic",
"max_stars_repo_path": "src/loader/TypeDefinition.h",
"max_stars_repo_stars_event_max_datetime": "2017-05-18T11:44:16.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-18T11:44:16.000Z",
"num_tokens": 113,
"size": 488
} |
/**
* \file ModellerFilter.h
*/
#ifndef ATK_MODELLING_MODELLERFILTER_H
#define ATK_MODELLING_MODELLERFILTER_H
#include <ATK/Modelling/config.h>
#include <ATK/Modelling/Types.h>
#include <ATK/Core/TypedBaseFilter.h>
#include <gsl/gsl>
#include <Eigen/Eigen>
#include <tuple>
#include <unordered_set>
#include <vector>
namespace ATK
{
/// The common class for ModellerFilter
template<typename DataType_>
class ATK_MODELLING_EXPORT ModellerFilter: public TypedBaseFilter<DataType_>
{
public:
using Parent = TypedBaseFilter<DataType_>;
using DataType = DataType_;
public:
/**
* The main ModellerFilter constructor
* @param nb_dynamic_pins is the number of dymanic pins (that have a voltage that may vary with time)
* @param nb_input_pins is the number of input pins (that will have varying voltage with time)
*/
ModellerFilter(gsl::index nb_dynamic_pins, gsl::index nb_input_pins);
virtual Eigen::Matrix<DataType, Eigen::Dynamic, 1> get_static_state() const = 0;
/// Returns the number of dynamic pins
virtual gsl::index get_nb_dynamic_pins() const = 0;
/// Returns the number of static pins
virtual gsl::index get_nb_static_pins() const = 0;
/// Returns the number of input pins
virtual gsl::index get_nb_input_pins() const = 0;
/// Returns the number of components
virtual gsl::index get_nb_components() const = 0;
/// Returns the name of a dynamic pin, usefull to set output
virtual std::string get_dynamic_pin_name(gsl::index identifier) const = 0;
/// Returns the name of a input pin, usefull to set input
virtual std::string
get_input_pin_name(gsl::index identifier) const = 0;
/// Returns the name of a static pin, usefull to set static
virtual std::string get_static_pin_name(gsl::index identifier) const = 0;
gsl::index find_dynamic_pin(const std::string& name);
gsl::index find_input_pin(const std::string& name);
gsl::index find_static_pin(const std::string& name);
/// Get number of parameters
virtual gsl::index get_number_parameters() const = 0;
/// Get the name of a parameter
virtual std::string get_parameter_name(gsl::index identifier) const = 0;
/// Get the value of a parameter
virtual DataType_ get_parameter(gsl::index identifier) const = 0;
/// Set the value of a parameter
virtual void set_parameter(gsl::index identifier, DataType_ value) = 0;
};
}
#endif
| {
"alphanum_fraction": 0.7101332257,
"avg_line_length": 30.2073170732,
"ext": "h",
"hexsha": "3af324e70ae4155d01967028f4f491eea351e13b",
"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": "fc22c908dc68f5a831d5f3e26e7ac4c943d0f1ff",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "AudioTK/ATK-Modelling-free",
"max_forks_repo_path": "ATK/Modelling/ModellerFilter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fc22c908dc68f5a831d5f3e26e7ac4c943d0f1ff",
"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": "AudioTK/ATK-Modelling-free",
"max_issues_repo_path": "ATK/Modelling/ModellerFilter.h",
"max_line_length": 105,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "fc22c908dc68f5a831d5f3e26e7ac4c943d0f1ff",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "AudioTK/ATK-Modelling-free",
"max_stars_repo_path": "ATK/Modelling/ModellerFilter.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-16T11:55:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-07T12:47:03.000Z",
"num_tokens": 615,
"size": 2477
} |
#include <gsl/gsl_errno.h>
#include <math.h>
#include "acceleration.h"
int func(double t, const double y[], double f[], void *params) {
/*
y[0], y[1], y[2] are x, y, z
y[3], y[4], y[5] are v_x, v_y, v_z
*/
(void)(t); /* avoid unused parameter warning */
struct HernquistParams pars = *(struct HernquistParams *)params;
double r;
double dPhi_dr;
r = sqrt(y[0]*y[0] + y[1]*y[1] + y[2]*y[2]);
dPhi_dr = pars.G * pars.m / pow(r + pars.c, 2);
// Derivative of position is just velocity
f[0] = y[3];
f[1] = y[4];
f[2] = y[5];
// Derivative of velocity is acceleration from potential
f[3] = -dPhi_dr * y[0] / r;
f[4] = -dPhi_dr * y[1] / r;
f[5] = -dPhi_dr * y[2] / r;
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.5413436693,
"avg_line_length": 24.1875,
"ext": "c",
"hexsha": "65aca17613c0ba93a615b95341875149112cd41c",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2021-09-03T14:37:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-10T09:26:47.000Z",
"max_forks_repo_head_hexsha": "b5c2f098206190de2180751591923bd94f97072c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "achapkowski/cython-tutorial",
"max_forks_repo_path": "4-package-advanced/gsl_integrate/src/acceleration.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b5c2f098206190de2180751591923bd94f97072c",
"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": "achapkowski/cython-tutorial",
"max_issues_repo_path": "4-package-advanced/gsl_integrate/src/acceleration.c",
"max_line_length": 68,
"max_stars_count": 58,
"max_stars_repo_head_hexsha": "b5c2f098206190de2180751591923bd94f97072c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "HaifengWangNAOC/Somethingnew",
"max_stars_repo_path": "4-package-advanced/gsl_integrate/src/acceleration.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-08T14:26:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-11-07T21:48:12.000Z",
"num_tokens": 282,
"size": 774
} |
/* specfunc/test_sf.c
*
* Copyright (C) 2007 Brian Gough
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2004 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_sf.h>
#include "test_sf.h"
double
test_sf_frac_diff(double x1, double x2)
{
if(x1 == 0.0 && x2 == 0.0) {
return 0.0;
}
else if (x1 == 0.0) {
return fabs(x2);
} else if(x1 <= DBL_MAX && x2 <= DBL_MAX && (x1 + x2 != 0.0)) {
return fabs((x1-x2)/(x1+x2));
}
else {
return 1.0;
}
}
/* Check a result against a given value and tolerance.
*/
int
test_sf_check_result(char * message_buff, gsl_sf_result r, double val, double tol)
{
int s = 0;
double f = 0, d = 0;
if (gsl_isnan(r.val) || gsl_isnan(val))
{
s = (gsl_isnan(r.val) != gsl_isnan(val)) ? TEST_SF_INCONS : s;
}
else if (gsl_isinf(r.val) || gsl_isinf(val))
{
s = (gsl_isinf(r.val) != gsl_isinf(val)) ? TEST_SF_INCONS : s;
}
else
{
f = test_sf_frac_diff(val, r.val);
d = fabs(val - r.val);
if(d > 2.0 * TEST_SIGMA * r.err) s |= TEST_SF_INCONS;
if(r.err < 0.0) s |= TEST_SF_ERRNEG;
if(gsl_isinf(r.err)) s |= TEST_SF_ERRBAD;
#if TEST_EXCESSIVE_ERROR
if(d > 0 && r.err > 1e4 * fabs(val)*tol) s |= TEST_SF_ERRBIG;
#endif
if(f > TEST_FACTOR * tol) s |= TEST_SF_TOLBAD;
}
if(s != 0) {
char buff[2048];
sprintf(buff, " expected: %20.16e\n", val);
strcat(message_buff, buff);
sprintf(buff, " obtained: %20.16e +/- %.16e (rel=%g)\n", r.val, r.err, r.err/(fabs(r.val) + r.err));
strcat(message_buff, buff);
sprintf(buff, " fracdiff: %20.16e\n", f);
strcat(message_buff, buff);
sprintf(buff, " tolerance: %20.16e\n", tol);
strcat(message_buff, buff);
}
if(s & TEST_SF_INCONS) {
strcat(message_buff, " value/expected not consistent within reported error\n");
}
if(s & TEST_SF_ERRNEG) {
strcat(message_buff, " reported error negative\n");
}
if(s & TEST_SF_ERRBAD) {
strcat(message_buff, " reported error is bad\n");
}
if(s & TEST_SF_ERRBIG) {
strcat(message_buff, " reported error is much too big\n");
}
if(s & TEST_SF_TOLBAD) {
strcat(message_buff, " value not within tolerance of expected value\n");
}
return s;
}
/* Check a result against a given value and tolerance.
*/
int
test_sf_check_e10(char * message_buff, int e10, int e10_in)
{
int s = 0;
if (e10 != e10_in)
{
s = TEST_SF_EXPBAD;
}
if(s != 0) {
char buff[2048];
sprintf(buff, " expected exponent: 10^%d\n", e10_in);
strcat(message_buff, buff);
sprintf(buff, " obtained exponent: 10^%d", e10);
strcat(message_buff, buff);
}
if(s & TEST_SF_EXPBAD) {
strcat(message_buff, " exponent is incorrect\n");
}
return s;
}
int
test_sf_check_val(char * message_buff, double rval, double val, double tol)
{
int s = 0;
double f = test_sf_frac_diff(val, rval);
if(f > TEST_FACTOR * tol) s |= TEST_SF_TOLBAD;
if(s != 0) {
char buff[2048];
sprintf(buff, " expected: %20.16e\n", val);
strcat(message_buff, buff);
sprintf(buff, " obtained: %20.16e\n", rval);
strcat(message_buff, buff);
sprintf(buff, " fracdiff: %20.16e\n", f);
strcat(message_buff, buff);
}
if(s & TEST_SF_TOLBAD) {
strcat(message_buff, " value not within tolerance of expected value\n");
}
return s;
}
/* Relax the condition on the agreement and on the usefulness
* of the error estimate.
*/
int
test_sf_check_result_relax(char * message_buff, gsl_sf_result r, double val, double tol)
{
int s = 0;
double f = test_sf_frac_diff(val, r.val);
if(f > GSL_MAX_DBL(TEST_SNGL, TEST_FACTOR * tol)) s |= TEST_SF_INCONS;
if(r.err < 0.0) s |= TEST_SF_ERRNEG;
if(gsl_isinf(r.err)) s |= TEST_SF_ERRBAD;
if(f > TEST_FACTOR * tol) s |= TEST_SF_TOLBAD;
if(s != 0) {
char buff[2048];
sprintf(buff, " expected: %20.16e\n", val);
strcat(message_buff, buff);
sprintf(buff, " obtained: %20.16e +/- %.16e (rel=%g)\n", r.val, r.err, r.err/(fabs(r.val) + r.err));
strcat(message_buff, buff);
sprintf(buff, " fracdiff: %20.16e\n", f);
strcat(message_buff, buff);
}
if(s & TEST_SF_INCONS) {
strcat(message_buff, " value/expected not consistent MAX(tol,SINGLE_PREC)\n");
}
if(s & TEST_SF_ERRNEG) {
strcat(message_buff, " reported error negative\n");
}
if(s & TEST_SF_ERRBAD) {
strcat(message_buff, " reported error is bad\n");
}
if(s & TEST_SF_TOLBAD) {
strcat(message_buff, " value not within tolerance of expected value\n");
}
return s;
}
/* Check a return value.
*/
int
test_sf_check_return(char * message_buff, int val_return, int expected_return)
{
if(val_return != expected_return) {
char buff[256];
sprintf(buff, " unexpected return code: %d\n", val_return);
strcat(message_buff, buff);
return TEST_SF_RETBAD;
}
else {
return 0;
}
}
int
test_sf (gsl_sf_result r, double val_in, double tol, int status,
int expect_return, const char * desc)
{
char message_buff[4096];
int local_s = 0;
message_buff[0] = '\0';
local_s |= test_sf_check_result(message_buff, r, val_in, tol);
local_s |= test_sf_check_return(message_buff, status, expect_return);
gsl_test(local_s, desc);
if(local_s != 0) {
/* printf(" %s %d\n", __FILE__, __LINE__); */
printf("%s", message_buff);
printf(" %22.18e %22.18e\n", r.val, r.err);
}
return local_s;
}
int
test_sf_e10 (gsl_sf_result_e10 re, double val_in, int e10_in, double tol, int status,
int expect_return, const char * desc)
{
char message_buff[4096];
int local_s = 0;
gsl_sf_result r;
r.val = re.val; r.err = re.err;
message_buff[0] = '\0';
local_s |= test_sf_check_result(message_buff, r, val_in, tol);
local_s |= test_sf_check_e10(message_buff, re.e10, e10_in);
local_s |= test_sf_check_return(message_buff, status, expect_return);
gsl_test(local_s, desc);
if(local_s != 0) {
/* printf(" %s %d\n", __FILE__, __LINE__); */
printf("%s", message_buff);
printf(" %22.18e %22.18e 10^%d\n", re.val, re.err, re.e10);
}
return local_s;
}
int
test_sf_val (double val, double val_in, double tol, const char * desc)
{
char message_buff[4096];
int local_s = 0;
message_buff[0] = '\0';
local_s |= test_sf_check_val(message_buff, val, val_in, tol);
gsl_test(local_s, desc);
if(local_s != 0) {
/* printf(" %s %d\n", __FILE__, __LINE__); */
printf("%s", message_buff);
printf(" %22.18e\n", val);
}
return local_s;
}
int
test_sf_rlx (gsl_sf_result r, double val_in, double tol, int status,
int expect_return, const char * desc)
{
char message_buff[4096];
int local_s = 0;
message_buff[0] = '\0';
local_s |= test_sf_check_result_relax(message_buff, r, val_in, tol);
local_s |= test_sf_check_return(message_buff, status, expect_return);
gsl_test(local_s, desc);
if(local_s != 0) {
/* printf(" %s %d\n", __FILE__, __LINE__); */
printf("%s", message_buff);
printf(" %22.18e %22.18e\n", r.val, r.err);
}
return local_s;
}
int
test_sf_2 (gsl_sf_result r1, double val1, double tol1,
gsl_sf_result r2, double val2, double tol2,
int status, int expect_return, const char * desc)
{
char message_buff[4096];
int local_s = 0;
message_buff[0] = '\0';
local_s |= test_sf_check_result(message_buff, r1, val1, tol1);
local_s |= test_sf_check_result(message_buff, r2, val2, tol2);
local_s |= test_sf_check_return(message_buff, status, expect_return);
gsl_test(local_s, desc);
if(local_s != 0) {
/* printf(" %s %d\n", __FILE__, __LINE__); */
printf("%s", message_buff);
printf(" %22.18e %22.18e\n", r1.val, r1.err);
printf(" %22.18e %22.18e\n", r2.val, r2.err);
}
return local_s;
}
int
test_sf_sgn (gsl_sf_result r, double sgn, double val_in, double tol, double expect_sgn, int status,
int expect_return, const char * desc)
{
char message_buff[4096];
gsl_sf_result local_r;
int local_s = 0;
message_buff[0] = '\0';
local_r.val = sgn;
local_r.err = 0.0;
local_s |= test_sf_check_result(message_buff, r, val_in, tol);
local_s |= test_sf_check_result(message_buff, local_r, expect_sgn, 0.0);
local_s |= test_sf_check_return(message_buff, status, expect_return);
gsl_test(local_s, desc);
if(local_s != 0) {
/* printf(" %s %d\n", __FILE__, __LINE__); */
printf("%s", message_buff);
printf(" %22.18e %22.18e\n", r.val, r.err);
}
return local_s;
}
int test_clausen(void)
{
gsl_sf_result r;
int s = 0;
TEST_SF(s, gsl_sf_clausen_e, (M_PI/20.0, &r), 0.4478882448133546, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_clausen_e, (M_PI/6.0, &r), 0.8643791310538927, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_clausen_e, (M_PI/3.0, &r), 1.0149416064096535, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_clausen_e, ( 2.0*M_PI + M_PI/3.0, &r), 1.0149416064096535, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_clausen_e, (100.0*M_PI + M_PI/3.0, &r), 1.0149416064096535, TEST_TOL0, GSL_SUCCESS);
return s;
}
int test_coupling(void)
{
gsl_sf_result r;
int s = 0;
/* Test 3j */
TEST_SF(s, gsl_sf_coupling_3j_e, (0, 1, 1, 0, 1, -1, &r), sqrt(1.0/2.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_3j_e, (1, 1, 2, 1, -1, 0, &r), sqrt(1.0/6.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_3j_e, (2, 4, 6, 0, 2, -2, &r), sqrt(8.0/105.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_3j_e, (4, 4, 8, 0, 0, 0, &r), sqrt(2.0/35.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_3j_e, (4, 4, 8, 2, -2, 0, &r), 2.0/3.0*sqrt(2.0/35.0), TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_3j_e, (4, 4, 8, 4, -4, 0, &r), 1.0/(3.0*sqrt(70.0)), TEST_TOL2, GSL_SUCCESS);
/* Test 3j error checking */
TEST_SF(s, gsl_sf_coupling_3j_e, (-1, 1, 2, 1, -1, 0, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_3j_e, (1, -1, 2, 1, -1, 0, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_3j_e, (1, 1, -2, 1, -1, 0, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
/* Test |m_i|<=j_i */
TEST_SF(s, gsl_sf_coupling_3j_e, (1, 1, 2, 2, -1, 0, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_3j_e, (1, 1, 2, 1, -2, 0, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_3j_e, (1, 1, 2, 1, -1, 3, &r), 0, 0, GSL_SUCCESS);
/* Test triangle condition j1 + j2 >= j, j >= j2 - j1, j>= j1 - j2 */
TEST_SF(s, gsl_sf_coupling_3j_e, (1, 1, 3, 1, -1, 0, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_3j_e, (1, 4, 2, 1, -1, 0, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_3j_e, (4, 1, 2, 1, -1, 0, &r), 0, 0, GSL_SUCCESS);
/* Test m1=m2=m3=0 with j1+j2+j3=odd*/
TEST_SF(s, gsl_sf_coupling_3j_e, (2*13, 2*13, 2*13, 0, 0, 0, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_3j_e, (2*2, 2*17, 2*18, 0, 0, 0, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_3j_e, (2*203, 2*203, 2*203, 0, 0, 0, &r), 0, 0, GSL_SUCCESS);
/* Test l1=249 l2=248, l3=2, m1=5, m2=-6, m3=1 */
TEST_SF(s, gsl_sf_coupling_3j_e, (2*249.0, 2*248.0, 2*2.0, 2*5.0, 2*(-6.0), 2*1.0, &r), 0.0228787564223517967033998, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_3j_e, (2*248.0, 2*247.0, 2*2.0, 2*5.0, 2*(-6.0), 2*1.0, &r), -0.022926660587726369939271424097, TEST_TOL3, GSL_SUCCESS);
/* Test 6j */
TEST_SF(s, gsl_sf_coupling_6j_e, (2, 2, 4, 2, 2, 2, &r), 1.0/6.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (4, 4, 2, 4, 4, 4, &r), -1.0/10.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (4, 4, 2, 4, 4, 2, &r), 1.0/6.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (4, 4, 2, 2, 2, 2, &r), -0.5/sqrt(5.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (4, 4, 4, 2, 2, 2, &r), sqrt(7.0/3.0)/10.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (6, 6, 6, 4, 4, 4, &r), -sqrt(3.0/5.0)/14.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (6, 6, 6, 4, 4, 2, &r), -sqrt(3.0/5.0)/7.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (1, 0, 1, 0, 1, 0, &r), -sqrt(1.0/2.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (1, 0, 1, 1, 0, 1, &r), -1.0/2.0, TEST_TOL0, GSL_SUCCESS);
/* Test 6j error checking */
TEST_SF(s, gsl_sf_coupling_6j_e, (-2, 2, 4, 2, 2, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_6j_e, (2, -2, 4, 2, 2, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_6j_e, (2, 2, -4, 2, 2, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_6j_e, (2, 2, 4, -2, 2, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_6j_e, (2, 2, 4, 2, -2, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_6j_e, (2, 2, 4, 2, 2, -2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
/* Test 6j triangle conditions */
TEST_SF(s, gsl_sf_coupling_6j_e, (2, 2, 4, 2, 2, 7, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (2, 2, 4, 2, 7, 2, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (2, 2, 4, 7, 2, 2, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (2, 2, 7, 2, 2, 2, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (2, 7, 4, 2, 2, 2, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (7, 2, 4, 2, 2, 2, &r), 0, 0, GSL_SUCCESS);
/* Test 6j half-integer/integer coupling conditions */
TEST_SF(s, gsl_sf_coupling_6j_e, (0, 2, 2, 44, 43, 43, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (1, 1, 1, 0, 1, 1, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (1, 1, 1, 1, 0, 1, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_6j_e, (1, 1, 1, 1, 1, 0, &r), 0, 0, GSL_SUCCESS);
/* Test 9j */
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, 3, 3, 2, 1, 1, 2, &r), -sqrt(1.0/6.0)/10.0, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_9j_e, (8, 4, 10, 7, 3, 8, 1, 1, 2, &r), sqrt(7.0/3.0)/60.0, TEST_TOL2, GSL_SUCCESS);
/* Test 9j error checking */
TEST_SF(s, gsl_sf_coupling_9j_e, (-4, 2, 4, 3, 3, 2, 1, 1, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, -2, 4, 3, 3, 2, 1, 1, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, -4, 3, 3, 2, 1, 1, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, -3, 3, 2, 1, 1, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, 3, -3, 2, 1, 1, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, 3, 3, -2, 1, 1, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, 3, 3, 2, -1, 1, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, 3, 3, 2, 1, -1, 2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, 3, 3, 2, 1, 1, -2, &r), GSL_NAN, GSL_NAN, GSL_EDOM);
TEST_SF(s, gsl_sf_coupling_9j_e, (10, 2, 4, 3, 3, 2, 1, 1, 2, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 10, 4, 3, 3, 2, 1, 1, 2, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 10, 3, 3, 2, 1, 1, 2, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, 10, 3, 2, 1, 1, 2, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, 3, 10, 2, 1, 1, 2, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, 3, 3, 10, 1, 1, 2, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, 3, 3, 2, 10, 1, 2, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, 3, 3, 2, 1, 10, 2, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_9j_e, (4, 2, 4, 3, 3, 2, 1, 1, 10, &r), 0, 0, GSL_SUCCESS);
/* Test 9j half-integer/integer coupling conditions */
TEST_SF(s, gsl_sf_coupling_9j_e, (1, 1, 1, 1, 1, 1, 0, 0, 0, &r), 0, 0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_coupling_9j_e, (1, 1, 0, 1, 1, 0, 1, 1, 0, &r), 0, 0, GSL_SUCCESS);
return s;
}
int test_dawson(void)
{
gsl_sf_result r;
int s = 0;
TEST_SF(s, gsl_sf_dawson_e, (1.0e-15, &r), 1.0e-15, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_dawson_e, (0.5, &r), 0.4244363835020222959, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_dawson_e, (2.0, &r), 0.30134038892379196603, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_dawson_e, (1000.0, &r), 0.0005000002500003750009, TEST_TOL0, GSL_SUCCESS);
return s;
}
int test_debye(void)
{
gsl_sf_result r;
int s = 0;
TEST_SF(s, gsl_sf_debye_1_e, (0.1, &r), 0.975277750004723276, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_1_e, (1.0, &r), 0.777504634112248239, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_1_e, (10.0, &r), 0.164443465679946027, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_2_e, (0.1, &r), 0.967083287045302664, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_2_e, (1.0, &r), 0.70787847562782924, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_2_e, (10.0, &r), 0.0479714980201218708, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_3_e, (0.1, &r), 0.962999940487211048, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_3_e, (1.0, &r), 0.674415564077814667, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_3_e, (10.0, &r), 0.0192957656903454886, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_4_e, (0.1, &r), 0.960555486124335944, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_4_e, (1.0, &r), 0.654874068886737049, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_4_e, (10.0, &r), 0.00967367556027115896, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_5_e, (0.1, &r), 0.95892849428310568745, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_5_e, (1.0, &r), 0.6421002580217790246, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_5_e, (10.0, &r), 0.005701535852992908538, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_6_e, (0.1, &r), 0.95776777382605465878, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_6_e, (1.0, &r), 0.63311142583495107588, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_debye_6_e, (10.0, &r), 3.7938493294615955279e-3, TEST_TOL0, GSL_SUCCESS);
return s;
}
int test_elementary(void)
{
gsl_sf_result r;
double x = 0.2*DBL_MAX;
int s = 0;
TEST_SF(s, gsl_sf_multiply_e, (-3.0,2.0, &r), -6.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_multiply_e, (x, 1.0/x, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_multiply_e, (x, 0.2, &r), 0.04*DBL_MAX, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_multiply_e, (x, 4.0, &r), 0.8*DBL_MAX, TEST_TOL1, GSL_SUCCESS);
s += ( gsl_sf_multiply_e(DBL_MAX, 1.1, &r) != GSL_EOVRFLW);
s += ( gsl_sf_multiply_e(DBL_MIN, DBL_MIN, &r) != GSL_EUNDRFLW);
s += ( gsl_sf_multiply_e(DBL_MIN, -DBL_MIN, &r) != GSL_EUNDRFLW);
return s;
}
int test_ellint(void)
{
gsl_sf_result r;
gsl_mode_t mode = GSL_MODE_DEFAULT;
int s = 0;
TEST_SF(s, gsl_sf_ellint_Kcomp_e, ( 0.99, mode, &r), 3.3566005233611923760, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_Kcomp_e, ( 0.50, mode, &r), 1.6857503548125960429, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_Kcomp_e, (0.010, mode, &r), 1.5708355989121522360, TEST_TOL0, GSL_SUCCESS);
/* Bug report from Thies Heidecke */
TEST_SF(s, gsl_sf_ellint_Kcomp_e, ( 0.99999999906867742538, mode, &r), 11.4369284843320018031, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_Ecomp_e, (0.99, mode, &r), 1.0284758090288040010, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_Ecomp_e, (0.50, mode, &r), 1.4674622093394271555, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_Ecomp_e, (0.01, mode, &r), 1.5707570561503852873, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_Pcomp_e, (0.99, 0.1, mode, &r), 3.13792612351836506315593, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_Pcomp_e, (0.50, 0.1, mode, &r), 1.60455249360848890075108, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_Pcomp_e, (0.01, 0.1, mode, &r), 1.49773208536003801277453, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_Dcomp_e, (0.99, mode, &r), 2.375395076351788975665323192, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_Dcomp_e, (0.50, mode, &r), 0.8731525818926755496456335628, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_Dcomp_e, (0.01, mode, &r), 0.7854276176694868932799393751, TEST_TOL0, GSL_SUCCESS);
/* Bug report from Will M. Farr bug #31362 */
/* FIXME: we are accepting MAXITER as the return code, but really
this should be changed to EINVAL in the routine itself */
TEST_SF(s, gsl_sf_ellint_Kcomp_e, (GSL_NAN, mode, &r), GSL_NAN, GSL_NAN, GSL_EMAXITER);
TEST_SF(s, gsl_sf_ellint_Ecomp_e, (GSL_NAN, mode, &r), GSL_NAN, GSL_NAN, GSL_EMAXITER);
TEST_SF(s, gsl_sf_ellint_F_e, (M_PI/3.0, 0.99, mode, &r), 1.3065333392738766762, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (M_PI/3.0, 0.50, mode, &r), 1.0895506700518854093, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (M_PI/3.0, 0.01, mode, &r), 1.0472129063770918952, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (M_PI/3.0, 0.99, mode, &r), 0.8704819220377943536, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (M_PI/3.0, 0.50, mode, &r), 1.0075555551444720293, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (M_PI/3.0, 0.01, mode, &r), 1.0471821963889481104, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (M_PI/3.0, 0.99, 0.5, mode, &r), 1.1288726598764099882, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (M_PI/3.0, 0.50, 0.5, mode, &r), 0.9570574331323584890, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (M_PI/3.0, 0.01, 0.5, mode, &r), 0.9228868127118118465, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_RF_e, (5.0e-11, 1.0e-10, 1.0, mode, &r), 12.36441982979439, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_RF_e, (1.0, 2.0, 3.0, mode, &r), 0.7269459354689082, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_RD_e, (5.0e-11, 1.0e-10, 1.0, mode, &r), 34.0932594919337362, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_RD_e, (1.0, 2.0, 3.0, mode, &r), 0.2904602810289906, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_RC_e, (1.0, 2.0, mode, &r), 0.7853981633974482, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_RJ_e, (2.0, 3.0, 4.0, 5.0, mode, &r), 0.1429757966715675, TEST_TOL0, GSL_SUCCESS);
/* E, argument phi > pi/2 */
TEST_SF(s, gsl_sf_ellint_E_e, (M_PI/2.0, 0.99, mode, &r), 1.02847580902880400098389, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (M_PI/2.0, 0.50, mode, &r), 1.46746220933942715545980, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (M_PI/2.0, 0.01, mode, &r), 1.57075705615038528733708, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (2*M_PI/3.0, 0.99, mode, &r), 1.18646969601981364833972, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (2*M_PI/3.0, 0.50, mode, &r), 1.92736886353438228163734, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (2*M_PI/3.0, 0.01, mode, &r), 2.09433191591182246425715, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (M_PI, 0.99, mode, &r), 2.05695161805760800196777, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (M_PI, 0.50, mode, &r), 2.93492441867885431091959, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (M_PI, 0.01, mode, &r), 3.14151411230077057467416, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (4*M_PI/3, 0.99, mode, &r), 2.92743354009540235559582, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (4*M_PI/3, 0.50, mode, &r), 3.94247997382332634020184, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (4*M_PI/3, 0.01, mode, &r), 4.18869630868971868509117, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (3*M_PI/2.0, 0.99, mode, &r), 3.08542742708641200295166, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (3*M_PI/2.0, 0.50, mode, &r), 4.40238662801828146637939, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (3*M_PI/2.0, 0.01, mode, &r), 4.71227116845115586201123, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (5*M_PI/3, 0.99, mode, &r), 3.24342131407742165030750, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (5*M_PI/3, 0.50, mode, &r), 4.86229328221323659255693, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (5*M_PI/3, 0.01, mode, &r), 5.23584602821259303893130, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (2*M_PI, 0.99, mode, &r), 4.11390323611521600393555, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (2*M_PI, 0.50, mode, &r), 5.86984883735770862183918, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (2*M_PI, 0.01, mode, &r), 6.28302822460154114934831, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (7*M_PI/3.0, 0.99, mode, &r), 4.98438515815301035756360, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (7*M_PI/3.0, 0.50, mode, &r), 6.87740439250218065112143, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (7*M_PI/3.0, 0.01, mode, &r), 7.33021042099048925976532, TEST_TOL0, GSL_SUCCESS);
/* Test some negative arguments, phi < 0 */
TEST_SF(s, gsl_sf_ellint_E_e, (-M_PI/2.0, 0.99, mode, &r), -1.02847580902880400098389, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-M_PI/2.0, 0.50, mode, &r), -1.46746220933942715545980, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-M_PI/2.0, 0.01, mode, &r), -1.57075705615038528733708, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-2*M_PI/3.0, 0.99, mode, &r), -1.18646969601981364833972, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-2*M_PI/3.0, 0.50, mode, &r), -1.92736886353438228163734, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-2*M_PI/3.0, 0.01, mode, &r), -2.09433191591182246425715, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-M_PI, 0.99, mode, &r), -2.05695161805760800196777, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-M_PI, 0.50, mode, &r), -2.93492441867885431091959, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-M_PI, 0.01, mode, &r), -3.14151411230077057467416, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-4*M_PI/3, 0.99, mode, &r), -2.92743354009540235559582, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-4*M_PI/3, 0.50, mode, &r), -3.94247997382332634020184, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-4*M_PI/3, 0.01, mode, &r), -4.18869630868971868509117, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-3*M_PI/2.0, 0.99, mode, &r), -3.08542742708641200295166, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-3*M_PI/2.0, 0.50, mode, &r), -4.40238662801828146637939, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-3*M_PI/2.0, 0.01, mode, &r), -4.71227116845115586201123, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-5*M_PI/3, 0.99, mode, &r), -3.24342131407742165030750, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-5*M_PI/3, 0.50, mode, &r), -4.86229328221323659255693, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-5*M_PI/3, 0.01, mode, &r), -5.23584602821259303893130, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-2*M_PI, 0.99, mode, &r), -4.11390323611521600393555, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-2*M_PI, 0.50, mode, &r), -5.86984883735770862183918, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-2*M_PI, 0.01, mode, &r), -6.28302822460154114934831, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-7*M_PI/3.0, 0.99, mode, &r), -4.98438515815301035756360, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-7*M_PI/3.0, 0.50, mode, &r), -6.87740439250218065112143, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_E_e, (-7*M_PI/3.0, 0.01, mode, &r), -7.33021042099048925976532, TEST_TOL0, GSL_SUCCESS);
/* F, argument phi > pi/2 */
TEST_SF(s, gsl_sf_ellint_F_e, (M_PI/2.0, 0.99, mode, &r), 3.35660052336119237603347, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (M_PI/2.0, 0.50, mode, &r), 1.68575035481259604287120, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (M_PI/2.0, 0.01, mode, &r), 1.57083559891215223602641, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (2*M_PI/3.0, 0.99, mode, &r), 5.40666770744850807588478, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (2*M_PI/3.0, 0.50, mode, &r), 2.28195003957330667648585, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (2*M_PI/3.0, 0.01, mode, &r), 2.09445829144721257687207, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (M_PI, 0.99, mode, &r), 6.71320104672238475206694, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (M_PI, 0.50, mode, &r), 3.37150070962519208574241, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (M_PI, 0.01, mode, &r), 3.14167119782430447205281, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (4*M_PI/3, 0.99, mode, &r), 8.01973438599626142824910, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (4*M_PI/3, 0.50, mode, &r), 4.46105137967707749499897, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (4*M_PI/3, 0.01, mode, &r), 4.18888410420139636723356, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (3*M_PI/2.0, 0.99, mode, &r), 10.0698015700835771281004, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (3*M_PI/2.0, 0.50, mode, &r), 5.05725106443778812861361, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (3*M_PI/2.0, 0.01, mode, &r), 4.71250679673645670807922, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (5*M_PI/3, 0.99, mode, &r), 12.1198687541708928279517, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (5*M_PI/3, 0.50, mode, &r), 5.65345074919849876222825, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (5*M_PI/3, 0.01, mode, &r), 5.23612948927151704892488, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (2*M_PI, 0.99, mode, &r), 13.4264020934447695041339, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (2*M_PI, 0.50, mode, &r), 6.74300141925038417148481, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (2*M_PI, 0.01, mode, &r), 6.28334239564860894410562, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (7*M_PI/3.0, 0.99, mode, &r), 14.7329354327186461803160, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (7*M_PI/3.0, 0.50, mode, &r), 7.83255208930226958074138, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (7*M_PI/3.0, 0.01, mode, &r), 7.33055530202570083928637, TEST_TOL0, GSL_SUCCESS);
/* F, negative argument phi < 0 */
TEST_SF(s, gsl_sf_ellint_F_e, (-M_PI/2.0, 0.99, mode, &r), -3.35660052336119237603347, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-M_PI/2.0, 0.50, mode, &r), -1.68575035481259604287120, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-M_PI/2.0, 0.01, mode, &r), -1.57083559891215223602641, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-2*M_PI/3.0, 0.99, mode, &r), -5.40666770744850807588478, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-2*M_PI/3.0, 0.50, mode, &r), -2.28195003957330667648585, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-2*M_PI/3.0, 0.01, mode, &r), -2.09445829144721257687207, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-M_PI, 0.99, mode, &r), -6.71320104672238475206694, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-M_PI, 0.50, mode, &r), -3.37150070962519208574241, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-M_PI, 0.01, mode, &r), -3.14167119782430447205281, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-4*M_PI/3, 0.99, mode, &r), -8.01973438599626142824910, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-4*M_PI/3, 0.50, mode, &r), -4.46105137967707749499897, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-4*M_PI/3, 0.01, mode, &r), -4.18888410420139636723356, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-3*M_PI/2.0, 0.99, mode, &r), -10.0698015700835771281004, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-3*M_PI/2.0, 0.50, mode, &r), -5.05725106443778812861361, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-3*M_PI/2.0, 0.01, mode, &r), -4.71250679673645670807922, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-5*M_PI/3, 0.99, mode, &r), -12.1198687541708928279517, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-5*M_PI/3, 0.50, mode, &r), -5.65345074919849876222825, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-5*M_PI/3, 0.01, mode, &r), -5.23612948927151704892488, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-2*M_PI, 0.99, mode, &r), -13.4264020934447695041339, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-2*M_PI, 0.50, mode, &r), -6.74300141925038417148481, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-2*M_PI, 0.01, mode, &r), -6.28334239564860894410562, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-7*M_PI/3.0, 0.99, mode, &r), -14.7329354327186461803160, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-7*M_PI/3.0, 0.50, mode, &r), -7.83255208930226958074138, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_F_e, (-7*M_PI/3.0, 0.01, mode, &r), -7.33055530202570083928637, TEST_TOL0, GSL_SUCCESS);
/* P, argument phi > pi/2 */
TEST_SF(s, gsl_sf_ellint_P_e, (M_PI/2.0, 0.99, -0.1, mode, &r), 3.61678162163246646783050, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (M_PI/2.0, 0.50, -0.1, mode, &r), 1.78030349465454812629168, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (M_PI/2.0, 0.01, -0.1, mode, &r), 1.65580719756898353270922, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (2*M_PI/3.0, 0.99, -0.1, mode, &r), 5.88008918207571119911983, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (2*M_PI/3.0, 0.50, -0.1, mode, &r), 2.43655207300356008717867, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (2*M_PI/3.0, 0.01, -0.1, mode, &r), 2.23211110528200554950903, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (M_PI, 0.99, -0.1, mode, &r), 7.23356324326493293566099, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (M_PI, 0.50, -0.1, mode, &r), 3.56060698930909625258336, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (M_PI, 0.01, -0.1, mode, &r), 3.31161439513796706541844, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (4*M_PI/3, 0.99, -0.1, mode, &r), 8.58703730445415467220216, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (4*M_PI/3, 0.50, -0.1, mode, &r), 4.68466190561463241798805, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (4*M_PI/3, 0.01, -0.1, mode, &r), 4.39111768499392858132786, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (3*M_PI/2.0, 0.99, -0.1, mode, &r), 10.8503448648973994034915, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (3*M_PI/2.0, 0.50, -0.1, mode, &r), 5.34091048396364437887504, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (3*M_PI/2.0, 0.01, -0.1, mode, &r), 4.96742159270695059812767, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (5*M_PI/3, 0.99, -0.1, mode, &r), 13.1136524253406441347808, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (5*M_PI/3, 0.50, -0.1, mode, &r), 5.99715906231265633976204, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (5*M_PI/3, 0.01, -0.1, mode, &r), 5.54372550041997261492747, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (2*M_PI, 0.99, -0.1, mode, &r), 14.4671264865298658713220, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (2*M_PI, 0.50, -0.1, mode, &r), 7.12121397861819250516672, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (2*M_PI, 0.01, -0.1, mode, &r), 6.62322879027593413083689, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (7*M_PI/3.0, 0.99, -0.1, mode, &r), 15.8206005477190876078631, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (7*M_PI/3.0, 0.50, -0.1, mode, &r), 8.24526889492372867057141, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (7*M_PI/3.0, 0.01, -0.1, mode, &r), 7.70273208013189564674630, TEST_TOL0, GSL_SUCCESS);
/* P, negative argument phi < 0 */
TEST_SF(s, gsl_sf_ellint_P_e, (-M_PI/2.0, 0.99, -0.1, mode, &r), -3.61678162163246646783050, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-M_PI/2.0, 0.50, -0.1, mode, &r), -1.78030349465454812629168, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-M_PI/2.0, 0.01, -0.1, mode, &r), -1.65580719756898353270922, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-2*M_PI/3.0, 0.99, -0.1, mode, &r), -5.88008918207571119911983, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-2*M_PI/3.0, 0.50, -0.1, mode, &r), -2.43655207300356008717867, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-2*M_PI/3.0, 0.01, -0.1, mode, &r), -2.23211110528200554950903, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-M_PI, 0.99, -0.1, mode, &r), -7.23356324326493293566099, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-M_PI, 0.50, -0.1, mode, &r), -3.56060698930909625258336, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-M_PI, 0.01, -0.1, mode, &r), -3.31161439513796706541844, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-4*M_PI/3, 0.99, -0.1, mode, &r), -8.58703730445415467220216, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-4*M_PI/3, 0.50, -0.1, mode, &r), -4.68466190561463241798805, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-4*M_PI/3, 0.01, -0.1, mode, &r), -4.39111768499392858132786, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-3*M_PI/2.0, 0.99, -0.1, mode, &r), -10.8503448648973994034915, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-3*M_PI/2.0, 0.50, -0.1, mode, &r), -5.34091048396364437887504, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-3*M_PI/2.0, 0.01, -0.1, mode, &r), -4.96742159270695059812767, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-5*M_PI/3, 0.99, -0.1, mode, &r), -13.1136524253406441347808, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-5*M_PI/3, 0.50, -0.1, mode, &r), -5.99715906231265633976204, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-5*M_PI/3, 0.01, -0.1, mode, &r), -5.54372550041997261492747, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-2*M_PI, 0.99, -0.1, mode, &r), -14.4671264865298658713220, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-2*M_PI, 0.50, -0.1, mode, &r), -7.12121397861819250516672, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-2*M_PI, 0.01, -0.1, mode, &r), -6.62322879027593413083689, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-7*M_PI/3.0, 0.99, -0.1, mode, &r), -15.8206005477190876078631, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-7*M_PI/3.0, 0.50, -0.1, mode, &r), -8.24526889492372867057141, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_P_e, (-7*M_PI/3.0, 0.01, -0.1, mode, &r), -7.70273208013189564674630, TEST_TOL0, GSL_SUCCESS);
/* D, argument phi > pi/2 */
TEST_SF(s, gsl_sf_ellint_D_e, (M_PI/2.0, 0.99, mode, &r), 2.375395076351788975665323192, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (M_PI/2.0, 0.50, mode, &r), 0.8731525818926755496456335628, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (M_PI/2.0, 0.01, mode, &r), 0.7854276176694868932799393751, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (2*M_PI/3.0, 0.99, mode, &r), 4.305885125424644860264320635, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (2*M_PI/3.0, 0.50, mode, &r), 1.418324704155697579394036402, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (2*M_PI/3.0, 0.01, mode, &r), 1.263755353901126149206022061, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (M_PI, 0.99, mode, &r), 4.750790152703577951330646444, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (M_PI, 0.50, mode, &r), 1.746305163785351099291267125, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (M_PI, 0.01, mode, &r), 1.570855235338973786559878750, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (4*M_PI/3, 0.99, mode, &r), 5.195695179982511042396972113, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (4*M_PI/3, 0.50, mode, &r), 2.074285623415004619188497818, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (4*M_PI/3, 0.01, mode, &r), 1.877955116776821423913735408, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (3*M_PI/2.0, 0.99, mode, &r), 7.126185229055366926995969476, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (3*M_PI/2.0, 0.50, mode, &r), 2.619457745678026648936900687, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (3*M_PI/2.0, 0.01, mode, &r), 2.356282853008460679839818125, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (5*M_PI/3, 0.99, mode, &r), 9.056675278128222811594967044, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (5*M_PI/3, 0.50, mode, &r), 3.164629867941048678685303509, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (5*M_PI/3, 0.01, mode, &r), 2.834610589240099935765900794, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (2*M_PI, 0.99, mode, &r), 9.501580305407155902661292832, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (2*M_PI, 0.50, mode, &r), 3.492610327570702198582534249, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (2*M_PI, 0.01, mode, &r), 3.141710470677947573119757500, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (7*M_PI/3.0, 0.99, mode, &r), 9.946485332686088993727618315, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (7*M_PI/3.0, 0.50, mode, &r), 3.820590787200355718479764901, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (7*M_PI/3.0, 0.01, mode, &r), 3.448810352115795210473614120, TEST_TOL0, GSL_SUCCESS);
/* P, negative argument phi < 0 */
TEST_SF(s, gsl_sf_ellint_D_e, (-M_PI/2.0, 0.99, mode, &r), -2.375395076351788975665323192, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-M_PI/2.0, 0.50, mode, &r), -0.8731525818926755496456335628, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-M_PI/2.0, 0.01, mode, &r), -0.7854276176694868932799393751, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-2*M_PI/3.0, 0.99, mode, &r), -4.305885125424644860264320635, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-2*M_PI/3.0, 0.50, mode, &r), -1.418324704155697579394036402, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-2*M_PI/3.0, 0.01, mode, &r), -1.263755353901126149206022061, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-M_PI, 0.99, mode, &r), -4.750790152703577951330646444, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-M_PI, 0.50, mode, &r), -1.746305163785351099291267125, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-M_PI, 0.01, mode, &r), -1.570855235338973786559878750, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-4*M_PI/3, 0.99, mode, &r), -5.195695179982511042396972113, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-4*M_PI/3, 0.50, mode, &r), -2.074285623415004619188497818, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-4*M_PI/3, 0.01, mode, &r), -1.877955116776821423913735408, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-3*M_PI/2.0, 0.99, mode, &r), -7.126185229055366926995969476, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-3*M_PI/2.0, 0.50, mode, &r), -2.619457745678026648936900687, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-3*M_PI/2.0, 0.01, mode, &r), -2.356282853008460679839818125, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-5*M_PI/3, 0.99, mode, &r), -9.056675278128222811594967044, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-5*M_PI/3, 0.50, mode, &r), -3.164629867941048678685303509, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-5*M_PI/3, 0.01, mode, &r), -2.834610589240099935765900794, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-2*M_PI, 0.99, mode, &r), -9.501580305407155902661292832, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-2*M_PI, 0.50, mode, &r), -3.492610327570702198582534249, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-2*M_PI, 0.01, mode, &r), -3.141710470677947573119757500, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-7*M_PI/3.0, 0.99, mode, &r), -9.946485332686088993727618315, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-7*M_PI/3.0, 0.50, mode, &r), -3.820590787200355718479764901, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_ellint_D_e, (-7*M_PI/3.0, 0.01, mode, &r), -3.448810352115795210473614120, TEST_TOL0, GSL_SUCCESS);
return s;
}
int test_erf(void)
{
gsl_sf_result r;
int s = 0;
TEST_SF(s, gsl_sf_erfc_e, (-10.0, &r), 2.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erfc_e, (-5.0000002, &r), 1.9999999999984625433, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erfc_e, (-5.0, &r), 1.9999999999984625402, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erfc_e, (-1.0, &r), 1.8427007929497148693, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erfc_e, (-0.5, &r), 1.5204998778130465377, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erfc_e, (1.0, &r), 0.15729920705028513066, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erfc_e, (3.0, &r), 0.000022090496998585441373, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erfc_e, (7.0, &r), 4.183825607779414399e-23, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erfc_e, (10.0, &r), 2.0884875837625447570e-45, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_erfc_e, (-1.0, &r), log(1.842700792949714869), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_erfc_e, (-0.1, &r), 0.106576400586522485015, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_erfc_e, (-1e-10, &r), 1.1283791670318505967e-10, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_erfc_e, (0.0, &r), log(1.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_erfc_e, (1e-10, &r), -1.128379167159174551e-10, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_erfc_e, (0.001, &r), -0.0011290158896213548027, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_erfc_e, (0.1, &r), -0.119304973737395598329, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_erfc_e, (1.0, &r), log(0.15729920705028513066), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_erfc_e, (10.0, &r), log(2.0884875837625447570e-45), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erf_e, (-10.0, &r), -1.0000000000000000000, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erf_e, (0.5, &r), 0.5204998778130465377, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erf_e, (1.0, &r), 0.8427007929497148693, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erf_e, (10.0, &r), 1.0000000000000000000, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erf_Z_e, (1.0, &r), 0.24197072451914334980, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_erf_Q_e, (10.0, &r), 7.619853024160526066e-24, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (-20.0, &r), 5.5209483621597631896e-88, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (-10.0, &r), 7.6945986267064193463e-23, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (-1.0, &r), 0.28759997093917836123, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, ( 0.0, &r), 0.79788456080286535588, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, ( 1.0, &r), 1.5251352761609812091, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (10.0, &r), 10.098093233962511963, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (20.0, &r), 20.049753068527850542, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (30.0, &r), 30.033259667433677037, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (50.0, &r), 50.019984031905639809, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (80.0, &r), 80.012496096798234468, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (150.0, &r), 150.00666607420571802, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (300.0, &r), 300.00333325926337415, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (900.0, &r), 900.00111110836764382, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (1001.0, &r), 1001.0009989990049990, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hazard_e, (2000.0, &r), 2000.0004999997500003, TEST_TOL0, GSL_SUCCESS);
return s;
}
int test_exp(void)
{
gsl_sf_result r;
gsl_sf_result_e10 re;
double x;
int sa;
int s = 0;
TEST_SF(s, gsl_sf_exp_e, (-10.0, &r), exp(-10.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_e, ( 10.0, &r), exp( 10.0), TEST_TOL0, GSL_SUCCESS);
sa = 0;
sa += gsl_sf_exp_e10_e(1.0, &re);
sa += ( test_sf_frac_diff(re.val, M_E ) > TEST_TOL0 );
sa += ( re.err > TEST_TOL1 );
sa += ( re.e10 != 0 );
gsl_test(sa, " gsl_sf_exp_e10_e(1.0, &re)");
sa = 0;
sa += gsl_sf_exp_e10_e(2000.0, &re);
sa += ( test_sf_frac_diff(re.val, 3.88118019428363725 ) > TEST_TOL3 );
sa += ( re.err > TEST_TOL5 );
sa += ( re.e10 != 868 );
gsl_test(sa, " gsl_sf_exp_e10_e(2000.0, &re)");
TEST_SF(s, gsl_sf_exp_err_e, (-10.0, TEST_TOL1, &r), exp(-10.0), TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_err_e, ( 10.0, TEST_TOL1, &r), exp( 10.0), TEST_TOL1, GSL_SUCCESS);
sa = 0;
sa += gsl_sf_exp_err_e10_e(1.0, TEST_SQRT_TOL0, &re);
sa += ( test_sf_frac_diff(re.val, M_E ) > TEST_TOL1 );
sa += ( re.err > 32.0 * TEST_SQRT_TOL0 );
sa += ( re.e10 != 0 );
gsl_test(sa, " gsl_sf_exp_err_e10_e(1.0, TEST_SQRT_TOL0, &re)");
sa = 0;
sa += gsl_sf_exp_err_e10_e(2000.0, 1.0e-10, &re);
sa += ( test_sf_frac_diff(re.val, 3.88118019428363725 ) > TEST_TOL3 );
sa += ( re.err > 1.0e-07 );
sa += ( re.e10 != 868 );
gsl_test(sa, " gsl_sf_exp_err_e10_e(2000.0, 1.0e-10, &re)");
x = 0.8*GSL_LOG_DBL_MAX;
TEST_SF(s, gsl_sf_exp_mult_e, (-10.0, 1.0e-06, &r), 1.0e-06*exp(-10.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_mult_e, (-10.0, 2.0, &r), 2.0*exp(-10.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_mult_e, (-10.0, -2.0, &r), -2.0*exp(-10.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_mult_e, ( 10.0, 1.0e-06, &r), 1.0e-06*exp( 10.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_mult_e, ( 10.0, -2.0, &r), -2.0*exp( 10.0), TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_mult_e, (x, 1.00001, &r), 1.00001*exp(x), TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_mult_e, (x, 1.000001, &r), 1.000001*exp(x), TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_mult_e, (x, 1.000000001, &r), 1.000000001*exp(x), TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_mult_e, (x, 100.0, &r), 100.0*exp(x), TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_mult_e, (x, 1.0e+20, &r), 1.0e+20*exp(x), TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_mult_e, (x, exp(-x)*exp(M_LN2), &r), 2.0, TEST_TOL4, GSL_SUCCESS );
TEST_SF(s, gsl_sf_exp_mult_err_e, (-10.0, TEST_SQRT_TOL0, 2.0, TEST_SQRT_TOL0, &r), 2.0*exp(-10.0), TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exp_mult_err_e, (x, TEST_SQRT_TOL0*x, exp(-x)*exp(M_LN2), TEST_SQRT_TOL0*exp(-x)*exp(M_LN2), &r), 2.0, TEST_SQRT_TOL0, GSL_SUCCESS );
sa = 0;
sa += gsl_sf_exp_mult_e10_e(1.0, 1.0, &re);
sa += ( test_sf_frac_diff(re.val, M_E ) > TEST_TOL0 );
sa += ( re.err > TEST_TOL2 );
sa += ( re.e10 != 0 );
gsl_test(sa, "gsl_sf_exp_mult_e10_e(1.0, 1.0, &re)");
TEST_SF_E10(s, gsl_sf_exp_mult_e10_e, (1.0, 1.0, &re), M_E, 0, TEST_TOL0, GSL_SUCCESS);
sa = 0;
sa += gsl_sf_exp_mult_e10_e(1000.0, 1.0e+200, &re);
sa += ( test_sf_frac_diff(re.val, 1.970071114017046993888879352) > TEST_TOL3 );
sa += ( re.err > 1.0e-11 );
sa += ( re.e10 != 634 );
gsl_test(sa, "gsl_sf_exp_mult_e10_e(1000.0, 1.0e+200, &re)");
TEST_SF_E10(s, gsl_sf_exp_mult_e10_e, (1000.0, 1.0e+200, &re), 1.970071114017046993888879352, 634, TEST_TOL3, GSL_SUCCESS);
sa = 0;
sa += gsl_sf_exp_mult_err_e10_e(1.0, TEST_TOL0, 1.0, TEST_TOL0, &re);
sa += ( test_sf_frac_diff(re.val, M_E ) > TEST_TOL0 );
sa += ( re.err > TEST_TOL2 );
sa += ( re.e10 != 0 );
gsl_test(sa, "gsl_sf_exp_mult_err_e10_e(1.0, TEST_TOL0, 1.0, TEST_TOL0, &re)");
TEST_SF_E10(s, gsl_sf_exp_mult_err_e10_e, (1.0, TEST_TOL0, 1.0, TEST_TOL0, &re), M_E, 0, TEST_TOL0, GSL_SUCCESS);
sa = 0;
sa += gsl_sf_exp_mult_err_e10_e(1000.0, 1.0e-12, 1.0e+200, 1.0e+190, &re);
sa += ( test_sf_frac_diff(re.val, 1.9700711140165661 ) > TEST_TOL3 );
sa += ( re.err > 1.0e-09 );
sa += ( re.e10 != 634 );
gsl_test(sa, "gsl_sf_exp_mult_err_e10_e(1.0e-12, 1.0e+200, &re)");
TEST_SF_E10(s, gsl_sf_exp_mult_err_e10_e, (1000.0, 1.0e-12, 1.0e+200, 1.0e+190, &re), 1.9700711140165661,634, TEST_TOL3, GSL_SUCCESS);
/* Test cases from Szymon Jaroszewicz */
TEST_SF_E10(s, gsl_sf_exp_mult_e10_e, (10000.0, 1.0, &re), 8.806818225662921587261496007, 4342, TEST_TOL5, GSL_SUCCESS);
TEST_SF_E10(s, gsl_sf_exp_mult_e10_e, (100.0, 1.0, &re), 2.688117141816135448412625551e43, 0, TEST_TOL2, GSL_SUCCESS);
TEST_SF_E10(s, gsl_sf_exp_e10_e, (100.0, &re), 2.688117141816135448412625551e43, 0, TEST_TOL2, GSL_SUCCESS);
TEST_SF_E10(s, gsl_sf_exp_e10_e, (1000.0, &re), 1.970071114017046993888879352, 434, TEST_TOL3, GSL_SUCCESS);
TEST_SF_E10(s, gsl_sf_exp_e10_e, (-100.0, &re), 3.720075976020835962959695803e-44, 0, TEST_TOL2, GSL_SUCCESS);
TEST_SF_E10(s, gsl_sf_exp_e10_e, (-1000.0, &re), 5.075958897549456765291809479, -435, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expm1_e, (-10.0, &r), exp(-10.0)-1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expm1_e, (-0.001, &r), -0.00099950016662500845, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expm1_e, (-1.0e-8, &r), -1.0e-08 + 0.5e-16, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expm1_e, ( 1.0e-8, &r), 1.0e-08 + 0.5e-16, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expm1_e, ( 0.001, &r), 0.0010005001667083417, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expm1_e, ( 10.0, &r), exp(10.0)-1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_e, (-10.0, &r), 0.0999954600070237515, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_e, (-0.001, &r), 0.9995001666250084, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_e, (-1.0e-8, &r), 1.0 - 0.5e-08, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_e, ( 1.0e-8, &r), 1.0 + 0.5e-08, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_e, ( 0.001, &r), 1.0005001667083417, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_e, ( 10.0, &r), 2202.5465794806716517, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_2_e, (-10.0, &r), 0.18000090799859524970, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_2_e, (-0.001, &r), 0.9996667499833361107, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_2_e, (-1.0e-8, &r), 0.9999999966666666750, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_2_e, ( 1.0e-8, &r), 1.0000000033333333417, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_2_e, ( 0.001, &r), 1.0003334166833361115, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_2_e, ( 10.0, &r), 440.3093158961343303, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (3, -1000.0, &r), 0.00299400600000000000, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (3, -100.0, &r), 0.02940600000000000000, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (3, -10.0, &r), 0.24599972760042142509, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (3, -3.0, &r), 0.5444917625849191238, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (3, -0.001, &r), 0.9997500499916678570, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (3, -1.0e-8, &r), 0.9999999975000000050, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (3, 1.0e-8, &r), 1.0000000025000000050, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (3, 0.001, &r), 1.0002500500083345240, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (3, 3.0, &r), 2.5745637607083706091, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (3, 3.1, &r), 2.6772417068460206247, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (3, 10.0, &r), 131.79279476884029910, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (3, 100.0, &r), 1.6128702850896812690e+38, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, -1000.0, &r), 0.04766231609253975959, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, -100.0, &r), 0.3348247572345889317, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, -10.0, &r), 0.8356287051853286482, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, -3.0, &r), 0.9443881609152163615, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, -1.0, &r), 0.980762245565660617, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, -1.0e-8, &r), 1.0 -1.0e-8/51.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, 1.0e-8, &r), 1.0 +1.0e-8/51.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, 1.0, &r), 1.01999216583666790, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, 3.0, &r), 1.0624205757460368307, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, 48.0, &r), 7.499573876877194416, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, 50.1, &r), 9.311803306230992272, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, 100.0, &r), 8.175664432485807634e+07, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (50, 500.0, &r), 4.806352370663185330e+146, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, -1000.0, &r), 0.3334815803127619256, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, -100.0, &r), 0.8335646217536183909, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, -10.0, &r), 0.9804297803131823066, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, -3.0, &r), 0.9940475488850672997, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, -1.0, &r), 0.9980079602383488808, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, -1.0e-8, &r), 1.0 -1.0e-8/501.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, 1.0e-8, &r), 1.0 +1.0e-8/501.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, 1.0, &r), 1.0019999920160634252, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, 3.0, &r), 1.0060240236632444934, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, 48.0, &r), 1.1059355517981272174, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, 100.0, &r), 1.2492221464878287204, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, 500.0, &r), 28.363019877927630858, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, 1000.0, &r), 2.4037563160335300322e+68, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (500, 1600.0, &r), 7.899293535320607403e+226, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_e, (1263131.0, 1261282.3637, &r), 545.0113107238425900305428360, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_exprel_n_CF_e, (6.315655e+05, 6.302583168053568806e+05, &r), 385.425369029433473098652465720, TEST_TOL4, GSL_SUCCESS);
return s;
}
int test_expint(void)
{
gsl_sf_result r;
int s = 0;
TEST_SF(s, gsl_sf_expint_E1_e, (-1.0, &r), -1.8951178163559367555, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_e, (1.0e-10, &r), 22.448635265138923980, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_e, (1.0e-05, &r), 10.935719800043695615, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_e, (0.1, &r), 1.82292395841939066610, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_e, (1.0, &r), 0.21938393439552027368, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_e, (10.0, &r), 4.156968929685324277e-06, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_e, (50.0, &r), 3.783264029550459019e-24, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_e, (300.0, &r), 1.710384276804510115e-133, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_e, (-1.0, &r), 0.8231640121031084799, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_e, (0.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_e, (1.0/4294967296.0, &r), 0.9999999947372139168, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_e, (1.0/65536.0, &r), 0.9998243233207178845, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_e, (0.1, &r), 0.7225450221940205066, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_e, (1.0, &r), 0.14849550677592204792, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_e, (10.0, &r), 3.830240465631608762e-06, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_e, (50.0, &r), 3.711783318868827367e-24, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_e, (300.0, &r), 1.7047391998483433998e-133, TEST_TOL2, GSL_SUCCESS);
/* Tests for E_n(x) */
TEST_SF(s, gsl_sf_expint_En_e, (1,-1.0, &r), -1.8951178163559367555, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (1,1.0e-10, &r), 22.448635265138923980, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (1,1.0e-05, &r), 10.935719800043695615, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (1,0.1, &r), 1.82292395841939066610, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (1,1.0, &r), 0.21938393439552027368, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (1,10.0, &r), 4.156968929685324277e-06, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (1,50.0, &r), 3.783264029550459019e-24, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (1,300.0, &r), 1.710384276804510115e-133, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (2,-1.0, &r), 0.8231640121031084799, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (2,0.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (2,1.0/4294967296.0, &r), 0.9999999947372139168, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (2,1.0/65536.0, &r), 0.9998243233207178845, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (2,0.1, &r), 0.7225450221940205066, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (2,1.0, &r), 0.14849550677592204792, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (2,10.0, &r), 3.830240465631608762e-06, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (2,50.0, &r), 3.711783318868827367e-24, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (2,300.0, &r), 1.7047391998483433998e-133, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (3,0.0, &r), 0.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (3,1.0/4294967296.0, &r), 0.499999999767169356972, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (3,1.0/65536.0, &r), 0.4999847426094515610, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (3,0.1, &r), 0.4162914579082787612543, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (3,1.0, &r), 0.10969196719776013683858, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (3,10.0, &r),0.000003548762553084381959981, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (3,50.0, &r), 3.6429094264752049812e-24, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (3,300.0, &r),1.699131143349179084e-133, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (10,0.0, &r), 0.111111111111111111, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (10,1.0/4294967296.0, &r), 0.111111111082007280658, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (10,1.0/65536.0, &r), 0.11110920377910896018606, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (10,0.1, &r), 0.099298432000896813567905, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (10,1.0, &r), 0.036393994031416401634164534, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (10,10.0, &r), 0.00000232530265702821081778968, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (10,50.0, &r), 3.223296586749110919572e-24, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_e, (10,300.0, &r), 1.6608815083360041367294736e-133, TEST_TOL2, GSL_SUCCESS);
/* Tests for Ei(x) */
TEST_SF(s, gsl_sf_expint_Ei_e, (-1.0, &r), -0.21938393439552027368, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_Ei_e, (1.0/4294967296.0, &r), -21.603494112783886397, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_Ei_e, (1.0, &r), 1.8951178163559367555, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (-10000.0, &r), -0.00010001000200060024012, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (-1000.0, &r), -0.0010010020060241207251, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (-10.0, &r), -0.11314702047341077803, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (-1.0, &r), -0.69717488323506606877, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (1.0e-10, &r), 22.448635267383787506, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (1.0e-05, &r), 10.935829157788483865, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (0.1, &r), 2.0146425447084516791, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (1.0, &r), 0.59634736232319407434, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (10.0, &r), 0.091563333939788081876, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (50.0, &r), 0.019615109930114870365, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (300.0, &r), 0.0033222955652707070644, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (1000.0, &r), 0.00099900199402388071500, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E1_scaled_e, (10000.0, &r), 0.000099990001999400239880, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (-10000.0, &r), -0.00010002000600240120072, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (-1000.0, &r), -0.0010020060241207250807, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (-10.0, &r), -0.13147020473410778034, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (-1.0, &r), 0.30282511676493393123, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (0.0, &r), 1.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (1.0/4294967296.0, &r), 0.99999999497004455927, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (1.0/65536.0, &r), 0.99983957954556245453, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (0.1, &r), 0.79853574552915483209, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (1.0, &r), 0.40365263767680592566, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (10.0, &r), 0.084366660602119181239, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (50.0, &r), 0.019244503494256481735, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (300.0, &r), 0.0033113304187878806691, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (1000.0, &r), 0.00099800597611928500004, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_E2_scaled_e, (10000.0, &r), 0.000099980005997601199281, TEST_TOL0, GSL_SUCCESS);
/* Tests for E_n(x) */
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,-10000.0, &r), -0.00010001000200060024012, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,-1000.0, &r), -0.0010010020060241207251, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,-10.0, &r), -0.11314702047341077803, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,-1.0, &r), -0.69717488323506606877, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,1.0e-10, &r), 22.448635267383787506, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,1.0e-05, &r), 10.935829157788483865, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,0.1, &r), 2.0146425447084516791, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,1.0, &r), 0.59634736232319407434, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,10.0, &r), 0.091563333939788081876, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,50.0, &r), 0.019615109930114870365, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,300.0, &r), 0.0033222955652707070644, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,1000.0, &r), 0.00099900199402388071500, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (1,10000.0, &r), 0.000099990001999400239880, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,-10000.0, &r), -0.00010002000600240120072, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,-1000.0, &r), -0.0010020060241207250807, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,-10.0, &r), -0.13147020473410778034, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,-1.0, &r), 0.30282511676493393123, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,0.0, &r), 1.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,1.0/4294967296.0, &r), 0.99999999497004455927, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,1.0/65536.0, &r), 0.99983957954556245453, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,0.1, &r), 0.79853574552915483209, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,1.0, &r), 0.40365263767680592566, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,10.0, &r), 0.084366660602119181239, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,50.0, &r), 0.019244503494256481735, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,300.0, &r), 0.0033113304187878806691, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,1000.0, &r), 0.00099800597611928500004, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (2,10000.0, &r), 0.000099980005997601199281, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (3,0.0, &r), 0.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (3,1.0/4294967296.0, &r), 0.4999999998835846787586, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (3,1.0/65536.0, &r), 0.4999923718293796877864492, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (3,0.1, &r), 0.4600732127235422583955, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (3,1.0, &r), 0.298173681161597037170539, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (3,10.0, &r), 0.07816669698940409380349, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (3,50.0, &r), 0.0188874126435879566345, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (3,300.0, &r), 0.00330043718181789963028657675, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (10,0.0, &r), 0.111111111111111111, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (10,1.0/4294967296.0, &r), 0.11111111110787735217158, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (10,1.0/65536.0, &r), 0.1111108991839472074435, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (10,0.1, &r), 0.1097417392579033988025, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (10,1.0, &r), 0.09892913264064615521915, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (10,10.0, &r), 0.0512181994376050593314159875, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (10,50.0, &r), 0.0167118436335939556034579, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_En_scaled_e, (10,300.0, &r), 0.0032261400811599644878615, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_Ei_scaled_e, (-1000.0, &r), -0.00099900199402388071500, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_Ei_scaled_e, (-1.0, &r), -0.59634736232319407434, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_Ei_scaled_e, (1.0/4294967296.0, &r), -21.603494107753930958, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_Ei_scaled_e, (1.0, &r), 0.69717488323506606877, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_Ei_scaled_e, (1000.0, &r), 0.0010010020060241207251, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Shi_e, (-1.0, &r), -1.0572508753757285146, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Shi_e, (1.0/4294967296.0, &r), 2.3283064365386962891e-10, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Shi_e, (1.0/65536.0, &r), 0.00001525878906269737298, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Shi_e, (0.1, &r), 0.1000555722250569955, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Shi_e, (1.0, &r), 1.0572508753757285146, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Shi_e, (10.0, &r), 1246.1144901994233444, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Shi_e, (50.0, &r), 5.292818448565845482e+19, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Shi_e, (300.0, &r), 3.248241254044332895e+127, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Chi_e, (-1.0, &r), 0.8378669409802082409, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Chi_e, (1.0/4294967296.0, &r), -21.603494113016717041, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Chi_e, (1.0/65536.0, &r), -10.513139223999384429, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Chi_e, (1.0/8.0, &r), -1.4983170827635760646, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Chi_e, (1.0, &r), 0.8378669409802082409, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Chi_e, (10.0, &r), 1246.1144860424544147, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Chi_e, (50.0, &r), 5.292818448565845482e+19, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Chi_e, (300.0, &r), 3.248241254044332895e+127, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_3_e, (1.0e-10, &r), 1.0e-10, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_3_e, (1.0e-05, &r), 9.9999999999999975e-06, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_3_e, (0.1, &r), 0.09997500714119079665122, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_3_e, (0.5, &r), 0.48491714311363971332427, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_3_e, (1.0, &r), 0.80751118213967145285833, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_3_e, (2.0, &r), 0.89295351429387631138208, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_3_e, (5.0, &r), 0.89297951156924921121856, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_3_e, (10.0, &r), 0.89297951156924921121856, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_expint_3_e, (100.0, &r), 0.89297951156924921121856, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Si_e, (-1.0, &r), -0.9460830703671830149, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Si_e, (1.0e-10, &r), 1.0e-10, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Si_e, (1.0e-05, &r), 9.999999999944444444e-06, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Si_e, (0.1, &r), 0.09994446110827695016, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Si_e, (1.0, &r), 0.9460830703671830149, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Si_e, (10.0, &r), 1.6583475942188740493, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Si_e, (50.0, &r), 1.5516170724859358947, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Si_e, (300.0, &r), 1.5708810882137495193, TEST_TOL0, GSL_SUCCESS);
/*
TEST_SF(s, gsl_sf_Si_e, (1.0e+20, &r), 1.5707963267948966192, TEST_TOL0, GSL_SUCCESS);
*/
TEST_SF(s, gsl_sf_Ci_e, (1.0/4294967296.0, &r), -21.603494113016717041, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Ci_e, (1.0/65536.0, &r), -10.513139224115799751, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Ci_e, (1.0/8.0, &r), -1.5061295845296396649, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Ci_e, (1.0, &r), 0.3374039229009681347, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Ci_e, (10.0, &r), -0.04545643300445537263, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Ci_e, (50.0, &r), -0.005628386324116305440, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Ci_e, (300.0, &r), -0.003332199918592111780, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Ci_e, (65536.0, &r), 0.000010560248837656279453, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Ci_e, (4294967296.0, &r), -1.0756463261957757485e-10, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_Ci_e, (1099511627776.0, &r), -3.689865584710764214e-13, 1024.0*TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_atanint_e, (1.0e-10, &r), 1.0e-10, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_atanint_e, (1.0e-05, &r), 9.99999999988888888889e-06, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_atanint_e, (0.1, &r), 0.09988928686033618404, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_atanint_e, (1.0, &r), 0.91596559417721901505, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_atanint_e, (2.0, &r), 1.57601540344632342236, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_atanint_e, (10.0, &r), 3.71678149306806859029, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_atanint_e, (50.0, &r), 6.16499047850274874222, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_atanint_e, (300.0, &r), 8.96281388924518959990, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_atanint_e, (1.0e+5, &r), 18.084471031038661920, TEST_TOL0, GSL_SUCCESS);
/* Bug report from Wolfgang Ehrhardt <Wolfgang.Ehrhardt@munich.netsurf.de> */
TEST_SF(s, gsl_sf_atanint_e, (1.0e+9, &r), 32.552029856869591656, TEST_TOL0, GSL_SUCCESS);
return s;
}
int test_fermidirac(void)
{
gsl_sf_result r;
int s = 0;
TEST_SF(s, gsl_sf_fermi_dirac_m1_e, (-10.0, &r), 0.00004539786870243439450, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_m1_e, ( -1.0, &r), 0.26894142136999512075, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_m1_e, ( 1.0, &r), 0.7310585786300048793, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_m1_e, ( 10.0, &r), 0.9999546021312975656, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_0_e, (-10.0, &r), 0.00004539889921686464677, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_0_e, ( -1.0, &r), 0.31326168751822283405, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_0_e, ( 1.0, &r), 1.3132616875182228340, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_0_e, ( 10.0, &r), 10.000045398899216865, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_1_e, (-10.0, &r), 0.00004539941448447633524, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_1_e, ( -2.0, &r), 0.13101248471442377127, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_1_e, ( -1.0, &r), 0.3386479964034521798, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_1_e, ( -0.4, &r), 0.5825520806897909028, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_1_e, ( 0.4, &r), 1.1423819861584355337, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_1_e, ( 1.0, &r), 1.8062860704447742567, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_1_e, ( 1.5, &r), 2.5581520872227806402, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_1_e, ( 2.5, &r), 4.689474797599761667, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_1_e, ( 10.0, &r), 51.64488866743374196, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_1_e, ( 12.0, &r), 73.64492792264531092, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_1_e, ( 20.0, &r), 201.64493406478707282, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_1_e, ( 50.0, &r), 1251.6449340668482264, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, (-10.0, &r), 0.00004539967212174776662, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, ( -2.0, &r), 0.13313272938565030508, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, ( -1.0, &r), 0.3525648792978077590, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, ( -0.4, &r), 0.6229402647001272120, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, ( 0.4, &r), 1.2915805581060844533, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, ( 1.0, &r), 2.1641656128127008622, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, ( 1.5, &r), 3.247184513920792475, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, ( 2.5, &r), 6.797764392735056317, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, ( 10.0, &r), 183.11605273482105278, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, ( 12.0, &r), 307.73921494638635166, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, ( 20.0, &r), 1366.2320146723590157, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, ( 50.0, &r), 20915.580036675744655, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_2_e, (200.0, &r), 1.3336623201467029786e+06, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_mhalf_e, (-10.0, &r), 0.00004539847236080549532, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_mhalf_e, ( -2.0, &r), 0.12366562180120994266, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_mhalf_e, ( -1.0, &r), 0.29402761761145122022, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_mhalf_e, ( -0.4, &r), 0.4631755336886027800, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_mhalf_e, ( 0.4, &r), 0.7654084737661656915, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_mhalf_e, ( 1.0, &r), 1.0270571254743506890, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_mhalf_e, ( 1.5, &r), 1.2493233478527122008, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_mhalf_e, ( 2.5, &r), 1.6663128834358313625, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_mhalf_e, ( 10.0, &r), 3.552779239536617160, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_mhalf_e, ( 12.0, &r), 3.897268231925439359, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_mhalf_e, ( 20.0, &r), 5.041018507535328603, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_mhalf_e, ( 50.0, &r), 7.977530858581869960, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_half_e, (-10.0, &r), 0.00004539920105264132755, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_half_e, ( -2.0, &r), 0.12929851332007559106, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_half_e, ( -1.0, &r), 0.3277951592607115477, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_half_e, ( -0.4, &r), 0.5522452153690688947, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_half_e, ( 0.4, &r), 1.0386797503389389277, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_half_e, ( 1.0, &r), 1.5756407761513002308, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_half_e, ( 1.5, &r), 2.1448608775831140360, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_half_e, ( 2.5, &r), 3.606975377950373251, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_half_e, ( 10.0, &r), 24.084656964637653615, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_half_e, ( 12.0, &r), 31.540203287044242593, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_half_e, ( 20.0, &r), 67.49151222165892049, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_half_e, ( 50.0, &r), 266.09281252136259343, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_3half_e, (-10.0, &r), 0.00004539956540456176333, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_3half_e, ( -2.0, &r), 0.13224678225177236685, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_3half_e, ( -1.0, &r), 0.3466747947990574170, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_3half_e, ( -0.4, &r), 0.6056120213305040910, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_3half_e, ( 0.4, &r), 1.2258236403963668282, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_3half_e, ( 1.0, &r), 2.0022581487784644573, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_3half_e, ( 1.5, &r), 2.9277494127932173068, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_3half_e, ( 2.5, &r), 5.768879312210516582, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_3half_e, ( 10.0, &r), 101.00510084332600020, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_3half_e, ( 12.0, &r), 156.51518642795728036, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_3half_e, ( 20.0, &r), 546.5630100657601959, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_3half_e, ( 50.0, &r), 5332.353566687145552, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (3, -2.0, &r), 0.1342199155038680215, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (3, 0.0, &r), 0.9470328294972459176, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (3, 0.1, &r), 1.0414170610956165759, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (3, 1.0, &r), 2.3982260822489407070, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (3, 3.0, &r), 12.621635313399690724, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (3, 100.0, &r), 4.174893231066566793e+06, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (3, 500.0, &r), 2.604372285319088354e+09, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (5, -2.0, &r), 0.13505242246823676478, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (5, 0.0, &r), 0.9855510912974351041, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (5, 0.1, &r), 1.0876519750101492782, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (5, 1.0, &r), 2.6222337848692390539, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (5, 3.0, &r), 17.008801618012113022, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (5, 100.0, &r), 1.3957522531334869874e+09, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (5, 500.0, &r), 2.1705672808114817955e+13, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (7, -2.0, &r), 0.1352641105671255851, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (7, 0.0, &r), 0.9962330018526478992, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (7, 0.1, &r), 1.1005861815180315485, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (7, 1.0, &r), 2.6918878172003129203, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (7, 3.0, &r), 19.033338976999367642, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (7, 10.0, &r), 5654.530932873610014, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (7, 50.0, &r), 1.005005069985066278e+09, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (7, 500.0, &r), 9.691690268341569514e+16, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (9, -2.0, &r), 0.1353174385330242691, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (9, 0.0, &r), 0.9990395075982715656, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (9, 0.1, &r), 1.1039997234712941212, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (9, 1.0, &r), 2.7113648898129249947, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (9, 3.0, &r), 19.768544008138602223, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (9, 10.0, &r), 10388.990167312912478, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (9, 50.0, &r), 2.85466960802601649e+10, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (9, 500.0, &r), 2.69273849842695876e+20, 2*TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (10, -2.0, &r), 0.13532635396712288092, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (10, 0.0, &r), 0.9995171434980607541, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (10, 0.1, &r), 1.1045818238852612296, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (10, 1.0, &r), 2.7147765350346120647, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (10, 3.0, &r), 19.917151938411675171, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (10, 10.0, &r), 12790.918595516495955, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (10, 50.0, &r), 1.3147703201869657654e+11, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (10, 500.0, &r), 1.2241331244469204398e+22, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (11, -2.0, &r), 0.1353308162894847149, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (11, 0.0, &r), 0.9997576851438581909, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (11, 0.1, &r), 1.1048751811565850418, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (11, 1.0, &r), 2.7165128749007313436, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (11, 3.0, &r), 19.997483022044603065, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (11, 10.0, &r), 14987.996005901818036, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (11, 50.0, &r), 5.558322924078990628e+11, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (11, 500.0, &r), 5.101293089606198280e+23, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (20, -2.0, &r), 0.13533527450327238373, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (20, 0.0, &r), 0.9999995232582155428, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (20, 0.1, &r), 1.1051703357941368203, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (20, 1.0, &r), 2.7182783069905721654, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (20, 3.0, &r), 20.085345296028242734, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (20, 10.0, &r), 21898.072920149606475, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (20, 50.0, &r), 1.236873256595717618e+16, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_fermi_dirac_int_e, (20, 500.0, &r), 9.358938204369557277e+36, TEST_TOL2, GSL_SUCCESS);
return s;
}
int test_gegen(void)
{
gsl_sf_result r;
double ga[100];
int s = 0;
int sa;
TEST_SF(s, gsl_sf_gegenpoly_1_e, (-0.2, 1.0, &r), -0.4, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_1_e, ( 0.0, 1.0, &r), 2.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_1_e, ( 1.0, 1.0, &r), 2.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_1_e, ( 1.0, 0.5, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_1_e, ( 5.0, 1.0, &r), 10.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_1_e, ( 100.0, 0.5, &r), 100.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_2_e, (-0.2, 0.5, &r), 0.12, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_2_e, ( 0.0, 1.0, &r), 1.00, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_2_e, ( 1.0, 1.0, &r), 3.00, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_2_e, ( 1.0, 0.1, &r), -0.96, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_2_e, ( 5.0, 1.0, &r), 55.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_2_e, ( 100.0, 0.5, &r), 4950.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_3_e, (-0.2, 0.5, &r), 0.112, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_3_e, ( 0.0, 1.0, &r), -2.0/3.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_3_e, ( 1.0, 1.0, &r), 4.000, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_3_e, ( 1.0, 0.1, &r), -0.392, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_3_e, ( 5.0, 1.0, &r), 220.000, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_3_e, ( 100.0, 0.5, &r), 161600.000, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_n_e, (1, 1.0, 1.0, &r), 2.000 , TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_n_e, (10, 1.0, 1.0, &r), 11.000 , TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_n_e, (10, 1.0, 0.1, &r), -0.4542309376 , TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_n_e, (10, 5.0, 1.0, &r), 9.23780e+4 , TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_n_e, (10, 100.0, 0.5, &r), 1.5729338392690000e+13, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_n_e, (1000, 100.0, 1.0, &r), 3.3353666135627322e+232, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_n_e, (100, 2000.0, 1.0, &r), 5.8753432034937579e+202, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_n_e, (103, 207.0, 2.0, &r), 1.4210272202235983e+145, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_gegenpoly_n_e, (103, -0.4, 0.3, &r), -1.64527498094522e-04, TEST_TOL1, GSL_SUCCESS);
sa = 0;
gsl_sf_gegenpoly_array(99, 5.0, 1.0, ga);
sa += ( test_sf_frac_diff( ga[1], 10.0 ) > TEST_TOL0 );
sa += ( test_sf_frac_diff( ga[10], 9.23780e+4 ) > TEST_TOL0 );
gsl_test(sa, " gsl_sf_gegenpoly_array");
s += sa;
return s;
}
int test_jac(void)
{
double u, m;
double sn, cn, dn;
int stat_ej;
int s = 0;
int sa;
u = 0.5;
m = 0.5;
sa = 0;
stat_ej = gsl_sf_elljac_e(u, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 0.4707504736556572833, TEST_TOL0, "gsl_sf_elljac_e(0.5|0.5) sn");
sa += test_sf_val(cn, 0.8822663948904402865, TEST_TOL0, "gsl_sf_elljac_e(0.5|0.5) cn");
sa += test_sf_val(dn, 0.9429724257773856873, TEST_TOL0, "gsl_sf_elljac_e(0.5|0.5) dn");
gsl_test(s, " gsl_sf_elljac_e(0.5|0.5)");
s += sa;
u = 1.0;
m = 0.3;
sa = 0;
stat_ej = gsl_sf_elljac_e(u, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 0.8187707145344889190, TEST_TOL0, "gsl_sf_elljac_e(1.0|0.3) sn");
sa += test_sf_val(cn, 0.5741206467465548795, TEST_TOL0, "gsl_sf_elljac_e(1.0|0.3) cn");
sa += test_sf_val(dn, 0.8938033089590823040, TEST_TOL0, "gsl_sf_elljac_e(1.0|0.3) dn");
gsl_test(sa, " gsl_sf_elljac_e(1.0|0.3)");
s += sa;
u = 1.0;
m = 0.6;
sa = 0;
stat_ej = gsl_sf_elljac_e(u, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 0.7949388393365780943, TEST_TOL0, "gsl_sf_elljac_e(1.0|0.6) sn");
sa += test_sf_val(cn, 0.6066895760718277578, TEST_TOL0, "gsl_sf_elljac_e(1.0|0.6) cn");
sa += test_sf_val(dn, 0.7879361300438814425, TEST_TOL0, "gsl_sf_elljac_e(1.0|0.6) dn");
gsl_test(sa, " gsl_sf_elljac_e(1.0|0.6)");
s += sa;
u = 3.0;
m = 0.6;
sa = 0;
stat_ej = gsl_sf_elljac_e(u, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 0.7432676860864044186, TEST_TOL0, " gsl_sf_elljac_e(3.0|0.6) sn");
sa += test_sf_val(cn, -0.6689941306317733154, TEST_TOL0, " gsl_sf_elljac_e(3.0|0.6) cn");
sa += test_sf_val(dn, 0.8176379933025723259, TEST_TOL0, " gsl_sf_elljac_e(3.0|0.6) dn");
gsl_test(sa, " gsl_sf_elljac_e(3.0|0.6)");
s += sa;
u = 2.0;
m = 0.999999;
sa = 0;
stat_ej = gsl_sf_elljac_e(u, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 0.96402778575700186570, TEST_TOL1, "gsl_sf_elljac_e(2.0|0.999999) sn");
sa += test_sf_val(cn, 0.26580148285600686381, TEST_TOL1, "gsl_sf_elljac_e(2.0|0.999999) cn");
sa += test_sf_val(dn, 0.26580323105264131136, TEST_TOL1, "gsl_sf_elljac_e(2.0|0.999999) dn");
gsl_test(sa, " gsl_sf_elljac_e(2.0|0.999999)");
s += sa;
/* test supplied by Ivan Panchenko */
u = 1.69695970624443;
m = 0.270378013104138;
sa = 0;
stat_ej = gsl_sf_elljac_e(u, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 1.0, TEST_TOL0, "gsl_sf_elljac_e(1.69..|0.27..) sn");
sa += test_sf_val(cn, 0.0, TEST_TOL1, "gsl_sf_elljac_e(1.69..|0.27..) cn");
sa += test_sf_val(dn, 0.8541791304497336, TEST_TOL1, "gsl_sf_elljac_e(1.69..|0.27..) dn");
gsl_test(sa, " gsl_sf_elljac_e(1.69695970624443|0.270378013104138)");
s += sa;
/* Check known values from Abramowitz & Stegun, Table 16.5 */
u = 0;
m = 0.1;
{
double mc = 1 - m;
/* quarter period K is (pi/2)/agm(1,mc) */
double K = (M_PI_2)/ 0.9741726903999478375938128316;
double A = 1.0 / sqrt(1+sqrt(mc));
double B = pow(mc, 0.25) / sqrt(1+sqrt(mc));
double C = pow(mc, 0.25);
double C2 = sqrt(mc);
double eps = 1e-10;
sa = 0;
stat_ej = gsl_sf_elljac_e(0.0, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 0.0, TEST_TOL0, "gsl_sf_elljac_e(0|0.1) sn");
sa += test_sf_val(cn, 1.0, TEST_TOL0, "gsl_sf_elljac_e(0|0.1) cn");
sa += test_sf_val(dn, 1.0, TEST_TOL0, "gsl_sf_elljac_e(0|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(0|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(-eps, m, &sn, &cn, &dn);
sa += test_sf_val(sn, -eps, TEST_TOL0, "gsl_sf_elljac_e(-1e-10|0.1) sn");
sa += test_sf_val(cn, 1.0, TEST_TOL0, "gsl_sf_elljac_e(-1e-10|0.1) cn");
sa += test_sf_val(dn, 1.0, TEST_TOL0, "gsl_sf_elljac_e(-1e-10|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(-1e-10|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(eps, m, &sn, &cn, &dn);
sa += test_sf_val(sn, eps, TEST_TOL0, "gsl_sf_elljac_e(1e-10|0.1) sn");
sa += test_sf_val(cn, 1.0, TEST_TOL0, "gsl_sf_elljac_e(1e-10|0.1) cn");
sa += test_sf_val(dn, 1.0, TEST_TOL0, "gsl_sf_elljac_e(1e-10|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(1e-10|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(1e-30, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 1e-30, TEST_TOL0, "gsl_sf_elljac_e(1e-30|0.1) sn");
sa += test_sf_val(cn, 1.0, TEST_TOL0, "gsl_sf_elljac_e(1e-30|0.1) cn");
sa += test_sf_val(dn, 1.0, TEST_TOL0, "gsl_sf_elljac_e(1e-30|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(1e-30|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(K / 2.0 - eps, m, &sn, &cn, &dn);
sa += test_sf_val(sn, A - eps*B*C, TEST_TOL2, "gsl_sf_elljac_e(K/2-1e-10|0.1) sn");
sa += test_sf_val(cn, B + eps*A*C, TEST_TOL2, "gsl_sf_elljac_e(K/2-1e-10|0.1) cn");
sa += test_sf_val(dn, C + m*eps*A*B, TEST_TOL2, "gsl_sf_elljac_e(K/2-1e-10|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(K/2-1e-10|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(K / 2.0, m, &sn, &cn, &dn);
sa += test_sf_val(sn, A, TEST_TOL2, "gsl_sf_elljac_e(K/2|0.1) sn");
sa += test_sf_val(cn, B, TEST_TOL2, "gsl_sf_elljac_e(K/2|0.1) cn");
sa += test_sf_val(dn, C, TEST_TOL2, "gsl_sf_elljac_e(K/2|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(K/2|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(K / 2.0 + eps, m, &sn, &cn, &dn);
sa += test_sf_val(sn, A + eps*B*C, TEST_TOL2, "gsl_sf_elljac_e(K/2+1e-10|0.1) sn");
sa += test_sf_val(cn, B - eps*A*C, TEST_TOL2, "gsl_sf_elljac_e(K/2+1e-10|0.1) cn");
sa += test_sf_val(dn, C - m*eps*A*B, TEST_TOL2, "gsl_sf_elljac_e(K/2+1e-10|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(K/2+1e-10|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(K - eps, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(K-1e-10|0.1) sn");
sa += test_sf_val(cn, eps*C2, 10*TEST_SNGL, "gsl_sf_elljac_e(K-1e-10|0.1) cn");
sa += test_sf_val(dn, C2, TEST_TOL2, "gsl_sf_elljac_e(K-1e-10|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(K-1e-10|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(K, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(K|0.1) sn");
sa += test_sf_val(cn, 0.0, TEST_TOL1, "gsl_sf_elljac_e(K|0.1) cn");
sa += test_sf_val(dn, C2, TEST_TOL2, "gsl_sf_elljac_e(K|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(K|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(K + eps, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(K+1e-10|0.1) sn");
sa += test_sf_val(cn, -eps*C2, 10*TEST_SNGL, "gsl_sf_elljac_e(K+1e-10|0.1) cn");
sa += test_sf_val(dn, C2, TEST_TOL2, "gsl_sf_elljac_e(K+1e-10|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(K+1e-10|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(3.0*K / 2.0, m, &sn, &cn, &dn);
sa += test_sf_val(sn, A, TEST_TOL2, "gsl_sf_elljac_e(3K/2|0.1) sn");
sa += test_sf_val(cn, -B, TEST_TOL2, "gsl_sf_elljac_e(3K/2|0.1) cn");
sa += test_sf_val(dn, C, TEST_TOL2, "gsl_sf_elljac_e(3K/2|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(3K/2|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(2.0*K - eps, m, &sn, &cn, &dn);
sa += test_sf_val(sn, eps, 10*TEST_SNGL, "gsl_sf_elljac_e(2K-1e-10|0.1) sn");
sa += test_sf_val(cn, -1.0, TEST_TOL1, "gsl_sf_elljac_e(2K-1e-10|0.1) cn");
sa += test_sf_val(dn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(2K-1e-10|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(2K-1e-10|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(2.0*K, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 0.0, TEST_TOL1, "gsl_sf_elljac_e(2K|0.1) sn");
sa += test_sf_val(cn, -1.0, TEST_TOL1, "gsl_sf_elljac_e(2K|0.1) cn");
sa += test_sf_val(dn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(2K|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(2K|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(2.0*K + eps, m, &sn, &cn, &dn);
sa += test_sf_val(sn, -eps, 10*TEST_SNGL, "gsl_sf_elljac_e(2K+1e-10|0.1) sn");
sa += test_sf_val(cn, -1.0, TEST_TOL1, "gsl_sf_elljac_e(2K+1e-10|0.1) cn");
sa += test_sf_val(dn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(2K+1e-10|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(2K+1e-10|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(5.0*K / 2.0, m, &sn, &cn, &dn);
sa += test_sf_val(sn, -A, TEST_TOL2, "gsl_sf_elljac_e(5K/2|0.1) sn");
sa += test_sf_val(cn, -B, TEST_TOL2, "gsl_sf_elljac_e(5K/2|0.1) cn");
sa += test_sf_val(dn, C, TEST_TOL2, "gsl_sf_elljac_e(5K/2|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(5K/2|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(3.0*K - eps, m, &sn, &cn, &dn);
sa += test_sf_val(sn, -1.0, TEST_TOL1, "gsl_sf_elljac_e(3K-1e-10|0.1) sn");
sa += test_sf_val(cn, -C2 * eps, 10*TEST_SNGL, "gsl_sf_elljac_e(3K-1e-10|0.1) cn");
sa += test_sf_val(dn, C2, TEST_TOL2, "gsl_sf_elljac_e(3K-1e-10|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(3K-1e-10|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(3.0*K, m, &sn, &cn, &dn);
sa += test_sf_val(sn, -1.0, TEST_TOL1, "gsl_sf_elljac_e(3K|0.1) sn");
sa += test_sf_val(cn, 0.0, TEST_TOL1, "gsl_sf_elljac_e(3K|0.1) cn");
sa += test_sf_val(dn, C2, TEST_TOL2, "gsl_sf_elljac_e(3K|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(3K|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(3.0*K + eps, m, &sn, &cn, &dn);
sa += test_sf_val(sn, -1.0, TEST_TOL1, "gsl_sf_elljac_e(3K+1e-10|0.1) sn");
sa += test_sf_val(cn, +C2 * eps, 10*TEST_SNGL, "gsl_sf_elljac_e(3K+1e-10|0.1) cn");
sa += test_sf_val(dn, C2, TEST_TOL2, "gsl_sf_elljac_e(3K+1e-10|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(3K+1e-10|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(7.0*K / 2.0, m, &sn, &cn, &dn);
sa += test_sf_val(sn, -A, TEST_TOL2, "gsl_sf_elljac_e(7K/2|0.1) sn");
sa += test_sf_val(cn, B, TEST_TOL2, "gsl_sf_elljac_e(7K/2|0.1) cn");
sa += test_sf_val(dn, C, TEST_TOL2, "gsl_sf_elljac_e(7K/2|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(7K/2|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(4.0*K - eps, m, &sn, &cn, &dn);
sa += test_sf_val(sn, -eps, 10*TEST_SNGL, "gsl_sf_elljac_e(4K-1e-10|0.1) sn");
sa += test_sf_val(cn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(4K-1e-10|0.1) cn");
sa += test_sf_val(dn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(4K-1e-10|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(4K-1e-10|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(4.0*K, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 0.0, TEST_TOL1, "gsl_sf_elljac_e(4K|0.1) sn");
sa += test_sf_val(cn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(4K|0.1) cn");
sa += test_sf_val(dn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(4K|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(4K|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(9.0 * K / 2.0, m, &sn, &cn, &dn);
sa += test_sf_val(sn, A, TEST_TOL2, "gsl_sf_elljac_e(9K/2|0.1) sn");
sa += test_sf_val(cn, B, TEST_TOL2, "gsl_sf_elljac_e(9K/2|0.1) cn");
sa += test_sf_val(dn, C, TEST_TOL2, "gsl_sf_elljac_e(9K/2|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(9K/2|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(-K / 2.0, m, &sn, &cn, &dn);
sa += test_sf_val(sn, -A, TEST_TOL2, "gsl_sf_elljac_e(-K/2|0.1) sn");
sa += test_sf_val(cn, B, TEST_TOL2, "gsl_sf_elljac_e(-K/2|0.1) cn");
sa += test_sf_val(dn, C, TEST_TOL2, "gsl_sf_elljac_e(-K/2|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(-K/2|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(-K, m, &sn, &cn, &dn);
sa += test_sf_val(sn, -1.0, TEST_TOL1, "gsl_sf_elljac_e(-K|0.1) sn");
sa += test_sf_val(cn, 0.0, TEST_TOL1, "gsl_sf_elljac_e(-K|0.1) cn");
sa += test_sf_val(dn, C2, TEST_TOL2, "gsl_sf_elljac_e(-K|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(-K|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(-3.0*K / 2.0, m, &sn, &cn, &dn);
sa += test_sf_val(sn, -A, TEST_TOL2, "gsl_sf_elljac_e(-3K/2|0.1) sn");
sa += test_sf_val(cn, -B, TEST_TOL2, "gsl_sf_elljac_e(-3K/2|0.1) cn");
sa += test_sf_val(dn, C, TEST_TOL2, "gsl_sf_elljac_e(-3K/2|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(-3K/2|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(-2.0*K, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 0.0, TEST_TOL1, "gsl_sf_elljac_e(-2K|0.1) sn");
sa += test_sf_val(cn, -1.0, TEST_TOL1, "gsl_sf_elljac_e(-2K|0.1) cn");
sa += test_sf_val(dn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(-2K|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(-2K|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(-5.0*K / 2.0, m, &sn, &cn, &dn);
sa += test_sf_val(sn, A, TEST_TOL2, "gsl_sf_elljac_e(-5K/2|0.1) sn");
sa += test_sf_val(cn, -B, TEST_TOL2, "gsl_sf_elljac_e(-5K/2|0.1) cn");
sa += test_sf_val(dn, C, TEST_TOL2, "gsl_sf_elljac_e(-5K/2|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(-5K/2|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(-3.0*K, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(-3K|0.1) sn");
sa += test_sf_val(cn, 0.0, TEST_TOL1, "gsl_sf_elljac_e(-3K|0.1) cn");
sa += test_sf_val(dn, C2, TEST_TOL2, "gsl_sf_elljac_e(-3K|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(-3K|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(-7.0*K / 2.0, m, &sn, &cn, &dn);
sa += test_sf_val(sn, A, TEST_TOL2, "gsl_sf_elljac_e(-7K/2|0.1) sn");
sa += test_sf_val(cn, B, TEST_TOL2, "gsl_sf_elljac_e(-7K/2|0.1) cn");
sa += test_sf_val(dn, C, TEST_TOL2, "gsl_sf_elljac_e(-7K/2|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(-7K/2|0.1)");
s += sa;
sa = 0;
stat_ej = gsl_sf_elljac_e(-4.0*K, m, &sn, &cn, &dn);
sa += test_sf_val(sn, 0.0, TEST_TOL1, "gsl_sf_elljac_e(-4K|0.1) sn");
sa += test_sf_val(cn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(-4K|0.1) cn");
sa += test_sf_val(dn, 1.0, TEST_TOL1, "gsl_sf_elljac_e(-4K|0.1) dn");
gsl_test(sa, " gsl_sf_elljac_e(-4K|0.1)");
s += sa;
}
return s;
}
int test_laguerre(void)
{
gsl_sf_result r;
int s = 0;
TEST_SF(s, gsl_sf_laguerre_1_e, (0.5, -1.0, &r), 2.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_1_e, (0.5, 1.0, &r), 0.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_1_e, (1.0, 1.0, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_2_e, ( 0.5, -1.0, &r), 4.875, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_2_e, ( 0.5, 1.0, &r), -0.125, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_2_e, ( 1.0, 1.0, &r), 0.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_2_e, (-1.0, 1.0, &r), -0.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_2_e, (-2.0, 1.0, &r), 0.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_2_e, (-3.0, 1.0, &r), 2.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_3_e, (0.5, -1.0, &r), 8.479166666666666667, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_3_e, (0.5, 1.0, &r), -0.6041666666666666667, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_3_e, (1.0, 1.0, &r), -0.16666666666666666667, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_3_e, ( 2.0, 1.0, &r), 2.3333333333333333333, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_3_e, (-2.0, 1.0, &r), 1.0/3.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_3_e, (-3.0, 1.0, &r), -1.0/6.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_3_e, (-4.0, 1.0, &r), -8.0/3.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (1, 0.5, 1.0, &r), 0.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (2, 1.0, 1.0, &r), 0.5, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (3, 2.0, 1.0, &r), 2.3333333333333333333, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (4, 2.0, 0.5, &r), 6.752604166666666667, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (90, 2.0, 0.5, &r), -48.79047157201507897, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (90, 2.0, -100.0, &r), 2.5295879275042410902e+63, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (90, 2.0, 100.0, &r), -2.0929042259546928670e+20, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, 2.0, -0.5, &r), 2.2521795545919391405e+07, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, 2.0, 0.5, &r), -28.764832945909097418, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (1000, 2.0, -0.5, &r), 2.4399915170947549589e+21, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (1000, 2.0, 0.5, &r), -306.77440254315317525, TEST_TOL2, GSL_SUCCESS); /**/
TEST_SF(s, gsl_sf_laguerre_n_e, (100000, 2.0, 1.0, &r), 5107.73491348319, TEST_TOL4, GSL_SUCCESS);
/* Compute these with the recurrence
* L(0,alpha,x)=1;
* L(1,alpha,x)=1+alpha-x;
* L(n,alpha,x)=((2*n-1+alpha-x)*L(n-1,alpha,x)-(n+alpha-1)*L(n-2,alpha,x))/k
*/
TEST_SF(s, gsl_sf_laguerre_n_e, (1e5, 2.5, 2.5, &r), -0.41491680394598644969113795e5, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (1e5+1, 2.5, 2.5, &r), -0.41629446949552321027514888e5, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (1e6+1, 2.5, 2.5, &r), -0.48017961545391273151977118e6, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (5e6+1, 2.5, 2.5, &r), -0.15174037401611122446089494e7, TEST_TOL6, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (8e6+1, 2.5, 2.5, &r), 0.63251509472091810994286362e6, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (1e7+1, 2.5, 2.5, &r), 0.15299484685632983178033887e7, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (1e8+1, 2.5, 2.5, &r), 0.23645341644922756725290777e8, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (1e9+1, 2.5, 2.5, &r), -0.17731002248958790286185878e8, 100*TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (1, -2.0, 1.0, &r), -2.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (2, -2.0, 1.0, &r), 0.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (3, -2.0, 1.0, &r), 1.0/3.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (10, -2.0, 1.0, &r), -0.04654954805996472663, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (10, -5.0, 1.0, &r), -0.0031385030864197530864, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (10, -9.0, 1.0, &r), -2.480158730158730159e-06, TEST_TOL5, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (10, -11.0, 1.0, &r), 2.7182818011463844797, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (10, -11.0, -1.0, &r), 0.3678794642857142857, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -2.0, 1.0, &r), -0.0027339992019526273866, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -2.0, -1.0, &r), 229923.09193402028290, TEST_TOL5, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -10.0, 1.0, &r), 3.25966665871244092e-11, TEST_TOL6, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -10.0, -1.0, &r), 0.00016484365618205810025, TEST_TOL6, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -20.0, 1.0, &r), 5.09567630343671251e-21, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -30.0, 1.0, &r), 3.46063150272466192e-34, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -50.0, 1.0, &r), 1.20981872933162889e-65, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -50.0, -1.0, &r), 8.60763477742332922e-65, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -50.5, 1.0, &r), 4.84021010426688393e-31, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -50.5, -1.0, &r), 8.49861345212160618e-33, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -101.0, 1.0, &r), 2.7182818284590452354, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -101.0, -1.0, &r), 0.3678794411714423216, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -102.0, 1.0, &r), 271.8281828459045235, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -102.0, -1.0, &r), 37.52370299948711680, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -110.0, 1.0, &r), 1.0666955248998831554e+13, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -110.0, -1.0, &r), 1.7028306108058225871e+12, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -200.0, 1.0, &r), 7.47851889721356628e+58, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -200.0, -1.0, &r), 2.73740299754732273e+58, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -50.0, 10.0, &r), 4.504712811317745591e-21, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, -50.0, -10.0, &r), 1.475165520610679937e-11, TEST_TOL1, GSL_SUCCESS);
/* test cases for Ed Smith-Rowland */
TEST_SF(s, gsl_sf_laguerre_n_e, (100, 0.0, 0.5, &r), 0.18682260367692278801, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, 0.0, 10.5, &r), 9.1796907354050059874, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, 0.0, -10.5, &r), 5.6329215744170606488e24, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, 0.0, 100.5, &r), -3.9844782875811907525e20, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_laguerre_n_e, (100, 0.0, 150, &r), -1.4463204337261709595e31, TEST_TOL2, GSL_SUCCESS);
return s;
}
int test_lambert(void)
{
gsl_sf_result r;
int s = 0;
TEST_SF(s, gsl_sf_lambert_W0_e, (0.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_W0_e, (1.0, &r), 0.567143290409783872999969, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_W0_e, (2.0, &r), 0.852605502013725491346472, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_W0_e, (20.0, &r), 2.205003278024059970493066, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_W0_e, (1000.0, &r), 5.24960285240159622712606, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_W0_e, (1.0e+6, &r), 11.38335808614005262200016, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_W0_e, (1.0e+12, &r), 24.43500440493491313826305, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_W0_e, (1.0e+308, &r), 702.641362034106812081125, TEST_TOL0, GSL_SUCCESS);
/* Test case from Katrin Wolff <katrin_wolff@gmx.de> fails under
double-precision */
TEST_SF(s, gsl_sf_lambert_W0_e, (1.6849341956993852953416990, &r), 0.775706963944252869680440, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_W0_e, (-1.0/M_E - GSL_DBL_EPSILON, &r), -1.0, TEST_TOL0, GSL_EDOM);
TEST_SF(s, gsl_sf_lambert_W0_e, (-1.0/M_E + 1.0/(1024.0*1024.0*1024.0), &r), -0.999928845560308370714970, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_W0_e, (-1.0/M_E + 1.0/(1024.0*1024.0), &r), -0.997724730359774141620354, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_W0_e, (-1.0/M_E + 1.0/512.0, &r), -0.900335676696088773044678, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_W0_e, (-1.0/M_E + 0.25, &r), -0.1349044682661213545487599, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_Wm1_e, (0.0, &r), 0.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_Wm1_e, (1.0, &r), 0.567143290409783872999969, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_Wm1_e, (2.0, &r), 0.852605502013725491346472, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_Wm1_e, (20.0, &r), 2.205003278024059970493066, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_Wm1_e, (-1.0/M_E - GSL_DBL_EPSILON, &r), -1.0, TEST_TOL0, GSL_EDOM);
TEST_SF(s, gsl_sf_lambert_Wm1_e, (-1.0/M_E + 1.0/(1024.0*1024.0*1024.0), &r), -1.000071157815154608049055, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_Wm1_e, (-1.0/M_E + 1.0/(1024.0*1024.0), &r), -1.002278726118593023934693, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_Wm1_e, (-1.0/M_E + 1.0/512.0, &r), -1.106761200865743124599130, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_Wm1_e, (-1.0/M_E + 1.0/64.0, &r), -1.324240940341812125489772, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lambert_Wm1_e, (-1.0/M_E + 0.25, &r), -3.345798131120112, TEST_TOL1, GSL_SUCCESS);
return s;
}
int test_log(void)
{
gsl_sf_result r;
gsl_sf_result r1, r2;
int s = 0;
TEST_SF(s, gsl_sf_log_e, (0.1, &r), -2.3025850929940456840, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_e, (1.1, &r), 0.09531017980432486004, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_e, (1000.0, &r), 6.907755278982137052, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_abs_e, (-0.1, &r), -2.3025850929940456840, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_abs_e, (-1.1, &r), 0.09531017980432486004, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_abs_e, (-1000.0, &r), 6.907755278982137052, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_abs_e, (0.1, &r), -2.3025850929940456840, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_abs_e, (1.1, &r), 0.09531017980432486004, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_abs_e, (1000.0, &r), 6.907755278982137052, TEST_TOL0, GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_log_e, (1.0, 1.0, &r1, &r2),
0.3465735902799726547, TEST_TOL0,
0.7853981633974483096, TEST_TOL0,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_log_e, (1.0, -1.0, &r1, &r2),
0.3465735902799726547, TEST_TOL0,
-0.7853981633974483096, TEST_TOL0,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_log_e, (1.0, 100.0, &r1, &r2),
4.605220183488258022, TEST_TOL0,
1.560796660108231381, TEST_TOL0,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_log_e, (-1000.0, -1.0, &r1, &r2),
6.907755778981887052, TEST_TOL0,
-3.1405926539231263718, TEST_TOL0,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_log_e, (-1.0, 0.0, &r1, &r2),
0.0, TEST_TOL0,
3.1415926535897932385, TEST_TOL0,
GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_e, (1.0e-10, &r), 9.999999999500000000e-11, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_e, (1.0e-8, &r), 9.999999950000000333e-09, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_e, (1.0e-4, &r), 0.00009999500033330833533, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_e, (0.1, &r), 0.09531017980432486004, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_e, (0.49, &r), 0.3987761199573677730, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_e, (-0.49, &r), -0.6733445532637655964, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_e, (1.0, &r), M_LN2, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_e, (-0.99, &r), -4.605170185988091368, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_mx_e, (1.0e-10, &r), -4.999999999666666667e-21, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_mx_e, (1.0e-8, &r), -4.999999966666666917e-17, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_mx_e, (1.0e-4, &r), -4.999666691664666833e-09, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_mx_e, (0.1, &r), -0.004689820195675139956, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_mx_e, (0.49, &r), -0.09122388004263222704, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_mx_e, (-0.49, &r), -0.18334455326376559639, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_mx_e, (1.0, &r), M_LN2-1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_log_1plusx_mx_e, (-0.99, &r), -3.615170185988091368, TEST_TOL0, GSL_SUCCESS);
return s;
}
int test_pow_int(void)
{
gsl_sf_result r;
int status = 0;
int s = 0;
TEST_SF(s, gsl_sf_pow_int_e, (2.0, 3, &r), 8.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (-2.0, 3, &r), -8.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (2.0, -3, &r), 1.0/8.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (-2.0, -3, &r), -1.0/8.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (10.0, 4, &r), 1.0e+4, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (10.0, -4, &r), 1.0e-4, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (-10.0, 4, &r), 1.0e+4, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (-10.0, -4, &r), 1.0e-4, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (10.0, 40, &r), 1.0e+40, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (8.0, -40, &r), 7.523163845262640051e-37, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (-10.0, 40, &r), 1.0e+40, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (-8.0, -40, &r), 7.523163845262640051e-37, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (10.0, 41, &r), 1.0e+41, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (8.0, -41, &r), 9.403954806578300064e-38, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (-10.0, 41, &r), -1.0e+41, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_pow_int_e, (-8.0, -41, &r), -9.403954806578300064e-38, TEST_TOL0, GSL_SUCCESS);
return status;
}
int test_psi(void)
{
gsl_sf_result r;
int s = 0;
/* Test values taken 1-4 from gp-pari */
TEST_SF(s, gsl_sf_psi_int_e, (1, &r), -0.57721566490153286060, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_int_e, (2, &r), 0.42278433509846713939, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_int_e, (3, &r), 0.92278433509846713939, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_int_e, (4, &r), 1.2561176684318004727, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_int_e, (5, &r), 1.5061176684318004727, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_int_e, (100, &r), 4.600161852738087400, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_int_e, (110, &r), 4.695928024251535633, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_int_e, (5000, &r), 8.517093188082904107, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_e, (5000.0, &r), 8.517093188082904107, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_e, (5.0, &r), 1.5061176684318004727, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_e, (-10.5, &r), 2.3982391295357816134, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_e, (-100.5, &r), 4.615124601338064117, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_e, (-1.0e+5-0.5, &r), 11.512935464924395337, 4.0*TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_e, (-262144.0-0.5, &r), 12.476653064769611581, 4.0*TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1piy_e, (0.8, &r), -0.07088340212750589223, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1piy_e, (1.0, &r), 0.09465032062247697727, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1piy_e, (5.0, &r), 1.6127848446157465854, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1piy_e, (100.0, &r), 4.605178519404762003, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1piy_e, (2000.0, &r), 7.600902480375416216, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1piy_e, (-0.8, &r), -0.07088340212750589223, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1piy_e, (-1.0, &r), 0.09465032062247697727, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1piy_e, (-5.0, &r), 1.6127848446157465854, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1piy_e, (-100.0, &r), 4.605178519404762003, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1piy_e, (-2000.0, &r), 7.600902480375416216, TEST_TOL0, GSL_SUCCESS);
/* Additional test values 1-4 computed using gp-pari and
Abramowitz & Stegun 6.4.6 */
TEST_SF(s, gsl_sf_psi_1_int_e, (1, &r), 1.6449340668482264364, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_int_e, (2, &r), 0.64493406684822643647, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_int_e, (3, &r), 0.39493406684822643647, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_int_e, (4, &r), 0.28382295573711532536, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_int_e, (1, &r), 1.6449340668482264365, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_int_e, (5, &r), 0.22132295573711532536, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_int_e, (100, &r), 0.010050166663333571395, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_int_e, (110, &r), 0.009132356622022545705, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_int_e, (500, &r), 0.0020020013333322666697, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_e, (1.0/32.0, &r), 1025.5728544782377089, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_e, (1.0, &r), 1.6449340668482264365, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_e, (5.0, &r), 0.22132295573711532536, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_e, (100.0, &r), 0.010050166663333571395, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_e, (110.0, &r), 0.009132356622022545705, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_e, (500.0, &r), 0.0020020013333322666697, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_e, (-1.0 - 1.0/128.0, &r), 16386.648472598746587, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_e, (-1.50, &r), 9.3792466449891237539, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_e, (-10.5, &r), 9.7787577398148123845, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_e, (-15.5, &r), 9.8071247184113896201, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_e, (-50.5, &r), 9.8499971860824842274, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_1_e, (-1000.5, &r), 9.8686054001734414233, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (1, 1, &r), 1.6449340668482264364, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (1, 2, &r), 0.64493406684822643647, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (1, 3, &r), 0.39493406684822643647, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (1, 4, &r), 0.28382295573711532536, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (1, 5, &r), 0.22132295573711532536, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (1, 100, &r), 0.010050166663333571395, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (1, 110, &r), 0.009132356622022545705, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (1, 500, &r), 0.0020020013333322666697, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (3, 5.0, &r), 0.021427828192755075022, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (3, 500.0, &r), 1.6048063999872000683e-08, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (10, 5.0, &r), -0.08675107579196581317, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (10, 50.0, &r), -4.101091112731268288e-12, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (0, -1.5, &r), 0.70315664064524318723, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_psi_n_e, (1, -1.5, &r), 9.3792466449891237539, TEST_TOL0, GSL_SUCCESS);
return s;
}
int test_psi_complex(void)
{
gsl_sf_result r1;
gsl_sf_result r2;
int s = 0;
TEST_SF_2(s, gsl_sf_complex_psi_e, (1.0e+07, 1.0e+06, &r1, &r2),
16.1230707668799525, TEST_TOL0,
0.09966865744165720, TEST_TOL0,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_psi_e, (10.0, 50.0, &r1, &r2),
3.92973987174863660, TEST_TOL0,
1.38302847985210276, TEST_TOL0,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_psi_e, (2.0, 21.0, &r1, &r2),
3.04697388853248195, TEST_TOL0,
1.49947549076817824, TEST_TOL0,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_psi_e, (1.5, 0.0, &r1, &r2),
0.0364899739785765206, TEST_TOL2,
0.0, TEST_TOL1,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_psi_e, (1.0, 5.0, &r1, &r2),
1.612784844615747, TEST_TOL1,
1.470796326794968, TEST_TOL1,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_psi_e, (-1.5, 5.0, &r1, &r2),
1.68260717336484070, TEST_TOL0,
1.95230236730713338, TEST_TOL0,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_psi_e, (-20.5, -20.5, &r1, &r2),
3.37919358657933066, TEST_TOL0,
-2.36829046481731091, TEST_TOL0,
GSL_SUCCESS);
return s;
}
int test_synch(void)
{
gsl_sf_result r;
int s = 0;
TEST_SF(s, gsl_sf_synchrotron_1_e, (0.01, &r), 0.444972504114210632, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_synchrotron_1_e, (1.0, &r), 0.651422815355364504, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_synchrotron_1_e, (10.0, &r), 0.000192238264300868882, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_synchrotron_1_e, (100.0, &r), 4.69759366592220221e-43, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_synchrotron_2_e, (0.01, &r), 0.23098077342226277732, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_synchrotron_2_e, (1.0, &r), 0.4944750621042082670, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_synchrotron_2_e, (10.0, &r), 0.00018161187569530204281, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_synchrotron_2_e, (256.0, &r), 1.3272635474353774058e-110, TEST_TOL4, GSL_SUCCESS); /* exp()... not my fault */
return s;
}
int test_transport(void)
{
gsl_sf_result r;
int s = 0;
TEST_SF(s, gsl_sf_transport_2_e, (1.0e-10, &r), 9.9999999999999999999e-11, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_2_e, (1.0, &r), 0.97303256135517012845, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_2_e, (3.0, &r), 2.41105004901695346199, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_2_e, (10.0, &r), 3.28432911449795173575, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_2_e, (100.0, &r), 3.28986813369645287294, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_2_e, (1.0e+05, &r), 3.28986813369645287294, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_3_e, (1.0e-10, &r), 4.999999999999999999997e-21, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_3_e, (1.0, &r), 0.479841006572417499939, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_3_e, (3.0, &r), 3.210604662942246772338, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_3_e, (5.0, &r), 5.614386613842273228585, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_3_e, (10.0, &r), 7.150322712008592975030, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_3_e, (30.0, &r), 7.212341416160946511930, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_3_e, (100.0, &r), 7.212341418957565712398, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_3_e, (1.0e+05, &r), 7.212341418957565712398, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_4_e, (1.0e-10, &r), 3.33333333333333333333e-31, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_4_e, (1.0e-07, &r), 3.33333333333333166666e-22, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_4_e, (1.0e-04, &r), 3.33333333166666666726e-13, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_4_e, (0.1, &r), 0.000333166726172109903824, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_4_e, (1.0, &r), 0.31724404523442648241, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_4_e, (3.0, &r), 5.96482239737147652446, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_4_e, (5.0, &r), 15.3597843168821829816, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_4_e, (10.0, &r), 25.2736676770304417334, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_4_e, (30.0, &r), 25.9757575220840937469, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_4_e, (100.0, &r), 25.9757576090673165963, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_4_e, (1.0e+05, &r), 25.9757576090673165963, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_5_e, (1.0e-10, &r), 2.49999999999999999999e-41, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_5_e, (1.0e-07, &r), 2.49999999999999861111e-29, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_5_e, (1.0e-04, &r), 2.49999999861111111163e-17, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_5_e, (0.1, &r), 0.000024986116317791487410, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_5_e, (1.0, &r), 0.236615879239094789259153, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_5_e, (3.0, &r), 12.77055769104415951115760, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_5_e, (5.0, &r), 50.26309221817518778543615, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_5_e, (10.0, &r), 116.3807454024207107698556, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_5_e, (30.0, &r), 124.4313279083858954839911, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_5_e, (100.0, &r), 124.4313306172043911597639, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_transport_5_e, (1.0e+05, &r), 124.43133061720439115976, TEST_TOL0, GSL_SUCCESS);
return s;
}
int test_trig(void)
{
gsl_sf_result r;
gsl_sf_result r1, r2;
double theta;
int s = 0;
int sa;
TEST_SF(s, gsl_sf_sin_e, (-10.0, &r), 0.5440211108893698134, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sin_e, (1.0, &r), 0.8414709848078965067, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sin_e, (1000.0, &r), 0.8268795405320025603, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sin_e, (1048576.75, &r), 0.8851545351115651914, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sin_e, (62831853.75, &r), 0.6273955953485000827, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sin_e, (1073741822.5, &r), -0.8284043541754465988, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sin_e, (1073741824.0, &r), -0.6173264150460421708, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sin_e, (1073741825.5, &r), 0.7410684679436226926, TEST_SQRT_TOL0, GSL_SUCCESS);
/*
TEST_SF(s, gsl_sf_sin_e, (1099511627776.0, &r), -0.4057050115328287198, 32.0*TEST_SQRT_TOL0, GSL_SUCCESS);
*/
TEST_SF(s, gsl_sf_cos_e, (-10.0, &r), -0.8390715290764524523, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_cos_e, (1.0, &r), 0.5403023058681397174, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_cos_e, (1000.0, &r), 0.5623790762907029911, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_cos_e, (1048576.75, &r), 0.4652971620066351799, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_cos_e, (62831853.75, &r), 0.7787006914966116436, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_cos_e, (1073741822.5, &r), -0.5601305436977716102, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_cos_e, (1073741824.0, &r), 0.7867071229411881196, TEST_SQRT_TOL0, GSL_SUCCESS);
/*
TEST_SF(s, gsl_sf_cos_e, (1099511627776.0, &r), -0.9140040719915570023, 128.0*TEST_SQRT_TOL0, GSL_SUCCESS);
*/
TEST_SF(s, gsl_sf_sinc_e, (1.0/1024.0, &r), 0.9999984312693665404, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sinc_e, (1.0/2.0, &r), 2.0/M_PI, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sinc_e, (80.5, &r), 0.0039541600768172754, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sinc_e, (100.5, &r), 0.0031672625490924445, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sinc_e, (1.0e+06 + 0.5, &r), 3.18309727028927157e-07, TEST_TOL0, GSL_SUCCESS);
/*
TEST_SF(s, gsl_sf_sin_pi_x_e, (1000.5, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sin_pi_x_e, (10000.0 + 1.0/65536.0, &r), 0.00004793689960306688455, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_sin_pi_x_e, (1099511627776.0 + 1 + 0.125, &r), -0.3826834323650897717, TEST_TOL0, GSL_SUCCESS);
*/
TEST_SF_2(s, gsl_sf_complex_sin_e, (1.0, 5.0, &r1, &r2),
62.44551846769653403, TEST_TOL0,
40.09216577799840254, TEST_TOL0,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_cos_e, (1.0, 5.0, &r1, &r2),
40.09580630629882573, TEST_TOL0,
-62.43984868079963017, TEST_TOL0,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_logsin_e, (1.0, 100.0, &r1, &r2),
99.3068528194400546900, TEST_TOL0,
0.5707963267948966192, TEST_TOL0,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_logsin_e, (1.0, -100.0, &r1, &r2),
99.3068528194400546900, TEST_TOL1,
-0.5707963267948966192, TEST_TOL1,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_complex_logsin_e, (5.0, 5.0, &r1, &r2),
4.3068909128079757420, TEST_TOL0,
2.8540063315538773952, TEST_TOL0,
GSL_SUCCESS);
TEST_SF(s, gsl_sf_lnsinh_e, (0.1, &r), -2.3009189815304652235, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lnsinh_e, (1.0, &r), 0.16143936157119563361, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lnsinh_e, (5.0, &r), 4.306807418479684201, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lnsinh_e, (100.0, &r), 99.30685281944005469, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lncosh_e, (0.125, &r), 0.007792239318898252791, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lncosh_e, (1.0, &r), 0.4337808304830271870, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lncosh_e, (5.0, &r), 4.306898218339271555, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lncosh_e, (100.0, &r), 99.30685281944005469, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lncosh_e, (1000.0, &r), 999.30685281944005469, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lncosh_e, (-0.125, &r), 0.007792239318898252791, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lncosh_e, (-1.0, &r), 0.4337808304830271870, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lncosh_e, (-5.0, &r), 4.306898218339271555, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lncosh_e, (-100.0, &r), 99.30685281944005469, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_lncosh_e, (-1000.0, &r), 999.30685281944005469, TEST_TOL0, GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_polar_to_rect, (10.0, M_PI/6.0, &r1, &r2),
(10.0 * sqrt(3) / 2.0), TEST_TOL0,
(10.0 * 0.5), TEST_TOL0,
GSL_SUCCESS);
TEST_SF_2(s, gsl_sf_polar_to_rect, (10.0, -2.0/3.0*M_PI, &r1, &r2),
(10.0 * (-0.5)), TEST_TOL1,
(10.0 * (-sqrt(3.0)/2.0)), TEST_TOL1,
GSL_SUCCESS);
/* In double precision M_PI = \pi - 1.2246467991473531772e-16,
i.e. the nearest machine number is slightly below the exact value
of \pi. The true value of \pi satisfies
M_PI < \pi < nextafter(M_PI,+Inf)
where nextafter(M_PI,+Inf) = M_PI + 2*DBL_EPSILON
This also means that 2*M_PI is less than \pi by 2.449e-16. The
true value of 2\pi satisfies
2*M_PI < 2\pi < nextafter(2*M_PI,+Inf)
where nextafter(2*M_PI,+Inf) = 2*M_PI + 4*DBL_EPSILON
BJG 25/9/06
*/
#define DELTA (1.2246467991473531772e-16)
TEST_SF_THETA(s, gsl_sf_angle_restrict_pos_e, (2.0*M_PI), 2*M_PI, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_pos_e, (-2.0*M_PI), 2*DELTA, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_pos_e, (2.0*M_PI+4*GSL_DBL_EPSILON), 4*GSL_DBL_EPSILON-2*DELTA, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_pos_e, (-2.0*M_PI-4*GSL_DBL_EPSILON), 2*M_PI-4*GSL_DBL_EPSILON+2*DELTA, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_pos_e, (4.0*M_PI+8*GSL_DBL_EPSILON), 8*GSL_DBL_EPSILON-4*DELTA, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_pos_e, (-4.0*M_PI-8*GSL_DBL_EPSILON), 2*M_PI-8*GSL_DBL_EPSILON+4*DELTA, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_pos_e, (1e9), 0.5773954235013851694, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_pos_e, (1e12), 5.625560548042800009446, TEST_SNGL);
TEST_SF_THETA(s, gsl_sf_angle_restrict_pos_e, (-1e9), 5.7057898836782013075, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_pos_e, (-1e12), 0.6576247591367864674792517289, 100*TEST_SNGL);
#ifdef EXTENDED
TEST_SF_THETA(s, gsl_sf_angle_restrict_pos_e, (1e15), 2.1096981170701125979, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_pos_e, (-1e15), 4.1734871901094738790, TEST_TOL1);
#endif
TEST_SF(s, gsl_sf_angle_restrict_pos_err_e, (2.0*M_PI, &r), 2*M_PI, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_angle_restrict_pos_err_e, (-2.0*M_PI, &r), 2*DELTA, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_angle_restrict_pos_err_e, (1e9, &r), 0.5773954235013851694, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_angle_restrict_pos_err_e, (1e12, &r), 5.625560548042800009446, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_angle_restrict_pos_err_e, (-1e9, &r), 5.7057898836782013075, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_angle_restrict_pos_err_e, (-1e12, &r), 0.6576247591367864674792517289, 100*TEST_SNGL, GSL_SUCCESS);
TEST_SF (s, gsl_sf_angle_restrict_pos_err_e, (1e15, &r), GSL_NAN, TEST_TOL1, GSL_ELOSS);
TEST_SF (s, gsl_sf_angle_restrict_pos_err_e, (-1e15, &r), GSL_NAN, TEST_TOL1, GSL_ELOSS);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (2.0*M_PI), -2*DELTA, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (-2.0*M_PI), 2*DELTA, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (M_PI), M_PI, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (-M_PI), -M_PI, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (M_PI+2*GSL_DBL_EPSILON), -M_PI+2*(GSL_DBL_EPSILON-DELTA), TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (-M_PI-2*GSL_DBL_EPSILON), M_PI-2*(GSL_DBL_EPSILON-DELTA), TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (3*M_PI+6*GSL_DBL_EPSILON), -M_PI+6*GSL_DBL_EPSILON-4*DELTA, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (-3*M_PI-6*GSL_DBL_EPSILON), M_PI-6*GSL_DBL_EPSILON+4*DELTA, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (1e9), 0.5773954235013851694, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (1e12), -0.6576247591367864674792517289, 100*TEST_SNGL);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (-1e9), -0.5773954235013851694, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (-1e12), 0.6576247591367864674792517289, 100*TEST_SNGL);
#ifdef EXTENDED
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (1e15), 2.1096981170701125979, TEST_TOL1);
TEST_SF_THETA(s, gsl_sf_angle_restrict_symm_e, (-1e15), -2.1096981170701125979, TEST_TOL1);
#endif
TEST_SF (s, gsl_sf_angle_restrict_symm_err_e, (2.0*M_PI, &r), -2*DELTA, TEST_TOL1, GSL_SUCCESS);
TEST_SF (s, gsl_sf_angle_restrict_symm_err_e, (-2.0*M_PI, &r), 2*DELTA, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_angle_restrict_symm_err_e, (1e9, &r), 0.5773954235013851694, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_angle_restrict_symm_err_e, (1e12, &r), -0.6576247591367864674792517289, 100*TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_angle_restrict_symm_err_e, (-1e9, &r), -0.5773954235013851694, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_angle_restrict_symm_err_e, (-1e12, &r), 0.6576247591367864674792517289, 100*TEST_SNGL, GSL_SUCCESS);
TEST_SF (s, gsl_sf_angle_restrict_symm_err_e, (1e15, &r), GSL_NAN, TEST_TOL1, GSL_ELOSS);
TEST_SF (s, gsl_sf_angle_restrict_symm_err_e, (-1e15, &r), GSL_NAN, TEST_TOL1, GSL_ELOSS);
theta = 5.0*M_PI + 5*DELTA + M_PI/2.0;
gsl_sf_angle_restrict_pos_e(&theta);
sa = 0;
sa += ( test_sf_frac_diff( theta, 3.0/2.0*M_PI ) > TEST_TOL0 );
gsl_test(sa, " gsl_angle_restrict_pos_e: theta = 11/2 Pi");
s += sa;
theta = -5.0*M_PI - 5*DELTA - M_PI/2.0;
gsl_sf_angle_restrict_pos_e(&theta);
sa = 0;
sa += ( test_sf_frac_diff( theta, M_PI/2.0 ) > 2.0*TEST_TOL0 );
gsl_test(sa, " gsl_angle_restrict_pos_e: theta = -11/2 Pi");
s += sa;
theta = 50000.0 + 1.0/65536.0;
gsl_sf_angle_restrict_pos_e(&theta);
sa = 0;
sa += ( test_sf_frac_diff( theta, 4.6945260308194656055 ) > TEST_TOL0 );
gsl_test(sa, " gsl_angle_restrict_pos_e: theta = 50000.0 + 1.0/65536.0");
s += sa;
theta = 5000000.0 + 1.0/65536.0;
gsl_sf_angle_restrict_pos_e(&theta);
sa = 0;
sa += ( test_sf_frac_diff( theta, 4.49537973053997376 ) > TEST_TOL0 );
gsl_test(sa, " gsl_angle_restrict_pos_e: theta = 5000000.0 + 1.0/65536.0");
s += sa;
/*
theta = 140737488355328.0;
gsl_sf_angle_restrict_pos_e(&theta);
sa = 0;
sa += ( test_sf_frac_diff( theta, 3.20652300406795792638 ) > TEST_TOL0 );
gsl_test(sa, " gsl_angle_restrict_pos_e: theta = 2^47");
s += sa;
*/
theta = 5.0*M_PI + (5.5*DELTA + M_PI/2.0);
gsl_sf_angle_restrict_symm_e(&theta);
sa = 0;
sa += ( test_sf_frac_diff( theta, -M_PI/2.0 ) > 2.0*TEST_TOL0 );
gsl_test(sa, " gsl_angle_restrict_symm_e: theta = 11/2 Pi");
s += sa;
theta = -5.0*M_PI - (5.5*DELTA + M_PI/2.0);
gsl_sf_angle_restrict_symm_e(&theta);
sa = 0;
sa += ( test_sf_frac_diff( theta, M_PI/2.0 ) > 2.0*TEST_TOL0 );
gsl_test(sa, " gsl_angle_restrict_symm_e: theta = -11/2 Pi");
s += sa;
theta = 5.0*M_PI + 5*DELTA - M_PI/2.0;
gsl_sf_angle_restrict_symm_e(&theta);
sa = 0;
sa += ( test_sf_frac_diff( theta, M_PI/2.0 ) > TEST_TOL0 );
gsl_test(sa, " gsl_angle_restrict_symm_e: theta = -9/2 Pi");
s += sa;
theta = 3.0/2.0*M_PI + 3.0/2.0*DELTA;
gsl_sf_angle_restrict_symm_e(&theta);
sa = 0;
sa += ( test_sf_frac_diff( theta, -M_PI/2.0 ) > TEST_TOL0 );
gsl_test(sa, " gsl_angle_restrict_symm_e: theta = 3/2 Pi");
s += sa;
theta = -3.0/2.0*M_PI;
gsl_sf_angle_restrict_symm_e(&theta);
sa = 0;
sa += ( test_sf_frac_diff( theta, M_PI/2.0 ) > TEST_TOL0 );
gsl_test(sa, " gsl_angle_restrict_symm_e: theta = -3/2 Pi");
s += sa;
theta = 50000.0 + 1.0/65536.0;
gsl_sf_angle_restrict_symm_e(&theta);
sa = 0;
sa += ( test_sf_frac_diff( theta, -1.5886592763601208714 ) > TEST_TOL0 );
gsl_test(sa, " gsl_angle_restrict_symm_e: theta = 50000.0 + 1.0/65536.0");
s += sa;
return s;
}
/* I computed the values of zeta for s = -1e-10, 0, 1e-10 using the
Jensen formula,
zeta(s) = -1/2 + 1/(1-s)
+ integ(sin(s arctan(t))/((1+t^2)^(s/2)(exp(2pi*t)-1)), t, 0, inf)
transforming the integral from a semi-infinite range to the range
[0,pi/2] using the substitution t = tan(u). After Taylor expansion
in s and numerical evaluation of the integrals this gave,
zeta(s) = 1/2 + 1/(1-s)
+ (0.0810614667944862 +/- 2e-16) s
+ (-3.17822795429232e-3 +/- 2e-17) s^2
+ ....
for an expansion about s = 0 [BJG 7/01]
*/
int test_zeta(void)
{
gsl_sf_result r;
int s = 0;
TEST_SF(s, gsl_sf_zeta_int_e, (-61.0, &r), -3.30660898765775767257e+34, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_int_e, (-8, &r), 0.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_int_e, (-6, &r), 0.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_int_e, (-5.0, &r), -0.003968253968253968253968, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_int_e, (-4, &r), 0.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_int_e, (-3, &r), 1.0/120.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_int_e, (-2, &r), 0.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_int_e, (-1, &r), -1.0/12.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_int_e, ( 5.0, &r), 1.0369277551433699263313655, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_int_e, (31.0, &r), 1.0000000004656629065033784, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_int_e, (-61.0, &r), -3.30660898765775767257e+34, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_int_e, (-5.0, &r), -1.003968253968253968253968, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_int_e, (-8, &r), -1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_int_e, (-6, &r), -1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_int_e, (-4, &r), -1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_int_e, (-3, &r), -119.0/120.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_int_e, (-2, &r), -1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_int_e, (-1, &r), -13.0/12.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_int_e, ( 5.0, &r), 0.0369277551433699263313655, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_int_e, (31.0, &r), 0.0000000004656629065033784, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (-151, &r), 8.195215221831378294e+143, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (-51, &r), 9.68995788746359406565e+24, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (-5, &r), -0.003968253968253968253968, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (-8, &r), 0.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (-6, &r), 0.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (-4, &r), 0.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (-3, &r), 1.0/120.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (-2, &r), 0.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (-1, &r), -1.0/12.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (-0.5, &r), -0.207886224977354566017307, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (-1e-10, &r), -0.49999999990810614668948, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (0.0, &r), -0.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (1e-10, &r), -0.50000000009189385333058, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (0.5, &r), -1.460354508809586812889499, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (1.0-1.0/1024.0, &r), -1023.4228554489429787, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (1.0+1.0/1048576, &r), 1.0485765772157343441e+06, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (5.0, &r), 1.036927755143369926331365, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zeta_e, (25.5, &r), 1.000000021074106110269959, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (-8, &r), -1.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (-6, &r), -1.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (-4, &r), -1.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (-3, &r), -119.0/120.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (-2, &r), -1.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (-1, &r), -13.0/12.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (-0.5, &r), -1.207886224977354566017307, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (-1e-10, &r), -1.49999999990810614668948, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (0.0, &r), -1.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (1e-10, &r), -1.50000000009189385333058, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (0.5, &r), -2.460354508809586812889499, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (2.0, &r), 0.64493406684822643647, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (3.0, &r), 0.20205690315959428540, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (5.0, &r), 0.0369277551433699263314, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (9.5, &r), 0.0014125906121736622712, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (10.5, &r), 0.000700842641736155219500, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (12.5, &r), 0.000173751733643178193390, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (13.5, &r), 0.000086686727462338155188, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (15.5, &r), 0.000021619904246069108133, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (16.5, &r), 0.000010803124900178547671, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_zetam1_e, (25.5, &r), 0.000000021074106110269959, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hzeta_e, (2, 1.0, &r), 1.6449340668482264365, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hzeta_e, (2, 10.0, &r), 0.1051663356816857461, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hzeta_e, (5, 1.0, &r), 1.0369277551433699263, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hzeta_e, (5, 10.0, &r), 0.000030413798676470276, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hzeta_e, (9, 0.1, &r), 1.0000000004253980e+09, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hzeta_e, (30, 0.5, &r), 1.0737418240000053e+09, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hzeta_e, (30, 0.9, &r), 2.3589824880264765e+01, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hzeta_e, (75, 0.25, &r), 1.4272476927059599e+45, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_int_e, (-91, &r), -4.945598888750002040e+94, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_int_e, (-51, &r), -4.363969073121683116e+40, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_int_e, (-5, &r), 0.25, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_int_e, (-1, &r), 0.25, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_int_e, ( 0, &r), 0.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_int_e, ( 5, &r), 0.9721197704469093059, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_int_e, ( 6, &r), 0.9855510912974351041, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_int_e, ( 20, &r), 0.9999990466115815221, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_int_e, ( 1000, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_e, (-51.5, &r), -1.2524184036924703656e+41, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_e, (-5, &r), 0.25, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_e, (0.5, &r), 0.6048986434216303702, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_e, (0.999, &r), 0.6929872789683383574, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_e, (1.0, &r), 0.6931471805599453094, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_e, (1.0+1.0e-10, &r), 0.6931471805759321998, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_e, ( 5, &r), 0.9721197704469093059, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_e, ( 5.2, &r), 0.9755278712546684682, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_e, ( 6, &r), 0.9855510912974351041, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_eta_e, ( 20, &r), 0.9999990466115815221, TEST_TOL0, GSL_SUCCESS);
return s;
}
int test_results(void)
{
int s = 0;
gsl_sf_result_e10 re;
gsl_sf_result r;
re.val = -1.0;
re.err = 0.5;
re.e10 = 0;
gsl_sf_result_smash_e(&re, &r);
s += ( test_sf_frac_diff(r.val, -1.0) > TEST_TOL0 );
s += ( test_sf_frac_diff(r.err, 0.5) > TEST_TOL0 );
re.val = -1.0;
re.err = 0.5;
re.e10 = 10;
gsl_sf_result_smash_e(&re, &r);
s += ( test_sf_frac_diff(r.val, -1.0e+10) > TEST_TOL1 );
s += ( test_sf_frac_diff(r.err, 0.5e+10) > TEST_TOL1 );
re.val = 1.0;
re.err = 0.5;
re.e10 = 10000;
s += ( gsl_sf_result_smash_e(&re, &r) != GSL_EOVRFLW );
re.val = 1.0;
re.err = 0.5;
re.e10 = -10000;
s += ( gsl_sf_result_smash_e(&re, &r) != GSL_EUNDRFLW );
return s;
}
int main(int argc, char * argv[])
{
gsl_ieee_env_setup ();
gsl_set_error_handler_off ();
gsl_test(test_airy(), "Airy Functions");
gsl_test(test_bessel(), "Bessel Functions");
gsl_test(test_clausen(), "Clausen Integral");
gsl_test(test_coulomb(), "Coulomb Wave Functions");
gsl_test(test_coupling(), "Coupling Coefficients");
gsl_test(test_dawson(), "Dawson Integral");
gsl_test(test_debye(), "Debye Functions");
gsl_test(test_dilog(), "Dilogarithm");
gsl_test(test_elementary(), "Elementary Functions (Misc)");
gsl_test(test_ellint(), "Elliptic Integrals");
gsl_test(test_jac(), "Elliptic Functions (Jacobi)");
gsl_test(test_erf(), "Error Functions");
gsl_test(test_exp(), "Exponential Functions");
gsl_test(test_expint(), "Exponential/Sine/Cosine Integrals");
gsl_test(test_fermidirac(), "Fermi-Dirac Functions");
gsl_test(test_gamma(), "Gamma Functions");
gsl_test(test_gegen(), "Gegenbauer Polynomials");
gsl_test(test_hyperg(), "Hypergeometric Functions");
gsl_test(test_laguerre(), "Laguerre Polynomials");
gsl_test(test_lambert(), "Lambert W Functions");
gsl_test(test_legendre(), "Legendre Functions");
gsl_test(test_log(), "Logarithm");
gsl_test(test_mathieu(), "Mathieu Functions");
gsl_test(test_pow_int(), "Integer Powers");
gsl_test(test_psi(), "Psi Functions");
gsl_test(test_psi_complex(), "Psi Function for complex argument");
gsl_test(test_synch(), "Synchrotron Functions");
gsl_test(test_transport(), "Transport Functions");
gsl_test(test_trig(), "Trigonometric and Related Functions");
gsl_test(test_zeta(), "Zeta Functions");
gsl_test(test_results(), "Result Methods");
exit (gsl_test_summary());
}
| {
"alphanum_fraction": 0.694777597,
"avg_line_length": 57.2719393283,
"ext": "c",
"hexsha": "cf472bf953f28dd84a22604a426224b801223dfa",
"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/specfunc/test_sf.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/specfunc/test_sf.c",
"max_line_length": 154,
"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/specfunc/test_sf.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": 69156,
"size": 158586
} |
/*
** Copyright (C) 2004 Jonathan G. Underwood <j.underwood@open.ac.uk>
**
** 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_SF_WIGNER_H__
#define __GSL_SF_WIGNER_H__ 1
#include <gsl/gsl_sf_result.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
double gsl_sf_wigner_3j (const int two_j1, const int two_j2,
const int two_j3, const int two_m1,
const int two_m2, const int two_m3);
int gsl_sf_wigner_3j_e (const int two_j1, const int two_j2, const int two_j3,
const int two_m1, const int two_m2, const int two_m3,
gsl_sf_result * result);
double gsl_sf_wigner_6j (const int two_j1, const int two_j2, const int two_j3,
const int two_j4, const int two_j5,
const int two_j6);
int gsl_sf_wigner_6j_e (const int two_j1, const int two_j2, const int two_j3,
const int two_j4, const int two_j5, const int two_j6,
gsl_sf_result * result);
double gsl_sf_wigner_9j (const int two_j1, const int two_j2, const int two_j3,
const int two_j4, const int two_j5, const int two_j6,
const int two_j7, const int two_j8,
const int two_j9);
int gsl_sf_wigner_9j_e (const int two_j1, const int two_j2, const int two_j3,
const int two_j4, const int two_j5, const int two_j6,
const int two_j7, const int two_j8, const int two_j9,
gsl_sf_result * result);
double gsl_sf_wigner_drot (const int two_j, const int two_m1,
const int two_m2, const double theta);
int gsl_sf_wigner_drot_e (const int two_j, const int two_m1, const int two_m2,
const double theta, gsl_sf_result * result);
__END_DECLS
#endif /* __GSL_SF_WIGNER_H__ */
| {
"alphanum_fraction": 0.6530172414,
"avg_line_length": 43.5,
"ext": "h",
"hexsha": "4585bcfc883683af48333761179546ef7f6c61e3",
"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": "115c007926ca80d51a37cdf887b5252338d8bc8d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "vinej/sml",
"max_forks_repo_path": "include/gsl/wigner.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "vinej/sml",
"max_issues_repo_path": "include/gsl/wigner.h",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "vinej/sml",
"max_stars_repo_path": "include/gsl/wigner.h",
"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": 705,
"size": 2784
} |
#pragma once
#include <optional>
#include <gsl/span>
#include "Ds4InputData.h"
/**
* \brief Serialized input report from a \c Ds4Device
* \sa Ds4Device
*/
class Ds4Input
{
public:
Ds4Input() = default;
/**
* \brief Indicates if button press state has changed since the last poll.
*/
bool buttonsChanged = false; // TODO: private set
/**
* \brief Indicates if touch state has changed since last poll.
*/
bool touchChanged = false; // TODO: private set
/**
* \brief Buttons currently held.
* \sa Ds4Buttons, Ds4Buttons_t
*/
Ds4Buttons_t heldButtons = 0; // TODO: private set
/**
* \brief Buttons pressed since last poll.
* \sa Ds4Buttons, Ds4Buttons_t
*/
Ds4Buttons_t pressedButtons = 0; // TODO: private set
/**
* \brief Buttons released since last poll.
* \sa Ds4Buttons, Ds4Buttons_t
*/
Ds4Buttons_t releasedButtons = 0; // TODO: private set
/**
* \brief Each axis that has changed since the last poll.
* \sa Ds4Axes, Ds4Axes_t
*/
Ds4Axes_t axes = 0; // TODO: private set
Ds4InputData data {};
/**
* \brief Updates serialized data using the given buffer.
* \param buffer Buffer containing raw input report data.
*/
void update(const gsl::span<uint8_t>& buffer);
/**
* \brief Updates button change states since last poll.
*/
void updateChangedState();
/**
* \brief Get the magnitude of an axis.
* \param axis The axis to retrieve.
* \param polarity The desired polarity of the axis, or \c std::nullopt for both positive and negative.
* \return The magnitude of the axis. If it does not align with the desired \a polarity, \c 0.0f is returned.
*/
[[nodiscard]] float getAxis(Ds4Axes_t axis, const std::optional<AxisPolarity>& polarity) const;
private:
Ds4Buttons_t lastHeldButtons = 0;
uint8_t lastTouchFrame {};
void addButton(bool pressed, Ds4Buttons_t buttons);
void updateButtons();
void updateAxes(const Ds4InputData& last);
};
| {
"alphanum_fraction": 0.6951788491,
"avg_line_length": 23.8148148148,
"ext": "h",
"hexsha": "a61aeddaf0e4320817cd7f46fb7aca627788b318",
"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": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SonicFreak94/ds4wizard",
"max_forks_repo_path": "ds4wizard-cpp/Ds4Input.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c",
"max_issues_repo_issues_event_max_datetime": "2020-06-30T04:00:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-01-29T20:34:26.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SonicFreak94/ds4wizard",
"max_issues_repo_path": "ds4wizard-cpp/Ds4Input.h",
"max_line_length": 110,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "4d2ddc15b7db7cc5618c8676c91cf81614921c3c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SonicFreak94/ds4wizard",
"max_stars_repo_path": "ds4wizard-cpp/Ds4Input.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-13T08:35:31.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-02-27T19:23:34.000Z",
"num_tokens": 540,
"size": 1929
} |
/*! \file Exceptions.h
* \brief header file that defines exceptions
*/
// Function.h
#ifndef NBODYEXCEPTION_H
#define NBODYEXCEPTION_H
#include <exception>
#include <string>
#include <utility>
#include <gsl/gsl_errno.h>
namespace Math
{
class gsl_error : public std::exception {
private:
int gsl_errno;
std::string errmsg;
public:
gsl_error(int gsl_errno) :
gsl_errno(gsl_errno),
errmsg(gsl_strerror(gsl_errno))
{
}
int get_gsl_errno() {
return gsl_errno;
}
const char *what() const noexcept
{
return errmsg.c_str();
}
};
template<typename Func, typename ... Args>
void gsl_invoke(Func &&f, Args ... args)
{
int status = f(std::forward<Args>(args)...);
if (status != GSL_SUCCESS) {
throw gsl_error(status);
}
}
}
#endif
| {
"alphanum_fraction": 0.6881578947,
"avg_line_length": 13.8181818182,
"ext": "h",
"hexsha": "d5915010e901e059865e82b623404bf88b34efca",
"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/Exceptions.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/Exceptions.h",
"max_line_length": 46,
"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/Exceptions.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 198,
"size": 760
} |
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <gbpLib.h>
#include <gbpMCMC.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_interp.h>
void add_MCMC_DS(MCMC_info *MCMC, const char *name, int n_D, int *D, double *DS, double *dDS, void *params, int n_arrays, ...) {
int i_array;
int i_D;
int n_M;
MCMC_DS_info *new_DS;
va_list vargs;
va_start(vargs, n_arrays);
SID_log("Adding data set {%s} to MCMC structure...", SID_LOG_OPEN, name);
#if USE_CFITSIO == 0
if(n_D > 1)
SID_exit_error("You can only use 2D datasets if you compile with USE_CFITSIO=1 at the moment.", SID_ERROR_LOGIC);
#endif
// Initialize new dataset
init_MCMC_DS(&new_DS, name, n_D, D, DS, dDS, params, n_arrays, vargs);
// Add new dataset to linked list
if(MCMC->DS == NULL)
MCMC->DS = new_DS;
else
MCMC->last->next = new_DS;
MCMC->last = new_DS;
MCMC->n_DS++;
SID_log("Done.", SID_LOG_CLOSE);
va_end(vargs);
}
| {
"alphanum_fraction": 0.623255814,
"avg_line_length": 25.5952380952,
"ext": "c",
"hexsha": "a71e19ac1dfdfacc6d80c24ee745476378ebe00a",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpMath/gbpMCMC/add_MCMC_DS.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpMath/gbpMCMC/add_MCMC_DS.c",
"max_line_length": 128,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpMath/gbpMCMC/add_MCMC_DS.c",
"max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z",
"num_tokens": 343,
"size": 1075
} |
//===--- Sudoku/Board.h ---===//
//
// Data container for sudoku puzzles
//===----------------------------------------------------------------------===//
//
// accepts only squared dimensions
// gives full, row, column and block access
// no processing functionality
//
//===----------------------------------------------------------------------===//
#pragma once
#include "Board_Iterators.h"
#include "Board_Section.h"
#include "Location.h"
#include "Location_Utilities.h"
#include "Size.h"
#include "exceptions.h"
#include <gsl/gsl>
#include <array>
#include <initializer_list>
#include <algorithm>
#include "Board.fwd.h" // Forward declarations
#include <cassert>
namespace Sudoku
{
template<typename T, int N = 3>
class Board
{
static_assert(N > 1, "Board.h base_size value too small");
static constexpr auto Size = size_t{full_size<N>};
using index = gsl::index;
using Location = ::Sudoku::Location<N>;
using Row = Board_Section::Row<T, N>;
using const_Row = Board_Section::const_Row<T, N>;
using Col = Board_Section::Col<T, N>;
using const_Col = Board_Section::const_Col<T, N>;
using Block = Board_Section::Block<T, N>;
using const_Block = Board_Section::const_Block<T, N>;
public:
using value_type = T;
using size_type = size_t;
using difference_type = std::ptrdiff_t;
using reference = value_type&;
using const_reference = value_type const&;
using pointer = value_type*;
using const_pointer = value_type const*;
using iterator = Board_iterator<T, N>;
using const_iterator = const_Board_iterator<T, N>;
using reverse_iterator = reverse_Board_iterator<T, N>;
using const_reverse_iterator = const_reverse_Board_iterator<T, N>;
constexpr Board() noexcept;
explicit constexpr Board(const T& default_value);
// NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions)
constexpr Board(std::array<T, Size> const& list) // NOLINT(runtime/explicit)
: board_(list)
{
}
Board(std::initializer_list<T>); // construct from initializer_list
void clear();
// Query properties
[[nodiscard]] static constexpr size_t size() noexcept { return Size; }
[[nodiscard]] static constexpr size_t max_size() noexcept { return size(); }
[[nodiscard]] static constexpr bool empty() noexcept { return false; }
[[nodiscard]] bool operator==(const Board&) const;
// Element access
[[nodiscard]] constexpr T& front() noexcept { return board_.front(); }
[[nodiscard]] constexpr T const& front() const noexcept
{
return board_.front();
}
[[nodiscard]] constexpr T& back() noexcept { return board_.back(); }
[[nodiscard]] constexpr T const& back() const noexcept
{
return board_.back();
}
// Checked
constexpr T& at(Location);
[[nodiscard]] constexpr T const& at(Location) const;
constexpr T& at(index row, index col);
[[nodiscard]] constexpr T const& at(index row, index col) const;
[[deprecated]] T& at(index elem);
[[deprecated, nodiscard]] const T& at(index elem) const;
// Unchecked
constexpr T& operator[](Location) noexcept;
constexpr T const& operator[](Location) const noexcept;
// Element Selection Operator (using a proxy object)
// usable as [row][col] where col is processed by the (const_)Row
Row operator[](index row_id) noexcept { return row(row_id); }
constexpr const_Row operator[](index row_id) const noexcept
{
return row(row_id);
}
// Iterators
constexpr iterator begin() noexcept;
constexpr iterator end() noexcept;
[[nodiscard]] constexpr const_iterator cbegin() const noexcept;
[[nodiscard]] constexpr const_iterator cend() const noexcept;
[[nodiscard]] constexpr const_iterator begin() const noexcept
{
return cbegin();
}
[[nodiscard]] constexpr const_iterator end() const noexcept
{
return cend();
}
constexpr reverse_iterator rbegin() noexcept;
constexpr reverse_iterator rend() noexcept;
[[nodiscard]] constexpr const_reverse_iterator crbegin() const noexcept;
[[nodiscard]] constexpr const_reverse_iterator crend() const noexcept;
[[nodiscard]] constexpr const_reverse_iterator rbegin() const noexcept
{
return crbegin();
}
[[nodiscard]] constexpr const_reverse_iterator rend() const noexcept
{
return crend();
}
// Sections
// clang-format off
Row row(index id) noexcept { return Row(*this, id); }
[[nodiscard]] constexpr const_Row row(index id) const noexcept
{ return const_Row(*this, id); }
Row row(Location loc) noexcept { return Row(*this, loc); }
[[nodiscard]] constexpr const_Row row(Location loc) const noexcept
{ return const_Row(*this, loc); }
Col col(index id) noexcept { return Col(*this, id); }
[[nodiscard]] constexpr const_Col col(index id) const noexcept
{ return const_Col(*this, id); }
Col col(Location loc) noexcept { return Col(*this, loc); }
[[nodiscard]] constexpr const_Col col(Location loc) const noexcept
{ return const_Col(*this, loc); }
Block block(index id) noexcept { return Block(*this, id); }
[[nodiscard]] constexpr const_Block block(index id) const noexcept
{ return const_Block(*this, id); }
Block block(Location loc) noexcept { return Block(*this, loc); }
[[nodiscard]] constexpr const_Block block(Location loc) const noexcept
{ return const_Block(*this, loc); }
// clang-format on
private:
std::array<T, Size> board_{};
}; // class Board
//===--- free-functions ---------------------------------------------------===//
template<typename T, int N>
constexpr bool operator!=(Board<T, N> const& left, Board<T, N> const& right)
{
return !(left == right);
}
//===----------------------------------------------------------------------===//
// Board - member-functions
//===----------------------------------------------------------------------===//
// Board - Constructors
template<typename T, int N>
constexpr Board<T, N>::Board() noexcept
{
valid_dimensions<N>();
}
template<typename T, int N>
constexpr Board<T, N>::Board(const T& default_value)
{
valid_dimensions<N>();
board_.fill(default_value);
}
template<typename T, int N>
Board<T, N>::Board(std::initializer_list<T> list)
{
valid_dimensions<N>();
if (list.size() != size_t{full_size<N>})
throw std::length_error{"Invalid length initializer_list"};
std::copy(std::begin(list), std::end(list), std::begin(board_));
}
//===----------------------------------------------------------------------===//
// properties
template<typename T, int N>
bool Board<T, N>::operator==(const Board& other) const
{
return board_ == other.board_;
}
//===----------------------------------------------------------------------===//
// Board - Operations
template<typename T, int N>
inline void Board<T, N>::clear()
{ // all elements to the empty value
board_.fill(T{});
}
//===----------------------------------------------------------------------===//
// Board - element access
template<typename T, int N>
constexpr T& Board<T, N>::at(const Location loc)
{
if (!is_valid<N>(loc))
{
throw error::invalid_Location{"Board::at(Location)"};
}
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
return board_[gsl::narrow_cast<size_t>(loc.element())];
}
template<typename T, int N>
constexpr T const& Board<T, N>::at(const Location loc) const
{
if (!is_valid<N>(loc))
{
throw error::invalid_Location{"Board::at(Location) const"};
}
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
return board_[gsl::narrow_cast<size_t>(loc.element())];
}
template<typename T, int N>
constexpr T& Board<T, N>::at(const index row, const index col)
{
if (!is_valid_size<N>(row, col))
{
throw error::invalid_Location{"Board::at(int row, col)"}; // <stdexcept>
}
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
return board_[gsl::narrow_cast<size_t>(Location(row, col).element())];
}
template<typename T, int N>
constexpr T const& Board<T, N>::at(const index row, const index col) const
{
if (!is_valid_size<N>(row, col))
{
throw error::invalid_Location{"Board::at(row, col) const"};
}
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
return board_[gsl::narrow_cast<size_t>(Location(row, col).element())];
}
// deprecated
template<typename T, int N>
T& Board<T, N>::at(const index elem)
{
if (!is_valid_size<N>(elem))
{
throw error::invalid_Location{"Board::at(int)"};
}
return board_.at(gsl::narrow_cast<size_t>(elem));
}
// deprecated
template<typename T, int N>
const T& Board<T, N>::at(const index elem) const
{
if (!is_valid_size<N>(elem))
{
throw error::invalid_Location{"Board::at(int) const"};
}
return board_.at(gsl::narrow_cast<size_t>(elem));
}
template<typename T, int N>
constexpr T& Board<T, N>::operator[](const Location loc) noexcept
{
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
return board_[gsl::narrow_cast<size_t>(loc.element())];
}
template<typename T, int N>
constexpr T const& Board<T, N>::operator[](const Location loc) const noexcept
{
// NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index)
return board_[gsl::narrow_cast<size_t>(loc.element())];
}
//===----------------------------------------------------------------------===//
// Board - Iterators
template<typename T, int N>
constexpr typename Board<T, N>::iterator Board<T, N>::begin() noexcept
{
return Board_iterator<T, N>(gsl::not_null<Board*>{this});
}
template<typename T, int N>
constexpr typename Board<T, N>::iterator Board<T, N>::end() noexcept
{
return Board_iterator<T, N>(
gsl::not_null<Board*>{this}, Location{full_size<N>});
}
template<typename T, int N>
constexpr typename Board<T, N>::const_iterator
Board<T, N>::cbegin() const noexcept
{
return const_Board_iterator<T, N>(gsl::not_null<Board const*>{this});
}
template<typename T, int N>
constexpr typename Board<T, N>::const_iterator
Board<T, N>::cend() const noexcept
{
return const_Board_iterator<T, N>(
gsl::not_null<Board const*>{this}, Location{full_size<N>});
}
template<typename T, int N>
constexpr typename Board<T, N>::reverse_iterator Board<T, N>::rbegin() noexcept
{
return reverse_Board_iterator<T, N>(gsl::not_null<Board*>{this});
}
template<typename T, int N>
constexpr typename Board<T, N>::reverse_iterator Board<T, N>::rend() noexcept
{
return reverse_Board_iterator<T, N>(
gsl::not_null<Board*>{this}, Location{-1});
}
template<typename T, int N>
constexpr typename Board<T, N>::const_reverse_iterator
Board<T, N>::crbegin() const noexcept
{
return const_reverse_Board_iterator<T, N>(
gsl::not_null<Board const*>{this});
}
template<typename T, int N>
constexpr typename Board<T, N>::const_reverse_iterator
Board<T, N>::crend() const noexcept
{
return const_reverse_Board_iterator<T, N>(
gsl::not_null<Board const*>{this}, Location{-1});
}
} // namespace Sudoku
| {
"alphanum_fraction": 0.6530257255,
"avg_line_length": 31.5693641618,
"ext": "h",
"hexsha": "10fec4523a44736ae8dc5f1f74f6aec5381115d8",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "FeodorFitsner/fwkSudoku",
"max_forks_repo_path": "Sudoku/Sudoku/Board.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "FeodorFitsner/fwkSudoku",
"max_issues_repo_path": "Sudoku/Sudoku/Board.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "FeodorFitsner/fwkSudoku",
"max_stars_repo_path": "Sudoku/Sudoku/Board.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2604,
"size": 10923
} |
/* randist/beta.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_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_gamma.h>
/* The beta distribution has the form
p(x) dx = (Gamma(a + b)/(Gamma(a) Gamma(b))) x^(a-1) (1-x)^(b-1) dx
The method used here is the one described in Knuth */
double
gsl_ran_beta (const gsl_rng * r, const double a, const double b)
{
if ( (a <= 1.0) && (b <= 1.0) )
{
double U, V, X, Y;
while (1)
{
U = gsl_rng_uniform_pos(r);
V = gsl_rng_uniform_pos(r);
X = pow(U, 1.0/a);
Y = pow(V, 1.0/b);
if ((X + Y ) <= 1.0)
{
if (X + Y > 0)
{
return X/ (X + Y);
}
else
{
double logX = log(U)/a;
double logY = log(V)/b;
double logM = logX > logY ? logX: logY;
logX -= logM;
logY -= logM;
return exp(logX - log(exp(logX) + exp(logY)));
}
}
}
}
else
{
double x1 = gsl_ran_gamma (r, a, 1.0);
double x2 = gsl_ran_gamma (r, b, 1.0);
return x1 / (x1 + x2);
}
}
double
gsl_ran_beta_pdf (const double x, const double a, const double b)
{
if (x < 0 || x > 1)
{
return 0 ;
}
else
{
double p;
double gab = gsl_sf_lngamma (a + b);
double ga = gsl_sf_lngamma (a);
double gb = gsl_sf_lngamma (b);
if (x == 0.0 || x == 1.0)
{
if (a > 1.0 && b > 1.0)
{
p = 0.0;
}
else
{
p = exp (gab - ga - gb) * pow (x, a - 1) * pow (1 - x, b - 1);
}
}
else
{
p = exp (gab - ga - gb + log(x) * (a - 1) + log1p(-x) * (b - 1));
}
return p;
}
}
| {
"alphanum_fraction": 0.511627907,
"avg_line_length": 25.8,
"ext": "c",
"hexsha": "03826f1e036b3b0cd92195a3d926b8b7d407db4f",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/randist/beta.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/beta.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/randist/beta.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": 829,
"size": 2709
} |
# ifndef __HEADER__GA__
# define __HEADER__GA__
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include "utils.h"
# define UL_SIZE sizeof(unsigned long)
# define GENES_C1 3
# define GENES_C2 11
// we are going to use a two chromosome genome,
typedef struct Genome {
unsigned long c1[GENES_C1];
unsigned long c2[GENES_C2];
double fitness;
} Genome;
void generate_genome(Genome * genome);
Genome * generate_population(int individuals);
int next_generation(
Genome * parents, Genome * children,
int n_elitism, int n_select, int n_cross, int n_new, double p_mutation, int mutation_bit
);
/*
* Copies the information in the input genome to the output genome.
* Note that the fitness function is also copied over.
*/
void copy_genome(Genome * in, Genome * out);
// a.k.a crossover
void tinder(Genome * population, int pop_size, Genome * out);
// actual crossover
void crossover_genomes(
Genome * gen1in,
Genome * gen2in,
Genome * out
);
void mutate_genome(Genome * genome, double p_mut);
/*
* Implementation of elitism operator.
* This selects the best of the best individuals to be passed over to the next generation.
*
* @param population the initial population with fitness values calculated
* @param pop_size the total population size
* @param number_elitism the number of best individuals to be selected
* @param out the population to be filled with the best individuals
*
* @return the position of the best individual
*/
int extinction(int ek, Genome * population, Genome * survivors, int pop_size, int number_survivors);
void elitism(Genome * population, int pop_size, int number_elitism, Genome * out);
/*
* Implementation of roulette wheel method.
* This method chooses the individuals according to their fidelity, individuals with
* lower fidelity have a lower change of being selected.
*
* @param population the initial population with fitness values calculated
* @param pop_size the total population size
* @param best_genomes the number of best individuals to choose
* @param out the population to be filled with the best individuals
*/
int casting(Genome * population, int pop_size, int best_genomes, Genome * out);
/*
* Add `n_new` individuals to the start of the passed genome array.
*/
void migration(
Genome * genome,
int n_new
);
# endif
| {
"alphanum_fraction": 0.7519214347,
"avg_line_length": 26.6136363636,
"ext": "h",
"hexsha": "837a03a2c4445025e127083ce9788579ad955959",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-02-23T11:40:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-23T11:40:36.000Z",
"max_forks_repo_head_hexsha": "cd4518b79d596a924660348e3799cc2594798aae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "urisawsing/Covid_GeneticAlg",
"max_forks_repo_path": "old/src/ga.h",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "cd4518b79d596a924660348e3799cc2594798aae",
"max_issues_repo_issues_event_max_datetime": "2021-02-05T17:16:45.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-19T15:17:55.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "urisawsing/Covid_GeneticAlg",
"max_issues_repo_path": "old/src/ga.h",
"max_line_length": 100,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "cd4518b79d596a924660348e3799cc2594798aae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "urisawsing/Covid_GeneticAlg",
"max_stars_repo_path": "old/src/ga.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 556,
"size": 2342
} |
/* specfunc/gsl_sf_bessel.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#ifndef __GSL_SF_BESSEL_H__
#define __GSL_SF_BESSEL_H__
#include <stdlib.h>
#include <gsl/gsl_mode.h>
#include <gsl/gsl_precision.h>
#include <gsl/gsl_sf_result.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* Regular Bessel Function J_0(x)
*
* exceptions: none
*/
GSL_EXPORT int gsl_sf_bessel_J0_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_J0(const double x);
/* Regular Bessel Function J_1(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_J1_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_J1(const double x);
/* Regular Bessel Function J_n(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Jn_e(int n, double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_Jn(const int n, const double x);
/* Regular Bessel Function J_n(x), nmin <= n <= nmax
*
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Jn_array(int nmin, int nmax, double x, double * result_array);
/* Irregular Bessel function Y_0(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Y0_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_Y0(const double x);
/* Irregular Bessel function Y_1(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Y1_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_Y1(const double x);
/* Irregular Bessel function Y_n(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Yn_e(int n,const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_Yn(const int n,const double x);
/* Irregular Bessel function Y_n(x), nmin <= n <= nmax
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Yn_array(const int nmin, const int nmax, const double x, double * result_array);
/* Regular modified Bessel function I_0(x)
*
* exceptions: GSL_EOVRFLW
*/
GSL_EXPORT int gsl_sf_bessel_I0_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_I0(const double x);
/* Regular modified Bessel function I_1(x)
*
* exceptions: GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_I1_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_I1(const double x);
/* Regular modified Bessel function I_n(x)
*
* exceptions: GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_In_e(const int n, const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_In(const int n, const double x);
/* Regular modified Bessel function I_n(x) for n=nmin,...,nmax
*
* nmin >=0, nmax >= nmin
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_In_array(const int nmin, const int nmax, const double x, double * result_array);
/* Scaled regular modified Bessel function
* exp(-|x|) I_0(x)
*
* exceptions: none
*/
GSL_EXPORT int gsl_sf_bessel_I0_scaled_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_I0_scaled(const double x);
/* Scaled regular modified Bessel function
* exp(-|x|) I_1(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_I1_scaled_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_I1_scaled(const double x);
/* Scaled regular modified Bessel function
* exp(-|x|) I_n(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_In_scaled_e(int n, const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_In_scaled(const int n, const double x);
/* Scaled regular modified Bessel function
* exp(-|x|) I_n(x) for n=nmin,...,nmax
*
* nmin >=0, nmax >= nmin
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_In_scaled_array(const int nmin, const int nmax, const double x, double * result_array);
/* Irregular modified Bessel function K_0(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_K0_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_K0(const double x);
/* Irregular modified Bessel function K_1(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_K1_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_K1(const double x);
/* Irregular modified Bessel function K_n(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Kn_e(const int n, const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_Kn(const int n, const double x);
/* Irregular modified Bessel function K_n(x) for n=nmin,...,nmax
*
* x > 0.0, nmin >=0, nmax >= nmin
* exceptions: GSL_EDOM, GSL_EOVRFLW, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Kn_array(const int nmin, const int nmax, const double x, double * result_array);
/* Scaled irregular modified Bessel function
* exp(x) K_0(x)
*
* x > 0.0
* exceptions: GSL_EDOM
*/
GSL_EXPORT int gsl_sf_bessel_K0_scaled_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_K0_scaled(const double x);
/* Scaled irregular modified Bessel function
* exp(x) K_1(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_K1_scaled_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_K1_scaled(const double x);
/* Scaled irregular modified Bessel function
* exp(x) K_n(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Kn_scaled_e(int n, const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_Kn_scaled(const int n, const double x);
/* Scaled irregular modified Bessel function exp(x) K_n(x) for n=nmin,...,nmax
*
* x > 0.0, nmin >=0, nmax >= nmin
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Kn_scaled_array(const int nmin, const int nmax, const double x, double * result_array);
/* Regular spherical Bessel function j_0(x) = sin(x)/x
*
* exceptions: none
*/
GSL_EXPORT int gsl_sf_bessel_j0_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_j0(const double x);
/* Regular spherical Bessel function j_1(x) = (sin(x)/x - cos(x))/x
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_j1_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_j1(const double x);
/* Regular spherical Bessel function j_2(x) = ((3/x^2 - 1)sin(x) - 3cos(x)/x)/x
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_j2_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_j2(const double x);
/* Regular spherical Bessel function j_l(x)
*
* l >= 0, x >= 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_jl_e(const int l, const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_jl(const int l, const double x);
/* Regular spherical Bessel function j_l(x) for l=0,1,...,lmax
*
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_jl_array(const int lmax, const double x, double * result_array);
/* Regular spherical Bessel function j_l(x) for l=0,1,...,lmax
* Uses Steed's method.
*
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_jl_steed_array(const int lmax, const double x, double * jl_x_array);
/* Irregular spherical Bessel function y_0(x)
*
* exceptions: none
*/
GSL_EXPORT int gsl_sf_bessel_y0_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_y0(const double x);
/* Irregular spherical Bessel function y_1(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_y1_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_y1(const double x);
/* Irregular spherical Bessel function y_2(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_y2_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_y2(const double x);
/* Irregular spherical Bessel function y_l(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_yl_e(int l, const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_yl(const int l, const double x);
/* Irregular spherical Bessel function y_l(x) for l=0,1,...,lmax
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_yl_array(const int lmax, const double x, double * result_array);
/* Regular scaled modified spherical Bessel function
*
* Exp[-|x|] i_0(x)
*
* exceptions: none
*/
GSL_EXPORT int gsl_sf_bessel_i0_scaled_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_i0_scaled(const double x);
/* Regular scaled modified spherical Bessel function
*
* Exp[-|x|] i_1(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_i1_scaled_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_i1_scaled(const double x);
/* Regular scaled modified spherical Bessel function
*
* Exp[-|x|] i_2(x)
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_i2_scaled_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_i2_scaled(const double x);
/* Regular scaled modified spherical Bessel functions
*
* Exp[-|x|] i_l(x)
*
* i_l(x) = Sqrt[Pi/(2x)] BesselI[l+1/2,x]
*
* l >= 0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_il_scaled_e(const int l, double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_il_scaled(const int l, const double x);
/* Regular scaled modified spherical Bessel functions
*
* Exp[-|x|] i_l(x)
* for l=0,1,...,lmax
*
* exceptions: GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_il_scaled_array(const int lmax, const double x, double * result_array);
/* Irregular scaled modified spherical Bessel function
* Exp[x] k_0(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_k0_scaled_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_k0_scaled(const double x);
/* Irregular modified spherical Bessel function
* Exp[x] k_1(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW, GSL_EOVRFLW
*/
GSL_EXPORT int gsl_sf_bessel_k1_scaled_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_k1_scaled(const double x);
/* Irregular modified spherical Bessel function
* Exp[x] k_2(x)
*
* x > 0.0
* exceptions: GSL_EDOM, GSL_EUNDRFLW, GSL_EOVRFLW
*/
GSL_EXPORT int gsl_sf_bessel_k2_scaled_e(const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_k2_scaled(const double x);
/* Irregular modified spherical Bessel function
* Exp[x] k_l[x]
*
* k_l(x) = Sqrt[Pi/(2x)] BesselK[l+1/2,x]
*
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_kl_scaled_e(int l, const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_kl_scaled(const int l, const double x);
/* Irregular scaled modified spherical Bessel function
* Exp[x] k_l(x)
*
* for l=0,1,...,lmax
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_kl_scaled_array(const int lmax, const double x, double * result_array);
/* Regular cylindrical Bessel function J_nu(x)
*
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Jnu_e(const double nu, const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_Jnu(const double nu, const double x);
/* Irregular cylindrical Bessel function Y_nu(x)
*
* exceptions:
*/
GSL_EXPORT int gsl_sf_bessel_Ynu_e(double nu, double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_Ynu(const double nu, const double x);
/* Regular cylindrical Bessel function J_nu(x)
* evaluated at a series of x values. The array
* contains the x values. They are assumed to be
* strictly ordered and positive. The array is
* over-written with the values of J_nu(x_i).
*
* exceptions: GSL_EDOM, GSL_EINVAL
*/
GSL_EXPORT int gsl_sf_bessel_sequence_Jnu_e(double nu, gsl_mode_t mode, size_t size, double * v);
/* Scaled modified cylindrical Bessel functions
*
* Exp[-|x|] BesselI[nu, x]
* x >= 0, nu >= 0
*
* exceptions: GSL_EDOM
*/
GSL_EXPORT int gsl_sf_bessel_Inu_scaled_e(double nu, double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_Inu_scaled(double nu, double x);
/* Modified cylindrical Bessel functions
*
* BesselI[nu, x]
* x >= 0, nu >= 0
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Inu_e(double nu, double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_Inu(double nu, double x);
/* Scaled modified cylindrical Bessel functions
*
* Exp[+|x|] BesselK[nu, x]
* x > 0, nu >= 0
*
* exceptions: GSL_EDOM
*/
GSL_EXPORT int gsl_sf_bessel_Knu_scaled_e(const double nu, const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_Knu_scaled(const double nu, const double x);
/* Modified cylindrical Bessel functions
*
* BesselK[nu, x]
* x > 0, nu >= 0
*
* exceptions: GSL_EDOM, GSL_EUNDRFLW
*/
GSL_EXPORT int gsl_sf_bessel_Knu_e(const double nu, const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_Knu(const double nu, const double x);
/* Logarithm of modified cylindrical Bessel functions.
*
* Log[BesselK[nu, x]]
* x > 0, nu >= 0
*
* exceptions: GSL_EDOM
*/
GSL_EXPORT int gsl_sf_bessel_lnKnu_e(const double nu, const double x, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_lnKnu(const double nu, const double x);
/* s'th positive zero of the Bessel function J_0(x).
*
* exceptions:
*/
GSL_EXPORT int gsl_sf_bessel_zero_J0_e(unsigned int s, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_zero_J0(unsigned int s);
/* s'th positive zero of the Bessel function J_1(x).
*
* exceptions:
*/
GSL_EXPORT int gsl_sf_bessel_zero_J1_e(unsigned int s, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_zero_J1(unsigned int s);
/* s'th positive zero of the Bessel function J_nu(x).
*
* exceptions:
*/
GSL_EXPORT int gsl_sf_bessel_zero_Jnu_e(double nu, unsigned int s, gsl_sf_result * result);
GSL_EXPORT double gsl_sf_bessel_zero_Jnu(double nu, unsigned int s);
__END_DECLS
#endif /* __GSL_SF_BESSEL_H__ */
| {
"alphanum_fraction": 0.747153669,
"avg_line_length": 27.6272727273,
"ext": "h",
"hexsha": "b208e3cbb8bda6459e556bc26574aee61c63b8af",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dynaryu/vaws",
"max_forks_repo_path": "src/core/gsl/include/gsl/gsl_sf_bessel.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_sf_bessel.h",
"max_line_length": 116,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dynaryu/vaws",
"max_stars_repo_path": "src/core/gsl/include/gsl/gsl_sf_bessel.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4503,
"size": 15195
} |
/**
*
* @file core_blas.h
*
* PLASMA auxiliary routines
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Jakub Kurzak
* @author Hatem Ltaief
* @date 2010-11-15
*
**/
#ifndef _PLASMA_CORE_BLAS_H_
#define _PLASMA_CORE_BLAS_H_
#ifdef USE_MKL
#include <mkl_cblas.h>
#else
#include <cblas.h>
#endif
#include "plasmatypes.h"
#include "descriptor.h"
#include "core_dblas.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Coreblas Error
*/
#define coreblas_error(k, str) fprintf(stderr, "%s: Parameter %d / %s\n", __func__, k, str);
/** ****************************************************************************
* LAPACK Constants
**/
extern char *plasma_lapack_constants[];
#define lapack_const(plasma_const) plasma_lapack_constants[plasma_const][0]
/*
* CBlas enum
*/
#define CBLAS_TRANSPOSE int
#define CBLAS_UPLO int
#define CBLAS_DIAG int
#define CBLAS_SIDE int
//#define CBLAS_TRANSPOSE enum CBLAS_TRANSPOSE
//#define CBLAS_UPLO enum CBLAS_UPLO
//#define CBLAS_DIAG enum CBLAS_DIAG
//#define CBLAS_SIDE enum CBLAS_SIDE
#ifdef __cplusplus
}
#endif
#endif /* _PLASMA_CORE_BLAS_H_ */
| {
"alphanum_fraction": 0.6603023071,
"avg_line_length": 20.95,
"ext": "h",
"hexsha": "c6a1e777d03c72e7886c06720669a74e157f8ca6",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2021-01-21T11:17:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-06-22T18:44:35.000Z",
"max_forks_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "tianyi93/hpxMP_mirror",
"max_forks_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/include/core_blas.h",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e",
"max_issues_repo_issues_event_max_datetime": "2019-10-16T20:43:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-06-18T14:59:09.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "tianyi93/hpxMP_mirror",
"max_issues_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/include/core_blas.h",
"max_line_length": 92,
"max_stars_count": 22,
"max_stars_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "tianyi93/hpxMP_mirror",
"max_stars_repo_path": "examples/omp/benchmarks/kastors-1.1/plasma/include/core_blas.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-08T11:25:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-16T14:39:17.000Z",
"num_tokens": 364,
"size": 1257
} |
/* Author: Romain "Artefact2" Dal Maso <artefact2@gmail.com> */
/* This program is free software. It comes without any warranty, to the
* extent permitted by applicable law. You can redistribute it and/or
* modify it under the terms of the Do What The Fuck You Want To Public
* License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details. */
#define warn(...) do { \
char msg[256]; \
snprintf(msg, 256, __VA_ARGS__); \
fprintf(stderr, "%s(): %s\n", __func__, msg); \
} while(0)
#define fatal(...) do { \
warn(__VA_ARGS__); \
exit(1); \
} while(0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include <gsl/gsl_sf_gamma.h>
#define MCTS (1 << 15)
void read_rolls(unsigned int, unsigned int* rcount, unsigned int* n);
unsigned int ecdf_distance(unsigned int, unsigned int*);
void ecdf_gen_mc_table(unsigned int sides, unsigned int n, unsigned int count, unsigned int*);
bool find_in_sorted_array(unsigned int val, unsigned int count, unsigned int* array, unsigned int* low, unsigned int* high);
double chisq_test(unsigned int sides, unsigned int n, unsigned int*);
void confidence_test(unsigned int sides, unsigned int n, unsigned int*);
int main(int argc, char** argv) {
if(argc != 2) {
fprintf(stderr, "Usage: %s <num-sides> < rolls.txt\n", argv[0]);
exit(2);
}
unsigned int sides = strtol(argv[1], NULL, 10);
if(sides < 2) {
fatal("must have at least 2 sides, got %d", sides);
}
unsigned int rcount[sides];
unsigned int n;
read_rolls(sides, rcount, &n);
if(n % sides) {
fatal("sample size (%d) not a multiple of sides (%d)", n, sides);
}
printf("SmpSize: n=%d\n", n);
unsigned int ecdf_table[MCTS];
ecdf_gen_mc_table(sides, n, MCTS, ecdf_table);
unsigned int dist = ecdf_distance(sides, rcount);
unsigned int lo, hi;
bool found;
found = find_in_sorted_array(dist, MCTS, ecdf_table, &lo, &hi);
printf("ECDF: p%s%5.4f\n", found ? "=" : "<", found ? (1.0 - (double)(lo + hi) / (double)(2 * MCTS)) : ((double)(MCTS - lo) / (double)MCTS));
printf("ChiSq: p=%5.4f\n", chisq_test(sides, n, rcount));
printf("ConfInt99:");
confidence_test(sides, n, rcount);
printf("\n");
}
void read_rolls(unsigned int sides, unsigned int* rcount, unsigned int* n) {
char buf[16];
unsigned int roll;
memset(rcount, 0, sides * sizeof(unsigned int));
*n = 0;
while(!feof(stdin)) {
if(fgets(buf, 16, stdin) == NULL) continue;
if(buf[0] == '\n' || buf[0] == '\0') continue;
roll = strtol(buf, NULL, 10);
if(roll < 1 || roll > sides) {
warn("ignoring roll %d", roll);
continue;
}
++(rcount[roll - 1]);
++(*n);
}
}
unsigned int ecdf_distance(unsigned int sides, unsigned int* rcount) {
unsigned int cumulative = 0, ideal_cumulative, ideal_step, i, distance, tdist;
for(i = 0; i < sides; ++i) {
cumulative += rcount[i];
}
ideal_cumulative = cumulative;
ideal_step = ideal_cumulative / sides;
distance = 0;
for(i = 0; i < sides; ++i) {
cumulative -= rcount[i];
ideal_cumulative -= ideal_step;
tdist = (cumulative >= ideal_cumulative) ? (cumulative - ideal_cumulative) : (ideal_cumulative - cumulative);
if(tdist > distance) distance = tdist;
}
return distance;
}
int cmpuint(const void* a, const void* b) {
return *(unsigned int*)a - *(unsigned int*)b;
}
void ecdf_gen_mc_table(unsigned int sides, unsigned int n, unsigned int count, unsigned int* table) {
unsigned int rcount[sides];
unsigned int i, j;
for(i = 0; i < count; ++i) {
memset(rcount, 0, sides * sizeof(unsigned int));
for(j = 0; j < n; ++j) {
++(rcount[rand() % sides]);
}
table[i] = ecdf_distance(sides, rcount);
}
qsort(table, count, sizeof(unsigned int), cmpuint);
}
bool find_in_sorted_array(unsigned int val, unsigned int count, unsigned int* array, unsigned int* low, unsigned int* high) {
if(array[0] > val) {
*low = *high = 0;
return false;
} else if(array[count - 1] < val) {
*low = *high = count - 1;
return false;
}
unsigned int mid;
*low = 0;
*high = count - 1;
while(*high > *low) {
mid = *low + (*high - *low) / 2;
if(array[mid] == val) {
*low = *high = mid;
while(*low < count && array[*low] == val) --(*low);
++(*low);
while(*high < count && array[*high] == val) ++high;
--(*high);
return true;
} else if(array[mid] > val) {
*high = mid;
} else {
*low = mid;
}
}
return false;
}
double chisq_test(unsigned int sides, unsigned int n, unsigned int* rcount) {
unsigned int ideal = n / sides;
double chisq = 0.0;
for(unsigned int i = 0; i < sides; ++i) {
chisq += (rcount[i] - ideal) * (rcount[i] - ideal);
}
chisq /= (double)ideal;
return 1.0 - gsl_sf_gamma_inc_P((double)(sides - 1) / (double)2, chisq / (double)2);
}
void confidence_test(unsigned int sides, unsigned int n, unsigned int* rcount) {
double f, amp, ideal = 1.0 / (double)sides;
bool anomalies = false;
for(unsigned int i = 0; i < sides; ++i) {
f = (double)rcount[i] / (double)n;
amp = 2.575 * sqrt(f * (1.0 - f) / (double)n);
if(ideal > f + amp) {
printf(" %d-", i+1);
anomalies = true;
} else if(ideal < f - amp) {
printf(" %d+", i+1);
anomalies = true;
}
}
if(!anomalies) {
printf(" OK");
}
}
| {
"alphanum_fraction": 0.6311895276,
"avg_line_length": 25.9655172414,
"ext": "c",
"hexsha": "9dddfbff3f445bb522da1ee05eec6e687e983d4d",
"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": "261919cbd5b7e515c66f292812d242c6f2ff761d",
"max_forks_repo_licenses": [
"WTFPL"
],
"max_forks_repo_name": "Artefact2/fairdice",
"max_forks_repo_path": "fairdice.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "261919cbd5b7e515c66f292812d242c6f2ff761d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"WTFPL"
],
"max_issues_repo_name": "Artefact2/fairdice",
"max_issues_repo_path": "fairdice.c",
"max_line_length": 147,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "261919cbd5b7e515c66f292812d242c6f2ff761d",
"max_stars_repo_licenses": [
"WTFPL"
],
"max_stars_repo_name": "Artefact2/fairdice",
"max_stars_repo_path": "fairdice.c",
"max_stars_repo_stars_event_max_datetime": "2019-09-06T15:08:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-06T15:08:01.000Z",
"num_tokens": 1679,
"size": 5271
} |
/* cheb/gsl_chebyshev.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __GSL_CHEBYSHEV_H__
#define __GSL_CHEBYSHEV_H__
#include <gsl/gsl_mode.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
/* data for a Chebyshev series over a given interval */
struct gsl_cheb_series_struct {
double * c; /* coefficients */
size_t order; /* order of expansion */
double a; /* lower interval point */
double b; /* upper interval point */
/* The following exists (mostly) for the benefit
* of the implementation. It is an effective single
* precision order, for use in single precision
* evaluation. Users can use it if they like, but
* only they know how to calculate it, since it is
* specific to the approximated function. By default,
* order_sp = order.
* It is used explicitly only by the gsl_cheb_eval_mode
* functions, which are not meant for casual use.
*/
size_t order_sp;
/* Additional elements not used by specfunc */
double * f; /* function evaluated at chebyschev points */
};
typedef struct gsl_cheb_series_struct gsl_cheb_series;
/* Calculate a Chebyshev series of specified order over
* a specified interval, for a given function.
* Return 0 on failure.
*/
gsl_cheb_series * gsl_cheb_alloc(const size_t order);
/* Free a Chebyshev series previously calculated with gsl_cheb_alloc().
*/
void gsl_cheb_free(gsl_cheb_series * cs);
/* Calculate a Chebyshev series using the storage provided.
* Uses the interval (a,b) and the order with which it
* was initially created.
*
*/
int gsl_cheb_init(gsl_cheb_series * cs, const gsl_function * func,
const double a, const double b);
/* Evaluate a Chebyshev series at a given point.
* No errors can occur for a struct obtained from gsl_cheb_new().
*/
double gsl_cheb_eval(const gsl_cheb_series * cs, const double x);
int gsl_cheb_eval_err(const gsl_cheb_series * cs, const double x,
double * result, double * abserr);
/* Evaluate a Chebyshev series at a given point, to (at most) the given order.
* No errors can occur for a struct obtained from gsl_cheb_new().
*/
double gsl_cheb_eval_n(const gsl_cheb_series * cs, const size_t order,
const double x);
int gsl_cheb_eval_n_err(const gsl_cheb_series * cs, const size_t order,
const double x, double * result, double * abserr);
/* Evaluate a Chebyshev series at a given point, using the default
* order for double precision mode(s) and the single precision
* order for other modes.
* No errors can occur for a struct obtained from gsl_cheb_new().
*/
double gsl_cheb_eval_mode(const gsl_cheb_series * cs, double x, gsl_mode_t mode);
int gsl_cheb_eval_mode_e(const gsl_cheb_series * cs, const double x, gsl_mode_t mode, double * result, double * abserr);
/* Compute the derivative of a Chebyshev series.
*/
int gsl_cheb_calc_deriv(gsl_cheb_series * deriv, const gsl_cheb_series * cs);
/* Compute the integral of a Chebyshev series. The
* integral is fixed by the condition that it equals zero at
* the left end-point, ie it is precisely
* Integrate[cs(t; a,b), {t, a, x}]
*/
int gsl_cheb_calc_integ(gsl_cheb_series * integ, const gsl_cheb_series * cs);
__END_DECLS
#endif /* __GSL_CHEBYSHEV_H__ */
| {
"alphanum_fraction": 0.7156050201,
"avg_line_length": 32.7364341085,
"ext": "h",
"hexsha": "65dbc2e923f79aa256fece6c580e918e3bce8630",
"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/cheb/gsl_chebyshev.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/cheb/gsl_chebyshev.h",
"max_line_length": 120,
"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/cheb/gsl_chebyshev.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z",
"num_tokens": 1063,
"size": 4223
} |
/*
* File: particle.h
* Author: adithya
*
* Created on December 15, 2014, 7:23 PM
*/
#ifndef PARTICLE_H
#define PARTICLE_H
//#include "myVector.h"
//#include "quaternion.h"
//#include "species.h"
//#include "simulationParameters.h"
//
//#include <fstream>
//#include <sstream>
//#include <vector>
//
//#include <gsl/gsl_rng.h>
//#include <gsl/gsl_randist.h>
#include "myVector.h"
#include "quaternion.h"
#include "main.h"
class particle
{
public:
particle();
particle(const particle& orig);
virtual ~particle();
public:
int particleID;/**This ID helps identifying the particle in question*/
int speciesType;/**Is the species type of the particle, which in turn holds information about the particles' physical properties.*/
int particleType;/**Describes the type of the particle, 1 if a particle with a domain(eGFRD), 2 if LD*/
//std::vector < std::pair <int, int> > complexList;
std::vector < std::pair <int, int> > complexList;/**Gives the list of all other particles (if any)
connectected to this particle in a complex
and the patches of the particle that are occupied*/
/**
* @memberVariableOfSpeciesClass is a vector that contains the
* the state of all patches
* for a substrate
* 0 is unphosphorylated
* 1 is phosphorylated
* for an enzyme its always 1
*/
std::vector<int> patchState;
myVector particlePosition; /**3D position of the centre of the particle*/
myVector force; /**force on the particle*/
quaternion q; /**The orientation of the particle in 3 dimensions*/
quaternion torque; /**The torque of the particle*/
std::vector<myVector> patchPos; /** 3D position of the centre of the patch of the particle which is used to
visualize the rotation*/
/*GREENS FUNCTIONS RELATED VARIABLES*/
myVector nextEscapePosition;/**The center of the particle when the particle escapes*/
myVector burstPosition;/**center of the particle when the domain bursts*/
double R;/**This is the radius of displacement of the particle from the original position, after bursting*/
/*DOMAIN RELATED MEMBER VARIABLES*/
int nextReactionType;/**if 0 then nothing (just Brownian step)
if 1 then monomolecular dissociation
if 2 hopping
if 3 phosphorylation/dephosphorylation*/
int nextEventType;/**If 0 its escape(from the domain)
if 1 its reaction
*/
double nextEscapeTime;/**The time at which the next escape occurs*/
double nextReactionTime;/**The time at which the next reaction occurs
minimum of dissociation time, hopping time and phosphorylation time*/
double nextEventTime;/**The time at which the next event occurs, the min of the above two values*/
double timeOfConstructionOfDomain;/**Global time at which the domain is constructed*/
double domainRadius;/**radius of the domain around the particle*/
bool operator < (const particle temp) const
{
return (this->nextEventTime < temp.nextEventTime);
}
/**Function prints out the particle class
*/
friend std::ostream& operator<< (std::ostream &out, particle &part);
/**
This function draws a random position at the sphere of domain radius if the particle escapes
*/
void drawNextEscapePosition();
/**
This function draws a new position for the particle if the domain is prematurely burst
*/
void drawBurstPosition (double time);
/**
This function gets a next event time and type using greens functions for a single domain
*/
void drawNextEventTimeAndType ();
/**
This function builds a domain on the particle which calls the function
@param nearestNeighborDistance radius of the domain to be built
*/
void buildADomain(double nearestNeighborDistance);
/**
This function bursts the given domain it can be used for bursting a domain, moving a particle or converting a particle to a LD particle
@param instruction escape, burst or convert
*/
void burstTheDomain(std::string instruction);
/**
This dissociates a particle in a domain
*/
void dissociateParticleFromDomain();
};/**Particle holds all information related to the particle in the simulation*/
#endif /* PARTICLE_H */
| {
"alphanum_fraction": 0.6423357664,
"avg_line_length": 34.5037037037,
"ext": "h",
"hexsha": "6617dcc3a0fff797aed709a6c720d6975de45e1e",
"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": "693d3bbd40588adb538209d606225b2d7c5f8df8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "adithyavijaykumar/adithyavijaykumar.github.io",
"max_forks_repo_path": "programming/particle.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "693d3bbd40588adb538209d606225b2d7c5f8df8",
"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": "adithyavijaykumar/adithyavijaykumar.github.io",
"max_issues_repo_path": "programming/particle.h",
"max_line_length": 140,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "693d3bbd40588adb538209d606225b2d7c5f8df8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "adithyavijaykumar/adithyavijaykumar.github.io",
"max_stars_repo_path": "programming/particle.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1004,
"size": 4658
} |
#ifndef _GP_H_
#define _GP_H_
#include "armadillo"
using namespace arma;
#include "myTypes.h"
#include "KernelFunction.h"
#include "MeanFunction.h"
#include <gsl/gsl_math.h>
#include <gsl/gsl_multimin.h>
double f_eval_mean(const gsl_vector *x, void *param);
void df_eval_mean(const gsl_vector *x, void *param, gsl_vector *g);
void fdf_eval_mean(const gsl_vector *x, void *param, double *f, gsl_vector *g);
double f_eval_kernel(const gsl_vector *x, void *param);
void df_eval_kernel(const gsl_vector *x, void *param, gsl_vector *g);
void fdf_eval_kernel(const gsl_vector *x, void *param, double *f, gsl_vector *g);
double f_eval_noise(const gsl_vector *x, void *param);
void df_eval_noise(const gsl_vector *x, void *param, gsl_vector *g);
void fdf_eval_noise(const gsl_vector *x, void *param, double *f, gsl_vector *g);
class GP {
public:
GP(REAL s2_n, KernelFunction *kernel, MeanFunction *mean);
void SetTraining(const Mat<REAL>& X, const Row<REAL> &y);
void AddTraining(const Mat<REAL>& X, const Row<REAL> &y);
void Predict(const Mat<REAL> &Xs, Row<REAL> &mu);
void Predict(const Mat<REAL> &Xs, Row<REAL> &mu, Row<REAL> &var);
void Predict(const Col<REAL> &Xs, REAL &mu);
void Predict(const Col<REAL> &Xs, REAL &mu, REAL &var);
void PredictGradient(const Col<REAL> &Xs, Col<REAL> &grad);
void PredictGradient(const Col<REAL> &Xs, Col<REAL> &grad, Col<REAL> &vargrad);
void ComputeAlpha();
void ComputeChol();
void ComputeW();
REAL ComputeLikelihood();
void SetKernelFuncParams(const Col<REAL>& param);
void SetMeanFuncParams(const Col<REAL>& param);
void SetNoise(const REAL &s2_n);
void GradLikelihoodMeanParams(Col<REAL> &grad);
void GradLikelihoodKernelParams(Col<REAL> &grad);
void GradLikelihoodNoise(Col<REAL> &grad);
void HessianLikelihoodMeanParams(Mat<REAL> &hessian);
void OptimizeNoiseParam(REAL &noise_param, int max_iterations=10);
void OptimizeMeanParam(Col<REAL> &mean_param, int max_iterations=10);
void OptimizeKernelParam(Col<REAL> &kernel_param, int max_iterations=10);
inline Mat<REAL> &GetTrainingData() { return X; }
inline KernelFunction *GetKernelFunction() { return this->kernel; }
inline MeanFunction *GetMeanFunction() { return this->mean; }
protected:
KernelFunction *kernel;
MeanFunction *mean;
Mat<REAL> K;
Mat<REAL> W;
Mat<REAL> X;
Mat<REAL> L;
Row<REAL> y;
Row<REAL> meanvals;
Col<REAL> alpha;
REAL s2_n;
REAL loglikelihood;
bool need_to_compute_alpha;
bool need_to_compute_chol;
bool need_to_compute_w;
void MatrixMap(Mat<REAL> &matrix, const Mat<REAL> &a, const Mat<REAL> &b);
};
#endif
| {
"alphanum_fraction": 0.7294520548,
"avg_line_length": 31.2857142857,
"ext": "h",
"hexsha": "2b82f66550300336af9e1411d6a75a4b8b5d7c85",
"lang": "C",
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2022-03-15T15:01:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-28T23:03:17.000Z",
"max_forks_repo_head_hexsha": "0015c066521b9412ebac4cda11559e44094ffdd9",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "RobustFieldAutonomyLab/GP",
"max_forks_repo_path": "src/GP.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "0015c066521b9412ebac4cda11559e44094ffdd9",
"max_issues_repo_issues_event_max_datetime": "2015-08-05T14:31:01.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-04-02T12:19:12.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "RobustFieldAutonomyLab/GP",
"max_issues_repo_path": "src/GP.h",
"max_line_length": 81,
"max_stars_count": 41,
"max_stars_repo_head_hexsha": "0015c066521b9412ebac4cda11559e44094ffdd9",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "jonfink/GP",
"max_stars_repo_path": "src/GP.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-25T00:59:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-02T12:20:54.000Z",
"num_tokens": 775,
"size": 2628
} |
#ifndef PyGSL_COMPLEX_HELPERS_H
#define PyGSL_COMPLEX_HELPERS_H 1
#include <pygsl/utils.h>
#include <pygsl/intern.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_errno.h>
/*
* These macros convert a PyObect to a complex if numeric
* Input recieved. If complex, accessing the data, otherwise
* reverting to a function.
*/
/* -------------------------------------------------------------------------
Helper Functions
------------------------------------------------------------------------- */
PyGSL_API_EXTERN int
PyGSL_PyComplex_to_gsl_complex(PyObject * src, gsl_complex * mycomplex);
PyGSL_API_EXTERN int
PyGSL_PyComplex_to_gsl_complex_float(PyObject * src,
gsl_complex_float * mycomplex);
PyGSL_API_EXTERN int
PyGSL_PyComplex_to_gsl_complex_long_double(PyObject * src,
gsl_complex_long_double * mycomplex);
#ifndef _PyGSL_API_MODULE
#define PyGSL_PyComplex_to_gsl_complex \
(*(int (*) (PyObject *, gsl_complex *)) PyGSL_API[PyGSL_PyComplex_to_gsl_complex_NUM])
#define PyGSL_PyComplex_to_gsl_complex_float \
(*(int (*) (PyObject *, gsl_complex_float *)) PyGSL_API[PyGSL_PyComplex_to_gsl_complex_float_NUM])
#define PyGSL_PyComplex_to_gsl_complex_long_double \
(*(int (*) (PyObject *, gsl_complex_long_double *)) PyGSL_API[PyGSL_PyComplex_to_gsl_complex_long_double_NUM])
#endif /* _PyGSL_API_MODULE */
#define PyGSL_PyCOMPLEX_TO_gsl_complex(object, tmp) \
(PyComplex_Check((object))) ? \
((tmp)->dat[0] = ((PyComplexObject *)(object))->cval.real,\
(tmp)->dat[1] = ((PyComplexObject *)(object))->cval.imag,\
GSL_SUCCESS) \
: PyGSL_PyComplex_to_gsl_complex(object, tmp)
#define PyGSL_PyCOMPLEX_TO_gsl_complex_float(object, tmp ) \
(PyComplex_Check((object))) ? \
((tmp)->dat[0] = ((PyComplexObject *)(object))->cval.real,\
(tmp)->dat[1] = ((PyComplexObject *)(object))->cval.imag,\
GSL_SUCCESS) \
: PyGSL_PyComplex_to_gsl_complex_float(object, tmp)
#define PyGSL_PyCOMPLEX_TO_gsl_complex_long_double(object, tmp ) \
(PyComplex_Check((object))) ? \
((tmp)->dat[0] = ((PyComplexObject *)(object))->cval.real, \
(tmp)->dat[1] = ((PyComplexObject *)(object))->cval.imag, \
GSL_SUCCESS) \
: PyGSL_PyComplex_to_gsl_complex_long_double(object, tmp)
#endif /* PyGSL_COMPLEX_HELPERS_H */
| {
"alphanum_fraction": 0.6219319082,
"avg_line_length": 44.3157894737,
"ext": "h",
"hexsha": "1719003716c8f38ffc1546da07d53affdaadaa58",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/Include/pygsl/complex_helpers.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/Include/pygsl/complex_helpers.h",
"max_line_length": 111,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/Include/pygsl/complex_helpers.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 630,
"size": 2526
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.