Search is not available for this dataset
text string | meta dict |
|---|---|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_errno.h>
#include "ccl.h"
ccl_a_finder *ccl_a_finder_new(int na, double *a_arr)
{
if(na<=0)
return NULL;
ccl_a_finder *finda=malloc(sizeof(ccl_a_finder));
if(finda == NULL)
return NULL;
finda->ia_last=0;
finda->amin = a_arr[0];
finda->amax = a_arr[na-1];
finda->na = na;
finda->a_arr = malloc(na*sizeof(double));
if(finda->a_arr==NULL) {
free(finda);
return NULL;
}
memcpy(finda->a_arr, a_arr, na*sizeof(double));
return finda;
}
void ccl_a_finder_free(ccl_a_finder *finda)
{
if(finda!=NULL) {
if(finda->na>0)
free(finda->a_arr);
free(finda);
}
}
int ccl_find_a_index(ccl_a_finder *finda, double a)
{
int ia_0;
if(a>=finda->amax)
ia_0=finda->na-1;
else if(a<=finda->amin)
ia_0=0;
else {
int gotit=0;
ia_0=finda->ia_last;
while(!gotit) {
if(ia_0==0) {
if(a<finda->a_arr[1])
gotit=1;
else
ia_0++;
}
else if(ia_0==finda->na-1) {
if(a>=finda->a_arr[ia_0-1])
gotit=1;
ia_0--;
}
else {
if(a<finda->a_arr[ia_0])
ia_0--;
else {
if(a>=finda->a_arr[ia_0+1])
ia_0++;
else
gotit=1;
}
}
}
}
finda->ia_last = ia_0;
return ia_0;
}
ccl_f3d_t *ccl_f3d_t_copy(ccl_f3d_t *f3d_o, int *status)
{
int ia, s2dstatus=0;
ccl_f3d_t *f3d = malloc(sizeof(ccl_f3d_t));
if (f3d == NULL)
*status = CCL_ERROR_MEMORY;
if(*status==0) {
f3d->lkmin = f3d_o->lkmin;
f3d->lkmax = f3d_o->lkmax;
f3d->na = f3d_o->na;
f3d->is_product = f3d_o->is_product;
f3d->extrap_linear_growth = f3d_o->extrap_linear_growth;
f3d->extrap_order_lok = f3d_o->extrap_order_lok;
f3d->extrap_order_hik = f3d_o->extrap_order_hik;
f3d->is_log = f3d_o->is_log;
f3d->growth_factor_0 = f3d_o->growth_factor_0;
f3d->growth_exponent = f3d_o->growth_exponent;
f3d->a_arr = malloc(f3d->na*sizeof(double));
if(f3d->a_arr == NULL)
*status = CCL_ERROR_MEMORY;
}
if(*status==0) {
memcpy(f3d->a_arr, f3d_o->a_arr, f3d->na*sizeof(double));
if(f3d_o->fka_1 != NULL)
f3d->fka_1 = ccl_f2d_t_copy(f3d_o->fka_1, status);
else
f3d->fka_1 = NULL;
}
if(*status==0) {
if(f3d_o->fka_2 != NULL)
f3d->fka_2 = ccl_f2d_t_copy(f3d_o->fka_2, status);
else
f3d->fka_2 = NULL;
}
if(*status==0) {
if(f3d_o->tkka != NULL) {
f3d->tkka = malloc(f3d->na*sizeof(gsl_spline2d));
if (f3d->tkka == NULL)
*status = CCL_ERROR_MEMORY;
if(*status == 0) {
s2dstatus = 0;
for(ia=0; ia<f3d->na; ia++) {
f3d->tkka[ia] = gsl_spline2d_alloc(gsl_interp2d_bicubic,
f3d_o->tkka[ia]->interp_object.xsize,
f3d_o->tkka[ia]->interp_object.ysize);
if(f3d->tkka[ia] == NULL)
*status = CCL_ERROR_MEMORY;
if(*status==0) {
s2dstatus |= gsl_spline2d_init(f3d->tkka[ia],
f3d_o->tkka[ia]->xarr,
f3d_o->tkka[ia]->yarr,
f3d_o->tkka[ia]->zarr,
f3d_o->tkka[ia]->interp_object.xsize,
f3d_o->tkka[ia]->interp_object.ysize);
if(s2dstatus)
*status = CCL_ERROR_SPLINE;
}
}
}
}
else
f3d->tkka = NULL;
}
return f3d;
}
ccl_f3d_t *ccl_f3d_t_new(int na,double *a_arr,
int nk,double *lk_arr,
double *tkka_arr,
double *fka1_arr,
double *fka2_arr,
int is_product,
int extrap_order_lok,
int extrap_order_hik,
ccl_f2d_extrap_growth_t extrap_linear_growth,
int is_tkka_log,
double growth_factor_0,
int growth_exponent,
ccl_f2d_interp_t interp_type,
int *status) {
int ia, s2dstatus;
ccl_f3d_t *f3d = malloc(sizeof(ccl_f3d_t));
if (f3d == NULL)
*status = CCL_ERROR_MEMORY;
if (*status == 0) {
is_product = is_product || (tkka_arr == NULL);
f3d->is_product = is_product;
f3d->extrap_order_lok = extrap_order_lok;
f3d->extrap_order_hik = extrap_order_hik;
f3d->extrap_linear_growth = extrap_linear_growth;
f3d->is_log = is_tkka_log;
f3d->growth_factor_0 = growth_factor_0;
f3d->growth_exponent = growth_exponent;
f3d->fka_1 = NULL;
f3d->fka_2 = NULL;
f3d->tkka = NULL;
f3d->lkmin = lk_arr[0];
f3d->lkmax = lk_arr[nk-1];
f3d->na = na;
f3d->a_arr = malloc(na*sizeof(double));
if(f3d->a_arr == NULL)
*status = CCL_ERROR_MEMORY;
}
if (*status == 0)
memcpy(f3d->a_arr, a_arr, na*sizeof(double));
if ((extrap_order_lok > 1) || (extrap_order_lok < 0) ||
(extrap_order_hik > 1) || (extrap_order_hik < 0))
*status = CCL_ERROR_INCONSISTENT;
if ((extrap_linear_growth != ccl_f2d_cclgrowth) &&
(extrap_linear_growth != ccl_f2d_constantgrowth) &&
(extrap_linear_growth != ccl_f2d_no_extrapol))
*status = CCL_ERROR_INCONSISTENT;
if (f3d->is_product) {
if ((fka1_arr == NULL) || (fka2_arr == NULL))
*status = CCL_ERROR_INCONSISTENT;
}
else {
if (tkka_arr == NULL)
*status = CCL_ERROR_INCONSISTENT;
}
if(*status == 0) {
if (f3d->is_product) {
f3d->fka_1 = ccl_f2d_t_new(na, a_arr,
nk, lk_arr,
fka1_arr, NULL, NULL, 0,
extrap_order_lok, extrap_order_hik,
extrap_linear_growth,
is_tkka_log,
growth_factor_0, growth_exponent/2,
interp_type, status);
f3d->fka_2 = ccl_f2d_t_new(na, a_arr,
nk, lk_arr,
fka2_arr, NULL, NULL, 0,
extrap_order_lok, extrap_order_hik,
extrap_linear_growth,
is_tkka_log,
growth_factor_0, growth_exponent/2,
interp_type, status);
}
else {
switch(interp_type) {
case(ccl_f2d_3):
f3d->tkka = malloc(na*sizeof(gsl_spline2d));
if (f3d->tkka == NULL)
*status = CCL_ERROR_MEMORY;
if(*status == 0) {
for(ia=0; ia<na; ia++) {
double *tkk = &(tkka_arr[ia*nk*nk]);
f3d->tkka[ia] = gsl_spline2d_alloc(gsl_interp2d_bicubic, nk, nk);
if (f3d->tkka[ia] == NULL) {
*status = CCL_ERROR_MEMORY;
break;
}
s2dstatus = gsl_spline2d_init(f3d->tkka[ia],
lk_arr, lk_arr, tkk, nk, nk);
if (s2dstatus) {
*status = CCL_ERROR_SPLINE;
break;
}
}
}
break;
default:
f3d->tkka = NULL;
}
}
}
return f3d;
}
double ccl_f3d_t_eval(ccl_f3d_t *f3d,double lk1,double lk2,double a,ccl_a_finder *finda,
void *cosmo, int *status) {
double tkka_post;
double a_ev = a;
int is_hiz = a < f3d->a_arr[0];
int is_loz = a > f3d->a_arr[f3d->na-1];
if (is_loz) { // Are we above the interpolation range in a?
if (f3d->extrap_linear_growth == ccl_f2d_no_extrapol) {
*status=CCL_ERROR_SPLINE_EV;
return NAN;
}
a_ev = f3d->a_arr[f3d->na-1];
}
else if (is_hiz) { // Are we below the interpolation range in a?
if (f3d->extrap_linear_growth == ccl_f2d_no_extrapol) {
*status=CCL_ERROR_SPLINE_EV;
return NAN;
}
a_ev = f3d->a_arr[0];
}
if (f3d->is_product) {
double fka1 = ccl_f2d_t_eval(f3d->fka_1, lk1, a_ev, cosmo, status);
double fka2 = ccl_f2d_t_eval(f3d->fka_2, lk2, a_ev, cosmo, status);
if(*status != 0)
return NAN;
tkka_post = fka1*fka2;
}
else {
double lk1_ev = lk1;
int is_hik1 = lk1 > f3d->lkmax;
int is_lok1 = lk1 < f3d->lkmin;
int extrap_k1 = (is_hik1 & (f3d->extrap_order_hik > 0)) || (is_lok1 & (f3d->extrap_order_lok > 0));
if (is_hik1) // Are we above the interpolation range in k?
lk1_ev = f3d->lkmax;
else if (is_lok1) // Are we below the interpolation range in k?
lk1_ev = f3d->lkmin;
double lk2_ev = lk2;
int is_hik2 = lk2 > f3d->lkmax;
int is_lok2 = lk2 < f3d->lkmin;
int extrap_k2 = (is_hik2 & (f3d->extrap_order_hik > 0)) || (is_lok2 & (f3d->extrap_order_lok > 0));
if (is_hik2) // Are we above the interpolation range in k?
lk2_ev = f3d->lkmax;
else if (is_lok2) // Are we below the interpolation range in k?
lk2_ev = f3d->lkmin;
int ia = ccl_find_a_index(finda, a_ev);
if(*status == 0) {
int spstatus = 0;
double tkka, dtkka1, dtkka2;
spstatus |= gsl_spline2d_eval_e(f3d->tkka[ia], lk1_ev, lk2_ev,
NULL, NULL, &tkka);
if(extrap_k1)
spstatus |= gsl_spline2d_eval_deriv_x_e(f3d->tkka[ia], lk1_ev, lk2_ev,
NULL, NULL, &dtkka1);
if(extrap_k2)
spstatus |= gsl_spline2d_eval_deriv_y_e(f3d->tkka[ia], lk1_ev, lk2_ev,
NULL, NULL, &dtkka2);
if(ia < f3d->na-1) {
double tkka_p1, dtkka1_p1, dtkka2_p1;
double h = (a_ev-f3d->a_arr[ia])/(f3d->a_arr[ia+1]-f3d->a_arr[ia]);
spstatus |= gsl_spline2d_eval_e(f3d->tkka[ia+1], lk1_ev, lk2_ev,
NULL, NULL, &tkka_p1);
if(!spstatus)
tkka = tkka*(1-h) + tkka_p1*h;
if(extrap_k1) {
spstatus |= gsl_spline2d_eval_deriv_x_e(f3d->tkka[ia+1], lk1_ev, lk2_ev,
NULL, NULL, &dtkka1_p1);
if(!spstatus)
dtkka1 = dtkka1*(1-h) + dtkka1_p1*h;
}
if(extrap_k2) {
spstatus |= gsl_spline2d_eval_deriv_y_e(f3d->tkka[ia+1], lk1_ev, lk2_ev,
NULL, NULL, &dtkka2_p1);
if(!spstatus)
dtkka2 = dtkka2*(1-h) + dtkka2_p1*h;
}
}
if(spstatus) {
*status = CCL_ERROR_SPLINE_EV;
return NAN;
}
// Extrapolate if needed
if(extrap_k1)
tkka += dtkka1 * (lk1 - lk1_ev);
if(extrap_k2)
tkka += dtkka2 * (lk2 - lk2_ev);
tkka_post = tkka;
}
// Exponentiate if needed
if (f3d->is_log)
tkka_post = exp(tkka_post);
}
// Extrapolate in a if needed
if (is_hiz) {
double gz;
if (f3d->extrap_linear_growth == ccl_f2d_cclgrowth) { // Use CCL's growth function
ccl_cosmology *csm = (ccl_cosmology *)cosmo;
if (!csm->computed_growth) {
*status = CCL_ERROR_GROWTH_INIT;
ccl_cosmology_set_status_message(
csm,
"ccl_f3d.c: ccl_f3d_t_eval(): growth factor splines have not been precomputed!");
return NAN;
}
gz = (
ccl_growth_factor(csm, a, status) /
ccl_growth_factor(csm, a_ev, status));
}
else // Use constant growth factor
gz = f3d->growth_factor_0;
tkka_post *= pow(gz, f3d->growth_exponent);
}
return tkka_post;
}
void ccl_f3d_t_free(ccl_f3d_t *f3d)
{
if(f3d != NULL) {
if(f3d->fka_1 != NULL)
ccl_f2d_t_free(f3d->fka_1);
if(f3d->fka_2 != NULL)
ccl_f2d_t_free(f3d->fka_2);
if(f3d->tkka != NULL) {
int ia;
for(ia=0; ia<f3d->na; ia++)
gsl_spline2d_free(f3d->tkka[ia]);
free(f3d->tkka);
}
if(f3d->na > 0)
free(f3d->a_arr);
free(f3d);
}
}
ccl_a_finder *ccl_a_finder_new_from_f3d(ccl_f3d_t *f3d)
{
return ccl_a_finder_new(f3d->na, f3d->a_arr);
}
| {
"alphanum_fraction": 0.5317853373,
"avg_line_length": 29.1182033097,
"ext": "c",
"hexsha": "0eee82eeb3999f70d8a36a0b753e963e51987459",
"lang": "C",
"max_forks_count": 54,
"max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z",
"max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Jappenn/CCL",
"max_forks_repo_path": "src/ccl_f3d.c",
"max_issues_count": 703,
"max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f",
"max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "Jappenn/CCL",
"max_issues_repo_path": "src/ccl_f3d.c",
"max_line_length": 104,
"max_stars_count": 91,
"max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Jappenn/CCL",
"max_stars_repo_path": "src/ccl_f3d.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z",
"num_tokens": 4088,
"size": 12317
} |
//This program takes a double array and returns the roots of the polynomial defined by them. The roots in question can be complex, and the complex data type will need usage in modelica.
#include <stdio.h>
#include <gsl/gsl_poly.h>
void poly_roots(double* a, const size_t size,double *z,size_t size_z);
void poly_roots(double* a, const size_t size,double *z,size_t size_z)
{
/* coefficients of P(x) = -1 + x^5 */
gsl_poly_complex_workspace * w = gsl_poly_complex_workspace_alloc ((size+1));
gsl_poly_complex_solve (a, size+1, w, z);
gsl_poly_complex_workspace_free (w);
for (int i = 0; i < size; i++)
{
printf ("z%d = %+.18f %+.18f\n",
i, z[2*i], z[2*i+1]);
}
}
//The main function has been provided solely for the sake of testing the function. It will be removed when the problem set is formally passed on.
/*
int main (void)
{
double a[6] = { -1, 0, 0, 0, 0, 1 };
int size_a = 5;
double *z;
poly_roots(a, size_a,z, 10);
return 0;
}
*/
| {
"alphanum_fraction": 0.6589769308,
"avg_line_length": 24.925,
"ext": "c",
"hexsha": "2237c6673d178b86be9f6bc80890bf44640e4737",
"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": "5836c24e21e53f31a43074468064a6c17c67845e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "RITUait/OpenModelica",
"max_forks_repo_path": "TestSample/Resources/Include/p3.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e",
"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": "RITUait/OpenModelica",
"max_issues_repo_path": "TestSample/Resources/Include/p3.c",
"max_line_length": 185,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5836c24e21e53f31a43074468064a6c17c67845e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "RITUait/OpenModelica",
"max_stars_repo_path": "Resources/Include/p3.c",
"max_stars_repo_stars_event_max_datetime": "2019-11-03T04:23:39.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-03T04:23:39.000Z",
"num_tokens": 298,
"size": 997
} |
#pragma once
#if SEAL_COMPILER == SEAL_COMPILER_MSVC
// Require Visual Studio 2015 or newer and C++14 support
#if (_MSC_VER < 1900) || (_MSVC_LANG < 201402L)
#error "Microsoft Visual Studio 2015 (14.0) or newer required; C++14 support required"
#endif
// Can work with Visual Studio 2015 (C++14) with some limitations
#if _MSVC_LANG == 1900
#undef SEAL_USE_SHARED_MUTEX_FOR_RW_LOCK
#endif
// Deal with Debug mode in Visual Studio
#ifdef _DEBUG
#define SEAL_DEBUG
#endif
// Cannot use std::shared_mutex when compiling with /clr
#ifdef _M_CEE
#undef SEAL_USE_SHARED_MUTEX_FOR_RW_LOCK
#endif
// Try to check presence of additional headers using __has_include
#ifdef __has_include
// Check for MSGSL
#if __has_include(<gsl/gsl>)
#include <gsl/gsl>
#define SEAL_USE_MSGSL
#else
#undef SEAL_USE_MSGSL
#endif //__has_include(<gsl/gsl>)
#endif
// X64
#ifdef _M_X64
// Use compiler intrinsics for better performance
#define SEAL_USE_INTRIN
#ifdef SEAL_USE_INTRIN
#include <intrin.h>
#pragma intrinsic(_addcarry_u64)
#define SEAL_ADD_CARRY_UINT64(operand1, operand2, carry, result) _addcarry_u64( \
carry, \
static_cast<unsigned long long>(operand1), \
static_cast<unsigned long long>(operand2), \
reinterpret_cast<unsigned long long*>(result))
#pragma intrinsic(_subborrow_u64)
#define SEAL_SUB_BORROW_UINT64(operand1, operand2, borrow, result) _subborrow_u64( \
borrow, \
static_cast<unsigned long long>(operand1), \
static_cast<unsigned long long>(operand2), \
reinterpret_cast<unsigned long long*>(result))
#pragma intrinsic(_BitScanReverse64)
#define SEAL_MSB_INDEX_UINT64(result, value) _BitScanReverse64(result, value)
#pragma intrinsic(_umul128)
#define SEAL_MULTIPLY_UINT64(operand1, operand2, result128) { \
result128[0] = _umul128( \
static_cast<unsigned long long>(operand1), \
static_cast<unsigned long long>(operand2), \
reinterpret_cast<unsigned long long*>(result128 + 1)); \
}
#define SEAL_MULTIPLY_UINT64_HW64(operand1, operand2, hw64) { \
_umul128( \
static_cast<unsigned long long>(operand1), \
static_cast<unsigned long long>(operand2), \
reinterpret_cast<unsigned long long*>(hw64)); \
}
#endif
#else
#undef SEAL_USE_INTRIN
#endif //_M_X64
#endif | {
"alphanum_fraction": 0.5804459691,
"avg_line_length": 34.7023809524,
"ext": "h",
"hexsha": "20e06aeec9e6ba4491d1bbe975badcbea59c0499",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-11-26T02:31:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-05-29T10:15:40.000Z",
"max_forks_repo_head_hexsha": "dca915e0964f6ae1b891876e64101f09c1ecfe08",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MarbleHE/SEAL4Pyfhel",
"max_forks_repo_path": "SEAL/seal2/msvc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "dca915e0964f6ae1b891876e64101f09c1ecfe08",
"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": "MarbleHE/SEAL4Pyfhel",
"max_issues_repo_path": "SEAL/seal2/msvc.h",
"max_line_length": 86,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "dca915e0964f6ae1b891876e64101f09c1ecfe08",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MarbleHE/SEAL4Pyfhel",
"max_stars_repo_path": "SEAL/seal2/msvc.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-27T06:25:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-01-19T17:09:42.000Z",
"num_tokens": 601,
"size": 2915
} |
/*
Pierwszy program stosuje metode Brenta
gsl_root_fsolver_brent
dla rownania
x^2 - 5 = 0
rozwiazaniem jest x = \sqrt 5 = 2.236068...
*/
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_roots.h>
#include <string.h>
#include "demo_fn.h"
int
main (int argc, char *argv[])
{
int status;
int iter = 0, max_iter = 100;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
double r = 0, r_expected = sqrt (5.0);
double x_lo = 0.0, x_hi = 5.0;
gsl_function F;
struct quadratic_params params = {1.0, -2.0, 1.0};
F.function = &quadratic;
F.params = ¶ms;
if (argc < 2) {
errno = EINVAL;
perror("");
return errno;
}
char *method = argv[1];
if (0 == strcmp("bisection", method)) {
T = gsl_root_fsolver_bisection;
} else if (0 == strcmp("secant", method)) {
T = gsl_root_fsolver_brent;
} else if (0 == strcmp("steffenson", method)) {
T = gsl_root_fsolver_falsepos;
} else {
errno = EINVAL;
perror("");
return errno;
}
T = gsl_root_fsolver_bisection;
s = gsl_root_fsolver_alloc (T);
gsl_root_fsolver_set (s, &F, x_lo, x_hi);
printf ("using %s method\n",
gsl_root_fsolver_name (s));
printf ("%5s [%9s, %9s] %9s %10s %9s\n",
"iter", "lower", "upper", "root",
"err", "err(est)");
do
{
iter++;
status = gsl_root_fsolver_iterate (s);
r = gsl_root_fsolver_root (s);
x_lo = gsl_root_fsolver_x_lower (s);
x_hi = gsl_root_fsolver_x_upper (s);
status = gsl_root_test_interval (x_lo, x_hi,
0, 0.001);
if (status == GSL_SUCCESS)
printf ("Converged:\n");
printf ("%5d [%.7f, %.7f] %.7f %+.7f %.7f\n",
iter, x_lo, x_hi,
r, r - r_expected,
x_hi - x_lo);
}
while (status == GSL_CONTINUE && iter < max_iter);
return status;
}
| {
"alphanum_fraction": 0.5737874097,
"avg_line_length": 23.0714285714,
"ext": "c",
"hexsha": "499c11d61de298465288a94e19e76377a933e16d",
"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": "d88c21308b863942497c111d044e359ce220d421",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mistyfiky/agh-mownit",
"max_forks_repo_path": "lab5/root_finding_modified.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421",
"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": "mistyfiky/agh-mownit",
"max_issues_repo_path": "lab5/root_finding_modified.c",
"max_line_length": 52,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d88c21308b863942497c111d044e359ce220d421",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mistyfiky/agh-mownit",
"max_stars_repo_path": "lab5/root_finding_modified.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 621,
"size": 1938
} |
//-*-C++-*-
/***************************************************************************
*
* Copyright (C) 2008 by Paul Demorest
* Licensed under the Academic Free License version 2.1
*
***************************************************************************/
#ifndef __Pulsar_Wavelet_h
#define __Pulsar_Wavelet_h
#include "ReferenceAble.h"
#include <gsl/gsl_wavelet.h>
namespace Pulsar {
class Profile;
//! Performs 1-D discrete wavelet transforms (DWT)
/*! This class is basically a wrapper for the GSL wavelet implementation.
* Refer to GSL documentation for more info.
*/
class WaveletTransform : public Reference::Able {
public:
//! Constructor
WaveletTransform();
//! Destructor
~WaveletTransform();
//! Set wavelet type
/*! Possible types (as of GSL 1.11) are:
* <ol>
* <li> gsl_wavelet_daubechies
* <li> gsl_wavelet_haar
* <li> gsl_wavelet_bspline
* </ol>
* All types can have _centered appended to their name to
* get centered versions.
*/
void set_type(const gsl_wavelet_type *t) { type=t; };
//! Set wavelet order
/*! Implemented values (as of GSL 1.11) are:
* <ol>
* <li> daubechies: order=4,6,...,20 (even values only).
* <li> haar: order=2 only.
* <li> bspline: order=103,105,202,204,206,208,301,303,305,307,309.
* </ol>
*/
void set_order(int o) { order=o; };
//! Set wavelet type and order using short string notation
void set_wavelet(std::string s);
//! Set whether or not to decimate during transform
void set_decimate(bool _dec=true) { decimate = _dec; }
//! Perform forward transform
void transform(unsigned npts, const float *in);
//! Perform forward transform
void transform(const std::vector<float>& in);
//! Perform forward transform
void transform(const Pulsar::Profile* in);
//! Perform inverse transform in-place
void invert();
//! Possible states of the data
enum State { Wavelet, Time, Empty };
//! Get decimation setting
const bool get_decimate() const { return decimate; }
//! Get current state
State get_state() { return state; }
//! Get wavelet data
double get_data(int level, int k);
//! Get data element
double get_data(int n);
//! Get pointer to data array
double* get_data();
//! Get const pointer to data array
const double* get_data() const;
//! Get number of pts currently in use
const int get_npts() const { return npts; };
//! Get log2 of number of pts currently in use
const int get_log2_npts() const { return log2_npts; };
//! Get total number of wavelet coeffs computed
const int get_ncoeff() const { return decimate ? npts : log2_npts*npts; }
//! Get number of coeffs at a given level
const int get_ncoeff(int level) const;
protected:
//! Wavelet type
const gsl_wavelet_type *type;
//! Use decimated (standard) or undecimated transform
bool decimate;
//! Wavelet order
int order;
//! Wavelet coeffs
gsl_wavelet *wave;
//! Number of points
int npts;
//! Log2 of npts
int log2_npts;
//! Data storage
double *data;
//! Mean of data
double mean;
//! Current state of the data
State state;
//! GSL workspace
gsl_wavelet_workspace *work;
private:
//! Free internal memory
void free_mem();
//! Allocate internal memory, set up wavelet coeffs
void init_mem();
};
}
#endif
| {
"alphanum_fraction": 0.5763348538,
"avg_line_length": 24.3594771242,
"ext": "h",
"hexsha": "59057746a034c70b9f0d53fc601c2efe1cd4c336",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-02-13T20:08:14.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-02-13T20:08:14.000Z",
"max_forks_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35",
"max_forks_repo_licenses": [
"AFL-2.1"
],
"max_forks_repo_name": "xuanyuanstar/psrchive_CDFT",
"max_forks_repo_path": "More/General/Pulsar/WaveletTransform.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"AFL-2.1"
],
"max_issues_repo_name": "xuanyuanstar/psrchive_CDFT",
"max_issues_repo_path": "More/General/Pulsar/WaveletTransform.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35",
"max_stars_repo_licenses": [
"AFL-2.1"
],
"max_stars_repo_name": "xuanyuanstar/psrchive_CDFT",
"max_stars_repo_path": "More/General/Pulsar/WaveletTransform.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 908,
"size": 3727
} |
/**
*
* @file core_dgbtype1cb.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 Azzam Haidar
* @date 2012-12-15
* @generated d Tue Jan 7 11:44:49 2014
*
**/
#include <lapacke.h>
#include "common.h"
//#define AU(m,n) &(A[(m) + LDA*(n)])
//#define AL(m,n) &(A[(m) + LDA*(n)])
#define AL(m_, n_) (A + NB + LDA * (n_) + ((m_)-(n_)))
#define AU(m_, n_) (A + NB + LDA * (n_) + ((m_)-(n_)+NB))
#define VQ(m) (VQ + (m))
#define VP(m) (VP + (m))
#define TAUQ(m) (TAUQ + (m))
#define TAUP(m) (TAUP + (m))
/***************************************************************************//**
*
* @ingroup CORE_double
*
* CORE_dgbtype1cb is a kernel that will operate on a region (triangle) of data
* bounded by st and ed. This kernel eliminate a column by an column-wise
* annihiliation, then it apply a left+right update on the hermitian triangle.
* Note that the column to be eliminated is located at st-1.
*
* All detail are available on technical report or SC11 paper.
* Azzam Haidar, Hatem Ltaief, and Jack Dongarra. 2011.
* Parallel reduction to condensed forms for symmetric eigenvalue problems
* using aggregated fine-grained and memory-aware kernels. In Proceedings
* of 2011 International Conference for High Performance Computing,
* Networking, Storage and Analysis (SC '11). ACM, New York, NY, USA, ,
* Article 8 , 11 pages.
* http://doi.acm.org/10.1145/2063384.2063394
*
*******************************************************************************
*
* @param[in] N
* The order of the matrix A.
*
* @param[in] NB
* The size of the band.
*
* @param[in, out] A
* A pointer to the matrix A of size (3*NB+1)-by-N.
*
* @param[in] LDA
* The leading dimension of the matrix A. LDA >= max(1,3*NB+1)
*
* @param[out] V
* double array, dimension N if eigenvalue only
* requested or (LDV*blkcnt*Vblksiz) if Eigenvectors requested
* The Householder reflectors are stored in this array.
*
* @param[out] TAU
* double array, dimension (N).
* The scalar factors of the Householder reflectors are stored
* in this array.
*
* @param[in] st
* A pointer to the start index where this kernel will operate.
*
* @param[in] ed
* A pointer to the end index where this kernel will operate.
*
* @param[in] sweep
* The sweep number that is eliminated. it serve to calculate the
* pointer to the position where to store the Vs and Ts.
*
* @param[in] Vblksiz
* constant which correspond to the blocking used when applying the Vs.
* it serve to calculate the pointer to the position where to store the
* Vs and Ts.
*
* @param[in] WANTZ
* constant which indicate if Eigenvalue are requested or both
* Eigenvalue/Eigenvectors.
*
* @param[in] WORK
* Workspace of size nb.
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
*
******************************************************************************/
/***************************************************************************
* TYPE 1-BAND-bidiag Lower/Upper columnwise-Householder
***************************************************************************/
void
CORE_dgbtype1cb(PLASMA_enum uplo, int N, int NB,
double *A, int LDA,
double *VQ, double *TAUQ,
double *VP, double *TAUP,
int st, int ed, int sweep, int Vblksiz, int WANTZ,
double *WORK)
{
double ctmp;
int i, len, LDX, lenj;
int blkid, vpos, taupos, tpos;
/* find the pointer to the Vs and Ts as stored by the bulgechasing
* note that in case no eigenvector required V and T are stored
* on a vector of size N
* */
if( WANTZ == 0 ) {
vpos = ((sweep+1)%2)*N + st;
taupos = ((sweep+1)%2)*N + st;
} else {
findVTpos(N, NB, Vblksiz, sweep, st,
&vpos, &taupos, &tpos, &blkid);
}
LDX = LDA-1;
len = ed-st+1;
if( uplo == PlasmaUpper ) {
/* ========================
* UPPER CASE
* ========================*/
/* Eliminate the row at st-1 */
*VP(vpos) = 1.;
for(i=1; i<len; i++){
*VP(vpos+i) = (*AU(st-1, st+i));
*AU(st-1, st+i) = 0.;
}
ctmp = (*AU(st-1, st));
LAPACKE_dlarfg_work(len, &ctmp, VP(vpos+1), 1, TAUP(taupos) );
*AU(st-1, st) = ctmp;
/* Apply right on A(st:ed,st:ed) */
ctmp = *TAUP(taupos);
LAPACKE_dlarfx_work(LAPACK_COL_MAJOR, lapack_const(PlasmaRight),
len, len, VP(vpos), ctmp, AU(st, st), LDX, WORK);
/* Eliminate the created col at st */
*VQ(vpos) = 1.;
memcpy( VQ(vpos+1), AU(st+1, st), (len-1)*sizeof(double) );
memset( AU(st+1, st), 0, (len-1)*sizeof(double) );
LAPACKE_dlarfg_work(len, AU(st, st), VQ(vpos+1), 1, TAUQ(taupos) );
lenj = len-1;
ctmp = (*TAUQ(taupos));
LAPACKE_dlarfx_work(LAPACK_COL_MAJOR, lapack_const(PlasmaLeft),
len, lenj, VQ(vpos), ctmp, AU(st, st+1), LDX, WORK);
}else{
/* ========================
* LOWER CASE
* ========================*/
/* Eliminate the col at st-1 */
*VQ(vpos) = 1.;
memcpy( VQ(vpos+1), AL(st+1, st-1), (len-1)*sizeof(double) );
memset( AL(st+1, st-1), 0, (len-1)*sizeof(double) );
LAPACKE_dlarfg_work(len, AL(st, st-1), VQ(vpos+1), 1, TAUQ(taupos) );
/* Apply left on A(st:ed,st:ed) */
ctmp = (*TAUQ(taupos));
LAPACKE_dlarfx_work(LAPACK_COL_MAJOR, lapack_const(PlasmaLeft),
len, len, VQ(vpos), ctmp, AL(st, st), LDX, WORK);
/* Eliminate the created row at st */
*VP(vpos) = 1.;
for(i=1; i<len; i++){
*VP(vpos+i) = (*AL(st, st+i));
*AL(st, st+i) = 0.;
}
ctmp = (*AL(st, st));
LAPACKE_dlarfg_work(len, &ctmp, VP(vpos+1), 1, TAUP(taupos) );
*AL(st, st) = ctmp;
lenj = len-1;
ctmp = (*TAUP(taupos));
LAPACKE_dlarfx_work(LAPACK_COL_MAJOR, lapack_const(PlasmaRight),
lenj, len, VP(vpos), ctmp, AL(st+1, st), LDX, WORK);
}
/* end of uplo case */
return;
}
/***************************************************************************/
#undef AU
#undef AL
#undef VQ
#undef VP
#undef TAUQ
#undef TAUP
| {
"alphanum_fraction": 0.5053967328,
"avg_line_length": 35.8952879581,
"ext": "c",
"hexsha": "d61a26e4ca86f752a3b2e436298ee2517a3da4d2",
"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_dgbtype1cb.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_dgbtype1cb.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_dgbtype1cb.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1968,
"size": 6856
} |
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>
#include <gbpLib.h>
#include <gbpRNG.h>
#include <gbpMCMC.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_interp.h>
void compute_MCMC_chain_stats(double **x,
int n_x,
int n_avg,
double * x_min,
double * x_bar_in,
double * x_max,
double * x_sigma,
double **auto_cor,
double * slopes,
double * dP_sub,
double * ln_Pr_in,
double * ln_Pr_min,
double * ln_Pr_avg,
double * ln_Pr_max) {
int i_P;
int i_avg;
double *x_bar;
double *s_temp;
double c0, c1, cov00, cov01, cov11, sumsq;
double covar;
double var;
// Allocate a temporary array for the mean if it hasn't been given/isn't requested but is needed
if((x_sigma != NULL || auto_cor != NULL || slopes != NULL) && x_bar_in == NULL)
x_bar = (double *)SID_malloc(sizeof(double) * n_x);
else
x_bar = x_bar_in;
// Compute the mean (if it's requested/needed)
if(x_bar != NULL) {
for(i_P = 0; i_P < n_x; i_P++) {
x_bar[i_P] = 0.;
for(i_avg = 0; i_avg < n_avg; i_avg++)
x_bar[i_P] += x[i_P][i_avg];
x_bar[i_P] /= (double)n_avg;
}
}
// Compute the std deviation (if it's requested/needed)
if(x_sigma != NULL) {
for(i_P = 0; i_P < n_x; i_P++) {
x_sigma[i_P] = 0.;
for(i_avg = 0; i_avg < n_avg; i_avg++)
x_sigma[i_P] += pow(x[i_P][i_avg] - x_bar[i_P], 2.);
x_sigma[i_P] = sqrt(x_sigma[i_P] / (double)n_avg);
}
}
// Compute the slope across the interval (if it's requested/needed)
if(slopes != NULL) {
s_temp = (double *)SID_malloc(sizeof(double) * n_avg);
for(i_avg = 0; i_avg < n_avg; i_avg++)
s_temp[i_avg] = (double)i_avg;
for(i_P = 0; i_P < n_x; i_P++) {
gsl_fit_linear(s_temp, 1, x[i_P], 1, n_avg, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);
slopes[i_P] = c1;
if(dP_sub != NULL)
dP_sub[i_P] = sqrt(sumsq / (double)n_avg);
}
SID_free(SID_FARG s_temp);
}
// Compute the auto correlation function (if it's requested/needed)
if(auto_cor != NULL) {
for(i_P = 0; i_P < n_x; i_P++) {
for(i_P = 1; i_P < n_avg; i_P++) {
for(i_avg = 0, var = 0., covar = 0.; i_avg < (n_avg - i_P); i_avg++) {
covar += (x[i_P][i_avg] - x_bar[i_P]) * (x[i_P][i_avg + i_P] - x_bar[i_P]);
var += (x[i_P][i_avg] - x_bar[i_P]) * (x[i_P][i_avg] - x_bar[i_P]);
}
auto_cor[i_P][i_P - 1] = covar / var;
}
}
}
// Compute ln_Pr statistics
if(ln_Pr_in != NULL) {
(*ln_Pr_min) = ln_Pr_in[0];
(*ln_Pr_avg) = ln_Pr_in[0];
(*ln_Pr_max) = ln_Pr_in[0];
for(i_avg = 1; i_avg < n_avg; i_avg++) {
(*ln_Pr_min) = GBP_MIN((*ln_Pr_min), ln_Pr_in[i_avg]);
(*ln_Pr_avg) += ln_Pr_in[i_avg];
(*ln_Pr_max) = GBP_MAX((*ln_Pr_max), ln_Pr_in[i_avg]);
}
(*ln_Pr_avg) /= (double)n_avg;
}
if(x_bar != x_bar_in)
SID_free(SID_FARG x_bar);
}
| {
"alphanum_fraction": 0.4744404532,
"avg_line_length": 35.1359223301,
"ext": "c",
"hexsha": "3f0460c59ece413b4ed5d15a2208def99e3f79c7",
"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/compute_MCMC_chain_stats.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/compute_MCMC_chain_stats.c",
"max_line_length": 100,
"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/compute_MCMC_chain_stats.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": 1036,
"size": 3619
} |
/* Copyright (C) 2021 Atsushi Togo */
/* All rights reserved. */
/* This file is part of phonopy. */
/* Redistribution and use in source and binary forms, with or without */
/* modification, are permitted provided that the following conditions */
/* are met: */
/* * Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* * Redistributions in binary form must reproduce the above copyright */
/* notice, this list of conditions and the following disclaimer in */
/* the documentation and/or other materials provided with the */
/* distribution. */
/* * Neither the name of the phonopy project nor the names of its */
/* contributors may be used to endorse or promote products derived */
/* from this software without specific prior written permission. */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */
/* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */
/* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */
/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */
/* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */
/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */
/* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */
/* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
#ifndef __phono3py_H__
#define __phono3py_H__
#if defined(MKL_LAPACKE) || defined(SCIPY_MKL_H)
#include <mkl.h>
#else
#include <lapacke.h>
#endif
#include "phonoc_array.h"
long ph3py_get_interaction(
Darray *fc3_normal_squared, const char *g_zero, const Darray *frequencies,
const lapack_complex_double *eigenvectors, const long (*triplets)[3],
const long num_triplets, const long (*bz_grid_addresses)[3],
const long D_diag[3], const long Q[3][3], const double *fc3,
const long is_compact_fc3, const double (*svecs)[3],
const long multi_dims[2], const long (*multi)[2], const double *masses,
const long *p2s_map, const long *s2p_map, const long *band_indices,
const long symmetrize_fc3_q, const double cutoff_frequency);
long ph3py_get_pp_collision(
double *imag_self_energy,
const long relative_grid_address[24][4][3], /* thm */
const double *frequencies, const lapack_complex_double *eigenvectors,
const long (*triplets)[3], const long num_triplets,
const long *triplet_weights, const long (*bz_grid_addresses)[3], /* thm */
const long *bz_map, /* thm */
const long bz_grid_type, const long D_diag[3], const long Q[3][3],
const double *fc3, const long is_compact_fc3, const double (*svecs)[3],
const long multi_dims[2], const long (*multi)[2], const double *masses,
const long *p2s_map, const long *s2p_map, const Larray *band_indices,
const Darray *temperatures, const long is_NU, const long symmetrize_fc3_q,
const double cutoff_frequency);
long ph3py_get_pp_collision_with_sigma(
double *imag_self_energy, const double sigma, const double sigma_cutoff,
const double *frequencies, const lapack_complex_double *eigenvectors,
const long (*triplets)[3], const long num_triplets,
const long *triplet_weights, const long (*bz_grid_addresses)[3],
const long D_diag[3], const long Q[3][3], const double *fc3,
const long is_compact_fc3, const double (*svecs)[3],
const long multi_dims[2], const long (*multi)[2], const double *masses,
const long *p2s_map, const long *s2p_map, const Larray *band_indices,
const Darray *temperatures, const long is_NU, const long symmetrize_fc3_q,
const double cutoff_frequency);
void ph3py_get_imag_self_energy_at_bands_with_g(
double *imag_self_energy, const Darray *fc3_normal_squared,
const double *frequencies, const long (*triplets)[3],
const long *triplet_weights, const double *g, const char *g_zero,
const double temperature, const double cutoff_frequency,
const long num_frequency_points, const long frequency_point_index);
void ph3py_get_detailed_imag_self_energy_at_bands_with_g(
double *detailed_imag_self_energy, double *imag_self_energy_N,
double *imag_self_energy_U, const Darray *fc3_normal_squared,
const double *frequencies, const long (*triplets)[3],
const long *triplet_weights, const long (*bz_grid_addresses)[3],
const double *g, const char *g_zero, const double temperature,
const double cutoff_frequency);
void ph3py_get_real_self_energy_at_bands(
double *real_self_energy, const Darray *fc3_normal_squared,
const long *band_indices, const double *frequencies,
const long (*triplets)[3], const long *triplet_weights,
const double epsilon, const double temperature,
const double unit_conversion_factor, const double cutoff_frequency);
void ph3py_get_real_self_energy_at_frequency_point(
double *real_self_energy, const double frequency_point,
const Darray *fc3_normal_squared, const long *band_indices,
const double *frequencies, const long (*triplets)[3],
const long *triplet_weights, const double epsilon, const double temperature,
const double unit_conversion_factor, const double cutoff_frequency);
void ph3py_get_collision_matrix(
double *collision_matrix, const Darray *fc3_normal_squared,
const double *frequencies, const long (*triplets)[3],
const long *triplets_map, const long *map_q,
const long *rotated_grid_points, const double *rotations_cartesian,
const double *g, const long num_ir_gp, const long num_gp,
const long num_rot, const double temperature,
const double unit_conversion_factor, const double cutoff_frequency);
void ph3py_get_reducible_collision_matrix(
double *collision_matrix, const Darray *fc3_normal_squared,
const double *frequencies, const long (*triplets)[3],
const long *triplets_map, const long *map_q, const double *g,
const long num_gp, const double temperature,
const double unit_conversion_factor, const double cutoff_frequency);
void ph3py_get_isotope_scattering_strength(
double *gamma, const long grid_point, const double *mass_variances,
const double *frequencies, const lapack_complex_double *eigenvectors,
const long num_grid_points, const long *band_indices, const long num_band,
const long num_band0, const double sigma, const double cutoff_frequency);
void ph3py_get_thm_isotope_scattering_strength(
double *gamma, const long grid_point, const long *ir_grid_points,
const long *weights, const double *mass_variances,
const double *frequencies, const lapack_complex_double *eigenvectors,
const long num_ir_grid_points, const long *band_indices,
const long num_band, const long num_band0,
const double *integration_weights, const double cutoff_frequency);
void ph3py_distribute_fc3(double *fc3, const long target, const long source,
const long *atom_mapping, const long num_atom,
const double *rot_cart);
void ph3py_rotate_delta_fc2(double (*fc3)[3][3][3],
const double (*delta_fc2s)[3][3],
const double *inv_U,
const double (*site_sym_cart)[3][3],
const long *rot_map_syms, const long num_atom,
const long num_site_sym, const long num_disp);
void ph3py_get_permutation_symmetry_fc3(double *fc3, const long num_atom);
void ph3py_get_permutation_symmetry_compact_fc3(
double *fc3, const long p2s[], const long s2pp[], const long nsym_list[],
const long perms[], const long n_satom, const long n_patom);
void ph3py_transpose_compact_fc3(double *fc3, const long p2s[],
const long s2pp[], const long nsym_list[],
const long perms[], const long n_satom,
const long n_patom, const long t_type);
long ph3py_get_triplets_reciprocal_mesh_at_q(
long *map_triplets, long *map_q, const long grid_point, const long mesh[3],
const long is_time_reversal, const long num_rot,
const long (*rec_rotations)[3][3], const long swappable);
long ph3py_get_BZ_triplets_at_q(long (*triplets)[3], const long grid_point,
const long (*bz_grid_addresses)[3],
const long *bz_map, const long *map_triplets,
const long num_map_triplets,
const long D_diag[3], const long Q[3][3],
const long bz_grid_type);
long ph3py_get_integration_weight(
double *iw, char *iw_zero, const double *frequency_points,
const long num_band0, const long relative_grid_address[24][4][3],
const long mesh[3], const long (*triplets)[3], const long num_triplets,
const long (*bz_grid_addresses)[3], const long *bz_map,
const long bz_grid_type, const double *frequencies1, const long num_band1,
const double *frequencies2, const long num_band2, const long tp_type,
const long openmp_per_triplets, const long openmp_per_bands);
void ph3py_get_integration_weight_with_sigma(
double *iw, char *iw_zero, const double sigma, const double sigma_cutoff,
const double *frequency_points, const long num_band0,
const long (*triplets)[3], const long num_triplets,
const double *frequencies, const long num_band, const long tp_type);
long ph3py_get_grid_index_from_address(const long address[3],
const long mesh[3]);
void ph3py_get_gr_grid_addresses(long gr_grid_addresses[][3],
const long D_diag[3]);
long ph3py_get_reciprocal_rotations(long rec_rotations[48][3][3],
const long (*rotations)[3][3],
const long num_rot,
const long is_time_reversal);
long ph3py_transform_rotations(long (*transformed_rots)[3][3],
const long (*rotations)[3][3],
const long num_rot, const long D_diag[3],
const long Q[3][3]);
long ph3py_get_snf3x3(long D_diag[3], long P[3][3], long Q[3][3],
const long A[3][3]);
long ph3py_transform_rotations(long (*transformed_rots)[3][3],
const long (*rotations)[3][3],
const long num_rot, const long D_diag[3],
const long Q[3][3]);
long ph3py_get_ir_grid_map(long *ir_grid_map, const long D_diag[3],
const long PS[3], const long (*grg_rotations)[3][3],
const long num_rot);
long ph3py_get_bz_grid_addresses(long (*bz_grid_addresses)[3], long *bz_map,
long *bzg2grg, const long D_diag[3],
const long Q[3][3], const long PS[3],
const double rec_lattice[3][3],
const long type);
long ph3py_rotate_bz_grid_index(const long bz_grid_index,
const long rotation[3][3],
const long (*bz_grid_addresses)[3],
const long *bz_map, const long D_diag[3],
const long PS[3], const long bz_grid_type);
void ph3py_symmetrize_collision_matrix(double *collision_matrix,
const long num_column,
const long num_temp,
const long num_sigma);
void ph3py_expand_collision_matrix(double *collision_matrix,
const long *rot_grid_points,
const long *ir_grid_points,
const long num_ir_gp,
const long num_grid_points,
const long num_rot, const long num_sigma,
const long num_temp, const long num_band);
long ph3py_get_neighboring_gird_points(
long *relative_grid_points, const long *grid_points,
const long (*relative_grid_address)[3], const long mesh[3],
const long (*bz_grid_addresses)[3], const long *bz_map,
const long bz_grid_type, const long num_grid_points,
const long num_relative_grid_address);
long ph3py_get_thm_integration_weights_at_grid_points(
double *iw, const double *frequency_points, const long num_band0,
const long num_band, const long num_gp,
const long (*relative_grid_address)[4][3], const long D_diag[3],
const long *grid_points, const long (*bz_grid_addresses)[3],
const long *bz_map, const long bz_grid_type, const double *frequencies,
const long *gp2irgp_map, const char function);
#endif
| {
"alphanum_fraction": 0.675241647,
"avg_line_length": 58.1371681416,
"ext": "h",
"hexsha": "ce2094edb80dc622a22a2ae5a0931863c460589b",
"lang": "C",
"max_forks_count": 30,
"max_forks_repo_forks_event_max_datetime": "2020-05-01T21:36:50.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-02-11T13:33:56.000Z",
"max_forks_repo_head_hexsha": "22740415512d2f9bd00cbf2dc43594de003a37df",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sjli47/phono3py-sjl",
"max_forks_repo_path": "c/phono3py.h",
"max_issues_count": 36,
"max_issues_repo_head_hexsha": "22740415512d2f9bd00cbf2dc43594de003a37df",
"max_issues_repo_issues_event_max_datetime": "2020-05-02T07:31:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-12-22T12:42:54.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sjli47/phono3py-sjl",
"max_issues_repo_path": "c/phono3py.h",
"max_line_length": 80,
"max_stars_count": 38,
"max_stars_repo_head_hexsha": "22740415512d2f9bd00cbf2dc43594de003a37df",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sjli47/phono3py-sjl",
"max_stars_repo_path": "c/phono3py.h",
"max_stars_repo_stars_event_max_datetime": "2020-05-01T07:46:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-27T04:43:25.000Z",
"num_tokens": 2988,
"size": 13139
} |
/* ode-initval/control.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include "gsl_odeiv.h"
gsl_odeiv_control *
gsl_odeiv_control_alloc(const gsl_odeiv_control_type * T)
{
gsl_odeiv_control * c =
(gsl_odeiv_control *) malloc(sizeof(gsl_odeiv_control));
if(c == 0)
{
GSL_ERROR_NULL ("failed to allocate space for control struct",
GSL_ENOMEM);
};
c->type = T;
c->state = c->type->alloc();
if (c->state == 0)
{
free (c); /* exception in constructor, avoid memory leak */
GSL_ERROR_NULL ("failed to allocate space for control state",
GSL_ENOMEM);
};
return c;
}
int
gsl_odeiv_control_init(gsl_odeiv_control * c,
double eps_abs, double eps_rel,
double a_y, double a_dydt)
{
return c->type->init (c->state, eps_abs, eps_rel, a_y, a_dydt);
}
void
gsl_odeiv_control_free(gsl_odeiv_control * c)
{
c->type->free(c->state);
free(c);
}
const char *
gsl_odeiv_control_name(const gsl_odeiv_control * c)
{
return c->type->name;
}
int
gsl_odeiv_control_hadjust (gsl_odeiv_control * c, gsl_odeiv_step * s, const double y0[], const double yerr[], const double dydt[], double * h)
{
return c->type->hadjust(c->state, s->dimension, s->type->order(s->state),
y0, yerr, dydt, h);
}
| {
"alphanum_fraction": 0.6634877384,
"avg_line_length": 27.1851851852,
"ext": "c",
"hexsha": "1b3a132b69ab613e85f36b542772ad6955991d95",
"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/ode-initval/control.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/ode-initval/control.c",
"max_line_length": 142,
"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/ode-initval/control.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": 615,
"size": 2202
} |
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_math.h>
#include "gsl_cblas.h"
#include "tests.h"
void
test_symv (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int order = 101;
int uplo = 121;
float alpha = 1.0f;
float beta = -1.0f;
int N = 1;
int lda = 1;
float A[] = { -0.428f };
float X[] = { -0.34f };
int incX = -1;
float Y[] = { -0.888f };
int incY = -1;
float y_expected[] = { 1.03352f };
cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "ssymv(case 1054)");
}
};
};
{
int order = 101;
int uplo = 121;
float alpha = 1.0f;
float beta = -1.0f;
int N = 1;
int lda = 1;
float A[] = { -0.428f };
float X[] = { -0.34f };
int incX = -1;
float Y[] = { -0.888f };
int incY = -1;
float y_expected[] = { 1.03352f };
cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "ssymv(case 1055)");
}
};
};
{
int order = 101;
int uplo = 122;
float alpha = 1.0f;
float beta = -1.0f;
int N = 1;
int lda = 1;
float A[] = { -0.428f };
float X[] = { -0.34f };
int incX = -1;
float Y[] = { -0.888f };
int incY = -1;
float y_expected[] = { 1.03352f };
cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "ssymv(case 1056)");
}
};
};
{
int order = 101;
int uplo = 122;
float alpha = 1.0f;
float beta = -1.0f;
int N = 1;
int lda = 1;
float A[] = { -0.428f };
float X[] = { -0.34f };
int incX = -1;
float Y[] = { -0.888f };
int incY = -1;
float y_expected[] = { 1.03352f };
cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "ssymv(case 1057)");
}
};
};
{
int order = 102;
int uplo = 121;
float alpha = 1.0f;
float beta = -1.0f;
int N = 1;
int lda = 1;
float A[] = { -0.428f };
float X[] = { -0.34f };
int incX = -1;
float Y[] = { -0.888f };
int incY = -1;
float y_expected[] = { 1.03352f };
cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "ssymv(case 1058)");
}
};
};
{
int order = 102;
int uplo = 121;
float alpha = 1.0f;
float beta = -1.0f;
int N = 1;
int lda = 1;
float A[] = { -0.428f };
float X[] = { -0.34f };
int incX = -1;
float Y[] = { -0.888f };
int incY = -1;
float y_expected[] = { 1.03352f };
cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "ssymv(case 1059)");
}
};
};
{
int order = 102;
int uplo = 122;
float alpha = 1.0f;
float beta = -1.0f;
int N = 1;
int lda = 1;
float A[] = { -0.428f };
float X[] = { -0.34f };
int incX = -1;
float Y[] = { -0.888f };
int incY = -1;
float y_expected[] = { 1.03352f };
cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "ssymv(case 1060)");
}
};
};
{
int order = 102;
int uplo = 122;
float alpha = 1.0f;
float beta = -1.0f;
int N = 1;
int lda = 1;
float A[] = { -0.428f };
float X[] = { -0.34f };
int incX = -1;
float Y[] = { -0.888f };
int incY = -1;
float y_expected[] = { 1.03352f };
cblas_ssymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], flteps, "ssymv(case 1061)");
}
};
};
{
int order = 101;
int uplo = 121;
double alpha = 0;
double beta = -0.3;
int N = 1;
int lda = 1;
double A[] = { 0.544 };
double X[] = { -0.601 };
int incX = -1;
double Y[] = { -0.852 };
int incY = -1;
double y_expected[] = { 0.2556 };
cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dsymv(case 1062)");
}
};
};
{
int order = 101;
int uplo = 121;
double alpha = 0;
double beta = -0.3;
int N = 1;
int lda = 1;
double A[] = { 0.544 };
double X[] = { -0.601 };
int incX = -1;
double Y[] = { -0.852 };
int incY = -1;
double y_expected[] = { 0.2556 };
cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dsymv(case 1063)");
}
};
};
{
int order = 101;
int uplo = 122;
double alpha = 0;
double beta = -0.3;
int N = 1;
int lda = 1;
double A[] = { 0.544 };
double X[] = { -0.601 };
int incX = -1;
double Y[] = { -0.852 };
int incY = -1;
double y_expected[] = { 0.2556 };
cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dsymv(case 1064)");
}
};
};
{
int order = 101;
int uplo = 122;
double alpha = 0;
double beta = -0.3;
int N = 1;
int lda = 1;
double A[] = { 0.544 };
double X[] = { -0.601 };
int incX = -1;
double Y[] = { -0.852 };
int incY = -1;
double y_expected[] = { 0.2556 };
cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dsymv(case 1065)");
}
};
};
{
int order = 102;
int uplo = 121;
double alpha = 0;
double beta = -0.3;
int N = 1;
int lda = 1;
double A[] = { 0.544 };
double X[] = { -0.601 };
int incX = -1;
double Y[] = { -0.852 };
int incY = -1;
double y_expected[] = { 0.2556 };
cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dsymv(case 1066)");
}
};
};
{
int order = 102;
int uplo = 121;
double alpha = 0;
double beta = -0.3;
int N = 1;
int lda = 1;
double A[] = { 0.544 };
double X[] = { -0.601 };
int incX = -1;
double Y[] = { -0.852 };
int incY = -1;
double y_expected[] = { 0.2556 };
cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dsymv(case 1067)");
}
};
};
{
int order = 102;
int uplo = 122;
double alpha = 0;
double beta = -0.3;
int N = 1;
int lda = 1;
double A[] = { 0.544 };
double X[] = { -0.601 };
int incX = -1;
double Y[] = { -0.852 };
int incY = -1;
double y_expected[] = { 0.2556 };
cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dsymv(case 1068)");
}
};
};
{
int order = 102;
int uplo = 122;
double alpha = 0;
double beta = -0.3;
int N = 1;
int lda = 1;
double A[] = { 0.544 };
double X[] = { -0.601 };
int incX = -1;
double Y[] = { -0.852 };
int incY = -1;
double y_expected[] = { 0.2556 };
cblas_dsymv(order, uplo, N, alpha, A, lda, X, incX, beta, Y, incY);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(Y[i], y_expected[i], dbleps, "dsymv(case 1069)");
}
};
};
}
| {
"alphanum_fraction": 0.4763645531,
"avg_line_length": 20.8763157895,
"ext": "c",
"hexsha": "c997598bc4c20db3fe51572a8c85b3fab6a95314",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_symv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_symv.c",
"max_line_length": 70,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_symv.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": 3210,
"size": 7933
} |
#include <math.h>
#include <stdio.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <Python.h>
int sum(int* npyArray3D, int npyLength1D, int npyLength2D, int npyLength3D)
{
int i, j, k;
int sum = 0;
double dummy = sqrt(9.0);
int MAT_DIM = 6;
gsl_matrix *m = gsl_matrix_alloc(MAT_DIM, MAT_DIM);
for (i=0; i < MAT_DIM*MAT_DIM; i++) {
gsl_matrix_set (m, i%MAT_DIM, i/MAT_DIM, (double) npyArray3D[i]);
}
for (i=0; i < MAT_DIM*MAT_DIM; i++) {
printf("%f, ", gsl_matrix_get (m, i%MAT_DIM, i/MAT_DIM));
}
printf("\n");
for (i=0;i<npyLength1D;i++)
for (j=0;j<npyLength2D;j++)
for (k=0;k<npyLength3D;k++)
sum += npyArray3D[i*npyLength3D*npyLength2D + k*npyLength2D + j];
printf("%f\n",dummy);
return sum;
}
double get_det(PyObject *A)
{
int MAT_DIM = 6;
int i, signum;
double det;
int nInts = PyList_Size(A);
gsl_matrix *m = gsl_matrix_alloc(MAT_DIM, MAT_DIM);
gsl_permutation *p;
p = gsl_permutation_alloc(m->size1);
for (i=0; i<nInts; i++)
{
PyObject *oo = PyList_GetItem(A, i);
gsl_matrix_set (m, i%MAT_DIM, i/MAT_DIM, PyFloat_AS_DOUBLE(oo));
}
gsl_linalg_LU_decomp(m, p, &signum);
det = gsl_linalg_LU_det(m, signum);
return det;
}
| {
"alphanum_fraction": 0.639516129,
"avg_line_length": 22.5454545455,
"ext": "c",
"hexsha": "83070afebb8475bbe831916c097a86b9dec637be",
"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": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tcrundall/chronostar",
"max_forks_repo_path": "playground/numpy/multid3/array3D.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"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": "tcrundall/chronostar",
"max_issues_repo_path": "playground/numpy/multid3/array3D.c",
"max_line_length": 75,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tcrundall/chronostar",
"max_stars_repo_path": "playground/numpy/multid3/array3D.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 456,
"size": 1240
} |
#ifndef GSL_INTERFACE_H
#define GSL_INTERFACE_H
#include <gsl/gsl_odeiv2.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#ifdef __cplusplus
extern "C" {
#endif
/*****************************
* Structure definitions
*****************************
*/
/**
* Encapsulation of the integrator;
*/
typedef struct cgsl_integrator{
const gsl_odeiv2_step_type * step_type; /* time step allocation */
gsl_odeiv2_step * step; /* time step control */
gsl_odeiv2_control * control; /* definition of the system */
gsl_odeiv2_system system; /* definition of the driver */
gsl_odeiv2_evolve * evolution; /* emove forward in time*/
gsl_odeiv2_driver * driver; /* high level interface */
} cgsl_integrator;
//see <gsl/gsl_odeiv2.h> for an explanation of these
typedef int (* ode_function_ptr ) (double t, const double y[], double dydt[], void * params);
typedef int (* ode_jacobian_ptr ) (double t, const double y[], double * dfdy, double dfdt[], void * params);
/** Pre/post step callbacks
* t: Start of the current time step (communicationPoint)
* dt: Length of the current time step (communicationStepSize)
* n: Size of system
* y: For pre, the values of the variables before stepping. For post, after.
* params: Opaque pointer
*/
typedef int (* pre_post_step_ptr ) (double t, double dt, int n, const double y[], void * params);
enum cgsl_callback_actions{
CGSL_RESTART = 1 // multistep integrators need a reset when
// used with the epce filter.
};
/**
*
* This is intended to contain everything needed to integrate only one
* little bit at a time *and* to be able to backtrack when needed, and to
* have multiple instances of the model.
*
* Here we use this for inheritance by aggregation so that each model is
* declared as
* typedef struct my_model{
* cgs_model m;
* .
* .
* extra stuff
* .
* .
* } my_model ;
*/
typedef struct cgsl_model{
int n_variables;
double *x; /** state variables */
double *x_backup; /** for get/set FMU state */
void * parameters;
/** Definition of the dynamical system: this assumes an *explicit* ODE */
ode_function_ptr function;
/** Jacobian */
ode_jacobian_ptr jacobian;
/** Pre/post step functions */
pre_post_step_ptr pre_step;
pre_post_step_ptr post_step;
/** Get/set FMU state
* Used to copy/retreive internal state to/from temporary storage inside the model
* params: Opaque pointer
*/
void (* get_state) (struct cgsl_model *model);
void (* set_state) (struct cgsl_model *model);
/** Destructor */
void (* free) (struct cgsl_model * model);
/** Needed by ModelExchange to store content from parameters */
void* (*get_model_parameters)(const struct cgsl_model *model);
} cgsl_model;
/**
* Useful function for allocating the most common type of model
*/
cgsl_model* cgsl_model_default_alloc(
int n_variables, /** Number of variables */
const double *x0, /** Initial values. If NULL, initialize model->x to all zeroes instead */
void *parameters, /** User pointer */
ode_function_ptr function, /** ODE function */
ode_jacobian_ptr jacobian, /** Jacobian */
pre_post_step_ptr pre_step, /** Pre-step function */
pre_post_step_ptr post_step,/** Post-step function */
size_t sz /** If sz > sizeof(cgsl_model) then allocate sz bytes instead.
Useful for the my_model case described earlier in this file */
);
/** Default destructor. Frees model->x and the model itself */
void cgsl_model_default_free(cgsl_model *model);
/**
* Finally we can put everything in a bag. The spefic model only has to
* fill in these fields.
*/
typedef struct cgsl_simulation {
cgsl_model * model; /** this contains the state variables */
cgsl_integrator i;
double t; /** current time */
double t1; /** stop time */
double h; /** first stepsize and current value */
int fixed_step; /** whether or not we move at fixed step */
FILE * file;
int store_data; /** whether or not we save the data in an array */
double * data; /** store variables as integration proceeds */
int buffer_size; /** size of data storage */
int n; /** number of time steps taken */
int save; /** persistence to file */
int print; /** verbose on stderr */
int iterations; /** Number of iterations done by last call to cgsl_step_to() */
} cgsl_simulation;
/*****************************
* Enum definitions
*****************************
*/
/**
* List of available time integration methods in the gsl_odeiv2 library
*/
enum cgsl_integrator_ids
{
rk2, /* 0 */
rk4, /* 1 */
rkf45, /* 2 */
rkck, /* 3 */
rk8pd, /* 4 */
rk1imp, /* 5 */
rk2imp, /* 6 */
rk4imp, /* 7 */
bsimp, /* 8 */
msadams, /* 9 */
msbdf /*10 */
};
/* this will flag integrators which need restart */
extern int restart_integrator;
/**************
* Function declarations.
**************
*/
/**
* Essentially the constructor for the cgsl_simulation object.
* The dynamical model is defined by a function, its Jacobian, an
* opaque parameter struct, and a set of initial values.
* All variables are assumed to be continuous.
*
* \TODO: fix semantics for saving. Use a filename
* instead of descriptor? Open and close file automatically?
*/
cgsl_simulation cgsl_init_simulation_tolerance(
cgsl_model * model, /** the model we work on */
enum cgsl_integrator_ids integrator, /** Integrator ID */
double h, /** Initial time-step: must be non-zero, even with variable step*/
int fixed_step, /** Boolean */
int save, /** Boolean */
int print, /** Boolean */
FILE *f, /** File descriptor if 'save' is enabled */
double reltol, double abstol
);
cgsl_simulation cgsl_init_simulation(
cgsl_model * model, /** the model we work on */
enum cgsl_integrator_ids integrator, /** Integrator ID */
double h, /** Initial time-step: must be non-zero, even with variable step*/
int fixed_step, /** Boolean */
int save, /** Boolean */
int print, /** Boolean */
FILE *f /** File descriptor if 'save' is enabled */
);
/**
* Memory deallocation.
*/
void cgsl_free_simulation( cgsl_simulation sim );
/** Step from current time to next communication point. */
int cgsl_step_to(void * _s, double comm_point, double comm_step ) ;
/** Accessor */
const gsl_odeiv2_step_type * cgsl_get_integrator( int i ) ;
/** Commit to file. */
void cgsl_save_data( struct cgsl_simulation * sim );
/** Mutators for fixed step*/
/** \TODO: make this a toggle */
void cgsl_simulation_set_fixed_step( cgsl_simulation * s, double h );
void cgsl_simulation_set_variable_step( cgsl_simulation * s );
/** Get/set FMU state */
void cgsl_simulation_get( cgsl_simulation *s );
void cgsl_simulation_set( cgsl_simulation *s );
#ifdef __cplusplus
}
#endif
#endif
| {
"alphanum_fraction": 0.6245546725,
"avg_line_length": 31.321888412,
"ext": "h",
"hexsha": "d1f70786672ec2e4e7c5cde9358372d6a32c5b66",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-02-20T15:50:01.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-20T15:50:01.000Z",
"max_forks_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Tjoppen/fmigo",
"max_forks_repo_path": "tools/cgsl/include/gsl-interface.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae",
"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": "Tjoppen/fmigo",
"max_issues_repo_path": "tools/cgsl/include/gsl-interface.h",
"max_line_length": 109,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Tjoppen/fmigo",
"max_stars_repo_path": "tools/cgsl/include/gsl-interface.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z",
"num_tokens": 1769,
"size": 7298
} |
/****************************************
* MIT License
*
* Copyright (c) 2020 Miguel Ramos Pernas
****************************************/
#ifdef USE_CPU
#include "Python.h"
#include "math.h"
#include <gsl/gsl_integration.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_miser.h>
#include <gsl/gsl_monte_plain.h>
#include <gsl/gsl_monte_vegas.h>
#if NDIM == 1
/// Function proxy to integrate using 1-dimensional methods
double function_proxy(double x, void *vparams) {
double *params = (double *)vparams;
return FUNCTION(x, FWD_PARAMS(params)); // Definitions in "evaluators.c"
}
#endif
/// Function proxy to integrate using Monte Carlo methods
double monte_function_proxy(double *data, size_t, void *vparams) {
double *params = (double *)vparams;
return FUNCTION(DATA(data),
FWD_PARAMS(params)); // Definitions in "evaluators.c"
}
extern "C" {
#if NDIM == 1
/// Exposed function to integrate using the QNG method
PyObject *integrate_qng(double lb, double ub, PyObject *config,
double *params) {
gsl_function func = {&function_proxy, params};
double atol, rtol;
PyArg_ParseTuple(config, "dd", &atol, &rtol);
double res, err;
size_t neval;
gsl_integration_qng(&func, lb, ub, atol, rtol, &res, &err, &neval);
return Py_BuildValue("(ddi)", res, err, neval);
}
/// Exposed function to integrate using the QAG method
PyObject *integrate_qag(double lb, double ub, PyObject *config,
double *params) {
gsl_function func = {&function_proxy, params};
double atol, rtol;
int limit, key, workspace_size;
PyArg_ParseTuple(config, "ddiii", &atol, &rtol, &limit, &key,
&workspace_size);
gsl_integration_workspace *w =
gsl_integration_workspace_alloc(workspace_size);
double res, aerr;
gsl_integration_qag(&func, lb, ub, atol, rtol, limit, key, w, &res, &aerr);
gsl_integration_workspace_free(w);
return Py_BuildValue("(dd)", res, aerr);
}
/// Exposed function to integrate using the CQUAD method
PyObject *integrate_cquad(double lb, double ub, PyObject *config,
double *params) {
gsl_function func = {&function_proxy, params};
double atol, rtol;
int workspace_size;
PyArg_ParseTuple(config, "ddi", &atol, &rtol, &workspace_size);
gsl_integration_cquad_workspace *w =
gsl_integration_cquad_workspace_alloc(workspace_size);
double res, err;
size_t neval;
gsl_integration_cquad(&func, lb, ub, atol, rtol, w, &res, &err, &neval);
gsl_integration_cquad_workspace_free(w);
return Py_BuildValue("(ddi)", res, err, neval);
}
#endif
/// Exposed function to integrate using plain MonteCarlo
PyObject *integrate_plain(double *lb, double *ub, PyObject *config,
double *params) {
gsl_monte_function func = {&monte_function_proxy, NDIM, params};
double res, err;
gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
// Define the state
gsl_monte_plain_state *s = gsl_monte_plain_alloc(NDIM);
int calls;
PyArg_ParseTuple(config, "i", &calls);
// Calculate the integral
gsl_monte_plain_integrate(&func, lb, ub, NDIM, calls, r, s, &res, &err);
gsl_monte_plain_free(s);
gsl_rng_free(r);
return Py_BuildValue("(dd)", res, err);
}
/// Exposed function to integrate using the MISER method
PyObject *integrate_miser(double *lb, double *ub, PyObject *config,
double *params) {
gsl_monte_function func = {&monte_function_proxy, NDIM, params};
double res, err;
gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
// Define the state
gsl_monte_miser_state *s = gsl_monte_miser_alloc(NDIM);
int calls;
double estimate_frac;
int min_calls;
int min_calls_per_bisection;
double alpha;
double dither;
PyArg_ParseTuple(config, "idiidd", &calls, &estimate_frac, &min_calls,
&min_calls_per_bisection, &alpha, &dither);
gsl_monte_miser_params p;
gsl_monte_miser_params_get(s, &p);
p.estimate_frac = estimate_frac;
p.min_calls = min_calls;
p.min_calls_per_bisection = min_calls_per_bisection;
p.alpha = alpha;
p.dither = dither;
gsl_monte_miser_params_set(s, &p);
// Calculate the integral
gsl_monte_miser_integrate(&func, lb, ub, NDIM, calls, r, s, &res, &err);
gsl_monte_miser_free(s);
gsl_rng_free(r);
return Py_BuildValue("(dd)", res, err);
}
/// Exposed function to integrate using the VEGAS method
PyObject *integrate_vegas(double *lb, double *ub, PyObject *config,
double *params) {
gsl_monte_function func = {&monte_function_proxy, NDIM, params};
double res, err;
gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
// Define the state
gsl_monte_vegas_state *s = gsl_monte_vegas_alloc(NDIM);
int calls;
double alpha;
int iterations;
int mode;
PyArg_ParseTuple(config, "idii", &calls, &alpha, &iterations, &mode);
gsl_monte_vegas_params p;
gsl_monte_vegas_params_get(s, &p);
p.alpha = alpha;
p.iterations = iterations;
p.mode = mode;
gsl_monte_vegas_params_set(s, &p);
// Calculate the integral
gsl_monte_vegas_integrate(&func, lb, ub, NDIM, calls, r, s, &res, &err);
do {
gsl_monte_vegas_integrate(&func, lb, ub, NDIM, calls, r, s, &res, &err);
} while (fabs(gsl_monte_vegas_chisq(s) - 1.0) > 0.5);
gsl_monte_vegas_free(s);
gsl_rng_free(r);
return Py_BuildValue("(dd)", res, err);
}
}
#endif // USE_CPU
| {
"alphanum_fraction": 0.6797721845,
"avg_line_length": 25.6745283019,
"ext": "c",
"hexsha": "130dd96cb058fb6457c559f808c9f8b7bc2fc573",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-02-03T22:59:00.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-02-03T22:59:00.000Z",
"max_forks_repo_head_hexsha": "fa6808a6ca8063751da92f683f2b810a0690a462",
"max_forks_repo_licenses": [
"MIT-0"
],
"max_forks_repo_name": "mramospe/minkit",
"max_forks_repo_path": "minkit/backends/src/templates/numerical_integral.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "fa6808a6ca8063751da92f683f2b810a0690a462",
"max_issues_repo_issues_event_max_datetime": "2020-11-10T09:13:47.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-01-30T18:30:33.000Z",
"max_issues_repo_licenses": [
"MIT-0"
],
"max_issues_repo_name": "mramospe/minkit",
"max_issues_repo_path": "minkit/backends/src/templates/numerical_integral.c",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "fa6808a6ca8063751da92f683f2b810a0690a462",
"max_stars_repo_licenses": [
"MIT-0"
],
"max_stars_repo_name": "mramospe/minkit",
"max_stars_repo_path": "minkit/backends/src/templates/numerical_integral.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1518,
"size": 5443
} |
// This file is part of playd.
// playd is licensed under the MIT licence: see LICENSE.txt.
/**
* @file
* Declaration of the Basic_audio, Null_audio and Audio classes.
* @see audio/audio.cpp
*/
#ifndef PLAYD_AUDIO_H
#define PLAYD_AUDIO_H
#include <chrono>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#undef max
#include <gsl/gsl>
#include "../response.h"
#include "sink.h"
#include "source.h"
namespace Playd::Audio
{
/**
* An audio item.
*
* Audio abstractly represents an audio item that can be played, stopped,
* and queried for its position and path (or equivalent).
*
* Audio is a virtual interface implemented concretely by PipeAudio, and
* also by mock implementations for testing purposes.
*
* @see PipeAudio
*/
class Audio
{
public:
/// Enumeration of possible states for Audio.
using State = Sink::State;
/// Virtual, empty destructor for Audio.
virtual ~Audio() = default;
//
// Control interface
//
/**
* Performs an update cycle on this Audio.
*
* Depending on the Audio implementation, this may do actions such as
* performing a decoding round, checking for end-of-file, transferring
* frames, and so on.
*
* @return The state of the Audio after updating.
* @see State
*/
virtual State Update() = 0;
/**
* Sets whether this Audio should be playing or not.
* @param playing True for playing; false for stopped.
* @exception NoAudioError if the current state is NONE.
*/
virtual void SetPlaying(bool playing) = 0;
/**
* Attempts to seek to the given position.
* @param position The position to seek to, in microseconds.
* @exception NoAudioError if the current state is NONE.
* @see Position
*/
virtual void SetPosition(std::chrono::microseconds position) = 0;
//
// Property access
//
/**
* This Audio's current file.
* @return The filename of this current file.
* @exception NoAudioError if the current state is NONE.
*/
virtual std::string_view File() const = 0;
/**
* The state of this Audio.
* @return this Audio's current state.
*/
virtual State CurrentState() const = 0;
/**
* This Audio's current position.
*
* As this may be executing whilst the playing callback is running,
* do not expect it to be highly accurate.
*
* @return The current position, in microseconds.
* @exception NoAudioError if the current state is NONE.
* @see Seek
*/
virtual std::chrono::microseconds Position() const = 0;
/**
* This Audio's length.
*
* @return The length, in microseconds.
* @exception NoAudioError if the current state is NONE.
* @see Seek
*/
virtual std::chrono::microseconds Length() const = 0;
};
/**
* A dummy Audio implementation representing a lack of file.
*
* NoAudio throws exceptions if any attempt is made to change, start, or stop
* the audio, and returns Audio::State::NONE during any attempt to Update.
* If asked to emit the audio file, NoAudio does nothing.
*
* @see Audio
*/
class NullAudio : public Audio
{
public:
Audio::State Update() override;
Audio::State CurrentState() const override;
// The following all raise an exception:
void SetPlaying(bool playing) override;
void SetPosition(std::chrono::microseconds position) override;
std::chrono::microseconds Position() const override;
std::chrono::microseconds Length() const override;
std::string_view File() const override;
};
/**
* A concrete implementation of Audio as a 'pipe'.
*
* Basic_audio is comprised of a 'source', which decodes frames from a
* file, and a 'sink', which plays out the decoded frames. Updating
* consists of shifting frames from the source to the sink.
*
* @see Audio
* @see Sink
* @see Source
*/
class BasicAudio : public Audio
{
public:
/**
* Constructs audio from a source and a sink.
* @param src The source of decoded audio frames.
* @param sink The target of decoded audio frames.
* @see AudioSystem::Load
*/
BasicAudio(std::unique_ptr<Source> src, std::unique_ptr<Sink> sink);
Audio::State Update() override;
std::string_view File() const override;
void SetPlaying(bool playing) override;
Audio::State CurrentState() const override;
void SetPosition(std::chrono::microseconds position) override;
std::chrono::microseconds Position() const override;
std::chrono::microseconds Length() const override;
private:
/// The source of audio data.
std::unique_ptr<Source> src;
/// The sink to which audio data is sent.
std::unique_ptr<Sink> sink;
/// The current decoded frame.
Source::DecodeVector frame;
/// A span representing the unclaimed part of the decoded frame.
gsl::span<const std::byte> frame_span;
/// Clears the current frame and its iterator.
void ClearFrame();
/**
* Decodes a new frame, if the current frame is empty.
* @return True if more frames are available to decode; false
* otherwise.
*/
bool DecodeIfFrameEmpty();
/**
* Returns whether the current frame has been finished.
* If this is true, then either the frame is empty, or all of the
* samples in the frame have been fed to the ringbuffer.
* @return True if the frame is finished; false otherwise.
*/
bool FrameFinished() const;
/// Transfers as much of the current frame as possible to the sink.
void TransferFrame();
};
} // namespace Playd::Audio
#endif // PLAYD_AUDIO_H
| {
"alphanum_fraction": 0.7041674453,
"avg_line_length": 24.1036036036,
"ext": "h",
"hexsha": "30aeed3abd26b6ed16fe9cf88559e001f68ebc60",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-02-23T12:41:21.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-09-04T23:04:46.000Z",
"max_forks_repo_head_hexsha": "dc072e4934acb21b9dddb225818732bd27671ae0",
"max_forks_repo_licenses": [
"BSL-1.0",
"MIT"
],
"max_forks_repo_name": "UniversityRadioYork/ury-playd",
"max_forks_repo_path": "src/audio/audio.h",
"max_issues_count": 56,
"max_issues_repo_head_hexsha": "dc072e4934acb21b9dddb225818732bd27671ae0",
"max_issues_repo_issues_event_max_datetime": "2020-01-28T13:48:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-01T19:22:34.000Z",
"max_issues_repo_licenses": [
"BSL-1.0",
"MIT"
],
"max_issues_repo_name": "UniversityRadioYork/ury-playd",
"max_issues_repo_path": "src/audio/audio.h",
"max_line_length": 77,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "dc072e4934acb21b9dddb225818732bd27671ae0",
"max_stars_repo_licenses": [
"BSL-1.0",
"MIT"
],
"max_stars_repo_name": "UniversityRadioYork/ury-playd",
"max_stars_repo_path": "src/audio/audio.h",
"max_stars_repo_stars_event_max_datetime": "2017-08-19T20:01:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-02-11T20:33:45.000Z",
"num_tokens": 1293,
"size": 5351
} |
#ifndef KGS_GSLQR_H
#define KGS_GSLQR_H
#include "math/QR.h"
#include <gsl/gsl_matrix.h>
class QRGSL: public QR {
public:
QRGSL(gsl_matrix* M): QR(M){}
protected:
void updateFromMatrix() override;
};
#endif //KGS_GSLQR_H
| {
"alphanum_fraction": 0.7051282051,
"avg_line_length": 12.3157894737,
"ext": "h",
"hexsha": "c7a0d856d19d39927ba2d6cdd47ba1d454cd6bc1",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_forks_repo_path": "src/math/QRGSL.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_issues_repo_path": "src/math/QRGSL.h",
"max_line_length": 35,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_stars_repo_path": "src/math/QRGSL.h",
"max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z",
"num_tokens": 77,
"size": 234
} |
/*
* SpectrumTransformer.h
*
* Created on: Jul 30, 2015
* Author: dpayne
*/
#ifndef _SPECTRUM_TRANSFORMER_H
#define _SPECTRUM_TRANSFORMER_H
#include <fftw.h>
#include "Transformer/GenericTransformer.h"
#include "Writer/NcursesWriter.h"
#include "Domain/Settings.h"
namespace vis
{
class SpectrumTransformer : public GenericTransformer
{
public:
explicit SpectrumTransformer(const Settings *const settings);
~SpectrumTransformer() override;
void execute_mono(pcm_stereo_sample *buffer,
vis::NcursesWriter *writer) override;
void execute_stereo(pcm_stereo_sample *buffer,
vis::NcursesWriter *writer) override;
private:
void execute(pcm_stereo_sample *buffer, vis::NcursesWriter *writer,
const bool is_stereo);
const Settings *const m_settings;
/** --- BEGIN MEMBER VARIABLES --- */
/** --- BEGIN --- fft calculations vars **/
size_t m_fftw_results;
double *m_fftw_input_left;
double *m_fftw_input_right;
fftw_complex *m_fftw_output_left;
fftw_complex *m_fftw_output_right;
fftw_plan m_fftw_plan_left;
fftw_plan m_fftw_plan_right;
/** --- END --- fft calculations vars **/
/** --- BEGIN --- frequency cutoff calculations vars **/
std::vector<uint32_t> m_low_cutoff_frequencies;
std::vector<uint32_t> m_high_cutoff_frequencies;
std::vector<double> m_frequency_constants_per_bin;
int32_t m_previous_win_width; // Used to determine if freq cutoffs need to
// be re-calculated
/** --- END --- frequency cutoff calculations vars **/
uint64_t m_silent_runs; // Used to determine if the transformer should sleep
// and wait for input
// Holds the current bar heights after processing, this is done as a member
// function to avoid memory allocations on every run
std::vector<double> m_bars_left;
std::vector<double> m_bars_right;
// falloff vectors hold the previous runs values, this is used to to apply
// falloff effect for the current run
std::vector<double> m_bars_falloff_left;
std::vector<double> m_bars_falloff_right;
std::vector<double> m_previous_max_heights;
// Used by monstercat smoothing to apply weights to a bar's height as
// determined by it's frequency range
// Note: this is only re-computed when screen width changes
std::vector<double> m_monstercat_smoothing_weights;
// Pre-compute colors calculations to avoid duplicate work
// Note: this is only re-computed when screen height changes
std::vector<vis::ColorIndex> m_precomputed_colors;
/** --- END MEMBER VARIABLES --- */
/** --- BEGIN MEMBER FUNCTIONS --- */
/**
* Copies the channel given by "channel_mode" to the fftw_input buffer
*/
bool prepare_fft_input(pcm_stereo_sample *buffer, uint32_t sample_size,
double *fftw_input, ChannelMode channel_mode);
/**
* Populates "bars" and "bars_falloff" with the bar heights to be displayed
*/
virtual void create_spectrum_bars(fftw_complex *fftw_output,
const size_t fftw_results,
const int32_t win_height,
const int32_t win_width,
const uint32_t number_of_bars,
std::vector<double> &bars,
std::vector<double> &bars_falloff);
void
generate_bars(std::vector<double> &bars, const uint32_t number_of_bars,
const fftw_complex *fftw_output, const size_t fftw_results,
const std::vector<uint32_t> &low_cutoff_frequencies,
const std::vector<uint32_t> &high_cutoff_frequencies) const;
void recalculate_cutoff_frequencies(
uint32_t number_of_bars, std::vector<uint32_t> *low_cutoff_frequencies,
std::vector<uint32_t> *high_cutoff_frequencies,
std::vector<double> *freqconst_per_bin);
/**
* Applies the smoothing operations based on the settings in m_settings to
* "bars"
*/
void smooth_bars(std::vector<double> &bars);
/**
* Applies the falloff effect based on the settings in m_settings to "bars".
* The old falloff from the previous run should be in "falloff_bars". The
* new falloff values will be updated in-place in "falloff_bars"
*/
std::vector<double> apply_falloff(const std::vector<double> &bars,
std::vector<double> &falloff_bars) const;
/**
* Calculates the moving average and the standard deviation for a given
* range of elements.
*
* "new_value" is added to "old_values".
*
* If "old_values.size()" > "max_number_of_elements" the first element of
* old_values is erased.
*/
void calculate_moving_average_and_std_dev(
const double new_value, const size_t max_number_of_elements,
std::vector<double> &old_values, double *moving_average,
double *std_dev) const;
/**
* A long term and short term running average are kept of the max bar
* heights for each frame. If the short term running average is very
* different than the long term running average then the scaling size
* should be reset to better suit the current music.
*
* This happens commonly if a there is a new song that is a lot quieter
* or louder than the previous song.
*/
void maybe_reset_scaling_window(const double current_max_height,
const size_t max_number_of_elements,
std::vector<double> *values,
double *moving_average, double *std_dev);
/**
* Renders the spectrum bars to the screen.
*/
virtual void draw_bars(const std::vector<double> &bars,
const std::vector<double> &bars_falloff,
int32_t win_height, const bool flipped,
const std::wstring &bar_row_msg,
vis::NcursesWriter *writer);
/**
* Scaling the given vector of points "bars" to a fit a screen with a window
* height of "height".
*/
virtual void scale_bars(std::vector<double> &bars, const int32_t height);
/**
* Creates the to be used for every section of the bar to be printed. For
* example if the bar width is set to two, and the bar character to '#'.
* Then the bar row msg would be "##";
*/
std::wstring create_bar_row_msg(const wchar_t character,
uint32_t bar_width);
/**
* Savitzky-Golay smoothng. This type of smoothing is usually much faster
* than monstercat.
*
* https://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter
*/
void sgs_smoothing(std::vector<double> &bars);
/**
* This type of smoothing is inspired by monstercat
* (https://www.youtube.com/user/MonstercatMedia). The code was largely
* taken from cava git@github.com:karlstav/cava.git
*/
void monstercat_smoothing(std::vector<double> &bars);
/** --- END MEMBER FUNCTIONS --- */
};
}
#endif
| {
"alphanum_fraction": 0.6352347162,
"avg_line_length": 36.0985221675,
"ext": "h",
"hexsha": "64fc7151e26031f2bab55dd00b011ce3e970688a",
"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": "5ab9253830f51918840da7b067bed132aabda2f3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kevinarefunny/cli-visualizer",
"max_forks_repo_path": "src/Transformer/SpectrumTransformer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5ab9253830f51918840da7b067bed132aabda2f3",
"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": "kevinarefunny/cli-visualizer",
"max_issues_repo_path": "src/Transformer/SpectrumTransformer.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5ab9253830f51918840da7b067bed132aabda2f3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kevinarefunny/cli-visualizer",
"max_stars_repo_path": "src/Transformer/SpectrumTransformer.h",
"max_stars_repo_stars_event_max_datetime": "2019-07-16T07:22:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-07-16T07:22:51.000Z",
"num_tokens": 1655,
"size": 7328
} |
/* ensure once-only inclusion. */
#ifndef __VFL_BLAS_H__
#define __VFL_BLAS_H__
/* include the matrix and vector headers. */
#include <vfl/util/matrix.h>
#include <vfl/util/vector.h>
/* determine whether or not atlas is used. */
#ifdef __VFL_USE_ATLAS
/* include the atlas blas header. */
#include <cblas.h>
#include <clapack.h>
#else
/* define values for cblas enumerations. */
#define CblasNoTrans 111
#define CblasTrans 112
#define CblasUpper 121
#define CblasLower 122
#endif
/* BlasTranspose: enumeration of all possible ways to transpose
* a matrix (or not) during calculations.
*/
typedef enum {
BLAS_NO_TRANS = CblasNoTrans,
BLAS_TRANS = CblasTrans
}
BlasTranspose;
/* BlasTriangle: enumeration of all possible ways to access
* a triangular matrix.
*/
typedef enum {
BLAS_UPPER = CblasUpper,
BLAS_LOWER = CblasLower
}
BlasTriangle;
/* function declarations (util/blas.c): */
double blas_dasum (const Vector *x);
double blas_dnrm2 (const Vector *x);
double blas_ddot (const Vector *x, const Vector *y);
void blas_daxpy (double alpha, const Vector *x, Vector *y);
void blas_dscal (double alpha, Vector *y);
/* --- */
void blas_dgemv (BlasTranspose trans, double alpha, const Matrix *A,
const Vector *x, double beta, Vector *y);
void blas_dtrmv (BlasTranspose trans, const Matrix *L,
const Vector *x, Vector *y);
void blas_dtrsv (BlasTriangle tri, const Matrix *L, Vector *x);
#endif /* !__VFL_BLAS_H__ */
| {
"alphanum_fraction": 0.7107215105,
"avg_line_length": 22.8153846154,
"ext": "h",
"hexsha": "e5f1add57e83693ca91454e4228bbc1e9d71bc7b",
"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": "6fd4a75207b460159aa6bc7693eecfc4c82e1756",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "geekysuavo/vfl",
"max_forks_repo_path": "vfl/util/blas.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6fd4a75207b460159aa6bc7693eecfc4c82e1756",
"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": "geekysuavo/vfl",
"max_issues_repo_path": "vfl/util/blas.h",
"max_line_length": 68,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6fd4a75207b460159aa6bc7693eecfc4c82e1756",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "geekysuavo/vfl",
"max_stars_repo_path": "vfl/util/blas.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 402,
"size": 1483
} |
// @(#)root/matrix:$Name: $:$Id: TMatrixTSparse.h,v 1.5 2006/05/17 06:22:06 brun Exp $
// Authors: Fons Rademakers, Eddy Offermann Feb 2004
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//#ifndef ROOT_TMatrixTSparse
//#define ROOT_TMatrixTSparse
//#ifndef ROOT_TMatrixTBase
#include "TMatrixTBase.cpp" //KEVIN .... program wont' link correctedly when using templates unless i include cxx file instead of .h
#include "Rtypes.h" //KEVIN ADDED THIS
//#endif
//#ifndef ROOT_TMatrixTUtils
//#include "TMatrixTUtils.h"
//#endif
//#ifdef CBLAS
//#include <vecLib/vBLAS.h>
//#include <cblas.h>
//#endif
//////////////////////////////////////////////////////////////////////////
// //
// TMatrixTSparse //
// //
// Template class of a general sparse matrix in the Harwell-Boeing //
// format //
// //
//////////////////////////////////////////////////////////////////////////
//template<class Element> class TMatrixT;
template<class Element> class TMatrixTSparse : public TMatrixTBase<Element> {
protected:
Int_t *fRowIndex; //[fNrowIndex] row index
Int_t *fColIndex; //[fNelems] column index
Element *fElements; //[fNelems]
void Allocate(Int_t nrows,Int_t ncols,Int_t row_lwb = 0,Int_t col_lwb = 0,
Int_t init = 0,Int_t nr_nonzeros = 0);
// Elementary constructors
//void AMultB (const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0) {
// const TMatrixTSparse<Element> bt(TMatrixTSparse::kTransposed,b); AMultBt(a,bt,constr); }
//void AMultB (const TMatrixTSparse<Element> &a,const TMatrixT<Element> &b,Int_t constr=0) {
// const TMatrixTSparse<Element> bsp = b;
// const TMatrixTSparse<Element> bt(TMatrixTSparse::kTransposed,bsp); AMultBt(a,bt,constr); }
//void AMultB (const TMatrixT<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0) {
// const TMatrixTSparse<Element> bt(TMatrixTSparse::kTransposed,b); AMultBt(a,bt,constr); }
//void AMultBt(const TMatrixTSparse<Element> &a,const TMatrixT<Element> &b,Int_t constr=0);
//void AMultBt(const TMatrixT<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0);
//void APlusB (const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0);
//void APlusB (const TMatrixTSparse<Element> &a,const TMatrixT<Element> &b,Int_t constr=0);
//void APlusB (const TMatrixT<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0) { APlusB(b,a,constr); }
//void AMinusB(const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0);
//void AMinusB(const TMatrixTSparse<Element> &a,const TMatrixT<Element> &b,Int_t constr=0);
//void AMinusB(const TMatrixT<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=0);
public:
enum EMatrixCreatorsOp1 { kZero,kUnit,kTransposed,kAtA }; //IN ROSA'S CODE THESE TWO LINES ARE IN TMATRIXDBASE.H
enum EMatrixCreatorsOp2 { kMult,kMultTranspose,kPlus,kMinus };
void AMultBt(const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b,Int_t constr=1); //CHANGED CONSTR=0 TO CONSTR = 1 FROM ROSA'S CODE
//IN ADDITION THIS WAS ORIGINALLY PRIVATE... MOVED IT TO PUBLIC FOR TESTTMATRIXDSPARSE.CPP
TMatrixTSparse() { fElements = 0; fRowIndex = 0; fColIndex = 0; }
TMatrixTSparse(Int_t nrows,Int_t ncols);
//TMatrixTSparse(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb);
TMatrixTSparse(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Int_t nr_nonzeros,
Int_t *row, Int_t *col,Element *data);
//TMatrixTSparse(const TMatrixTSparse<Element> &another);
//TMatrixTSparse(const TMatrixT<Element> &another);
//TMatrixTSparse(EMatrixCreatorsOp1 op,const TMatrixTSparse<Element> &prototype);
//TMatrixTSparse(const TMatrixTSparse<Element> &a,EMatrixCreatorsOp2 op,const TMatrixTSparse<Element> &b);
//virtual ~TMatrixTSparse() { Clear(); }
virtual const Element *GetMatrixArray () const;
virtual Element *GetMatrixArray ();
virtual const Int_t *GetRowIndexArray() const;
virtual Int_t *GetRowIndexArray();
virtual const Int_t *GetColIndexArray() const;
virtual Int_t *GetColIndexArray();
//virtual TMatrixTBase<Element> &SetRowIndexArray(Int_t *data) { memmove(fRowIndex,data,(this->fNrows+1)*sizeof(Int_t)); return *this; }
//virtual TMatrixTBase<Element> &SetColIndexArray(Int_t *data) { memmove(fColIndex,data,this->fNelems*sizeof(Int_t)); return *this; }
//virtual void GetMatrix2Array (Element *data,Option_t *option="") const;
//virtual TMatrixTBase<Element> &SetMatrixArray (const Element *data,Option_t * /*option*/="")
// { memcpy(fElements,data,this->fNelems*sizeof(Element)); return *this; }
//KEVIN: SetMatrixArray used to be virtual..... gives me vtable errors.... don't know what it is though... googled it
TMatrixTBase<Element> &SetMatrixArray (Int_t nr_nonzeros,Int_t *irow,Int_t *icol,Element *data);
TMatrixTSparse<Element> &SetSparseIndex (Int_t nelem_new);
// TMatrixTSparse<Element> &SetSparseIndex (const TMatrixTBase<Element> &another);
//TMatrixTSparse<Element> &SetSparseIndexAB(const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b);
//virtual TMatrixTBase<Element> &InsertRow (Int_t row,Int_t col,const Element *v,Int_t n=-1);
//virtual void ExtractRow (Int_t row,Int_t col, Element *v,Int_t n=-1) const;
//virtual TMatrixTBase<Element> &ResizeTo(Int_t nrows,Int_t ncols,Int_t nr_nonzeros=-1);
// virtual TMatrixTBase<Element> &ResizeTo(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Int_t nr_nonzeros=-1);
//inline TMatrixTBase<Element> &ResizeTo(const TMatrixTSparse<Element> &m) {return ResizeTo(m.GetRowLwb(),m.GetRowUpb(),m.GetColLwb(),
// m.GetColUpb(),m.GetNoElements()); }
//virtual void Clear(Option_t * /*option*/ ="") { if (this->fIsOwner) {
// if (fElements) delete [] fElements; fElements = 0;
// if (fRowIndex) delete [] fRowIndex; fRowIndex = 0;
// if (fColIndex) delete [] fColIndex; fColIndex = 0;
// }
// this->fNelems = 0;
// this->fNrowIndex = 0;
// }
// TMatrixTSparse<Element> &Use (Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Int_t nr_nonzeros,
// Int_t *pRowIndex,Int_t *pColIndex,Element *pData);
// TMatrixTSparse<Element> &Use (Int_t nrows,Int_t ncols,Int_t nr_nonzeros,
// Int_t *pRowIndex,Int_t *pColIndex,Element *pData);
// TMatrixTSparse<Element> &Use (TMatrixTSparse<Element> &a);
// virtual TMatrixTBase<Element> &GetSub(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,
// TMatrixTBase<Element> &target,Option_t *option="S") const;
// TMatrixTSparse<Element> GetSub(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,Option_t *option="S") const;
// virtual TMatrixTBase<Element> &SetSub(Int_t row_lwb,Int_t col_lwb,const TMatrixTBase<Element> &source);
// virtual Bool_t IsSymmetric() const { return (*this == TMatrixTSparse<Element>(kTransposed,*this)); }
TMatrixTSparse<Element> &Transpose (const TMatrixTSparse<Element> &source);
inline TMatrixTSparse<Element> &T () { return this->Transpose(*this); }
// inline void Mult(const TMatrixTSparse<Element> &a,const TMatrixTSparse<Element> &b) { AMultB(a,b,0); }
// virtual TMatrixTBase<Element> &Zero ();
// virtual TMatrixTBase<Element> &UnitMatrix ();
// virtual Element RowNorm () const;
// virtual Element ColNorm () const;
virtual Int_t NonZeros() const { return this->fNelems; }
// virtual TMatrixTBase<Element> &NormByDiag(const TVectorT<Element> &/*v*/,Option_t * /*option*/)
// { MayNotUse("NormByDiag"); return *this; }
// Either access a_ij as a(i,j)
// inline Element operator()(Int_t rown,Int_t coln) const;
// Element &operator()(Int_t rown,Int_t coln);
// or as a[i][j]
// inline const TMatrixTSparseRow_const<Element> operator[](Int_t rown) const { return TMatrixTSparseRow_const<Element>(*this,rown); }
// inline TMatrixTSparseRow <Element> operator[](Int_t rown) { return TMatrixTSparseRow <Element>(*this,rown); }
// TMatrixTSparse<Element> &operator=(const TMatrixT<Element> &source);
// TMatrixTSparse<Element> &operator=(const TMatrixTSparse<Element> &source);
// TMatrixTSparse<Element> &operator= (Element val);
// TMatrixTSparse<Element> &operator-=(Element val);
// TMatrixTSparse<Element> &operator+=(Element val);
// TMatrixTSparse<Element> &operator*=(Element val);
// TMatrixTSparse<Element> &operator+=(const TMatrixTSparse<Element> &source) { TMatrixTSparse<Element> tmp(*this);
// if (this == &source) APlusB (tmp,tmp,1);
// else APlusB (tmp,source,1); return *this; }
// TMatrixTSparse<Element> &operator+=(const TMatrixT<Element> &source) { TMatrixTSparse<Element> tmp(*this);
// APlusB(tmp,source,1); return *this; }
// TMatrixTSparse<Element> &operator-=(const TMatrixTSparse<Element> &source) { TMatrixTSparse<Element> tmp(*this);
// if (this == &source) AMinusB (tmp,tmp,1);
// else AMinusB(tmp,source,1); return *this; }
// TMatrixTSparse<Element> &operator-=(const TMatrixT<Element> &source) { TMatrixTSparse<Element> tmp(*this);
// AMinusB(tmp,source,1); return *this; }
// TMatrixTSparse<Element> &operator*=(const TMatrixTSparse<Element> &source) { TMatrixTSparse<Element> tmp(*this);
// if (this == &source) AMultB (tmp,tmp,1);
// else AMultB (tmp,source,1); return *this; }
// TMatrixTSparse<Element> &operator*=(const TMatrixT<Element> &source) { TMatrixTSparse<Element> tmp(*this);
// AMultB(tmp,source,1); return *this; }
// virtual TMatrixTBase <Element> &Randomize (Element alpha,Element beta,Double_t &seed);
// virtual TMatrixTSparse<Element> &RandomizePD(Element alpha,Element beta,Double_t &seed);
// ClassDef(TMatrixTSparse,3) // Template of Sparse Matrix class
};
template <class Element> inline const Element *TMatrixTSparse<Element>::GetMatrixArray () const { return fElements; }
template <class Element> inline Element *TMatrixTSparse<Element>::GetMatrixArray () { return fElements; }
template <class Element> inline const Int_t *TMatrixTSparse<Element>::GetRowIndexArray() const { return fRowIndex; }
template <class Element> inline Int_t *TMatrixTSparse<Element>::GetRowIndexArray() { return fRowIndex; }
template <class Element> inline const Int_t *TMatrixTSparse<Element>::GetColIndexArray() const { return fColIndex; }
template <class Element> inline Int_t *TMatrixTSparse<Element>::GetColIndexArray() { return fColIndex; }
//template <class Element>
//inline TMatrixTSparse<Element> &TMatrixTSparse<Element>::Use (Int_t nrows,Int_t ncols,Int_t nr_nonzeros,
// Int_t *pRowIndex,Int_t *pColIndex,Element *pData)
// { return Use(0,nrows-1,0,ncols-1,nr_nonzeros,pRowIndex,pColIndex,pData); }
//template <class Element>
//inline TMatrixTSparse<Element> &TMatrixTSparse<Element>::Use (TMatrixTSparse<Element> &a)
// { R__ASSERT(a.IsValid());
// return Use(a.GetRowLwb(),a.GetRowUpb(),a.GetColLwb(),a.GetColUpb(),
// a.GetNoElements(),a.GetRowIndexArray(),
// a.GetColIndexArray(),a.GetMatrixArray()); }
//template <class Element>
//inline TMatrixTSparse<Element> TMatrixTSparse<Element>::GetSub(Int_t row_lwb,Int_t row_upb,Int_t col_lwb,Int_t col_upb,
// Option_t *option) const
// {
// TMatrixTSparse<Element> tmp;
// this->GetSub(row_lwb,row_upb,col_lwb,col_upb,tmp,option);
// return tmp;
// }
//template <class Element>
//inline Element TMatrixTSparse<Element>::operator()(Int_t rown,Int_t coln) const
//{
// R__ASSERT(this->IsValid());
// if (this->fNrowIndex > 0 && this->fRowIndex[this->fNrowIndex-1] == 0) {
// Error("operator=()(Int_t,Int_t) const","row/col indices are not set");
// printf("fNrowIndex = %d fRowIndex[fNrowIndex-1] = %d\n",this->fNrowIndex,this->fRowIndex[this->fNrowIndex-1]);
// return 0.0;
// }
// const Int_t arown = rown-this->fRowLwb;
// const Int_t acoln = coln-this->fColLwb;
// R__ASSERT(arown < this->fNrows && arown >= 0);
// R__ASSERT(acoln < this->fNcols && acoln >= 0);
// const Int_t sIndex = fRowIndex[arown];
// const Int_t eIndex = fRowIndex[arown+1];
// const Int_t index = TMath::BinarySearch(eIndex-sIndex,fColIndex+sIndex,acoln)+sIndex;
// if (index < sIndex || fColIndex[index] != acoln) return 0.0;
// else return fElements[index];
//}
//template <class Element> TMatrixTSparse<Element> operator+ (const TMatrixTSparse<Element> &source1,const TMatrixTSparse<Element> &source2);
//template <class Element> TMatrixTSparse<Element> operator+ (const TMatrixTSparse<Element> &source1,const TMatrixT<Element> &source2);
//template <class Element> TMatrixTSparse<Element> operator+ (const TMatrixT<Element> &source1,const TMatrixTSparse<Element> &source2);
//template <class Element> TMatrixTSparse<Element> operator+ (const TMatrixTSparse<Element> &source , Element val );
//template <class Element> TMatrixTSparse<Element> operator+ ( Element val ,const TMatrixTSparse<Element> &source );
//template <class Element> TMatrixTSparse<Element> operator- (const TMatrixTSparse<Element> &source1,const TMatrixTSparse<Element> &source2);
//template <class Element> TMatrixTSparse<Element> operator- (const TMatrixTSparse<Element> &source1,const TMatrixT<Element> &source2);
//template <class Element> TMatrixTSparse<Element> operator- (const TMatrixT<Element> &source1,const TMatrixTSparse<Element> &source2);
//template <class Element> TMatrixTSparse<Element> operator- (const TMatrixTSparse<Element> &source , Element val );
//template <class Element> TMatrixTSparse<Element> operator- ( Element val ,const TMatrixTSparse<Element> &source );
//template <class Element> TMatrixTSparse<Element> operator* (const TMatrixTSparse<Element> &source1,const TMatrixTSparse<Element> &source2);
//template <class Element> TMatrixTSparse<Element> operator* (const TMatrixTSparse<Element> &source1,const TMatrixT<Element> &source2);
//template <class Element> TMatrixTSparse<Element> operator* (const TMatrixT<Element> &source1,const TMatrixTSparse<Element> &source2);
///template <class Element> TMatrixTSparse<Element> operator* ( Element val ,const TMatrixTSparse<Element> &source );
//template <class Element> TMatrixTSparse<Element> operator* (const TMatrixTSparse<Element> &source, Element val );
//template <class Element> TMatrixTSparse<Element> &Add (TMatrixTSparse<Element> &target, Element scalar,
// const TMatrixTSparse<Element> &source);
//template <class Element> TMatrixTSparse<Element> &ElementMult(TMatrixTSparse<Element> &target,const TMatrixTSparse<Element> &source);
//template <class Element> TMatrixTSparse<Element> &ElementDiv (TMatrixTSparse<Element> &target,const TMatrixTSparse<Element> &source);
//template <class Element> Bool_t AreCompatible(const TMatrixTSparse<Element> &m1,const TMatrixTSparse<Element> &m2,Int_t verbose=0);
//#endif
| {
"alphanum_fraction": 0.5823202032,
"avg_line_length": 69.8377358491,
"ext": "h",
"hexsha": "6f085905929c35f157b1bbbf5bde784a6f328a08",
"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": "daddd76858a53035f5d713f648d13373c22506e8",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "sharugupta/OpenUH",
"max_forks_repo_path": "osprey/testsuite/cases/cern/root/TMatrixTSparse/TMatrixTSparse.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "daddd76858a53035f5d713f648d13373c22506e8",
"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": "sharugupta/OpenUH",
"max_issues_repo_path": "osprey/testsuite/cases/cern/root/TMatrixTSparse/TMatrixTSparse.h",
"max_line_length": 148,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "daddd76858a53035f5d713f648d13373c22506e8",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "sharugupta/OpenUH",
"max_stars_repo_path": "osprey/testsuite/cases/cern/root/TMatrixTSparse/TMatrixTSparse.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4504,
"size": 18507
} |
/* Standard C Libraries */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "interpolation.h"
#include "float.h"
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
typedef struct {
int start_index;
int end_index;
int n;
double* x;
double* y;
} segment;
typedef struct {
int n;
segment * seg;
} segments;
void free_segments(segments segs)
{
for(int i=0; i<segs.n; i++)
{
free(segs.seg[i].x);
free(segs.seg[i].y);
}
// free(segs.seg);
}
/***
* What is segment:
* mask | 00000000000000000111111111111100000000000000000 |
* | signal | no signal | signal |
* signal data | ~~|~~~~~~~|~~~~~|_____________|~~~~~|~~~~~~~|~~ |
* params | | edges | cut | | cut | edges | |
* stored for intrpolation | |-------| |-------| |
* will interpolate | |-------------------------| |
* start_index | X |
* end_index | X |
* start_data | X |
* start_data_to | X |
* end_data | X |
***/
segments add_new_segment(segments segs, int start_index, int end_index, int edges, int cut, vector data)
{
int start_data = start_index - edges - cut;
if(start_data < 0) start_data = 0;
int start_data_to = start_index - cut;
if(start_data_to < 0) start_data_to = 0;
int end_data = end_index + cut;
if(end_data > data.x) end_data = data.x - 1;
int new_size = segs.n + 1;
segs.seg = realloc(segs.seg, sizeof(segment)*new_size);
int data_size = edges * 2;
segs.seg[segs.n].start_index = start_data_to;
segs.seg[segs.n].end_index = end_data;
segs.seg[segs.n].n = data_size;
segs.seg[segs.n].x = calloc(data_size, sizeof(double));
segs.seg[segs.n].y = calloc(data_size, sizeof(double));
for(int i=0; i<edges; i++)
{
int x = i + start_data;
segs.seg[segs.n].x[i] = x;
segs.seg[segs.n].y[i] = getv(data, x);
x = edges + i + end_data;
segs.seg[segs.n].x[i+edges] = x;
segs.seg[segs.n].y[i+edges] = getv(data, x);
}
segs.n = new_size;
return segs;
}
segments vector_split_by_mask(vector data, vector mask, int edges, int cut)
{
segments segs;
segs.n = 0;
segs.seg = calloc(1, sizeof(segment));
int start_index = -1;
int end_index = -1;
for(int i=0; i<data.x; i++)
{
if(start_index == -1 && getv(mask, i) == 1.0)
{
start_index = i;
continue;
}
if(start_index != -1 && getv(mask, i) != 1.0)
{
end_index = i;
segs = add_new_segment(segs, start_index, end_index, edges, cut, data);
start_index = -1;
end_index = -1;
continue;
}
}
// if(start_index != -1)
// {
// end_index = data.x - 1;
// segs = add_new_segment(segs, start_index, end_index, edges, 0, data);
// }
return segs;
}
vector vector_interpolate(vector data, vector mask, int cut, const gsl_interp_type * T)
{
int edges = gsl_interp_type_min_size(T);
segments segs = vector_split_by_mask(data, mask, edges, cut);
vector result = copyv(data);
for(int i=0; i<segs.n; i++)
{
gsl_interp_accel *acc = gsl_interp_accel_alloc ();
gsl_spline *liner = gsl_spline_alloc(T, segs.seg[i].n);
gsl_spline_init (liner, segs.seg[i].x, segs.seg[i].y, segs.seg[i].n);
for(int j=segs.seg[i].start_index; j<segs.seg[i].end_index; j++)
{
setv(result, j, gsl_spline_eval (liner, j, acc));
}
gsl_spline_free (liner);
gsl_interp_accel_free (acc);
}
free_segments(segs);
return result;
}
vector vector_interpolate_by_mask(vector data, vector mask, int cut, int type)
{
vector result;
switch (type) {
case 1: // Linear interpolation
result = vector_interpolate(data, mask, cut, gsl_interp_linear);
break;
case 2: // Cubic spline (тatural boundary conditions)
result = vector_interpolate(data, mask, cut, gsl_interp_cspline);
break;
case 3: // Cubic spline (periodic boundary conditions)
result = vector_interpolate(data, mask, cut, gsl_interp_cspline_periodic);
break;
case 4: // Non-rounded Akima spline (natural boundary conditions)
result = vector_interpolate(data, mask, cut, gsl_interp_akima);
break;
case 5: // Non-rounded Akima spline (periodic boundary conditions)
result = vector_interpolate(data, mask, cut, gsl_interp_akima_periodic);
break;
case 6: // Steffen’s method
result = vector_interpolate(data, mask, cut, gsl_interp_steffen);
break;
default:
result = copyv(data);
break;
}
return result;
}
void interpolate_part(vector * data, int start, int end, const gsl_interp_type * T)
{
int edges = gsl_interp_type_min_size(T);
int start_index = start - edges;
if (start_index < 0) start_index = 0;
int end_index = end + edges;
if (end_index >= data->x) end_index = data->x;
int n = (start - start_index) + (end_index - end) + 1;
int index = 0;
vector x = zerov(n);
vector y = zerov(n);
for(int i=start_index; i<=start; i++)
{
// printf("i %i\n", i);
// fprintf(stdout, "val %f\n", data->v[i]);
setv(y, index, data->v[i]);
setv(x, index, i);
index++;
}
for(int i=end; i<end_index; i++)
{
// printf("i %i\n", i);
// fprintf(stdout, "val %f\n", data->v[i]);
setv(y, index, getv(*data, i));
setv(x, index, i);
index++;
}
// for (int i=start_index; i<end_index; i++)
// {
// if((i<=start_index || i>=end_index)&&(index<n)&&(data->v[i]!=0||i==start_index||i==end_index))
// {
// setv(y, index, getv(data, i));
// setv(x, index, i);
// index++;
// }
// }
n = index;
gsl_interp_accel *acc = gsl_interp_accel_alloc ();
gsl_spline *liner = gsl_spline_alloc(T, n);
gsl_spline_init (liner, x.v, y.v, n);
for(int j=(start); j<end; j++)
{
data->v[j] = gsl_spline_eval (liner, j, acc);
}
gsl_spline_free (liner);
gsl_interp_accel_free (acc);
freev(x);
freev(y);
}
void vector_interpolate_part(vector * data, int start, int end, int type)
{
if(end - start > 1)
switch (type) {
case 1: // Linear interpolation
interpolate_part(data, start, end, gsl_interp_linear);
break;
case 2: // Cubic spline (тatural boundary conditions)
interpolate_part(data, start, end, gsl_interp_cspline);
break;
case 3: // Cubic spline (periodic boundary conditions)
interpolate_part(data, start, end, gsl_interp_cspline_periodic);
break;
case 4: // Non-rounded Akima spline (natural boundary conditions)
interpolate_part(data, start, end, gsl_interp_akima);
break;
case 5: // Non-rounded Akima spline (periodic boundary conditions)
interpolate_part(data, start, end, gsl_interp_akima_periodic);
break;
case 6: // Steffen’s method
interpolate_part(data, start, end, gsl_interp_steffen);
break;
}
}
| {
"alphanum_fraction": 0.5259054326,
"avg_line_length": 30.2357414449,
"ext": "c",
"hexsha": "19743812633e9746924cb33b0c000e035d2f0657",
"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": "d70de9ae4c3c20efe51864a174310ca59d31c11f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zhitko/inton-trainer",
"max_forks_repo_path": "sptk/others/interpolation.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "d70de9ae4c3c20efe51864a174310ca59d31c11f",
"max_issues_repo_issues_event_max_datetime": "2019-03-27T21:31:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-03-27T21:31:30.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zhitko/sptk-analyzer",
"max_issues_repo_path": "sptk/others/interpolation.c",
"max_line_length": 105,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "d70de9ae4c3c20efe51864a174310ca59d31c11f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zhitko/sptk-analyzer",
"max_stars_repo_path": "sptk/others/interpolation.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-17T12:22:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-02T20:47:53.000Z",
"num_tokens": 2075,
"size": 7952
} |
#include <cblas.h>
#include "tasks.h"
#include "utils.h"
void trsm_task_par_reconfigure(int nth)
{
// empty
}
void trsm_task_par_finalize(void)
{
// empty
}
void trsm_task_par(void *ptr, int nth, int me)
{
struct trsm_task_arg *arg = (struct trsm_task_arg*) ptr;
int n = arg->n;
int m = arg->m;
double *A21 = arg->A21;
double *A11 = arg->A11;
int ldA = arg->ldA;
// Compute nominal block size.
int blksz = iceil(m, nth);
// Determine my share of the rows of A21.
int my_first_row = blksz * me;
int my_num_rows = min(blksz, m - my_first_row);
// Compute A21 := A21 * inv(A11'), using my block of A21.
if (my_num_rows > 0) {
cblas_dtrsm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit,
my_num_rows, n,
1.0, A11, ldA,
A21 + my_first_row, ldA);
}
}
| {
"alphanum_fraction": 0.563559322,
"avg_line_length": 20.9777777778,
"ext": "c",
"hexsha": "b72568025dfe9907e60830f99b54418c755ca381",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/pcp-runtime",
"max_forks_repo_path": "src/examples/dpotrf/task-trsm-par.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/pcp-runtime",
"max_issues_repo_path": "src/examples/dpotrf/task-trsm-par.c",
"max_line_length": 84,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/pcp-runtime",
"max_stars_repo_path": "src/examples/dpotrf/task-trsm-par.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 287,
"size": 944
} |
#ifndef problems_h
#define problems_h
#include <ceed.h>
#include <petsc.h>
#include "../problems/cl-problems.h"
#include "../problems/neo-hookean.h"
#include "../problems/mooney-rivlin.h"
// Physics options
#define SOLIDS_PROBLEM_REGISTER(list, name, fname, physics) \
ierr = PetscFunctionListAdd(&list->setupPhysics, name, \
PhysicsContext_ ## physics); CHKERRQ(ierr); \
ierr = PetscFunctionListAdd(&list->setupSmootherPhysics, name, \
PhysicsSmootherContext_ ## physics); CHKERRQ(ierr); \
ierr = PetscFunctionListAdd(&list->setupLibceedFineLevel, name, \
SetupLibceedFineLevel_ ## fname); CHKERRQ(ierr); \
ierr = PetscFunctionListAdd(&list->setupLibceedLevel, name, \
SetupLibceedLevel_ ## fname); CHKERRQ(ierr); \
typedef struct ProblemFunctions_ *ProblemFunctions;
struct ProblemFunctions_ {
PetscFunctionList setupPhysics, setupSmootherPhysics, setupLibceedFineLevel,
setupLibceedLevel;
};
PetscErrorCode RegisterProblems(ProblemFunctions problem_functions);
#define SOLIDS_PROBLEM(name) \
PetscErrorCode SetupLibceedFineLevel_ ## name (DM dm, DM dm_energy, \
DM dm_diagnostic, Ceed ceed, AppCtx app_ctx, CeedQFunctionContext phys_ctx, \
PetscInt fine_level, PetscInt num_comp_u, PetscInt U_g_size, \
PetscInt U_loc_size, CeedVector force_ceed, CeedVector neumann_ceed, \
CeedData *data); \
PetscErrorCode SetupLibceedLevel_ ## name (DM dm, Ceed ceed, \
AppCtx app_ctx, PetscInt level, PetscInt num_comp_u, PetscInt U_g_size, \
PetscInt u_loc_size, CeedVector fine_mult, CeedData *data); \
SOLIDS_PROBLEM(ElasLinear);
SOLIDS_PROBLEM(ElasSSNH);
SOLIDS_PROBLEM(ElasFSCurrentNH1);
SOLIDS_PROBLEM(ElasFSCurrentNH2);
SOLIDS_PROBLEM(ElasFSInitialNH1);
SOLIDS_PROBLEM(ElasFSInitialNH2);
SOLIDS_PROBLEM(ElasFSInitialMR1);
#endif //problems_h
| {
"alphanum_fraction": 0.6508379888,
"avg_line_length": 44.75,
"ext": "h",
"hexsha": "4ce53c6a02704c904919f7fa13d60eeb2d830d49",
"lang": "C",
"max_forks_count": 41,
"max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z",
"max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "AdelekeBankole/libCEED",
"max_forks_repo_path": "examples/solids/problems/problems.h",
"max_issues_count": 781,
"max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "AdelekeBankole/libCEED",
"max_issues_repo_path": "examples/solids/problems/problems.h",
"max_line_length": 83,
"max_stars_count": 123,
"max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "AdelekeBankole/libCEED",
"max_stars_repo_path": "examples/solids/problems/problems.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z",
"num_tokens": 520,
"size": 2148
} |
#include <gsl/gsl_math.h>
#include "gsl_cblas.h"
#include "cblas.h"
void
cblas_dsyr2k (const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,
const enum CBLAS_TRANSPOSE Trans, const int N, const int K,
const double alpha, const double *A, const int lda,
const double *B, const int ldb, const double beta, double *C,
const int ldc)
{
#define BASE double
#include "source_syr2k_r.h"
#undef BASE
}
| {
"alphanum_fraction": 0.7072599532,
"avg_line_length": 26.6875,
"ext": "c",
"hexsha": "d05156dffee12501dedcd594ec8e2140c2dffc38",
"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/dsyr2k.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/dsyr2k.c",
"max_line_length": 71,
"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/dsyr2k.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": 124,
"size": 427
} |
#include <gsl/gsl_math.h>
#include <gsl/gsl_cblas.h>
#include "cblas.h"
#include "error_cblas_l2.h"
void
cblas_sspmv (const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo,
const int N, const float alpha, const float *Ap, const float *X,
const int incX, const float beta, float *Y, const int incY)
{
#define BASE float
#include "source_spmv.h"
#undef BASE
}
| {
"alphanum_fraction": 0.6984536082,
"avg_line_length": 25.8666666667,
"ext": "c",
"hexsha": "8aca4cc36b017c259d1a08b5bb818fcb6b7e6627",
"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/cblas/sspmv.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/cblas/sspmv.c",
"max_line_length": 77,
"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/cblas/sspmv.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": 115,
"size": 388
} |
/**
*
* @file zcposv.c
*
* PLASMA computational 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 Emmanuel Agullo
* @date 2010-11-15
* @precisions mixed zc -> ds
*
**/
#include <stdlib.h>
#include <math.h>
#include <lapacke.h>
#include "common.h"
#define PLASMA_zlag2c(_descA, _descSB) \
plasma_parallel_call_4(plasma_pzlag2c, \
PLASMA_desc, (_descA), \
PLASMA_desc, (_descSB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
#define PLASMA_clag2z(_descSA, _descB) \
plasma_parallel_call_4(plasma_pclag2z, \
PLASMA_desc, (_descSA), \
PLASMA_desc, (_descB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
#define PLASMA_zlange(_norm, _descA, _result, _work) \
_result = 0; \
plasma_parallel_call_6(plasma_pzlange, \
PLASMA_enum, (_norm), \
PLASMA_desc, (_descA), \
double*, (_work), \
double*, &(_result), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request);
#define PLASMA_zlanhe(_norm, _uplo, _descA, _result, _work) \
_result = 0; \
plasma_parallel_call_7(plasma_pzlanhe, \
PLASMA_enum, (_norm), \
PLASMA_enum, (_uplo), \
PLASMA_desc, (_descA), \
double*, (_work), \
double*, &(_result), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request);
#define PLASMA_zlacpy(_descA, _descB) \
plasma_parallel_call_5(plasma_pzlacpy, \
PLASMA_enum, PlasmaUpperLower, \
PLASMA_desc, (_descA), \
PLASMA_desc, (_descB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
#define PLASMA_zgeadd(_alpha, _descA, _descB) \
plasma_parallel_call_5(plasma_pzgeadd, \
PLASMA_Complex64_t, (_alpha), \
PLASMA_desc, (_descA), \
PLASMA_desc, (_descB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
/***************************************************************************//**
*
* @ingroup PLASMA_Complex64_t
*
* PLASMA_zcposv - Computes the solution to a system of linear equations A * X = B,
* where A is an N-by-N symmetric positive definite (or Hermitian positive definite
* in the complex case) matrix and X and B are N-by-NRHS matrices.
* The Cholesky decomposition is used to factor A as
*
* A = U**H * U, if uplo = PlasmaUpper, or
* A = L * L**H, if uplo = PlasmaLower,
*
* where U is an upper triangular matrix and L is a lower triangular matrix.
* The factored form of A is then used to solve the system of equations A * X = B.
*
* PLASMA_zcposv first attempts to factorize the matrix in COMPLEX and use this
* factorization within an iterative refinement procedure to produce a
* solution with COMPLEX*16 normwise backward error quality (see below).
* If the approach fails the method switches to a COMPLEX*16
* factorization and solve.
*
* The iterative refinement is not going to be a winning strategy if
* the ratio COMPLEX performance over COMPLEX*16 performance is too
* small. A reasonable strategy should take the number of right-hand
* sides and the size of the matrix into account. This might be done
* with a call to ILAENV in the future. Up to now, we always try
* iterative refinement.
*
* The iterative refinement process is stopped if ITER > ITERMAX or
* for all the RHS we have: RNRM < N*XNRM*ANRM*EPS*BWDMAX
* where:
*
* - ITER is the number of the current iteration in the iterative refinement process
* - RNRM is the infinity-norm of the residual
* - XNRM is the infinity-norm of the solution
* - ANRM is the infinity-operator-norm of the matrix A
* - EPS is the machine epsilon returned by DLAMCH('Epsilon').
*
* Actually, in its current state (PLASMA 2.1.0), the test is slightly relaxed.
*
* The values ITERMAX and BWDMAX are fixed to 30 and 1.0D+00 respectively.
*
*******************************************************************************
*
* @param[in] uplo
* Specifies whether the matrix A is upper triangular or lower triangular:
* = PlasmaUpper: Upper triangle of A is stored;
* = PlasmaLower: Lower triangle of A is stored.
*
* @param[in] N
* The number of linear equations, i.e., the order of the matrix A. N >= 0.
*
* @param[in] NRHS
* The number of right hand sides, i.e., the number of columns of the matrix B.
* NRHS >= 0.
*
* @param[in] A
* The N-by-N symmetric positive definite (or Hermitian) coefficient matrix A.
* If uplo = PlasmaUpper, the leading N-by-N upper triangular part of A
* contains the upper triangular part of the matrix A, and the strictly lower triangular
* part of A is not referenced.
* If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower
* triangular part of the matrix A, and the strictly upper triangular part of A is not
* referenced.
* This matrix is not modified.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,N).
*
* @param[in] B
* The N-by-NRHS matrix of right hand side matrix B.
*
* @param[in] LDB
* The leading dimension of the array B. LDB >= max(1,N).
*
* @param[out] X
* If return value = 0, the N-by-NRHS solution matrix X.
*
* @param[in] LDX
* The leading dimension of the array B. LDX >= max(1,N).
*
* @param[out] ITER
* The number of the current iteration in the iterative refinement process
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
* \retval >0 if i, the leading minor of order i of A is not positive definite, so the
* factorization could not be completed, and the solution has not been computed.
*
*******************************************************************************
*
* @sa PLASMA_zcposv_Tile
* @sa PLASMA_zcposv_Tile_Async
* @sa PLASMA_dsposv
* @sa PLASMA_zposv
*
******************************************************************************/
int PLASMA_zcposv(PLASMA_enum uplo, int N, int NRHS,
PLASMA_Complex64_t *A, int LDA,
PLASMA_Complex64_t *B, int LDB,
PLASMA_Complex64_t *X, int LDX, int *ITER)
{
int NB;
int status;
PLASMA_desc descA;
PLASMA_desc descB;
PLASMA_desc descX;
plasma_context_t *plasma;
PLASMA_sequence *sequence = NULL;
PLASMA_request request = PLASMA_REQUEST_INITIALIZER;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_zcposv", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
*ITER = 0;
/* Check input arguments */
if (uplo != PlasmaUpper && uplo != PlasmaLower) {
plasma_error("PLASMA_zcposv", "illegal value of uplo");
return -1;
}
if (N < 0) {
plasma_error("PLASMA_zcposv", "illegal value of N");
return -2;
}
if (NRHS < 0) {
plasma_error("PLASMA_zcposv", "illegal value of NRHS");
return -3;
}
if (LDA < max(1, N)) {
plasma_error("PLASMA_zcposv", "illegal value of LDA");
return -5;
}
if (LDB < max(1, N)) {
plasma_error("PLASMA_zcposv", "illegal value of LDB");
return -7;
}
if (LDX < max(1, N)) {
plasma_error("PLASMA_zcposv", "illegal value of LDX");
return -9;
}
/* Quick return - currently NOT equivalent to LAPACK's
* LAPACK does not have such check for ZCPOSV */
if (min(N, NRHS) == 0)
return PLASMA_SUCCESS;
/* Tune NB depending on M, N & NRHS; Set NBNBSIZE */
status = plasma_tune(PLASMA_FUNC_ZCPOSV, N, N, NRHS);
if (status != PLASMA_SUCCESS) {
plasma_error("PLASMA_zcposv", "plasma_tune() failed");
return status;
}
NB = PLASMA_NB;
plasma_sequence_create(plasma, &sequence);
/* DOUBLE PRECISION INITIALIZATION */
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_zooplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N, sequence, &request,
plasma_desc_mat_free(&(descA)) );
plasma_zooplap2tile( descB, B, NB, NB, LDB, NRHS, 0, 0, N, NRHS, sequence, &request,
plasma_desc_mat_free(&(descA)); plasma_desc_mat_free(&(descB)) );
plasma_zdesc_alloc( descX, NB, NB, N, NRHS, 0, 0, N, NRHS, plasma_desc_mat_free(&(descA)); plasma_desc_mat_free(&(descB)); plasma_desc_mat_free(&(descX)) );
} else {
plasma_ziplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N,
sequence, &request);
plasma_ziplap2tile( descB, B, NB, NB, LDB, NRHS, 0, 0, N, NRHS,
sequence, &request);
descX = plasma_desc_init(
PlasmaComplexDouble, NB, NB, (NB*NB),
LDX, NRHS, 0, 0, N, NRHS);
descX.mat = X;
}
/* Call the native interface */
status = PLASMA_zcposv_Tile_Async(uplo, &descA, &descB, &descX, ITER, sequence, &request);
if (status == PLASMA_SUCCESS) {
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_zooptile2lap( descX, X, NB, NB, LDX, NRHS, sequence, &request);
plasma_dynamic_sync();
plasma_desc_mat_free(&descA);
plasma_desc_mat_free(&descB);
plasma_desc_mat_free(&descX);
} else {
plasma_ziptile2lap( descA, A, NB, NB, LDA, N, sequence, &request);
plasma_ziptile2lap( descB, B, NB, NB, LDB, NRHS, sequence, &request);
plasma_ziptile2lap( descX, X, NB, NB, LDX, NRHS, sequence, &request);
plasma_dynamic_sync();
}
}
status = sequence->status;
plasma_sequence_destroy(plasma, sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup PLASMA_Complex64_t_Tile
*
* PLASMA_zcposv_Tile - Solves a symmetric positive definite or Hermitian positive definite
* system of linear equations using the Cholesky factorization and mixed-precision iterative refinement.
* Tile equivalent of PLASMA_zcposv().
* Operates on matrices stored by tiles.
* All matrices are passed through descriptors.
* All dimensions are taken from the descriptors.
*
*******************************************************************************
*
* @param[in] uplo
* Specifies whether the matrix A is upper triangular or lower triangular:
* = PlasmaUpper: Upper triangle of A is stored;
* = PlasmaLower: Lower triangle of A is stored.
*
* @param[in,out] A
* On entry, the N-by-N symmetric positive definite (or Hermitian) coefficient matrix A.
* If uplo = PlasmaUpper, the leading N-by-N upper triangular part of A
* contains the upper triangular part of the matrix A, and the strictly lower triangular
* part of A is not referenced.
* If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower
* triangular part of the matrix A, and the strictly upper triangular part of A is not
* referenced.
* - If the iterative refinement converged, A is not modified;
* - otherwise, it falled backed to double precision solution,
*
* @param[in] B
* On entry, the N-by-NRHS matrix of right hand side matrix B.
*
* @param[out] X
* On exit, if return value = 0, the N-by-NRHS solution matrix X.
*
* @param[out] ITER
* The number of the current iteration in the iterative refinement process
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval >0 if i, the leading minor of order i of A is not positive definite, so the
* factorization could not be completed, and the solution has not been computed.
*
*******************************************************************************
*
* @sa PLASMA_zcposv
* @sa PLASMA_zcposv_Tile_Async
* @sa PLASMA_dsposv_Tile
* @sa PLASMA_zposv_Tile
*
******************************************************************************/
int PLASMA_zcposv_Tile(PLASMA_enum uplo, PLASMA_desc *A, PLASMA_desc *B,
PLASMA_desc *X, int *ITER)
{
plasma_context_t *plasma;
PLASMA_sequence *sequence = NULL;
PLASMA_request request = PLASMA_REQUEST_INITIALIZER;
int status;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_zcposv_Tile", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
plasma_sequence_create(plasma, &sequence);
status = PLASMA_zcposv_Tile_Async(uplo, A, B, X, ITER, sequence, &request);
if (status != PLASMA_SUCCESS)
return status;
plasma_dynamic_sync();
status = sequence->status;
plasma_sequence_destroy(plasma, sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup PLASMA_Complex64_t_Tile_Async
*
* PLASMA_zcposv_Tile_Async - Solves a symmetric positive definite or Hermitian
* positive definite system of linear equations using the Cholesky factorization
* and mixed-precision iterative refinement.
* Non-blocking equivalent of PLASMA_zcposv_Tile().
* May return before the computation is finished.
* Allows for pipelining of operations at runtime.
*
*******************************************************************************
*
* @param[in] sequence
* Identifies the sequence of function calls that this call belongs to
* (for completion checks and exception handling purposes).
*
* @param[out] request
* Identifies this function call (for exception handling purposes).
*
*******************************************************************************
*
* @sa PLASMA_zcposv
* @sa PLASMA_zcposv_Tile
* @sa PLASMA_dsposv_Tile_Async
* @sa PLASMA_zposv_Tile_Async
*
******************************************************************************/
int PLASMA_zcposv_Tile_Async(PLASMA_enum uplo, PLASMA_desc *A, PLASMA_desc *B,
PLASMA_desc *X, int *ITER,
PLASMA_sequence *sequence, PLASMA_request *request)
{
int N, NB;
PLASMA_desc descA;
PLASMA_desc descB;
PLASMA_desc descX;
plasma_context_t *plasma;
double *work;
PLASMA_desc descR, descSA, descSX;
const int itermax = 30;
const double bwdmax = 1.0;
const PLASMA_Complex64_t negone = -1.0;
const PLASMA_Complex64_t one = 1.0;
int iiter;
double Anorm, cte, eps, Rnorm, Xnorm;
*ITER=0;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_zcposv_Tile_Async", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
if (sequence == NULL) {
plasma_fatal_error("PLASMA_zcposv_Tile_Async", "NULL sequence");
return PLASMA_ERR_UNALLOCATED;
}
if (request == NULL) {
plasma_fatal_error("PLASMA_zcposv_Tile_Async", "NULL request");
return PLASMA_ERR_UNALLOCATED;
}
/* Check sequence status */
if (sequence->status == PLASMA_SUCCESS)
request->status = PLASMA_SUCCESS;
else
return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);
/* Check descriptors for correctness */
if (plasma_desc_check(A) != PLASMA_SUCCESS) {
plasma_error("PLASMA_zcposv_Tile_Async", "invalid first descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descA = *A;
}
if (plasma_desc_check(B) != PLASMA_SUCCESS) {
plasma_error("PLASMA_zcposv_Tile_Async", "invalid second descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descB = *B;
}
if (plasma_desc_check(X) != PLASMA_SUCCESS) {
plasma_error("PLASMA_zcposv_Tile_Async", "invalid third descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descX = *X;
}
/* Check input arguments */
if (descA.nb != descA.mb || descB.nb != descB.mb || descX.nb != descX.mb) {
plasma_error("PLASMA_zcposv_Tile_Async", "only square tiles supported");
return PLASMA_ERR_ILLEGAL_VALUE;
}
if (uplo != PlasmaUpper && uplo != PlasmaLower) {
plasma_error("PLASMA_zcposv_Tile_Async", "illegal value of uplo");
return -1;
}
/* Quick return - currently NOT equivalent to LAPACK's
* LAPACK does not have such check for DPOSV */
/*
if (min(N, NRHS) == 0)
return PLASMA_SUCCESS;
*/
/* Set N, NRHS */
N = descA.m;
NB = descA.nb;
work = (double *)plasma_shared_alloc(plasma, PLASMA_SIZE, PlasmaRealDouble);
if (work == NULL) {
plasma_error("PLASMA_zcposv_Tile_Async", "plasma_shared_alloc() failed");
plasma_shared_free(plasma, work);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
plasma_zdesc_alloc( descR, NB, NB, descB.m, descB.n, 0, 0, descB.m, descB.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR) );
plasma_cdesc_alloc( descSA, NB, NB, descA.m, descA.n, 0, 0, descA.m, descA.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR); plasma_desc_mat_free(&descSA) );
plasma_cdesc_alloc( descSX, NB, NB, descX.m, descX.n, 0, 0, descX.m, descX.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR); plasma_desc_mat_free(&descSA); plasma_desc_mat_free(&descSX) );
/* Compute some constants */
PLASMA_zlanhe(PlasmaInfNorm, uplo, descA, Anorm, work);
eps = LAPACKE_dlamch_work('e');
/* Convert B from double precision to single precision and store
the result in SX. */
PLASMA_zlag2c(descB, descSX);
if (sequence->status != PLASMA_SUCCESS)
return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);
/* Convert A from double precision to single precision and store
the result in SA. */
PLASMA_zlag2c(descA, descSA);
if (sequence->status != PLASMA_SUCCESS)
return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);
/* Compute the Cholesky factorization of SA */
plasma_parallel_call_4(plasma_pcpotrf,
PLASMA_enum, uplo,
PLASMA_desc, descSA,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Solve the system SA*SX = SB */
/* Forward substitution */
plasma_parallel_call_9(plasma_pctrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, uplo,
PLASMA_enum, uplo == PlasmaUpper ? PlasmaConjTrans : PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
PLASMA_Complex32_t, 1.0,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Backward substitution */
plasma_parallel_call_9(plasma_pctrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, uplo,
PLASMA_enum, uplo == PlasmaUpper ? PlasmaNoTrans : PlasmaConjTrans,
PLASMA_enum, PlasmaNonUnit,
PLASMA_Complex32_t, 1.0,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Convert SX back to double precision */
PLASMA_clag2z(descSX, descX);
/* Compute R = B - AX. */
PLASMA_zlacpy(descB,descR);
plasma_parallel_call_9(plasma_pzhemm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, uplo,
PLASMA_Complex64_t, negone,
PLASMA_desc, descA,
PLASMA_desc, descX,
PLASMA_Complex64_t, one,
PLASMA_desc, descR,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Check whether the NRHS normwise backward error satisfies the
stopping criterion. If yes return. Note that ITER=0 (already set). */
PLASMA_zlange(PlasmaInfNorm, descX, Xnorm, work);
PLASMA_zlange(PlasmaInfNorm, descR, Rnorm, work);
/* Wait for the end of Anorm, Xnorm and Bnorm computations */
plasma_dynamic_sync();
cte = Anorm*eps*((double) N)*bwdmax;
if (Rnorm < Xnorm * cte){
/* The NRHS normwise backward errors satisfy the
stopping criterion. We are good to exit. */
plasma_desc_mat_free(&descSA);
plasma_desc_mat_free(&descSX);
plasma_desc_mat_free(&descR);
plasma_shared_free(plasma, work);
return PLASMA_SUCCESS;
}
/* Iterative refinement */
for (iiter = 0; iiter < itermax; iiter++){
/* Convert R from double precision to single precision
and store the result in SX. */
PLASMA_zlag2c(descR, descSX);
/* Solve the system SA*SX = SR */
/* Forward substitution */
plasma_parallel_call_9(plasma_pctrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, uplo,
PLASMA_enum, uplo == PlasmaUpper ? PlasmaConjTrans : PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
PLASMA_Complex32_t, 1.0,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Backward substitution */
plasma_parallel_call_9(plasma_pctrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, uplo,
PLASMA_enum, uplo == PlasmaUpper ? PlasmaNoTrans : PlasmaConjTrans,
PLASMA_enum, PlasmaNonUnit,
PLASMA_Complex32_t, 1.0,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Convert SX back to double precision and update the current
iterate. */
PLASMA_clag2z(descSX, descR);
PLASMA_zgeadd(one, descR, descX);
/* Compute R = B - AX. */
PLASMA_zlacpy(descB,descR);
plasma_parallel_call_9(plasma_pzhemm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, uplo,
PLASMA_Complex64_t, negone,
PLASMA_desc, descA,
PLASMA_desc, descX,
PLASMA_Complex64_t, one,
PLASMA_desc, descR,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Check whether the NRHS normwise backward errors satisfy the
stopping criterion. If yes, set ITER=IITER>0 and return. */
PLASMA_zlange(PlasmaInfNorm, descX, Xnorm, work);
PLASMA_zlange(PlasmaInfNorm, descR, Rnorm, work);
/* Wait for the end of Xnorm and Bnorm computations */
plasma_dynamic_sync();
if (Rnorm < Xnorm * cte){
/* The NRHS normwise backward errors satisfy the
stopping criterion. We are good to exit. */
*ITER = iiter;
plasma_desc_mat_free(&descSA);
plasma_desc_mat_free(&descSX);
plasma_desc_mat_free(&descR);
plasma_shared_free(plasma, work);
return PLASMA_SUCCESS;
}
}
/* We have performed ITER=itermax iterations and never satisified
the stopping criterion, set up the ITER flag accordingly and
follow up on double precision routine. */
*ITER = -itermax - 1;
plasma_desc_mat_free(&descSA);
plasma_desc_mat_free(&descSX);
plasma_desc_mat_free(&descR);
plasma_shared_free(plasma, work);
/* Single-precision iterative refinement failed to converge to a
satisfactory solution, so we resort to double precision. */
plasma_parallel_call_4(plasma_pzpotrf,
PLASMA_enum, uplo,
PLASMA_desc, descA,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
PLASMA_zlacpy(descB,descX);
plasma_parallel_call_9(plasma_pztrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, uplo,
PLASMA_enum, uplo == PlasmaUpper ? PlasmaConjTrans : PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
PLASMA_Complex64_t, 1.0,
PLASMA_desc, descA,
PLASMA_desc, descX,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_9(plasma_pztrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, uplo,
PLASMA_enum, uplo == PlasmaUpper ? PlasmaNoTrans : PlasmaConjTrans,
PLASMA_enum, PlasmaNonUnit,
PLASMA_Complex64_t, 1.0,
PLASMA_desc, descA,
PLASMA_desc, descX,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.5906743798,
"avg_line_length": 38.4432835821,
"ext": "c",
"hexsha": "9a61790380ac1fcc5cf4514046a2a9a29bf169dc",
"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": "compute/zcposv.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": "compute/zcposv.c",
"max_line_length": 211,
"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": "compute/zcposv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6688,
"size": 25757
} |
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#pragma warning (disable : 4514 4710 4711) // inlining
#pragma warning (disable: 5045) // TODO Spectre
// #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#pragma warning (push, 1)
#pragma warning (disable : 5039 4668 4996 26814 4548 4355 4917 4702 26400 4987 4820 4365 4623 4625 4626 5026 5027 4571 4774 26412 26461 26426 26432 26447 26472 26446 26473 26440 26429 26496 26472 26482 26486 26487 26434)
#include <gsl.h>
#pragma warning (pop) // unbalanced push in span.h
#include <windows.h>
#include <Shlobj.h>
#include <Strsafe.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <memory>
#include <string>
#include <vector>
#include <array>
#include <ranges>
#include <span>
#include "Resource.h"
#pragma warning (pop)
| {
"alphanum_fraction": 0.7416829746,
"avg_line_length": 30.0588235294,
"ext": "h",
"hexsha": "b5517d39f4d960e4e588e3db55d21301e073f963",
"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": "8ff11aea865a5a1e5c7ada0c39d34b72f8f77ba6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SteveGilham/drophash",
"max_forks_repo_path": "drophash/stdafx.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8ff11aea865a5a1e5c7ada0c39d34b72f8f77ba6",
"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": "SteveGilham/drophash",
"max_issues_repo_path": "drophash/stdafx.h",
"max_line_length": 220,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8ff11aea865a5a1e5c7ada0c39d34b72f8f77ba6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SteveGilham/drophash",
"max_stars_repo_path": "drophash/stdafx.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 304,
"size": 1022
} |
/* movstat/mmacc.c
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* This module contains routines for tracking minimum/maximum values of a
* moving fixed-sized window. It is based on the algorithm of:
*
* [1] Daniel Lemire, Streaming Maximum-Minimum Filter Using No More than Three Comparisons per Element,
* Nordic Journal of Computing, Volume 13, Number 4, pages 328-339, 2006
*
* Also available as a preprint here: https://arxiv.org/abs/cs/0610046
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_movstat.h>
typedef double mmacc_type_t;
typedef mmacc_type_t ringbuf_type_t;
#include "deque.c"
#include "ringbuf.c"
typedef struct
{
size_t n; /* window size */
size_t k; /* number of samples in current window */
mmacc_type_t xprev; /* previous sample added to window */
ringbuf *rbuf; /* ring buffer storing current window, size n */
deque *minque; /* double-ended queue of min values (L) */
deque *maxque; /* double-ended queue of max values (U) */
} mmacc_state_t;
static size_t mmacc_size(const size_t n);
static int mmacc_init(const size_t n, void * vstate);
static int mmacc_insert(const mmacc_type_t x, void * vstate);
static int mmacc_delete(void * vstate);
static int mmacc_min(void * params, mmacc_type_t * result, const void * vstate);
static int mmacc_max(void * params, mmacc_type_t * result, const void * vstate);
static int mmacc_minmax(void * params, mmacc_type_t * result, const void * vstate);
static size_t
mmacc_size(const size_t n)
{
size_t size = 0;
size += sizeof(mmacc_state_t);
size += ringbuf_size(n); /* rbuf */
size += 2 * deque_size(n + 1); /* minque/maxque */
return size;
}
static int
mmacc_init(const size_t n, void * vstate)
{
mmacc_state_t * state = (mmacc_state_t *) vstate;
state->n = n;
state->k = 0;
state->xprev = 0.0;
state->rbuf = (ringbuf *) ((unsigned char *) vstate + sizeof(mmacc_state_t));
state->minque = (deque *) ((unsigned char *) state->rbuf + ringbuf_size(n));
state->maxque = (deque *) ((unsigned char *) state->minque + deque_size(n + 1));
ringbuf_init(n, state->rbuf);
deque_init(n + 1, state->minque);
deque_init(n + 1, state->maxque);
return GSL_SUCCESS;
}
static int
mmacc_insert(const mmacc_type_t x, void * vstate)
{
mmacc_state_t * state = (mmacc_state_t *) vstate;
int head, tail;
if (state->k == 0)
{
/* first sample */
ringbuf_insert(x, state->rbuf);
head = state->rbuf->head;
deque_push_back(head, state->maxque);
deque_push_back(head, state->minque);
}
else
{
if (x > state->xprev)
{
deque_pop_back(state->maxque);
while (!deque_is_empty(state->maxque))
{
if (x <= state->rbuf->array[deque_peek_back(state->maxque)])
break;
deque_pop_back(state->maxque);
}
}
else
{
deque_pop_back(state->minque);
while (!deque_is_empty(state->minque))
{
if (x >= state->rbuf->array[deque_peek_back(state->minque)])
break;
deque_pop_back(state->minque);
}
}
/* store new sample into ring buffer */
tail = state->rbuf->tail;
ringbuf_insert(x, state->rbuf);
head = state->rbuf->head;
deque_push_back(head, state->maxque);
deque_push_back(head, state->minque);
if (state->k == state->n)
{
/*
* window is full - check if oldest window element is a global minimum/maximum
* of current window - if so pop it from U/L queues;
* the check head != tail ensures there is more than 1 element in the
* queue, do not pop if queue has only 1 element, since this element would
* be the newest sample
*/
if (state->maxque->head != state->maxque->tail && tail == deque_peek_front(state->maxque))
deque_pop_front(state->maxque);
else if (state->minque->head != state->minque->tail && tail == deque_peek_front(state->minque))
deque_pop_front(state->minque);
}
}
if (state->k < state->n)
++(state->k);
state->xprev = x;
return GSL_SUCCESS;
}
static int
mmacc_delete(void * vstate)
{
mmacc_state_t * state = (mmacc_state_t *) vstate;
if (state->k > 0)
{
/*
* check if oldest window element is a global minimum/maximum; if so
* pop it from U/L queues
*/
if (state->rbuf->tail == deque_peek_front(state->maxque))
deque_pop_front(state->maxque);
else if (state->rbuf->tail == deque_peek_front(state->minque))
deque_pop_front(state->minque);
/* remove oldest element from ring buffer */
ringbuf_pop_back(state->rbuf);
--(state->k);
}
return GSL_SUCCESS;
}
static int
mmacc_min(void * params, mmacc_type_t * result, const void * vstate)
{
const mmacc_state_t * state = (const mmacc_state_t *) vstate;
(void) params;
if (state->k == 0)
{
GSL_ERROR ("no samples yet added to workspace", GSL_EINVAL);
}
else
{
*result = state->rbuf->array[deque_peek_front(state->minque)];
return GSL_SUCCESS;
}
}
static int
mmacc_max(void * params, mmacc_type_t * result, const void * vstate)
{
const mmacc_state_t * state = (const mmacc_state_t *) vstate;
(void) params;
if (state->k == 0)
{
GSL_ERROR ("no samples yet added to workspace", GSL_EINVAL);
}
else
{
*result = state->rbuf->array[deque_peek_front(state->maxque)];
return GSL_SUCCESS;
}
}
static int
mmacc_minmax(void * params, mmacc_type_t * result, const void * vstate)
{
const mmacc_state_t * state = (const mmacc_state_t *) vstate;
(void) params;
if (state->k == 0)
{
GSL_ERROR ("no samples yet added to workspace", GSL_EINVAL);
}
else
{
result[0] = state->rbuf->array[deque_peek_front(state->minque)];
result[1] = state->rbuf->array[deque_peek_front(state->maxque)];
return GSL_SUCCESS;
}
}
static const gsl_movstat_accum min_accum_type =
{
mmacc_size,
mmacc_init,
mmacc_insert,
mmacc_delete,
mmacc_min
};
const gsl_movstat_accum *gsl_movstat_accum_min = &min_accum_type;
static const gsl_movstat_accum max_accum_type =
{
mmacc_size,
mmacc_init,
mmacc_insert,
mmacc_delete,
mmacc_max
};
const gsl_movstat_accum *gsl_movstat_accum_max = &max_accum_type;
static const gsl_movstat_accum minmax_accum_type =
{
mmacc_size,
mmacc_init,
mmacc_insert,
mmacc_delete,
mmacc_minmax
};
const gsl_movstat_accum *gsl_movstat_accum_minmax = &minmax_accum_type;
| {
"alphanum_fraction": 0.6466115261,
"avg_line_length": 26.964028777,
"ext": "c",
"hexsha": "6a88921530ebb7d601a85a27ea6226434b5d979f",
"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/mmacc.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/mmacc.c",
"max_line_length": 105,
"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/mmacc.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": 2028,
"size": 7496
} |
/*
* bspline.c: Routines for calculating values of B-splines and their
* derivatives, as well as efficient computation of the values of
* N-dimensional B-spline surfaces.
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include "photospline/bspline.h"
/*
* Compute the value of the ith nth-order basis spline of a set
* defined by knots at the point x.
*
* This is implemented using the De Boor algorithm, as outlined on
* Wikipedia.
*/
double
bspline(const double *knots, double x, int i, int n)
{
double result;
if (n == 0) {
/*
* Special case the 0th order case, where B-Splines
* are constant functions from one knot to the next.
*/
if (x >= knots[i] && x < knots[i+1])
return 1.0;
else
return 0.0;
}
result = (x - knots[i])*bspline(knots, x, i, n-1) /
(knots[i+n] - knots[i]);
result += (knots[i+n+1] - x)*bspline(knots, x, i+1, n-1) /
(knots[i+n+1] - knots[i+1]);
return result;
}
/*
* A brain-dead reimplementation of de Boor's BSPLVB, which generates
* the values of the non-zero B-splines at x from the bottom up without
* unnecessarily recalculating terms.
*
* NB: for bsplvb_simple(), bspline_nonzero(), and bspline_deriv_nonzero(),
* `left' must be the index of the nearest fully-supported knot
* span for splines of order n, i.e. n <= left <= nknots-n-2. For bsplvb(),
* `left' must be the index of the nonzero 0-th order spline, i.e.
* knots[left] <= x < knots[left+1].
*
* See Chapter X in:
*
* Carl de Boor. A Practical Guide to Splines, volume 27 of Applied
* Mathematical Sciences. Springer-Verlag, 1978.
*/
void
bsplvb_simple(const double *knots, const unsigned nknots,
double x, int left, int degree, float *restrict biatx)
{
assert(degree>0);
int i, j;
double saved, term;
double delta_l[degree], delta_r[degree];
biatx[0] = 1.0;
/*
* Handle the (rare) cases where x is outside the full
* support of the spline surface.
*/
if (left == degree-1)
while (left >= 0 && x < knots[left])
left--;
else if (left == nknots-degree-1)
while (left < nknots-1 && x > knots[left+1])
left++;
/*
* NB: if left < degree-1 or left > nknots-degree-1,
* the following loop will dereference addresses ouside
* of knots[0:nknots]. While terms involving invalid knot
* indices will be discarded, it is important that `knots'
* have (maxdegree-1)*sizeof(double) bytes of padding
* before and after its valid range to prevent segfaults
* (see parsefitstable()).
*/
for (j = 0; j < degree-1; j++) {
delta_r[j] = knots[left+j+1] - x;
delta_l[j] = x - knots[left-j];
saved = 0.0;
for (i = 0; i < j+1; i++) {
term = biatx[i] / (delta_r[i] + delta_l[j-i]);
biatx[i] = saved + delta_r[i]*term;
saved = delta_l[j-i]*term;
}
biatx[j+1] = saved;
}
/*
* If left < (spline order), only the first (left+1)
* splines are valid; the remainder are utter nonsense.
*/
if ((i = degree-1-left) > 0) {
for (j = 0; j < left+1; j++)
biatx[j] = biatx[j+i]; /* Move valid splines over. */
for ( ; j < degree; j++)
biatx[j] = 0.0; /* The rest are zero by construction. */
} else if ((i = left+degree+1-nknots) > 0) {
for (j = degree-1; j > i-1; j--)
biatx[j] = biatx[j-i];
for ( ; j >= 0; j--)
biatx[j] = 0.0;
}
}
void
bsplvb(const double *knots, const double x, const int left, const int jlow,
const int jhigh, float *restrict biatx,
double *restrict delta_l, double *restrict delta_r)
{
int i, j;
double saved, term;
if (jlow == 0)
biatx[0] = 1.0;
for (j = jlow; j < jhigh-1; j++) {
delta_r[j] = knots[left+j+1] - x;
delta_l[j] = x - knots[left-j];
saved = 0.0;
for (i = 0; i < j+1; i++) {
term = biatx[i] / (delta_r[i] + delta_l[j-i]);
biatx[i] = saved + delta_r[i]*term;
saved = delta_l[j-i]*term;
}
biatx[j+1] = saved;
}
}
void
bspline_deriv_nonzero(const double *knots, const unsigned nknots,
const double x, int left, const int n, float *restrict biatx)
{
/* NB: it might be tempting to use unsigned integers *left* and *n* here,
but indices into the knot vector may be negative (up to -order) before
the first fully-supported knot. */
assert(n>0);
int i, j;
double temp, a;
double delta_l[n], delta_r[n];
/* Special case for constant splines */
if (n == 0)
return;
/*
* Handle the (rare) cases where x is outside the full
* support of the spline surface.
*/
if (left == n)
while (left >= 0 && x < knots[left])
left--;
else if (left == nknots-n-2)
while (left < nknots-1 && x > knots[left+1])
left++;
/* Get the non-zero n-1th order B-splines at x */
bsplvb(knots, x, left, 0 /* jlow */, n /* jhigh */,
biatx, delta_l, delta_r);
/*
* Now, form the derivatives of the nth order B-splines from
* linear combinations of the lower-order splines.
*/
/*
* On the last supported segment of the ith nth order spline,
* only the i+1th n-1th order spline is nonzero.
*/
temp = biatx[0];
biatx[0] = - n*temp / ((knots[left+1] - knots[left+1-n]));
/* On the middle segments, both the ith and i+1th splines contribute. */
for (i = 1; i < n; i++) {
a = n*temp/((knots[left+i] - knots[left+i-n]));
temp = biatx[i];
biatx[i] = a - n*temp/(knots[left+i+1] - knots[left+i+1-n]);
}
/*
* On the first supported segment of the i+nth nth order spline,
* only the ith n-1th order spline is nonzero.
*/
biatx[n] = n*temp/((knots[left+n] - knots[left]));
/* Rearrange for partially-supported points. */
if ((i = n-left) > 0) {
for (j = 0; j < left+1; j++)
biatx[j] = biatx[j+i]; /* Move valid splines over. */
for ( ; j < n+1; j++)
biatx[j] = 0.0; /* The rest are zero by construction. */
} else if ((i = left+n+2-nknots) > 0) {
for (j = n; j > i-1; j--)
biatx[j] = biatx[j-i];
for ( ; j >= 0; j--)
biatx[j] = 0.0;
}
}
double
bspline_deriv(const double *knots, double x, int i, int n, unsigned order)
{
double result;
if (n == 0) {
/*
* Special case the 0th order case, where B-Splines
* are constant functions from one knot to the next.
*/
return 0.0;
}
if (order <= 1) {
result = n * bspline(knots, x, i, n-1) / (knots[i+n] - knots[i]);
result -= n * bspline(knots, x, i+1, n-1) / (knots[i+n+1] - knots[i+1]);
} else {
result = n * bspline_deriv(knots, x, i, n-1, order-1) / (knots[i+n] - knots[i]);
result -= n * bspline_deriv(knots, x, i+1, n-1, order-1) / (knots[i+n+1] - knots[i+1]);
}
return result;
}
double
bspline_deriv_2(const double *knots, double x, int i, int n)
{
double result;
if (n <= 1) {
/*
* Special case the 1st order case, where B-Splines
* are linear functions from one knot to the next.
*/
return 0.0;
}
result = bspline(knots, x, i, n-2) /
((knots[i+n] - knots[i])*(knots[i+n-1] - knots[i]));
result -= bspline(knots, x, i+1, n-2) *
(1./(knots[i+n] - knots[i]) + 1./(knots[i+n+1] - knots[i+1])) /
(knots[i+n] - knots[i+1]);
result += bspline(knots, x, i+2, n-2) /
((knots[i+n+1] - knots[i+1])*(knots[i+n+1] - knots[i+2]));
result *= n*(n-1);
return result;
}
/*
* Evaluates the results of a full spline basis given a set of knots,
* a position, an order, and a central spline for the position (or -1).
* The central spline should be the index of the 0th order basis spline
* that is non-zero at the position x.
*/
double
splineeval(const double *knots, const double *weights, int nknots, double x, int order,
int center)
{
double work = 0.0;
int i;
if (center < 0) {
/* XXX: should be a binary search */
for (center = 0; center+1 < nknots; center++) {
if (x > knots[center] && x < knots[center+1])
break;
}
if (center+1 >= nknots)
return 0.0;
}
i = center - order;
if (i < 0)
i = 0;
while (i < nknots-order-1 && i <= center) {
work += weights[i]*bspline(knots, x, i, order);
i++;
}
return work;
}
int
tablesearchcenters(const struct splinetable *table, const double *x, int *centers)
{
int i, min, max;
for (i = 0; i < table->ndim; i++) {
/* Ensure we are actually inside the table. */
if (x[i] <= table->knots[i][0] ||
x[i] > table->knots[i][table->nknots[i]-1])
return (-1);
/*
* If we're only a few knots in, take the center to be
* the nearest fully-supported knot.
*/
if (x[i] < table->knots[i][table->order[i]]) {
centers[i] = table->order[i];
continue;
} else if (x[i] >= table->knots[i][table->naxes[i]]) {
centers[i] = table->naxes[i]-1;
continue;
}
min = table->order[i];
max = table->nknots[i]-2;
do {
centers[i] = (max+min)/2;
if (x[i] < table->knots[i][centers[i]])
max = centers[i]-1;
else
min = centers[i]+1;
} while (x[i] < table->knots[i][centers[i]] ||
x[i] >= table->knots[i][centers[i]+1]);
/*
* B-splines are defined on a half-open interval. For the
* last point of the interval, move center one point to the
* left to get the limit of the sum without evaluating
* absent basis functions.
*/
if (centers[i] == table->naxes[i])
centers[i]--;
}
return (0);
}
static int
maxorder(int *order, int ndim)
{
int i, max = 0;
for (i = 0; i < ndim; i++)
if (order[i] > max)
max = order[i];
return (max);
}
/*
* The N-Dimensional tensor product basis version of splineeval.
* Evaluates the results of a full spline basis given a set of knots,
* a position, an order, and a central spline for the position (or -1).
* The central spline should be the index of the 0th order basis spline
* that is non-zero at the position x.
*
* x is the vector at which we will evaluate the space
*/
static double
ndsplineeval_core(const struct splinetable *table, const int *centers, int maxdegree,
float localbasis[table->ndim][maxdegree])
{
assert(table->ndim>0);
int i, j, n, tablepos;
float result;
float basis_tree[table->ndim+1];
int nchunks;
int decomposedposition[table->ndim];
tablepos = 0;
for (n = 0; n < table->ndim; n++) {
decomposedposition[n] = 0;
tablepos += (centers[n] - table->order[n])*table->strides[n];
}
basis_tree[0] = 1;
for (n = 0; n < table->ndim; n++)
basis_tree[n+1] = basis_tree[n]*localbasis[n][0];
nchunks = 1;
for (n = 0; n < table->ndim - 1; n++)
nchunks *= (table->order[n] + 1);
result = 0;
n = 0;
while (1) {
for (i = 0; __builtin_expect(i < table->order[table->ndim-1] +
1, 1); i++) {
result += basis_tree[table->ndim-1]*
localbasis[table->ndim-1][i]*
table->coefficients[tablepos + i];
}
if (__builtin_expect(++n == nchunks, 0))
break;
tablepos += table->strides[table->ndim-2];
decomposedposition[table->ndim-2]++;
/* Carry to higher dimensions */
for (i = table->ndim-2;
decomposedposition[i] > table->order[i]; i--) {
decomposedposition[i-1]++;
tablepos += (table->strides[i-1]
- decomposedposition[i]*table->strides[i]);
decomposedposition[i] = 0;
}
for (j = i; __builtin_expect(j < table->ndim-1, 1); j++)
basis_tree[j+1] = basis_tree[j]*
localbasis[j][decomposedposition[j]];
}
return result;
}
/* This function returns bspline coefficients along a given dimension, fixing the values+coefficients for the
other dimensions. Used to obtain a 1-d spline representation that can be easily further convolved. */
void
ndsplineeval_slice_coeffs(const struct splinetable *table, const double *x, const int *centers, double *results,int slice_dimension, int derivative, int area_norm )
{
assert(table->ndim>0);
int n;
int maxdegree = maxorder(table->order, table->ndim) + 1;
float localbasis[table->ndim][maxdegree];
if(slice_dimension==table->ndim-1)
{
printf("ERROR!!! slice dimension cannot be ndim-1 in this implementation!");
}
for (n = 0; n < table->ndim; n++) {
bsplvb_simple(table->knots[n], table->nknots[n],
x[n], centers[n], table->order[n] + 1,
localbasis[n]);
}
int i, j, tablepos, slice_dimension_stride, num_coeffs;
//double result;
num_coeffs=table->nknots[slice_dimension]-table->order[slice_dimension]-1;
memset(results, 0, sizeof(double)*num_coeffs);
// temp_result is stored to teomporarily store coefficients for derivative calculation
double temp_result[num_coeffs];
float basis_tree[table->ndim+1]; // the last basis_tree dimension is unused ..
int nchunks;
int decomposedposition[table->ndim];
//int derivative_correction[table->ndim];
nchunks = 1;
for (n = 0; n < table->ndim - 1; n++)
{
//derivative_correction[n]=0;
if(n==slice_dimension)
{
continue;
}
nchunks *= (table->order[n] + 1);
}
// initialize overall table position
tablepos = 0;
for (n = 0; n < table->ndim; n++) {
decomposedposition[n]=0;
if(n!=slice_dimension)
{
tablepos += (centers[n] - table->order[n])*table->strides[n];
}
else
{
slice_dimension_stride=table->strides[n];
}
}
// initialize local basis
basis_tree[0] = 1;
for (n = 0; n < table->ndim; n++)
{
if(n==slice_dimension)
{
basis_tree[n+1] = basis_tree[n];
continue;
}
basis_tree[n+1] = basis_tree[n]*localbasis[n][0];
}
double temp_base_eval=0.0;
n=0;
while (1) {
for (i = 0; __builtin_expect(i < table->order[table->ndim-1] +
1, 1); i++) {
// in contrast to ndsplineeval_core, save a value for each coefficient, separated by the slice dimension stride
temp_base_eval=basis_tree[table->ndim-1]*localbasis[table->ndim-1][i];
for(int nc=0; __builtin_expect(nc<num_coeffs,1) ;nc++)
{
results[nc] += temp_base_eval*table->coefficients[tablepos + i + nc*slice_dimension_stride];
}
}
if (__builtin_expect(++n == nchunks, 0))
break;
// special case when the slicing dimension is ndim-2 .. skip over this dimension immediately by pushing tablepos forward by (order+1)*strides
if(slice_dimension==table->ndim-2)
{
tablepos += table->strides[table->ndim-2]*(table->order[table->ndim-2]+1);
decomposedposition[table->ndim-2]+=(table->order[table->ndim-2]+1);
}
else
{
// otherwise just add one stride
tablepos += table->strides[table->ndim-2];
decomposedposition[table->ndim-2]++;
}
// Carry to higher dimensions
for (i = table->ndim-2;
decomposedposition[i] > table->order[i]; i--) {
if(i==slice_dimension+1)
{
//printf("i=slicedimsino +1 .. \n");
decomposedposition[i-2]++;
tablepos += (table->strides[i-2]
- decomposedposition[i]*table->strides[i]);
decomposedposition[i] = 0;
// add one extra -1, since we want to skip the slicing dimension
i=i-1;
}
else
{
decomposedposition[i-1]++;
tablepos += (table->strides[i-1]
- decomposedposition[i]*table->strides[i]);
decomposedposition[i] = 0;
}
}
// stacks the tree basis up .. never include the dimension of interest, ie.e the slice dimension
for (j = i; __builtin_expect(j < table->ndim-1, 1); j++)
{
//printf("last loop index .. %d\n", j);
if(j==slice_dimension)
{
basis_tree[j+1] = basis_tree[j];
}
else
{
basis_tree[j+1] = basis_tree[j]*
localbasis[j][decomposedposition[j]];
}
}
}
for(int nc=0; __builtin_expect(nc<num_coeffs,1) ;nc++)
{
if(derivative>0)
{
double y_diff;
double x_diff;
int deriv_order=table->order[slice_dimension];
if(nc==0)
{
// first one is special
y_diff=deriv_order*results[0];
}
else
{
// first form derivatives
// requires two coefficient results usually ... so only start once we know >=2 coefficients
// since table->order is really the degree, the new derivative order is just the degree of the original spline
y_diff=deriv_order*(results[nc]-results[nc-1]);
}
x_diff=table->knots[slice_dimension][deriv_order+nc]-table->knots[slice_dimension][nc];
temp_result[nc]=y_diff/((double)x_diff);
if(area_norm)
{
double norm_factor= ((double)deriv_order)/( table->knots[slice_dimension][deriv_order+nc] - table->knots[slice_dimension][nc]);
temp_result[nc]/=norm_factor;
}
// check again for area normalization
}
else
{
if(area_norm)
{
int real_order=table->order[slice_dimension]+1;
double norm_factor= ((double)(real_order))/ ( table->knots[slice_dimension][real_order+nc] - table->knots[slice_dimension][nc]);
results[nc]/=norm_factor;
}
//printf("SLICE: abs res: %d %.10f\n", nc, results[nc]);
}
}
// calculated the derivate .. copy temp_result into result
if(derivative>0)
{
memcpy(results, temp_result, sizeof(temp_result));
}
}
double
ndsplineeval(const struct splinetable *table, const double *x, const int *centers,
int derivatives)
{
assert(table->ndim>0);
int n;
int maxdegree = maxorder(table->order, table->ndim) + 1;
float localbasis[table->ndim][maxdegree];
for (n = 0; n < table->ndim; n++) {
if (derivatives & (1 << n)) {
bspline_deriv_nonzero(table->knots[n],
table->nknots[n], x[n], centers[n],
table->order[n], localbasis[n]);
} else {
bsplvb_simple(table->knots[n], table->nknots[n],
x[n], centers[n], table->order[n] + 1,
localbasis[n]);
}
}
return ndsplineeval_core(table, centers, maxdegree, localbasis);
}
double
ndsplineeval_deriv(const struct splinetable *table, const double *x,
const int *centers, const unsigned *derivatives)
{
assert(table->ndim>0);
int i, n;
int maxdegree = maxorder(table->order, table->ndim) + 1;
float localbasis[table->ndim][maxdegree];
for (n = 0; n < table->ndim; n++) {
if (derivatives == NULL || derivatives[n] == 0) {
bsplvb_simple(table->knots[n], table->nknots[n],
x[n], centers[n], table->order[n] + 1,
localbasis[n]);
} else if (derivatives[n] == 1) {
bspline_deriv_nonzero(table->knots[n],
table->nknots[n], x[n], centers[n],
table->order[n], localbasis[n]);
} else {
for (i = 0; i <= table->order[n]; i++)
localbasis[n][i] = bspline_deriv(
table->knots[n], x[n],
centers[n] - table->order[n] + i,
table->order[n], derivatives[n]);
}
}
return ndsplineeval_core(table, centers, maxdegree, localbasis);
}
double
ndsplineeval_linalg(const struct splinetable *table, const double *x,
const int *centers, int derivatives)
{
assert(table->ndim>0);
int totalcoeff, n;
int coeffstrides[table->ndim];
gsl_matrix_float *basis1, *basis2, *basis_elem;
assert(table->ndim > 0);
coeffstrides[table->ndim - 1] = totalcoeff = 1;
for (n = table->ndim-1; n >= 0; n--) {
totalcoeff *= (table->order[n] + 1);
if (n > 0)
coeffstrides[n-1] = totalcoeff;
}
float basis1_data[totalcoeff], basis2_data[totalcoeff],
elem_data[maxorder(table->order, table->ndim) + 1];
gsl_matrix_float b1, b2, be;
basis1 = &b1; basis2 = &b2; basis_elem = &be;
basis1->data = basis1_data;
basis2->data = basis2_data;
basis_elem->data = elem_data;
/*
* Form outer product basis1 = basis2 x basis_elem, filling basis_elem
* every time with the non-zero basis functions on each axis and
* swapping basis1 and basis2 via tmp_basis.
*/
basis2->size1 = 1;
basis2->size2 = 1;
basis2->data[0] = 1.0;
for (n = table->ndim-1; n >= 0; n--) {
gsl_matrix_float *tmp_basis;
if (derivatives & (1 << n)) {
bspline_deriv_nonzero(table->knots[n],
table->nknots[n], x[n], centers[n],
table->order[n], basis_elem->data);
} else {
bsplvb_simple(table->knots[n], table->nknots[n],
x[n], centers[n], table->order[n] + 1,
basis_elem->data);
}
basis_elem->size1 = table->order[n] + 1;
basis_elem->size2 = 1;
basis1->size2 = basis2->size2;
basis1->size1 = basis_elem->size1;
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
basis1->size1, basis1->size2, basis_elem->size2, 1.0,
basis_elem->data, 1, basis2->data, basis2->size2, 0,
basis1->data, basis1->size2);
basis1->size2 = basis1->size1 * basis1->size2;
basis1->size1 = 1;
tmp_basis = basis1;
basis1 = basis2;
basis2 = tmp_basis;
}
/* Now basis1 is free, so fill it with the spline coefficients */
int i, tablepos;
int decomposedposition[table->ndim];
tablepos = 0;
for (n = 0; n < table->ndim; n++) {
decomposedposition[n] = 0;
tablepos += (centers[n] - table->order[n])*table->strides[n];
}
for (i = 0; i < table->order[table->ndim-1] + 1; i++)
basis1->data[i] = table->coefficients[tablepos + i];
for (n = 1; n < coeffstrides[0] /* number of chunks */; n++) {
tablepos += table->strides[table->ndim-2];
decomposedposition[table->ndim-2]++;
/* Carry to higher dimensions */
for (i = table->ndim-2; __builtin_expect(i > 0 &&
decomposedposition[i] > table->order[i], 0); i--) {
decomposedposition[i-1]++;
tablepos += (table->strides[i-1]
- decomposedposition[i]*table->strides[i]);
decomposedposition[i] = 0;
}
for (i = 0; i < table->order[table->ndim-1] + 1; i++)
basis1->data[n*(table->order[table->ndim-1] + 1) + i] =
table->coefficients[tablepos + i];
}
/* Take the dot product */
__builtin_prefetch(basis1->data);
__builtin_prefetch(basis2->data);
return cblas_sdot(totalcoeff, basis1->data, 1, basis2->data, 1);
}
| {
"alphanum_fraction": 0.62282925,
"avg_line_length": 25.794188862,
"ext": "c",
"hexsha": "97272fd19515174a250d489cf223703c9d836d5f",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z",
"max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "hschwane/offline_production",
"max_forks_repo_path": "photospline/private/lib/bspline.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e",
"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": "hschwane/offline_production",
"max_issues_repo_path": "photospline/private/lib/bspline.c",
"max_line_length": 164,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "hschwane/offline_production",
"max_stars_repo_path": "photospline/private/lib/bspline.c",
"max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z",
"num_tokens": 7025,
"size": 21306
} |
/*
* aeif_cond_beta_multisynapse.h
*
* This file is part of NEST.
*
* Copyright (C) 2004 The NEST Initiative
*
* NEST 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.
*
* NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef AEIF_COND_BETA_MULTISYNAPSE_H
#define AEIF_COND_BETA_MULTISYNAPSE_H
// Generated includes:
#include "config.h"
#ifdef HAVE_GSL
// External includes:
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv.h>
// Includes from nestkernel:
#include "archiving_node.h"
#include "connection.h"
#include "event.h"
#include "nest_types.h"
#include "ring_buffer.h"
#include "universal_data_logger.h"
/* BeginDocumentation
Name: aeif_cond_beta_multisynapse - Conductance based adaptive exponential
integrate-and-fire neuron model according
to Brette and Gerstner (2005) with
multiple synaptic rise time and decay
time constants, and synaptic conductance
modeled by a beta function.
Description:
aeif_cond_beta_multisynapse is a conductance-based adaptive exponential
integrate-and-fire neuron model. It allows an arbitrary number of synaptic
rise time and decay time constants. Synaptic conductance is modeled by a
beta function, as described by A. Roth and M.C.W. van Rossum
in Computational Modeling Methods for Neuroscientists, MIT Press 2013,
Chapter 6.
The time constants are supplied by two arrays, "tau_rise" and "tau_decay" for
the synaptic rise time and decay time, respectively. The synaptic
reversal potentials are supplied by the array "E_rev". The port numbers
are automatically assigned in the range from 1 to n_receptors.
During connection, the ports are selected with the property "receptor_type".
The membrane potential is given by the following differential equation:
C dV/dt = -g_L(V-E_L) + g_L*Delta_T*exp((V-V_T)/Delta_T) + I_syn_tot(V, t)
- w + I_e
where:
I_syn_tot(V,t) = \sum_i g_i(t) (V - E_{rev,i}) ,
the synapse i is excitatory or inhibitory depending on the value of E_{rev,i}
and the differential equation for the spike-adaptation current w is:
tau_w * dw/dt = a(V - E_L) - w
When the neuron fires a spike, the adaptation current w <- w + b.
Parameters:
The following parameters can be set in the status dictionary.
Dynamic state variables:
V_m double - Membrane potential in mV
w double - Spike-adaptation current in pA.
Membrane Parameters:
C_m double - Capacity of the membrane in pF
t_ref double - Duration of refractory period in ms.
V_reset double - Reset value for V_m after a spike. In mV.
E_L double - Leak reversal potential in mV.
g_L double - Leak conductance in nS.
I_e double - Constant external input current in pA.
Delta_T double - Slope factor in mV
V_th double - Spike initiation threshold in mV
V_peak double - Spike detection threshold in mV.
Adaptation parameters:
a double - Subthreshold adaptation in nS.
b double - Spike-triggered adaptation in pA.
tau_w double - Adaptation time constant in ms
Synaptic parameters
E_rev double vector - Reversal potential in mV.
tau_rise double vector - Rise time of synaptic conductance in ms (beta
function).
tau_decay double vector - Decay time of synaptic conductance in ms (beta
function).
Integration parameters
gsl_error_tol double - This parameter controls the admissible error of the
GSL integrator. Reduce it if NEST complains about
numerical instabilities.
Examples:
import nest
import numpy as np
neuron = nest.Create('aeif_cond_beta_multisynapse')
nest.SetStatus(neuron, {"V_peak": 0.0, "a": 4.0, "b":80.5})
nest.SetStatus(neuron, {'E_rev':[0.0,0.0,0.0,-85.0],
'tau_decay':[50.0,20.0,20.0,20.0],
'tau_rise':[10.0,10.0,1.0,1.0]})
spike = nest.Create('spike_generator', params = {'spike_times':
np.array([10.0])})
voltmeter = nest.Create('voltmeter', 1, {'withgid': True})
delays=[1.0, 300.0, 500.0, 700.0]
w=[1.0, 1.0, 1.0, 1.0]
for syn in range(4):
nest.Connect(spike, neuron, syn_spec={'model': 'static_synapse',
'receptor_type': 1 + syn,
'weight': w[syn],
'delay': delays[syn]})
nest.Connect(voltmeter, neuron)
nest.Simulate(1000.0)
dmm = nest.GetStatus(voltmeter)[0]
Vms = dmm["events"]["V_m"]
ts = dmm["events"]["times"]
import pylab
pylab.figure(2)
pylab.plot(ts, Vms)
pylab.show()
Sends: SpikeEvent
Receives: SpikeEvent, CurrentEvent, DataLoggingRequest
author: Bruno Golosio 07/10/2016
SeeAlso: aeif_cond_alpha_multisynapse
*/
namespace nest
{
/**
* Function computing right-hand side of ODE for GSL solver.
* @note Must be declared here so we can befriend it in class.
* @note Must have C-linkage for passing to GSL. Internally, it is
* a first-class C++ function, but cannot be a member function
* because of the C-linkage.
* @note No point in declaring it inline, since it is called
* through a function pointer.
* @param void* Pointer to model neuron instance.
*/
extern "C" int
aeif_cond_beta_multisynapse_dynamics( double, const double*, double*, void* );
/**
* Conductance based exponential integrate-and-fire neuron model according to
* Brette and Gerstner
* (2005) with multiple ports.
*/
class aeif_cond_beta_multisynapse : public Archiving_Node
{
public:
aeif_cond_beta_multisynapse();
aeif_cond_beta_multisynapse( const aeif_cond_beta_multisynapse& );
virtual ~aeif_cond_beta_multisynapse();
friend int
aeif_cond_beta_multisynapse_dynamics( double, const double*, double*, void* );
/**
* Import sets of overloaded virtual functions.
* @see Technical Issues / Virtual Functions: Overriding, Overloading, and
* Hiding
*/
using Node::handle;
using Node::handles_test_event;
port send_test_event( Node&, rport, synindex, bool );
void handle( SpikeEvent& );
void handle( CurrentEvent& );
void handle( DataLoggingRequest& );
port handles_test_event( SpikeEvent&, rport );
port handles_test_event( CurrentEvent&, rport );
port handles_test_event( DataLoggingRequest&, rport );
void get_status( DictionaryDatum& ) const;
void set_status( const DictionaryDatum& );
private:
void init_state_( const Node& proto );
void init_buffers_();
void calibrate();
void update( Time const&, const long, const long );
// The next two classes need to be friends to access the State_ class/member
friend class RecordablesMap< aeif_cond_beta_multisynapse >;
friend class UniversalDataLogger< aeif_cond_beta_multisynapse >;
// ----------------------------------------------------------------
/**
* Independent parameters of the model.
*/
struct Parameters_
{
double V_peak_; //!< Spike detection threshold in mV
double V_reset_; //!< Reset Potential in mV
double t_ref_; //!< Refractory period in ms
double g_L; //!< Leak Conductance in nS
double C_m; //!< Membrane Capacitance in pF
double E_L; //!< Leak reversal Potential (aka resting potential) in mV
double Delta_T; //!< Slope faktor in ms.
double tau_w; //!< adaptation time-constant in ms.
double a; //!< Subthreshold adaptation in nS.
double b; //!< Spike-triggered adaptation in pA
double V_th; //!< Spike threshold in mV.
std::vector< double > tau_rise; //!< Rise time of synaptic conductance
//!< in ms.
std::vector< double > tau_decay; //!< Decay time of synaptic conductance
//!< in ms.
std::vector< double > E_rev; //!< reversal potentials in mV
double I_e; //!< Intrinsic current in pA.
double gsl_error_tol; //!< error bound for GSL integrator
// boolean flag which indicates whether the neuron has connections
bool has_connections_;
Parameters_(); //!< Sets default parameter values
void get( DictionaryDatum& ) const; //!< Store current values in dictionary
void set( const DictionaryDatum& ); //!< Set values from dictionary
//! Return the number of receptor ports
inline size_t
n_receptors() const
{
return E_rev.size();
}
};
// ----------------------------------------------------------------
/**
* State variables of the model.
* @note Copy constructor and assignment operator required because
* of C-style arrays.
*/
struct State_
{
/**
* Enumeration identifying elements in state vector State_::y_.
* This enum identifies the elements of the vector. It must be public to be
* accessible from the iteration function. The last two elements of this
* enum (DG, G) will be repeated
* n times at the end of the state vector State_::y with n being the number
* of synapses.
*/
enum StateVecElems
{
V_M = 0,
W, // 1
DG, // 2
G, // 3
STATE_VECTOR_MIN_SIZE
};
static const size_t NUMBER_OF_FIXED_STATES_ELEMENTS = 2; // V_M, W
static const size_t NUMBER_OF_STATES_ELEMENTS_PER_RECEPTOR = 2; // DG, G
std::vector< double > y_; //!< neuron state
int r_; //!< number of refractory steps remaining
State_( const Parameters_& ); //!< Default initialization
State_( const State_& );
State_& operator=( const State_& );
void get( DictionaryDatum& ) const;
void set( const DictionaryDatum& );
}; // State_
// ----------------------------------------------------------------
/**
* Buffers of the model.
*/
struct Buffers_
{
Buffers_( aeif_cond_beta_multisynapse& );
Buffers_( const Buffers_&, aeif_cond_beta_multisynapse& );
//! Logger for all analog data
UniversalDataLogger< aeif_cond_beta_multisynapse > logger_;
/** buffers and sums up incoming spikes/currents */
std::vector< RingBuffer > spikes_;
RingBuffer currents_;
/** GSL ODE stuff */
gsl_odeiv_step* s_; //!< stepping function
gsl_odeiv_control* c_; //!< adaptive stepsize control function
gsl_odeiv_evolve* e_; //!< evolution function
gsl_odeiv_system sys_; //!< struct describing system
// IntergrationStep_ should be reset with the neuron on ResetNetwork,
// but remain unchanged during calibration. Since it is initialized with
// step_, and the resolution cannot change after nodes have been created,
// it is safe to place both here.
double step_; //!< simulation step size in ms
double IntegrationStep_; //!< current integration time step,
//!< updated by solver
/**
* Input current injected by CurrentEvent.
* This variable is used to transport the current applied into the
* _dynamics function computing the derivative of the state vector.
* It must be a part of Buffers_, since it is initialized once before
* the first simulation, but not modified before later Simulate calls.
*/
double I_stim_;
};
// ----------------------------------------------------------------
/**
* Internal variables of the model.
*/
struct Variables_
{
/** initial value to normalise synaptic conductance */
std::vector< double > g0_;
/**
* Threshold detection for spike events: P.V_peak if Delta_T > 0.,
* P.V_th if Delta_T == 0.
*/
double V_peak;
unsigned int refractory_counts_;
};
// Access functions for UniversalDataLogger -------------------------------
//! Read out state vector elements, used by UniversalDataLogger
template < State_::StateVecElems elem >
double
get_y_elem_() const
{
return S_.y_[ elem ];
}
// Data members -----------------------------------------------------------
/**
* @defgroup aeif_cond_beta_multisynapse
* Instances of private data structures for the different types
* of data pertaining to the model.
* @note The order of definitions is important for speed.
* @{
*/
Parameters_ P_;
State_ S_;
Variables_ V_;
Buffers_ B_;
/** @} */
//! Mapping of recordables names to access functions
static RecordablesMap< aeif_cond_beta_multisynapse > recordablesMap_;
};
inline port
aeif_cond_beta_multisynapse::send_test_event( Node& target,
rport receptor_type,
synindex,
bool )
{
SpikeEvent e;
e.set_sender( *this );
return target.handles_test_event( e, receptor_type );
}
inline port
aeif_cond_beta_multisynapse::handles_test_event( CurrentEvent&,
rport receptor_type )
{
if ( receptor_type != 0 )
{
throw UnknownReceptorType( receptor_type, get_name() );
}
return 0;
}
inline port
aeif_cond_beta_multisynapse::handles_test_event( DataLoggingRequest& dlr,
rport receptor_type )
{
if ( receptor_type != 0 )
{
throw UnknownReceptorType( receptor_type, get_name() );
}
return B_.logger_.connect_logging_device( dlr, recordablesMap_ );
}
inline void
aeif_cond_beta_multisynapse::get_status( DictionaryDatum& d ) const
{
P_.get( d );
S_.get( d );
Archiving_Node::get_status( d );
( *d )[ names::recordables ] = recordablesMap_.get_list();
}
inline void
aeif_cond_beta_multisynapse::set_status( const DictionaryDatum& d )
{
Parameters_ ptmp = P_; // temporary copy in case of errors
ptmp.set( d ); // throws if BadProperty
State_ stmp = S_; // temporary copy in case of errors
stmp.set( d ); // throws if BadProperty
// We now know that (ptmp, stmp) are consistent. We do not
// write them back to (P_, S_) before we are also sure that
// the properties to be set in the parent class are internally
// consistent.
Archiving_Node::set_status( d );
// if we get here, temporaries contain consistent set of properties
P_ = ptmp;
S_ = stmp;
}
} // namespace
#endif // HAVE_GSL
#endif // AEIF_COND_BETA_MULTISYNAPSE_H //
| {
"alphanum_fraction": 0.6533125804,
"avg_line_length": 31.7103004292,
"ext": "h",
"hexsha": "d3d5b7876f1bfeb7e640442658962eb450a45499",
"lang": "C",
"max_forks_count": 10,
"max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z",
"max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster",
"max_forks_repo_path": "NEST-14.0-FPGA/models/aeif_cond_beta_multisynapse.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster",
"max_issues_repo_path": "NEST-14.0-FPGA/models/aeif_cond_beta_multisynapse.h",
"max_line_length": 80,
"max_stars_count": 45,
"max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster",
"max_stars_repo_path": "NEST-14.0-FPGA/models/aeif_cond_beta_multisynapse.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z",
"num_tokens": 3606,
"size": 14777
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** This file forms part of the Underworld geophysics modelling application. **
** **
** For full license and copyright information, please refer to the LICENSE.md file **
** located at the project root, or contact the authors. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#include <petsc.h>
#include <petscvec.h>
#include <petscmat.h>
#include "common-driver-utils.h"
// Calculate {r} = {F} - [K]{u} - [G]{p}
// Calculate || {r} ||_2
double BSSCR_StokesMomentumResidual( Mat K, Mat G, Vec F, Vec u, Vec p )
{
Vec uStar;
// PetscReal negOne = -1.0;
PetscReal f_norm;
PetscReal r1_norm;
VecNorm( F, NORM_2, &f_norm ); // u_norm = || {uStar} ||_2
VecDuplicate( u, &uStar );
MatMult( K, u, uStar ); // {uStar} = [K]{u}
MatMultAdd( G, p, uStar, uStar ); // {uStar} = {uStar} + [G]{p}
VecAYPX( uStar, -1.0, F ); // {uStar} = {F} - {uStar}
VecNorm( uStar, NORM_2, &r1_norm ); // r_norm = || {uStar} ||_2
Stg_VecDestroy(&uStar );
/*
printf("%s \n", __func__ );
printf("\t||f - Ku - Gp|| = %g \n", r1_norm );
printf("\t||f - Ku - Gp||/||f|| = %g \n", r1_norm/f_norm );
*/
// return ( (double)(r1_norm/f_norm) );
return ( (double)(r1_norm) );
}
// Calculate {r} = {H} - [G]^T{u} - [C]{p}
// Calculate || {r} ||_2
double BSSCR_StokesContinuityResidual( Mat G, Mat C, Vec H, Vec u, Vec p )
{
Vec pStar;
// PetscReal negOne = -1.0;
PetscReal r2_norm;
PetscReal u_norm;
VecNorm( u, NORM_2, &u_norm ); // u_norm = || {uStar} ||_2
VecDuplicate( H, &pStar );
MatMultTranspose( G, u, pStar ); // {pStar} = [G]^T{u}
if( C != PETSC_NULL ) {
MatMultAdd( C, p, pStar, pStar ); /* {pStar} = {pStar} + [C] {p} */
}
VecAYPX( pStar, -1.0, H ); // {pStar} = {H} - {pStar}
VecNorm( pStar, NORM_2, &r2_norm ); // norm = || {pStar} ||_2
Stg_VecDestroy(&pStar );
/*
printf("%s \n", __func__ );
printf("\t||h - Du|| = %g \n", r2_norm );
printf("\t||h - Du||/||u|| = %g \n", r2_norm/u_norm );
*/
// return ( (double)(r2_norm/u_norm) );
return ( (double)(r2_norm) );
}
| {
"alphanum_fraction": 0.4162062615,
"avg_line_length": 36.2,
"ext": "c",
"hexsha": "cc8cbe87b5240eda6db351e1885ba39059b395cb",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z",
"max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "longgangfan/underworld2",
"max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_residual.c",
"max_issues_count": 561,
"max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "longgangfan/underworld2",
"max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_residual.c",
"max_line_length": 87,
"max_stars_count": 116,
"max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "longgangfan/underworld2",
"max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/stokes_residual.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z",
"num_tokens": 956,
"size": 2715
} |
#pragma once
#define EXPORT __declspec(dllexport)
#define WIN32_LEAN_AND_MEAN
// STL
#include <array>
#include <cassert>
#include <cstdint>
#include <deque>
#include <exception>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
// Windows
#include <Windows.h>
#include <VersionHelpers.h>
#include <WTypes.h>
// DirectX 11
#include <d3d11_1.h>
#include "d3d8types.h"
#include <d3dcompiler.h>
#include <DirectXMath.h>
// GSL
#include <gsl/span>
// DirectXTK
#include <wrl/client.h>
#include <SimpleMath.h>
// Local
#include "cbuffers.h"
#include "CBufferWriter.h"
#include "d3d8to11.hpp"
#include "d3d8to11_base.h"
#include "d3d8to11_device.h"
#include "d3d8to11_index_buffer.h"
#include "d3d8to11_resource.h"
#include "d3d8to11_surface.h"
#include "d3d8to11_texture.h"
#include "d3d8to11_vertex_buffer.h"
#include "d3d8types.hpp"
#include "defs.h"
#include <dirty_t.h>
#include "hash_combine.h"
#include "int_multiple.h"
#include "Light.h"
#include "Material.h"
#include "Shader.h"
#include "simple_math.h"
#include "SimpleMath.h"
#include "typedefs.h"
#include "Unknown.h"
#include "dynarray.h"
| {
"alphanum_fraction": 0.7442996743,
"avg_line_length": 18.8923076923,
"ext": "h",
"hexsha": "45bf20948ad3455872f478c06c69389d1054b8b4",
"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": "f830e567e020305d30fc2ad3751e2b367382a09f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "basecq/d3d8to11",
"max_forks_repo_path": "d3d8to11/stdafx.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f830e567e020305d30fc2ad3751e2b367382a09f",
"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": "basecq/d3d8to11",
"max_issues_repo_path": "d3d8to11/stdafx.h",
"max_line_length": 36,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f830e567e020305d30fc2ad3751e2b367382a09f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "basecq/d3d8to11",
"max_stars_repo_path": "d3d8to11/stdafx.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 345,
"size": 1228
} |
#pragma once
#include "common.h"
#include <string>
#include <vector>
#include <array>
#include <map>
#include <gsl\gsl>
#include <type_traits>
namespace multiformats {
enum base_t {
dynamic_base = -1,
identity = 0,
base256,
//base1, // '1'
base2, // '01'
base8, // '01234567'
base10, // '0123456789'
base16, // '0123456789abcdef'
BASE16, // '0123456789ABCDEF'
base32, // 'abcdefghijklmnopqrstuvwxyz234567' - rfc4648 no padding
BASE32, // 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' - rfc4648 no padding
base32pad, // 'abcdefghijklmnopqrstuvwxyz234567=' - rfc4648 with padding
BASE32pad, // 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=' - rfc4648 with padding
base32hex, // '0123456789abcdefghijklmnopqrstuv' - rfc4648 no padding - highest char
BASE32hex, // '0123456789ABCDEFGHIJKLMNOPQRSTUV' - rfc4648 no padding - highest char
base32hexpad, // '0123456789abcdefghijklmnopqrstuv=' - rfc4648 with padding
BASE32hexpad, // '0123456789ABCDEFGHIJKLMNOPQRSTUV=' - rfc4648 with padding
base32z, // 'ybndrfg8ejkmcpqxot1uwisza345h769' - z - base - 32 - used by Tahoe - LAFS - highest letter
base58flickr, // '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ' - highest letter
base58btc, // '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' - highest letter
base64, // 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - rfc4648 no padding
base64pad, // 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' - rfc4648 with padding - MIME encoding
base64url, // 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_' - rfc4648 no padding
base64urlpad, // 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=' - rfc4648 with padding
};
namespace details {
typedef buffer_t(*CodecFunc)(bufferview_t, const char*);
inline buffer_t codec_noimpl(bufferview_t /*data*/, const char* /*digits*/) { return {}; }
buffer_t encode_base0(bufferview_t data, const char* digits);
buffer_t encode_base2(bufferview_t data, const char* digits);
buffer_t encode_base8(bufferview_t data, const char* digits);
//buffer_t encode_base10(bufferview_t data, const char* digits);
buffer_t encode_base16(bufferview_t data, const char* digits);
buffer_t encode_base32(bufferview_t data, const char* digits);
//buffer_t encode_base58(bufferview_t data, const char* digits);
buffer_t encode_base64(bufferview_t data, const char* digits);
buffer_t decode_base0(bufferview_t data, const char* digits);
buffer_t decode_base2(bufferview_t data, const char* digits);
buffer_t decode_base8(bufferview_t data, const char* digits);
//buffer_t decode_base10(bufferview_t data, const char* digits);
buffer_t decode_base16(bufferview_t data, const char* digits);
buffer_t decode_base32(bufferview_t data, const char* digits);
//buffer_t decode_base58(bufferview_t data, const char* digits);
buffer_t decode_base64(bufferview_t data, const char* digits);
template <base_t _FromBase, base_t _ToBase>
buffer_t convert_base(bufferview_t from, const char*);
struct baseimpl {
base_t key;
const char* name;
char code;
int radix;
CodecFunc encode;
CodecFunc decode;
const char* digits;
};
constexpr baseimpl _BaseTable[] = {
{ dynamic_base, "dynamic_base", -1, -1, codec_noimpl , codec_noimpl , nullptr },
{ base256, "base256", 0, 256, codec_noimpl , codec_noimpl , nullptr },
{ identity, "identity", 0, 0, encode_base0 , decode_base0 , nullptr },
{ base2, "base2", '0', 2, encode_base2 , decode_base2 , "01" },
{ base8, "base8", '7', 8, encode_base8 , decode_base8 , "01234567" },
{ base10, "base10", '9', 10, convert_base<base256, base10> , convert_base<base10, base256> , "0123456789" },
{ base16, "base16", 'f', 16, encode_base16 , decode_base16 , "0123456789abcdef" },
{ BASE16, "BASE16", 'F', 16, encode_base16 , decode_base16 , "0123456789ABCDEF" },
{ base32, "base32", 'b', 32, encode_base32 , decode_base32 , "abcdefghijklmnopqrstuvwxyz234567" },
{ BASE32, "BASE32", 'B', 32, encode_base32 , decode_base32 , "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" },
{ base32pad, "base32pad", 'c', 32, encode_base32 , decode_base32 , "abcdefghijklmnopqrstuvwxyz234567=" },
{ BASE32pad, "BASE32pad", 'C', 32, encode_base32 , decode_base32 , "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=" },
{ base32hex, "base32hex", 'v', 32, encode_base32 , decode_base32 , "0123456789abcdefghijklmnopqrstuv" },
{ BASE32hex, "BASE32hex", 'V', 32, encode_base32 , decode_base32 , "0123456789ABCDEFGHIJKLMNOPQRSTUV" },
{ base32hexpad, "base32hexpad", 't', 32, encode_base32 , decode_base32 , "0123456789abcdefghijklmnopqrstuv=" },
{ BASE32hexpad, "BASE32hexpad", 'T', 32, encode_base32 , decode_base32 , "0123456789ABCDEFGHIJKLMNOPQRSTUV=" },
{ base32z, "base32z", 'h', 32, encode_base32 , decode_base32 , "ybndrfg8ejkmcpqxot1uwisza345h769" },
{ base58flickr, "base58flickr", 'Z', 58, convert_base<base256, base58flickr>, convert_base<base58flickr, base256>, "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" },
{ base58btc, "base58btc", 'z', 58, convert_base<base256, base58btc> , convert_base<base58btc, base256> , "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" },
{ base64, "base64", 'm', 64, encode_base64 , decode_base64 , "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" },
{ base64pad, "base64pad", 'M', 64, encode_base64 , decode_base64 , "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" },
{ base64url, "base64url", 'u', 64, encode_base64 , decode_base64 , "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" },
{ base64urlpad, "base64urlpad", 'U', 64, encode_base64 , decode_base64 , "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=" },
};
constexpr int find_baseimpl(base_t code) {
for (auto i = 0; i < _countof(_BaseTable); i++)
if (_BaseTable[i].key == code) return i;
return 0;
}
constexpr base_t find_basecode(byte_t code) {
for (auto i = 0; i < _countof(_BaseTable); i++)
if (_BaseTable[i].code == code) return _BaseTable[i].key;
return dynamic_base;
}
inline byte_t from_digit(byte_t digit, const char* begin, const char* end)
{
auto ptr = std::find(begin, end, digit);
if (ptr == end) throw std::out_of_range("Provided digit is not in alphabet");
return gsl::narrow<byte_t>(ptr - begin);
}
template <base_t _Base>
byte_t from_digit(byte_t digit) {
constexpr auto _Index = details::find_baseimpl(_Base);
constexpr auto _Impl = details::_BaseTable[_Index];
static_assert(_Index > 0, "base not implemented");
const auto begin = _Impl.digits;
const auto end = _Impl.digits + _Impl.radix;
return from_digit(digit, begin, end);
}
template<>
inline byte_t from_digit<base256>(byte_t digit) {
return digit;
}
template <base_t _Base>
byte_t to_digit(byte_t value) {
constexpr auto _Index = details::find_baseimpl(_Base);
constexpr auto _Impl = details::_BaseTable[_Index];
static_assert(_Index > 0, "base not implemented");
if (value >= _Impl.radix) throw std::out_of_range(std::string("Provided value is not in accepted range of ") + _Impl.name + ".");
return _Impl.digits[value];
}
template<>
inline byte_t to_digit<base256>(byte_t value) {
return value;
}
template <base_t _FromBase, base_t _ToBase>
buffer_t convert_base(bufferview_t from, const char*)
{
constexpr auto _FromIndex = details::find_baseimpl(_FromBase);
constexpr auto _ToIndex = details::find_baseimpl(_ToBase);
constexpr auto _FromImpl = details::_BaseTable[_FromIndex];
constexpr auto _ToImpl = details::_BaseTable[_ToIndex];
static_assert(_FromIndex > 0 && _ToIndex > 0, "base not implemented");
// Skip & count leading zeroes.
auto first = std::find_if_not(std::begin(from), std::end(from), [](auto v) { return v == 0; });
auto last = std::end(from);
const auto leadingZeroes = first - std::begin(from);
const auto dataSize = last - first;
// Compute the max size of the encoded string, maybe shorter (log(256) / log(10), rounded up).
const auto tmpSize = size_t(dataSize * log((double)_FromImpl.radix) / log((double)_ToImpl.radix)) + 1;
auto tmp = buffer_t(tmpSize, 0);
// Process the data
auto encodedLen = 0;
while (first != last)
{
auto carry = static_cast<uint32_t>(from_digit<_FromBase>(*first++));
auto i = 0;
for (auto it = tmp.rbegin(); it != tmp.rend() && (carry || i < encodedLen); i++, it++)
{
carry += _FromImpl.radix * (*it);
*it = gsl::narrow<byte_t>(carry % _ToImpl.radix);
carry /= _ToImpl.radix;
}
encodedLen = i;
}
// Skip leading zeroes in encoded buffer (keep at least one zero if null)
auto tmpFirst = std::find_if_not(std::begin(tmp), std::end(tmp), [](auto v) { return v == 0; });
if (tmpFirst == std::end(tmp)) tmpFirst--;
// translate with digits
const auto encodedSize = leadingZeroes + (std::end(tmp) - tmpFirst);
auto encoded = buffer_t(encodedSize, to_digit<_ToBase>(0));
for (auto i = leadingZeroes; i < encodedSize; ++i)
encoded[i] = to_digit<_ToBase>(*tmpFirst++);
return encoded;
}
template <base_t _Base = dynamic_base, int _Index = find_baseimpl(_Base)>
class basecode_type
{
public:
static_assert(_Base != dynamic_base, "dynamic_base is not allowed here");
static_assert(_Index > 0, "The base_t is not implemented");
constexpr basecode_type(base_t base) { Expects(base == _Base); }
constexpr base_t base() const { return _BaseTable[_Index].key; }
constexpr const char* name() const { return _BaseTable[_Index].name; }
constexpr uint32_t code() const { return _BaseTable[_Index].code; }
constexpr int32_t radix() const { return _BaseTable[_Index].radix; }
constexpr const char* digits() const { return _BaseTable[_Index].digits; }
constexpr CodecFunc encode() const { return _BaseTable[_Index].encode; }
constexpr CodecFunc decode() const { return _BaseTable[_Index].decode; }
constexpr int index() const { return _Index; }
};
template <>
class basecode_type<dynamic_base>
{
public:
explicit constexpr basecode_type(base_t base) : _index(find_baseimpl(base)) { Expects(_index > 0); }
constexpr base_t base() const { return _BaseTable[_index].key; }
constexpr const char* name() const { return _BaseTable[_index].name; }
constexpr uint32_t code() const { return _BaseTable[_index].code; }
constexpr int32_t radix() const { return _BaseTable[_index].radix; }
constexpr const char* digits() const { return _BaseTable[_index].digits; }
constexpr CodecFunc encode() const { return _BaseTable[_index].encode; }
constexpr CodecFunc decode() const { return _BaseTable[_index].decode; }
constexpr int index() const { return _index; }
private:
const int _index;
};
}
//
// The class `encoded_string<base_t>` is used to strongly type strings that are encoded in a base known at compile-time.
// The specialization `encoded_string<dynamic_base>` is used to type encoded strings for which the base is not known at compile-time.
//
template <base_t _Base = dynamic_base>
class encoded_string
{
public:
// Construct empty encoded_string<>
encoded_string() : _base(_Base) {}
encoded_string(base_t code) : _base(code) {}
// Construct by copying _Right
// - from string
encoded_string(stringview_t _Right) : _string(to_string(_Right)), _base(_Base) {}
encoded_string(base_t code, stringview_t _Right) : _string(to_string(_Right)), _base(code) {}
encoded_string(const char* _Right) : encoded_string(gsl::ensure_z(_Right)) {}
encoded_string(base_t code, const char* _Right) : encoded_string(code, gsl::ensure_z(_Right)) {}
// - from encoded_string<>
encoded_string(const encoded_string<_Base>& _Right) : _string(_Right._string), _base(_Right.base()) {}
template <base_t _RightBase>
encoded_string(const encoded_string<_RightBase>& _Right) : _string(_Right._string), _base(_Right.base())
{
static_assert(_RightBase == _Base || _RightBase == dynamic_base || _Base == dynamic_base, "Mismatch between codes.");
}
// Construct by moving _Right
// - from string
encoded_string(string_t&& _Right) : _string(std::move(_Right)), _base(_Base) {}
encoded_string(base_t code, string_t&& _Right) : _string(std::move(_Right)), _base(code) {}
// - from encoded_string<>
encoded_string(encoded_string<_Base>&& _Right) : _string(std::move(_Right._string)), _base(_Right.base()) {}
template <base_t _RightBase>
encoded_string(encoded_string<_RightBase>&& _Right) : _string(std::move(_Right._string)), _base(_Right.base())
{
static_assert(_RightBase == _Base || _RightBase == dynamic_base || _Base == dynamic_base, "Mismatch between codes.");
}
// Assign by copying _Right
// Note: an encoded_string<> is immutable once initialized
// - from string
encoded_string<_Base>& operator =(stringview_t _Right)
{
Expects(_string.empty() && !_Right.empty());
_string = to_string(_Right);
return *this;
}
encoded_string<_Base>& operator =(const char* _Right)
{
return operator+(gsl::ensure_z(_Right));
}
// - from encoded_string<>
encoded_string<_Base>& operator =(const encoded_string<_Base>& _Right)
{
Expects(_Right.base() == base());
Expects(_string.empty() && !_Right.empty());
_string = _Right._string;
return *this;
}
template <base_t _RightBase>
encoded_string<_Base>& operator =(const encoded_string<_RightBase>& _Right)
{
static_assert(_RightBase == _Base || _RightBase == dynamic_base || _Base == dynamic_base, "Mismatch between codes.");
Expects(_Right.base() == base());
Expects(_string.empty() && !_Right.empty());
_string = _Right._string;
return *this;
}
// Assign by moving _Right
// Note: an encoded_string<> is immutable once initialized
// - from string
encoded_string<_Base>& operator =(string_t&& _Right)
{
Expects(_string.empty() && !_Right.empty());
_string = std::move(_Right);
return *this;
}
// - from encoded_string<>
encoded_string<_Base>& operator =(encoded_string<_Base>&& _Right)
{
Expects(_Right.base() == base());
Expects(_string.empty() && !_Right.empty());
_string = std::move(_Right._string);
return *this;
}
template <base_t _RightBase>
encoded_string<_Base>& operator =(encoded_string<_RightBase>&& _Right)
{
static_assert(_RightBase == _Base || _RightBase == dynamic_base || _Base == dynamic_base, "Mismatch between codes.");
Expects(_Right.base() == base());
Expects(_string.empty() && !_Right.empty());
_string = std::move(_Right._string);
return *this;
}
base_t base() const { return _base.base(); }
const string_t& str() const { return _string; }
bool empty() const { return _string.empty(); }
private:
const details::basecode_type<_Base> _base;
string_t _string;
template <base_t _FriendBase> friend class encoded_string;
};
// operator+
template <base_t _Base>
string_t operator+(stringview_t _Left, const encoded_string<_Base>& _Right) { return (_Left + _Right.str()); }
template <base_t _Base>
string_t operator+(const encoded_string<_Base>& _Left, stringview_t _Right) { return (_Left.str() + _Right); }
template <base_t _Base>
string_t operator+(const char* _Left, const encoded_string<_Base>& _Right) { return (_Left + _Right.str()); }
template <base_t _Base>
string_t operator+(const encoded_string<_Base>& _Left, const char* _Right) { return (_Left.str() + _Right); }
// operator==
template <base_t _BaseLeft, base_t _BaseRight>
bool operator==(const encoded_string<_BaseLeft>& _Left, const encoded_string<_BaseRight>& _Right)
{
return (_Left.base() == _Right.base()) && (_Left.str() == _Right.str());
}
template <base_t _Base>
bool operator==(const std::string& _Left, const encoded_string<_Base>& _Right) { return (_Left == _Right.str()); }
template <base_t _Base>
bool operator==(const encoded_string<_Base>& _Left, const std::string& _Right) { return (_Left.str() == _Right); }
// operator!=
template <base_t _BaseLeft, base_t _BaseRight>
bool operator!=(const encoded_string<_BaseLeft>& _Left, const encoded_string<_BaseRight>& _Right) { return !(_Left == _Right); }
template <base_t _Base>
bool operator!=(const std::string& _Left, const encoded_string<_Base>& _Right) { return !(_Left == _Right); }
template <base_t _Base>
bool operator!=(const encoded_string<_Base>& _Left, const std::string& _Right) { return !(_Left == _Right); }
// operator<
template <base_t _BaseLeft, base_t _BaseRight>
bool operator<(const encoded_string<_BaseLeft>& _Left, const encoded_string<_BaseRight>& _Right)
{
if (_Left.base() < _Right.base()) return true;
if (_Left.base() > _Right.base()) return false;
return (_Left.str() < _Right.str());
}
template <base_t _Base>
bool operator<(const std::string& _Left, const encoded_string<_Base>& _Right) { return (_Left < _Right.str()); }
template <base_t _Base>
bool operator<(const encoded_string<_Base>& _Left, const std::string& _Right) { return (_Left.str() < _Right); }
//
template <base_t _Base>
std::ostream& operator<< (std::ostream& os, const encoded_string<_Base>& _Right) { return os << _Right.str(); }
//
// Encode a buffer/string into a _Base encoded_string
//
template <base_t _Base>
encoded_string<_Base> encode(bufferview_t data)
{
constexpr auto _Index = details::find_baseimpl(_Base);
constexpr auto _Impl = details::_BaseTable[_Index];
static_assert(_Base != dynamic_base, "encode<_Base>(bufferview_t) is not allowed for _Base == basecode::dynamic_base");
static_assert(_Index > 0, "encode<_Base>(bufferview_t) is not implementeed for this _Base");
Expects(!data.empty());
return as_string(_Impl.encode(data, _Impl.digits));
}
inline encoded_string<> encode(base_t base, bufferview_t data)
{
Expects(!data.empty());
const auto index = details::find_baseimpl(base);
const auto impl = details::_BaseTable[index];
Expects(index > 0);
return { base, as_string(impl.encode(data, impl.digits)) };
}
template <base_t _Base>
encoded_string<_Base> encode(const std::string& string) { return encode<_Base>(as_buffer(string)); }
inline encoded_string<> encode(base_t code, const std::string& string) { return encode(code, as_buffer(string)); }
//
// Decode a _Base encoded_string into a buffer
//
template <base_t _Base>
buffer_t decode(const encoded_string<_Base>& string)
{
constexpr auto _Index = details::find_baseimpl(_Base);
constexpr auto _Impl = details::_BaseTable[_Index];
static_assert(_Base != dynamic_base, "decode<_Base>(encoded_string) is not allowed for _Base == basecode::dynamic_base");
static_assert(_Index > 0, "decode<_Base>(encoded_string) is not implementeed for this _Base");
Expects(!string.empty());
return _Impl.decode(as_buffer(string.str()), _Impl.digits);
}
inline buffer_t decode(const encoded_string<>& string)
{
Expects(!string.empty());
const auto index = details::find_baseimpl(string.base());
const auto impl = details::_BaseTable[index];
Expects(index > 0);
return impl.decode(as_buffer(string.str()), impl.digits);
}
inline stringview_t decode(base_t base, stringview_t src, buffer_t& dst)
{
Expects(!src.empty());
const auto index = details::find_baseimpl(base);
const auto impl = details::_BaseTable[index];
Expects(index > 0);
auto pos = to_string(src).find_first_not_of(impl.digits);
if (pos == string_t::npos) pos = src.size();
dst += decode({ base, src.first(pos) });
return src.last(src.size() - pos);
}
inline buffer_t decode(base_t base, stringview_t src)
{
auto dst = buffer_t{};
decode(base, src, dst);
return dst;
}
inline buffer_t decode(base_t base, const char* src)
{
return decode(base, gsl::ensure_z(src));
}
//
// Self-identifying base-encoded string
//
template <base_t _Base = dynamic_base>
using multibase = std::string;
template <base_t _Base>
multibase<_Base> encode_multibase(bufferview_t data) {
constexpr auto _Index = details::find_baseimpl(_Base);
constexpr auto _Impl = details::_BaseTable[_Index];
static_assert(_Base != dynamic_base, "make_multibase<_Base>(bufferview_t) is not allowed for _Base == basecode::dynamic_base");
static_assert(_Index > 0, "make_multibase<_Base>(bufferview_t) is not implementeed for this _Base");
return _Impl.code + encode<_Base>(data).str();
}
inline multibase<> encode_multibase(base_t base, bufferview_t data) {
const auto index = details::find_baseimpl(base);
const auto impl = details::_BaseTable[index];
Expects(index > 0);
return impl.code + encode(base, data).str();
}
template <base_t _Base>
multibase<_Base> encode_multibase(const std::string& string) { return encode_multibase<_Base>(as_buffer(string)); }
inline multibase<> encode_multibase(base_t code, const std::string& string) { return encode_multibase(code, as_buffer(string)); }
template <base_t _Base>
encoded_string<_Base> decode_multibase(multibase<_Base> mb) { return mb.substr(1); }
inline encoded_string<> decode_multibase(const std::string& mb) { return { details::find_basecode(mb[0]), mb.substr(1) }; }
}
inline multiformats::encoded_string<multiformats::base16> operator "" _16(const char* s, std::size_t)
{ return multiformats::encoded_string<multiformats::base16>(s); }
inline multiformats::encoded_string<multiformats::base64url> operator "" _64url(const char* s, std::size_t)
{
return multiformats::encoded_string<multiformats::base64url>(s);
}
| {
"alphanum_fraction": 0.589869156,
"avg_line_length": 48.1362799263,
"ext": "h",
"hexsha": "2db1c375d2220f464c745ae64d28af028ca2ad69",
"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": "5516d857d4429544bd641b7fdde24c6cad9265b7",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "cedrou/multiformats",
"max_forks_repo_path": "include/multiformats/multibase.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5516d857d4429544bd641b7fdde24c6cad9265b7",
"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": "cedrou/multiformats",
"max_issues_repo_path": "include/multiformats/multibase.h",
"max_line_length": 199,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5516d857d4429544bd641b7fdde24c6cad9265b7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "cedrou/cpp-multiformats",
"max_stars_repo_path": "include/multiformats/multibase.h",
"max_stars_repo_stars_event_max_datetime": "2019-07-29T20:33:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-07-29T20:33:02.000Z",
"num_tokens": 6106,
"size": 26138
} |
/* filter/gsl_filter.h
*
* 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.
*/
#ifndef __GSL_FILTER_H__
#define __GSL_FILTER_H__
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_movstat.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
/* end point handling methods */
typedef enum
{
GSL_FILTER_END_PADZERO = GSL_MOVSTAT_END_PADZERO,
GSL_FILTER_END_PADVALUE = GSL_MOVSTAT_END_PADVALUE,
GSL_FILTER_END_TRUNCATE = GSL_MOVSTAT_END_TRUNCATE
} gsl_filter_end_t;
/* robust scale estimates */
typedef enum
{
GSL_FILTER_SCALE_MAD, /* median absolute deviation */
GSL_FILTER_SCALE_IQR, /* interquartile range */
GSL_FILTER_SCALE_SN, /* S_n scale statistic */
GSL_FILTER_SCALE_QN /* Q_n scale statistic */
} gsl_filter_scale_t;
/* workspace for Gaussian filter */
typedef struct
{
size_t K; /* window size */
double *kernel; /* Gaussian kernel, size K */
gsl_movstat_workspace *movstat_workspace_p;
} gsl_filter_gaussian_workspace;
gsl_filter_gaussian_workspace *gsl_filter_gaussian_alloc(const size_t K);
void gsl_filter_gaussian_free(gsl_filter_gaussian_workspace * w);
int gsl_filter_gaussian(const gsl_filter_end_t endtype, const double alpha, const size_t order, const gsl_vector * x,
gsl_vector * y, gsl_filter_gaussian_workspace * w);
int gsl_filter_gaussian_kernel(const double alpha, const size_t order, const int normalize, gsl_vector * kernel);
/* workspace for standard median filter */
typedef struct
{
gsl_movstat_workspace *movstat_workspace_p;
} gsl_filter_median_workspace;
gsl_filter_median_workspace *gsl_filter_median_alloc(const size_t K);
void gsl_filter_median_free(gsl_filter_median_workspace * w);
int gsl_filter_median(const gsl_filter_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_filter_median_workspace * w);
/* workspace for recursive median filter */
typedef struct
{
size_t H; /* window half-length (K / 2) */
size_t K; /* window size */
void *state; /* workspace for min/max accumulator */
double *window; /* array holding first window */
const gsl_movstat_accum * minmaxacc; /* minimum/maximum accumulator */
gsl_movstat_workspace *movstat_workspace_p;
} gsl_filter_rmedian_workspace;
gsl_filter_rmedian_workspace *gsl_filter_rmedian_alloc(const size_t K);
void gsl_filter_rmedian_free(gsl_filter_rmedian_workspace * w);
int gsl_filter_rmedian(const gsl_filter_end_t, const gsl_vector * x, gsl_vector * y, gsl_filter_rmedian_workspace * w);
int gsl_filter_rmedian2(const gsl_vector * x, gsl_vector * y, gsl_filter_rmedian_workspace * w);
typedef struct
{
gsl_movstat_workspace *movstat_workspace_p;
} gsl_filter_impulse_workspace;
gsl_filter_impulse_workspace *gsl_filter_impulse_alloc(const size_t K);
void gsl_filter_impulse_free(gsl_filter_impulse_workspace * w);
int gsl_filter_impulse(const gsl_filter_end_t endtype, const gsl_filter_scale_t scale_type, const double t,
const gsl_vector * x, gsl_vector * y, gsl_vector * xmedian, gsl_vector * xsigma, size_t * noutlier,
gsl_vector_int * ioutlier, gsl_filter_impulse_workspace * w);
__END_DECLS
#endif /* __GSL_FILTER_H__ */
| {
"alphanum_fraction": 0.7525922354,
"avg_line_length": 37.7,
"ext": "h",
"hexsha": "0339da26a003c38ed65ba390f74cfeac95b06042",
"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": "3ca418add85a59ac7e805d55a600b78330d7e53d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzhmark/vaa3d_tools",
"max_forks_repo_path": "hackathon/liyad/steerablefilter3D/gsl_include/gsl_filter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d",
"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": "zzhmark/vaa3d_tools",
"max_issues_repo_path": "hackathon/liyad/steerablefilter3D/gsl_include/gsl_filter.h",
"max_line_length": 125,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzhmark/vaa3d_tools",
"max_stars_repo_path": "hackathon/liyad/steerablefilter3D/gsl_include/gsl_filter.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z",
"num_tokens": 973,
"size": 4147
} |
#include "matrix.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
/*************************** Complex Number *************************/
/*
typedef struct {
double dat[2];
} Complex;
*/
Complex ComplexPolar(double r, double theta) {
Complex z = {r * cos(theta), r * sin(theta)};
return z;
}
void ComplexPrint(Complex z) {
printf("%f + %fi\n", z.re, z.im);
}
Complex ComplexAdd(Complex z, Complex w) {
Complex x = {z.re + w.re, z.im + w.im};
return x;
}
Complex ComplexMul(Complex z, Complex w) {
Complex x = {z.re*w.re - z.im*w.im, z.re*w.im + w.re*z.im};
return x;
}
Complex ComplexMulReal(Complex z, double r) {
Complex x = {z.re*r, z.im*r};
return x;
}
double ComplexMag(Complex z) {
return sqrt(ComplexMagSquare(z));
}
double ComplexMagSquare(Complex z) {
return z.re*z.re + z.im*z.im;
}
/*************************** Bit Vector *************************/
/*
struct BitVector {
unsigned int size;
unsigned char* data;
};
*/
// alloc and init to 0
struct BitVector* newBitVector(unsigned int size) {
assert(size > 0);
struct BitVector* vec = (struct BitVector*)malloc(sizeof(struct BitVector));
vec->size = size;
vec->data = (unsigned char*)gsl_vector_alloc(vec->size);
gsl_vector_set_zero((gsl_vector*)vec->data);
return vec;
}
// alloc and init randomly
struct BitVector* newBitVectorRandom(unsigned int size) {
assert(size > 0);
struct BitVector* vec = (struct BitVector*)malloc(sizeof(struct BitVector));
vec->size = size;
vec->data = (unsigned char*)gsl_vector_alloc(vec->size);
BitVectorSetRandom(vec);
return vec;
}
void BitVectorSetRandom(struct BitVector* vec) {
for (unsigned int i = 0; i < vec->size; i++) {
BitVectorSet(vec, i, rand());
}
}
void BitVectorSetZero(struct BitVector* vec) {
gsl_vector_set_zero((gsl_vector*)vec->data);
}
void BitVectorFree(struct BitVector* vec) {
gsl_vector_free((gsl_vector*)vec->data);
free(vec);
}
// copy vec2 to vec1
void BitVectorCopy(struct BitVector* vec1, struct BitVector* vec2) {
assert(vec1->size == vec2->size);
gsl_vector_memcpy((gsl_vector*)vec1->data, (gsl_vector*)vec2->data);
}
unsigned int BitVectorGet(struct BitVector* vec, unsigned int loc) {
assert(vec->size > loc);
return (int)gsl_vector_get((gsl_vector*)vec->data, loc) % 2;
};
void BitVectorSet(struct BitVector* vec, unsigned int loc, unsigned int value) {
assert(vec->size > loc);
gsl_vector_set((gsl_vector*)vec->data, loc, (double) (value % 2));
}
void BitVectorFlip(struct BitVector* vec, unsigned int loc) {
assert(vec->size > loc);
BitVectorSet(vec, loc, 1-BitVectorGet(vec, loc));
}
int BitVectorSame(struct BitVector* vec1, struct BitVector* vec2) {
assert(vec1->size == vec2->size);
for (unsigned int i = 0; i < vec1->size; i++) {
if (BitVectorGet(vec1, i) != BitVectorGet(vec2, i)) return 0;
}
return 1;
}
void BitVectorPrint(struct BitVector* vec) {
printf("[");
for (unsigned int i = 0; i < vec->size; i++) {
printf("%d", BitVectorGet(vec, i));
}
printf("]\n");
}
unsigned int BitVectorInner(struct BitVector* vec1, struct BitVector* vec2) {
assert(vec1->size == vec2->size);
double inner;
gsl_blas_ddot((gsl_vector*)vec1->data, (gsl_vector*)vec2->data, &inner);
return (unsigned int)inner;
}
// vec1 <- vec1 ^ vec2
void BitVectorXorSet(struct BitVector* vec1, struct BitVector* vec2) {
assert(vec1->size == vec2->size);
for (unsigned int i = 0; i < vec1->size; i++) {
BitVectorSet(vec1, i, BitVectorGet(vec1,i) + BitVectorGet(vec2,i) % 2);
}
}
// helper
void BitVectorMod2(struct BitVector* vec) {
for (unsigned int i = 0; i < vec->size; i++) {
BitVectorSet(vec, i, BitVectorGet(vec, i));
}
}
/*************************** Bit Matrix *************************/
/*
struct BitMatrix {
unsigned int rows;
unsigned int cols;
unsigned char* data;
};
*/
// alloc and init to 0
struct BitMatrix* newBitMatrixZero(unsigned int rows, unsigned int cols) {
assert(rows > 0);
assert(cols > 0);
struct BitMatrix* mat = (struct BitMatrix*)malloc(sizeof(struct BitMatrix));
mat->rows = rows;
mat->cols = cols;
mat->data = (unsigned char*)gsl_matrix_alloc(mat->rows, mat->cols);
gsl_matrix_set_zero((gsl_matrix*)mat->data);
return mat;
}
// alloc and init to identity
struct BitMatrix* newBitMatrixIdentity(unsigned int rows) {
struct BitMatrix* mat = newBitMatrixZero(rows, rows);
gsl_matrix_set_identity((gsl_matrix*)mat->data);
return mat;
}
// alloc and init randomly
struct BitMatrix* newBitMatrixRandom(unsigned int rows, unsigned int cols) {
assert(rows > 0);
assert(cols > 0);
struct BitMatrix* mat = newBitMatrixZero(rows, rows);
BitMatrixSetRandom(mat);
return mat;
}
void BitMatrixFree(struct BitMatrix* mat) {
gsl_matrix_free((gsl_matrix*)mat->data);
free(mat);
}
void BitMatrixCopy(struct BitMatrix* mat1, struct BitMatrix* mat2) {
assert(mat1->rows == mat2->rows);
assert(mat1->cols == mat2->cols);
gsl_matrix_memcpy((gsl_matrix*)mat1->data, (gsl_matrix*)mat2->data);
}
void BitMatrixSetZero(struct BitMatrix* mat) {
gsl_matrix_set_zero((gsl_matrix*)mat->data);
}
void BitMatrixSetRandom(struct BitMatrix* mat) {
for (unsigned int i = 0; i < mat->rows; i++) {
for (unsigned int j = 0; j < mat->cols; j++) {
BitMatrixSet(mat, i, j, rand());
}
}
}
void BitMatrixSetIdentity(struct BitMatrix* mat) {
gsl_matrix_set_identity((gsl_matrix*)mat->data);
}
void BitMatrixPrint(struct BitMatrix* mat) {
printf("[");
for (unsigned int i = 0; i < mat->rows; i++) {
if (i != 0) printf("\n ");
printf("[");
for (unsigned int j = 0; j < mat->cols; j++) {
printf("%d", BitMatrixGet(mat, i, j));
}
printf("]");
}
printf("]\n");
}
unsigned int BitMatrixGet(struct BitMatrix* mat, unsigned int row, unsigned int col) {
assert(mat->cols > col);
assert(mat->rows > row);
return (int)gsl_matrix_get((gsl_matrix*)mat->data, row, col) % 2;
}
void BitMatrixSet(struct BitMatrix* mat, unsigned int row, unsigned int col, unsigned int value) {
assert(mat->cols > col);
assert(mat->rows > row);
gsl_matrix_set((gsl_matrix*)mat->data, row, col, (double)(value % 2));
}
void BitMatrixFlip(struct BitMatrix* mat, unsigned int row, unsigned int col) {
assert(mat->cols > col);
assert(mat->rows > row);
BitMatrixSet(mat, row, col, 1-BitMatrixGet(mat, row, col));
}
int BitMatrixSame(struct BitMatrix* mat1, struct BitMatrix* mat2) {
assert(mat1->rows == mat2->rows);
assert(mat1->cols == mat2->cols);
for (unsigned int i = 0; i < mat1->rows; i++) {
for (unsigned int j = 0; j < mat1->cols; j++) {
if (BitMatrixGet(mat1, i, j) != BitMatrixGet(mat2, i, j)) return 0;
}
}
return 1;
}
void BitMatrixXorSet(struct BitMatrix* mat1, struct BitMatrix* mat2) { // mat1 <- mat1 ^ mat2
assert(mat1->cols == mat2->cols);
assert(mat1->rows == mat2->cols);
for (unsigned int i = 0; i < mat1->rows; i++) {
for (unsigned int j = 0; j < mat1->cols; j++) {
BitMatrixSet(mat1, i, j, BitMatrixGet(mat1,i,j) + BitMatrixGet(mat2,i,j) % 2);
}
}
}
void BitMatrixSetCol(struct BitMatrix* mat, struct BitVector* vec, unsigned int col) {
assert(vec->size == mat->rows);
assert(col < mat->cols);
gsl_matrix_set_col((gsl_matrix*)mat->data, col, (gsl_vector*)vec->data);
}
void BitMatrixSetRow(struct BitMatrix* mat, struct BitVector* vec, unsigned int row) {
assert(vec->size == mat->cols);
assert(row < mat->rows);
gsl_matrix_set_row((gsl_matrix*)mat->data, row, (gsl_vector*)vec->data);
}
struct BitVector* BitMatrixGetCol(struct BitMatrix* mat, unsigned int col) {
assert(col < mat->cols);
struct BitVector* vec = newBitVector(mat->rows);
gsl_matrix_get_col((gsl_vector*)vec->data, (gsl_matrix*)mat->data, col);
return vec;
}
struct BitVector* BitMatrixGetRow(struct BitMatrix* mat, unsigned int row) {
assert(row < mat->rows);
struct BitVector* vec = newBitVector(mat->cols);
gsl_matrix_get_row((gsl_vector*)vec->data, (gsl_matrix*)mat->data, row);
return vec;
}
void BitMatrixSwapCols(struct BitMatrix* mat, unsigned int col1, unsigned int col2) {
gsl_matrix_swap_columns((gsl_matrix*)mat->data, col1, col2);
}
void BitMatrixSwapRows(struct BitMatrix* mat, unsigned int row1, unsigned int row2) {
gsl_matrix_swap_rows((gsl_matrix*)mat->data, row1, row2);
}
// helper
void BitMatrixMod2(struct BitMatrix* mat) {
for (unsigned int i = 0; i < mat->rows; i++) {
for (unsigned int j = 0; j < mat->cols; j++) {
BitMatrixSet(mat, i, j, BitMatrixGet(mat,i,j));
}
}
}
struct BitMatrix* BitMatrixTranspose(struct BitMatrix* mat) {
struct BitMatrix* matT = newBitMatrixZero(mat->cols, mat->rows);
gsl_matrix_transpose_memcpy((gsl_matrix*)matT->data, (gsl_matrix*)mat->data);
return matT;
}
void BitMatrixTransposeSet(struct BitMatrix* mat) {
struct BitMatrix* matT = BitMatrixTranspose(mat);
mat->rows = matT->rows;
mat->cols = matT->cols;
BitMatrixCopy(matT, mat);
BitMatrixFree(matT);
}
struct BitMatrix* BitMatrixMulMatrix(struct BitMatrix* mat1, struct BitMatrix* mat2) {
assert(mat1->cols == mat2->rows);
struct BitMatrix* matOut = newBitMatrixZero(mat1->rows, mat2->cols);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1, (gsl_matrix*)mat1->data, (gsl_matrix*)mat2->data, 0, (gsl_matrix*)matOut->data);
BitMatrixMod2(matOut);
return matOut;
}
// mat2 <- mat1*mat2;
void BitMatrixMulMatrixLeft(struct BitMatrix* mat1, struct BitMatrix* mat2) {
struct BitMatrix* matTmp = BitMatrixMulMatrix(mat1, mat2);
BitMatrixCopy(mat2, matTmp);
BitMatrixFree(matTmp);
}
// mat1 <- mat1*mat2;
void BitMatrixMulMatrixRight(struct BitMatrix* mat1, struct BitMatrix* mat2) {
struct BitMatrix* matTmp = BitMatrixMulMatrix(mat1, mat2);
BitMatrixCopy(mat1, matTmp);
BitMatrixFree(matTmp);
}
struct BitVector* BitMatrixMulVector(struct BitMatrix* mat, struct BitVector* vec) {
assert(mat->cols == vec->size);
struct BitVector* vecOut = newBitVector(mat->rows);
gsl_blas_dgemv(CblasNoTrans, 1, (gsl_matrix*)mat->data, (gsl_vector*)vec->data, 0, (gsl_vector*)vecOut->data);
BitVectorMod2(vecOut);
return vecOut;
}
// vec <- mat*vec
void BitMatrixMulVectorSet(struct BitMatrix* mat, struct BitVector* vec) {
assert(mat->cols == vec->size);
assert(mat->cols == mat->rows);
gsl_blas_dgemv(CblasNoTrans, 1, (gsl_matrix*)mat->data, (gsl_vector*)vec->data, 0, (gsl_vector*)vec->data);
BitVectorMod2(vec);
}
unsigned int BitMatrixRank(struct BitMatrix* mat) {
struct BitMatrix* null = newBitMatrixIdentity(mat->cols);
unsigned int rank = mat->cols; // rank of the null space
struct BitMatrix* good = newBitMatrixZero(mat->cols, mat->cols);
struct BitMatrix* bad = newBitMatrixZero(mat->cols, mat->cols);
unsigned int numgood, numbad;
for (unsigned int row = 0; row < mat->rows; row++) {
struct BitVector* rowVec = BitMatrixGetRow(mat, row);
numgood = 0;
numbad = 0;
for (unsigned int i = 0; i < rank; i++) {
struct BitVector* nullVec = BitMatrixGetRow(null, i);
if (BitVectorInner(nullVec, rowVec) % 2 == 0) {
BitMatrixSetRow(good, nullVec, numgood);
numgood += 1;
} else {
BitMatrixSetRow(bad, nullVec, numbad);
numbad += 1;
}
}
// copy good into null
for (rank = 0; rank < numgood; rank++) {
struct BitVector* goodVec = BitMatrixGetRow(good, rank);
BitMatrixSetRow(null, goodVec, rank);
}
if (numbad > 1) {
struct BitVector* flipVec = BitMatrixGetRow(bad, 0);
for (; rank+1 < numbad+numgood; rank++) {
struct BitVector* badVec = BitMatrixGetRow(bad, 1+rank-numgood);
BitVectorXorSet(badVec, flipVec);
BitMatrixSetRow(null, badVec, rank);
}
}
}
BitMatrixFree(null);
BitMatrixFree(good);
BitMatrixFree(bad);
rank = mat->cols - rank; // rank of null space to rank of mat
return rank;
}
| {
"alphanum_fraction": 0.6292011019,
"avg_line_length": 26.46875,
"ext": "c",
"hexsha": "2e2315ad71ee78ce13415a6ed4af3ea521a2212f",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-07-19T21:30:55.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-25T20:00:21.000Z",
"max_forks_repo_head_hexsha": "a925996440313d96c3f102c52caa376f38fed015",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "patrickrall/CircuitSimulator",
"max_forks_repo_path": "libcirc/utils/matrix-blas.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a925996440313d96c3f102c52caa376f38fed015",
"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": "patrickrall/CircuitSimulator",
"max_issues_repo_path": "libcirc/utils/matrix-blas.c",
"max_line_length": 130,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "a925996440313d96c3f102c52caa376f38fed015",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "patrickrall/CircuitSimulator",
"max_stars_repo_path": "libcirc/utils/matrix-blas.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-15T01:05:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-11-07T13:32:00.000Z",
"num_tokens": 3631,
"size": 12705
} |
#include <assert.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <float.h>
#include "nn.h"
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#else
#include <cblas.h>
#endif
#define AVERAGE_FISHER 10
/**
* A function for generating random numbers according to a N(mu, sigma) Gaussian
* distribution.
*/
double randn (double mu, double sigma)
{
double U1, U2, W, mult;
static double X1, X2;
static int call = 0;
if (call == 1) {
call = !call;
return (mu + sigma * (double) X2);
}
do {
U1 = -1 + ((double) rand () / RAND_MAX) * 2;
U2 = -1 + ((double) rand () / RAND_MAX) * 2;
W = pow (U1, 2) + pow (U2, 2);
} while (W >= 1 || W == 0);
mult = sqrt ((-2 * log (W)) / W);
X1 = U1 * mult;
X2 = U2 * mult;
call = !call;
return (mu + sigma * (double) X1);
}
/**
* Shorthand to generate normally distributed random numbers.
*/
double rand_normal()
{
return randn(0.0, 1.0);
}
/**
* @brief Shuffle the index array.
*/
void shuffle_index(size_t num_pattern, size_t random_idx[num_pattern])
{
size_t p, np, op;
for (p = 0; p < num_pattern; ++p) {
random_idx[p] = p;
}
for (p = 0; p < num_pattern; ++p) {
np = p + ((double)rand()/((double)RAND_MAX+1)) * (num_pattern - 1 - p);
op = random_idx[p];
random_idx[p] = random_idx[np];
random_idx[np] = op;
}
}
/**
* This function fills the input and target vector with the list of training
* examples from automaton.
*/
void fill_input_target(size_t size, double* input, uint8_t* target,
uint8_t* automaton, int offset, int states)
{
size_t index;
int counter;
int side = 2 * offset + 1;
int num_input = states * (side * side - 1);
uint8_t val;
for (size_t i = 0; i < size; ++i) {
for (size_t j = 0; j < size; ++j) {
index = i * size + j;
counter = 1;
/* Add bias in the main vector */
input[index * (num_input + 1)] = 1.0;
for (int a = -offset; a < offset + 1; ++a) {
for (int b = -offset; b < offset + 1; ++b) {
if (a != 0 || b != 0) { /* Don't take index i,j */
val = automaton[((i + a + size) % size) * size
+ ((j + b + size) % size)];
for (uint8_t s = 0; s < states; ++s) {
input[index * (num_input + 1) + counter] = (val == s) ? 1.: 0.;
counter++;
}
}
}
}
target[index] = automaton[i * size + j];
}
}
}
void init_weights(int num_hidden, int num_input, int num_output,
double* delta_w_ih, double* weight_ih,
double* delta_w_ho, double* weight_ho)
{
int i, j, k;
/* Initialize weights input -> hidden */
for (j = 0; j < num_hidden; ++j) {
delta_w_ih[j] = 0.0;
weight_ih[j] = 0.0;
for (i = 1; i < num_input + 1; ++i) {
delta_w_ih[i * num_hidden + j] = 0.0;
weight_ih[i * num_hidden + j] = rand_normal() *
sqrt(1 / (double)(num_input));
}
}
/* Initialize weights hidden -> output */
for (k = 0; k < num_output; ++k) {
delta_w_ho[k] = 0.0;
weight_ho[k] = 0.0;
for (j = 1; j < num_hidden + 1; ++j) {
delta_w_ho[j * num_output + k] = 0.0;
weight_ho[j * num_output + k] = rand_normal() *
sqrt(1 / (double)(num_hidden));
}
}
}
void forward(double* input, double* output,
int num_hidden, int num_pattern,
int num_input, int num_output,
double* hidden,
double* hidden_bias,
double* weight_ih,
double* weight_ho)
{
int j, k, p;
double max_out, agg_out = 0.0;
/* Compute hidden activations */
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
num_pattern, num_hidden, num_input + 1, 1.0,
input, num_input + 1, weight_ih, num_hidden,
0.0, hidden, num_hidden);
/* ReLU non-linearity */
for (p = 0; p < num_pattern; ++p) {
hidden_bias[p * (num_hidden + 1)] = 1.0;
for (j = 1; j < num_hidden + 1; ++j) {
hidden_bias[p * (num_hidden + 1) + j] =
(hidden[p * num_hidden + j - 1] > 0.0) ?
hidden[p * num_hidden + j - 1]: 0.0;
}
}
/* Compute output unit activations */
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
num_pattern, num_output, num_hidden + 1, 1.0,
hidden_bias, num_hidden + 1, weight_ho, num_output,
0.0, output, num_output);
/* Compute softmax of output */
for (p = 0; p < num_pattern; ++p) {
max_out = output[p * num_output];
for (k = 1; k < num_output; ++k) {
if (output[p * num_output + k] > max_out) {
max_out = output[p * num_output + k];
}
}
agg_out = 0.0;
for (k = 0; k < num_output; ++k) {
output[p * num_output + k] = exp(output[p * num_output + k] - max_out);
agg_out += output[p * num_output + k];
}
for (k = 0; k < num_output; ++k) {
output[p * num_output + k] /= agg_out;
}
}
}
void update_weights(int num_input, int num_hidden, int num_output,
double eta,
double* batch_error, double reg, double alpha,
double* weight_ih, double* delta_w_ih,
double* delta_w_ih_prev,
double* weight_ho, double* delta_w_ho,
double* delta_w_ho_prev)
{
int i, j, k;
/* Update weights with average gradient */
for (i = 0; i < num_input + 1; ++i) {
for (j = 0; j < num_hidden; ++j) {
if (reg > 0.) {
*batch_error += 0.5 * reg *
weight_ih[i * num_hidden + j] * weight_ih[i * num_hidden + j] ;
weight_ih[i * num_hidden + j] += (1 + alpha) *
reg * weight_ih[i * num_hidden + j];
}
weight_ih[i * num_hidden + j] -= (1 + alpha) *
(eta * delta_w_ih[i * num_hidden + j]);
if (alpha > 0.) {
weight_ih[i * num_hidden + j] += (-alpha) *
delta_w_ih_prev[i * num_hidden + j];
}
}
}
for (j = 0; j < num_hidden + 1; ++j) {
for (k = 0; k < num_output; ++k) {
if (reg > 0.) {
*batch_error += 0.5 * reg *
weight_ho[j * num_output + k] * weight_ho[j * num_output + k];
weight_ho[j * num_output + k] += (1 + alpha) *
reg * weight_ho[j * num_output + k];
}
weight_ho[j * num_output + k] -= (1 + alpha) *
(eta * delta_w_ho[j * num_output + k]);
if (alpha > 0.) {
weight_ho[j * num_output + k] += (-alpha) *
delta_w_ho_prev[j * num_output + k];
}
}
}
}
void compute_batch_gradients(int base_index, double alpha,
int batch_size, int num_input, int num_output,
int num_hidden, size_t* random_idx,
double* output,
uint8_t* target, double* delta_output,
double* delta_w_ho, double* hidden_bias,
double* weight_ho, double* delta_h,
double* delta_w_ih, double* input,
double* delta_w_ih_prev,
double* delta_w_ho_prev,
network_opts_t* opts)
{
int i, j, k, p;
/* Gradient initialization (Nesterov momentum) */
if (opts->optim_type == NESTEROV) {
memcpy(delta_w_ih_prev, delta_w_ih,
sizeof(double) * num_hidden * (num_input + 1));
for (i = 0; i < num_input + 1; ++i) {
for (j = 0; j < num_hidden; ++j) {
delta_w_ih[i * num_hidden + j] *= alpha;
}
}
memcpy(delta_w_ho_prev, delta_w_ho,
sizeof(double) * num_output * (num_hidden + 1));
for (j = 0; j < num_hidden + 1; ++j) {
for (k = 0; k < num_output; ++k) {
delta_w_ho[j * num_output + k] *= alpha;
}
}
}
for (int b = 0; b < batch_size; ++b) {
p = random_idx[(base_index + b)];
/* Backpropagation */
for (k = 0; k < num_output; ++k) {
/* Output gradients */
delta_output[b * num_output + k] =
(output[b * num_output + k] - ((k == target[p])? 1.0: 0.0));
delta_output[b * num_output + k] /= (double) batch_size;
}
}
/* Dot product hidden_bias x delta_output stored in delta_w_ho */
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans,
num_hidden + 1, num_output, batch_size,
1 , hidden_bias, num_hidden + 1,
delta_output, num_output,
(opts->optim_type == NESTEROV)? 1.0: 0.0,
delta_w_ho, num_output);
/* Dot product weight_ho x delta_output (we don't count the bias in
weight_ho) stored in delta_h */
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
batch_size, num_hidden, num_output,
1.0, delta_output, num_output,
&weight_ho[num_output], num_output,
0.0, delta_h, num_hidden);
/* Hidden layer non linearity gradients */
for (int b = 0; b < batch_size; ++b) {
for (j = 0; j < num_hidden; ++j) {
delta_h[b * num_hidden + j] *=
((hidden_bias[b * (num_hidden + 1) + j + 1] > 0) ? 1.0: 0.0);
}
}
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans,
num_input + 1, num_hidden, batch_size,
1 , input, num_input + 1,
delta_h, num_hidden,
(opts->optim_type == NESTEROV)? 1.0: 0.0,
delta_w_ih, num_hidden);
}
double compute_loss(int base_index, int batch_size,
size_t* random_idx,
int num_output, double* output,
uint8_t* target)
{
double batch_error = 0.0;
int p;
for (int b = 0; b < batch_size; ++b) {
p = random_idx[(base_index + b)];
/* Compute loss */
batch_error +=
- log((output[b * num_output + target[p]] > 0) ?
output[b * num_output + target[p]]: DBL_MIN);
}
batch_error /= (double) batch_size;
return batch_error;
}
double compute_fisher(int states, int neighbors,
int num_pattern, int num_output,
int num_hidden, int num_input,
double* input,
double* weight_ih, double* weight_ho)
{
double fisher_information = 0.0;
int base, index, delta;
/* Build the secondary input that will be perturbed */
double* perturbed_input =
(double*) malloc(sizeof(double) * num_pattern * (num_input + 1));
/* Allocate placeholders in the function to make it more
adaptable to the input dataset. */
double* output =
(double*) malloc(sizeof(double) * num_pattern * num_output);
double* output_pert =
(double*) malloc(sizeof(double) * num_pattern * num_output);
double* hidden =
(double*) malloc(sizeof(double) * num_pattern * num_hidden);
double* hidden_bias =
(double*) malloc(sizeof(double) * num_pattern * (num_hidden + 1));
/* Compute the output of the network on the base dataset */
forward(input, output, num_hidden, num_pattern, num_input, num_output,
hidden, hidden_bias, weight_ih, weight_ho);
for (int n = 0; n < AVERAGE_FISHER; ++n) {
for (int neighbor_n = 0; neighbor_n < neighbors; ++neighbor_n) {
/* Perturb second input */
memcpy(perturbed_input, input,
sizeof(double) * num_pattern * (num_input + 1));
for (int i = 0; i < num_pattern; ++i) {
/* Choose index of the input cell to perturb */
index = i * (num_input + 1) + neighbor_n * states;
for (int t = 0; t < states; ++t) {
base = 1 + (rand() % (states - 1));
perturbed_input[index + ((base + t) % states)] =
input[index + t];
}
}
/* Compute the output of the network on the perturbed dataset */
forward(perturbed_input, output_pert, num_hidden, num_pattern,
num_input, num_output, hidden, hidden_bias, weight_ih, weight_ho);
for (int i = 0; i < num_pattern; ++i) {
for (int j = 0; j < num_output; ++j) {
if (output_pert[i * num_output + j] > 0
&& output[i * num_output + j] > 0) {
delta = log(output[i * num_output + j]
/ output_pert[i * num_output + j]);
fisher_information += output[i * num_output + j]
* delta * delta;
}
}
}
}
}
free(output);
free(hidden);
free(hidden_bias);
free(perturbed_input);
free(output_pert);
return fisher_information / (AVERAGE_FISHER * num_pattern);
}
double compute_error(int num_pattern, int num_output,
int num_hidden, int num_input,
double* input, uint8_t* target,
double* weight_ih, double* weight_ho)
{
double test_error = 0.0;
double val;
/* Allocate placeholders in the function to make it more
adaptable to the input dataset. */
double* output =
(double*) malloc(sizeof(double) * num_pattern * num_output);
double* hidden =
(double*) malloc(sizeof(double) * num_pattern * num_hidden);
double* hidden_bias =
(double*) malloc(sizeof(double) * num_pattern * (num_hidden + 1));
/* Compute the output of the network */
forward(input, output, num_hidden, num_pattern, num_input, num_output,
hidden, hidden_bias, weight_ih, weight_ho);
/* Compute loss */
for (int p = 0; p < num_pattern; ++p) {
val = output[p * num_output + target[p]];
test_error += - log((val > 0) ? val: DBL_MIN);
}
test_error /= num_pattern;
free(output);
free(hidden);
free(hidden_bias);
return test_error;
}
void train_nn_on_automaton(size_t size, int states,
uint8_t* train_automaton,
uint8_t** test_automata,
int n_tests,
network_opts_t* opts,
network_result_t* res)
{
if (opts->verbosity >= 1) {
fprintf(stdout, "\nProcessing with options: h%i r%i e%i\n",
opts->num_hid, opts->offset, opts->max_epoch);
}
size_t num_pattern = size * size;
int side = 2 * opts->offset + 1;
int num_input = states * (side * side - 1);
int num_hidden = opts->num_hid;
int num_output = states;
double batch_error, error, eta = 1, alpha = 0.9;
if (opts->optim_type != NESTEROV) {
alpha = 0.;
}
const int batch_size = 8;
/* Regression parameter */
double reg = 0.;
/* ====== Network and training variables declaration ====== */
/* num_pattern x (num_input + 1) array that holds all the training set */
double* base_input =
(double *) malloc(num_pattern * (num_input + 1) * sizeof(double));
/* Array that holds the training labels */
uint8_t* target = (uint8_t *) malloc(num_pattern * sizeof(uint8_t));
/* Fill those arrays with the automaton's content */
fill_input_target(size, base_input, target,
train_automaton, opts->offset, states);
/* Arrays for the test data */
double* test_input =
(double *) malloc(num_pattern * (num_input + 1) * sizeof(double));
uint8_t* test_target = (uint8_t *) malloc(num_pattern * sizeof(uint8_t));
/* Weights of the network */
double weight_ih[(num_input + 1) * num_hidden];
double weight_ho[(num_hidden + 1) * num_output];
/* Gradients of the output and hidden layer placeholders */
double delta_output[batch_size * num_output];
double delta_h[batch_size * num_hidden];
/* Weight gradients and previous gradients for Nesterov momentum */
double delta_w_ih[(num_input + 1) * num_hidden];
double delta_w_ho[(num_input + 1) * num_hidden];
double* delta_w_ih_prev = NULL;
double* delta_w_ho_prev = NULL;
/* Allocate only if being used later */
if (opts->optim_type == NESTEROV) {
delta_w_ih_prev = malloc(sizeof(double) * (num_input + 1) * num_hidden);
delta_w_ho_prev = malloc(sizeof(double) * (num_hidden + 1) * num_output);
}
/* Allocate the arrays that will hold data for each batch */
double input[(batch_size) * (num_input + 1)];
double hidden[batch_size * num_hidden];
double hidden_bias[batch_size * (num_hidden + 1)];
double output[batch_size * num_output];
int epoch;
size_t random_idx[num_pattern];
double test_error = 0.0;
double test_var = 0.0;
/* ===================== End declarations ====================== */
/* Initialize the weights of the network */
init_weights(num_hidden, num_input, num_output,
delta_w_ih, weight_ih,
delta_w_ho, weight_ho);
for (epoch = 0; epoch < opts->max_epoch; ++epoch) {
/* Initialize error */
error = 0.0;
/* Learning rate decay */
if (epoch > 0 && epoch%10 == 0 && opts->decay == DECAY) {
eta -= .5 * eta;
}
/* Random ordering of input patterns done at each epoch */
shuffle_index(num_pattern, random_idx);
/* Loop through every batch in the dataset */
for (size_t s = 0; s < num_pattern; s += batch_size) {
for (int b = 0; b < batch_size; ++b) {
if (s + b >= num_pattern) {
break;
}
/* Copy batch elements to the input array for processing */
memcpy(input + b * (num_input + 1),
base_input + (random_idx[(s + b)] *
(num_input + 1)),
sizeof(double) * (num_input + 1));
}
/* Forward pass */
forward(input, output, num_hidden, batch_size, num_input, num_output,
hidden, hidden_bias, weight_ih, weight_ho);
batch_error = compute_loss(s, batch_size, random_idx, num_output,
output, target);
/* Compute the gradients for each weight matrix */
compute_batch_gradients(s, alpha, batch_size, num_input, num_output,
num_hidden,
random_idx, output, target,
delta_output, delta_w_ho, hidden_bias, weight_ho,
delta_h, delta_w_ih, input,
delta_w_ih_prev, delta_w_ho_prev, opts);
/* Update the weights of the network */
update_weights(num_input, num_hidden, num_output, eta, &batch_error, reg,
alpha, weight_ih, delta_w_ih, delta_w_ih_prev, weight_ho,
delta_w_ho, delta_w_ho_prev);
/* Error is only updated here because it might have been changed by
`update_weights` */
error += batch_error * batch_size;
}
error /= (double)(num_pattern);
if (opts-> verbosity >= 1 && epoch%5 == 0) {
fprintf(stdout, "\nEpoch %d: Error = %f", epoch, error);
}
}
/* Compute error on the training set */
error = compute_error(num_pattern, num_output, num_hidden,
num_input, base_input, target,
weight_ih, weight_ho);
if (opts->verbosity >= 1) {
fprintf(stdout, "\nTrain error: %f", error);
}
/* Compute Fisher information if the flag requires it */
if (opts->fisher == FISHER) {
res->fisher_info = compute_fisher(states, (side*side - 1), num_pattern,
num_output, num_hidden, num_input,
base_input, weight_ih, weight_ho);
}
/* Was an array of states to test on provided ? */
if (test_automata != NULL) {
double test_errors[n_tests];
for (int i = 0; i < n_tests; ++i) {
/* Fill the placeholders with test data */
fill_input_target(size, test_input, test_target,
test_automata[i], opts->offset, states);
/* Compute error on the test set */
test_errors[i] = compute_error(num_pattern, num_output, num_hidden,
num_input, test_input, test_target,
weight_ih, weight_ho);
test_error += error / test_errors[i];
}
/* Average score across all tested states */
test_error /= n_tests;
/* Compute variance of scores */
for (int i = 0; i < n_tests; ++i) {
test_var += (error / test_errors[i] - test_error)
* (error / test_errors[i] - test_error);
}
test_var /= n_tests;
test_var = sqrt(test_var);
if (opts->verbosity >= 1) {
fprintf(stdout, "\tTest error: %f\tVar: %f\tRatio: %f",
error / test_error, test_var, test_error);
}
}
/* Log results */
if (opts->verbosity >= 1 && opts->fisher== FISHER) {
fprintf(stdout, "\tFisher: %f\n", res->fisher_info);
} else if (opts->verbosity >= 1){
fprintf(stdout, "\n");
}
/* Output data */
res->train_error = error;
res->test_error = error / test_error;
res->error_var = test_var;
/* Cleanup allocated arrays */
free(target);
free(base_input);
free(test_input);
free(test_target);
free(delta_w_ih_prev);
free(delta_w_ho_prev);
}
| {
"alphanum_fraction": 0.5625841832,
"avg_line_length": 32.2294573643,
"ext": "c",
"hexsha": "5ca10152159a91c3981587801bea7f96410044ee",
"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": "7e877c917f83bdd5032959205564ca06928b1a6c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "smearle/evolving-structures-in-complex-systems",
"max_forks_repo_path": "src/nn/nn.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7e877c917f83bdd5032959205564ca06928b1a6c",
"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": "smearle/evolving-structures-in-complex-systems",
"max_issues_repo_path": "src/nn/nn.c",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "7e877c917f83bdd5032959205564ca06928b1a6c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "smearle/evolving-structures-in-complex-systems",
"max_stars_repo_path": "src/nn/nn.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-12T05:38:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-12T05:38:21.000Z",
"num_tokens": 5759,
"size": 20788
} |
////////////////////////////////////////////////////////////
//
// Copyright (c) 2018 Sir Ementaler
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
////////////////////////////////////////////////////////////
#ifndef PICTOLEV_BINARY_SERIALIZATION_H
#define PICTOLEV_BINARY_SERIALIZATION_H
#include <algorithm>
#include <iterator>
#include <limits>
#include <ostream>
#include <type_traits>
#include <gsl/gsl_util>
enum class endian {
#ifdef _WIN32
little = 0,
big = 1,
native = little
#else
little = __ORDER_LITTLE_ENDIAN__,
big = __ORDER_BIG_ENDIAN__,
native = __BYTE_ORDER__
#endif
};
template<std::size_t N>
void write_buffer(std::ostream& stream, const char (&buffer)[N]) {
stream.write(buffer, N);
}
template<endian Endian = endian::native, typename T>
std::enable_if_t<std::is_integral_v<T> && (sizeof(T) == 1)>
write_binary(std::ostream& stream, T value) {
stream.put(value);
}
template<endian Endian, typename T>
std::enable_if_t<std::is_integral_v<T> && (sizeof(T) > 1)>
write_binary(std::ostream& stream, T value) {
static_assert(Endian == endian::little || Endian == endian::big);
std::make_unsigned_t<T> u_value = value;
const auto generator = [&u_value]() {
const char result = gsl::narrow_cast<unsigned char>(u_value);
u_value >>= std::numeric_limits<unsigned char>::digits;
return result;
};
char buffer[sizeof(T)] {};
if constexpr (Endian == endian::little)
std::generate(std::begin(buffer), std::end(buffer), generator);
else
std::generate(std::rbegin(buffer), std::rend(buffer), generator);
write_buffer(stream, buffer);
}
#endif
| {
"alphanum_fraction": 0.7050938338,
"avg_line_length": 33.9090909091,
"ext": "h",
"hexsha": "0db140f09f7a69468db29c3bad1fb40619e18171",
"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": "2319122aef4827e0b81294f5177f6f6de08a506c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SirEmentaler/PicToLev",
"max_forks_repo_path": "PicToLev/include/binary_serialization.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2319122aef4827e0b81294f5177f6f6de08a506c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SirEmentaler/PicToLev",
"max_issues_repo_path": "PicToLev/include/binary_serialization.h",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2319122aef4827e0b81294f5177f6f6de08a506c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SirEmentaler/PicToLev",
"max_stars_repo_path": "PicToLev/include/binary_serialization.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 602,
"size": 2611
} |
/////////////////////////////////////////////////////////////////////////////////
//
// Solution of linear systems involved in the Levenberg - Marquardt
// minimization algorithm
// Copyright (C) 2004 Manolis Lourakis (lourakis at ics forth gr)
// Institute of Computer Science, Foundation for Research & Technology - Hellas
// Heraklion, Crete, Greece.
//
// 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.
//
/////////////////////////////////////////////////////////////////////////////////
/* Solvers for the linear systems Ax=b. Solvers should NOT modify their A & B arguments! */
#ifndef LM_REAL // not included by Axb.c
#error This file should not be compiled directly!
#endif
#ifdef LINSOLVERS_RETAIN_MEMORY
#define __STATIC__ static
#else
#define __STATIC__ // empty
#endif /* LINSOLVERS_RETAIN_MEMORY */
#ifdef HAVE_LAPACK
/* prototypes of LAPACK routines */
#define GEQRF LM_MK_LAPACK_NAME(geqrf)
#define ORGQR LM_MK_LAPACK_NAME(orgqr)
#define TRTRS LM_MK_LAPACK_NAME(trtrs)
#define POTF2 LM_MK_LAPACK_NAME(potf2)
#define POTRF LM_MK_LAPACK_NAME(potrf)
#define POTRS LM_MK_LAPACK_NAME(potrs)
#define GETRF LM_MK_LAPACK_NAME(getrf)
#define GETRS LM_MK_LAPACK_NAME(getrs)
#define GESVD LM_MK_LAPACK_NAME(gesvd)
#define GESDD LM_MK_LAPACK_NAME(gesdd)
#define SYTRF LM_MK_LAPACK_NAME(sytrf)
#define SYTRS LM_MK_LAPACK_NAME(sytrs)
#define PLASMA_POSV LM_CAT_(PLASMA_, LM_ADD_PREFIX(posv))
#ifdef __cplusplus
extern "C" {
#endif
/* QR decomposition */
extern int GEQRF(int *m, int *n, LM_REAL *a, int *lda, LM_REAL *tau, LM_REAL *work, int *lwork, int *info);
extern int ORGQR(int *m, int *n, int *k, LM_REAL *a, int *lda, LM_REAL *tau, LM_REAL *work, int *lwork, int *info);
/* solution of triangular systems */
extern int TRTRS(char *uplo, char *trans, char *diag, int *n, int *nrhs, LM_REAL *a, int *lda, LM_REAL *b, int *ldb, int *info);
/* Cholesky decomposition and systems solution */
extern int POTF2(char *uplo, int *n, LM_REAL *a, int *lda, int *info);
extern int POTRF(char *uplo, int *n, LM_REAL *a, int *lda, int *info); /* block version of dpotf2 */
extern int POTRS(char *uplo, int *n, int *nrhs, LM_REAL *a, int *lda, LM_REAL *b, int *ldb, int *info);
/* LU decomposition and systems solution */
extern int GETRF(int *m, int *n, LM_REAL *a, int *lda, int *ipiv, int *info);
extern int GETRS(char *trans, int *n, int *nrhs, LM_REAL *a, int *lda, int *ipiv, LM_REAL *b, int *ldb, int *info);
/* Singular Value Decomposition (SVD) */
extern int GESVD(char *jobu, char *jobvt, int *m, int *n, LM_REAL *a, int *lda, LM_REAL *s, LM_REAL *u, int *ldu,
LM_REAL *vt, int *ldvt, LM_REAL *work, int *lwork, int *info);
/* lapack 3.0 new SVD routine, faster than xgesvd().
* In case that your version of LAPACK does not include them, use the above two older routines
*/
extern int GESDD(char *jobz, int *m, int *n, LM_REAL *a, int *lda, LM_REAL *s, LM_REAL *u, int *ldu, LM_REAL *vt, int *ldvt,
LM_REAL *work, int *lwork, int *iwork, int *info);
/* LDLt/UDUt factorization and systems solution */
extern int SYTRF(char *uplo, int *n, LM_REAL *a, int *lda, int *ipiv, LM_REAL *work, int *lwork, int *info);
extern int SYTRS(char *uplo, int *n, int *nrhs, LM_REAL *a, int *lda, int *ipiv, LM_REAL *b, int *ldb, int *info);
#ifdef __cplusplus
}
#endif
/* precision-specific definitions */
#define AX_EQ_B_QR LM_ADD_PREFIX(Ax_eq_b_QR)
#define AX_EQ_B_QRLS LM_ADD_PREFIX(Ax_eq_b_QRLS)
#define AX_EQ_B_CHOL LM_ADD_PREFIX(Ax_eq_b_Chol)
#define AX_EQ_B_LU LM_ADD_PREFIX(Ax_eq_b_LU)
#define AX_EQ_B_SVD LM_ADD_PREFIX(Ax_eq_b_SVD)
#define AX_EQ_B_BK LM_ADD_PREFIX(Ax_eq_b_BK)
#define AX_EQ_B_PLASMA_CHOL LM_ADD_PREFIX(Ax_eq_b_PLASMA_Chol)
/*
* This function returns the solution of Ax = b
*
* The function is based on QR decomposition with explicit computation of Q:
* If A=Q R with Q orthogonal and R upper triangular, the linear system becomes
* Q R x = b or R x = Q^T b.
* The last equation can be solved directly.
*
* A is mxm, b is mx1
*
* The function returns 0 in case of error, 1 if successful
*
* This function is often called repetitively to solve problems of identical
* dimensions. To avoid repetitive malloc's and free's, allocated memory is
* retained between calls and free'd-malloc'ed when not of the appropriate size.
* A call with NULL as the first argument forces this memory to be released.
*/
int AX_EQ_B_QR(LM_REAL *A, LM_REAL *B, LM_REAL *x, int m)
{
__STATIC__ LM_REAL *buf=NULL;
__STATIC__ int buf_sz=0;
static int nb=0; /* no __STATIC__ decl. here! */
LM_REAL *a, *tau, *r, *work;
int a_sz, tau_sz, r_sz, tot_sz;
register int i, j;
int info, worksz, nrhs=1;
register LM_REAL sum;
if(!A)
#ifdef LINSOLVERS_RETAIN_MEMORY
{
if(buf) free(buf);
buf=NULL;
buf_sz=0;
return 1;
}
#else
return 1; /* NOP */
#endif /* LINSOLVERS_RETAIN_MEMORY */
/* calculate required memory size */
a_sz=m*m;
tau_sz=m;
r_sz=m*m; /* only the upper triangular part really needed */
if(!nb){
LM_REAL tmp;
worksz=-1; // workspace query; optimal size is returned in tmp
GEQRF((int *)&m, (int *)&m, NULL, (int *)&m, NULL, (LM_REAL *)&tmp, (int *)&worksz, (int *)&info);
nb=((int)tmp)/m; // optimal worksize is m*nb
}
worksz=nb*m;
tot_sz=a_sz + tau_sz + r_sz + worksz;
#ifdef LINSOLVERS_RETAIN_MEMORY
if(tot_sz>buf_sz){ /* insufficient memory, allocate a "big" memory chunk at once */
if(buf) free(buf); /* free previously allocated memory */
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_QR) "() failed!\n");
exit(1);
}
}
#else
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_QR) "() failed!\n");
exit(1);
}
#endif /* LINSOLVERS_RETAIN_MEMORY */
a=buf;
tau=a+a_sz;
r=tau+tau_sz;
work=r+r_sz;
/* store A (column major!) into a */
for(i=0; i<m; i++)
for(j=0; j<m; j++)
a[i+j*m]=A[i*m+j];
/* QR decomposition of A */
GEQRF((int *)&m, (int *)&m, a, (int *)&m, tau, work, (int *)&worksz, (int *)&info);
/* error treatment */
if(info!=0){
if(info<0){
printf(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", GEQRF) " in ", AX_EQ_B_QR) "()\n", -info);
exit(1);
}
else{
printf(RCAT(RCAT("Unknown LAPACK error %d for ", GEQRF) " in ", AX_EQ_B_QR) "()\n", info);
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
/* R is stored in the upper triangular part of a; copy it in r so that ORGQR() below won't destroy it */
memcpy(r, a, r_sz*sizeof(LM_REAL));
/* compute Q using the elementary reflectors computed by the above decomposition */
ORGQR((int *)&m, (int *)&m, (int *)&m, a, (int *)&m, tau, work, (int *)&worksz, (int *)&info);
if(info!=0){
if(info<0){
printf(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", ORGQR) " in ", AX_EQ_B_QR) "()\n", -info);
exit(1);
}
else{
printf(RCAT("Unknown LAPACK error (%d) in ", AX_EQ_B_QR) "()\n", info);
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
/* Q is now in a; compute Q^T b in x */
for(i=0; i<m; i++){
for(j=0, sum=0.0; j<m; j++)
sum+=a[i*m+j]*B[j];
x[i]=sum;
}
/* solve the linear system R x = Q^t b */
TRTRS("U", "N", "N", (int *)&m, (int *)&nrhs, r, (int *)&m, x, (int *)&m, &info);
/* error treatment */
if(info!=0){
if(info<0){
printf(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", TRTRS) " in ", AX_EQ_B_QR) "()\n", -info);
exit(1);
}
else{
printf(RCAT("LAPACK error: the %d-th diagonal element of A is zero (singular matrix) in ", AX_EQ_B_QR) "()\n", info);
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 1;
}
/*
* This function returns the solution of min_x ||Ax - b||
*
* || . || is the second order (i.e. L2) norm. This is a least squares technique that
* is based on QR decomposition:
* If A=Q R with Q orthogonal and R upper triangular, the normal equations become
* (A^T A) x = A^T b or (R^T Q^T Q R) x = A^T b or (R^T R) x = A^T b.
* This amounts to solving R^T y = A^T b for y and then R x = y for x
* Note that Q does not need to be explicitly computed
*
* A is mxn, b is mx1
*
* The function returns 0 in case of error, 1 if successful
*
* This function is often called repetitively to solve problems of identical
* dimensions. To avoid repetitive malloc's and free's, allocated memory is
* retained between calls and free'd-malloc'ed when not of the appropriate size.
* A call with NULL as the first argument forces this memory to be released.
*/
int AX_EQ_B_QRLS(LM_REAL *A, LM_REAL *B, LM_REAL *x, int m, int n)
{
__STATIC__ LM_REAL *buf=NULL;
__STATIC__ int buf_sz=0;
static int nb=0; /* no __STATIC__ decl. here! */
LM_REAL *a, *tau, *r, *work;
int a_sz, tau_sz, r_sz, tot_sz;
register int i, j;
int info, worksz, nrhs=1;
register LM_REAL sum;
if(!A)
#ifdef LINSOLVERS_RETAIN_MEMORY
{
if(buf) free(buf);
buf=NULL;
buf_sz=0;
return 1;
}
#else
return 1; /* NOP */
#endif /* LINSOLVERS_RETAIN_MEMORY */
if(m<n){
printf(RCAT("Normal equations require that the number of rows is greater than number of columns in ", AX_EQ_B_QRLS) "() [%d x %d]! -- try transposing\n", m, n);
exit(1);
}
/* calculate required memory size */
a_sz=m*n;
tau_sz=n;
r_sz=n*n;
if(!nb){
LM_REAL tmp;
worksz=-1; // workspace query; optimal size is returned in tmp
GEQRF((int *)&m, (int *)&m, NULL, (int *)&m, NULL, (LM_REAL *)&tmp, (int *)&worksz, (int *)&info);
nb=((int)tmp)/m; // optimal worksize is m*nb
}
worksz=nb*m;
tot_sz=a_sz + tau_sz + r_sz + worksz;
#ifdef LINSOLVERS_RETAIN_MEMORY
if(tot_sz>buf_sz){ /* insufficient memory, allocate a "big" memory chunk at once */
if(buf) free(buf); /* free previously allocated memory */
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_QRLS) "() failed!\n");
exit(1);
}
}
#else
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_QRLS) "() failed!\n");
exit(1);
}
#endif /* LINSOLVERS_RETAIN_MEMORY */
a=buf;
tau=a+a_sz;
r=tau+tau_sz;
work=r+r_sz;
/* store A (column major!) into a */
for(i=0; i<m; i++)
for(j=0; j<n; j++)
a[i+j*m]=A[i*n+j];
/* compute A^T b in x */
for(i=0; i<n; i++){
for(j=0, sum=0.0; j<m; j++)
sum+=A[j*n+i]*B[j];
x[i]=sum;
}
/* QR decomposition of A */
GEQRF((int *)&m, (int *)&n, a, (int *)&m, tau, work, (int *)&worksz, (int *)&info);
/* error treatment */
if(info!=0){
if(info<0){
printf(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", GEQRF) " in ", AX_EQ_B_QRLS) "()\n", -info);
exit(1);
}
else{
printf(RCAT(RCAT("Unknown LAPACK error %d for ", GEQRF) " in ", AX_EQ_B_QRLS) "()\n", info);
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
/* R is stored in the upper triangular part of a. Note that a is mxn while r nxn */
for(j=0; j<n; j++){
for(i=0; i<=j; i++)
r[i+j*n]=a[i+j*m];
/* lower part is zero */
for(i=j+1; i<n; i++)
r[i+j*n]=0.0;
}
/* solve the linear system R^T y = A^t b */
TRTRS("U", "T", "N", (int *)&n, (int *)&nrhs, r, (int *)&n, x, (int *)&n, &info);
/* error treatment */
if(info!=0){
if(info<0){
printf(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", TRTRS) " in ", AX_EQ_B_QRLS) "()\n", -info);
exit(1);
}
else{
printf(RCAT("LAPACK error: the %d-th diagonal element of A is zero (singular matrix) in ", AX_EQ_B_QRLS) "()\n", info);
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
/* solve the linear system R x = y */
TRTRS("U", "N", "N", (int *)&n, (int *)&nrhs, r, (int *)&n, x, (int *)&n, &info);
/* error treatment */
if(info!=0){
if(info<0){
printf(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", TRTRS) " in ", AX_EQ_B_QRLS) "()\n", -info);
exit(1);
}
else{
printf(RCAT("LAPACK error: the %d-th diagonal element of A is zero (singular matrix) in ", AX_EQ_B_QRLS) "()\n", info);
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 1;
}
/*
* This function returns the solution of Ax=b
*
* The function assumes that A is symmetric & postive definite and employs
* the Cholesky decomposition:
* If A=L L^T with L lower triangular, the system to be solved becomes
* (L L^T) x = b
* This amounts to solving L y = b for y and then L^T x = y for x
*
* A is mxm, b is mx1
*
* The function returns 0 in case of error, 1 if successful
*
* This function is often called repetitively to solve problems of identical
* dimensions. To avoid repetitive malloc's and free's, allocated memory is
* retained between calls and free'd-malloc'ed when not of the appropriate size.
* A call with NULL as the first argument forces this memory to be released.
*/
int AX_EQ_B_CHOL(LM_REAL *A, LM_REAL *B, LM_REAL *x, int m)
{
__STATIC__ LM_REAL *buf=NULL;
__STATIC__ int buf_sz=0;
LM_REAL *a;
int a_sz, tot_sz;
int info, nrhs=1;
if(!A)
#ifdef LINSOLVERS_RETAIN_MEMORY
{
if(buf) free(buf);
buf=NULL;
buf_sz=0;
return 1;
}
#else
return 1; /* NOP */
#endif /* LINSOLVERS_RETAIN_MEMORY */
/* calculate required memory size */
a_sz=m*m;
tot_sz=a_sz;
#ifdef LINSOLVERS_RETAIN_MEMORY
if(tot_sz>buf_sz){ /* insufficient memory, allocate a "big" memory chunk at once */
if(buf) free(buf); /* free previously allocated memory */
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_CHOL) "() failed!\n");
exit(1);
}
}
#else
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_CHOL) "() failed!\n");
exit(1);
}
#endif /* LINSOLVERS_RETAIN_MEMORY */
a=buf;
/* store A into a and B into x. A is assumed symmetric,
* hence no transposition is needed
*/
memcpy(a, A, a_sz*sizeof(LM_REAL));
memcpy(x, B, m*sizeof(LM_REAL));
/* Cholesky decomposition of A */
//POTF2("L", (int *)&m, a, (int *)&m, (int *)&info);
POTRF("L", (int *)&m, a, (int *)&m, (int *)&info);
/* error treatment */
if(info!=0){
if(info<0){
printf(RCAT(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", POTF2) "/", POTRF) " in ",
AX_EQ_B_CHOL) "()\n", -info);
exit(1);
}
else{
printf(RCAT(RCAT(RCAT("LAPACK error: the leading minor of order %d is not positive definite,\nthe factorization could not be completed for ", POTF2) "/", POTRF) " in ", AX_EQ_B_CHOL) "()\n", info);
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
/* solve using the computed Cholesky in one lapack call */
POTRS("L", (int *)&m, (int *)&nrhs, a, (int *)&m, x, (int *)&m, &info);
if(info<0){
printf(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", POTRS) " in ", AX_EQ_B_CHOL) "()\n", -info);
exit(1);
}
#if 0
/* alternative: solve the linear system L y = b ... */
TRTRS("L", "N", "N", (int *)&m, (int *)&nrhs, a, (int *)&m, x, (int *)&m, &info);
/* error treatment */
if(info!=0){
if(info<0){
printf(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", TRTRS) " in ", AX_EQ_B_CHOL) "()\n", -info);
exit(1);
}
else{
printf(RCAT("LAPACK error: the %d-th diagonal element of A is zero (singular matrix) in ", AX_EQ_B_CHOL) "()\n", info);
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
/* ... solve the linear system L^T x = y */
TRTRS("L", "T", "N", (int *)&m, (int *)&nrhs, a, (int *)&m, x, (int *)&m, &info);
/* error treatment */
if(info!=0){
if(info<0){
printf(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", TRTRS) "in ", AX_EQ_B_CHOL) "()\n", -info);
exit(1);
}
else{
printf(RCAT("LAPACK error: the %d-th diagonal element of A is zero (singular matrix) in ", AX_EQ_B_CHOL) "()\n", info);
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
#endif /* 0 */
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 1;
}
#ifdef HAVE_PLASMA
/* Linear algebra using PLASMA parallel library for multicore CPUs.
* http://icl.cs.utk.edu/plasma/
*
* WARNING: BLAS multithreading should be disabled, e.g. setenv MKL_NUM_THREADS 1
*/
#ifndef _LM_PLASMA_MISC_
/* avoid multiple inclusion of helper code */
#define _LM_PLASMA_MISC_
#include <plasma.h>
#include <cblas.h>
#include <lapacke.h>
#include <plasma_tmg.h>
#include <core_blas.h>
/* programmatically determine the number of cores on the current machine */
#ifdef _WIN32
#include <windows.h>
#elif __linux
#include <unistd.h>
#endif
static int getnbcores()
{
#ifdef _WIN32
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
#elif __linux
return sysconf(_SC_NPROCESSORS_ONLN);
#else // unknown system
return 2<<1; // will be halved by right shift below
#endif
}
static int PLASMA_ncores=-(getnbcores()>>1); // >0 if PLASMA initialized, <0 otherwise
/* user-specified number of cores */
void levmar_PLASMA_setnbcores(int cores)
{
PLASMA_ncores=(cores>0)? -cores : ((cores)? cores : -2);
}
#endif /* _LM_PLASMA_MISC_ */
/*
* This function returns the solution of Ax=b
*
* The function assumes that A is symmetric & positive definite and employs the
* Cholesky decomposition implemented by PLASMA for homogeneous multicore processors.
*
* A is mxm, b is mx1
*
* The function returns 0 in case of error, 1 if successfull
*
* This function is often called repetitively to solve problems of identical
* dimensions. To avoid repetitive malloc's and free's, allocated memory is
* retained between calls and free'd-malloc'ed when not of the appropriate size.
* A call with NULL as the first argument forces this memory to be released.
*/
int AX_EQ_B_PLASMA_CHOL(LM_REAL *A, LM_REAL *B, LM_REAL *x, int m)
{
__STATIC__ LM_REAL *buf=NULL;
__STATIC__ int buf_sz=0;
LM_REAL *a;
int a_sz, tot_sz;
int info, nrhs=1;
if(A==NULL){
#ifdef LINSOLVERS_RETAIN_MEMORY
if(buf) free(buf);
buf=NULL;
buf_sz=0;
#endif /* LINSOLVERS_RETAIN_MEMORY */
PLASMA_Finalize();
PLASMA_ncores=-PLASMA_ncores;
return 1;
}
/* calculate required memory size */
a_sz=m*m;
tot_sz=a_sz;
#ifdef LINSOLVERS_RETAIN_MEMORY
if(tot_sz>buf_sz){ /* insufficient memory, allocate a "big" memory chunk at once */
if(buf) free(buf); /* free previously allocated memory */
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_PLASMA_CHOL) "() failed!\n");
exit(1);
}
}
#else
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_PLASMA_CHOL) "() failed!\n");
exit(1);
}
#endif /* LINSOLVERS_RETAIN_MEMORY */
a=buf;
/* store A into a and B into x; A is assumed to be symmetric,
* hence no transposition is needed
*/
memcpy(a, A, a_sz*sizeof(LM_REAL));
memcpy(x, B, m*sizeof(LM_REAL));
/* initialize PLASMA */
if(PLASMA_ncores<0){
PLASMA_ncores=-PLASMA_ncores;
PLASMA_Init(PLASMA_ncores);
printf(RCAT("\n", AX_EQ_B_PLASMA_CHOL) "(): PLASMA is running on %d cores.\n\n", PLASMA_ncores);
}
/* Solve the linear system */
info=PLASMA_POSV(PlasmaLower, m, 1, a, m, x, m);
/* error treatment */
if(info!=0){
if(info<0){
printf(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", PLASMA_POSV) " in ",
AX_EQ_B_PLASMA_CHOL) "()\n", -info);
exit(1);
}
else{
printf(RCAT(RCAT("LAPACK error: the leading minor of order %d is not positive definite,\n"
"the factorization could not be completed for ", PLASMA_POSV) " in ", AX_EQ_B_CHOL) "()\n", info);
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 1;
}
#endif /* HAVE_PLASMA */
/*
* This function returns the solution of Ax = b
*
* The function employs LU decomposition:
* If A=L U with L lower and U upper triangular, then the original system
* amounts to solving
* L y = b, U x = y
*
* A is mxm, b is mx1
*
* The function returns 0 in case of error, 1 if successful
*
* This function is often called repetitively to solve problems of identical
* dimensions. To avoid repetitive malloc's and free's, allocated memory is
* retained between calls and free'd-malloc'ed when not of the appropriate size.
* A call with NULL as the first argument forces this memory to be released.
*/
int AX_EQ_B_LU(LM_REAL *A, LM_REAL *B, LM_REAL *x, int m)
{
__STATIC__ LM_REAL *buf=NULL;
__STATIC__ int buf_sz=0;
int a_sz, ipiv_sz, tot_sz;
register int i, j;
int info, *ipiv, nrhs=1;
LM_REAL *a;
if(!A)
#ifdef LINSOLVERS_RETAIN_MEMORY
{
if(buf) free(buf);
buf=NULL;
buf_sz=0;
return 1;
}
#else
return 1; /* NOP */
#endif /* LINSOLVERS_RETAIN_MEMORY */
/* calculate required memory size */
ipiv_sz=m;
a_sz=m*m;
tot_sz=a_sz*sizeof(LM_REAL) + ipiv_sz*sizeof(int); /* should be arranged in that order for proper doubles alignment */
#ifdef LINSOLVERS_RETAIN_MEMORY
if(tot_sz>buf_sz){ /* insufficient memory, allocate a "big" memory chunk at once */
if(buf) free(buf); /* free previously allocated memory */
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz);
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_LU) "() failed!\n");
exit(1);
}
}
#else
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz);
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_LU) "() failed!\n");
exit(1);
}
#endif /* LINSOLVERS_RETAIN_MEMORY */
a=buf;
ipiv=(int *)(a+a_sz);
/* store A (column major!) into a and B into x */
for(i=0; i<m; i++){
for(j=0; j<m; j++)
a[i+j*m]=A[i*m+j];
x[i]=B[i];
}
/* LU decomposition for A */
GETRF((int *)&m, (int *)&m, a, (int *)&m, ipiv, (int *)&info);
if(info!=0){
if(info<0){
printf(RCAT(RCAT("argument %d of ", GETRF) " illegal in ", AX_EQ_B_LU) "()\n", -info);
exit(1);
}
else{
printf(RCAT(RCAT("singular matrix A for ", GETRF) " in ", AX_EQ_B_LU) "()\n");
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
/* solve the system with the computed LU */
GETRS("N", (int *)&m, (int *)&nrhs, a, (int *)&m, ipiv, x, (int *)&m, (int *)&info);
if(info!=0){
if(info<0){
printf(RCAT(RCAT("argument %d of ", GETRS) " illegal in ", AX_EQ_B_LU) "()\n", -info);
exit(1);
}
else{
printf(RCAT(RCAT("unknown error for ", GETRS) " in ", AX_EQ_B_LU) "()\n");
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 1;
}
/*
* This function returns the solution of Ax = b
*
* The function is based on SVD decomposition:
* If A=U D V^T with U, V orthogonal and D diagonal, the linear system becomes
* (U D V^T) x = b or x=V D^{-1} U^T b
* Note that V D^{-1} U^T is the pseudoinverse A^+
*
* A is mxm, b is mx1.
*
* The function returns 0 in case of error, 1 if successful
*
* This function is often called repetitively to solve problems of identical
* dimensions. To avoid repetitive malloc's and free's, allocated memory is
* retained between calls and free'd-malloc'ed when not of the appropriate size.
* A call with NULL as the first argument forces this memory to be released.
*/
int AX_EQ_B_SVD(LM_REAL *A, LM_REAL *B, LM_REAL *x, int m)
{
__STATIC__ LM_REAL *buf=NULL;
__STATIC__ int buf_sz=0;
static LM_REAL eps=LM_CNST(-1.0);
register int i, j;
LM_REAL *a, *u, *s, *vt, *work;
int a_sz, u_sz, s_sz, vt_sz, tot_sz;
LM_REAL thresh, one_over_denom;
register LM_REAL sum;
int info, rank, worksz, *iwork, iworksz;
if(!A)
#ifdef LINSOLVERS_RETAIN_MEMORY
{
if(buf) free(buf);
buf=NULL;
buf_sz=0;
return 1;
}
#else
return 1; /* NOP */
#endif /* LINSOLVERS_RETAIN_MEMORY */
/* calculate required memory size */
#if 1 /* use optimal size */
worksz=-1; // workspace query. Keep in mind that GESDD requires more memory than GESVD
/* note that optimal work size is returned in thresh */
GESVD("A", "A", (int *)&m, (int *)&m, NULL, (int *)&m, NULL, NULL, (int *)&m, NULL, (int *)&m, (LM_REAL *)&thresh, (int *)&worksz, &info);
//GESDD("A", (int *)&m, (int *)&m, NULL, (int *)&m, NULL, NULL, (int *)&m, NULL, (int *)&m, (LM_REAL *)&thresh, (int *)&worksz, NULL, &info);
worksz=(int)thresh;
#else /* use minimum size */
worksz=5*m; // min worksize for GESVD
//worksz=m*(7*m+4); // min worksize for GESDD
#endif
iworksz=8*m;
a_sz=m*m;
u_sz=m*m; s_sz=m; vt_sz=m*m;
tot_sz=(a_sz + u_sz + s_sz + vt_sz + worksz)*sizeof(LM_REAL) + iworksz*sizeof(int); /* should be arranged in that order for proper doubles alignment */
#ifdef LINSOLVERS_RETAIN_MEMORY
if(tot_sz>buf_sz){ /* insufficient memory, allocate a "big" memory chunk at once */
if(buf) free(buf); /* free previously allocated memory */
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz);
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_SVD) "() failed!\n");
exit(1);
}
}
#else
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz);
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_SVD) "() failed!\n");
exit(1);
}
#endif /* LINSOLVERS_RETAIN_MEMORY */
a=buf;
u=a+a_sz;
s=u+u_sz;
vt=s+s_sz;
work=vt+vt_sz;
iwork=(int *)(work+worksz);
/* store A (column major!) into a */
for(i=0; i<m; i++)
for(j=0; j<m; j++)
a[i+j*m]=A[i*m+j];
/* SVD decomposition of A */
GESVD("A", "A", (int *)&m, (int *)&m, a, (int *)&m, s, u, (int *)&m, vt, (int *)&m, work, (int *)&worksz, &info);
//GESDD("A", (int *)&m, (int *)&m, a, (int *)&m, s, u, (int *)&m, vt, (int *)&m, work, (int *)&worksz, iwork, &info);
/* error treatment */
if(info!=0){
if(info<0){
printf(RCAT(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", GESVD), "/" GESDD) " in ", AX_EQ_B_SVD) "()\n", -info);
exit(1);
}
else{
printf(RCAT("LAPACK error: dgesdd (dbdsdc)/dgesvd (dbdsqr) failed to converge in ", AX_EQ_B_SVD) "() [info=%d]\n", info);
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
if(eps<0.0){
LM_REAL aux;
/* compute machine epsilon */
for(eps=LM_CNST(1.0); aux=eps+LM_CNST(1.0), aux-LM_CNST(1.0)>0.0; eps*=LM_CNST(0.5))
;
eps*=LM_CNST(2.0);
}
/* compute the pseudoinverse in a */
for(i=0; i<a_sz; i++) a[i]=0.0; /* initialize to zero */
for(rank=0, thresh=eps*s[0]; rank<m && s[rank]>thresh; rank++){
one_over_denom=LM_CNST(1.0)/s[rank];
for(j=0; j<m; j++)
for(i=0; i<m; i++)
a[i*m+j]+=vt[rank+i*m]*u[j+rank*m]*one_over_denom;
}
/* compute A^+ b in x */
for(i=0; i<m; i++){
for(j=0, sum=0.0; j<m; j++)
sum+=a[i*m+j]*B[j];
x[i]=sum;
}
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 1;
}
/*
* This function returns the solution of Ax = b for a real symmetric matrix A
*
* The function is based on LDLT factorization with the pivoting
* strategy of Bunch and Kaufman:
* A is factored as L*D*L^T where L is lower triangular and
* D symmetric and block diagonal (aka spectral decomposition,
* Banachiewicz factorization, modified Cholesky factorization)
*
* A is mxm, b is mx1.
*
* The function returns 0 in case of error, 1 if successfull
*
* This function is often called repetitively to solve problems of identical
* dimensions. To avoid repetitive malloc's and free's, allocated memory is
* retained between calls and free'd-malloc'ed when not of the appropriate size.
* A call with NULL as the first argument forces this memory to be released.
*/
int AX_EQ_B_BK(LM_REAL *A, LM_REAL *B, LM_REAL *x, int m)
{
__STATIC__ LM_REAL *buf=NULL;
__STATIC__ int buf_sz=0, nb=0;
LM_REAL *a, *work;
int a_sz, ipiv_sz, work_sz, tot_sz;
int info, *ipiv, nrhs=1;
if(!A)
#ifdef LINSOLVERS_RETAIN_MEMORY
{
if(buf) free(buf);
buf=NULL;
buf_sz=0;
return 1;
}
#else
return 1; /* NOP */
#endif /* LINSOLVERS_RETAIN_MEMORY */
/* calculate required memory size */
ipiv_sz=m;
a_sz=m*m;
if(!nb){
LM_REAL tmp;
work_sz=-1; // workspace query; optimal size is returned in tmp
SYTRF("L", (int *)&m, NULL, (int *)&m, NULL, (LM_REAL *)&tmp, (int *)&work_sz, (int *)&info);
nb=((int)tmp)/m; // optimal worksize is m*nb
}
work_sz=(nb!=-1)? nb*m : 1;
tot_sz=(a_sz + work_sz)*sizeof(LM_REAL) + ipiv_sz*sizeof(int); /* should be arranged in that order for proper doubles alignment */
#ifdef LINSOLVERS_RETAIN_MEMORY
if(tot_sz>buf_sz){ /* insufficient memory, allocate a "big" memory chunk at once */
if(buf) free(buf); /* free previously allocated memory */
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz);
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_BK) "() failed!\n");
exit(1);
}
}
#else
buf_sz=tot_sz;
buf=(LM_REAL *)malloc(buf_sz);
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_BK) "() failed!\n");
exit(1);
}
#endif /* LINSOLVERS_RETAIN_MEMORY */
a=buf;
work=a+a_sz;
ipiv=(int *)(work+work_sz);
/* store A into a and B into x; A is assumed to be symmetric, hence
* the column and row major order representations are the same
*/
memcpy(a, A, a_sz*sizeof(LM_REAL));
memcpy(x, B, m*sizeof(LM_REAL));
/* LDLt factorization for A */
SYTRF("L", (int *)&m, a, (int *)&m, ipiv, work, (int *)&work_sz, (int *)&info);
if(info!=0){
if(info<0){
printf(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", SYTRF) " in ", AX_EQ_B_BK) "()\n", -info);
exit(1);
}
else{
printf(RCAT(RCAT("LAPACK error: singular block diagonal matrix D for", SYTRF) " in ", AX_EQ_B_BK)"() [D(%d, %d) is zero]\n", info, info);
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
}
/* solve the system with the computed factorization */
SYTRS("L", (int *)&m, (int *)&nrhs, a, (int *)&m, ipiv, x, (int *)&m, (int *)&info);
if(info<0){
printf(RCAT(RCAT("LAPACK error: illegal value for argument %d of ", SYTRS) " in ", AX_EQ_B_BK) "()\n", -info);
exit(1);
}
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 1;
}
/* undefine all. IT MUST REMAIN IN THIS POSITION IN FILE */
#undef AX_EQ_B_QR
#undef AX_EQ_B_QRLS
#undef AX_EQ_B_CHOL
#undef AX_EQ_B_LU
#undef AX_EQ_B_SVD
#undef AX_EQ_B_BK
#undef AX_EQ_B_PLASMA_CHOL
#undef GEQRF
#undef ORGQR
#undef TRTRS
#undef POTF2
#undef POTRF
#undef POTRS
#undef GETRF
#undef GETRS
#undef GESVD
#undef GESDD
#undef SYTRF
#undef SYTRS
#undef PLASMA_POSV
#else // no LAPACK
/* precision-specific definitions */
#define AX_EQ_B_LU LM_ADD_PREFIX(Ax_eq_b_LU_noLapack)
/*
* This function returns the solution of Ax = b
*
* The function employs LU decomposition followed by forward/back substitution (see
* also the LAPACK-based LU solver above)
*
* A is mxm, b is mx1
*
* The function returns 0 in case of error, 1 if successful
*
* This function is often called repetitively to solve problems of identical
* dimensions. To avoid repetitive malloc's and free's, allocated memory is
* retained between calls and free'd-malloc'ed when not of the appropriate size.
* A call with NULL as the first argument forces this memory to be released.
*/
int AX_EQ_B_LU(LM_REAL *A, LM_REAL *B, LM_REAL *x, int m)
{
__STATIC__ void *buf=NULL;
__STATIC__ int buf_sz=0;
register int i, j, k;
int *idx, maxi=-1, idx_sz, a_sz, work_sz, tot_sz;
LM_REAL *a, *work, max, sum, tmp;
if(!A)
#ifdef LINSOLVERS_RETAIN_MEMORY
{
if(buf) free(buf);
buf=NULL;
buf_sz=0;
return 1;
}
#else
return 1; /* NOP */
#endif /* LINSOLVERS_RETAIN_MEMORY */
/* calculate required memory size */
idx_sz=m;
a_sz=m*m;
work_sz=m;
tot_sz=(a_sz+work_sz)*sizeof(LM_REAL) + idx_sz*sizeof(int); /* should be arranged in that order for proper doubles alignment */
#ifdef LINSOLVERS_RETAIN_MEMORY
if(tot_sz>buf_sz){ /* insufficient memory, allocate a "big" memory chunk at once */
if(buf) free(buf); /* free previously allocated memory */
buf_sz=tot_sz;
buf=(void *)malloc(tot_sz);
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_LU) "() failed!\n");
exit(1);
}
}
#else
buf_sz=tot_sz;
buf=(void *)malloc(tot_sz);
if(!buf){
printf(RCAT("memory allocation in ", AX_EQ_B_LU) "() failed!\n");
exit(1);
}
#endif /* LINSOLVERS_RETAIN_MEMORY */
a=buf;
work=a+a_sz;
idx=(int *)(work+work_sz);
/* avoid destroying A, B by copying them to a, x resp. */
memcpy(a, A, a_sz*sizeof(LM_REAL));
memcpy(x, B, m*sizeof(LM_REAL));
/* compute the LU decomposition of a row permutation of matrix a; the permutation itself is saved in idx[] */
for(i=0; i<m; ++i){
max=0.0;
for(j=0; j<m; ++j)
if((tmp=FABS(a[i*m+j]))>max)
max=tmp;
if(max==0.0){
printf(RCAT("Singular matrix A in ", AX_EQ_B_LU) "()!\n");
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 0;
}
work[i]=LM_CNST(1.0)/max;
}
for(j=0; j<m; ++j){
for(i=0; i<j; ++i){
sum=a[i*m+j];
for(k=0; k<i; ++k)
sum-=a[i*m+k]*a[k*m+j];
a[i*m+j]=sum;
}
max=0.0;
for(i=j; i<m; ++i){
sum=a[i*m+j];
for(k=0; k<j; ++k)
sum-=a[i*m+k]*a[k*m+j];
a[i*m+j]=sum;
if((tmp=work[i]*FABS(sum))>=max){
max=tmp;
maxi=i;
}
}
if(j!=maxi){
for(k=0; k<m; ++k){
tmp=a[maxi*m+k];
a[maxi*m+k]=a[j*m+k];
a[j*m+k]=tmp;
}
work[maxi]=work[j];
}
idx[j]=maxi;
if(a[j*m+j]==0.0)
a[j*m+j]=LM_REAL_EPSILON;
if(j!=m-1){
tmp=LM_CNST(1.0)/(a[j*m+j]);
for(i=j+1; i<m; ++i)
a[i*m+j]*=tmp;
}
}
/* The decomposition has now replaced a. Solve the linear system using
* forward and back substitution
*/
for(i=k=0; i<m; ++i){
j=idx[i];
sum=x[j];
x[j]=x[i];
if(k!=0)
for(j=k-1; j<i; ++j)
sum-=a[i*m+j]*x[j];
else
if(sum!=0.0)
k=i+1;
x[i]=sum;
}
for(i=m-1; i>=0; --i){
sum=x[i];
for(j=i+1; j<m; ++j)
sum-=a[i*m+j]*x[j];
x[i]=sum/a[i*m+i];
}
#ifndef LINSOLVERS_RETAIN_MEMORY
free(buf);
#endif
return 1;
}
/* undefine all. IT MUST REMAIN IN THIS POSITION IN FILE */
#undef AX_EQ_B_LU
#endif /* HAVE_LAPACK */
| {
"alphanum_fraction": 0.6243044736,
"avg_line_length": 28.0155884645,
"ext": "c",
"hexsha": "89ffab0316e5f853ff69f58cf6764c6ddcd2222d",
"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": "ec7ed158a52b872390b57892a678300a710c1ca1",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "jongwonjlee/CLAPACK",
"max_forks_repo_path": "levmar-2.6/Axb_core.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ec7ed158a52b872390b57892a678300a710c1ca1",
"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": "jongwonjlee/CLAPACK",
"max_issues_repo_path": "levmar-2.6/Axb_core.c",
"max_line_length": 203,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ec7ed158a52b872390b57892a678300a710c1ca1",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "jongwonjlee/CLAPACK",
"max_stars_repo_path": "levmar-2.6/Axb_core.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 11265,
"size": 35944
} |
#include <string.h>
#include <math.h>
#include <cblas.h>
#define SWAP(x, y, T) do { T SWAP = x; x = y; y = SWAP; } while (0)
//The Struct that contains the k nearest neighbors of m queries
typedef struct knnresult{
int * nidx; //!< Indices (0-based) of nearest neighbors [m-by-k]
double * ndist; //!< Distance of nearest neighbors [m-by-k]
int m; //!< Number of query points [scalar]
int k; //!< Number of nearest neighbors [scalar]
} knnresult;
//A sorting alogorithm for the k first items of a list
void k_select(int * nidx,
double * ndist,
int k,
int n)
{
for(int i=0; i<k; i++){
int minidx = i;
double min = ndist[i];
for(int j=i+1; j<n; j++){
if(min > ndist[j]){
min = ndist[j];
minidx = nidx[j];
SWAP(ndist[i],ndist[j], double);
SWAP(nidx[i], nidx[j], int);
}
}
}
}
int partition(int * nidx,
double * ndist,
int left,
int right,
int pivot)
{
double val = ndist[pivot];
SWAP(ndist[right], ndist[pivot], double);
SWAP(nidx[right], nidx[pivot], int);
int storeIdx = left;
for(int i=left; i<right; i++){
if(ndist[i] < val){
SWAP(ndist[storeIdx], ndist[i], double);
SWAP(nidx[storeIdx], nidx[i], int);
storeIdx++;
}
}
SWAP(ndist[storeIdx], ndist[right], double);
SWAP(nidx[storeIdx], nidx[right], int);
return storeIdx;
}
void quickselect(int * nidx,
double * ndist,
int left,
int right,
int k)
{
if(left >= right) return;
int pivot = left + rand() % (right - left + 1);
pivot = partition(nidx, ndist, left, right, pivot);
if(k == pivot){
return;
}else if(k< pivot){
quickselect(nidx, ndist, left, pivot - 1, k);
}else{
quickselect(nidx, ndist, pivot + 1, right, k);
}
}
//Calculates a column of the Euclidean distance matrix D
double *calc_Dcol( double *X,
double *Y,
int n,
int d,
int row)
{
double *Dcol= (double *)malloc(n * sizeof(double));
for(int i=0; i<n; i++) Dcol[i] = 0;
for(int i=0; i<n; i++){
for(int k=0; k<d; k++){
Dcol[i] += X[k + i*d]*X[k + i*d] + Y[k + row*d]*Y[k + row*d] - 2*X[k + i*d]*Y[k + row*d];
}
}
return Dcol;
}
//Calculates the Euclidean distance matrix D
double *calc_D( double *X,
double *Y,
int n,
int d,
int m)
{
double *D= (double *)malloc(n * m * sizeof(double));
double xsum[n],
ysum[m];
for(int i=0; i<n; i++) xsum[i] = cblas_ddot(d, X + i*d, 1, X + i*d, 1);
for(int i=0; i<m; i++) ysum[i] = cblas_ddot(d, Y + i*d, 1, Y + i*d, 1);
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n, m, d, -2, X, d, Y, d, 0, D, m);
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
D[j + m*i] += xsum[i] + ysum[j];
}
}
return D;
}
void calc_part_knn( double *D,
int n,
int m,
int k,
int col,
int *final_nidx,
double *final_ndist)
{
int * nidx = (int *)malloc(n * sizeof(int));
double * ndist = (double *)malloc(n * sizeof(double));
for(int i=0; i<n; i++){
nidx[i] = i;
ndist[i] = D[i * m + col];
}
quickselect(nidx, ndist, 0, n-1, k);
memcpy(final_nidx, nidx, k * sizeof(int));
memcpy(final_ndist, ndist, k * sizeof(double));
free(nidx);
free(ndist);
}
//Finds for each point in a query set Y the k nearest neighbors
//in the corpus set X
knnresult kNN( double *X,
double *Y,
int n,
int m,
int d,
int k)
{
knnresult knn;
knn.m = m;
knn.k = k;
knn.nidx = (int *)malloc(m * k * sizeof(int));
knn.ndist = (double *)malloc(m * k * sizeof(double));
int max_m = 1e3;
if(m > max_m){
int iteration_m[m/max_m];
for(int i=0; i<m/max_m; i++) iteration_m[i] = max_m;
iteration_m[m/max_m - 1] = max_m + m%max_m;
int displ = 0;
for(int i=0; i<m/max_m; i++){
double *D = calc_D(X, Y + displ * d, n, d, iteration_m[i]);
for(int j=0; j<iteration_m[i]; j++) calc_part_knn(D, n, iteration_m[i], k, j, knn.nidx + (j + displ) * k, knn.ndist + (j + displ) * k);
free(D);
displ += iteration_m[i];
}
}else{
double *D = calc_D(X, Y, n, d, m);
for(int j=0; j<m; j++) calc_part_knn(D, n, m, k, j, knn.nidx + j * k, knn.ndist + j * k);
free(D);
}
return knn;
}
knnresult alt_kNN( double *X,
double *Y,
int n,
int m,
int d,
int k)
{
knnresult knn;
knn.m = m;
knn.k = k;
knn.nidx = (int *)malloc(m * k * sizeof(int));
knn.ndist = (double *)malloc(m * k * sizeof(double));
for(int j=0; j<m; j++){
double * ndist = calc_Dcol(X, Y, n, d, j);
int * nidx = (int *)malloc(n * sizeof(int));
for(int i=0; i<n; i++) nidx[i] = i;
quickselect(nidx, ndist, 0, n-1, k);
memcpy(knn.nidx + j * k, nidx, k * sizeof(int));
memcpy(knn.ndist + j * k, ndist, k * sizeof(double));
free(nidx);
free(ndist);
}
return knn;
}
| {
"alphanum_fraction": 0.4612450147,
"avg_line_length": 24.5404255319,
"ext": "h",
"hexsha": "3736dc064802e4dfb7f68823b413e09bfe228df5",
"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": "b2825028c99882d6563e510ca28a271f46c8932b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "panagiotou23/pds_project2",
"max_forks_repo_path": "src/v0.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b2825028c99882d6563e510ca28a271f46c8932b",
"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": "panagiotou23/pds_project2",
"max_issues_repo_path": "src/v0.h",
"max_line_length": 147,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "b2825028c99882d6563e510ca28a271f46c8932b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "panagiotou23/pds_project2",
"max_stars_repo_path": "src/v0.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-18T23:46:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-18T21:01:40.000Z",
"num_tokens": 1739,
"size": 5767
} |
#ifndef OPENMC_TALLIES_FILTER_CELL_H
#define OPENMC_TALLIES_FILTER_CELL_H
#include <cstdint>
#include <unordered_map>
#include <gsl/gsl>
#include "openmc/tallies/filter.h"
#include "openmc/vector.h"
namespace openmc {
//==============================================================================
//! Specifies which geometric cells tally events reside in.
//==============================================================================
class CellFilter : public Filter
{
public:
//----------------------------------------------------------------------------
// Constructors, destructors
~CellFilter() = default;
//----------------------------------------------------------------------------
// Methods
std::string type() const override {return "cell";}
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<int32_t>& cells() const { return cells_; }
void set_cells(gsl::span<int32_t> cells);
protected:
//----------------------------------------------------------------------------
// Data members
//! The indices of the cells binned by this filter.
vector<int32_t> cells_;
//! A map from cell indices to filter bin indices.
std::unordered_map<int32_t, int> map_;
};
} // namespace openmc
#endif // OPENMC_TALLIES_FILTER_CELL_H
| {
"alphanum_fraction": 0.5125628141,
"avg_line_length": 26.5333333333,
"ext": "h",
"hexsha": "e4180148f45473b0cbc3e6c6aaa3d37f2c85b2e8",
"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": "a9e85f4d5b59d133c17caccf4704a032184841d4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "cjwyett/openmc",
"max_forks_repo_path": "include/openmc/tallies/filter_cell.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4",
"max_issues_repo_issues_event_max_datetime": "2021-05-21T17:34:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-22T07:57:36.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "cjwyett/openmc",
"max_issues_repo_path": "include/openmc/tallies/filter_cell.h",
"max_line_length": 84,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "a9e85f4d5b59d133c17caccf4704a032184841d4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "cjwyett/openmc",
"max_stars_repo_path": "include/openmc/tallies/filter_cell.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-30T13:08:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-30T13:08:45.000Z",
"num_tokens": 300,
"size": 1592
} |
#ifndef _SPC_SPC_H
#define _SPC_SPC_H
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <string.h>
#include <gsl/gsl_nan.h>
#include <gsl/gsl_sys.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
#include "fitsio.h"
#define SPCTOL 1.0e-5
// interpolation type used for the
// response function
#define RESP_FUNC_INTERP_TYPE gsl_interp_linear
extern spectrum *
allocate_spectrum (const int numbin);
extern void
free_spectrum (spectrum * const spec);
extern void
fprintf_spectrum (FILE * output, const spectrum * const sp);
extern spectrum *
subtract_spectra (spectrum * a, spectrum * b);
extern int
get_ID_index_to_SPC (char filename[], char ID[]);
extern void
add_ID_index_to_SPC (char filename[], char ID[], int hdunum);
extern int
add_ID_to_SPC (char filename[], int N, char ID[]);
extern int
find_ID_in_SPC (char filename[], char ID[]);
extern void
create_SPC (char filename[], int overwrite);
extern int
get_SPC_colnum (fitsfile * input, char colname[]);
extern void
add_spectra_to_SPC (char filename[], spectrum * obj_spec,
spectrum * bck_spec, spectrum * sobj_spec,
int aperID, int beamID);
extern void
add_data_to_SPC (spectrum * spec, char countcolname[],
char errorcolname[], char weightcolname[], char ID[],
char filename[], int hdunum, long N);
extern spectrum *
trim_spectrum (spectrum * spc);
extern spectrum *
empty_counts_spectrum_copy (spectrum * a);
extern void
add_ID_to_SPC_opened (fitsfile *output, int N, char ID[]);
extern void
add_spectra_to_SPC_opened (fitsfile *input, spectrum * obj_spec,
spectrum * bck_spec, spectrum * sobj_spec,
int aperID, int beamID);
extern void
add_data_to_SPC_opened (spectrum * spec, char countcolname[],
char errorcolname[], char weightcolname[],
char ID[], fitsfile *input, long N);
extern fitsfile *
create_SPC_opened (char filename[], int overwrite);
#endif
| {
"alphanum_fraction": 0.7387434555,
"avg_line_length": 21.9540229885,
"ext": "h",
"hexsha": "ac41e157ab557557acca82d3e5a3c0eaeccba016",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/spc_spc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/spc_spc.h",
"max_line_length": 64,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/spc_spc.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 519,
"size": 1910
} |
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <galpy_potentials.h>
// MovingObjectPotential
// 3 arguments: amp, t0, tf
void constrain_range3(double * d) {
// Constrains index to be within interpolation range
if (*d < 0) *d = 0.0;
if (*d > 1) *d = 1.0;
}
void cosinerule(double R1, double R2, double Rdist, double * cosphi, double *sinphi) {
// R1 is the distane of the LMC from the MW
// R2 is the distance of the Sat from the MW
// Rdist is the estimated distance of the sat from the LMC
*cosphi = (R1*R1 - R2*R2 - Rdist*Rdist)/(2*R2*Rdist);
*sinphi = pow(1 - (*cosphi)*(*cosphi), 0.5);
}
double MovingObjectDissipativeRforce(double R,double z, double phi,
double t,
struct potentialArg * potentialArgs,
double vR,double vT,
double vz){
double amp,t0,tf,d_ind, Rdist, Rorb, RF, TF;
double x,y,vx,vy, obj_x,obj_y,obj_z,obj_vx,obj_vy,obj_vz;
double costheta, sintheta, phi2;
double vxd, vyd, vzd, vR1, vT1;
double * args= potentialArgs->args;
//Get args
amp= *args;
t0= *(args+1);
tf= *(args+2);
d_ind= (t-t0)/(tf-t0);
constrain_range3(&d_ind);
// convert to cartesian coodinates
x= R*cos(phi);
y= R*sin(phi);
vx= vR*cos(phi) - vT*sin(phi);
vy= vR*sin(phi) + vT*cos(phi);
// Interpolate x, y, z, vx, vy, vz
obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);
obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,
*(potentialArgs->acc1d+1));
obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind,
*(potentialArgs->acc1d+2));
obj_vx= gsl_spline_eval(*(potentialArgs->spline1d+3),d_ind,
*(potentialArgs->acc1d+3));
obj_vy= gsl_spline_eval(*(potentialArgs->spline1d+4),d_ind,
*(potentialArgs->acc1d+4));
obj_vz= gsl_spline_eval(*(potentialArgs->spline1d+5),d_ind,
*(potentialArgs->acc1d+5));
// convert velocity to reference frame of LMC
vxd = vx - obj_vx;
vyd = vy - obj_vy;
vzd = vz - obj_vz;
// determine angles for transformation
Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);
Rorb = pow(obj_x*obj_x + obj_y*obj_y, 0.5);
phi2 = atan2(y-obj_y, x-obj_x);
cosinerule(Rorb,R,Rdist,&costheta,&sintheta);
// convert velocity to cyclindrical coordinates in reference frame of LMC.
vR1= cos(phi2)*vxd + sin(phi2)*vyd;
vT1= -sin(phi2)*vxd + cos(phi2)*vyd;
// Calculate Radial and transverse forces
RF= calcRforce(Rdist,(z-obj_z),phi,t,potentialArgs->nwrapped,
potentialArgs->wrappedPotentialArg,vR1,vT1,vzd);
TF= calcPhiforce(Rdist,(z-obj_z),phi,t,potentialArgs->nwrapped,
potentialArgs->wrappedPotentialArg,vR1,vT1,vzd);
// Transform force back into the refernce frame of the MW
return -amp*(RF*costheta +TF*sintheta);
}
double MovingObjectDissipativezforce(double R,double z,double phi,
double t,
struct potentialArg * potentialArgs,
double vR,double vT,
double vz){
double amp,t0,tf,d_ind, Rdist, Rorb;
double x,y,vx,vy, obj_x,obj_y,obj_z,obj_vx,obj_vy,obj_vz;
double costheta, sintheta, phi2;
double vxd, vyd, vzd, vR1, vT1;
double * args= potentialArgs->args;
//Get args
amp= *args;
t0= *(args+1);
tf= *(args+2);
d_ind= (t-t0)/(tf-t0);
constrain_range3(&d_ind);
// convert to cartesian coodinates
x= R*cos(phi);
y= R*sin(phi);
vx= vR*cos(phi) - vT*sin(phi);
vy= vR*sin(phi) + vT*cos(phi);
// Interpolate x, y, z, vx, vy, vz
obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);
obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,
*(potentialArgs->acc1d+1));
obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind,
*(potentialArgs->acc1d+2));
obj_vx= gsl_spline_eval(*(potentialArgs->spline1d+3),d_ind,
*(potentialArgs->acc1d+3));
obj_vy= gsl_spline_eval(*(potentialArgs->spline1d+4),d_ind,
*(potentialArgs->acc1d+4));
obj_vz= gsl_spline_eval(*(potentialArgs->spline1d+5),d_ind,
*(potentialArgs->acc1d+5));
// convert velocity to reference frame of LMC
vxd = vx - obj_vx;
vyd = vy - obj_vy;
vzd = vz - obj_vz;
// determine angles for transformation
Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);
Rorb = pow(obj_x*obj_x + obj_y*obj_y, 0.5);
phi2 = atan2(y-obj_y, x-obj_x);
cosinerule(Rorb,R,Rdist,&costheta,&sintheta);
// convert velocity to cyclindrical coordinates in reference frame of LMC.
vR1= cos(phi2)*vxd + sin(phi2)*vyd;
vT1= -sin(phi2)*vxd + cos(phi2)*vyd;
// Calculate z force
return amp * calczforce(Rdist,(z-obj_z),phi,t,potentialArgs->nwrapped,
potentialArgs->wrappedPotentialArg,vR1,vT1,vzd);
}
double MovingObjectDissipativephiforce(double R,double z,double phi,
double t,
struct potentialArg * potentialArgs,
double vR,double vT,
double vz){
double amp,t0,tf,d_ind, Rdist, Rorb, RF, TF;
double x,y,vx,vy, obj_x,obj_y,obj_z,obj_vx,obj_vy,obj_vz;
double costheta, sintheta, phi2;
double vxd, vyd, vzd, vR1, vT1;
double * args= potentialArgs->args;
//Get args
amp= *args;
t0= *(args+1);
tf= *(args+2);
d_ind= (t-t0)/(tf-t0);
constrain_range3(&d_ind);
// convert to cartesian coodinates
x= R*cos(phi);
y= R*sin(phi);
vx= vR*cos(phi) - vT*sin(phi);
vy= vR*sin(phi) + vT*cos(phi);
// Interpolate x, y, z, vx, vy, vz
obj_x= gsl_spline_eval(*potentialArgs->spline1d,d_ind,*potentialArgs->acc1d);
obj_y= gsl_spline_eval(*(potentialArgs->spline1d+1),d_ind,
*(potentialArgs->acc1d+1));
obj_z= gsl_spline_eval(*(potentialArgs->spline1d+2),d_ind,
*(potentialArgs->acc1d+2));
obj_vx= gsl_spline_eval(*(potentialArgs->spline1d+3),d_ind,
*(potentialArgs->acc1d+3));
obj_vy= gsl_spline_eval(*(potentialArgs->spline1d+4),d_ind,
*(potentialArgs->acc1d+4));
obj_vz= gsl_spline_eval(*(potentialArgs->spline1d+5),d_ind,
*(potentialArgs->acc1d+5));
// convert velocity to reference frame of LMC
vxd = vx - obj_vx;
vyd = vy - obj_vy;
vzd = vz - obj_vz;
// determine angles for transformation
Rdist= pow(pow(x-obj_x, 2)+pow(y-obj_y, 2), 0.5);
Rorb = pow(obj_x*obj_x + obj_y*obj_y, 0.5);
phi2 = atan2(y-obj_y, x-obj_x);
cosinerule(Rorb,R,Rdist,&costheta,&sintheta);
// convert velocity to cyclindrical coordinates in reference frame of LMC.
vR1= cos(phi2)*vxd + sin(phi2)*vyd;
vT1= -sin(phi2)*vxd + cos(phi2)*vyd;
// Calculate Radial and transverse forces
RF= calcRforce(Rdist,(z-obj_z),phi,t,potentialArgs->nwrapped,
potentialArgs->wrappedPotentialArg,vR1,vT1,vzd);
TF= calcPhiforce(Rdist,(z-obj_z),phi,t,potentialArgs->nwrapped,
potentialArgs->wrappedPotentialArg,vR1,vT1,vzd);
// Transform force back into the refernce frame of the MW
return -amp*(-RF*sintheta +TF*costheta);
}
| {
"alphanum_fraction": 0.670334507,
"avg_line_length": 33.7425742574,
"ext": "c",
"hexsha": "58922c8ffa51ce22e412bbdd5f2bb7f7a765dcdc",
"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": "83e9b3de53c59d51e3bb44751baf41d766ec5a52",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "radsouza/galpy",
"max_forks_repo_path": "galpy/potential/potential_c_ext/MovingObjectDissipative.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "83e9b3de53c59d51e3bb44751baf41d766ec5a52",
"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": "radsouza/galpy",
"max_issues_repo_path": "galpy/potential/potential_c_ext/MovingObjectDissipative.c",
"max_line_length": 86,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "83e9b3de53c59d51e3bb44751baf41d766ec5a52",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "radsouza/galpy",
"max_stars_repo_path": "galpy/potential/potential_c_ext/MovingObjectDissipative.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2405,
"size": 6816
} |
/* vector/gsl_vector_float.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_VECTOR_FLOAT_H__
#define __GSL_VECTOR_FLOAT_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_block_float.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
float *data;
gsl_block_float *block;
int owner;
}
gsl_vector_float;
typedef struct
{
gsl_vector_float vector;
} _gsl_vector_float_view;
typedef _gsl_vector_float_view gsl_vector_float_view;
typedef struct
{
gsl_vector_float vector;
} _gsl_vector_float_const_view;
typedef const _gsl_vector_float_const_view gsl_vector_float_const_view;
/* Allocation */
gsl_vector_float *gsl_vector_float_alloc (const size_t n);
gsl_vector_float *gsl_vector_float_calloc (const size_t n);
gsl_vector_float *gsl_vector_float_alloc_from_block (gsl_block_float * b,
const size_t offset,
const size_t n,
const size_t stride);
gsl_vector_float *gsl_vector_float_alloc_from_vector (gsl_vector_float * v,
const size_t offset,
const size_t n,
const size_t stride);
void gsl_vector_float_free (gsl_vector_float * v);
/* Views */
_gsl_vector_float_view
gsl_vector_float_view_array (float *v, size_t n);
_gsl_vector_float_view
gsl_vector_float_view_array_with_stride (float *base,
size_t stride,
size_t n);
_gsl_vector_float_const_view
gsl_vector_float_const_view_array (const float *v, size_t n);
_gsl_vector_float_const_view
gsl_vector_float_const_view_array_with_stride (const float *base,
size_t stride,
size_t n);
_gsl_vector_float_view
gsl_vector_float_subvector (gsl_vector_float *v,
size_t i,
size_t n);
_gsl_vector_float_view
gsl_vector_float_subvector_with_stride (gsl_vector_float *v,
size_t i,
size_t stride,
size_t n);
_gsl_vector_float_const_view
gsl_vector_float_const_subvector (const gsl_vector_float *v,
size_t i,
size_t n);
_gsl_vector_float_const_view
gsl_vector_float_const_subvector_with_stride (const gsl_vector_float *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
float gsl_vector_float_get (const gsl_vector_float * v, const size_t i);
void gsl_vector_float_set (gsl_vector_float * v, const size_t i, float x);
float *gsl_vector_float_ptr (gsl_vector_float * v, const size_t i);
const float *gsl_vector_float_const_ptr (const gsl_vector_float * v, const size_t i);
void gsl_vector_float_set_zero (gsl_vector_float * v);
void gsl_vector_float_set_all (gsl_vector_float * v, float x);
int gsl_vector_float_set_basis (gsl_vector_float * v, size_t i);
int gsl_vector_float_fread (FILE * stream, gsl_vector_float * v);
int gsl_vector_float_fwrite (FILE * stream, const gsl_vector_float * v);
int gsl_vector_float_fscanf (FILE * stream, gsl_vector_float * v);
int gsl_vector_float_fprintf (FILE * stream, const gsl_vector_float * v,
const char *format);
int gsl_vector_float_memcpy (gsl_vector_float * dest, const gsl_vector_float * src);
int gsl_vector_float_reverse (gsl_vector_float * v);
int gsl_vector_float_swap (gsl_vector_float * v, gsl_vector_float * w);
int gsl_vector_float_swap_elements (gsl_vector_float * v, const size_t i, const size_t j);
float gsl_vector_float_max (const gsl_vector_float * v);
float gsl_vector_float_min (const gsl_vector_float * v);
void gsl_vector_float_minmax (const gsl_vector_float * v, float * min_out, float * max_out);
size_t gsl_vector_float_max_index (const gsl_vector_float * v);
size_t gsl_vector_float_min_index (const gsl_vector_float * v);
void gsl_vector_float_minmax_index (const gsl_vector_float * v, size_t * imin, size_t * imax);
int gsl_vector_float_add (gsl_vector_float * a, const gsl_vector_float * b);
int gsl_vector_float_sub (gsl_vector_float * a, const gsl_vector_float * b);
int gsl_vector_float_mul (gsl_vector_float * a, const gsl_vector_float * b);
int gsl_vector_float_div (gsl_vector_float * a, const gsl_vector_float * b);
int gsl_vector_float_scale (gsl_vector_float * a, const double x);
int gsl_vector_float_add_constant (gsl_vector_float * a, const double x);
int gsl_vector_float_isnull (const gsl_vector_float * v);
int gsl_vector_float_ispos (const gsl_vector_float * v);
int gsl_vector_float_isneg (const gsl_vector_float * v);
#ifdef HAVE_INLINE
extern inline
float
gsl_vector_float_get (const gsl_vector_float * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return v->data[i * v->stride];
}
extern inline
void
gsl_vector_float_set (gsl_vector_float * v, const size_t i, float x)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}
extern inline
float *
gsl_vector_float_ptr (gsl_vector_float * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (float *) (v->data + i * v->stride);
}
extern inline
const float *
gsl_vector_float_const_ptr (const gsl_vector_float * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (const float *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_FLOAT_H__ */
| {
"alphanum_fraction": 0.6744153675,
"avg_line_length": 31.3711790393,
"ext": "h",
"hexsha": "4fb280ba9c4ddaa02a68f2fbb0ceaf6d04563e61",
"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/vector/gsl_vector_float.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/vector/gsl_vector_float.h",
"max_line_length": 94,
"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/vector/gsl_vector_float.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 1679,
"size": 7184
} |
/**
*
* @file core_clarfy.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 Azzam Haidar
* @date 2011-05-15
* @generated c Tue Jan 7 11:44:49 2014
*
**/
#include <math.h>
#include <lapacke.h>
#include "common.h"
#undef REAL
#define COMPLEX
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex32_t
*
* CORE_clarfy applies an elementary reflector, or Householder matrix, H,
* to a N-by-N hermitian matrix C, from both the left and the right.
*
* H is represented in the form
*
* H = I - tau * v * v'
*
* where tau is a scalar and v is a vector.
*
* If tau is zero, then H is taken to be the unit matrix.
*
*******************************************************************************
*
* @param[in] N
* The number of rows and columns of the matrix C. N >= 0.
*
* @param[in,out] A
* COMPLEX*16 array, dimension (LDA, N)
* On entry, the Hermetian matrix A.
* On exit, A is overwritten by H * A * H'.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,N).
*
* @param[in] V
* The vector V that contains the Householder reflectors.
*
* @param[in] TAU
* The value tau.
*
* @param[out] WORK
* Workspace.
*
******************************************************************************/
void
CORE_clarfy(int N,
PLASMA_Complex32_t *A, int LDA,
const PLASMA_Complex32_t *V,
const PLASMA_Complex32_t *TAU,
PLASMA_Complex32_t *WORK)
{
static PLASMA_Complex32_t zzero = 0.0;
static PLASMA_Complex32_t zmone = -1.0;
int j;
PLASMA_Complex32_t dtmp;
/* Compute dtmp = X'*V */
/* X = AVtau */
cblas_chemv(CblasColMajor, CblasLower,
N, CBLAS_SADDR(*TAU), A, LDA,
V, 1, CBLAS_SADDR(zzero), WORK, 1);
/* cblas_cdotc_sub(N, WORK, 1, V, 1, &dtmp);*/
dtmp = 0.;
for (j = 0; j < N ; j++)
dtmp = dtmp + conjf(WORK[j]) * V[j];
/* Compute 1/2 X'*V*t = 1/2*dtmp*tau */
dtmp = -dtmp * 0.5 * (*TAU);
/* Compute W=X-1/2VX'Vt = X - dtmp*V */
cblas_caxpy(N, CBLAS_SADDR(dtmp),
V, 1, WORK, 1);
/*
* Performs the symmetric rank 2 operation
* A := alpha*x*y' + alpha*y*x' + A
*/
cblas_cher2(CblasColMajor, CblasLower, N,
CBLAS_SADDR(zmone), WORK, 1,
V, 1,
A, LDA);
return;
}
#undef COMPLEX
| {
"alphanum_fraction": 0.5025906736,
"avg_line_length": 26.2330097087,
"ext": "c",
"hexsha": "163fa798388111f620a6074d59f137a221032261",
"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_clarfy.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_clarfy.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_clarfy.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 819,
"size": 2702
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/vector/gsl_vector.h>
#include <gsl/gsl_math.h>
#define BASE_DOUBLE
#include <gsl/templates_on.h>
#include <gsl/vector/minmax_source.c>
#include <gsl/templates_off.h>
#undef BASE_DOUBLE
| {
"alphanum_fraction": 0.7625,
"avg_line_length": 20,
"ext": "c",
"hexsha": "00a3849860eebcdea32338646aec1c80b769bc93",
"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": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/minmax.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"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": "MontyThibault/centre-of-mass-awareness",
"max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/minmax.c",
"max_line_length": 37,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/vector/minmax.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 63,
"size": 240
} |
/*
* SPDX-License-Identifier: BSD-3-Clause
*
* example_10-StructOfArrays-CellLinkedList-OuterLoop-SymmetricalLoadBalancing.c :
* Example of SPH Density Calculation using
* fast neighbor search the main density loop via
* Cell Linked List method, Struct of Arrays (SoA)
* data layout, OpenMP parallelization at the
* cell-pair level, SIMD directives in the kernel
* and in the inner-most loop. It also implements
* symmetrical load balancing by moving the parallelism
* from iterating over cells to iterate over
* unique pairs of cell (i.e. i<j) and recyling the
* intermediary calculations.
*
* (C) Copyright 2021 José Hugo Elsas
* Author: José Hugo Elsas <jhelsas@gmail.com>
*
* Command Line Options:
* -runs <int> : Set the number of repetitions (runs) for
* calculating the density. The value of
* the density is based on the last
* iteration.
* Default value: 1
* -run_seed <int>: Flag to set an alternative seed use for
* for the PRNG. Instead of feeding seed
* to the PRNG directly, it feeds
* seed + iteration, as to generate different
* configurations for each iteration.
* Default value: 0 - (possible 0/1)
* -seed <int>: Set the seed to use for the SPH particles
* uniform position generation in the box
* Default value: 123123123
*
* -N <int>: Set the number of SPH particles to be used
* Default value: 1e5 = 100,000
* -h <float>: Set the value of the smoothing kernel
* parameter h, which corresponds to half
* of the support of the kernel.
* Default value: 0.05
*
* -Nx <int>: Set the number of Cells in the X direction
* Default value: 10
* -Ny <int>: Set the number of Cells in the Y direction
* Default value: 10
* -Nz <int>: Set the number of Cells in the Z direction
* Default value: 10
*
* -Xmin <float>: Set the lower bound in the X direction for
* the Cell Linked List box
* Default value: 0.0
* -Ymin <float>: Set the lower bound in the Y direction for
* the Cell Linked List box
* Default value: 0.0
* -Ymin <float>: Set the lower bound in the Z direction for
* the Cell Linked List box
* Default value: 0.0
*
* -Xmax <float>: Set the lower bound in the X direction for
* the Cell Linked List box
* Default value: 1.0
* -Ymax <float>: Set the lower bound in the Y direction for
* the Cell Linked List box
* Default value: 1.0
* -Zmax <float>: Set the lower bound in the Z direction for
* the Cell Linked List box
* Default value: 1.0
*/
#include <math.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/time.h>
#include <inttypes.h>
#include <omp.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_heapsort.h>
#include "sph_data_types.h"
#include "sph_linked_list.h"
#include "sph_utils.h"
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
#define COMPUTE_BLOCKS 5
#define dbg false
int main_loop(int run, bool run_seed, int64_t N, double h, long int seed,
void *swap_arr,int64_t *temp_hash, linkedListBox *box, SPHparticle *lsph, double *times);
int compute_density_3d_symmetrical_load_ballance(int N, double h, SPHparticle *lsph, linkedListBox *box);
int compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end,
int64_t nb_begin, int64_t nb_end,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rhoi, double* restrict rhoj);
//void quickSort_int64_t2(int64_t *arr, int64_t low, int64_t high);
void quickSort_int64_t_2(int64_t *arr, int64_t low, int64_t high);
void mergeSort(int64_t arr[], int64_t l, int64_t r);
double w_bspline_3d_constant(double h);
#pragma omp declare simd
double w_bspline_3d_simd(double q);
#define ip_swap(a,b) (b)^=((a)^=((b)^=(a)))
KHASH_MAP_INIT_INT64(2, int64_t)
void counting_sort(int64_t N, linkedListBox *box, SPHparticle *lsph,void *swap_arr,int64_t *temp_hash);
int main(int argc, char **argv){
bool run_seed = false; // By default the behavior is is to use the same seed
int runs = 1,err; // it only runs once
long int seed = 123123123; // The default seed is 123123123
int64_t N = 100000; // The default number of particles is N = 1e5 = 100,000
double h=0.05; // The default kernel smoothing length is h = 0.05
linkedListBox *box; // Uninitialized Box containing the cells for the cell linked list method
SPHparticle *lsph; // Uninitialized array of SPH particles
box = (linkedListBox*)malloc(1*sizeof(linkedListBox)); // Create a box representing the entire 3d domain
// allow for command line customization of the run
arg_parse(argc,argv,&N,&h,&seed,&runs,&run_seed,box); // Parse the command line options
// line arguments and override default values
err = SPHparticle_SoA_malloc(N,&lsph);
if(err)
fprintf(stderr,"error in SPHparticle_SoA_malloc\n");
void *swap_arr = malloc(N*sizeof(double));
int64_t *temp_hash = (int64_t*)malloc(2*N*sizeof(int64_t));
double times[runs*COMPUTE_BLOCKS];
for(int run=0;run<runs;run+=1)
main_loop(run,run_seed,N,h,seed,swap_arr,temp_hash,box,lsph,times);
bool is_cll = true;
const char *prefix = "ex11,cll,SoA,outer,simd,symmLB,quicker";
print_time_stats(prefix,is_cll,N,h,seed,runs,lsph,box,times);
print_sph_particles_density(prefix,is_cll,N,h,seed,runs,lsph,box);
SPHparticleSOA_safe_free(N,&lsph);
safe_free_box(box);
free(swap_arr);
free(temp_hash);
return 0;
}
/*
* Function main_loop:
* Runs the main loop of the program, including the particle array generation,
* density calculation and the timings annotations.
*
* Arguments:
* run <int> : index (or value) or the present iteration
* run_seed <bool> : boolean defining whether to use run index for seed or not
* N <int> : Number of SPH particles to be used in the run
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* seed <long int> : seed for GSL PRNG generator to generate particle positions
* box <linkedListBox> : Box of linked list cells, encapsulating the 3d domain
* lsph <SPHparticle> : Array (pointer) of SPH particles to be updated
* times <double> : Array to store the computation timings to be updated
* Returns:
* 0 : error code returned
* lsph <SPHparticle> : SPH particle array is updated in the rho field by reference
* times <double> : Times is updated by reference
*/
int main_loop(int run, bool run_seed, int64_t N, double h, long int seed,
void *swap_arr, int64_t *temp_hash, linkedListBox *box, SPHparticle *lsph, double *times)
{
int err;
if(run_seed)
err = gen_unif_rdn_pos_box(N,seed+run,box,lsph);
else
err = gen_unif_rdn_pos_box(N,seed,box,lsph);
if(err)
fprintf(stderr,"error in gen_unif_rdn_pos\n");
// ------------------------------------------------------ //
double t0,t1,t2,t3,t4,t5;
t0 = omp_get_wtime();
err = compute_hash_MC3D(N,lsph,box); // Compute Morton Z 3D hash based on the
if(err) // cell index for each of the X, Y and Z
fprintf(stderr,"error in compute_hash_MC3D\n"); // directions, in which a given particle reside
t1 = omp_get_wtime();
counting_sort(N,box,lsph,swap_arr,temp_hash);
t2 = omp_get_wtime();
t3 = omp_get_wtime();
t4 = omp_get_wtime();
err = compute_density_3d_symmetrical_load_ballance(N,h,lsph,box); // Compute the density of the particles based
if(err) // on the cell linked list method for fast
fprintf(stderr,"error in compute_density_3d_load_ballanced\n"); // neighbor search
// --------------------------------------------------------------- //
t5 = omp_get_wtime();
kh_clear(0, box->hbegin);
kh_clear(1, box->hend);
times[COMPUTE_BLOCKS*run+0] = t1-t0; // Time for compute morton Z 3d hash
times[COMPUTE_BLOCKS*run+1] = t2-t1; // Time for sorting the particles' hashes
times[COMPUTE_BLOCKS*run+2] = t3-t2; // Time for reordering all other arrays accordingly
times[COMPUTE_BLOCKS*run+3] = t4-t3; // Time for setting up the interval hash tables
times[COMPUTE_BLOCKS*run+4] = t5-t4; // Time for computing the SPH particle densities
return 0;
}
/*
* Function compute_density_3d_symmetrical_load_ballance:
* Computes the SPH density from the particles using cell linked list with
* vectorization at the compute_density_3d_chunk level, but the parallelization
* done at the level of the outer-most loop of the compute_density_3d_cll_outerOmp
* function, not at the chunk level.
*
* The parallelization is done at the level of unique cell pair instead of cells,
* with the indexes for the cell pairs pre-computed before parallelization.
*
* Arguments:
* N <int> : Number of SPH particles to be used in the run
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* lsph <SPHparticle> : Array (pointer) of SPH particles to be updated
* Returns:
* 0 : error code returned
* lsph <SPHparticle> : SPH particle array is updated in the rho field by reference
*/
int compute_density_3d_symmetrical_load_ballance(int N, double h, SPHparticle *lsph, linkedListBox *box){
int64_t *node_begin,*node_end,*nb_begin,*nb_end; // Define the arrays for cell boundaries
int64_t max_cell_pair_count = 0; // and the number of cell pairs
const double kernel_constant = w_bspline_3d_constant(h);
max_cell_pair_count = count_box_pairs(box); // compute the maximum number of cell pairs
node_begin = (int64_t*)malloc(max_cell_pair_count*sizeof(int64_t)); // allocate space for node_begin
node_end = (int64_t*)malloc(max_cell_pair_count*sizeof(int64_t)); // allocate space for node_end
nb_begin = (int64_t*)malloc(max_cell_pair_count*sizeof(int64_t)); // allocate space for nb_begin
nb_end = (int64_t*)malloc(max_cell_pair_count*sizeof(int64_t)); // allocate space for nb_end
max_cell_pair_count = setup_unique_box_pairs(box, // set the values for cell pairs
node_begin,node_end,
nb_begin,nb_end);
memset(lsph->rho,(int)0,N*sizeof(double)); // Pre-initialize the density to zero
// Parallelism was moved
// to the level of unique pairs
#pragma omp parallel for schedule(dynamic,5) proc_bind(master) // Execute in parallel
for(size_t i=0;i<max_cell_pair_count;i+=1){ // over the unique pairs' array
double local_rhoi[node_end[i] - node_begin[i]]; // partial density array for node indexs
double local_rhoj[ nb_end[i] - nb_begin[i]]; // partial density array for nb indexs
memset(local_rhoi,(int)0,(node_end[i]-node_begin[i])*sizeof(double)); // initialize node partial density to zero
memset(local_rhoj,(int)0, (nb_end[i]-nb_begin[i])*sizeof(double)); // initialize nb partial density to zero
compute_density_3d_chunk_symmetrical(node_begin[i],node_end[i], // Compute the density contribution
nb_begin[i],nb_end[i],h, // from this particular cell pair
lsph->x,lsph->y,lsph->z, // for both node and nb partial density
lsph->nu,local_rhoi,
local_rhoj);
// merging the results can result in race conditions, therefore needs to be serialized
#pragma omp critical // this serializes this code section
{
for(size_t ii=node_begin[i];ii<node_end[i];ii+=1){ // iterate over the node_ cell
lsph->rho[ii] += kernel_constant*local_rhoi[ii-node_begin[i]]; // add the partial density contribution
}
if(node_begin[i] != nb_begin[i]) // if sender and receiver are different
for(size_t ii=nb_begin[i];ii<nb_end[i];ii+=1){ // iterate over the nb_ cell
lsph->rho[ii] += kernel_constant*local_rhoj[ii-nb_begin[i]]; // add the partial density contribution
}
}
}
free(node_begin);
free(node_end);
free(nb_begin);
free(nb_end);
return 0;
}
/*
* Function compute_density_3d_chunk_symmetrical:
* Computes the SPH density contribution to both the node_ cell and the nb_ cell.
* Vectorization in the inner-most loop, but no parallelization.
* The density contribution is symmetrical.
*
* Arguments:
* N <int> : Number of SPH particles to be used in the run
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* x <double*> : Array of particles' X positions
* y <double*> : Array of particles' Y positions
* z <double*> : Array of particles' Z positions
* nu <double*> : Array of particles' density weights (i.e. masses)
* Returns:
* 0 : error code returned
* rho <double*> : Array of particles' densities
*/
int compute_density_3d_chunk_symmetrical(int64_t node_begin, int64_t node_end,
int64_t nb_begin, int64_t nb_end,double h,
double* restrict x, double* restrict y,
double* restrict z, double* restrict nu,
double* restrict rhoi, double* restrict rhoj){
const double inv_h = 1./h;
for(int64_t ii=node_begin;ii<node_end;ii+=1){ // Iterate over the ii index of the chunk
double xii = x[ii]; // Load the X component of the ii particle position
double yii = y[ii]; // Load the Y component of the ii particle position
double zii = z[ii]; // Load the Z component of the ii particle position
#pragma omp simd // Hint at the compiler to vectorize the inner most loop
for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ // Iterate over the each other particle in jj loop
double q = 0.; // Initialize the distance
double xij = xii-x[jj]; // Load and subtract jj particle's X position component
double yij = yii-y[jj]; // Load and subtract jj particle's Y position component
double zij = zii-z[jj]; // Load and subtract jj particle's Z position component
q += xij*xij; // Add the jj contribution to the ii distance in X
q += yij*yij; // Add the jj contribution to the ii distance in Y
q += zij*zij; // Add the jj contribution to the ii distance in Z
q = sqrt(q)*inv_h; // Sqrt to compute the normalized distance, measured in h
double wij = w_bspline_3d_simd(q); // compute the smoothing kernel separately for re-use
rhoi[ii-node_begin] += nu[jj]*wij; // add the jj contribution to ii density
rhoj[jj-nb_begin] += nu[ii]*wij; // add the ii contribution to jj density
}
}
return 0;
}
/*
* Function w_bspline_3d_constant:
* Returns the 3d normalization constant for the cubic b-spline SPH smoothing kernel
*
* Arguments:
* h <double> : Smoothing Length for the Smoothing Kernel w_bspline
* Returns:
* 3d bspline normalization density <double>
*/
double w_bspline_3d_constant(double h){
return 3./(2.*M_PI*h*h*h); // 3d normalization value for the b-spline kernel
}
/*
* Function w_bspline_3d_simd:
* Returns the un-normalized value of the cubic b-spline SPH smoothing kernel
*
* Arguments:
* q <double> : Distance between particles normalized by the smoothing length h
* Returns:
* wq <double> : Unnormalized value of the kernel
*
* Observation:
* Why not else if(q<2.)?
* Because if you use "else if", the compiler refuses to vectorize,
* This results in a large slowdown, as of 2.5x slower for example_04
*/
#pragma omp declare simd
double w_bspline_3d_simd(double q){
double wq=0;
double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q); // The first polynomial of the spline
double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q); // The second polynomial of the spline
if(q<2.) // If the distance is below 2
wq = wq2; // Use the 2nd polynomial for the spline
if(q<1.) // If the distance is below 1
wq = wq1; // Use the 1st polynomial for the spline
return wq; // return which ever value corresponds to the distance
}
int cmp_int64_t(const void *p,const void *q){
int64_t *data1,*data2;
data1 = (int64_t*)p;
data2 = (int64_t*)q;
if(*data1 < *data2) // data[0] is the hash value,
return -1;
else if(*data1 == *data2) // in the unsorted array
return 0;
else
return 1;
}
#define swap_loop(N,lsph,temp_swap,member,type) for(int64_t i=0;i<(N);i+=1) \
(temp_swap)[i] = (lsph)->member[(lsph)->hash[2*i+1]];\
memcpy((lsph)->member,temp_swap,(N)*sizeof(type))
/*
* Function counting_sort:
*
*
* Arguments:
* N <int64_t> :
* box <linkedListBox*> :
* lsph <SPHparticle*> :
* swap_arr <double*> :
* temp_hash <int64_t*> :
* Returns:
* box <linkedListBox*> :
*
* Observation:
* Why not else if(q<2.)?
* Because if you use "else if", the compiler refuses to vectorize,
* This results in a large slowdown, as of 2.5x slower for example_04
*/
void counting_sort(int64_t N, linkedListBox *box, SPHparticle *lsph,void *swap_arr,int64_t *temp_hash){
double t0,t1,t2,t3,t4,t5,t6;
double t31,t32,t33,t34;
t0 = omp_get_wtime();
for(int64_t i=0;i<N;i+=1){
int ret;
khiter_t k = kh_put(0, box->hbegin, lsph->hash[2*i+0], &ret);
if(ret==1)
kh_value(box->hbegin, k) = 1;
else if(ret==0){
int64_t val = kh_value(box->hbegin, k);
kh_value(box->hbegin, k) = val + 1;
}
else{
printf("error counting_sort init");
return;
}
}
t1 = omp_get_wtime();
unsigned int dict_size = kh_size(box->hbegin);
int64_t hash[dict_size];
int64_t prefix[dict_size];
int idx = 0;
for (khiter_t k = kh_begin(box->hbegin); k != kh_end(box->hbegin); ++k){
if (kh_exist(box->hbegin, k)){
hash[idx] = kh_key(box->hbegin,k);
idx+=1;
}
}
t2 = omp_get_wtime();
qsort(hash,dict_size,sizeof(int64_t),cmp_int64_t);
t3 = omp_get_wtime();
prefix[0] = 0;
for(int i=1;i<dict_size;i+=1){
prefix[i] = prefix[i-1];
khiter_t k = kh_get(0, box->hbegin, hash[i-1]);
prefix[i] += kh_value(box->hbegin, k);
}
t31 = omp_get_wtime();
for(int i = 0; i< dict_size;i+=1){
khiter_t kp = kh_get(0, box->hbegin, hash[i]);
kh_value(box->hbegin, kp) = prefix[i];
}
t32 = omp_get_wtime();
for (khiter_t k = kh_begin(box->hbegin); k != kh_end(box->hbegin); ++k){
if (kh_exist(box->hbegin, k)){
int ret;
int64_t hash = kh_key(box->hbegin,k);
khiter_t ke = kh_put(1, box->hend, hash, &ret);
kh_value(box->hend, ke) = kh_value(box->hbegin, k);
}
}
t33 = omp_get_wtime();
for(int64_t i=0;i<N;i+=1){
khiter_t kp = kh_get(1, box->hend, lsph->hash[2*i]);
if (kh_exist(box->hend, kp)){
lsph->hash[2*i+1] = kh_value(box->hend, kp);
kh_value(box->hend, kp) += 1;
}
else{
printf("there is an issue\n");
}
}
t34 = omp_get_wtime();
t4 = omp_get_wtime();
for(int64_t i=0;i<N;i+=1){
int64_t idx = lsph->hash[2*i+1];
temp_hash[2*idx+0] = lsph->hash[2*i+0];
temp_hash[2*idx+1] = i;
}
for(int64_t i=0;i<N;i+=1){
lsph->hash[2*i+0] = temp_hash[2*i+0];
lsph->hash[2*i+1] = temp_hash[2*i+1];
}
t4 = omp_get_wtime();
int64_t *int64_temp_swap = (int64_t *)swap_arr;
swap_loop(N,lsph,int64_temp_swap,id ,int64_t);
double *double_temp_swap = (double *)swap_arr;
swap_loop(N,lsph,double_temp_swap,nu ,double);
swap_loop(N,lsph,double_temp_swap,rho,double);
swap_loop(N,lsph,double_temp_swap,x ,double);
swap_loop(N,lsph,double_temp_swap,y ,double);
swap_loop(N,lsph,double_temp_swap,z ,double);
swap_loop(N,lsph,double_temp_swap,ux ,double);
swap_loop(N,lsph,double_temp_swap,uy ,double);
swap_loop(N,lsph,double_temp_swap,uz ,double);
swap_loop(N,lsph,double_temp_swap,Fx ,double);
swap_loop(N,lsph,double_temp_swap,Fy ,double);
swap_loop(N,lsph,double_temp_swap,Fz ,double);
t5 = omp_get_wtime();
for(int64_t i=0;i<N;i+=1)
lsph->hash[i] = lsph->hash[2*i];
t6 = omp_get_wtime();
if(dbg){
printf("1: %lf \n",t1-t0);
printf("2: %lf \n",t2-t1);
printf("3: %lf \n",t3-t2);
printf("4: %lf \n",t4-t3);
printf(" 31: %lf\n",t31-t3);
printf(" 32: %lf\n",t32-t31);
printf(" 33: %lf\n",t33-t32);
printf(" 34: %lf\n",t34-t33);
printf(" 35: %lf\n",t4-t34);
printf("5: %lf \n",t5-t4);
printf("6: %lf \n",t6-t5);
}
return;
} | {
"alphanum_fraction": 0.5788667036,
"avg_line_length": 40.5682210708,
"ext": "c",
"hexsha": "6ffea1e10a40fd8f8425a9a326156e2728e5d61f",
"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": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "jhelsas/sphalerite",
"max_forks_repo_path": "SoA/exec/example_11-StructOfArrays-CellLinkedList-OuterLoop-SymmLB-quickerSort.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"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": "jhelsas/sphalerite",
"max_issues_repo_path": "SoA/exec/example_11-StructOfArrays-CellLinkedList-OuterLoop-SymmLB-quickerSort.c",
"max_line_length": 121,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "jhelsas/sphalerite",
"max_stars_repo_path": "SoA/exec/example_11-StructOfArrays-CellLinkedList-OuterLoop-SymmLB-quickerSort.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6133,
"size": 23489
} |
////////////////////////////////////////////////////////////
//
// Copyright (c) 2018 Jan Filipowicz, Filip Turobos
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
////////////////////////////////////////////////////////////
#ifndef GENETIC_ALGORITHM_LIBRARY_ELITIST_SELECTION_H
#define GENETIC_ALGORITHM_LIBRARY_ELITIST_SELECTION_H
#include <algorithm>
#include <cstddef>
#include <functional>
#include <vector>
#include <gsl/gsl_assert>
template<class Compare = std::less<>>
class elitist_selection {
public:
explicit elitist_selection(const Compare& comp = Compare()) noexcept(noexcept(Compare(comp)));
template<class Specimen>
void operator()(std::vector<Specimen>& specimens, std::size_t n) const;
private:
Compare comparator;
};
template<class Compare>
inline elitist_selection<Compare>::elitist_selection(const Compare& comp) noexcept(noexcept(Compare(comp)))
: comparator(comp) {}
template<class Compare>
template<class Specimen>
inline void elitist_selection<Compare>::operator()(std::vector<Specimen>& specimens, std::size_t n) const {
Expects(specimens.size() >= n);
std::nth_element(specimens.begin(), specimens.begin() + n, specimens.end(), [this](const Specimen& lhs, const Specimen& rhs) {
return comparator(rhs.rating(), lhs.rating());
});
specimens.resize(n);
}
#endif
| {
"alphanum_fraction": 0.7243891985,
"avg_line_length": 39.5423728814,
"ext": "h",
"hexsha": "f95afb251a262e0a3e47726e9abfacc93c3f815d",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SirEmentaler/Eugenics-Wars",
"max_forks_repo_path": "Genetic-Algorithm-Library/elitist_selection.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SirEmentaler/Eugenics-Wars",
"max_issues_repo_path": "Genetic-Algorithm-Library/elitist_selection.h",
"max_line_length": 127,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8a093d42ca935556e7d6ccaee5a57b8dd0c6b3e2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SirEmentaler/Eugenics-Wars",
"max_stars_repo_path": "Genetic-Algorithm-Library/elitist_selection.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 492,
"size": 2333
} |
#include <cblas.h>
#include "util.h"
#include "conv.h"
extern float *scratch;
convLayer convLayer_init(int Sm, int Sn, int p)
{
convLayer cl; CONVL_INIT(cl);
cl.Sm=Sm; cl.Sn=Sn; cl.p=p;
return cl;
}
void convLayer_free(convLayer *cl)
{
ftens_free(&cl->W); ftens_free(&cl->b);
ftens_free(&cl->dW); ftens_free(&cl->db);
ftens_free(&cl->out); ftens_free(&cl->in);
}
void convLayer_print_shape(convLayer *cl)
{
printf("conv: D=%d M=%d N=%d L=%d Sm=%d Sn=%d p=%d\n",
cl->D, cl->M, cl->N, cl->L, cl->Sm, cl->Sn, cl->p);
}
void convLayer_set(ftens *W, convLayer *cl)
{
int D=W->D, M=W->M, N=W->N, L=W->L;
ftens_free(&cl->W);
cl->D=D; cl->M=M; cl->N=N; cl->L=L;
cl->W = ftens_copy(W);
}
void convLayer_copy_input(ftens *t, convLayer *cl)
{
if (!cl->in.data)
cl->in=ftens_init(t->D, t->M, t->N, t->L);
memcpy(cl->in.data, t->data, t->bytes);
}
ftens convLayer_pad_input(ftens *t, float *scr,
int *M, int *N, int p)
{
ftens tp; const int D=t->D, L=t->L;
*M=PAD(*M, p); *N=PAD(*N, p);
if (!scratch) tp=ftens_copy_pad(t, p);
else {
tp = ftens_from_ptr(D, *M, *N, L, scr);
ftens_pad(t, &tp, p);
scr += (*M)*(*N)*L*D;
}
return tp;
}
void convLayer_forward(ftens *t, convLayer *cl, int save)
{
float *scr = scratch; ftens tp, tmp;
int D=t->D, Ms=t->M, Ns=t->N, Ls=t->L;
int F=cl->D, W=cl->M, H=cl->N, L=cl->L;
int p=cl->p, Sy=cl->Sm, Sx=cl->Sn;
ASSERT(t->L == cl->L, "err: conv shape\n");
if (save) convLayer_copy_input(t, cl);
if (p) tp = convLayer_pad_input(t, scr, &Ms, &Ns, p);
// lower
const int Md = OUT_LEN(Ms, H, Sy);
const int Nd = OUT_LEN(Ns, W, Sx);
const int Ld = W*H*L;
if (!scratch) tmp=ftens_init(D, Md, Nd, Ld);
else tmp=ftens_from_ptr(D, Md, Nd, Ld, scr);
ftens_lower(p ? &tp : t, &tmp, W, H, Sx, Sy);
// mat mul
if (!cl->out.data) cl->out=ftens_init(D, Md, Nd, F);
int M=Md*Nd, N=F, K=cl->W.MNL;
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans,
M, N, K, 1, tmp.data, K, cl->W.data, K,
0, cl->out.data, N);
if (!scratch) ftens_free(&tmp);
if (!scratch && p) ftens_free(&tp);
}
void convLayer_backward(ftens *dout, convLayer *cl)
{
exit(-2);
}
void convLayer_update(convLayer *cl)
{
exit(-3);
}
| {
"alphanum_fraction": 0.5299595142,
"avg_line_length": 23.0841121495,
"ext": "c",
"hexsha": "e74dbf0ce0e9fcdce340fb1c205faf92f18473e1",
"lang": "C",
"max_forks_count": 21,
"max_forks_repo_forks_event_max_datetime": "2021-09-16T17:50:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-06-10T17:50:57.000Z",
"max_forks_repo_head_hexsha": "84e359418845ad80923c563716848216df94db12",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "pppoe/espresso",
"max_forks_repo_path": "src/layers/convl.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "84e359418845ad80923c563716848216df94db12",
"max_issues_repo_issues_event_max_datetime": "2019-04-18T08:06:59.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-06-20T06:06:58.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "pppoe/espresso",
"max_issues_repo_path": "src/layers/convl.c",
"max_line_length": 63,
"max_stars_count": 55,
"max_stars_repo_head_hexsha": "84e359418845ad80923c563716848216df94db12",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "pppoe/espresso",
"max_stars_repo_path": "src/layers/convl.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-04T03:18:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-06-01T15:17:05.000Z",
"num_tokens": 902,
"size": 2470
} |
/* Copyright (c) 2014, J.M. Hernandez-Lobato, M.W. Hoffman, Z. Ghahramani
This function is from the code for the paper
Hernández-Lobato J. M., Hoffman M. W. and Ghahramani Z.
Predictive Entropy Search for Efficient Global Optimization of Black-box
Functions, In NIPS, 2014.
https://bitbucket.org/jmh233/codepesnips2014
*/
#include "mex.h"
#include <gsl/gsl_math.h>
#include <gsl/gsl_linalg.h>
/* Function that computes the inverse of a matrix using its Cholesky decomposition */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
#define L_matlab prhs[0]
#define ret_matlab plhs[0]
int i, j, n, m;
double *L, *ret;
gsl_matrix *result;
n = mxGetN(L_matlab);
m = mxGetM(L_matlab);
/* We ask for memory to store the matrix in the gnu library format */
result = gsl_matrix_alloc(n, m);
/* We copy the matrix from the matlab format to the gnu library format */
L = mxGetPr(L_matlab);
for (i = 0 ; i < n ; i++)
for (j = 0 ; j < m ; j++)
gsl_matrix_set(result, i, j, L[ i + n * j ]);
gsl_linalg_cholesky_decomp(result);
/* We obtain the inverse of the matrix */
gsl_linalg_cholesky_invert(result);
/* We ask for memory to return the solution */
ret_matlab = mxCreateDoubleMatrix(n, m, mxREAL);
/* We copy the solution from the gnu library representation to the matlab representation */
ret = mxGetPr(ret_matlab);
for (i = 0 ; i < n ; i++)
for (j = 0 ; j < m ; j++)
ret[ i + j * n ] = gsl_matrix_get(result, i, j);
/* We are done */
gsl_matrix_free(result);
return;
}
| {
"alphanum_fraction": 0.6782945736,
"avg_line_length": 25.8,
"ext": "c",
"hexsha": "e313a649a94120c6e1fa73e4007e4c29418d360d",
"lang": "C",
"max_forks_count": 15,
"max_forks_repo_forks_event_max_datetime": "2022-02-22T21:41:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-05-27T02:48:48.000Z",
"max_forks_repo_head_hexsha": "ff2fbd6bb376b6cb84363006960c7d78abf891af",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ntienvu/ICDM2019_PVRS",
"max_forks_repo_path": "baselines/FITBO/utility/chol2invchol.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "ff2fbd6bb376b6cb84363006960c7d78abf891af",
"max_issues_repo_issues_event_max_datetime": "2021-05-11T19:21:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-06-12T02:35:05.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ntienvu/ICDM2019_PVRS",
"max_issues_repo_path": "baselines/FITBO/utility/chol2invchol.c",
"max_line_length": 92,
"max_stars_count": 46,
"max_stars_repo_head_hexsha": "59bbd0b7332481fc6ef95a590c6a507049e7db30",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "pubino/Max-value-Entropy-Search",
"max_stars_repo_path": "utils/chol2invchol.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-07T13:36:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-22T16:13:35.000Z",
"num_tokens": 470,
"size": 1548
} |
/* statistics/gsl_statistics_int.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Jim Davies, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_STATISTICS_INT_H__
#define __GSL_STATISTICS_INT_H__
#include <stddef.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
GSL_EXPORT double gsl_stats_int_mean (const int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_int_variance (const int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_int_sd (const int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_int_variance_with_fixed_mean (const int data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_int_sd_with_fixed_mean (const int data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_int_absdev (const int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_int_skew (const int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_int_kurtosis (const int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_int_lag1_autocorrelation (const int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_int_covariance (const int data1[], const size_t stride1,const int data2[], const size_t stride2, const size_t n);
GSL_EXPORT double gsl_stats_int_variance_m (const int data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_int_sd_m (const int data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_int_absdev_m (const int data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_int_skew_m_sd (const int data[], const size_t stride, const size_t n, const double mean, const double sd);
GSL_EXPORT double gsl_stats_int_kurtosis_m_sd (const int data[], const size_t stride, const size_t n, const double mean, const double sd);
GSL_EXPORT double gsl_stats_int_lag1_autocorrelation_m (const int data[], const size_t stride, const size_t n, const double mean);
GSL_EXPORT double gsl_stats_int_covariance_m (const int data1[], const size_t stride1,const int data2[], const size_t stride2, const size_t n, const double mean1, const double mean2);
GSL_EXPORT double gsl_stats_int_pvariance (const int data1[], const size_t stride1, const size_t n1, const int data2[], const size_t stride2, const size_t n2);
GSL_EXPORT double gsl_stats_int_ttest (const int data1[], const size_t stride1, const size_t n1, const int data2[], const size_t stride2, const size_t n2);
GSL_EXPORT int gsl_stats_int_max (const int data[], const size_t stride, const size_t n);
GSL_EXPORT int gsl_stats_int_min (const int data[], const size_t stride, const size_t n);
GSL_EXPORT void gsl_stats_int_minmax (int * min, int * max, const int data[], const size_t stride, const size_t n);
GSL_EXPORT size_t gsl_stats_int_max_index (const int data[], const size_t stride, const size_t n);
GSL_EXPORT size_t gsl_stats_int_min_index (const int data[], const size_t stride, const size_t n);
GSL_EXPORT void gsl_stats_int_minmax_index (size_t * min_index, size_t * max_index, const int data[], const size_t stride, const size_t n);
GSL_EXPORT double gsl_stats_int_median_from_sorted_data (const int sorted_data[], const size_t stride, const size_t n) ;
GSL_EXPORT double gsl_stats_int_quantile_from_sorted_data (const int sorted_data[], const size_t stride, const size_t n, const double f) ;
__END_DECLS
#endif /* __GSL_STATISTICS_INT_H__ */
| {
"alphanum_fraction": 0.7881165919,
"avg_line_length": 57.9220779221,
"ext": "h",
"hexsha": "48f128814a1a49d16dfdb96ce0b9693794ad6776",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dynaryu/vaws",
"max_forks_repo_path": "src/core/gsl/include/gsl/gsl_statistics_int.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_statistics_int.h",
"max_line_length": 183,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dynaryu/vaws",
"max_stars_repo_path": "src/core/gsl/include/gsl/gsl_statistics_int.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1126,
"size": 4460
} |
#pragma once
#include <gsl/gsl>
#include <vector>
#include <memory>
struct AVCodecContext;
struct AVPacket;
struct AVFrame;
namespace video_streamer
{
class FrameEncoder
{
public:
explicit FrameEncoder(gsl::not_null<AVCodecContext*> codecContext);
std::vector<unsigned char> encode(gsl::not_null<const AVFrame*> frame);
private:
gsl::not_null<AVCodecContext*> m_codecContext;
gsl::not_null<AVPacket*> m_packet;
};
std::shared_ptr<FrameEncoder> createFrameEncoder(
const std::string& encoderName, gsl::not_null<const AVCodecContext*> codecContext);
} // video_streamer
| {
"alphanum_fraction": 0.7567114094,
"avg_line_length": 19.8666666667,
"ext": "h",
"hexsha": "d7975efb41d45441467fd1188b4a7f44abe583ea",
"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": "e695e0b544a61bb4e74149005c69723dbbecb952",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "nicledomaS/VideoStream",
"max_forks_repo_path": "modules/http_streamer/src/FrameEncoder.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "e695e0b544a61bb4e74149005c69723dbbecb952",
"max_issues_repo_issues_event_max_datetime": "2022-03-16T07:16:25.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-16T07:16:25.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "nicledomaS/VideoStream",
"max_issues_repo_path": "modules/http_streamer/src/FrameEncoder.h",
"max_line_length": 87,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e695e0b544a61bb4e74149005c69723dbbecb952",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "nicledomaS/VideoStream",
"max_stars_repo_path": "modules/http_streamer/src/FrameEncoder.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 148,
"size": 596
} |
#ifndef BASIS_H
#define BASIS_H
#include <algorithm>
#include <cstddef>
#include <cmath>
#include <map>
#include <memory>
#include <mutex>
#include <vector>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_spblas.h>
#include <gsl/gsl_spmatrix.h>
#include <gsl/gsl_wavelet.h>
#include "constants.h"
#include "vector.h"
using std::array;
using std::shared_ptr;
using std::unique_ptr;
using std::vector;
using std::map;
using std::pair;
using BasisMap = Vector[]; // length
using ConvMap = Vector[]; // length * length
void projForward(gsl_vector *f);
void projBackward(gsl_vector *u);
void projForward(gsl_vector *f, gsl_vector *u);
void projBackward(gsl_vector *u, gsl_vector *f);
const Vector& getBasis(size_t k);
const Vector& getConvoluted(size_t p, size_t f);
double convolutedBasis(size_t p, size_t f, size_t mu);
void normalize(gsl_vector *f);
extern unique_ptr<BasisMap> storedBases;
extern unique_ptr<ConvMap> storedConvs;
#endif // WAVELETS_H
| {
"alphanum_fraction": 0.7445972495,
"avg_line_length": 19.2075471698,
"ext": "h",
"hexsha": "7b2cc5dbbb157d0a238291dccfb2c8240e13acb1",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-03-27T14:41:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-27T00:23:35.000Z",
"max_forks_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ichi-rika/glottal-inverse",
"max_forks_repo_path": "inc/linalg.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ichi-rika/glottal-inverse",
"max_issues_repo_path": "inc/linalg.h",
"max_line_length": 54,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "c922ed540278e3c8eec528c2cf66b89e6d310575",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ichi-rika/glottal-inverse",
"max_stars_repo_path": "inc/linalg.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-26T16:22:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-01-24T17:01:28.000Z",
"num_tokens": 289,
"size": 1018
} |
/* specfunc/bessel_K1.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
* Copyright (C) 2016 Pavel Holoborodko, 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.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_poly.h>
#include <gsl/gsl_sf_exp.h>
#include <gsl/gsl_sf_bessel.h>
#include "error.h"
#include "chebyshev.h"
#include "cheb_eval.c"
/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/
/*
Minimax rational approximation for [0,1), peak relative error = 1.83*GSL_DBL_EPSILON.
Source: http://www.advanpix.com/?p=3987
*/
static double k1_poly[9] = {
-3.0796575782920622440538935e-01,
-8.5370719728650778045782736e-02,
-4.6421827664715603298154971e-03,
-1.1253607036630425931072996e-04,
-1.5592887702110907110292728e-06,
-1.4030163679125934402498239e-08,
-8.8718998640336832196558868e-11,
-4.1614323580221539328960335e-13,
-1.5261293392975541707230366e-15
};
static double i1_poly[7] = {
8.3333333333333325191635191e-02,
6.9444444444467956461838830e-03,
3.4722222211230452695165215e-04,
1.1574075952009842696580084e-05,
2.7555870002088181016676934e-07,
4.9724386164128529514040614e-09
};
/*
Chebyshev expansion for [1,8], peak relative error = 1.28*GSL_DBL_EPSILON.
Source: Pavel Holoborodko.
*/
static double ak1_data[25] = {
+2.07996868001418246e-01,
+1.62581565017881476e-01,
-5.87070423518863640e-03,
+4.95021520115789501e-04,
-5.78958347598556986e-05,
+8.18614610209334726e-06,
-1.31604832009487277e-06,
+2.32546031520101213e-07,
-4.42206518311557987e-08,
+8.92163994883100361e-09,
-1.89046270526983427e-09,
+4.17568808108504702e-10,
-9.55912361791375794e-11,
+2.25769353153867758e-11,
-5.48128000211158482e-12,
+1.36386122546441926e-12,
-3.46936690565986409e-13,
+9.00354564415705942e-14,
-2.37950577776254432e-14,
+6.39447503964025336e-15,
-1.74498363492322044e-15,
+4.82994547989290473e-16,
-1.35460927805445606e-16,
+3.84604274446777234e-17,
-1.10456856122581316e-17
};
static cheb_series ak1_cs = {
ak1_data,
24,
-1, 1,
9
};
/*
Chebyshev expansion for [8,inf), peak relative error = 1.25*GSL_DBL_EPSILON.
Source: SLATEC/dbsk1e.f
*/
static double ak12_data[14] = {
+.637930834373900104E-1,
+.283288781304972094E-1,
-.247537067390525035E-3,
+.577197245160724882E-5,
-.206893921953654830E-6,
+.973998344138180418E-8,
-.558533614038062498E-9,
+.373299663404618524E-10,
-.282505196102322545E-11,
+.237201900248414417E-12,
-.217667738799175398E-13,
+.215791416161603245E-14,
-.229019693071826928E-15,
+.258288572982327496E-16
};
static cheb_series ak12_cs = {
ak12_data,
13,
-1, 1,
7
};
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int gsl_sf_bessel_K1_scaled_e(const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x <= 0.0) {
DOMAIN_ERROR(result);
}
else if(x < 2.0*GSL_DBL_MIN) {
OVERFLOW_ERROR(result);
}
else if(x < 1.0) {
const double lx = log(x);
const double ex = exp(x);
const double x2 = x*x;
const double t = 0.25*x2;
const double i1 = 0.5 * x * (1.0 + t * (0.5 + t * gsl_poly_eval(i1_poly,6,t)));
result->val = ex * (x2 * gsl_poly_eval(k1_poly,9,x2) + x * lx * i1 + 1) / x;
result->err = ex * (1.6+fabs(lx)*0.6) * GSL_DBL_EPSILON;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else if(x <= 8.0) {
const double sx = sqrt(x);
gsl_sf_result c;
cheb_eval_e(&ak1_cs, (16.0/x-9.0)/7.0, &c);
result->val = (1.375 + c.val) / sx; /* 1.375 = 11/8 */
result->err = c.err / sx;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else {
const double sx = sqrt(x);
gsl_sf_result c;
cheb_eval_e(&ak12_cs, 16.0/x-1.0, &c);
result->val = (1.25 + c.val) / sx;
result->err = c.err / sx;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
}
int gsl_sf_bessel_K1_e(const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x <= 0.0) {
DOMAIN_ERROR(result);
}
else if(x < 2.0*GSL_DBL_MIN) {
OVERFLOW_ERROR(result);
}
else if(x < 1.0) {
const double lx = log(x);
const double x2 = x*x;
const double t = 0.25*x2;
const double i1 = 0.5 * x * (1.0 + t * (0.5 + t * gsl_poly_eval(i1_poly,6,t)));
result->val = (x2 * gsl_poly_eval(k1_poly,9,x2) + x * lx * i1 + 1) / x;
result->err = (1.6+fabs(lx)*0.6) * GSL_DBL_EPSILON;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else {
gsl_sf_result K1_scaled;
int stat_K1 = gsl_sf_bessel_K1_scaled_e(x, &K1_scaled);
int stat_e = gsl_sf_exp_mult_err_e(-x, 0.0,
K1_scaled.val, K1_scaled.err,
result);
result->err = fabs(result->val) * (GSL_DBL_EPSILON*fabs(x) + K1_scaled.err/K1_scaled.val);
return GSL_ERROR_SELECT_2(stat_e, stat_K1);
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_bessel_K1_scaled(const double x)
{
EVAL_RESULT(gsl_sf_bessel_K1_scaled_e(x, &result));
}
double gsl_sf_bessel_K1(const double x)
{
EVAL_RESULT(gsl_sf_bessel_K1_e(x, &result));
}
| {
"alphanum_fraction": 0.6595187428,
"avg_line_length": 28.0229357798,
"ext": "c",
"hexsha": "0c2369c0145c1af788742ba2a2d7966628d63f23",
"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/specfunc/bessel_K1.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_K1.c",
"max_line_length": 94,
"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/specfunc/bessel_K1.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": 2279,
"size": 6109
} |
#pragma once
#include <unordered_map>
#include <vector>
#include <gsl/span>
#include <json.hpp>
#include <optional.hpp>
#include "Quiver/Animation/AnimationData.h"
#include "Quiver/Animation/AnimationId.h"
#include "Quiver/Animation/Rect.h"
#include "Quiver/Animation/TimeUnit.h"
namespace qvr
{
// Tells us about where to find an Animation on disk.
struct AnimationSourceInfo {
std::string name;
std::string filename;
};
inline bool operator==(const AnimationSourceInfo& a, const AnimationSourceInfo& b) {
return a.name == b.name && a.filename == b.filename;
}
class AnimationLibrary
{
public:
AnimationId Add(const AnimationData& anim);
AnimationId Add(
const AnimationData& anim,
const AnimationSourceInfo& sourceInfo);
bool Remove(const AnimationId anim);
bool Contains(const AnimationId anim) const;
auto GetCount() const -> int;
auto GetAnimation(const AnimationSourceInfo& sourceInfo)
const -> AnimationId;
auto GetSourceInfo(const AnimationId anim)
const -> std::experimental::optional<AnimationSourceInfo>;
auto GetFrameCount(const AnimationId anim) const -> int;
auto GetViewCount(const AnimationId anim) const -> int;
auto HasAltViews(const AnimationId anim) const -> bool;
auto GetRect(
const AnimationId anim,
const int frameIndex,
const int viewIndex = 0)
const -> Animation::Rect;
auto GetRects(
const AnimationId anim,
const int frameIndex)
const -> gsl::span<const Animation::Rect>;
auto GetTime(
const AnimationId anim,
const int frameIndex)
const -> Animation::TimeUnit;
auto GetIds() const -> std::vector<AnimationId>;
friend void to_json(nlohmann::json& j, const AnimationLibrary& animations);
private:
struct AnimationInfo {
AnimationInfo(
const unsigned indexOfFirstRect,
const unsigned indexOfFirstTime,
const unsigned numRects,
const unsigned numRectsPerFrame)
: mIndexOfFirstRect(indexOfFirstRect)
, mIndexOfFirstTime(indexOfFirstTime)
, mNumRects(numRects)
, mNumRectsPerFrame(numRectsPerFrame)
{}
AnimationInfo(const AnimationInfo& other) = default;
AnimationInfo() = default;
unsigned NumFrames() const { return mNumRects / mNumRectsPerFrame; }
std::experimental::optional<AnimationSourceInfo> mSourceInfo;
unsigned mIndexOfFirstRect = 0;
unsigned mIndexOfFirstTime = 0;
unsigned mNumRects = 0;
unsigned mNumRectsPerFrame = 0;
};
std::unordered_map<AnimationId, AnimationInfo> infos;
// Time values for each frame in every animation.
std::vector<Animation::TimeUnit> allFrameTimes;
// Rects for each frame in every animation, including alt view rects.
std::vector<Animation::Rect> allFrameRects;
};
void to_json(nlohmann::json& j, const AnimationLibrary& animations);
void to_json(nlohmann::json& j, const AnimationSourceInfo& sourceInfo);
void from_json(const nlohmann::json& j, AnimationLibrary& animations);
void from_json(const nlohmann::json& j, AnimationSourceInfo& animationSource);
} | {
"alphanum_fraction": 0.7551502871,
"avg_line_length": 25.9736842105,
"ext": "h",
"hexsha": "6165c47cb49b67a74acc6ffeee3a93ff70677f69",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2020-03-19T10:08:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-22T14:47:57.000Z",
"max_forks_repo_head_hexsha": "c8ef9591117bdfc8d6fa509ae53451e0807f5686",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "rachelnertia/Quiver",
"max_forks_repo_path": "Source/Quiver/Quiver/Animation/AnimationLibrary.h",
"max_issues_count": 46,
"max_issues_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4",
"max_issues_repo_issues_event_max_datetime": "2018-10-13T14:46:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-26T21:21:51.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "rachelnertia/Quarrel",
"max_issues_repo_path": "External/Quiver/Source/Quiver/Quiver/Animation/AnimationLibrary.h",
"max_line_length": 84,
"max_stars_count": 39,
"max_stars_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "rachelnertia/Quarrel",
"max_stars_repo_path": "External/Quiver/Source/Quiver/Quiver/Animation/AnimationLibrary.h",
"max_stars_repo_stars_event_max_datetime": "2020-03-31T22:19:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-10-22T15:47:39.000Z",
"num_tokens": 738,
"size": 2961
} |
#include <lapacke.h>
#include <mpi.h>
#include <stdio.h>
#include "../include/paralleltt.h"
#include <unistd.h>
// X is r1 x n x r2, transpose is r2 x n x r1
double* train_transpose(const double* X, int r1, int n, int r2){
double* X_T = (double*) calloc(r1*n*r2, sizeof(double));
for (int ii = 0; ii < r1; ++ii){
for (int jj = 0; jj < n; ++jj){
for (int kk = 0; kk < r2; ++kk){
X_T[kk + jj*r2 + ii*n*r2] = X[ii + jj*r1 + kk*n*r1];
}
}
}
return X_T;
}
void two_sketches_to_train(sketch* s1, sketch* s2, double** train_ptr)
{
double* train = *train_ptr;
int head = 0;
if ((s1 == NULL) || (s2 == NULL)){
sketch* s = (s1 == NULL) ? s2 : s1;
MPI_tensor* ten = s->ten;
MPI_Comm comm = ten->comm;
int iscol = s->iscol;
int flattening = s->flattening;
flattening_info* fi = flattening_info_init(ten, flattening, iscol, 0);
int d = ten->d;
int n = ten->n[(iscol) ? 0 : d-1];
int r = s->r;
matrix_tt* train_mat = (iscol) ? matrix_tt_wrap(n, r, train) : matrix_tt_wrap(r, n, train);
matrix_tt_fill_zeros(train_mat);
int* op = s->owner_partition;
int rank = ten->rank;
for (int ii = op[rank]; ii < op[rank+1]; ++ii){
// X submatrix
matrix_tt* X_submat = own_submatrix(s, ii, 0);
// train submatrix
flattening_info_f_update(fi, ten, ii);
int i0 = fi->f_t_index[0];
int i1 = i0 + fi->f_t_sizes[0];
matrix_tt* train_submat = (iscol) ? submatrix(train_mat, i0, i1, 0, r) : submatrix(train_mat, 0, r, i0, i1);
train_submat->transpose = (iscol) ? 0 : 1;
matrix_tt_copy_data(train_submat, X_submat);
free(train_submat);
free(X_submat);
}
matrix_tt_reduce(comm, rank, train_mat, NULL, head);
flattening_info_free(fi);
free(train_mat);
return;
}
int iscol = s1->iscol ? 1 : 0;
int iscol2 = s2->iscol ? 1 : 0;
if (iscol != iscol2){
printf("two_sketches_to_train: Cannot convert a column and a row to a train\n");
return;
}
int flattening1 = s1->flattening;
int flattening2 = s2->flattening;
// We want s2 to be the taller sketch, so that we only communicate s1 if necessary (which should be cheaper!)
if (((iscol) && (flattening1 > flattening2)) || (!(iscol) && (flattening2 > flattening1))){
sketch* tmp = s1;
s1 = s2;
s2 = tmp;
flattening1 = s1->flattening;
flattening2 = s2->flattening;
}
// We want the flattening dimensions to be one off of each other
MPI_tensor* ten = s1->ten;
flattening_info* fi1 = flattening_info_init(ten, flattening1, iscol, 0);
flattening_info* fi2 = flattening_info_init(ten, flattening2, iscol, 0);
if (fi2->f_d - fi1->f_d != 1){
printf("two_sketches_to_train: The difference between the two flattening dimensions is not correct!\n");
return;
}
MPI_Comm comm = ten->comm;
int size = ten->comm_size;
int rank = ten->rank;
int r1 = s1->r;
int r2 = s2->r;
int n_index = (iscol) ? flattening1 : flattening2;
int n = ten->n[n_index];
matrix_tt* train_mat = matrix_tt_wrap(r1, n*r2, train);
matrix_tt_fill_zeros(train_mat);
// Loop over all blocks of fi2
matrix_tt* s_mat1 = (matrix_tt*) calloc(1, sizeof(matrix_tt));
for (int block2 = 0; block2 < fi2->f_Nblocks; ++block2){
flattening_info_f_update(fi2, ten, block2);
int owner2 = s_get_owner(s2, block2);
// Get the corresponding block1
int* f_t_block1 = fi2->f_t_block + ((iscol) ? 0 : 1);
int* f_nps1 = fi2->f_nps + ((iscol) ? 0 : 1);
int block1 = 0;
for (int ii = (fi1->f_d) - 1; ii >= 0; --ii){
block1 = block1*f_nps1[ii] + f_t_block1[ii];
}
flattening_info_f_update(fi1, ten, block1);
int owner1 = s_get_owner(s1, block1);
sendrecv_sketch_block(s_mat1, s1, fi1, owner2, 0);
if (rank == owner2){
// Get submatrix of s2
matrix_tt* s_mat2 = own_submatrix(s2, block2 , 0);
// Multiply
matrix_tt* train_submat = submatrix(train_mat, 0, 0, 0, 0);
matrix_tt* s_submat2 = submatrix(s_mat2, 0, 0, 0, 0);
s_submat2->transpose = (iscol) ? 0 : 1;
for (int kk = 0; kk < r2; ++kk){
int jj0 = (fi2->f_t_index[(iscol) ? (fi2->f_d) - 1 : 0]) + kk * n;
int sz = fi2->f_t_sizes[(iscol) ? (fi2->f_d) - 1 : 0];
submatrix_update(train_submat, 0, r1, jj0, jj0+sz);
s_submat2->X = s_mat2->X + s_mat2->offset + kk*(s_mat2->lda);
if (iscol){
s_submat2->m = s_mat1->m;
s_submat2->lda = s_mat1->m;
s_submat2->n = sz;
}
else{
s_submat2->m = sz;
s_submat2->lda = sz;
s_submat2->n = s_mat1->m;
}
s_mat1->transpose = 1;
matrix_tt_dgemm(s_mat1, s_submat2, train_submat, 1.0, 1.0);
}
free(train_submat);
free(s_mat2);
free(s_submat2);
}
}
free(s_mat1);
matrix_tt_reduce(comm, rank, train_mat, NULL, head);
// If it was a row sketch, we need to transpose
if ((!iscol) && (rank == head)){
double* train_cp = train_transpose(train, r1, n, r2);
*train_ptr = train_cp;
matrix_tt_free(train_mat); train_mat = NULL;
}
else{
free(train_mat); train_mat = NULL;
}
flattening_info_free(fi1);
flattening_info_free(fi2);
}
void PSTT2_final_train(tensor_train* tt, sketch** sketches, int mid)
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int head = 0;
sketch* s1 = sketches[mid-1];
int r1 = s1->r;
sketch* s2 = sketches[mid];
int r2 = s2->r;
int n = tt->n[mid];
MPI_tensor* ten = s1->ten;
MPI_Comm comm = ten->comm;
int size = ten->comm_size;
int* schedule_rank = ten->schedule[rank];
flattening_info* fi1 = flattening_info_init(ten, s1->flattening, s1->iscol, 0);
flattening_info* fi2 = flattening_info_init(ten, s2->flattening, s2->iscol, 0);
matrix_tt* train_mat = matrix_tt_wrap(r1*n, r2, tt->trains[mid]);
matrix_tt_fill_zeros(train_mat);
int tmp_n = 1;
int* mid_partition = ten->partitions[mid];
for (int ii = 0; ii < ten->nps[mid]; ++ii){
int candidate = mid_partition[ii+1] - mid_partition[ii];
tmp_n = (candidate > tmp_n) ? candidate : tmp_n;
}
matrix_tt* tmp = matrix_tt_init(r1, tmp_n);
matrix_tt* recv_mat = (matrix_tt*) calloc(1, sizeof(matrix_tt));
matrix_tt* s_mat1 = (matrix_tt*) calloc(1, sizeof(matrix_tt));
matrix_tt* s_mat2 = (matrix_tt*) calloc(1, sizeof(matrix_tt));
matrix_tt* s_submat2 = (matrix_tt*) calloc(1, sizeof(matrix_tt));
matrix_tt* subtensor_mat = (matrix_tt*) calloc(1, sizeof(matrix_tt));
// Loop over schedule and stream
for (int ii = 0; ii < ten->n_schedule; ++ii){
int block = schedule_rank[ii];
stream(ten, block);
// Get the correct sketch matrices for multiplication
for (int jj = 0; jj < size; ++jj){
int* schedule_jj = ten->schedule[jj];
int block_jj = schedule_jj[ii];
if (block_jj != -1){
// NOTE: Valgrind says I have a memory leak with these allocations.
// I think it's just confused by MPI, but maybe it's worth checking out
flattening_info_update(fi1, ten, block_jj);
sendrecv_sketch_block(recv_mat, s1, fi1, jj, 0);
if (recv_mat->X != NULL){
matrix_tt* swtch = recv_mat;
recv_mat = s_mat1;
s_mat1 = swtch;
}
flattening_info_update(fi2, ten, block_jj);
sendrecv_sketch_block(recv_mat, s2, fi2, jj, 0);
if (recv_mat->X != NULL){
matrix_tt* swtch = recv_mat;
recv_mat = s_mat2;
s_mat2 = swtch;
}
}
}
flattening_info_update(fi1, ten, block);
flattening_info_update(fi2, ten, block);
// Multiply
if (block != -1){
int jj0 = fi1->t_t_index[mid];
int sz = fi1->t_t_sizes[mid];
submatrix_update(tmp, 0, r1, 0, sz);
matrix_tt_wrap_update(subtensor_mat, fi1->f_N, fi1->s_N, get_X(ten));
s_mat1->transpose = 1;
submatrix_update(train_mat, jj0*r1, (jj0 + sz)*r1, 0, r2);
submatrix_update(subtensor_mat, 0, 0, 0, 0);
s_submat2->transpose = s_mat2->transpose;
s_submat2->offset = 0;
s_submat2->lda = s_mat2->lda;
s_submat2->X_size = s_mat2->X_size;
s_submat2->X = s_mat2->X + s_mat2->offset;
for (int jj = 0; jj < fi2->f_N; ++jj){
matrix_tt_reshape(r1, sz, tmp);
submatrix_update(subtensor_mat, 0, fi1->f_N, jj*sz, (jj+1)*sz);
matrix_tt_dgemm(s_mat1, subtensor_mat, tmp, 1.0, 0.0);
matrix_tt_reshape(r1*sz, 1, tmp);
submatrix_update(s_submat2, jj, jj+1, 0, r2);
matrix_tt_dgemm(tmp, s_submat2, train_mat, 1.0, 1.0);
}
}
}
free(recv_mat);
free(s_mat1);
free(s_mat2);
free(s_submat2);
free(subtensor_mat);
flattening_info_free(fi1);
flattening_info_free(fi2);
submatrix_update(train_mat, 0, n*r1, 0, r2);
matrix_tt_reduce(comm, rank, train_mat, NULL, head);
matrix_tt_free(tmp);
free(train_mat);
}
int PSTT2_get_mid(MPI_tensor* ten, int mid)
{
int d = ten->d;
if ((mid > 0) && (mid < d)){
return mid;
}
int* n = ten->n;
long n_left = 1;
long n_right = 1;
for (int ii = 0; ii < d; ++ii){
n_right = (long) n_right * n[ii];
}
for (int ii = 0; ii < d; ++ii){
n_left = (long) n_left * n[ii];
n_right = (long) n_right / n[ii];
if ( (mid == -1) && (n_right < n_left) ){
mid = ii;
}
}
// Just in case, but this should never actually happen
if (mid == -1){
printf("You entered a weird tensor (probably n_i = 1 identically), setting mid = d-1\n");
mid = d-1;
}
return mid;
}
void PSTT2(tensor_train* tt, MPI_tensor* ten, int mid)
{
mid = PSTT2_get_mid(ten, mid);
int rank = ten->rank;
int BUF = 2;
int* r = tt->r;
int d = ten->d;
// Create sketches
sketch** sketches = (sketch**) calloc(d-1, sizeof(sketch*));
for (int ii = 0; ii < d-1; ++ii){
int iscol = (ii < mid) ? 1 : 0; // Column sketch below mid, row sketch above it
sketches[ii] = sketch_init(ten, ii+1, r[ii+1], BUF, iscol);
}
// Sketch the tensor
multi_perform_sketch(sketches, d-1);
for (int ii = 0; ii < d-1; ++ii){
sketch_qr(sketches[ii]);
}
// multiply out the sketches
for (int ii = 0; ii < mid; ++ii){
sketch* s1 = (ii == 0) ? NULL : sketches[ii-1];
sketch* s2 = sketches[ii];
two_sketches_to_train(s1, s2, tt->trains + ii);
}
for (int ii = mid; ii < d-1; ++ii){
sketch* s1 = (ii == d-2) ? NULL : sketches[ii+1];
sketch* s2 = sketches[ii];
two_sketches_to_train(s1, s2, tt->trains + ii + 1);
}
// Get the middle train
PSTT2_final_train(tt, sketches, mid);
// free
for (int ii = 0; ii < d-1; ++ii){
sketch_free(sketches[ii]); sketches[ii] = NULL;
}
free(sketches);
}
void PSTT2_onepass_final_train(tensor_train* tt, sketch** sketches, int mid)
{
sketch* sketch_mid = sketches[mid];
sketch* Q_right = sketches[mid+1];
sketch** Q_left = sketches + mid - 1; //Note that we are using the pointer here to feed into sketch_to_tensor
// Multiply the middle not-QRed sketch against the sketch to its right
int p = sketch_mid->r; // this is r_left + buf
int r_left = tt->r[mid];
int n_mid = tt->n[mid];
int r_right = tt->r[mid+1];
double* b = (double*) malloc(p*n_mid*r_right*sizeof(double)); // Named for the Ax=b solve that we will do later
two_sketches_to_train(sketch_mid, Q_right, &b);
MPI_tensor* ten_left = sketch_to_tensor(Q_left);
sketch* sketch_left = sketch_init_with_Omega(ten_left, ten_left->d - 1, p, 0, 0, sketch_mid->Omegas); // buf = 0, is_col = 0
perform_sketch(sketch_left);
double* A = (double*) calloc(p * r_left, sizeof(double));
two_sketches_to_train(sketch_left, NULL, &A); // This reduces the matrix A
// Solve least squares
matrix_tt* A_mat = matrix_tt_wrap(p, r_left, A);
matrix_tt* b_mat = matrix_tt_wrap(p, n_mid*r_right, b);
matrix_tt* x_mat = matrix_tt_wrap(r_left, n_mid*r_right, tt->trains[mid]);
int head = 0;
if (ten_left->rank == head){
matrix_tt_dgels(x_mat, A_mat, b_mat);
}
// Free
sketch_free(sketch_left); sketch_left = NULL;
MPI_tensor_free(ten_left); ten_left = NULL;
matrix_tt_free(A_mat); A_mat = NULL;
matrix_tt_free(b_mat); b_mat = NULL;
free(x_mat);
}
void PSTT2_onepass(tensor_train* tt, MPI_tensor* ten, int mid)
{
// Number of times in PSTT2: 5
// Number of times in multi_perform_sketch: 3
mid = PSTT2_get_mid(ten, mid);
int rank = ten->rank;
int BUF = 2;
int* r = tt->r;
int d = ten->d;
// Create sketches
sketch** sketches = (sketch**) calloc(d, sizeof(sketch*));
for (int ii = 0; ii < mid; ++ii){
int iscol = 1; // Column sketch below mid, row sketch above it
sketches[ii] = sketch_init(ten, ii+1, r[ii+1], BUF, iscol);
}
// putting the BUF into the rank here, so that two_sketches_to_train and perform_sketch don't get confused in the future
sketches[mid] = sketch_init(ten, mid, r[mid] + BUF, 0, 0);
for (int ii = mid + 1; ii < d; ++ii){
int iscol = 0;
sketches[ii] = sketch_init(ten, ii, r[ii], BUF, iscol);
}
// Sketch the tensor
multi_perform_sketch(sketches, d);
// Find orthogonal basis
for (int ii = 0; ii < mid; ++ii){
sketch_qr(sketches[ii]);
}
for (int ii = mid+1; ii < d; ++ii){
sketch_qr(sketches[ii]);
}
// multiply out the sketches
for (int ii = 0; ii < mid; ++ii){
sketch* s1 = (ii == 0) ? NULL : sketches[ii-1];
sketch* s2 = sketches[ii];
two_sketches_to_train(s1, s2, tt->trains + ii);
}
for (int ii = mid+1; ii < d; ++ii){
sketch* s1 = (ii == d-1) ? NULL : sketches[ii+1];
sketch* s2 = sketches[ii];
two_sketches_to_train(s1, s2, tt->trains + ii);
}
// Get the middle train
PSTT2_onepass_final_train(tt, sketches, mid);
// free
for (int ii = 0; ii < d; ++ii){
if(sketches[ii] != NULL){
sketch_free(sketches[ii]); sketches[ii] = NULL;
}
}
free(sketches);
}
| {
"alphanum_fraction": 0.558305975,
"avg_line_length": 30.5823293173,
"ext": "c",
"hexsha": "1987cc46a867496a85304f391fdb1a7c4aef06a2",
"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": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SidShi/Parallel_TT_sketching",
"max_forks_repo_path": "src/PSTT.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf",
"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": "SidShi/Parallel_TT_sketching",
"max_issues_repo_path": "src/PSTT.c",
"max_line_length": 128,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SidShi/Parallel_TT_sketching",
"max_stars_repo_path": "src/PSTT.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4676,
"size": 15230
} |
#pragma once
#include <gsl-lite/gsl-lite.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/unit_test.hpp>
#include <cuda/runtime_api.hpp>
#include <thrustshift/managed-vector.h>
#include <thrustshift/copy.h>
namespace thrustshift {
template<class MemoryResource>
void touch_all_memory_resource_pages(MemoryResource& memory_resource) {
auto device = cuda::device::current::get();
auto stream = device.default_stream();
for (const auto [k, v] : memory_resource.get_book()) {
for (const auto& page : v) {
BOOST_TEST(!page.allocated);
using T = std::byte;
const size_t N = k.bytes / sizeof(T);
managed_vector<T> dst(N);
gsl_lite::span<T> src(
reinterpret_cast<T*>(page.ptr), N);
async::copy(stream, src, dst);
stream.synchronize();
for (size_t i = 0; i < N; ++i) {
dst[i] = src[i];
}
}
}
}
}
| {
"alphanum_fraction": 0.6752037253,
"avg_line_length": 22.6052631579,
"ext": "h",
"hexsha": "1ac8a3cc1e31013f10c3c8e546244b9205fc0e8a",
"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": "763805f862e3121374286c927dd6949960bffb84",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pauleonix/thrustshift",
"max_forks_repo_path": "test/memory-resource-check.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pauleonix/thrustshift",
"max_issues_repo_path": "test/memory-resource-check.h",
"max_line_length": 71,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pauleonix/thrustshift",
"max_stars_repo_path": "test/memory-resource-check.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z",
"num_tokens": 232,
"size": 859
} |
/* vector/gsl_vector_long_double.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_VECTOR_LONG_DOUBLE_H__
#define __GSL_VECTOR_LONG_DOUBLE_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_block_long_double.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
long double *data;
gsl_block_long_double *block;
int owner;
}
gsl_vector_long_double;
typedef struct
{
gsl_vector_long_double vector;
} _gsl_vector_long_double_view;
typedef _gsl_vector_long_double_view gsl_vector_long_double_view;
typedef struct
{
gsl_vector_long_double vector;
} _gsl_vector_long_double_const_view;
typedef const _gsl_vector_long_double_const_view gsl_vector_long_double_const_view;
/* Allocation */
GSL_FUN gsl_vector_long_double *gsl_vector_long_double_alloc (const size_t n);
GSL_FUN gsl_vector_long_double *gsl_vector_long_double_calloc (const size_t n);
GSL_FUN gsl_vector_long_double *gsl_vector_long_double_alloc_from_block (gsl_block_long_double * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN gsl_vector_long_double *gsl_vector_long_double_alloc_from_vector (gsl_vector_long_double * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN void gsl_vector_long_double_free (gsl_vector_long_double * v);
/* Views */
GSL_FUN _gsl_vector_long_double_view
gsl_vector_long_double_view_array (long double *v, size_t n);
GSL_FUN _gsl_vector_long_double_view
gsl_vector_long_double_view_array_with_stride (long double *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_long_double_const_view
gsl_vector_long_double_const_view_array (const long double *v, size_t n);
GSL_FUN _gsl_vector_long_double_const_view
gsl_vector_long_double_const_view_array_with_stride (const long double *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_long_double_view
gsl_vector_long_double_subvector (gsl_vector_long_double *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_long_double_view
gsl_vector_long_double_subvector_with_stride (gsl_vector_long_double *v,
size_t i,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_long_double_const_view
gsl_vector_long_double_const_subvector (const gsl_vector_long_double *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_long_double_const_view
gsl_vector_long_double_const_subvector_with_stride (const gsl_vector_long_double *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
GSL_FUN void gsl_vector_long_double_set_zero (gsl_vector_long_double * v);
GSL_FUN void gsl_vector_long_double_set_all (gsl_vector_long_double * v, long double x);
GSL_FUN int gsl_vector_long_double_set_basis (gsl_vector_long_double * v, size_t i);
GSL_FUN int gsl_vector_long_double_fread (FILE * stream, gsl_vector_long_double * v);
GSL_FUN int gsl_vector_long_double_fwrite (FILE * stream, const gsl_vector_long_double * v);
GSL_FUN int gsl_vector_long_double_fscanf (FILE * stream, gsl_vector_long_double * v);
GSL_FUN int gsl_vector_long_double_fprintf (FILE * stream, const gsl_vector_long_double * v,
const char *format);
GSL_FUN int gsl_vector_long_double_memcpy (gsl_vector_long_double * dest, const gsl_vector_long_double * src);
GSL_FUN int gsl_vector_long_double_reverse (gsl_vector_long_double * v);
GSL_FUN int gsl_vector_long_double_swap (gsl_vector_long_double * v, gsl_vector_long_double * w);
GSL_FUN int gsl_vector_long_double_swap_elements (gsl_vector_long_double * v, const size_t i, const size_t j);
GSL_FUN long double gsl_vector_long_double_max (const gsl_vector_long_double * v);
GSL_FUN long double gsl_vector_long_double_min (const gsl_vector_long_double * v);
GSL_FUN void gsl_vector_long_double_minmax (const gsl_vector_long_double * v, long double * min_out, long double * max_out);
GSL_FUN size_t gsl_vector_long_double_max_index (const gsl_vector_long_double * v);
GSL_FUN size_t gsl_vector_long_double_min_index (const gsl_vector_long_double * v);
GSL_FUN void gsl_vector_long_double_minmax_index (const gsl_vector_long_double * v, size_t * imin, size_t * imax);
GSL_FUN int gsl_vector_long_double_add (gsl_vector_long_double * a, const gsl_vector_long_double * b);
GSL_FUN int gsl_vector_long_double_sub (gsl_vector_long_double * a, const gsl_vector_long_double * b);
GSL_FUN int gsl_vector_long_double_mul (gsl_vector_long_double * a, const gsl_vector_long_double * b);
GSL_FUN int gsl_vector_long_double_div (gsl_vector_long_double * a, const gsl_vector_long_double * b);
GSL_FUN int gsl_vector_long_double_scale (gsl_vector_long_double * a, const double x);
GSL_FUN int gsl_vector_long_double_add_constant (gsl_vector_long_double * a, const double x);
GSL_FUN int gsl_vector_long_double_isnull (const gsl_vector_long_double * v);
GSL_FUN int gsl_vector_long_double_ispos (const gsl_vector_long_double * v);
GSL_FUN int gsl_vector_long_double_isneg (const gsl_vector_long_double * v);
GSL_FUN int gsl_vector_long_double_isnonneg (const gsl_vector_long_double * v);
GSL_FUN INLINE_DECL long double gsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i);
GSL_FUN INLINE_DECL void gsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x);
GSL_FUN INLINE_DECL long double * gsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i);
GSL_FUN INLINE_DECL const long double * gsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i);
#ifdef HAVE_INLINE
INLINE_FUN
long double
gsl_vector_long_double_get (const gsl_vector_long_double * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return v->data[i * v->stride];
}
INLINE_FUN
void
gsl_vector_long_double_set (gsl_vector_long_double * v, const size_t i, long double x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}
INLINE_FUN
long double *
gsl_vector_long_double_ptr (gsl_vector_long_double * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (long double *) (v->data + i * v->stride);
}
INLINE_FUN
const long double *
gsl_vector_long_double_const_ptr (const gsl_vector_long_double * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (const long double *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_LONG_DOUBLE_H__ */
| {
"alphanum_fraction": 0.69813404,
"avg_line_length": 38.0546218487,
"ext": "h",
"hexsha": "abd22aa6ced4461b73567adb2f739fc8aa840a49",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "deps/include/gsl/gsl_vector_long_double.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "berkus/music-cs",
"max_issues_repo_path": "deps/include/gsl/gsl_vector_long_double.h",
"max_line_length": 125,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "berkus/music-cs",
"max_stars_repo_path": "deps/include/gsl/gsl_vector_long_double.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2074,
"size": 9057
} |
/*
GENETIC - A simple genetic algorithm.
Copyright 2014, 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 population.c
* \brief Header file to define the population functions.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2014 Javier Burguete Tolosa. All rights reserved.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <glib.h>
#include "bits.h"
#include "entity.h"
#include "population.h"
/**
* Function to init a population.
*
* \return 1 on succes, 0 on error.
*/
int
population_new (Population * population, ///< Population.
GeneticVariable * variable, ///< Variables data.
unsigned int nvariables, ///< Number of variables.
unsigned int genome_nbits,
///< Number of bits of each entity genome.
unsigned int nentities, ///< Number of entities.
double mutation_ratio, ///< Mutation ratio.
double reproduction_ratio, ///< Reproduction ratio.
double adaptation_ratio, ///< Adaptation ratio.
double threshold)
///< Threshold to finish the simulations.
{
unsigned int i, nmutations, nreproductions, nadaptations;
nmutations = mutation_ratio * nentities;
nreproductions = reproduction_ratio * nentities;
nadaptations = adaptation_ratio * nentities;
i = nmutations + nreproductions + nadaptations;
if (!i)
{
fprintf (stderr, "ERROR: no evolution\n");
return 0;
}
if (i >= nentities)
{
fprintf (stderr, "ERROR: no survival of entities\n");
return 0;
}
population->nsurvival = nentities - i;
if (population->nsurvival < 2)
{
fprintf (stderr, "ERROR: unable to reproduce the entities\n");
return 0;
}
population->variable = variable;
population->nvariables = nvariables;
population->nentities = nentities;
population->mutation_max = nentities;
population->mutation_min = population->reproduction_max
= nentities - nmutations;
population->reproduction_min = population->adaptation_max
= population->reproduction_max - nreproductions;
population->adaptation_min = population->nsurvival;
population->genome_nbits = genome_nbits;
population->genome_nbytes = bit_sizeof (genome_nbits);
population->objective
= (double *) g_slice_alloc (nentities * sizeof (double));
population->entity = (Entity *) g_slice_alloc (nentities * sizeof (Entity));
for (i = 0; i < population->nentities; ++i)
{
entity_new (population->entity + i, population->genome_nbytes, i);
population->objective[i] = G_MAXDOUBLE;
}
population->threshold = threshold;
population->stop = 0;
return 1;
}
/**
* Function to free the memory allocated in a population.
*/
void
population_init_genomes (Population * population, ///< Population.
gsl_rng * rng) ///< GSL random numbers generator.
{
unsigned int i;
for (i = 0; i < population->nentities; ++i)
entity_init (population->entity + i, rng);
}
/**
* Function to free the memory allocated in a population.
*/
void
population_free (Population * population) ///< Population.
{
unsigned int i, nentities;
nentities = population->nentities;
for (i = 0; i < nentities; ++i)
entity_free (population->entity + i);
g_slice_free1 (nentities * sizeof (Entity), population->entity);
g_slice_free1 (nentities * sizeof (double), population->objective);
}
| {
"alphanum_fraction": 0.698449777,
"avg_line_length": 36.2230769231,
"ext": "c",
"hexsha": "75d3d6e74218659cdd2ac8fec544bdb814100c33",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2017-05-22T08:54:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-05-22T08:54:08.000Z",
"max_forks_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/genetic",
"max_forks_repo_path": "3.0.0/population.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d",
"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/genetic",
"max_issues_repo_path": "3.0.0/population.c",
"max_line_length": 79,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "e7b5473412eeb4bdd9d1f724ab555d7329b7156d",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/genetic",
"max_stars_repo_path": "3.0.0/population.c",
"max_stars_repo_stars_event_max_datetime": "2017-05-02T02:31:16.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-07T07:31:25.000Z",
"num_tokens": 1064,
"size": 4709
} |
/* matrix/gsl_matrix_int.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATRIX_INT_H__
#define __GSL_MATRIX_INT_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_int.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size1;
size_t size2;
size_t tda;
int * data;
gsl_block_int * block;
int owner;
} gsl_matrix_int;
typedef struct
{
gsl_matrix_int matrix;
} _gsl_matrix_int_view;
typedef _gsl_matrix_int_view gsl_matrix_int_view;
typedef struct
{
gsl_matrix_int matrix;
} _gsl_matrix_int_const_view;
typedef const _gsl_matrix_int_const_view gsl_matrix_int_const_view;
/* Allocation */
GSL_FUN gsl_matrix_int *
gsl_matrix_int_alloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_int *
gsl_matrix_int_calloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_int *
gsl_matrix_int_alloc_from_block (gsl_block_int * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
GSL_FUN gsl_matrix_int *
gsl_matrix_int_alloc_from_matrix (gsl_matrix_int * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
GSL_FUN gsl_vector_int *
gsl_vector_int_alloc_row_from_matrix (gsl_matrix_int * m,
const size_t i);
GSL_FUN gsl_vector_int *
gsl_vector_int_alloc_col_from_matrix (gsl_matrix_int * m,
const size_t j);
GSL_FUN void gsl_matrix_int_free (gsl_matrix_int * m);
/* Views */
GSL_FUN _gsl_matrix_int_view
gsl_matrix_int_submatrix (gsl_matrix_int * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_int_view
gsl_matrix_int_row (gsl_matrix_int * m, const size_t i);
GSL_FUN _gsl_vector_int_view
gsl_matrix_int_column (gsl_matrix_int * m, const size_t j);
GSL_FUN _gsl_vector_int_view
gsl_matrix_int_diagonal (gsl_matrix_int * m);
GSL_FUN _gsl_vector_int_view
gsl_matrix_int_subdiagonal (gsl_matrix_int * m, const size_t k);
GSL_FUN _gsl_vector_int_view
gsl_matrix_int_superdiagonal (gsl_matrix_int * m, const size_t k);
GSL_FUN _gsl_vector_int_view
gsl_matrix_int_subrow (gsl_matrix_int * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_int_view
gsl_matrix_int_subcolumn (gsl_matrix_int * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_int_view
gsl_matrix_int_view_array (int * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_int_view
gsl_matrix_int_view_array_with_tda (int * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_int_view
gsl_matrix_int_view_vector (gsl_vector_int * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_int_view
gsl_matrix_int_view_vector_with_tda (gsl_vector_int * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_int_const_view
gsl_matrix_int_const_submatrix (const gsl_matrix_int * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_int_const_view
gsl_matrix_int_const_row (const gsl_matrix_int * m,
const size_t i);
GSL_FUN _gsl_vector_int_const_view
gsl_matrix_int_const_column (const gsl_matrix_int * m,
const size_t j);
GSL_FUN _gsl_vector_int_const_view
gsl_matrix_int_const_diagonal (const gsl_matrix_int * m);
GSL_FUN _gsl_vector_int_const_view
gsl_matrix_int_const_subdiagonal (const gsl_matrix_int * m,
const size_t k);
GSL_FUN _gsl_vector_int_const_view
gsl_matrix_int_const_superdiagonal (const gsl_matrix_int * m,
const size_t k);
GSL_FUN _gsl_vector_int_const_view
gsl_matrix_int_const_subrow (const gsl_matrix_int * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_int_const_view
gsl_matrix_int_const_subcolumn (const gsl_matrix_int * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_int_const_view
gsl_matrix_int_const_view_array (const int * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_int_const_view
gsl_matrix_int_const_view_array_with_tda (const int * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_int_const_view
gsl_matrix_int_const_view_vector (const gsl_vector_int * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_int_const_view
gsl_matrix_int_const_view_vector_with_tda (const gsl_vector_int * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_FUN void gsl_matrix_int_set_zero (gsl_matrix_int * m);
GSL_FUN void gsl_matrix_int_set_identity (gsl_matrix_int * m);
GSL_FUN void gsl_matrix_int_set_all (gsl_matrix_int * m, int x);
GSL_FUN int gsl_matrix_int_fread (FILE * stream, gsl_matrix_int * m) ;
GSL_FUN int gsl_matrix_int_fwrite (FILE * stream, const gsl_matrix_int * m) ;
GSL_FUN int gsl_matrix_int_fscanf (FILE * stream, gsl_matrix_int * m);
GSL_FUN int gsl_matrix_int_fprintf (FILE * stream, const gsl_matrix_int * m, const char * format);
GSL_FUN int gsl_matrix_int_memcpy(gsl_matrix_int * dest, const gsl_matrix_int * src);
GSL_FUN int gsl_matrix_int_swap(gsl_matrix_int * m1, gsl_matrix_int * m2);
GSL_FUN int gsl_matrix_int_swap_rows(gsl_matrix_int * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_int_swap_columns(gsl_matrix_int * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_int_swap_rowcol(gsl_matrix_int * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_int_transpose (gsl_matrix_int * m);
GSL_FUN int gsl_matrix_int_transpose_memcpy (gsl_matrix_int * dest, const gsl_matrix_int * src);
GSL_FUN int gsl_matrix_int_max (const gsl_matrix_int * m);
GSL_FUN int gsl_matrix_int_min (const gsl_matrix_int * m);
GSL_FUN void gsl_matrix_int_minmax (const gsl_matrix_int * m, int * min_out, int * max_out);
GSL_FUN void gsl_matrix_int_max_index (const gsl_matrix_int * m, size_t * imax, size_t *jmax);
GSL_FUN void gsl_matrix_int_min_index (const gsl_matrix_int * m, size_t * imin, size_t *jmin);
GSL_FUN void gsl_matrix_int_minmax_index (const gsl_matrix_int * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_FUN int gsl_matrix_int_equal (const gsl_matrix_int * a, const gsl_matrix_int * b);
GSL_FUN int gsl_matrix_int_isnull (const gsl_matrix_int * m);
GSL_FUN int gsl_matrix_int_ispos (const gsl_matrix_int * m);
GSL_FUN int gsl_matrix_int_isneg (const gsl_matrix_int * m);
GSL_FUN int gsl_matrix_int_isnonneg (const gsl_matrix_int * m);
GSL_FUN int gsl_matrix_int_add (gsl_matrix_int * a, const gsl_matrix_int * b);
GSL_FUN int gsl_matrix_int_sub (gsl_matrix_int * a, const gsl_matrix_int * b);
GSL_FUN int gsl_matrix_int_mul_elements (gsl_matrix_int * a, const gsl_matrix_int * b);
GSL_FUN int gsl_matrix_int_div_elements (gsl_matrix_int * a, const gsl_matrix_int * b);
GSL_FUN int gsl_matrix_int_scale (gsl_matrix_int * a, const double x);
GSL_FUN int gsl_matrix_int_add_constant (gsl_matrix_int * a, const double x);
GSL_FUN int gsl_matrix_int_add_diagonal (gsl_matrix_int * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_FUN int gsl_matrix_int_get_row(gsl_vector_int * v, const gsl_matrix_int * m, const size_t i);
GSL_FUN int gsl_matrix_int_get_col(gsl_vector_int * v, const gsl_matrix_int * m, const size_t j);
GSL_FUN int gsl_matrix_int_set_row(gsl_matrix_int * m, const size_t i, const gsl_vector_int * v);
GSL_FUN int gsl_matrix_int_set_col(gsl_matrix_int * m, const size_t j, const gsl_vector_int * v);
/***********************************************************************/
/* inline functions if you are using GCC */
GSL_FUN INLINE_DECL int gsl_matrix_int_get(const gsl_matrix_int * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL void gsl_matrix_int_set(gsl_matrix_int * m, const size_t i, const size_t j, const int x);
GSL_FUN INLINE_DECL int * gsl_matrix_int_ptr(gsl_matrix_int * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL const int * gsl_matrix_int_const_ptr(const gsl_matrix_int * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
int
gsl_matrix_int_get(const gsl_matrix_int * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
}
}
#endif
return m->data[i * m->tda + j] ;
}
INLINE_FUN
void
gsl_matrix_int_set(gsl_matrix_int * m, const size_t i, const size_t j, const int x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
}
#endif
m->data[i * m->tda + j] = x ;
}
INLINE_FUN
int *
gsl_matrix_int_ptr(gsl_matrix_int * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (int *) (m->data + (i * m->tda + j)) ;
}
INLINE_FUN
const int *
gsl_matrix_int_const_ptr(const gsl_matrix_int * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (const int *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_INT_H__ */
| {
"alphanum_fraction": 0.6531709632,
"avg_line_length": 35.0304709141,
"ext": "h",
"hexsha": "a67df8b2db9b0bede764f0c864e911b5f4b18b8d",
"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": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mharding01/augmented-neuromuscular-RT-running",
"max_forks_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_matrix_int.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834",
"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": "mharding01/augmented-neuromuscular-RT-running",
"max_issues_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_matrix_int.h",
"max_line_length": 128,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mharding01/augmented-neuromuscular-RT-running",
"max_stars_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_matrix_int.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3196,
"size": 12646
} |
/* err/gsl_message.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MESSAGE_H__
#define __GSL_MESSAGE_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
/* Provide a general messaging service for client use. Messages can
* be selectively turned off at compile time by defining an
* appropriate message mask. Client code which uses the GSL_MESSAGE()
* macro must provide a mask which is or'ed with the GSL_MESSAGE_MASK.
*
* The messaging service can be completely turned off
* by defining GSL_MESSAGING_OFF. */
void gsl_message(const char * message, const char * file, int line,
unsigned int mask);
#ifndef GSL_MESSAGE_MASK
#define GSL_MESSAGE_MASK 0xffffffffu /* default all messages allowed */
#endif
GSL_VAR unsigned int gsl_message_mask ;
/* Provide some symolic masks for client ease of use. */
enum {
GSL_MESSAGE_MASK_A = 1,
GSL_MESSAGE_MASK_B = 2,
GSL_MESSAGE_MASK_C = 4,
GSL_MESSAGE_MASK_D = 8,
GSL_MESSAGE_MASK_E = 16,
GSL_MESSAGE_MASK_F = 32,
GSL_MESSAGE_MASK_G = 64,
GSL_MESSAGE_MASK_H = 128
} ;
#ifdef GSL_MESSAGING_OFF /* throw away messages */
#define GSL_MESSAGE(message, mask) do { } while(0)
#else /* output all messages */
#define GSL_MESSAGE(message, mask) \
do { \
if (mask & GSL_MESSAGE_MASK) \
gsl_message (message, __FILE__, __LINE__, mask) ; \
} while (0)
#endif
__END_DECLS
#endif /* __GSL_MESSAGE_H__ */
| {
"alphanum_fraction": 0.7190082645,
"avg_line_length": 29.8765432099,
"ext": "h",
"hexsha": "4d3a9d51302678270ca6428e2938548cd371996c",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z",
"max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "snipekill/FPGen",
"max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_message.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "snipekill/FPGen",
"max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_message.h",
"max_line_length": 81,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "snipekill/FPGen",
"max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_message.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z",
"num_tokens": 600,
"size": 2420
} |
/* W. H. Bell
** A program to generate random numbers obeying a Landau distribution
** using the GNU scientific libraries.
*/
#include <stdio.h>
/* Header files needed for the Landau distribution generator */
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
int main() {
int i;
double ran_num;
const gsl_rng_type * T;
gsl_rng * r;
/* Initialise the random number generator */
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
printf("Loop Num | Value\n");
printf("----------------\n");
for (i=0;i<2500;i++) {
/* Generate a random number obeying the Landau distribution */
ran_num=gsl_ran_landau (r);
printf("%.4d | %lf\n", i, ran_num);
}
return 0;
}
| {
"alphanum_fraction": 0.6416666667,
"avg_line_length": 20.5714285714,
"ext": "c",
"hexsha": "69a81ef7e913daa60a42294487900e5ab54eeacf",
"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": "43b1f1ddccf9a35d34c493fd40fb97e474336bbf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "williamhbell/PhysCIntro",
"max_forks_repo_path": "problem_01/generator/generator.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "43b1f1ddccf9a35d34c493fd40fb97e474336bbf",
"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": "williamhbell/PhysCIntro",
"max_issues_repo_path": "problem_01/generator/generator.c",
"max_line_length": 69,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "43b1f1ddccf9a35d34c493fd40fb97e474336bbf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "williamhbell/PhysCIntro",
"max_stars_repo_path": "problem_01/generator/generator.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 198,
"size": 720
} |
#ifndef BASIC_PARTICLE_H
#define BASIC_PARTICLE_H
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include "basic_changepoint.h"
#include "binary.h"
#include "regime.h"
class particle{
public:
particle(const unsigned long int & start_time = 0, const unsigned long int & end_time = 1, const vector< unsigned long int > & separators = vector< unsigned long int >(0), const changepoint & intercept_changepoint = changepoint(), const double & p = 1, const double & var_p = 0); // this sets m_dimension = 0, sets if m_random_p is true, sets m_var_p
void increase_log_likelihood(const double & likelihood_change);
void increase_log_k_prior(const double & log_k_prior_change){ m_log_k_prior += log_k_prior_change; }
void increase_log_binary_I_prior(const double & log_binary_I_prior_change) { m_log_binary_I_prior += log_binary_I_prior_change; }
void increase_log_full_I_prior(const double & log_full_I_prior_change, const bool & adding_new_regime, const unsigned int & process);
void increase_log_full_I_prior(const double & log_full_I_prior_change, const bool & adding_new_regime, const unsigned int & process, const unsigned int & trace_index, const bool & adding_new_trace);
void decrease_log_full_I_prior(const double & log_full_I_prior_change, const bool & removing_unobserved_regime, const bool & adding_new_regime, const unsigned int & process);
void increase_log_full_I_prior_unobserved(const double & log_full_I_prior_ratio, const vector< int > & unobserved_regime_change);
void increase_log_regimes_prior(const double & log_regimes_prior) { m_log_regimes_prior += log_regimes_prior; }
void set_log_likelihood(const double & log_likelihood) { m_log_likelihood = log_likelihood; }
void set_changepoint_log_likelihood(const int & index, const double & log_likelihood);
void calculate_and_set_log_k_prior();
void calculate_and_set_log_binary_I_prior(const size_t & number_of_processes);
double calculate_and_get_basic_log_likelihood(const size_t & number_of_processes);
double calculate_and_get_binary_log_likelihood(const size_t & number_of_processes);
double calculate_and_get_log_binary_I_prior(const size_t & number_of_processes);
double calculate_and_get_log_full_I_prior(const size_t & number_of_processes);
void set_log_binary_I_prior(const double & prior) { m_log_binary_I_prior = prior; }
void set_log_full_I_prior(const double & prior) { m_log_full_I_prior = prior; }
double calculate_and_get_log_regimes_prior(const size_t & number_of_processes);
void set_log_regimes_prior(const double & prior) { m_log_regimes_prior = prior; }
double calculate_and_get_log_full_separators_prior(const size_t & number_of_processes);
void set_log_full_separators_prior(const double & prior) { m_log_full_separators_prior = prior; }
void set_arbitrary_extension_density(const double & density) {m_log_arbitrary_extension_density = density;}
void increase_arbitrary_extension_density(const double & change) {m_log_arbitrary_extension_density += change;}
double calculate_and_get_full_log_likelihood(const size_t & number_of_processes);
double dirichlet_ratio(const vector< unsigned int > & transitions);
double calculate_and_get_basic_log_posterior(const size_t & number_of_processes);
double calculate_and_get_binary_log_posterior(const size_t & number_of_processes);
double calculate_and_get_full_log_posterior(const size_t & number_of_processes);
void print_likelihood() { std::cout << "the likelihood is " << m_log_likelihood << std::endl; }
void print_sum_of_regime_likelihoods();
void print_log_k_prior() { cout << m_log_k_prior << endl; }
double calculate_and_get_log_k_prior();
void print_log_full_I_prior() { cout << "log_full_I_prior = " << m_log_full_I_prior << endl; }
void print_calculated_log_full_I_prior();
void print_log_regimes_prior() { cout << "log_regimes_prior = " << m_log_regimes_prior << endl; }
void print_calculated_log_regimes_prior();
void add_separator_changepoint(const changepoint & separator_changepoint, unsigned int index); // this sets m_include_separator = true, sets the separator index, adds the separator cp to tau
bool get_include_separator() { return m_include_separator; }
void add_changepoint(const unsigned int & index, const changepoint & new_changepoint);
void remove_changepoint(const unsigned int & remove_index);
void move_changepoint(const unsigned int & index, const unsigned long int & position, const double & left_log_likelihood, const double & right_log_likelihood);
void change_changepoint(const changepoint & changepoint, const unsigned int & change_index);
void add_binary_changepoint(const unsigned int & index, const changepoint & new_changepoint, const vector< bool > & accept_cp, const vector< double > & left_log_likelihood, const vector< double > & right_log_likelihood);
void remove_binary_changepoint(const unsigned int & index, const vector< bool > & remove_effective_cp, const vector< double > & merged_log_likelihood);
void move_binary_changepoint(const unsigned int & index, const unsigned long int & changepoint_position, const vector< bool > & remove_effective_cp, const vector< bool > & accept_cp, const vector< double > & left_log_likelihood, const vector< double > & right_log_likelihood, const vector< double > & merged_log_likelihood);
void resample_binary_changepoint(const unsigned int & index, const vector< bool > & remove_effective_cp, const vector< bool > & accept_cp, const vector< double > & left_log_likelihood, const vector< double > & right_log_likelihood, const vector< double > & merged_log_likelihood);
void add_new_binary(const unsigned int & process, const int & cp_index, const double & log_likelihood);
void add_to_binary(const unsigned int & process, const int & cp_index, const double & combined_log_likelihood);
unsigned int get_dimension() { return m_dimension; }
unsigned int calculate_trace_dimension(const unsigned int & trace_index);
unsigned long int calculate_trace_length(const unsigned int & trace_index);
unsigned int calculate_and_get_full_effective_dimension();
bool is_last_changepoint_effective();
bool is_changepoint_effective_for_process(const unsigned int & cp_index, const unsigned int & process);
bool does_changepoint_introduce_new_regime_for_process(const unsigned int & cp_idx, const unsigned int & process);
changepoint & get_changepoint(int cp_index); // if cp_index = -1 returns m_intercept, otherwise m_tau[cp_intercept]
double get_log_likelihood() { return m_log_likelihood; }
bool does_changepoint_exist_in_particle(const unsigned long int & changepoint_position, int lower = 0, int upper = -1); // checks if any elements in m_tau has position changepoint_position and if it does not, sets m_add_changepoint_index to the position that the changepoint would be added
bool is_changepoint_index_separator_index(const unsigned int & changepoint_index);
unsigned int get_separator_index(const unsigned int & i) { return m_separator_indices[i]; }
unsigned int get_add_changepoint_index() { return m_add_changepoint_index; }
double calculate_and_get_add_cp_proposal_ratio(const unsigned long int & trace_length, const unsigned int & trace_index, const bool & basic_changepoint);
double calculate_and_get_remove_cp_proposal_ratio(const unsigned long int & trace_length = 0, const unsigned int & trace_index = 0, const bool & basic_changepoint = true);
double calculate_and_get_add_cp_k_prior_ratio();
double calculate_and_get_remove_cp_k_prior_ratio();
vector< double > calculate_and_get_binary_log_I_prior_add_ratio(const unsigned int & process);
vector< double > calculate_and_get_binary_log_I_prior_remove_ratio(const unsigned int & process, const bool & removing_effective_cp);
vector< double > calculate_and_get_binary_log_I_prior_move_ratio(const unsigned int & j, const bool & removing_effective_cp);
double full_log_I_prior_add_ratio(const int & index, const bool & new_regime, const unsigned int & process, const unsigned int & previous_regime, const unsigned int & proposed_regime, const unsigned int & subsequent_regime = -1);
double full_log_I_prior_remove_ratio(const int & index, const unsigned int & process, const unsigned int & previous_regime, const unsigned int & proposed_regime, const bool & new_regime, const unsigned int & actual_regime, const bool & removing_unobserved_regime, const unsigned int & subsequent_regime = -1);
double log_resampling_separator_changepoint_prior_ratio(const unsigned int & process, const bool & no_following_regime, const bool & new_regime, const bool & removing_unobserved_regime, const unsigned int & actual_regime = -1, const unsigned int & following_regime = -1, const unsigned int & proposed_regime = -1);
double calculate_and_get_add_unobserved_regimes_full_I_prior_ratio(const vector< bool > & accepted, const size_t & number_of_processes);
double calculate_and_get_add_unobserved_regimes_full_I_prior_ratio(const unsigned int & process);
double calculate_and_get_add_unobserved_regimes_proposal_ratio(const vector< bool > & accepted, const size_t & number_of_processes);
double calculate_and_get_add_unobserved_regimes_regimes_prior_ratio(const vector< bool > & m_adding_unobserved_regimes, const size_t & number_of_processes);
double calculate_and_get_remove_unobserved_regimes_full_I_prior_ratio(const vector< bool > & rejected, const size_t & number_of_processes);
double calculate_and_get_remove_unobserved_regimes_full_I_prior_ratio(const unsigned int & process);
double calculate_and_get_remove_unobserved_regimes_proposal_ratio(const vector< bool > & rejected, const size_t & number_of_processes);
double calculate_and_get_remove_unobserved_regimes_regimes_prior_ratio(const vector< bool > & removing_unobserved_regimes, const size_t & number_of_processes);
vector< double > calculate_and_get_adding_binary_log_I_prior_ratio(const unsigned int & process, const bool & new_trace, const unsigned int & trace_index, const int & new_left_cp_index);
double calculate_and_get_full_adding_binary_log_I_prior_ratio(const unsigned int & process, const unsigned int & regime, const int & number_of_changepoints, const bool & new_trace, const unsigned int & trace_index, const unsigned int & previous_regime);
void set_binary_marked_vectors(const size_t & number_of_processes, const vector< vector< double > > & log_likelihoods);
void initiate_binaries(const size_t & number_of_processes) { m_binaries = vector< vector< binary > >(number_of_processes, vector< binary >(0)); }
void set_all_binary_marked_vectors_equal_to_0_vectors(const size_t & number_of_processes);
void add_end_binaries(const size_t & number_of_processes);
void set_binary_indices_from_full_indices(particle & full_particle, const size_t & number_of_processes);
void set_binary_log_likelihoods(const vector< vector< double > > & log_likelihoods, const size_t & number_of_processes);
void add_full_changepoint(const unsigned int & index, const changepoint & new_changepoint, const vector< unsigned int > & new_regimes, const vector< vector< double > > & sufficient_statistics, const vector< vector< double > > & log_likelihoods, const vector< double > & previous_log_likelihoods, const vector< double > & number_of_observations);
void remove_full_changepoint(const unsigned int & index, const vector< vector< double > > & right_sufficient_statistics_reverse, const vector< double > & actual_log_likelihoods_without_right_sufficient_statistics_rev, const vector< double > & previous_log_likelihoods_with_right_sufficient_statistics_rev, const vector< double > & number_of_observations_rev, const vector< bool > & removing_unobserved_regimes);
void move_full_changepoint(const unsigned int & index, const changepoint & new_changepoint, const vector< unsigned int > & new_regimes, const bool & tau_h_greater_than_tau_h_prime, const vector< vector< double > > & right_sufficient_statistics, const vector< double > & right_number_of_observations, const vector< vector< double > > & right_sufficient_statistics_reverse, const vector< double > & right_number_of_observations_reverse, const vector< vector< double > > & middle_sufficient_statistics, const vector< double > & middle_number_of_observations, const vector< double > & previous_log_likelihoods_without_right_sufficient_statistics, const vector< double > & previous_log_likelihoods_with_right_sufficient_statistics_reverse, const vector< double > & previous_log_likelihoods_with_middle_sufficient_statistics, const vector< double > & previous_log_likelihoods_without_middle_sufficient_statistics, const vector< vector< double > > & log_likelihoods_with_right_sufficient_statistics, const vector< double > & actual_regime_log_likelihoods_with_middle_sufficient_statistics, const vector< double > & actual_regime_log_likelihoods_without_middle_sufficient_statistics, const vector< double > & actual_regime_log_likelihoods_without_right_sufficient_statistics_reverse, const vector< bool > & removing_unobserved_regimes);
void resample_full_changepoint(const unsigned int & index, const vector< unsigned int > & new_regimes, const vector< vector< double > > & right_sufficient_statistics_reverse, const vector< double > & right_number_of_observations_reverse, const vector< vector< double > > & regime_log_likelihoods_with_right_sufficient_statistics_reverse, const vector< double > & actual_log_likelihoods_without_right_sufficient_statistics_reverse, const vector< bool > & removing_unobserved_regimes);
void alter_unobserved_regimes(const vector< int > & altering_unobserved_regimes, const size_t & number_of_processes);
vector< unsigned long int > calculate_and_get_changepoint_histogram(const unsigned long int & m_number_of_changepoint_bins);
// for binary marked vectors, we record a set of bins for each process. Record how many times each interval contains at least 1 effective changepoint for that process.
vector< unsigned long int > calculate_and_get_binary_changepoint_histogram(const unsigned long int & number_of_changepoint_bins, const size_t & number_of_processes);
// for regimes, record a set of bins for each process. Record how many times each interval contains at least 1 effective changepoint for that process.
vector< unsigned long int > calculate_and_get_full_changepoint_histogram(const unsigned long int & number_of_changepoint_bins, const size_t & number_of_processes);
void calculate_and_add_similarity_matrices(vector< vector< double > > & similarity_matrix, const size_t & number_of_processes);
void calculate_and_add_min_proportion_similarity_matrices(vector< vector< double > > & min_proportion_similarity_matrix, const size_t & number_of_processes, const vector< unsigned long int > & actual_number_of_observations);
void add_to_association_matrix(vector< vector< double > > & association_matrix, const unsigned int & process);
double get_basic_log_posterior();
double get_binary_log_posterior();
double get_full_log_posterior();
double get_full_log_SMC_posterior();
double get_log_full_I_prior() { return m_log_full_I_prior; }
double get_log_regimes_prior() { return m_log_regimes_prior; }
vector< unsigned long int > get_vector_of_binary_left_positions(const unsigned int process);
vector< int > get_vector_of_binary_left_indices(const unsigned int process);
int get_binary_left_index(const size_t & process, const unsigned int & index);
int get_binary_right_index(const size_t & process, const unsigned int & index);
unsigned int get_binary_I_i_j(const unsigned int & i, const unsigned int & j);
unsigned int get_full_I_i_j(const unsigned int & i, const unsigned int & j);
vector< int > get_right_changepoint_indices(const unsigned int & process, const unsigned int & regime) { return m_regimes[process][regime].get_right_changepoint_indices(); }
unsigned int get_number_of_right_transitions(const unsigned int & process, const unsigned int & regime) { return m_regimes[process][regime].get_number_of_right_transitions(); }
double get_binary_log_likelihood(const unsigned int & j, const unsigned int & index);
void set_beta_alpha(const double & alpha) { m_beta_alpha = alpha; }
void set_full_marked_vectors(const size_t & number_of_processes, const vector< vector< vector< double > > > & sufficient_statistics, const vector< vector< double > > & number_of_observations);
void set_full_marked_vectors_without_binaries(const size_t & number_of_processes, const vector< vector< vector< double > > > & sufficient_statistics, const vector< vector< double > > & number_of_observations, const vector< vector< double > > & log_likelihoods);
void set_all_full_marked_vectors_equal_to_binary_marked_vectors(const size_t & number_of_processes);
void set_all_regimes_to_be_observed(const size_t & number_of_processes);
void set_number_of_unobserved_regimes(const vector< unsigned int > & number_of_unobserved_regimes) { m_number_of_unobserved_regimes = number_of_unobserved_regimes; }
void initiate_regime_vectors(const size_t & number_of_processes) { m_regimes = vector< vector< regime > >(number_of_processes, vector< regime >(0)); }
void add_new_regime(const unsigned int & process, vector< int > & right_changepoint_indices, vector< unsigned int > & right_transitions, vector< unsigned int > & right_transitions_histogram, vector< double > & sufficient_statistics, double & number_of_observations, double & log_likelihood, size_t & number_of_traces, const bool & new_trace, const unsigned int & trace_index, const unsigned int & previous_regime);
void add_binary_to_regime(const unsigned int & process, const unsigned int & regime_index, const vector< int > & right_changepoint_indices, const vector< unsigned int > & right_transitions, const vector< unsigned int > & right_transitions_histogram, const vector< double > & extra_sufficient_statistics, const unsigned int & extra_number_of_observations, const double & log_likelihood_with_right_sufficient_statistics, const size_t & number_of_traces, const bool & new_trace, const unsigned int & trace_index, const unsigned int & previous_regime);
void set_dirichlet_alpha(const double & alpha) { m_dirichlet_alpha = alpha; }
double get_dirichlet_alpha() { return m_dirichlet_alpha; }
void set_rho(const double & rho) { m_rho = rho; }
double get_rho() { return m_rho; }
size_t get_number_of_binaries(const unsigned int process) { return m_binaries[process].size(); }
size_t get_number_of_regimes(const unsigned int process) { return m_regimes[process].size(); }
vector< unsigned int > get_number_of_unobserved_regimes() { return m_number_of_unobserved_regimes; }
bool is_regime_unobserved(const unsigned int & process, const size_t & regime) { return m_unobserved_regimes[process][regime]; }
unsigned int get_number_of_observed_regimes(const unsigned int & process);
bool removing_full_changepoint_leaves_highest_regime_unobserved(const unsigned int & process, const unsigned int & regime);
bool removing_full_changepoint_leaves_regime_unobserved(const unsigned int & process, const unsigned int & regime);
vector< bool > any_unobserved_regimes();
unsigned int get_previous_regime(const int & cp_index, const unsigned int & process);
vector< double > get_sufficient_statistics(const unsigned int & process, const unsigned int & regime_index);
double get_regime_log_likelihood(const unsigned int & process, const unsigned int & regime_index);
bool deleting_left_changepoint_removes_regime(const unsigned int & process, const unsigned int & regime_index);
void increase_separator_indices_greater_or_equal_to_index(const unsigned int & index);
void decrease_separator_indices_greater_than_index(const unsigned int & index);
void check_unobserved_regimes(const unsigned int process);
void check_separator_changepoints();
void check_observations_in_traces(const unsigned long int & time);
void check_regimes_and_right_changepoints();
void check_full_log_posterior(const bool & always_new_regime);
void check_transitions_out();
// smc-only functions
double calculate_and_get_add_cp_proposal_ratio(const unsigned long int & available_cp_positions, const unsigned long int & total_cp_positions);
double calculate_and_get_remove_cp_proposal_ratio(const unsigned long int & available_cp_positions, const unsigned long int & total_cp_positions);
void extend_regime(const unsigned int & process, const unsigned int & previous_regime, const vector< double > & previous_regime_new_sufficient_statistics, const double & previous_regime_new_log_likelihood, const unsigned int & trace_index, const double & number_of_observations);
void add_full_separator_changepoint(changepoint & separator_changepoint, const vector< unsigned int > & new_regimes, const vector< vector< double > > & sufficient_statistics, const vector< vector< double > > & log_likelihoods, const vector< double > & number_of_observations);
void add_guaranteed_full_changepoint(changepoint & adding_changepoint, const vector< unsigned int > & new_regimes, const vector< vector< double > > & right_sufficient_statistics, const vector< vector< double > > & log_likelihoods_with_right_sufficient_statistics, const vector< double > & right_number_of_observations);
void increase_log_separator_prior(const double & full_log_prior, const bool & adding_new_regime, const unsigned int & process);
void resample_number_of_unobserved_regimes(vector< double > uniform_rvs, vector< unsigned int > new_numbers_of_unobserved_regimes); // can either pass uniform RVs to choose the number of regimes for each process or pass in the number of unobserved regimes for each process
void permute_process_regimes(const unsigned int & process, const vector< unsigned int > & permutation_vector);
bool is_regime_observed_before(const unsigned int & cp_index, const unsigned int & process);
int find_changepoint_with_same_regime(const unsigned int & cp_index, const unsigned int & process);
void add_to_association_matrix_up_to_time(vector< vector< double > > & association_matrix, const unsigned int & process, const unsigned long int & time);
// returns the log of the full I prior ratio if we were adding the changepoint that we are proposing removing with regime proposed_regime. Index gives the position of the changepoint that we are proposing to remove. new_regime gives whether the proposed_regime is a new regime, either in the sense that if the changepoint were deleted it would remove regime proposed_regime, or in the sense that if we were proposing a changepoint here we would be proposing a new regime for it. actual_regime gives the actual regime of the changepoint that we are removing
double full_log_I_prior_smc_remove_ratio(const int & index, const unsigned int & process, const unsigned int & previous_regime, const unsigned int & proposed_regime, const bool & new_regime, const unsigned int & actual_regime, const bool & removing_unobserved_regime, const unsigned int & subsequent_regime = -1);
double log_smc_resampling_separator_changepoint_prior_ratio(const unsigned int & process, const bool & no_following_regime, const bool & new_regime, const bool & removing_unobserved_regime, const unsigned int & actual_regime = -1, const unsigned int & following_regime = -1, const unsigned int & proposed_regime = -1);
void remove_full_changepoint_smc(const unsigned int & index, const vector< vector< double > > & right_sufficient_statistics_reverse, const vector< double > & actual_log_likelihoods_without_right_sufficient_statistics_rev, const vector< double > & previous_log_likelihoods_with_right_sufficient_statistics_rev, const vector< double > & number_of_observations_rev, const vector< bool > & removing_unobserved_regimes);
void move_full_changepoint_smc(const unsigned int & index, const changepoint & new_changepoint, const vector< unsigned int > & new_regimes, const bool & tau_h_greater_than_tau_h_prime, const vector< vector< double > > & right_sufficient_statistics, const vector< double > & right_number_of_observations, const vector< vector< double > > & right_sufficient_statistics_reverse, const vector< double > & right_number_of_observations_reverse, const vector< vector< double > > & middle_sufficient_statistics, const vector< double > & middle_number_of_observations, const vector< double > & previous_log_likelihoods_without_right_sufficient_statistics, const vector< double > & previous_log_likelihoods_with_right_sufficient_statistics_reverse, const vector< double > & previous_log_likelihoods_with_middle_sufficient_statistics, const vector< double > & previous_log_likelihoods_without_middle_sufficient_statistics, const vector< vector< double > > & log_likelihoods_with_right_sufficient_statistics, const vector< double > & actual_regime_log_likelihoods_with_middle_sufficient_statistics, const vector< double > & actual_regime_log_likelihoods_without_middle_sufficient_statistics, const vector< double > & actual_regime_log_likelihoods_without_right_sufficient_statistics_reverse, const vector< bool > & removing_unobserved_regimes);
void resample_full_changepoint_smc(const unsigned int & index, const vector< unsigned int > & new_regimes, const vector< vector< double > > & right_sufficient_statistics_reverse, const vector< double > & right_number_of_observations_reverse, const vector< vector< double > > & regime_log_likelihoods_with_right_sufficient_statistics_reverse, const vector< double > & actual_log_likelihoods_without_right_sufficient_statistics_reverse, const vector< bool > & removing_unobserved_regimes);
double calculate_and_get_log_resampling_last_changepoint_regimes_probability();
double full_log_I_prior_add_ratio_always_new_regime(const unsigned int & process, const bool & new_regime);
double full_log_I_prior_remove_ratio_always_new_regime(const unsigned int & process, const bool & new_regime, const bool & removing_unobserved_regime);
double calculate_and_get_add_unobserved_regimes_full_I_prior_ratio_always_new_regime(const unsigned int & process);
double calculate_and_get_remove_unobserved_regimes_full_I_prior_ratio_always_new_regime(const unsigned int & process);
protected:
unsigned long int m_start;
unsigned long int m_end;
vector< unsigned long int > m_separators;
size_t m_number_of_traces;
unsigned int m_trace_index;
unsigned int m_h_trace_index;
unsigned long int m_intercept;
bool m_include_separator = false;
vector< unsigned int > m_separator_indices;
double m_log_likelihood;
double m_log_k_prior;
double m_log_binary_I_prior;
double m_log_full_I_prior;
double m_log_regimes_prior;
double m_log_full_separators_prior;
double m_log_arbitrary_extension_density;
unsigned int m_dimension;
changepoint m_intercept_changepoint;
vector< bool > m_intercept_binary_marked_vector;
changepoint m_separator_changepoint;
vector< changepoint > m_tau;
vector< vector< binary > > m_binaries;
vector< vector< regime > > m_regimes;
vector< vector< bool > > m_unobserved_regimes;
vector< unsigned int > m_number_of_unobserved_regimes;
double m_p;
double m_var_p;
double m_p_alpha;
double m_p_beta;
bool m_random_p;
double m_beta_alpha;
double m_dirichlet_alpha;
double m_rho;
unsigned int m_add_changepoint_index;
const gsl_rng_type * r_type;
gsl_rng * r;
};
particle::particle(const unsigned long int & start_time, const unsigned long int & end_time, const vector< unsigned long int > & separators, const changepoint & intercept_changepoint, const double & p, const double & var_p):m_start(start_time), m_end(end_time), m_separators(separators), m_number_of_traces(m_separators.size() + 1), m_intercept_changepoint(intercept_changepoint), m_p(p), m_var_p(var_p) {
m_dimension = 0;
m_trace_index = 0;
if (m_var_p > 0) {
m_random_p = true;
if (m_var_p > m_p * (1 - m_p)) {
cerr << "var > mean (1 - mean)";
}
m_p_alpha = m_p * (m_p * (1 - m_p) / m_var_p - 1);
m_p_beta = m_p_alpha * (1 - m_p) / m_p;
} else {
m_random_p = false;
}
gsl_rng_env_setup();
r_type = gsl_rng_default;
r = gsl_rng_alloc(r_type);
gsl_rng_set(r, 1);
}
void particle::increase_log_likelihood(const double & likelihood_change){
m_log_likelihood += likelihood_change;
}
void particle::increase_log_full_I_prior(const double & log_full_I_prior_change, const bool & adding_new_regime, const unsigned int & process) {
m_log_full_I_prior += log_full_I_prior_change;
if (adding_new_regime) {
m_log_full_I_prior -= log(1 - m_rho);
m_log_regimes_prior += log(1 - m_rho);
double number_of_regimes = static_cast< double >(m_regimes[process].size());
m_log_full_I_prior -= static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
m_log_full_separators_prior += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
}
}
void particle::increase_log_full_I_prior(const double & log_full_I_prior_change, const bool & adding_new_regime, const unsigned int & process, const unsigned int & trace_index, const bool & adding_new_trace) {
m_log_full_I_prior += log_full_I_prior_change;
if (adding_new_regime) {
m_log_full_I_prior -= log(1 - m_rho);
m_log_regimes_prior += log(1 - m_rho);
}
double number_of_regimes = static_cast< double >(m_regimes[process].size());
if (!adding_new_trace) {
if (adding_new_regime) {
m_log_full_separators_prior += static_cast< double >(trace_index) * log(static_cast< double >(number_of_regimes) / static_cast< double >(number_of_regimes + 1));
m_log_full_I_prior -= static_cast< double >(trace_index) * log(static_cast< double >(number_of_regimes) / static_cast< double >(number_of_regimes + 1));
}
}
else {
if (adding_new_regime) {
m_log_full_I_prior -= static_cast< double >(trace_index) * log(1 / static_cast< double >(number_of_regimes + 1));
m_log_full_I_prior -= static_cast< double >(trace_index - 1) * log(static_cast< double >(number_of_regimes));
m_log_full_separators_prior += static_cast< double >(trace_index) * log(1 / static_cast< double >(number_of_regimes + 1));
m_log_full_separators_prior += static_cast< double >(trace_index - 1) * log(static_cast< double >(number_of_regimes));
}
else {
m_log_full_I_prior -= log(1 / static_cast< double >(number_of_regimes));
m_log_full_separators_prior += log(1 / static_cast< double >(number_of_regimes));
}
}
}
void particle::decrease_log_full_I_prior(const double & log_full_I_prior_change, const bool & removing_unobserved_regime, const bool & adding_new_regime, const unsigned int & process) {
m_log_full_I_prior -= log_full_I_prior_change;
if (removing_unobserved_regime != adding_new_regime) {
if (removing_unobserved_regime) {
m_log_full_I_prior += log(1 - m_rho);
m_log_regimes_prior -= log(1 - m_rho);
double number_of_regimes = static_cast< double >(m_regimes[process].size());
m_log_full_I_prior += static_cast< double >(m_separator_indices.size()) * log((number_of_regimes - 1) / (number_of_regimes));
m_log_full_separators_prior -= static_cast< double >(m_separator_indices.size()) * log((number_of_regimes - 1) / (number_of_regimes));
}
else {
m_log_full_I_prior -= log(1 - m_rho);
m_log_regimes_prior += log(1 - m_rho);
double number_of_regimes = static_cast< double >(m_regimes[process].size());
m_log_full_I_prior -= static_cast< double >(m_separator_indices.size()) * log((number_of_regimes) / (number_of_regimes + 1));
m_log_full_separators_prior += static_cast< double >(m_separator_indices.size()) * log((number_of_regimes) / (number_of_regimes + 1));
}
}
}
void particle::increase_log_full_I_prior_unobserved(const double & log_full_I_prior_ratio, const vector< int > & unobserved_regime_change) {
m_log_full_I_prior += log_full_I_prior_ratio;
for (unsigned int process = 0; process < unobserved_regime_change.size(); process++) {
if (unobserved_regime_change[process] == 1) {
double number_of_regimes = static_cast< double >(m_regimes[process].size());
double s = static_cast< double >(m_separator_indices.size());
m_log_full_I_prior -= s * log(number_of_regimes / (number_of_regimes + 1));
m_log_full_separators_prior += s * log(number_of_regimes / (number_of_regimes + 1));
}
else if (unobserved_regime_change[process] == -1) {
double number_of_regimes = static_cast< double >(m_regimes[process].size());
double s = static_cast< double >(m_separator_indices.size());
m_log_full_I_prior -= s * log(number_of_regimes / (number_of_regimes - 1));
m_log_full_separators_prior += s * log(number_of_regimes / (number_of_regimes - 1));
}
}
}
void particle::set_changepoint_log_likelihood(const int & index, const double & log_likelihood) {
if (index < 0) {
m_intercept_changepoint.set_log_likelihood(log_likelihood);
}
else {
m_tau[index].set_log_likelihood(log_likelihood);
}
}
void particle::calculate_and_set_log_k_prior(){
if(m_random_p){
m_log_k_prior = gsl_sf_lnbeta(static_cast< double >(m_dimension) + m_p_alpha, m_end - static_cast< double >(m_dimension)) - gsl_sf_lnbeta(m_p_alpha, m_p_beta);
} else {
m_log_k_prior = static_cast< double >(m_dimension) * log(m_p) + static_cast< double >(m_end - m_dimension) * log(1 - m_p);
}
}
void particle::calculate_and_set_log_binary_I_prior(const size_t & number_of_processes){
m_log_binary_I_prior = 0;
double k = static_cast< double >(m_dimension);
double seps = static_cast< double >(m_number_of_traces - 1);
for (unsigned int j = 0; j < number_of_processes; j++){
double k_j = static_cast< double >(m_binaries[j].size()) - 2;
m_log_binary_I_prior += gsl_sf_lnbeta(m_beta_alpha + k_j - seps, m_beta_alpha + k - k_j) - gsl_sf_lnbeta(m_beta_alpha, m_beta_alpha); // don't need seps in m_beta_alpha + k - k_j as would add and subtract
}
}
double particle::calculate_and_get_basic_log_likelihood(const size_t & number_of_processes) {
double basic_log_likelihood = m_intercept_changepoint.get_log_likelihood();
for (unsigned int cp_idx = 0; cp_idx < m_dimension; cp_idx++) {
basic_log_likelihood += m_tau[cp_idx].get_log_likelihood();
}
return basic_log_likelihood;
}
// calculate log likelihood by proceeding adding the log likelihood values stored in the binaries
double particle::calculate_and_get_binary_log_likelihood(const size_t & number_of_processes) {
double log_likelihood = 0;
for (unsigned int j = 0; j < number_of_processes; j++) {
for (unsigned int i = 0; i < m_binaries[j].size() - 1; i++) {
log_likelihood += m_binaries[j][i].get_log_likelihood();
}
}
return log_likelihood;
}
double particle::calculate_and_get_log_binary_I_prior(const size_t & number_of_processes) {
double log_binary_I_prior = 0;
double k = static_cast< double >(m_dimension);
double seps = static_cast< double >(m_number_of_traces - 1);
for (unsigned int j = 0; j < number_of_processes; j++){
double k_j = static_cast< double >(m_binaries[j].size()) - 2;
log_binary_I_prior += gsl_sf_lnbeta(m_beta_alpha + k_j - seps, m_beta_alpha + k - k_j) - gsl_sf_lnbeta(m_beta_alpha, m_beta_alpha);
}
return log_binary_I_prior;
}
// use m_regimes to calculate the log prior for the regimes
double particle::calculate_and_get_log_full_I_prior(const size_t & number_of_processes) {
double log_prior = 0;
for (unsigned int process = 0; process < number_of_processes; process++) {
for (unsigned int regime = 0; regime < m_regimes[process].size(); regime++) {
log_prior += dirichlet_ratio(m_regimes[process][regime].get_right_transitions_histogram());
}
}
return log_prior;
}
// use m_regimes to calculate the log regimes prior
double particle::calculate_and_get_log_regimes_prior(const size_t & number_of_processes) {
double log_prior = static_cast< double >(number_of_processes) * log(m_rho);
for (unsigned int j = 0; j < number_of_processes; j++) {
log_prior += static_cast< double >(m_regimes[j].size() - 1) * log(1 - m_rho);
}
return log_prior;
}
// use m_regimes to calculate the prior for the separators (since there are no regime transitions to separators)
double particle::calculate_and_get_log_full_separators_prior(const size_t & number_of_processes) {
double log_separators_prior = 0;
for (unsigned int j = 0; j < number_of_processes; j++) {
double r_j = static_cast< double >(m_regimes[j].size());
double s = static_cast< double >(m_separators.size());
log_separators_prior += s * log(1 / r_j);
}
return log_separators_prior;
}
// calculate the log likelihood for the whole multivariate process using information stored in m_regimes
double particle::calculate_and_get_full_log_likelihood(const size_t & number_of_processes) {
double log_likelihood = 0;
for (unsigned int process = 0; process < number_of_processes; process++) {
for (unsigned int regime_index = 0; regime_index < m_regimes[process].size(); regime_index++) {
log_likelihood += m_regimes[process][regime_index].get_log_likelihood();
}
}
return log_likelihood;
}
// given a histogram of transitions out of a regime, calculate the contribution of that regime to the full log regime prior
double particle::dirichlet_ratio(const vector< unsigned int > & transitions) {
double ratio = 0;
double transitions_out = 0;
double alpha_sum = 0;
// for each regime that can be transitioned to, calculate the gamma ratio G(alpha + k_{u,v}) / G(alpha) and add the log of it to ratio
for (unsigned int regime = 0; regime < transitions.size(); regime++) {
double trans = static_cast< double >(transitions[regime]);
transitions_out += trans;
ratio += gsl_sf_lngamma(trans + m_dirichlet_alpha) - gsl_sf_lngamma(m_dirichlet_alpha);
alpha_sum += m_dirichlet_alpha;
}
// calculate the ratio G(alpha + ... + alpha) / G(k_{u,1} + alpha + ... + k_{u,r} + alpha) and add log of it to ratio
ratio += gsl_sf_lngamma(alpha_sum) - gsl_sf_lngamma(alpha_sum + transitions_out);
return ratio;
}
double particle::calculate_and_get_basic_log_posterior(const size_t & number_of_processes) {
double log_k_prior = 0;
log_k_prior = calculate_and_get_log_k_prior();
double basic_log_likelihood;
basic_log_likelihood = calculate_and_get_basic_log_likelihood(number_of_processes);
return basic_log_likelihood + log_k_prior;
}
double particle::calculate_and_get_binary_log_posterior(const size_t & number_of_processes) {
double log_k_prior = 0;
log_k_prior = calculate_and_get_log_k_prior();
double binary_log_I_prior;
binary_log_I_prior = calculate_and_get_log_binary_I_prior(number_of_processes);
double binary_log_likelihood;
binary_log_likelihood = calculate_and_get_binary_log_likelihood(number_of_processes);
return binary_log_likelihood + binary_log_I_prior + log_k_prior;
}
double particle::calculate_and_get_full_log_posterior(const size_t & number_of_processes) {
double log_k_prior = 0;
log_k_prior = calculate_and_get_log_k_prior();
double full_log_I_prior;
full_log_I_prior = calculate_and_get_log_full_I_prior(number_of_processes);
double full_log_regime_prior;
full_log_regime_prior = calculate_and_get_log_regimes_prior(number_of_processes);
double full_log_separators_prior;
full_log_separators_prior = calculate_and_get_log_full_separators_prior(number_of_processes);
double full_log_likelihood;
full_log_likelihood = calculate_and_get_full_log_likelihood(number_of_processes);
return full_log_likelihood + full_log_regime_prior + full_log_I_prior + log_k_prior + full_log_separators_prior;
}
void particle::print_sum_of_regime_likelihoods() {
double sum = 0;
for (unsigned int j = 0; j < m_regimes.size(); j++) {
for (unsigned int i = 0; i < m_regimes[j].size(); i++) {
sum += m_regimes[j][i].get_log_likelihood();
}
}
cout << sum << endl;
}
double particle::calculate_and_get_log_k_prior(){
if(m_random_p){
return gsl_sf_lnbeta(static_cast< double >(m_dimension) + m_p_alpha, m_end - static_cast< double >(m_dimension)) - gsl_sf_lnbeta(m_p_alpha, m_p_beta);
} else {
return static_cast< double >(m_dimension) * log(m_p) + static_cast< double >(m_end - m_dimension) * log(1 - m_p);
}
}
void particle::print_calculated_log_regimes_prior() {
// check if the number of unobserved regimes is right
for (unsigned int j = 0; j < m_unobserved_regimes.size(); j++) {
unsigned int number_of_unobserved_regimes = 0;
for (unsigned int i = 0; i < m_unobserved_regimes[j].size(); i++) {
number_of_unobserved_regimes += m_unobserved_regimes[j][i] ? 1 : 0;
}
if (number_of_unobserved_regimes != m_number_of_unobserved_regimes[j]) {
cerr << "number of unobserved regimes does not match";
}
}
// calculate the log regimes prior
double prior = 0;
for (unsigned int j = 0; j < m_unobserved_regimes.size(); j++) {
prior += log(m_rho) + static_cast< double >(m_regimes[j].size() - 1) * log(1 - m_rho);
}
cout << "regimes prior " << prior << endl;
}
// add a separator changepoint (assumed to be at the end of the set of separator changepoints already added)
void particle::add_separator_changepoint(const changepoint & separator_changepoint, unsigned int index) {
m_separator_indices.push_back(index);
m_tau.insert(m_tau.begin() + index, separator_changepoint);
m_include_separator = true;
m_dimension++;
}
void particle::add_changepoint(const unsigned int & index, const changepoint & new_changepoint) {
m_tau.insert(m_tau.begin() + index, new_changepoint);
if (m_include_separator) {
// increase by 1 the cp_index of any separator that is greater than or equal to index
increase_separator_indices_greater_or_equal_to_index(index);
}
m_dimension++;
}
void particle::remove_changepoint(const unsigned int & remove_index) {
m_tau.erase(m_tau.begin() + remove_index);
if (m_include_separator) {
// increase by 1 the cp_index of any separator that is greater than or equal to index
decrease_separator_indices_greater_than_index(remove_index);
}
m_dimension--;
}
void particle::move_changepoint(const unsigned int & index, const unsigned long int & position, const double & left_log_likelihood, const double & right_log_likelihood) {
m_tau[index].set_log_likelihood(right_log_likelihood);
m_tau[index].set_position(position);
if (index == 0) {
m_intercept_changepoint.set_log_likelihood(left_log_likelihood);
}
else {
m_tau[index - 1].set_log_likelihood(left_log_likelihood);
}
}
void particle::change_changepoint(const changepoint & changepoint, const unsigned int & change_index){
m_tau[change_index] = changepoint;
}
// index gives the position for the new cp, new_changepoint is a changepoint object with position, accept_cp is a vector of bools giving which processes accept the cp, left_log_likelihood gives the log likelihood for the binary to the left of the new cp, and right_log_likelihood gives the log likelihood that would be created by the new cp if it is accepted for each process
void particle::add_binary_changepoint(const unsigned int & index, const changepoint & new_changepoint, const vector< bool > & accept_cp, const vector< double > & left_log_likelihood, const vector< double > & right_log_likelihood){
m_tau.insert(m_tau.begin() + index, new_changepoint); //insert new cp in correct place in tau
m_dimension++; //increase dimension
size_t number_of_processes = accept_cp.size();
if (m_include_separator) {
increase_separator_indices_greater_or_equal_to_index(index);
}
//start by assigning the vector of binary indices to be the same as the binary indices for the previous changepoint.
if (index == 0) {
m_tau[index].set_binary_index(m_intercept_changepoint.get_binary_index());
}
else {
m_tau[index].set_binary_index(m_tau[index - 1].get_binary_index());
}
for (unsigned int j = 0; j < number_of_processes; j++) {
unsigned int prev_binary_index;
// calculate the binary index of the previous changepoint
if (index == 0) {
prev_binary_index = 0;
}
else {
prev_binary_index = m_tau[index - 1].get_binary_index_row(j);
}
if (accept_cp[j]){ //if process j accepts the new cp
// set the log likelihood for the previous binary
m_binaries[j][prev_binary_index].set_log_likelihood(left_log_likelihood[j]);
// insert a new binary beginning at the new changepoint.
m_binaries[j].insert(m_binaries[j].begin() + prev_binary_index + 1, binary(right_log_likelihood[j], index));
// for every cp after (and including) index, increase the binary index for process j
for (unsigned int cp_index = index; cp_index < m_dimension; cp_index++){
m_tau[cp_index].increase_binary_index_row(j, 1);
}
// for every binary after the one that has just been inserted, increase the left index for process j.
for (unsigned int binary_index = prev_binary_index + 2; binary_index < m_binaries[j].size(); binary_index++) {
m_binaries[j][binary_index].increase_left_index(1);
}
}
else { // process j does not affect the new cp
// for every binary after prev_binary_index, we need to increase the left indent because we have inserted a new changepoint.
for (unsigned int binary_index = prev_binary_index + 1; binary_index < m_binaries[j].size(); binary_index++) {
m_binaries[j][binary_index].increase_left_index(1);
}
}
}
}
// index gives the position to remove the changepoint from tau, remove_effective_cp details if the changepoint to be removed affected each process, and merged log likelihood gives the log likelihood for the entire interval for the merged binary if the removed cp did affect the process
void particle::remove_binary_changepoint(const unsigned int & index, const vector< bool > & remove_effective_cp, const vector< double > & merged_log_likelihood) {
m_tau.erase(m_tau.begin() + index); // erase the chosen cp
m_dimension--; //reduce the dimension
size_t number_of_processes = remove_effective_cp.size();
if (m_include_separator) {
// decrease by 1 the cp_index of any separator that is greater than or equal to index
decrease_separator_indices_greater_than_index(index);
}
for (unsigned int j = 0; j < number_of_processes; j++){
unsigned int prev_binary_index;
// calculate the binary index of the previous changepoint (for process j)
if (index == 0) {
prev_binary_index = 0;
}
else {
prev_binary_index = m_tau[index - 1].get_binary_index_row(j);
}
if (remove_effective_cp[j]){ // if process j was affected by the removed cp
// set the log likelihood for the merged binary to be the merged log likelihood
m_binaries[j][prev_binary_index].set_log_likelihood(merged_log_likelihood[j]);
m_binaries[j].erase(m_binaries[j].begin() + prev_binary_index + 1);
// every cp after the deleted one is now in a binary with index one less than before the removal
for (unsigned int cp_index = index; cp_index < m_dimension; cp_index++){
m_tau[cp_index].increase_binary_index_row(j, -1);
}
// every binary after the previous_binary_index now drops its left index by 1
for (unsigned int binary_index = prev_binary_index + 1; binary_index < m_binaries[j].size(); binary_index++) {
m_binaries[j][binary_index].increase_left_index(-1);
}
}
else { // if process j was unaffected by the removed cp
for (unsigned int binary_index = prev_binary_index + 1; binary_index < m_binaries[j].size(); binary_index++) {
// need to drop the left index for every binary after prev_binary_index
m_binaries[j][binary_index].increase_left_index(-1);
}
}
}
}
// index gives the position of the changepoint to move (it will keep this index after it moves), changepoint position gives the position to move the changepoint to, remove_effective_cp states whether the cp that is being moved and resampled affects each process, accept_cp states whether the resampled cp affects each process, left log_likelihood gives the log_likelihood for each process if the new cp affects process j, right_log_likelihood is similar, merged_log_likelihood gives the likelihood for the binary that contains the moved changepoint if the changepoint does not affect process j.
void particle::move_binary_changepoint(const unsigned int & index, const unsigned long int & changepoint_position, const vector< bool > & remove_effective_cp, const vector< bool > & accept_cp, const vector< double > & left_log_likelihood, const vector< double > & right_log_likelihood, const vector< double > & merged_log_likelihood) {
m_tau[index].set_position(changepoint_position); // change the position of the moved cp
size_t number_of_processes = remove_effective_cp.size();
for (unsigned int j = 0; j < number_of_processes; j++){
unsigned int prev_binary_index;
// calculate the binary index of the previous cp
if (index == 0) {
prev_binary_index = 0;
}
else {
prev_binary_index = m_tau[index - 1].get_binary_index_row(j);
}
if (remove_effective_cp[j]) {
if (accept_cp[j]) { // if the cp that was moved affected process j and the new one also affects process j
m_binaries[j][prev_binary_index].set_log_likelihood(left_log_likelihood[j]);
m_binaries[j][prev_binary_index + 1].set_log_likelihood(right_log_likelihood[j]);
}
else { // if the cp that was moved affected process j and the new one doesn't affect process j
m_binaries[j][prev_binary_index].set_log_likelihood(merged_log_likelihood[j]);
m_binaries[j].erase(m_binaries[j].begin() + prev_binary_index + 1);
// the old cp was in m_binaies[j][prev_binary_index + 1] but this binary is deleted now, so m_tau[index], ..., m_tau[dimension - 1] should all drop their binary index for process j
for (unsigned int cp_index = index; cp_index < m_dimension; cp_index++) {
m_tau[cp_index].increase_binary_index_row(j, -1);
}
}
}
else {
if (accept_cp[j]) { // if the cp that was moved didn't affect process j and the new one does affect process j
// correct the log likelihood for the prev_binary_index binary object
m_binaries[j][prev_binary_index].set_log_likelihood(left_log_likelihood[j]);
// need to create a new binary
m_binaries[j].insert(m_binaries[j].begin() + prev_binary_index + 1, binary(right_log_likelihood[j], index));
// m_tau[index] was in binary prev_binary_index. Now m_tau[cp_index] and all indices above it should increase their binary index by 1
for (unsigned int cp_index = index; cp_index < m_dimension; cp_index++){
m_tau[cp_index].increase_binary_index_row(j, 1);
}
}
}
}
}
// index gives the position of the changepoint to resample, remove_effective_cp states whether the cp that is being resampled affects each process, accept_cp states whether the resampled cp affects each process, left log_likelihood gives the log_likelihood for each process if the resampled cp affects process j, right_log_likelihood is similar, merged_log_likelihood gives the likelihood for the binary that contains the resampled changepoint if it doesn't affect process j.
void particle::resample_binary_changepoint(const unsigned int & index, const vector< bool > & remove_effective_cp, const vector< bool > & accept_cp, const vector< double > & left_log_likelihood, const vector< double > & right_log_likelihood, const vector< double > & merged_log_likelihood) {
size_t number_of_processes = remove_effective_cp.size();
for (unsigned int j = 0; j < number_of_processes; j++){
if (remove_effective_cp[j] != accept_cp[j]) { // if they are equal then there is no change so we don't need to do anything
unsigned int prev_binary_index;
// calculate the binary index of the previous cp
if (index == 0) {
prev_binary_index = 0;
}
else {
prev_binary_index = m_tau[index - 1].get_binary_index_row(j);
}
if (accept_cp[j]) { // accept the resampled cp, didn't accept the cp previously
m_binaries[j][prev_binary_index].set_log_likelihood(left_log_likelihood[j]);
// create a new binary starting at the resampled cp
m_binaries[j].insert(m_binaries[j].begin() + prev_binary_index + 1, binary(right_log_likelihood[j], index));
for (unsigned int cp_index = index; cp_index < m_dimension; cp_index++){
// increase the binary index for the resampled cp and all those above it for process j
m_tau[cp_index].increase_binary_index_row(j, 1);
}
}
else if (remove_effective_cp[j]) { // accepted the cp before, don't accept it now
m_binaries[j][prev_binary_index].set_log_likelihood(merged_log_likelihood[j]);
// remove the binary object that contained the resampled cp
m_binaries[j].erase(m_binaries[j].begin() + prev_binary_index + 1);
for (unsigned int cp_index = index; cp_index < m_dimension; cp_index++) {
// redo the binary index for m_tau[index], ..., m_tau[m_dimension - 1]
m_tau[cp_index].increase_binary_index_row(j, -1);
}
}
}
}
}
void particle::add_new_binary(const unsigned int & process, const int & cp_index, const double & log_likelihood) {
m_binaries[process].push_back(binary(log_likelihood, cp_index));
//m_log_likelihood += log_likelihood; don't need this as done before
//alter the binary index of the changepoint cp_index
if (-1 < cp_index) {
m_tau[cp_index].set_binary_index_row(process, static_cast< unsigned int >(m_binaries[process].size() - 1));
}
}
void particle::add_to_binary(const unsigned int & process, const int & cp_index, const double & combined_log_likelihood) {
//m_log_likelihood += combined_log_likelihood - m_binaries[process].back().get_log_likelihood();
m_binaries[process].back().set_log_likelihood(combined_log_likelihood);
//alter the binary index of the changepoint cp_index
if (-1 < cp_index) {
m_tau[cp_index].set_binary_index_row(process, static_cast< unsigned int >(m_binaries[process].size() - 1));
}
}
changepoint & particle::get_changepoint(int cp_index){
if(cp_index < 0){
return m_intercept_changepoint;
} else {
return m_tau[cp_index];
}
}
// returns if a cp with changepoint_position exists in the particle. If it doesn't exist, m_add_changepoint_index is set to the add_changepoint_index
bool particle::does_changepoint_exist_in_particle(const unsigned long int & changepoint_position, int lower, int upper){//lower defaults to 0, upper to -1
if(m_dimension == 0){
m_add_changepoint_index = 0;
return false;
}
if (upper == -1) {
upper = m_dimension - 1;
}
while (upper >= lower) {
unsigned int mid = (lower + upper) / 2;
unsigned long int mid_position = m_tau[ mid ].get_position();
if(mid_position == changepoint_position)
return true;
else if(mid_position < changepoint_position)
lower = mid + 1;
else
upper = mid - 1;
}
if (lower >= m_dimension) {
lower = m_dimension - 1;
}
if (m_tau[ lower ].get_position() > changepoint_position) {
m_add_changepoint_index = lower;
} else {
m_add_changepoint_index = lower + 1;
}
return false;
}
// searches for changepoint in the separator indices, returning true if it is a separator index. If it is not a separator index, false is returned and m_trace_index is set to be the index of the trace that contains the changepoint index
bool particle::is_changepoint_index_separator_index(const unsigned int & changepoint_index) {
if (!m_include_separator || changepoint_index == numeric_limits< unsigned int >::max()) {
m_trace_index = 0;
return false;
} else {
// run a binary search to check if changepoint_index is contained within m_separator_indices
int low = 0, high = static_cast< unsigned int >(m_separator_indices.size() - 1);
while (low <= high) {
int mid = (low + high) / 2;
if (m_separator_indices[mid] == changepoint_index) {
m_trace_index = static_cast< unsigned int >(mid + 1);
return true;
}
else if (m_separator_indices[mid] < changepoint_index) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
if (low >= m_separator_indices.size()) {
low = static_cast< int >(m_separator_indices.size() - 1);
}
if (changepoint_index < m_separator_indices[low]) {
m_trace_index = static_cast< unsigned int >(low);
}
else {
m_trace_index = static_cast< unsigned int >(low + 1);
}
return false;
}
}
// probability of adding the cp we did is 1/(end - dimension). Probability of the reverse move (removing the cp we are now adding) is 1 / (dimension + 1)
double particle::calculate_and_get_add_cp_proposal_ratio(const unsigned long int & trace_length = 0, const unsigned int & trace_index = 0, const bool & basic_changepoint = true) {
unsigned int trace_dimension = calculate_trace_dimension(trace_index);
double proposal_ratio = log(static_cast< double >(trace_length - trace_dimension));
proposal_ratio -= log(static_cast< double >(trace_dimension) + 1);
if (trace_dimension == 0) {
if (basic_changepoint) {
proposal_ratio -= log(3);
}
else {
proposal_ratio -= log(4);
}
}
return proposal_ratio;
}
// probability of adding the cp we are deleting is 1 / (end - (dimension - 1)). Probability of removing the cp is 1 / (dimension)
double particle::calculate_and_get_remove_cp_proposal_ratio(const unsigned long int & trace_dimension, const unsigned int & trace_index, const bool & basic_changepoint) {
unsigned long int trace_length = calculate_trace_length(trace_index);
double proposal_ratio = log(static_cast< double >(trace_dimension));
proposal_ratio -= log(static_cast< double >(trace_length) - static_cast< double >(trace_dimension - 1));
if (trace_dimension == 1) {
if (basic_changepoint) {
proposal_ratio += log(3);
}
else {
proposal_ratio += log(4);
}
}
return proposal_ratio;
/*if (m_include_separator) {
return log(static_cast< double >(m_dimension - m_number_of_traces + 1)) - log(m_end - static_cast< double >(m_dimension) + 1); //log(m_dimension - (m_number_of_traces - 1)) as can't choose to remove a separator
} else {
return log(static_cast< double >(m_dimension)) - log(m_end - static_cast< double >(m_dimension) + 1);
}*/
}
double particle::calculate_and_get_add_cp_k_prior_ratio(){
if (m_random_p) {
return log(static_cast< double >(m_dimension) + m_p_alpha) - log(m_end - static_cast< double >(m_dimension) + m_p_beta);
} else {
return log(m_p) - log(1 - m_p);
}
}
double particle::calculate_and_get_remove_cp_k_prior_ratio(){
if(m_random_p){
return log(m_end - static_cast< double >(m_dimension) + 1 + m_p_beta) - log(static_cast< double >(m_dimension) - 1 + m_p_alpha);
} else {
return log(1 - m_p) - log(m_p);
}
}
vector< double > particle::calculate_and_get_binary_log_I_prior_add_ratio(const unsigned int & process) {
vector< double > q = vector< double >(2, 0);
double k = static_cast< double >(m_dimension);
double k_j = static_cast< double >(m_binaries[process].size()) - 2;
double seps = static_cast< double >(m_number_of_traces - 1);
q[0] = log(m_beta_alpha + k - k_j) - log(m_beta_alpha + m_beta_alpha + k - seps); // don't need to do (-m_number_of_trace + 1) for the first one as we would add and subtract this
q[1] = log(m_beta_alpha + k_j - seps) - log(m_beta_alpha + m_beta_alpha + k - seps);
return q;
}
vector< double > particle::calculate_and_get_binary_log_I_prior_remove_ratio(const unsigned int & process, const bool & removing_effective_cp){
vector< double > q = vector< double >(2, 0);
double k = static_cast< double >(m_dimension);
double k_j = static_cast< double >(m_binaries[process].size()) - 2;
double seps = static_cast< double >(m_number_of_traces - 1);
if (!removing_effective_cp){
q[0] = log(m_beta_alpha + (k - 1) - k_j) - log(m_beta_alpha + m_beta_alpha + (k - 1) - seps);
q[1] = log(m_beta_alpha + k_j - seps) - log(m_beta_alpha + m_beta_alpha + (k - 1) - seps);
} else {
q[0] = log(m_beta_alpha + (k - 1) - (k_j - 1)) - log(m_beta_alpha + m_beta_alpha + (k - 1) - seps);
q[1] = log(m_beta_alpha + (k_j - 1) - seps) - log(m_beta_alpha + m_beta_alpha + (k - 1) - seps);
}
return q;
}
vector< double > particle::calculate_and_get_binary_log_I_prior_move_ratio(const unsigned int & process, const bool & removing_effective_cp){
vector< double > q = vector< double >(2, 0);
double k = static_cast< double >(m_dimension);
double k_j = static_cast< double >(m_binaries[process].size()) - 2;
double seps = static_cast< double >(m_number_of_traces - 1);
if (!removing_effective_cp){
q[0] = log(m_beta_alpha + (k - 1) - k_j); // = log(m_beta_alpha + k - (k_j + 1)
q[1] = log(m_beta_alpha + k_j - seps);
}
else {
q[0] = log(m_beta_alpha + k - k_j); // = log(m_beta_alpha + (k - 1) - (k_j - 1))
q[1] = log(m_beta_alpha + (k_j - 1) - seps);
}
return q;
}
// how many change points are there between the two separators? Does not include the separators, can equal 0.
unsigned int particle::calculate_trace_dimension(const unsigned int & trace_index) {
int lower_changepoint_index = ((trace_index == 0) ? -1 : static_cast< int >(m_separator_indices[trace_index - 1]));
int right_changepoint_index = ((trace_index == m_separators.size()) ? static_cast< int >(m_dimension) : static_cast< int >(m_separator_indices[trace_index]));
return static_cast< unsigned int >(right_changepoint_index - lower_changepoint_index - 1);
}
unsigned long int particle::calculate_trace_length(const unsigned int & trace_index) {
unsigned long int lower_bound = ((trace_index == 0) ? 0 : m_separators[trace_index - 1]);
unsigned long int upper_bound = ((trace_index == m_number_of_traces - 1) ? m_end + 1 : m_separators[trace_index]);
return upper_bound - lower_bound - 1;
}
// calculate the number of changepoints where at least one process is affected by the changepoint
unsigned int particle::calculate_and_get_full_effective_dimension() {
if (m_dimension == 0) {
return 0;
}
unsigned int effective_dimension = 0;
size_t number_of_processes = m_tau[0].get_full_index().size();
// create a regime vector for the intercept changepoint
vector< unsigned int > prev_regime_vector(number_of_processes, 0);
for (const auto cp:m_tau) {
auto new_regime_vector = cp.get_full_index();
bool any_different = false;
unsigned int proc_idx = 0;
while (!any_different && proc_idx < number_of_processes) {
any_different = new_regime_vector[proc_idx] != prev_regime_vector[proc_idx];
proc_idx++;
}
if (any_different) {
effective_dimension++;
}
prev_regime_vector = new_regime_vector;
}
return effective_dimension;
}
bool particle::is_last_changepoint_effective() {
if (m_dimension == 0) {
return true;
}
size_t number_of_processes = m_tau[0].get_full_index().size();
vector< unsigned int > final_regime_vector = m_tau.back().get_full_index();
vector< unsigned int > penultimate_regime_vector;
if (m_dimension == 1) {
penultimate_regime_vector = vector< unsigned int >(number_of_processes, 0);
}
else {
penultimate_regime_vector = m_tau[m_dimension - 2].get_full_index();
}
bool any_different = false;
unsigned int proc_idx = 0;
while (!any_different && proc_idx < number_of_processes) {
any_different = final_regime_vector[proc_idx] != penultimate_regime_vector[proc_idx];
proc_idx++;
}
return any_different;
}
bool particle::is_changepoint_effective_for_process(const unsigned int & cp_index, const unsigned int & process) {
if (m_dimension <= cp_index) {
cerr << "change point index is too high" << endl;
}
if (m_regimes.size() <= process) {
cerr << "process number is too high" << endl;
}
if (cp_index == 0) {
return m_tau[0].get_full_index_row(process) != 0;
}
else {
return m_tau[cp_index].get_full_index_row(process) != m_tau[cp_index - 1].get_full_index_row(process);
}
}
bool particle::does_changepoint_introduce_new_regime_for_process(const unsigned int & cp_idx, const unsigned int & process) {
if (m_dimension <= cp_idx) {
cerr << "change point index is too high" << endl;
}
if (m_regimes.size() <= process) {
cerr << "process number is too high" << endl;
}
unsigned int regime = m_tau[cp_idx].get_full_index_row(process);
if (regime == 0) {
return false;
}
unsigned int first_occurence_of_regime = static_cast< unsigned int >(m_regimes[process][regime].get_right_changepoint_indices()[0] - 1); // know this isn't -1 because we already checked if the regime is 0
return first_occurence_of_regime == cp_idx;
}
// calculates the prior ratio for the marked vectors for adding a proposed_regime at index for process. If new_regime is true then this is a new regime, if the changepoint has no subsequent regime then leave the last argument empty.
double particle::full_log_I_prior_add_ratio(const int & index, const bool & new_regime, const unsigned int & process, const unsigned int & previous_regime, const unsigned int & proposed_regime, const unsigned int & subsequent_regime) {
double q;
double number_of_regimes = static_cast< double >(get_number_of_regimes(process));
if (subsequent_regime == numeric_limits< unsigned int >::max()) {
if (new_regime) {
q = log(m_dirichlet_alpha);
double transitions_out_of_previous_regime = static_cast< double >(m_regimes[process][previous_regime].get_number_of_right_transitions());
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_previous_regime) - gsl_sf_lngamma(m_dirichlet_alpha + 1 + number_of_regimes * m_dirichlet_alpha + transitions_out_of_previous_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
for (unsigned int regime = 0; regime < previous_regime; regime++) {
double transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions());
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
for (unsigned int regime = previous_regime + 1; regime < number_of_regimes; regime++) {
double transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions());
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
q += log(1 - m_rho);
q += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
}
else {
double transitions_from_previous_to_proposed = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(proposed_regime));
double transitions_out_of_previous_regime = static_cast< double >(m_regimes[process][previous_regime].get_number_of_right_transitions());
q = log(m_dirichlet_alpha + transitions_from_previous_to_proposed) - log(number_of_regimes * m_dirichlet_alpha + transitions_out_of_previous_regime);
}
}
else {
if (new_regime) {
double transitions_from_previous_to_subsequent_regime = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(subsequent_regime));
q = 2 * log(m_dirichlet_alpha) - log(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - log(m_dirichlet_alpha + transitions_from_previous_to_subsequent_regime - 1);
for (unsigned int regime = 0; regime < number_of_regimes; regime++) {
double transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions());
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) + gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
q += log(1 - m_rho);
q += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
}
else {
if (proposed_regime == previous_regime) {
double transitions_from_previous_to_previous_regime = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(previous_regime));
double transitions_out_of_previous_regime = static_cast< double >(m_regimes[process][previous_regime].get_number_of_right_transitions());
q = log(m_dirichlet_alpha + transitions_from_previous_to_previous_regime) - log(number_of_regimes * m_dirichlet_alpha + transitions_out_of_previous_regime);
}
else {
if (subsequent_regime == proposed_regime) {
double transitions_from_subsequent_to_subsequent_regime = static_cast< double >(m_regimes[process][subsequent_regime].get_right_transitions_histogram_element(subsequent_regime));
double transitions_out_of_subsequent_regime = static_cast< double >(m_regimes[process][subsequent_regime].get_number_of_right_transitions());
q = log(m_dirichlet_alpha + transitions_from_subsequent_to_subsequent_regime) - log(m_dirichlet_alpha * number_of_regimes + transitions_out_of_subsequent_regime);
}
else {
double transitions_from_previous_to_proposed_regime = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(proposed_regime));
double transitions_from_proposed_to_subsequent_regime = static_cast< double >(m_regimes[process][proposed_regime].get_right_transitions_histogram_element(subsequent_regime));
double transitions_from_previous_to_subsequent_regime = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(subsequent_regime));
double transitions_out_of_proposed_regime = static_cast< double >(m_regimes[process][proposed_regime].get_number_of_right_transitions());
q = log(m_dirichlet_alpha + transitions_from_previous_to_proposed_regime) + log(m_dirichlet_alpha + transitions_from_proposed_to_subsequent_regime) - log(m_dirichlet_alpha + transitions_from_previous_to_subsequent_regime - 1) - log(number_of_regimes * m_dirichlet_alpha + transitions_out_of_proposed_regime);
}
}
}
}
return q;
}
// returns the log of the full I prior ratio if we were adding the changepoint that we are proposing removing with regime proposed_regime. Index gives the position of the changepoint that we are proposing to remove. new_regime gives whether the proposed_regime is a new regime, either in the sense that if the changepoint were deleted it would remove regime proposed_regime, or in the sense that if we were proposing a changepoint here we would be proposing a new regime for it. actual_regime gives the actual regime of the changepoint that we are removing
double particle::full_log_I_prior_remove_ratio(const int & index, const unsigned int & process, const unsigned int & previous_regime, const unsigned int & proposed_regime, const bool & new_regime, const unsigned int & actual_regime, const bool & removing_unobserved_regime, const unsigned int & subsequent_regime) {
double q;
// check if the number of regimes has been reduced before running this, if so then reduce the number of regimes by 1.
double number_of_regimes = static_cast< double >(get_number_of_regimes(process)) - (removing_unobserved_regime ? 1.0 : 0.0);
if (subsequent_regime == numeric_limits< unsigned int >::max()) {
if (new_regime) {
q = log(m_dirichlet_alpha);
double transitions_out_of_previous_regime = static_cast< double >(m_regimes[process][previous_regime].get_number_of_right_transitions() - 1);
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_previous_regime) - gsl_sf_lngamma(m_dirichlet_alpha + 1 + number_of_regimes * m_dirichlet_alpha + transitions_out_of_previous_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
for (unsigned int regime = 0; regime < previous_regime; regime++) {
double transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions());
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
for (unsigned int regime = previous_regime + 1; regime < (get_number_of_regimes(process) - (removing_unobserved_regime ? 1 : 0)); regime++) {
double transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions());
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
q += log(1 - m_rho);
q += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
}
else {
double transitions_from_previous_to_proposed = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(proposed_regime)) - (proposed_regime == actual_regime ? 1 : 0);
double transitions_out_of_previous_regime = static_cast< double >(m_regimes[process][previous_regime].get_number_of_right_transitions() - 1);
q = log(m_dirichlet_alpha + transitions_from_previous_to_proposed) - log(number_of_regimes * m_dirichlet_alpha + transitions_out_of_previous_regime);
}
}
else {
if (new_regime) {
double transitions_from_previous_to_subsequent_regime = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(subsequent_regime));
if (actual_regime == subsequent_regime) {
if (previous_regime == actual_regime) {
transitions_from_previous_to_subsequent_regime--;
}
}
else {
if (previous_regime != actual_regime) {
transitions_from_previous_to_subsequent_regime++;
}
}
q = 2 * log(m_dirichlet_alpha) - log(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - log(m_dirichlet_alpha + transitions_from_previous_to_subsequent_regime - 1);
for (unsigned int regime = 0; regime < number_of_regimes; regime++) {
double transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions());
transitions_out_of_regime -= (actual_regime == regime ? 1 : 0);
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) + gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
q += log(1 - m_rho);
q += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
}
else {
if (proposed_regime == previous_regime) {
double transitions_from_previous_to_previous_regime = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(previous_regime));
double transitions_out_of_previous_regime = static_cast< double >(m_regimes[process][previous_regime].get_number_of_right_transitions());
if (previous_regime == actual_regime) {
transitions_from_previous_to_previous_regime--;
transitions_out_of_previous_regime--;
}
else {
if (previous_regime == subsequent_regime) {
transitions_from_previous_to_previous_regime++;
}
}
q = log(m_dirichlet_alpha + transitions_from_previous_to_previous_regime) - log(number_of_regimes * m_dirichlet_alpha + transitions_out_of_previous_regime);
}
else {
if (subsequent_regime == proposed_regime) {
double transitions_from_subsequent_to_subsequent_regime = static_cast< double >(m_regimes[process][subsequent_regime].get_right_transitions_histogram_element(subsequent_regime));
double transitions_out_of_subsequent_regime = static_cast< double >(m_regimes[process][subsequent_regime].get_number_of_right_transitions());
if (actual_regime == subsequent_regime) {
transitions_out_of_subsequent_regime--;
transitions_from_subsequent_to_subsequent_regime--;
}
else {
if (previous_regime == subsequent_regime) {
transitions_from_subsequent_to_subsequent_regime++;
}
}
q = log(m_dirichlet_alpha + transitions_from_subsequent_to_subsequent_regime) - log(m_dirichlet_alpha * number_of_regimes + transitions_out_of_subsequent_regime);
}
else { // know proposed != previous and proposed != subsequent
// therefore these three transition counts are definitely different
double transitions_from_previous_to_proposed_regime = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(proposed_regime));
double transitions_from_proposed_to_subsequent_regime = static_cast< double >(m_regimes[process][proposed_regime].get_right_transitions_histogram_element(subsequent_regime));
double transitions_from_previous_to_subsequent_regime = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(subsequent_regime));
if (actual_regime == subsequent_regime) {
if (previous_regime == actual_regime) {
transitions_from_previous_to_subsequent_regime--;
}
else {
if (proposed_regime == actual_regime) {
transitions_from_proposed_to_subsequent_regime--;
}
}
}
else {
if (previous_regime != actual_regime) {
if (proposed_regime == actual_regime) {
transitions_from_previous_to_proposed_regime--;
transitions_from_proposed_to_subsequent_regime--;
}
transitions_from_previous_to_subsequent_regime++;
}
}
double transitions_out_of_proposed_regime = static_cast< double >(m_regimes[process][proposed_regime].get_number_of_right_transitions());
if (proposed_regime == actual_regime) {
transitions_out_of_proposed_regime--;
}
q = log(m_dirichlet_alpha + transitions_from_previous_to_proposed_regime) + log(m_dirichlet_alpha + transitions_from_proposed_to_subsequent_regime) - log(m_dirichlet_alpha + transitions_from_previous_to_subsequent_regime - 1) - log(number_of_regimes * m_dirichlet_alpha + transitions_out_of_proposed_regime);
}
}
}
}
return q;
}
// following_regime and proposed_regime default to -1. Gives the log of the full I prior ratio for adding the separator as a changepoint after it has been removed.
double particle::log_resampling_separator_changepoint_prior_ratio(const unsigned int & process, const bool & no_following_regime, const bool & new_regime, const bool & removing_unobserved_regime, const unsigned int & actual_regime, const unsigned int & following_regime, const unsigned int & proposed_regime) {
double q = 0;
double number_of_regimes = static_cast< double >(get_number_of_regimes(process)) - (removing_unobserved_regime ? 1.0 : 0.0);
if (no_following_regime) {
if (new_regime) {
for (unsigned int regime = 0; regime < m_regimes[process].size(); regime++) {
double transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions());
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
q += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
q += log(1 - m_rho);
}
}
else {
if (new_regime) {
for (unsigned int regime = 0; regime < m_regimes[process].size(); regime++) {
double transitions_out_of_regime;
if (regime == actual_regime) { // one transition has been removed from the actual regime.
transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions()) - 1;
}
else {
transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions());
}
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
q += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
q += log(m_dirichlet_alpha) - log(number_of_regimes * m_dirichlet_alpha + m_dirichlet_alpha);
q += log(1 - m_rho);
}
else {
if (actual_regime == proposed_regime) {
double transitions_from_proposed_to_following_regime = static_cast< double >(m_regimes[process][proposed_regime].get_right_transitions_histogram_element(following_regime));
double transitions_out_of_proposed_regime = static_cast< double >(m_regimes[process][proposed_regime].get_number_of_right_transitions());
q += log(transitions_from_proposed_to_following_regime - 1 + m_dirichlet_alpha) - log(transitions_out_of_proposed_regime - 1 + (number_of_regimes * m_dirichlet_alpha));
}
else {
double transitions_from_proposed_to_following_regime = static_cast< double >(m_regimes[process][proposed_regime].get_right_transitions_histogram_element(following_regime));
double transitions_out_of_proposed_regime = static_cast< double >(m_regimes[process][proposed_regime].get_number_of_right_transitions());
q += log(transitions_from_proposed_to_following_regime + m_dirichlet_alpha) - log(transitions_out_of_proposed_regime + number_of_regimes * m_dirichlet_alpha);
}
}
}
return q;
}
double particle::calculate_and_get_add_unobserved_regimes_full_I_prior_ratio(const vector< bool > & accepted, const size_t & number_of_processes) {
double ratio = 0;
for (unsigned int process = 0; process < number_of_processes; process++) {
if (accepted[process]) {
double number_of_regimes = static_cast< double >(m_regimes[process].size());
for (unsigned int regime = 0; regime < m_regimes[process].size(); regime++) {
ratio += gsl_sf_lngamma((number_of_regimes + 1) * m_dirichlet_alpha) + gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions())) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma((number_of_regimes + 1) * m_dirichlet_alpha + static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions()));
}
ratio += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
}
}
return ratio;
}
double particle::calculate_and_get_add_unobserved_regimes_full_I_prior_ratio(const unsigned int & process) {
double ratio = 0;
double number_of_regimes = static_cast< double >(m_regimes[process].size());
for (unsigned int regime = 0; regime < m_regimes[process].size(); regime++) {
ratio += gsl_sf_lngamma((number_of_regimes + 1) * m_dirichlet_alpha) + gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions())) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma((number_of_regimes + 1) * m_dirichlet_alpha + static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions()));
}
ratio += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
return ratio;
}
double particle::calculate_and_get_add_unobserved_regimes_proposal_ratio(const vector< bool > & accepted, const size_t & number_of_processes) {
double ratio = 0;
for (unsigned int process = 0; process < number_of_processes; process++) {
if (accepted[process]) {
ratio += log(static_cast< double >(m_regimes[process].size()));
ratio -= log(static_cast< double >(m_number_of_unobserved_regimes[process]) + 1);
}
}
return ratio;
}
double particle::calculate_and_get_add_unobserved_regimes_regimes_prior_ratio(const vector< bool > & adding_unobserved_regimes, const size_t & number_of_processes) {
double ratio = 0;
for (unsigned int j = 0; j < number_of_processes; j++) {
if (adding_unobserved_regimes[j]) {
ratio += log(1 - m_rho);
}
}
return ratio;
}
double particle::calculate_and_get_remove_unobserved_regimes_full_I_prior_ratio(const vector< bool > & rejected, const size_t & number_of_processes) {
double ratio = 0;
for (unsigned int process = 0; process < number_of_processes; process++) {
if (rejected[process]) {
double number_of_regimes = static_cast< double >(m_regimes[process].size());
for (unsigned int regime = 0; regime < m_regimes[process].size(); regime++) {
ratio += gsl_sf_lngamma((number_of_regimes - 1) * m_dirichlet_alpha) + gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions())) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma((number_of_regimes - 1) * m_dirichlet_alpha + static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions()));
}
ratio += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes - 1));
}
}
return ratio;
}
double particle::calculate_and_get_remove_unobserved_regimes_full_I_prior_ratio(const unsigned int & process) {
double ratio = 0;
double number_of_regimes = static_cast< double >(m_regimes[process].size());
for (unsigned int regime = 0; regime < m_regimes[process].size(); regime++) {
ratio += gsl_sf_lngamma((number_of_regimes - 1) * m_dirichlet_alpha) + gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions())) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma((number_of_regimes - 1) * m_dirichlet_alpha + static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions()));
}
ratio += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes - 1));
return ratio;
}
double particle::calculate_and_get_remove_unobserved_regimes_proposal_ratio(const vector< bool > & rejected, const size_t & number_of_processes) {
double ratio = 0;
for (unsigned int process = 0; process < number_of_processes; process++) {
if (rejected[process]) {
ratio -= log(static_cast< double >(m_regimes[process].size()) - 1);
ratio += log(static_cast< double >(m_number_of_unobserved_regimes[process]));
}
}
return ratio;
}
double particle::calculate_and_get_remove_unobserved_regimes_regimes_prior_ratio(const vector< bool > & removing_unobserved_regimes, const size_t & number_of_processes) {
double ratio = 0;
for (unsigned int j = 0; j < number_of_processes; j++) {
if (removing_unobserved_regimes[j]) {
ratio -= log(1 - m_rho);
}
}
return ratio;
}
vector< double > particle::calculate_and_get_adding_binary_log_I_prior_ratio(const unsigned int & process, const bool & new_trace, const unsigned int & trace_index, const int & new_left_cp_index) {
if (new_left_cp_index == -1) {
return vector< double >(2, 0);
}
double old_k = static_cast< double >(new_left_cp_index);
double old_seps = static_cast< double >(trace_index - (new_trace ? 1 : 0));
double old_k_j = static_cast< double >(m_binaries[process].size()) - 1;
double old_log_binary_I_prior = gsl_sf_lnbeta(m_beta_alpha + old_k_j - old_seps, m_beta_alpha + old_k - old_k_j) - gsl_sf_lnbeta(m_beta_alpha, m_beta_alpha);
double new_k = old_k + 1;
double new_seps = trace_index;
vector< double > log_binary_prior_ratio(2, 0);
if (new_trace) { // if we are adding a new trace then we must accept this binary so set the ratio for not changing to -infinity so it won't be chosen
log_binary_prior_ratio[0] = -1e300;
}
else {
log_binary_prior_ratio[0] = gsl_sf_lnbeta(m_beta_alpha + old_k_j - new_seps, m_beta_alpha + new_k - old_k_j) - gsl_sf_lnbeta(m_beta_alpha, m_beta_alpha) - old_log_binary_I_prior;
}
log_binary_prior_ratio[1] = gsl_sf_lnbeta(m_beta_alpha + (old_k_j + 1) - new_seps, m_beta_alpha + new_k - (old_k_j + 1)) - gsl_sf_lnbeta(m_beta_alpha, m_beta_alpha) - old_log_binary_I_prior;
return log_binary_prior_ratio;
}
double particle::calculate_and_get_full_adding_binary_log_I_prior_ratio(const unsigned int & process, const unsigned int & regime, const int & number_of_changepoints, const bool & new_trace, const unsigned int & trace_index, const unsigned int & previous_regime) {
unsigned int number_of_regimes = static_cast< unsigned int >(m_regimes[process].size());
// set the last transition of the previous regime to be regime (unless we are starting a new trace)
double log_prior;
// need to add the number_of_changepoints - 1 transitions from regime -> regime to the transitions_histogram_vector for regime
if (!new_trace) { // no new trace, so need to add a transition at the end of the previous regime
if (regime == number_of_regimes) { // need to add 1 to the length of each transition_histogram_vector
log_prior = 0;
for (unsigned int i = 0; i < number_of_regimes; i++) {
vector< unsigned int > transitions_histogram = m_regimes[process][i].get_right_transitions_histogram();
log_prior -= dirichlet_ratio(transitions_histogram);
transitions_histogram.push_back(0);
if (i == previous_regime) {
transitions_histogram.back()++;
}
log_prior += dirichlet_ratio(transitions_histogram);
}
// and now make the transitions_histogram_vector for the new regime
vector< unsigned int > regime_transitions_histogram(number_of_regimes + 1);
for (int i = 0; i < number_of_changepoints - 1; i++) {
regime_transitions_histogram[regime]++;
}
log_prior += dirichlet_ratio(regime_transitions_histogram);
log_prior += log(1 - m_rho);
if (0 < trace_index) {
log_prior += static_cast< double >(trace_index) * log(static_cast< double >(number_of_regimes) / static_cast< double >(number_of_regimes + 1));
}
}
else { // log prior is dir_ratio(regime_hist_with_new_transitions) + dir_ratio(prev_hist_with_new_transitions) - dir_ratio(previous_hist) - dir_ratio(regime_hist)
if (regime != previous_regime) {
// calculate the log prior ratio for adding these transitions to the regime
double nr = static_cast< double >(number_of_regimes), kr = static_cast< double >(m_regimes[process][regime].get_transitions_out()), krr = static_cast< double >(m_regimes[process][regime].get_right_transitions_histogram_element(regime));
log_prior = gsl_sf_lngamma(nr * m_dirichlet_alpha + kr);
log_prior -= gsl_sf_lngamma(nr * m_dirichlet_alpha + kr + number_of_changepoints - 1);
log_prior += gsl_sf_lngamma(m_dirichlet_alpha + krr + number_of_changepoints - 1);
log_prior -= gsl_sf_lngamma(m_dirichlet_alpha + krr);
/*vector< unsigned int > regime_transitions_histogram = m_regimes[process][regime].get_right_transitions_histogram();
double flog_prior = -dirichlet_ratio(regime_transitions_histogram);
// add self-transitions for the binary that we are adding
for (int i = 0; i < number_of_changepoints - 1; i++) {
regime_transitions_histogram[regime]++;
}
flog_prior += dirichlet_ratio(regime_transitions_histogram);
cout << "log prior diff: " << log_prior - flog_prior << endl;*/
// calculate the log prior ratio for adding the new transition out of the previous regime
double kpr = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(regime)), kp = static_cast< double >(m_regimes[process][previous_regime].get_transitions_out());
log_prior += log(m_dirichlet_alpha + kpr);
log_prior -= log(nr * m_dirichlet_alpha + kp);
}
else {
vector< unsigned int > regime_transitions_histogram = m_regimes[process][regime].get_right_transitions_histogram();
log_prior = -dirichlet_ratio(regime_transitions_histogram);
// add self-transitions for the binary that we are adding
for (int i = 0; i < number_of_changepoints - 1; i++) {
regime_transitions_histogram[regime]++;
}
// add a transition from the previous regime since this isn't a new trace
regime_transitions_histogram[regime]++;
log_prior += dirichlet_ratio(regime_transitions_histogram);
}
}
}
else { // don't add a transition at the end of the previous_regime
if (regime == number_of_regimes) { // need to add 1 to the length of each transition_histogram_vector
log_prior = 0;
for (unsigned int i = 0; i < number_of_regimes; i++) {
vector< unsigned int > transitions_histogram = m_regimes[process][i].get_right_transitions_histogram();
log_prior -= dirichlet_ratio(transitions_histogram);
transitions_histogram.push_back(0);
log_prior += dirichlet_ratio(transitions_histogram);
}
// and now make the transitions_histogram_vector for the new regime
vector< unsigned int > regime_transitions_histogram(number_of_regimes + 1);
for (int i = 0; i < number_of_changepoints - 1; i++) {
regime_transitions_histogram[regime]++;
}
log_prior += dirichlet_ratio(regime_transitions_histogram);
log_prior += log(1 - m_rho);
log_prior += static_cast< double >(trace_index) * log(1 / static_cast< double >(number_of_regimes + 1));
if (0 < trace_index) {
log_prior += static_cast< double >(trace_index - 1) * log(static_cast< double >(number_of_regimes));
}
}
else { // log prior is dir_ratio(regime_hist_with_new_transitions) + dir_ratio(prev_hist_with_new_transitions) - dir_ratio(previous_hist) - dir_ratio(regime_hist)
vector< unsigned int > regime_transitions_histogram = m_regimes[process][regime].get_right_transitions_histogram();
log_prior = -dirichlet_ratio(regime_transitions_histogram);
for (int i = 0; i < number_of_changepoints - 1; i++) {
regime_transitions_histogram[regime]++;
}
log_prior += dirichlet_ratio(regime_transitions_histogram);
if (0 < trace_index) {
log_prior += log(1 / static_cast< double >(number_of_regimes));
}
}
}
return log_prior;
}
// index gives the index for the new changepoint, new_changepoint gives the changepoint object to add, new_regimes is a vector with the new regime to add for each process, sufficient_statistics gives the sufficient statistics in the interval [tau_h^\prime, \tau_h+1), log_likelihoods[j][0] gives the log likelihood for the previous regime and log_likelihoods[j][1] gives the log likelihood for new_regimes[j]
void particle::add_full_changepoint(const unsigned int & index, const changepoint & new_changepoint, const vector< unsigned int > & new_regimes, const vector< vector< double > > & sufficient_statistics, const vector< vector< double > > & log_likelihoods, const vector< double > & previous_log_likelihoods, const vector< double > & number_of_observations) {
// insert new_changepoint into m_tau
m_tau.insert(m_tau.begin() + index, new_changepoint);
m_dimension++; //increase dimension
size_t number_of_processes = new_regimes.size();
// assign the regime indices for the new changepoint.
m_tau[index].set_full_index(new_regimes);
if (m_include_separator) {
// increase by 1 the cp_index of any separator that is greater than or equal to index
increase_separator_indices_greater_or_equal_to_index(index);
}
for (unsigned int j = 0; j < number_of_processes; j++) {
unsigned int prev_regime_index;
// calculate the regime index of the previous changepoint
if (index == 0) {
prev_regime_index = 0;
}
else {
prev_regime_index = m_tau[index - 1].get_full_index_row(j);
}
// if adding a new regime, insert it into the collection of existing regimes, and change the other regimes so that they know the number of regimes has increased.
bool adding_new_regime = new_regimes[j] == m_regimes[j].size();
if (adding_new_regime) {
for (unsigned int i = 0; i < m_regimes[j].size(); i++) {
// increase the size of the transitions histogram for each of the regimes in this process.
m_regimes[j][i].add_regime_to_transitions_histogram(new_regimes[j]);
}
// insert new regime into m_regimes[j]. We don't include the right changepoint position, right transition, sufficient statistics or number_of_observations here as it will be added later
// these will be converted to the correct values later
m_regimes[j].push_back(regime(vector< int >(0), vector< unsigned int >(0), vector< unsigned int >(m_regimes[j].size() + 1, 0), vector< double >(sufficient_statistics[j].size(), 0), m_number_of_traces, m_trace_index, 0));
// these unobserved regime values will be corrected later
m_unobserved_regimes[j].push_back(true);
m_number_of_unobserved_regimes[j]++;
}
// increase the values for the right indices in every regime so that index + 1 -> index + 2, ...
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].increase_right_indices_greater_than_or_equal_to(index + 1);
}
// insert the interval and transition out of the new_regime
// replace the right transition from previous regime to subsequent regime with a transition to new_regime (unless new_regime is equal to subsequent_regime), adding a transition out of previous regime if the new changepoint is inserted at the end of m_tau.
if (index == m_dimension - 1 || is_changepoint_index_separator_index(index + 1)) {
// if index + 1 is a separator then m_trace_index is set to be the trace index of index
m_regimes[j][prev_regime_index].alter_right_transition(index, new_regimes[j]);
m_regimes[j][new_regimes[j]].add_interval(index + 1, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j]);
if (index == m_dimension - 1) {
m_trace_index = static_cast< unsigned int >(m_number_of_traces - 1);
}
}
else {
unsigned int subs_regime_index = m_tau[index + 1].get_full_index_row(j);
if (new_regimes[j] != subs_regime_index) {
m_regimes[j][prev_regime_index].alter_right_transition(index, new_regimes[j]);
}
m_regimes[j][new_regimes[j]].add_interval(index + 1, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j], subs_regime_index);
}
// calculate the trace index
is_changepoint_index_separator_index(index); // only running this to set the trace_index. If not run, m_trace_index may give the trace index of the next trace because is_changepoint_index_separator_index(index + 1) has just been run
// assign right sufficient statistics and observation numbers to the new regime and take them away from the previous regime (unless both regimes are equal). Calculate the log likelihood for each regime
if (new_regimes[j] != prev_regime_index) {
m_regimes[j][new_regimes[j]].add_sufficient_statistics(sufficient_statistics[j]);
m_regimes[j][new_regimes[j]].set_log_likelihood(log_likelihoods[j][new_regimes[j]]);
m_regimes[j][new_regimes[j]].add_observations(m_trace_index, number_of_observations[j]);
m_regimes[j][prev_regime_index].remove_sufficient_statistics(sufficient_statistics[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods[j]);
m_regimes[j][prev_regime_index].remove_observations(m_trace_index, number_of_observations[j]);
}
}
}
void particle::remove_full_changepoint(const unsigned int & index, const vector< vector< double > > & right_sufficient_statistics_rev, const vector< double > & actual_log_likelihoods_without_right_sufficient_statistics_rev, const vector< double > & previous_log_likelihoods_with_right_sufficient_statistics_rev, const vector< double > & number_of_observations_rev, const vector< bool > & removing_unobserved_regimes) {
// get the regime indices for the index'th changepoint
vector< unsigned int > removed_regimes(0);
removed_regimes = m_tau[index].get_full_index();
// remove the changepoint from m_tau
m_tau.erase(m_tau.begin() + index);
m_dimension--;
size_t number_of_processes = right_sufficient_statistics_rev.size();
if (m_include_separator) {
// if there are separators, decrease the index of any separator greater than index
decrease_separator_indices_greater_than_index(index);
}
for (unsigned int j = 0; j < number_of_processes; j++) {
unsigned int prev_regime_index;
// calculate the regime index of the previous changepoint
if (index == 0) {
prev_regime_index = 0;
}
else {
prev_regime_index = m_tau[index - 1].get_full_index_row(j);
}
// remove the interval and transition out of the removed_regime
// replace the right transition from previous regime to removed_regime with a transition to subsequent_regime (unless new_regime is equal to subsequent_regime), removing a transition out of previous regime if the changepoint is removed from the end of m_tau.
// calculate m_trace_index for the changepoint we are removing
if (is_changepoint_index_separator_index(index) || index == m_dimension) {
if (index == m_dimension) {
m_trace_index = static_cast< unsigned int >(m_number_of_traces - 1);
}
m_regimes[j][prev_regime_index].remove_right_transition(index);
m_regimes[j][removed_regimes[j]].remove_interval(index + 1, m_unobserved_regimes[j], removed_regimes[j], m_number_of_unobserved_regimes[j]);
}
else {
unsigned int subs_regime_index = m_tau[index].get_full_index_row(j);
if (removed_regimes[j] != subs_regime_index) {
m_regimes[j][prev_regime_index].alter_right_transition(index, subs_regime_index);
}
m_regimes[j][removed_regimes[j]].remove_interval(index + 1, m_unobserved_regimes[j], removed_regimes[j], m_number_of_unobserved_regimes[j]);
}
// calculate the trace index
is_changepoint_index_separator_index(index - 1); // only running this to set the trace_index. If not run, m_trace_index may give the trace index of the next trace because is_changepoint_index_separator_index(index) has just been run and index now corresponds to the next changepoint
// remove right sufficient statistics from the regime for the deleted cp and add them to the previous regime (unless both regimes are equal). Calculate the log likelihood for each regime
if (removed_regimes[j] != prev_regime_index) {
m_regimes[j][removed_regimes[j]].remove_sufficient_statistics(right_sufficient_statistics_rev[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_log_likelihoods_without_right_sufficient_statistics_rev[j]);
m_regimes[j][removed_regimes[j]].remove_observations(m_trace_index, number_of_observations_rev[j]);
m_regimes[j][prev_regime_index].add_sufficient_statistics(right_sufficient_statistics_rev[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_with_right_sufficient_statistics_rev[j]);
m_regimes[j][prev_regime_index].add_observations(m_trace_index, number_of_observations_rev[j]);
}
if (removing_unobserved_regimes[j]) {
// if we are removing the top regime, then this regime must be deleted
if (!m_unobserved_regimes[j].back()) {
cerr << "regime to delete is not unobserved" << endl;
}
m_regimes[j].erase(m_regimes[j].end() - 1);
unsigned int regime_to_remove = static_cast< unsigned int >(m_regimes[j].size());
// for all other regimes, remove any trace of this unobserved regime (i.e. delete the 0 from m_right_transitions_histogram, decrease the indices of transitions greate than regime_to_remove by 1
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].remove_unobserved_regime(regime_to_remove);
}
m_unobserved_regimes[j].erase(m_unobserved_regimes[j].end() - 1);
m_number_of_unobserved_regimes[j]--;
}
// decrease the values for right indices in every regime so that index + 2 -> index + 1, index + 3 -> index + 2, ...
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].decrease_right_indices_greater_than(index + 1);
}
}
}
void particle::move_full_changepoint(const unsigned int & index, const changepoint & new_changepoint, const vector< unsigned int > & new_regimes, const bool & tau_h_greater_than_tau_h_prime, const vector< vector< double > > & right_sufficient_statistics, const vector< double > & right_number_of_observations, const vector< vector< double > > & right_sufficient_statistics_reverse,const vector< double > & right_number_of_observations_reverse, const vector< vector< double > > & middle_sufficient_statistics, const vector< double > & middle_number_of_observations, const vector< double > & previous_log_likelihoods_without_right_sufficient_statistics, const vector< double > & previous_log_likelihoods_with_right_sufficient_statistics_reverse, const vector< double > & previous_log_likelihoods_with_middle_sufficient_statistics, const vector< double > & previous_log_likelihoods_without_middle_sufficient_statistics, const vector< vector< double > > & log_likelihoods_with_right_sufficient_statistics, const vector< double > & actual_regime_log_likelihoods_with_middle_sufficient_statistics, const vector< double > & actual_regime_log_likelihoods_without_middle_sufficient_statistics, const vector< double > & actual_regime_log_likelihoods_without_right_sufficient_statistics_reverse, const vector< bool > & removing_unobserved_regimes) {
vector< unsigned int > removed_regimes(0);
removed_regimes = m_tau[index].get_full_index();
m_tau[index] = new_changepoint;
m_tau[index].set_full_index(new_regimes);
size_t number_of_processes = removed_regimes.size();
for (unsigned int j = 0; j < number_of_processes; j++) {
unsigned int prev_regime_index;
// calculate the regime index of the previous changepoint
if (index == 0) {
prev_regime_index = 0;
}
else {
prev_regime_index = m_tau[index - 1].get_full_index_row(j);
}
// if adding a new regime, insert it into the collection of existing regimes, and change the other regimes so that they know the number of regimes has increased.
bool adding_new_regime = new_regimes[j] == m_regimes[j].size();
if (adding_new_regime) {
for (unsigned int i = 0; i < m_regimes[j].size(); i++) {
// increase the size of the transitions histogram for each of the regimes in this process.
m_regimes[j][i].add_regime_to_transitions_histogram(new_regimes[j]);
}
m_regimes[j].push_back(regime(vector< int >(0), vector< unsigned int >(0), vector< unsigned int >(m_regimes[j].size() + 1, 0), vector< double >(right_sufficient_statistics[j].size(), 0), m_number_of_traces, m_trace_index, 0));
// the interval will be added later
m_unobserved_regimes[j].push_back(true);
m_number_of_unobserved_regimes[j]++;
}
// remove right sufficient statistics from the regime for the deleted cp and add them to the previous regime (unless both regimes are equal). Calculate the log likelihood for each regime
if (removed_regimes[j] == prev_regime_index) {
if (prev_regime_index != new_regimes[j]) {
m_regimes[j][prev_regime_index].remove_sufficient_statistics(right_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_without_right_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].remove_observations(m_trace_index, right_number_of_observations[j]);
m_regimes[j][new_regimes[j]].add_sufficient_statistics(right_sufficient_statistics[j]);
m_regimes[j][new_regimes[j]].set_log_likelihood(log_likelihoods_with_right_sufficient_statistics[j][new_regimes[j]]);
m_regimes[j][new_regimes[j]].add_observations(m_trace_index, right_number_of_observations[j]);
}
}
else {
if (new_regimes[j] == prev_regime_index) {
m_regimes[j][prev_regime_index].add_sufficient_statistics(right_sufficient_statistics_reverse[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_with_right_sufficient_statistics_reverse[j]);
m_regimes[j][prev_regime_index].add_observations(m_trace_index, right_number_of_observations_reverse[j]);
m_regimes[j][removed_regimes[j]].remove_sufficient_statistics(right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_regime_log_likelihoods_without_right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].remove_observations(m_trace_index, right_number_of_observations_reverse[j]);
}
else {
if (new_regimes[j] == removed_regimes[j]) {
if (tau_h_greater_than_tau_h_prime) {
m_regimes[j][prev_regime_index].remove_sufficient_statistics(middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_without_middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].remove_observations(m_trace_index, middle_number_of_observations[j]);
m_regimes[j][removed_regimes[j]].add_sufficient_statistics(middle_sufficient_statistics[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_regime_log_likelihoods_with_middle_sufficient_statistics[j]);
m_regimes[j][removed_regimes[j]].add_observations(m_trace_index, middle_number_of_observations[j]);
}
else {
m_regimes[j][prev_regime_index].add_sufficient_statistics(middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_with_middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].add_observations(m_trace_index, middle_number_of_observations[j]);
m_regimes[j][removed_regimes[j]].remove_sufficient_statistics(middle_sufficient_statistics[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_regime_log_likelihoods_without_middle_sufficient_statistics[j]);
m_regimes[j][removed_regimes[j]].remove_observations(m_trace_index, middle_number_of_observations[j]);
}
}
else {
if (tau_h_greater_than_tau_h_prime) {
m_regimes[j][removed_regimes[j]].remove_sufficient_statistics(right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_regime_log_likelihoods_without_right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].remove_observations(m_trace_index, right_number_of_observations_reverse[j]);
m_regimes[j][new_regimes[j]].add_sufficient_statistics(right_sufficient_statistics[j]);
m_regimes[j][new_regimes[j]].set_log_likelihood(log_likelihoods_with_right_sufficient_statistics[j][new_regimes[j]]);
m_regimes[j][new_regimes[j]].add_observations(m_trace_index, right_number_of_observations[j]);
m_regimes[j][prev_regime_index].remove_sufficient_statistics(middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_without_middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].remove_observations(m_trace_index, middle_number_of_observations[j]);
}
else {
m_regimes[j][removed_regimes[j]].remove_sufficient_statistics(right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_regime_log_likelihoods_without_right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].remove_observations(m_trace_index, right_number_of_observations_reverse[j]);
m_regimes[j][new_regimes[j]].add_sufficient_statistics(right_sufficient_statistics[j]);
m_regimes[j][new_regimes[j]].set_log_likelihood(log_likelihoods_with_right_sufficient_statistics[j][new_regimes[j]]);
m_regimes[j][new_regimes[j]].add_observations(m_trace_index, right_number_of_observations[j]);
m_regimes[j][prev_regime_index].add_sufficient_statistics(middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_with_middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].add_observations(m_trace_index, middle_number_of_observations[j]);
}
}
}
}
// replace the interval for removed_regime with an interval for new_regime (if they differ)
if (index == m_dimension - 1 || is_changepoint_index_separator_index(index + 1)) {
if (new_regimes[j] != removed_regimes[j]) {
m_regimes[j][prev_regime_index].alter_right_transition(index, new_regimes[j]);
m_regimes[j][new_regimes[j]].add_interval(index + 1, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j]);
m_regimes[j][removed_regimes[j]].remove_interval(index + 1, m_unobserved_regimes[j], removed_regimes[j], m_number_of_unobserved_regimes[j]);
}
}
else {
unsigned int subs_regime_index = m_tau[index + 1].get_full_index_row(j);
if (removed_regimes[j] != new_regimes[j]) {
m_regimes[j][removed_regimes[j]].remove_interval(index + 1, m_unobserved_regimes[j], removed_regimes[j], m_number_of_unobserved_regimes[j]);
m_regimes[j][new_regimes[j]].add_interval(index + 1, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j], subs_regime_index);
m_regimes[j][prev_regime_index].alter_right_transition(index, new_regimes[j]);
}
}
// calculate the trace index
is_changepoint_index_separator_index(index); // only running this to set the trace_index. If not run, m_trace_index may give the trace index of the next trace because is_changepoint_index_separator_index(index + 1) has just been run
// if we are removing an unobserved regime and we don't add it back in, then the top regime must be removed
if (removing_unobserved_regimes[j] && new_regimes[j] != m_regimes[j].size() - 1) {
if (!m_unobserved_regimes[j].back()) {
cerr << "regime to delete is not unobserved" << endl;
}
m_regimes[j].erase(m_regimes[j].end() - 1);
unsigned int regime_to_remove = static_cast< unsigned int >(m_regimes[j].size());
// for all other regimes, remove any trace of this unobserved regime (i.e. delete the 0 from m_right_transitions_histogram, decrease the indices of transitions greate than regime_to_remove by 1
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].remove_unobserved_regime(regime_to_remove);
}
m_unobserved_regimes[j].erase(m_unobserved_regimes[j].end() - 1);
m_number_of_unobserved_regimes[j]--;
}
}
}
void particle::resample_full_changepoint(const unsigned int & index, const vector< unsigned int > & new_regimes, const vector< vector< double > > & right_sufficient_statistics_reverse, const vector< double > & right_number_of_observations_reverse, const vector< vector< double > > & regime_log_likelihoods_with_right_sufficient_statistics_reverse, const vector< double > & actual_log_likelihoods_without_right_sufficient_statistics_reverse, const vector< bool > & removing_unobserved_regimes) {
// calculate the regimes that we are going to lose, and set m_tau[index] to be associated with the new regimes.
vector< unsigned int > removed_regimes(0);
removed_regimes = m_tau[index].get_full_index();
m_tau[index].set_full_index(new_regimes);
size_t number_of_processes = new_regimes.size();
for (unsigned int j = 0; j < number_of_processes; j++) {
// if adding a new regime, insert it into the collection of existing regimes, and change the other regimes so that they know the number of regimes has increased.
bool adding_new_regime = new_regimes[j] == m_regimes[j].size();
if (adding_new_regime) {
for (unsigned int i = 0; i < m_regimes[j].size(); i++) {
// increase the size of the transitions histogram for each of the regimes in this process.
m_regimes[j][i].add_regime_to_transitions_histogram(new_regimes[j]);
}
m_regimes[j].push_back(regime(vector< int >(0), vector< unsigned int >(0), vector< unsigned int >(m_regimes[j].size() + 1, 0), vector< double >(right_sufficient_statistics_reverse[j].size(), 0), m_number_of_traces, m_trace_index, 0));
m_unobserved_regimes[j].push_back(true);
m_number_of_unobserved_regimes[j]++;
}
unsigned int prev_regime_index;
// calculate the regime index of the previous changepoint
if (index == 0) {
prev_regime_index = 0;
}
else {
prev_regime_index = m_tau[index - 1].get_full_index_row(j);
}
// replace the interval for removed_regime with an interval for new_regime (if they differ)
if (index == m_dimension - 1 || is_changepoint_index_separator_index(index + 1)) {
if (index == m_dimension - 1) {
// there is a separator changepoint at the beginning of the last trace, so we must be in the last trace.
m_h_trace_index = static_cast< unsigned int >(m_number_of_traces - 1);
}
else {
// calculate the trace index
is_changepoint_index_separator_index(index); // only running this to set the trace_index. If not run, m_trace_index may give the trace index of the next trace because is_changepoint_index_separator_index(index + 1) has just been run
m_h_trace_index = m_trace_index;
}
if (new_regimes[j] != removed_regimes[j]) {
if (!is_changepoint_index_separator_index(index)) {
m_regimes[j][prev_regime_index].alter_right_transition(index, new_regimes[j]);
}
m_regimes[j][new_regimes[j]].add_interval(index + 1, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j]);
m_regimes[j][removed_regimes[j]].remove_interval(index + 1, m_unobserved_regimes[j], removed_regimes[j], m_number_of_unobserved_regimes[j]);
}
}
else {
m_h_trace_index = m_trace_index;
unsigned int subs_regime_index = m_tau[index + 1].get_full_index_row(j);
if (removed_regimes[j] != new_regimes[j]) {
m_regimes[j][removed_regimes[j]].remove_interval(index + 1, m_unobserved_regimes[j], removed_regimes[j], m_number_of_unobserved_regimes[j]);
m_regimes[j][new_regimes[j]].add_interval(index + 1, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j], subs_regime_index);
if (!is_changepoint_index_separator_index(index)) {
m_regimes[j][prev_regime_index].alter_right_transition(index, new_regimes[j]);
}
}
}
if (removed_regimes[j] != new_regimes[j]) {
m_regimes[j][removed_regimes[j]].remove_sufficient_statistics(right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_log_likelihoods_without_right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].remove_observations(m_h_trace_index, right_number_of_observations_reverse[j]);
m_regimes[j][new_regimes[j]].add_sufficient_statistics(right_sufficient_statistics_reverse[j]);
m_regimes[j][new_regimes[j]].set_log_likelihood(regime_log_likelihoods_with_right_sufficient_statistics_reverse[j][new_regimes[j]]);
m_regimes[j][new_regimes[j]].add_observations(m_h_trace_index, right_number_of_observations_reverse[j]);
}
// if we are removing an unobserved regime and we don't add it back in, then the top regime must be removed
if (removing_unobserved_regimes[j] && new_regimes[j] != m_regimes[j].size() - 1) {
if (!m_unobserved_regimes[j].back()) {
cerr << "regime to delete is not unobserved" << endl;
}
m_regimes[j].erase(m_regimes[j].end() - 1);
unsigned int regime_to_remove = static_cast< unsigned int >(m_regimes[j].size());
// for all other regimes, remove any trace of this unobserved regime (i.e. delete the 0 from m_right_transitions_histogram, decrease the indices of transitions greate than regime_to_remove by 1
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].remove_unobserved_regime(regime_to_remove);
}
m_unobserved_regimes[j].erase(m_unobserved_regimes[j].end() - 1);
m_number_of_unobserved_regimes[j]--;
}
}
}
void particle::alter_unobserved_regimes(const vector< int > & altering_unobserved_regimes, const size_t & number_of_processes) {
for (unsigned int j = 0; j < number_of_processes; j++) {
if (altering_unobserved_regimes[j] == 1) {
// choose the new unobserved regime (the only restriction is that it can't be regime 0)
unsigned int new_unobserved_regime = static_cast< unsigned int >(gsl_rng_uniform_int(r, m_regimes[j].size()) + 1);
size_t size_of_sufficient_statistics = m_regimes[j][0].get_size_of_sufficient_statistics();
// insert the new unobserved regime into m_regimes[j]
m_regimes[j].insert(m_regimes[j].begin() + new_unobserved_regime, regime(vector< int >(0), vector< unsigned int >(0), vector< unsigned int >(m_regimes[j].size(), 0), vector< double >(size_of_sufficient_statistics, 0), m_number_of_traces, 0, 0));
// set the likelihood to be 0 for this new regime
m_regimes[j][new_unobserved_regime].set_log_likelihood(0);
// for all other regimes, include an empty transition in m_right_transitions_histogram and, for each element in m_right_transitions, if the element is greater than or equal to the new_unobserved_regime then add 1 to it
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].insert_new_unobserved_regime(new_unobserved_regime);
}
for (unsigned int cp_index = 0; cp_index < m_dimension; cp_index++) {
m_tau[cp_index].increase_full_index_row_for_inserting_unobserved_regime_if_necessary(j, new_unobserved_regime);
}
m_unobserved_regimes[j].insert(m_unobserved_regimes[j].begin() + new_unobserved_regime, true);
m_number_of_unobserved_regimes[j]++;
}
else if (altering_unobserved_regimes[j] == -1) {
// choose which unobserved regime to remove using sub-linear method - keep guessing at unobserved regimes
unsigned int regime_to_remove = static_cast< unsigned int >(gsl_rng_uniform_int(r, m_regimes[j].size() - 1) + 1);
bool unobserved = m_unobserved_regimes[j][regime_to_remove];
while (!unobserved) {
regime_to_remove = static_cast< unsigned int >(gsl_rng_uniform_int(r, m_regimes[j].size() - 1) + 1);
unobserved = m_unobserved_regimes[j][regime_to_remove];
}
m_regimes[j].erase(m_regimes[j].begin() + regime_to_remove);
// for all other regimes, remove any trace of this unobserved regime (i.e. delete the 0 from m_right_transitions_histogram, decrease the indices of transitions greate than regime_to_remove by 1
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].remove_unobserved_regime(regime_to_remove);
}
for (unsigned int cp_index = 0; cp_index < m_dimension; cp_index++) {
m_tau[cp_index].decrease_full_index_row_for_removing_unobserved_regime_if_necessary(j, regime_to_remove);
}
m_unobserved_regimes[j].erase(m_unobserved_regimes[j].begin() + regime_to_remove);
m_number_of_unobserved_regimes[j]--;
}
}
}
//each changepoint now becomes the beginning of a binary
void particle::set_binary_marked_vectors(const size_t & number_of_processes, const vector< vector< double > > & log_likelihoods){
for (size_t j = 0; j < number_of_processes; j++){
m_binaries.push_back(vector< binary >(m_dimension + 2));
m_binaries[j][0] = binary(log_likelihoods[j][0], -1);
for (unsigned int cp_index = 0; cp_index < m_dimension; cp_index++){
m_binaries[j][cp_index + 1] = binary(log_likelihoods[j][cp_index + 1], cp_index);
}
m_binaries[j][m_dimension + 1] = binary(-1e300, m_dimension);
}
m_intercept_changepoint.set_binary_index(vector< unsigned int >(number_of_processes, 0));
for (unsigned int cp_index = 0; cp_index < m_dimension; cp_index++){
m_tau[cp_index].set_binary_index(vector< unsigned int >(number_of_processes, cp_index + 1));
}
}
void particle::set_all_binary_marked_vectors_equal_to_0_vectors(const size_t & number_of_processes) {
m_intercept_changepoint.set_binary_index(vector< unsigned int >(number_of_processes, 0));
for (int i = 0; i < m_dimension; i++) {
m_tau[i].set_binary_index(vector< unsigned int >(number_of_processes, 0));
}
}
void particle::add_end_binaries(const size_t & number_of_processes) {
for (unsigned int foo = 0; foo < number_of_processes; foo++) {
m_binaries[foo].push_back(binary(-1e300, m_dimension));
}
}
// use the full changepoint indices in full_particle to set binary indices in this particle. Changepoints after the full_particle dimension will be set as new binaries
void particle::set_binary_indices_from_full_indices(particle & full_particle, const size_t & number_of_processes) {
size_t full_dimension = full_particle.get_dimension();
// we know that the full index and the binary index for the intercept changepoint must both be 0.
m_binaries = vector< vector< binary > >(number_of_processes);
for (unsigned int process = 0; process < number_of_processes; process++) {
unsigned int binary_index = 0;
// set the 0th binary to have likelihood = 0, left_index = -1
m_binaries[process].push_back(binary(0, -1));
if (full_dimension > 0) {
if (full_particle.get_full_I_i_j(0, process) == 0) {
// if the 0th changepoint has full index == 0, then we do not need to make a new binary
m_tau[0].set_binary_index_row(process, binary_index);
}
else {
// if the 0th changpoint is a change in regime then we need to increase the binary index and make a new binary.
m_tau[0].set_binary_index_row(process, ++binary_index);
// make a new binary with likelihood 0 and left index 0 (the likelihoods will be set later)
m_binaries[process].push_back(binary(0, 0));
}
}
for (unsigned int cp_index = 1; cp_index < full_dimension; cp_index++) {
// Any regime change? If so, make a new binary
if (full_particle.get_full_I_i_j(cp_index, process) == full_particle.get_full_I_i_j(cp_index - 1, process)) {
m_tau[cp_index].set_binary_index_row(process, binary_index);
}
else {
m_tau[cp_index].set_binary_index_row(process, ++binary_index);
// set a new binary with log_likelihood 0 (it will be assigned later) and left index = cp_index
m_binaries[process].push_back(binary(0, cp_index));
}
}
if (m_dimension > full_dimension) {
for (unsigned int cp_index = static_cast< unsigned int >(full_dimension); cp_index < m_dimension; cp_index++) {
m_tau[cp_index].set_binary_index_row(process, ++binary_index);
m_binaries[process].push_back(binary(m_tau[cp_index].get_log_likelihood(), cp_index));
}
}
m_binaries[process].push_back(binary(-1e300, m_dimension));
}
}
// set the log likelihoods for all the binaries
void particle::set_binary_log_likelihoods(const vector< vector< double > > & log_likelihoods, const size_t & number_of_processes) {
for (unsigned int process = 0; process < number_of_processes; process++) {
if (log_likelihoods[process].size() != m_binaries[process].size() - 1) { cout << "log_likelihoods and binaries sizes don't match" << endl; }
for (unsigned int binary_index = 0; binary_index < log_likelihoods.size(); binary_index++) {
m_binaries[process][binary_index].set_log_likelihood(log_likelihoods[process][binary_index]);
}
}
}
vector< unsigned long int > particle::calculate_and_get_changepoint_histogram(const unsigned long int & number_of_changepoint_bins){
vector< unsigned long int > changepoints_vector(number_of_changepoint_bins, 0);
unsigned long int old_bin_index = m_dimension; // set this so that the bin_index can't equal old_bin_index
for (unsigned int cp_index = 0; cp_index < m_dimension; cp_index++){
unsigned long int bin_index = (number_of_changepoint_bins * (m_tau[cp_index].get_position() - 1)) / m_end;
if (bin_index != old_bin_index){ // do we already know that there's at least one cp in this bin?
changepoints_vector[bin_index]++;
}
old_bin_index = bin_index;
}
return changepoints_vector;
}
vector< unsigned long int > particle::calculate_and_get_binary_changepoint_histogram(const unsigned long int & number_of_changepoint_bins, const size_t & number_of_processes){
vector< unsigned long int > changepoints_vector(number_of_changepoint_bins * number_of_processes, 0);
for (unsigned int process = 0; process < number_of_processes; process++) {
size_t number_of_binaries = m_binaries[process].size() - 2;
unsigned long int old_bin_index = number_of_binaries + 1; // set this so that the bin_index doesn't begin equalling the old_bin_index
for (unsigned int binary_index = 1; binary_index < number_of_binaries + 1; binary_index++) {
unsigned long int bin_index = (number_of_changepoint_bins * (m_tau[m_binaries[process][binary_index].get_left_index()].get_position() - 1)) / m_end + number_of_changepoint_bins * process;
if (bin_index != old_bin_index) { // have we already recorded that there's at least one cp in this bin?
changepoints_vector[bin_index]++;
}
old_bin_index = bin_index;
}
}
return changepoints_vector;
}
vector< unsigned long int > particle::calculate_and_get_full_changepoint_histogram(const unsigned long int & number_of_changepoint_bins, const size_t & number_of_processes) {
vector< unsigned long int > changepoints_vector(number_of_changepoint_bins * number_of_processes, 0);
unsigned long int old_bin_index;
unsigned long int bin_index;
for (unsigned int process = 0; process < number_of_processes; process++) {
// old_bin_index is a dummy to make sure that we don't keep adding changepoints from the same bin
old_bin_index = -1;
// is m_tau[0] an effective changepoint?
if (0 < m_dimension && m_tau[0].get_full_index_row(process) != 0) {
bin_index = (number_of_changepoint_bins * (m_tau[0].get_position() - 1)) / m_end + number_of_changepoint_bins * process;
// have we already added a changepoint for this section?
if (bin_index != old_bin_index) {
changepoints_vector[bin_index]++;
}
old_bin_index = bin_index;
}
for (unsigned int cp_index = 1; cp_index < m_dimension; cp_index++) {
if (m_tau[cp_index].get_full_index_row(process) != m_tau[cp_index - 1].get_full_index_row(process)) {
bin_index = (number_of_changepoint_bins * (m_tau[cp_index].get_position() - 1)) / m_end + number_of_changepoint_bins * process;
// have we already added a changepoint for this section?
if (bin_index != old_bin_index) {
changepoints_vector[bin_index]++;
}
old_bin_index = bin_index;
}
}
}
return changepoints_vector;
}
void particle::calculate_and_add_similarity_matrices(vector< vector< double > > & similarity_matrix, const size_t & number_of_processes) {
for (unsigned int proc = 0; proc < number_of_processes; proc++) {
for (unsigned int reg_idx = 0; reg_idx < m_regimes[proc].size(); reg_idx++) {
m_regimes[proc][reg_idx].add_to_similarity_matrix(similarity_matrix);
}
}
}
void particle::calculate_and_add_min_proportion_similarity_matrices(vector< vector< double > > & min_proportion_similarity_matrix, const size_t & number_of_processes, const vector< unsigned long int > & actual_number_of_observations) {
// make two matrices, with 0 giving the sum over processes and regimes of I(n_{r,i,.}^{(s_0)} > 0, n_{r,i,.}^{(s_1)} > 0) n_{r,i,.}^{(s_0)} all divided by n_{s_0} and 1 giving the same but for the second trace. We will take the minimum after all computation.
vector< vector< double > > min_prop_mat_0(min_proportion_similarity_matrix.size(), vector< double >(min_proportion_similarity_matrix[0].size(), 0));
vector< vector< double > > min_prop_mat_1(min_proportion_similarity_matrix.size(), vector< double >(min_proportion_similarity_matrix[0].size(), 0));
for (unsigned int proc = 0; proc < number_of_processes; proc++) {
for (unsigned int reg_idx = 0; reg_idx < m_regimes[proc].size(); reg_idx++) {
m_regimes[proc][reg_idx].add_to_min_proportion_similarity_matrices(min_prop_mat_0, min_prop_mat_1, actual_number_of_observations);
}
}
// now work out which of these is the minimum for each pair of traces
for (unsigned int ind_0 = 0; ind_0 < min_proportion_similarity_matrix.size(); ind_0++) {
for (unsigned int ind_1 = 0; ind_1 < min_proportion_similarity_matrix.size(); ind_1++) {
min_proportion_similarity_matrix[ind_0][ind_1] += min_prop_mat_0[ind_0][ind_1] < min_prop_mat_1[ind_0][ind_1] ? min_prop_mat_0[ind_0][ind_1] : min_prop_mat_1[ind_0][ind_1];
}
}
}
void particle::add_to_association_matrix(vector< vector< double > > & association_matrix, const unsigned int & process) {
unsigned long int number_of_association_matrix_bins = association_matrix.size();
// for each regime that affects this process, add implied associations to matrix
for (unsigned int regime_index = 0; regime_index < m_regimes[process].size(); regime_index++) {
vector< int > regime_right_cp_indices = m_regimes[process][regime_index].get_right_changepoint_indices();
// work out the indices of the bins that are within this regime
vector< unsigned long int > regime_bin_indices = vector< unsigned long int >(0);
for (unsigned int regime_right_cp_indices_index = 0; regime_right_cp_indices_index < regime_right_cp_indices.size(); regime_right_cp_indices_index++) {
// work out the left and right change point indices for this interval
int right_cp_index = regime_right_cp_indices[regime_right_cp_indices_index];
unsigned long int right_changepoint_position;
if (right_cp_index == m_dimension) {
right_changepoint_position = m_end;
}
else {
right_changepoint_position = m_tau[right_cp_index].get_position();
}
unsigned long int left_changepoint_position;
if (right_cp_index == 0) {
left_changepoint_position = 0;
}
else {
left_changepoint_position = m_tau[right_cp_index - 1].get_position();
}
// i is the first bin association bin point that lies within the range of this interval
unsigned long int i, i_limit;
if ((left_changepoint_position * number_of_association_matrix_bins) % m_end == 0) {
i = (left_changepoint_position * number_of_association_matrix_bins) / m_end;
}
else {
i = (left_changepoint_position * number_of_association_matrix_bins) / m_end + 1;
}
// now feed in valid values of i to regime_bin_indices
if ((right_changepoint_position * number_of_association_matrix_bins) % m_end == 0) {
i_limit = (right_changepoint_position * number_of_association_matrix_bins) / m_end;
}
else {
i_limit = (right_changepoint_position * number_of_association_matrix_bins) / m_end + 1;
}
while (i < i_limit) {
regime_bin_indices.push_back(i);
i++;
}
}
size_t number_of_bin_indices = regime_bin_indices.size();
for (unsigned int bin_index = 0; bin_index < number_of_bin_indices; bin_index++) {
for (unsigned int bin_index_1 = 0; bin_index_1 < number_of_bin_indices; bin_index_1++) {
unsigned long int i_0 = regime_bin_indices[bin_index], i_1 = regime_bin_indices[bin_index_1];
association_matrix[i_0][i_1] += 1;
}
}
}
}
double particle::get_basic_log_posterior(){
return m_log_likelihood + m_log_k_prior;
}
double particle::get_binary_log_posterior(){
return m_log_likelihood + m_log_k_prior + m_log_binary_I_prior;
}
double particle::get_full_log_posterior(){
return m_log_likelihood + m_log_k_prior + m_log_full_I_prior + m_log_regimes_prior + m_log_full_separators_prior;
}
double particle::get_full_log_SMC_posterior() {
return m_log_likelihood + m_log_k_prior + m_log_full_I_prior + m_log_regimes_prior + m_log_full_separators_prior + m_log_arbitrary_extension_density;
}
// this function is called by a function manually calculating the log_likelihood for the process
vector< unsigned long int > particle::get_vector_of_binary_left_positions(const unsigned int process) {
vector< unsigned long int > binary_left_positions;
size_t number_of_left_positions = m_binaries[process].size();
for (unsigned int i = 0; i < number_of_left_positions; i++) {
int left_index = m_binaries[process][i].get_left_index();
if (left_index == -1) {
binary_left_positions.push_back(m_intercept_changepoint.get_position());
}
else if (left_index == m_dimension) {
binary_left_positions.push_back(m_end + 1);
}
else {
binary_left_positions.push_back(m_tau[left_index].get_position());
}
}
return binary_left_positions;
}
// work out the left indices for all the changepoints that correspond to a left index for a binary for the given process
vector< int > particle::get_vector_of_binary_left_indices(const unsigned int process) {
vector< int > binary_left_indices;
size_t number_of_left_indices = m_binaries[process].size();
for (unsigned int i = 0; i < number_of_left_indices; i++) {
int left_index = m_binaries[process][i].get_left_index();
binary_left_indices.push_back(left_index);
}
return binary_left_indices;
}
// get the left index of the binary containing m_tau[index - 1]. Often used to test if I_{h,j} == 1, as get_binary_left_index(j, h + 1) == h if this is true
int particle::get_binary_left_index(const size_t & process, const unsigned int & index){
if (index == 0){
return -1;
} else {
return m_binaries[process][m_tau[index - 1].get_binary_index_row(process)].get_left_index();
}
}
// get the left index of the binary to the right of the one containing m_tau[index - 1]
int particle::get_binary_right_index(const size_t & process, const unsigned int & index){
if (index == 0){
return m_binaries[process][1].get_left_index();
} else {
return m_binaries[process][m_tau[index - 1].get_binary_index_row(process) + 1].get_left_index();
}
}
// returns I_{i,j}
unsigned int particle::get_binary_I_i_j(const unsigned int & i, const unsigned int & j) { //i > -1
if (i == m_binaries[j][m_tau[i].get_binary_index_row(j)].get_left_index()) { //if i is the beginning of a binary
return 1;
}
else {
return 0;
}
}
// returns the index of the binary that contains m_tau[i] for process j
unsigned int particle::get_full_I_i_j(const unsigned int & i, const unsigned int & j) { //i > -1
return m_tau[i].get_full_index_row(j);
}
// returns the log_likelihood of binary that contains m_tau[index - 1]
double particle::get_binary_log_likelihood(const unsigned int & j, const unsigned int & index){
if (index == 0){
return m_binaries[j][0].get_log_likelihood();
} else {
return m_binaries[j][m_tau[index - 1].get_binary_index_row(j)].get_log_likelihood();
}
}
// sets the regimes based on the existing binaries and the sufficient statistics. sufficient statistics gives the vector vectors of cumulative data for each changepoint. e.g. sufficient_statistics[0][0] gives the cumulative sufficient statistics up to changepoint -1 for process 0.
void particle::set_full_marked_vectors(const size_t & number_of_processes, const vector< vector< vector< double > > > & sufficient_statistics, const vector< vector< double > > & number_of_observations) {
m_log_regimes_prior = static_cast< double >(number_of_processes) * log(m_rho);
m_log_full_separators_prior = 0;
m_regimes = vector< vector< regime > >(0);
m_unobserved_regimes = vector< vector< bool > >(0);
// set the full index for each changepoint to be equal to the binary index for each changepoint
m_intercept_changepoint.set_full_index_equal_to_binary_index();
for (unsigned int i = 0; i < m_dimension; i++) {
m_tau[i].set_full_index_equal_to_binary_index();
}
for (unsigned int j = 0; j < number_of_processes; j++) {
// each binary corresponds to a regime
m_regimes.push_back(vector< regime >(0));
unsigned int trace_index = 0;
for (unsigned int binary_index = 0; binary_index < m_binaries[j].size() - 2; binary_index++) {
// calculate sufficient statistics
vector< double > stats1 = sufficient_statistics[m_binaries[j][binary_index].get_left_index() + 1][j]; // +1 because sufficient stats contains the suffcient stats for cp_index -1
vector< double > stats2 = sufficient_statistics[m_binaries[j][binary_index + 1].get_left_index() + 1][j];
for (unsigned int proc = 0; proc < number_of_processes; proc++) {
stats2[proc] -= stats1[proc];
}
// calculate number of observations
double number_of_obs = number_of_observations[m_binaries[j][binary_index + 1].get_left_index() + 1][j] - number_of_observations[m_binaries[j][binary_index].get_left_index() + 1][j];
// calculate the right changepoint indices for each regime
vector< int > right_indices = vector< int >(0);
for (int i = m_binaries[j][binary_index].get_left_index(); i < m_binaries[j][binary_index + 1].get_left_index(); i++) {
right_indices.push_back(i + 1);
}
// calculate the right transitions and the right transitions histogram
vector< unsigned int > transitions = vector< unsigned int >(0);
vector< unsigned int > transitions_histogram = vector< unsigned int >(m_binaries[j].size() - 1, 0); // there is no slot for a non-regime at the end (can't transition to the non-regime at the end)
for (int i = m_binaries[j][binary_index].get_left_index(); i < m_binaries[j][binary_index + 1].get_left_index() - 1; i++) {
transitions.push_back(binary_index);
transitions_histogram[binary_index]++;
}
if (is_changepoint_index_separator_index(m_binaries[j][binary_index + 1].get_left_index())) {
transitions.push_back(-1);
}
else {
transitions.push_back(binary_index + 1);
transitions_histogram[binary_index + 1]++;
}
if (is_changepoint_index_separator_index(m_binaries[j][binary_index].get_left_index())) {
trace_index++;
}
m_regimes[j].push_back(regime(right_indices, transitions, transitions_histogram, stats2, m_number_of_traces, trace_index, number_of_obs));
// set the likelihood for the regime
m_regimes[j][binary_index].set_log_likelihood(m_binaries[j][binary_index].get_log_likelihood());
}
// calculate sufficient statistics
unsigned int binary_index = static_cast< unsigned int >(m_binaries[j].size() - 2);
vector< double > stats1 = sufficient_statistics[m_binaries[j][binary_index].get_left_index() + 1][j]; // +1 because sufficient_stats contains the suffcient stats for cp_index -1
vector< double > stats2 = sufficient_statistics[m_binaries[j][binary_index + 1].get_left_index() + 1][j];
for (unsigned int i = 0; i < stats2.size(); i++) {
stats2[i] -= stats1[i];
}
// calculate number of observations
double number_of_obs = number_of_observations[m_binaries[j][binary_index + 1].get_left_index() + 1][j] - number_of_observations[m_binaries[j][binary_index].get_left_index() + 1][j];
// calculate the left and right changepoint indices for each regime
vector< int > right_indices = vector< int >(0);
for (int i = m_binaries[j][binary_index].get_left_index(); i < m_binaries[j][binary_index + 1].get_left_index(); i++) {
right_indices.push_back(i + 1);
}
// calculate the right transitions and the right transitions histogram
vector< unsigned int > transitions = vector< unsigned int >(0);
for (int i = m_binaries[j][binary_index].get_left_index(); i < m_binaries[j][binary_index + 1].get_left_index() - 1; i++) {
transitions.push_back(binary_index);
}
// add a transition to nothing at the end.
transitions.push_back(-1);
vector< unsigned int > transitions_histogram = vector< unsigned int >(m_binaries[j].size() - 1, 0); // there is no slot for a non-regime at the end (can't transition to the non-regime at the end)
transitions_histogram[binary_index] = m_binaries[j][binary_index + 1].get_left_index() - m_binaries[j][binary_index].get_left_index() - 1;
// create the regime
if (m_include_separator) {
trace_index = static_cast< unsigned int >(m_number_of_traces - 1);
}
m_regimes[j].push_back(regime(right_indices, transitions, transitions_histogram, stats2, m_number_of_traces, trace_index, number_of_obs));
// set the log likelihood for the new regime
m_regimes[j][binary_index].set_log_likelihood(m_binaries[j][binary_index].get_log_likelihood());
m_log_regimes_prior += static_cast< double >(m_regimes[j].size() - 1) * log(1 - m_rho);
m_log_full_separators_prior -= static_cast< double >(m_separator_indices.size()) * log(static_cast< double >(m_regimes[j].size()));
// set the unobserved regimes indicator to be false for every regime
m_unobserved_regimes.push_back(vector< bool >(m_regimes[j].size(), false));
}
// set the number of unobserved regimes for each process to be 0
m_number_of_unobserved_regimes = vector< unsigned int >(number_of_processes, 0);
}
void particle::set_full_marked_vectors_without_binaries(const size_t & number_of_processes, const vector< vector< vector< double > > > & sufficient_statistics, const vector< vector< double > > & number_of_observations, const vector< vector< double > > & log_likelihoods) {
m_log_regimes_prior = static_cast< double >(number_of_processes) * log(m_rho);
m_log_full_separators_prior = 0;
m_regimes = vector< vector< regime > >(0);
m_unobserved_regimes = vector< vector< bool > >(0);
// set the full index for each changepoint to be equal to the binary index for each changepoint
m_intercept_changepoint.set_full_index(vector< unsigned int >(number_of_processes, 0));
// add separator changepoints?
for (unsigned int i = 0; i < m_dimension; i++) {
m_tau[i].set_full_index(vector< unsigned int >(number_of_processes, i + 1));
}
for (unsigned int j = 0; j < number_of_processes; j++) {
// each binary corresponds to a regime
m_regimes.push_back(vector< regime >(0));
unsigned int trace_index = 0;
for (unsigned int regime_index = 0; regime_index < m_dimension; regime_index++) {
// calculate sufficient statistics
vector< double > stats1 = sufficient_statistics[regime_index][j];
vector< double > stats2 = sufficient_statistics[regime_index + 1][j];
for (unsigned int proc = 0; proc < stats1.size(); proc++) {
stats2[proc] -= stats1[proc];
}
// calculate number of observations
double number_of_obs = number_of_observations[regime_index + 1][j] - number_of_observations[regime_index][j];
// calculate the right changepoint indices for each regime
vector< int > right_indices = vector< int >(0);
right_indices.push_back(regime_index);
// calculate the right transitions and the right transitions histogram
vector< unsigned int > transitions = vector< unsigned int >(0);
vector< unsigned int > transitions_histogram = vector< unsigned int >(m_dimension + 1, 0); // there is no slot for a non-regime at the end (can't transition to the non-regime at the end)
if (is_changepoint_index_separator_index(regime_index)) {
transitions.push_back(-1);
}
else {
transitions.push_back(regime_index + 1);
transitions_histogram[regime_index + 1]++;
}
if (is_changepoint_index_separator_index(regime_index - 1)) {
trace_index++;
}
m_regimes[j].push_back(regime(right_indices, transitions, transitions_histogram, stats2, m_number_of_traces, trace_index, number_of_obs));
// set the likelihood for the regime
m_regimes[j][regime_index].set_log_likelihood(log_likelihoods[regime_index + 1][j]);
}
// calculate sufficient statistics
unsigned int regime_index = m_dimension;
vector< double > stats1 = sufficient_statistics[regime_index][j];
vector< double > stats2 = sufficient_statistics[regime_index + 1][j];
for (unsigned int i = 0; i < stats2.size(); i++) {
stats2[i] -= stats1[i];
}
// calculate number of observations
double number_of_obs = number_of_observations[regime_index + 1][j] - number_of_observations[regime_index][j];
// calculate the left and right changepoint indices for each regime
vector< int > right_indices = vector< int >(0);
right_indices.push_back(regime_index);
// calculate the right transitions and the right transitions histogram
vector< unsigned int > transitions = vector< unsigned int >(0);
vector< unsigned int > transitions_histogram = vector< unsigned int >(m_dimension + 1, 0);
// add a transition to nothing at the end.
transitions.push_back(-1);
// create the regime
if (m_include_separator) {
trace_index = static_cast< unsigned int >(m_number_of_traces - 1);
}
m_regimes[j].push_back(regime(right_indices, transitions, transitions_histogram, stats2, m_number_of_traces, trace_index, number_of_obs));
// set the log likelihood for the new regime
m_regimes[j][regime_index].set_log_likelihood(log_likelihoods[regime_index + 1][j]); // IS THIS RIGHT?
m_log_regimes_prior += static_cast< double >(m_regimes[j].size() - 1) * log(1 - m_rho);
m_log_full_separators_prior -= static_cast< double >(m_separator_indices.size()) * log(static_cast< double >(m_regimes[j].size()));
// set the unobserved regimes indicator to be false for every regime
m_unobserved_regimes.push_back(vector< bool >(m_regimes[j].size(), false));
}
// set the number of unobserved regimes for each process to be 0
m_number_of_unobserved_regimes = vector< unsigned int >(number_of_processes, 0);
}
void particle::set_all_full_marked_vectors_equal_to_binary_marked_vectors(const size_t & number_of_processes) {
m_intercept_changepoint.set_full_index(vector< unsigned int >(number_of_processes, 0));
// add separator changepoints?
for (unsigned int i = 0; i < m_dimension; i++) {
m_tau[i].set_full_index(vector< unsigned int >(number_of_processes, i + 1));
}
}
void particle::set_all_regimes_to_be_observed(const size_t & number_of_processes) {
m_unobserved_regimes = vector< vector< bool > >(0);
m_number_of_unobserved_regimes = vector< unsigned int >(0);
for (unsigned int foo = 0; foo < number_of_processes; foo++) {
m_unobserved_regimes.push_back(vector< bool >(m_regimes[foo].size(), false));
m_number_of_unobserved_regimes.push_back(0);
}
}
void particle::add_new_regime(const unsigned int & process, vector< int > & right_changepoint_indices, vector< unsigned int > & right_transitions, vector< unsigned int > & right_transitions_histogram, vector< double > & sufficient_statistics, double & number_of_observations, double & log_likelihood, size_t & number_of_traces, const bool & new_trace, const unsigned int & trace_index, const unsigned int & previous_regime) {
unsigned int new_regime_index = static_cast< unsigned int >(m_regimes[process].size());
// increase the number of slots in the transitions_histogram for each other regime, adding a new transition from the previous regime unless this is the beginning of a new trace
for (unsigned int bar = 0; bar < new_regime_index; bar++) {
m_regimes[process][bar].add_regime_to_transitions_histogram(new_regime_index);
if (bar == previous_regime && !new_trace) {
m_regimes[process][bar].alter_last_transition(new_regime_index);
}
}
m_regimes[process].push_back(regime(right_changepoint_indices, right_transitions, right_transitions_histogram, sufficient_statistics, number_of_traces, trace_index, number_of_observations));
m_regimes[process].back().set_log_likelihood(log_likelihood);
// alter the full_indices for the changepoints
for (int foo = right_changepoint_indices[0]; foo <= right_changepoint_indices.back(); foo++) {
if (0 < foo) {
m_tau[foo - 1].set_full_index_row(process, new_regime_index);
}
}
m_regimes[process].back().set_transitions_out(m_regimes[process].back().get_number_of_right_transitions());
// the new regime will be set to be observed later
}
void particle::add_binary_to_regime(const unsigned int & process, const unsigned int & regime_index, const vector< int > & right_changepoint_indices, const vector< unsigned int > & right_transitions, const vector< unsigned int > & right_transitions_histogram, const vector< double > & extra_sufficient_statistics, const unsigned int & extra_number_of_observations, const double & log_likelihood_with_right_sufficient_statistics, const size_t & number_of_traces, const bool & new_trace, const unsigned int & trace_index, const unsigned int & previous_regime) {
m_regimes[process][regime_index].append_right_changepoint_indices(right_changepoint_indices);
m_regimes[process][regime_index].append_right_transitions(right_transitions);
m_regimes[process][regime_index].add_right_transitions_histogram(right_transitions_histogram);
m_regimes[process][regime_index].add_sufficient_statistics(extra_sufficient_statistics);
m_regimes[process][regime_index].add_observations(trace_index, extra_number_of_observations);
m_regimes[process][regime_index].set_log_likelihood(log_likelihood_with_right_sufficient_statistics);
// alter the full_indices of the changepoints
for (int foo = right_changepoint_indices[0]; foo <= right_changepoint_indices.back(); foo++) {
if (0 < foo) {
m_tau[foo - 1].set_full_index_row(process, regime_index);
}
}
// if this is not a new trace, need to add a transition to the end of the previous regime
if (!new_trace && previous_regime != regime_index) {
m_regimes[process][previous_regime].alter_last_transition(regime_index);
}
else if (!new_trace && previous_regime == regime_index) {
m_regimes[process][previous_regime].alter_right_transition(right_changepoint_indices[0] - 1, regime_index);
}
}
// calculate and get the number of observed regimes
unsigned int particle::get_number_of_observed_regimes(const unsigned int & process) {
unsigned int num_obs_regimes = 0;
for (const auto obs_bool:m_unobserved_regimes[process]) {
if (!obs_bool) {
num_obs_regimes++;
}
}
// check this matches number of regimes - number of unobserved regimes
unsigned int x = static_cast< unsigned int >(m_regimes[process].size()) - m_number_of_unobserved_regimes[process];
if (x != num_obs_regimes) {
cerr << "number of unobserved regimes don't match!" << endl;
}
return num_obs_regimes;
}
bool particle::removing_full_changepoint_leaves_highest_regime_unobserved(const unsigned int & process, const unsigned int & regime) {
return (m_regimes[process][regime].get_number_of_left_indices() == 1) && (regime > 0) && (regime == m_regimes[process].size() - 1);
}
bool particle::removing_full_changepoint_leaves_regime_unobserved(const unsigned int & process, const unsigned int & regime) {
return (m_regimes[process][regime].get_number_of_left_indices() == 1) && (regime > 0);
}
// are there any unobserved regimes for this process?
vector< bool > particle::any_unobserved_regimes() {
size_t number_of_processes = m_number_of_unobserved_regimes.size();
vector< bool > any_unobserved_regimes(number_of_processes, 0);
for (unsigned int j = 0; j < number_of_processes; j++) {
any_unobserved_regimes[j] = m_number_of_unobserved_regimes[j] > 0;
}
return any_unobserved_regimes;
}
// find the regime index for the regime which affects the changepoint prior to cp_index
unsigned int particle::get_previous_regime(const int & cp_index, const unsigned int & process) {
if (cp_index == 0) {
return 0;
}
else {
return m_tau[cp_index - 1].get_full_index_row(process);
}
}
// obtain the vector of sufficient statistics for the regime that affects process with index regime_index
vector< double > particle::get_sufficient_statistics(const unsigned int & process, const unsigned int & regime_index) {
return m_regimes[process][regime_index].get_sufficient_statistics();
}
// recover the log likelihood for regime regime_index for process
double particle::get_regime_log_likelihood(const unsigned int & process, const unsigned int & regime_index) {
return m_regimes[process][regime_index].get_log_likelihood();
}
bool particle::deleting_left_changepoint_removes_regime(const unsigned int & process, const unsigned int & regime_index) {
return m_regimes[process][regime_index].get_number_of_left_indices() > 1;
}
void particle::increase_separator_indices_greater_or_equal_to_index(const unsigned int & index) {
unsigned int i = static_cast< unsigned int >(m_separator_indices.size()) - 1;
bool greater_or_equal = m_separator_indices[i] >= index;
bool can_go_lower = true;
while (greater_or_equal && can_go_lower) {
m_separator_indices[i]++;
i--;
can_go_lower = i != numeric_limits< unsigned int >::max();
if (can_go_lower) {
greater_or_equal = m_separator_indices[i] >= index;
}
}
}
void particle::decrease_separator_indices_greater_than_index(const unsigned int & index) {
unsigned int i = static_cast< unsigned int >(m_separator_indices.size()) - 1;
bool greater_or_equal = m_separator_indices[i] > index;
bool can_go_lower = true;
while (greater_or_equal && can_go_lower) {
m_separator_indices[i]--;
i--;
can_go_lower = i != numeric_limits< unsigned int >::max();
if (can_go_lower) {
greater_or_equal = m_separator_indices[i] > index;
}
}
}
void particle::check_unobserved_regimes(const unsigned int process) {
unsigned int no_unob_regs = 0;
for (unsigned int i = 0; i < m_unobserved_regimes[process].size(); i++) {
if (m_unobserved_regimes[process][i]) {
no_unob_regs++;
}
}
if (no_unob_regs != m_number_of_unobserved_regimes[process]) {
cerr << "don't match" << endl;
}
}
void particle::check_separator_changepoints() {
if (m_separator_indices.size() != m_separators.size()) {
cerr << "sizes don't match" << endl;
}
for (unsigned int i = 0; i < m_separator_indices.size(); i++) {
if (m_separators[i] != m_tau[m_separator_indices[i]].get_position()) {
cerr << "m_separators are wrong" << endl;
}
}
}
void particle::check_observations_in_traces(const unsigned long int & time) {
double total_number_of_observations = 0;
for (unsigned int process = 0; process < m_regimes.size(); process++) {
for (unsigned int regime = 0; regime < m_regimes[process].size(); regime++) {
for (unsigned int trace = 0; trace < m_number_of_traces; trace++) {
if (m_regimes[process][regime].get_number_of_observations(trace) < -0.0001) {
cerr << "negative number of observations" << endl;
}
}
double number_of_observations = 0;
for (unsigned int trace = 0; trace < m_number_of_traces; trace++) {
number_of_observations += m_regimes[process][regime].get_number_of_observations(trace);
}
total_number_of_observations += number_of_observations;
double number_of_sufficient_statistics = 0;
for (unsigned int i = 0; i < m_regimes[process][regime].get_sufficient_statistics().size(); i++) {
number_of_sufficient_statistics += m_regimes[process][regime].get_sufficient_statistics()[i];
}
if (abs(number_of_sufficient_statistics - number_of_observations) > 0.0001) {
cerr << "number of observations doesn't match" << endl;
}
}
}
/*if (abs(time - 1 - total_number_of_observations - static_cast< double >(m_number_of_traces - 1)) > 0.0001) {
cerr << "wrong number of observations" << endl;
cerr << "total number of observations: " << total_number_of_observations << ", time: " << time << ", m_trace_index: " << m_trace_index << endl;
}*/
}
void particle::check_regimes_and_right_changepoints() {
for (unsigned int proc = 0; proc < m_regimes.size(); proc++) {
// check if regime 0 has changepoint 0 (possibly at end) as a right changepoint index
if (m_regimes[proc][0].get_right_changepoint_indices()[0] != 0) {
cerr << "regime 0 doesn't have changepoint 0 as a right changepoint index" << endl;
}
// go though each of the right changepoint indices in each regime and see if it matches the full indices of the changepoints
for (unsigned int reg = 0; reg < m_regimes[proc].size(); reg++) {
vector< int > right_changepoint_indices = m_regimes[proc][reg].get_right_changepoint_indices();
vector< unsigned int > right_transitions = m_regimes[proc][reg].get_right_transitions();
for (unsigned int i = 0; i < right_changepoint_indices.size(); i++) {
if (right_changepoint_indices[i] != 0) {
if (reg != m_tau[right_changepoint_indices[i] - 1].get_full_index_row(proc)) {
cerr << "regimes don't match" << endl;
}
}
if (right_changepoint_indices[i] != m_dimension) {
if (right_transitions[i] != numeric_limits< unsigned int >::max()) {
if (right_transitions[i] != m_tau[right_changepoint_indices[i]].get_full_index_row(proc)) {
cerr << "regimes don't match" << endl;
}
}
}
}
// also check that right transitions and right transitions histogram match up
vector< unsigned int > right_transitions_histogram = m_regimes[proc][reg].get_right_transitions_histogram();
for (unsigned int i = 0; i < right_transitions.size(); i++) {
if (right_transitions[i] < numeric_limits< unsigned int >::max()) {
right_transitions_histogram[right_transitions[i]]--;
}
}
for (unsigned int i = 0; i < right_transitions_histogram.size(); i++) {
if (right_transitions_histogram[i] != 0) {
cerr << "transitions don't match" << endl;
}
}
}
}
}
void particle::check_full_log_posterior(const bool & always_new_regime = false) {
unsigned int number_of_processes = static_cast< unsigned int >(m_regimes.size());
double log_k_prior = 0;
log_k_prior = calculate_and_get_log_k_prior();
if (0.01 < abs(log_k_prior - m_log_k_prior)) {
cout << "k prior difference " << log_k_prior - m_log_k_prior << endl;
}
double full_log_I_prior;
if (always_new_regime) {
full_log_I_prior = 0;
}
else {
full_log_I_prior = calculate_and_get_log_full_I_prior(number_of_processes);
}
if (0.01 < abs(full_log_I_prior - m_log_full_I_prior)) {
cout << "full log I prior difference " << full_log_I_prior - m_log_full_I_prior << endl;
}
double full_log_regime_prior;
full_log_regime_prior = calculate_and_get_log_regimes_prior(number_of_processes);
if (0.01 < abs(full_log_regime_prior - m_log_regimes_prior)) {
cout << "full log regime prior difference " << full_log_regime_prior - m_log_regimes_prior << endl;
}
double full_log_separators_prior;
full_log_separators_prior = calculate_and_get_log_full_separators_prior(number_of_processes);
if (0.01 < abs(full_log_separators_prior - m_log_full_separators_prior)) {
cout << "full log separators difference " << full_log_separators_prior - m_log_full_separators_prior << endl;
}
double full_log_likelihood;
full_log_likelihood = calculate_and_get_full_log_likelihood(number_of_processes);
if (0.01 < abs(full_log_likelihood - m_log_likelihood)) {
cout << "full log likelihood difference " << full_log_likelihood - m_log_likelihood << endl;
}
}
void particle::check_transitions_out() {
for (unsigned int process = 0; process < m_regimes.size(); process++) {
for (unsigned int reg = 0; reg < m_regimes[process].size(); reg++) {
vector< unsigned int > right_transitions = m_regimes[process][reg].get_right_transitions_histogram();
unsigned int trans_out = 0;
for (unsigned int i = 0; i < right_transitions.size(); i++) {
trans_out += right_transitions[i];
}
if (trans_out != m_regimes[process][reg].get_transitions_out()) {
cout << "difference" << endl;
}
}
}
}
//smc-only functions
double particle::calculate_and_get_add_cp_proposal_ratio(const unsigned long int & available_cp_positions, const unsigned long int & total_cp_positions) {
double proposal_ratio = log(static_cast< double >(available_cp_positions)) - log(static_cast< double >(total_cp_positions - available_cp_positions + 1));
if (total_cp_positions == available_cp_positions) { // i.e. dimension == 0
proposal_ratio -= log(4); // prob 1 of proposing increase, prob 1/4 of proposing decrease, (1/4)/1 = 1/4
}
else if (available_cp_positions == 1) { // i.e. there is a single spot left for adding a changepoint
proposal_ratio += log(4); // prob 1/4 of proposing increase, prob 1 of proposing decrease, 1/(1/4) = 4
}
return proposal_ratio;
}
double particle::calculate_and_get_remove_cp_proposal_ratio(const unsigned long int & available_cp_positions, const unsigned long int & total_cp_positions) {
return log(static_cast< double >(total_cp_positions - available_cp_positions)) - log(available_cp_positions + 1);
}
void particle::extend_regime(const unsigned int & process, const unsigned int & previous_regime, const vector< double > & new_interval_sufficient_statistics, const double & previous_regime_new_log_likelihood, const unsigned int & trace_index, const double & number_of_observations) {
m_regimes[process][previous_regime].add_sufficient_statistics(new_interval_sufficient_statistics);
m_log_likelihood += previous_regime_new_log_likelihood - m_regimes[process][previous_regime].get_log_likelihood();
m_regimes[process][previous_regime].set_log_likelihood(previous_regime_new_log_likelihood);
m_regimes[process][previous_regime].add_observations(trace_index, number_of_observations);
}
void particle::add_full_separator_changepoint(changepoint & separator_changepoint, const vector< unsigned int > & new_regimes, const vector< vector< double > > & sufficient_statistics, const vector< vector< double > > & log_likelihoods, const vector< double > & number_of_observations) {
m_log_k_prior += calculate_and_get_add_cp_k_prior_ratio();
separator_changepoint.set_full_index(new_regimes);
// insert new_changepoint into m_tau
m_tau.push_back(separator_changepoint);
m_dimension++; //increase dimension
size_t number_of_processes = new_regimes.size();
// make sure the m_include_separator is true
m_include_separator = true;
// add this separator to the list of separator indices
m_separators.push_back(separator_changepoint.get_position());
m_separator_indices.push_back(m_dimension - 1);
m_number_of_traces++;
// add an extra trace to each regime (for the number of observations in each regime)
for (unsigned int proc = 0; proc < number_of_processes; proc++) {
for (unsigned int reg = 0; reg < m_regimes[proc].size(); reg++) {
m_regimes[proc][reg].add_new_trace();
}
}
double s = static_cast<double>(m_separator_indices.size());
for (unsigned int j = 0; j < number_of_processes; j++) {
double number_of_regimes = static_cast< double >(m_regimes[j].size());
m_log_full_separators_prior -= log(number_of_regimes);
// if adding a new regime, insert it into the collection of existing regimes, and change the other regimes so that they know the number of regimes has increased.
bool adding_new_regime = new_regimes[j] == m_regimes[j].size();
if (adding_new_regime) {
for (unsigned int i = 0; i < m_regimes[j].size(); i++) {
// increase the size of the transitions histogram for each of the regimes in this process.
m_regimes[j][i].add_regime_to_transitions_histogram(new_regimes[j]);
}
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_log_full_I_prior += gsl_sf_lngamma((number_of_regimes + 1) * m_dirichlet_alpha) + gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + static_cast< double >(m_regimes[j][regime].get_number_of_right_transitions())) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma((number_of_regimes + 1) * m_dirichlet_alpha + static_cast< double >(m_regimes[j][regime].get_number_of_right_transitions()));
}
m_log_regimes_prior += log(1.0 - m_rho);
m_log_full_separators_prior += s * log(number_of_regimes) - s * log(number_of_regimes + 1);
// insert new regime into m_regimes[j]. We don't include the right changepoint position, right transition, sufficient statistics or number_of_observations here as it will be added later
// these will be converted to the correct values later
m_regimes[j].push_back(regime(vector< int >(0), vector< unsigned int >(0), vector< unsigned int >(m_regimes[j].size() + 1, 0), vector< double >(sufficient_statistics[j].size(), 0), m_number_of_traces, m_trace_index, 0));
// these unobserved regime values will be corrected later
m_unobserved_regimes[j].push_back(true);
m_number_of_unobserved_regimes[j]++;
}
}
m_trace_index = static_cast< unsigned int >(m_separators.size());
for (unsigned int j = 0; j < number_of_processes; j++) {
// insert the interval
m_regimes[j][new_regimes[j]].add_interval(m_dimension, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j]);
m_log_likelihood += log_likelihoods[j][new_regimes[j]] - m_regimes[j][new_regimes[j]].get_log_likelihood();
// assign right sufficient statistics and observation numbers to the new regime. Set the log likelihood for each regime
m_regimes[j][new_regimes[j]].add_sufficient_statistics(sufficient_statistics[j]);
m_regimes[j][new_regimes[j]].set_log_likelihood(log_likelihoods[j][new_regimes[j]]);
m_regimes[j][new_regimes[j]].add_observations(m_trace_index, number_of_observations[j]);
}
}
// add a changepoint that was guaranteed to be accepted to the particle. It will be added to the end of m_tau and new sufficient statistics, observations and likelihood will be added
void particle::add_guaranteed_full_changepoint(changepoint & adding_changepoint, const vector< unsigned int > & new_regimes, const vector< vector< double > > & right_sufficient_statistics, const vector< vector< double > > & log_likelihoods_with_right_sufficient_statistics, const vector< double > & right_number_of_observations) {
m_log_k_prior += calculate_and_get_add_cp_k_prior_ratio();
// insert new_changepoint into m_tau
m_tau.push_back(adding_changepoint);
m_dimension++; //increase dimension
size_t number_of_processes = new_regimes.size();
// assign the regime indices for the new changepoint.
m_tau.back().set_full_index(new_regimes);
for (unsigned int j = 0; j < number_of_processes; j++) {
unsigned int prev_regime_index;
// calculate the regime index of the previous changepoint
if (m_dimension == 1) {
prev_regime_index = 0;
}
else {
prev_regime_index = m_tau[m_dimension - 2].get_full_index_row(j);
}
// if adding a new regime, insert it into the collection of existing regimes, and change the other regimes so that they know the number of regimes has increased.
bool adding_new_regime = new_regimes[j] == m_regimes[j].size();
if (adding_new_regime) {
for (unsigned int i = 0; i < m_regimes[j].size(); i++) {
// increase the size of the transitions histogram for each of the regimes in this process.
m_regimes[j][i].add_regime_to_transitions_histogram(new_regimes[j]);
}
// insert new regime into m_regimes[j]. We don't include the right changepoint position, right transition, sufficient statistics or number_of_observations here as it will be added later
// these will be converted to the correct values later
m_regimes[j].push_back(regime(vector< int >(0), vector< unsigned int >(0), vector< unsigned int >(m_regimes[j].size() + 1, 0), vector< double >(right_sufficient_statistics[j].size(), 0), m_number_of_traces, m_trace_index, 0));
// these unobserved regime values will be corrected later
m_unobserved_regimes[j].push_back(true);
m_number_of_unobserved_regimes[j]++;
}
// insert the interval and transition out of the new_regime
// replace the right transition from previous regime to subsequent regime with a transition to new_regime (unless new_regime is equal to subsequent_regime), adding a transition out of previous regime if the new changepoint is inserted at the end of m_tau.
m_regimes[j][prev_regime_index].alter_right_transition(m_dimension - 1, new_regimes[j]);
m_regimes[j][new_regimes[j]].add_interval(m_dimension, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j]);
m_trace_index = static_cast< unsigned int >(m_number_of_traces - 1);
// assign right sufficient statistics and observation numbers to the new regime. Calculate the log likelihood for each regime
m_log_likelihood += log_likelihoods_with_right_sufficient_statistics[j][new_regimes[j]] - m_regimes[j][new_regimes[j]].get_log_likelihood();
m_regimes[j][new_regimes[j]].add_sufficient_statistics(right_sufficient_statistics[j]);
m_regimes[j][new_regimes[j]].set_log_likelihood(log_likelihoods_with_right_sufficient_statistics[j][new_regimes[j]]);
m_regimes[j][new_regimes[j]].add_observations(m_trace_index, right_number_of_observations[j]);
}
}
void particle::increase_log_separator_prior(const double & full_log_prior, const bool & adding_new_regime, const unsigned int & process) {
// if we are not adding a new regime then full_log_prior = -log(number_of_regimes)
//m_log_full_separators_prior += full_log_prior;
if (adding_new_regime) {
// if we are adding a new regime then full_log_prior = log_full_I_prior_ratio + log(1 - rho) + s * log(number_of_regimes) - (s + 1) * log(number_of_regimes + 1)
//m_log_full_separators_prior -= log(1.0 - m_rho);
m_log_regimes_prior += log(1 - m_rho);
double number_of_regimes = static_cast< double >(m_regimes[process].size());
double s = static_cast<double>(m_separator_indices.size());
double log_full_I_prior_ratio = full_log_prior - log(1.0 - m_rho) - s * log(number_of_regimes) + (s + 1) * log(number_of_regimes + 1);
m_log_full_I_prior += log_full_I_prior_ratio;
//m_log_full_separators_prior -= log_full_I_prior_ratio;
}
}
// can either pass uniform RVs to choose the number of regimes for each process or pass in the number of unobserved regimes for each process
void particle::resample_number_of_unobserved_regimes(vector< double > uniform_rvs, vector< unsigned int > new_numbers_of_unobserved_regimes = vector< unsigned int >(0)) {
unsigned int number_of_processes = static_cast< unsigned int >(m_regimes.size());
for (unsigned int proc = 0; proc < number_of_processes; proc++) {
unsigned int new_number_of_unobserved_regimes = 0;
if (0 < new_numbers_of_unobserved_regimes.size()) { // is new_numbers_of_unobserved_regimes not an empty vector?
new_number_of_unobserved_regimes = new_numbers_of_unobserved_regimes[proc];
}
else {
// use the uniform RV to choose the number of unobserved regimes for this process
if (m_rho < uniform_rvs[proc]) {
new_number_of_unobserved_regimes = 1;
double temp = m_rho * (1 - m_rho);
double temp_sum = m_rho + temp;
while (temp_sum < uniform_rvs[proc]) {
new_number_of_unobserved_regimes++;
temp *= (1 - m_rho);
temp_sum += temp;
}
}
}
if (m_number_of_unobserved_regimes[proc] < new_number_of_unobserved_regimes) { // need to add more unobserved regimes
for (unsigned int new_reg = 0; new_reg < new_number_of_unobserved_regimes - m_number_of_unobserved_regimes[proc]; new_reg++) {
// alter the priors: full_I, separators, regimes
double number_of_regimes = static_cast< double >(m_regimes[proc].size());
double log_full_I_prior_ratio = calculate_and_get_add_unobserved_regimes_full_I_prior_ratio(proc) - static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
m_log_full_I_prior += log_full_I_prior_ratio;
m_log_full_separators_prior += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
m_log_regimes_prior += log(1 - m_rho);
// add the new regime
unsigned int new_regime = static_cast< unsigned int >(m_regimes[proc].size());
for (unsigned int i = 0; i < m_regimes[proc].size(); i++) {
// increase the size of the transitions histogram for each of the regimes in this process.
m_regimes[proc][i].add_regime_to_transitions_histogram(new_regime);
}
// calculate the size of the sufficient statistics vector for process proc
size_t suff_stats_size = m_regimes[proc][0].get_size_of_sufficient_statistics();
// insert new regime into m_regimes[proc]
m_regimes[proc].push_back(regime(vector< int >(0), vector< unsigned int >(0), vector< unsigned int >(m_regimes[proc].size() + 1, 0), vector< double >(suff_stats_size, 0), m_number_of_traces, m_trace_index, 0));
m_unobserved_regimes[proc].push_back(true);
m_number_of_unobserved_regimes[proc]++;
}
}
else if (new_number_of_unobserved_regimes < m_number_of_unobserved_regimes[proc]) { // removing unobserved regimes
// find the indices of the unobserved regimes
vector < unsigned int > unobserved_regime_indices = vector< unsigned int >(m_number_of_unobserved_regimes[proc]);
unsigned int uo_idx = 0;
for (unsigned int id = 0; id < m_unobserved_regimes[proc].size(); id++) {
if (m_unobserved_regimes[proc][id]) {
unobserved_regime_indices[uo_idx] = id;
uo_idx++;
}
}
for (int del_reg = new_number_of_unobserved_regimes - m_number_of_unobserved_regimes[proc]; del_reg < 0; del_reg++) {
// alter the priors: full_I, separators, regimes
double number_of_regimes = static_cast< double >(m_regimes[proc].size());
double log_full_I_prior_ratio = calculate_and_get_remove_unobserved_regimes_full_I_prior_ratio(proc) - static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes - 1));
m_log_full_I_prior += log_full_I_prior_ratio;
m_log_full_separators_prior += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes - 1));
m_log_regimes_prior -= log(1 - m_rho);
// delete the highest unobserved regime (so we don't have to keep changing the unobserved_regime_indices)
m_regimes[proc].erase(m_regimes[proc].begin() + unobserved_regime_indices.back());
unsigned int regime_to_remove = static_cast< unsigned int >(unobserved_regime_indices.back());
unobserved_regime_indices.erase(unobserved_regime_indices.end() - 1);
// for all other regimes, remove any trace of this unobserved regime (i.e. delete the 0 from m_right_transitions_histogram, decrease the indices of transitions greate than regime_to_remove by 1
for (unsigned int regime = 0; regime < m_regimes[proc].size(); regime++) {
m_regimes[proc][regime].remove_unobserved_regime(regime_to_remove);
}
for (unsigned int cp_index = 0; cp_index < m_dimension; cp_index++) {
m_tau[cp_index].decrease_full_index_row_for_removing_unobserved_regime_if_necessary(proc, regime_to_remove);
}
m_unobserved_regimes[proc].erase(m_unobserved_regimes[proc].begin() + regime_to_remove);
m_number_of_unobserved_regimes[proc]--;
}
}
}
}
void particle::permute_process_regimes(const unsigned int & process, const vector< unsigned int > & permutation_vector) {
// permute the regimes stored in m_regimes[process] and the boolean values of m_unobserved_regimes
vector< regime > regimes_copy = m_regimes[process];
vector< bool > unobserved_regimes_copy = m_unobserved_regimes[process];
for (unsigned int i = 0; i < m_regimes[process].size(); i++) {
m_regimes[process][permutation_vector[i]] = regimes_copy[i];
m_unobserved_regimes[process][permutation_vector[i]] = unobserved_regimes_copy[i];
}
for (unsigned int i = 0; i < m_regimes[process].size(); i++) {
// permute the transitions histogram and right_transitions for this regime
m_regimes[process][i].permute_transitions_histogram(permutation_vector);
m_regimes[process][i].permute_right_transitions(permutation_vector);
}
// alter the full regime index for process for any changepoints (don't need to do the intercept changepoint because we know that the full index will be [0, ..., 0] for it.
for (unsigned int j = 0; j < m_dimension; j++) {
unsigned int current_reg = m_tau[j].get_full_index_row(process);
m_tau[j].set_full_index_row(process, permutation_vector[current_reg]);
}
}
bool particle::is_regime_observed_before(const unsigned int & cp_index, const unsigned int & process) { // is the regime for changepoint cp_index for the process observed before changepoint cp_index?
unsigned int regime = m_tau[cp_index].get_full_index_row(process);
if (regime == 0) {
return true;
}
bool found = false;
unsigned int j = 0;
while (!found && j < cp_index) {
found = m_tau[j].get_full_index_row(process) == regime;
j++;
}
return found;
}
int particle::find_changepoint_with_same_regime(const unsigned int & cp_index, const unsigned int & process) { // given that the regime for the changepoint cp_index is observed before changepoint cp_index, when is it first observed?
unsigned int regime = m_tau[cp_index].get_full_index_row(process);
if (regime == 0) {
return -1;
}
bool found = false;
int j = 0;
while (!found && j < cp_index) {
found = m_tau[cp_index].get_full_index_row(process) == regime;
j++;
}
j--;
return j;
}
void particle::add_to_association_matrix_up_to_time(vector< vector< double > > & association_matrix, const unsigned int & process, const unsigned long int & time) {
unsigned long int number_of_association_matrix_bins = association_matrix.size();
// for each regime that affects this process, add implied associations to matrix
for (unsigned int regime_index = 0; regime_index < m_regimes[process].size(); regime_index++) {
vector< int > regime_right_cp_indices = m_regimes[process][regime_index].get_right_changepoint_indices();
// work out the indices of the bins that are within this regime
vector< unsigned long int > regime_bin_indices = vector< unsigned long int >(0);
for (unsigned int regime_right_cp_indices_index = 0; regime_right_cp_indices_index < regime_right_cp_indices.size(); regime_right_cp_indices_index++) {
// work out the left and right change point indices for this interval
int right_cp_index = regime_right_cp_indices[regime_right_cp_indices_index];
unsigned long int right_changepoint_position;
if (right_cp_index == m_dimension) {
right_changepoint_position = time;
}
else {
right_changepoint_position = m_tau[right_cp_index].get_position();
}
unsigned long int left_changepoint_position;
if (right_cp_index == 0) {
left_changepoint_position = 0;
}
else {
left_changepoint_position = m_tau[right_cp_index - 1].get_position();
}
// i is the first bin association bin point that lies within the range of this interval
unsigned long int i, i_limit;
if ((left_changepoint_position * number_of_association_matrix_bins) % m_end == 0) {
i = (left_changepoint_position * number_of_association_matrix_bins) / m_end;
}
else {
i = (left_changepoint_position * number_of_association_matrix_bins) / m_end + 1;
}
// now feed in valid values of i to regime_bin_indices
if ((right_changepoint_position * number_of_association_matrix_bins) % m_end == 0) {
i_limit = (right_changepoint_position * number_of_association_matrix_bins) / m_end;
}
else {
i_limit = (right_changepoint_position * number_of_association_matrix_bins) / m_end + 1;
}
while (i < i_limit) {
regime_bin_indices.push_back(i);
i++;
}
}
size_t number_of_bin_indices = regime_bin_indices.size();
for (unsigned int bin_index = 0; bin_index < number_of_bin_indices; bin_index++) {
for (unsigned int bin_index_1 = 0; bin_index_1 < number_of_bin_indices; bin_index_1++) {
unsigned long int i_0 = regime_bin_indices[bin_index], i_1 = regime_bin_indices[bin_index_1];
association_matrix[i_0][i_1] += 1;
}
}
}
}
// returns the log of the full I prior ratio if we were adding the changepoint that we are proposing removing with regime proposed_regime. Index gives the position of the changepoint that we are proposing to remove. new_regime gives whether the proposed_regime is a new regime, either in the sense that if the changepoint were deleted it would remove regime proposed_regime, or in the sense that if we were proposing a changepoint here we would be proposing a new regime for it. actual_regime gives the actual regime of the changepoint that we are removing
double particle::full_log_I_prior_smc_remove_ratio(const int & index, const unsigned int & process, const unsigned int & previous_regime, const unsigned int & proposed_regime, const bool & new_regime, const unsigned int & actual_regime, const bool & removing_unobserved_regime, const unsigned int & subsequent_regime) {
double q;
// check if the number of regimes has been reduced before running this, if so then reduce the number of regimes by 1.
double number_of_regimes = static_cast< double >(get_number_of_regimes(process)) - (removing_unobserved_regime ? 1.0 : 0.0);
if (subsequent_regime == numeric_limits< unsigned int >::max()) {
if (new_regime) {
q = log(m_dirichlet_alpha);
double transitions_out_of_previous_regime = static_cast< double >(m_regimes[process][previous_regime].get_number_of_right_transitions() - 1);
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_previous_regime) - gsl_sf_lngamma(m_dirichlet_alpha + 1 + number_of_regimes * m_dirichlet_alpha + transitions_out_of_previous_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
for (unsigned int regime = 0; regime < previous_regime; regime++) {
if (!removing_unobserved_regime || (regime != actual_regime)) { // only do this if we haven't removed this regime - if actual_regime is removed, then actual_regime can't be used to compute q.
double transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions());
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
}
for (unsigned int regime = previous_regime + 1; regime < get_number_of_regimes(process); regime++) {
if (!removing_unobserved_regime || (regime != actual_regime)) { // only do this if we haven't removed this regime
double transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions());
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
}
q += log(1 - m_rho);
q += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
}
else {
double transitions_from_previous_to_proposed = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(proposed_regime)) - (proposed_regime == actual_regime ? 1 : 0);
double transitions_out_of_previous_regime = static_cast< double >(m_regimes[process][previous_regime].get_number_of_right_transitions() - 1);
q = log(m_dirichlet_alpha + transitions_from_previous_to_proposed) - log(number_of_regimes * m_dirichlet_alpha + transitions_out_of_previous_regime);
}
}
else {
if (new_regime) {
double transitions_from_previous_to_subsequent_regime = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(subsequent_regime));
if (actual_regime == subsequent_regime) {
if (previous_regime == actual_regime) {
transitions_from_previous_to_subsequent_regime--;
}
}
else {
if (previous_regime != actual_regime) {
transitions_from_previous_to_subsequent_regime++;
}
}
q = 2 * log(m_dirichlet_alpha) - log(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - log(m_dirichlet_alpha + transitions_from_previous_to_subsequent_regime - 1);
for (unsigned int regime = 0; regime < get_number_of_regimes(process); regime++) {
if (!removing_unobserved_regime || (regime != actual_regime)) { // only do this if we haven't removed this regime - if actual_regime is removed, then actual_regime can't be used to compute q.
double transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions());
transitions_out_of_regime -= (actual_regime == regime ? 1 : 0);
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) + gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
}
q += log(1 - m_rho);
q += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
}
else {
if (proposed_regime == previous_regime) {
double transitions_from_previous_to_previous_regime = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(previous_regime));
double transitions_out_of_previous_regime = static_cast< double >(m_regimes[process][previous_regime].get_number_of_right_transitions());
if (previous_regime == actual_regime) {
transitions_from_previous_to_previous_regime--;
transitions_out_of_previous_regime--;
}
else {
if (previous_regime == subsequent_regime) {
transitions_from_previous_to_previous_regime++;
}
}
q = log(m_dirichlet_alpha + transitions_from_previous_to_previous_regime) - log(number_of_regimes * m_dirichlet_alpha + transitions_out_of_previous_regime);
}
else {
if (subsequent_regime == proposed_regime) {
double transitions_from_subsequent_to_subsequent_regime = static_cast< double >(m_regimes[process][subsequent_regime].get_right_transitions_histogram_element(subsequent_regime));
double transitions_out_of_subsequent_regime = static_cast< double >(m_regimes[process][subsequent_regime].get_number_of_right_transitions());
if (actual_regime == subsequent_regime) {
transitions_out_of_subsequent_regime--;
transitions_from_subsequent_to_subsequent_regime--;
}
else {
if (previous_regime == subsequent_regime) {
transitions_from_subsequent_to_subsequent_regime++;
}
}
q = log(m_dirichlet_alpha + transitions_from_subsequent_to_subsequent_regime) - log(m_dirichlet_alpha * number_of_regimes + transitions_out_of_subsequent_regime);
}
else { // know proposed != previous and proposed != subsequent
// therefore these three transition counts are definitely different
double transitions_from_previous_to_proposed_regime = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(proposed_regime));
double transitions_from_proposed_to_subsequent_regime = static_cast< double >(m_regimes[process][proposed_regime].get_right_transitions_histogram_element(subsequent_regime));
double transitions_from_previous_to_subsequent_regime = static_cast< double >(m_regimes[process][previous_regime].get_right_transitions_histogram_element(subsequent_regime));
if (actual_regime == subsequent_regime) {
if (previous_regime == actual_regime) {
transitions_from_previous_to_subsequent_regime--;
}
else {
if (proposed_regime == actual_regime) {
transitions_from_proposed_to_subsequent_regime--;
}
}
}
else {
if (previous_regime != actual_regime) {
if (proposed_regime == actual_regime) {
transitions_from_previous_to_proposed_regime--;
transitions_from_proposed_to_subsequent_regime--;
}
transitions_from_previous_to_subsequent_regime++;
}
}
double transitions_out_of_proposed_regime = static_cast< double >(m_regimes[process][proposed_regime].get_number_of_right_transitions());
if (proposed_regime == actual_regime) {
transitions_out_of_proposed_regime--;
}
q = log(m_dirichlet_alpha + transitions_from_previous_to_proposed_regime) + log(m_dirichlet_alpha + transitions_from_proposed_to_subsequent_regime) - log(m_dirichlet_alpha + transitions_from_previous_to_subsequent_regime - 1) - log(number_of_regimes * m_dirichlet_alpha + transitions_out_of_proposed_regime);
}
}
}
}
return q;
}
// following_regime and proposed_regime default to -1. Gives the log of the full I prior ratio for adding the separator as a changepoint after it has been removed.
double particle::log_smc_resampling_separator_changepoint_prior_ratio(const unsigned int & process, const bool & no_following_regime, const bool & new_regime, const bool & removing_unobserved_regime, const unsigned int & actual_regime, const unsigned int & following_regime, const unsigned int & proposed_regime) {
double q = 0;
double number_of_regimes = static_cast< double >(get_number_of_regimes(process)) - (removing_unobserved_regime ? 1.0 : 0.0);
if (no_following_regime) {
if (new_regime) {
for (unsigned int regime = 0; regime < m_regimes[process].size(); regime++) {
if (!removing_unobserved_regime || (actual_regime != regime)) {
double transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions());
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
}
q += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
q += log(1 - m_rho);
}
}
else {
if (new_regime) {
for (unsigned int regime = 0; regime < m_regimes[process].size(); regime++) {
if (!removing_unobserved_regime || (actual_regime != regime)) {
double transitions_out_of_regime = static_cast< double >(m_regimes[process][regime].get_number_of_right_transitions() - (actual_regime == regime ? 1 : 0));
q += gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime) - gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha + transitions_out_of_regime);
q += gsl_sf_lngamma(m_dirichlet_alpha + number_of_regimes * m_dirichlet_alpha) - gsl_sf_lngamma(number_of_regimes * m_dirichlet_alpha);
}
}
q += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
q += log(m_dirichlet_alpha) - log(number_of_regimes * m_dirichlet_alpha + m_dirichlet_alpha);
q += log(1 - m_rho);
}
else {
if (actual_regime == proposed_regime) {
double transitions_from_proposed_to_following_regime = static_cast< double >(m_regimes[process][proposed_regime].get_right_transitions_histogram_element(following_regime));
double transitions_out_of_proposed_regime = static_cast< double >(m_regimes[process][proposed_regime].get_number_of_right_transitions());
q += log(transitions_from_proposed_to_following_regime - 1 + m_dirichlet_alpha) - log(transitions_out_of_proposed_regime - 1 + (number_of_regimes * m_dirichlet_alpha));
}
else {
double transitions_from_proposed_to_following_regime = static_cast< double >(m_regimes[process][proposed_regime].get_right_transitions_histogram_element(following_regime));
double transitions_out_of_proposed_regime = static_cast< double >(m_regimes[process][proposed_regime].get_number_of_right_transitions());
q += log(transitions_from_proposed_to_following_regime + m_dirichlet_alpha) - log(transitions_out_of_proposed_regime + number_of_regimes * m_dirichlet_alpha);
}
}
}
return q;
}
void particle::remove_full_changepoint_smc(const unsigned int & index, const vector< vector< double > > & right_sufficient_statistics_rev, const vector< double > & actual_log_likelihoods_without_right_sufficient_statistics_rev, const vector< double > & previous_log_likelihoods_with_right_sufficient_statistics_rev, const vector< double > & number_of_observations_rev, const vector< bool > & removing_unobserved_regimes) {
// get the regime indices for the index'th changepoint
vector< unsigned int > removed_regimes(0);
removed_regimes = m_tau[index].get_full_index();
// remove the changepoint from m_tau
m_tau.erase(m_tau.begin() + index);
m_dimension--;
size_t number_of_processes = removed_regimes.size();
if (m_include_separator) {
// if there are separators, decrease the index of any separator greater than index
decrease_separator_indices_greater_than_index(index);
}
for (unsigned int j = 0; j < number_of_processes; j++) {
unsigned int prev_regime_index;
// calculate the regime index of the previous changepoint
if (index == 0) {
prev_regime_index = 0;
}
else {
prev_regime_index = m_tau[index - 1].get_full_index_row(j);
}
// remove the interval and transition out of the removed_regime
// replace the right transition from previous regime to removed_regime with a transition to subsequent_regime (unless new_regime is equal to subsequent_regime), removing a transition out of previous regime if the changepoint is removed from the end of m_tau.
// calculate m_trace_index for the changepoint we are removing
if (is_changepoint_index_separator_index(index) || index == m_dimension) {
if (index == m_dimension) {
m_trace_index = static_cast< unsigned int >(m_number_of_traces - 1);
}
m_regimes[j][prev_regime_index].remove_right_transition(index);
m_regimes[j][removed_regimes[j]].remove_interval(index + 1, m_unobserved_regimes[j], removed_regimes[j], m_number_of_unobserved_regimes[j]);
}
else {
unsigned int subs_regime_index = m_tau[index].get_full_index_row(j);
if (removed_regimes[j] != subs_regime_index) {
m_regimes[j][prev_regime_index].alter_right_transition(index, subs_regime_index);
}
m_regimes[j][removed_regimes[j]].remove_interval(index + 1, m_unobserved_regimes[j], removed_regimes[j], m_number_of_unobserved_regimes[j]);
}
// calculate the trace index
is_changepoint_index_separator_index(index - 1); // only running this to set the trace_index. If not run, m_trace_index may give the trace index of the next trace because is_changepoint_index_separator_index(index) has just been run and index now corresponds to the next changepoint
// remove right sufficient statistics from the regime for the deleted cp and add them to the previous regime (unless both regimes are equal). Calculate the log likelihood for each regime
if (removed_regimes[j] != prev_regime_index) {
m_regimes[j][removed_regimes[j]].remove_sufficient_statistics(right_sufficient_statistics_rev[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_log_likelihoods_without_right_sufficient_statistics_rev[j]);
m_regimes[j][removed_regimes[j]].remove_observations(m_trace_index, number_of_observations_rev[j]);
m_regimes[j][prev_regime_index].add_sufficient_statistics(right_sufficient_statistics_rev[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_with_right_sufficient_statistics_rev[j]);
m_regimes[j][prev_regime_index].add_observations(m_trace_index, number_of_observations_rev[j]);
}
if (removing_unobserved_regimes[j]) {
// if we are removing the top regime, then this regime must be deleted
if (!m_unobserved_regimes[j][removed_regimes[j]]) {
cerr << "regime to delete is not unobserved" << endl;
}
m_regimes[j].erase(m_regimes[j].begin() + removed_regimes[j]);
// for all other regimes, remove any trace of this unobserved regime (i.e. delete the 0 from m_right_transitions_histogram, decrease the indices of transitions greate than regime_to_remove by 1
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].remove_unobserved_regime(removed_regimes[j]);
}
for (unsigned int cp_index = 0; cp_index < m_dimension; cp_index++) {
m_tau[cp_index].decrease_full_index_row_for_removing_unobserved_regime_if_necessary(j, removed_regimes[j]);
}
m_unobserved_regimes[j].erase(m_unobserved_regimes[j].begin() + removed_regimes[j]);
m_number_of_unobserved_regimes[j]--;
}
// decrease the values for right indices in every regime so that index + 2 -> index + 1, index + 3 -> index + 2, ...
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].decrease_right_indices_greater_than(index + 1);
}
}
}
void particle::move_full_changepoint_smc(const unsigned int & index, const changepoint & new_changepoint, const vector< unsigned int > & new_regimes, const bool & tau_h_greater_than_tau_h_prime, const vector< vector< double > > & right_sufficient_statistics, const vector< double > & right_number_of_observations, const vector< vector< double > > & right_sufficient_statistics_reverse, const vector< double > & right_number_of_observations_reverse, const vector< vector< double > > & middle_sufficient_statistics, const vector< double > & middle_number_of_observations, const vector< double > & previous_log_likelihoods_without_right_sufficient_statistics, const vector< double > & previous_log_likelihoods_with_right_sufficient_statistics_reverse, const vector< double > & previous_log_likelihoods_with_middle_sufficient_statistics, const vector< double > & previous_log_likelihoods_without_middle_sufficient_statistics, const vector< vector< double > > & log_likelihoods_with_right_sufficient_statistics, const vector< double > & actual_regime_log_likelihoods_with_middle_sufficient_statistics, const vector< double > & actual_regime_log_likelihoods_without_middle_sufficient_statistics, const vector< double > & actual_regime_log_likelihoods_without_right_sufficient_statistics_reverse, const vector< bool > & removing_unobserved_regimes) {
vector< unsigned int > removed_regimes(0);
removed_regimes = m_tau[index].get_full_index();
m_tau[index] = new_changepoint;
m_tau[index].set_full_index(new_regimes);
size_t number_of_processes = removed_regimes.size();
for (unsigned int j = 0; j < number_of_processes; j++) {
unsigned int prev_regime_index;
// calculate the regime index of the previous changepoint
if (index == 0) {
prev_regime_index = 0;
}
else {
prev_regime_index = m_tau[index - 1].get_full_index_row(j);
}
// if adding a new regime, insert it into the collection of existing regimes, and change the other regimes so that they know the number of regimes has increased.
bool adding_new_regime = new_regimes[j] == m_regimes[j].size();
if (adding_new_regime) {
for (unsigned int i = 0; i < m_regimes[j].size(); i++) {
// increase the size of the transitions histogram for each of the regimes in this process.
m_regimes[j][i].add_regime_to_transitions_histogram(new_regimes[j]);
}
m_regimes[j].push_back(regime(vector< int >(0), vector< unsigned int >(0), vector< unsigned int >(m_regimes[j].size() + 1, 0), vector< double >(right_sufficient_statistics[j].size(), 0), m_number_of_traces, m_trace_index, 0));
// the interval will be added later
m_unobserved_regimes[j].push_back(true);
m_number_of_unobserved_regimes[j]++;
}
// remove right sufficient statistics from the regime for the deleted cp and add them to the previous regime (unless both regimes are equal). Calculate the log likelihood for each regime
if (removed_regimes[j] == prev_regime_index) {
if (prev_regime_index != new_regimes[j]) {
m_regimes[j][prev_regime_index].remove_sufficient_statistics(right_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_without_right_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].remove_observations(m_trace_index, right_number_of_observations[j]);
m_regimes[j][new_regimes[j]].add_sufficient_statistics(right_sufficient_statistics[j]);
m_regimes[j][new_regimes[j]].set_log_likelihood(log_likelihoods_with_right_sufficient_statistics[j][new_regimes[j]]);
m_regimes[j][new_regimes[j]].add_observations(m_trace_index, right_number_of_observations[j]);
}
}
else {
if (new_regimes[j] == prev_regime_index) {
m_regimes[j][prev_regime_index].add_sufficient_statistics(right_sufficient_statistics_reverse[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_with_right_sufficient_statistics_reverse[j]);
m_regimes[j][prev_regime_index].add_observations(m_trace_index, right_number_of_observations_reverse[j]);
m_regimes[j][removed_regimes[j]].remove_sufficient_statistics(right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_regime_log_likelihoods_without_right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].remove_observations(m_trace_index, right_number_of_observations_reverse[j]);
}
else {
if (new_regimes[j] == removed_regimes[j]) {
if (tau_h_greater_than_tau_h_prime) {
m_regimes[j][prev_regime_index].remove_sufficient_statistics(middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_without_middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].remove_observations(m_trace_index, middle_number_of_observations[j]);
m_regimes[j][removed_regimes[j]].add_sufficient_statistics(middle_sufficient_statistics[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_regime_log_likelihoods_with_middle_sufficient_statistics[j]);
m_regimes[j][removed_regimes[j]].add_observations(m_trace_index, middle_number_of_observations[j]);
}
else {
m_regimes[j][prev_regime_index].add_sufficient_statistics(middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_with_middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].add_observations(m_trace_index, middle_number_of_observations[j]);
m_regimes[j][removed_regimes[j]].remove_sufficient_statistics(middle_sufficient_statistics[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_regime_log_likelihoods_without_middle_sufficient_statistics[j]);
m_regimes[j][removed_regimes[j]].remove_observations(m_trace_index, middle_number_of_observations[j]);
}
}
else {
if (tau_h_greater_than_tau_h_prime) {
m_regimes[j][removed_regimes[j]].remove_sufficient_statistics(right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_regime_log_likelihoods_without_right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].remove_observations(m_trace_index, right_number_of_observations_reverse[j]);
m_regimes[j][new_regimes[j]].add_sufficient_statistics(right_sufficient_statistics[j]);
m_regimes[j][new_regimes[j]].set_log_likelihood(log_likelihoods_with_right_sufficient_statistics[j][new_regimes[j]]);
m_regimes[j][new_regimes[j]].add_observations(m_trace_index, right_number_of_observations[j]);
m_regimes[j][prev_regime_index].remove_sufficient_statistics(middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_without_middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].remove_observations(m_trace_index, middle_number_of_observations[j]);
}
else {
m_regimes[j][removed_regimes[j]].remove_sufficient_statistics(right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_regime_log_likelihoods_without_right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].remove_observations(m_trace_index, right_number_of_observations_reverse[j]);
m_regimes[j][new_regimes[j]].add_sufficient_statistics(right_sufficient_statistics[j]);
m_regimes[j][new_regimes[j]].set_log_likelihood(log_likelihoods_with_right_sufficient_statistics[j][new_regimes[j]]);
m_regimes[j][new_regimes[j]].add_observations(m_trace_index, right_number_of_observations[j]);
m_regimes[j][prev_regime_index].add_sufficient_statistics(middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].set_log_likelihood(previous_log_likelihoods_with_middle_sufficient_statistics[j]);
m_regimes[j][prev_regime_index].add_observations(m_trace_index, middle_number_of_observations[j]);
}
}
}
}
// replace the interval for removed_regime with an interval for new_regime (if they differ)
if (index == m_dimension - 1 || is_changepoint_index_separator_index(index + 1)) {
if (new_regimes[j] != removed_regimes[j]) {
m_regimes[j][prev_regime_index].alter_right_transition(index, new_regimes[j]);
m_regimes[j][new_regimes[j]].add_interval(index + 1, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j]);
m_regimes[j][removed_regimes[j]].remove_interval(index + 1, m_unobserved_regimes[j], removed_regimes[j], m_number_of_unobserved_regimes[j]);
}
}
else {
unsigned int subs_regime_index = m_tau[index + 1].get_full_index_row(j);
if (removed_regimes[j] != new_regimes[j]) {
m_regimes[j][removed_regimes[j]].remove_interval(index + 1, m_unobserved_regimes[j], removed_regimes[j], m_number_of_unobserved_regimes[j]);
m_regimes[j][new_regimes[j]].add_interval(index + 1, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j], subs_regime_index);
m_regimes[j][prev_regime_index].alter_right_transition(index, new_regimes[j]);
}
}
// calculate the trace index
is_changepoint_index_separator_index(index); // only running this to set the trace_index. If not run, m_trace_index may give the trace index of the next trace because is_changepoint_index_separator_index(index + 1) has just been run
// if we are removing an unobserved regime and we don't add it back in, then the top regime must be removed
if (removing_unobserved_regimes[j]) {
if (!m_unobserved_regimes[j][removed_regimes[j]]) {
cerr << "regime to delete is not unobserved" << endl;
}
m_regimes[j].erase(m_regimes[j].begin() + removed_regimes[j]);
// for all other regimes, remove any trace of this unobserved regime (i.e. delete the 0 from m_right_transitions_histogram, decrease the indices of transitions greate than regime_to_remove by 1
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].remove_unobserved_regime(removed_regimes[j]);
}
for (unsigned int cp_index = 0; cp_index < m_dimension; cp_index++) {
m_tau[cp_index].decrease_full_index_row_for_removing_unobserved_regime_if_necessary(j, removed_regimes[j]);
}
m_unobserved_regimes[j].erase(m_unobserved_regimes[j].begin() + removed_regimes[j]);
m_number_of_unobserved_regimes[j]--;
}
}
}
void particle::resample_full_changepoint_smc(const unsigned int & index, const vector< unsigned int > & new_regimes, const vector< vector< double > > & right_sufficient_statistics_reverse, const vector< double > & right_number_of_observations_reverse, const vector< vector< double > > & regime_log_likelihoods_with_right_sufficient_statistics_reverse, const vector< double > & actual_log_likelihoods_without_right_sufficient_statistics_reverse, const vector< bool > & removing_unobserved_regimes) {
// calculate the regimes that we are going to lose, and set m_tau[index] to be associated with the new regimes.
vector< unsigned int > removed_regimes(0);
removed_regimes = m_tau[index].get_full_index();
m_tau[index].set_full_index(new_regimes);
size_t number_of_processes = new_regimes.size();
for (unsigned int j = 0; j < number_of_processes; j++) {
// if adding a new regime, insert it into the collection of existing regimes, and change the other regimes so that they know the number of regimes has increased.
bool adding_new_regime = new_regimes[j] == m_regimes[j].size();
if (adding_new_regime) {
for (unsigned int i = 0; i < m_regimes[j].size(); i++) {
// increase the size of the transitions histogram for each of the regimes in this process.
m_regimes[j][i].add_regime_to_transitions_histogram(new_regimes[j]);
}
m_regimes[j].push_back(regime(vector< int >(0), vector< unsigned int >(0), vector< unsigned int >(m_regimes[j].size() + 1, 0), vector< double >(right_sufficient_statistics_reverse[j].size(), 0), m_number_of_traces, m_trace_index, 0));
m_unobserved_regimes[j].push_back(true);
m_number_of_unobserved_regimes[j]++;
}
unsigned int prev_regime_index;
// calculate the regime index of the previous changepoint
if (index == 0) {
prev_regime_index = 0;
}
else {
prev_regime_index = m_tau[index - 1].get_full_index_row(j);
}
// replace the interval for removed_regime with an interval for new_regime (if they differ)
if (index == m_dimension - 1 || is_changepoint_index_separator_index(index + 1)) {
if (index == m_dimension - 1) {
// there is a separator changepoint at the beginning of the last trace, so we must be in the last trace.
m_h_trace_index = static_cast< unsigned int >(m_number_of_traces - 1);
}
else {
// calculate the trace index
is_changepoint_index_separator_index(index); // only running this to set the trace_index. If not run, m_trace_index may give the trace index of the next trace because is_changepoint_index_separator_index(index + 1) has just been run
m_h_trace_index = m_trace_index;
}
if (new_regimes[j] != removed_regimes[j]) {
if (!is_changepoint_index_separator_index(index)) {
m_regimes[j][prev_regime_index].alter_right_transition(index, new_regimes[j]);
}
m_regimes[j][new_regimes[j]].add_interval(index + 1, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j]);
m_regimes[j][removed_regimes[j]].remove_interval(index + 1, m_unobserved_regimes[j], removed_regimes[j], m_number_of_unobserved_regimes[j]);
}
}
else {
m_h_trace_index = m_trace_index;
unsigned int subs_regime_index = m_tau[index + 1].get_full_index_row(j);
if (removed_regimes[j] != new_regimes[j]) {
m_regimes[j][removed_regimes[j]].remove_interval(index + 1, m_unobserved_regimes[j], removed_regimes[j], m_number_of_unobserved_regimes[j]);
m_regimes[j][new_regimes[j]].add_interval(index + 1, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j], subs_regime_index);
if (!is_changepoint_index_separator_index(index)) {
m_regimes[j][prev_regime_index].alter_right_transition(index, new_regimes[j]);
}
}
}
if (removed_regimes[j] != new_regimes[j]) {
m_regimes[j][removed_regimes[j]].remove_sufficient_statistics(right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].set_log_likelihood(actual_log_likelihoods_without_right_sufficient_statistics_reverse[j]);
m_regimes[j][removed_regimes[j]].remove_observations(m_h_trace_index, right_number_of_observations_reverse[j]);
m_regimes[j][new_regimes[j]].add_sufficient_statistics(right_sufficient_statistics_reverse[j]);
m_regimes[j][new_regimes[j]].set_log_likelihood(regime_log_likelihoods_with_right_sufficient_statistics_reverse[j][new_regimes[j]]);
m_regimes[j][new_regimes[j]].add_observations(m_h_trace_index, right_number_of_observations_reverse[j]);
}
// if we are removing an unobserved regime it must be removed
if (removing_unobserved_regimes[j]) {
if (!m_unobserved_regimes[j][removed_regimes[j]]) {
cerr << "regime to delete is not unobserved" << endl;
}
m_regimes[j].erase(m_regimes[j].begin() + removed_regimes[j]);
// for all other regimes, remove any trace of this unobserved regime (i.e. delete the 0 from m_right_transitions_histogram, decrease the indices of transitions greate than regime_to_remove by 1
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].remove_unobserved_regime(removed_regimes[j]);
}
for (unsigned int cp_index = 0; cp_index < m_dimension; cp_index++) {
m_tau[cp_index].decrease_full_index_row_for_removing_unobserved_regime_if_necessary(j, removed_regimes[j]);
}
m_unobserved_regimes[j].erase(m_unobserved_regimes[j].begin() + removed_regimes[j]);
m_number_of_unobserved_regimes[j]--;
}
}
}
double particle::full_log_I_prior_add_ratio_always_new_regime(const unsigned int & process, const bool & new_regime) {
double number_of_regimes = static_cast< double >(get_number_of_regimes(process));
if (new_regime) {
double q = log(1 - m_rho);
q += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
return q;
}
else {
return 0;
}
}
double particle::full_log_I_prior_remove_ratio_always_new_regime(const unsigned int & process, const bool & new_regime, const bool & removing_unobserved_regime) {
double q;
// check if the number of regimes has been reduced before running this, if so then reduce the number of regimes by 1.
double number_of_regimes = static_cast< double >(get_number_of_regimes(process)) - (removing_unobserved_regime ? 1.0 : 0.0);
if (new_regime) {
q = log(1 - m_rho);
q += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
}
else {
q = 0;
}
return q;
}
double particle::calculate_and_get_add_unobserved_regimes_full_I_prior_ratio_always_new_regime(const unsigned int & process) {
double ratio = 0;
double number_of_regimes = static_cast< double >(m_regimes[process].size());
ratio += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
return ratio;
}
double particle::calculate_and_get_remove_unobserved_regimes_full_I_prior_ratio_always_new_regime(const unsigned int & process) {
double ratio = 0;
double number_of_regimes = static_cast< double >(m_regimes[process].size());
ratio += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes - 1));
return ratio;
}
#endif
/*void particle::add_new_interval_changepoints(const vector< changepoint > & new_changepoints, const vector< vector< vector< double > > > & sufficient_statistics, const vector< vector< double > > & log_likelihoods, const vector< vector< double > > & number_of_observations) { // sufficient_statistics has a vector of vectors of doubles for each changepoint
size_t number_of_processes = sufficient_statistics[0].size();
m_trace_index = static_cast< unsigned int >(m_separators.size());
for (unsigned int cp_count = 0; cp_count < new_changepoints.size(); cp_count++) {
unsigned int new_cp_index = m_dimension;
// insert new_changepoint into m_tau
m_tau.insert(m_tau.begin() + new_cp_index, new_changepoints[cp_count]);
m_dimension++;
m_log_k_prior += calculate_and_get_add_cp_k_prior_ratio();
// new_regimes is a vector of the regimes that will be adopted at the spearator changepoint
vector< unsigned int > new_regimes = vector< unsigned int >(number_of_processes);
for (unsigned int j = 0; j < number_of_processes; j++) {
new_regimes[j] = static_cast< unsigned int >(m_regimes[j].size());
}
for (unsigned int j = 0; j < number_of_processes; j++) {
unsigned int prev_regime_index;
// calculate the regime index of the previous changepoint
if (new_cp_index == 0) {
prev_regime_index = 0;
}
else {
prev_regime_index = m_tau[new_cp_index - 1].get_full_index_row(j);
}
// if adding a new regime, insert it into the collection of existing regimes, and change the other regimes so that they know the number of regimes has increased.
bool adding_new_regime = new_regimes[j] == m_regimes[j].size();
if (adding_new_regime) {
for (unsigned int i = 0; i < m_regimes[j].size(); i++) {
// increase the size of the transitions histogram for each of the regimes in this process.
m_regimes[j][i].add_regime_to_transitions_histogram(new_regimes[j]);
}
// insert new regime into m_regimes[j]. We don't include the right changepoint position, right transition, sufficient statistics or number_of_observations here as it will be added later
// these will be converted to the correct values later
m_regimes[j].push_back(regime(vector< int >(0), vector< unsigned int >(0), vector< unsigned int >(m_regimes[j].size() + 1, 0), vector< double >(sufficient_statistics[j].size(), 0), m_number_of_traces, m_trace_index, 0));
// these unobserved regime values will be corrected later
m_unobserved_regimes[j].push_back(true);
m_number_of_unobserved_regimes[j]++;
m_log_regimes_prior += log(1 - m_rho);
}
// increase the values for the right indices in every regime so that index + 1 -> index + 2, ...
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].increase_right_indices_greater_than_or_equal_to(new_cp_index + 1);
}
// insert the interval and transition out of the new_regime
// replace the right transition from previous regime to subsequent regime with a transition to new_regime (unless new_regime is equal to subsequent_regime), adding a transition out of previous regime if the new changepoint is inserted at the end of m_tau.
m_regimes[j][prev_regime_index].alter_right_transition(new_cp_index, new_regimes[j]);
m_regimes[j][new_regimes[j]].add_interval(new_cp_index + 1, m_unobserved_regimes[j], new_regimes[j], m_number_of_unobserved_regimes[j]);
// assign right sufficient statistics and observation numbers to the new regime and take them away from the previous regime (unless both regimes are equal). Calculate the log likelihood for each regime
m_regimes[j][prev_regime_index].remove_sufficient_statistics(sufficient_statistics[cp_count][j]);
m_log_likelihood += log_likelihoods[cp_count][j] - m_regimes[j][prev_regime_index].get_log_likelihood(); // this will be zero except for the first time
m_regimes[j][prev_regime_index].set_log_likelihood(log_likelihoods[cp_count][j]);
m_regimes[j][prev_regime_index].remove_observations(m_trace_index, number_of_observations[cp_count][j]);
m_regimes[j][new_regimes[j]].add_sufficient_statistics(sufficient_statistics[cp_count][j]);
m_regimes[j][new_regimes[j]].set_log_likelihood(log_likelihoods[cp_count + 1][j]);
m_log_likelihood += m_regimes[j][new_regimes[j]].get_log_likelihood();
m_regimes[j][new_regimes[j]].add_observations(m_trace_index, number_of_observations[cp_count][j]);
}
}
m_log_full_I_prior = calculate_and_get_log_full_I_prior(number_of_processes);
}
*/
// finds where a new changepoint would go
/*unsigned int particle::index_finder(const changepoint & new_changepoint, unsigned int lower_bound, unsigned int upper_bound){
if(lower_bound == m_dimension)
return m_dimension;
if(m_dimension == 0 || new_changepoint < m_tau[lower_bound])
return lower_bound;
if(!upper_bound)
upper_bound = m_dimension - 1;
if(new_changepoint > m_tau[upper_bound])
return upper_bound + 1;
unsigned int m = (lower_bound + upper_bound) / 2;
while(upper_bound - lower_bound > 1){
(new_changepoint < m_tau[m]) ? upper_bound = m : lower_bound = m;
m = (lower_bound + upper_bound) / 2;
}
return m + 1;
}*/
/*
changepoint particle::get_binary_left_cp(const size_t & process, const unsigned int & index){
if (index == 0){
return m_intercept_changepoint;
} else {
int left_index = get_binary_left_index(process, index);
if (left_index == -1) {
return m_intercept_changepoint;
}
else {
return m_tau[m_binaries[process][m_tau[index - 1].get_binary_index_row(process)].get_left_index()];
}
}
}
changepoint particle::get_binary_right_cp(const size_t & process, const unsigned int & index){
if (index == 0){
return m_tau[m_binaries[process][1].get_left_index()];
} else {
return m_tau[m_binaries[process][m_tau[index - 1].get_binary_index_row(process) + 1].get_left_index()];
}
}*/
/*void particle::increase_log_full_I_prior_unobserved(const double & log_full_I_prior_ratio, const vector< bool > & unobserved_regime_change, const bool & adding_unobserved_regimes) {
m_log_full_I_prior += log_full_I_prior_ratio;
if (adding_unobserved_regimes) {
for (unsigned int process = 0; process < unobserved_regime_change.size(); process++) {
if (unobserved_regime_change[process]) {
double number_of_regimes = static_cast< double >(m_regimes[process].size());
m_log_full_I_prior -= static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
m_log_full_separators_prior += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes + 1));
}
}
}
else {
for (unsigned int process = 0; process < unobserved_regime_change.size(); process++) {
if (unobserved_regime_change[process]) {
double number_of_regimes = static_cast< double >(m_regimes[process].size());
m_log_full_I_prior -= static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes - 1));
m_log_full_separators_prior += static_cast< double >(m_separator_indices.size()) * log(number_of_regimes / (number_of_regimes - 1));
}
}
}
}*/
/*void particle::add_unobserved_regimes(const vector< bool > & adding_unobserved_regimes, const size_t & number_of_processes) {
for (unsigned int j = 0; j < number_of_processes; j++) {
if (adding_unobserved_regimes[j]) {
// choose the new unobserved regime (the only restriction is that it can't be regime 0)
unsigned int new_unobserved_regime = static_cast< unsigned int >(gsl_rng_uniform_int(r, m_regimes[j].size()) + 1);
size_t size_of_sufficient_statistics = m_regimes[j][0].get_size_of_sufficient_statistics();
// insert the new unobserved regime into m_regimes[j]
m_regimes[j].insert(m_regimes[j].begin() + new_unobserved_regime, regime(vector< int >(0), vector< unsigned int >(0), vector< unsigned int >(m_regimes[j].size(), 0), vector< double >(size_of_sufficient_statistics, 0), m_number_of_traces, 0, 0));
// set the likelihood to be 0 for this new regime
m_regimes[j][new_unobserved_regime].set_log_likelihood(0);
// for all other regimes, include an empty transition in m_right_transitions_histogram and, for each element in m_right_transitions, if the element is greater than or equal to the new_unobserved_regime then add 1 to it
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].insert_new_unobserved_regime(new_unobserved_regime);
}
for (unsigned int cp_index = 0; cp_index < m_dimension; cp_index++) {
m_tau[cp_index].increase_full_index_row_for_inserting_unobserved_regime_if_necessary(j, new_unobserved_regime);
}
m_unobserved_regimes[j].insert(m_unobserved_regimes[j].begin() + new_unobserved_regime, true);
m_number_of_unobserved_regimes[j]++;
}
}
}
void particle::remove_unobserved_regimes(const vector< bool > & removing_unobserved_regimes, const size_t & number_of_processes) {
for (unsigned int j = 0; j < number_of_processes; j++) {
if (removing_unobserved_regimes[j]) {
// choose which unobserved regime to remove using sub-linear method - keep guessing at unobserved regimes
unsigned int regime_to_remove = static_cast< unsigned int >(gsl_rng_uniform_int(r, m_regimes[j].size() - 1) + 1);
bool unobserved = m_unobserved_regimes[j][regime_to_remove];
while (!unobserved) {
regime_to_remove = static_cast< unsigned int >(gsl_rng_uniform_int(r, m_regimes[j].size() - 1) + 1);
unobserved = m_unobserved_regimes[j][regime_to_remove];
}
m_regimes[j].erase(m_regimes[j].begin() + regime_to_remove);
// for all other regimes, remove any trace of this unobserved regime (i.e. delete the 0 from m_right_transitions_histogram, decrease the indices of transitions greate than regime_to_remove by 1
for (unsigned int regime = 0; regime < m_regimes[j].size(); regime++) {
m_regimes[j][regime].remove_unobserved_regime(regime_to_remove);
}
for (unsigned int cp_index = 0; cp_index < m_dimension; cp_index++) {
m_tau[cp_index].decrease_full_index_row_for_removing_unobserved_regime_if_necessary(j, regime_to_remove);
}
m_unobserved_regimes[j].erase(m_unobserved_regimes[j].begin() + regime_to_remove);
m_number_of_unobserved_regimes[j]--;
}
}
}*/
| {
"alphanum_fraction": 0.7151266031,
"avg_line_length": 66.7251782776,
"ext": "h",
"hexsha": "ca58dbc033010a9d16f74023aaec537c4f9b1db9",
"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": "759724c67f12db9155f83dd7dd8f63d526ecbd79",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "AlexanderDBolton/Regimes_RJMCMC",
"max_forks_repo_path": "Code/basic_particle.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "759724c67f12db9155f83dd7dd8f63d526ecbd79",
"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": "AlexanderDBolton/Regimes_RJMCMC",
"max_issues_repo_path": "Code/basic_particle.h",
"max_line_length": 1343,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "759724c67f12db9155f83dd7dd8f63d526ecbd79",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "AlexanderDBolton/Regimes_RJMCMC",
"max_stars_repo_path": "Code/basic_particle.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 57740,
"size": 243280
} |
//STARTWHOLE
static char help[] = "Newton's method for a two-variable system.\n"
"No analytical Jacobian. Run with -snes_fd or -snes_mf.\n\n";
#include <petsc.h>
extern PetscErrorCode FormFunction(SNES, Vec, Vec, void*);
int main(int argc,char **argv) {
PetscErrorCode ierr;
SNES snes; // nonlinear solver context
Vec x, r; // solution, residual vectors
PetscInitialize(&argc,&argv,NULL,help);
ierr = VecCreate(PETSC_COMM_WORLD,&x); CHKERRQ(ierr);
ierr = VecSetSizes(x,PETSC_DECIDE,2); CHKERRQ(ierr);
ierr = VecSetFromOptions(x); CHKERRQ(ierr);
ierr = VecSet(x,1.0); CHKERRQ(ierr);
ierr = VecDuplicate(x,&r); CHKERRQ(ierr);
ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);
ierr = SNESSetFunction(snes,r,FormFunction,NULL); CHKERRQ(ierr);
ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);
ierr = SNESSolve(snes,NULL,x); CHKERRQ(ierr);
ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
VecDestroy(&x); VecDestroy(&r); SNESDestroy(&snes);
return PetscFinalize();
}
PetscErrorCode FormFunction(SNES snes, Vec x, Vec F, void *ctx) {
PetscErrorCode ierr;
const double b = 2.0, *ax;
double *aF;
ierr = VecGetArrayRead(x,&ax);CHKERRQ(ierr);
ierr = VecGetArray(F,&aF);CHKERRQ(ierr);
aF[0] = (1.0 / b) * PetscExpReal(b * ax[0]) - ax[1];
aF[1] = ax[0] * ax[0] + ax[1] * ax[1] - 1.0;
ierr = VecRestoreArrayRead(x,&ax);CHKERRQ(ierr);
ierr = VecRestoreArray(F,&aF);CHKERRQ(ierr);
return 0;
}
//ENDWHOLE
| {
"alphanum_fraction": 0.6497102382,
"avg_line_length": 33.7608695652,
"ext": "c",
"hexsha": "fcd6b338bcc9ff6fada8885c201f20d27f6a1ed0",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mapengfei-nwpu/p4pdes",
"max_forks_repo_path": "c/ch4/expcircle.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "mapengfei-nwpu/p4pdes",
"max_issues_repo_path": "c/ch4/expcircle.c",
"max_line_length": 68,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mapengfei-nwpu/p4pdes",
"max_stars_repo_path": "c/ch4/expcircle.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 483,
"size": 1553
} |
#pragma once
#include "macros.h"
#include <gsl/span>
#include <array>
#include <optional>
#include <string>
namespace linkollector::win {
enum class activity { url, text };
constexpr std::string_view activity_delimiter = "\uedfd";
constexpr std::array<std::byte, activity_delimiter.size()>
activity_delimiter_bin = []() {
std::array<std::byte, activity_delimiter.size()> delim = {};
for (std::size_t i = 0; i < activity_delimiter.size(); ++i) {
delim.at(i) = static_cast<std::byte>(activity_delimiter[i]);
}
return delim;
}();
[[nodiscard]] std::string activity_to_string(activity activity_) noexcept;
[[nodiscard]] std::wstring activity_to_wstring(activity activity_) noexcept;
[[nodiscard]] std::optional<activity>
activity_from_string(std::string_view activity_) noexcept;
std::optional<std::pair<activity, std::string>>
deserialize(gsl::span<std::byte> msg) noexcept;
} // namespace linkollector::win
| {
"alphanum_fraction": 0.6955624355,
"avg_line_length": 26.1891891892,
"ext": "h",
"hexsha": "53a1886c6904543f86f7c97e01a7451d81f2d18c",
"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": "a76b08fa4f20a3612988a0d84e5b14f7822638ee",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Longhanks/linkollector-win",
"max_forks_repo_path": "src/activity.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee",
"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": "Longhanks/linkollector-win",
"max_issues_repo_path": "src/activity.h",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a76b08fa4f20a3612988a0d84e5b14f7822638ee",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Longhanks/linkollector-win",
"max_stars_repo_path": "src/activity.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 225,
"size": 969
} |
/*
Performing approximate Bayesian computation sequential Monte Carlo (Toni et al.
2009) for linear regression.
Synthetic data is generated by `ground_truth_and_analysis.ipynb`.
This script writes particles.csv, where each row corresponds to a particle and
each column corresponds to a round of SMC.
Defining #DEBUG_MODE will silence all writing to stdout. One may then add
printf statements in the code, and perhaps write the output to file as:
`./run.sh > output.txt`
Parameter ordering convention:
0 - gradient
1 - intercept
2 - standard deviation
Author: Juvid Aryaman
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sort_double.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_fit.h>
#define N_DATA 30
#define N_PARAMETERS 3
#define N_PARTICLES 2000
#define N_ROUNDS_SMC 25
#define QUANTILE_ACCEPT_DISTANCE 0.8
#define RND gsl_rng_uniform(r)
#define SEED 1
#define DISTANCE_THRESHOLD_INIT_GRADIENT 2
#define DISTANCE_THRESHOLD_INIT_INTERCEPT 50
#define DISTANCE_THRESHOLD_INIT_SIGMA 2
#define X_DATA_FILENAME "x.csv"
#define Y_DATA_FILENAME "y.csv"
//#define DEBUG_MODE
#include "smc.h"
#include "lin_reg.h"
int main(int argc, char *argv[]) {
/* set up GSL RNG */
gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);
/* end of GSL setup */
gsl_rng_set(r, SEED);
/////////////////////////
/*Read data*/
/////////////////////////
FILE *data_pointer_x, *data_pointer_y;
data_pointer_x = fopen(X_DATA_FILENAME, "r");
data_pointer_y = fopen(Y_DATA_FILENAME, "r");
double data_x[N_DATA];
double data_y[N_DATA];
int i, j, read_error_status_x, read_error_status_y;
for (i=0; i < N_DATA; i++){
read_error_status_x = fscanf(data_pointer_x, "%lf\n", &data_x[i]);
read_error_status_y = fscanf(data_pointer_y, "%lf\n", &data_y[i]);
}
if (read_error_status_x != 1){printf("Error reading X data\n"); return 0;}
if (read_error_status_y != 1){printf("Error reading Y data\n"); return 0;}
/////////////////////////
/*Initialise variables*/
/////////////////////////
/*Fit a linear model to the data, which will be used as summary statistics of
the data*/
double gradient_fit_data, intercept_fit_data, sigma_fit_data, cov00, cov01, cov11, sumsq;
int gsl_fit_return_value;
gsl_fit_return_value = gsl_fit_linear(data_x, 1, data_y, 1, N_DATA,
&intercept_fit_data, &gradient_fit_data,
&cov00, &cov01, &cov11, &sumsq);
if (gsl_fit_return_value != 0) {printf("Fit failed.\n"); return -1;}
sigma_fit_data = sqrt(sumsq/(N_DATA-2));
#ifndef DEBUG_MODE
printf("gradient ML = %.8f\n", gradient_fit_data);
printf("intercept ML = %.8f\n", intercept_fit_data);
printf("sigma ML = %.8f\n", sigma_fit_data);
#endif
/*Make a (N_PARAMETERS X N_ROUNDS_SMC X N_PARTICLES) array to store all
particles at all rounds of SMC*/
double*** theta_particle;
theta_particle = (double***) malloc(N_PARAMETERS * sizeof(double**));
for (i = 0; i < N_PARAMETERS; i++){
theta_particle[i] = (double**) malloc(N_ROUNDS_SMC * sizeof(double*));
}
for (i = 0; i < N_PARAMETERS; i++){
for (j = 0; j < N_ROUNDS_SMC; j++){
theta_particle[i][j] = (double*) malloc(N_PARTICLES * sizeof(double));
}
}
double** distance;
distance = (double**) malloc(N_PARAMETERS * sizeof(double*));
for (i = 0; i < N_PARAMETERS; i++) {
distance[i] = (double*) malloc(N_PARTICLES * sizeof(double));
}
double **distance_threshold_all = malloc(N_PARAMETERS * sizeof(double*));
for (i = 0; i < N_PARAMETERS; i++) {
distance_threshold_all[i] = (double*) malloc(N_ROUNDS_SMC * sizeof(double));
}
double distance_threshold[] = {DISTANCE_THRESHOLD_INIT_GRADIENT,
DISTANCE_THRESHOLD_INIT_INTERCEPT,
DISTANCE_THRESHOLD_INIT_SIGMA};
double *simulated_data = (double*) malloc(N_DATA * sizeof(double));
double *weight = malloc(N_PARTICLES * sizeof(double));
double weight_normalizer = 0.0;
int time_smc=0; // an index of each round of SMC
int param_index_chosen, prior_violated;
int particle_index;
/////////////////////////
/*Perform ABC SMC*/
/////////////////////////
/*For every round of SMC*/
for (time_smc = 0; time_smc < N_ROUNDS_SMC; time_smc++) {
#ifndef DEBUG_MODE
printf("Round %d of SMC\n", time_smc);
#endif
for (i = 0; i < N_PARAMETERS; i++) {
distance_threshold_all[i][time_smc] = distance_threshold[i];
}
/*Draw or perturb a particle and compute distance*/
for (particle_index = 0; particle_index < N_PARTICLES; particle_index++) {
// printf("%d\n", particle_index);
for (i = 0; i < N_PARAMETERS; i++) {
// reset distance of particle along each dimension
distance[i][particle_index] = distance_threshold[i] + 1.0;
}
while ((distance[0][particle_index] > distance_threshold[0])||
(distance[1][particle_index] > distance_threshold[1])||
(distance[2][particle_index] > distance_threshold[2])) {
if (time_smc == 0) {
// Sample from the prior
sample_prior(r, theta_particle, particle_index);
}
else{
/*Sample from the old weights*/
param_index_chosen = weighted_choice(r, weight);
if ((param_index_chosen < 0)||(param_index_chosen >= N_PARTICLES)) {
printf("Error in param_index_chosen\n");
printf("time_smc = %d\n", time_smc);
return -1;
}
perturb_particle(r, theta_particle, time_smc, param_index_chosen,
particle_index);
// Check if prior support is 0
prior_violated = check_prior_violated(theta_particle, time_smc,
particle_index);
if(prior_violated == 1) continue;
}
simulate_dataset(r, theta_particle, data_x, simulated_data, time_smc,
particle_index);
// Compute distance between data and simulation
distance_metric_sum_stats(simulated_data,
data_x,
gradient_fit_data,
intercept_fit_data,
sigma_fit_data,
distance, particle_index);
//distance[particle_index] = distance_metric_sum_res(simulated_data, data_y);
// distance[particle_index] = distance_metric_sum_abs_res(simulated_data, data_y);
}
}
#ifndef DEBUG_MODE
printf("Particles sampled.\n");
#endif
/*Compute weights*/
if (time_smc==0){ for (i = 0; i < N_PARTICLES; i++) weight[i] = 1.0;}
else{
weight_normalizer = 0.0;
for (particle_index = 0; particle_index < N_PARTICLES; particle_index++) {
weight_normalizer += weight[particle_index]*kernel_pdf();
}
// print_double_array(weight, N_PARTICLES);
// printf("\n" );
// printf("weight_normalizer=%f\n", weight_normalizer);
// printf("kernel_pdf()=%f\n", kernel_pdf());
for (particle_index = 0; particle_index < N_PARTICLES; particle_index++) {
weight[particle_index] = prior_pdf(theta_particle, time_smc,
particle_index)/weight_normalizer;
}
}
/*Normalise weights*/
weight_normalizer = 0.0;
for (i = 0; i < N_PARTICLES; i++) weight_normalizer += weight[i];
for (i = 0; i < N_PARTICLES; i++) weight[i] = weight[i]/weight_normalizer;
/* Resample weights*/
distance_threshold[0] = update_distance_threshold(distance[0]);
distance_threshold[1] = update_distance_threshold(distance[1]);
distance_threshold[2] = update_distance_threshold(distance[2]);
}
#ifndef DEBUG_MODE
printf("Writing particles to file\n");
#endif
write_particles_to_csv(theta_particle);
char *dist_filename = "distances.txt";
write_2d_double_array_to_csv(distance_threshold_all, N_PARAMETERS, N_ROUNDS_SMC, dist_filename);
#ifndef DEBUG_MODE
printf("Done!\n");
#endif
return 0; //return from main
} //close main
| {
"alphanum_fraction": 0.6697871249,
"avg_line_length": 31.0677290837,
"ext": "c",
"hexsha": "faab26c0d683e2330e7f3bc0fb82a53980228af4",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-07-02T14:25:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-07-02T14:25:20.000Z",
"max_forks_repo_head_hexsha": "df270b58d35d1248079e4651988ded4074237bfc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jaryaman/ML_demos",
"max_forks_repo_path": "Notebooks/ABC_SMC/Linear_regression/distance_metric_3d/smc.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "df270b58d35d1248079e4651988ded4074237bfc",
"max_issues_repo_issues_event_max_datetime": "2020-09-28T14:21:39.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-21T18:23:19.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jaryaman/ML_demos",
"max_issues_repo_path": "Notebooks/ABC_SMC/Linear_regression/distance_metric_3d/smc.c",
"max_line_length": 98,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "df270b58d35d1248079e4651988ded4074237bfc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jaryaman/ML_demos",
"max_stars_repo_path": "Notebooks/ABC_SMC/Linear_regression/distance_metric_3d/smc.c",
"max_stars_repo_stars_event_max_datetime": "2018-07-31T16:51:10.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-28T18:14:12.000Z",
"num_tokens": 2016,
"size": 7798
} |
#ifndef KGS_NULLSPACEQR_H
#define KGS_NULLSPACEQR_H
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <string>
#include "math/QR.h"
#include "math/Nullspace.h"
#include "TransposeQR.h"
/**
* An implementation of Nullspace backed by a QR decomposition
*/
class NullspaceQR: public Nullspace {
public:
/** Will construct a nullspace using a QR (transpose) decomposition */
NullspaceQR(TransposeQR* qr);
~NullspaceQR();
/** Update the Nullspace (and underlying SVD) to reflect an updated state of the matrix */
void updateFromMatrix() override;
private:
TransposeQR* m_qr; ///< SVD underlying this nullspace
friend class Configuration;
};
#endif //KGS_nullptrSPACE_H
| {
"alphanum_fraction": 0.7219917012,
"avg_line_length": 21.2647058824,
"ext": "h",
"hexsha": "9e144ca69c2d76919d6c5c7d0d4755488b09925a",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_forks_repo_path": "src/math/NullspaceQR.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_issues_repo_path": "src/math/NullspaceQR.h",
"max_line_length": 92,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_stars_repo_path": "src/math/NullspaceQR.h",
"max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z",
"num_tokens": 180,
"size": 723
} |
/* integration/fixed.c
*
* Copyright (C) 2017 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* the code in this module performs fixed-point quadrature calculations for
* integrands and is based on IQPACK */
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
static int fixed_compute(const double a, const double b, const double alpha, const double beta,
gsl_integration_fixed_workspace * w);
static int imtqlx ( const int n, double d[], double e[], double z[] );
gsl_integration_fixed_workspace *
gsl_integration_fixed_alloc(const gsl_integration_fixed_type * type, const size_t n,
const double a, const double b, const double alpha, const double beta)
{
int status;
gsl_integration_fixed_workspace *w;
/* check inputs */
if (n < 1)
{
GSL_ERROR_VAL ("workspace size n must be at least 1", GSL_EDOM, 0);
}
w = calloc(1, sizeof(gsl_integration_fixed_workspace));
if (w == NULL)
{
GSL_ERROR_VAL ("unable to allocate workspace", GSL_ENOMEM, 0);
}
w->weights = malloc(n * sizeof(double));
if (w->weights == NULL)
{
gsl_integration_fixed_free(w);
GSL_ERROR_VAL ("unable to allocate weights", GSL_ENOMEM, 0);
}
w->x = malloc(n * sizeof(double));
if (w->x == NULL)
{
gsl_integration_fixed_free(w);
GSL_ERROR_VAL ("unable to allocate x", GSL_ENOMEM, 0);
}
w->diag = malloc(n * sizeof(double));
if (w->diag == NULL)
{
gsl_integration_fixed_free(w);
GSL_ERROR_VAL ("unable to allocate diag", GSL_ENOMEM, 0);
}
w->subdiag = malloc(n * sizeof(double));
if (w->subdiag == NULL)
{
gsl_integration_fixed_free(w);
GSL_ERROR_VAL ("unable to allocate subdiag", GSL_ENOMEM, 0);
}
w->n = n;
w->type = type;
/* compute quadrature weights and nodes */
status = fixed_compute(a, b, alpha, beta, w);
if (status)
{
gsl_integration_fixed_free(w);
GSL_ERROR_VAL ("error in integration parameters", GSL_EDOM, 0);
}
return w;
}
void
gsl_integration_fixed_free(gsl_integration_fixed_workspace * w)
{
if (w->weights)
free(w->weights);
if (w->x)
free(w->x);
if (w->diag)
free(w->diag);
if (w->subdiag)
free(w->subdiag);
free(w);
}
size_t
gsl_integration_fixed_n(const gsl_integration_fixed_workspace * w)
{
return w->n;
}
double *
gsl_integration_fixed_nodes(const gsl_integration_fixed_workspace * w)
{
return w->x;
}
double *
gsl_integration_fixed_weights(const gsl_integration_fixed_workspace * w)
{
return w->weights;
}
int
gsl_integration_fixed(const gsl_function * func, double * result,
const gsl_integration_fixed_workspace * w)
{
const size_t n = w->n;
size_t i;
double sum = 0.0;
for (i = 0; i < n; ++i)
{
double fi = GSL_FN_EVAL(func, w->x[i]);
sum += w->weights[i] * fi;
}
*result = sum;
return GSL_SUCCESS;
}
/*
fixed_compute()
Compute quadrature weights and nodes
*/
static int
fixed_compute(const double a, const double b, const double alpha, const double beta,
gsl_integration_fixed_workspace * w)
{
int s;
const size_t n = w->n;
gsl_integration_fixed_params params;
size_t i;
params.a = a;
params.b = b;
params.alpha = alpha;
params.beta = beta;
/* check input parameters */
s = (w->type->check)(n, ¶ms);
if (s)
return s;
/* initialize Jacobi matrix */
s = (w->type->init)(n, w->diag, w->subdiag, ¶ms);
if (s)
return s;
if (params.zemu <= 0.0)
{
GSL_ERROR("zeroth moment must be positive", GSL_EINVAL);
}
for ( i = 0; i < n; i++ )
{
w->x[i] = w->diag[i];
}
w->weights[0] = sqrt (params.zemu);
for ( i = 1; i < n; i++ )
{
w->weights[i] = 0.0;
}
/* diagonalize the Jacobi matrix */
s = imtqlx (n, w->x, w->subdiag, w->weights);
if (s)
return s;
for (i = 0; i < n; i++)
{
w->weights[i] = w->weights[i] * w->weights[i];
}
/*
* The current weights and nodes are valid for a = 0, b = 1.
* Now scale them for arbitrary a,b
*/
{
double p = pow ( params.slp, params.al + params.be + 1.0 );
size_t k;
for ( k = 0; k < n; k++ )
{
w->x[k] = params.shft + params.slp * w->x[k];
w->weights[k] = w->weights[k] * p;
}
}
return GSL_SUCCESS;
}
/******************************************************************************/
/*
Purpose:
IMTQLX diagonalizes a symmetric tridiagonal matrix.
Discussion:
This routine is a slightly modified version of the EISPACK routine to
perform the implicit QL algorithm on a symmetric tridiagonal matrix.
The authors thank the authors of EISPACK for permission to use this
routine.
It has been modified to produce the product Q' * Z, where Z is an input
vector and Q is the orthogonal matrix diagonalizing the input matrix.
The changes consist (essentially) of applying the orthogonal transformations
directly to Z as they are generated.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
11 January 2010
Author:
Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.
C version by John Burkardt.
Reference:
Sylvan Elhay, Jaroslav Kautsky,
Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of
Interpolatory Quadrature,
ACM Transactions on Mathematical Software,
Volume 13, Number 4, December 1987, pages 399-415.
Roger Martin, James Wilkinson,
The Implicit QL Algorithm,
Numerische Mathematik,
Volume 12, Number 5, December 1968, pages 377-383.
Parameters:
Input, int N, the order of the matrix.
Input/output, double D(N), the diagonal entries of the matrix.
On output, the information in D has been overwritten.
Input/output, double E(N), the subdiagonal entries of the
matrix, in entries E(1) through E(N-1). On output, the information in
E has been overwritten.
Input/output, double Z(N). On input, a vector. On output,
the value of Q' * Z, where Q is the matrix that diagonalizes the
input symmetric tridiagonal matrix.
*/
static int
imtqlx ( const int n, double d[], double e[], double z[] )
{
double b;
double c;
double f;
double g;
int i;
int ii;
int itn = 30;
int j;
int k;
int l;
int m;
int mml;
double p;
double r;
double s;
if ( n == 1 )
{
return GSL_SUCCESS;
}
e[n-1] = 0.0;
for ( l = 1; l <= n; l++ )
{
j = 0;
for ( ; ; )
{
for ( m = l; m <= n; m++ )
{
if ( m == n )
{
break;
}
if ( fabs ( e[m-1] ) <= GSL_DBL_EPSILON * ( fabs ( d[m-1] ) + fabs ( d[m] ) ) )
{
break;
}
}
p = d[l-1];
if ( m == l )
{
break;
}
if ( itn <= j )
{
return GSL_EMAXITER;
}
j = j + 1;
g = ( d[l] - p ) / ( 2.0 * e[l-1] );
r = sqrt ( g * g + 1.0 );
g = d[m-1] - p + e[l-1] / ( g + fabs ( r ) * GSL_SIGN ( g ) );
s = 1.0;
c = 1.0;
p = 0.0;
mml = m - l;
for ( ii = 1; ii <= mml; ii++ )
{
i = m - ii;
f = s * e[i-1];
b = c * e[i-1];
if ( fabs ( g ) <= fabs ( f ) )
{
c = g / f;
r = sqrt ( c * c + 1.0 );
e[i] = f * r;
s = 1.0 / r;
c = c * s;
}
else
{
s = f / g;
r = sqrt ( s * s + 1.0 );
e[i] = g * r;
c = 1.0 / r;
s = s * c;
}
g = d[i] - p;
r = ( d[i-1] - g ) * s + 2.0 * c * b;
p = s * r;
d[i] = g + p;
g = c * r - b;
f = z[i];
z[i] = s * z[i-1] + c * f;
z[i-1] = c * z[i-1] - s * f;
}
d[l-1] = d[l-1] - p;
e[l-1] = g;
e[m-1] = 0.0;
}
}
/*
Sorting.
*/
for ( ii = 2; ii <= m; ii++ )
{
i = ii - 1;
k = i;
p = d[i-1];
for ( j = ii; j <= n; j++ )
{
if ( d[j-1] < p )
{
k = j;
p = d[j-1];
}
}
if ( k != i )
{
d[k-1] = d[i-1];
d[i-1] = p;
p = z[i-1];
z[i-1] = z[k-1];
z[k-1] = p;
}
}
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.557018029,
"avg_line_length": 22.0512195122,
"ext": "c",
"hexsha": "746e5fb3491b92b44a77a74100f8e3586edc329e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/fixed.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/fixed.c",
"max_line_length": 98,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017",
"max_stars_repo_path": "gsl-2.4/integration/fixed.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z",
"num_tokens": 2691,
"size": 9041
} |
/**
*
* @file core_ssbtype1cb.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 Azzam Haidar
* @date 2011-05-15
* @generated s Tue Jan 7 11:44:49 2014
*
**/
#include <lapacke.h>
#include "common.h"
#define A(m,n) (A + LDA * (n) + ((m)-(n)))
#define V(m) (V + (m))
#define TAU(m) (TAU + (m))
/***************************************************************************//**
*
* @ingroup CORE_float
*
* CORE_ssbtype1cb is a kernel that will operate on a region (triangle) of data
* bounded by st and ed. This kernel eliminate a column by an column-wise
* annihiliation, then it apply a left+right update on the hermitian triangle.
* Note that the column to be eliminated is located at st-1.
*
* All detail are available on technical report or SC11 paper.
* Azzam Haidar, Hatem Ltaief, and Jack Dongarra. 2011.
* Parallel reduction to condensed forms for symmetric eigenvalue problems
* using aggregated fine-grained and memory-aware kernels. In Proceedings
* of 2011 International Conference for High Performance Computing,
* Networking, Storage and Analysis (SC '11). ACM, New York, NY, USA, ,
* Article 8 , 11 pages.
* http://doi.acm.org/10.1145/2063384.2063394
*
*******************************************************************************
*
* @param[in] N
* The order of the matrix A.
*
* @param[in] NB
* The size of the band.
*
* @param[in, out] A
* A pointer to the matrix A of size (2*NB+1)-by-N.
*
* @param[in] LDA
* The leading dimension of the matrix A. LDA >= max(1,2*NB+1)
*
* @param[out] V
* float array, dimension N if eigenvalue only
* requested or (LDV*blkcnt*Vblksiz) if Eigenvectors requested
* The Householder reflectors are stored in this array.
*
* @param[out] TAU
* float array, dimension (N).
* The scalar factors of the Householder reflectors are stored
* in this array.
*
* @param[in] st
* A pointer to the start index where this kernel will operate.
*
* @param[in] ed
* A pointer to the end index where this kernel will operate.
*
* @param[in] sweep
* The sweep number that is eliminated. it serve to calculate the
* pointer to the position where to store the Vs and Ts.
*
* @param[in] Vblksiz
* constant which correspond to the blocking used when applying the Vs.
* it serve to calculate the pointer to the position where to store the
* Vs and Ts.
*
* @param[in] WANTZ
* constant which indicate if Eigenvalue are requested or both
* Eigenvalue/Eigenvectors.
*
* @param[in] WORK
* Workspace of size nb.
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
*
******************************************************************************/
/***************************************************************************
* TYPE 1-BAND Lower-columnwise-Householder
***************************************************************************/
void
CORE_ssbtype1cb(int N, int NB,
float *A, int LDA,
float *V, float *TAU,
int st, int ed, int sweep, int Vblksiz, int WANTZ,
float *WORK)
{
int len, LDX;
int blkid, vpos, taupos, tpos;
/* find the pointer to the Vs and Ts as stored by the bulgechasing
* note that in case no eigenvector required V and T are stored
* on a vector of size N
* */
if( WANTZ == 0 ) {
vpos = ((sweep+1)%2)*N + st;
taupos = ((sweep+1)%2)*N + st;
} else {
findVTpos(N, NB, Vblksiz, sweep, st,
&vpos, &taupos, &tpos, &blkid);
}
LDX = LDA-1;
len = ed-st+1;
*V(vpos) = 1.;
memcpy( V(vpos+1), A(st+1, st-1), (len-1)*sizeof(float) );
memset( A(st+1, st-1), 0, (len-1)*sizeof(float) );
/* Eliminate the col at st-1 */
LAPACKE_slarfg_work(len, A(st, st-1), V(vpos+1), 1, TAU(taupos) );
/* Apply left and right on A(st:ed,st:ed) */
CORE_slarfy(len, A(st,st), LDX, V(vpos), TAU(taupos), WORK);
return;
}
/***************************************************************************/
#undef A
#undef V
#undef TAU
| {
"alphanum_fraction": 0.532627866,
"avg_line_length": 32.6330935252,
"ext": "c",
"hexsha": "10808e5b003c69347f8c6a11653b95f79506f7c5",
"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_ssbtype1cb.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_ssbtype1cb.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_ssbtype1cb.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1202,
"size": 4536
} |
#ifndef GRAPH_H_
#define GRAPH_H_
#include "common.h"
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/** A graph represented by an adjacency list (made of dynamic arrays). */
typedef struct
{
int num_v; /** Number of vertices. */
int *num_e; /** Number of edges per vertex. */
int *capacity; /** Space allocated to each vertex. */
int **adj_list; /** Adjacency list. */
double **w_list; /** Weights. */
}
graph;
/** Initialize a graph with a fixed number of vertices. */
void graph_init(graph *g, int vertices);
/** Number of edges in the entire graph. */
int graph_edges(const graph *g);
/** Number of proper edges in the entire graph. */
int graph_proper_edges(const graph *g);
/** Number of loops in the entire graph. */
int graph_loops(const graph *g);
/** Number of outgoing edges for vertex \f$v\f$. \f$O(1)\f$.*/
int graph_outdegree(const graph *g, int u);
/** Number of ingoing edges for vertex \f$v\f$. \f$O(|V||E|)\f$.*/
int graph_indegree(const graph *g, int u);
/** Return true if the graph is balanced (i.e.: for each vertex \f$v\f$, indegree(v) == outdegree(v)). \f$O(|V||E|)\f$. */
int graph_is_balanced(const graph *g);
/** Add an edge between vertices 'u' and 'v' with weight. O(1), worst-case O(|N|). */
void graph_add_edge(graph *g, int u, int v, double weight);
/** Add an edge between vertices 'u' and 'v' and vice-versa. */
void graph_add_sym_edges(graph *g, int u, int v, double weight);
/** Remove the edge between vertices 'u' and 'v'. */
int graph_rmv_edge(graph *g, int u, int v);
/** Remove the edges between 'u' and 'v' and vice-versa. Return false if only 1 or 0 edges were removed. */
int graph_rmv_sym_edges(graph *g, int u, int v);
/** Return true if the graph has an edge between 'u' and 'v'. O(|E|). */
int graph_has_edge(graph *g, int u, int v);
/** Return true if the graph is strongly connected. */
int graph_strongly_connected(const graph *g);
/** Print as a svg file (assumes all points are in the [0, 1) range).*/
void graph_svg(const graph *g, double *x, double *y, double size, double offset, FILE *out);
/**
* Print as a svg file with stronger colors for higher abundances. abun must point to an array
* with one double in the [0, 1) range for each vertex. color = 0 (red), 1 (green), 2 (blue).
*/
void graph_svg_abun(const graph *g, double *x, double *y, double size, double offset, double *abun, int color, FILE *out);
/** Print the graph in GraphML format. */
void graph_graphml(const graph *g, FILE *out, unsigned int id);
/** Print the adjacency list. */
void graph_print(const graph *g, FILE *out);
/** Free the memory of the struct. */
void graph_free(graph *g);
/**
* Get a random geometric graph in [0,1]^2 with radius 'r'.
*
* 'x' and 'y' must be initialized and the correct amount of space must
* be allocated. The weight of the realized edges is 'r - d', where 'd'
* is the geometric distance between the two vertices (in short the
* weight is always between 0 and 1.0).
*/
void graph_get_rgg(graph *g, int vertices, double r, double *x, double *y, gsl_rng *rng);
/**
* Get a connected random geometric graph in [0,1]^2 with radius 'r'.
*
* 'x' and 'y' must be initialized and the correct amount of space must
* be allocated. The weight of the realized edges is 'r - d', where 'd'
* is the geometric distance between the two vertices (in short the
* weight is always between 0 and 1.0).
*/
void graph_get_crgg(graph *g, int vertices, double r, double *x, double *y, gsl_rng *rng);
/**
* Get a random geometric graph in a rectangle with an area of 1 and
* radius 'r'.
*
* 'x' and 'y' must be initialized and the correct amount of space must
* be allocated. The weight of the realized edges is 'r - d', where 'd'
* is the geometric distance between the two vertices (in short the
* weight is always between 0 and 1.0).
*/
void graph_get_rec_rgg(graph *g, int vertices, double width, double r, double *x, double *y, gsl_rng *rng);
/**
* Get a connected random geometric graph in a rectangle with an area of
* 1 and radius 'r'.
*
* 'x' and 'y' must be initialized and the correct amount of space must
* be allocated. The weight of the realized edges is 'r - d', where 'd'
* is the geometric distance between the two vertices (in short the
* weight is always between 0 and 1.0).
*/
void graph_get_rec_crgg(graph *g, int vertices, double width, double r, double *x, double *y, gsl_rng *rng);
/**
* Return a complete graph (all vertices linked to each other). Realized
* edges have a default weight of 1.0.
*/
void graph_get_complete(graph *g, int vertices);
/**
* Return a circle. Realized edges have a default weight of 1.0.
*/
void graph_get_circle(graph *g, int vertices);
/**
* Return a star. Realized edges have a default weight of 1.0.
*/
void graph_get_star(graph *g, int vertices);
///////////////////////////////////////////////////////////////
// 'Private' functions. You shouldn't need those.
/** Recursive function used to test connectivity. */
void graph_test_cc(const graph *g, int *group, int u);
/** Increse the storage of the lists for vertex 'u'. O(|E|). */
void graph_grow_lists(graph *g, int u);
#endif
| {
"alphanum_fraction": 0.6736538462,
"avg_line_length": 34.8993288591,
"ext": "h",
"hexsha": "d62a9bf8c36801a4a18a77f892cdcee3572e6ba9",
"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": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "PhDP/Origin",
"max_forks_repo_path": "src/graph.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712",
"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": "PhDP/Origin",
"max_issues_repo_path": "src/graph.h",
"max_line_length": 122,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "PhDP/Origin",
"max_stars_repo_path": "src/graph.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1408,
"size": 5200
} |
/*
* Copyright (c) 2007, Michael Lehn
*
* 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 FLENS development group nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FLENS_FLENS_H
#define FLENS_FLENS_H 1
#define ADDRESS(x) reinterpret_cast<const void *>(&x)
#ifndef ASSERT
#define ASSERT(x) assert(x)
#endif //ASSERT
#include <array.h>
#include <bandstorage.h>
#include <blas.h>
#include <blas_flens.h>
#include <cg.h>
#include <complex_helper.h>
#include <crs.h>
#include <densevector.h>
#include <evalclosure.h>
#include <fullstorage.h>
#include <generalmatrix.h>
#include <generic_blas.h>
#include <refcounter.h>
#include <lapack.h>
#include <lapack_flens.h>
#include <listinitializer.h>
#include <matvec.h>
#include <matvecclosures.h>
#include <matvecio.h>
#include <matvecoperations.h>
#include <multigrid.h>
#include <packedstorage.h>
#include <range.h>
#include <snapshot.h>
#include <storage.h>
#include <sparsematrix.h>
#include <sparse_blas.h>
#include <sparse_blas_flens.h>
#include <symmetricmatrix.h>
#include <traits.h>
#include <triangularmatrix.h>
#include <underscore.h>
#include <uplo.h>
#endif // FLENS_FLENS_H
| {
"alphanum_fraction": 0.7426610751,
"avg_line_length": 34.0649350649,
"ext": "h",
"hexsha": "5a47a6c4655bb9fcb11624e840778c567ce07f02",
"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": "2a8f82e1492c9efccde9a4935ce3019df1c68cde",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "wmotte/toolkid",
"max_forks_repo_path": "src/flens/flens.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde",
"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": "wmotte/toolkid",
"max_issues_repo_path": "src/flens/flens.h",
"max_line_length": 75,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "wmotte/toolkid",
"max_stars_repo_path": "src/flens/flens.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 610,
"size": 2623
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_fft_complex.h>
#define REAL(z,i) ((z)[2*(i)])
#define IMAG(z,i) ((z)[2*(i)+1])
int
main (void)
{
int i; double data[2*128];
for (i = 0; i < 128; i++)
{
REAL(data,i) = 0.0; IMAG(data,i) = 0.0;
}
REAL(data,0) = 1.0;
for (i = 1; i <= 10; i++)
{
REAL(data,i) = REAL(data,128-i) = 1.0;
}
for (i = 0; i < 128; i++)
{
printf ("%d %e %e\n", i,
REAL(data,i), IMAG(data,i));
}
printf ("\n");
gsl_fft_complex_radix2_forward (data, 1, 128);
for (i = 0; i < 128; i++)
{
printf ("%d %e %e\n", i,
REAL(data,i)/sqrt(128),
IMAG(data,i)/sqrt(128));
}
return 0;
}
| {
"alphanum_fraction": 0.4623513871,
"avg_line_length": 17.2045454545,
"ext": "c",
"hexsha": "aa00242fdade49fbb0acc77054b977ddea2b3cac",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/doc/examples/fft.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/doc/examples/fft.c",
"max_line_length": 48,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/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": 286,
"size": 757
} |
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_blas.h>
#ifndef gauge_config
#include "config.h"
#define gauge_config 1
#define sq(x) ((x)*(x))
#define cb(x) ((x)*(x)*(x))
#endif
// SU(2) Matrix
// only the first row carries useful information (Lang p.80)
// note that for the first row must be normalized, i.e. |a|^2+ |b|^2 = 1
// use su2_normalize() for this
typedef struct{
gsl_complex a;
gsl_complex b;
} su2_matrix;
// SU(2) matrix methods --------------------------------------
// print matrix
void su2_print(const su2_matrix A){
printf("%f + i*%f \t", GSL_REAL(A.a), GSL_IMAG(A.a));
printf("%f + i*%f \n", GSL_REAL(A.b), GSL_IMAG(A.b));
}
// the identity matrix
su2_matrix su2_unit(){
su2_matrix u;
u.a=GSL_COMPLEX_ONE;
u.b=GSL_COMPLEX_ZERO;
return u;
}
// normalize matrix
su2_matrix su2_norm(const su2_matrix A){
su2_matrix result;
double norm = sqrt(gsl_complex_abs2(A.a)+gsl_complex_abs2(A.b));
result.a = gsl_complex_div(A.a,gsl_complex_rect(norm,0));
result.b = gsl_complex_div(A.b,gsl_complex_rect(norm,0));
return result;
}
// multiply matrices
su2_matrix su2_mul(const su2_matrix A, const su2_matrix B){
su2_matrix result;
result.a = gsl_complex_sub(gsl_complex_mul(A.a,B.a), gsl_complex_mul(A.b,gsl_complex_conjugate(B.b))); // ac-bd*
result.b = gsl_complex_add(gsl_complex_mul(A.a,B.b), gsl_complex_mul(A.b,gsl_complex_conjugate(B.a))); // ad+bc*
return result;
}
// inverse matrix
su2_matrix su2_inv(const su2_matrix A){
su2_matrix result;
result.a = gsl_complex_conjugate(A.a);
result.b = gsl_complex_sub(GSL_COMPLEX_ZERO,A.b);
return result;
}
// generate random matrix
su2_matrix su2_rand(const gsl_rng* r){
su2_matrix result;
result.a = gsl_complex_rect(1,eps*(gsl_rng_uniform(r)*2-1));
result.b = gsl_complex_rect(0,eps*(gsl_rng_uniform(r)*2-1));
return su2_norm(result);
}
double su2_trace(const su2_matrix A){
return 2*GSL_REAL(A.a);
}
// end of SU(2) matrix methods ---------------------------------------------
| {
"alphanum_fraction": 0.6863013699,
"avg_line_length": 26.3855421687,
"ext": "c",
"hexsha": "7ab95266004f3ec729f29db1700cfdc8bdf945f0",
"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": "b73f218593cecf0313e3d97b7ce2262844baab2e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "uchuutamashi/lqcd",
"max_forks_repo_path": "su2/su2_matrix.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e",
"max_issues_repo_issues_event_max_datetime": "2015-06-11T18:46:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-04-23T03:08:28.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "uchuutamashi/lqcd",
"max_issues_repo_path": "su2/su2_matrix.c",
"max_line_length": 114,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b73f218593cecf0313e3d97b7ce2262844baab2e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "uchuutamashi/lqcd",
"max_stars_repo_path": "su2/su2_matrix.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 648,
"size": 2190
} |
#if !defined(STRIPWS_H_INCLUDED)
#define STRIPWS_H_INCLUDED
#include "FileEnumerator.h"
#include "Utils.h"
#include <filesystem>
#include <gsl/gsl>
#include <iosfwd>
#include <string>
class StripWS
{
public:
static int usage(::std::ostream& strm, const ::std::string& progName,
const char* pMsg);
StripWS(::gsl::span<const char*const> args);
int run() const;
StripWS(const StripWS&) = delete;
StripWS& operator=(const StripWS&) = delete;
StripWS(StripWS&&) = delete;
StripWS& operator=(StripWS&&) = delete;
PRIVATE_EXCEPT_IN_TEST:
using Path = ::std::filesystem::path;
void queryFile(const Path& p) const;
void translateFile(const Path& p) const;
/// \brief Scans the input file, counts the occurrences of white space at
/// the end of a line, and optionally strips them into the provided stream.
///
/// If pOut is null, then the method simply counts the occurrences of white
/// space at the end of a line.
///
/// If pOut is not null, then the method additionally translates the file
/// into *pOut.
static void scanFile(::std::istream& in, /* out */ size_t& numLinesAffected,
/* out */ size_t& numSpacesStripped, /* out */ size_t& numTabsStripped,
::std::ostream* pOut = nullptr);
static void updateCounts(::std::string const& wsRun,
/* in-out */ size_t& numLinesAffected,
/* in-out */ size_t& numSpacesStripped,
/* in-out */ size_t& numTabsStripped);
static void replaceOriginalFileWithTemp(const Path& originalPath,
const Path& tempPath);
bool m_isInQueryMode;
FileEnumerator m_fileEnumerator;
};
#endif // STRIPWS_H_INCLUDED
| {
"alphanum_fraction": 0.7140151515,
"avg_line_length": 27.7894736842,
"ext": "h",
"hexsha": "6e25d82d4bc67212295743681914d1318e1614ae",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "IanEmmons/CmdLineUtil",
"max_forks_repo_path": "StripWS.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "IanEmmons/CmdLineUtil",
"max_issues_repo_path": "StripWS.h",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bd20d59d4d9fcc0d7d82a3031106d56ad10aad16",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "IanEmmons/CmdLineUtil",
"max_stars_repo_path": "StripWS.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 431,
"size": 1584
} |
/* specfunc/gsl_sf_coulomb.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.
*/
/* Author: G. Jungman */
#ifndef __GSL_SF_COULOMB_H__
#define __GSL_SF_COULOMB_H__
#include <gsl/gsl_mode.h>
#include <gsl/gsl_sf_result.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* Normalized hydrogenic bound states, radial dependence. */
/* R_1 := 2Z sqrt(Z) exp(-Z r)
*/
int gsl_sf_hydrogenicR_1_e(const double Z, const double r, gsl_sf_result * result);
double gsl_sf_hydrogenicR_1(const double Z, const double r);
/* R_n := norm exp(-Z r/n) (2Z/n)^l Laguerre[n-l-1, 2l+1, 2Z/n r]
*
* normalization such that psi(n,l,r) = R_n Y_{lm}
*/
int gsl_sf_hydrogenicR_e(const int n, const int l, const double Z, const double r, gsl_sf_result * result);
double gsl_sf_hydrogenicR(const int n, const int l, const double Z, const double r);
/* Coulomb wave functions F_{lam_F}(eta,x), G_{lam_G}(eta,x)
* and their derivatives; lam_G := lam_F - k_lam_G
*
* lam_F, lam_G > -0.5
* x > 0.0
*
* Conventions of Abramowitz+Stegun.
*
* Because there can be a large dynamic range of values,
* overflows are handled gracefully. If an overflow occurs,
* GSL_EOVRFLW is signalled and exponent(s) are returned
* through exp_F, exp_G. These are such that
*
* F_L(eta,x) = fc[k_L] * exp(exp_F)
* G_L(eta,x) = gc[k_L] * exp(exp_G)
* F_L'(eta,x) = fcp[k_L] * exp(exp_F)
* G_L'(eta,x) = gcp[k_L] * exp(exp_G)
*/
int
gsl_sf_coulomb_wave_FG_e(const double eta, const double x,
const double lam_F,
const int k_lam_G,
gsl_sf_result * F, gsl_sf_result * Fp,
gsl_sf_result * G, gsl_sf_result * Gp,
double * exp_F, double * exp_G);
/* F_L(eta,x) as array */
int gsl_sf_coulomb_wave_F_array(
double lam_min, int kmax,
double eta, double x,
double * fc_array,
double * F_exponent
);
/* F_L(eta,x), G_L(eta,x) as arrays */
int gsl_sf_coulomb_wave_FG_array(double lam_min, int kmax,
double eta, double x,
double * fc_array, double * gc_array,
double * F_exponent,
double * G_exponent
);
/* F_L(eta,x), G_L(eta,x), F'_L(eta,x), G'_L(eta,x) as arrays */
int gsl_sf_coulomb_wave_FGp_array(double lam_min, int kmax,
double eta, double x,
double * fc_array, double * fcp_array,
double * gc_array, double * gcp_array,
double * F_exponent,
double * G_exponent
);
/* Coulomb wave function divided by the argument,
* F(eta, x)/x. This is the function which reduces to
* spherical Bessel functions in the limit eta->0.
*/
int gsl_sf_coulomb_wave_sphF_array(double lam_min, int kmax,
double eta, double x,
double * fc_array,
double * F_exponent
);
/* Coulomb wave function normalization constant.
* [Abramowitz+Stegun 14.1.8, 14.1.9]
*/
int gsl_sf_coulomb_CL_e(double L, double eta, gsl_sf_result * result);
int gsl_sf_coulomb_CL_array(double Lmin, int kmax, double eta, double * cl);
__END_DECLS
#endif /* __GSL_SF_COULOMB_H__ */
| {
"alphanum_fraction": 0.6473429952,
"avg_line_length": 32.0930232558,
"ext": "h",
"hexsha": "65f0ac8da4549e57139b1164a9376022bbcfafd4",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_coulomb.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/specfunc/gsl_sf_coulomb.h",
"max_line_length": 107,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_coulomb.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": 1151,
"size": 4140
} |
/* multifit_nlinear/scaling.c
*
* Copyright (C) 2015, 2016 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* This module handles the updating of the scaling matrix D_k in the
* trust region subproblem:
*
* min m_k (dx), || D_k dx || <= Delta_k
*
* where m_k(dx) is a model which approximates the cost function
* F(x_k + dx) near the current iteration point x_k
*
* D_k can be updated according to several different strategies.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_multifit_nlinear.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
static int init_diag_levenberg(const gsl_matrix * J, gsl_vector * diag);
static int update_diag_levenberg(const gsl_matrix * J,
gsl_vector * diag);
static int init_diag_marquardt(const gsl_matrix * J, gsl_vector * diag);
static int update_diag_marquardt (const gsl_matrix * J,
gsl_vector * diag);
static int init_diag_more(const gsl_matrix * J, gsl_vector * diag);
static int update_diag_more(const gsl_matrix * J, gsl_vector * diag);
/* Levenberg scaling, D = I */
static int
init_diag_levenberg(const gsl_matrix * J, gsl_vector * diag)
{
(void)J; /* avoid unused parameter warning */
gsl_vector_set_all(diag, 1.0);
return GSL_SUCCESS;
}
static int
update_diag_levenberg(const gsl_matrix * J, gsl_vector * diag)
{
(void)J; /* avoid unused parameter warning */
(void)diag; /* avoid unused parameter warning */
/* nothing to do */
return GSL_SUCCESS;
}
/* initialize diagonal scaling matrix D according to Marquardt method */
static int
init_diag_marquardt(const gsl_matrix * J, gsl_vector * diag)
{
return update_diag_marquardt(J, diag);
}
/* update diagonal scaling matrix D according to Marquardt method */
static int
update_diag_marquardt (const gsl_matrix * J, gsl_vector * diag)
{
const size_t p = J->size2;
size_t j;
for (j = 0; j < p; j++)
{
gsl_vector_const_view v = gsl_matrix_const_column(J, j);
double norm = gsl_blas_dnrm2(&v.vector);
if (norm == 0.0)
norm = 1.0;
gsl_vector_set(diag, j, norm);
}
return GSL_SUCCESS;
}
/* initialize diagonal scaling matrix D according to Eq 6.3 of
* More, 1978 */
static int
init_diag_more(const gsl_matrix * J, gsl_vector * diag)
{
int status;
gsl_vector_set_zero(diag);
status = update_diag_more(J, diag);
return status;
}
/* update diagonal scaling matrix D according to Eq. 6.3 of
* More, 1978 */
static int
update_diag_more (const gsl_matrix * J, gsl_vector * diag)
{
const size_t p = J->size2;
size_t j;
for (j = 0; j < p; j++)
{
gsl_vector_const_view v = gsl_matrix_const_column(J, j);
double norm = gsl_blas_dnrm2(&v.vector);
double *diagj = gsl_vector_ptr(diag, j);
if (norm == 0.0)
norm = 1.0;
*diagj = GSL_MAX(*diagj, norm);
}
return GSL_SUCCESS;
}
static const gsl_multifit_nlinear_scale levenberg_type =
{
"levenberg",
init_diag_levenberg,
update_diag_levenberg
};
static const gsl_multifit_nlinear_scale marquardt_type =
{
"marquardt",
init_diag_marquardt,
update_diag_marquardt
};
static const gsl_multifit_nlinear_scale more_type =
{
"more",
init_diag_more,
update_diag_more
};
const gsl_multifit_nlinear_scale *gsl_multifit_nlinear_scale_levenberg = &levenberg_type;
const gsl_multifit_nlinear_scale *gsl_multifit_nlinear_scale_marquardt = &marquardt_type;
const gsl_multifit_nlinear_scale *gsl_multifit_nlinear_scale_more = &more_type;
| {
"alphanum_fraction": 0.7127585406,
"avg_line_length": 27.0628930818,
"ext": "c",
"hexsha": "fc2efda7cb0142b0ea6817e76aeaa76def9c07b2",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/scaling.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/scaling.c",
"max_line_length": 89,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/multifit_nlinear/scaling.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": 1167,
"size": 4303
} |
/*******************************************************************************
NAME: extract_rgb_palette
ALGORITHM DESCRIPTION:
Dumps RGB indexed color palette from graphics file to stdout
ISSUES:
Only color indexed TIFF files currently supported
*******************************************************************************/
#include "asf.h"
#include "asf_nan.h"
#include <math.h>
#include <ctype.h>
#include "asf_raster.h"
#include "typlim.h"
#include <float_image.h>
#include <uint8_image.h>
#include <geokeys.h>
#include <geo_tiffp.h>
#include <geo_keyp.h>
#include <geotiff.h>
#include <geotiffio.h>
#include <tiff.h>
#include <tiffio.h>
#include <xtiffio.h>
#include <gsl/gsl_math.h>
#include "geotiff_support.h"
#include "extract_rgb_palette_help.h"
/**** TYPES ****/
typedef enum {
UNKNOWN_GRAPHICS_TYPE=0,
ASF_IMG,
JPEG,
PGM,
PPM,
PBM,
STD_TIFF,
GEO_TIFF,
BMP,
GIF,
PNG
} graphics_file_t;
#define MISSING_TIFF_DATA -1
typedef struct {
uint32 width;
uint32 height;
short sample_format;
short bits_per_sample;
short planar_config;
data_type_t data_type; // ASF data type
short num_bands;
int is_scanline_format;
int is_palette_color_tiff;
} tiff_data_t;
#define MISSING_GTIF_DATA -1
typedef struct {
int gtif_data_exists;
char *GTcitation;
char *PCScitation;
int tie_point_elements; // Number of tie point elements (usually a multiple of 6)
int num_tie_points; // Number of elements divided by 6 since (i,j,k) maps to (x,y,z)
double *tie_point; // Usually only 1, but who knows what evil lurks in the hearts of men?
int pixel_scale_elements; // Usually a multiple of 3
int num_pixel_scales;
double *pixel_scale; // Should always be 3 of these ...for ScaleX, ScaleY, and ScaleZ
short model_type;
short raster_type;
short linear_units;
double scale_factor;
datum_type_t datum;
char hemisphere;
unsigned long pro_zone; // UTM zone (UTM only)
short proj_coords_trans;
short pcs;
short geodetic_datum;
short geographic_datum;
double false_easting;
double false_northing;
double natLonOrigin;
double lonCenter;
double falseOriginLon;
double falseOriginLat;
double natLatOrigin;
double latCenter;
double stdParallel1;
double stdParallel2;
double lonPole;
} geotiff_data_t;
/**** PROTOTYPES ****/
graphics_file_t getGraphicsFileType (char *file);
void graphicsFileType_toStr (graphics_file_t type, char *type_str);
float get_maxval(data_type_t data_type);
char *data_type2str(data_type_t data_type);
void get_tiff_info_from_file(char *file, tiff_data_t *t);
void get_tiff_info(TIFF *tif, tiff_data_t *t);
void get_geotiff_keys(char *file, geotiff_data_t *g);
void dump_tiff_rgb_palette(char *inFile);
int main(int argc, char **argv)
{
char *inFile;
char msg[1024];
char type_str[255];
asfSplashScreen(argc, argv);
if (argc != 2) {
usage();
exit(1);
}
else {
check_for_help(argc, argv);
}
inFile=argv[1];
if (!fileExists(inFile)) {
sprintf(msg, "File not found: %s\n => Did you forget to use the filename extension?\n", inFile);
asfPrintError(msg);
}
graphics_file_t type;
type = getGraphicsFileType(inFile);
if (type != STD_TIFF &&
type != GEO_TIFF )
{
graphicsFileType_toStr(type, type_str);
sprintf(msg, "Graphics file type %s is not currently supported (Graphics file: %s)\n",
type_str, inFile);
asfPrintError(msg);
}
switch (type) {
case STD_TIFF:
case GEO_TIFF:
dump_tiff_rgb_palette(inFile);
break;
default:
sprintf(msg, "Unrecognized image file type found.\n");
asfPrintError(msg);
break;
}
return (0);
}
graphics_file_t getGraphicsFileType (char *file)
{
FILE *fp = (FILE *)FOPEN(file, "rb");
uint8 magic[4];
graphics_file_t file_type = UNKNOWN_GRAPHICS_TYPE;
TIFF *itif = NULL;
GTIF *gtif = NULL;
if (fp != NULL) {
int i;
// Read the magic number from the file header
for (i=0; i<4; i++) {
magic[i] = (uint8)fgetc(fp);
}
if(fp) FCLOSE(fp);
// Check for a valid magic number combination
if (magic[0] == 0xFF && magic[1] == 0xD8) {
file_type = JPEG;
}
else if (magic[0] == 'P' && (magic[1] == '4' || magic[1] == '1')) {
file_type = PBM;
}
else if (magic[0] == 'P' && (magic[1] == '5' || magic[1] == '2')) {
file_type = PGM;
}
else if (magic[0] == 'P' && (magic[1] == '6' || magic[1] == '3')) {
file_type = PPM;
}
else if ((magic[0] == 'I' && magic[1] == 'I') || (magic[0] == 'M' && magic[1] == 'M')) {
file_type = STD_TIFF;
itif = XTIFFOpen(file, "rb");
if (itif != NULL) {
gtif = GTIFNew(itif);
if (gtif != NULL) {
double *tie_point = NULL;
double *pixel_scale = NULL;
short model_type, raster_type, linear_units;
int read_count, tie_points, pixel_scales;
(gtif->gt_methods.get)(gtif->gt_tif, GTIFF_TIEPOINTS, &tie_points, &tie_point);
(gtif->gt_methods.get)(gtif->gt_tif, GTIFF_PIXELSCALE, &pixel_scales, &pixel_scale);
read_count = GTIFKeyGet(gtif, GTModelTypeGeoKey, &model_type, 0, 1);
read_count += GTIFKeyGet(gtif, GTRasterTypeGeoKey, &raster_type, 0, 0);
read_count += GTIFKeyGet(gtif, ProjLinearUnitsGeoKey, &linear_units, 0, 1);
if (tie_points == 6 && pixel_scales == 3 && read_count == 3) {
file_type = GEO_TIFF;
}
if (tie_point != NULL) free(tie_point);
if (pixel_scale != NULL) free(pixel_scale);
GTIFFree(gtif);
}
XTIFFClose(itif);
}
}
else if (magic[0] == 'B' && magic[1] == 'M') {
file_type = BMP;
}
else if (magic[0] == 'G' && magic[1] == 'I' && magic[2] == 'F') {
file_type = GIF;
}
else if (magic[1] == 'P' && magic[2] == 'N' && magic[3] == 'G') {
file_type = PNG;
}
else {
file_type = UNKNOWN_GRAPHICS_TYPE;
}
}
return file_type;
}
void graphicsFileType_toStr (graphics_file_t type, char *type_str)
{
switch (type) {
case ASF_IMG:
strcpy (type_str, "ASF_IMG");
break;
case JPEG:
strcpy (type_str, "JPEG");
break;
case PBM:
strcpy (type_str, "PBM");
break;
case PGM:
strcpy (type_str, "PGM");
break;
case PPM:
strcpy (type_str, "PPM");
break;
case STD_TIFF:
strcpy (type_str, "TIFF");
break;
case GEO_TIFF:
strcpy (type_str, "GEOTIFF");
break;
case BMP:
strcpy (type_str, "BMP");
break;
case GIF:
strcpy (type_str, "GIF");
break;
case PNG:
strcpy (type_str, "PNG");
break;
case UNKNOWN_GRAPHICS_TYPE:
default:
strcpy(type_str, "UNRECOGNIZED");
break;
}
}
float get_maxval(data_type_t data_type)
{
float ret;
// Only non-complex types with 32 bits or less are supported
switch (data_type) {
case BYTE:
ret = powf(2, sizeof(unsigned char)) - 1.0;
break;
case INTEGER16:
ret = powf(2, sizeof(short int)) - 1.0;
break;
case INTEGER32:
ret = powf(2, sizeof(int)) - 1.0;
break;
case REAL32:
ret = MAXREAL;
break;
default:
ret = 0.0;
break;
}
return ret;
}
// User must free the returned string
char *data_type2str(data_type_t data_type)
{
char *retstr = (char*)CALLOC(64, sizeof(char));
switch (data_type) {
case BYTE:
strcpy(retstr, "BYTE");
break;
case INTEGER16:
strcpy(retstr, "INTEGER16");
break;
case INTEGER32:
strcpy(retstr, "INTEGER32");
break;
case REAL32:
strcpy(retstr, "REAL32");
break;
case REAL64:
strcpy(retstr, "REAL64");
break;
case COMPLEX_BYTE:
strcpy(retstr, "COMPLEX_BYTE");
break;
case COMPLEX_INTEGER16:
strcpy(retstr, "COMPLEX_INTEGER16");
break;
case COMPLEX_INTEGER32:
strcpy(retstr, "COMPLEX_INTEGER32");
break;
case COMPLEX_REAL32:
strcpy(retstr, "COMPLEX_REAL32");
break;
case COMPLEX_REAL64:
strcpy(retstr, "COMPLEX_REAL64");
break;
default:
strcpy(retstr, "UNKNOWN");
break;
}
return retstr;
}
void get_tiff_info_from_file(char *file, tiff_data_t *t)
{
TIFF *tif;
t->sample_format = MISSING_TIFF_DATA;
t->bits_per_sample = MISSING_TIFF_DATA;
t->planar_config = MISSING_TIFF_DATA;
t->data_type = 0;
t->num_bands = 0;
t->is_scanline_format = 0;
t->height = 0;
t->width = 0;
tif = XTIFFOpen(file, "rb");
if (tif != NULL) {
get_tiff_info(tif, t);
}
XTIFFClose(tif);
}
void get_tiff_info(TIFF *tif, tiff_data_t *t)
{
get_tiff_data_config(tif,
&t->sample_format,
&t->bits_per_sample,
&t->planar_config,
&t->data_type,
&t->num_bands,
&t->is_scanline_format,
&t->is_palette_color_tiff,
REPORT_LEVEL_NONE);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &t->height);
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &t->width);
if (t->planar_config != PLANARCONFIG_CONTIG &&
t->planar_config != PLANARCONFIG_SEPARATE &&
t->num_bands == 1)
{
t->planar_config = PLANARCONFIG_CONTIG;
}
}
void get_geotiff_keys(char *file, geotiff_data_t *g)
{
TIFF *tif = XTIFFOpen(file, "rb");
GTIF *gtif = NULL;
// Init values to 'missing'
g->gtif_data_exists = 0;
g->GTcitation = NULL; // Should be unallocated
g->PCScitation = NULL; // Should be unallocated
// Read geotiff info
if (tif != NULL) {
gtif = GTIFNew(tif);
if (gtif != NULL) {
int count, read_count;
int citation_length;
int typeSize;
tagtype_t citation_type;
// Get citations
citation_length = GTIFKeyInfo(gtif, GTCitationGeoKey, &typeSize, &citation_type);
if (citation_length > 0) {
g->GTcitation = (char*)MALLOC(citation_length * typeSize);
GTIFKeyGet(gtif, GTCitationGeoKey, g->GTcitation, 0, citation_length);
}
else {
g->GTcitation = NULL;
}
citation_length = GTIFKeyInfo(gtif, PCSCitationGeoKey, &typeSize, &citation_type);
if (citation_length > 0) {
g->PCScitation = (char*)MALLOC(citation_length * typeSize);
GTIFKeyGet(gtif, PCSCitationGeoKey, g->PCScitation, 0, citation_length);
}
else {
g->PCScitation = NULL;
}
if ((g->GTcitation != NULL && strlen(g->GTcitation) > 0) ||
(g->PCScitation != NULL && strlen(g->PCScitation) > 0))
{
g->gtif_data_exists = 1;
}
// Get tie points and pixel scale
(gtif->gt_methods.get)(gtif->gt_tif, GTIFF_TIEPOINTS, &count, &g->tie_point);
if (count >= 6) {
g->gtif_data_exists = 1;
g->tie_point_elements = count;
g->num_tie_points = count / 6;
}
(gtif->gt_methods.get)(gtif->gt_tif, GTIFF_PIXELSCALE, &count, &g->pixel_scale);
if (count >= 3) {
g->gtif_data_exists = 1;
g->pixel_scale_elements = count;
g->num_pixel_scales = count / 3;
}
// Get model type, raster type, and linear units
read_count = GTIFKeyGet (gtif, GTModelTypeGeoKey, &g->model_type, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
read_count = GTIFKeyGet (gtif, GTRasterTypeGeoKey, &g->raster_type, 0, 0);
if (read_count >= 1) g->gtif_data_exists = 1;
read_count = GTIFKeyGet (gtif, ProjLinearUnitsGeoKey, &g->linear_units, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
// Get UTM related info if it exists
read_count = GTIFKeyGet(gtif, ProjectedCSTypeGeoKey, &g->pcs, 0, 1);
if (read_count == 1 && PCS_2_UTM(g->pcs, &g->hemisphere, &g->datum, &g->pro_zone)) {
g->gtif_data_exists = 1;
}
else {
read_count = GTIFKeyGet(gtif, ProjectionGeoKey, &g->pcs, 0, 1);
if (read_count == 1 && PCS_2_UTM(g->pcs, &g->hemisphere, &g->datum, &g->pro_zone)) {
g->gtif_data_exists = 1;
}
else {
g->hemisphere = '\0';
g->datum = UNKNOWN_DATUM;
g->pro_zone = MISSING_GTIF_DATA;
}
}
// Get projection type (ProjCoordTransGeoKey) and other projection parameters
read_count = GTIFKeyGet(gtif, ProjCoordTransGeoKey, &g->proj_coords_trans, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->proj_coords_trans = MISSING_GTIF_DATA;
read_count = GTIFKeyGet(gtif, GeographicTypeGeoKey, &g->geographic_datum, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->geographic_datum = MISSING_GTIF_DATA;
read_count = GTIFKeyGet(gtif, GeogGeodeticDatumGeoKey, &g->geodetic_datum, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->geodetic_datum = MISSING_GTIF_DATA;
read_count = GTIFKeyGet(gtif, ProjScaleAtNatOriginGeoKey, &g->scale_factor, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->scale_factor = MISSING_GTIF_DATA;
// Get generic projection parameters (Note: projection type is defined by
// the g->proj_coords_trans value)
read_count = GTIFKeyGet (gtif, ProjFalseEastingGeoKey, &g->false_easting, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->false_easting = MISSING_GTIF_DATA;
read_count = GTIFKeyGet (gtif, ProjFalseNorthingGeoKey, &g->false_northing, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->false_northing = MISSING_GTIF_DATA;
read_count = GTIFKeyGet (gtif, ProjNatOriginLongGeoKey, &g->natLonOrigin, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->natLonOrigin = MISSING_GTIF_DATA;
read_count = GTIFKeyGet (gtif, ProjNatOriginLatGeoKey, &g->natLatOrigin, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->natLatOrigin = MISSING_GTIF_DATA;
read_count = GTIFKeyGet (gtif, ProjStdParallel1GeoKey, &g->stdParallel1, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->stdParallel1 = MISSING_GTIF_DATA;
read_count = GTIFKeyGet (gtif, ProjStdParallel2GeoKey, &g->stdParallel2, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->stdParallel2 = MISSING_GTIF_DATA;
read_count = GTIFKeyGet (gtif, ProjCenterLongGeoKey, &g->lonCenter, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->lonCenter = MISSING_GTIF_DATA;
read_count = GTIFKeyGet (gtif, ProjCenterLatGeoKey, &g->latCenter, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->latCenter = MISSING_GTIF_DATA;
read_count = GTIFKeyGet (gtif, ProjFalseOriginLongGeoKey, &g->falseOriginLon, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->falseOriginLon = MISSING_GTIF_DATA;
read_count = GTIFKeyGet (gtif, ProjFalseOriginLatGeoKey, &g->falseOriginLat, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->falseOriginLat = MISSING_GTIF_DATA;
read_count = GTIFKeyGet (gtif, ProjStraightVertPoleLongGeoKey, &g->lonPole, 0, 1);
if (read_count >= 1) g->gtif_data_exists = 1;
else g->lonPole = MISSING_GTIF_DATA;
}
}
}
void tiff_get_float_line(TIFF *tif, float *buf, int row, int band_no)
{
tiff_data_t t;
get_tiff_info(tif, &t);
// Note: For single-plane (greyscale) images, planar_config may remain unset so
// we can't use it as a guide for checking TIFF validity...
if (t.sample_format == MISSING_TIFF_DATA ||
t.bits_per_sample == MISSING_TIFF_DATA ||
t.data_type == 0 ||
t.num_bands == MISSING_TIFF_DATA ||
t.is_scanline_format == MISSING_TIFF_DATA ||
t.height == 0 ||
t.width == 0)
{
asfPrintError("Cannot read tif file\n");
}
// Read a scanline
tsize_t scanlineSize = TIFFScanlineSize(tif);
tdata_t *tif_buf = _TIFFmalloc(scanlineSize);
if (t.planar_config == PLANARCONFIG_CONTIG || t.num_bands == 1) {
TIFFReadScanline(tif, tif_buf, row, 0);
}
else {
// Planar configuration is band-sequential
TIFFReadScanline(tif, tif_buf, row, band_no);
}
int col;
for (col=0; col<t.width; col++) {
switch(t.bits_per_sample) {
case 8:
switch(t.sample_format) {
case SAMPLEFORMAT_UINT:
if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {
buf[col] = (float)(((uint8*)(tif_buf))[(col*t.num_bands)+band_no]); // Current sample.
}
else {
// Planar configuration is band-sequential or single-banded
buf[col] = (float)(((uint8*)(tif_buf))[col]);
}
break;
case SAMPLEFORMAT_INT:
if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {
buf[col] = (float)(((int8*)(tif_buf))[(col*t.num_bands)+band_no]); // Current sample.
}
else {
// Planar configuration is band-sequential or single-banded
buf[col] = (float)(((int8*)(tif_buf))[col]); // Current sample.
}
break;
default:
// There is no such thing as an IEEE 8-bit floating point
if (tif_buf) _TIFFfree(tif_buf);
if (tif) XTIFFClose(tif);
asfPrintError("tiff_get_float_line(): Unexpected data type in TIFF file.\n");
break;
}
break;
case 16:
switch(t.sample_format) {
case SAMPLEFORMAT_UINT:
if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {
buf[col] = (float)(((uint16*)(tif_buf))[(col*t.num_bands)+band_no]); // Current sample.
}
else {
// Planar configuration is band-sequential or single-banded
buf[col] = (float)(((uint16*)(tif_buf))[col]); // Current sample.
}
break;
case SAMPLEFORMAT_INT:
if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {
buf[col] = (float)(((int16*)(tif_buf))[(col*t.num_bands)+band_no]); // Current sample.
}
else {
// Planar configuration is band-sequential or single-banded
buf[col] = (float)(((uint16*)(tif_buf))[col]); // Current sample.
}
break;
default:
// There is no such thing as an IEEE 16-bit floating point
if (tif_buf) _TIFFfree(tif_buf);
if (tif) XTIFFClose(tif);
asfPrintError("tiff_get_float_line(): Unexpected data type in TIFF file.\n");
break;
}
break;
case 32:
switch(t.sample_format) {
case SAMPLEFORMAT_UINT:
if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {
buf[col] = (float)(((uint32*)(tif_buf))[(col*t.num_bands)+band_no]); // Current sample.
}
else {
// Planar configuration is band-sequential or single-banded
buf[col] = (float)(((uint32*)(tif_buf))[col]); // Current sample.
}
break;
case SAMPLEFORMAT_INT:
if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {
buf[col] = (float)(((long*)(tif_buf))[(col*t.num_bands)+band_no]); // Current sample.
}
else {
// Planar configuration is band-sequential or single-banded
buf[col] = (float)(((long*)(tif_buf))[col]); // Current sample.
}
break;
case SAMPLEFORMAT_IEEEFP:
if (t.planar_config == PLANARCONFIG_CONTIG && t.num_bands > 1) {
buf[col] = (float)(((float*)(tif_buf))[(col*t.num_bands)+band_no]); // Current sample.
}
else {
// Planar configuration is band-sequential or single-banded
buf[col] = (float)(((float*)(tif_buf))[col]); // Current sample.
}
break;
default:
if (tif_buf) _TIFFfree(tif_buf);
if (tif) XTIFFClose(tif);
asfPrintError("tiff_get_float_line(): Unexpected data type in TIFF file.\n");
break;
}
break;
default:
if (tif_buf) _TIFFfree(tif_buf);
if (tif) XTIFFClose(tif);
asfPrintError("tiff_get_float_line(): Unexpected data type in TIFF file.\n");
break;
}
}
if (tif_buf) {
_TIFFfree(tif_buf);
}
}
float tiff_image_get_float_pixel(TIFF *tif, int row, int col, int band_no)
{
tiff_data_t t;
float cs;
get_tiff_info(tif, &t);
// Note: For single-plane (greyscale) images, planar_config may remain unset so
// we can't use it as a guide for checking TIFF validity...
if (t.sample_format == MISSING_TIFF_DATA ||
t.bits_per_sample == MISSING_TIFF_DATA ||
t.data_type == 0 ||
t.num_bands == MISSING_TIFF_DATA ||
t.is_scanline_format == MISSING_TIFF_DATA ||
t.height == 0 ||
t.width == 0)
{
asfPrintError("Cannot read tif file\n");
}
// Get a float line from the file
float *buf = (float*)MALLOC(t.width*sizeof(float));
tiff_get_float_line(tif, buf, row, band_no);
cs = buf[col];
FREE(buf);
// Return as float
return cs;
}
void dump_tiff_rgb_palette(char *inFile)
{
TIFF *tiff = NULL;
tiff_data_t tiff_data;
get_tiff_info_from_file(inFile, &tiff_data);
tiff = XTIFFOpen(inFile, "rb");
if (!tiff) asfPrintError("Cannot open TIFF file (%s)\n", inFile);
int color;
int num_colors=(int)powl(2,tiff_data.bits_per_sample);
uint16* red=NULL;
uint16* green=NULL;
uint16* blue=NULL;
uint16 rmin, gmin, bmin, min;
uint16 rmax, gmax, bmax, max;
TIFFGetField(tiff, TIFFTAG_COLORMAP, &red, &green, &blue);
if (red == NULL || green == NULL || blue == NULL) asfPrintError("Cannot read palette from TIFF file (%s)\n", inFile);
rmin=gmin=bmin=min=65535; // Max uint16
rmax=gmax=bmax=max=0; // Min uint16
for (color=0; color<num_colors; color++) {
unsigned short r, g, b;
r=red[color];
g=green[color];
b=blue[color];
r = (unsigned short)(((float)r/65535)*255 + .5);
g = (unsigned short)(((float)g/65535)*255 + .5);
b = (unsigned short)(((float)b/65535)*255 + .5);
rmin = (r < rmin) ? r : rmin;
gmin = (g < gmin) ? g : gmin;
bmin = (b < bmin) ? b : bmin;
min = (r < min) ? r : min;
min = (g < min) ? g : min;
min = (b < min) ? b : min;
rmax = (r > rmax) ? r : rmax;
gmax = (g > gmax) ? g : gmax;
bmax = (b > bmax) ? b : bmax;
max = (r > max) ? r : max;
max = (g > max) ? g : max;
max = (b > max) ? b : max;
}
fprintf(stdout, "# red min = %03d, green min = %03d, blue min = %03d, overall min = %03d\n",
rmin, gmin, bmin, min);
fprintf(stdout, "# red max = %03d, green max = %03d, blue max = %03d, overall max = %03d\n",
rmax, gmax, bmax, max);
fprintf(stdout, "# \n# color\tred\tgreen\tblue\n");
for (color=0; color<num_colors; color++) {
unsigned short r, g, b;
r=red[color];
g=green[color];
b=blue[color];
r = (unsigned short)(((float)r/65535)*255 + .5);
g = (unsigned short)(((float)g/65535)*255 + .5);
b = (unsigned short)(((float)b/65535)*255 + .5);
fprintf(stdout, "%03d\t%03d\t%03d\t%03d\n",
color, r, g, b);
}
XTIFFClose(tiff);
}
| {
"alphanum_fraction": 0.5935846981,
"avg_line_length": 31.5922459893,
"ext": "c",
"hexsha": "e5fdae00743b45a481fc1c79ce6bd0347d17812e",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z",
"max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "glshort/MapReady",
"max_forks_repo_path": "src/extract_rgb_palette/extract_rgb_palette.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "glshort/MapReady",
"max_issues_repo_path": "src/extract_rgb_palette/extract_rgb_palette.c",
"max_line_length": 121,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "glshort/MapReady",
"max_stars_repo_path": "src/extract_rgb_palette/extract_rgb_palette.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z",
"num_tokens": 6959,
"size": 23631
} |
#include <math.h>
#include <stdio.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
int main(void)
{
size_t i, j;
gsl_matrix *m = gsl_matrix_alloc(10,10);
for (i=0; i<10; i++)
for (j=0; j<10; j++)
gsl_matrix_set(m, i, j, sin(i) + cos(j));
for (j=0; j<10; j++)
{
gsl_vector_view column = gsl_matrix_column(m, j);
double d;
d = gsl_blas_dnrm2(&column.vector);
printf("matrix column %zu, norm = %g\n", j, d);
}
gsl_matrix_free(m);
return 0;
}
| {
"alphanum_fraction": 0.5875251509,
"avg_line_length": 16.5666666667,
"ext": "c",
"hexsha": "7b1663692a4f2efc2c34c7462af863f663253cca",
"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": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tcrundall/chronostar",
"max_forks_repo_path": "playground/norm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"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": "tcrundall/chronostar",
"max_issues_repo_path": "playground/norm.c",
"max_line_length": 53,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bdb5cd965e862ba5cc21bee75d5c8620e106c0cc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tcrundall/chronostar",
"max_stars_repo_path": "playground/norm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 175,
"size": 497
} |
/*
* Author : Pierre Schnizer
* Date : December 2004
*
*/
/*
#ifdef DEBUG
#undef DEBUG
#endif
#define DEBUG 10
*/
#include <gsl/gsl_fft.h>
#include <gsl/gsl_fft_complex.h>
#include <gsl/gsl_fft_real.h>
#include <gsl/gsl_fft_halfcomplex.h>
#include <gsl/gsl_fft_complex_float.h>
#include <gsl/gsl_fft_real_float.h>
#include <gsl/gsl_fft_halfcomplex_float.h>
#include <pygsl/error_helpers.h>
#include <pygsl/block_helpers.h>
enum pygsl_fft_space_type{
COMPLEX_WORKSPACE = 0,
REAL_WORKSPACE,
COMPLEX_WAVETABLE,
REAL_WAVETABLE,
HALFCOMPLEX_WAVETABLE,
COMPLEX_WORKSPACE_FLOAT,
REAL_WORKSPACE_FLOAT,
COMPLEX_WAVETABLE_FLOAT,
REAL_WAVETABLE_FLOAT,
HALFCOMPLEX_WAVETABLE_FLOAT
};
enum pygsl_fft_mode{
MODE_DOUBLE = 0,
MODE_FLOAT
};
union pygsl_fft_space_t{
gsl_fft_complex_workspace *cws;
gsl_fft_complex_wavetable *cwt;
gsl_fft_real_workspace *rws;
gsl_fft_real_wavetable *rwt;
gsl_fft_halfcomplex_wavetable *hcwt;
gsl_fft_complex_workspace_float *cwsf;
gsl_fft_complex_wavetable_float *cwtf;
gsl_fft_real_workspace_float *rwsf;
gsl_fft_real_wavetable_float *rwtf;
gsl_fft_halfcomplex_wavetable_float *hcwtf;
void *v;
};
typedef struct {
PyObject_HEAD
union pygsl_fft_space_t space;
int type;
} PyGSL_fft_space;
static PyObject *module = NULL;
static const char filename[] = __FILE__;
static const char PyGSL_fft_space_type_doc[] = "\
A catch all of the various space types of the fft module. Call the method\n\
'get_type' to find what object is wrapped underneath!\n\
";
static void
PyGSL_fft_space_dealloc(PyGSL_fft_space * self);
static PyObject*
PyGSL_fft_space_getattr(PyGSL_fft_space * self, char * name);
#define PyGSL_fft_space_check(op) ((op)->ob_type == &PyGSL_fft_space_pytype)
#define PyGSL_complex_fft_work_space_check(op) \
(PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == COMPLEX_WORKSPACE)
#define PyGSL_complex_fft_wave_table_check(op) \
(PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == COMPLEX_WAVETABLE)
#define PyGSL_halfcomplex_fft_wave_table_check(op) \
(PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == HALFCOMPLEX_WAVETABLE)
#define PyGSL_real_fft_work_space_check(op) \
(PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == REAL_WORKSPACE)
#define PyGSL_real_fft_wave_table_check(op) \
(PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == REAL_WAVETABLE)
#define PyGSL_complex_fft_work_space_float_check(op) \
(PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == COMPLEX_WORKSPACE_FLOAT)
#define PyGSL_complex_fft_wave_table_float_check(op) \
(PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == COMPLEX_WAVETABLE_FLOAT)
#define PyGSL_halfcomplex_fft_wave_table_float_check(op) \
(PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == HALFCOMPLEX_WAVETABLE_FLOAT)
#define PyGSL_real_fft_work_space_float_check(op) \
(PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == REAL_WORKSPACE_FLOAT)
#define PyGSL_real_fft_wave_table_float_check(op) \
(PyGSL_fft_space_check(op) && ((PyGSL_fft_space *)op)->type == REAL_WAVETABLE_FLOAT)
#define PyGSL_FFT_MODE_SWITCH(mode, double_element, float_element) \
(mode == MODE_DOUBLE) ? double_element : float_element
PyTypeObject PyGSL_fft_space_pytype = {
PyObject_HEAD_INIT(NULL) /* fix up the type slot in initcrng */
0, /* ob_size */
"PyGSL_fft_space", /* tp_name */
sizeof(PyGSL_fft_space), /* tp_basicsize */
0, /* tp_itemsize */
/* standard methods */
(destructor) PyGSL_fft_space_dealloc, /* tp_dealloc ref-count==0 */
(printfunc) 0, /* tp_print "print x" */
(getattrfunc) PyGSL_fft_space_getattr, /* tp_getattr "x.attr" */
(setattrfunc) 0, /* tp_setattr "x.attr=v" */
(cmpfunc) 0, /* tp_compare "x > y" */
(reprfunc) 0, /* tp_repr `x`, print x */
/* type categories */
0, /* tp_as_number +,-,*,/,%,&,>>,pow...*/
0, /* tp_as_sequence +,[i],[i:j],len, ...*/
0, /* tp_as_mapping [key], len, ...*/
/* more methods */
(hashfunc) 0, /* tp_hash "dict[x]" */
(ternaryfunc) 0, /* tp_call "x()" */
(reprfunc) 0, /* tp_str "str(x)" */
(getattrofunc) 0, /* tp_getattro */
(setattrofunc) 0, /* tp_setattro */
0, /* tp_as_buffer */
0L, /* tp_flags */
(char *) PyGSL_fft_space_type_doc /* tp_doc */
};
static PyObject *
PyGSL_fft_space_get_factors(PyGSL_fft_space *self, PyGSL_fft_space *args)
{
int nf, i;
long *data=NULL;
size_t *cp_data=NULL;
PyArrayObject * a_array = NULL;
assert(PyGSL_fft_space_check(self));
DEBUG_MESS(2, "Type = %d", self->type);
switch(self->type){
case COMPLEX_WAVETABLE: nf = self->space.cwt ->nf; cp_data = self->space.cwt ->factor; break;
case REAL_WAVETABLE: nf = self->space.rwt ->nf; cp_data = self->space.rwt ->factor; break;
case HALFCOMPLEX_WAVETABLE: nf = self->space.hcwt->nf; cp_data = self->space.hcwt->factor; break;
case COMPLEX_WAVETABLE_FLOAT: nf = self->space.cwtf ->nf; cp_data = self->space.cwtf ->factor; break;
case REAL_WAVETABLE_FLOAT: nf = self->space.rwtf ->nf; cp_data = self->space.rwtf ->factor; break;
case HALFCOMPLEX_WAVETABLE_FLOAT: nf = self->space.hcwtf->nf; cp_data = self->space.hcwtf->factor; break;
default: gsl_error("Got unknown switch", filename, __LINE__, GSL_ESANITY); return NULL; break;
}
assert(nf < 64);
a_array = (PyArrayObject *) PyGSL_New_Array(1, &nf, PyArray_LONG);
if(a_array == NULL)
return NULL;
data = (long *) a_array->data;
for(i=0; i<nf; i++){
data[i] = (long) cp_data[i];
}
return (PyObject *) a_array;
}
static const char PyGSL_fft_space_get_factors_doc[] = " Get the factors ...";
static const char PyGSL_fft_space_get_type_doc[] = " Get the type of this space";
static PyObject *
PyGSL_fft_space_get_type(PyGSL_fft_space *self, PyObject *notused)
{
char *p = NULL;
switch(self->type){
case COMPLEX_WORKSPACE: p = "COMPLEX_WORKSPACE"; break;
case REAL_WORKSPACE: p = "REAL_WORKSPACE"; break;
case COMPLEX_WAVETABLE: p = "COMPLEX_WAVETABLE"; break;
case REAL_WAVETABLE: p = "REAL_WAVETABLE"; break;
case HALFCOMPLEX_WAVETABLE: p = "HALFCOMPLEX_WAVETABLE"; break;
case COMPLEX_WORKSPACE_FLOAT: p = "COMPLEX_WORKSPACE_FLOAT"; break;
case REAL_WORKSPACE_FLOAT: p = "REAL_WORKSPACE_FLOAT"; break;
case COMPLEX_WAVETABLE_FLOAT: p = "COMPLEX_WAVETABLE_FLOAT"; break;
case REAL_WAVETABLE_FLOAT: p = "REAL_WAVETABLE_FLOAT"; break;
case HALFCOMPLEX_WAVETABLE_FLOAT: p = "HALFCOMPLEX_WAVETABLE_FLOAT"; break;
default: gsl_error("Got unknown switch", filename, __LINE__, GSL_ESANITY); return NULL;
}
return PyString_FromString(p);
}
static PyMethodDef PyGSL_fft_wavetable_methods[] = {
{"get_factors", (PyCFunction)PyGSL_fft_space_get_factors, METH_NOARGS, (char *)PyGSL_fft_space_get_factors_doc},
{"get_type", (PyCFunction)PyGSL_fft_space_get_type, METH_NOARGS, (char *)PyGSL_fft_space_get_type_doc},
{NULL, NULL, 0, NULL} /* sentinel */
};
static PyMethodDef PyGSL_fft_space_methods[] = {
{"get_type", (PyCFunction)PyGSL_fft_space_get_type, METH_NOARGS, (char *)PyGSL_fft_space_get_type_doc},
{NULL, NULL, 0, NULL} /* sentinel */
};
static PyObject*
PyGSL_fft_space_getattr(PyGSL_fft_space *self, char *name)
{
PyObject *tmp = NULL;
FUNC_MESS_BEGIN();
assert(PyGSL_fft_space_check(self));
switch(self->type){
case COMPLEX_WORKSPACE:
case REAL_WORKSPACE:
case COMPLEX_WORKSPACE_FLOAT:
case REAL_WORKSPACE_FLOAT:
tmp = Py_FindMethod(PyGSL_fft_space_methods, (PyObject *) self, name);
default:
tmp = Py_FindMethod(PyGSL_fft_wavetable_methods, (PyObject *) self, name);
}
FUNC_MESS_END();
return tmp;
}
static void
PyGSL_fft_space_dealloc(PyGSL_fft_space * self)
{
FUNC_MESS_BEGIN();
assert(PyGSL_fft_space_check(self));
switch(self->type){
case COMPLEX_WORKSPACE: gsl_fft_complex_workspace_free(self->space.cws); break;
case COMPLEX_WAVETABLE: gsl_fft_complex_wavetable_free(self->space.cwt); break;
case REAL_WORKSPACE: gsl_fft_real_workspace_free(self->space.rws); break;
case REAL_WAVETABLE: gsl_fft_real_wavetable_free(self->space.rwt); break;
case HALFCOMPLEX_WAVETABLE: gsl_fft_halfcomplex_wavetable_free(self->space.hcwt); break;
case COMPLEX_WORKSPACE_FLOAT: gsl_fft_complex_workspace_float_free(self->space.cwsf); break;
case COMPLEX_WAVETABLE_FLOAT: gsl_fft_complex_wavetable_float_free(self->space.cwtf); break;
case REAL_WORKSPACE_FLOAT: gsl_fft_real_workspace_float_free(self->space.rwsf); break;
case REAL_WAVETABLE_FLOAT: gsl_fft_real_wavetable_float_free(self->space.rwtf); break;
case HALFCOMPLEX_WAVETABLE_FLOAT: gsl_fft_halfcomplex_wavetable_float_free(self->space.hcwtf); break;
default: gsl_error("Got unknown switch", filename, __LINE__, GSL_ESANITY); break;
}
FUNC_MESS_END();
}
static PyObject*
PyGSL_fft_space_init(PyObject *self, PyObject *args, int type)
{
PyGSL_fft_space *o=NULL;
size_t n;
o = (PyGSL_fft_space *) PyObject_NEW(PyGSL_fft_space, &PyGSL_fft_space_pytype);
if(o == NULL){
return NULL;
}
if (0==PyArg_ParseTuple(args,"l", &n))
return NULL;
if (n<=0) {
PyErr_SetString(PyExc_RuntimeError, "dimension must be >0");
return NULL;
}
o->type = type;
switch(type){
case COMPLEX_WORKSPACE: o->space.cws = gsl_fft_complex_workspace_alloc(n); break;
case COMPLEX_WAVETABLE: o->space.cwt = gsl_fft_complex_wavetable_alloc(n); break;
case REAL_WORKSPACE: o->space.rws = gsl_fft_real_workspace_alloc(n); break;
case REAL_WAVETABLE: o->space.rwt = gsl_fft_real_wavetable_alloc(n); break;
case HALFCOMPLEX_WAVETABLE: o->space.hcwt = gsl_fft_halfcomplex_wavetable_alloc(n); break;
case COMPLEX_WORKSPACE_FLOAT: o->space.cwsf = gsl_fft_complex_workspace_float_alloc(n); break;
case COMPLEX_WAVETABLE_FLOAT: o->space.cwtf = gsl_fft_complex_wavetable_float_alloc(n); break;
case REAL_WORKSPACE_FLOAT: o->space.rwsf = gsl_fft_real_workspace_float_alloc(n); break;
case REAL_WAVETABLE_FLOAT: o->space.rwtf = gsl_fft_real_wavetable_float_alloc(n); break;
case HALFCOMPLEX_WAVETABLE_FLOAT: o->space.hcwtf = gsl_fft_halfcomplex_wavetable_float_alloc(n); break;
default: gsl_error("Got unknown switch", filename, __LINE__, GSL_ESANITY); return NULL; break;
}
return (PyObject *) o;
}
#define PyGSL_SPACE_ALLOC(TYPE) \
static PyObject * \
PyGSL_fft_space_init_ ## TYPE (PyObject *self, PyObject *args)\
{ \
return PyGSL_fft_space_init(self, args, TYPE); \
}
PyGSL_SPACE_ALLOC(COMPLEX_WORKSPACE)
PyGSL_SPACE_ALLOC(COMPLEX_WAVETABLE)
PyGSL_SPACE_ALLOC(REAL_WORKSPACE)
PyGSL_SPACE_ALLOC(REAL_WAVETABLE)
PyGSL_SPACE_ALLOC(HALFCOMPLEX_WAVETABLE)
PyGSL_SPACE_ALLOC(COMPLEX_WORKSPACE_FLOAT)
PyGSL_SPACE_ALLOC(COMPLEX_WAVETABLE_FLOAT)
PyGSL_SPACE_ALLOC(REAL_WORKSPACE_FLOAT)
PyGSL_SPACE_ALLOC(REAL_WAVETABLE_FLOAT)
PyGSL_SPACE_ALLOC(HALFCOMPLEX_WAVETABLE_FLOAT)
/*
typedef int (complex_transform)(gsl_complex_packed_array
DATA, size_t STRIDE, size_t N, const
gsl_fft_complex_wavetable * WAVETABLE,
gsl_fft_complex_workspace * WORK);
*/
typedef int transform(void * data, size_t stride, size_t N, const void *, void *);
typedef int transform_r2(void * data, size_t stride, size_t N);
typedef void * pygsl_fft_helpn_t(int);
typedef void * pygsl_fft_help_t(void *);
struct _pygsl_fft_help_s {
pygsl_fft_helpn_t * space_alloc;
pygsl_fft_help_t * space_free;
pygsl_fft_helpn_t * table_alloc;
pygsl_fft_help_t * table_free;
enum pygsl_fft_space_type space_type;
enum pygsl_fft_space_type table_type;
void * space;
void * table;
int free_space;
int free_table;
};
typedef struct _pygsl_fft_help_s pygsl_fft_help_s;
static const
pygsl_fft_help_s complex_helpers = {(pygsl_fft_helpn_t *) gsl_fft_complex_workspace_alloc,
(pygsl_fft_help_t *) gsl_fft_complex_workspace_free,
(pygsl_fft_helpn_t *) gsl_fft_complex_wavetable_alloc,
(pygsl_fft_help_t *) gsl_fft_complex_wavetable_free,
COMPLEX_WORKSPACE, COMPLEX_WAVETABLE};
static const
pygsl_fft_help_s halfcomplex_helpers = {(pygsl_fft_helpn_t *) gsl_fft_real_workspace_alloc,
(pygsl_fft_help_t *) gsl_fft_real_workspace_free,
(pygsl_fft_helpn_t *) gsl_fft_halfcomplex_wavetable_alloc,
(pygsl_fft_help_t *) gsl_fft_halfcomplex_wavetable_free,
REAL_WORKSPACE, HALFCOMPLEX_WAVETABLE};
static const
pygsl_fft_help_s real_helpers = {(pygsl_fft_helpn_t *) gsl_fft_real_workspace_alloc,
(pygsl_fft_help_t *) gsl_fft_real_workspace_free,
(pygsl_fft_helpn_t *) gsl_fft_real_wavetable_alloc,
(pygsl_fft_help_t *) gsl_fft_real_wavetable_free,
REAL_WORKSPACE, REAL_WAVETABLE};
static const
pygsl_fft_help_s complex_helpers_float = {(pygsl_fft_helpn_t *) gsl_fft_complex_workspace_float_alloc,
(pygsl_fft_help_t *) gsl_fft_complex_workspace_float_free,
(pygsl_fft_helpn_t *) gsl_fft_complex_wavetable_float_alloc,
(pygsl_fft_help_t *) gsl_fft_complex_wavetable_float_free,
COMPLEX_WORKSPACE, COMPLEX_WAVETABLE};
static const
pygsl_fft_help_s halfcomplex_helpers_float = {(pygsl_fft_helpn_t *) gsl_fft_real_workspace_float_alloc,
(pygsl_fft_help_t *) gsl_fft_real_workspace_float_free,
(pygsl_fft_helpn_t *) gsl_fft_halfcomplex_wavetable_float_alloc,
(pygsl_fft_help_t *) gsl_fft_halfcomplex_wavetable_float_free,
REAL_WORKSPACE, HALFCOMPLEX_WAVETABLE};
static const
pygsl_fft_help_s real_helpers_float = {(pygsl_fft_helpn_t *) gsl_fft_real_workspace_float_alloc,
(pygsl_fft_help_t *) gsl_fft_real_workspace_float_free,
(pygsl_fft_helpn_t *) gsl_fft_real_wavetable_float_alloc,
(pygsl_fft_help_t *) gsl_fft_real_wavetable_float_free,
REAL_WORKSPACE, REAL_WAVETABLE};
static int
PyGSL_fft_helpers_alloc(PyObject *s_o, PyObject *t_o, pygsl_fft_help_s * h, int n)
{
h->free_space = 0;
h->free_table = 0;
h->table = NULL;
h->space = NULL;
if(s_o){
if(PyGSL_fft_space_check(s_o) && ((PyGSL_fft_space * )s_o)->type == h->space_type){
h->space = ((PyGSL_fft_space * )s_o) ->space.v;
} else {
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 4);
GSL_ERROR("Need a pygsl fft space of proper type!", GSL_EINVAL);
}
}
if(t_o){
if(PyGSL_fft_space_check(t_o) && ((PyGSL_fft_space * )t_o)->type == h->table_type){
h->table = ((PyGSL_fft_space * )t_o) ->space.v;
} else {
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 4);
GSL_ERROR("Need a pygsl fft wave table of proper type!", GSL_EINVAL);
}
}
/* Check for the approbriate type and initialise it!*/
if(h->space == NULL || h->table == NULL){
/* Store if I need to free these arrays */
h->free_space = (h->space == NULL) ? 1 : 0;
h->free_table = (h->table == NULL) ? 1 : 0;
if(!h->space) h->space = h->space_alloc(n);
if(!h->table) h->table = h->table_alloc(n);
if(!h->space || !h->table)
return GSL_ENOMEM;
}
return GSL_SUCCESS;
}
static void
PyGSL_fft_helpers_free(pygsl_fft_help_s * h)
{
if(h->table && h->free_table){
h->table_free(h->table);
h->table = NULL;
}
if(h->space && h->free_space){
h->space_free(h->space);
h->space = NULL;
}
}
/*
* Copies real data to complex in the special way that it will be passed to the
* transform with an offset of one!
*/
static int
PyGSL_copy_real_to_complex(PyArrayObject *dst, PyArrayObject *src, enum pygsl_fft_mode mode)
{
int i, n, n_check, n_2;
n = src->dimensions[0];
n_check = dst->dimensions[0];
for(i = 0; i < n; ++i){
double *srcd=NULL, *dstd=NULL;
float *srcf=NULL, *dstf=NULL;
if(mode == MODE_DOUBLE){
srcd = (double *)(src->data + src->strides[0] * (i));
n_2 = (i+1)/2;
dstd = (double *)(dst->data + dst->strides[0] * (n_2));
if(n_2 >= n_check)
GSL_ERROR("Complex array too small!", GSL_ESANITY);
dstd[(i+1)%2] = *srcd;
DEBUG_MESS(5, "R -> C [%d] srcd %e\t dstd %e + %ej", i, *srcd, dstd[0], dstd[1]);
}else if(mode == MODE_FLOAT){
srcf = (float *)(src->data + src->strides[0] * (i));
n_2 = (i+1)/2;
dstf = (float *)(dst->data + dst->strides[0] * (n_2));
if(n_2 >= n_check)
GSL_ERROR("Complex array too small!", GSL_ESANITY);
dstf[(i+1)%2] = *srcd;
}
}
/* XXX Sometimes the last value must be set to zero ... */
return GSL_SUCCESS;
}
/* Assumes special halfcomplex arrangement to be made and used ! */
static int
PyGSL_copy_halfcomplex_to_real(PyArrayObject *dst, PyArrayObject *src, double eps, enum pygsl_fft_mode mode
)
{
int n, n_check, i, n_2;
double *srcd=NULL, *dstd=NULL;
float *srcf=NULL, *dstf=NULL;
n_check = src->dimensions[0];
n = dst->dimensions[0];
/* The first element is a bit special */
if(mode == MODE_DOUBLE){
srcd = (double *)(src->data);
dstd = (double *)(dst->data);
} else {
srcf = (float *)(src->data);
dstf = (float *)(dst->data);
}
/* Should be zero ... */
if(gsl_fcmp(PyGSL_FFT_MODE_SWITCH(mode, srcd[1], srcf[1]), 0, eps) != 0)
GSL_ERROR("The complex part of the nyquist freqency was not"
"zero as it ought to be!", GSL_EINVAL);
*dstd = *srcd;
for(i = 1; i < n; ++i){
n_2 = (i+1)/2;
if(n_2 >= n_check){
GSL_ERROR("Sizes of the complex array too small!", GSL_ESANITY);
}
if(mode == MODE_DOUBLE){
srcd = (double *)(src->data + src->strides[0] * n_2);
dstd = (double *)(dst->data + dst->strides[0] * i);
*dstd = srcd[(i+1)%2];
DEBUG_MESS(5, "C -> R [%d] srcd %e + %ej\t dstd %e", i, srcd[0], srcd[1], *dstd);
} else {
srcf = (float *)(src->data + src->strides[0] * n_2);
dstf = (float *)(dst->data + dst->strides[0] * i);
*dstf = srcf[(i+1)%2];
DEBUG_MESS(5, "C -> R [%d] srcf %e + %ej\t dstf %e", i, srcf[0], srcf[1], *dstf);
}
}
return GSL_SUCCESS;
}
static int
PyGSL_copy_complex_to_complex(PyArrayObject *dst, PyArrayObject *src, enum pygsl_fft_mode mode)
{
int n, n_check, i;
FUNC_MESS_BEGIN();
n = dst->dimensions[0];
n_check = src->dimensions[0];
if(n_check != n){
GSL_ERROR("Sizes of the arrays did not match!", GSL_ESANITY);
}
for(i = 0; i < n; i ++){
double *srcd=NULL, *dstd=NULL;
float *srcf=NULL, *dstf=NULL;
if(mode == MODE_DOUBLE){
srcd = (double *)(src->data + src->strides[0] * i);
dstd = (double *)(dst->data + dst->strides[0] * i);
dstd[0] = srcd[0];
dstd[1] = srcd[1];
} else {
srcf = (float *)(src->data + src->strides[0] * i);
dstf = (float *)(dst->data + dst->strides[0] * i);
dstf[0] = srcf[0];
dstf[1] = srcf[1];
}
}
FUNC_MESS_END();
return GSL_SUCCESS;
}
#if 0
/*
* Copy a complex array to a real one or to the other ...
*/
static int
PyGSL_copy_complex_real(PyArrayObject *dst, PyArrayObject *src)
{
int in_type, out_type;
int flag = GSL_FAILURE, line = -1;
FUNC_MESS_BEGIN();
in_type = src->descr->type_num;
out_type = dst->descr->type_num;
if(in_type == PyArray_CDOUBLE){
DEBUG_MESS(2, "Src is a complex array!", NULL);
} else if (in_type == PyArray_DOUBLE){
DEBUG_MESS(2, "Src is a real array!", NULL);
}
if(out_type == PyArray_CDOUBLE){
DEBUG_MESS(2, "Dst is a complex array!", NULL);
} else if (out_type == PyArray_DOUBLE){
DEBUG_MESS(2, "Dst is a real array!", NULL);
}
if(out_type == PyArray_CDOUBLE && in_type == PyArray_CDOUBLE){
if(PyGSL_copy_complex_to_complex(dst, src) != GSL_SUCCESS){
line = __LINE__ - 1;
goto fail;
}
} else if(out_type == PyArray_DOUBLE && in_type == PyArray_CDOUBLE){
if(PyGSL_copy_halfcomplex_to_real(dst, src) != GSL_SUCCESS){
line = __LINE__ - 1;
goto fail;
}
} else if(out_type == PyArray_CDOUBLE && in_type == PyArray_DOUBLE){
if(PyGSL_copy_real_to_complex(dst, src) != GSL_SUCCESS){
line = __LINE__ - 1;
goto fail;
}
} else{
flag = GSL_ESANITY;
line = __LINE__;
goto fail;
}
FUNC_MESS_END();
return GSL_SUCCESS;
fail:
FUNC_MESS("Fail");
gsl_error("Not specifed error", filename, line, flag);
PyGSL_add_traceback(module, filename, __FUNCTION__, line);
return flag;
}
#endif
/*
* Only shift the last one. Assumes that it was passed to the GSL function with
* an offset of one. Further assumes an contingous array.
*/
static int
PyGSL_fft_halfcomplex_unpack(PyArrayObject *a, int n_orig, enum pygsl_fft_mode mode)
{
double *d;
float *f;
FUNC_MESS_BEGIN();
if(mode == MODE_DOUBLE){
d = (double *) a->data;
d[0] = d[1];
d[1] = 0.0;
/* Set the last imaginary to zero for even length as it ought to be */
if(n_orig%2)
d[n_orig] = 0.0;
}else{
f = (float *) a->data;
f[0] = f[1];
f[1] = 0.0;
/* Set the last imaginary to zero for even length as it ought to be */
if(n_orig%2)
f[n_orig] = 0.0;
}
FUNC_MESS_END();
return GSL_SUCCESS;
}
/*
* I only need to reorder the imaginary data?
* I have to do it inplace thus I can not use the gsl function ...
*/
static PyObject *
PyGSL_fft_halfcomplex_radix2_unpack(PyObject *self, PyObject *args)
{
PyObject *a_o=NULL;
PyArrayObject *a=NULL, *r=NULL;
int i, n, rn;
double *data, *real, *imag;
FUNC_MESS_BEGIN();
if(!PyArg_ParseTuple(args, "O",&a_o))
return NULL;
a = PyGSL_PyArray_PREPARE_gsl_vector_view(a_o, PyArray_DOUBLE, 0, -1, 1, NULL);
if(a == NULL)
goto fail;
n = a->dimensions[0];
if(n%2 != 0){
gsl_error("The length of the vector must be a multiple of two!",
__FILE__, __LINE__, GSL_EDOM); goto fail;
}
rn = n / 2 + 1;
if((r = (PyArrayObject *) PyGSL_New_Array(1, &rn, PyArray_CDOUBLE)) == NULL)
goto fail;
assert(r->dimensions[0] == rn);
/* first one special */
data = (double *) r->data;
data[0] = a->data[0];
data[1] = 0.0;
for(i = 1; i < rn - 1; ++i){
data = (double *)(r->data + r->strides[0] * i);
real = (double *)(a->data + a->strides[0] * i);
imag = (double *)(a->data + a->strides[0] * (n-i));
assert(i>0 && i < n);
data[0] = *real;
data[1] = *imag;
DEBUG_MESS(6, "n = %d, i = %d, n - i = %d, rn = %d", n, i, n - i, rn);
DEBUG_MESS(6, "real = %e, %p, imag = %e, %p", *real, real, *imag, imag);
DEBUG_MESS(5, "Data[%d] = %e + %e j", i, data[0], data[1]);
}
data = (double *)(r->data + r->strides[0] * (rn-1));
data[0] = *((double *)(a->data + a->strides[0] * (n/2)));
data[1] = 0.0;
/* data[n_orig] = 0.0; */
Py_DECREF(a);
FUNC_MESS_END();
return (PyObject *) r;
fail:
Py_XDECREF(a);
Py_XDECREF(r);
return NULL;
}
static PyObject *
PyGSL_fft_halfcomplex_radix2_unpack_float(PyObject *self, PyObject *args)
{
PyObject *a_o=NULL;
PyArrayObject *a=NULL, *r=NULL;
int i, n, rn;
float *data, *real, *imag;
FUNC_MESS_BEGIN();
if(!PyArg_ParseTuple(args, "O",&a_o))
return NULL;
a = PyGSL_PyArray_PREPARE_gsl_vector_view(a_o, PyArray_FLOAT, 0, -1, 1, NULL);
if(a == NULL)
goto fail;
n = a->dimensions[0];
if(n%2 != 0){
gsl_error("The length of the vector must be a multiple of two!",
__FILE__, __LINE__, GSL_EDOM); goto fail;
}
rn = n / 2 + 1;
if((r = (PyArrayObject *) PyGSL_New_Array(1, &rn, PyArray_CFLOAT)) == NULL)
goto fail;
assert(r->dimensions[0] == rn);
/* first one special */
data = (float *) r->data;
data[0] = a->data[0];
data[1] = 0.0;
for(i = 1; i < rn - 1; ++i){
data = (float *)(r->data + r->strides[0] * i);
real = (float *)(a->data + a->strides[0] * i);
imag = (float *)(a->data + a->strides[0] * (n-i));
assert(i>0 && i < n);
data[0] = *real;
data[1] = *imag;
DEBUG_MESS(6, "n = %d, i = %d, n - i = %d, rn = %d", n, i, n - i, rn);
DEBUG_MESS(6, "real = %e, %p, imag = %e, %p", *real, real, *imag, imag);
DEBUG_MESS(5, "Data[%d] = %e + %e j", i, data[0], data[1]);
}
data = (float *)(r->data + r->strides[0] * (rn-1));
data[0] = *((float *)(a->data + a->strides[0] * (n/2)));
data[1] = 0.0;
/* data[n_orig] = 0.0; */
Py_DECREF(a);
FUNC_MESS_END();
return (PyObject *) r;
fail:
Py_XDECREF(a);
Py_XDECREF(r);
return NULL;
}
# if 0
/*
* All the arithmetic here will be only possible if the array is
* continguous.
*/
if(a->strides[0] == sizeof(double) *2)
;
else
GSL_ERROR("Can only unpack continuous halfcomplex arrays!", GSL_ESANITY);
n = a->dimensions[0] - 1;
if(n * 2 < n_orig)
GSL_ERROR("Original size too big!!", GSL_ESANITY);
if(n_orig %2 == 0)
;
else
GSL_ERROR("Got non even length for radix2!?!", GSL_ESANITY);
DEBUG_MESS(2, "Unpacking a half complex array of size %d, storage size = %d",
n_orig, a->dimensions[0]);
data = (double *) a->data;
data[0] = data[1];
data[1] = 0.0;
/* Take the shift into account ++data; */
/*
* now data starts were the real array would start withot the shift
* trick
*/
for(i = 1; i < n_orig+1; i++)
DEBUG_MESS(5, "Putting data[%d]= %e", i, data[i]);
/* For two destinct arrays ....
for(i=1; i< n; ++i){
newdata[i*2] = data[i+1];
newdata[i*2+1] = data[n_orig-i+1];
}
*/
for(i = n_orig/2 - 1; i > 0; --i){
/* move the real data backward */
tmp1 = data[i+1];
tmp2 = data[n_orig-i+1];
DEBUG_MESS(5, "Putting %e + %ej from %d,%d -> %d %d", tmp1,
tmp2, i+1, n_orig-i+1, i*2, i*2+1);
/* get the imaginary data from the end */
if(i >= n)
GSL_ERROR("Out of range for unpack!", GSL_ESANITY);
tmp3 = data[i*2];
tmp4 = data[i*2+1];
data[i*2] = tmp1;
data[i*2+1] = tmp2;
}
#endif
/*
* A catch all of the various type handling routines. Perhaps too much in one function!
*/
static PyArrayObject *
PyGSL_Shadow_array(PyObject *shadow, PyObject *master, enum pygsl_fft_mode mode)
{
PyArrayObject * ret = NULL, *s=NULL, *m=NULL;
int line = -1;
/* Check if I got a return array */
if(!PyArray_Check(master)){
line = __LINE__ - 1;
goto fail;
}
m = (PyArrayObject *) master;
if(shadow == NULL){
FUNC_MESS("Generating an output array");
ret = (PyArrayObject *) PyGSL_Copy_Array(m);
if(ret == NULL){
line = __LINE__ -2;
goto fail;
}
} else {
if (shadow == master) {
Py_INCREF(shadow);
ret = m;
}else{
FUNC_MESS("Copying input to output array");
/* Check if it is an array of the approbriate size */
s = (PyArrayObject *) shadow;
if((PyArray_Check(s)) && (s->nd == 1 )
&& (s->descr->type_num == m->descr->type_num)
&& (s->dimensions[0] == m->dimensions[0])){
Py_INCREF(s);
ret = (PyArrayObject *) s;
} else {
gsl_error("The return array must be of approbriate size and type!",
filename, __LINE__, GSL_EINVAL);
line = __LINE__ -7;
goto fail;
}
if(PyGSL_ERROR_FLAG(PyGSL_copy_complex_to_complex(s, m, mode) != GSL_SUCCESS)){
line = __LINE__ -1;
goto fail;
}
}
}
return ret;
fail:
PyGSL_add_traceback(module, filename, __FUNCTION__, line);
return NULL;
}
static int
PyGSL_guess_halfcomplex_length(PyArrayObject *a, int length, double eps, enum pygsl_fft_mode mode)
{
int n, call_n = -1;
void *v;
n = a->dimensions[0];
if(length == -1){
/* length was not given, try to guess */
v = (a->data + a->strides[0] * (n - 1));
if(gsl_fcmp(PyGSL_FFT_MODE_SWITCH(mode, ((double *)v)[1], ((float *)v)[1]), 0, eps) == 0){
call_n = n*2-2;
}else{
/*
* The last element was close to zero, thus I assume
* that I got original data of even length.
*/
call_n = n*2-1;
}
}else if(length < -1){
gsl_error("The given length must be a positive number!",
__FILE__, __LINE__, GSL_EINVAL);
return length;
}else{
call_n = length;
}
DEBUG_MESS(5, "Using a length of %d", call_n);
return call_n;
}
static PyObject *
PyGSL_fft_halfcomplex(PyObject *self, PyObject *args, transform * transform, enum pygsl_fft_mode mode)
{
PyObject *data = NULL, *s_o= NULL, *t_o = NULL;
PyArrayObject *a = NULL, *r=NULL;
int strides=0;
int flag, call_n, return_n, length=-1;
int line = -1;
double eps=1e-6;
FUNC_MESS_BEGIN();
if(! PyArg_ParseTuple(args, "O|iOOd",&data, &length, &s_o, &t_o, &eps)){
return NULL;
}
a = PyGSL_PyArray_PREPARE_gsl_vector_view(data, PyGSL_FFT_MODE_SWITCH(mode, PyArray_CDOUBLE, PyArray_CFLOAT), 0, -1, 1, NULL);
if(a == NULL)
return NULL;
call_n = PyGSL_guess_halfcomplex_length(a, length, eps, mode);
if(call_n < 0)
goto fail;
return_n = call_n;
PyGSL_fft_helpers_alloc(s_o, t_o, PyGSL_FFT_MODE_SWITCH(mode, halfcomplex_helpers, halfcomplex_helpers_float));
r = (PyArrayObject *) PyGSL_New_Array(1, &return_n, PyArray_DOUBLE);
if(r == NULL){
line = __LINE__ - 2;
goto fail;
}
if(PyGSL_ERROR_FLAG(PyGSL_copy_halfcomplex_to_real(r, a, eps, mode) != GSL_SUCCESS)){
line = __LINE__ - 1;
goto fail;
}
flag = PyGSL_STRIDE_RECALC(r->strides[0], sizeof(double), &strides);
if(flag != GSL_SUCCESS){
line = __LINE__ - 2;
goto fail;
}
flag = transform((double *)(r->data), strides, call_n, table, space);
if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){
line = __LINE__ - 2;
goto fail;
}
PyGSL_fft_helpers_free(PyGSL_FFT_MODE_SWITCH(mode, halfcomplex_helpers, halfcomplex_helpers_float));
Py_DECREF(a);
FUNC_MESS_END();
return (PyObject *) r;
fail:
FUNC_MESS("Fail");
PyGSL_add_traceback(module, filename, __FUNCTION__, line);
PyGSL_fft_helpers_free(PyGSL_FFT_MODE_SWITCH(mode, halfcomplex_helpers, halfcomplex_helpers_float));
Py_XDECREF(a);
Py_XDECREF(r);
return NULL;
}
static PyObject *
PyGSL_fft_halfcomplex_radix2(PyObject *self, PyObject *args, transform_r2 * transform, enum pygsl_fft_mode mode)
{
PyObject *data = NULL;
PyArrayObject *a = NULL, *r=NULL;
int strides=0;
int flag, call_n, return_n;
int line = -1;
FUNC_MESS_BEGIN();
if(! PyArg_ParseTuple(args, "O", &data)){
return NULL;
}
a = PyGSL_PyArray_PREPARE_gsl_vector_view(data, PyArray_CDOUBLE, 0, -1, 1, NULL);
if(a == NULL)
return NULL;
call_n = a->dimensions[0];
return_n = call_n;
r = (PyArrayObject *) PyGSL_Copy_Array(a);
if(r == NULL){
line = __LINE__ - 2;
goto fail;
}
flag = PyGSL_STRIDE_RECALC(r->strides[0], sizeof(double), &strides);
if(flag != GSL_SUCCESS){
line = __LINE__ - 2;
goto fail;
}
flag = transform((double *)(r->data), strides, call_n);
if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){
line = __LINE__ - 2;
goto fail;
}
Py_DECREF(a);
FUNC_MESS_END();
return (PyObject *) r;
fail:
FUNC_MESS("Fail");
PyGSL_add_traceback(module, filename, __FUNCTION__, line);
Py_XDECREF(a);
Py_XDECREF(r);
return NULL;
}
static PyObject *
PyGSL_fft_real(PyObject *self, PyObject *args, transform * transform, enum pygsl_fft_mode mode)
{
PyObject *data = NULL, *s_o= NULL, *t_o = NULL;
PyArrayObject *a = NULL, *r=NULL;
gsl_fft_real_workspace *space=NULL;
gsl_fft_real_wavetable *table=NULL;
int strides=0, n=0, line=-1;
int free_space = 0, free_table=0, flag, call_n, return_n;
FUNC_MESS_BEGIN();
if(! PyArg_ParseTuple(args, "O|OO", &data, &s_o, &t_o)){
return NULL;
}
a = PyGSL_PyArray_PREPARE_gsl_vector_view(data, PyArray_DOUBLE, 0, -1, 1, NULL);
if(a == NULL)
return NULL;
n = a->dimensions[0];
call_n = n;
return_n = n/2 + 1;
if(s_o){
flag = PyGSL_real_fft_work_space_check(s_o);
if(flag){
space = ((PyGSL_fft_space * )s_o) ->space.rws;
} else {
line = __LINE__ -5;
gsl_error("Need a pygsl fft space!", filename, __LINE__ - 5, GSL_EINVAL);
goto fail;
}
}
if(t_o){
flag = PyGSL_real_fft_wave_table_check(t_o);
if(flag){
table = ((PyGSL_fft_space * )t_o) ->space.rwt;
} else {
line = __LINE__ -5;
gsl_error("Need a pygsl fft table!", filename, __LINE__ - 5, GSL_EINVAL);
goto fail;
}
}
/* Check for the approbriate type and initialise it!*/
if(space == NULL || table == NULL){
/* Store if I need to free these arrays */
free_space = (space == NULL) ? 1 : 0;
free_table = (table == NULL) ? 1 : 0;
if(!space) space = gsl_fft_real_workspace_alloc(call_n);
if(!table) table = gsl_fft_real_wavetable_alloc(call_n);
if(!space || !table)
goto fail;
}
/* Check if I got a return array */
r = (PyArrayObject *) PyGSL_New_Array(1, &return_n, PyArray_CDOUBLE);
if(r == NULL){
line = __LINE__ -2;
goto fail;
}
if(PyGSL_copy_real_to_complex(r, a, MODE_DOUBLE) != GSL_SUCCESS){
line = __LINE__ -1;
goto fail;
}
flag = PyGSL_STRIDE_RECALC(r->strides[0], sizeof(double) * 2, &strides);
if(flag != GSL_SUCCESS){
line = __LINE__ -2;
goto fail;
}
FUNC_MESS("Transforming ...");
flag = transform(((double *) r->data)+1, strides, call_n, table, space);
FUNC_MESS(" ... Done");
if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){
line = __LINE__ -2;
goto fail;
}
/* Rearange half complex data */
if(PyGSL_fft_halfcomplex_unpack(r, call_n, mode) != GSL_SUCCESS){
line = __LINE__ -1;
goto fail;
}
if(free_space == 1 && space != NULL) gsl_fft_real_workspace_free(space);
if(free_table == 1 && table != NULL) gsl_fft_real_wavetable_free(table);
Py_DECREF(a);
FUNC_MESS_END();
return (PyObject *) r;
fail:
FUNC_MESS("Fail");
PyGSL_add_traceback(module, filename, __FUNCTION__, line);
if(free_space == 1 && space != NULL) gsl_fft_real_workspace_free(space);
if(free_table == 1 && table != NULL) gsl_fft_real_wavetable_free(table);
Py_XDECREF(a);
Py_XDECREF(r);
return NULL;
}
static PyObject *
PyGSL_fft_real_radix2(PyObject *self, PyObject *args, transform_r2 * transform, enum pygsl_fft_mode mode)
{
PyObject *data = NULL;
PyArrayObject *a = NULL, *r=NULL;
int strides=0, n=0, line=-1;
int flag, call_n, return_n;
FUNC_MESS_BEGIN();
if(! PyArg_ParseTuple(args, "O", &data)){
return NULL;
}
a = PyGSL_PyArray_PREPARE_gsl_vector_view(data, PyArray_DOUBLE, 0, -1, 1, NULL);
if(a == NULL)
return NULL;
n = a->dimensions[0];
call_n = n;
return_n = n;
/* Check if I got a return array */
r = (PyArrayObject *) PyGSL_Copy_Array(a);
if(r == NULL)
goto fail;
flag = PyGSL_STRIDE_RECALC(r->strides[0], sizeof(double), &strides);
if(flag != GSL_SUCCESS){
line = __LINE__ -2;
goto fail;
}
flag = transform(((double *)r->data), strides, call_n);
if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){
line = __LINE__ -2;
goto fail;
}
/* No rearange handled in a separate function ... */
Py_DECREF(a);
FUNC_MESS_END();
return (PyObject *) r;
fail:
FUNC_MESS("Fail");
PyGSL_add_traceback(module, filename, __FUNCTION__, line);
Py_XDECREF(a);
Py_XDECREF(r);
return NULL;
}
static PyObject *
PyGSL_complex_fft_(PyObject *self, PyObject *args, transform * transform, enum pygsl_fft_mode mode)
{
PyObject *data = NULL, *s_o= NULL, *t_o = NULL, *ret=NULL;
PyArrayObject *a = NULL, *r=NULL;
gsl_fft_complex_workspace *space=NULL;
gsl_fft_complex_wavetable *table=NULL;
int strides=0, n=0;
int free_space = 0, free_table=0, flag, call_n;
FUNC_MESS_BEGIN();
if(!PyArg_ParseTuple(args, "O|OOO", &data, &s_o, &t_o, &ret)){
return NULL;
}
a = PyGSL_PyArray_PREPARE_gsl_vector_view(data, PyArray_CDOUBLE, 0, -1, 1, NULL);
if(a == NULL)
goto fail;
n = a->dimensions[0];
call_n = n;
r = PyGSL_Shadow_array((PyObject *) ret, (PyObject *) a, mode);
if(r == NULL)
goto fail;
/*
* Return n is used to allocate an array, while call_n is the length passed on.
* This is necessary as the halfcomplex transform needs space to store the nyquist
* frequency.
*
* The following assert is protecting against surprises of missing space.
*/
/*
if(call_n > return_n){
fprintf(stderr, "In %s at Line %d call_n = %d, return_n = %d",
filename, __LINE__, call_n, return_n);
gsl_error("call_n larger than return_n!", filename, __LINE__ - 2, GSL_ESANITY); goto fail;
}
*/
if(s_o){
flag = PyGSL_complex_fft_work_space_check(s_o);
if(flag){
space = ((PyGSL_fft_space *) s_o)->space.cws;
} else {
gsl_error("Need a pygsl complex fft space!", filename, __LINE__, GSL_EINVAL);
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 5);
goto fail;
}
}
if(t_o){
flag = PyGSL_complex_fft_wave_table_check(t_o);
if(flag){
table = ((PyGSL_fft_space *) t_o) ->space.cwt;
} else {
gsl_error("Need a pygsl complex fft wave table!", filename, __LINE__, GSL_EINVAL);
PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 5);
goto fail;
}
}
/*
* Check, if I have to init the the tables
*/
if(space == NULL || table == NULL){
/* Store if I need to free these arrays */
free_space = (space == NULL) ? 1 : 0;
free_table = (table == NULL) ? 1 : 0;
if(!space) space = gsl_fft_complex_workspace_alloc(call_n);
if(!table) table = gsl_fft_complex_wavetable_alloc(call_n);
if(!space || !table)
goto fail;
}
flag = PyGSL_STRIDE_RECALC(r->strides[0], sizeof(double) * 2, &strides);
if(flag != GSL_SUCCESS){
goto fail;
}
DEBUG_MESS(2, "Array is at %p data at %p strides = %d length = %d", (void *) r, (void *) r->data,
r->strides[0], r->dimensions[0]);
DEBUG_MESS(2, "Starting a transform with an array of a size of %d and a stride of %d", call_n, strides);
flag = transform((double *) r->data, strides, call_n, table, space);
if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){
goto fail;
}
if(free_space == 1 && space != NULL) gsl_fft_complex_workspace_free(space);
if(free_table == 1 && table != NULL) gsl_fft_complex_wavetable_free(table);
Py_DECREF(a);
FUNC_MESS_END();
return (PyObject *) r;
fail:
FUNC_MESS("Fail");
Py_XDECREF(a);
Py_XDECREF(r);
if(free_space == 1 && space != NULL) gsl_fft_complex_workspace_free(space);
if(free_table == 1 && table != NULL) gsl_fft_complex_wavetable_free(table);
return NULL;
}
static PyObject *
PyGSL_complex_fft_radix2(PyObject *self, PyObject *args, transform_r2 * transform, enum pygsl_fft_mode mode)
{
PyObject *data = NULL, *ret=NULL;
PyArrayObject *a = NULL, *r=NULL;
int strides=0, n=0, flag;
FUNC_MESS_BEGIN();
if(!PyArg_ParseTuple(args, "O|O", &data, &ret)){
return NULL;
}
a = PyGSL_PyArray_PREPARE_gsl_vector_view(data, PyArray_CDOUBLE, 0, -1, 1, NULL);
if(a == NULL)
goto fail;
n = a->dimensions[0];
r = PyGSL_Shadow_array((PyObject *) ret, (PyObject *) a, mode);
if(r == NULL)
goto fail;
flag = PyGSL_STRIDE_RECALC(r->strides[0], sizeof(double) * 2, &strides);
if(flag != GSL_SUCCESS){
goto fail;
}
DEBUG_MESS(2, "Array is at %p data at %p strides = %d length = %d", (void *) r, (void *) r->data,
r->strides[0], r->dimensions[0]);
DEBUG_MESS(2, "Starting a transform with an array of a size of %d and a stride of %d", n, strides);
flag = transform((double *) r->data, strides, n);
if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){
goto fail;
}
Py_DECREF(a);
FUNC_MESS_END();
return (PyObject *) r;
fail:
FUNC_MESS("Fail");
Py_XDECREF(a);
Py_XDECREF(r);
return NULL;
}
/*
int gsl_fft_real_transform (double DATA[], size_t STRIDE,
size_t N, const gsl_fft_real_wavetable * WAVETABLE,
gsl_fft_real_workspace * WORK)
int gsl_fft_halfcomplex_transform (double DATA[], size_t
STRIDE, size_t N, const gsl_fft_halfcomplex_wavetable *
WAVETABLE, gsl_fft_real_workspace * WORK)
*/
#define PyGSL_COMPLEX(direction) \
static PyObject * \
PyGSL_complex_fft_ ## direction(PyObject *self, PyObject *args){\
PyObject *r;\
FUNC_MESS_BEGIN();\
r = PyGSL_complex_fft_(self, args, (transform * )gsl_fft_complex_ ## direction, MODE_DOUBLE); \
FUNC_MESS_END();\
return r;\
}
PyGSL_COMPLEX(forward)
PyGSL_COMPLEX(backward)
PyGSL_COMPLEX(inverse)
#define PyGSL_COMPLEX_RADIX2(direction) \
static PyObject * \
PyGSL_complex_fft_radix2_ ## direction(PyObject *self, PyObject *args){\
PyObject *r;\
FUNC_MESS_BEGIN();\
r = PyGSL_complex_fft_radix2(self, args, (transform_r2 * )gsl_fft_complex_radix2_ ## direction, MODE_DOUBLE); \
FUNC_MESS_END();\
return r;\
}
PyGSL_COMPLEX_RADIX2(forward)
PyGSL_COMPLEX_RADIX2(backward)
PyGSL_COMPLEX_RADIX2(inverse)
PyGSL_COMPLEX_RADIX2(dif_forward)
PyGSL_COMPLEX_RADIX2(dif_backward)
PyGSL_COMPLEX_RADIX2(dif_inverse)
#define PyGSL_REAL_RADIX2(direction) \
static PyObject * \
PyGSL_real_fft_radix2_ ## direction(PyObject *self, PyObject *args){\
PyObject *r;\
FUNC_MESS_BEGIN();\
r = PyGSL_fft_real_radix2(self, args, (transform_r2 * )gsl_fft_real_radix2_ ## direction, MODE_DOUBLE); \
FUNC_MESS_END();\
return r;\
}
PyGSL_REAL_RADIX2(transform)
#define PyGSL_REAL(direction) \
static PyObject * \
PyGSL_real_fft_ ## direction(PyObject *self, PyObject *args){\
PyObject *r;\
FUNC_MESS_BEGIN();\
r = PyGSL_fft_real(self, args, (transform * )gsl_fft_real_ ## direction, MODE_DOUBLE); \
FUNC_MESS_END();\
return r;\
}
PyGSL_REAL(transform)
#define PyGSL_HALFCOMPLEX(direction) \
static PyObject * \
PyGSL_halfcomplex_fft_ ## direction(PyObject *self, PyObject *args){\
return PyGSL_fft_halfcomplex(self, args, (transform * )gsl_fft_halfcomplex_ ## direction, MODE_DOUBLE); \
}
PyGSL_HALFCOMPLEX(transform)
PyGSL_HALFCOMPLEX(inverse)
#define PyGSL_HALFCOMPLEX_RADIX2(direction) \
static PyObject * \
PyGSL_halfcomplex_fft_radix2_ ## direction(PyObject *self, PyObject *args){\
return PyGSL_fft_halfcomplex_radix2(self, args, (transform_r2 * )gsl_fft_halfcomplex_radix2_ ## direction, MODE_DOUBLE); \
}
PyGSL_HALFCOMPLEX_RADIX2(transform)
PyGSL_HALFCOMPLEX_RADIX2(inverse)
static const char fft_module_doc[] = "\
Wrapper for the FFT Module of the GSL Library\n\
\n\
";
static const char cws_doc[] = "\
Complex Workspace\n\
\n\
Needed as working space for mixed radix routines.\n\
\n\
Input:\n\
n ... Length of the data to transform\n\
";
static const char cwt_doc[] = "\
Complex Wavetable\n\
\n\
Stores the precomputed trigonometric functions\n\
Input:\n\
n ... Length of the data to transform\n\
";
static const char rws_doc[] = "\
Real Workspace\n\
\n\
Needed as working space for mixed radix routines.\n\
\n\
Input:\n\
n ... Length of the data to transform\n\
";
static const char rwt_doc[] = "\
Real Wavetable\n\
\n\
Stores the precomputed trigonometric functions\n\
Input:\n\
n ... Length of the data to transform\n\
";
static const char hcwt_doc[] = "\
Half Complex Wavetable\n\
\n\
Stores the precomputed trigonometric functions\n\
Input:\n\
n ... Length of the data to transform\n\
";
#define TRANSFORM_INPUT "\
Input:\n\
data ... an array of complex numbers\n\
\n\
Optional Input:\n\
If these objects are not provided, they will be generated by the\n\
function automatically.\n\
\n\
space ... a workspace of approbriate type and size\n\
table ... a wavetable of approbriate type and size\n\
output ... array to store the output into. GSL computes the FFT\n\
in place. So if this array is provided, the wrapper\n\
will use this array as output array. If the input and\n\
output array are identical no internal copy will be\n\
made. \n\
This works only for the complex transform types!\n"
#define TRANSFORM_INPUT_RADIX2 "\
Input:\n\
data ... an array of complex numbers\n\
\n\
Optional Input:\n\
If these objects are not provided, they will be generated by the\n\
function automatically.\n\
\n\
output ... array to store the output into. GSL computes the FFT\n\
in place. So if this array is provided, the wrapper\n\
will use this array as output array. If the input and\n\
output array are identical no internal copy will be\n\
made. \n\
This works only for the complex transform types!\n"
#define TRANSFORM_INPUT_REAL "\
Input:\n\
data ... an array of real numbers\n\
\n\
Optional Input:\n\
If these objects are not provided, they will be generated by the\n\
function automatically.\n\
\n\
space ... a workspace of approbriate type and size\n\
table ... a wavetable of approbriate type and size\n\
output ... array to store the output into. GSL computes the FFT\n\
in place. So if this array is provided, the wrapper\n\
will use this array as output array. If the input and\n\
output array are identical no internal copy will be\n\
made. \n\
This works only for the complex transform types!\n"
#define TRANSFORM_INPUT_REAL_RADIX2 "\
Input:\n\
data ... an array of real numbers\n\
\n\
Output:\n\
the transformed data in its special storage. Halfcomplex data\n\
in an real array. Use halfcomplex_radix2_unpack to transform it\n\
into an approbriate complex array.\n\
"
#define TRANSFORM_INPUT_HALFCOMPLEX "\
Input:\n\
data ... an array of complex numbers\n\
\n\
Optional Input:\n\
If these objects are not provided, they will be generated by the\n\
function automatically.\n\
\n\
n ... length of the real array. From the complex input I can not\n\
compute the original length if it was odd or even. Thus I \n\
allow to give the input here. If not given the routine will guess\n\
the input length. If the last imaginary part is zero it will\n\
assume an real output array of even length\n\
space ... a workspace of approbriate type and size\n\
table ... a wavetable of approbriate type and size\n\
eps ... epsilon to use in the comparisons (default 1e-8)\n\
"
#define TRANSFORM_INPUT_HALFCOMPLEX_RADIX2 "\
Input:\n\
data ... an array of real data containing the complex data\n\
as required by this transform. See the GSL Reference Document\n\
\n\
"
static const char cf_doc[] = "\
Complex forward transform\n\
" TRANSFORM_INPUT;
static const char cb_doc[] = "\
Complex backward transform\n\
\n\
The output is not scaled!\n\
" TRANSFORM_INPUT;
static const char ci_doc[] = "\
Complex inverse transform\n\
\n\
The output is to scale.\n\
" TRANSFORM_INPUT;
static const char cf_doc_r2[] = "\
Complex forward radix2 transform\n\
" TRANSFORM_INPUT_RADIX2;
static const char cb_doc_r2[] = "\
Complex backward radix2 transform\n\
\n\
The output is not scaled!\n\
" TRANSFORM_INPUT_RADIX2;
static const char ci_doc_r2[] = "\
Complex inverse radix2 transform\n\
\n\
The output is to scale.\n\
" TRANSFORM_INPUT_RADIX2;
static const char cf_doc_r2_dif[] = "\
Complex forward radix2 decimation-in-frequency transform\n\
" TRANSFORM_INPUT_RADIX2;
static const char cb_doc_r2_dif[] = "\
Complex backward radix2 decimation-in-frequency transform\n\
\n\
The output is not scaled!\n\
" TRANSFORM_INPUT_RADIX2;
static const char ci_doc_r2_dif[] = "\
Complex inverse radix2 decimation-in-frequency transform\n\
\n\
The output is to scale.\n\
" TRANSFORM_INPUT_RADIX2;
static const char rt_doc[] = "\
Real transform\n\
" TRANSFORM_INPUT_REAL;
static const char hc_doc[] = "\
Half complex transform\n\
\n\
The output is not scaled!\n\
" TRANSFORM_INPUT_HALFCOMPLEX;
static const char hi_doc[] = "\
Half complex inverse\n\
" TRANSFORM_INPUT_HALFCOMPLEX;
static const char rt_doc_r2[] = "\
Real radix2 transform\n\
" TRANSFORM_INPUT_REAL_RADIX2;
static const char hc_doc_r2[] = "\
Half complex radix2 transform\n\
\n\
The output is not scaled!\n\
" TRANSFORM_INPUT_HALFCOMPLEX_RADIX2;
static const char hi_doc_r2[] = "\
Half complex radix2 inverse\n\
" TRANSFORM_INPUT_HALFCOMPLEX_RADIX2;
static const char un_doc_r2[] = "\
Unpack the frequency data from the output of a real radix 2 transform to an approbriate complex array.\n\
";
static PyMethodDef fftMethods[] = {
{"complex_workspace", PyGSL_fft_space_init_COMPLEX_WORKSPACE, METH_VARARGS, (char*)cws_doc},
{"complex_wavetable", PyGSL_fft_space_init_COMPLEX_WAVETABLE, METH_VARARGS, (char*)cwt_doc},
{"real_workspace", PyGSL_fft_space_init_REAL_WORKSPACE, METH_VARARGS, (char*)rws_doc},
{"real_wavetable", PyGSL_fft_space_init_REAL_WAVETABLE, METH_VARARGS, (char*)rwt_doc},
{"halfcomplex_wavetable", PyGSL_fft_space_init_HALFCOMPLEX_WAVETABLE, METH_VARARGS, (char*)hcwt_doc},
{"complex_workspace_float", PyGSL_fft_space_init_COMPLEX_WORKSPACE_FLOAT, METH_VARARGS, (char*)cws_doc},
{"complex_wavetable_float", PyGSL_fft_space_init_COMPLEX_WAVETABLE_FLOAT, METH_VARARGS, (char*)cwt_doc},
{"real_workspace_float", PyGSL_fft_space_init_REAL_WORKSPACE_FLOAT, METH_VARARGS, (char*)rws_doc},
{"real_wavetable_float", PyGSL_fft_space_init_REAL_WAVETABLE_FLOAT, METH_VARARGS, (char*)rwt_doc},
{"halfcomplex_wavetable_float", PyGSL_fft_space_init_HALFCOMPLEX_WAVETABLE_FLOAT, METH_VARARGS, (char*)hcwt_doc},
{"complex_forward", PyGSL_complex_fft_forward, METH_VARARGS, (char*)cf_doc},
{"complex_backward", PyGSL_complex_fft_backward, METH_VARARGS, (char*)cb_doc},
{"complex_inverse", PyGSL_complex_fft_inverse, METH_VARARGS, (char*)ci_doc},
{"complex_radix2_forward", PyGSL_complex_fft_radix2_forward, METH_VARARGS, (char*)cf_doc_r2},
{"complex_radix2_backward", PyGSL_complex_fft_radix2_backward, METH_VARARGS, (char*)cb_doc_r2},
{"complex_radix2_inverse", PyGSL_complex_fft_radix2_inverse, METH_VARARGS, (char*)ci_doc_r2},
{"complex_radix2_dif_forward", PyGSL_complex_fft_radix2_dif_forward, METH_VARARGS, (char*)cf_doc_r2_dif},
{"complex_radix2_dif_backward", PyGSL_complex_fft_radix2_dif_backward, METH_VARARGS, (char*)cb_doc_r2_dif},
{"complex_radix2_dif_inverse", PyGSL_complex_fft_radix2_dif_inverse, METH_VARARGS, (char*)ci_doc_r2_dif},
{"real_transform", PyGSL_real_fft_transform, METH_VARARGS, (char*)rt_doc},
{"halfcomplex_transform", PyGSL_halfcomplex_fft_transform, METH_VARARGS, (char*)hc_doc},
{"halfcomplex_inverse", PyGSL_halfcomplex_fft_inverse, METH_VARARGS, (char*)hi_doc},
{"real_radix2_transform", PyGSL_real_fft_radix2_transform, METH_VARARGS, (char*)rt_doc_r2},
{"halfcomplex_radix2_transform",PyGSL_halfcomplex_fft_radix2_transform,METH_VARARGS, (char*)hc_doc_r2},
{"halfcomplex_radix2_inverse", PyGSL_halfcomplex_fft_radix2_inverse, METH_VARARGS, (char*)hi_doc_r2},
{"halfcomplex_radix2_unpack", PyGSL_fft_halfcomplex_radix2_unpack, METH_VARARGS, (char*)un_doc_r2},
{NULL, NULL} /* Sentinel */
};
DL_EXPORT(void) initfft(void)
{
PyObject *m = NULL, *dict = NULL, *item = NULL;
PyGSL_fft_space_pytype.ob_type = &PyType_Type;
m = Py_InitModule("fft", fftMethods);
module = m;
import_array();
init_pygsl();
if (m == NULL)
return;
dict = PyModule_GetDict(m);
if (dict == NULL)
return;
if (!(item = PyString_FromString(fft_module_doc))){
PyErr_SetString(PyExc_ImportError,
"I could not generate module doc string!");
return;
}
if (PyDict_SetItemString(dict, "__doc__", item) != 0){
PyErr_SetString(PyExc_ImportError,
"I could not init doc string!");
return;
}
return;
}
/*
* Local Variables:
* mode: C
* c-file-style: "python"
* End:
*/
| {
"alphanum_fraction": 0.6679639571,
"avg_line_length": 31.4785757393,
"ext": "c",
"hexsha": "889c3bcfae77f9c58a877c8b7f1bd013f207bbfd",
"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/testing/src/fftfloatmodule.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/testing/src/fftfloatmodule.c",
"max_line_length": 127,
"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/testing/src/fftfloatmodule.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 15738,
"size": 52160
} |
// Sammlung verwendeter Funktionen
#include "global.h"
#include "targets.h"
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_gamma.h>
#include <math.h>
#include <stdio.h>
#include "utility.h"
#include <string.h>
#include <time.h>
#include <omp.h>
int Get_Lattice_Targets_Center_Circle( int *pos, double *targets, // leaves esc_cell radius free
double lattice_spacing, int escape_cells) // targets one in cell center
{
int ret_value = 0; //leave starting cell empty, else particle starts in Target
if ( (pos[0] == 0)&&
(pos[1] == 0)
)
{
ret_value = 0; //catch mistake if zero cell was still supposed to have target
return (ret_value);
}
if (pos[0] * pos[0] + pos[1] * pos[1] > escape_cells * escape_cells ) //If outside circle
{
ret_value = 1; //single target center cell
targets[0] = pos[0] * lattice_spacing;
targets[1] = pos[1] * lattice_spacing;
return (ret_value);
}
return (ret_value);
}
int Get_Lattice_Targets_PORE_3( int *pos, double *targets, // leaves esc_cell radius free
double lattice_spacing, int escape_cells) // targets one in cell center
{
double corner_vec[2];
int corner = 0;
//corner one oben links
for (double i_x = -1.0; i_x < 2.0; i_x+= 2.0)
{
for (double i_y = -1.0; i_y < 2.0; i_y+= 2.0)
{
int stride = 2 * corner * (NUMBER_PORE_OBSTACLES + 1);
corner_vec[0] = (pos[0] + i_x *0.5) * LATTICE_SPACING;
corner_vec[1] = (pos[1] + i_y *0.5) * LATTICE_SPACING;
targets[0 + stride] = corner_vec[0];
targets[1 + stride] = corner_vec[1];
for (int i_pore = 0; i_pore < NUMBER_PORE_OBSTACLES; i_pore++)
{
targets[2 + stride + i_pore * 4] = corner_vec[0] - i_x * TARGET_LENGTH * (i_pore + 1);
targets[3 + stride + i_pore * 4] = corner_vec[1];
targets[4 + stride + i_pore * 4] = corner_vec[0];
targets[5 + stride + i_pore * 4] = corner_vec[1] - i_y * TARGET_LENGTH * (i_pore + 1);
}
corner++;
}
corner++;
}
return (4 *(1 + 2* NUMBER_PORE_OBSTACLES));
}
int Get_Lattice_Targets_Center_Square( int *pos, double *targets, // leaves esc_cell^2 square free
double lattice_spacing, int escape_cells) // targets one in cell center
{
int ret_value = 0; //leave starting cell empty, else particle starts in Target
if ( (pos[0] == 0)&&
(pos[1] == 0)
)
{
ret_value = 0; //catch mistake if zero cell was still supposed to have target
return (ret_value);
}
if ( (abs(pos[0]) > escape_cells)||
(abs(pos[1]) > escape_cells)
)
{
ret_value = 1; //single target center cell
targets[0] = pos[0] * lattice_spacing;
targets[1] = pos[1] * lattice_spacing;
return (ret_value);
}
return (ret_value);
}
int Get_Lattice_Targets_Corner_Square( int *pos, double *targets,
double lattice_spacing, int escape_cells)
// get target vectors for corner, middle or porous region. save in targest[4*DIM], return number targets
{
int ret_value = 0;
if(escape_cells == 0) // catch case no free cells
{
ret_value = 4; // 4 targets per lattice cell
int count = -1;
for (int i = -1; i< 2; i+=2) //i,j in (-1,1)
{
for (int j = -1; j< 2; j+=2)
{
count++;
targets[0 + count * DIM] = i * lattice_spacing/2.0 + pos[0] * lattice_spacing;
targets[1 + count * DIM] = j * lattice_spacing/2.0 + pos[1] * lattice_spacing;
}
}
return (ret_value);
}
// check porous are
if( (abs(pos[0]) > escape_cells)||
(abs(pos[1]) > escape_cells) )
{
ret_value = 4; // 4 targets per lattice cell
int count = -1;
for (int i = -1; i< 2; i+=2) //i,j in (-1,1)
{
for (int j = -1; j< 2; j+=2)
{
count++;
targets[0 + count * DIM] = i * lattice_spacing/2.0 + pos[0] * lattice_spacing;
targets[1 + count * DIM] = j * lattice_spacing/2.0 + pos[1] * lattice_spacing;
}
}
return (ret_value);
}
//Check corner
for (int i = -1; i< 2; i+=2) //i,j in (-1,1)
{
for (int j = -1; j< 2; j+=2)
{
if( (pos[0] == i * escape_cells)&&
(pos[1] == j * escape_cells))
{
ret_value = 3; // corner and two sides
targets[0] = i * lattice_spacing/2.0 + pos[0] * lattice_spacing; //corner
targets[1] = j * lattice_spacing/2.0 + pos[1] * lattice_spacing;
targets[2] = i * (-1) * lattice_spacing/2.0 + pos[0] * lattice_spacing; //first side
targets[3] = j * lattice_spacing/2.0 + pos[1] * lattice_spacing;
targets[4] = i * lattice_spacing/2.0 + pos[0] * lattice_spacing; //first side
targets[5] = j * (-1) * lattice_spacing/2.0 + pos[1] * lattice_spacing;
return (ret_value);
} // corner
}
}
// check sides after sure you are not in corner
for( int d = 0; d < DIM; d++)// loop over dimension
{
int e = 1-d;
for (int i = -1; i< 2; i+=2)
{
if(pos[d] == i * escape_cells)
{
ret_value = 2; //two sides
targets[d] = i * lattice_spacing/2.0 + pos[d] * lattice_spacing;
targets[e] = (-1) * lattice_spacing/2.0 + pos[e] * lattice_spacing;
targets[d +DIM] = i * lattice_spacing/2.0 + pos[d] * lattice_spacing;
targets[e +DIM] = (1) * lattice_spacing/2.0 + pos[e] * lattice_spacing;
return (ret_value);
}
}
}
return (ret_value);
} | {
"alphanum_fraction": 0.6188349515,
"avg_line_length": 31.0240963855,
"ext": "c",
"hexsha": "82e5dae58f4807acf988a34b34f44b88870b6639",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_forks_repo_path": "targets.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_issues_repo_path": "targets.c",
"max_line_length": 104,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nowottnm/KAC_ZWANZIG_SIM",
"max_stars_repo_path": "targets.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1845,
"size": 5150
} |
/**************************************************************************/
/* Common definitions for the c vader routines */
/**************************************************************************/
/**************************************************************************/
/* General note on naming conventions: arrays without subscripts have */
/* indices that range from 0 to nr-1, with no ghost zones, and are cell- */
/* centered. Arrays with _h are edge centered and have indices that run */
/* from 0 to nr. Arrays with _g are cell-centered with one ghost zone, */
/* and have indices that go from 0 to nr+1; indices 0 and nr are the */
/* ghost zones. */
/**************************************************************************/
#ifndef _vader_common_h_
#define _vader_common_h_
#include <gsl/gsl_vector.h>
#include <float.h>
#include <stdbool.h>
#include <time.h>
/* Slope limit parameter */
#define SLOPELIMIT 0.1
/* Descriptor for a grid */
typedef struct {
unsigned long nr; /* Number of real cells */
bool linear; /* Is this a linear or logarithmic grid? */
double *r_g, *r_h; /* Cell center, edge locations */
double *dr_g; /* Cell sizes / log sizes */
double *area; /* Area of a zone */
double *vphi_g, *vphi_h; /* Rotation curve */
double *beta_g, *beta_h; /* Logarithmic index of rotation curve */
double *psiEff_g, *psiEff_h; /* Effective gravitational potential */
double *g_h; /* Factor appearing in derivatives */
} grid;
/* Workspace for calculations */
typedef struct {
double *pres_g, *presNew_g, *colNew, *colTmp;
double *alpha_g, *hint_g, *hintL_g, *hintR_g;
double *ppmwksp_g;
double *fmLast_h, *fmNew_h;
double *ftLast_h, *feLast_h;
double *massSrcLast, *massSrcNew, *intEnSrc;
double *eIntTmp, *eIntNew;
double *gammaLast, *deltaLast, *gammaNew, *deltaNew;
double *mSrc, *eSrc;
gsl_vector *ud_g, *ld_g, *diag_g, *rhs_g, *presTmp_g;
#if AA_M > 0
double *colHist, *presHist, *eIntHist;
double *colResid, *presResid, *eIntResid;
gsl_vector *constraint;
#endif
} wksp;
/* Pressure boundary condition types */
typedef enum { FIXED_MASS_FLUX, FIXED_TORQUE_FLUX, FIXED_TORQUE }
pres_bc_type;
/* Enthalpy boundary condition types */
typedef enum { FIXED_ENTHALPY_VALUE, FIXED_ENTHALPY_GRADIENT }
enth_bc_type;
/* IO status indicators */
typedef enum { GOOD_IO, IO_ERROR, ALLOCATION_ERROR } iostatus;
/* Startup status indicators */
typedef enum { GOOD_START, RESTART_ERROR, MEMORY_ERROR, FIRST_DT_ERROR }
setup_status;
/* Simulation status indicators */
typedef enum { RUNNING, NORMAL_EXIT, ZENO_ERROR, TOO_MANY_STEPS }
status;
/* Macros used various places in code */
#define SQR(x) ((x)*(x))
#define LARGE DBL_MAX
#define SMALL DBL_MIN
#endif
/* end _vader_common_h_ */
| {
"alphanum_fraction": 0.5941295547,
"avg_line_length": 35.2857142857,
"ext": "h",
"hexsha": "a1c382acf517db0bc745c09dfa9e1d7e4c6a72d6",
"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": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "franciscaconcha/amuse-vader",
"max_forks_repo_path": "src/amuse/community/vader/src/vader_common.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"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": "franciscaconcha/amuse-vader",
"max_issues_repo_path": "src/amuse/community/vader/src/vader_common.h",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "franciscaconcha/amuse-vader",
"max_stars_repo_path": "src/amuse/community/vader/src/vader_common.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 721,
"size": 2964
} |
/*
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 steps.c
* \brief Source file with common variables and functions to optimize
* multi-steps methods.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2011-2019.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.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"
#include "optimize.h"
#include "steps.h"
#define a0(x) x[0]
///< a0 multi-steps coefficient.
#define b0(x) x[1]
///< b0 multi-steps coefficient.
#define a1(x) x[2]
///< a1 multi-steps coefficient.
#define b1(x) x[3]
///< b1 multi-steps coefficient.
#define a2(x) x[4]
///< a2 multi-steps coefficient.
#define b2(x) x[5]
///< b2 multi-steps coefficient.
#define a3(x) x[6]
///< a3 multi-steps coefficient.
#define b3(x) x[7]
///< b3 multi-steps coefficient.
#define a4(x) x[8]
///< a4 multi-steps coefficient.
#define b4(x) x[9]
///< b4 multi-steps coefficient.
#define a5(x) x[10]
///< a5 multi-steps coefficient.
#define b5(x) x[11]
///< b5 multi-steps coefficient.
#define a6(x) x[12]
///< a6 multi-steps coefficient.
#define b6(x) x[13]
///< b6 multi-steps coefficient.
#define a7(x) x[14]
///< a7 multi-steps coefficient.
#define b7(x) x[15]
///< b7 multi-steps coefficient.
#define a8(x) x[16]
///< a8 multi-steps coefficient.
#define b8(x) x[17]
///< b8 multi-steps coefficient.
#define a9(x) x[18]
///< a9 multi-steps coefficient.
#define b9(x) x[19]
///< b9 multi-steps coefficient.
#define a10(x) x[20]
///< a10 multi-steps coefficient.
#define b10(x) x[21]
///< b10 multi-steps coefficient.
#define a11(x) x[22]
///< a11 multi-steps coefficient.
#define b11(x) x[23]
///< b11 multi-steps coefficient.
#define a12(x) x[24]
///< a12 multi-steps coefficient.
#define b12(x) x[25]
///< b12 multi-steps coefficient.
#define c(a, b) (b / a)
///< macro to calculate the c multi-steps coefficients.
#define c0(x) (c(a0(x), b0(x)))
///< c0 multi-steps coefficient.
#define c1(x) (c(a1(x), b1(x)))
///< c1 multi-steps coefficient.
#define c2(x) (c(a2(x), b2(x)))
///< c2 multi-steps coefficient.
#define c3(x) (c(a3(x), b3(x)))
///< c3 multi-steps coefficient.
#define c4(x) (c(a4(x), b4(x)))
///< c4 multi-steps coefficient.
#define c5(x) (c(a5(x), b5(x)))
///< c5 multi-steps coefficient.
#define c6(x) (c(a6(x), b6(x)))
///< c6 multi-steps coefficient.
#define c7(x) (c(a7(x), b7(x)))
///< c7 multi-steps coefficient.
#define c8(x) (c(a8(x), b8(x)))
///< c8 multi-steps coefficient.
#define c9(x) (c(a9(x), b9(x)))
///< c9 multi-steps coefficient.
#define c10(x) (c(a10(x), b10(x)))
///< c10 multi-steps coefficient.
#define c11(x) (c(a11(x), b11(x)))
///< c11 multi-steps coefficient.
#define c12(x) (c(a11(x), b11(x)))
///< c12 multi-steps coefficient.
/**
* Function to get the coefficients on a 3 steps 2nd order multi-steps method.
*/
static int
steps_3_2 (Optimize * optimize) ///< Optimize struct.
{
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
b2 (x) = r[2];
b1 (x) = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) - 1.L);
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) - b1 (x) - b2 (x);
a0 (x) = 1.L - a1 (x) - a2 (x);
return 1;
}
/**
* Function to get the coefficients on a 3 steps 3th order multi-steps method.
*/
static int
steps_3_3 (Optimize * optimize) ///< Optimize struct.
{
long double A[2], B[2], C[2];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
A[0] = 2.L;
B[0] = 4.L;
C[0] = -1.L + a1 (x) + 4.L * a2 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 1.L + a1 (x) + 8.L * a2 (x);
solve_2 (A, B, C);
b2 (x) = C[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = C[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) - b1 (x) - b2 (x);
a0 (x) = 1.L - a1 (x) - a2 (x);
return 1;
}
/**
* Function to get the coefficients on a 4 steps 2nd order multi-steps method.
*/
static int
steps_4_2 (Optimize * optimize) ///< Optimize struct.
{
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
b3 (x) = r[3];
b2 (x) = r[4];
b1 (x) =
0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x) - 6.L * b3 (x) -
1.L);
b0 (x) =
1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) - b1 (x) - b2 (x) - b3 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x);
return 1;
}
/**
* Function to get the coefficients on a 4 steps 3th order multi-steps method.
*/
static int
steps_4_3 (Optimize * optimize) ///< Optimize struct.
{
long double A[2], B[2], C[2];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
b3 (x) = r[3];
A[0] = 2.L;
B[0] = 4.L;
C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) - 6.L * b3 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x));
solve_2 (A, B, C);
b2 (x) = C[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = C[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) - b1 (x) - b2 (x)
- b3 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x);
return 1;
}
/**
* Function to get the coefficients on a 4 steps 4th order multi-steps method.
*/
static int
steps_4_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[3], B[3], C[3], D[3];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x);
solve_3 (A, B, C, D);
b3 (x) = D[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = D[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = D[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) - b1 (x) - b2 (x)
- b3 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x);
return 1;
}
/**
* Function to get the coefficients on a 5 steps 2nd order multi-steps method.
*/
static int
steps_5_2 (Optimize * optimize) ///< Optimize struct.
{
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
b4 (x) = r[4];
b3 (x) = r[5];
b2 (x) = r[6];
b1 (x) = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)
+ 16.L * a4 (x) - 6.L * b3 (x) - 8.L * b4 (x) - 1.L);
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x) - b1 (x)
- b2 (x) - b3 (x) - b4 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x);
return 1;
}
/**
* Function to get the coefficients on a 5 steps 3th order multi-steps method.
*/
static int
steps_5_3 (Optimize * optimize) ///< Optimize struct.
{
long double A[2], B[2], C[2];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
b4 (x) = r[4];
b3 (x) = r[5];
A[0] = 2.L;
B[0] = 4.L;
C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
- 6.L * b3 (x) - 8.L * b4 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)
- 48.L * b4 (x);
solve_2 (A, B, C);
b2 (x) = C[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = C[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x) - b1 (x)
- b2 (x) - b3 (x) - b4 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x);
return 1;
}
/**
* Function to get the coefficients on a 5 steps 4th order multi-steps method.
*/
static int
steps_5_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[3], B[3], C[3], D[3];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
b4 (x) = r[4];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
- 8.L * b4 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
- 48.L * b4 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)
+ 256.L * (a4 (x) - b4 (x));
solve_3 (A, B, C, D);
b3 (x) = D[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = D[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = D[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x) - b1 (x)
- b2 (x) - b3 (x) - b4 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x);
return 1;
}
/**
* Function to get the coefficients on a 5 steps 5th order multi-steps method.
*/
static int
steps_5_5 (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x);
solve_4 (A, B, C, D, E);
b4 (x) = E[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = E[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = E[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = E[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x) - b1 (x)
- b2 (x) - b3 (x) - b4 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x);
return 1;
}
/**
* Function to get the coefficients on a 6 steps 2nd order multi-steps method.
*/
static int
steps_6_2 (Optimize * optimize) ///< Optimize struct.
{
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
b5 (x) = r[5];
b4 (x) = r[6];
b3 (x) = r[7];
b2 (x) = r[8];
b1 (x) = 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)
+ 16.L * a4 (x) + 25.L * a5 (x) - 6.L * b3 (x) - 8.L * b4 (x)
- 10.L * b5 (x) - 1.L);
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x);
return 1;
}
/**
* Function to get the coefficients on a 6 steps 3th order multi-steps method.
*/
static int
steps_6_3 (Optimize * optimize) ///< Optimize struct.
{
long double A[2], B[2], C[2];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
b5 (x) = r[5];
b4 (x) = r[6];
b3 (x) = r[7];
A[0] = 2.L;
B[0] = 4.L;
C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) - 6.L * b3 (x) - 8.L * b4 (x) - 10.L * b5 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)
+ 125.L * a5 (x) - 48.L * b4 (x) - 75.L * b5 (x);
solve_2 (A, B, C);
b2 (x) = C[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = C[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x);
return 1;
}
/**
* Function to get the coefficients on a 6 steps 4th order multi-steps method.
*/
static int
steps_6_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[3], B[3], C[3], D[3];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
b5 (x) = r[5];
b4 (x) = r[6];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) - 8.L * b4 (x) - 10.L * b5 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) - 48.L * b4 (x) - 75.L * b5 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)
+ 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) - 500.L * b5 (x);
solve_3 (A, B, C, D);
b3 (x) = D[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = D[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = D[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x);
return 1;
}
/**
* Function to get the coefficients on a 6 steps 5th order multi-steps method.
*/
static int
steps_6_5 (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
b5 (x) = r[5];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) - 10.L * b5 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) - 75.L * b5 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) - 500.L * b5 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * (a5 (x) - b5 (x));
solve_4 (A, B, C, D, E);
b4 (x) = E[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = E[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = E[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = E[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x);
return 1;
}
/**
* Function to get the coefficients on a 6 steps 6th order multi-steps method.
*/
static int
steps_6_6 (Optimize * optimize) ///< Optimize struct.
{
long double A[5], B[5], C[5], D[5], E[5], F[5];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x);
solve_5 (A, B, C, D, E, F);
b5 (x) = F[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = F[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = F[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = F[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = F[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x);
return 1;
}
/**
* Function to get the coefficients on a 7 steps 2nd order multi-steps method.
*/
static int
steps_7_2 (Optimize * optimize) ///< Optimize struct.
{
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
b6 (x) = r[6];
b5 (x) = r[7];
b4 (x) = r[8];
b3 (x) = r[9];
b2 (x) = r[10];
b1 (x)
= 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x) - 6.L * b3 (x) - 8.L * b4 (x)
- 10.L * b5 (x) - 12.L * b6 (x) - 1.L);
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x)
- b6 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x);
return 1;
}
/**
* Function to get the coefficients on a 7 steps 3th order multi-steps method.
*/
static int
steps_7_3 (Optimize * optimize) ///< Optimize struct.
{
long double A[2], B[2], C[2];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
b6 (x) = r[6];
b5 (x) = r[7];
b4 (x) = r[8];
b3 (x) = r[9];
A[0] = 2.L;
B[0] = 4.L;
C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x) - 6.L * b3 (x) - 8.L * b4 (x)
- 10.L * b5 (x) - 12.L * b6 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) - 48.L * b4 (x) - 75.L * b5 (x)
- 108.L * b6 (x);
solve_2 (A, B, C);
b2 (x) = C[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = C[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x)
- b6 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x);
return 1;
}
/**
* Function to get the coefficients on a 7 steps 4th order multi-steps method.
*/
static int
steps_7_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[3], B[3], C[3], D[3];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
b6 (x) = r[6];
b5 (x) = r[7];
b4 (x) = r[8];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x) - 8.L * b4 (x) - 10.L * b5 (x)
- 12.L * b6 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) - 48.L * b4 (x) - 75.L * b5 (x)
- 108.L * b6 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)
+ 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)
- 500.L * b5 (x) - 864.L * b6 (x);
solve_3 (A, B, C, D);
b3 (x) = D[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = D[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = D[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x)
- b6 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x);
return 1;
}
/**
* Function to get the coefficients on a 7 steps 5th order multi-steps method.
*/
static int
steps_7_5 (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
b6 (x) = r[6];
b5 (x) = r[7];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x) - 10.L * b5 (x) - 12.L * b6 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) - 75.L * b5 (x) - 108.L * b6 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) - 500.L * b5 (x) - 864.L * b6 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) - 6480.L * b6 (x);
solve_4 (A, B, C, D, E);
b4 (x) = E[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = E[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = E[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = E[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x)
- b6 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x);
return 1;
}
/**
* Function to get the coefficients on a 7 steps 6th order multi-steps method.
*/
static int
steps_7_6 (Optimize * optimize) ///< Optimize struct.
{
long double A[5], B[5], C[5], D[5], E[5], F[5];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
b6 (x) = r[6];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x) - 12.L * b6 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) - 108.L * b6 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) - 864.L * b6 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) - 6480.L * b6 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x));
solve_5 (A, B, C, D, E, F);
b5 (x) = F[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = F[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = F[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = F[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = F[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x)
- b6 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x);
return 1;
}
/**
* Function to get the coefficients on a 7 steps 7th order multi-steps method.
*/
static int
steps_7_7 (Optimize * optimize) ///< Optimize struct.
{
long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x);
solve_6 (A, B, C, D, E, F, G);
b6 (x) = G[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = G[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = G[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = G[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = G[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = G[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x)
- b6 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x);
return 1;
}
/**
* Function to get the coefficients on a 8 steps 2nd order multi-steps method.
*/
static int
steps_8_2 (Optimize * optimize) ///< Optimize struct.
{
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
b7 (x) = r[7];
b6 (x) = r[8];
b5 (x) = r[9];
b4 (x) = r[10];
b3 (x) = r[11];
b2 (x) = r[12];
b1 (x)
= 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) - 6.L * b3 (x)
- 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x)
- 1.L);
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)
- b4 (x) - b5 (x) - b6 (x) - b7 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);
return 1;
}
/**
* Function to get the coefficients on a 8 steps 3th order multi-steps method.
*/
static int
steps_8_3 (Optimize * optimize) ///< Optimize struct.
{
long double A[2], B[2], C[2];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
b7 (x) = r[7];
b6 (x) = r[8];
b5 (x) = r[9];
b4 (x) = r[10];
b3 (x) = r[11];
A[0] = 2.L;
B[0] = 4.L;
C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) - 6.L * b3 (x)
- 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) - 48.L * b4 (x)
- 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x);
solve_2 (A, B, C);
b2 (x) = C[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = C[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)
- b4 (x) - b5 (x) - b6 (x) - b7 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);
return 1;
}
/**
* Function to get the coefficients on a 8 steps 4th order multi-steps method.
*/
static int
steps_8_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[3], B[3], C[3], D[3];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
b7 (x) = r[7];
b6 (x) = r[8];
b5 (x) = r[9];
b4 (x) = r[10];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) - 8.L * b4 (x)
- 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) - 48.L * b4 (x)
- 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)
+ 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)
+ 2401.L * a7 (x) - 500.L * b5 (x) - 864.L * b6 (x) - 1372.L * b7 (x);
solve_3 (A, B, C, D);
b3 (x) = D[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = D[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = D[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)
- b4 (x) - b5 (x) - b6 (x) - b7 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);
return 1;
}
/**
* Function to get the coefficients on a 8 steps 5th order multi-steps method.
*/
static int
steps_8_5 (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
b7 (x) = r[7];
b6 (x) = r[8];
b5 (x) = r[9];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) - 10.L * b5 (x)
- 12.L * b6 (x) - 14.L * b7 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) - 75.L * b5 (x)
- 108.L * b6 (x) - 147.L * b7 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) - 500.L * b5 (x)
- 864.L * b6 (x) - 1372.L * b7 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) + 16807.L * a7 (x)
- 6480.L * b6 (x) - 12005.L * b7 (x);
solve_4 (A, B, C, D, E);
b4 (x) = E[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = E[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = E[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = E[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)
- b4 (x) - b5 (x) - b6 (x) - b7 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);
return 1;
}
/**
* Function to get the coefficients on a 8 steps 6th order multi-steps method.
*/
static int
steps_8_6 (Optimize * optimize) ///< Optimize struct.
{
long double A[5], B[5], C[5], D[5], E[5], F[5];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
b7 (x) = r[7];
b6 (x) = r[8];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) - 12.L * b6 (x)
- 14.L * b7 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) - 108.L * b6 (x)
- 147.L * b7 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) - 864.L * b6 (x)
- 1372.L * b7 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) - 6480.L * b6 (x)
- 12005.L * b7 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x)) + 117649.L * a7 (x)
- 100842.L * b7 (x);
solve_5 (A, B, C, D, E, F);
b5 (x) = F[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = F[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = F[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = F[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = F[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)
- b4 (x) - b5 (x) - b6 (x) - b7 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);
return 1;
}
/**
* Function to get the coefficients on a 8 steps 7th order multi-steps method.
*/
static int
steps_8_7 (Optimize * optimize) ///< Optimize struct.
{
long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
b7 (x) = r[7];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) - 14.L * b7 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) - 147.L * b7 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) - 1372.L * b7 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) - 12005.L * b7 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)
- 100842.L * b7 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * (a7 (x) - b7 (x));
solve_6 (A, B, C, D, E, F, G);
b6 (x) = G[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = G[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = G[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = G[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = G[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = G[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)
- b4 (x) - b5 (x) - b6 (x) - b7 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);
return 1;
}
/**
* Function to get the coefficients on a 8 steps 8th order multi-steps method.
*/
static int
steps_8_8 (Optimize * optimize) ///< Optimize struct.
{
long double A[7], B[7], C[7], D[7], E[7], F[7], G[7], H[7];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = 14.L;
H[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * a4 (x)
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 147.L;
H[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = 1372.L;
H[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 12005.L;
H[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = 100842.L;
H[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 823543.L;
H[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * a7 (x);
A[6] = 8.L;
B[6] = 1024.L;
C[6] = 17496.L;
D[6] = 131072.L;
E[6] = 625000.L;
F[6] = 2239488.L;
G[6] = 6588344.L;
H[6] = -1.L + a1 (x) + 256.L * a2 (x) + 6561.L * a3 (x) + 65536.L * a4 (x)
+ 390625.L * a5 (x) + 1679616.L * a6 (x) + 5764801.L * a7 (x);
solve_7 (A, B, C, D, E, F, G, H);
b7 (x) = H[6];
if (isnan (b7 (x)))
return 0;
b6 (x) = H[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = H[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = H[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = H[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = H[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = H[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) - b1 (x) - b2 (x) - b3 (x)
- b4 (x) - b5 (x) - b6 (x) - b7 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x);
return 1;
}
/**
* Function to get the coefficients on a 9 steps 2nd order multi-steps method.
*/
static int
steps_9_2 (Optimize * optimize) ///< Optimize struct.
{
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
b8 (x) = r[8];
b7 (x) = r[9];
b6 (x) = r[10];
b5 (x) = r[11];
b4 (x) = r[12];
b3 (x) = r[13];
b2 (x) = r[14];
b1 (x)
= 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)
+ 16.L * (a4 (x) - b8 (x)) + 25.L * a5 (x) + 36.L * a6 (x)
+ 49.L * a7 (x) + 64.L * a8 (x) - 6.L * b3 (x) - 8.L * b4 (x)
- 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x) - 1.L);
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)
- b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x);
return 1;
}
/**
* Function to get the coefficients on a 9 steps 3th order multi-steps method.
*/
static int
steps_9_3 (Optimize * optimize) ///< Optimize struct.
{
long double A[2], B[2], C[2];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
b8 (x) = r[8];
b7 (x) = r[9];
b6 (x) = r[10];
b5 (x) = r[11];
b4 (x) = r[12];
b3 (x) = r[13];
A[0] = 2.L;
B[0] = 4.L;
C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
- 6.L * b3 (x) - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x)
- 14.L * b7 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
- 48.L * b4 (x) - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x)
- 192.L * b8 (x);
solve_2 (A, B, C);
b2 (x) = C[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = C[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)
- b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x);
return 1;
}
/**
* Function to get the coefficients on a 9 steps 4th order multi-steps method.
*/
static int
steps_9_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[3], B[3], C[3], D[3];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
b8 (x) = r[8];
b7 (x) = r[9];
b6 (x) = r[10];
b5 (x) = r[11];
b4 (x) = r[12];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
- 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
- 48.L * b4 (x) - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x)
- 192.L * b8 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)
+ 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)
+ 2401.L * a7 (x) + 4096.L * a8 (x) - 500.L * b5 (x) - 864.L * b6 (x)
- 1372.L * b7 (x) - 2048.L * b8 (x);
solve_3 (A, B, C, D);
b3 (x) = D[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = D[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = D[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)
- b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x);
return 1;
}
/**
* Function to get the coefficients on a 9 steps 5th order multi-steps method.
*/
static int
steps_9_5 (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
b8 (x) = r[8];
b7 (x) = r[9];
b6 (x) = r[10];
b5 (x) = r[11];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
- 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
- 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
- 500.L * b5 (x) - 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) + 16807.L * a7 (x)
+ 32768.L * a8 (x) - 6480.L * b6 (x) - 12005.L * b7 (x) - 20480.L * b8 (x);
solve_4 (A, B, C, D, E);
b4 (x) = E[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = E[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = E[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = E[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)
- b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x);
return 1;
}
/**
* Function to get the coefficients on a 9 steps 6th order multi-steps method.
*/
static int
steps_9_6 (Optimize * optimize) ///< Optimize struct.
{
long double A[5], B[5], C[5], D[5], E[5], F[5];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
b8 (x) = r[8];
b7 (x) = r[9];
b6 (x) = r[10];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
- 12.L * b6 (x) - 14.L * b7 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
- 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
- 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
- 6480.L * b6 (x) - 12005.L * b7 (x) - 20480.L * b8 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x)) + 117649.L * a7 (x)
+ 262144.L * a8 (x) - 100842.L * b7 (x) - 196608.L * b8 (x);
solve_5 (A, B, C, D, E, F);
b5 (x) = F[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = F[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = F[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = F[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = F[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)
- b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x);
return 1;
}
/**
* Function to get the coefficients on a 9 steps 7th order multi-steps method.
*/
static int
steps_9_7 (Optimize * optimize) ///< Optimize struct.
{
long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
b8 (x) = r[8];
b7 (x) = r[9];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
- 14.L * b7 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
- 147.L * b7 (x) - 192.L * b8 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
- 1372.L * b7 (x) - 2048.L * b8 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
- 12005.L * b7 (x) - 20480.L * b8 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)
+ 262144.L * a8 (x) - 100842.L * b7 (x) - 196608.L * b8 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * (a7 (x) - b7 (x))
+ 2097152.L * a8 (x) - 1835008.L * b8 (x);
solve_6 (A, B, C, D, E, F, G);
b6 (x) = G[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = G[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = G[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = G[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = G[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = G[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)
- b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x);
return 1;
}
/**
* Function to get the coefficients on a 9 steps 8th order multi-steps method.
*/
static int
steps_9_8 (Optimize * optimize) ///< Optimize struct.
{
long double A[7], B[7], C[7], D[7], E[7], F[7], G[7], H[7];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
b8 (x) = r[8];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = 14.L;
H[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 147.L;
H[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
- 192.L * b8 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = 1372.L;
H[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
- 2048.L * b8 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 12005.L;
H[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
- 20480.L * b8 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = 100842.L;
H[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)
+ 262144.L * a8 (x) - 196608.L * b8 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 823543.L;
H[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * a7 (x)
+ 2097152.L * a8 (x) - 1835008.L * b8 (x);
A[6] = 8.L;
B[6] = 1024.L;
C[6] = 17496.L;
D[6] = 131072.L;
E[6] = 625000.L;
F[6] = 2239488.L;
G[6] = 6588344.L;
H[6] = -1.L + a1 (x) + 256.L * a2 (x) + 6561.L * a3 (x) + 65536.L * a4 (x)
+ 390625.L * a5 (x) + 1679616.L * a6 (x) + 5764801.L * a7 (x)
+ 16777216.L * (a8 (x) - b8 (x));
solve_7 (A, B, C, D, E, F, G, H);
b7 (x) = H[6];
if (isnan (b7 (x)))
return 0;
b6 (x) = H[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = H[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = H[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = H[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = H[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = H[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) - b1 (x)
- b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x);
return 1;
}
/**
* Function to get the coefficients on a 10 steps 2nd order multi-steps method.
*/
static int
steps_10_2 (Optimize * optimize) ///< Optimize struct.
{
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
b9 (x) = r[9];
b8 (x) = r[10];
b7 (x) = r[11];
b6 (x) = r[12];
b5 (x) = r[13];
b4 (x) = r[14];
b3 (x) = r[15];
b2 (x) = r[16];
b1 (x)
= 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)
+ 16.L * (a4 (x) - b8 (x)) + 25.L * a5 (x) + 36.L * a6 (x)
+ 49.L * a7 (x) + 64.L * a8 (x) + 81.L * a9 (x) - 6.L * b3 (x)
- 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x)
- 18.L * b9 (x) - 1.L);
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
- b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)
- b9 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x);
return 1;
}
/**
* Function to get the coefficients on a 10 steps 3th order multi-steps method.
*/
static int
steps_10_3 (Optimize * optimize) ///< Optimize struct.
{
long double A[2], B[2], C[2];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
b9 (x) = r[9];
b8 (x) = r[10];
b7 (x) = r[11];
b6 (x) = r[12];
b5 (x) = r[13];
b4 (x) = r[14];
b3 (x) = r[15];
A[0] = 2.L;
B[0] = 4.L;
C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) - 6.L * b3 (x) - 8.L * b4 (x) - 10.L * b5 (x)
- 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) - 48.L * b4 (x) - 75.L * b5 (x) - 108.L * b6 (x)
- 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x);
solve_2 (A, B, C);
b2 (x) = C[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = C[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
- b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)
- b9 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x);
return 1;
}
/**
* Function to get the coefficients on a 10 steps 4th order multi-steps method.
*/
static int
steps_10_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[3], B[3], C[3], D[3];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
b9 (x) = r[9];
b8 (x) = r[10];
b7 (x) = r[11];
b6 (x) = r[12];
b5 (x) = r[13];
b4 (x) = r[14];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x)
- 14.L * b7 (x) - 18.L * b9 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) - 48.L * b4 (x) - 75.L * b5 (x) - 108.L * b6 (x)
- 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)
+ 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)
+ 2401.L * a7 (x) + 4096.L * a8 (x) + 6561.L * a9 (x) - 500.L * b5 (x)
- 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x);
solve_3 (A, B, C, D);
b3 (x) = D[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = D[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = D[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
- b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)
- b9 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x);
return 1;
}
/**
* Function to get the coefficients on a 10 steps 5th order multi-steps method.
*/
static int
steps_10_5 (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
b9 (x) = r[9];
b8 (x) = r[10];
b7 (x) = r[11];
b6 (x) = r[12];
b5 (x) = r[13];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x)
- 18.L * b9 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x)
- 192.L * b8 (x) - 243.L * b9 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) - 500.L * b5 (x) - 864.L * b6 (x) - 1372.L * b7 (x)
- 2048.L * b8 (x) - 2916.L * b9 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) + 16807.L * a7 (x)
+ 32768.L * a8 (x) + 59049.L * a9 (x) - 6480.L * b6 (x) - 12005.L * b7 (x)
- 20480.L * b8 (x) - 32805.L * b9 (x);
solve_4 (A, B, C, D, E);
b4 (x) = E[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = E[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = E[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = E[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
- b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)
- b9 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x);
return 1;
}
/**
* Function to get the coefficients on a 10 steps 6th order multi-steps method.
*/
static int
steps_10_6 (Optimize * optimize) ///< Optimize struct.
{
long double A[5], B[5], C[5], D[5], E[5], F[5];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
b9 (x) = r[9];
b8 (x) = r[10];
b7 (x) = r[11];
b6 (x) = r[12];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x)
- 243.L * b9 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) - 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x)
- 2916.L * b9 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
+ 59049.L * a9 (x) - 6480.L * b6 (x) - 12005.L * b7 (x) - 20480.L * b8 (x)
- 32805.L * b9 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x)) + 117649.L * a7 (x)
+ 262144.L * a8 (x) + 531441.L * a9 (x) - 100842.L * b7 (x)
- 196608.L * b8 (x) - 354294.L * b9 (x);
solve_5 (A, B, C, D, E, F);
b5 (x) = F[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = F[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = F[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = F[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = F[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
- b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)
- b9 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x);
return 1;
}
/**
* Function to get the coefficients on a 10 steps 7th order multi-steps method.
*/
static int
steps_10_7 (Optimize * optimize) ///< Optimize struct.
{
long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
b9 (x) = r[9];
b8 (x) = r[10];
b7 (x) = r[11];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) - 14.L * b7 (x) - 18.L * b9 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) - 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
+ 59049.L * a9 (x) - 12005.L * b7 (x) - 20480.L * b8 (x) - 32805.L * b9 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)
+ 262144.L * a8 (x) + 531441.L * a9 (x) - 100842.L * b7 (x)
- 196608.L * b8 (x) - 354294.L * b9 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * (a7 (x) - b7 (x))
+ 2097152.L * a8 (x) + 4782969.L * a9 (x) - 1835008.L * b8 (x)
- 3720087.L * b9 (x);
solve_6 (A, B, C, D, E, F, G);
b6 (x) = G[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = G[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = G[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = G[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = G[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = G[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
- b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)
- b9 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x);
return 1;
}
/**
* Function to get the coefficients on a 10 steps 8th order multi-steps method.
*/
static int
steps_10_8 (Optimize * optimize) ///< Optimize struct.
{
long double A[7], B[7], C[7], D[7], E[7], F[7], G[7], H[7];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
b9 (x) = r[9];
b8 (x) = r[10];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = 14.L;
H[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) - 18.L * b9 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 147.L;
H[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) - 192.L * b8 (x) - 243.L * b9 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = 1372.L;
H[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) - 2048.L * b8 (x) - 2916.L * b9 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 12005.L;
H[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
+ 59049.L * a9 (x) - 20480.L * b8 (x) - 32805.L * b9 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = 100842.L;
H[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)
+ 262144.L * a8 (x) + 531441.L * a9 (x) - 196608.L * b8 (x)
- 354294.L * b9 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 823543.L;
H[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * a7 (x)
+ 2097152.L * a8 (x) + 4782969.L * a9 (x) - 1835008.L * b8 (x)
- 3720087.L * b9 (x);
A[6] = 8.L;
B[6] = 1024.L;
C[6] = 17496.L;
D[6] = 131072.L;
E[6] = 625000.L;
F[6] = 2239488.L;
G[6] = 6588344.L;
H[6] = -1.L + a1 (x) + 256.L * a2 (x) + 6561.L * a3 (x) + 65536.L * a4 (x)
+ 390625.L * a5 (x) + 1679616.L * a6 (x) + 5764801.L * a7 (x)
+ 16777216.L * (a8 (x) - b8 (x)) + 43046721.L * a9 (x)
- 38263752.L * b9 (x);
solve_7 (A, B, C, D, E, F, G, H);
b7 (x) = H[6];
if (isnan (b7 (x)))
return 0;
b6 (x) = H[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = H[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = H[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = H[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = H[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = H[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
- b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x)
- b9 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x);
return 1;
}
/**
* Function to get the coefficients on a 11 steps 2nd order multi-steps method.
*/
static int
steps_11_2 (Optimize * optimize) ///< Optimize struct.
{
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
b10 (x) = r[10];
b9 (x) = r[11];
b8 (x) = r[12];
b7 (x) = r[13];
b6 (x) = r[14];
b5 (x) = r[15];
b4 (x) = r[16];
b3 (x) = r[17];
b2 (x) = r[18];
b1 (x)
= 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)
+ 16.L * (a4 (x) - b8 (x)) + 25.L * a5 (x) + 36.L * a6 (x)
+ 49.L * a7 (x) + 64.L * a8 (x) + 81.L * a9 (x) + 100.L * a10 (x)
- 6.L * b3 (x) - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x)
- 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x) - 1.L);
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)
- b7 (x) - b8 (x) - b9 (x) - b10 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x);
return 1;
}
/**
* Function to get the coefficients on a 11 steps 3th order multi-steps method.
*/
static int
steps_11_3 (Optimize * optimize) ///< Optimize struct.
{
long double A[2], B[2], C[2];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
b10 (x) = r[10];
b9 (x) = r[11];
b8 (x) = r[12];
b7 (x) = r[13];
b6 (x) = r[14];
b5 (x) = r[15];
b4 (x) = r[16];
b3 (x) = r[17];
A[0] = 2.L;
B[0] = 4.L;
C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) - 6.L * b3 (x) - 8.L * b4 (x)
- 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x)
- 20.L * b10 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) - 48.L * b4 (x) - 75.L * b5 (x)
- 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x)
- 300.L * b10 (x);
solve_2 (A, B, C);
b2 (x) = C[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = C[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)
- b7 (x) - b8 (x) - b9 (x) - b10 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x);
return 1;
}
/**
* Function to get the coefficients on a 11 steps 4th order multi-steps method.
*/
static int
steps_11_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[3], B[3], C[3], D[3];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
b10 (x) = r[10];
b9 (x) = r[11];
b8 (x) = r[12];
b7 (x) = r[13];
b6 (x) = r[14];
b5 (x) = r[15];
b4 (x) = r[16];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) - 8.L * b4 (x) - 10.L * b5 (x)
- 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) - 48.L * b4 (x) - 75.L * b5 (x)
- 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x)
- 300.L * b10 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)
+ 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)
+ 2401.L * a7 (x) + 4096.L * a8 (x) + 6561.L * a9 (x) + 10000.L * a10 (x)
- 500.L * b5 (x) - 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x)
- 2916.L * b9 (x) - 4000.L * b10 (x);
solve_3 (A, B, C, D);
b3 (x) = D[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = D[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = D[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)
- b7 (x) - b8 (x) - b9 (x) - b10 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x);
return 1;
}
/**
* Function to get the coefficients on a 11 steps 5th order multi-steps method.
*/
static int
steps_11_5 (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
b10 (x) = r[10];
b9 (x) = r[11];
b8 (x) = r[12];
b7 (x) = r[13];
b6 (x) = r[14];
b5 (x) = r[15];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) - 10.L * b5 (x) - 12.L * b6 (x)
- 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) - 75.L * b5 (x) - 108.L * b6 (x)
- 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) + 10000.L * a10 (x) - 500.L * b5 (x) - 864.L * b6 (x)
- 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) + 16807.L * a7 (x)
+ 32768.L * a8 (x) + 59049.L * a9 (x) + 100000.L * a10 (x) - 6480.L * b6 (x)
- 12005.L * b7 (x) - 20480.L * b8 (x) - 32805.L * b9 (x)
- 50000.L * b10 (x);
solve_4 (A, B, C, D, E);
b4 (x) = E[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = E[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = E[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = E[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)
- b7 (x) - b8 (x) - b9 (x) - b10 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x);
return 1;
}
/**
* Function to get the coefficients on a 11 steps 6th order multi-steps method.
*/
static int
steps_11_6 (Optimize * optimize) ///< Optimize struct.
{
long double A[5], B[5], C[5], D[5], E[5], F[5];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
b10 (x) = r[10];
b9 (x) = r[11];
b8 (x) = r[12];
b7 (x) = r[13];
b6 (x) = r[14];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) - 12.L * b6 (x) - 14.L * b7 (x)
- 18.L * b9 (x) - 20.L * b10 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) - 108.L * b6 (x) - 147.L * b7 (x)
- 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) + 10000.L * a10 (x) - 864.L * b6 (x) - 1372.L * b7 (x)
- 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
+ 59049.L * a9 (x) + 100000.L * a10 (x) - 6480.L * b6 (x) - 12005.L * b7 (x)
- 20480.L * b8 (x) - 32805.L * b9 (x) - 50000.L * b10 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x)) + 117649.L * a7 (x)
+ 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)
- 100842.L * b7 (x) - 196608.L * b8 (x) - 354294.L * b9 (x)
- 600000.L * b10 (x);
solve_5 (A, B, C, D, E, F);
b5 (x) = F[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = F[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = F[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = F[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = F[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)
- b7 (x) - b8 (x) - b9 (x) - b10 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x);
return 1;
}
/**
* Function to get the coefficients on a 11 steps 7th order multi-steps method.
*/
static int
steps_11_7 (Optimize * optimize) ///< Optimize struct.
{
long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
b10 (x) = r[10];
b9 (x) = r[11];
b8 (x) = r[12];
b7 (x) = r[13];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) - 14.L * b7 (x) - 18.L * b9 (x)
- 20.L * b10 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) - 147.L * b7 (x) - 192.L * b8 (x)
- 243.L * b9 (x) - 300.L * b10 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) + 10000.L * a10 (x) - 1372.L * b7 (x) - 2048.L * b8 (x)
- 2916.L * b9 (x) - 4000.L * b10 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
+ 59049.L * a9 (x) + 100000.L * a10 (x) - 12005.L * b7 (x)
- 20480.L * b8 (x) - 32805.L * b9 (x) - 50000.L * b10 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)
+ 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)
- 100842.L * b7 (x) - 196608.L * b8 (x) - 354294.L * b9 (x)
- 600000.L * b10 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * (a7 (x) - b7 (x))
+ 2097152.L * a8 (x) + 4782969.L * a9 (x) + 10000000.L * a10 (x)
- 1835008.L * b8 (x) - 3720087.L * b9 (x) - 7000000.L * b10 (x);
solve_6 (A, B, C, D, E, F, G);
b6 (x) = G[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = G[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = G[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = G[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = G[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = G[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)
- b7 (x) - b8 (x) - b9 (x) - b10 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x);
return 1;
}
/**
* Function to get the coefficients on a 11 steps 8th order multi-steps method.
*/
static int
steps_11_8 (Optimize * optimize) ///< Optimize struct.
{
long double A[7], B[7], C[7], D[7], E[7], F[7], G[7], H[7];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
b10 (x) = r[10];
b9 (x) = r[11];
b8 (x) = r[12];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = 14.L;
H[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) - 18.L * b9 (x) - 20.L * b10 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 147.L;
H[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) - 192.L * b8 (x) - 243.L * b9 (x)
- 300.L * b10 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = 1372.L;
H[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) + 10000.L * a10 (x) - 2048.L * b8 (x) - 2916.L * b9 (x)
- 4000.L * b10 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 12005.L;
H[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
+ 59049.L * a9 (x) + 100000.L * a10 (x) - 20480.L * b8 (x)
- 32805.L * b9 (x) - 50000.L * b10 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = 100842.L;
H[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)
+ 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)
- 196608.L * b8 (x) - 354294.L * b9 (x) - 600000.L * b10 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 823543.L;
H[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * a7 (x)
+ 2097152.L * a8 (x) + 4782969.L * a9 (x) + 10000000.L * a10 (x)
- 1835008.L * b8 (x) - 3720087.L * b9 (x) - 7000000.L * b10 (x);
A[6] = 8.L;
B[6] = 1024.L;
C[6] = 17496.L;
D[6] = 131072.L;
E[6] = 625000.L;
F[6] = 2239488.L;
G[6] = 6588344.L;
H[6] = -1.L + a1 (x) + 256.L * a2 (x) + 6561.L * a3 (x) + 65536.L * a4 (x)
+ 390625.L * a5 (x) + 1679616.L * a6 (x) + 5764801.L * a7 (x)
+ 16777216.L * (a8 (x) - b8 (x)) + 43046721.L * a9 (x)
+ 100000000.L * a10 (x) - 38263752.L * b9 (x) - 80000000.L * b10 (x);
solve_7 (A, B, C, D, E, F, G, H);
b7 (x) = H[6];
if (isnan (b7 (x)))
return 0;
b6 (x) = H[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = H[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = H[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = H[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = H[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = H[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x) - b5 (x) - b6 (x)
- b7 (x) - b8 (x) - b9 (x) - b10 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x);
return 1;
}
/**
* Function to get the coefficients on a 12 steps 2nd order multi-steps method.
*/
static int
steps_12_2 (Optimize * optimize) ///< Optimize struct.
{
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
b11 (x) = r[11];
b10 (x) = r[12];
b9 (x) = r[13];
b8 (x) = r[14];
b7 (x) = r[15];
b6 (x) = r[16];
b5 (x) = r[17];
b4 (x) = r[18];
b3 (x) = r[19];
b2 (x) = r[20];
b1 (x)
= 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)
+ 16.L * (a4 (x) - b8 (x)) + 25.L * a5 (x) + 36.L * a6 (x)
+ 49.L * a7 (x) + 64.L * a8 (x) + 81.L * a9 (x) + 100.L * a10 (x)
+ 121.L * a11 (x) - 6.L * b3 (x) - 8.L * b4 (x) - 10.L * b5 (x)
- 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x)
- 22.L * b11 (x) - 1.L);
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)
- b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x);
return 1;
}
/**
* Function to get the coefficients on a 12 steps 3th order multi-steps method.
*/
static int
steps_12_3 (Optimize * optimize) ///< Optimize struct.
{
long double A[2], B[2], C[2];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
b11 (x) = r[11];
b10 (x) = r[12];
b9 (x) = r[13];
b8 (x) = r[14];
b7 (x) = r[15];
b6 (x) = r[16];
b5 (x) = r[17];
b4 (x) = r[18];
b3 (x) = r[19];
A[0] = 2.L;
B[0] = 4.L;
C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) - 6.L * b3 (x)
- 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x)
- 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) - 48.L * b4 (x)
- 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x)
- 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x);
solve_2 (A, B, C);
b2 (x) = C[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = C[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)
- b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x);
return 1;
}
/**
* Function to get the coefficients on a 12 steps 4th order multi-steps method.
*/
static int
steps_12_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[3], B[3], C[3], D[3];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
b11 (x) = r[11];
b10 (x) = r[12];
b9 (x) = r[13];
b8 (x) = r[14];
b7 (x) = r[15];
b6 (x) = r[16];
b5 (x) = r[17];
b4 (x) = r[18];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) - 8.L * b4 (x)
- 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x)
- 20.L * b10 (x) - 22.L * b11 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) - 48.L * b4 (x)
- 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x)
- 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)
+ 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)
+ 2401.L * a7 (x) + 4096.L * a8 (x) + 6561.L * a9 (x) + 10000.L * a10 (x)
+ 14641.L * a11 (x) - 500.L * b5 (x) - 864.L * b6 (x) - 1372.L * b7 (x)
- 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x) - 5324.L * b11 (x);
solve_3 (A, B, C, D);
b3 (x) = D[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = D[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = D[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)
- b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x);
return 1;
}
/**
* Function to get the coefficients on a 12 steps 5th order multi-steps method.
*/
static int
steps_12_5 (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
b11 (x) = r[11];
b10 (x) = r[12];
b9 (x) = r[13];
b8 (x) = r[14];
b7 (x) = r[15];
b6 (x) = r[16];
b5 (x) = r[17];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) - 10.L * b5 (x)
- 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x)
- 22.L * b11 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) - 75.L * b5 (x)
- 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x)
- 300.L * b10 (x) - 363.L * b11 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x) - 500.L * b5 (x)
- 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x)
- 4000.L * b10 (x) - 5324.L * b11 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) + 16807.L * a7 (x)
+ 32768.L * a8 (x) + 59049.L * a9 (x) + 100000.L * a10 (x)
+ 161051.L * a11 (x) - 6480.L * b6 (x) - 12005.L * b7 (x) - 20480.L * b8 (x)
- 32805.L * b9 (x) - 50000.L * b10 (x) - 73205.L * b11 (x);
solve_4 (A, B, C, D, E);
b4 (x) = E[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = E[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = E[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = E[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)
- b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x);
return 1;
}
/**
* Function to get the coefficients on a 12 steps 6th order multi-steps method.
*/
static int
steps_12_6 (Optimize * optimize) ///< Optimize struct.
{
long double A[5], B[5], C[5], D[5], E[5], F[5];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
b11 (x) = r[11];
b10 (x) = r[12];
b9 (x) = r[13];
b8 (x) = r[14];
b7 (x) = r[15];
b6 (x) = r[16];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) - 12.L * b6 (x)
- 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) - 108.L * b6 (x)
- 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x)
- 363.L * b11 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x) - 864.L * b6 (x)
- 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x)
- 5324.L * b11 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
+ 59049.L * a9 (x) + 100000.L * a10 (x) + 161051.L * a11 (x)
- 6480.L * b6 (x) - 12005.L * b7 (x) - 20480.L * b8 (x) - 32805.L * b9 (x)
- 50000.L * b10 (x) - 73205.L * b11 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x)) + 117649.L * a7 (x)
+ 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)
+ 1771561.L * a11 (x) - 100842.L * b7 (x) - 196608.L * b8 (x)
- 354294.L * b9 (x) - 600000.L * b10 (x) - 966306.L * b11 (x);
solve_5 (A, B, C, D, E, F);
b5 (x) = F[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = F[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = F[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = F[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = F[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)
- b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x);
return 1;
}
/**
* Function to get the coefficients on a 12 steps 7th order multi-steps method.
*/
static int
steps_12_7 (Optimize * optimize) ///< Optimize struct.
{
long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
b11 (x) = r[11];
b10 (x) = r[12];
b9 (x) = r[13];
b8 (x) = r[14];
b7 (x) = r[15];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) - 14.L * b7 (x)
- 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) - 147.L * b7 (x)
- 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x) - 1372.L * b7 (x)
- 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x) - 5324.L * b11 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
+ 59049.L * a9 (x) + 100000.L * a10 (x) + 161051.L * a11 (x)
- 12005.L * b7 (x) - 20480.L * b8 (x) - 32805.L * b9 (x) - 50000.L * b10 (x)
- 73205.L * b11 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)
+ 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)
+ 1771561.L * a11 (x) - 100842.L * b7 (x) - 196608.L * b8 (x)
- 354294.L * b9 (x) - 600000.L * b10 (x) - 966306.L * b11 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * (a7 (x) - b7 (x))
+ 2097152.L * a8 (x) + 4782969.L * a9 (x) + 10000000.L * a10 (x)
+ 19487171.L * a11 (x) - 1835008.L * b8 (x) - 3720087.L * b9 (x)
- 7000000.L * b10 (x) - 12400927.L * b11 (x);
solve_6 (A, B, C, D, E, F, G);
b6 (x) = G[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = G[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = G[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = G[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = G[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = G[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)
- b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x);
return 1;
}
/**
* Function to get the coefficients on a 12 steps 8th order multi-steps method.
*/
static int
steps_12_8 (Optimize * optimize) ///< Optimize struct.
{
long double A[7], B[7], C[7], D[7], E[7], F[7], G[7], H[7];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
b11 (x) = r[11];
b10 (x) = r[12];
b9 (x) = r[13];
b8 (x) = r[14];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = 14.L;
H[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) - 18.L * b9 (x)
- 20.L * b10 (x) - 22.L * b11 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 147.L;
H[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) - 192.L * b8 (x)
- 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = 1372.L;
H[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x) - 2048.L * b8 (x)
- 2916.L * b9 (x) - 4000.L * b10 (x) - 5324.L * b11 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 12005.L;
H[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
+ 59049.L * a9 (x) + 100000.L * a10 (x) + 161051.L * a11 (x)
- 20480.L * b8 (x) - 32805.L * b9 (x) - 50000.L * b10 (x)
- 73205.L * b11 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = 100842.L;
H[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)
+ 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)
+ 1771561.L * a11 (x) - 196608.L * b8 (x) - 354294.L * b9 (x)
- 600000.L * b10 (x) - 966306.L * b11 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 823543.L;
H[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * a7 (x)
+ 2097152.L * a8 (x) + 4782969.L * a9 (x) + 10000000.L * a10 (x)
+ 19487171.L * a11 (x) - 1835008.L * b8 (x) - 3720087.L * b9 (x)
- 7000000.L * b10 (x) - 12400927.L * b11 (x);
A[6] = 8.L;
B[6] = 1024.L;
C[6] = 17496.L;
D[6] = 131072.L;
E[6] = 625000.L;
F[6] = 2239488.L;
G[6] = 6588344.L;
H[6] = -1.L + a1 (x) + 256.L * a2 (x) + 6561.L * a3 (x) + 65536.L * a4 (x)
+ 390625.L * a5 (x) + 1679616.L * a6 (x) + 5764801.L * a7 (x)
+ 16777216.L * (a8 (x) - b8 (x)) + 43046721.L * a9 (x)
+ 100000000.L * a10 (x) + 214358881.L * a11 (x) - 38263752.L * b9 (x)
- 80000000.L * b10 (x) - 155897368.L * b11 (x);
solve_7 (A, B, C, D, E, F, G, H);
b7 (x) = H[6];
if (isnan (b7 (x)))
return 0;
b6 (x) = H[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = H[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = H[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = H[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = H[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = H[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) - b1 (x) - b2 (x) - b3 (x) - b4 (x)
- b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x) - b11 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x);
return 1;
}
/**
* Function to get the coefficients on a 13 steps 2nd order multi-steps method.
*/
static int
steps_13_2 (Optimize * optimize) ///< Optimize struct.
{
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
a12 (x) = r[11];
b12 (x) = r[12];
b11 (x) = r[13];
b10 (x) = r[14];
b9 (x) = r[15];
b8 (x) = r[16];
b7 (x) = r[17];
b6 (x) = r[18];
b5 (x) = r[19];
b4 (x) = r[20];
b3 (x) = r[21];
b2 (x) = r[22];
b1 (x)
= 0.5L * (a1 (x) + 4.L * (a2 (x) - b2 (x)) + 9.L * a3 (x)
+ 16.L * (a4 (x) - b8 (x)) + 25.L * a5 (x) + 36.L * a6 (x)
+ 49.L * a7 (x) + 64.L * a8 (x) + 81.L * a9 (x) + 100.L * a10 (x)
+ 121.L * a11 (x) + 144.L * a12 (x) - 6.L * b3 (x) - 8.L * b4 (x)
- 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x)
- 20.L * b10 (x) - 22.L * b11 (x) - 24.L * b12 (x) - 1.L);
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)
- b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)
- b11 (x) - b12 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);
return 1;
}
/**
* Function to get the coefficients on a 13 steps 3th order multi-steps method.
*/
static int
steps_13_3 (Optimize * optimize) ///< Optimize struct.
{
long double A[2], B[2], C[2];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
a12 (x) = r[11];
b12 (x) = r[12];
b11 (x) = r[13];
b10 (x) = r[14];
b9 (x) = r[15];
b8 (x) = r[16];
b7 (x) = r[17];
b6 (x) = r[18];
b5 (x) = r[19];
b4 (x) = r[20];
b3 (x) = r[21];
A[0] = 2.L;
B[0] = 4.L;
C[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) + 144.L * a12 (x)
- 6.L * b3 (x) - 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x)
- 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x)
- 24.L * b12 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * (a3 (x) - b3 (x)) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) + 1728.L * a12 (x)
- 48.L * b4 (x) - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x)
- 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x)
- 432.L * b12 (x);
solve_2 (A, B, C);
b2 (x) = C[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = C[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)
- b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)
- b11 (x) - b12 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);
return 1;
}
/**
* Function to get the coefficients on a 13 steps 4th order multi-steps method.
*/
static int
steps_13_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[3], B[3], C[3], D[3];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
a12 (x) = r[11];
b12 (x) = r[12];
b11 (x) = r[13];
b10 (x) = r[14];
b9 (x) = r[15];
b8 (x) = r[16];
b7 (x) = r[17];
b6 (x) = r[18];
b5 (x) = r[19];
b4 (x) = r[20];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) + 144.L * a12 (x)
- 8.L * b4 (x) - 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x)
- 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x) - 24.L * b12 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) + 1728.L * a12 (x)
- 48.L * b4 (x) - 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x)
- 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x)
- 432.L * b12 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x)
+ 256.L * (a4 (x) - b4 (x)) + 625.L * a5 (x) + 1296.L * a6 (x)
+ 2401.L * a7 (x) + 4096.L * a8 (x) + 6561.L * a9 (x) + 10000.L * a10 (x)
+ 14641.L * a11 (x) + 20736.L * a12 (x) - 500.L * b5 (x) - 864.L * b6 (x)
- 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x)
- 5324.L * b11 (x) - 6912.L * b12 (x);
solve_3 (A, B, C, D);
b3 (x) = D[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = D[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = D[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)
- b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)
- b11 (x) - b12 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);
return 1;
}
/**
* Function to get the coefficients on a 13 steps 5th order multi-steps method.
*/
static int
steps_13_5 (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
a12 (x) = r[11];
b12 (x) = r[12];
b11 (x) = r[13];
b10 (x) = r[14];
b9 (x) = r[15];
b8 (x) = r[16];
b7 (x) = r[17];
b6 (x) = r[18];
b5 (x) = r[19];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) + 144.L * a12 (x)
- 10.L * b5 (x) - 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x)
- 20.L * b10 (x) - 22.L * b11 (x) - 24.L * b12 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) + 1728.L * a12 (x)
- 75.L * b5 (x) - 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x)
- 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x) - 432.L * b12 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x)
+ 20736.L * a12 (x) - 500.L * b5 (x) - 864.L * b6 (x) - 1372.L * b7 (x)
- 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x) - 5324.L * b11 (x)
- 6912.L * b12 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * (a5 (x) - b5 (x)) + 7776.L * a6 (x) + 16807.L * a7 (x)
+ 32768.L * a8 (x) + 59049.L * a9 (x) + 100000.L * a10 (x)
+ 161051.L * a11 (x) + 248832.L * a12 (x) - 6480.L * b6 (x)
- 12005.L * b7 (x) - 20480.L * b8 (x) - 32805.L * b9 (x) - 50000.L * b10 (x)
- 73205.L * b11 (x) - 103680.L * b12 (x);
solve_4 (A, B, C, D, E);
b4 (x) = E[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = E[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = E[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = E[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)
- b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)
- b11 (x) - b12 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);
return 1;
}
/**
* Function to get the coefficients on a 13 steps 6th order multi-steps method.
*/
static int
steps_13_6 (Optimize * optimize) ///< Optimize struct.
{
long double A[5], B[5], C[5], D[5], E[5], F[5];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
a12 (x) = r[11];
b12 (x) = r[12];
b11 (x) = r[13];
b10 (x) = r[14];
b9 (x) = r[15];
b8 (x) = r[16];
b7 (x) = r[17];
b6 (x) = r[18];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) + 144.L * a12 (x)
- 12.L * b6 (x) - 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x)
- 22.L * b11 (x) - 24.L * b12 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) + 1728.L * a12 (x)
- 108.L * b6 (x) - 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x)
- 300.L * b10 (x) - 363.L * b11 (x) - 432.L * b12 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x)
+ 20736.L * a12 (x) - 864.L * b6 (x) - 1372.L * b7 (x) - 2048.L * b8 (x)
- 2916.L * b9 (x) - 4000.L * b10 (x) - 5324.L * b11 (x) - 6912.L * b12 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
+ 59049.L * a9 (x) + 100000.L * a10 (x) + 161051.L * a11 (x)
+ 248832.L * a12 (x) - 6480.L * b6 (x) - 12005.L * b7 (x) - 20480.L * b8 (x)
- 32805.L * b9 (x) - 50000.L * b10 (x) - 73205.L * b11 (x)
- 103680.L * b12 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * (a6 (x) - b6 (x)) + 117649.L * a7 (x)
+ 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)
+ 1771561.L * a11 (x) + 2985984.L * a12 (x) - 100842.L * b7 (x)
- 196608.L * b8 (x) - 354294.L * b9 (x) - 600000.L * b10 (x)
- 966306.L * b11 (x) - 1492992.L * b12 (x);
solve_5 (A, B, C, D, E, F);
b5 (x) = F[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = F[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = F[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = F[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = F[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)
- b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)
- b11 (x) - b12 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);
return 1;
}
/**
* Function to get the coefficients on a 13 steps 7th order multi-steps method.
*/
static int
steps_13_7 (Optimize * optimize) ///< Optimize struct.
{
long double A[6], B[6], C[6], D[6], E[6], F[6], G[6];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
a12 (x) = r[11];
b12 (x) = r[12];
b11 (x) = r[13];
b10 (x) = r[14];
b9 (x) = r[15];
b8 (x) = r[16];
b7 (x) = r[17];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) + 144.L * a12 (x)
- 14.L * b7 (x) - 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x)
- 24.L * b12 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) + 1728.L * a12 (x)
- 147.L * b7 (x) - 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x)
- 363.L * b11 (x) - 432.L * b12 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x)
+ 20736.L * a12 (x) - 1372.L * b7 (x) - 2048.L * b8 (x) - 2916.L * b9 (x)
- 4000.L * b10 (x) - 5324.L * b11 (x) - 6912.L * b12 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
+ 59049.L * a9 (x) + 100000.L * a10 (x) + 161051.L * a11 (x)
+ 248832.L * a12 (x) - 12005.L * b7 (x) - 20480.L * b8 (x)
- 32805.L * b9 (x) - 50000.L * b10 (x) - 73205.L * b11 (x)
- 103680.L * b12 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)
+ 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)
+ 1771561.L * a11 (x) + 2985984.L * a12 (x) - 100842.L * b7 (x)
- 196608.L * b8 (x) - 354294.L * b9 (x) - 600000.L * b10 (x)
- 966306.L * b11 (x) - 1492992.L * b12 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * (a7 (x) - b7 (x))
+ 2097152.L * a8 (x) + 4782969.L * a9 (x) + 10000000.L * a10 (x)
+ 19487171.L * a11 (x) + 35831808.L * a12 (x) - 1835008.L * b8 (x)
- 3720087.L * b9 (x) - 7000000.L * b10 (x) - 12400927.L * b11 (x)
- 20901888.L * b12 (x);
solve_6 (A, B, C, D, E, F, G);
b6 (x) = G[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = G[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = G[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = G[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = G[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = G[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)
- b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)
- b11 (x) - b12 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);
return 1;
}
/**
* Function to get the coefficients on a 13 steps 8th order multi-steps method.
*/
static int
steps_13_8 (Optimize * optimize) ///< Optimize struct.
{
long double A[7], B[7], C[7], D[7], E[7], F[7], G[7], H[7];
long double *x, *r;
x = optimize->coefficient;
r = optimize->random_data;
a1 (x) = r[0];
a2 (x) = r[1];
a3 (x) = r[2];
a4 (x) = r[3];
a5 (x) = r[4];
a6 (x) = r[5];
a7 (x) = r[6];
a8 (x) = r[7];
a9 (x) = r[8];
a10 (x) = r[9];
a11 (x) = r[10];
a12 (x) = r[11];
b12 (x) = r[12];
b11 (x) = r[13];
b10 (x) = r[14];
b9 (x) = r[15];
b8 (x) = r[16];
A[0] = 2.L;
B[0] = 4.L;
C[0] = 6.L;
D[0] = 8.L;
E[0] = 10.L;
F[0] = 12.L;
G[0] = 14.L;
H[0] = -1.L + a1 (x) + 4.L * a2 (x) + 9.L * a3 (x) + 16.L * (a4 (x) - b8 (x))
+ 25.L * a5 (x) + 36.L * a6 (x) + 49.L * a7 (x) + 64.L * a8 (x)
+ 81.L * a9 (x) + 100.L * a10 (x) + 121.L * a11 (x) + 144.L * a12 (x)
- 18.L * b9 (x) - 20.L * b10 (x) - 22.L * b11 (x) - 24.L * b12 (x);
A[1] = 3.L;
B[1] = 12.L;
C[1] = 27.L;
D[1] = 48.L;
E[1] = 75.L;
F[1] = 108.L;
G[1] = 147.L;
H[1] = 1.L + a1 (x) + 8.L * a2 (x) + 27.L * a3 (x) + 64.L * a4 (x)
+ 125.L * a5 (x) + 216.L * a6 (x) + 343.L * a7 (x) + 512.L * a8 (x)
+ 729.L * a9 (x) + 1000.L * a10 (x) + 1331.L * a11 (x) + 1728.L * a12 (x)
- 192.L * b8 (x) - 243.L * b9 (x) - 300.L * b10 (x) - 363.L * b11 (x)
- 432.L * b12 (x);
A[2] = 4.L;
B[2] = 32.L;
C[2] = 108.L;
D[2] = 256.L;
E[2] = 500.L;
F[2] = 864.L;
G[2] = 1372.L;
H[2] = -1.L + a1 (x) + 16.L * a2 (x) + 81.L * a3 (x) + 256.L * a4 (x)
+ 625.L * a5 (x) + 1296.L * a6 (x) + 2401.L * a7 (x) + 4096.L * a8 (x)
+ 6561.L * a9 (x) + 10000.L * a10 (x) + 14641.L * a11 (x)
+ 20736.L * a12 (x) - 2048.L * b8 (x) - 2916.L * b9 (x) - 4000.L * b10 (x)
- 5324.L * b11 (x) - 6912.L * b12 (x);
A[3] = 5.L;
B[3] = 80.L;
C[3] = 405.L;
D[3] = 1280.L;
E[3] = 3125.L;
F[3] = 6480.L;
G[3] = 12005.L;
H[3] = 1.L + a1 (x) + 32.L * a2 (x) + 243.L * a3 (x) + 1024.L * a4 (x)
+ 3125.L * a5 (x) + 7776.L * a6 (x) + 16807.L * a7 (x) + 32768.L * a8 (x)
+ 59049.L * a9 (x) + 100000.L * a10 (x) + 161051.L * a11 (x)
+ 248832.L * a12 (x) - 20480.L * b8 (x) - 32805.L * b9 (x)
- 50000.L * b10 (x) - 73205.L * b11 (x) - 103680.L * b12 (x);
A[4] = 6.L;
B[4] = 192.L;
C[4] = 1458.L;
D[4] = 6144.L;
E[4] = 18750.L;
F[4] = 46656.L;
G[4] = 100842.L;
H[4] = -1.L + a1 (x) + 64.L * a2 (x) + 729.L * a3 (x) + 4096.L * a4 (x)
+ 15625.L * a5 (x) + 46656.L * a6 (x) + 117649.L * a7 (x)
+ 262144.L * a8 (x) + 531441.L * a9 (x) + 1000000.L * a10 (x)
+ 1771561.L * a11 (x) + 2985984.L * a12 (x) - 196608.L * b8 (x)
- 354294.L * b9 (x) - 600000.L * b10 (x) - 966306.L * b11 (x)
- 1492992.L * b12 (x);
A[5] = 7.L;
B[5] = 448.L;
C[5] = 5103.L;
D[5] = 28672.L;
E[5] = 109375.L;
F[5] = 326592.L;
G[5] = 823543.L;
H[5] = 1.L + a1 (x) + 128.L * a2 (x) + 2187.L * a3 (x) + 16384.L * a4 (x)
+ 78125.L * a5 (x) + 279936.L * a6 (x) + 823543.L * a7 (x)
+ 2097152.L * a8 (x) + 4782969.L * a9 (x) + 10000000.L * a10 (x)
+ 19487171.L * a11 (x) + 35831808.L * a12 (x) - 1835008.L * b8 (x)
- 3720087.L * b9 (x) - 7000000.L * b10 (x) - 12400927.L * b11 (x)
- 20901888.L * b12 (x);
A[6] = 8.L;
B[6] = 1024.L;
C[6] = 17496.L;
D[6] = 131072.L;
E[6] = 625000.L;
F[6] = 2239488.L;
G[6] = 6588344.L;
H[6] = -1.L + a1 (x) + 256.L * a2 (x) + 6561.L * a3 (x) + 65536.L * a4 (x)
+ 390625.L * a5 (x) + 1679616.L * a6 (x) + 5764801.L * a7 (x)
+ 16777216.L * (a8 (x) - b8 (x)) + 43046721.L * a9 (x)
+ 100000000.L * a10 (x) + 214358881.L * a11 (x) + 429981696.L * a12 (x)
- 38263752.L * b9 (x) - 80000000.L * b10 (x) - 155897368.L * b11 (x)
- 286654464.L * b12 (x);
solve_7 (A, B, C, D, E, F, G, H);
b7 (x) = H[6];
if (isnan (b7 (x)))
return 0;
b6 (x) = H[5];
if (isnan (b6 (x)))
return 0;
b5 (x) = H[4];
if (isnan (b5 (x)))
return 0;
b4 (x) = H[3];
if (isnan (b4 (x)))
return 0;
b3 (x) = H[2];
if (isnan (b3 (x)))
return 0;
b2 (x) = H[1];
if (isnan (b2 (x)))
return 0;
b1 (x) = H[0];
if (isnan (b1 (x)))
return 0;
b0 (x) = 1.L + a1 (x) + 2.L * a2 (x) + 3.L * a3 (x) + 4.L * a4 (x)
+ 5.L * a5 (x) + 6.L * a6 (x) + 7.L * a7 (x) + 8.L * a8 (x) + 9.L * a9 (x)
+ 10.L * a10 (x) + 11.L * a11 (x) + 12.L * a12 (x) - b1 (x) - b2 (x)
- b3 (x) - b4 (x) - b5 (x) - b6 (x) - b7 (x) - b8 (x) - b9 (x) - b10 (x)
- b11 (x) - b12 (x);
a0 (x) = 1.L - a1 (x) - a2 (x) - a3 (x) - a4 (x) - a5 (x) - a6 (x) - a7 (x)
- a8 (x) - a9 (x) - a10 (x) - a11 (x) - a12 (x);
return 1;
}
/**
* Function to print on a file the coefficients of the multi-steps methods.
*/
static void
steps_print (Optimize * optimize, ///< Optimize struct.
FILE * file) ///< file.
{
long double *x;
unsigned int i;
x = optimize->coefficient;
for (i = 0; i < optimize->nsteps; ++i)
{
fprintf (file, "a%u:%.19Le;\n", i, x[2 * i]);
fprintf (file, "b%u:%.19Le;\n", i, x[2 * i + 1]);
fprintf (file, "c%u:%.19Le;\n", i, c (x[2 * i], x[2 * i + 1]));
}
}
/**
* Function to print a maxima format file to check the accuracy order of a
* multi-steps method.
*/
static void
steps_print_maxima (FILE * file, ///< file.
unsigned int nsteps, ///< steps number.
unsigned int order) ///< accuracy order.
{
int m;
unsigned int i, j, k, l;
// 0th order
fprintf (file, "a0");
for (i = 1; i < nsteps; ++i)
fprintf (file, "+a%u", i);
fprintf (file, "-1b0;\n");
// 1st order
fprintf (file, "b0");
for (i = 1; i < nsteps; ++i)
fprintf (file, "+b%u", i);
for (i = 1; i < nsteps; ++i)
fprintf (file, "-%ub0*a%u", i, i);
fprintf (file, "-1b0;\n");
// high order
for (j = 2, m = 1; j <= order; ++j, m = -m)
{
for (i = 1; i < nsteps; ++i)
{
for (k = 1, l = i; k < j; ++k)
l *= i;
fprintf (file, "-%ub0*a%u", l, i);
}
for (i = 1; i < nsteps; ++i)
{
for (k = 2, l = i * j; k < j; ++k)
l *= i;
fprintf (file, "+%ub0*b%u", l, i);
}
fprintf (file, "+%db0;\n", m);
}
}
/**
* Function to get the objective function of a 3 steps mult-steps method.
*
* \return objective function value.
*/
static long double
steps_objective_3 (Optimize * optimize) ///< Optimize struct.
{
register long double *x;
register long double k, C;
x = optimize->coefficient;
k = 0.L;
if (a0 (x) < -LDBL_EPSILON)
k += a0 (x);
if (a1 (x) < -LDBL_EPSILON)
k += a1 (x);
if (a2 (x) < -LDBL_EPSILON)
k += a2 (x);
if (k < -LDBL_EPSILON)
return 30.L - k;
k = 0.L;
if (b0 (x) < -LDBL_EPSILON)
k += b0 (x);
if (b1 (x) < -LDBL_EPSILON)
k += b1 (x);
if (b2 (x) < -LDBL_EPSILON)
k += b2 (x);
if (k < -LDBL_EPSILON)
return 20.L - k;
k = 0.L;
C = c0 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c1 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c2 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
if (k == 0.L || k > 20.L)
return 20.L;
return k;
}
/**
* Function to get the objective function of a 4 steps mult-steps method.
*
* \return objective function value.
*/
static long double
steps_objective_4 (Optimize * optimize) ///< Optimize struct.
{
register long double *x;
register long double k, C;
x = optimize->coefficient;
k = 0.L;
if (a0 (x) < -LDBL_EPSILON)
k += a0 (x);
if (a1 (x) < -LDBL_EPSILON)
k += a1 (x);
if (a2 (x) < -LDBL_EPSILON)
k += a2 (x);
if (a3 (x) < -LDBL_EPSILON)
k += a3 (x);
if (k < -LDBL_EPSILON)
return 30.L - k;
k = 0.L;
if (b0 (x) < -LDBL_EPSILON)
k += b0 (x);
if (b1 (x) < -LDBL_EPSILON)
k += b1 (x);
if (b2 (x) < -LDBL_EPSILON)
k += b2 (x);
if (b3 (x) < -LDBL_EPSILON)
k += b3 (x);
if (k < -LDBL_EPSILON)
return 20.L - k;
k = 0.L;
C = c0 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c1 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c2 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c3 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
if (k == 0.L || k > 20.L)
return 20.L;
return k;
}
/**
* Function to get the objective function of a 5 steps mult-steps method.
*
* \return objective function value.
*/
static long double
steps_objective_5 (Optimize * optimize) ///< Optimize struct.
{
register long double *x;
register long double k, C;
x = optimize->coefficient;
k = 0.L;
if (a0 (x) < -LDBL_EPSILON)
k += a0 (x);
if (a1 (x) < -LDBL_EPSILON)
k += a1 (x);
if (a2 (x) < -LDBL_EPSILON)
k += a2 (x);
if (a3 (x) < -LDBL_EPSILON)
k += a3 (x);
if (a4 (x) < -LDBL_EPSILON)
k += a4 (x);
if (k < -LDBL_EPSILON)
return 30.L - k;
k = 0.L;
if (b0 (x) < -LDBL_EPSILON)
k += b0 (x);
if (b1 (x) < -LDBL_EPSILON)
k += b1 (x);
if (b2 (x) < -LDBL_EPSILON)
k += b2 (x);
if (b3 (x) < -LDBL_EPSILON)
k += b3 (x);
if (b4 (x) < -LDBL_EPSILON)
k += b4 (x);
if (k < -LDBL_EPSILON)
return 20.L - k;
k = 0.L;
C = c0 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c1 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c2 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c3 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c4 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
if (k == 0.L || k > 20.L)
return 20.L;
return k;
}
/**
* Function to get the objective function of a 6 steps mult-steps method.
*
* \return objective function value.
*/
static long double
steps_objective_6 (Optimize * optimize) ///< Optimize struct.
{
register long double *x;
register long double k, C;
x = optimize->coefficient;
k = 0.L;
if (a0 (x) < -LDBL_EPSILON)
k += a0 (x);
if (a1 (x) < -LDBL_EPSILON)
k += a1 (x);
if (a2 (x) < -LDBL_EPSILON)
k += a2 (x);
if (a3 (x) < -LDBL_EPSILON)
k += a3 (x);
if (a4 (x) < -LDBL_EPSILON)
k += a4 (x);
if (a5 (x) < -LDBL_EPSILON)
k += a5 (x);
if (k < -LDBL_EPSILON)
return 30.L - k;
k = 0.L;
if (b0 (x) < -LDBL_EPSILON)
k += b0 (x);
if (b1 (x) < -LDBL_EPSILON)
k += b1 (x);
if (b2 (x) < -LDBL_EPSILON)
k += b2 (x);
if (b3 (x) < -LDBL_EPSILON)
k += b3 (x);
if (b4 (x) < -LDBL_EPSILON)
k += b4 (x);
if (b5 (x) < -LDBL_EPSILON)
k += b5 (x);
if (k < -LDBL_EPSILON)
return 20.L - k;
k = 0.L;
C = c0 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c1 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c2 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c3 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c4 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c5 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
if (k == 0.L || k > 20.L)
return 20.L;
return k;
}
/**
* Function to get the objective function of a 7 steps mult-steps method.
*
* \return objective function value.
*/
static long double
steps_objective_7 (Optimize * optimize) ///< Optimize struct.
{
register long double *x;
register long double k, C;
x = optimize->coefficient;
k = 0.L;
if (a0 (x) < -LDBL_EPSILON)
k += a0 (x);
if (a1 (x) < -LDBL_EPSILON)
k += a1 (x);
if (a2 (x) < -LDBL_EPSILON)
k += a2 (x);
if (a3 (x) < -LDBL_EPSILON)
k += a3 (x);
if (a4 (x) < -LDBL_EPSILON)
k += a4 (x);
if (a5 (x) < -LDBL_EPSILON)
k += a5 (x);
if (a6 (x) < -LDBL_EPSILON)
k += a6 (x);
if (k < -LDBL_EPSILON)
return 30.L - k;
k = 0.L;
if (b0 (x) < -LDBL_EPSILON)
k += b0 (x);
if (b1 (x) < -LDBL_EPSILON)
k += b1 (x);
if (b2 (x) < -LDBL_EPSILON)
k += b2 (x);
if (b3 (x) < -LDBL_EPSILON)
k += b3 (x);
if (b4 (x) < -LDBL_EPSILON)
k += b4 (x);
if (b5 (x) < -LDBL_EPSILON)
k += b5 (x);
if (b6 (x) < -LDBL_EPSILON)
k += b6 (x);
if (k < -LDBL_EPSILON)
return 20.L - k;
k = 0.L;
C = c0 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c1 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c2 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c3 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c4 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c5 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c6 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
if (k == 0.L || k > 20.L)
return 20.L;
return k;
}
/**
* Function to get the objective function of a 8 steps mult-steps method.
*
* \return objective function value.
*/
static long double
steps_objective_8 (Optimize * optimize) ///< Optimize struct.
{
register long double *x;
register long double k, C;
x = optimize->coefficient;
k = 0.L;
if (a0 (x) < -LDBL_EPSILON)
k += a0 (x);
if (a1 (x) < -LDBL_EPSILON)
k += a1 (x);
if (a2 (x) < -LDBL_EPSILON)
k += a2 (x);
if (a3 (x) < -LDBL_EPSILON)
k += a3 (x);
if (a4 (x) < -LDBL_EPSILON)
k += a4 (x);
if (a5 (x) < -LDBL_EPSILON)
k += a5 (x);
if (a6 (x) < -LDBL_EPSILON)
k += a6 (x);
if (a7 (x) < -LDBL_EPSILON)
k += a7 (x);
if (k < -LDBL_EPSILON)
return 30.L - k;
k = 0.L;
if (b0 (x) < -LDBL_EPSILON)
k += b0 (x);
if (b1 (x) < -LDBL_EPSILON)
k += b1 (x);
if (b2 (x) < -LDBL_EPSILON)
k += b2 (x);
if (b3 (x) < -LDBL_EPSILON)
k += b3 (x);
if (b4 (x) < -LDBL_EPSILON)
k += b4 (x);
if (b5 (x) < -LDBL_EPSILON)
k += b5 (x);
if (b6 (x) < -LDBL_EPSILON)
k += b6 (x);
if (b7 (x) < -LDBL_EPSILON)
k += b7 (x);
if (k < -LDBL_EPSILON)
return 20.L - k;
k = 0.L;
C = c0 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c1 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c2 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c3 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c4 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c5 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c6 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c7 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
if (k == 0.L || k > 20.L)
return 20.L;
return k;
}
/**
* Function to get the objective function of a 9 steps mult-steps method.
*
* \return objective function value.
*/
static long double
steps_objective_9 (Optimize * optimize) ///< Optimize struct.
{
register long double *x;
register long double k, C;
x = optimize->coefficient;
k = 0.L;
if (a0 (x) < -LDBL_EPSILON)
k += a0 (x);
if (a1 (x) < -LDBL_EPSILON)
k += a1 (x);
if (a2 (x) < -LDBL_EPSILON)
k += a2 (x);
if (a3 (x) < -LDBL_EPSILON)
k += a3 (x);
if (a4 (x) < -LDBL_EPSILON)
k += a4 (x);
if (a5 (x) < -LDBL_EPSILON)
k += a5 (x);
if (a6 (x) < -LDBL_EPSILON)
k += a6 (x);
if (a7 (x) < -LDBL_EPSILON)
k += a7 (x);
if (a8 (x) < -LDBL_EPSILON)
k += a8 (x);
if (k < -LDBL_EPSILON)
return 30.L - k;
k = 0.L;
if (b0 (x) < -LDBL_EPSILON)
k += b0 (x);
if (b1 (x) < -LDBL_EPSILON)
k += b1 (x);
if (b2 (x) < -LDBL_EPSILON)
k += b2 (x);
if (b3 (x) < -LDBL_EPSILON)
k += b3 (x);
if (b4 (x) < -LDBL_EPSILON)
k += b4 (x);
if (b5 (x) < -LDBL_EPSILON)
k += b5 (x);
if (b6 (x) < -LDBL_EPSILON)
k += b6 (x);
if (b7 (x) < -LDBL_EPSILON)
k += b7 (x);
if (b8 (x) < -LDBL_EPSILON)
k += b8 (x);
if (k < -LDBL_EPSILON)
return 20.L - k;
k = 0.L;
C = c0 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c1 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c2 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c3 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c4 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c5 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c6 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c7 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c8 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
if (k == 0.L || k > 20.L)
return 20.L;
return k;
}
/**
* Function to get the objective function of a 10 steps mult-steps method.
*
* \return objective function value.
*/
static long double
steps_objective_10 (Optimize * optimize) ///< Optimize struct.
{
register long double *x;
register long double k, C;
x = optimize->coefficient;
k = 0.L;
if (a0 (x) < -LDBL_EPSILON)
k += a0 (x);
if (a1 (x) < -LDBL_EPSILON)
k += a1 (x);
if (a2 (x) < -LDBL_EPSILON)
k += a2 (x);
if (a3 (x) < -LDBL_EPSILON)
k += a3 (x);
if (a4 (x) < -LDBL_EPSILON)
k += a4 (x);
if (a5 (x) < -LDBL_EPSILON)
k += a5 (x);
if (a6 (x) < -LDBL_EPSILON)
k += a6 (x);
if (a7 (x) < -LDBL_EPSILON)
k += a7 (x);
if (a8 (x) < -LDBL_EPSILON)
k += a8 (x);
if (a9 (x) < -LDBL_EPSILON)
k += a9 (x);
if (k < -LDBL_EPSILON)
return 30.L - k;
k = 0.L;
if (b0 (x) < -LDBL_EPSILON)
k += b0 (x);
if (b1 (x) < -LDBL_EPSILON)
k += b1 (x);
if (b2 (x) < -LDBL_EPSILON)
k += b2 (x);
if (b3 (x) < -LDBL_EPSILON)
k += b3 (x);
if (b4 (x) < -LDBL_EPSILON)
k += b4 (x);
if (b5 (x) < -LDBL_EPSILON)
k += b5 (x);
if (b6 (x) < -LDBL_EPSILON)
k += b6 (x);
if (b7 (x) < -LDBL_EPSILON)
k += b7 (x);
if (b8 (x) < -LDBL_EPSILON)
k += b8 (x);
if (b9 (x) < -LDBL_EPSILON)
k += b9 (x);
if (k < -LDBL_EPSILON)
return 20.L - k;
k = 0.L;
C = c0 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c1 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c2 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c3 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c4 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c5 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c6 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c7 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c8 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c9 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
if (k == 0.L || k > 20.L)
return 20.L;
return k;
}
/**
* Function to get the objective function of a 11 steps mult-steps method.
*
* \return objective function value.
*/
static long double
steps_objective_11 (Optimize * optimize) ///< Optimize struct.
{
register long double *x;
register long double k, C;
x = optimize->coefficient;
k = 0.L;
if (a0 (x) < -LDBL_EPSILON)
k += a0 (x);
if (a1 (x) < -LDBL_EPSILON)
k += a1 (x);
if (a2 (x) < -LDBL_EPSILON)
k += a2 (x);
if (a3 (x) < -LDBL_EPSILON)
k += a3 (x);
if (a4 (x) < -LDBL_EPSILON)
k += a4 (x);
if (a5 (x) < -LDBL_EPSILON)
k += a5 (x);
if (a6 (x) < -LDBL_EPSILON)
k += a6 (x);
if (a7 (x) < -LDBL_EPSILON)
k += a7 (x);
if (a8 (x) < -LDBL_EPSILON)
k += a8 (x);
if (a9 (x) < -LDBL_EPSILON)
k += a9 (x);
if (a10 (x) < -LDBL_EPSILON)
k += a10 (x);
if (k < -LDBL_EPSILON)
return 30.L - k;
k = 0.L;
if (b0 (x) < -LDBL_EPSILON)
k += b0 (x);
if (b1 (x) < -LDBL_EPSILON)
k += b1 (x);
if (b2 (x) < -LDBL_EPSILON)
k += b2 (x);
if (b3 (x) < -LDBL_EPSILON)
k += b3 (x);
if (b4 (x) < -LDBL_EPSILON)
k += b4 (x);
if (b5 (x) < -LDBL_EPSILON)
k += b5 (x);
if (b6 (x) < -LDBL_EPSILON)
k += b6 (x);
if (b7 (x) < -LDBL_EPSILON)
k += b7 (x);
if (b8 (x) < -LDBL_EPSILON)
k += b8 (x);
if (b9 (x) < -LDBL_EPSILON)
k += b9 (x);
if (b10 (x) < -LDBL_EPSILON)
k += b10 (x);
if (k < -LDBL_EPSILON)
return 20.L - k;
k = 0.L;
C = c0 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c1 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c2 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c3 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c4 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c5 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c6 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c7 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c8 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c9 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c10 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
if (k == 0.L || k > 20.L)
return 20.L;
return k;
}
/**
* Function to get the objective function of a 12 steps mult-steps method.
*
* \return objective function value.
*/
static long double
steps_objective_12 (Optimize * optimize) ///< Optimize struct.
{
register long double *x;
register long double k, C;
x = optimize->coefficient;
k = 0.L;
if (a0 (x) < -LDBL_EPSILON)
k += a0 (x);
if (a1 (x) < -LDBL_EPSILON)
k += a1 (x);
if (a2 (x) < -LDBL_EPSILON)
k += a2 (x);
if (a3 (x) < -LDBL_EPSILON)
k += a3 (x);
if (a4 (x) < -LDBL_EPSILON)
k += a4 (x);
if (a5 (x) < -LDBL_EPSILON)
k += a5 (x);
if (a6 (x) < -LDBL_EPSILON)
k += a6 (x);
if (a7 (x) < -LDBL_EPSILON)
k += a7 (x);
if (a8 (x) < -LDBL_EPSILON)
k += a8 (x);
if (a9 (x) < -LDBL_EPSILON)
k += a9 (x);
if (a10 (x) < -LDBL_EPSILON)
k += a10 (x);
if (a11 (x) < -LDBL_EPSILON)
k += a11 (x);
if (k < -LDBL_EPSILON)
return 30.L - k;
k = 0.L;
if (b0 (x) < -LDBL_EPSILON)
k += b0 (x);
if (b1 (x) < -LDBL_EPSILON)
k += b1 (x);
if (b2 (x) < -LDBL_EPSILON)
k += b2 (x);
if (b3 (x) < -LDBL_EPSILON)
k += b3 (x);
if (b4 (x) < -LDBL_EPSILON)
k += b4 (x);
if (b5 (x) < -LDBL_EPSILON)
k += b5 (x);
if (b6 (x) < -LDBL_EPSILON)
k += b6 (x);
if (b7 (x) < -LDBL_EPSILON)
k += b7 (x);
if (b8 (x) < -LDBL_EPSILON)
k += b8 (x);
if (b9 (x) < -LDBL_EPSILON)
k += b9 (x);
if (b10 (x) < -LDBL_EPSILON)
k += b10 (x);
if (b11 (x) < -LDBL_EPSILON)
k += b11 (x);
if (k < -LDBL_EPSILON)
return 20.L - k;
k = 0.L;
C = c0 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c1 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c2 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c3 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c4 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c5 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c6 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c7 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c8 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c9 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c10 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c11 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
if (k == 0.L || k > 20.L)
return 20.L;
return k;
}
/**
* Function to get the objective function of a 13 steps mult-steps method.
*
* \return objective function value.
*/
static long double
steps_objective_13 (Optimize * optimize) ///< Optimize struct.
{
register long double *x;
register long double k, C;
x = optimize->coefficient;
k = 0.L;
if (a0 (x) < -LDBL_EPSILON)
k += a0 (x);
if (a1 (x) < -LDBL_EPSILON)
k += a1 (x);
if (a2 (x) < -LDBL_EPSILON)
k += a2 (x);
if (a3 (x) < -LDBL_EPSILON)
k += a3 (x);
if (a4 (x) < -LDBL_EPSILON)
k += a4 (x);
if (a5 (x) < -LDBL_EPSILON)
k += a5 (x);
if (a6 (x) < -LDBL_EPSILON)
k += a6 (x);
if (a7 (x) < -LDBL_EPSILON)
k += a7 (x);
if (a8 (x) < -LDBL_EPSILON)
k += a8 (x);
if (a9 (x) < -LDBL_EPSILON)
k += a9 (x);
if (a10 (x) < -LDBL_EPSILON)
k += a10 (x);
if (a11 (x) < -LDBL_EPSILON)
k += a11 (x);
if (a12 (x) < -LDBL_EPSILON)
k += a12 (x);
if (k < -LDBL_EPSILON)
return 30.L - k;
k = 0.L;
if (b0 (x) < -LDBL_EPSILON)
k += b0 (x);
if (b1 (x) < -LDBL_EPSILON)
k += b1 (x);
if (b2 (x) < -LDBL_EPSILON)
k += b2 (x);
if (b3 (x) < -LDBL_EPSILON)
k += b3 (x);
if (b4 (x) < -LDBL_EPSILON)
k += b4 (x);
if (b5 (x) < -LDBL_EPSILON)
k += b5 (x);
if (b6 (x) < -LDBL_EPSILON)
k += b6 (x);
if (b7 (x) < -LDBL_EPSILON)
k += b7 (x);
if (b8 (x) < -LDBL_EPSILON)
k += b8 (x);
if (b9 (x) < -LDBL_EPSILON)
k += b9 (x);
if (b10 (x) < -LDBL_EPSILON)
k += b10 (x);
if (b11 (x) < -LDBL_EPSILON)
k += b11 (x);
if (b12 (x) < -LDBL_EPSILON)
k += b12 (x);
if (k < -LDBL_EPSILON)
return 20.L - k;
k = 0.L;
C = c0 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c1 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c2 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c3 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c4 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c5 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c6 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c7 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c8 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c9 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c10 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c11 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
C = c12 (x);
if (C < -LDBL_EPSILON)
return 20.L;
if (!isnan (C))
k = fmaxl (k, C);
if (k == 0.L || k > 20.L)
return 20.L;
return k;
}
/**
* Function to select the multi-steps method.
*
* \return 1 on success, 0 on error.
*/
static inline int
steps_select (Optimize * optimize, ///< Optimize struct.
unsigned int nsteps, ///< number of steps.
unsigned int order) ///< order of accuracy.
{
static long double (*objective[14]) (Optimize *) =
{
NULL,
NULL,
NULL,
&steps_objective_3,
&steps_objective_4,
&steps_objective_5,
&steps_objective_6,
&steps_objective_7,
&steps_objective_8,
&steps_objective_9,
&steps_objective_10,
&steps_objective_11, &steps_objective_12, &steps_objective_13};
static int (*method[14][9]) (Optimize *) =
{
{
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL},
{
NULL, NULL, &steps_3_2, &steps_3_3, NULL, NULL, NULL, NULL, NULL},
{
NULL, NULL, &steps_4_2, &steps_4_3, &steps_4_4, NULL, NULL, NULL, NULL},
{
NULL, NULL, &steps_5_2, &steps_5_3, &steps_5_4, &steps_5_5, NULL, NULL,
NULL},
{
NULL, NULL, &steps_6_2, &steps_6_3, &steps_6_4, &steps_6_5, &steps_6_6,
NULL, NULL},
{
NULL, NULL, &steps_7_2, &steps_7_3, &steps_7_4, &steps_7_5, &steps_7_6,
&steps_7_7, NULL},
{
NULL, NULL, &steps_8_2, &steps_8_3, &steps_8_4, &steps_8_5, &steps_8_6,
&steps_8_7, &steps_8_8},
{
NULL, NULL, &steps_9_2, &steps_9_3, &steps_9_4, &steps_9_5, &steps_9_6,
&steps_9_7, &steps_9_8},
{
NULL, NULL, &steps_10_2, &steps_10_3, &steps_10_4, &steps_10_5,
&steps_10_6, &steps_10_7, &steps_10_8},
{
NULL, NULL, &steps_11_2, &steps_11_3, &steps_11_4, &steps_11_5,
&steps_11_6, &steps_11_7, &steps_11_8},
{
NULL, NULL, &steps_12_2, &steps_12_3, &steps_12_4, &steps_12_5,
&steps_12_6, &steps_12_7, &steps_12_8},
{
NULL, NULL, &steps_13_2, &steps_13_3, &steps_13_4, &steps_13_5,
&steps_13_6, &steps_13_7, &steps_13_8}
};
#if DEBUG_STEPS
fprintf (stderr, "steps_run: start\n");
#endif
if (nsteps < 3 || nsteps > 14 || order < 2 || order > 8)
goto exit_on_error;
optimize->nsteps = nsteps;
optimize->order = order;
optimize->size = 2 * nsteps;
optimize->nfree = optimize->size - order - 1;
optimize->minimum0
= (long double *) g_slice_alloc (optimize->nfree * sizeof (long double));
optimize->interval0
= (long double *) g_slice_alloc (optimize->nfree * sizeof (long double));
optimize->random_type
= (unsigned int *) g_slice_alloc (optimize->nfree * sizeof (unsigned int));
optimize->data = NULL;
optimize->objective = objective[nsteps];
optimize->method = method[nsteps][order];
if (!optimize->method)
goto exit_on_error;
#if DEBUG_STEPS
fprintf (stderr, "steps_select: end\n");
#endif
return 1;
exit_on_error:
error_message = g_strdup (_("Unknown method"));
#if DEBUG_STEPS
fprintf (stderr, "steps_select: end\n");
#endif
return 0;
}
/**
* Function to read the multi-steps method data on a XML node.
*
* \return 1 on success, 0 on error.
*/
int
steps_run (xmlNode * node, ///< XML node.
gsl_rng ** rng) ///< array of gsl_rng structs.
{
Optimize s[nthreads];
char filename[64];
gchar *buffer;
FILE *file;
long double *value_optimal;
long double optimal;
int code;
unsigned int i, j, nsteps, order, nfree;
#if DEBUG_STEPS
fprintf (stderr, "steps_run: start\n");
#endif
nsteps = xml_node_get_uint (node, XML_STEPS, &code);
if (code)
{
error_message = g_strdup (_("Bad steps number"));
goto exit_on_error;
}
order = xml_node_get_uint (node, XML_ORDER, &code);
if (code)
{
error_message = g_strdup (_("Bad order"));
goto exit_on_error;
}
if (!steps_select (s, nsteps, order))
goto exit_on_error;
if (!optimize_read (s, node))
goto exit_on_error;
nfree = s->nfree;
value_optimal = (long double *) g_slice_alloc (nfree * sizeof (long double));
optimize_create (s, &optimal, value_optimal);
node = node->children;
for (i = 0; i < nfree; ++i, node = node->next)
if (!read_variable (node, s->minimum0, s->interval0, s->random_type, i))
goto exit_on_error;
for (i = 1; i < nthreads; ++i)
memcpy (s + i, s, sizeof (Optimize));
j = rank * nthreads;
for (i = 0; i < nthreads; ++i)
optimize_init (s + i, rng[j + i], i);
// Method bucle
printf ("Optimize bucle\n");
optimize_bucle (s);
// Print the optimal coefficients
printf ("Print the optimal coefficients\n");
memcpy (s->random_data, s->value_optimal, nfree * sizeof (long double));
code = s->method (s);
snprintf (filename, 64, "steps-%u-%u.mc", nsteps, order);
file = fopen (filename, "w");
print_maxima_precision (file);
steps_print (s, file);
steps_print_maxima (file, nsteps, order);
fclose (file);
snprintf (filename, 64, "sed -i 's/e+/b+/g' steps-%u-%u.mc", nsteps, order);
code = system (filename);
snprintf (filename, 64, "sed -i 's/e-/b-/g' steps-%u-%u.mc", nsteps, order);
code = system (filename);
// Free memory
g_slice_free1 (nfree * sizeof (unsigned int), s->random_type);
g_slice_free1 (nfree * sizeof (long double), s->interval0);
g_slice_free1 (nfree * sizeof (long double), s->minimum0);
for (i = 0; i < nthreads; ++i)
optimize_delete (s + i);
g_slice_free1 (nfree * sizeof (long double), value_optimal);
#if DEBUG_STEPS
fprintf (stderr, "steps_run: end\n");
#endif
return 1;
exit_on_error:
buffer = error_message;
error_message = g_strconcat ("Multi-steps:\n", buffer, NULL);
g_free (buffer);
#if DEBUG_STEPS
fprintf (stderr, "steps_run: end\n");
#endif
return 0;
}
| {
"alphanum_fraction": 0.4330998076,
"avg_line_length": 28.0782683983,
"ext": "c",
"hexsha": "fb8f88850df833dd440cb98e89802e6e1abd5330",
"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": "steps.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": "steps.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": "steps.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 85677,
"size": 162152
} |
#ifndef libceed_solids_examples_misc_h
#define libceed_solids_examples_misc_h
#include <ceed.h>
#include <petsc.h>
#include "../include/structs.h"
// -----------------------------------------------------------------------------
// Context setup
// -----------------------------------------------------------------------------
// Setup context data for Jacobian evaluation
PetscErrorCode SetupJacobianCtx(MPI_Comm comm, AppCtx app_ctx, DM dm, Vec V,
Vec V_loc, CeedData ceed_data, Ceed ceed,
CeedQFunctionContext ctx_phys,
CeedQFunctionContext ctx_phys_smoother,
UserMult jacobian_ctx);
// Setup context data for prolongation and restriction operators
PetscErrorCode SetupProlongRestrictCtx(MPI_Comm comm, AppCtx app_ctx, DM dm_c,
DM dm_f, Vec V_f, Vec V_loc_c, Vec V_loc_f,
CeedData ceed_data_c, CeedData ceed_data_f,
Ceed ceed,
UserMultProlongRestr prolong_restr_ctx);
// -----------------------------------------------------------------------------
// Jacobian setup
// -----------------------------------------------------------------------------
PetscErrorCode FormJacobian(SNES snes, Vec U, Mat J, Mat J_pre, void *ctx);
// -----------------------------------------------------------------------------
// Solution output
// -----------------------------------------------------------------------------
PetscErrorCode ViewSolution(MPI_Comm comm, AppCtx app_ctx, Vec U,
PetscInt increment, PetscScalar load_increment);
PetscErrorCode ViewDiagnosticQuantities(MPI_Comm comm, DM dm_U,
UserMult user, AppCtx app_ctx, Vec U,
CeedElemRestriction elem_restr_diagnostic);
// -----------------------------------------------------------------------------
// Regression testing
// -----------------------------------------------------------------------------
PetscErrorCode RegressionTests_solids(AppCtx app_ctx, PetscReal energy);
#endif // libceed_solids_examples_misc_h
| {
"alphanum_fraction": 0.4448367167,
"avg_line_length": 49.2608695652,
"ext": "h",
"hexsha": "daae9d9d06edddeba2b52a42d68bf7e34ed02906",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "wence-/libCEED",
"max_forks_repo_path": "examples/solids/include/misc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "wence-/libCEED",
"max_issues_repo_path": "examples/solids/include/misc.h",
"max_line_length": 83,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "wence-/libCEED",
"max_stars_repo_path": "examples/solids/include/misc.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 352,
"size": 2266
} |
#pragma once
#include "halley/plugin/iasset_importer.h"
#include <yaml-cpp/node/node.h>
#include "halley/core/graphics/material/material_definition.h"
#include <gsl/span>
namespace Halley
{
class MaterialDefinition;
class MaterialImporter : public IAssetImporter
{
public:
ImportAssetType getType() const override { return ImportAssetType::MaterialDefinition; }
void import(const ImportingAsset& asset, IAssetCollector& collector) override;
MaterialDefinition parseMaterial(Path basePath, gsl::span<const gsl::byte> data, IAssetCollector& collector) const;
private:
static void loadPass(MaterialDefinition& material, const ConfigNode& node, IAssetCollector& collector, int passN);
static void loadUniforms(MaterialDefinition& material, const YAML::Node& topNode);
static void loadTextures(MaterialDefinition& material, const YAML::Node& topNode);
static void loadAttributes(MaterialDefinition& material, const YAML::Node& topNode);
static ShaderParameterType parseParameterType(String rawType);
static int getAttributeSize(ShaderParameterType type);
static Bytes loadShader(const String& name, IAssetCollector& collector);
static Bytes doLoadShader(const String& name, IAssetCollector& collector, std::set<String>& loaded);
};
}
| {
"alphanum_fraction": 0.7954186414,
"avg_line_length": 38.3636363636,
"ext": "h",
"hexsha": "afc66dd702423636d6a8bb0d4636c878349e140a",
"lang": "C",
"max_forks_count": 193,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z",
"max_forks_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "code-disaster/halley",
"max_forks_repo_path": "src/tools/tools/src/assets/importers/material_importer.h",
"max_issues_count": 53,
"max_issues_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80",
"max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "code-disaster/halley",
"max_issues_repo_path": "src/tools/tools/src/assets/importers/material_importer.h",
"max_line_length": 117,
"max_stars_count": 3262,
"max_stars_repo_head_hexsha": "5c85c889b76c69c6bdef6f4801c6aba282b7af80",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "code-disaster/halley",
"max_stars_repo_path": "src/tools/tools/src/assets/importers/material_importer.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z",
"num_tokens": 278,
"size": 1266
} |
#pragma once
#include "GradUtil.h"
#include "DistanceGrad.h"
#ifndef _NOGSL
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#else
#include "CustomSolver.h"
#endif
#include <limits>
#include <math.h>
#include <vector>
#include "BasicError.h"
using namespace std;
class ValueGrad {
double val;
gsl_vector* grad;
public:
bool set;
ValueGrad(double _val, gsl_vector* _grad): val(_val), grad(_grad), set(false) {}
~ValueGrad(void) {
gsl_vector_free(grad);
}
double getVal() const { return val; }
gsl_vector* getGrad() const { return grad; }
void update(double _val) {
val = _val;
}
static double vg_plus(ValueGrad* m, ValueGrad* f, gsl_vector* ograd);
static void vg_plus(ValueGrad* m, ValueGrad* f, ValueGrad* o); // o = m + f
static double vg_times(ValueGrad* m, ValueGrad* f, gsl_vector* ograd);
static void vg_times(ValueGrad* m, ValueGrad* f, ValueGrad* o); // o = m * f
static double vg_div(ValueGrad* m, ValueGrad* f, gsl_vector* o);
static void vg_div(ValueGrad* m, ValueGrad* f, ValueGrad* o); // o = m / f
static void vg_neg(ValueGrad* m, ValueGrad* o); // o = -m
static void vg_equal(ValueGrad* m, ValueGrad* f, DistanceGrad* o); // o = m == f
static void vg_lt(ValueGrad* m, ValueGrad* f, DistanceGrad* o); // o = m < f
static double vg_lt(ValueGrad* m, ValueGrad* f, gsl_vector* o);
static void vg_lt(ValueGrad* m, ValueGrad* f, ValueGrad* o);
static void vg_square(ValueGrad* m, ValueGrad* o); // o = m * m
static void vg_arctan(ValueGrad* m, ValueGrad* o); // o = arctan(m)
static void vg_sin(ValueGrad* m, ValueGrad* o); // o = sin(m)
static void vg_cos(ValueGrad* m, ValueGrad* o); // o = cos(m)
static void vg_tan(ValueGrad* m, ValueGrad* o); // o = tan(m)
static void vg_sqrt(ValueGrad* m, ValueGrad* o); // o = sqrt(m)
static void vg_exp(ValueGrad* m, ValueGrad* o);
static double vg_copy(ValueGrad* m, gsl_vector* ograd);
static void vg_copy(ValueGrad* i1, ValueGrad* i2); // copy i1 into i2
static void vg_cast_int_float(ValueGrad* m, ValueGrad* o);
static void vg_ite(ValueGrad* m, ValueGrad* f, DistanceGrad* d, ValueGrad* o); // o = ite(d, m, f)
static void vg_ite(ValueGrad* m, ValueGrad* f, ValueGrad* d, ValueGrad* o); // o = ite(d, m, f)
static void vg_ite(DistanceGrad* m, DistanceGrad* f, ValueGrad* d, DistanceGrad* o);
static void vg_ite(ValueGrad* m, ValueGrad* f, double dval, gsl_vector* dgrad, ValueGrad* o);
static double vg_ite(ValueGrad* m, ValueGrad* f, double cval, gsl_vector* cgrad, gsl_vector* ograd);
static double vg_or(ValueGrad* m, ValueGrad* f, gsl_vector* ograd);
static void vg_or(ValueGrad* m, ValueGrad* f, ValueGrad* o);
static double vg_and(ValueGrad* m, ValueGrad* f, gsl_vector* ograd);
static void vg_and(ValueGrad* m, ValueGrad* f, ValueGrad* o);
static void vg_not(ValueGrad* m, ValueGrad* o);
string print() {
stringstream str;
str << "Val: " << val;
return str.str();
}
string printFull() {
stringstream str;
str << "Val: " << val << endl;
str << "Grads: ";
for (int i = 0; i < grad->size; i++) {
str << gsl_vector_get(grad, i) << ", ";
}
str << endl;
if (val > 1e5 || gsl_blas_dnrm2(grad) > 1e5) {
str << "LARGE VALUES" << endl;
}
return str.str();
}
#ifdef _NOGSL
void bound() {
double oldVal = val;
val = GradUtil::bound(val);
if (oldVal != val) {
GradUtil::default_grad(grad);
}
int sz = grad->size;
double* it = grad->data;
for (int i = 0; i < sz; i++) {
*it = GradUtil::bound(*it);
++it;
}
}
#else
void bound() {
double oldVal = val;
val = GradUtil::bound(val);
if (oldVal != val) {
GradUtil::default_grad(grad);
}
for (int i = 0; i < grad->size; i++) {
gsl_vector_set(grad, i, GradUtil::bound(gsl_vector_get(grad, i)));
}
}
#endif
};
| {
"alphanum_fraction": 0.6585430464,
"avg_line_length": 32.5431034483,
"ext": "h",
"hexsha": "cfeb598918c5c7d11566450f5fba03dc85b4dd3f",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z",
"max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_forks_repo_licenses": [
"X11"
],
"max_forks_repo_name": "natebragg/sketch-backend",
"max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/ValueGrad.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z",
"max_issues_repo_licenses": [
"X11"
],
"max_issues_repo_name": "natebragg/sketch-backend",
"max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/ValueGrad.h",
"max_line_length": 105,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_stars_repo_licenses": [
"X11"
],
"max_stars_repo_name": "natebragg/sketch-backend",
"max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/DataStructures/ValueGrad.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z",
"num_tokens": 1202,
"size": 3775
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <time.h>
#include <assert.h>
#include "core_allvars.h"
#include "core_proto.h"
#include "temporal_array.h"
void init_galaxy(int p, int halonr, int treenr, int32_t filenr)
{
int32_t j, step, status;
assert(halonr == Halo[halonr].FirstHaloInFOFgroup);
Gal[p].FileNr = filenr;
Gal[p].Type = 0;
Gal[p].TreeNr = treenr;
Gal[p].GalaxyNr = GalaxyCounter;
GalaxyCounter++;
Gal[p].HaloNr = halonr;
Gal[p].MostBoundID = Halo[halonr].MostBoundID;
//Gal[p].MostBoundID = -1;
Gal[p].SnapNum = Halo[halonr].SnapNum - 1;
Gal[p].mergeType = 0;
Gal[p].mergeIntoID = -1;
Gal[p].mergeIntoSnapNum = -1;
Gal[p].dT = -1.0;
for(j = 0; j < 3; j++)
{
Gal[p].Pos[j] = Halo[halonr].Pos[j];
Gal[p].Vel[j] = Halo[halonr].Vel[j];
}
Gal[p].Len = Halo[halonr].Len;
Gal[p].Vmax = Halo[halonr].Vmax;
Gal[p].Vvir = get_virial_velocity(halonr);
Gal[p].Mvir = get_virial_mass(halonr);
Gal[p].Rvir = get_virial_radius(halonr);
Gal[p].deltaMvir = 0.0;
Gal[p].ColdGas = 0.0;
Gal[p].StellarMass = 0.0;
Gal[p].BulgeMass = 0.0;
Gal[p].HotGas = 0.0;
Gal[p].EjectedMass = 0.0;
Gal[p].EjectedMassSN = 0.0;
Gal[p].EjectedMassQSO = 0.0;
Gal[p].BlackHoleMass = 0.0;
Gal[p].ICS = 0.0;
Gal[p].MetalsColdGas = 0.0;
Gal[p].MetalsStellarMass = 0.0;
Gal[p].MetalsBulgeMass = 0.0;
Gal[p].MetalsHotGas = 0.0;
Gal[p].MetalsEjectedMass = 0.0;
Gal[p].MetalsICS = 0.0;
for(step = 0; step < STEPS; step++)
{
Gal[p].SfrDisk[step] = 0.0;
Gal[p].SfrBulge[step] = 0.0;
Gal[p].SfrDiskColdGas[step] = 0.0;
Gal[p].SfrDiskColdGasMetals[step] = 0.0;
Gal[p].SfrBulgeColdGas[step] = 0.0;
Gal[p].SfrBulgeColdGasMetals[step] = 0.0;
}
Gal[p].DiskScaleRadius = get_disk_radius(halonr, p);
Gal[p].MergTime = 999.9;
Gal[p].Cooling = 0.0;
Gal[p].Heating = 0.0;
Gal[p].r_heat = 0.0;
Gal[p].QuasarModeBHaccretionMass = 0.0;
Gal[p].TimeOfLastMajorMerger = -1.0;
Gal[p].TimeOfLastMinorMerger = -1.0;
Gal[p].OutflowRate = 0.0;
Gal[p].TotalSatelliteBaryons = 0.0;
// infall properties
Gal[p].infallMvir = -1.0;
Gal[p].infallVvir = -1.0;
Gal[p].infallVmax = -1.0;
Gal[p].IsMerged = -1;
status = malloc_temporal_arrays(&Gal[p]);
if (status == EXIT_FAILURE)
{
ABORT(EXIT_FAILURE);
}
++gal_mallocs;
for (j = 0; j < MAXSNAPS; ++j)
{
Gal[p].GridType[j] = -1;
Gal[p].GridFoFHaloNr[j] = -1;
Gal[p].GridHistory[j] = -1;
Gal[p].GridColdGas[j] = 0.0;
Gal[p].GridHotGas[j] = 0.0;
Gal[p].GridEjectedMass[j] = 0.0;
Gal[p].GridDustColdGas[j] = 0.0;
Gal[p].GridDustHotGas[j] = 0.0;
Gal[p].GridDustEjectedMass[j] = 0.0;
Gal[p].GridStellarMass[j] = 0.0;
Gal[p].GridBHMass[j] = 0.0;
Gal[p].GridSFR[j] = 0.0;
Gal[p].GridZ[j] = 0.0;
Gal[p].GridFoFMass[j] = 0.0;
Gal[p].GridHaloMass[j] = 0.0;
Gal[p].EjectedFraction[j] = 0.0;
Gal[p].EjectedFractionSN[j] = 0.0;
Gal[p].EjectedFractionQSO[j] = 0.0;
Gal[p].LenHistory[j] = -1;
Gal[p].GridOutflowRate[j] = 0.0;
Gal[p].GridInfallRate[j] = 0.0;
Gal[p].QuasarActivity[j] = 0;
Gal[p].QuasarSubstep[j] = -1;
Gal[p].DynamicalTime[j] = 0.0;
Gal[p].LenMergerGal[j] = -1;
Gal[p].GridReionMod[j] = -1.0;
Gal[p].GridNgamma_HI[j] = 0.0;
Gal[p].Gridfesc[j] = 0.0;
Gal[p].ColdCrit[j] = 0.0;
Gal[p].MUV[j] = 999.99;
}
Gal[p].GrandSum = 0.0;
Gal[p].StellarAge_Numerator = 0.0;
Gal[p].StellarAge_Denominator = 0.0;
Gal[p].reheated_mass = 0.0;
Gal[p].ejected_mass = 0.0;
Gal[p].mass_stars_recycled = 0.0;
Gal[p].mass_metals_new = 0.0;
Gal[p].NSN = 0.0;
if (IRA == 0)
{
for (j = 0; j < SN_Array_Len; ++j)
{
Gal[p].SN_Stars[j] = 0.0;
}
}
Gal[p].Total_SN_SF_Time = 0.0;
Gal[p].Total_SN_Stars = 0.0;
// Dust Reservoirs.
Gal[p].DustColdGas = 0.0;
Gal[p].DustHotGas = 0.0;
Gal[p].DustEjectedMass = 0.0;
// Quasar Activity Tracking
Gal[p].QuasarActivityToggle = 0;
Gal[p].TargetQuasarTime = 0.0;
Gal[p].QuasarBoostActiveTime = 0.0;
Gal[p].QuasarFractionalPhotons = 0.0;
// Stellar Age Tracking
if (PhotonPrescription == 1)
{
for (j = 0; j < StellarTracking_Len; ++j)
{
Gal[p].Stellar_Stars[j] = 0.0;
}
}
Gal[p].Total_Stellar_SF_Time = 0.0;
Gal[p].Total_Stellar_Stars = 0.0;
}
double get_disk_radius(int halonr, int p)
{
double SpinMagnitude, SpinParameter;
if(Gal[p].Vvir > 0.0 && Gal[p].Rvir > 0.0)
{
// See Mo, Shude & White (1998) eq12, and using a Bullock style lambda.
SpinMagnitude = sqrt(Halo[halonr].Spin[0] * Halo[halonr].Spin[0] +
Halo[halonr].Spin[1] * Halo[halonr].Spin[1] + Halo[halonr].Spin[2] * Halo[halonr].Spin[2]);
SpinParameter = SpinMagnitude / (1.414 * Gal[p].Vvir * Gal[p].Rvir);
return (SpinParameter / 1.414) * Gal[p].Rvir;
}
else
return 0.1 * Gal[p].Rvir;
}
double get_metallicity(double gas, double metals)
{
double metallicity;
if(gas > 0.0 && metals > 0.0)
{
metallicity = metals / gas;
if(metallicity < 1.0)
return metallicity;
else
return 1.0;
}
else
return 0.0;
}
double get_dust_fraction(double gas, double dust)
{
double dust_fraction;
if (gas > 0.0 && dust > 0.0)
{
dust_fraction = dust / gas;
if (dust_fraction < 1.0)
return dust_fraction;
else
return 1.0;
}
else
{
return 0.0;
}
}
double dmax(double x, double y)
{
if(x > y)
return x;
else
return y;
}
double get_virial_mass(int halonr)
{
if(halonr == Halo[halonr].FirstHaloInFOFgroup && Halo[halonr].Mvir >= 0.0)
{
++count_Mvir;
return Halo[halonr].Mvir; /* take spherical overdensity mass estimate */
}
else
{
++count_Len;
return Halo[halonr].Len * PartMass;
}
}
double get_virial_velocity(int halonr)
{
double Rvir;
Rvir = get_virial_radius(halonr);
if(Rvir > 0.0)
return sqrt(sage_G * get_virial_mass(halonr) / Rvir);
else
return 0.0;
}
double get_virial_radius(int halonr)
{
// return Halo[halonr].Rvir; // Used for Bolshoi
double zplus1, hubble_of_z_sq, rhocrit, fac;
zplus1 = 1 + ZZ[Halo[halonr].SnapNum];
hubble_of_z_sq =
sage_Hubble * sage_Hubble *(Omega * zplus1 * zplus1 * zplus1 + (1 - Omega - OmegaLambda) * zplus1 * zplus1 +
OmegaLambda);
rhocrit = 3 * hubble_of_z_sq / (8 * M_PI * sage_G);
fac = 1 / (200 * 4 * M_PI / 3.0 * rhocrit);
return cbrt(get_virial_mass(halonr) * fac);
}
int32_t determine_1D_idx(float pos_x, float pos_y, float pos_z, int32_t *grid_1D)
{
int32_t x_grid, y_grid, z_grid;
x_grid = round(pos_x * GridSize/BoxSize);
if (x_grid == GridSize)
--x_grid;
y_grid = round(pos_y * GridSize/BoxSize);
if (y_grid == GridSize)
--y_grid;
z_grid = round(pos_z * GridSize/BoxSize);
if (z_grid == GridSize)
--z_grid;
*grid_1D = (z_grid*GridSize+y_grid)*GridSize+x_grid; // Convert the grid (x,y,z) to a 1D value.
if(*grid_1D > CUBE(GridSize) || *grid_1D < 0) // Sanity check to ensure that no Grid Positions are outside the box.
{
fprintf(stderr, "Found a Grid Position outside the bounds of the box or negative\nPos[0] = %.4f\tPos[1] = %.4f\tPos[2] = %.4f\n", pos_x, pos_y, pos_z);
fprintf(stderr, "Grid indices were x = %d\ty = %d\tz = %d\t1D = %d\tMaximum Allowed = %d\n", x_grid, y_grid, z_grid, *grid_1D, CUBE(GridSize) - 1);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.6153743849,
"avg_line_length": 22.8541033435,
"ext": "c",
"hexsha": "af494f3f40b312e1c6ab4a839da5f42ec509cd6d",
"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": "b3b0a3fa3c676eab188991e37d06894396bfc74f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jacobseiler/rsage",
"max_forks_repo_path": "src/sage/model_misc.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f",
"max_issues_repo_issues_event_max_datetime": "2019-01-16T05:40:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-08-17T05:04:57.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jacobseiler/rsage",
"max_issues_repo_path": "src/sage/model_misc.c",
"max_line_length": 155,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "b3b0a3fa3c676eab188991e37d06894396bfc74f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jacobseiler/rsage",
"max_stars_repo_path": "src/sage/model_misc.c",
"max_stars_repo_stars_event_max_datetime": "2019-05-23T04:11:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-23T04:11:32.000Z",
"num_tokens": 2966,
"size": 7519
} |
/* Starting from version 7.8, MATLAB BLAS expects ptrdiff_t arguments for integers */
#if MATLAB_VERSION >= 0x0708
#include <stddef.h>
#include <stdlib.h>
#endif
/* Starting from version 7.6, MATLAB BLAS is seperated */
#if MATLAB_VERSION >= 0x0705
#include <blas.h>
#endif
#include <lapack.h>
#ifndef min
#define min(a,b) ((a) <= (b) ? (a) : (b))
#endif
| {
"alphanum_fraction": 0.6595174263,
"avg_line_length": 23.3125,
"ext": "h",
"hexsha": "e5aa2e0aad3da3401a2d275c208220a16138c9e0",
"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": "cd51554954c1bfb77f250751d586ae4c1ab7eec0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "krishnakumarg1984/EKF_DAE_example",
"max_forks_repo_path": "matrix_factorisations_mex_fileexchg/factor.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cd51554954c1bfb77f250751d586ae4c1ab7eec0",
"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": "krishnakumarg1984/EKF_DAE_example",
"max_issues_repo_path": "matrix_factorisations_mex_fileexchg/factor.h",
"max_line_length": 86,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "cd51554954c1bfb77f250751d586ae4c1ab7eec0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "krishnakumarg1984/EKF_DAE_example",
"max_stars_repo_path": "matrix_factorisations_mex_fileexchg/factor.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 106,
"size": 373
} |
#pragma once
#include "detail.h"
#include "schedule.h"
#include <gsl/gsl-lite.hpp>
#include <vector>
#ifndef UNIT_TEST
#include "random_utils.h"
#include "temperature.h"
#include "utils.h"
#else // UNIT_TEST
#include "stub/random_utils.h"
#include "stub/temperature.h"
#include "stub/utils.h"
#endif // UNIT_TEST
namespace angonoka::stun {
struct ScheduleParams;
/**
Stochastic tunneling algorithm.
The internal schedule can be updated as many times as
needed.
*/
class StochasticTunneling {
public:
/**
STUN auxiliary data and utilities.
@var mutator Instance of Mutator
@var random Instance of RandomUtils
@var makespan Instance of Makespan
@var temp Instance of Temperature
@var gamma Tunneling parameter
*/
struct Options {
gsl::not_null<const Mutator*> mutator;
gsl::not_null<RandomUtils*> random;
gsl::not_null<Makespan*> makespan;
gsl::not_null<Temperature*> temp;
float gamma;
};
/**
Default constructor.
The object will be in an uninitialized state. User must call
reset to set the initial schedule.
@param options Instance of StochasticTunneling::Options
*/
StochasticTunneling(const Options& options);
/**
Constructor.
@param options Instance of StochasticTunneling::Options
@param schedule Initial schedule
*/
StochasticTunneling(const Options& options, Schedule schedule);
StochasticTunneling(const StochasticTunneling& other);
StochasticTunneling(StochasticTunneling&& other) noexcept;
StochasticTunneling& operator=(const StochasticTunneling& other);
StochasticTunneling&
operator=(StochasticTunneling&& other) noexcept;
~StochasticTunneling() noexcept;
/**
Reset stochastic tunneling algorithm to a new
schedule.
@param schedule Initial schedule
*/
void reset(Schedule schedule);
/**
Set stochastic tunneling options.
@param options Instance of Options
*/
void options(const Options& options);
/**
Get stochastic tunneling options.
@return Stochastic tunneling options.
*/
[[nodiscard]] Options options() const;
/**
Update the internal state according to stochastic
tunneling algorithm.
*/
void update() noexcept;
/**
The best schedule so far.
@return A schedule.
*/
[[nodiscard]] Schedule schedule() const;
/**
The best makespan so far.
@return Makespan.
*/
[[nodiscard]] float normalized_makespan() const;
private:
struct Impl;
using index = MutSchedule::index_type;
gsl::not_null<const Mutator*> mutator;
gsl::not_null<RandomUtils*> random;
gsl::not_null<Makespan*> makespan;
gsl::not_null<Temperature*> temp;
std::vector<ScheduleItem> schedule_buffer;
MutSchedule best_schedule;
MutSchedule current_schedule;
MutSchedule target_schedule;
float current_e;
float lowest_e;
float target_e;
float gamma;
float current_s;
float target_s;
};
} // namespace angonoka::stun
| {
"alphanum_fraction": 0.6598873592,
"avg_line_length": 23.3284671533,
"ext": "h",
"hexsha": "d86207b61165d4dd81169588fb7455ef46347946",
"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": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "coffee-lord/angonoka",
"max_forks_repo_path": "src/stun/stochastic_tunneling.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "coffee-lord/angonoka",
"max_issues_repo_path": "src/stun/stochastic_tunneling.h",
"max_line_length": 69,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "coffee-lord/angonoka",
"max_stars_repo_path": "src/stun/stochastic_tunneling.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z",
"num_tokens": 713,
"size": 3196
} |
#include <cblas.h>
#include "tasks.h"
void syrk_task_seq(void *ptr)
{
struct syrk_task_arg *arg = (struct syrk_task_arg*) ptr;
int n = arg->n;
int k = arg->k;
double *A21 = arg->A21;
double *A22 = arg->A22;
int ldA = arg->ldA;
// Compute A22 := A21 - A21 * A21'.
cblas_dsyrk(CblasColMajor, CblasLower, CblasNoTrans,
n, k,
-1.0, A21, ldA,
1.0, A22, ldA);
}
| {
"alphanum_fraction": 0.5131004367,
"avg_line_length": 20.8181818182,
"ext": "c",
"hexsha": "9be59dc10e0ca05f4f62594635f5083f7a0f6bd5",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/pcp-runtime",
"max_forks_repo_path": "src/examples/dpotrf/task-syrk-seq.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/pcp-runtime",
"max_issues_repo_path": "src/examples/dpotrf/task-syrk-seq.c",
"max_line_length": 60,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/pcp-runtime",
"max_stars_repo_path": "src/examples/dpotrf/task-syrk-seq.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 155,
"size": 458
} |
/* specfunc/test_hyperg.c
*
* Copyright (C) 2007, 2009, 2010 Brian Gough
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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_test.h>
#include <gsl/gsl_sf.h>
#include "test_sf.h"
int test_hyperg(void)
{
gsl_sf_result r;
int s = 0;
/* 0F1 */
TEST_SF(s, gsl_sf_hyperg_0F1_e, (1, 0.5, &r), 1.5660829297563505373, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_0F1_e, (5, 0.5, &r), 1.1042674404828684574, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_0F1_e, (100, 30, &r), 1.3492598639485110176, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_0F1_e, (-0.5, 3, &r), -39.29137997543434276, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_0F1_e, (-100.5, 50, &r), 0.6087930289227538496, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_0F1_e, (1, -5.0, &r), -0.3268752818235339109, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_0F1_e, (-0.5, -5.0, &r),-4.581634759005381184, TEST_TOL1, GSL_SUCCESS);
/* 1F1 for integer parameters */
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (1, 1, 0.5, &r), 1.6487212707001281468, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (1, 2, 500.0, &r), 2.8071844357056748215e+214, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (1, 2, -500.0, &r), 0.002, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (8, 1, 0.5, &r), 13.108875178030540372, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 1, 1.0, &r), 131.63017574352619931, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 1, 10.0, &r), 8.514625476546280796e+09, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 1, 100.0, &r), 1.5671363646800353320e+56, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 20, 1.0, &r), 1.6585618002669675465, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 20, 10.0, &r), 265.26686430340188871, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 20, 100.0, &r), 3.640477355063227129e+34, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 100, 1.0, &r), 1.1056660194025527099, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 100, 10.0, &r), 2.8491063634727594206, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 100, 40.0, &r), 133.85880835831230986, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 100, 80.0, &r), 310361.16228011433406, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 100, 100.0, &r), 8.032171336754168282e+07, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 100, 500.0, &r), 7.633961202528731426e+123, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 1, 1.0, &r), 6.892842729046469965e+07, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 1, 10.0, &r), 2.4175917112200409098e+28, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 1, 100.0, &r), 1.9303216896309102993e+110, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 200, 1.0, &r), 1.6497469106162459226, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 200, 10.0, &r), 157.93286197349321981, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 200, 100.0, &r), 2.1819577501255075240e+24, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 200, 400.0, &r), 3.728975529926573300e+119, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 400, 10.0, &r), 12.473087623658878813, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 400, 100.0, &r), 9.071230376818550241e+11, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 400, 150.0, &r), 7.160949515742170775e+18, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 400, 200.0, &r), 2.7406690412731576823e+26, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 400, 300.0, &r), 6.175110613473276193e+43, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 400, 400.0, &r), 1.1807417662711371440e+64, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 400, 600.0, &r), 2.4076076354888886030e+112, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 1, -1.0, &r), 0.11394854824644542810, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 1, -10.0, &r), 0.0006715506365396127863, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 1, -100.0, &r), -4.208138537480269868e-32, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 50, -1.0, &r), 0.820006196079380, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 100, -10.0, &r), 0.38378859043466243, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 100, -100.0, &r), 0.0008460143401464189061, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 100, -500.0, &r), 1.1090822141973655929e-08, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (10, 100, -10000.0, &r), 5.173783508088272292e-21, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (50, 1, -90.0, &r), -1.6624258547648311554e-21, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (50, 1, -100.0, &r), 4.069661775122048204e-24, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (50, 1, -110.0, &r), 1.0072444993946236025e-25, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 10, -100.0, &r), -2.7819353611733941962e-37, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 1, -90.0, &r), 7.501705041159802854e-22, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 1, -100.0, &r), 6.305128893152291187e-25, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 1, -110.0, &r), -7.007122115422439755e-26, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (100, 10, -100.0, &r), -2.7819353611733941962e-37, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (200, 50, -1.0, &r), 0.016087060191732290813, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (200, 50, -300.0, &r), -4.294975979706421471e-121, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (200, 100, -1.0, &r), 0.13397521083325179687, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (200, 100, -10.0, &r), 5.835134393749807387e-10, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (200, 100, -100.0, &r), 4.888460453078914804e-74, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (200, 100, -500.0, &r), -1.4478509059582015053e-195, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-1, 1, 2.0, &r), -1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-1, -2, 2.0, &r), 2.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-2, -3, 2.0, &r), 3.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, 1, 1.0, &r), 0.4189459325396825397, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, 1, 10.0, &r), 27.984126984126984127, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, 1, 100.0, &r), 9.051283795429571429e+12, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-100, 20, 1.0, &r), 0.0020203016320697069566, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, -20, 1.0, &r), 1.6379141878548080173, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, -20, 10.0, &r), 78.65202404521289970, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, -20, 100.0, &r), 4.416169713262624315e+08, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, -100, 1.0, &r), 1.1046713999681950919, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, -100, 10.0, &r), 2.6035952191039006838, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, -100, 100.0, &r), 1151.6852040836932392, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-100, -200, 1.0, &r), 1.6476859702535324743, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-100, -200, 10.0, &r), 139.38026829540687270, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-100, -200, 100.0, &r), 1.1669433576237933752e+19, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, -20, -1.0, &r), 0.6025549561148035735, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, -20, -10.0, &r), 0.00357079636732993491, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, -20, -100.0, &r), 1.64284868563391159e-35, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, -100, -1.0, &r), 0.90442397250313899, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, -100, -10.0, &r), 0.35061515251367215, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-10, -100, -100.0, &r), 8.19512187960476424e-09, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-100, -200, -1.0, &r), 0.6061497939628952629, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-100, -200, -10.0, &r), 0.0063278543908877674, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-100, -200, -100.0, &r), 4.34111795007336552e-25, TEST_TOL2, GSL_SUCCESS);
/* 1F1 */
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1, 1.5, 1, &r), 2.0300784692787049755, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1, 1.5, 10, &r), 6172.859561078406855, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1, 1.5, 100, &r), 2.3822817898485692114e+42, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1, 1.5, 500, &r), 5.562895351723513581e+215, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1.5, 2.5, 1, &r), 1.8834451238277954398, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1.5, 2.5, 10, &r), 3128.7352996840916381, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (10, 1.1, 1, &r), 110.17623733873889579, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (10, 1.1, 10, &r), 6.146657975268385438e+09, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (10, 1.1, 100, &r), 9.331833897230312331e+55, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (10, 1.1, 500, &r), 4.519403368795715843e+235, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (10, 50.1, 2, &r), 1.5001295507968071788, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (10, 50.1, 10, &r), 8.713385849265044908, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (10, 50.1, 100, &r), 5.909423932273380330e+18, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (10, 50.1, 500, &r), 9.740060618457198900e+165, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 1.1, 1, &r), 5.183531067116809033e+07, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 1.1, 10, &r), 1.6032649110096979462e+28, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 1.1, 100, &r), 1.1045151213192280064e+110, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 50.1, 1, &r), 7.222953133216603757, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 50.1, 10, &r), 1.0998696410887171538e+08, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 50.1, 100, &r), 7.235304862322283251e+63, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1, 1.5, -1, &r), 0.5380795069127684191, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1, 1.5, -10, &r), 0.05303758099290164485, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1, 1.5, -100, &r), 0.005025384718759852803, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1, 1.5, -500, &r), 0.0010010030151059555322, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1, 1.1, -500, &r), 0.00020036137599690208265, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (10, 1.1, -1, &r), 0.07227645648935938168, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (10, 1.1, -10, &r), 0.0003192415409695588126, TEST_TOL1, GSL_SUCCESS);
/*
sensitive to the pair_ratio hack in hyperg_1F1.c
TEST_SF_RLX(s, gsl_sf_hyperg_1F1_e, (10, 1.1, -100, &r), -8.293425316123158950e-16, 50.0*TEST_SNGL, GSL_SUCCESS);
*/
TEST_SF(s, gsl_sf_hyperg_1F1_e, (10, 1.1, -500, &r), -3.400379216707701408e-23, TEST_TOL2, GSL_SUCCESS);
TEST_SF_RLX(s, gsl_sf_hyperg_1F1_e, (50, 1.1, -90, &r), -7.843129411802921440e-22, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (50, 1.1, -100, &r), 4.632883869540640460e-24, TEST_SQRT_TOL0, GSL_SUCCESS);
/* FIXME:
tolerance is poor, but is consistent within reported error
*/
TEST_SF(s, gsl_sf_hyperg_1F1_e, (50, 1.1, -110.0, &r), 5.642684651305310023e-26, 0.03, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 1.1, -1, &r), 0.0811637344096042096, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 1.1, -10, &r), 0.00025945610092231574387, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 1.1, -50, &r), 2.4284830988994084452e-13, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 1.1, -90, &r), 2.4468224638378426461e-22, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 1.1, -99, &r), 1.0507096272617608461e-23, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 1.1, -100, &r), 1.8315497474210138602e-24, TEST_TOL2, GSL_SUCCESS);
/* FIXME:
Reported error is too small.
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 1.1, -101, &r), -2.3916306291344452490e-24, 0.04, GSL_SUCCESS);
*/
/* FIXME:
Reported error is too small.
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 1.1, -110, &r), -4.517581986037732280e-26, TEST_TOL0, GSL_SUCCESS);
*/
/* FIXME:
Result is terrible, but reported error is very large, so consistent.
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, 10.1, -220, &r), -4.296130300021696573e-64, TEST_TOL1, GSL_SUCCESS);
*/
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-10, -10.1, 10.0, &r), 10959.603204633058116, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-10, -10.1, 1000.0, &r), 2.0942691895502242831e+23, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-10, -100.1, 10.0, &r), 2.6012036337980078062, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-1000, -1000.1, 10.0, &r), 22004.341698908631636, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-1000, -1000.1, 200.0, &r), 7.066514294896245043e+86, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-8.1, -10.1, -10.0, &r), 0.00018469685276347199258, TEST_TOL0, GSL_SUCCESS);
/* TEST_SF(s, gsl_sf_hyperg_1F1_e, (-8.1, -1000.1, -10.0, &r), 0.9218280185080036020, TEST_TOL0, GSL_SUCCESS); */
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-10, -5.1, 1, &r), 16.936141866089601635, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-10, -5.1, 10, &r), 771534.0349543820541, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-10, -5.1, 100, &r), 2.2733956505084964469e+17, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, -50.1, -1, &r), 0.13854540373629275583, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, -50.1, -10, &r), -9.142260314353376284e+19, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, -50.1, -100, &r), -1.7437371339223929259e+87, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, -50.1, 1, &r), 7.516831748170351173, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, -50.1, 10, &r), 1.0551632286359671976e+11, TEST_SQRT_TOL0, GSL_SUCCESS);
/*
These come out way off. On the other hand, the error estimates
are also very large; so much so that the answers are consistent
within the reported error. Something will need to be done about
this eventually
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, -50.1, 50, &r), -7.564755600940346649e+36, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, -50.1, 100, &r), 4.218776962675977e+55, TEST_TOL3, GSL_SUCCESS);
*/
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-10.5, -8.1, 0.1, &r), 1.1387201443786421724, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-10.5, -11.1, 1, &r), 2.5682766147138452362, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100.5, -80.1, 10, &r), 355145.4517305220603, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100.5, -102.1, 10, &r), 18678.558725244365016, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100.5, -500.1, 10, &r), 7.342209011101454, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100.5, -500.1, 100, &r), 1.2077443075367177662e+8, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-500.5, -80.1, 2, &r), 774057.8541325341699, TEST_TOL4, GSL_SUCCESS);
/*
UNIMPL
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, -10.1, 1, &r), -2.1213846338338567395e+12, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, -10.1, 10, &r), -6.624849346145112398e+39, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, -10.1, 100, &r), -1.2413466759089171904e+129, TEST_TOL0, GSL_SUCCESS);
*/
/*
UNIMPL
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, -10.1, -1, &r), 34456.29405305551691, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, -10.1, -10, &r), -7.809224251467710833e+07, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (100, -10.1, -100, &r), -5.214065452753988395e-07, TEST_TOL0, GSL_SUCCESS);
*/
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, 1.1, 1, &r), 0.21519810496314438414, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, 1.1, 10, &r), 8.196123715597869948, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, 1.1, 100, &r), -1.4612966715976530293e+20, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, 20.1, 1, &r), 0.0021267655527278456412, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, 20.1, 10, &r), 2.0908665169032186979e-11, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, 20.1, 100, &r), -0.04159447537001340412, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, 1.1, -1, &r), 2.1214770215694685282e+07, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, 1.1, -10, &r), 1.0258848879387572642e+24, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, 1.1, -100, &r), 1.1811367147091759910e+67, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, 50.1, -1, &r), 6.965259317271427390, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, 50.1, -10, &r), 1.0690052487716998389e+07, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-100, 50.1, -100, &r), 6.889644435777096248e+36, TEST_TOL3, GSL_SUCCESS);
/* Bug report from Fernando Pilotto */
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-2.05, 1.0, 5.05, &r), 3.79393389516785e+00, TEST_TOL3, GSL_SUCCESS);
/* Bug reports from Ivan Liu */
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-26, 2.0, 100.0, &r), 1.444786781107436954e+19, TEST_TOL3, GSL_SUCCESS);
#ifdef FIXME
/* This one is computed with a huge error, there is loss of
precision but the error estimate flags the problem (assuming the
user looks at it). We should probably trap any return with
err>|val| and signal loss of precision */
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-26.1, 2.0, 100.0, &r), 1.341557199575986995e+19, TEST_TOL3, GSL_SUCCESS);
#endif
/* Bug report H.Moseby */
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1.2, 1.1e-15, 1.5, &r), 8254503159672429.02, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1.0, 1000000.5, 0.8e6 + 0.5, &r), 4.999922505099443804e+00, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1.0, 1000000.5, 1001000.5, &r), 3480.3699557431856166, TEST_TOL4, GSL_SUCCESS);
#ifdef FIXME /* FIX THESE NEXT RELEASE */
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1.1, 1000000.5, 1001000.5, &r), 7304.6126942641350122, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (0.9, 1000000.5, 1001000.5, &r), 1645.4879293475410982, TEST_TOL3, GSL_SUCCESS);
#endif
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-1.1, 1000000.5, 1001000.5, &r), -5.30066488697455e-04, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (1.5, 1000000.5, 0.8e6 + 0.5, &r), 11.18001288977894650469927615, TEST_TOL4, GSL_SUCCESS);
/* Bug report Lorenzo Moneta <Lorenzo.Moneta@cern.ch> */
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-1.5, 1.5, -100., &r), 456.44010011787485545, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-1.5, 1.5, 99., &r), 4.13360436014643309757065e36, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-1.5, 1.5, 100., &r), 1.0893724312430935129254e37, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-1.5, 1.5, 709., &r), 8.7396804160264899999692120e298, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-1.5, 1.5, 710., &r), 2.36563187217417898169834615e299, TEST_TOL4, GSL_SUCCESS);
/* Bug report from Weibin Li <weibinli@mpipks-dresden.mpg.de> */
#ifdef FIXME
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-37.8, 2.01, 103.58, &r), -6.21927211009e17, TEST_TOL1, GSL_SUCCESS);
#endif
/* Testing BJG */
#ifdef COMPARISON_WITH_MATHEMATICA
/* Mathematica uses a different convention for M(-m,-n,x) */
TEST_SF(s, gsl_sf_hyperg_1F1_int_e, (-1, -1, 0.1, &r), 1.1, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_1F1_e, (-1, -1, 0.1, &r), 1.1, TEST_TOL0, GSL_SUCCESS);
#endif
/* U for integer parameters */
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 1, 0.0001, &r), 8.634088070212725330, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 1, 0.01, &r), 4.078511443456425847, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 1, 0.5, &r), 0.9229106324837304688, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 1, 2.0, &r), 0.3613286168882225847, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 1, 100, &r), 0.009901942286733018406, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 1, 1000, &r), 0.0009990019940238807150, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 8, 0.01, &r), 7.272361203006010000e+16, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 8, 1, &r), 1957.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 8, 5, &r), 1.042496, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 8, 8, &r), 0.3207168579101562500, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 8, 50, &r), 0.022660399001600000000, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 8, 100, &r), 0.010631236727200000000, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 8, 1000, &r), 0.0010060301203607207200, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 20, 1, &r), 1.7403456103284421000e+16, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 20, 20, &r), 0.22597813610531052969, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 50, 1, &r), 3.374452117521520758e+61, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 50, 50, &r), 0.15394136814987651785, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 100, 0.1, &r), 1.0418325171990852858e+253, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 100, 1, &r), 2.5624945006073464385e+154, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 100, 50, &r), 3.0978624160896431391e+07, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 100, 100, &r), 0.11323192555773717475, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 100, 200, &r), 0.009715680951406713589, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 100, 1000, &r), 0.0011085142546061528661, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, 1000, 2000, &r), 0.0009970168547036318206, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -1, 1, &r), 0.29817368116159703717, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -1, 10, &r), 0.07816669698940409380, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -10, 1, &r), 0.08271753756946041959, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -10, 5, &r), 0.06127757419425055261, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -10, 10, &r), 0.04656199948873187212, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -10, 20, &r), 0.031606421847946077709, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -100, 0.01, &r), 0.009900000099999796950, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -100, 1, &r), 0.009802970197050404429, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -100, 10, &r), 0.009001648897173103447, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -100, 20, &r), 0.008253126487166557546, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -100, 50, &r), 0.006607993916432051008, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -100, 90, &r), 0.005222713769726871937, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -100, 110, &r), 0.004727658137692606210, TEST_TOL2, GSL_SUCCESS);
TEST_SF_RLX(s, gsl_sf_hyperg_U_int_e, (1, -1000, 1, &r), 0.0009980029970019970050, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (1, -1000, 1010, &r), 0.0004971408839859245170, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (8, 1, 0.001, &r), 0.0007505359326875706975, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (8, 1, 0.5, &r), 6.449509938973479986e-06, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (8, 1, 8, &r), 6.190694573035761284e-10, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (8, 1, 20, &r), 3.647213845460374016e-12, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (8, 8, 1, &r), 0.12289755012652317578, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (8, 8, 10, &r), 5.687710359507564272e-09, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (8, 8, 20, &r), 2.8175404594901039724e-11, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (100, 100, 0.01, &r), 1.0099979491941914867e+196, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (100, 100, 0.1, &r), 1.0090713562719862833e+97, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (100, 100, 1, &r), 0.009998990209084729106, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (100, 100, 20, &r), 1.3239363905866130603e-131, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-10, 1, 0.01, &r), 3.274012540759009536e+06, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-10, 1, 1, &r), 1.5202710000000000000e+06, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-10, 1, 10, &r), 1.0154880000000000000e+08, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-10, 1, 100, &r), 3.284529863685482880e+19, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-10, 10, 1, &r), 1.1043089864100000000e+11, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-10, 100, 1, &r), 1.3991152402448957897e+20, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-10, 100, 10, &r), 5.364469916567136000e+19, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-10, 100, 100, &r), 3.909797568000000000e+12, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-10, 100, 500, &r), 8.082625576697984130e+25, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-50, 1, 0.01, &r), 1.6973422555823855798e+64, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-50, 1, 1, &r), 7.086160198304780325e+63, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-50, 1, 10, &r), 5.332862895528712200e+65, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-50, 10, 1, &r), -7.106713471565790573e+71, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-50, 100, 1, &r), 2.4661377199407186476e+104, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-50, 10, 10, &r), 5.687538583671241287e+68, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-50, 100, 10, &r), 1.7880761664553373445e+102, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-90, 1, 0.01, &r), 4.185245354032917715e+137, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-90, 1, 0.1, &r), 2.4234043408007841358e+137, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-90, 1, 10, &r), -1.8987677149221888807e+139, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-90, 10, 10, &r), -5.682999988842066677e+143, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-90, 100, 10, &r), 2.3410029853990624280e+189, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-90, 1000, 10, &r), 1.9799451517572225316e+271, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-50, -1, 10, &r), -9.083195466262584149e+64, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-50, -10, 10, &r), -1.4418257327071634407e+62, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-50, -100, 0.01, &r), 3.0838993811468983931e+93, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-50, -100, 10, &r), 4.014552630378340665e+95, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-100, -100, 10, &r), 2.0556466922347982030e+162, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-100, -200, 10, &r), 1.1778399522973555582e+219, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (-100, -200, 100, &r), 9.861313408898201873e+235, TEST_TOL3, GSL_SUCCESS);
/* U */
TEST_SF(s, gsl_sf_hyperg_U_e, (0.0001, 0.0001, 0.0001, &r), 1.0000576350699863577, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0.0001, 0.0001, 1.0, &r), 0.9999403679233247536, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0.0001, 0.0001, 100.0, &r), 0.9995385992657260887, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0.0001, 1, 0.0001, &r), 1.0009210608660065989, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0.0001, 1.0, 1.0, &r), 0.9999999925484179084, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0.0001, 10, 1, &r), 13.567851006281412726, TEST_TOL3, GSL_SUCCESS);
TEST_SF_RLX(s, gsl_sf_hyperg_U_e, (0.0001, 10, 5, &r), 1.0006265020064596364, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0.0001, 10, 10, &r), 0.9999244381454633265, TEST_TOL0, GSL_SUCCESS);
TEST_SF_RLX(s, gsl_sf_hyperg_U_e, (0.0001, 100, 1, &r), 2.5890615708804247881e+150, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF_RLX(s, gsl_sf_hyperg_U_e, (0.0001, 100, 10, &r), 2.3127845417739661466e+55, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF_RLX(s, gsl_sf_hyperg_U_e, (0.0001, 100, 50, &r), 6402.818715083582554, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0.0001, 100, 98, &r), 0.9998517867411840044, TEST_TOL2, GSL_SUCCESS);
TEST_SF_RLX(s, gsl_sf_hyperg_U_e, (0.0001, 1000, 300, &r), 2.5389557274938010716e+213, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0.0001, 1000, 999, &r), 0.9997195294193261604, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0.0001, 1000, 1100, &r), 0.9995342990014584713, TEST_TOL1, GSL_SUCCESS);
TEST_SF_RLX(s, gsl_sf_hyperg_U_e, (0.5, 1000, 300, &r), 1.1977955438214207486e+217, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0.5, 1000, 800, &r), 9.103916020464797207e+08, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0.5, 1000, 998, &r), 0.21970269691801966806, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0.5, 0.5, 1.0, &r), 0.7578721561413121060, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (1, 0.0001, 0.0001, &r), 0.9992361337764090785, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (1, 0.0001, 1, &r), 0.4036664068111504538, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (1, 0.0001, 100, &r), 0.009805780851264329587, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (1, 1.2, 2.0, &r), 0.3835044780075602550, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (1, -0.0001, 1, &r), 0.4036388693605999482, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (8, 10.5, 1, &r), 27.981926466707438538, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (8, 10.5, 10, &r), 2.4370135607662056809e-8, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (8, 10.5, 100, &r), 1.1226567526311488330e-16, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (10, -2.5, 10, &r), 6.734690720346560349e-14, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (10, 2.5, 10, &r), 6.787780794037971638e-13, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (10, 2.5, 50, &r), 2.4098720076596087125e-18, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 1.1, 1, &r), -3.990841457734147e+6, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 1.1, 10, &r), 1.307472052129343e+8, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 1.1, 50, &r), 3.661978424114088e+16, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 1.1, 90, &r), 8.09469542130868e+19, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 1.1, 99, &r), 2.546328328942063e+20, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 1.1, 100, &r), 2.870463201832814e+20, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 1.1, 200, &r), 8.05143453769373e+23, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 10.1, 0.1, &r), -3.043016255306515e+20, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 10.1, 1, &r), -3.194745265896115e+12, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 10.1, 4, &r), -6.764203430361954e+07, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 10.1, 10, &r), -2.067399425480545e+09, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 10.1, 50, &r), 4.661837330822824e+14, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 100.4, 10, &r), -6.805460513724838e+66, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 100.4, 50, &r), -2.081052558162805e+18, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 100.4, 80, &r), 2.034113191014443e+14, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 100.4, 100, &r), 6.85047268436107e+13, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-10.5, 100.4, 200, &r), 1.430815706105649e+20, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-19.5, 82.1, 10, &r), 5.464313196201917432e+60, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-50.5, 100.1, 10, &r), -5.5740216266953e+126, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-50.5, 100.1, 40, &r), 5.937463786613894e+91, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-50.5, 100.1, 50, &r), -1.631898534447233e+89, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-50.5, 100.1, 70, &r), 3.249026971618851e+84, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-50.5, 100.1, 100, &r), 1.003401902126641e+85, TEST_TOL1, GSL_SUCCESS);
/* Bug report from Stefan Gerlach */
TEST_SF(s, gsl_sf_hyperg_U_e, (-2.0, 4.0, 1.0, &r), 11.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2.0, 0.5, 3.14, &r), 1.1896, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2.0, 0.5, 1.13, &r), -1.3631, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2.0, 0.5, 0.0, &r), 0.75, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2.0, 0.5, 1e-20, &r), 0.75, TEST_TOL2, GSL_SUCCESS);
/* U(a,b,x) for x<0 [bug #27859] */
/* Tests for b >= 0 */
TEST_SF(s, gsl_sf_hyperg_U_e, ( 0, 0, -0.1, &r), 1, TEST_TOL0, GSL_SUCCESS);
#ifdef FIXME /* unimplemented case */
TEST_SF(s, gsl_sf_hyperg_U_e, (-1, 0, -0.1, &r), -0.1, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2, 0, -0.1, &r), 0.21, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-3, 0, -0.1, &r), -0.661, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-4, 0, -0.1, &r), 2.7721, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-5, 0, -0.1, &r), -14.52201, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-6, 0, -0.1, &r), 91.230301, TEST_TOL0, GSL_SUCCESS);
#endif
TEST_SF(s, gsl_sf_hyperg_U_e, ( 0, 1, -0.1, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-1, 1, -0.1, &r), -1.1, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2, 1, -0.1, &r), 2.41, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-3, 1, -0.1, &r), -7.891, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-4, 1, -0.1, &r), 34.3361, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-5, 1, -0.1, &r), -186.20251, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-6, 1, -0.1, &r), 1208.445361, TEST_TOL0, GSL_SUCCESS);
#ifdef FIXME /* unimplemented case */
TEST_SF(s, gsl_sf_hyperg_U_e, ( 1, 2, -0.1, &r), -10.0, TEST_TOL0, GSL_SUCCESS);
#endif
TEST_SF(s, gsl_sf_hyperg_U_e, ( 0, 2, -0.1, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-1, 2, -0.1, &r), -2.1, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2, 2, -0.1, &r), 6.61, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-3, 2, -0.1, &r), -27.721, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-4, 2, -0.1, &r), 145.2201, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-5, 2, -0.1, &r), -912.30301, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-6, 2, -0.1, &r), 6682.263421, TEST_TOL0, GSL_SUCCESS);
#ifdef FIXME /* unimplemented case */
TEST_SF(s, gsl_sf_hyperg_U_e, ( 2, 3, -0.1, &r), 100.0, TEST_TOL0, GSL_SUCCESS);
#endif
TEST_SF(s, gsl_sf_hyperg_U_e, ( 1, 3, -0.1, &r), 90.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, ( 0, 3, -0.1, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-1, 3, -0.1, &r), -3.10, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2, 3, -0.1, &r), 12.81, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-3, 3, -0.1, &r), -66.151, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-4, 3, -0.1, &r), 409.8241, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-5, 3, -0.1, &r), -2961.42351, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-6, 3, -0.1, &r), 24450.804481, TEST_TOL0, GSL_SUCCESS);
#ifdef FIXME /* unimplemented case */
TEST_SF(s, gsl_sf_hyperg_U_e, ( 3, 4, -0.1, &r), -1000.0, TEST_TOL0, GSL_SUCCESS);
#endif
TEST_SF(s, gsl_sf_hyperg_U_e, ( 2, 4, -0.1, &r), -1900.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, ( 1, 4, -0.1, &r), -1810.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, ( 0, 4, -0.1, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-1, 4, -0.1, &r), -4.10, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2, 4, -0.1, &r), 21.01, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-3, 4, -0.1, &r), -129.181, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-4, 4, -0.1, &r), 926.5481, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-5, 4, -0.1, &r), -7594.16401, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-6, 4, -0.1, &r), 70015.788541, TEST_TOL0, GSL_SUCCESS);
/* Tests for b < 0 */
TEST_SF(s, gsl_sf_hyperg_U_e, ( 0, -1, -0.1, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
#ifdef FIXME /* unimplemented case */
TEST_SF(s, gsl_sf_hyperg_U_e, (-1, -1, -0.1, &r), 0.9, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2, -1, -0.1, &r), 0.01, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-3, -1, -0.1, &r), -0.031, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-4, -1, -0.1, &r), 0.1281, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-5, -1, -0.1, &r), -0.66151, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-6, -1, -0.1, &r), 4.098241, TEST_TOL0, GSL_SUCCESS);
#endif
TEST_SF(s, gsl_sf_hyperg_U_e, ( 0, -2, -0.1, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-1, -2, -0.1, &r), 1.9, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2, -2, -0.1, &r), 1.81, TEST_TOL0, GSL_SUCCESS);
#ifdef FIXME /* unimplemented case */
TEST_SF(s, gsl_sf_hyperg_U_e, (-3, -2, -0.1, &r), -0.001, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-4, -2, -0.1, &r), 0.0041, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-5, -2, -0.1, &r), -0.02101, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-6, -2, -0.1, &r), 0.129181, TEST_TOL0, GSL_SUCCESS);
#endif
TEST_SF(s, gsl_sf_hyperg_U_e, ( 0, -3, -0.1, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-1, -3, -0.1, &r), 2.9, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2, -3, -0.1, &r), 5.61, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-3, -3, -0.1, &r), 5.429, TEST_TOL0, GSL_SUCCESS);
#ifdef FIXME /* unimplemented case */
TEST_SF(s, gsl_sf_hyperg_U_e, (-4, -3, -0.1, &r), 0.0001, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-5, -3, -0.1, &r), -0.00051, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-6, -3, -0.1, &r), 0.003121, TEST_TOL0, GSL_SUCCESS);
#endif
TEST_SF(s, gsl_sf_hyperg_U_e, ( 0, -4, -0.1, &r), 1.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-1, -4, -0.1, &r), 3.9, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2, -4, -0.1, &r), 11.41, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-3, -4, -0.1, &r), 22.259, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-4, -4, -0.1, &r), 21.7161, TEST_TOL0, GSL_SUCCESS);
#ifdef FIXME /* unimplemented case */
TEST_SF(s, gsl_sf_hyperg_U_e, (-5, -4, -0.1, &r), -1e-5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-6, -4, -0.1, &r), 0.000061, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-7, -4, -0.1, &r), -0.0004341, TEST_TOL0, GSL_SUCCESS);
#endif
/* Tests for integer a */
TEST_SF(s, gsl_sf_hyperg_U_e, (-3, 0.5, -0.5, &r), -9.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-8, 0.5, -0.5, &r), 180495.0625, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-8, 1.5, -0.5, &r), 827341.0625, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-8, 1.5, -10, &r), 7.162987810253906e9, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (3, 6, -0.5, &r), -296.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (3, 7, -0.5, &r), 2824, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (5, 12, -1.7, &r), -153.262676210016018065768591104, TEST_TOL0, GSL_SUCCESS);
/* A few random tests */
TEST_SF(s, gsl_sf_hyperg_U_e, (0, 0, -0.5, &r), 1, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0, 1, -0.5, &r), 1, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (0, 1, -0.001, &r), 1, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-1, 0.99, -0.1, &r), -1.09, TEST_TOL0, GSL_SUCCESS);
#ifdef FIXME /* unimplemented case */
TEST_SF(s, gsl_sf_hyperg_U_e, (-1, 0, -0.5, &r), -0.5, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-2, 0, -0.5, &r), 1.25, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_e, (-7, 0, -0.1, &r), -668.2263421, TEST_TOL0, GSL_SUCCESS);
#endif
TEST_SF(s, gsl_sf_hyperg_U_int_e, (3, 6, -0.5, &r), -296.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (3, 7, -0.5, &r), 2824, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_U_int_e, (5, 12, -1.7, &r), -153.262676210016018065768591104, TEST_TOL0, GSL_SUCCESS);
/* 2F1 */
TEST_SF(s, gsl_sf_hyperg_2F1_e, (1, 1, 1, 0.5, &r), 2.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (8, 8, 1, 0.5, &r), 12451584.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (8, -8, 1, 0.5, &r), 0.13671875, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (8, -8.1, 1, 0.5, &r), 0.14147385378899930422, TEST_TOL4, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (8, -8, 1, -0.5, &r), 4945.136718750000000, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (8, -8, -5.5, 0.5, &r), -906.6363636363636364, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (8, -8, -5.5, -0.5, &r), 24565.363636363636364, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (8, 8, 1, -0.5, &r), -0.006476312098196747669, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (8, 8, 5, 0.5, &r), 4205.714285714285714, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (8, 8, 5, -0.5, &r), 0.0028489656290296436616, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (9, 9, 1, 0.99, &r), 1.2363536673577259280e+38 , TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (9, 9, -1.5, 0.99, &r), 3.796186436458346579e+46, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (9, 9, -1.5, -0.99, &r), 0.14733409946001025146, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (9, 9, -8.5, 0.99, &r), -1.1301780432998743440e+65, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (9, 9, -8.5, -0.99, &r), -8.856462606575344483, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (9, 9, -21.5, 0.99, &r), 2.0712920991876073253e+95, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (9, 9, -21.5, -0.99, &r), -74.30517015382249216, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (9, 9, -100.5, 0.99, &r), -3.186778061428268980e+262, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (9, 9, -100.5, -0.99, &r), 2.4454358338375677520, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (25, 25, 1, -0.5, &r), -2.9995530823639545027e-06, TEST_SQRT_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (1.5, 0.5, 2.0, 1.0-1.0/64.0, &r), 3.17175539044729373926, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (1.5, 0.5, 2.0, 1.0-1.0/128.0, &r), 3.59937243502024563424, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (1.5, 0.5, 2.0, 1.0-1.0/256.0, &r), 4.03259299524392504369, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (1.5, 0.5, 2.0, 1.0-1.0/1024.0, &r), 4.90784159359675398250, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (1.5, 0.5, 2.0, 1.0-1.0/65536.0, &r), 7.552266033399683914, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (1.5, 0.5, 2.0, 1.0-1.0/16777216.0, &r), 11.08235454026043830363, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (1.5, 0.5, 2.0, -1.0+1.0/1024.0, &r), 0.762910940909954974527, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (1.5, 0.5, 2.0, -1.0+1.0/65536.0, &r), 0.762762124908845424449, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (1.5, 0.5, 2.0, -1.0+1.0/1048576.0, &r), 0.762759911089064738044, TEST_TOL0, GSL_SUCCESS);
/* added special handling with x == 1.0 , Richard J. Mathar, 2008-01-09 */
TEST_SF(s, gsl_sf_hyperg_2F1_e, (1.5, 0.5, 3.0, 1.0, &r), 1.6976527263135502482014268 , TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (1.5, -4.2, 3.0, 1.0, &r), .15583601560025710649555254 , TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (-7.4, 0.7, -1.5, 1.0, &r), -.34478866959246584996859 , TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_e, (0.1, -2.7, -1.5, 1.0, &r), 1.059766766063610122925 , TEST_TOL2, GSL_SUCCESS);
/* Taylor Binnington a = 0 */
TEST_SF(s, gsl_sf_hyperg_2F1_e, (0, -2, -4, 0.5, &r), 1.0 , TEST_TOL2, GSL_SUCCESS);
/* 2F1 conj */
TEST_SF(s, gsl_sf_hyperg_2F1_conj_e, (1, 1, 1, 0.5, &r), 3.352857095662929028, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_conj_e, (8, 8, 1, 0.5, &r), 1.7078067538891293983e+09, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_conj_e, (8, 8, 5, 0.5, &r), 285767.15696901140627, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_conj_e, (8, 8, 1, -0.5, &r), 0.007248196261471276276, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_conj_e, (8, 8, 5, -0.5, &r), 0.00023301916814505902809, TEST_TOL3, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_conj_e, (25, 25, 1, -0.5, &r), 5.1696944096e-06, TEST_SQRT_TOL0, GSL_SUCCESS);
/* updated correct values, testing enabled, Richard J. Mathar, 2008-01-09 */
TEST_SF(s, gsl_sf_hyperg_2F0_e, (0.01, 1.0, -0.02, &r), .99980388665511730901180717 , TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F0_e, (0.1, 0.5, -0.02, &r), .99901595171179281891589794 , TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F0_e, (1, 1, -0.02, &r), .98075549650574351826538049000 , TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F0_e, (8, 8, -0.02, &r), .32990592849626965538692141 , TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F0_e, (50, 50, -0.02, &r), .2688995263772964415245902e-12 , TEST_TOL0, GSL_SUCCESS);
/* 2F1 renorm */
TEST_SF(s, gsl_sf_hyperg_2F1_renorm_e, (1, 1, 1, 0.5, &r), 2.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_renorm_e, (8, 8, 1, 0.5, &r), 12451584.0, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_renorm_e, (8, -8, 1, 0.5, &r), 0.13671875, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_renorm_e, (8, -8, 1, -0.5, &r), 4945.13671875, TEST_TOL0, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_renorm_e, (8, -8, -5.5, 0.5, &r), -83081.19167659493609, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_renorm_e, (8, -8, -5.5, -0.5, &r), 2.2510895952730178518e+06, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_renorm_e, (8, 8, 5, 0.5, &r), 175.2380952380952381, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_renorm_e, (9, 9, -1.5, 0.99, &r), 1.6063266334913066551e+46, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_renorm_e, (9, 9, -1.5, -0.99, &r), 0.06234327316254516616, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_renorm_e, (5, 5, -1, 0.5, &r), 4949760.0, TEST_TOL1, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_renorm_e, (5, 5, -10, 0.5, &r), 139408493229637632000.0, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_renorm_e, (5, 5, -100, 0.5, &r), 3.0200107544594411315e+206, TEST_TOL3, GSL_SUCCESS);
/* 2F1 conj renorm */
TEST_SF(s, gsl_sf_hyperg_2F1_conj_renorm_e, (9, 9, -1.5, 0.99, &r), 5.912269095984229412e+49, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_conj_renorm_e, (9, 9, -1.5, -0.99, &r), 0.10834020229476124874, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_conj_renorm_e, (5, 5, -1, 0.5, &r), 1.4885106335357933625e+08, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_conj_renorm_e, (5, 5, -10, 0.5, &r), 7.968479361426355095e+21, TEST_TOL2, GSL_SUCCESS);
TEST_SF(s, gsl_sf_hyperg_2F1_conj_renorm_e, (5, 5, -100, 0.5, &r), 3.1113180227052313057e+208, TEST_TOL3, GSL_SUCCESS);
return s;
}
| {
"alphanum_fraction": 0.7065851039,
"avg_line_length": 77.2562962963,
"ext": "c",
"hexsha": "23354eac3712196268f87a137f1d5b561820f9e6",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "parasol-ppl/PPL_utils",
"max_forks_repo_path": "folding_libs/gsl-1.14/specfunc/test_hyperg.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "parasol-ppl/PPL_utils",
"max_issues_repo_path": "folding_libs/gsl-1.14/specfunc/test_hyperg.c",
"max_line_length": 124,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "parasol-ppl/PPL_utils",
"max_stars_repo_path": "folding_libs/gsl-1.14/specfunc/test_hyperg.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 23741,
"size": 52148
} |
/* $Id$ */
/*--------------------------------------------------------------------*/
/*; Copyright (C) 2008-2020 */
/*; Associated Universities, Inc. Washington DC, USA. */
/*; */
/*; This program is free software; you can redistribute it and/or */
/*; modify it under the terms of the GNU General Public License as */
/*; published by the Free Software Foundation; either version 2 of */
/*; the License, or (at your option) any later version. */
/*; */
/*; This program is distributed in the hope that it will be useful, */
/*; but WITHOUT ANY WARRANTY; without even the implied warranty of */
/*; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/*; GNU General Public License for more details. */
/*; */
/*; You should have received a copy of the GNU General Public */
/*; License along with this program; if not, write to the Free */
/*; Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, */
/*; MA 02139, USA. */
/*; */
/*;Correspondence about this software should be addressed as follows: */
/*; Internet email: bcotton@nrao.edu. */
/*; Postal address: William Cotton */
/*; National Radio Astronomy Observatory */
/*; 520 Edgemont Road */
/*; Charlottesville, VA 22903-2475 USA */
/*--------------------------------------------------------------------*/
#include "ObitSpectrumFit.h"
#include "ObitImageMF.h"
#include "ObitThread.h"
#ifdef HAVE_GSL
#include <gsl/gsl_blas.h>
#endif /* HAVE_GSL */
/*----------------Obit: Merx mollis mortibus nuper ------------------*/
/**
* \file ObitSpectrumFit.c
* ObitSpectrumFit class function definitions.
* This class is derived from the Obit base class.
*/
/** name of the class defined in this file */
static gchar *myClassName = "ObitSpectrumFit";
/** Function to obtain parent ClassInfo */
static ObitGetClassFP ObitParentGetClass = ObitGetClass;
/**
* ClassInfo structure ObitSpectrumFitClassInfo.
* This structure is used by class objects to access class functions.
*/
static ObitSpectrumFitClassInfo myClassInfo = {FALSE};
/*--------------- File Global Variables ----------------*/
/*---------------Private function prototypes----------------*/
/** Private: Initialize newly instantiated object. */
void ObitSpectrumFitInit (gpointer in);
/** Private: Deallocate members. */
void ObitSpectrumFitClear (gpointer in);
/** Private: Set Class function pointers. */
static void ObitSpectrumFitClassInfoDefFn (gpointer inClass);
#ifdef HAVE_GSL
/** Private: Solver function evaluation */
static int SpecFitFunc (const gsl_vector *x, void *params,
gsl_vector *f);
/** Private: Solver Jacobian evaluation */
static int SpecFitJac (const gsl_vector *x, void *params,
gsl_matrix *J);
/** Private: Solver function + Jacobian evaluation */
static int SpecFitFuncJac (const gsl_vector *x, void *params,
gsl_vector *f, gsl_matrix *J);
/** Private: Solver function evaluation - broken power law */
static int SpecFitFuncBP (const gsl_vector *x, void *params,
gsl_vector *f);
/** Private: Solver Jacobian evaluation - broken power law */
static int SpecFitJacBP (const gsl_vector *x, void *params,
gsl_matrix *J);
/** Private: Solver function + Jacobian evaluation - broken power law */
static int SpecFitFuncJacBP (const gsl_vector *x, void *params,
gsl_vector *f, gsl_matrix *J);
#endif /* HAVE_GSL */
/** Private: Threaded fitting */
static gpointer ThreadNLFit (gpointer arg);
/*---------------Private structures----------------*/
/* FT threaded function argument */
typedef struct {
/** ObitSpectrumFit object */
ObitSpectrumFit *in;
/* Obit error stack object */
ObitErr *err;
/** First (1-rel) value in y to process this thread */
olong first;
/** Highest (1-rel) value in y to process this thread */
olong last;
/** thread number, >0 -> no threading */
olong ithread;
/** max number of terms to fit */
olong nterm;
/** number of terms being fitted */
olong fitTerm;
/** number of frequencies */
olong nfreq;
/** Minimum fraction of weight */
ofloat minWt;
/** Array of Nu per frequency point - broken power law */
ofloat *nu;
/** Array of log (Nu/Nu_0) per frequency point */
ofloat *logNuOnu0;
/** Array of weights (1/RMS**2) per inFArrays (nfreq) */
ofloat *weight;
/** Array of 1/RMS per inFArrays (nfreq) */
ofloat *isigma;
/** Array of pixel values being fitted per frequency point */
ofloat *obs;
/** maximum iteration */
olong maxIter;
/** acceptable iteration delta, rel and abs. */
odouble minDelta;
/** max acceptable normalized chi squares */
ofloat maxChiSq;
/** Reference frequency */
ofloat refFreq;
/* Spectral index correction to be applied to data */
ofloat corAlpha;
/** Vector of guess/fitted coefficients, optional errors */
ofloat *coef;
/** Chi squared of fit */
ofloat ChiSq;
/** Do error analysis? */
gboolean doError;
/** Do broken power law ? */
gboolean doBrokePow;
/** Do Primary beam correction? */
gboolean doPBCorr;
#ifdef HAVE_GSL
/** Fitting solver for two terms */
gsl_multifit_fdfsolver *solver2;
/** Fitting solver for three terms */
gsl_multifit_fdfsolver *solver3;
/** Fitting solver for four terms */
gsl_multifit_fdfsolver *solver4;
/** Fitting solver for five terms */
gsl_multifit_fdfsolver *solver5;
/** Fitting solver function structure */
gsl_multifit_function_fdf *funcStruc;
/** Fitting work vector of length 2 */
gsl_vector *work2;
/** Fitting work vector of length 3 */
gsl_vector *work3;
/** Fitting work vector of length 4 */
gsl_vector *work4;
/** Fitting work vector of length 5 */
gsl_vector *work5;
/** Covariance matrix for two terms */
gsl_matrix *covar2;
/** Covariance matrix for three terms */
gsl_matrix *covar3;
/** Covariance matrix for four terms */
gsl_matrix *covar4;
/** Covariance matrix for five terms */
gsl_matrix *covar5;
#endif /* HAVE_GSL */
} NLFitArg;
/** Private: Actual fitting */
static void NLFit (NLFitArg *arg);
/** Private: Actual fitting broken power */
static void NLFitBP (NLFitArg *arg);
/*----------------------Public functions---------------------------*/
/**
* Constructor.
* Initializes class if needed on first call.
* \param name An optional name for the object.
* \return the new object.
*/
ObitSpectrumFit* newObitSpectrumFit (gchar* name)
{
ObitSpectrumFit* out;
/* Class initialization if needed */
if (!myClassInfo.initialized) ObitSpectrumFitClassInit();
/* allocate/init structure */
out = g_malloc0(sizeof(ObitSpectrumFit));
/* initialize values */
if (name!=NULL) out->name = g_strdup(name);
else out->name = g_strdup("Noname");
/* set ClassInfo */
out->ClassInfo = (gpointer)&myClassInfo;
/* initialize other stuff */
ObitSpectrumFitInit((gpointer)out);
return out;
} /* end newObitSpectrumFit */
/**
* Returns ClassInfo pointer for the class.
* \return pointer to the class structure.
*/
gconstpointer ObitSpectrumFitGetClass (void)
{
/* Class initialization if needed */
if (!myClassInfo.initialized) ObitSpectrumFitClassInit();
return (gconstpointer)&myClassInfo;
} /* end ObitSpectrumFitGetClass */
/**
* Make a deep copy of an ObitSpectrumFit.
* \param in The object to copy
* \param out An existing object pointer for output or NULL if none exists.
* \param err Obit error stack object.
* \return pointer to the new object.
*/
ObitSpectrumFit* ObitSpectrumFitCopy (ObitSpectrumFit *in, ObitSpectrumFit *out, ObitErr *err)
{
const ObitClassInfo *ParentClass;
gboolean oldExist;
gchar *outName;
olong i, nOut;
/* error checks */
if (err->error) return out;
g_assert (ObitIsA(in, &myClassInfo));
if (out) g_assert (ObitIsA(out, &myClassInfo));
/* Create if it doesn't exist */
oldExist = out!=NULL;
if (!oldExist) {
/* derive object name */
outName = g_strconcat ("Copy: ",in->name,NULL);
out = newObitSpectrumFit(outName);
g_free(outName);
}
/* deep copy any base class members */
ParentClass = myClassInfo.ParentClass;
g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));
ParentClass->ObitCopy (in, out, err);
/* copy this class */
out->nfreq = in->nfreq;
out->nterm = in->nterm;
/* Arrays */
if (out->RMS) g_free(out->RMS);
out->RMS = g_malloc0(out->nfreq*sizeof(ofloat));
if (in->RMS)
for (i=0; i<out->nfreq; i++) out->RMS[i] = in->RMS[i];
if (out->calFract) g_free(out->calFract);
out->calFract = g_malloc0(out->nfreq*sizeof(ofloat));
if (in->calFract)
if (out->calFract) g_free(out->calFract);
/* reference this class members */
if (out->outDesc) out->outDesc = ObitImageDescUnref(out->outDesc);
if (in->outDesc) out->outDesc = ObitImageDescRef(in->outDesc);
if (out->inFArrays) {
for (i=0; i<in->nfreq; i++) out->inFArrays[i] = ObitFArrayUnref(out->inFArrays[i]);
}
if (in->inFArrays) {
for (i=0; i<in->nfreq; i++) out->inFArrays[i] = ObitFArrayRef(in->inFArrays[i]);
}
if (out->BeamShapes) {
for (i=0; i<in->nfreq; i++) out->BeamShapes[i] = ObitBeamShapeUnref(out->BeamShapes[i]);
}
if (in->BeamShapes) {
for (i=0; i<in->nfreq; i++) out->BeamShapes[i] = ObitBeamShapeRef(in->BeamShapes[i]);
}
/* How many output planes */
if (in->doError) nOut = 1+in->nterm*2;
else nOut = in->nterm;
if (out->outFArrays) {
for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayUnref(out->outFArrays[i]);
}
if (in->outFArrays) {
for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayRef(in->outFArrays[i]);
}
return out;
} /* end ObitSpectrumFitCopy */
/**
* Make a copy of a object but do not copy the actual data
* This is useful to create an SpectrumFit similar to the input one.
* \param in The object to copy
* \param out An existing object pointer for output, must be defined.
* \param err Obit error stack object.
*/
void ObitSpectrumFitClone (ObitSpectrumFit *in, ObitSpectrumFit *out, ObitErr *err)
{
const ObitClassInfo *ParentClass;
olong i, nOut;
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return;
g_assert (ObitIsA(in, &myClassInfo));
g_assert (ObitIsA(out, &myClassInfo));
/* deep copy any base class members */
ParentClass = myClassInfo.ParentClass;
g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));
ParentClass->ObitCopy (in, out, err);
/* copy this class */
out->nfreq = in->nfreq;
out->nterm = in->nterm;
/* Arrays */
if (out->RMS) g_free(out->RMS);
out->RMS = g_malloc0(out->nfreq*sizeof(ofloat));
if (in->RMS)
for (i=0; i<out->nfreq; i++) out->RMS[i] = in->RMS[i];
if (out->calFract) g_free(out->calFract);
out->calFract = g_malloc0(out->nfreq*sizeof(ofloat));
if (in->calFract)
if (out->calFract) g_free(out->calFract);
/* reference this class members */
if (out->outDesc) out->outDesc = ObitImageDescUnref(out->outDesc);
if (in->outDesc) out->outDesc = ObitImageDescRef(in->outDesc);
if (out->inFArrays) {
for (i=0; i<in->nfreq; i++) out->inFArrays[i] = ObitFArrayUnref(out->inFArrays[i]);
}
if (in->inFArrays) {
for (i=0; i<in->nfreq; i++) out->inFArrays[i] = ObitFArrayRef(in->inFArrays[i]);
}
if (out->BeamShapes) {
for (i=0; i<in->nfreq; i++) out->BeamShapes[i] = ObitBeamShapeUnref(out->BeamShapes[i]);
}
if (in->BeamShapes) {
for (i=0; i<in->nfreq; i++) out->BeamShapes[i] = ObitBeamShapeRef(in->BeamShapes[i]);
}
/* How many output planes */
if (in->doError) nOut = 1+in->nterm*2;
else nOut = in->nterm;
if (out->outFArrays) {
for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayUnref(out->outFArrays[i]);
}
if (in->outFArrays) {
for (i=0; i<nOut; i++) out->outFArrays[i] = ObitFArrayRef(in->outFArrays[i]);
}
} /* end ObitSpectrumFitClone */
/**
* Creates an ObitSpectrumFit
* \param name An optional name for the object.
* \param nterm Number of coefficients of powers of log(nu)
* \return the new object.
*/
ObitSpectrumFit* ObitSpectrumFitCreate (gchar* name, olong nterm)
{
ObitSpectrumFit* out;
/* Create basic structure */
out = newObitSpectrumFit (name);
out->nterm = nterm;
return out;
} /* end ObitSpectrumFitCreate */
/**
* Fit spectra to an image cube pixels.
* The third axis of the output image will be "SPECLOGF" to indicate that then
* planes are spectral fit parameters. The "CRVAL" on this axis will be the reference
* Frequency for the fitting.
* Item "NTERM" is added to the output image descriptor to give the maximum number
* Item ""BROKENPO" is added to the output image descriptor if fit is a broken power law
* of terms fitted
* \param in Spectral fitting object
* Potential parameters on in->info:
* \li "refFreq" OBIT_double scalar Reference frequency for fit [def ref for inImage]
* \li "maxChi2" OBIT_float scalar Max. Chi Sq for accepting a partial spectrum [def 1.5]
* \li "doError" OBIT_boolean scalar If true do error analysis [def False]
* \li "doPBCor" OBIT_boolean scalar If true do primary beam correction. [def False]
* \li "doBrokePow" OBIT_boolean scalar If true do broken power law (3 terms). [def False]
* \li "calFract" OBIT_float (?,1,1) Calibration error as fraction of flux
* One per frequency or one for all, def 1.0e-5
* \li "PBmin" OBIT_float (?,1,1) Minimum beam gain correction
* One per frequency or one for all, def 0.05, 1.0 => no gain corrections
* \li "antSize" OBIT_float (?,1,1) Antenna diameter (m) for gain corr,
* One per frequency or one for all, def 25.0
* \li corAlpha OBIT_float scalar, if non zero, spectral index
* correction to apply, def = 0.0
*
* \param inImage Image cube to be fitted
* If an ObitImageMF the the fitter in that class is called
* \param outImage Image cube with fitted spectra.
* Should be defined but not created.
* Planes 1->nterm are coefficients per pixel
* if doError:
* Planes nterm+1->2*nterm are uncertainties in coefficients
* Plane 2*nterm+1 = Chi squared of fit
* \param err Obit error stack object.
*/
void ObitSpectrumFitCube (ObitSpectrumFit* in, ObitImage *inImage,
ObitImage *outImage, ObitErr *err)
{
olong i, iplane, nOut;
olong naxis[2];
ObitIOSize IOBy;
ObitInfoType type;
ObitIOCode retCode;
union ObitInfoListEquiv InfoReal;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}, PBdim[MAXINFOELEMDIM], ASdim[MAXINFOELEMDIM];
ofloat *calFract, *PBmin, *antSize, aSize, pbmin, antsize;
gboolean doGain, isMF;
gchar *today=NULL, *SPECLOGF = "SPECLOGF";
gchar *routine = "ObitSpectrumFitCube";
/* error checks */
if (err->error) return;
g_assert (ObitIsA(in, &myClassInfo));
g_assert(ObitImageIsA(inImage));
g_assert(ObitImageIsA(outImage));
/* Control parameters */
/* Min Chi^2 for fit */
InfoReal.flt = 1.5; type = OBIT_float;
in->maxChi2 = 1.5;
ObitInfoListGetTest(in->info, "maxChi2", &type, dim, &InfoReal);
if (type==OBIT_float) in->maxChi2 = InfoReal.flt;
else if (type==OBIT_double) in->maxChi2 = (ofloat)InfoReal.dbl;
/* Want Error analysis? */
InfoReal.itg = (olong)FALSE; type = OBIT_bool;
ObitInfoListGetTest(in->info, "doError", &type, dim, &InfoReal);
in->doError = InfoReal.itg;
/* Want primary beam correction? */
InfoReal.itg = (olong)FALSE; type = OBIT_bool;
ObitInfoListGetTest(in->info, "doPBCor", &type, dim, &InfoReal);
in->doPBCorr = InfoReal.itg;
/* Want Broken power law ? */
InfoReal.itg = (olong)FALSE; type = OBIT_bool;
ObitInfoListGetTest(in->info, "doBrokePow", &type, dim, &InfoReal);
in->doBrokePow = InfoReal.itg;
/* Spectral index correction */
in->corAlpha = 0.0;
ObitInfoListGetTest(in->info, "corAlpha", &type, dim, &in->corAlpha);
/* Min PB gain */
ObitInfoListGetP(in->info, "PBmin", &type, PBdim, (gpointer)&PBmin);
/* Antenna diameter */
ObitInfoListGetP(in->info, "antSize", &type, ASdim, (gpointer)&antSize);
/* Check if an ObitImageMF input image */
isMF = ObitImageMFIsA(inImage);
/* Use ObitImageMF class for fitting */
if (isMF) {
/* Copy pixels first */
outImage = (ObitImage*)ObitImageMFCopy ((ObitImageMF*)inImage, (ObitImageMF*)outImage, err);
/* Then Fit */
if (!in->doPBCorr) aSize = 0.0;
else aSize = antSize[0];
ObitImageMFFitSpec ((ObitImageMF*)outImage, aSize, err);
if (err->error) Obit_traceback_msg (err, routine, inImage->name);
return;
}
/* Open input image to get info */
IOBy = OBIT_IO_byPlane;
dim[0] = 1;
ObitInfoListAlwaysPut (inImage->info, "IOBy", OBIT_long, dim, &IOBy);
inImage->extBuffer = TRUE; /* Using inFArrays as I/O buffer */
retCode = ObitImageOpen (inImage, OBIT_IO_ReadOnly, err);
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error))
Obit_traceback_msg (err, routine, inImage->name);
/* Get Reference frequency , default input ref. freq. */
InfoReal.dbl = inImage->myDesc->crval[inImage->myDesc->jlocf];
type = OBIT_double;
in->refFreq = InfoReal.dbl;
ObitInfoListGetTest(in->info, "refFreq", &type, dim, &InfoReal);
if (type==OBIT_float) in->refFreq = InfoReal.flt;
else if (type==OBIT_double) in->refFreq = (ofloat)InfoReal.dbl;
/* Determine number of frequency planes and initialize in */
in->nfreq = inImage->myDesc->inaxes[inImage->myDesc->jlocf];
in->BeamShapes = g_malloc0(in->nfreq*sizeof(ObitBeamShape*));
for (i=0; i<in->nfreq; i++) in->BeamShapes[i] = NULL;
in->RMS = g_malloc0(in->nfreq*sizeof(ofloat));
in->calFract = g_malloc0(in->nfreq*sizeof(ofloat));
in->inFArrays = g_malloc0(in->nfreq*sizeof(ObitFArray*));
in->freqs = g_malloc0(in->nfreq*sizeof(odouble));
/* How many output planes? */
if (in->doError) nOut = 1+in->nterm*2;
else nOut = in->nterm;
/* Define term arrays */
in->outFArrays = g_malloc0((nOut)*sizeof(ObitFArray*));
for (i=0; i<nOut; i++) in->outFArrays[i] = NULL;
/* Image size */
in->nx = inImage->myDesc->inaxes[0];
in->ny = inImage->myDesc->inaxes[1];
naxis[0] = (olong)in->nx; naxis[1] = (olong)in->ny;
for (i=0; i<in->nfreq; i++) in->inFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);
for (i=0; i<nOut; i++) in->outFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);
/* Calibration error */
for (i=0; i<in->nfreq; i++) in->calFract[i] = 1.0e-5; /* default */
if (ObitInfoListGetP(in->info, "calFract", &type, dim, (gpointer)&calFract)) {
if (dim[0]>=in->nfreq) for (i=0; i<in->nfreq; i++) in->calFract[i] = calFract[i];
else for (i=0; i<in->nfreq; i++) in->calFract[i] = calFract[0];
}
/* Output Image descriptor */
outImage->myDesc = ObitImageDescCopy (inImage->myDesc, in->outDesc, err);
if (err->error) Obit_traceback_msg (err, routine, inImage->name);
/* Change third axis to type "SPECLOGF" and leave the reference frequency
as the "CRVAL" */
outImage->myDesc->inaxes[outImage->myDesc->jlocf] = nOut;
outImage->myDesc->crval[outImage->myDesc->jlocf] = in->refFreq;
outImage->myDesc->crpix[outImage->myDesc->jlocf] = 1.0;
outImage->myDesc->cdelt[outImage->myDesc->jlocf] = 1.0;
strncpy (outImage->myDesc->ctype[outImage->myDesc->jlocf], SPECLOGF, IMLEN_KEYWORD);
outImage->myDesc->bitpix = -32; /* Float it */
/* Creation date today */
today = ObitToday();
strncpy (outImage->myDesc->date, today, IMLEN_VALUE);
if (today) g_free(today);
/* Copy of output descriptor to in */
in->outDesc = ObitImageDescCopy (outImage->myDesc, in->outDesc, err);
/* Loop reading planes */
for (iplane=0; iplane<in->nfreq; iplane++) {
retCode = ObitImageRead (inImage, in->inFArrays[iplane]->array, err);
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inImage->name);
/* Get BeamShape */
antsize = 25.0;
if (antSize) antsize = antSize[0];
if (antSize && (ASdim[0]>=in->nfreq)) antsize = antSize[i];
pbmin = 0.05;
if (PBmin) pbmin = PBmin[0];
if (PBmin && (PBdim[0]>=in->nfreq)) pbmin = PBmin[i];
doGain = pbmin<0.999;
in->BeamShapes[iplane] = ObitBeamShapeCreate ("BS", inImage, pbmin, antsize, doGain);
/* Plane RMS */
in->RMS[iplane] = ObitFArrayRMS(in->inFArrays[iplane]);
/* Frequency */
in->freqs[iplane] = inImage->myDesc->crval[inImage->myDesc->jlocf] +
inImage->myDesc->cdelt[inImage->myDesc->jlocf] *
(inImage->myDesc->plane - inImage->myDesc->crpix[inImage->myDesc->jlocf]);
} /* end loop reading planes */
/* Close input */
retCode = ObitImageClose (inImage, err);
inImage->extBuffer = FALSE; /* May need I/O buffer later */
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error))
Obit_traceback_msg (err, routine, inImage->name);
/* Average Frequency - no
in->refFreq = 0.0;
for (i=0; i<in->nfreq; i++) in->refFreq += in->freqs[i];
in->refFreq /= in->nfreq;*/
/* Do actual fitting */
ObitSpectrumFitter (in, err);
if (err->error) Obit_traceback_msg (err, routine, inImage->name);
/* Update output header to reference Frequency */
outImage->myDesc->crval[outImage->myDesc->jlocf] = in->refFreq;
in->outDesc->crval[in->outDesc->jlocf] = in->refFreq;
/* Write output */
ObitSpectrumWriteOutput(in, outImage, err);
if (err->error) Obit_traceback_msg (err, routine, inImage->name);
} /* end ObitSpectrumFitCube */
/**
* Fit spectra to an array of images
* The third axis of the output image will be "SPECLOGF" to indicate that then
* planes are spectral fit parameters. The "CRVAL" on this axis will be the reference
* Frequency for the fitting.
* Item "NTERM" is added to the output image descriptor to give the maximum number
* of terms fitted
* Item ""BROKENPO" is added to the output image descriptor if fit is a broken power law
* \param in Spectral fitting object
* \li "refFreq" OBIT_double scalar Reference frequency for fit [def average of inputs]
* \li "maxChi2" OBIT_float scalar Max. Chi Sq for accepting a partial spectrum [def 1.5]
* \li "doError" OBIT_boolean scalar If true do error analysis [def False]
* \li "doPBCor" OBIT_boolean scalar If true do primary beam correction.[def False]
* \li "doBrokePow" OBIT_boolean scalar If true do broken power law (3 terms). [def False]
* \li "calFract" OBIT_float (?,1,1) Calibration error as fraction of flux
* One per frequency or one for all, def 0.05
* \li "PBmin" OBIT_float (?,1,1) Minimum beam gain correction
* One per frequency or one for all, def 0.05, 1.0 => no gain corrections
* \li "antSize" OBIT_float (?,1,1) Antenna diameter (m) for gain corr,
* One per frequency or one for all, def 25.0
* \li corAlpha OBIT_float scalar, if non zero, spectral index
* correction to apply, def = 0.0
* \param nimage Number of entries in imArr
* \param imArr Array of images to be fitted
* \param outImage Image cube with fitted spectra.
* Should be defined but not created.
* Planes 1->nterm are coefficients per pixel
* if doError:
* Planes nterm+1->2*nterm are uncertainties in coefficients
* Plane 2*nterm+1 = Chi squared of fit
* \param err Obit error stack object.
*/
void ObitSpectrumFitImArr (ObitSpectrumFit* in, olong nimage, ObitImage **imArr,
ObitImage *outImage, ObitErr *err)
{
olong i, jlocf, iplane, nOut;
olong naxis[2];
ObitIOSize IOBy;
ObitInfoType type;
ObitIOCode retCode;
union ObitInfoListEquiv InfoReal;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}, PBdim[MAXINFOELEMDIM], ASdim[MAXINFOELEMDIM];
ofloat *calFract=NULL, *PBmin=NULL, *antSize=NULL, pbmin, antsize, ipixel[2], opixel[2];
gboolean doGain, bad;
odouble avgFreq;
gchar *today=NULL, *SPECLOGF = "SPECLOGF";
gchar *routine = "ObitSpectrumFitCube";
/* error checks */
if (err->error) return;
g_assert (ObitIsA(in, &myClassInfo));
g_assert(ObitImageIsA(outImage));
/* Control parameters */
/* Max Chi^2 for fit */
InfoReal.flt = 1.5; type = OBIT_float;
in->maxChi2 = 1.5;
ObitInfoListGetTest(in->info, "maxChi2", &type, dim, &InfoReal);
if (type==OBIT_float) in->maxChi2 = InfoReal.flt;
else if (type==OBIT_double) in->maxChi2 = (ofloat)InfoReal.dbl;
/* Want Error analysis? */
InfoReal.itg = (olong)FALSE; type = OBIT_bool;
ObitInfoListGetTest(in->info, "doError", &type, dim, &InfoReal);
in->doError = InfoReal.itg;
/* Want primary beam correction? */
InfoReal.itg = (olong)FALSE; type = OBIT_bool;
ObitInfoListGetTest(in->info, "doPBCor", &type, dim, &InfoReal);
in->doPBCorr = InfoReal.itg;
/* Want Broken power law ? */
InfoReal.itg = (olong)FALSE; type = OBIT_bool;
ObitInfoListGetTest(in->info, "doBrokePow", &type, dim, &InfoReal);
in->doBrokePow = InfoReal.itg;
/* Spectral index correction */
in->corAlpha = 0.0;
ObitInfoListGetTest(in->info, "corAlpha", &type, dim, &in->corAlpha);
/* Min PB gain */
ObitInfoListGetP(in->info, "PBmin", &type, PBdim, (gpointer)&PBmin);
/* Antenna diameter */
ObitInfoListGetP(in->info, "antSize", &type, ASdim, (gpointer)&antSize);
/* Determine number of frequency planes and initialize in */
in->nfreq = nimage;
in->BeamShapes = g_malloc0(in->nfreq*sizeof(ObitBeamShape*));
for (i=0; i<in->nfreq; i++) in->BeamShapes[i] = NULL;
in->RMS = g_malloc0(in->nfreq*sizeof(ofloat));
in->calFract = g_malloc0(in->nfreq*sizeof(ofloat));
in->inFArrays = g_malloc0(in->nfreq*sizeof(ObitFArray*));
in->freqs = g_malloc0(in->nfreq*sizeof(odouble));
/* Calibration error */
for (i=0; i<in->nfreq; i++) in->calFract[i] = 0.05; /* default */
if (ObitInfoListGetP(in->info, "calFract", &type, dim, (gpointer)&calFract)) {
if (dim[0]>=in->nfreq) for (i=0; i<in->nfreq; i++) in->calFract[i] = calFract[i];
else for (i=0; i<in->nfreq; i++) in->calFract[i] = calFract[0];
}
/* How many output planes? */
if (in->doError) nOut = 1+in->nterm*2;
else nOut = in->nterm;
/* Define term arrays */
in->outFArrays = g_malloc0((nOut)*sizeof(ObitFArray*));
for (i=0; i<nOut; i++) in->outFArrays[i] = NULL;
/* Loop over images */
for (iplane = 0; iplane<nimage; iplane++) {
/* Open input image to get info */
IOBy = OBIT_IO_byPlane;
dim[0] = 1;
ObitInfoListAlwaysPut (imArr[iplane]->info, "IOBy", OBIT_long, dim, &IOBy);
imArr[iplane]->extBuffer = TRUE; /* Using inFArrays as I/O buffer */
retCode = ObitImageOpen (imArr[iplane], OBIT_IO_ReadOnly, err);
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error))
Obit_traceback_msg (err, routine, imArr[iplane]->name);
/* On first image initialize */
if (iplane==0) {
/* Image size */
in->nx = imArr[iplane]->myDesc->inaxes[0];
in->ny = imArr[iplane]->myDesc->inaxes[1];
naxis[0] = (olong)in->nx; naxis[1] = (olong)in->ny;
for (i=0; i<in->nfreq; i++) in->inFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);
for (i=0; i<nOut; i++) in->outFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);
/* Output Image descriptor */
outImage->myDesc = ObitImageDescCopy (imArr[iplane]->myDesc, in->outDesc, err);
if (err->error) Obit_traceback_msg (err, routine, imArr[iplane]->name);
/* Change third axis to type "SPECLOGF" and leave the reference frequency
as the "CRVAL" */
if (outImage->myDesc->jlocf>0) jlocf = outImage->myDesc->jlocf;
else jlocf = 2; /* Trap CASA problem */
outImage->myDesc->inaxes[jlocf] = nOut;
outImage->myDesc->crpix[jlocf] = 1.0;
outImage->myDesc->cdelt[jlocf] = 1.0;
strncpy (outImage->myDesc->ctype[jlocf], SPECLOGF, IMLEN_KEYWORD);
outImage->myDesc->bitpix = -32; /* Float it */
/* Creation date today */
today = ObitToday();
strncpy (outImage->myDesc->date, today, IMLEN_VALUE);
if (today) g_free(today);
/* Copy of output descriptor to in */
in->outDesc = ObitImageDescCopy (outImage->myDesc, in->outDesc, err);
} else { /* On subsequent images check for consistency */
/* Check size of planes */
Obit_return_if_fail(((imArr[iplane]->myDesc->inaxes[0]==in->outDesc->inaxes[0]) &&
(imArr[iplane]->myDesc->inaxes[1]==in->outDesc->inaxes[1])), err,
"%s: Image planes incompatible %d!= %d or %d!= %d",
routine, imArr[iplane]->myDesc->inaxes[0], in->outDesc->inaxes[0],
imArr[iplane]->myDesc->inaxes[1], in->outDesc->inaxes[1]) ;
/* Check alignment of pixels */
ipixel[0] = 1.0; ipixel[1] = 1.0;
bad = !ObitImageDescCvtPixel (imArr[iplane]->myDesc, in->outDesc, ipixel, opixel, err);
if (err->error) Obit_traceback_msg (err, routine, imArr[iplane]->name);
Obit_return_if_fail(!bad, err,
"%s: Image planes incompatible", routine);
Obit_return_if_fail(((fabs(ipixel[0]-opixel[0])<0.01) &&
(fabs(ipixel[1]-opixel[1])<0.01)), err,
"%s: Image pixels not aligned %f!=%f or %f!=%f",
routine, ipixel[0], opixel[0], ipixel[1], opixel[1]) ;
} /* end consistency check */
/* Read plane */
retCode = ObitImageRead (imArr[iplane], in->inFArrays[iplane]->array, err);
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, imArr[iplane]->name);
/* Get BeamShape */
antsize = 25.0;
if (antSize) antsize = antSize[0];
if (antSize && (ASdim[0]>=in->nfreq)) antsize = antSize[iplane];
pbmin = 0.05;
if (PBmin) pbmin = PBmin[0];
if (PBmin && (PBdim[0]>=in->nfreq)) pbmin = PBmin[iplane];
doGain = pbmin<0.999;
in->BeamShapes[iplane] = ObitBeamShapeCreate ("BS", imArr[iplane], pbmin, antsize, doGain);
/* Plane RMS */
in->RMS[iplane] = ObitFArrayRMS(in->inFArrays[iplane]);
/* Frequency */
in->freqs[iplane] = imArr[iplane]->myDesc->crval[imArr[iplane]->myDesc->jlocf] +
imArr[iplane]->myDesc->cdelt[imArr[iplane]->myDesc->jlocf] *
(imArr[iplane]->myDesc->plane - imArr[iplane]->myDesc->crpix[imArr[iplane]->myDesc->jlocf]);
/* Close input */
retCode = ObitImageClose (imArr[iplane], err);
imArr[iplane]->extBuffer = FALSE; /* May need I/O buffer later */
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error))
Obit_traceback_msg (err, routine, imArr[iplane]->name);
} /* end loop over input images */
/* Average Frequency */
avgFreq = 0.0;
for (i=0; i<in->nfreq; i++) avgFreq += in->freqs[i];
avgFreq /= in->nfreq;
/* Get Reference frequency , default avg. input ref. freq. */
InfoReal.dbl = avgFreq; type = OBIT_double;
in->refFreq = InfoReal.dbl;
ObitInfoListGetTest(in->info, "refFreq", &type, dim, &InfoReal);
if (type==OBIT_float) in->refFreq = InfoReal.flt;
else if (type==OBIT_double) in->refFreq = (ofloat)InfoReal.dbl;
/* Update output header to reference Frequency */
outImage->myDesc->crval[outImage->myDesc->jlocf] = in->refFreq;
in->outDesc->crval[in->outDesc->jlocf] = in->refFreq;
/* Do actual fitting */
ObitSpectrumFitter (in, err);
if (err->error) Obit_traceback_msg (err, routine, imArr[0]->name);
/* Write output */
ObitSpectrumWriteOutput(in, outImage, err);
if (err->error) Obit_traceback_msg (err, routine, outImage->name);
} /* end ObitSpectrumFitImArr */
/**
* Evaluate spectrum at a given frequency
* \param in Spectral fitting object
* \param inImage Spectral coefficient image
* Planes 1->nterm are coefficients per pixel
* Planes nterm+1->2*nterm are uncertainties in coefficients
* Plane 2*nterm+1 = Chi squared of fit
* \param outFreq Output Frequency in Hz
* \param outImage Image to write, must be defined but not yet exist.
* \param err Obit error stack object.
*/
void ObitSpectrumFitEval (ObitSpectrumFit* in, ObitImage *inImage,
odouble outFreq, ObitImage *outImage, ObitErr *err)
{
olong ix, iy, i, indx, nx, ny, nterm, jlocspec;
olong naxis[2];
ObitIOSize IOBy;
ObitIOCode retCode;
ObitInfoType type;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitFArray **inArrays=NULL, *outArray=NULL;
odouble refFreq, arg, aarg, sum;
gchar *today=NULL, *SPECLOGF = "SPECLOGF";
gchar *routine = "ObitSpectrumFitEval";
/* error checks */
if (err->error) return;
g_assert (ObitIsA(in, &myClassInfo));
g_assert(ObitImageIsA(inImage));
g_assert(ObitImageIsA(outImage));
/* Open input image to get info */
IOBy = OBIT_IO_byPlane;
dim[0] = 1;
ObitInfoListAlwaysPut (inImage->info, "IOBy", OBIT_long, dim, &IOBy);
inImage->extBuffer = TRUE; /* Using inFArrays as I/O buffer */
retCode = ObitImageOpen (inImage, OBIT_IO_ReadOnly, err);
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error))
Obit_traceback_msg (err, routine, inImage->name);
/* Find "SPECLOGF" axis */
jlocspec = -1;
for (i=0; i<inImage->myDesc->naxis; i++) {
if (!strncmp (inImage->myDesc->ctype[i], SPECLOGF, 8)) jlocspec = i;
}
Obit_return_if_fail((jlocspec>=0), err,
"%s: No %s axis on %s", routine, SPECLOGF, inImage->name);
/* Reference frequency is on inImage */
refFreq = inImage->myDesc->crval[jlocspec];
/* Output Image descriptor */
outImage->myDesc = ObitImageDescCopy (inImage->myDesc, outImage->myDesc, err);
if (err->error) Obit_traceback_msg (err, routine, inImage->name);
/* Frequency axis is actually fitted spectrum parameters and errors */
outImage->myDesc->inaxes[outImage->myDesc->jlocf] = 1;
outImage->myDesc->crval[outImage->myDesc->jlocf] = outFreq;
/* Creation date today */
today = ObitToday();
strncpy (outImage->myDesc->date, today, IMLEN_VALUE);
if (today) g_free(today);
outImage->myDesc->bitpix = -32; /* Float it */
/* Determine number of frequency terms and initialize storage arrays
get nterm from input image descriptor with default number of pixels on
SPECLOGF" axis */
nterm = inImage->myDesc->inaxes[jlocspec];
ObitInfoListGetTest (outImage->myDesc->info, "NTERM", &type, dim, &nterm);
/* Image size */
nx = inImage->myDesc->inaxes[0];
ny = inImage->myDesc->inaxes[1];
naxis[0] = (olong)nx; naxis[1] = (olong)ny;
for (i=0; i<nterm; i++) inArrays[i] = ObitFArrayCreate (NULL, 2, naxis);
outArray = ObitFArrayCreate (NULL, 2, naxis);
/* Loop reading planes */
for (i=0; i<nterm; i++) {
retCode = ObitImageRead (inImage, inArrays[i]->array, err);
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error)) goto cleanup;
} /* end loop over planes */
/* Loop over pixels evaluating spectrum */
arg = log(outFreq/refFreq);
/* Loop over pixels in Y */
indx = -1;
for (iy=0; iy<ny; iy++) {
/* Loop over pixels in X */
for (ix=0; ix<nx; ix++) {
indx ++;
sum = 0.0;
aarg = arg;
/* Sum polynomial in log(nv/nvRef) */
for (i=1; i<nterm; i++) {
sum += inArrays[i]->array[indx]*aarg;
aarg *= arg;
}
/* Add value at reference frequency */
sum = exp(sum) * inArrays[0]->array[indx];
outArray->array[indx] = sum;
} /* end loop in X */
} /* end loop in y */
/* Write output */
IOBy = OBIT_IO_byPlane;
dim[0] = 1;
ObitInfoListAlwaysPut (outImage->info, "IOBy", OBIT_long, dim, &IOBy);
inImage->extBuffer = TRUE; /* Using outFArrays as I/O buffer */
retCode = ObitImageOpen (outImage, OBIT_IO_WriteOnly, err);
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error)) goto cleanup;
/* Write */
retCode = ObitImageWrite (outImage, outArray->array, err);
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error)) goto cleanup;
/* Close output */
retCode = ObitImageClose (outImage, err);
outImage->extBuffer = FALSE; /* May need I/O buffer later */
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error)) goto cleanup;
/* Cleanup */
cleanup:
if (inArrays) {
for (i=0; i<nterm; i++) inArrays[i] = ObitFArrayUnref (inArrays[i]);
g_free(inArrays);
}
if (outArray) outArray = ObitFArrayUnref (outArray);
if (err->error) Obit_traceback_msg (err, routine, outImage->name);
} /* end ObitSpectrumFitEval */
/**
* Fit single spectrum to flux measurements
* Without GSL, only the average intensity is determined (no spectrum)
* \param nfreq Number of entries in freq, flux, sigma
* \param nterm Number of coefficients of powers of log(nu) to fit
* \param refFreq Reference frequency (Hz)
* \param freq Array of Frequencies (Hz)
* \param flux Array of fluxes (Jy) same dim as freq
* \param sigma Array of errors (Jy) same dim as freq
* \param doBrokePow TRUE if a broken power law fit is desired (3 terms)
* \param err Obit error stack object.
* \return Array of fitter parameters, errors for each and Chi Squares of fit
* Initial terms are in Jy, other in log.
*/
ofloat* ObitSpectrumFitSingle (olong nfreq, olong nterm, odouble refFreq,
odouble *freq, ofloat *flux, ofloat *sigma,
gboolean doBrokePow, ObitErr *err)
{
ofloat *out = NULL;
olong i, j;
NLFitArg *arg=NULL;
gchar *routine = "ObitSpectrumFitSingle";
/* GSL implementation */
#ifdef HAVE_GSL
const gsl_multifit_fdfsolver_type *T=NULL;
#endif /* HAVE_GSL */
if (err->error) return out;
/* Warn if too many terms asked for */
if (nterm>5) {
Obit_log_error(err, OBIT_InfoWarn,
"%s: Asked for %d terms, will limit to 5", routine, nterm);
}
/* Warn if incorrect number of terms */
if (doBrokePow && (nterm!=3)) {
Obit_log_error(err, OBIT_InfoWarn,
"%s: Must have three terms for broken power law, not %d",
routine, nterm);
}
/* Warn if ref. freq <= 0, set to 1.0e9 */
if (refFreq<=0.0) {
refFreq = 1.0e9;
Obit_log_error(err, OBIT_InfoWarn,
"%s: Setting reference Frequency to 1 GHz", routine);
}
/* Create function argument */
arg = g_malloc(sizeof(NLFitArg));
arg->in = NULL; /* Not needed here */
arg->nfreq = nfreq;
arg->nterm = nterm;
arg->doError = TRUE;
arg->doBrokePow = doBrokePow;
arg->doPBCorr = FALSE;
arg->corAlpha = 0.0;
arg->maxIter = 100;
arg->minDelta = 1.0e-5; /* Min step size */
arg->maxChiSq = 1.5; /* max acceptable normalized chi squares */
arg->refFreq = refFreq; /* Reference Frequency */
arg->weight = g_malloc0(arg->nfreq*sizeof(ofloat));
arg->isigma = g_malloc0(arg->nfreq*sizeof(ofloat));
arg->obs = g_malloc0(arg->nfreq*sizeof(ofloat));
arg->nu = g_malloc0(arg->nfreq*sizeof(ofloat));
arg->logNuOnu0 = g_malloc0(arg->nfreq*sizeof(ofloat));
arg->coef = g_malloc0(3*arg->nterm*sizeof(ofloat));
for (i=0; i<nfreq; i++) {
if (sigma[i]>0.0) {
arg->isigma[i] = 1.0 / sigma[i];
arg->weight[i] = arg->isigma[i]*arg->isigma[i];
} else {
arg->isigma[i] = 0.0;
arg->weight[i] = 0.0;
}
arg->obs[i] = flux[i];
arg->nu[i] = freq[i];
arg->logNuOnu0[i] = log(freq[i]/refFreq);
}
/* GSL implementation */
#ifdef HAVE_GSL
arg->solver2 = arg->solver3 = arg->solver4 = arg->solver5 = NULL;
arg->covar2 = arg->covar3 = arg->covar4 = arg->covar5 = NULL;
arg->work2 = arg->work3 = arg->work4 = arg->work5 = NULL;
/* Setup solvers */
T = gsl_multifit_fdfsolver_lmder;
if (arg->nterm>=2)
arg->solver2 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 2);
if (arg->nterm>=3)
arg->solver3 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 3);
if (arg->nterm>=4)
arg->solver4 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 4);
if (arg->nterm>=5)
arg->solver5 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 5);
/* Fitting function info */
arg->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf));
if (doBrokePow) {
arg->funcStruc->f = &SpecFitFuncBP;
arg->funcStruc->df = &SpecFitJacBP;
arg->funcStruc->fdf = &SpecFitFuncJacBP;
} else {
arg->funcStruc->f = &SpecFitFunc;
arg->funcStruc->df = &SpecFitJac;
arg->funcStruc->fdf = &SpecFitFuncJac;
}
arg->funcStruc->n = arg->nfreq;
arg->funcStruc->p = arg->nterm;
arg->funcStruc->params = arg;
/* Set up work arrays */
if (arg->nterm>=2) {
arg->covar2 = gsl_matrix_alloc(2, 2);
arg->work2 = gsl_vector_alloc(2);
}
if (arg->nterm>=3) {
arg->covar3 = gsl_matrix_alloc(3, 3);
arg->work3 = gsl_vector_alloc(3);
}
if (arg->nterm>=4) {
arg->covar4 = gsl_matrix_alloc(4, 4);
arg->work4 = gsl_vector_alloc(4);
}
if (arg->nterm>=5) {
arg->covar5 = gsl_matrix_alloc(5, 5);
arg->work5 = gsl_vector_alloc(5);
}
#endif /* HAVE_GSL */
/* Fit - poly power or broken power */
if (arg->doBrokePow) {
/* Broken power law */
arg->nterm = 2; /* simple power law */
arg->funcStruc->f = &SpecFitFunc;
arg->funcStruc->df = &SpecFitJac;
arg->funcStruc->fdf = &SpecFitFuncJac;
NLFit(arg);
arg->nterm = 3; /* broken power law */
arg->funcStruc->f = &SpecFitFuncBP;
arg->funcStruc->df = &SpecFitJacBP;
arg->funcStruc->fdf = &SpecFitFuncJacBP;
NLFitBP(arg);
} else {
/* multi term power */
NLFit(arg);
}
/* get results parameters + errors */
out = g_malloc0((2*arg->nterm+1)*sizeof(ofloat));
for (j=0; j<nterm*2; j++) out[j] = arg->coef[j];
/* Chi squared */
out[nterm*2] = arg->ChiSq;
/* Cleanup */
if (arg->weight) g_free(arg->weight);
if (arg->isigma) g_free(arg->isigma);
if (arg->obs) g_free(arg->obs);
if (arg->nu) g_free(arg->nu);
if (arg->logNuOnu0) g_free(arg->logNuOnu0);
if (arg->coef) g_free(arg->coef);
#ifdef HAVE_GSL
if (arg->solver2) gsl_multifit_fdfsolver_free (arg->solver2);
if (arg->solver3) gsl_multifit_fdfsolver_free (arg->solver3);
if (arg->solver4) gsl_multifit_fdfsolver_free (arg->solver4);
if (arg->solver5) gsl_multifit_fdfsolver_free (arg->solver5);
if (arg->work2) gsl_vector_free(arg->work2);
if (arg->work3) gsl_vector_free(arg->work3);
if (arg->work4) gsl_vector_free(arg->work4);
if (arg->work5) gsl_vector_free(arg->work5);
if (arg->covar2) gsl_matrix_free(arg->covar2);
if (arg->covar3) gsl_matrix_free(arg->covar3);
if (arg->covar4) gsl_matrix_free(arg->covar4);
if (arg->covar5) gsl_matrix_free(arg->covar5);
if (arg->funcStruc) g_free(arg->funcStruc);
#endif /* HAVE_GSL */
g_free(arg);
return out;
} /* end ObitSpectrumFitSingle */
/**
* Make single spectrum fitting argument array
* Without GSL, only the average intensity is determined (no spectrum)
* \param nfreq Number of entries in freq, flux, sigma
* \param nterm Number of coefficients of powers of log(nu) to fit
* \param refFreq Reference frequency (Hz)
* \param freq Array of Frequencies (Hz)
* \param flux Array of fluxes (Jy) same dim as freq
* \param sigma Array of errors (Jy) same dim as freq
* \param doBrokePow TRUE if a broken power law fit is desired (3 terms)
* \param out Array for output results, should be g_freed when done
* \param err Obit error stack object.
* \return argument for single spectrum fitting, use ObitSpectrumFitKillArg to dispose.
*/
gpointer ObitSpectrumFitMakeArg (olong nfreq, olong nterm, odouble refFreq,
odouble *freq, gboolean doBrokePow,
ofloat **out, ObitErr *err)
{
olong i;
NLFitArg *arg=NULL;
gchar *routine = "ObitSpectrumFitMakeArg";
/* GSL implementation */
#ifdef HAVE_GSL
const gsl_multifit_fdfsolver_type *T=NULL;
#endif /* HAVE_GSL */
if (err->error) return out;
/* Warn if too many terms asked for */
if (nterm>5) {
Obit_log_error(err, OBIT_InfoWarn,
"%s: Asked for %d terms, will limit to 5", routine, nterm);
}
/* Warn if incorrect number of terms */
if (doBrokePow && (nterm!=3)) {
Obit_log_error(err, OBIT_InfoWarn,
"%s: Must have three terms for broken power law, not %d",
routine, nterm);
}
/* Warn if ref. freq <= 0, set to 1.0e9 */
if (refFreq<=0.0) {
refFreq = 1.0e9;
Obit_log_error(err, OBIT_InfoWarn,
"%s: Setting reference Frequency to 1 GHz", routine);
}
/* Create function argument */
arg = g_malloc(sizeof(NLFitArg));
arg->in = NULL; /* Not needed here */
arg->nfreq = nfreq;
arg->nterm = nterm;
arg->doError = TRUE;
arg->doBrokePow = doBrokePow;
arg->doPBCorr = FALSE;
arg->corAlpha = 0.0;
arg->maxIter = 100;
arg->minDelta = 1.0e-5; /* Min step size */
arg->maxChiSq = 3.0; /* max acceptable normalized chi squares */
arg->refFreq = refFreq; /* Reference Frequency */
arg->weight = g_malloc0(arg->nfreq*sizeof(ofloat));
arg->isigma = g_malloc0(arg->nfreq*sizeof(ofloat));
arg->obs = g_malloc0(arg->nfreq*sizeof(ofloat));
arg->nu = g_malloc0(arg->nfreq*sizeof(ofloat));
arg->logNuOnu0 = g_malloc0(arg->nfreq*sizeof(ofloat));
arg->coef = g_malloc0(3*arg->nterm*sizeof(ofloat));
for (i=0; i<nfreq; i++) {
arg->nu[i] = freq[i];
arg->logNuOnu0[i] = log(freq[i]/refFreq);
}
/* GSL implementation */
#ifdef HAVE_GSL
arg->solver2 = arg->solver3 = arg->solver4 = arg->solver5 = NULL;
arg->covar2 = arg->covar3 = arg->covar4 = arg->covar5 = NULL;
arg->work2 = arg->work3 = arg->work4 = arg->work5 = NULL;
/* Setup solvers */
T = gsl_multifit_fdfsolver_lmder;
if (arg->nterm>=2)
arg->solver2 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 2);
if (arg->nterm>=3)
arg->solver3 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 3);
if (arg->nterm>=4)
arg->solver4 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 4);
if (arg->nterm>=5)
arg->solver5 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 5);
/* Fitting function info */
arg->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf));
if (doBrokePow) {
arg->funcStruc->f = &SpecFitFuncBP;
arg->funcStruc->df = &SpecFitJacBP;
arg->funcStruc->fdf = &SpecFitFuncJacBP;
} else {
arg->funcStruc->f = &SpecFitFunc;
arg->funcStruc->df = &SpecFitJac;
arg->funcStruc->fdf = &SpecFitFuncJac;
}
arg->funcStruc->n = arg->nfreq;
arg->funcStruc->p = arg->nterm;
arg->funcStruc->params = arg;
/* Set up work arrays */
if (arg->nterm>=2) {
arg->covar2 = gsl_matrix_alloc(2, 2);
arg->work2 = gsl_vector_alloc(2);
}
if (arg->nterm>=3) {
arg->covar3 = gsl_matrix_alloc(3, 3);
arg->work3 = gsl_vector_alloc(3);
}
if (arg->nterm>=4) {
arg->covar4 = gsl_matrix_alloc(4, 4);
arg->work4 = gsl_vector_alloc(4);
}
if (arg->nterm>=5) {
arg->covar5 = gsl_matrix_alloc(5, 5);
arg->work5 = gsl_vector_alloc(5);
}
#endif /* HAVE_GSL */
/* output array */
*out = (ofloat*)g_malloc0((2*arg->nterm+1)*sizeof(ofloat));
return (gpointer)arg;
} /* end ObitSpectrumFitMakeArg */
/**
* Fit single spectrum to flux measurements using precomputed argument
* \param aarg pointer to argument for fitting
* \param flux Array of values to be fitted
* \param sigma Array of uncertainties of flux
* \param out Result array at least 2*nterms+1 in size.
* in order, fitted parameters, error estimates, chi sq of fit.
*/
void ObitSpectrumFitSingleArg (gpointer aarg, ofloat *flux, ofloat *sigma,
ofloat *out)
{
olong i, j;
NLFitArg *arg=(NLFitArg*)aarg;
ofloat fblank = ObitMagicF();
gboolean allBad;
/* Save flux array, sigma, Check if all data blanked */
allBad = TRUE;
for (i=0; i<arg->nfreq; i++) arg->obs[i] = flux[i];
for (i=0; i<arg->nfreq; i++) {
arg->obs[i] = flux[i];
if (arg->obs[i]!=fblank) allBad = FALSE;
arg->isigma[i] = 1.0 / sigma[i];
arg->weight[i] = arg->isigma[i]*arg->isigma[i];
}
/* Return fblanks/zeroes for no data */
if (allBad) {
out[0] = fblank;
for (j=1; j<=arg->nterm*2; j++) out[j] = 0.0;
return;
}
/* Fit - poly power or broken power */
if (arg->doBrokePow) {
/* Broken power law */
arg->nterm = 2; /* simple power law */
arg->funcStruc->f = &SpecFitFunc;
arg->funcStruc->df = &SpecFitJac;
arg->funcStruc->fdf = &SpecFitFuncJac;
NLFit(arg);
arg->nterm = 3; /* broken power law */
arg->funcStruc->f = &SpecFitFuncBP;
arg->funcStruc->df = &SpecFitJacBP;
arg->funcStruc->fdf = &SpecFitFuncJacBP;
NLFitBP(arg);
} else {
/* multi term power */
NLFit(arg);
}
/* get results parameters + errors */
for (j=0; j<arg->nterm*2; j++) out[j] = arg->coef[j];
/* Chi squared */
out[arg->nterm*2] = arg->ChiSq;
return;
} /* end ObitSpectrumFitSingleArg */
/**
* Delete single fitting argument
* \param aarg pointer to argument to kill
*/
void ObitSpectrumFitKillArg (gpointer aarg)
{
NLFitArg *arg= (NLFitArg*)aarg;
if (arg==NULL) return;
if (arg->weight) g_free(arg->weight);
if (arg->isigma) g_free(arg->isigma);
if (arg->obs) g_free(arg->obs);
if (arg->nu) g_free(arg->nu);
if (arg->logNuOnu0) g_free(arg->logNuOnu0);
if (arg->coef) g_free(arg->coef);
#ifdef HAVE_GSL
if (arg->solver2) gsl_multifit_fdfsolver_free (arg->solver2);
if (arg->solver3) gsl_multifit_fdfsolver_free (arg->solver3);
if (arg->solver4) gsl_multifit_fdfsolver_free (arg->solver4);
if (arg->solver5) gsl_multifit_fdfsolver_free (arg->solver5);
if (arg->work2) gsl_vector_free(arg->work2);
if (arg->work3) gsl_vector_free(arg->work3);
if (arg->work4) gsl_vector_free(arg->work4);
if (arg->work5) gsl_vector_free(arg->work5);
if (arg->covar2) gsl_matrix_free(arg->covar2);
if (arg->covar3) gsl_matrix_free(arg->covar3);
if (arg->covar4) gsl_matrix_free(arg->covar4);
if (arg->covar5) gsl_matrix_free(arg->covar5);
if (arg->funcStruc) g_free(arg->funcStruc);
#endif /* HAVE_GSL */
g_free(arg);
} /* end ObitSpectrumFitKillArg */
/**
* Initialize global ClassInfo Structure.
*/
void ObitSpectrumFitClassInit (void)
{
if (myClassInfo.initialized) return; /* only once */
/* Set name and parent for this class */
myClassInfo.ClassName = g_strdup(myClassName);
myClassInfo.ParentClass = ObitParentGetClass();
/* Set function pointers */
ObitSpectrumFitClassInfoDefFn ((gpointer)&myClassInfo);
myClassInfo.initialized = TRUE; /* Now initialized */
} /* end ObitSpectrumFitClassInit */
/**
* Initialize global ClassInfo Function pointers.
*/
static void ObitSpectrumFitClassInfoDefFn (gpointer inClass)
{
ObitSpectrumFitClassInfo *theClass = (ObitSpectrumFitClassInfo*)inClass;
ObitClassInfo *ParentClass = (ObitClassInfo*)myClassInfo.ParentClass;
if (theClass->initialized) return; /* only once */
/* Check type of inClass */
g_assert (ObitInfoIsA(inClass, (ObitClassInfo*)&myClassInfo));
/* Initialize (recursively) parent class first */
if ((ParentClass!=NULL) &&
(ParentClass->ObitClassInfoDefFn!=NULL))
ParentClass->ObitClassInfoDefFn(theClass);
/* function pointers defined or overloaded this class */
theClass->ObitClassInit = (ObitClassInitFP)ObitSpectrumFitClassInit;
theClass->newObit = (newObitFP)newObitSpectrumFit;
theClass->ObitClassInfoDefFn = (ObitClassInfoDefFnFP)ObitSpectrumFitClassInfoDefFn;
theClass->ObitGetClass = (ObitGetClassFP)ObitSpectrumFitGetClass;
theClass->ObitCopy = (ObitCopyFP)ObitSpectrumFitCopy;
theClass->ObitClone = NULL;
theClass->ObitClear = (ObitClearFP)ObitSpectrumFitClear;
theClass->ObitInit = (ObitInitFP)ObitSpectrumFitInit;
theClass->ObitSpectrumFitCreate = (ObitSpectrumFitCreateFP)ObitSpectrumFitCreate;
theClass->ObitSpectrumFitCube = (ObitSpectrumFitCubeFP)ObitSpectrumFitCube;
theClass->ObitSpectrumFitImArr = (ObitSpectrumFitImArrFP)ObitSpectrumFitImArr;
theClass->ObitSpectrumFitEval = (ObitSpectrumFitEvalFP)ObitSpectrumFitEval;
theClass->ObitSpectrumFitSingle = (ObitSpectrumFitSingleFP)ObitSpectrumFitSingle;
theClass->ObitSpectrumFitter = (ObitSpectrumFitterFP)ObitSpectrumFitter;
theClass->ObitSpectrumWriteOutput = (ObitSpectrumWriteOutputFP)ObitSpectrumWriteOutput;
} /* end ObitSpectrumFitClassDefFn */
/*---------------Private functions--------------------------*/
/**
* Creates empty member objects, initialize reference count.
* Parent classes portions are (recursively) initialized first
* \param inn Pointer to the object to initialize.
*/
void ObitSpectrumFitInit (gpointer inn)
{
ObitClassInfo *ParentClass;
ObitSpectrumFit *in = inn;
/* error checks */
g_assert (in != NULL);
/* recursively initialize parent class members */
ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass);
if ((ParentClass!=NULL) && ( ParentClass->ObitInit!=NULL))
ParentClass->ObitInit (inn);
/* set members in this class */
in->thread = newObitThread();
in->info = newObitInfoList();
in->nterm = 0;
in->nfreq = 0;
in->doBrokePow = FALSE;
in->maxChi2 = 1.5;
in->minWt = 0.5;
in->RMS = NULL;
in->calFract = NULL;
in->outDesc = NULL;
in->inFArrays = NULL;
in->BeamShapes = NULL;
in->outFArrays = NULL;
in->freqs = NULL;
} /* end ObitSpectrumFitInit */
/**
* Deallocates member objects.
* Does (recursive) deallocation of parent class members.
* \param inn Pointer to the object to deallocate.
* Actually it should be an ObitSpectrumFit* cast to an Obit*.
*/
void ObitSpectrumFitClear (gpointer inn)
{
ObitClassInfo *ParentClass;
ObitSpectrumFit *in = inn;
olong i, nOut;
/* error checks */
g_assert (ObitIsA(in, &myClassInfo));
/* delete this class members */
if (in->RMS) g_free(in->RMS);
if (in->calFract) g_free(in->calFract);
in->thread = ObitThreadUnref(in->thread);
in->info = ObitInfoListUnref(in->info);
if (in->outDesc) in->outDesc = ObitImageDescUnref(in->outDesc);
if (in->inFArrays) {
for (i=0; i<in->nfreq; i++) in->inFArrays[i] = ObitFArrayUnref(in->inFArrays[i]);
g_free(in->inFArrays);
}
if (in->BeamShapes) {
for (i=0; i<in->nfreq; i++) in->BeamShapes[i] = ObitBeamShapeUnref(in->BeamShapes[i]);
g_free(in->BeamShapes);
}
/* How many output planes */
if (in->doError) nOut = 1+in->nterm*2;
else nOut = in->nterm;
if (in->outFArrays) {
for (i=0; i<nOut; i++) in->outFArrays[i] = ObitFArrayUnref(in->outFArrays[i]);
g_free(in->outFArrays);
}
if (in->freqs) g_free(in->freqs);
/* unlink parent class members */
ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass);
/* delete parent class members */
if ((ParentClass!=NULL) && ( ParentClass->ObitClear!=NULL))
ParentClass->ObitClear (inn);
} /* end ObitSpectrumFitClear */
/**
* Does spectral fitting, input and output on input object
* Work divided up amoung 1 or more threads
* In each pixel determines weighted average and RMS and if the SNR
* exceeds maxChi2 then the spectrum is fitted.
* The pixel value at the reference frequency is either the average pixel
* if the SNR is too low or 10^(first term) of fit.
* The results are stored in outFArrays:
* \li first entry is the pixel value (Jy/bm) at the reference freq
* \li entries 1->nterm-1 are the coefficients of log(freq/refFreq)^n
* possibly magic value blanked for pixels with no signal
* \li outFArrays[nterm] = RMS estimate for pixel values (Jy/bm) at refFreq
* \li entries nterm+1->nterm*2 RMS uncertainties on higher order coefficients
* \li entry 1+nterm*2 = the Chi squared of the fit
*
* \param in SpectrumFit to fit
* \param err Obit error stack object.
*/
void ObitSpectrumFitter (ObitSpectrumFit* in, ObitErr *err)
{
olong i, loy, hiy, nyPerThread, nThreads;
gboolean OK;
NLFitArg **threadArgs;
NLFitArg *args=NULL;
ObitThreadFunc func=(ObitThreadFunc)ThreadNLFit;
gchar *routine = "ObitSpectrumFitter";
/* GSL implementation */
#ifdef HAVE_GSL
const gsl_multifit_fdfsolver_type *T=NULL;
#endif /* HAVE_GSL */
/* error checks */
if (err->error) return;
/* Warn if too many terms asked for */
if (in->nterm>5) {
Obit_log_error(err, OBIT_InfoWarn,
"%s: Asked for %d terms, will limit to 5", routine, in->nterm);
}
/* How many threads to use? */
nThreads = MAX (1, ObitThreadNumProc(in->thread));
/* Initialize threadArg array */
threadArgs = g_malloc0(nThreads*sizeof(NLFitArg*));
for (i=0; i<nThreads; i++)
threadArgs[i] = g_malloc0(sizeof(NLFitArg));
/* Set up thread arguments */
for (i=0; i<nThreads; i++) {
args = (NLFitArg*)threadArgs[i];
args->in = in;
args->err = err;
args->nfreq = in->nfreq;
args->nterm = in->nterm;
args->doError = in->doError;
args->doBrokePow = in->doBrokePow;
args->doPBCorr = in->doPBCorr;
args->corAlpha = in->corAlpha;
args->minWt = in->minWt;
args->maxIter = 100;
args->minDelta = 1.0e-2; /* Min step size */
args->maxChiSq = in->maxChi2; /* max acceptable normalized chi squares */
args->weight = g_malloc0(args->nfreq*sizeof(ofloat));
args->isigma = g_malloc0(args->nfreq*sizeof(ofloat));
args->obs = g_malloc0(args->nfreq*sizeof(ofloat));
args->nu = g_malloc0(args->nfreq*sizeof(ofloat));
args->logNuOnu0 = g_malloc0(args->nfreq*sizeof(ofloat));
if (args->doError)
args->coef = g_malloc0(2*args->nterm*sizeof(ofloat));
else
args->coef = g_malloc0(args->nterm*sizeof(ofloat));
/* GSL implementation */
#ifdef HAVE_GSL
args->solver2 = args->solver3 = args->solver4 = args->solver5 = NULL;
args->covar2 = args->covar3 = args->covar4 = args->covar5 = NULL;
args->work2 = args->work3 = args->work4 = args->work5 = NULL;
/* Setup solvers */
T = gsl_multifit_fdfsolver_lmder;
if (args->nterm>=2)
args->solver2 = gsl_multifit_fdfsolver_alloc(T, args->nfreq, 2);
if (args->nterm>=3)
args->solver3 = gsl_multifit_fdfsolver_alloc(T, args->nfreq, 3);
if (args->nterm>=4)
args->solver4 = gsl_multifit_fdfsolver_alloc(T, args->nfreq, 4);
if (args->nterm>=5)
args->solver5 = gsl_multifit_fdfsolver_alloc(T, args->nfreq, 5);
/* Fitting function info */
args->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf));
if (in->doBrokePow) {
args->funcStruc->f = &SpecFitFuncBP;
args->funcStruc->df = &SpecFitJacBP;
args->funcStruc->fdf = &SpecFitFuncJacBP;
} else {
args->funcStruc->f = &SpecFitFunc;
args->funcStruc->df = &SpecFitJac;
args->funcStruc->fdf = &SpecFitFuncJac;
}
args->funcStruc->n = args->nfreq;
args->funcStruc->p = args->nterm;
args->funcStruc->params = args;
/* Set up work arrays */
if (args->nterm>=2) {
args->covar2 = gsl_matrix_alloc(2, 2);
args->work2 = gsl_vector_alloc(2);
}
if (args->nterm>=3) {
args->covar3 = gsl_matrix_alloc(3, 3);
args->work3 = gsl_vector_alloc(3);
}
if (args->nterm>=4) {
args->covar4 = gsl_matrix_alloc(4, 4);
args->work4 = gsl_vector_alloc(4);
}
if (args->nterm>=5) {
args->covar5 = gsl_matrix_alloc(5, 5);
args->work5 = gsl_vector_alloc(5);
}
#endif /* HAVE_GSL */
}
/* end initialize */
/* Divide up work */
nyPerThread = in->ny/nThreads;
loy = 1;
hiy = nyPerThread;
hiy = MIN (hiy, in->ny);
/* Set up thread arguments */
for (i=0; i<nThreads; i++) {
if (i==(nThreads-1)) hiy = in->ny; /* Make sure do all */
args = (NLFitArg*)threadArgs[i];
args->first = loy;
args->last = hiy;
if (nThreads>1) args->ithread = i;
else args->ithread = -1;
/* Update which y */
loy += nyPerThread;
hiy += nyPerThread;
hiy = MIN (hiy, in->ny);
}
/* Do operation possibly with threads */
OK = ObitThreadIterator (in->thread, nThreads, func, (gpointer)threadArgs);
/* Check for problems */
if (!OK) {
Obit_log_error(err, OBIT_Error,"%s: Problem in threading", routine);
}
/* Shut down any threading */
ObitThreadPoolFree (in->thread);
if (threadArgs) {
for (i=0; i<nThreads; i++) {
args = (NLFitArg*)threadArgs[i];
if (args->weight) g_free(args->weight);
if (args->isigma) g_free(args->isigma);
if (args->obs) g_free(args->obs);
if (args->nu) g_free(args->nu);
if (args->logNuOnu0) g_free(args->logNuOnu0);
if (args->coef) g_free(args->coef);
#ifdef HAVE_GSL
if (args->solver2) gsl_multifit_fdfsolver_free (args->solver2);
if (args->solver3) gsl_multifit_fdfsolver_free (args->solver3);
if (args->solver4) gsl_multifit_fdfsolver_free (args->solver3);
if (args->solver4) gsl_multifit_fdfsolver_free (args->solver3);
if (args->work2) gsl_vector_free(args->work2);
if (args->work3) gsl_vector_free(args->work3);
if (args->work4) gsl_vector_free(args->work4);
if (args->work5) gsl_vector_free(args->work5);
if (args->covar2) gsl_matrix_free(args->covar2);
if (args->covar3) gsl_matrix_free(args->covar3);
if (args->covar4) gsl_matrix_free(args->covar4);
if (args->covar5) gsl_matrix_free(args->covar5);
if (args->funcStruc) g_free(args->funcStruc);
#endif /* HAVE_GSL */
g_free(threadArgs[i]);
}
g_free(threadArgs);
}
} /* end ObitSpectrumFitter */
/**
* Write contents on in to outImage
* \param in Spectral fitting object
* \param outImage Image cube with fitted spectra.
* Should be defined but not created.
* Planes 1->nterm are coefficients per pixel
* Planes nterm+1->2*nterm are uncertainties in coefficients
* \param err Obit error stack object.
*/
void ObitSpectrumWriteOutput (ObitSpectrumFit* in, ObitImage *outImage,
ObitErr *err)
{
olong iplane, nOut;
ObitIOSize IOBy;
olong i, blc[IM_MAXDIM], trc[IM_MAXDIM];
ObitIOCode retCode;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
gchar *routine = "ObitSpectrumWriteOutput";
/* error checks */
if (err->error) return;
g_assert (ObitIsA(in, &myClassInfo));
g_assert(ObitImageIsA(outImage));
/* Open output- all, by plane */
dim[0] = IM_MAXDIM;
for (i=0; i<IM_MAXDIM; i++) blc[i] = 1;
for (i=0; i<IM_MAXDIM; i++) trc[i] = 0;
ObitInfoListPut (outImage->info, "BLC", OBIT_long, dim, blc, err);
ObitInfoListPut (outImage->info, "TRC", OBIT_long, dim, trc, err);
IOBy = OBIT_IO_byPlane;
dim[0] = 1;
ObitInfoListAlwaysPut (outImage->info, "IOBy", OBIT_long, dim, &IOBy);
outImage->extBuffer = TRUE; /* Using outFArrays as I/O buffer */
retCode = ObitImageOpen (outImage, OBIT_IO_ReadWrite, err);
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error))
Obit_traceback_msg (err, routine, outImage->name);
/* save descriptive material */
ObitImageDescCopyDesc (in->outDesc, outImage->myDesc, err);
if (err->error) Obit_traceback_msg (err, routine, outImage->name);
/* How many output planes? */
if (in->doError) nOut = 1+in->nterm*2;
else nOut = in->nterm;
/* Loop writing planes */
for (iplane=0; iplane<nOut; iplane++) {
retCode = ObitImageWrite (outImage, in->outFArrays[iplane]->array, err);
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, outImage->name);
} /* end loop writing planes */
/* Save nterms on output descriptor */
dim[0] = dim[1] = dim[2] = 1;
ObitInfoListAlwaysPut (outImage->myDesc->info, "NTERM", OBIT_long, dim, &in->nterm);
ObitInfoListAlwaysPut (((ObitImageDesc*)outImage->myIO->myDesc)->info, "NTERM",
OBIT_long, dim, &in->nterm);
/* If doBrokePow set "BROKENPO" to TRUE on output descriptor */
if (in->doBrokePow) {
dim[0] = dim[1] = dim[2] = 1;
ObitInfoListAlwaysPut (outImage->myDesc->info, "BROKENPO", OBIT_bool, dim, &in->doBrokePow);
ObitInfoListAlwaysPut (((ObitImageDesc*)outImage->myIO->myDesc)->info, "BROKENPO",
OBIT_bool, dim, &in->doBrokePow);
}
/* Close output */
retCode = ObitImageClose (outImage, err);
outImage->extBuffer = FALSE; /* May need I/O buffer later */
/* if it didn't work bail out */
if ((retCode!=OBIT_IO_OK) || (err->error))
Obit_traceback_msg (err, routine, outImage->name);
} /* end ObitSpectrumWriteOutput */
/**
* Thread function to fit a portion of the image set
* \param arg NLFitArg structure
*/
static gpointer ThreadNLFit (gpointer arg)
{
NLFitArg *larg = (NLFitArg*)arg;
ObitSpectrumFit* in = (ObitSpectrumFit*)larg->in;
olong lo = larg->first-1; /* First in y range */
olong hi = larg->last; /* Highest in y range */
gboolean doError = larg->doError; /* Error analysis? */
gboolean doPBCorr = larg->doPBCorr; /* Primary beam correction? */
ofloat corAlpha = larg->corAlpha;
ofloat *Freq = larg->nu;
ObitErr *err = larg->err;
olong ix, iy, indx, i, nOut;
odouble Angle=0.0, pos[2];
ofloat pbfact, spFact, pixel[2];
ofloat fblank = ObitMagicF();
ObitBeamShapeClassInfo *BSClass;
ofloat sumWt, allWt;
gchar *routine = "ThreadNLFit";
/* error checks */
if (err->error) return NULL;
g_assert (ObitIsA(in, &myClassInfo));
/* Set up frequency info */
larg->refFreq = in->refFreq;
for (i=0; i<in->nfreq; i++) {
larg->logNuOnu0[i] = log(in->freqs[i]/in->refFreq);
larg->nu[i] = in->freqs[i];
}
/* How many output planes */
if (in->doError) nOut = 1+in->nterm*2;
else nOut = in->nterm;
/* Get maximum possible weight */
allWt = 0.0;
for (i=0; i<in->nfreq; i++) {
if (in->RMS[i]>0.0) {
allWt += 1.0 / (in->RMS[i]*in->RMS[i]);
}
}
/* Loop over pixels in Y */
indx = lo*in->nx -1; /* Offset in pixel arrays */
for (iy=lo; iy<hi; iy++) {
/* Loop over pixels in X */
for (ix=0; ix<in->nx; ix++) {
indx ++;
/* Primary beam correction? */
if (doPBCorr) {
/* Distance from Center */
pixel[0] = (ofloat)(ix+1.0); pixel[1] = (ofloat)(iy+1.0);
ObitImageDescGetPos(in->outDesc, pixel, pos, err);
if (err->error) {
ObitThreadLock(in->thread); /* Lock against other threads */
Obit_log_error(err, OBIT_Error,"%s Error with position %s",
routine, in->name);
ObitThreadUnlock(in->thread);
return NULL;
}
BSClass = (ObitBeamShapeClassInfo*)(in->BeamShapes[0]->ClassInfo);
Angle = BSClass->ObitBeamShapeAngle(in->BeamShapes[0], pos[0], pos[1], 0.0);
}
/* Collect values; */
sumWt = 0.0;
for (i=0; i<in->nfreq; i++) {
larg->obs[i] = in->inFArrays[i]->array[indx];
if (larg->obs[i]!=fblank) {
/* Statistical weight */
if (in->RMS[i]>0.0) {
larg->isigma[i] = 1.0 / (in->RMS[i]*in->RMS[i] +
in->calFract[i]*in->calFract[i]*
larg->obs[i]*larg->obs[i]);
larg->weight[i] = larg->isigma[i];
larg->isigma[i] = sqrt(larg->isigma[i]);
} else {
larg->weight[i] = 0.0;
larg->isigma[i] = 0.0;
}
/* Primary beam correction */
if (doPBCorr) {
BSClass = (ObitBeamShapeClassInfo*)(in->BeamShapes[i]->ClassInfo);
pbfact = BSClass->ObitBeamShapeGainSym(in->BeamShapes[i], Angle);
if ((pbfact==fblank) ||(pbfact<1.001*in->BeamShapes[i]->pbmin)) {
larg->obs[i] = fblank;
larg->weight[i] = 0.0;
} else {
larg->obs[i] /= pbfact;
larg->weight[i] *= pbfact*pbfact;
sumWt += 1.0 / (in->RMS[i]*in->RMS[i]);
}
}
/* End if datum valid */
} else { /* invalid pixel */
larg->weight[i] = 0.0;
larg->isigma[i] = 0.0;
}
} /* end loop over frequencies */
/* Enough data to bother with? */
if (sumWt<larg->minWt*allWt) {
/* Save to output */
if (doError) {
for (i=0; i<nOut-1; i++)
in->outFArrays[i]->array[indx] = fblank;
in->outFArrays[nOut-1]->array[indx] = 0.0;
} else { /* only values */
for (i=0; i<in->nterm; i++)
in->outFArrays[i]->array[indx] = fblank;
}
continue; /* Done with pixel */
}
/* Spectral index correction */
if (corAlpha!=0.0) {
for (i=0; i<in->nfreq; i++) {
spFact = (ofloat)pow(Freq[i]/in->refFreq, -corAlpha);
larg->obs[i] *= spFact;
larg->weight[i] /= spFact*spFact;
larg->isigma[i] /= spFact;
}
}
/* initialize with values from last time */
if (doError) {
for (i=0; i<nOut-1; i++)
larg->coef[i] = in->outFArrays[i]->array[indx];
larg->ChiSq = 0.0;
} else { /* only values */
for (i=0; i<in->nterm; i++)
larg->coef[i] = in->outFArrays[i]->array[indx];
}
/* Fit - poly power or broken power */
if (larg->doBrokePow) {
/* Broken power law */
in->nterm = 2; /* simple power law */
larg->funcStruc->f = &SpecFitFunc;
larg->funcStruc->df = &SpecFitJac;
larg->funcStruc->fdf = &SpecFitFuncJac;
NLFit(larg);
in->nterm = 3; /* broken power law */
larg->funcStruc->f = &SpecFitFuncBP;
larg->funcStruc->df = &SpecFitJacBP;
larg->funcStruc->fdf = &SpecFitFuncJacBP;
NLFitBP(larg);
} else {
/* multi term power */
NLFit(larg);
}
/* Spectral index correction */
if (nOut>=1) larg->coef[1] += corAlpha;
/* Save to output */
if (doError) {
for (i=0; i<nOut-1; i++)
in->outFArrays[i]->array[indx] = larg->coef[i];
in->outFArrays[nOut-1]->array[indx] = larg->ChiSq;
} else { /* only values */
for (i=0; i<in->nterm; i++)
in->outFArrays[i]->array[indx] = larg->coef[i];
}
} /* end x loop */
} /* end y loop */
/* Indicate completion */
if (larg->ithread>=0)
ObitThreadPoolDone (in->thread, (gpointer)&larg->ithread);
return NULL;
} /* end ThreadNLFit */
/**
* Do non linear fit to a spectrum
* Only fits for up to 5 terms
* \param arg NLFitArg structure
* fitted parameters returned in arg->in->coef
*/
static void NLFit (NLFitArg *arg)
{
olong iter=0, i, nterm=arg->nterm, nvalid, best;
ofloat avg, delta, chi2Test, sigma, fblank = ObitMagicF();
ofloat meanSNR, SNRperTerm=1.0;
odouble sum, sumwt, sum2;
gboolean isDone;
int status;
#ifdef HAVE_GSL
gsl_multifit_fdfsolver *solver=NULL;
gsl_matrix *covar=NULL;
gsl_vector *work=NULL;
gsl_matrix *J;
#endif /* HAVE_GSL */
/* Initialize output */
if (arg->doError)
for (i=0; i<2*arg->nterm; i++) arg->coef[i] = 0.0;
else
for (i=0; i<arg->nterm; i++) arg->coef[i] = 0.0;
/* determine weighted average, count valid data */
sum = sumwt = 0.0;
nvalid = 0;
for (i=0; i<arg->nfreq; i++) {
if ((arg->obs[i]!=fblank) && (arg->weight[i]>0.0)) {
sum += arg->weight[i] * arg->obs[i];
sumwt += arg->weight[i];
nvalid++;
}
}
if (nvalid<=0) return; /* any good data? */
avg = sum/sumwt;
/* Estimate of noise */
sigma = 1.0 / sqrt(sumwt);
/* Initial fit */
arg->coef[0] = avg;
best = 1; /* best fit number of terms */
if (nvalid==1) return; /* Only one? */
/* determine chi squared, mean SNR */
sum = sum2 = sumwt = 0.0;
for (i=0; i<arg->nfreq; i++) {
if ((arg->obs[i]!=fblank) && (arg->weight[i]>0.0)) {
delta = (arg->obs[i]-avg);
sumwt += arg->weight[i] * delta*delta;
sum += delta*delta;
sum2 += fabs(arg->obs[i])*sqrt(arg->weight[i]);
}
}
/* normalized Chi squares */
if (nvalid>1) {
arg->ChiSq = sumwt/(nvalid-1);
meanSNR = sum2/nvalid; /* mean SNR */
} else {
arg->ChiSq = -1.0;
meanSNR = 0.0; /* Only one value - don't need mean SNR */
}
/* Errors wanted? */
if (arg->doError) {
arg->coef[2] = sigma; /* Flux error */
arg->coef[2*arg->nterm] = sum/nvalid;
}
/* Is this good enough? */
isDone = (arg->ChiSq<0.0) || (arg->ChiSq<=arg->maxChiSq);
//if (meanSNR>(SNRperTerm*3.0)) isDone = FALSE; /* Always try for high SNR */
if (meanSNR>SNRperTerm) isDone = FALSE; /*Always try for high SNR */
if (isDone) goto done;
/* Higher order terms do nonlinear least-squares fit */
nterm = 2;
while ((nterm<=MIN(5,arg->nterm)) && (nterm<=nvalid)) {
arg->fitTerm = nterm; /* How many actually being fitted */
#ifdef HAVE_GSL
/* Set solver and covar */
if (nterm==2) {
solver = arg->solver2;
covar = arg->covar2;
work = arg->work2;
} else if (nterm==3) {
solver = arg->solver3;
covar = arg->covar3;
work = arg->work3;
} else if (nterm==4) {
solver = arg->solver4;
covar = arg->covar4;
work = arg->work4;
} else if (nterm==5) {
solver = arg->solver5;
covar = arg->covar5;
work = arg->work5;
}
/* set initial guess - start with lower order fit */
for (i=0; i<nterm; i++) gsl_vector_set(work, i, (double)arg->coef[i]);
arg->funcStruc->n = arg->nfreq;
arg->funcStruc->p = nterm;
arg->funcStruc->params = arg;
gsl_multifit_fdfsolver_set (solver, arg->funcStruc, work);
iter = 0;
/* iteration loop */
do {
iter++;
status = gsl_multifit_fdfsolver_iterate(solver);
/*if (status) break;???*/
status = gsl_multifit_test_delta (solver->dx, solver->x,
(double)arg->minDelta,
(double)arg->minDelta);
} while ((status==GSL_CONTINUE) && (iter<arg->maxIter));
/* If it didn't work - bail */
if ((status!=GSL_SUCCESS) && (status!=GSL_CONTINUE)) {
fprintf (stderr, "Failed, status = %s\n", gsl_strerror(status));
return;
}
J = gsl_matrix_alloc(nterm, nterm);
/* normalized Chi squares */
if (nvalid>nterm) {
sumwt = (ofloat)gsl_blas_dnrm2(solver->f);
chi2Test = (sumwt*sumwt)/(nvalid-nterm);
} else chi2Test = -1.0;
/* Did it significantly improve over lower order? */
//if (chi2Test<0.9*arg->ChiSq) {
if (chi2Test<1.5*arg->ChiSq) { /* Not much worse */
best = nterm;
arg->ChiSq = chi2Test;
/* Get fitted values */
for (i=0; i<nterm; i++) arg->coef[i] = (ofloat)gsl_vector_get(solver->x, i);
/* Errors wanted? */
if (arg->doError) {
#ifdef HAVE_GSL_MULTIFIT_FDFSOLVER_JAC
gsl_multifit_fdfsolver_jac(solver, J);
#else
gsl_matrix_memcpy(J, solver->J);
#endif
gsl_multifit_covar (J, 0.0, covar);
for (i=0; i<nterm; i++) {
arg->coef[arg->nterm+i] = sqrt(gsl_matrix_get(covar, i, i));
/* Clip to sanity range */
arg->coef[arg->nterm+i] = MAX (-1.0e5, MIN (1.0e5, arg->coef[arg->nterm+i]));
}
} /* end of get errors */
/* Sanity check on spectral parameters [-3,3]
for (i=1; i<nterm; i++) arg->coef[i] = MAX(-3.0, MIN(3.0,arg->coef[i])); */
} /* End if better than lower order */
gsl_matrix_free(J);
/* Is this good enough? */
isDone = (arg->ChiSq<0.0) || (arg->ChiSq<=arg->maxChiSq) || (chi2Test>arg->ChiSq);
if ((meanSNR>(SNRperTerm*nterm)) && (nterm<arg->nterm))
isDone = FALSE; /* Always try for high SNR */
if (isDone) goto done;
/* if ((arg->ChiSq>0.0) && (arg->ChiSq<=arg->maxChiSq)) goto done;*/
nterm++; /* next term */
} /* end loop over adding terms */
#endif /* HAVE_GSL */
done:
if (best==1) arg->coef[0] = avg; /* Only fitted one term? */
/* sanity check, if flux < sigma, don't include higher order terms */
if (fabs(arg->coef[0])<sigma) {
arg->coef[0] = avg;
for (i=1; i<arg->nterm; i++) arg->coef[i] = 0.0;
}
/* Gonzo higher order fit */
if ((fabs(arg->coef[1])>3.0) || ((nterm>2) && (fabs(arg->coef[2])>2.0))) {
arg->coef[0] = avg;
for (i=1; i<arg->nterm; i++) arg->coef[i] = 0.0;
}
} /* end NLFit */
/**
* Do non linear fit to a broken power law spectrum
* Only fits 3 terms
* Broken power law version, above nv_b the spectrum steepens by half
* Parameters:
* S_0 = Flux density at frequency nu_0
* alpha = spectral index
* nu_b = Break frequency
* When called the S_O and the alpha terms should have been estimated
* (call to NLFit with 2 terms); the initial break frequency is set to
* the reference frequency.
* \param arg NLFitArg structure
* fitted parameters returned in arg->in->coef
*/
static void NLFitBP (NLFitArg *arg)
{
olong iter=0, i, nterm, nvalid;
ofloat chi2Test, sigma, fblank = ObitMagicF();
odouble sum, sumwt;
int status;
#ifdef HAVE_GSL
gsl_multifit_fdfsolver *solver;
gsl_matrix *covar;
gsl_vector *work;
gsl_matrix *J;
#endif /* HAVE_GSL */
/* determine weighted average, count valid data */
sum = sumwt = 0.0;
nvalid = 0;
for (i=0; i<arg->nfreq; i++) {
if ((arg->obs[i]!=fblank) && (arg->weight[i]>0.0)) {
sum += arg->weight[i] * arg->obs[i];
sumwt += arg->weight[i];
nvalid++;
}
}
if (nvalid<=(arg->nterm)) return; /* enough good data? */
/*avg = sum/sumwt;*/
/* Estimate of noise */
sigma = 1.0 / sqrt(sumwt);
/* Do nonlinear least-squares fit */
nterm = 3;
arg->fitTerm = nterm; /* How many actually being fitted */
#ifdef HAVE_GSL
/* Set solver and covar */
solver = arg->solver3;
covar = arg->covar3;
work = arg->work3;
/* set initial guess - start with lower order fit */
/* Initial break frequency is reference freq */
arg->coef[2] = arg->refFreq;
for (i=0; i<nterm; i++) gsl_vector_set(work, i, (double)arg->coef[i]);
arg->funcStruc->n = arg->nfreq;
arg->funcStruc->p = nterm;
arg->funcStruc->params = arg;
gsl_multifit_fdfsolver_set (solver, arg->funcStruc, work);
iter = 0;
/* iteration loop */
do {
iter++;
status = gsl_multifit_fdfsolver_iterate(solver);
/*if (status) break;???*/
status = gsl_multifit_test_delta (solver->dx, solver->x,
(double)arg->minDelta,
(double)arg->minDelta);
} while ((status==GSL_CONTINUE) && (iter<arg->maxIter));
/* If it didn't work - bail */
if ((status!=GSL_SUCCESS) && (status!=GSL_CONTINUE)) {
fprintf (stderr, "Failed, status = %s\n", gsl_strerror(status));
return;
}
/* normalized Chi squares */
if (nvalid>nterm) {
sumwt = (ofloat)gsl_blas_dnrm2(solver->f);
chi2Test = (sumwt*sumwt)/(nvalid-nterm);
} else chi2Test = -1.0;
/* Is this better than a simple power law? */
/*if (chi2Test<arg->ChiSq) {*/
arg->ChiSq = chi2Test;
/* Get fitted values */
for (i=0; i<nterm; i++) arg->coef[i] = (ofloat)gsl_vector_get(solver->x, i);
/* DEBUG
if (arg->coef[0]>50.0*sigma) {
fprintf (stdout, "DEBUG %f %f %f \n",arg->coef[0], arg->coef[1], arg->coef[2]);
}*/
/* Errors wanted? */
if (arg->doError) {
J = gsl_matrix_alloc(nterm, nterm);
#ifdef HAVE_GSL_MULTIFIT_FDFSOLVER_JAC
gsl_multifit_fdfsolver_jac(solver, J);
#else
gsl_matrix_memcpy(J, solver->J);
#endif
gsl_multifit_covar (J, 0.0, covar);
for (i=0; i<nterm; i++) {
arg->coef[arg->nterm+i] = sqrt(gsl_matrix_get(covar, i, i));
/* Clip to sanity range
arg->coef[arg->nterm+i] = MAX (-1.0e5, MIN (1.0e5, arg->coef[arg->nterm+i])); */
}
gsl_matrix_free(J);
} /* end of get errors */
/* Sanity check on spectral parameters [-3,3]
for (i=1; i<nterm; i++) arg->coef[i] = MAX(-3.0, MIN(3.0,arg->coef[i])); */
/* End if better than simple power law */
/*} else {*/
/* Worse, use simple power law Make break very high */
/* arg->coef[2] = 1.0e20;*/
/*}*/
#endif /* HAVE_GSL */
/* sanity check, if flux < sigma, don't include higher order terms */
if (fabs(arg->coef[0])<sigma)
for (i=1; i<arg->nterm; i++) arg->coef[i] = 0.0;
/* Gonzo higher order fit
if ((fabs(arg->coef[1])>3.0) || (arg->coef[2]>arg->nu[arg->nfreq-1])) {
arg->coef[0] = avg;
for (i=1; i<arg->nterm; i++) arg->coef[i] = 0.0;
}*/
} /* end NLFitBP */
#ifdef HAVE_GSL
/**
* Function evaluator for spectral fitting solver
* Evaluates (model-observed) / sigma
* \param x Vector of parameters to be fitted
* Flux,array_of spectral_terms
* \param param Function parameter structure (NLFitArg)
* \param f Vector of (model-obs)/sigma for data points
* \return completion code GSL_SUCCESS=OK
*/
static int SpecFitFunc (const gsl_vector *x, void *params,
gsl_vector *f)
{
NLFitArg *args = (NLFitArg*)params;
ofloat fblank = ObitMagicF();
double flux, spec[10], func;
odouble model, arg, argx, isigma, spect;
size_t i, j;
/* get model parameters */
flux = gsl_vector_get(x, 0);
for (j=1; j<args->fitTerm; j++) spec[j-1] = gsl_vector_get(x, j);
/* Loop over spectral points */
for (i=0; i<args->nfreq; i++) {
if ((args->obs[i]!=fblank) && (args->isigma[i]>0.0)) {
isigma = args->isigma[i];
arg = 0.0;
argx = args->logNuOnu0[i];
for (j=1; j<args->fitTerm; j++) {
arg += spec[j-1]*argx;
argx *= args->logNuOnu0[i];
}
spect = exp(arg);
model = flux * spect;
func = (model - args->obs[i]) * isigma;
gsl_vector_set(f, i, func); /* Save function residual */
} else { /* Invalid data */
func = 0.0;
gsl_vector_set(f, i, func); /* Save function residual */
}
} /* End loop over spectral points */
return GSL_SUCCESS;
} /* end SpecFitFunc */
/**
* Jacobian evaluator for spectral fitting solver
* Evaluates partial derivatives of model wrt each parameter
* \param x Vector of parameters to be fitted
* Flux,array_of spectral_terms
* \param param Function parameter structure (NLFitArg)
* \param J Jacobian matrix J[data_point, parameter]
* \return completion code GSL_SUCCESS=OK
*/
static int SpecFitJac (const gsl_vector *x, void *params,
gsl_matrix *J)
{
NLFitArg *args = (NLFitArg*)params;
ofloat fblank = ObitMagicF();
double flux, spec[10], jac;
odouble model, arg, argx, isigma, spect;
size_t i, j;
/* get model parameters */
flux = gsl_vector_get(x, 0);
for (j=1; j<args->fitTerm; j++) spec[j-1] = gsl_vector_get(x, j);
/* Loop over spectral points */
for (i=0; i<args->nfreq; i++) {
if ((args->obs[i]!=fblank) && (args->isigma[i]>0.0)) {
isigma = args->isigma[i];
arg = 0.0;
argx = args->logNuOnu0[i];
for (j=1; j<args->fitTerm; j++) {
arg += spec[j-1]*argx;
argx *= args->logNuOnu0[i];
}
spect = exp(arg);
model = flux * spect;
/* Jacobian terms - first flux */
jac = spect * isigma;
gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */
argx = args->logNuOnu0[i];
for (j=1; j<args->fitTerm; j++) {
jac = model * isigma * argx;
gsl_matrix_set(J, i, j, jac); /* Save Jacobian */
argx *= args->logNuOnu0[i];
}
} else { /* Invalid data */
jac = 0.0;
gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */
for (j=1; j<args->fitTerm; j++) {
gsl_matrix_set(J, i, j, jac); /* Save Jacobian */
}
}
} /* End loop over spectral points */
return GSL_SUCCESS;
} /* end SpecFitJac */
/**
* Function and Jacobian evaluator for spectral fitting solver
* Function = (model-observed) / sigma
* Jacobian = partial derivatives of model wrt each parameter
* \param x Vector of parameters to be fitted
* Flux,array_of spectral_terms
* \param param Function parameter structure (NLFitArg)
* \param f Vector of (model-obs)/sigma for data points
* \param J Jacobian matrix J[data_point, parameter]
* \return completion code GSL_SUCCESS=OK
*/
static int SpecFitFuncJac (const gsl_vector *x, void *params,
gsl_vector *f, gsl_matrix *J)
{
NLFitArg *args = (NLFitArg*)params;
ofloat fblank = ObitMagicF();
double flux, spec[10], func, jac;
odouble model, arg, argx, isigma, spect;
size_t i, j;
/* get model parameters */
flux = gsl_vector_get(x, 0);
for (j=1; j<args->fitTerm; j++) spec[j-1] = gsl_vector_get(x, j);
/* Loop over spectral points */
for (i=0; i<args->nfreq; i++) {
if ((args->obs[i]!=fblank) && (args->isigma[i]>0.0)) {
isigma = args->isigma[i];
arg = 0.0;
argx = args->logNuOnu0[i];
for (j=1; j<args->fitTerm; j++) {
arg += spec[j-1]*argx;
argx *= args->logNuOnu0[i];
}
spect = exp(arg);
model = flux * spect;
func = (model - args->obs[i]) * isigma;
gsl_vector_set(f, i, func); /* Save function residual */
/* Jacobian terms - first flux */
jac = spect * isigma;
gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */
argx = args->logNuOnu0[i];
for (j=1; j<args->fitTerm; j++) {
jac = model * isigma * argx;
gsl_matrix_set(J, i, j, jac); /* Save Jacobian */
argx *= args->logNuOnu0[i];
}
} else { /* Invalid data */
func = 0.0;
gsl_vector_set(f, i, func); /* Save function residual */
jac = 0.0;
gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */
for (j=1; j<args->fitTerm; j++) {
gsl_matrix_set(J, i, j, jac); /* Save Jacobian */
}
}
} /* End loop over spectral points */
return GSL_SUCCESS;
} /* end SpecFitFuncJac */
/**
* Function evaluator for spectral fitting solver
* Broken power law version, above nv_b the spectrum steepens by half
* Parameters:
* S_0 = Flux density at frequency nu_0
* alpha = spectral index
* nu_b = Break frequency
* Evaluates (model-observed) / sigma
* \param x Vector of parameters to be fitted
* Flux,array_of spectral_terms
* \param param Function parameter structure (NLFitArg)
* \param f Vector of (model-obs)/sigma for data points
* \return completion code GSL_SUCCESS=OK
*/
static int SpecFitFuncBP (const gsl_vector *x, void *params,
gsl_vector *f)
{
NLFitArg *args = (NLFitArg*)params;
ofloat fblank = ObitMagicF();
double flux, spec[10], func;
odouble model, fluxb, arg, isigma, spect;
size_t i, j;
/* get model parameters */
flux = gsl_vector_get(x, 0);
/* Spectral terms - alpha, nu_b */
for (j=1; j<args->fitTerm; j++) spec[j-1] = gsl_vector_get(x, j);
/* Loop over spectral points */
for (i=0; i<args->nfreq; i++) {
if ((args->obs[i]!=fblank) && (args->isigma[i]>0.0)) {
/* Above or below the break? */
if (args->nu[i]<spec[1]) { /* Below - simple power law */
arg = spec[0] * args->logNuOnu0[i];
spect = exp(arg);
model = flux * spect;
} else { /* above */
/* Get the flux density at the break */
arg = spec[0] * log (spec[1] / args->refFreq);
spect = exp(arg);
fluxb = flux * spect;
/* Flux density at frequency */
arg = (spec[0]-0.5) * log (args->nu[i] / spec[1]);
spect = exp(arg);
model = fluxb * spect;
} /* End of above or below the break */
isigma = args->isigma[i];
func = (model - args->obs[i]) * isigma;
gsl_vector_set(f, i, func); /* Save function residual */
} else { /* Invalid data */
func = 0.0;
gsl_vector_set(f, i, func); /* Save function residual */
}
} /* End loop over spectral points */
return GSL_SUCCESS;
} /* end SpecFitFuncBP */
/**
* Jacobian evaluator for spectral fitting solver
* Broken power law version, above nv_b the spectrum steepens by half
* Parameters:
* S_0 = Flux density at frequency nu_0
* alpha = spectral index
* nu_b = Break frequency
* Evaluates partial derivatives of model wrt each parameter
* \param x Vector of parameters to be fitted
* Flux,array_of spectral_terms
* \param param Function parameter structure (NLFitArg)
* \param J Jacobian matrix J[data_point, parameter]
* \return completion code GSL_SUCCESS=OK
*/
static int SpecFitJacBP (const gsl_vector *x, void *params,
gsl_matrix *J)
{
NLFitArg *args = (NLFitArg*)params;
ofloat fblank = ObitMagicF();
double flux, spec[10], jac;
odouble model, fluxb, arg, isigma, spect, spect2;
odouble logNubONu0, logNuONub;
size_t i, j;
/* get model parameters */
flux = gsl_vector_get(x, 0);
/* Spectral terms - alpha, nu_b */
for (j=1; j<args->fitTerm; j++) spec[j-1] = gsl_vector_get(x, j);
/* Loop over spectral points */
for (i=0; i<args->nfreq; i++) {
if ((args->obs[i]!=fblank) && (args->isigma[i]>0.0)) {
isigma = args->isigma[i];
/* Above or below the break? */
if (args->nu[i]<spec[1]) { /* Below - simple power law */
arg = spec[0] * args->logNuOnu0[i];
spect = exp(arg);
model = flux * spect;
/* Jacobian terms - first flux */
jac = spect * isigma;
gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */
/* Spectral index */
jac = model * isigma * args->logNuOnu0[i];
gsl_matrix_set(J, i, 1, jac); /* Save spectral index Jacobian */
/* Break frequency - no dependency */
jac = 0.0;
gsl_matrix_set(J, i, 2, jac); /* Save spectral index Jacobian */
} else { /* above */
/* Get the flux density at the break */
logNubONu0 = log (spec[1] / args->refFreq);
arg = spec[0] * logNubONu0;
spect = exp(arg);
fluxb = flux * spect;
/* Flux density at frequency */
logNuONub = log (args->nu[i] / spec[1]);
arg = (spec[0]-0.5) * logNuONub;
spect2 = exp(arg);
model = fluxb * spect2;
/* Jacobian terms - first flux */
jac = spect * spect2 * isigma;
gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */
/* Spectral index */
jac = (fluxb*logNubONu0 + model*logNuONub) * isigma;
gsl_matrix_set(J, i, 1, jac); /* Save spectral index Jacobian */
/* Break frequency */
jac = isigma * (fluxb*spec[0] - model*(spec[0]-0.5)) / spec[1];
gsl_matrix_set(J, i, 2, jac); /* Save break frequency Jacobian */
} /* End of above or below the break */
} else { /* Invalid data */
jac = 0.0;
gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */
for (j=1; j<args->fitTerm; j++) {
gsl_matrix_set(J, i, j, jac); /* Save Jacobian */
}
}
} /* End loop over spectral points */
return GSL_SUCCESS;
} /* end SpecFitJacBP */
/**
* Function and Jacobian evaluator for spectral fitting solver
* Broken power law version, above nv_b the spectrum steepens by half
* Parameters:
* S_0 = Flux density at frequency nu_0
* alpha = spectral index
* nu_b = Break frequency
* Function = (model-observed) / sigma
* Jacobian = partial derivatives of model wrt each parameter
* \param x Vector of parameters to be fitted
* Flux,array_of spectral_terms
* \param param Function parameter structure (NLFitArg)
* \param f Vector of (model-obs)/sigma for data points
* \param J Jacobian matrix J[data_point, parameter]
* \return completion code GSL_SUCCESS=OK
*/
static int SpecFitFuncJacBP (const gsl_vector *x, void *params,
gsl_vector *f, gsl_matrix *J)
{
NLFitArg *args = (NLFitArg*)params;
ofloat fblank = ObitMagicF();
double flux, spec[10], func, jac;
odouble model, arg, fluxb, isigma, spect, spect2;
odouble logNubONu0, logNuONub;
size_t i, j;
/* get model parameters */
flux = gsl_vector_get(x, 0);
/* Spectral terms - alpha, nu_b */
for (j=1; j<args->fitTerm; j++) spec[j-1] = gsl_vector_get(x, j);
/* Loop over spectral points */
for (i=0; i<args->nfreq; i++) {
if ((args->obs[i]!=fblank) && (args->isigma[i]>0.0)) {
isigma = args->isigma[i];
/* Above or below the break? */
if (args->nu[i]<spec[1]) { /* Below - simple power law */
arg = spec[0] * args->logNuOnu0[i];
spect = exp(arg);
model = flux * spect;
func = (model - args->obs[i]) * isigma;
gsl_vector_set(f, i, func); /* Save function residual */
/* Jacobian terms - first flux */
jac = spect * isigma;
gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */
/* Spectral index */
jac = model * isigma * args->logNuOnu0[i];
gsl_matrix_set(J, i, 1, jac); /* Save spectral index Jacobian */
/* Break frequency - no dependency */
jac = 0.0;
gsl_matrix_set(J, i, 2, jac); /* Save spectral index Jacobian */
} else { /* above */
/* Get the flux density at the break */
logNubONu0 = log (spec[1] / args->refFreq);
arg = spec[0] * logNubONu0;
spect = exp(arg);
fluxb = flux * spect;
/* Flux density at frequency */
logNuONub = log (args->nu[i] / spec[1]);
arg = (spec[0]-0.5) * logNuONub;
spect2 = exp(arg);
model = fluxb * spect2;
func = (model - args->obs[i]) * isigma;
gsl_vector_set(f, i, func); /* Save function residual */
/* Jacobian terms - first flux */
jac = spect * spect2 * isigma;
gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */
/* Spectral index */
jac = (fluxb*logNubONu0 + model*logNuONub) * isigma;
gsl_matrix_set(J, i, 1, jac); /* Save spectral index Jacobian */
/* Break frequency */
jac = isigma * (fluxb*spec[0] - model*(spec[0]-0.5)) / spec[1];
gsl_matrix_set(J, i, 2, jac); /* Save break frequency Jacobian */
} /* End of above or below the break */
} else { /* Invalid data */
func = 0.0;
gsl_vector_set(f, i, func); /* Save function residual */
jac = 0.0;
gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */
for (j=1; j<args->fitTerm; j++) {
gsl_matrix_set(J, i, j, jac); /* Save Jacobian */
}
}
} /* End loop over spectral points */
return GSL_SUCCESS;
} /* end SpecFitFuncJacBP */
#endif /* HAVE_GSL */
| {
"alphanum_fraction": 0.6223390165,
"avg_line_length": 35.2269503546,
"ext": "c",
"hexsha": "8d62e5d93092ed3e21b5e5e89d742e54b345763a",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-12-22T14:07:41.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-12-22T14:07:41.000Z",
"max_forks_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5",
"max_forks_repo_licenses": [
"Linux-OpenIB"
],
"max_forks_repo_name": "kettenis/Obit",
"max_forks_repo_path": "ObitSystem/Obit/src/ObitSpectrumFit.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Linux-OpenIB"
],
"max_issues_repo_name": "kettenis/Obit",
"max_issues_repo_path": "ObitSystem/Obit/src/ObitSpectrumFit.c",
"max_line_length": 102,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5",
"max_stars_repo_licenses": [
"Linux-OpenIB"
],
"max_stars_repo_name": "kettenis/Obit",
"max_stars_repo_path": "ObitSystem/Obit/src/ObitSpectrumFit.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 30396,
"size": 94373
} |
/* vector/gsl_vector_uchar.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __GSL_VECTOR_UCHAR_H__
#define __GSL_VECTOR_UCHAR_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_block_uchar.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
unsigned char *data;
gsl_block_uchar *block;
int owner;
}
gsl_vector_uchar;
typedef struct
{
gsl_vector_uchar vector;
} _gsl_vector_uchar_view;
typedef _gsl_vector_uchar_view gsl_vector_uchar_view;
typedef struct
{
gsl_vector_uchar vector;
} _gsl_vector_uchar_const_view;
typedef const _gsl_vector_uchar_const_view gsl_vector_uchar_const_view;
/* Allocation */
gsl_vector_uchar *gsl_vector_uchar_alloc (const size_t n);
gsl_vector_uchar *gsl_vector_uchar_calloc (const size_t n);
gsl_vector_uchar *gsl_vector_uchar_alloc_from_block (gsl_block_uchar * b,
const size_t offset,
const size_t n,
const size_t stride);
gsl_vector_uchar *gsl_vector_uchar_alloc_from_vector (gsl_vector_uchar * v,
const size_t offset,
const size_t n,
const size_t stride);
void gsl_vector_uchar_free (gsl_vector_uchar * v);
/* Views */
_gsl_vector_uchar_view
gsl_vector_uchar_view_array (unsigned char *v, size_t n);
_gsl_vector_uchar_view
gsl_vector_uchar_view_array_with_stride (unsigned char *base,
size_t stride,
size_t n);
_gsl_vector_uchar_const_view
gsl_vector_uchar_const_view_array (const unsigned char *v, size_t n);
_gsl_vector_uchar_const_view
gsl_vector_uchar_const_view_array_with_stride (const unsigned char *base,
size_t stride,
size_t n);
_gsl_vector_uchar_view
gsl_vector_uchar_subvector (gsl_vector_uchar *v,
size_t i,
size_t n);
_gsl_vector_uchar_view
gsl_vector_uchar_subvector_with_stride (gsl_vector_uchar *v,
size_t i,
size_t stride,
size_t n);
_gsl_vector_uchar_const_view
gsl_vector_uchar_const_subvector (const gsl_vector_uchar *v,
size_t i,
size_t n);
_gsl_vector_uchar_const_view
gsl_vector_uchar_const_subvector_with_stride (const gsl_vector_uchar *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
unsigned char gsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i);
void gsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x);
unsigned char *gsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i);
const unsigned char *gsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i);
void gsl_vector_uchar_set_zero (gsl_vector_uchar * v);
void gsl_vector_uchar_set_all (gsl_vector_uchar * v, unsigned char x);
int gsl_vector_uchar_set_basis (gsl_vector_uchar * v, size_t i);
int gsl_vector_uchar_fread (FILE * stream, gsl_vector_uchar * v);
int gsl_vector_uchar_fwrite (FILE * stream, const gsl_vector_uchar * v);
int gsl_vector_uchar_fscanf (FILE * stream, gsl_vector_uchar * v);
int gsl_vector_uchar_fprintf (FILE * stream, const gsl_vector_uchar * v,
const char *format);
int gsl_vector_uchar_memcpy (gsl_vector_uchar * dest, const gsl_vector_uchar * src);
int gsl_vector_uchar_reverse (gsl_vector_uchar * v);
int gsl_vector_uchar_swap (gsl_vector_uchar * v, gsl_vector_uchar * w);
int gsl_vector_uchar_swap_elements (gsl_vector_uchar * v, const size_t i, const size_t j);
unsigned char gsl_vector_uchar_max (const gsl_vector_uchar * v);
unsigned char gsl_vector_uchar_min (const gsl_vector_uchar * v);
void gsl_vector_uchar_minmax (const gsl_vector_uchar * v, unsigned char * min_out, unsigned char * max_out);
size_t gsl_vector_uchar_max_index (const gsl_vector_uchar * v);
size_t gsl_vector_uchar_min_index (const gsl_vector_uchar * v);
void gsl_vector_uchar_minmax_index (const gsl_vector_uchar * v, size_t * imin, size_t * imax);
int gsl_vector_uchar_add (gsl_vector_uchar * a, const gsl_vector_uchar * b);
int gsl_vector_uchar_sub (gsl_vector_uchar * a, const gsl_vector_uchar * b);
int gsl_vector_uchar_mul (gsl_vector_uchar * a, const gsl_vector_uchar * b);
int gsl_vector_uchar_div (gsl_vector_uchar * a, const gsl_vector_uchar * b);
int gsl_vector_uchar_scale (gsl_vector_uchar * a, const double x);
int gsl_vector_uchar_add_constant (gsl_vector_uchar * a, const double x);
int gsl_vector_uchar_isnull (const gsl_vector_uchar * v);
#ifdef HAVE_INLINE
extern inline
unsigned char
gsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return v->data[i * v->stride];
}
extern inline
void
gsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}
extern inline
unsigned char *
gsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (unsigned char *) (v->data + i * v->stride);
}
extern inline
const unsigned char *
gsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (const unsigned char *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_UCHAR_H__ */
| {
"alphanum_fraction": 0.6760993203,
"avg_line_length": 31.7577092511,
"ext": "h",
"hexsha": "b778ad65c7b60ae0e4dee0f48686bcac713d4ab9",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2021-06-10T03:09:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-04-29T20:31:00.000Z",
"max_forks_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pvnuffel/test_repos",
"max_forks_repo_path": "gsl_subset/gsl/gsl_vector_uchar.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_issues_repo_issues_event_max_datetime": "2020-07-20T16:32:02.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-07T05:42:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pvnuffel/test_repos",
"max_issues_repo_path": "gsl_subset/gsl/gsl_vector_uchar.h",
"max_line_length": 108,
"max_stars_count": 30,
"max_stars_repo_head_hexsha": "c0d957265608b15f216ece67363c827d01122102",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pvnuffel/test_repos",
"max_stars_repo_path": "gsl_subset/gsl/gsl_vector_uchar.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T02:07:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-29T05:13:02.000Z",
"num_tokens": 1782,
"size": 7209
} |
/*
Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file 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 NNTYPES_H
#define NNTYPES_H
#include <vector>
#include <set>
#include <string>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <netcdf>
#ifndef __NVCC__
#include <tuple>
#include <json/json.h>
#endif
#include <cmath>
#include <memory>
class NNDataSetBase;
class NNLayer;
class NNNetwork;
class NNWeight;
// Activates step by step CPU validation
#define VALIDATION
#ifdef VALIDATION
extern "C"
{
#include <cblas.h>
}
#endif
static const float NN_VERSION = 0.9f;
static const float MIN_ERROR = 1.0e-12f;
static const float MIN_ACTIVATION = 0.000001f;
static const float MAX_ACTIVATION = 0.999999f;
static const float MAX_VALUE = 999999999999999.0f;
template <typename T> struct GpuBuffer;
enum
{
DefaultBatch = 512
};
enum Mode {
Prediction = 0,
Training = 1,
Validation = 2,
Unspecified = 3
};
enum TrainingMode
{
SGD = 0,
Momentum = 1,
AdaGrad = 2,
Nesterov = 3,
RMSProp = 4,
AdaDelta = 5,
Adam = 6,
};
ostream& operator<< (ostream& out, const TrainingMode& e);
enum ErrorFunction
{
L1,
L2,
CrossEntropy,
ScaledMarginalCrossEntropy,
DataScaledMarginalCrossEntropy,
Hinge,
L2Hinge,
};
ostream& operator<< (ostream& out, const ErrorFunction& e);
enum Activation {
Sigmoid,
Tanh,
RectifiedLinear,
Linear,
ParametricRectifiedLinear,
SoftPlus,
SoftSign,
SoftMax,
RELUMax,
LinearMax,
ExponentialLinear,
LeakyRectifiedLinear,
ScaledExponentialLinear,
};
ostream& operator<< (ostream& out, const Activation& a);
enum WeightInitialization
{
Xavier,
CaffeXavier,
Gaussian,
Uniform,
UnitBall,
Constant,
SELU,
};
ostream& operator<< (ostream& out, const WeightInitialization& w);
enum PoolingFunction {
None,
Max,
Average,
LRN,
Maxout,
DotProduct,
Cosine,
Stochastic,
LCN,
GlobalTemporal,
};
ostream& operator<< (ostream& out, const PoolingFunction& p);
#include "kernels.h"
#include "GpuSort.h"
#include "NNEnum.h"
#include "NNWeight.h"
#include "NNLayer.h"
#include "NNNetwork.h"
int MPI_Bcast_string(string& s);
struct NNDataSetDimensions
{
uint32_t _dimensions;
uint32_t _width;
uint32_t _height;
uint32_t _length;
NNDataSetDimensions();
NNDataSetDimensions(uint32_t width, uint32_t height = 1, uint32_t length = 1);
};
struct NNDataSetDescriptor
{
string _name; // dataset name
NNDataSetEnums::DataType _dataType; // dataset type
uint32_t _attributes; // dataset attributes
NNDataSetDimensions _dim; // dataset dimensions
uint32_t _examples; // number of examples in this dataset
float _sparseDensity; // sparseness density of this dataset
/**
* Only support vanilla sparse and dense datasets for now
*/
static bool isSupported(uint32_t attributes)
{
using NNDataSetEnums::Attributes;
static const vector<Attributes> SUPPORTED_ATTRIBUTES(Attributes::Sparse);
for (auto mask : SUPPORTED_ATTRIBUTES)
{
if (attributes & mask)
{
attributes -= mask;
}
}
return attributes == 0;
}
};
/**
* Creates a new NNDatSetBase object given the descriptor.
* Only attributes specified by the NNDataSetDescriptor::isSupported
* is valid. If any other attributes are specified, a std::runtime_error
* is thrown. It is the caller's responsibility to delete the returned object
* (not wrapping the return value with a unique_ptr to be consistent with
* the rest of the code base).
*/
NNDataSetBase* createNNDataSet(const NNDataSetDescriptor &descriptor);
struct NNDataSetBase {
string _name; // Dataset name
NNDataSetEnums::DataType _dataType; // Dataset type (see above enum)
uint32_t _attributes; // Dataset characteristics (see NNDataSetEnum::Attributes in NNEnum.h)
uint32_t _examples; // Number of examples
uint32_t _uniqueExamples; // Number of unique examples for indexed data (set to examples if unindexed)
uint32_t _localExamples; // Number of local examples when data sharded
uint32_t _dimensions; // Dimensionality of data set
uint32_t _width; // Dataset x dimension
uint32_t _height; // Dataset y dimension
uint32_t _length; // Dataset z dimension
uint32_t _stride; // Stride between examples
NNDataSetEnums::Sharding _sharding; // Sharding of dataset for parallel execution
uint32_t _minX; // Beginning of local X sharding for model parallel execution
uint32_t _maxX; // End of local X sharding for model parallel execution
uint64_t _sparseDataSize; // Total sparse datapoints
NNFloat _sparseDensity; // Overall sparse density (0.0 - 1.0)
vector<uint64_t> _vSparseStart; // Vector of sparse datapoint starts per example
unique_ptr<GpuBuffer<uint64_t>> _pbSparseStart; // GPU copy of _vSparseStart
vector<uint64_t> _vSparseEnd; // Vector of sparse datapoint ends per example
unique_ptr<GpuBuffer<uint64_t>> _pbSparseEnd; // GPU copy of _vSparseEnd
vector<uint32_t> _vSparseIndex; // Vector of sparse indices
unique_ptr<GpuBuffer<uint32_t>> _pbSparseIndex; // GPU copy of _vSparseIndex
vector<NNFloat> _vDataWeight; // Per example sparse index weights
unique_ptr<GpuBuffer<NNFloat>> _pbDataWeight; // GPU copy of _vDataWeight
vector<uint32_t> _vIndex; // Indexed data array
unique_ptr<GpuBuffer<uint32_t>> _pbIndex; // GPU copy of _vIndex;
unique_ptr<GpuBuffer<NNFloat>> _pbDenoisingRandom; // Denoising randoms
// Transposed sparse lookup for sparse backpropagation
vector<uint64_t> _vSparseDatapointCount;
vector<uint32_t> _vSparseMaxDatapointCount;
vector<uint32_t> _vSparseMultiDatapointCount;
vector<uint32_t> _vSparseTransposedStart;
uint64_t _sparseTransposedIndices;
unique_ptr<GpuBuffer<uint32_t>> _pbSparseTransposedStart;
unique_ptr<GpuBuffer<uint32_t>> _pbSparseTransposedEnd;
unique_ptr<GpuBuffer<uint32_t>> _pbSparseTransposedIndex;
unique_ptr<GpuBuffer<NNFloat>> _pbSparseTransposedData;
// States
bool _bDenoising;
bool _bDirty;
bool _bStreaming;
bool _bIndexed;
uint32_t _batch;
NNDataSetBase();
NNDataSetDimensions GetDimensions();
uint32_t GetExamples() { return _examples; };
uint32_t GetUniqueExamples() { return _uniqueExamples; };
virtual bool SaveNetCDF(const string& fname) = 0;
virtual bool WriteNetCDF(netCDF::NcFile& nfc, const string& fname, const uint32_t n) = 0;
virtual ~NNDataSetBase() = 0;
virtual void RefreshState(uint32_t batch) = 0;
virtual bool Shard(NNDataSetEnums::Sharding sharding) = 0;
virtual bool UnShard() = 0;
virtual bool SetStreaming(bool flag) = 0;
virtual bool GetStreaming() = 0;
virtual vector<tuple<uint64_t, uint64_t> > getMemoryUsage() = 0;
virtual bool CalculateSparseDatapointCounts() = 0;
virtual bool GenerateSparseTransposedMatrix(uint32_t batch, NNLayer* pLayer) = 0;
virtual bool CalculateSparseTransposedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer) = 0;
virtual bool CalculateSparseTransposedDenoisedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer) = 0;
virtual bool CalculateSparseTransposedWeightGradient(NNFloat alpha, NNFloat beta, uint32_t m, uint32_t n, NNFloat* pDelta, NNFloat* pWeightGradient) = 0;
virtual bool SetDenoising(bool flag) = 0;
virtual bool GenerateDenoisingData() = 0;
virtual bool LoadInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual bool LoadSparseInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual bool LoadSparseDenoisedInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual bool CalculateSparseZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta = (NNFloat)0.0) = 0;
virtual bool CalculateSparseDenoisedZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta = (NNFloat)0.0) = 0;
virtual float CalculateL1Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateL2Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateL2HingeError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateMultinomialCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateMultinomialScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateDataScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateHingeError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual bool CalculateL1OutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta, NNFloat slope, NNFloat alpha, NNFloat lambda) = 0;
virtual bool CalculateCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta) = 0;
virtual bool CalculateScaledMarginalCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta) = 0;
virtual bool CalculateOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta, NNFloat slope, NNFloat alpha, NNFloat lambda) = 0;
virtual bool CalculateL2HingeOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta, NNFloat slope, NNFloat alpha, NNFloat lambda) = 0;
virtual bool CalculateDataScaledMarginalCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta) = 0;
virtual bool CalculateHingeOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta) = 0;
/**
* Copies data from srcData to this dataset and uploads to GPU.
* The length to copy is determined by the example size and stride
* of this dataset. Only valid for dense and dense indexed datasets.
* If the dataset is indexed this sets the unique data
* and NNDataSet::SetIndexedData sets the actual examples.
* An exception is thrown if this dataset is not dense.
*/
virtual void LoadDenseData(const void *srcData) = 0;
/**
* Copies data from srcData to this dataset but doesn't upload to GPU.
*/
virtual void CopyDenseData(const void *srcData) = 0;
/**
* Copies sparse data points from the specified src to this NNDataSet
* and uploads to GPU. Any existing data is overwritten.
* An exception is thrown if this dataset is not sparse.
*/
virtual void LoadSparseData(const uint64_t *srcSparseStart, const uint64_t *srcSparseEnd, const void *srcSparseData,
const uint32_t *srcSparseIndex) = 0;
/**
* Copies sparse data points from the specified src to this NNDataSet
* but doesn't upload to GPU. Any existing data is overwritten.
* An exception is thrown if this dataset is not sparse.
*/
virtual void CopySparseData(const uint64_t *srcSparseStart, const uint64_t *srcSparseEnd, const void *srcSparseData,
const uint32_t *srcSparseIndex) = 0;
/**
* Same as LoadSparseData(const uint64_t*, const uint64_t*, const void*, const uint32_t*) except that
* it takes long* for the sparse start, end and indexes and casts them into
* uint64_t and uint32_t during load. It is up to the caller to ensure that the cast is bounds safe
* (e.g. no negative indexes). This method is useful when writing language extensions for those languages
* that do not have unsigned primitive types (e.g. Java).
*/
virtual void LoadSparseData(const long *srcSparseStart, const long *srcSparseEnd, const void *srcSparseData,
const long *srcSparseIndex) = 0;
/**
* Same as CopySparseData(const uint64_t*, const uint64_t*, const void*, const uint32_t*) except that
* it takes long* for the sparse start, end and indexes and casts them into
* uint64_t and uint32_t during load. It is up to the caller to ensure that the cast is bounds safe
* (e.g. no negative indexes). This method is useful when writing language extensions for those languages
* that do not have unsigned primitive types (e.g. Java).
*/
virtual void CopySparseData(const long *srcSparseStart, const long *srcSparseEnd, const void *srcSparseData,
const long *srcSparseIndex) = 0;
/**
* If this dataset is indexed, then sets the actual (unique) examples.
* An exception is thrown if this dataset is not indexed.
*/
virtual void LoadIndexedData(const uint32_t *srcIndexedData) = 0;
/**
* If this dataset is weighted, then sets the weights for each example.
* An exception is thrown if this dataset is not weighted.
*/
virtual void LoadDataWeight(const NNFloat *srcWeightData) = 0;
protected:
NNDataSetBase(const string &name, NNDataSetEnums::DataType dataType, uint32_t examples, uint32_t uniqueExamples,
const NNDataSetDimensions &datasetDim);
};
ostream& operator<< (ostream& out, NNDataSetEnums::Attributes& a);
ostream& operator<< (ostream& out, NNDataSetEnums::Kind& k);
ostream& operator<< (ostream& out, NNDataSetEnums::DataType& t);
ostream& operator<< (ostream& out, NNDataSetEnums::Sharding& s);
template<typename T> class NNDataSet : public NNDataSetBase {
public:
friend class NNetwork;
friend class NNLayer;
friend vector<NNDataSetBase*> LoadNetCDF(const string& fname);
friend bool SaveNetCDF(const string& fname, vector<NNDataSetBase*> vDataSet);
private:
// Type-specific data
vector<T> _vData;
unique_ptr<GpuBuffer<T>> _pbData;
vector<T> _vSparseData;
unique_ptr<GpuBuffer<T>> _pbSparseData;
// Force constructor private
NNDataSet(const string& fname, uint32_t n);
bool Rename(const string& name);
bool SaveNetCDF(const string& fname);
bool WriteNetCDF(netCDF::NcFile& nfc, const string& fname, const uint32_t n);
void RefreshState(uint32_t batch) {}
bool Shard(NNDataSetEnums::Sharding sharding);
bool UnShard();
vector<tuple<uint64_t, uint64_t> > getMemoryUsage();
bool CalculateSparseDatapointCounts();
bool GenerateSparseTransposedMatrix(uint32_t batch, NNLayer* pLayer);
bool CalculateSparseTransposedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer);
bool CalculateSparseTransposedDenoisedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer);
bool CalculateSparseTransposedWeightGradient(NNFloat alpha, NNFloat beta, uint32_t m, uint32_t n, NNFloat* pDelta, NNFloat* pWeightGradient);
bool SetStreaming(bool flag);
bool GetStreaming();
bool SetDenoising(bool flag);
bool GenerateDenoisingData();
bool LoadInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
bool LoadSparseInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
bool LoadSparseDenoisedInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
bool CalculateSparseZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta);
bool CalculateSparseDenoisedZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta);
float CalculateL1Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateL2Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateL2HingeError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateMultinomialCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateMultinomialScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateDataScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateHingeError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
bool CalculateL1OutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta, NNFloat slope, NNFloat alpha, NNFloat lambda);
bool CalculateCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta);
bool CalculateScaledMarginalCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta);
bool CalculateOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta, NNFloat slope, NNFloat alpha, NNFloat lambda);
bool CalculateL2HingeOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta, NNFloat slope, NNFloat alpha, NNFloat lambda);
bool CalculateDataScaledMarginalCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta);
bool CalculateHingeOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta);
public:
/**
* Creates dense dataset with the specified dimensions and name
* with space allocated for the specified number of examples
*/
NNDataSet(uint32_t examples, const NNDataSetDimensions &dim, const string &name = "");
/**
* Creates dense indexed dataset with the specified dimensions and name
* with space allocated for the specified number of examples
* and index data space allocated for the specified number of uniqueExamples.
*/
NNDataSet(uint32_t examples, uint32_t uniqueExamples, const NNDataSetDimensions &dim, const string &name = "");
/**
* Creates sparse dataset for the layer with space allocated
* for the specified number of examples. The isWeighted parameter
* can be set to true to create a sparse weighted dataset.
*/
NNDataSet(uint32_t examples, NNFloat sparseDensity, const NNDataSetDimensions &dim, bool isWeighted = false, const string &name = "");
/**
* Creates a sparse dataset with the specified dimensions
* and name with space allocated for the specified number of
* examples and index data (if isIndexed).
* The isIndexed and isWeighted parameters can be set to
* create a sparse indexed, weighted dataset.
*/
NNDataSet(uint32_t examples, uint32_t uniqueExamples, size_t sparseDataSize, const NNDataSetDimensions &dim,
bool isIndexed = false, bool isWeighted = false, const string &name = "");
void LoadDenseData(const void *srcData) override;
void CopyDenseData(const void *srcData) override;
void LoadSparseData(const uint64_t *srcSparseStart, const uint64_t *srcSparseEnd, const void *srcSparseData,
const uint32_t *srcSparseIndex) override;
void CopySparseData(const uint64_t *srcSparseStart, const uint64_t *srcSparseEnd, const void *srcSparseData,
const uint32_t *srcSparseIndex) override;
void LoadSparseData(const long *srcSparseStart, const long *srcSparseEnd, const void *srcSparseData,
const long *srcSparseIndex) override;
void CopySparseData(const long *srcSparseStart, const long *srcSparseEnd, const void *srcSparseData,
const long *srcSparseIndex) override;
void LoadIndexedData(const uint32_t *srcIndexedData) override;
void LoadDataWeight(const NNFloat *srcWeightData) override;
~NNDataSet();
void Shuffle();
T GetDataPoint(uint32_t n, uint32_t x, uint32_t y = 0, uint32_t z = 0);
bool SetDataPoint(T v, uint32_t n, uint32_t x, uint32_t y = 0, uint32_t z = 0);
uint64_t GetSparseDataPoints(uint32_t n);
uint32_t GetSparseIndex(uint32_t n, uint32_t i);
bool SetSparseIndex(uint32_t n, uint32_t i, uint32_t v);
T GetSparseDataPoint(uint32_t n, uint32_t i);
bool SetSparseDataPoint(uint32_t n, uint32_t i, T v);
};
template<typename T> bool NNDataSet<T>::LoadInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
if (_attributes & NNDataSetEnums::Indexed)
kLoadIndexedInputUnit(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbData->_pDevData);
else
kLoadInputUnit(position, batch, stride, pUnit, _pbData->_pDevData);
return true;
}
template<typename T> bool NNDataSet<T>::LoadSparseInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
kLoadIndexedSparseInputUnit(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight);
else
kLoadSparseInputUnit(position, batch, stride, pUnit, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight);
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kLoadIndexedSparseAnalogInputUnit(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData);
else
kLoadSparseAnalogInputUnit(position, batch, stride, pUnit, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData);
}
return true;
}
template<typename T> bool NNDataSet<T>::LoadSparseDenoisedInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
kLoadIndexedSparseDenoisedInputUnit(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbDenoisingRandom->_pDevData);
else
kLoadSparseDenoisedInputUnit(position, batch, stride, pUnit, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbDenoisingRandom->_pDevData);
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kLoadIndexedSparseAnalogDenoisedInputUnit(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, _pbDenoisingRandom->_pDevData);
else
kLoadSparseAnalogDenoisedInputUnit(position, batch, stride, pUnit, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, _pbDenoisingRandom->_pDevData);
}
return true;
}
template<typename T> bool NNDataSet<T>::CalculateSparseZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseZ(position, batch, stride, pWeight, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, pUnit, beta);
else
kCalculateSparseZ(position, batch, stride, pWeight, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, pUnit, beta);
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseAnalogZ(position, batch, stride, pWeight, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, pUnit, beta);
else
kCalculateSparseAnalogZ(position, batch, stride, pWeight, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, pUnit, beta);
}
return true;
}
template<typename T> bool NNDataSet<T>::CalculateSparseDenoisedZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseDenoisedZ(position, batch, stride, pWeight, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbDenoisingRandom->_pDevData, pUnit, beta);
else
kCalculateSparseDenoisedZ(position, batch, stride, pWeight, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbDenoisingRandom->_pDevData, pUnit, beta);
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseAnalogDenoisedZ(position, batch, stride, pWeight, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, _pbDenoisingRandom->_pDevData, pUnit, beta);
else
kCalculateSparseAnalogDenoisedZ(position, batch, stride, pWeight, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, _pbDenoisingRandom->_pDevData, pUnit, beta);
}
return true;
}
template<typename T> bool NNDataSet<T>::CalculateSparseTransposedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer)
{
// Rebuild sparse data table if dataset changed
if (_bDirty || (batch != _batch))
{
GenerateSparseTransposedMatrix(batch, pLayer);
}
// Initialize transposed sparse offsets
_pbSparseTransposedEnd->Copy(_pbSparseTransposedStart->_pDevData);
// Call appropriate matrix generation kernel
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
NNFloat* pSparseTransposedData = ((_attributes & NNDataSetEnums::Weighted) || !(_attributes & NNDataSetEnums::Boolean)) ? _pbSparseTransposedData->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseTransposedMatrix(position, batch, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, pSparseTransposedData);
else
kCalculateSparseTransposedMatrix(position, batch, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, pSparseTransposedData);
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseTransposedAnalogMatrix(position, batch, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, pSparseTransposedData);
else
kCalculateSparseTransposedAnalogMatrix(position, batch, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, pSparseTransposedData);
}
return true;
}
template<typename T> bool NNDataSet<T>::CalculateSparseTransposedDenoisedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer)
{
// Rebuild sparse data table if dataset changed
if (_bDirty || (batch != _batch))
{
GenerateSparseTransposedMatrix(batch, pLayer);
}
// Initialize transposed sparse offsets
_pbSparseTransposedEnd->Copy(_pbSparseTransposedStart->_pDevData);
// Call appropriate matrix generation kernel
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
NNFloat* pSparseTransposedData = ((_attributes & NNDataSetEnums::Weighted) || !(_attributes & NNDataSetEnums::Boolean)) ? _pbSparseTransposedData->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseTransposedDenoisedMatrix(position, batch, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbDenoisingRandom->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, pSparseTransposedData);
else
kCalculateSparseTransposedDenoisedMatrix(position, batch, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbDenoisingRandom->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, pSparseTransposedData);
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseTransposedAnalogDenoisedMatrix(position, batch, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, _pbDenoisingRandom->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, pSparseTransposedData);
else
kCalculateSparseTransposedAnalogDenoisedMatrix(position, batch, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, _pbDenoisingRandom->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, pSparseTransposedData);
}
#if 0
vector<uint32_t> vSparseTransposedStart(53120);
vector<uint32_t> vSparseTransposedEnd(53120);
_pbSparseTransposedStart->Download(&vSparseTransposedStart[0]);
_pbSparseTransposedEnd->Download(&vSparseTransposedEnd[0]);
for (uint32_t i = 0; i < 53120; i++)
printf("%6u %9u %9u %9u %9u\n", i, vSparseTransposedStart[i], vSparseTransposedEnd[i], vSparseTransposedEnd[i] - vSparseTransposedStart[i], (uint32_t)_vSparseDatapointCount[i]);
exit(-1);
#endif
return true;
}
template<typename T> bool NNDataSet<T>::CalculateSparseTransposedWeightGradient(NNFloat alpha, NNFloat beta, uint32_t m, uint32_t n, NNFloat* pDelta, NNFloat* pWeightGradient)
{
if ((_attributes & NNDataSetEnums::Boolean) && !(_attributes & NNDataSetEnums::Weighted))
kCalculateSparseTransposedWeightGradient(alpha, beta, m, n, _pbSparseTransposedStart->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, pDelta, pWeightGradient);
else
kCalculateSparseTransposedAnalogWeightGradient(alpha, beta, m, n, _pbSparseTransposedStart->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, _pbSparseTransposedData->_pDevData, pDelta, pWeightGradient);
return true;
}
template<typename T> float NNDataSet<T>::CalculateL1Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseL1Error(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
bSparseIgnoreZero);
}
else
{
return kCalculateSparseL1Error(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
bSparseIgnoreZero);
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseAnalogL1Error(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
_pbSparseData->_pDevData,
bSparseIgnoreZero);
}
else
{
return kCalculateSparseAnalogL1Error(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
_pbSparseData->_pDevData,
bSparseIgnoreZero);
}
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
return kCalculateIndexedL1Error(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight);
else
return kCalculateL1Error(position, batch, stride, pUnit, _pbData->_pDevData, pDataWeight);
}
}
template<typename T> float NNDataSet<T>::CalculateL2Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseL2Error(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
bSparseIgnoreZero);
}
else
{
return kCalculateSparseL2Error(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
bSparseIgnoreZero);
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseAnalogL2Error(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
_pbSparseData->_pDevData,
bSparseIgnoreZero);
}
else
{
return kCalculateSparseAnalogL2Error(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
_pbSparseData->_pDevData,
bSparseIgnoreZero);
}
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
return kCalculateIndexedL2Error(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight);
else
return kCalculateL2Error(position, batch, stride, pUnit, _pbData->_pDevData, pDataWeight);
}
}
template<typename T> float NNDataSet<T>::CalculateL2HingeError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseL2HingeError(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
bSparseIgnoreZero);
}
else
{
return kCalculateSparseL2HingeError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
bSparseIgnoreZero);
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseAnalogL2HingeError(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
_pbSparseData->_pDevData,
bSparseIgnoreZero);
}
else
{
return kCalculateSparseAnalogL2HingeError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
_pbSparseData->_pDevData,
bSparseIgnoreZero);
}
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
return kCalculateIndexedL2HingeError(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight);
else
return kCalculateL2HingeError(position, batch, stride, pUnit, _pbData->_pDevData, pDataWeight);
}
}
template<typename T> float NNDataSet<T>::CalculateCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseCrossEntropyError(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
bSparseIgnoreZero);
}
else
{
return kCalculateSparseCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
bSparseIgnoreZero);
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
return kCalculateIndexedCrossEntropyError(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight);
else
return kCalculateCrossEntropyError(position, batch, stride, pUnit, _pbData->_pDevData, pDataWeight);
}
}
template<typename T> float NNDataSet<T>::CalculateScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
bSparseIgnoreZero);
}
else
{
return kCalculateSparseScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
bSparseIgnoreZero);
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
return kCalculateIndexedScaledMarginalCrossEntropyError(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight);
else
return kCalculateScaledMarginalCrossEntropyError(position, batch, stride, pUnit, _pbData->_pDevData, pDataWeight);
}
}
template<typename T> float NNDataSet<T>::CalculateMultinomialCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse)
{
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseMultinomialCrossEntropyError(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight);
}
else
{
return kCalculateSparseMultinomialCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight);
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseAnalogMultinomialCrossEntropyError(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
_pbSparseData->_pDevData);
}
else
{
return kCalculateSparseAnalogMultinomialCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
_pbSparseData->_pDevData);
}
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
return kCalculateIndexedMultinomialCrossEntropyError(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight);
else
return kCalculateMultinomialCrossEntropyError(position, batch, stride, pUnit, _pbData->_pDevData, pDataWeight);
}
}
template<typename T> float NNDataSet<T>::CalculateMultinomialScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse)
{
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseMultinomialScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight);
}
else
{
return kCalculateSparseMultinomialScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight);
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseAnalogMultinomialScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
_pbSparseData->_pDevData);
}
else
{
return kCalculateSparseAnalogMultinomialScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
_pbSparseData->_pDevData);
}
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
return kCalculateIndexedMultinomialScaledMarginalCrossEntropyError(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight);
else
return kCalculateMultinomialScaledMarginalCrossEntropyError(position, batch, stride, pUnit, _pbData->_pDevData, pDataWeight);
}
}
template<typename T> float NNDataSet<T>::CalculateDataScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
// Scale by 1 if data is Boolean
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
bSparseIgnoreZero);
}
else
{
return kCalculateSparseScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
pDataWeight,
bSparseIgnoreZero);
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
{
return kCalculateIndexedSparseDataScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbIndex->_pDevData,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
_pbSparseData->_pDevData, bSparseIgnoreZero);
}
else
{
return kCalculateSparseDataScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData,
_pbSparseData->_pDevData, bSparseIgnoreZero);
}
}
}
else
{
// BUG BUG BUG unacceptable behavior, this should be caught at startup
cout << "unsupported data format of this cost function" << endl;
getGpu().Shutdown();
exit(-1);
}
}
template<typename T> float NNDataSet<T>::CalculateHingeError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Indexed)
return kCalculateIndexedHingeError(position, batch, stride, pUnit, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight);
else
return kCalculateHingeError(position, batch, stride, pUnit, _pbData->_pDevData, pDataWeight);
}
template<typename T> bool NNDataSet<T>::CalculateL1OutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta, NNFloat slope, NNFloat alpha, NNFloat lambda)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseL1OutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, bSparseIgnoreZero, slope, alpha, lambda);
else
kCalculateSparseL1OutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, bSparseIgnoreZero, slope, alpha, lambda);
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedL1OutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight, slope, alpha, lambda);
else
kCalculateL1OutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData, pDataWeight, slope, alpha, lambda);
}
return true;
}
template<typename T> bool NNDataSet<T>::CalculateCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, bSparseIgnoreZero);
else
kCalculateSparseCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, bSparseIgnoreZero);
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight);
else
kCalculateCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData, pDataWeight);
}
return true;
}
template<typename T> bool NNDataSet<T>::CalculateScaledMarginalCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseScaledMarginalCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, bSparseIgnoreZero);
else
kCalculateSparseScaledMarginalCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, bSparseIgnoreZero);
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedScaledMarginalCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight);
else
kCalculateScaledMarginalCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData, pDataWeight);
}
return true;
}
template<typename T> bool NNDataSet<T>::CalculateOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta, NNFloat slope, NNFloat alpha, NNFloat lambda)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse) {
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, bSparseIgnoreZero, slope, alpha, lambda);
else
kCalculateSparseOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, bSparseIgnoreZero, slope, alpha, lambda);
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseAnalogOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, bSparseIgnoreZero, slope, alpha, lambda);
else
kCalculateSparseAnalogOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, bSparseIgnoreZero, slope, alpha, lambda);
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight, slope, alpha, lambda);
else
kCalculateOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData, pDataWeight, slope, alpha, lambda);
}
return true;
}
template<typename T> bool NNDataSet<T>::CalculateL2HingeOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta, NNFloat slope, NNFloat alpha, NNFloat lambda)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Sparse) {
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Boolean)
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseL2HingeOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, bSparseIgnoreZero, slope, alpha, lambda);
else
kCalculateSparseL2HingeOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, bSparseIgnoreZero, slope, alpha, lambda);
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedSparseAnalogL2HingeOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, bSparseIgnoreZero, slope, alpha, lambda);
else
kCalculateSparseAnalogL2HingeOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pDataWeight, _pbSparseData->_pDevData, bSparseIgnoreZero, slope, alpha, lambda);
}
}
else
{
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedL2HingeOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight, slope, alpha, lambda);
else
kCalculateL2HingeOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData, pDataWeight, slope, alpha, lambda);
}
return true;
}
template<typename T> bool NNDataSet<T>::CalculateDataScaledMarginalCrossEntropyOutputDelta(Activation activation,
uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta)
{
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Indexed)
{
kCalculateIndexedSparseDataScaledMarginalCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta,
_pbIndex->_pDevData, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData,
_pbSparseData->_pDevData, bSparseIgnoreZero);
}
else
{
kCalculateSparseDataScaledMarginalCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta,
_pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData,
_pbSparseData->_pDevData, bSparseIgnoreZero);
}
}
else
{
cout << "unsupported data format of this cost function" << endl;
getGpu().Shutdown();
exit(-1);
}
return true;
}
template<typename T> bool NNDataSet<T>::CalculateHingeOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta)
{
NNFloat* pDataWeight = (_attributes & NNDataSetEnums::Weighted) ? _pbDataWeight->_pDevData : NULL;
if (_attributes & NNDataSetEnums::Indexed)
kCalculateIndexedHingeOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbIndex->_pDevData, _pbData->_pDevData, pDataWeight);
else
kCalculateHingeOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData, pDataWeight);
return true;
}
vector<NNDataSetBase*> LoadNetCDF(const string& fname);
bool SaveNetCDF(const string& fname, vector<NNDataSetBase*> vDataset);
vector<NNDataSetBase*> LoadImageData(const string& fname);
vector<NNDataSetBase*> LoadCSVData(const string& fname);
vector<NNDataSetBase*> LoadJSONData(const string& fname);
vector<NNDataSetBase*> LoadAudioData(const string& name);
#endif
| {
"alphanum_fraction": 0.6668535826,
"avg_line_length": 50.9119746233,
"ext": "h",
"hexsha": "4d94a6b87195169386afd3bf775fd5ff34f364fb",
"lang": "C",
"max_forks_count": 633,
"max_forks_repo_forks_event_max_datetime": "2017-05-02T11:33:50.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-05-10T23:07:33.000Z",
"max_forks_repo_head_hexsha": "f64044d1e467333d0c9bb0643f0edf75328c503b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "saminfante/amazon-dsstne",
"max_forks_repo_path": "src/amazon/dsstne/engine/NNTypes.h",
"max_issues_count": 88,
"max_issues_repo_head_hexsha": "f64044d1e467333d0c9bb0643f0edf75328c503b",
"max_issues_repo_issues_event_max_datetime": "2017-04-24T02:34:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-05-11T05:11:45.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "saminfante/amazon-dsstne",
"max_issues_repo_path": "src/amazon/dsstne/engine/NNTypes.h",
"max_line_length": 350,
"max_stars_count": 3924,
"max_stars_repo_head_hexsha": "f64044d1e467333d0c9bb0643f0edf75328c503b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "farruhnet/AmazonDeepEngine",
"max_stars_repo_path": "src/amazon/dsstne/engine/NNTypes.h",
"max_stars_repo_stars_event_max_datetime": "2017-05-02T17:54:20.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-05-10T22:40:39.000Z",
"num_tokens": 15668,
"size": 64200
} |
/* ----------------------------------------------------------------------------
JAM_AXI_VEL_WMMT
Calculates weighted first moments.
INPUTS
xp : projected x' [pc]
yp : projected y' [pc]
nxy : number of x' and y' values given
incl : inclination [radians]
lum : projected luminous MGE
pot : projected potential MGE
beta : velocity anisotropy (1 - vz^2 / vr^2)
kappa : rotation parameter
NOTES
* Based on janis1_weighted_first_moment IDL code by Michele Cappellari.
Laura L Watkins [lauralwatkins@gmail.com]
This code is released under a BSD 2-clause license.
If you use this code for your research, please cite:
Watkins et al. 2013, MNRAS, 436, 2598
"Discrete dynamical models of omega Centauri"
http://adsabs.harvard.edu/abs/2013MNRAS.436.2598W
---------------------------------------------------------------------------- */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include "jam.h"
#include "../mge/mge.h"
#include "../tools/tools.h"
double** jam_axi_vel_wmmt( double *xp, double *yp, int nxy, double incl, \
struct multigaussexp *lum, struct multigaussexp *pot, \
double *beta, double *kappa, int *gslFlag_vel ) {
struct params_losint lp;
struct multigaussexp ilum, ipot;
double *bani, *s2l, *q2l, *s2q2l, *s2p, *e2p;
double *iz0, *iz1;
double lim, result, error, si, ci, trpig, **sb_mu1;
int i;
size_t neval;
int status = 0, *gslFlag;
int TadejaVar = 0; gslFlag = &TadejaVar;
// ---------------------------------
// MGE parameters for inner integrand function
// convert from projected MGEs to intrinsic MGEs
ilum = mge_deproject( lum, incl );
ipot = mge_deproject( pot, incl );
// calculate useful quantities
bani = (double *) malloc( ilum.ntotal * sizeof( double ) );
s2l = (double *) malloc( ilum.ntotal * sizeof( double ) );
q2l = (double *) malloc( ilum.ntotal * sizeof( double ) );
s2q2l = (double *) malloc( ilum.ntotal * sizeof( double ) );
s2p = (double *) malloc( ipot.ntotal * sizeof( double ) );
e2p = (double *) malloc( ipot.ntotal * sizeof( double ) );
for ( i = 0; i < ilum.ntotal; i++ ) {
bani[i] = 1. / ( 1. - beta[i] );
s2l[i] = pow( ilum.sigma[i], 2 );
q2l[i] = pow( ilum.q[i], 2 );
s2q2l[i] = s2l[i] * q2l[i];
}
for ( i = 0; i < ipot.ntotal; i++ ) {
s2p[i] = pow( ipot.sigma[i], 2 );
e2p[i] = 1. - pow( ipot.q[i], 2 );
}
// parameters for integrand function
lp.incl = incl;
lp.lum = &ilum;
lp.pot = &ipot;
lp.bani = bani;
lp.s2l = s2l;
lp.q2l = q2l;
lp.s2q2l = s2q2l;
lp.s2p = s2p;
lp.e2p = e2p;
lp.kappa = kappa;
lp.gslFlag_losint = gslFlag;
// ---------------------------------
// set up integration
gsl_integration_workspace *w = gsl_integration_workspace_alloc( 1000 );
gsl_integration_cquad_workspace *ww = gsl_integration_cquad_workspace_alloc(1000);
gsl_function F;
F.function = &jam_axi_vel_losint;
// trig angles
si = sin( incl );
ci = cos( incl );
// outer limit of integration
lim = 4. * maximum( ilum.sigma, ilum.ntotal );
iz0 = (double *) malloc( nxy * sizeof( double ) );
iz1 = (double *) malloc( nxy * sizeof( double ) );
for ( i = 0; i < nxy; i++ ) {
// parameters for integrand function
lp.xp = xp[i];
lp.yp = yp[i];
// do z^0 integral
lp.zpow = 0.;
F.function = &jam_axi_vel_losint;
F.params = &lp;
gsl_integration_cquad(&F, -lim, lim, 0., 1e-4, ww, &result,
&error, &neval);
iz0[i] = result;
// do z^1 integral
lp.zpow = 1.;
F.function = &jam_axi_vel_losint;
F.params = &lp;
gsl_set_error_handler_off();
status += gsl_integration_qag( &F, -lim, lim, 1., 1., 1000, 2, w,
&result, &error );
/* uncomment these two lines for testing
int test = 1;// Tadeja
status += test; // Tadeja
*/
if (status > 0 && *gslFlag<20) { // the limiting value is very arbitrary
*gslFlag_vel += 1; }
if (status > 0 && *gslFlag>=20) { // the limiting value is very arbitrary so that the values do not exceed allowed size for integers
*gslFlag_vel -= 1; }
*gslFlag_vel += *gslFlag; // if there was an integration error in losint
if ( fabs( result ) > 1e-6 ) {
gsl_integration_cquad(&F, -lim, lim, 0., 1e-3, ww, &result,
&error, &neval);
}
iz1[i] = result;
}
// tidy up
gsl_integration_workspace_free( w );
gsl_integration_cquad_workspace_free(ww);
// ---------------------------------
sb_mu1 = (double **) malloc( nxy * sizeof( double* ) );
for ( i = 0; i < nxy; i++ ) \
sb_mu1[i] = (double *) malloc( 3 * sizeof( double ) );
// calculate for each velocity component
trpig = 2. * sqrt( M_PI * G );
for ( i = 0; i < nxy; i++ ) {
sb_mu1[i][0] = trpig * ( yp[i] * ci * iz0[i] - si * iz1[i] );
sb_mu1[i][1] = -trpig * xp[i] * ci * iz0[i];
sb_mu1[i][2] = trpig * xp[i] * si * iz0[i];
}
// ---------------------------------
free( bani );
free( s2l );
free( q2l );
free( s2q2l );
free( s2p );
free( e2p );
free( iz0 );
free( iz1 );
return sb_mu1;
}
| {
"alphanum_fraction": 0.521024735,
"avg_line_length": 31.0989010989,
"ext": "c",
"hexsha": "9c3f175ada10b110e4df101e405dac262bbb4ef7",
"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": "392486d328521415386f1ccaf3a140438223f00f",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "tadejaversic/cjam",
"max_forks_repo_path": "src/jam/jam_axi_vel_wmmt.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "392486d328521415386f1ccaf3a140438223f00f",
"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": "tadejaversic/cjam",
"max_issues_repo_path": "src/jam/jam_axi_vel_wmmt.c",
"max_line_length": 140,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "392486d328521415386f1ccaf3a140438223f00f",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "tadejaversic/cjam",
"max_stars_repo_path": "src/jam/jam_axi_vel_wmmt.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1763,
"size": 5660
} |
#pragma once
/*
* (C) Copyright 2020-2021 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
/*! \defgroup ioda_cxx_attribute Attributes and Has_Attributes
* \brief Ancillary data attached to variables and groups.
* \ingroup ioda_cxx_api
*
* @{
* \file Attribute.h
* \brief @link ioda_cxx_attribute Interfaces @endlink for ioda::Attribute and related classes.
*/
#include <functional>
#include <gsl/gsl-lite.hpp>
#include <iostream>
#include <memory>
#include <string>
#include <valarray>
#include <vector>
#include "ioda/Exception.h"
#include "ioda/Misc/Dimensions.h"
#include "ioda/Misc/Eigen_Compat.h"
#include "ioda/Python/Att_ext.h"
#include "ioda/Types/Marshalling.h"
#include "ioda/Types/Type.h"
#include "ioda/Types/Type_Provider.h"
#include "ioda/defs.h"
namespace ioda {
class Attribute;
namespace detail {
class Attribute_Backend;
class Variable_Backend;
/// \brief Base class for Attributes
/// \ingroup ioda_cxx_attribute
///
/// \details You might wonder why we have this class
/// as a template. This is because we are using
/// a bit of compile-time template polymorphism to return
/// Attribute objects from base classes before Attribute is fully declared.
/// This is a variation of the (Curiously Recurring Template
/// Pattern)[https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern].
template <class Attribute_Implementation = Attribute>
class Attribute_Base {
protected:
/// Using an opaque object to implement the backend.
std::shared_ptr<Attribute_Backend> backend_;
// Variable_Backend's derived classes do occasionally need access to the Attribute_Backend object.
friend class Variable_Backend;
/// @name General Functions
/// @{
Attribute_Base(std::shared_ptr<Attribute_Backend>);
public:
virtual ~Attribute_Base();
/// @}
/// @name Writing Data
/// \note Writing metadata is an all-or-nothing-process, unlike writing
/// segments of data to a variable.
/// \note Dimensions are fixed. Attribute are not resizable.
/// @{
///
/// \brief The fundamental write function. Backends overload this function to implement all write
/// operations.
///
/// \details This function writes a span of bytes (characters) to the backend attribute storage.
/// No type conversions take place here (see the templated conversion function, below).
///
/// \param data is a span of data.
/// \param in_memory_datatype is an opaque (backend-level) object that describes the placement of
/// the data in memory. Usually ignorable - needed for complex data structures.
/// \throws ioda::Exception if data has the wrong size.
/// \returns The attribute (for chaining).
virtual Attribute_Implementation write(gsl::span<const char> data, const Type& type);
/// \brief Write data.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \tparam Marshaller is the class that serializes the data type into something that the backend
/// library can use.
/// \tparam TypeWrapper is a helper class that creates Type objects for the backend.
/// \param data is a gsl::span (a pointer-length pair) that contains the data to be written.
/// \param in_memory_dataType is the memory layout needed to parse data's type.
/// \returns Another instance of this Attribute. Used for operation chaining.
/// \throws ioda::Exception if data.size() does not match getDimensions().numElements.
/// \see gsl::span for details of how to make a span.
/// \see gsl::make_span
template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,
class TypeWrapper = Types::GetType_Wrapper<DataType>>
Attribute_Implementation write(gsl::span<const DataType> data) {
try {
Marshaller m;
auto d = m.serialize(data);
auto spn = gsl::make_span<const char>(reinterpret_cast<const char*>(d->DataPointers.data()),
d->DataPointers.size() * Marshaller::bytesPerElement_);
write(spn, TypeWrapper::GetType(getTypeProvider()));
return Attribute_Implementation{backend_};
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
}
/// \brief Write data
/// \note Normally the gsl::span write is fine. This one exists for easy Python binding.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \tparam Marshaller is the class that serializes the data type into something that the backend
/// library can use.
/// \tparam TypeWrapper is a helper class that creates Type objects for the backend.
/// \param data is a std::vector that contains the data to be written.
/// \param in_memory_dataType is the memory layout needed to parse data's type.
/// \returns Another instance of this Attribute. Used for operation chaining.
/// \throws ioda::Exception if data.size() does not match getDimensions().numElements.
/// \see gsl::span for details of how to make a span.
/// \see gsl::make_span for details on how to make a span.
template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,
class TypeWrapper = Types::GetType_Wrapper<DataType>>
Attribute_Implementation write(const std::vector<DataType>& data) {
std::vector<DataType> vd = data;
return this->write<DataType, Marshaller, TypeWrapper>(gsl::make_span(vd));
}
/// \brief Write data.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param data is an initializer list that contains the data to be written.
/// \param in_memory_dataType is the memory layout needed to parse data's type.
/// \returns Another instance of this Attribute. Used for operation chaining.
/// \throws ioda::Exception if data.size() does not match getDimensions().numElements.
/// \see gsl::span for details of how to make a span.
template <class DataType>
Attribute_Implementation write(std::initializer_list<DataType> data) {
std::vector<DataType> v(data);
return this->write<DataType>(gsl::make_span(v));
}
/// \brief Write a datum.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param data is the data to be written.
/// \returns Another instance of this Attribute. Used for operation chaining.
/// \throws ioda::Exception if the Attribute dimensions are larger than a single point.
template <class DataType> //, class Marshaller = HH::Types::Object_Accessor<DataType> >
Attribute_Implementation write(DataType data) {
try {
if (getDimensions().numElements != 1)
throw Exception("Wrong number of elements. Use a different write() method.", ioda_Here());
return write<DataType>(gsl::make_span<DataType>(&data, 1));
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
}
/// \brief Write an Eigen object (a Matrix, an Array, a Block, a Map).
/// \tparam EigenClass is the Eigen object to write.
/// \param d is the data to be written.
/// \throws ioda::Exception on a dimension mismatch.
/// \returns the attribute
template <class EigenClass>
Attribute_Implementation writeWithEigenRegular(const EigenClass& d) {
#if 1 //__has_include("Eigen/Dense")
try {
typedef typename EigenClass::Scalar ScalarType;
// If d is already in Row Major form, then this is optimized out.
Eigen::Array<ScalarType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> dout;
dout.resize(d.rows(), d.cols());
dout = d;
const auto& dconst = dout; // To make some compilers happy.
auto sp = gsl::make_span(dconst.data(), static_cast<int>(d.rows() * d.cols()));
return write<ScalarType>(sp);
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
#else
static_assert(false, "The Eigen headers cannot be found, so this function cannot be used.");
#endif
}
/// \brief Write an Eigen Tensor-like object
/// \tparam EigenClass is the Eigen tensor to write.
/// \param d is the data to be written.
/// \throws ioda::Exception on a dimension mismatch.
/// \returns the attribute
template <class EigenClass>
Attribute_Implementation writeWithEigenTensor(const EigenClass& d) {
#if 1 //__has_include("unsupported/Eigen/CXX11/Tensor")
try {
ioda::Dimensions dims = detail::EigenCompat::getTensorDimensions(d);
auto sp = (gsl::make_span(d.data(), dims.numElements));
auto res = write(sp);
return res;
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
#else
static_assert(
false, "The Eigen unsupported/ headers cannot be found, so this function cannot be used.");
#endif
}
/// @}
/// @name Reading Data
/// @{
///
/// \brief The fundamental read function. Backends overload this function to implement all read
/// operations.
///
/// \details This function reads in a span of characters from the backend attribute storage.
/// No type conversions take place here (see the templated conversion function, below).
///
/// \param data is a span of data that has length of getStorageSize().
/// \param in_memory_datatype is an opaque (backend-level) object that describes the placement of
/// the data in memory. Usually ignorable - needed for complex data structures.
/// \throws ioda::Exception if data has the wrong size.
/// \returns The attribute (for chaining).
virtual Attribute_Implementation read(gsl::span<char> data, const Type& in_memory_dataType) const;
/// \brief Read data.
///
/// \details This is a fundamental function that reads a span of characters from backend storage,
/// and then performs the appropriate type conversion / deserialization into objects in data.
///
/// \tparam DataType is the type if the data to be read. I.e. float, int, int32_t, uint16_t,
/// std::string, etc.
/// \tparam Marshaller is the class that performs the deserialization operation.
/// \tparam TypeWrapper is a helper class that passes Type information to the backend.
/// \param data is a pointer-size pair to the data buffer that is filled with the metadata's
/// contents. It should be
/// pre-sized to accomodate all of the matadata. See getDimensions().numElements. data will be
/// filled in row-major order.
/// \param in_memory_datatype is an opaque (backend-level) object that describes the placement of
/// the data in memory. Usually this does not need to be set to anything other than its default
/// value. Kept as a parameter for debugging purposes.
/// \returns Another instance of this Attribute. Used for operation chaining.
/// \throws ioda::Exception if data.size() != getDimensions().numElements.
/// \see getDimensions for buffer size information.
template <class DataType, class Marshaller = ioda::Object_Accessor<DataType>,
class TypeWrapper = Types::GetType_Wrapper<DataType>>
Attribute_Implementation read(gsl::span<DataType> data) const {
try {
const size_t numObjects = data.size();
if (getDimensions().numElements != gsl::narrow<ioda::Dimensions_t>(numObjects))
throw Exception("Size mismatch between underlying object and user-provided data range.",
ioda_Here());
detail::PointerOwner pointerOwner = getTypeProvider()->getReturnedPointerOwner();
Marshaller m(pointerOwner);
auto p = m.prep_deserialize(numObjects);
read(gsl::make_span<char>(reinterpret_cast<char*>(p->DataPointers.data()),
p->DataPointers.size() * Marshaller::bytesPerElement_),
TypeWrapper::GetType(getTypeProvider()));
m.deserialize(p, data);
return Attribute_Implementation{backend_};
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
}
/// \brief Vector read convenience function.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param data is a vector acting as a data buffer that is filled with the metadata's contents.
/// It gets resized as needed.
/// \returns Another instance of this Attribute. Used for operation chaining.
/// \note data will be stored in row-major order.
template <class DataType>
Attribute_Implementation read(std::vector<DataType>& data) const {
data.resize(getDimensions().numElements);
return read<DataType>(gsl::make_span<DataType>(data.data(), data.size()));
}
/// \brief Valarray read convenience function.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param data is a valarray acting as a data buffer that is filled with the metadata's contents.
/// It gets resized as needed.
/// \returns Another instance of this Attribute. Used for operation chaining.
/// \note data will be stored in row-major order.
template <class DataType>
Attribute_Implementation read(std::valarray<DataType>& data) const {
data.resize(getDimensions().numElements);
return read<DataType>(gsl::make_span<DataType>(std::begin(data), std::end(data)));
}
/// \brief Read into a single value (convenience function).
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \param data is where the datum is read to.
/// \returns Another instance of this Attribute. Used for operation chaining.
/// \throws ioda::Exception if the underlying data have multiple elements.
template <class DataType>
Attribute_Implementation read(DataType& data) const {
try {
if (getDimensions().numElements != 1)
throw Exception("Wrong number of elements. Use a different read() method.", ioda_Here());
return read<DataType>(gsl::make_span<DataType>(&data, 1));
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
}
/// \brief Read a single value (convenience function).
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \returns A datum of type DataType.
/// \throws ioda::Exception if the underlying data have size greater than 1.
/// \note The Python function is read_datum_*
template <class DataType>
DataType read() const {
DataType ret;
read<DataType>(ret);
return ret;
}
/// \brief Read into a new vector. Python convenience function.
/// \tparam DataType is the type of the data.
/// \note The Python function is read_list_*
template <class DataType>
std::vector<DataType> readAsVector() const {
std::vector<DataType> data(getDimensions().numElements);
read<DataType>(gsl::make_span<DataType>(data.data(), data.size()));
return data;
}
/// \brief Read data into an Eigen::Array, Eigen::Matrix, Eigen::Map, etc.
/// \tparam EigenClass is a template pointing to the Eigen object.
/// This template must provide the EigenClass::Scalar typedef.
/// \tparam Resize indicates whether the Eigen object should be resized
/// if there is a dimension mismatch. Not all Eigen objects can be resized.
/// \param res is the Eigen object.
/// \returns Another instance of this Attribute. Used for operation chaining.
/// \throws ioda::Exception if the attribute's dimensionality is
/// too high.
/// \throws ioda::Exception if resize = false and there is a dimension mismatch.
/// \note When reading in a 1-D object, the data are read as a column vector.
template <class EigenClass, bool Resize = detail::EigenCompat::CanResize<EigenClass>::value>
Attribute_Implementation readWithEigenRegular(EigenClass& res) const {
#if 1 //__has_include("Eigen/Dense")
try {
typedef typename EigenClass::Scalar ScalarType;
static_assert(
!(Resize && !detail::EigenCompat::CanResize<EigenClass>::value),
"This object cannot be resized, but you have specified that a resize is required.");
// Check that the dimensionality is 1 or 2.
const auto dims = getDimensions();
if (dims.dimensionality > 2)
throw Exception(
"Dimensionality too high for a regular Eigen read. Use "
"Eigen::Tensor reads instead.",
ioda_Here());
int nDims[2] = {1, 1};
if (dims.dimsCur.size() >= 1) nDims[0] = gsl::narrow<int>(dims.dimsCur[0]);
if (dims.dimsCur.size() >= 2) nDims[1] = gsl::narrow<int>(dims.dimsCur[1]);
// Resize if needed.
if (Resize)
detail::EigenCompat::DoEigenResize(res, nDims[0],
nDims[1]); // nullop if the size is already correct.
else if (dims.numElements != (size_t)(res.rows() * res.cols()))
throw Exception("Size mismatch", ioda_Here());
// Array copy to preserve row vs column major format.
// Should be optimized away by the compiler if unneeded.
// Note to the reader: We are reading in the data to a temporary object.
// We can size _this_ temporary object however we want.
// The temporary is used to swap row / column indices if needed.
// It should be optimized away if not needed... making sure this happens is a todo.
Eigen::Array<ScalarType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> data_in(res.rows(),
res.cols());
auto ret = read<ScalarType>(gsl::span<ScalarType>(data_in.data(), dims.numElements));
res = data_in;
return ret;
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
#else
static_assert(false, "The Eigen headers cannot be found, so this function cannot be used.");
#endif
}
/// \brief Read data into an Eigen::Array, Eigen::Matrix, Eigen::Map, etc.
/// \tparam EigenClass is a template pointing to the Eigen object.
/// This template must provide the EigenClass::Scalar typedef.
/// \param res is the Eigen object.
/// \returns Another instance of this Attribute. Used for operation chaining.
/// \throws ioda::Exception if there is a size mismatch.
/// \note When reading in a 1-D object, the data are read as a column vector.
template <class EigenClass>
Attribute_Implementation readWithEigenTensor(EigenClass& res) const {
#if 1 //__has_include("unsupported/Eigen/CXX11/Tensor")
try {
// Check dimensionality of source and destination
const auto ioda_dims = getDimensions();
const auto eigen_dims = ioda::detail::EigenCompat::getTensorDimensions(res);
if (ioda_dims.numElements != eigen_dims.numElements)
throw Exception("Size mismatch for Eigen Tensor-like read.", ioda_Here());
auto sp = (gsl::make_span(res.data(), eigen_dims.numElements));
return read(sp);
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
#else
static_assert(
false, "The Eigen unsupported/ headers cannot be found, so this function cannot be used.");
#endif
}
/// \internal Python binding function
template <class EigenClass>
EigenClass _readWithEigenRegular_python() const {
EigenClass data;
readWithEigenRegular(data);
return data;
}
/// @}
/// @name Type-querying Functions
/// @{
/// \brief Get Attribute type.
virtual Type getType() const;
/// \brief Get Attribute type.
inline Type type() const { return getType(); }
/// Query the backend and get the type provider.
virtual detail::Type_Provider* getTypeProvider() const;
/// \brief Convenience function to check an Attribute's storage type.
/// \tparam DataType is the type of the data. I.e. float, int, int32_t, uint16_t, std::string, etc.
/// \returns True if the type matches
/// \returns False (0) if the type does not match
/// \throws ioda::Exception if an error occurred.
template <class DataType>
bool isA() const {
Type templateType = Types::GetType_Wrapper<DataType>::GetType(getTypeProvider());
return isA(templateType);
}
/// Hand-off to the backend to check equivalence
virtual bool isA(Type lhs) const;
/// Python compatability function
inline bool isA(BasicTypes dataType) { return isA(Type(dataType, getTypeProvider())); }
/// \internal pybind11
inline bool _py_isA2(BasicTypes dataType) { return isA(dataType); }
/// @}
/// @name Data Space-Querying Functions
/// @{
// Get an Attribute's dataspace
// virtual Encapsulated_Handle getSpace() const;
/// \brief Get Attribute's dimensions.
virtual Dimensions getDimensions() const;
/// @}
};
// extern template class Attribute_Base<>;
} // namespace detail
/** \brief This class represents attributes, which may be attached to both Variables and Groups.
* \ingroup ioda_cxx_attribute
*
* Attributes are used to store small objects that get tagged to a Variable or a
* Group to provide context to users and other programs. Attributes include
* descriptions, units, alternate names, dimensions, and similar constructs.
* Attributes may have different types (ints, floats, datetimes, strings, etc.),
* and may be 0- or 1-dimensional.
*
* We can open an Attribute from a Has_Attribute object, which is a member of Groups and
* Variables.
*
* \note Multidimensional attributes are supported by some of the underlying backends,
* like HDF5, but are incompatible with the NetCDF file format.
* \see Has_Attribute for the class that can create and open new Attribute objects.
* \throws ioda::Exception on all exceptions.
**/
class IODA_DL Attribute : public detail::Attribute_Base<> {
public:
Attribute();
Attribute(std::shared_ptr<detail::Attribute_Backend> b);
Attribute(const Attribute&);
Attribute& operator=(const Attribute&);
virtual ~Attribute();
/// @name Python compatability objects
/// @{
detail::python_bindings::AttributeIsA<Attribute> _py_isA;
detail::python_bindings::AttributeReadSingle<Attribute> _py_readSingle;
detail::python_bindings::AttributeReadVector<Attribute> _py_readVector;
detail::python_bindings::AttributeReadNPArray<Attribute> _py_readNPArray;
detail::python_bindings::AttributeWriteSingle<Attribute> _py_writeSingle;
detail::python_bindings::AttributeWriteVector<Attribute> _py_writeVector;
detail::python_bindings::AttributeWriteNPArray<Attribute> _py_writeNPArray;
/// @}
};
namespace detail {
/// \brief Attribute backends inherit from this.
class IODA_DL Attribute_Backend : public Attribute_Base<> {
public:
virtual ~Attribute_Backend();
protected:
Attribute_Backend();
};
} // namespace detail
} // namespace ioda
/// @} // End Doxygen block
| {
"alphanum_fraction": 0.6960331088,
"avg_line_length": 42.8547169811,
"ext": "h",
"hexsha": "da507b2de331c42ac43f37b4cf82fff80445ddb6",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "NOAA-EMC/ioda",
"max_forks_repo_path": "src/engines/ioda/include/ioda/Attributes/Attribute.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "NOAA-EMC/ioda",
"max_issues_repo_path": "src/engines/ioda/include/ioda/Attributes/Attribute.h",
"max_line_length": 101,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "NOAA-EMC/ioda",
"max_stars_repo_path": "src/engines/ioda/include/ioda/Attributes/Attribute.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5387,
"size": 22713
} |
/*
* BRAINS
* (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling
* Yan-Rong Li, liyanrong@ihep.ac.cn
* Thu, Aug 4, 2016
*/
/*! \file dnest_sa1d.c
* \brief run dnest sampling for sa and 1d rm analysis.
*/
#ifdef SA
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stddef.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_interp.h>
#include <mpi.h>
#include "brains.h"
DNestFptrSet *fptrset_sa1d;
/*
* run denst for SA and 1D RM analysis.
*/
int dnest_sa1d(int argc, char **argv)
{
int i;
double logz_sa1d;
if(parset.flag_sa_par_mutual == 0) /* SA and RM have the same BLR */
{
set_blr_model2d();
num_params_sa_blr_model = 0;
}
else /* SA and RM have different BLRs but share the same inc. */
{
set_blr_model1d();
set_sa_blr_model();
}
/* RM */
num_params_blr = num_params_blr_model + 1; /* include line sys err */
num_params_rm = parset.n_con_recon + num_params_var + num_params_blr;
/* SA */
num_params_sa_blr = num_params_sa_blr_model + num_params_sa_extpar;
num_params_sa = num_params_sa_blr;
/* total */
num_params_blr_tot = num_params_blr + num_params_sa_blr;
num_params = num_params_sa + num_params_rm;
idx_resp = num_params_blr_tot + num_params_drw + num_params_trend;
idx_difftrend = idx_resp + num_params_resp;
par_fix = (int *) malloc(num_params * sizeof(int));
par_fix_val = (double *) malloc(num_params * sizeof(double));
par_range_model = malloc( num_params * sizeof(double *));
par_prior_gaussian = malloc( num_params * sizeof(double *));
for(i=0; i<num_params; i++)
{
par_range_model[i] = malloc(2*sizeof(double));
par_prior_gaussian[i] = malloc(2*sizeof(double));
}
par_prior_model = malloc( num_params * sizeof(int));
fptrset_sa1d = dnest_malloc_fptrset();
/* setup functions used for dnest*/
fptrset_sa1d->from_prior = from_prior_sa1d;
fptrset_sa1d->print_particle = print_particle_sa1d;
fptrset_sa1d->restart_action = restart_action_sa;
fptrset_sa1d->accept_action = accept_action_sa1d;
fptrset_sa1d->kill_action = kill_action_sa1d;
fptrset_sa1d->perturb = perturb_sa1d;
fptrset_sa1d->read_particle = read_particle_sa1d;
fptrset_sa1d->log_likelihoods_cal_initial = log_likelihoods_cal_initial_sa1d;
fptrset_sa1d->log_likelihoods_cal_restart = log_likelihoods_cal_restart_sa1d;
fptrset_sa1d->log_likelihoods_cal = log_likelihoods_cal_sa1d;
set_par_range_sa1d();
set_par_fix_blrmodel();
set_par_fix_sa_blrmodel();
/* the rest parameters */
for(i=num_params_blr_model; i<num_params_blr; i++)
{
par_fix[i] = 0;
par_fix_val[i] = -DBL_MAX;
}
for(i=num_params_blr + num_params_sa_blr_model; i<num_params; i++)
{
par_fix[i] = 0;
par_fix_val[i] = -DBL_MAX;
}
/* fix non-linear response */
if(parset.flag_nonlinear !=1)
{
par_fix[idx_resp+1] = 1;
par_fix_val[idx_resp+1] = 0.0;
}
/* fix systematic error of line */
if(parset.flag_line_sys_err != 1)
{
par_fix[num_params_blr-1] = 1;
par_fix_val[num_params_blr-1] = log(1.0);
}
/* fix inc of SA BLR if SA and RM have different BLR
* in this case, DA must be fixed.
*/
if(parset.flag_sa_par_mutual != 0)
{
/* get the index for mbh and inclination parameters */
set_idx_par_mutual();
/* inc */
par_fix[num_params_blr + idx_sa_par_mutual[1]] = 1;
par_fix_val[num_params_blr + idx_sa_par_mutual[1]] = 0.0;
/* fix DA */
par_fix[num_params_blr + num_params_sa_blr_model] = 1;
par_fix_val[num_params_blr + num_params_sa_blr_model] = log(550.0);
}
/* fix FA */
par_fix[num_params_blr + num_params_sa_blr_model+2] = 1;
par_fix_val[num_params_blr + num_params_sa_blr_model+2] = log(1.0);
/* fix systematic error of continuum */
if(parset.flag_con_sys_err != 1)
{
par_fix[num_params_blr_tot] = 1;
par_fix_val[num_params_blr_tot] = log(1.0);
}
/* fix continuum variation parameter sigma and tau if flag_fixvar is true */
if(parset.flag_fixvar == 1)
{
par_fix[num_params_blr_tot + 1] = 1;
par_fix_val[num_params_blr_tot + 1] = var_param[1];
par_fix[num_params_blr_tot + 2] = 1;
par_fix_val[num_params_blr_tot + 2] = var_param[2];
}
print_par_names_sa1d();
force_update = parset.flag_force_update;
if(parset.flag_para_name != 1)
logz_sa1d = dnest(argc, argv, fptrset_sa1d, num_params, dnest_options_file);
dnest_free_fptrset(fptrset_sa1d);
return 0;
}
void set_par_range_sa1d()
{
int i, j, i1, i2;
/* RM BLR parameters first */
for(i=0; i<num_params_blr_model; i++)
{
par_range_model[i][0] = blr_range_model[i][0];
par_range_model[i][1] = blr_range_model[i][1];
par_prior_model[i] = UNIFORM;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 0.0;
}
/* systematic line error */
i = num_params_blr -1;
par_range_model[i][0] = sys_err_line_range[0];
par_range_model[i][1] = sys_err_line_range[1];
par_prior_model[i] = UNIFORM;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 0.0;
/* SA BLR parameters */
for(i=num_params_blr; i<num_params_blr + num_params_sa_blr_model; i++)
{
par_range_model[i][0] = sa_blr_range_model[i-num_params_blr][0];
par_range_model[i][1] = sa_blr_range_model[i-num_params_blr][1];
par_prior_model[i] = UNIFORM;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 0.0;
}
/* SA extra parameters */
for(i=num_params_blr + num_params_sa_blr_model; i<num_params_blr_tot; i++)
{
par_range_model[i][0] = sa_extpar_range[i-(num_params_blr + num_params_sa_blr_model)][0];
par_range_model[i][1] = sa_extpar_range[i-(num_params_blr + num_params_sa_blr_model)][1];
par_prior_model[i] = UNIFORM;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 0.0;
}
/* variability parameters */
/* first systematic error */
i = num_params_blr_tot;
par_range_model[i][0] = var_range_model[0][0];
par_range_model[i][1] = var_range_model[0][1];
par_prior_model[i] = UNIFORM;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 0.0;
/* drw parameters */
for(i=num_params_blr_tot+1; i<num_params_drw + num_params_blr_tot; i++)
{
if(var_param_std[i-num_params_blr_tot] > 0.0)
{
par_range_model[i][0] = var_param[i-num_params_blr_tot] - 5.0 * var_param_std[i-num_params_blr_tot];
par_range_model[i][1] = var_param[i-num_params_blr_tot] + 5.0 * var_param_std[i-num_params_blr_tot];
/* make sure that the range lies within the initial range */
par_range_model[i][0] = fmax(par_range_model[i][0], var_range_model[i-num_params_blr_tot][0]);
par_range_model[i][1] = fmin(par_range_model[i][1], var_range_model[i-num_params_blr_tot][1]);
par_prior_model[i] = GAUSSIAN;
par_prior_gaussian[i][0] = var_param[i-num_params_blr_tot];
par_prior_gaussian[i][1] = var_param_std[i-num_params_blr_tot];
}
else
{
par_range_model[i][0] = var_range_model[i-num_params_blr_tot][0];
par_range_model[i][1] = var_range_model[i-num_params_blr_tot][1];
par_prior_model[i] = UNIFORM;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 0.0;
}
}
/* long-term trend */
for(i=num_params_drw + num_params_blr_tot; i< num_params_drw + num_params_trend + num_params_blr_tot; i++)
{
par_range_model[i][0] = var_range_model[3][0];
par_range_model[i][1] = var_range_model[3][1];
par_prior_model[i] = GAUSSIAN;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 1.0;
}
/* response A and Ag */
j = 0;
i1 = idx_resp;
i2 = idx_resp + num_params_resp;
for(i=i1; i<i2; i++)
{
par_range_model[i][0] = resp_range[j][0];
par_range_model[i][1] = resp_range[j][1];
par_prior_model[i] = UNIFORM;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 0.0;
j++;
}
/* different trend */
j = 0;
i1 = idx_difftrend;
i2 = idx_difftrend + num_params_difftrend;
for(i=i1; i< i2; i++)
{
par_range_model[i][0] = var_range_model[4 + j][0];
par_range_model[i][1] = var_range_model[4 + j][1];
par_prior_model[i] = UNIFORM;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 0.0;
j++;
}
/* continuum light curve parameters */
for(i=num_params_blr_tot+num_params_var; i<num_params; i++)
{
par_range_model[i][0] = var_range_model[4+num_params_difftrend][0];
par_range_model[i][1] = var_range_model[4+num_params_difftrend][1];
par_prior_model[i] = GAUSSIAN;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 1.0;
}
return;
}
/*!
* print names and prior ranges for parameters
*
*/
void print_par_names_sa1d()
{
if(thistask!= roottask)
return;
int i, j;
FILE *fp;
char fname[BRAINS_MAX_STR_LENGTH], str_fmt[BRAINS_MAX_STR_LENGTH];
sprintf(fname, "%s/%s", parset.file_dir, "data/para_names_sa1d.txt");
fp = fopen(fname, "w");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s.\n", fname);
exit(0);
}
strcpy(str_fmt, "%4d %-15s %10.6f %10.6f %4d %4d %15.6e\n");
printf("# Print parameter name in %s\n", fname);
fprintf(fp, "#*************************************************\n");
fprint_version(fp);
fprintf(fp, "#*************************************************\n");
fprintf(fp, "%4s %-15s %10s %10s %4s %4s %15s\n", "#", "Par", "Min", "Max", "Prior", "Fix", "Val");
i=-1;
for(j=0; j<num_params_blr_model; j++)
{
i++;
fprintf(fp, str_fmt, i, "BLR model", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
}
i++;
fprintf(fp, str_fmt, i, "sys_err_line", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
for(j=0; j<num_params_sa_blr_model; j++)
{
i++;
fprintf(fp, str_fmt, i, "SA BLR model", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
}
for(j=0; j<num_params_sa_extpar; j++)
{
i++;
fprintf(fp, str_fmt, i, "SA Extra Par", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
}
i++;
fprintf(fp, str_fmt, i, "sys_err_con", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
i++;
fprintf(fp, str_fmt, i, "sigmad", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
i++;
fprintf(fp, str_fmt, i, "taud", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
for(j=0; j<num_params_trend; j++)
{
i++;
fprintf(fp, str_fmt, i, "trend", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
}
i++;
fprintf(fp, str_fmt, i, "A", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
i++;
fprintf(fp, str_fmt, i, "Ag", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
for(j=0; j<num_params_difftrend; j++)
{
i++;
fprintf(fp, str_fmt, i, "diff trend", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
}
for(j=0; j<parset.n_con_recon; j++)
{
i++;
fprintf(fp, str_fmt, i, "time series", par_range_model[i][0], par_range_model[i][1], par_prior_model[i],
par_fix[i], par_fix_val[i]);
}
fclose(fp);
}
/*!
* this function generates a sample from prior.
*/
void from_prior_sa1d(void *model)
{
int i;
double *pm = (double *)model;
for(i=0; i<num_params; i++)
{
if(par_prior_model[i] == GAUSSIAN)
{
pm[i] = dnest_randn()*par_prior_gaussian[i][1] + par_prior_gaussian[i][0];
dnest_wrap(&pm[i], par_range_model[i][0], par_range_model[i][1]);
}
else
{
pm[i] = par_range_model[i][0] + dnest_rand() * (par_range_model[i][1] - par_range_model[i][0]);
}
}
/* cope with fixed parameters */
for(i=0; i<num_params; i++)
{
if(par_fix[i] == 1)
pm[i] = par_fix_val[i];
}
which_parameter_update = -1;
return;
}
/*!
* this function calculates likelihood at initial step.
*/
double log_likelihoods_cal_initial_sa1d(const void *model)
{
double logL;
logL = prob_initial_sa1d(model);
return logL;
}
/*!
* this function calculates likelihood at initial step.
*/
double log_likelihoods_cal_restart_sa1d(const void *model)
{
double logL;
logL = prob_initial_sa1d(model);
return logL;
}
/*!
* this function calculates likelihood.
*/
double log_likelihoods_cal_sa1d(const void *model)
{
double logL;
logL = prob_sa1d(model);
return logL;
}
/*!
* this function prints out parameters.
*/
void print_particle_sa1d(FILE *fp, const void *model)
{
int i;
double *pm = (double *)model;
for(i=0; i<num_params; i++)
{
fprintf(fp, "%e ", pm[i] );
}
fprintf(fp, "\n");
return;
}
/*!
* This function read the particle from the file.
*/
void read_particle_sa1d(FILE *fp, void *model)
{
int j;
double *psample = (double *)model;
for(j=0; j < dnest_num_params; j++)
{
if(fscanf(fp, "%lf", psample+j) < 1)
{
printf("%f\n", *psample);
fprintf(stderr, "#Error: Cannot read file %s.\n", options.sample_file);
exit(0);
}
}
return;
}
/*!
* this function perturbs parameters.
*/
double perturb_sa1d(void *model)
{
double *pm = (double *)model;
double logH = 0.0, limit1, limit2, width, rnd;
int which, which_level;
/*
* fixed parameters need not to update
* perturb important parameters more frequently
*/
do
{
rnd = dnest_rand();
if(rnd < fmax(0.2, 1.0*(num_params_blr_tot+num_params_var)/num_params))
which = dnest_rand_int(num_params_blr_tot + num_params_var);
else
which = dnest_rand_int(parset.n_con_recon) + num_params_blr_tot + num_params_var;
}while(par_fix[which] == 1);
which_parameter_update = which;
/* level-dependent width */
count_saves = dnest_get_count_saves();
which_level_update = dnest_get_which_level_update();
which_level = which_level_update > (size_levels-10)?(size_levels-10):which_level_update;
if( which_level > 0)
{
limit1 = limits[(which_level-1) * num_params *2 + which *2];
limit2 = limits[(which_level-1) * num_params *2 + which *2 + 1];
width = (limit2 - limit1);
}
else
{
limit1 = par_range_model[which][0];
limit2 = par_range_model[which][1];
width = (par_range_model[which][1] - par_range_model[which][0]);
}
width /= (2.35);
if(par_prior_model[which] == GAUSSIAN)
{
logH -= (-0.5*pow((pm[which] - par_prior_gaussian[which][0])/par_prior_gaussian[which][1], 2.0) );
pm[which] += dnest_randh() * width;
dnest_wrap(&pm[which], par_range_model[which][0], par_range_model[which][1]);
//dnest_wrap(&pm[which], limit1, limit2);
logH += (-0.5*pow((pm[which] - par_prior_gaussian[which][0])/par_prior_gaussian[which][1], 2.0) );
}
else
{
pm[which] += dnest_randh() * width;
dnest_wrap(&(pm[which]), par_range_model[which][0], par_range_model[which][1]);
//dnest_wrap(&pm[which], limit1, limit2);
}
return logH;
}
/*!
* this function calculates likelihood.
*/
double log_likelihoods_cal_sa1d_exam(const void *model)
{
return 0.0;
}
void accept_action_sa1d()
{
int param;
double *ptemp;
// the parameter previously updated
param = which_parameter_update;
/* continuum parameter is updated */
if( param >= num_params_blr_tot )
{
/*
*note that (response) Fline is also changed as long as Fcon is changed.
*num_params_blr-the parameter is the systematic error of continuum.
*the change of this parameter also changes continuum reconstruction.
*/
ptemp = Fcon_rm_particles[which_particle_update];
Fcon_rm_particles[which_particle_update] = Fcon_rm_particles_perturb[which_particle_update];
Fcon_rm_particles_perturb[which_particle_update] = ptemp;
if(force_update != 1)
{
ptemp = Fline_at_data_particles[which_particle_update];
Fline_at_data_particles[which_particle_update] = Fline_at_data_particles_perturb[which_particle_update];
Fline_at_data_particles_perturb[which_particle_update] = ptemp;
}
}
else if( param != num_params_blr-1 && force_update != 1)
{
/* RM and SA BLR parameter is updated
* Note a) that the (num_par_blr-1)-th parameter is systematic error of line.
* when this parameter is updated, Trans1D and Fline, phase_sa, and Fline_sa are unchanged.
* b) Fline is always changed, except param = num_params_blr-1.
*/
{
ptemp = TransTau_particles[which_particle_update];
TransTau_particles[which_particle_update] = TransTau_particles_perturb[which_particle_update];
TransTau_particles_perturb[which_particle_update] = ptemp;
ptemp = Trans1D_particles[which_particle_update];
Trans1D_particles[which_particle_update] = Trans1D_particles_perturb[which_particle_update];
Trans1D_particles_perturb[which_particle_update] = ptemp;
ptemp = Fline_at_data_particles[which_particle_update];
Fline_at_data_particles[which_particle_update] = Fline_at_data_particles_perturb[which_particle_update];
Fline_at_data_particles_perturb[which_particle_update] = ptemp;
prob_sa_particles[which_particle_update] = prob_sa_particles_perturb[which_particle_update];
}
}
return;
}
/*
* action when particle i is killed in cdnest sampling.
* particle i_copy's properties is copyed to particle i.
*/
void kill_action_sa1d(int i, int i_copy)
{
memcpy(Fcon_rm_particles[i], Fcon_rm_particles[i_copy], parset.n_con_recon * sizeof(double));
memcpy(Fline_at_data_particles[i], Fline_at_data_particles[i_copy], n_line_data * sizeof(double));
memcpy(TransTau_particles[i], TransTau_particles[i_copy], parset.n_tau*sizeof(double));
memcpy(Trans1D_particles[i], Trans1D_particles[i_copy], parset.n_tau * sizeof(double));
prob_sa_particles[i] = prob_sa_particles[i_copy];
return;
}
#endif
| {
"alphanum_fraction": 0.6621066292,
"avg_line_length": 28.6728682171,
"ext": "c",
"hexsha": "45c99536229a4add59d3621d6ea7a32dce57cfa3",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "yzxamos/BRAINS",
"max_forks_repo_path": "src/dnest_sa1d.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "yzxamos/BRAINS",
"max_issues_repo_path": "src/dnest_sa1d.c",
"max_line_length": 110,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "yzxamos/BRAINS",
"max_stars_repo_path": "src/dnest_sa1d.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5614,
"size": 18494
} |
/**
*
* @file qwrapper_dlaset.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @date 2010-11-15
* @generated d Tue Jan 7 11:44:58 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_dlaset(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int M, int N,
double alpha, double beta,
double *A, int LDA)
{
DAG_CORE_LASET;
QUARK_Insert_Task(quark, CORE_dlaset_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &M, VALUE,
sizeof(int), &N, VALUE,
sizeof(double), &alpha, VALUE,
sizeof(double), &beta, VALUE,
sizeof(double)*LDA*N, A, OUTPUT,
sizeof(int), &LDA, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dlaset_quark = PCORE_dlaset_quark
#define CORE_dlaset_quark PCORE_dlaset_quark
#endif
void CORE_dlaset_quark(Quark *quark)
{
PLASMA_enum uplo;
int M;
int N;
double alpha;
double beta;
double *A;
int LDA;
quark_unpack_args_7(quark, uplo, M, N, alpha, beta, A, LDA);
LAPACKE_dlaset_work(
LAPACK_COL_MAJOR,
lapack_const(uplo),
M, N, alpha, beta, A, LDA);
}
| {
"alphanum_fraction": 0.5145228216,
"avg_line_length": 27.6557377049,
"ext": "c",
"hexsha": "9b2ef499b7dbeb613e371bb70f93f0faccefec64",
"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_dlaset.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_dlaset.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas-qwrapper/qwrapper_dlaset.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 444,
"size": 1687
} |
/* cdf/gammainv.c
*
* Copyright (C) 2003, 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_gamma.h>
#include <stdio.h>
double
gsl_cdf_gamma_Pinv (const double P, const double a, const double b)
{
double x;
if (P == 1.0)
{
return GSL_POSINF;
}
else if (P == 0.0)
{
return 0.0;
}
/* Consider, small, large and intermediate cases separately. The
boundaries at 0.05 and 0.95 have not been optimised, but seem ok
for an initial approximation.
BJG: These approximations aren't really valid, the relevant
criterion is P*gamma(a+1) < 1. Need to rework these routines and
use a single bisection style solver for all the inverse
functions.
*/
if (P < 0.05)
{
double x0 = exp ((gsl_sf_lngamma (a) + log (P)) / a);
x = x0;
}
else if (P > 0.95)
{
double x0 = -log1p (-P) + gsl_sf_lngamma (a);
x = x0;
}
else
{
double xg = gsl_cdf_ugaussian_Pinv (P);
double x0 = (xg < -0.5*sqrt (a)) ? a : sqrt (a) * xg + a;
x = x0;
}
/* Use Lagrange's interpolation for E(x)/phi(x0) to work backwards
to an improved value of x (Abramowitz & Stegun, 3.6.6)
where E(x)=P-integ(phi(u),u,x0,x) and phi(u) is the pdf.
*/
{
double lambda, dP, phi;
unsigned int n = 0;
start:
dP = P - gsl_cdf_gamma_P (x, a, 1.0);
phi = gsl_ran_gamma_pdf (x, a, 1.0);
if (dP == 0.0 || n++ > 32)
goto end;
lambda = dP / GSL_MAX (2 * fabs (dP / x), phi);
{
double step0 = lambda;
double step1 = -((a - 1) / x - 1) * lambda * lambda / 4.0;
double step = step0;
if (fabs (step1) < 0.5 * fabs (step0))
step += step1;
if (x + step > 0)
x += step;
else
{
x /= 2.0;
}
if (fabs (step0) > 1e-10 * x || fabs(step0 * phi) > 1e-10 * P)
goto start;
}
end:
if (fabs(dP) > GSL_SQRT_DBL_EPSILON * P)
{
GSL_ERROR_VAL("inverse failed to converge", GSL_EFAILED, GSL_NAN);
}
return b * x;
}
}
double
gsl_cdf_gamma_Qinv (const double Q, const double a, const double b)
{
double x;
if (Q == 1.0)
{
return 0.0;
}
else if (Q == 0.0)
{
return GSL_POSINF;
}
/* Consider, small, large and intermediate cases separately. The
boundaries at 0.05 and 0.95 have not been optimised, but seem ok
for an initial approximation. */
if (Q < 0.05)
{
double x0 = -log (Q) + gsl_sf_lngamma (a);
x = x0;
}
else if (Q > 0.95)
{
double x0 = exp ((gsl_sf_lngamma (a) + log1p (-Q)) / a);
x = x0;
}
else
{
double xg = gsl_cdf_ugaussian_Qinv (Q);
double x0 = (xg < -0.5*sqrt (a)) ? a : sqrt (a) * xg + a;
x = x0;
}
/* Use Lagrange's interpolation for E(x)/phi(x0) to work backwards
to an improved value of x (Abramowitz & Stegun, 3.6.6)
where E(x)=P-integ(phi(u),u,x0,x) and phi(u) is the pdf.
*/
{
double lambda, dQ, phi;
unsigned int n = 0;
start:
dQ = Q - gsl_cdf_gamma_Q (x, a, 1.0);
phi = gsl_ran_gamma_pdf (x, a, 1.0);
if (dQ == 0.0 || n++ > 32)
goto end;
lambda = -dQ / GSL_MAX (2 * fabs (dQ / x), phi);
{
double step0 = lambda;
double step1 = -((a - 1) / x - 1) * lambda * lambda / 4.0;
double step = step0;
if (fabs (step1) < 0.5 * fabs (step0))
step += step1;
if (x + step > 0)
x += step;
else
{
x /= 2.0;
}
if (fabs (step0) > 1e-10 * x)
goto start;
}
}
end:
return b * x;
}
| {
"alphanum_fraction": 0.5608715184,
"avg_line_length": 22.7142857143,
"ext": "c",
"hexsha": "84815fcd5b081e34a2d186b05594aa782364c20a",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "skair39/structured",
"max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/cdf/gammainv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "skair39/structured",
"max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/cdf/gammainv.c",
"max_line_length": 77,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "parasol-ppl/PPL_utils",
"max_stars_repo_path": "folding_libs/gsl-1.14/cdf/gammainv.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": 1484,
"size": 4452
} |
/************************************************************/
/********* Interval Censoring data analysis ***********/
/********* by Hao Liu on 6/7/07 **********/
/************************************************************/
/*** accepted data file: first p colmuns are covariates, last 2 columns are observed time intervals, 9999=censored ***/
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sort_double.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_vector.h>
#define MAX_ITER 10000
#define TOL 1.0e-6
#define sim_num 300
/** sim_num is the bootstrap replicates **/
#define machine_p 1.0e-15
#define myPHO 0.5
#define myPI 0.01
#define Sigma 20.0
struct fun_params {
double *dij;
double *zij;
double *pj;
int nn;
int np;
int mk;
};
double fdf_eplike(int, const double *, double *, void *);
void myxij(double *, const double *, const double *, void *);
void deveplike(double *, double *, const double *, double *, double *, void *);
double maxp(double *, double *, double, const double *, double *, void *);
double normf(double *, double *, double, double, const double *, double *, void *);
extern int conmin(int, double *, double *, double *, int *, int *, double, int, double *, int, double, int,
double (*)(int, const double *, double *, void *), void *);
int main(int argc, char *argv[])
{
FILE *fpi, *fpo1, *fpo2;
if(argc<=4) {
printf("need: 1) data file name, 2) sample size n, 3) number of covariate p, and 4) the output file1 5) files2...\n");
return 0;
}
fpi=fopen(argv[1], "r");
fpo1=fopen(argv[4], "w");
fpo2=fopen(argv[5], "w");
int nn=0, np=0, i, j;
char *cs=malloc(1000*sizeof(char));
sscanf(argv[2], "%i", &nn);
sscanf(argv[3], "%i", &np);
if (np>nn) {
printf("sample size should be larger than the number of covariates.");
return 0;
}
double *li= malloc(nn*sizeof(double)), *lia= malloc(nn*sizeof(double)), *li0=malloc(nn*sizeof(double));
double *ri= malloc(nn*sizeof(double)), *ria= malloc(nn*sizeof(double)), *ri0=malloc(nn*sizeof(double));
double *zij= malloc(nn*np*sizeof(double)), *zij0= malloc(nn*np*sizeof(double)), *dij=malloc(nn*nn*sizeof(double));
double *q=malloc(nn*sizeof(double)), *p=malloc(nn*sizeof(double)), *gam= malloc(nn*nn*sizeof(double));
double *pj=calloc(nn, sizeof(double)), *mypj=calloc(nn, sizeof(double));
double alpha0=1.0, theta0=1.0, nvold;
register double *tau= calloc(nn, sizeof(double));
double past_time, now_time, mysize, tmp00;
double curt, wt, u, likval1, likval2, likval;
int j1, k, mk, ss, iter, status, iter2, cure;
int *bsi=malloc(nn*sizeof(int)), *bsi2=malloc(nn*sizeof(int));
double *ww=calloc(2*(np+1)*(np+8), sizeof(double)),
*xx=calloc(2*(np+1), sizeof(double)), *gg=calloc(2*(np+1), sizeof(double)), fval;
double acc=1e-11, eps=1e-5;;
int nflag=-1, ifun=-1, ifunter=-1;
struct fun_params *mydata=malloc(sizeof(struct fun_params));
const gsl_rng_type *Ty;
gsl_rng *rn;
gsl_rng_env_setup();
Ty = gsl_rng_default;
rn = gsl_rng_alloc (Ty);
gsl_rng_set(rn, 100);
/** read the data, first line is the hearder and thus removed ***/
fgets(cs, 1000, fpi);
for (i = 0; i<nn; i++) {
for (j=0;j<np;j++) fscanf(fpi, "%lf,", zij0+np*i+j);
fscanf(fpi, "%lf,%lf", li0+i, ri0+i);
bsi[i]=i;
}
fclose(fpi);
mydata->nn = nn;
mydata->np = np;
/** sim_num is the bootstrap replicates **/
for (ss=0;ss<sim_num;ss++){
/** select the bootstrap sample ***/
/*** random sample with replacement **/
gsl_ran_sample (rn, bsi2, nn, bsi, nn, sizeof(int));
for(i=0;i<nn;i++) {
for (j=0;j<np;j++) zij[np*i+j] = zij0[np*bsi2[i]+j];
lia[i]=li0[bsi2[i]];
li[i]=li0[bsi2[i]];
ria[i]=ri0[bsi2[i]];
ri[i]=ri0[bsi2[i]];
}
mydata->zij = zij;
gsl_sort(ria,1,nn);
gsl_sort(lia,1,nn);
/*** generate p, q data ***/
p[0]=ria[0];
i=j=k=0;
do {
while (lia[i]<=p[k] && i<nn) i++;
q[k]=lia[i-1];
k++;
while (ria[j]<lia[i] && j<nn) j++;
if (j<nn) p[k]=ria[j];
else p[k]=ria[j-1];
} while (i<nn && j<nn);
mk=k-1;
mydata->mk=mk;
for (i=0; i<nn; i++)
for (j = 0; j <= mk; j++)
dij[i*(mk+1)+j]=(li[i]<=q[j] && p[j]<=ri[i]) ? 1.0: 0.0;
mydata->dij= dij;
/** Initial values **/
for (j=0; j<mk; j++) pj[j] = 1.0/mk;
(mydata->pj)=pj;
for (j=0; j<=np; j++) xx[j] = 0.0;
nflag=2;
fval=9999.0;
iter2=0;
do {
iter2++;
likval2=fval;
for (j = 0; j < mk; j++) tau[j]=1.0/(mydata->pj)[j];
nvold = 0.1;
/*** calculate expected Xij ***/
myxij(gam, xx, pj, mydata);
/*** Primal-dual interior-point method ***/
nvold = maxp(pj, tau, nvold, xx, gam, mydata);
/** minimize to get theta **/
if (nflag!=0) for (j=0; j<=np; j++) xx[j] = 0.1;
nflag= conmin(np+1, xx, &fval, gg, &ifun, &ifunter, 0.001, 300, ww, 400, 1e-18, 1, fdf_eplike, mydata);
likval1=fval;
} while(fabs(likval1-likval2)>0.0001 & iter2 < MAX_ITER);
now_time = (double) clock ();
/*** outputs ****/
for(j=0; j<=np; j++) fprintf(fpo1, "%.10f, ", xx[j]);
fprintf(fpo1, "%.10f, %.2f \n", fval, now_time/(double) CLOCKS_PER_SEC);
for(j=0; j<mk; j++) fprintf(fpo2, "%.10f,", (mydata->pj)[j]);
fprintf(fpo2, "%i\n", mk);
}
fclose(fpo1);
fclose(fpo2);
free(li);
free(ri);
free(zij);
free(li0);
free(ri0);
free(zij0);
free(lia);
free(ria);
free(p);
free(q);
free(mypj);
free(gam);
free(tau);
free(xx);
free(ww);
free(gg);
free(mydata);
return 0;
}
/*** the expected likelihood, 0=alpha, 1=theta and the derivative ***/
double fdf_eplike(int np1, const double *theta, double *df, void * par)
{
struct fun_params * param = (struct fun_params *) par;
int i,j,j1, m=(param->mk), nn=(param->nn), tmpi;
double alp0, sz, likval, msumval, tmpz, tmpz1, tmpa, tmpc, tmpd, tmp0, dfz1, dfz2;
double *xij, *cij, *pps, pp;
xij=calloc(m+1, sizeof(double));
pps=calloc(m+1, sizeof(double));
cij=calloc(m+1, sizeof(double));
alp0=theta[0];
for(j=0;j<m;j++) {
pps[j]=0.0;
for(j1=0;j1<j;j1++) pps[j] += ((param->pj)[j1]) ;
}
for(j=0;j<np1;j++) df[j]=0.0;
likval=0.0;
for(i=0;i<nn;i++) {
tmpz1=0.0;
for(j=1;j<np1;j++) tmpz1 += theta[j] * (param->zij)[i*(np1-1)+j-1];
tmpz=exp(alp0 + tmpz1);
tmpc=0.0;
for(j=0;j<m;j++) {
pp = (param->pj)[j];
xij[j] = ((param->dij)[i*(m+1)+j]) * exp( -tmpz* pps[j]) *(1.0- exp(-pp*tmpz));
tmpc += xij[j];
}
xij[m]= (param -> dij)[i*(m+1)+m] * exp(-tmpz);
tmpc += xij[m];
if (tmpc == 0.0) {
for(j=0;j<np1;j++) df[j]=-9999999.0;
return 9999999.0;
}
for(j=0;j<=m;j++) {
cij[j]=0.0;
for(j1=j+1; j1<m; j1++) cij[j] += xij[j1];
xij[j] /=tmpc;
}
msumval=0.0;
for(j=0;j<m;j++) {
cij[j] /=tmpc;
pp= (param -> pj)[j];
likval += ( xij[j]* log(1.0- exp(- pp* tmpz )) - cij[j] * pp * tmpz);
msumval += (( xij[j] *exp(-pp* tmpz) /(1.0- exp(-pp* tmpz)) - cij[j] )*pp);
}
df[0] += ((msumval-xij[m])*tmpz);
for(j=1;j<np1;j++) df[j] += ((msumval-xij[m])*(param->zij)[i*(np1-1)+j-1]*tmpz);
likval -= xij[m]*tmpz;
}
for(j=0;j<np1;j++) df[j] = - df[j]/((double) nn);
free(cij);
free(xij);
free(pps);
return -likval/((double) nn);
}
/*** Calculate the updated Xij ***/
void myxij(double *lamij, const double *the, const double *mypj, void * parm)
{
struct fun_params * para = (struct fun_params *) parm;
double alp0, tmp0, tmpc, pp, tmpz, tmpz1;
int i,j,j1, tmpi, m=(para->mk), nn=(para->nn), np=(para->np);
double *gj=calloc(m+1, sizeof(double)), *xij=calloc(m+1, sizeof(double));
double *dij=(para->dij), *zij=(para->zij);
alp0=the[0];
for(j=0;j<m;j++) {
gj[j]=0.0;
for(j1=0;j1<j;j1++) gj[j] += mypj[j1];
}
for(i=0;i<nn;i++) {
tmpz1=0.0;
for(j=0;j<np;j++) tmpz1 += the[j+1] * zij[j+i*np];
tmpz=exp(alp0+ tmpz1);
tmpc=0.0;
for(j=0;j<m;j++) {
pp = mypj[j];
xij[j] = dij[i*(m+1)+j] * exp( -tmpz* gj[j]) *(1.0- exp(-pp*tmpz));
tmpc += xij[j];
}
xij[m]= dij[i*(m+1)+m] * exp(-tmpz);
tmpc += xij[m];
for(j=0;j<m;j++) lamij[i*m+j] = xij[j] / tmpc;
}
free(xij);
free(gj);
}
/*** Calculate the first derivative and second derivative wrt p of the expected liklihood ***/
void deveplike(double *df, double *ddf, const double *the, double *gam, double * myp, void *parm)
{
struct fun_params * para = (struct fun_params *) parm;
double alp0, tmp1, tmpz1, tmp2, tmpa, pp;
int i,j,k,j1, m=(para->mk), nn=(para->nn), np=(para->np);
double *zij=(para->zij);
alp0=the[0];
for(j=0;j<m;j++) {
df[j] = ddf[j] = 0.0;
pp = myp[j];
for(i=0;i<nn;i++) {
tmpz1=0.0;
for(k=0;k<np;k++) tmpz1 += the[k+1] * zij[k+i*np];
tmp1=exp(alp0+ tmpz1);
tmp2=exp(tmp1 * pp);
tmpa =0.0;
for(j1=j+1; j1<m; j1++) tmpa += gam[i*m+j1];
df[j] += tmp1*( gam[i*m+j] /( tmp2- 1.0) - tmpa);
ddf[j] -= (gam[i*m+j]*tmp1*tmp1*tmp2 / (tmp2 - 1.0) / (tmp2 - 1.0));
}
}
}
/*** NormF ***/
double normf(double *p, double *tau, double nv, double eta, const double *the, double *gam, void *parm)
{
struct fun_params * para = (struct fun_params *) parm;
double *fj, *ffj, sum1, tmp1, tmp2;
int j, m=(para->mk);
fj=calloc(m, sizeof(double));
ffj=calloc(m, sizeof(double));
deveplike(fj, ffj, the, gam, p, parm);
sum1=0.0;
for(j=0;j<m;j++) {
tmp1 = (fj[j] + tau[j] - nv);
tmp2 = p[j] * tau[j] - 1.0/eta;
sum1 += (tmp1*tmp1 + tmp2*tmp2);
}
free(fj);
free(ffj);
return sqrt(sum1);
}
/**** Maximize for p ****/
double maxp(double *pj, double *tau, double nvold, const double *the, double *gam, void *parm)
{
struct fun_params * para = (struct fun_params *) parm;
int j, iter, m=(para->mk), nn=(para->nn), np=(para->np);
double eta, nv, curnv, steps, sum1, sum2, tmp1, tmp2;
double *fj, *ffj, *delp, *curp, *taunew, *curtau;
fj = calloc(m, sizeof(double));
ffj = calloc(m, sizeof(double));
delp = calloc(m, sizeof(double));
curp= calloc(m, sizeof(double));
taunew = calloc(m, sizeof(double));
curtau = calloc(m, sizeof(double));
iter=0;
do {
iter++;
// calculate the df=fj and diag(ddf)=ffj
for(j=0;j<m;j++) eta += pj[j]*tau[j];
eta = m*Sigma/eta;
deveplike(fj, ffj, the, gam, pj, parm);
sum1 = sum2 = 0.0;
for(j=0;j<m;j++) {
sum1 += ((1.0/eta + pj[j] * fj[j]) / (tau[j] - pj[j] * ffj[j]));
sum2 += (pj[j] / (tau[j] - pj[j] * ffj[j]));
}
nv=sum1/sum2;
// backtracking: find the largest positive step = steps
steps=1.0;
for(j=0;j<m;j++) {
delp[j] = (pj[j] * (fj[j]-nv) + 1.0/eta) / (tau[j] - pj[j] * ffj[j]);
taunew[j] = nv - ffj[j] * delp[j] - fj[j];
tmp1 = taunew[j] - tau[j];
if (tmp1 <0) steps = fmin(steps, -tau[j]/tmp1);
}
steps *= 0.99;
// backtracking: to keep the minimal p > 0;
tmp2 = 1.0;
for(j=0;j<m;j++) tmp2=fmin(tmp2, pj[j] + steps * delp[j]);
while(tmp2 <= 0) {
steps *= myPHO;
tmp2 = 1.0;
for(j=0;j<m;j++) tmp2=fmin(tmp2, pj[j] + steps * delp[j]);
}
// backtracking:
for(j=0;j<m;j++) {
curp[j] = pj[j] + steps * delp[j];
curtau[j] = tau[j] + steps * (taunew[j]-tau[j]);
}
curnv=nvold + steps * (nv-nvold);
tmp2 = normf(curp, curtau, curnv, eta, the, gam, parm);
tmp1 = normf(pj, tau, nvold, eta, the, gam, parm);
while(tmp2 > (1.0-myPI*steps)*tmp1) {
steps *= myPHO;
for(j=0;j<m;j++) {
curp[j] = pj[j] + steps * delp[j];
curtau[j] = tau[j] + steps * (taunew[j]-tau[j]);
}
curnv=nvold + steps * (nv-nvold);
tmp2=normf(curp, curtau, curnv, eta, the, gam, parm);
}
deveplike(fj, ffj, the, gam, curp, parm);
sum1=sum2=0.0;
for(j=0;j<m;j++) {
tmp1 = (fj[j] + curtau[j] - curnv);
sum1 += (tmp1*tmp1);
sum2 += curp[j] * curtau[j];
pj[j] = curp[j];
tau[j] = curtau[j];
}
nvold=curnv;
// printf("iter=%i: sum1=%.20f sum2=%f \n", iter, sqrt(sum1), sum2/m);
} while ( (sqrt(sum1)> TOL)& iter < MAX_ITER*10 );
free(fj);
free(ffj);
free(delp);
free(curtau);
free(taunew);
free(curp);
return nvold;
}
| {
"alphanum_fraction": 0.4738690643,
"avg_line_length": 28.9938900204,
"ext": "c",
"hexsha": "373b43d92a50bdcbb24b51b17eb1e746d0140098",
"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": "c0ec2b7f691c382329fe9f8afa95cc201223380c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "hliubcm/Semiparametric-Regression-Cure-Model-for-Interval-Censored-Data",
"max_forks_repo_path": "data_ana.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c0ec2b7f691c382329fe9f8afa95cc201223380c",
"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": "hliubcm/Semiparametric-Regression-Cure-Model-for-Interval-Censored-Data",
"max_issues_repo_path": "data_ana.c",
"max_line_length": 126,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c0ec2b7f691c382329fe9f8afa95cc201223380c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "hliubcm/Semiparametric-Regression-Cure-Model-for-Interval-Censored-Data",
"max_stars_repo_path": "data_ana.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4770,
"size": 14236
} |
/** @file */
#ifndef __CCL_F1D_H_INCLUDED__
#define __CCL_F1D_H_INCLUDED__
#include <gsl/gsl_spline.h>
CCL_BEGIN_DECLS
/*
* Spline wrapper
* Used to take care of evaluations outside the supported range
*/
typedef struct {
gsl_spline *spline;
double x0,xf; //Interpolation limits
double y0,yf; //Constant values to use beyond interpolation limit
} ccl_f1d_t;
ccl_f1d_t *ccl_f1d_t_new(int n,double *x,double *y,double y0,double yf);
double ccl_f1d_t_eval(ccl_f1d_t *spl,double x);
void ccl_f1d_t_free(ccl_f1d_t *spl);
CCL_END_DECLS
#endif
| {
"alphanum_fraction": 0.7621621622,
"avg_line_length": 19.1379310345,
"ext": "h",
"hexsha": "5425dfb57ad21e89eaba32d99858dd36699c9df8",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-02-10T07:35:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-10T07:35:07.000Z",
"max_forks_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "benediktdiemer/CCL",
"max_forks_repo_path": "include/ccl_f1d.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "benediktdiemer/CCL",
"max_issues_repo_path": "include/ccl_f1d.h",
"max_line_length": 72,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "benediktdiemer/CCL",
"max_stars_repo_path": "include/ccl_f1d.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 177,
"size": 555
} |
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_matrix.h>
#include "bstrlib/bstrlib.h"
#include "DosValues.h"
int write_dos_vals(char *outPath, int num_dos, double *Es, double *dos_vals);
int main(int argc, char *argv[]) {
if (argc < 15) {
printf("Usage: DosValues.out 'out_path' 'n' 'num_dos' 'Tae' 'Tce' 'Tbe' 'Tao' 'Tco' 'Tbo' 'EpsilonR' 'EpsilonM' 'M' 'W' 'Mu'\n");
printf("Example: DosValues.out 'dos_vals' '8' '500' '0.2' '1.0' '0.4' '0.08' '0.4' '0.16' '0.05' '0.05' '1.0' '1.0' '-2.0'\n");
return 2;
}
// Parse arguments.
char *out_path = argv[1];
int n = atoi(argv[2]);
int num_dos = atoi(argv[3]);
double Tae = atof(argv[4]);
double Tce = atof(argv[5]);
double Tbe = atof(argv[6]);
double Tao = atof(argv[7]);
double Tco = atof(argv[8]);
double Tbo = atof(argv[9]);
double EpsilonR = atof(argv[10]);
double EpsilonM = atof(argv[11]);
double M = atof(argv[12]);
double W = atof(argv[13]);
double Mu = atof(argv[14]);
// Set up data.
double *Es = malloc(num_dos * sizeof(double));
Environment *env = malloc(sizeof(Environment));
env->Tae = Tae;
env->Tce = Tce;
env->Tbe = Tbe;
env->Tao = Tao;
env->Tco = Tco;
env->Tbo = Tbo;
env->EpsilonM = EpsilonM;
env->EpsilonR = EpsilonR;
env->M = M;
env->W = W;
env->Mu = Mu;
// Calculate DOS.
double *dos_vals = DosValues(env, n, Es, num_dos);
// Write out DOS.
int write_err = write_dos_vals(out_path, num_dos, Es, dos_vals);
if (write_err != 0) {
printf("Error writing DOS values\n");
}
// Cleanup.
free(dos_vals);
free(Es);
return 0;
}
int write_dos_vals(char *outPath, int num_dos, double *Es, double *dos_vals) {
FILE *fp = fopen(outPath, "w");
if (fp == NULL) {
return 1;
}
// Write header.
fprintf(fp, "E\tDOS\n");
// Write DOS data.
int i;
for (i = 0; i < num_dos; i++) {
fprintf(fp, "%.10f\t%.10f\n", Es[i], dos_vals[i]);
}
fclose(fp);
return 0;
}
| {
"alphanum_fraction": 0.5581730769,
"avg_line_length": 26.6666666667,
"ext": "c",
"hexsha": "915af309974fc3b7d1d10233a31db98e53edd355",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-18T15:11:23.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-18T15:11:23.000Z",
"max_forks_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tflovorn/vo2mft",
"max_forks_repo_path": "tetra_dos/RunDosValues.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tflovorn/vo2mft",
"max_issues_repo_path": "tetra_dos/RunDosValues.c",
"max_line_length": 137,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "734f691ba2dd245601bf3835be481e2f061723bc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tflovorn/vo2mft",
"max_stars_repo_path": "tetra_dos/RunDosValues.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 712,
"size": 2080
} |
#ifndef LAPACKWRAPPER_H
#define LAPACKWRAPPER_H
#include <vector>
extern "C" {
// void dbdsqr_(char *uplo, int *n, int *ncvt, int *nru, int *ncc, double *D, double *E, double *VT, int *ldvt, double *U, int *ldu, double *C, int *ldc, double *work, int *info);
// void dgetrf_(int *m, int *n, double *A, int *lda, int *ipiv, int *info);
// void dgetrs_(char *trans, int *n, int *nrhs, double *A, int *lda, int *ipiv, double *B, int *ldb, int *info);
// void dgetri_(int *n, double *A, int *lda, int *ipiv, double *work, int *lwork, int *info);
// void dgehrd_(int *n, int*ilo, int *ihi, double *A, int *lda, double *tau, double *work, int *lwork, int *info);
// void dhseqr_(char *job, char *compz, int* n, int* ilo, int *ihi, double *H, int *ldh, double *WR, double *WI, double *Z, int *ldz, double *work, int *lwork, int *info);
// void dorghr_(int *n, int *ilo, int *ihi, double *A, int *lda, double *tau, double *work, int *lwork, int *info);
// void dtrsyl_(char *trana, char *tranb, int *isgn, int *m, int *n, double *A, int *lda, double *B, int *ldb, double *C, int *ldc, double *scale, int *info);
#include <lapack.h>
#include <cblas.h>
}
//---------------------------------------------------------------------------
// LAPACK FUNCTIONS
//---------------------------------------------------------------------------
// Compute the bidiagonal SVD
int cdbdsqr(char uplo, int n, int ncvt, int nru, int ncc,
double *D, double *E, double *VT, int ldvt,
double *U, int ldu, double *C, int ldc);
// Compute LU factorization of A
int cdgetrf(int m, int n, double *A, int lda, int *ipiv);
// Solve linear system from LU factorization from cdgetrf
int cdgetrs(char trans, int n, int nrhs, double *A, int lda, int *ipiv, double *B, int ldb);
// Invert matrix given the LU factorization from dgetrf_
int cdgetri(int n, double *A, int lda, int *ipiv);
//-----------------------------------------------------------------
// Computing the Schur Decompotision to apply preconditioner
// --- 1. Reduce to upper Hessenberg using cdgehrd
// --- 2. Generate Orthogonal Matrix using cdorghr
// --- 3. Compute Schur decomposition of Hessenberg Matrix using cdorghr
//----------------------------------------------------------------
// Reduce matrix to upper Hessenberg form
int cdgehrd(int n, int ilo, int ihi, double *A, int lda, double *tau);
// Schur decomposition of a Hessenberg matrix
int cdhseqr(char job, char compz, int n, int ilo, int ihi, double *H, int ldh, double *WR, double *WI, double *Z, int ldz);
// Generate the orthogonal matrix Q implictly created in dgehrd
int cdorghr(int n, int ilo, int ihi, double *A, int lda, double *tau);
// Solve Sylvester System
int cdtrsyl(char trana, char tranb, int isgn, int m, int n, double *A, int lda, double *B, int ldb, double *C, int ldc, double scale);
//-----------------------------------------------------------------------------------
// C++ Class interfaces for LAPACK FUNCTIONS
//-----------------------------------------------------------------------------------
void Print(const std::string str, const std::vector<int> &size, const double *A);
void Transpose(std::vector<int> &size, double *A, double *AT);
// LU decomposition
class LU{
private:
// Data is stored column-major fashion
double *data;
int *ipiv;
public:
std::vector<int> size; // (number of rows, number of cols)
LU(const int m_, const int n_, const double *data_);
~LU();
void Factor();
void SetData(const double *data_);
void Solve(const int mb, const int nb, double *B, bool trans);
void GetInverse(const int m, const int n, double *invA);
void PrintLU();
};
// Schur Decomposition
class Schur{
private:
double *Qdata, *Tdata;
public:
std::vector<int> size;
Schur(const int m_, const int n_, const double *data);
~Schur();
void Factor();
double* Q() const;
double* T() const;
void PrintQ();
void PrintT();
};
#endif | {
"alphanum_fraction": 0.5841683367,
"avg_line_length": 42.4680851064,
"ext": "h",
"hexsha": "966d0ffc140206b86c468799ccc6eac2d1075c31",
"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": "105537eccb8a31e3171eea2168a680d06756b884",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mjrodriguez/qwiklapack",
"max_forks_repo_path": "include/lapackwrapper.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "105537eccb8a31e3171eea2168a680d06756b884",
"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": "mjrodriguez/qwiklapack",
"max_issues_repo_path": "include/lapackwrapper.h",
"max_line_length": 183,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "105537eccb8a31e3171eea2168a680d06756b884",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mjrodriguez/qwiklapack",
"max_stars_repo_path": "include/lapackwrapper.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1148,
"size": 3992
} |
/* -*- linux-c -*- */
/* cluster.c
Copyright (C) 2002-2004 John M. Fregeau
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <getopt.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_roots.h>
#include "fewbody.h"
#include "cluster.h"
/* print the usage */
void print_usage(FILE *stream)
{
fprintf(stream, "USAGE:\n");
fprintf(stream, " cluster [options...]\n");
fprintf(stream, "\n");
fprintf(stream, "OPTIONS:\n");
fprintf(stream, " -n --n <n> : set number of stars in cluster [%d]\n", FB_N);
fprintf(stream, " -m --m <m/MSUN> : set mass of each star [%.6g]\n", FB_M/FB_CONST_MSUN);
fprintf(stream, " -r --r <r/RSUN> : set radius of each star [%.6g]\n", FB_R/FB_CONST_RSUN);
fprintf(stream, " -S --sigma <sigma/(km/s)> : set central velocity dispersion [%.6g]\n", FB_SIGMA/1.0e5);
fprintf(stream, " -T --rmax <rmax/PARSEC> : set truncation radius [%.6g]\n", FB_RMAX/FB_CONST_PARSEC);
fprintf(stream, " -t --tstop <tstop/t_dyn> : set stopping time [%.6g]\n", FB_TSTOP);
fprintf(stream, " -P --tphysstop <tphysstop/yr> : set physical stopping time [%.6g]\n", FB_TPHYSSTOP/FB_CONST_YR);
fprintf(stream, " -D --dt <dt/t_dyn> : set approximate output dt [%.6g]\n", FB_DT);
fprintf(stream, " -c --tcpustop <tcpustop/sec> : set cpu stopping time [%.6g]\n", FB_TCPUSTOP);
fprintf(stream, " -A --absacc <absacc> : set integrator's absolute accuracy [%.6g]\n", FB_ABSACC);
fprintf(stream, " -R --relacc <relacc> : set integrator's relative accuracy [%.6g]\n", FB_RELACC);
fprintf(stream, " -N --ncount <ncount> : set number of integration steps between calls\n");
fprintf(stream, " to fb_classify() [%d]\n", FB_NCOUNT);
fprintf(stream, " -z --tidaltol <tidaltol> : set tidal tolerance [%.6g]\n", FB_TIDALTOL);
fprintf(stream, " -x --fexp <f_exp> : set expansion factor of merger product [%.6g]\n", FB_FEXP);
fprintf(stream, " -k --ks : turn K-S regularization on or off [%d]\n", FB_KS);
fprintf(stream, " -s --seed : set random seed [%ld]\n", FB_SEED);
fprintf(stream, " -d --debug : turn on debugging\n");
fprintf(stream, " -V --version : print version info\n");
fprintf(stream, " -h --help : display this help text\n");
}
/* calculate the units used (N-body units) */
void calc_units(fb_hier_t hier, fb_units_t *units)
{
int i, j, k;
double petot, ketot, r[3];
/* the unit of mass is defined so that M_tot=1 */
units->m = 0.0;
for (i=0; i<hier.nstar; i++) {
units->m += hier.hier[hier.hi[1]+i].m;
}
/* calculate total potential and kinetic energy */
petot = 0.0;
for (i=0; i<hier.nstar-1; i++) {
for (j=i+1; j<hier.nstar; j++) {
for (k=0; k<3; k++) {
r[k] = hier.hier[hier.hi[1]+j].x[k] - hier.hier[hier.hi[1]+i].x[k];
}
petot += - FB_CONST_G * hier.hier[hier.hi[1]+i].m * hier.hier[hier.hi[1]+j].m / fb_mod(r);
}
}
ketot = 0.0;
for (i=0; i<hier.nstar; i++) {
ketot += 0.5 * hier.hier[hier.hi[1]+i].m * fb_dot(hier.hier[hier.hi[1]+i].v, hier.hier[hier.hi[1]+i].v);
}
/* the unit of energy is defined so that E=-1/4 */
units->E = -4.0 * (petot + ketot);
/* with G=1, all other units are derived */
units->t = FB_CONST_G * pow(units->m, 2.5) * pow(units->E, -1.5);
units->l = FB_CONST_G * fb_sqr(units->m) / units->E;
units->v = units->l / units->t;
}
/* f_0-f(v/v_esc) for the Plummer model */
double fv(double v, void *params)
{
double f;
f = ((double *)params)[0];
return(f - 512.0/(7.0*FB_CONST_PI) * (sqrt(1.0-fb_sqr(v))*(-7.0*v/256.0 + 121.0*fb_cub(v)/384.0 - 263.0*fb_sqr(v)*fb_cub(v)/480.0 + 31.0*v*fb_sqr(fb_cub(v))/80.0 - fb_cub(fb_cub(v))/10.0) + 7.0*asin(v)/256.0));
}
/* get speed from Plummer distribution */
double vf(double f)
{
int status, iter;
double v, params[1];
gsl_function F;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
/* set up the root solver */
F.function = &fv;
F.params = ¶ms;
/* set the parameters */
params[0] = f;
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc(T);
gsl_root_fsolver_set(s, &F, 0.0, 1.0);
/* get v/v_esc by root-finding */
iter = 0;
do {
iter++;
gsl_root_fsolver_iterate(s);
status = gsl_root_test_interval(gsl_root_fsolver_x_lower(s), gsl_root_fsolver_x_upper(s), \
FB_ROOTSOLVER_ABS_ACC, FB_ROOTSOLVER_REL_ACC);
} while (status == GSL_CONTINUE && iter < FB_ROOTSOLVER_MAX_ITER);
if (iter >= FB_ROOTSOLVER_MAX_ITER) {
fprintf(stderr, "Root finder failed to converge.\n");
exit(1);
}
/* we've got the root */
v = gsl_root_fsolver_root(s);
/* free memory associated with root solver */
gsl_root_fsolver_free(s);
return(v);
}
/* the main attraction */
int main(int argc, char *argv[])
{
int i, j, n;
unsigned long int seed;
double tphysstop, m, r, Ei, Li[3], Lint[3], t, M, a, sigma, rmax, Xmax, radius, v, theta, phi, xcm[3], vcm[3];
fb_hier_t hier;
fb_input_t input;
fb_ret_t retval;
fb_units_t units;
char string1[FB_MAX_STRING_LENGTH], string2[FB_MAX_STRING_LENGTH];
gsl_rng *rng;
const gsl_rng_type *rng_type=gsl_rng_mt19937;
const char *short_opts = "n:m:r:S:T:t:P:D:c:A:R:N:z:x:k:s:dVh";
const struct option long_opts[] = {
{"n", required_argument, NULL, 'n'},
{"m", required_argument, NULL, 'm'},
{"r", required_argument, NULL, 'r'},
{"sigma", required_argument, NULL, 'S'},
{"rmax", required_argument, NULL, 'T'},
{"tstop", required_argument, NULL, 't'},
{"tphysstop", required_argument, NULL, 'P'},
{"dt", required_argument, NULL, 'D'},
{"tcpustop", required_argument, NULL, 'c'},
{"absacc", required_argument, NULL, 'A'},
{"relacc", required_argument, NULL, 'R'},
{"ncount", required_argument, NULL, 'N'},
{"tidaltol", required_argument, NULL, 'z'},
{"fexp", required_argument, NULL, 'x'},
{"ks", required_argument, NULL, 'k'},
{"seed", required_argument, NULL, 's'},
{"debug", no_argument, NULL, 'd'},
{"version", no_argument, NULL, 'V'},
{"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0}
};
/* set parameters to default values */
n = FB_N;
m = FB_M;
r = FB_R;
sigma = FB_SIGMA;
rmax = FB_RMAX;
input.ks = FB_KS;
input.tstop = FB_TSTOP;
tphysstop = FB_TPHYSSTOP;
input.Dflag = 0;
input.dt = FB_DT;
input.tcpustop = FB_TCPUSTOP;
input.absacc = FB_ABSACC;
input.relacc = FB_RELACC;
input.ncount = FB_NCOUNT;
input.tidaltol = FB_TIDALTOL;
input.fexp = FB_FEXP;
seed = FB_SEED;
fb_debug = FB_DEBUG;
while ((i = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1) {
switch (i) {
case 'n':
n = atoi(optarg);
break;
case 'm':
m = atof(optarg) * FB_CONST_MSUN;
break;
case 'r':
r = atof(optarg) * FB_CONST_RSUN;
break;
case 'S':
sigma = atof(optarg) * 1.0e5;
break;
case 'T':
rmax = atof(optarg) * FB_CONST_PARSEC;
break;
case 't':
input.tstop = atof(optarg);
break;
case 'P':
tphysstop = atof(optarg) * FB_CONST_YR;
break;
case 'D':
input.Dflag = 1;
input.dt = atof(optarg);
break;
case 'c':
input.tcpustop = atof(optarg);
break;
case 'A':
input.absacc = atof(optarg);
break;
case 'R':
input.relacc = atof(optarg);
break;
case 'N':
input.ncount = atoi(optarg);
break;
case 'z':
input.tidaltol = atof(optarg);
break;
case 'x':
input.fexp = atof(optarg);
break;
case 'k':
input.ks = atoi(optarg);
break;
case 's':
seed = atol(optarg);
break;
case 'd':
fb_debug = 1;
break;
case 'V':
fb_print_version(stdout);
return(0);
case 'h':
fb_print_version(stdout);
fprintf(stdout, "\n");
print_usage(stdout);
return(0);
default:
break;
}
}
/* check to make sure there was nothing crazy on the command line */
if (optind < argc) {
print_usage(stdout);
return(1);
}
/* set up parameters for Plummer model */
M = ((double) n) * m;
a = FB_CONST_G * M / (6.0*fb_sqr(sigma));
Xmax = pow(1.0+fb_sqr(a/rmax), -1.5);
/* initialize a few things for integrator */
t = 0.0;
hier.nstarinit = n;
hier.nstar = n;
fb_malloc_hier(&hier);
fb_init_hier(&hier);
/* put stuff in log entry */
snprintf(input.firstlogentry, FB_MAX_LOGENTRY_LENGTH, " command line:");
for (i=0; i<argc; i++) {
snprintf(&(input.firstlogentry[strlen(input.firstlogentry)]),
FB_MAX_LOGENTRY_LENGTH-strlen(input.firstlogentry), " %s", argv[i]);
}
snprintf(&(input.firstlogentry[strlen(input.firstlogentry)]),
FB_MAX_LOGENTRY_LENGTH-strlen(input.firstlogentry), "\n");
/* print out values of paramaters */
fprintf(stderr, "PARAMETERS:\n");
fprintf(stderr, " ks=%d seed=%ld\n", input.ks, seed);
fprintf(stderr, " M=%.6g MSUN sigma=%.6g km/s a=%.6g PARSEC rmax=%.6g PARSEC rmax/a=%.6g\n",
M/FB_CONST_MSUN, sigma/1.0e5, a/FB_CONST_PARSEC, rmax/FB_CONST_PARSEC, rmax/a);
fprintf(stderr, " n=%d m=%.6g MSUN r=%.6g RSUN tstop=%.6g tphysstop=%.6g yr tcpustop=%.6g\n", \
n, m/FB_CONST_MSUN, r/FB_CONST_RSUN, input.tstop, tphysstop/FB_CONST_YR, input.tcpustop);
fprintf(stderr, " tidaltol=%.6g abs_acc=%.6g rel_acc=%.6g ncount=%d fexp=%.6g\n\n", \
input.tidaltol, input.absacc, input.relacc, input.ncount, input.fexp);
/* initialize GSL rng */
gsl_rng_env_setup();
rng = gsl_rng_alloc(rng_type);
gsl_rng_set(rng, seed);
/* prepare to calculate the center of mass position and velocity */
for (i=0; i<3; i++) {
xcm[i] = 0.0;
vcm[i] = 0.0;
}
/* give the objects some properties */
for (j=0; j<hier.nstar; j++) {
hier.hier[hier.hi[1]+j].ncoll = 1;
hier.hier[hier.hi[1]+j].id[0] = j;
snprintf(hier.hier[hier.hi[1]+j].idstring, FB_MAX_STRING_LENGTH, "%d", j);
hier.hier[hier.hi[1]+j].n = 1;
hier.hier[hier.hi[1]+j].obj[0] = NULL;
hier.hier[hier.hi[1]+j].obj[1] = NULL;
hier.hier[hier.hi[1]+j].Eint = 0.0;
hier.hier[hier.hi[1]+j].Lint[0] = 0.0;
hier.hier[hier.hi[1]+j].Lint[1] = 0.0;
hier.hier[hier.hi[1]+j].Lint[2] = 0.0;
hier.hier[hier.hi[1]+j].m = m;
hier.hier[hier.hi[1]+j].R = r;
/* draw radius from Plummer distribution */
radius = a / sqrt(pow(Xmax*gsl_rng_uniform(rng), -2.0/3.0)-1.0);
theta = acos(2.0 * gsl_rng_uniform(rng) - 1.0);
phi = 2.0 * FB_CONST_PI * gsl_rng_uniform(rng);
hier.hier[hier.hi[1]+j].x[0] = radius * sin(theta) * cos(phi);
hier.hier[hier.hi[1]+j].x[1] = radius * sin(theta) * sin(phi);
hier.hier[hier.hi[1]+j].x[2] = radius * cos(theta);
/* draw velocity from Plummer distribution */
v = vf(gsl_rng_uniform(rng)) * sqrt(2.0*FB_CONST_G*M/(a*sqrt(1.0+fb_sqr(radius/a))));
theta = acos(2.0 * gsl_rng_uniform(rng) - 1.0);
phi = 2.0 * FB_CONST_PI * gsl_rng_uniform(rng);
hier.hier[hier.hi[1]+j].v[0] = v * sin(theta) * cos(phi);
hier.hier[hier.hi[1]+j].v[1] = v * sin(theta) * sin(phi);
hier.hier[hier.hi[1]+j].v[2] = v * cos(theta);
/* calculate center of mass position and velocity */
for (i=0; i<3; i++) {
xcm[i] += hier.hier[hier.hi[1]+j].x[i] / ((double) n);
vcm[i] += hier.hier[hier.hi[1]+j].v[i] / ((double) n);
}
}
/* transform to center of mass frame */
for (j=0; j<hier.nstar; j++) {
for (i=0; i<3; i++) {
hier.hier[hier.hi[1]+j].x[i] -= xcm[i];
hier.hier[hier.hi[1]+j].v[i] -= vcm[i];
}
}
/* get the units and normalize */
calc_units(hier, &units);
fb_normalize(&hier, units);
/* reset input.tstop if necessary, based on the value of tphysstop */
if (tphysstop/units.t < input.tstop) {
input.tstop = tphysstop/units.t;
fb_dprintf("decreasing tstop in accord with tphysstop: tstop=%.6g\n", input.tstop);
}
fb_dprintf("virial ratio: q=%.6g\n", -fb_ketot(&(hier.hier[hier.hi[1]]), hier.nstar)/fb_petot(&(hier.hier[hier.hi[1]]), hier.nstar));
fprintf(stderr, "UNITS:\n");
fprintf(stderr, " v=%.6g km/s l=%.6g AU t=t_dyn=%.6g yr\n", \
units.v/1.0e5, units.l/FB_CONST_AU, units.t/FB_CONST_YR);
fprintf(stderr, " M=%.6g M_sun E=%.6g erg\n\n", units.m/FB_CONST_MSUN, units.E);
/* calculate the initial energy and angular momentum, for bookkeeping */
Ei = fb_petot(&(hier.hier[hier.hi[1]]), hier.nstar) + fb_ketot(&(hier.hier[hier.hi[1]]), hier.nstar) +
fb_einttot(&(hier.hier[hier.hi[1]]), hier.nstar);
fb_angmom(&(hier.hier[hier.hi[1]]), hier.nstar, Li);
fb_angmomint(&(hier.hier[hier.hi[1]]), hier.nstar, Lint);
for (j=0; j<3; j++) {
Li[j] += Lint[j];
}
/* integrate along */
fb_dprintf("calling fewbody()...\n");
/* call fewbody! */
retval = fewbody(input, &hier, &t);
/* print information to screen */
fprintf(stderr, "OUTCOME:\n");
if (retval.retval == 1) {
fprintf(stderr, " encounter complete: t=%.6g (%.6g yr) %s (%s)\n\n",
t, t * units.t/FB_CONST_YR,
fb_sprint_hier(hier, string1),
fb_sprint_hier_hr(hier, string2));
} else {
fprintf(stderr, " encounter NOT complete: t=%.6g (%.6g yr) %s (%s)\n\n",
t, t * units.t/FB_CONST_YR,
fb_sprint_hier(hier, string1),
fb_sprint_hier_hr(hier, string2));
}
fb_dprintf("there were %ld integration steps\n", retval.count);
fb_dprintf("fb_classify() was called %ld times\n", retval.iclassify);
fprintf(stderr, "FINAL:\n");
fprintf(stderr, " t_final=%.6g (%.6g yr) t_cpu=%.6g s\n", \
t, t*units.t/FB_CONST_YR, retval.tcpu);
fprintf(stderr, " L0=%.6g DeltaL/L0=%.6g DeltaL=%.6g\n", fb_mod(Li), retval.DeltaLfrac, retval.DeltaL);
fprintf(stderr, " E0=%.6g DeltaE/E0=%.6g DeltaE=%.6g\n", Ei, retval.DeltaEfrac, retval.DeltaE);
fprintf(stderr, " Rmin=%.6g (%.6g RSUN) Rmin_i=%d Rmin_j=%d\n", \
retval.Rmin, retval.Rmin*units.l/FB_CONST_RSUN, retval.Rmin_i, retval.Rmin_j);
fprintf(stderr, " Nosc=%d (%s)\n", retval.Nosc, (retval.Nosc>=1?"resonance":"non-resonance"));
/* free GSL stuff */
gsl_rng_free(rng);
/* free our own stuff */
fb_free_hier(hier);
/* done! */
return(0);
}
| {
"alphanum_fraction": 0.6272926362,
"avg_line_length": 33.3607305936,
"ext": "c",
"hexsha": "c8f3d1f8bd175a8ec2e0a3af02c0698dc93d7964",
"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": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_forks_repo_licenses": [
"PSF-2.0"
],
"max_forks_repo_name": "gnodvi/cosmos",
"max_forks_repo_path": "ext/fewbod/fewbody-0.26/cluster.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z",
"max_issues_repo_licenses": [
"PSF-2.0"
],
"max_issues_repo_name": "gnodvi/cosmos",
"max_issues_repo_path": "ext/fewbod/fewbody-0.26/cluster.c",
"max_line_length": 211,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c",
"max_stars_repo_licenses": [
"PSF-2.0"
],
"max_stars_repo_name": "gnodvi/cosmos",
"max_stars_repo_path": "ext/fewbod/fewbody-0.26/cluster.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5080,
"size": 14612
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.