Search is not available for this dataset
text string | meta dict |
|---|---|
/****************************************************************
wigner_gsl.h / wigner_gsl_twice.h
Defines Wigner coupling and recoupling symbols as wrappers for GSL
angular momentum functions:
- wigner_gsl.h -- takes HalfInt angular momentum arguments (RECOMMENDED)
- wigner_gsl_twice.h -- takes integer "twice value" angular momentum arguments
Naming convention:
- Function names *not* ending in '2' accept HalfInt arguments J.
- Function names ending in '2' accept integer arguments 2*J.
See, e.g., appendix to de Shalit and Talmi for underlying formulas.
DOCUMENTATION: See wigner_gsl.h (rather than wigner_gsl_twice.h) for
more complete function comments.
Language: C++
Mark A. Caprio
University of Notre Dame
+ 02/16/10 (mac): Created.
+ 11/13/15 (mac): Add unitary 6J for (12)3-(13)2 recoupling
and Racah reduction factor.
+ 02/27/16 (mac): Update includes for restructured header files.
+ 03/8/16 (mac): Enclose in namespace.
+ 06/8/16 (mac): Update #define guard directive.
+ 06/21/16 (mac): Remove Racah reduction factor. Update comments.
+ 10/18/16 (mac): Update Unitary6J comment. Rename wigner2_gsl.h to
wigner_gsl_twice.h.
+ 04/28/18 (mac): Restore missing Hat2 and ParitySign2 to
wigner_gsl_twice.h.
+ 04/10/20 (pjf): Replace assertions with exceptions.
****************************************************************/
#ifndef WIGNER2_GSL_H_
#define WIGNER2_GSL_H_
#include <stdexcept>
#include <gsl/gsl_sf_coupling.h>
#include "am.h"
namespace am {
// angular momentum hat symbol
inline
double Hat2(int two_j)
{
return sqrt(static_cast<double>(two_j+1));
}
// phase sign (-)^sum
inline
int ParitySign2(int two_sum)
{
if ((two_sum%2)!=0) throw std::domain_error("two_sum not even");
int remainder = abs(two_sum/2) % 2;
int sign = 1 - 2*remainder;
return sign;
}
// Wigner3J(ja,jb,jc,ma,mb,mc)
// returns Wigner 3-J symbol
// wrapper for gsl_sf_coupling_3j
inline
double Wigner3J2(
int two_ja, int two_jb, int two_jc,
int two_ma, int two_mb, int two_mc
)
{
return gsl_sf_coupling_3j(
two_ja, two_jb, two_jc,
two_ma, two_mb, two_mc
);
}
// ClebschGordan(ja,ma,jb,mb,jc,mc)
// returns Clebsch-Gordan coefficient
// wrapper for gsl_sf_coupling_3j
inline
double ClebschGordan2(
int two_ja, int two_ma,
int two_jb, int two_mb,
int two_jc, int two_mc
)
{
return Hat2(two_jc)*ParitySign2(two_ja-two_jb+two_mc)
*gsl_sf_coupling_3j(
two_ja, two_jb, two_jc,
two_ma, two_mb, -two_mc
);
}
// Wigner6J(ja,jb,jc,jd,je,jf)
// returns Wigner 6-J symbol
// wrapper for gsl_sf_coupling_6j
inline
double Wigner6J2(
int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf
)
{
return gsl_sf_coupling_6j(
two_ja, two_jb, two_jc,
two_jd, two_je, two_jf
);
}
// Unitary6J(ja,jb,jc,jd,je,jf)
// wrapper for gsl_sf_coupling_6j
// returns unitary recoupling symbol for (12)3-1(23) recoupling
inline
double Unitary6J2(
int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf
)
{
return ParitySign2(two_ja+two_jb+two_jd+two_je)*Hat2(two_jc)*Hat2(two_jf)*gsl_sf_coupling_6j(
two_ja, two_jb, two_jc,
two_jd, two_je, two_jf
);
}
// Wigner9J(ja,jb,jc,jd,je,jf,jg,jh,ji)
// returns Wigner 9-J symbol
// wrapper for gsl_sf_coupling_9j
inline
double Wigner9J2(
int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
int two_jg, int two_jh, int two_ji
)
{
return gsl_sf_coupling_9j(
two_ja, two_jb, two_jc,
two_jd, two_je, two_jf,
two_jg, two_jh, two_ji
);
}
// Unitary9J(ja,jb,jc,jd,je,jf,jg,jh,ji)
// returns unitary 9-J symbol
// wrapper for gsl_sf_coupling_9j
inline
double Unitary9J2(
int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
int two_jg, int two_jh, int two_ji
)
{
return Hat2(two_jc)*Hat2(two_jf)*Hat2(two_jg)*Hat2(two_jh)
*gsl_sf_coupling_9j(
two_ja, two_jb, two_jc,
two_jd, two_je, two_jf,
two_jg, two_jh, two_ji
);
}
} // namespace
#endif
| {
"alphanum_fraction": 0.6283707229,
"avg_line_length": 25.2171428571,
"ext": "h",
"hexsha": "af9fde39622925fa7625480db0a9e5e1d7c92081",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2019-08-09T02:14:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-24T20:23:16.000Z",
"max_forks_repo_head_hexsha": "e2c715513ca1b9df98e71b78084914f00a50f8dc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mark-caprio/am",
"max_forks_repo_path": "wigner_gsl_twice.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e2c715513ca1b9df98e71b78084914f00a50f8dc",
"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": "mark-caprio/am",
"max_issues_repo_path": "wigner_gsl_twice.h",
"max_line_length": 97,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e2c715513ca1b9df98e71b78084914f00a50f8dc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mark-caprio/am",
"max_stars_repo_path": "wigner_gsl_twice.h",
"max_stars_repo_stars_event_max_datetime": "2020-03-30T18:34:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-03-30T18:34:33.000Z",
"num_tokens": 1496,
"size": 4413
} |
/* dwt_undec.c
* Paul Demorest, 2007/10
*
* Undecimated wavelet transform and inverse. These
* do the usual wavelet filter tree, but don't decimate
* by 2 after each step. This makes the transform
* translation-invariant (to translations which are
* integer numbers of samples anyways).
*
* Ends up with n*log2(n) sized array, from size n input.
*
* Wavelet coeffs g and h need to be externally supplied.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_wavelet.h>
/* Do one UDWT step on input data, out-of-place (original
* data array is unaltered).
* Vars:
* in pointer to input data (n doubles)
* outl pointer to low-pass output data (n doubles)
* outh pointer to high-pass output data (n doubles)
* n size of in/out
* h Wavelet coeffs, low-pass (nc doubles)
* g Wavelet coeffs, high-pass (nc doubles)
* nc size of h/g
* s scale (filters expand by 2^s)
*/
void udwt_forward_step(double *in, double *outl, double *outh, size_t n,
const double h[], const double g[], size_t nc, int s) {
int i,j,idx;
/* Zero output array */
for (i=0; i<n; i++) { outl[i]=0.0; outh[i]=0.0; }
/* Filter */
for (i=0; i<n; i++) {
for (j=0; j<nc; j++) {
idx = (i + (1<<s)*j) % n;
outl[i] += h[j] * in[idx];
outh[i] += g[j] * in[idx];
}
}
}
/* Inverse UDWT step similar to above. Remember to stay
* consistent about which half contains h and which
* contains g chunks!
*/
void udwt_inverse_step(double *inl, double *inh, double *out, size_t n,
const double h[], const double g[], size_t nc, int s) {
int i,j,idx;
/* Zero output */
for (i=0; i<n; i++) { out[i]=0.0; }
/* filter, add */
for (i=0; i<n; i++) {
for (j=0; j<nc; j++) {
idx = (i - (1<<s)*j) % n;
out[i] += h[j] * inl[idx];
out[i] += g[j] * inh[idx];
}
}
/* Inverse needs a rescaling */
for (i=0; i<n; i++) { out[i] *= 0.5; }
}
/* Return integer log 2 of input.
* Error if not a power of 2?
*/
static int log2i(int n) {
int rv=0;
while ((n>>rv)>1) { rv++; }
return(rv);
}
/* Do a undec wavelet transform on input data n.
* Vars:
* in pointer to input data (n doubles)
* out pointer to output data (n*log2(n) doubles)
* n size of in
* h Wavelet coeffs, high-pass (nc doubles)
* g Wavelet coeffs, low-pass (nc doubles)
* nc size of h/g
*
* This can be called using a GSL wavelet definition struct like:
* gsl_wavelet *w;
* (etc, init wavelet...)
* dwt_undec_transform(in, &out, n, w->h1, w->g1, w->nc);
*/
int _dwt_undec_transform(double *in, double *out, size_t n,
const double h[], const double g[], size_t nc) {
/* Determine number of levels of decomp */
int nl=0;
nl = log2i(n);
/* maybe do some value checks on n, nl .. */
/* Temporary low-pass outputs */
double *tmp1 = (double *)malloc(sizeof(double)*n);
double *tmp2 = (double *)malloc(sizeof(double)*n);
/* Loop to do dwts */
int i;
double *curi, *curol, *curoh, *swp;
curi = in;
curol = tmp1;
curoh = out;
for (i=0; i<nl; i++) {
udwt_forward_step(curi, curol, curoh, n, h, g, nc, i);
if (i==0) { curi=tmp2; }
swp = curi;
curi = curol;
curol = swp;
curoh = &(out[(i+1)*n]);
}
free(tmp1);
free(tmp2);
return(nl);
}
/* Inverse, similar to above, but switch in/out
* This can be called using a GSL wavelet definition struct like:
* gsl_wavelet *w;
* (etc, init wavelet...)
* dwt_undec_inverse(in, out, n, w->h2, w->g2, w->nc);
*/
int _dwt_undec_inverse(double *in, double *out, size_t n,
const double h[], const double g[], size_t nc) {
/* Determine number of levels of decomp */
int nl=0;
nl = log2i(n);
/* maybe do some value checks on n, nl .. */
/* Temporary low-pass outputs */
int i;
double *tmp1 = (double *)malloc(sizeof(double)*n);
double *tmp2 = (double *)malloc(sizeof(double)*n);
for (i=0; i<n; i++) { tmp1[i]=0.0; }
/* Loop to do dwts */
double *curil, *curih, *curo, *swp;
curil = tmp1;
curih = &in[(nl-1)*n];
curo = tmp2;
for (i=nl-1; i>=0; i--) {
udwt_inverse_step(curil, curih, curo, n, h, g, nc, i);
swp = curil;
curil = curo;
curo = swp;
curih = &in[(i-1)*n];
}
/* We end up with final output in curil */
for (i=0; i<n; i++) { out[i] = curil[i]; }
free(tmp1);
free(tmp2);
return(nl);
}
/* Wrappers using GSL wavelet definitions */
int dwt_undec_transform(double *in, double *out, size_t n, const gsl_wavelet *w) {
return _dwt_undec_transform(in, out, n, w->h1, w->g1, w->nc);
}
int dwt_undec_inverse(double *in, double *out, size_t n, const gsl_wavelet *w) {
return _dwt_undec_inverse(in, out, n, w->h2, w->g2, w->nc);
}
| {
"alphanum_fraction": 0.5688852923,
"avg_line_length": 27.4611111111,
"ext": "c",
"hexsha": "39601933d7f8a82cbe845f79879c52e03d38a6ce",
"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": "453c4dc05b8e901ea661cd02d4f0a30665dcaf35",
"max_forks_repo_licenses": [
"AFL-2.1"
],
"max_forks_repo_name": "xuanyuanstar/psrchive_CDFT",
"max_forks_repo_path": "Util/genutil/dwt_undec.c",
"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": "Util/genutil/dwt_undec.c",
"max_line_length": 82,
"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": "Util/genutil/dwt_undec.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1614,
"size": 4943
} |
/*****************************************************************************
*
* Rokko: Integrated Interface for libraries of eigenvalue decomposition
*
* Copyright (C) 2012-2020 by Rokko Developers https://github.com/t-sakashita/rokko
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*****************************************************************************/
#ifndef ROKKO_CSCALAPACK_H
#define ROKKO_CSCALAPACK_H
#include <rokko/config.h>
#include <lapacke.h>
#ifdef __cplusplus
extern "C" {
#endif
int cscalapack_descinit(int* desc, int m, int n, int mb, int nb, int irsrc, int icsrc,
int ictxt, int lld);
int cscalapack_indxg2p(int indxglob, int nb, int iproc, int isrcproc, int nprocs);
int cscalapack_numroc(int n, int nb, int iproc, int isrcproc, int nprocs);
double cscalapack_pdelget(char scope, char top, const double* A, int ia, int ja, const int* descA);
void cscalapack_pdelset(double* A, int ia, int ja, const int* descA, double alpha);
double cscalapack_pdlamch(int icnt, char cmch);
double cscalapack_pdlange(char norm, int m, int n, const double* A, const int* descA);
double cscalapack_pdlange_work(char norm, int m, int n, const double* A, const int* descA,
double* work);
void cscalapack_pdlaprnt(int m, int n, const double* A, int ia, int ja, const int* descA,
int irprnt, int icprnt, const char* cmatnm, int nout, double* work);
#define CSCALAPACK_PSYEV_DECL(NAMES, NAMEL, TYPE, TYPE_REAL) \
int cscalapack_ ## NAMES ## _work (char jobz, char uplo, int n, \
TYPE* A, int ia, int ja, const int* descA, \
TYPE_REAL* w, TYPE* Z, int iz, int jz, const int* descZ, \
TYPE* work, int lwork); \
int cscalapack_ ## NAMES (char jobz, char uplo, int n, \
TYPE* A, int ia, int ja, const int* descA, \
TYPE_REAL* w, TYPE* Z, int iz, int jz, const int* descZ);
CSCALAPACK_PSYEV_DECL(pssyev, PSSYEV, float, float);
CSCALAPACK_PSYEV_DECL(pdsyev, PDSYEV, double, double);
CSCALAPACK_PSYEV_DECL(pcheev, PCHEEV, lapack_complex_float, float);
CSCALAPACK_PSYEV_DECL(pzheev, PZHEEV, lapack_complex_double, double);
#undef CSCALAPACK_PSYEV_DECL
#define CSCALAPACK_PSYEVD_DECL(NAMES, NAMEL, TYPE, TYPE_REAL) \
int cscalapack_ ## NAMES ## _work (char jobz, char uplo, int n, \
TYPE* A, int ia, int ja, const int* descA, \
TYPE_REAL* w, TYPE* Z, int iz, int jz, const int* descZ, \
TYPE* work, int lwork, int* iwork, int liwork); \
int cscalapack_ ## NAMES (char jobz, char uplo, int n, \
TYPE* A, int ia, int ja, const int* descA, \
TYPE_REAL* w, TYPE* Z, int iz, int jz, const int* descZ);
CSCALAPACK_PSYEVD_DECL(pssyevd, PSSYEVD, float, float);
CSCALAPACK_PSYEVD_DECL(pdsyevd, PDSYEVD, double, double);
CSCALAPACK_PSYEVD_DECL(pcheevd, PCHEEVD, lapack_complex_float, float);
CSCALAPACK_PSYEVD_DECL(pzheevd, PZHEEVD, lapack_complex_double, double);
#undef CSCALAPACK_PSYEVD_DECL
#define CSCALAPACK_PSYEVX_DECL(NAMES, NAMEL, TYPE, TYPE_REAL) \
int cscalapack_ ## NAMES ## _work(char jobz, char range, char uplo, int n, \
TYPE* A, int ia, int ja, const int* descA, \
TYPE_REAL vl, TYPE_REAL vu, int il, int iu, \
TYPE_REAL abstol, int* m, int* nZ, TYPE_REAL* w, TYPE_REAL orfac, \
TYPE* Z, int iz, int jz, const int* descZ, \
TYPE* work, int lwork, int* iwork, int liwork, \
int* ifail, int* iclustr, TYPE_REAL* gap); \
int cscalapack_ ## NAMES (char jobz, char range, char uplo, int n, \
TYPE* A, int ia, int ja, const int* descA, \
TYPE_REAL vl, TYPE_REAL vu, int il, int iu, \
TYPE_REAL abstol, int* m, int* nZ, TYPE_REAL* w, TYPE_REAL orfac, \
TYPE* Z, int iz, int jz, const int* descZ, \
int* ifail, int* iclustr, TYPE_REAL* gap);
CSCALAPACK_PSYEVX_DECL(pssyevx, PSSYEVX, float, float);
CSCALAPACK_PSYEVX_DECL(pdsyevx, PDSYEVX, double, double);
CSCALAPACK_PSYEVX_DECL(pcheevx, PCHEEVX, lapack_complex_float, float);
CSCALAPACK_PSYEVX_DECL(pzheevx, PZHEEVX, lapack_complex_double, double);
#undef CSCALAPACK_PSYEVX_DECL
#ifdef ROKKO_HAVE_SCALAPACK_PDSYEVR
#define CSCALAPACK_PSYEVR_DECL(NAMES, NAMEL, TYPE, TYPE_REAL) \
int cscalapack_## NAMES ##_work(char jobz, char range, char uplo, int n, \
TYPE* A, int ia, int ja, const int* descA, \
TYPE_REAL vl, TYPE_REAL vu, int il, int iu, \
int* m, int* nz, \
TYPE_REAL* w, TYPE* Z, int iz, int jz, const int* descZ, \
TYPE* work, int lwork, int* iwork, int liwork); \
int cscalapack_## NAMES (char jobz, char range, char uplo, int n, \
TYPE* A, int ia, int ja, const int* descA, \
TYPE_REAL vl, TYPE_REAL vu, int il, int iu, \
int* m, int* nz, \
TYPE_REAL* w, TYPE* Z, int iz, int jz, const int* descZ);
CSCALAPACK_PSYEVR_DECL(pssyevr, PSSYEVR, float, float);
CSCALAPACK_PSYEVR_DECL(pdsyevr, PDSYEVR, double, double);
CSCALAPACK_PSYEVR_DECL(pcheevr, PCHEEVR, lapack_complex_float, float);
CSCALAPACK_PSYEVR_DECL(pzheevr, PZHEEVR, lapack_complex_double, double);
#undef CSCALAPACK_PSYEVR_DECL
#endif
float cscalapack_pselget(char scope, char top, const float* A, int ia, int ja, const int* descA);
void cscalapack_pselset(float* A, int ia, int ja, const int* descA, float alpha);
float cscalapack_pslamch(int icnt, char cmch);
float cscalapack_pslange(char norm, int m, int n, const float* A, const int* descA);
float cscalapack_pslange_work(char norm, int m, int n, const float* A, const int* descA,
float* work);
void cscalapack_pslaprnt(int m, int n, const float* A, int ia, int ja, const int* descA,
int irprnt, int icprnt, const char* cmatnm, int nout, float* work);
#define CSCALAPACK_PSTEBZ_DECL(NAMES, NAMEL, TYPE) \
int cscalapack_## NAMES ##_work(int ictxt, char range, char order, int n, \
TYPE vl, TYPE vu, int il, int iu, \
TYPE abstol, const TYPE* d, const TYPE* e, int* m, int* nsplit, \
TYPE* w, int* iblock, int* isplit, \
TYPE* work, int lwork, int* iwork, int liwork); \
int cscalapack_## NAMES (int ictxt, char range, char order, int n, \
TYPE vl, TYPE vu, int il, int iu, \
TYPE abstol, const TYPE* d, const TYPE* e, int* m, int* nsplit, \
TYPE* w, int* iblock, int* isplit);
CSCALAPACK_PSTEBZ_DECL(psstebz, PSSTEBZ, float);
CSCALAPACK_PSTEBZ_DECL(pdstebz, PDSTEBZ, double);
#undef CSCALAPACK_PSTEBZ_DECL
#define CSCALAPACK_PSTEIN_DECL(NAMES, NAMEL, TYPE, TYPE_REAL) \
int cscalapack_## NAMES ##_work(int n, const TYPE_REAL* d, const TYPE_REAL* e, int m, \
TYPE_REAL* w, const int* iblock, const int* isplit, TYPE_REAL orfac, \
TYPE* Z, const int* iZ, const int* jZ, const int* descZ, \
TYPE* work, int lwork, int* iwork, int liwork, \
int* ifail, int* iclustr, TYPE_REAL* gap); \
int cscalapack_## NAMES (int n, const TYPE_REAL* d, const TYPE_REAL* e, int m, \
TYPE_REAL* w, const int* iblock, const int* isplit, TYPE_REAL orfac, \
TYPE* Z, const int* iZ, const int* jZ, const int* descZ, \
int* ifail, int* iclustr, TYPE_REAL* gap);
CSCALAPACK_PSTEIN_DECL(psstein, PSSTEIN, float, float);
CSCALAPACK_PSTEIN_DECL(pdstein, PDSTEIN, double, double);
CSCALAPACK_PSTEIN_DECL(pcstein, PCSTEIN, lapack_complex_float, float);
CSCALAPACK_PSTEIN_DECL(pzstein, PZSTEIN, lapack_complex_double, double);
#undef CSCALAPACK_PSTEIN_DECL
#define CSCALAPACK_PSTEDC_DECL(NAMES, NAMEL, TYPE) \
int cscalapack_## NAMES ##_work(char compz, int n, TYPE* d, TYPE* e, \
TYPE* Q, int iq, int jq, const int* descQ, \
TYPE* work, int lwork, int* iwork, int liwork); \
int cscalapack_## NAMES (char compz, int n, TYPE* d, TYPE* e, \
TYPE* Q, int iq, int jq, const int* descQ);
CSCALAPACK_PSTEDC_DECL(psstedc, PSSTEDC, float);
CSCALAPACK_PSTEDC_DECL(pdstedc, PDSTEDC, double);
#undef CSCALAPACK_PSTEDC_DECL
#ifdef __cplusplus
}
#endif
#endif // ROKKO_CSCALAPACK_H
| {
"alphanum_fraction": 0.5981976041,
"avg_line_length": 48.1428571429,
"ext": "h",
"hexsha": "eb4a14c417604cc729aed5c383f3f2d8fe102e46",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z",
"max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "t-sakashita/rokko",
"max_forks_repo_path": "rokko/cscalapack.h",
"max_issues_count": 514,
"max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9",
"max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "t-sakashita/rokko",
"max_issues_repo_path": "rokko/cscalapack.h",
"max_line_length": 102,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "t-sakashita/rokko",
"max_stars_repo_path": "rokko/cscalapack.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z",
"num_tokens": 2713,
"size": 9099
} |
#pragma once
#include <gsl.h>
#include <memory>
namespace crimson {
class ISolverSetupManager;
/*! \brief A solver setup service interface. */
class ISolverSetupService
{
public:
/*!
* \brief Gets solver setup manager.
*/
virtual gsl::not_null<ISolverSetupManager*> getSolverSetupManager() const = 0;
virtual ~ISolverSetupService() {}
};
} | {
"alphanum_fraction": 0.6846361186,
"avg_line_length": 16.8636363636,
"ext": "h",
"hexsha": "c88748028d702979ca4167f717cfda1703580098",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z",
"max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "carthurs/CRIMSONGUI",
"max_forks_repo_path": "Modules/SolverSetupService/include/ISolverSetupService.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "carthurs/CRIMSONGUI",
"max_issues_repo_path": "Modules/SolverSetupService/include/ISolverSetupService.h",
"max_line_length": 82,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "carthurs/CRIMSONGUI",
"max_stars_repo_path": "Modules/SolverSetupService/include/ISolverSetupService.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z",
"num_tokens": 89,
"size": 371
} |
// 02.05.2021 - Colloid in a fluctuating scalar field
// Davide Venturelli & Benjamin Walter
// Last update 08.11.21
/* COMMENTS:
- Stochastic Runge-Kutta II for colloid evolution, Euler-Maruyama for field evolution (can be enhanced, but the price is O(N) at least. We could even think of anisotropic resolution, i.e. better around the colloid).
- No boundary conditions on the colloid displacement; they only get enforced when locating the nearest site.
- Space is measured in units of the lattice spacing.
- I am saving X(t) in colloid_pos and Y(t) in colloid_msd. Printing only X(t) at the moment.
- Finite size colloid, Gaussian interaction potential.
- Zero set in correspondence of trap center when printing out colloid data.
- Random inizialitazion of the field in Fourier space
- There is no limit on the size of R (other than physical, L/2)
- Compile as $ gcc -o colloid colloid_RF.c -lm -lgsl -lfftw3 -O3 -Wall -Wextra -O3
*/
// LIBRARIES, TYPES, DEFINITIONS
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <time.h>
#include <unistd.h>
#include <fftw3.h>
#define ALLOC(p,n) (p)=malloc( (n) * sizeof(*(p))); if( (p) == NULL){printf("Allocation of '%s' failed. Terminate. \n", #p); exit(2); }
#define CALLOC(p,n) (p)=calloc( (n) , sizeof(*(p))); if( (p) == NULL){printf("Allocation of '%s' failed. Terminate. \n", #p); exit(2); }
//#define long unsigned long // This is to make long hold twice as much
#define DD printf("# Debug: line %d \n",__LINE__);
#define DEBUG (1)
#define EPS 0.0000000001 // Used to compare non-integer variables to 0
// Data types
typedef struct{
double mass; // Mass of the field
double lambda; // Field-colloid coupling strength
double quartic_u; // Self-interaction coupling strength
double temperature; // Temperature of the common bath
double relativeD; // Ratio of colloid to field mobility (it's basically \nu of the particle)
double trap_strength; // Stiffness of the harmonic trap
int rng_seed; // Seed for random number generator
int system_size; // Side of the DIM-dimensional lattice
double delta_t; // Time-discretization step
long n_timestep; // Number of timesteps
int mc_runs; // Number of Monte Carlo iterations
double R; // Size of colloid in lattice units
double X0; // Initial displacement of the colloid
} parameter;
typedef struct{ // This structure bundles all observables
double** field_average; // Saves the measured field-average <phi[i]> for certain subset of i's (eg along an axis) AND at all writing times
double** field_correlation; // Saves the measured field-correlator < phi[0] phi[i]> for certain subset of i's (eg along an axis) AND at all writing times
double* colloid_pos; // Saves the measured displacement of the colloid at all writing times
double* colloid_msd; // Saves the measured mean square displacement of the colloid at all writing times
double write_time_delta; // This is the gap between writing times (at the moment linear, maybe later exponential writing times?)
int write_count;
// double* colloid_fpt_distribution; // Saves the first-passage time distribution of the colloid
} observables;
// Global variables
int DIM = 1; // Physical dimensions
int MOD = 2; // 0 for Model A, 2 for Model B
int top; // Actual number of sites within 5R around a single site
double gauss_norm; // Normalization constant of Gaussian functions
const gsl_rng_type *T; // GSL RNG (it turns out Ziggurat is faster than Box-Muller)
gsl_rng *seed;
// FUNCTION PROTOTYPES
void default_parameters(parameter*);
void initialise(long***, parameter*, long***);
void initialise_observable(observables*, parameter*);
void wipe(double**, double**, parameter*);
void prethermalize(double**, parameter*);
void field_prepare(double**, parameter*);
void evolveB(double**, double**, long**, parameter*, observables*, long**);
void evolveA(double**, double**, long**, parameter*, observables*, long**);
void laplacian(double**, double*, long**, long);
void laplacian_of_cube(double**, double*, long**, long);
void generate_noise_field(double**, long, parameter*);
void gradient_field(double**, double*, long**, long);
void phi_evolveB(double**, double*, double*, double*, double*, long, parameter*, double*, long**);
void phi_evolveA(double**, double*, double*, long, parameter*, double*, long**);
void measure(double**, double**, long, parameter*, observables*);
void print_observables(observables*, parameter*);
void print_trajectory(observables*, parameter*);
void print_params(parameter*);
void printhelp(parameter*);
void print_source(void);
void neighborhood(long***, int);
int ind2coord(int, int, int);
int vec2ind(int*, int);
void ind2vecROW(int**, int, int, int);
int closest_site(double*, int);
double distance(double*, int, int);
unsigned modulo(int, unsigned);
double modular(double, double, double);
int factorial(int);
int double_factorial(int);
int intpow(int, int);
double floatpow(double, int);
void print_lookup(long **, int, int);
double gaussian(double, double);
double laplacian_gaussian(double, double);
void evolve_quenched(double**, double**, parameter*, observables*, long**);
// MAIN BODY
int main(int argc, char *argv[]){
setlinebuf(stdout);
// INPUT PARAMETERS
parameter params;
default_parameters(¶ms);
opterr = 0;
int c = 0;
// ./colloid -r 2 -L 23 (order doesn't count)
while( (c = getopt (argc, argv, "L:r:l:u:T:d:k:S:t:N:M:n:m:R:X:hP") ) != -1){
switch(c){
case 'L':
params.system_size = atoi(optarg);
break;
case 'r':
params.mass = atof(optarg);
break;
case 'l':
params.lambda = atof(optarg);
break;
case 'u':
params.quartic_u = atof(optarg);
break;
case 'T':
params.temperature = atof(optarg);
break;
case 'n':
params.relativeD = atof(optarg);
break;
case 'k':
params.trap_strength = atof(optarg);
break;
case 'S':
params.rng_seed = atoi(optarg);
break;
case 't':
params.delta_t = atof(optarg);
break;
case 'N':
params.n_timestep = atol(optarg);
break;
case 'M':
params.mc_runs = atoi(optarg);
break;
case 'd':
DIM = atoi(optarg);
break;
case 'm':
MOD = atoi(optarg);
break;
case 'R':
params.R = atof(optarg);
break;
case 'X':
params.X0 = atof(optarg);
break;
case 'P':
print_source();
exit(2);
case 'h':
printhelp(¶ms);
exit(2);
default:
printhelp(¶ms);
exit(EXIT_FAILURE);
}
}
// VARIABLES, ALLOCATION
int i, j;
long L = params.system_size;
long n_sites = intpow(L, DIM);
int max_within_5R;
double prefactor[3] = {2,M_PI,4.0/3*M_PI};
if(DIM<4) max_within_5R = (int) ceil( prefactor[DIM-1]*floatpow(ceil(5*params.R), DIM) ) + 2;
else max_within_5R=10000; // Overkill, maybe I'll generalize it one day
double* phi; // Field on lattice NxNxN
double* y_colloid; // Colloid position (DIM real numbers)
long** neighbours; // i x j - table with j neighbours of site i
long** mosaic; // Table with neighbours of site i with distance < 4R
ALLOC(phi, n_sites);
CALLOC(y_colloid, DIM);
ALLOC(neighbours, n_sites);
ALLOC(mosaic, n_sites);
for(i = 0; i < n_sites; i++){
neighbours[i]=calloc( 2 * DIM , sizeof(long)); // At each index there are 2*D neighbours
if( neighbours[i] == NULL){printf("Allocation of neighbour list failed. Terminate. \n"); exit(2);}
mosaic[i]=calloc( max_within_5R , sizeof(long)); // At each index, all the sites within 5R
if( mosaic[i] == NULL){printf("Allocation of mosaic list failed. Terminate. \n"); exit(2);}
}
// INITIALIZATION
initialise(&neighbours, ¶ms, &mosaic); // Random function, nearest neighbours list, mosaic
observables obvs; // Creates a pointer to an observables structure
initialise_observable(&obvs, ¶ms); // Initialise observables
print_params(¶ms); // Print header with all parameters
gauss_norm = 1/(pow(2*M_PI,DIM*0.5) * floatpow(params.R,DIM)); // Normalization for Gaussian functions
printf("# Max within 5R: %d\n", max_within_5R);
printf("# Actual within 5R: %d\n", top);
//print_lookup(neighbours, n_sites, 2*DIM); // Prints nearest-neighbours list
//print_lookup(mosaic, n_sites, top); // Prints cell-list
// MC ITERATION
int mc_counter, flag;
printf("\n# MC ITERATION BEGINS\n");
for(mc_counter = 0; mc_counter < params.mc_runs; mc_counter++){
//wipe(&phi, &y_colloid, ¶ms); // Reset field and colloid to initial conditions
prethermalize(&phi, ¶ms); // Pre-thermalization cycle
//field_prepare(&phi, ¶ms);
for(j=0; j<DIM; j++) y_colloid[j] = L/2; // Colloid initially in the middle of the trap
y_colloid[0] = (L/2)+params.X0; // Add initial displacement in one direction
// Numerical integration of the dynamics
if(MOD==0){ // Model A
evolveA(&phi, &y_colloid, neighbours, ¶ms, &obvs, mosaic);
} else if(MOD==2){ // Model B
evolveB(&phi, &y_colloid, neighbours, ¶ms, &obvs, mosaic);
} else if(MOD==1){ // Evolution in a quenched potential
evolve_quenched(&phi, &y_colloid, ¶ms, &obvs, mosaic);
} else {
printhelp(¶ms);
exit(EXIT_FAILURE);
}
flag = params.mc_runs/10; // Prints completing percentage
if( flag !=0 && ((mc_counter +1)%flag) == 0 ) printf("# MC PROGRESS %d%%\n", (mc_counter +1)/flag*10);
}
//print_observables(&obvs, ¶ms);
print_trajectory(&obvs, ¶ms);
// Free memory and exit
free(phi);
free(y_colloid);
for(i=0; i<n_sites; i++) free(neighbours[i]);
for(i=0; i<n_sites; i++) free(mosaic[i]);
free(obvs.colloid_pos); // Add any other observable you are storing
return 0;
}
// DEFINITION OF FUNCTIONS
// Default parameters
void default_parameters(parameter* params){
params->mass = 0.0;
params->lambda = 0.25;
params->quartic_u = 0.0;
params->temperature = 0.001;
params->relativeD = 1.0;
params->trap_strength = 0.1;
params->rng_seed = -1; // if seed is -1 (not given by user), it will be picked randomly
params->system_size = 128;
params->delta_t = 0.01;
params->n_timestep = 100000;
params->mc_runs = 10000;
params->R = 1;
params->X0 = 2;
}
// All that needs to be done once
void initialise(long*** neighbours, parameter* params, long*** mosaic){
// i) GSL random number generator setup
gsl_rng_env_setup();
T = gsl_rng_default;
seed = gsl_rng_alloc (T); // This is probably not really a seed, but sticazzi
time_t t; // If no seed provided, draw a random one
if(params->rng_seed==-1) params->rng_seed = (unsigned) time(&t) % 100000;
gsl_rng_set(seed, params->rng_seed);
// ii) What are each position's neighbours?
long L = params->system_size;
neighborhood(neighbours, L);
// iii) Initialize the mosaic
double dist;
long n_sites = intpow(L, DIM);
int i, j, d;
for(i=0; i<n_sites; i++){
top=0; // Number of sites within 5R around a given site (global variable)
for(j=0; j<n_sites; j++){
dist=0;
for(d=0; d<DIM; d++) dist += floatpow( modular( ind2coord(d,i,L), ind2coord(d,j,L), L) , 2);
dist = sqrt(dist);
if(dist < ceil(5*params->R) + EPS ){
(*mosaic)[i][top]=j;
top++;
}
}
}
}
// Reset field and colloid to initial conditions
void wipe(double** phi, double** y_colloid, parameter* params)
{
int n_sites, i;
n_sites = intpow(params->system_size, DIM);
for(i = 0; i < n_sites; i++){
//(*phi)[i] = gsl_ran_gaussian_ziggurat(seed,1.0); // Infinite temperature state
(*phi)[i] = 0; // Initially flat field - default after calloc()
//(*phi)[i] = (i % 2 ? 1 : -1); // Staggered
}
// y - colloid (initially in the middle of the lattice, where the harmonic well stands)
long L = params->system_size;
for(i=0; i<DIM; i++) (*y_colloid)[i] = L/2;
}
// This initialises the observables structure later containing the measurements
void initialise_observable(observables* obvs, parameter* params)
{
obvs->write_time_delta = 0.2; // This is in physical time units, so writing occurs every (write_time_delta / n_timestep) integration step
// This counts how many writing events will occur in time (including t=0, thus + 1). If you choose exp distributed measurements, it still works (but it's overestimated).
int writing_times = (int)(1 + (((params->n_timestep)*params->delta_t)/obvs->write_time_delta));
//CALLOC(obvs->colloid_msd, writing_times); // Save MSD vs time
CALLOC(obvs->colloid_pos, writing_times); // Save position vs time
/*
// FIELD MEASUREMENTS ONLY
CALLOC(obvs->field_average, writing_times); // Prepare writing_times many arrays to store averages
//CALLOC(obvs->field_correlation, writing_times); // Prepare writing_times many arrays to store correlations
int i;
for(i = 0; i < writing_times; i++)
{
//obvs->field_correlation[i] = calloc( params->system_size , sizeof(double) );
//if( (obvs->field_correlation[i]) == NULL){printf("Allocation of '(obvs->field_correlation[%i])' failed. Terminate. \n", i); exit(2);}
obvs->field_average[i] = calloc( params->system_size , sizeof(double) );
if( (obvs->field_average[i]) == NULL){
printf("Allocation of '(obvs->field_average[%i])' failed. Terminate. \n", i);
exit(2);
}
}
*/
}
// Perform measurements and print them out
void measure(double** phi, double** y_colloid, long tstep, parameter* params, observables* obvs){
long i;
printf("%g\t", tstep*params->delta_t);
for(i = 0; i < params->system_size; i++){
obvs->field_average[obvs->write_count][i] += (*phi)[i];
obvs->field_correlation[obvs->write_count][i] += ((*phi)[0] * (*phi)[i]);
}
long n_sites = intpow(params->system_size , DIM);
for(i = 0; i < DIM; i++){
obvs->colloid_msd[obvs->write_count] += ((*y_colloid)[i] - ind2coord(i, n_sites/2 , params->system_size))*((*y_colloid)[i] - ind2coord(i, n_sites/2 , params->system_size));
}
//printf("\n");
}
// Creates list of nearest neighbours in DIM dimensions
void neighborhood(long*** list, int L){
int k,d;
int vec[DIM], neigh[DIM];
for(k=0; k<intpow(L,DIM); k++){ // Cycles over lattice sites
for(d=0; d<DIM; d++){ // Finds the DIM coordinates of the current site
vec[d] = ind2coord(d,k,L);
neigh[d] = vec[d];
}
for(d=0; d<DIM; d++){
neigh[d] = (vec[d]+1)%L; // Finds right neighbour
(*list)[k][2*d] = vec2ind(neigh,L); // Stores it in the neighbour list
neigh[d] = (vec[d]+L-1)%L; // Finds left neighbour
(*list)[k][2*d+1] = vec2ind(neigh,L); // Stores it in the neighbour list
neigh[d] = vec[d]; // Restores local copy (prepares for next dimension)
}
}
}
// Pre-thermalization of the field
void prethermalize(double** phi, parameter* params){
// Benjamin: 20/08/21, spectral thermalisation
// \phi_k are complex normal random variables with <\phi_k> = 0, < |\phi_k|^2> = k_B T*(k^2+r)^-1, and \phi_k = \phi^*_{-k}
// Using FFTW library, -lfftw3
fftw_complex *phi_fourier;
fftw_plan p;
int n_sites = intpow(params->system_size, DIM);
int i, j;
phi_fourier = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (n_sites/2 + 1)); // complex Hermitian array
int *vec = malloc(DIM * sizeof(int));
/* fill with random data */
double inverse_variance, variance;
double inv_L_square = (39.438/pow(((double) params->system_size), 2)); //(2\pi /L)^2
double radius;
double polar_angle;
int centre = (n_sites/2);
for(i = centre; i >=0 ; i--) // Fill half the reciprocal lattice without the zero mode first. The first entry is at the centre of the reciprocal lattice and therefore the zero mode (~ k_BT/r)
{
// What's the L2 norm of the reciprocal vector?
inverse_variance = params->mass;
ind2vecROW(&vec, i, DIM, params->system_size);
for(j = 0; j < DIM; j++)
{
inverse_variance += inv_L_square*(vec[j]*vec[j]);
}
variance = (params->temperature/inverse_variance); // k_B T /(q^2 + r)
if(inverse_variance > 0){
radius = gsl_ran_gaussian_ziggurat(seed, sqrt(variance));
polar_angle = gsl_ran_flat(seed, 0, 6.2831); // pick random angle
phi_fourier[centre-i][0] = radius*cos(polar_angle);
phi_fourier[centre-i][1] = radius*sin(polar_angle);
}
else{ // Critical mode is force set to zero
phi_fourier[centre-i][0] = 0.0;
phi_fourier[centre-i][1] = 0.0;
}
}
// _c2r transforms a half-complex array into real fft http://www.fftw.org/fftw3_doc/Real_002ddata-DFTs.html
int lattice_dimensions[DIM];
for(i = 0; i < DIM; i++){lattice_dimensions[i] = ((int) params->system_size);} //It's a cube
double* phi_real;
phi_real = (double*)fftw_malloc(n_sites * sizeof(double));
// http://www.fftw.org/fftw3_doc/Real_002ddata-DFTs.html
//fftw_plan fftw_plan_dft_c2r(int rank, const int *n, fftw_complex *in, double *out, unsigned flags);
p = fftw_plan_dft_c2r(DIM, lattice_dimensions, phi_fourier, phi_real, FFTW_ESTIMATE);
if(p == NULL){printf("fftw plan didn't work\n");}
fftw_execute(p);
// normalising inverse transform with V^(-d/2), ass fftw3 doesn't do that.
double normalising_volume = (1.0/(((double) n_sites)));
// Now transform rowmajor phi_real into col_major *phi -> matrix transpose
/* Only for D > 1
* int row_maj_index, col_maj_index, dir;
for(row_maj_index = 0; row_maj_index < n_sites; row_maj_index++)
{
for(dir = 0; dir < DIM; dir++)
{
vec[dir] = ((int) (row_maj_index / intpow(params->system_size, (DIM - dir -1))) % params->system_size);
}
col_maj_index = vec2ind(vec, params->system_size);
if(row_maj_ind
printf("RM %i CM %i | phi_real: %g\n", row_maj_index, col_maj_index, phi_real[row_maj_index]);
(*phi)[col_maj_index] = phi_real[row_maj_index];
}*/
// For D = 1
// Shift origin to centre
for(i = 0; i <= centre; i++) (*phi)[i] = normalising_volume*phi_real[centre-i];
for(i = centre+1; i < n_sites; i++) (*phi)[i] = normalising_volume*phi_real[n_sites+centre-i];
fftw_free(phi_fourier);
fftw_free(phi_real);
fftw_destroy_plan(p);
}
// Preparation of the field in equilibrium at T=0 around X0
// 1d only at the moment. It can probably be generalized to finite T by adding noise later on.
void field_prepare(double** phi, parameter* params){
// Spectral initialization using FFTW library, -lfftw3
// \phi_k are complex normal random variables with <\phi_k> = 0, < |\phi_k|^2> = k_B T*(k^2+r)^-1, and \phi_k = \phi^*_{-k}
fftw_complex *phi_fourier;
fftw_plan p;
int n_sites = intpow(params->system_size, DIM);
int i, j;
phi_fourier = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (n_sites/2 + 1)); // complex Hermitian array
int *vec = malloc(DIM * sizeof(int));
/* fill with random data */
//double inverse_variance, variance;
double inverse_variance;
double inv_L = 6.28318530718/params->system_size; // 2pi/L
double inv_L_square = (39.438/intpow(params->system_size, 2)); // (2\pi /L)^2
double radius;
double polar_angle;
int centre = (n_sites/2);
for(i = centre; i >=0 ; i--) // Fill half the reciprocal lattice without the zero mode first. The first entry is at the centre of the reciprocal lattice and therefore the zero mode (~ k_BT/r)
{
// What's the L2 norm of the reciprocal vector?
inverse_variance = params->mass;
ind2vecROW(&vec, i, DIM, params->system_size);
for(j = 0; j < DIM; j++)
{
inverse_variance += inv_L_square*(vec[j]*vec[j]);
}
//variance = (params->temperature/inverse_variance); // k_B T /(q^2 + r)
radius = params->lambda * exp(- floatpow(params->R,2)*(inverse_variance - params->mass)/2) /inverse_variance ; // l* exp(-q^2 R^2/2) / (q^2 + r)
if(inverse_variance > 0){
//radius = gsl_ran_gaussian_ziggurat(seed, sqrt(variance));
//polar_angle = gsl_ran_flat(seed, 0, 6.2831); // pick random angle
polar_angle = - inv_L * vec[j] * (params->system_size/2+params->X0); // Careful if you ever generalize to higher dimensions
phi_fourier[centre-i][0] = radius*cos(polar_angle);
phi_fourier[centre-i][1] = radius*sin(polar_angle);
}
else{ // Critical mode is force set to zero
phi_fourier[centre-i][0] = 0.0;
phi_fourier[centre-i][1] = 0.0;
}
}
// _c2r transforms a half-complex array into real fft http://www.fftw.org/fftw3_doc/Real_002ddata-DFTs.html
int lattice_dimensions[DIM];
for(i = 0; i < DIM; i++){lattice_dimensions[i] = ((int) params->system_size);} //It's a cube
double* phi_real;
phi_real = (double*)fftw_malloc(n_sites * sizeof(double));
// http://www.fftw.org/fftw3_doc/Real_002ddata-DFTs.html
//fftw_plan fftw_plan_dft_c2r(int rank, const int *n, fftw_complex *in, double *out, unsigned flags);
p = fftw_plan_dft_c2r(DIM, lattice_dimensions, phi_fourier, phi_real, FFTW_ESTIMATE);
if(p == NULL){printf("fftw plan didn't work\n");}
fftw_execute(p);
// normalising inverse transform with V^(-d/2), ass fftw3 doesn't do that.
double normalising_volume = (1.0/(((double) n_sites)));
// Now transform rowmajor phi_real into col_major *phi -> matrix transpose
/* Only for D > 1
* int row_maj_index, col_maj_index, dir;
for(row_maj_index = 0; row_maj_index < n_sites; row_maj_index++)
{
for(dir = 0; dir < DIM; dir++)
{
vec[dir] = ((int) (row_maj_index / intpow(params->system_size, (DIM - dir -1))) % params->system_size);
}
col_maj_index = vec2ind(vec, params->system_size);
if(row_maj_ind
printf("RM %i CM %i | phi_real: %g\n", row_maj_index, col_maj_index, phi_real[row_maj_index]);
(*phi)[col_maj_index] = phi_real[row_maj_index];
}*/
// For D = 1
// Shift origin to centre
for(i = 0; i <= centre; i++) (*phi)[i] = normalising_volume*phi_real[centre-i];
for(i = centre+1; i < n_sites; i++) (*phi)[i] = normalising_volume*phi_real[n_sites+centre-i];
fftw_free(phi_fourier);
fftw_free(phi_real);
fftw_destroy_plan(p);
}
// Evolution - colloid only (quenched potential)
void evolve_quenched(double** phi, double** y_colloid, parameter* params, observables* obvs, long** mosaic){
// Preparing variables for field evolution (Euler-Maruyama)
long tstep, n_timestep;
n_timestep = params->n_timestep;
// Preparing variables for colloid evolution (Stochastic Runge-Kutta II)
int i, j, y_site;
double grad, noise, F2, r, weight;
double w[DIM], F1[DIM], Y[DIM];
long L = params->system_size;
double noise_intensity = sqrt(2.0 * params->temperature * params->relativeD * params->delta_t);
for(j=0; j<DIM; j++) w[j] = L/2; // Finds position of the harmonic well
// Preparing measurement process
int write_time_delta_step = (int) ((obvs->write_time_delta)/(params->delta_t));
int next_writing_step = 0;
obvs->write_count = 0;
for(tstep = 0; tstep < n_timestep; tstep++){ // Time evolution
// MEASUREMENT
if(tstep == next_writing_step){
obvs->colloid_pos[obvs->write_count] += (*y_colloid)[0]; // Save colloid position
//obvs->colloid_msd[obvs->write_count] += (*y_colloid)[1]; // Save colloid position of 2nd coordinate
next_writing_step += write_time_delta_step; // Linearly distributed
obvs->write_count++;
}
// EVOLUTION
// i) Create local copy of the colloid variable
for(i=0; i<DIM; i++) Y[i] = (*y_colloid)[i];
// ii) Prediction step for the colloid
y_site = closest_site(Y,L); // Finds the lattice site closest to Y
for(i=0; i<DIM; i++){ // Evolves each of the components separately
// Compute gradient of the field under the colloid
grad = 0;
for(j=0; j<top; j++){
r = distance(Y, mosaic[y_site][j], L);
weight = gaussian(r,params->R);
grad += 0.5 * ( (*phi)[mosaic[y_site][j]+intpow(L,i)] - (*phi)[mosaic[y_site][j]-intpow(L,i)] ) * weight;
}
// Compute temporary position
noise = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);
F1[i] = params->relativeD * (params->lambda*grad -params->trap_strength*( Y[i]-w[i] ));
(*y_colloid)[i] += params->delta_t * F1[i] + noise;
}
// iv) Correction step for the colloid (with the evolved field)
y_site = closest_site(*y_colloid,L); // Compute new site of the colloid
for(i=0; i< DIM; i++){ // Evolve each of the components separately
// Compute new gradient
grad = 0;
for(j=0; j<top; j++){
r = distance(*y_colloid, mosaic[y_site][j], L);
weight = gaussian(r,params->R);
grad += 0.5 * ( (*phi)[mosaic[y_site][j]+intpow(L,i)] - (*phi)[mosaic[y_site][j]-intpow(L,i)] ) * weight;
}
// Compute corrected contribution
F2 = params->relativeD * ( params->lambda*grad -params->trap_strength*( (*y_colloid)[i]-w[i] ) );
// Sum the two contributions: y_n+1 = y_n + 1/2(F1+F2)*dt + noise
noise = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);
(*y_colloid)[i] = Y[i] + 0.5*(F1[i]+F2)*params->delta_t + noise;
}
}
}
// Model B evolution
void evolveB(double** phi, double** y_colloid, long** neighbours, parameter* params, observables* obvs, long** mosaic){
// Preparing variables for field evolution (Euler-Maruyama)
long tstep, n_sites, n_timestep;
n_sites = intpow(params->system_size, DIM);
n_timestep = params->n_timestep;
// TODO it's a terrible idea to allocate memory here, because this function is called M times
double* laplacian_phi;
ALLOC(laplacian_phi, n_sites);
double* laplacian_square_phi;
ALLOC(laplacian_square_phi, n_sites);
double* laplacian_phi_cubed;
CALLOC(laplacian_phi_cubed, n_sites);
double* noise_field;
CALLOC(noise_field, DIM * n_sites);
double* noise_gradient;
CALLOC(noise_gradient, n_sites);
// Preparing variables for colloid evolution (Stochastic Runge-Kutta II)
int i, j, y_site;
double grad, noise, F2, r, weight;
double w[DIM], F1[DIM], Y[DIM];
long L = params->system_size;
double noise_intensity = sqrt(2.0 * params->temperature * params->relativeD * params->delta_t);
for(j=0; j<DIM; j++) w[j] = L/2; // Finds position of the harmonic well
// Preparing measurement process
int write_time_delta_step = (int) ((obvs->write_time_delta)/(params->delta_t));
int next_writing_step = 0;
obvs->write_count = 0;
for(tstep = 0; tstep < n_timestep; tstep++){ // Time evolution
// MEASUREMENT
if(tstep == next_writing_step){
//measure(phi, y_colloid, tstep, params, obvs); // Evaluate all sorts of correlators etc. here
//for(i = 0; i < params->system_size; i++) obvs->field_average[obvs->write_count][i] += (*phi)[i]; // Save field average
obvs->colloid_pos[obvs->write_count] += (*y_colloid)[0]; // Save colloid position
//obvs->colloid_msd[obvs->write_count] += (*y_colloid)[1]; // Save colloid position of 2nd coordinate
next_writing_step += write_time_delta_step; // Linearly distributed
obvs->write_count++;
}
// EVOLUTION
// i) Create local copy of the colloid variable
for(i=0; i<DIM; i++) Y[i] = (*y_colloid)[i];
// ii) Prediction step for the colloid
y_site = closest_site(Y,L); // Finds the lattice site closest to Y
for(i=0; i<DIM; i++){ // Evolves each of the components separately
// Compute gradient of the field under the colloid
grad = 0;
for(j=0; j<top; j++){
r = distance(Y, mosaic[y_site][j], L);
weight = gaussian(r,params->R);
grad += 0.5 * ( (*phi)[mosaic[y_site][j]+intpow(L,i)] - (*phi)[mosaic[y_site][j]-intpow(L,i)] ) * weight;
}
// Compute temporary position
noise = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);
F1[i] = params->relativeD * (params->lambda*grad -params->trap_strength*( Y[i]-w[i] ));
(*y_colloid)[i] += params->delta_t * F1[i] + noise;
}
// iii) Evolve the field with the local copy of the colloid position
laplacian(&laplacian_phi, *phi, neighbours, n_sites); // Write Laplacian of phi into laplacian_phi
laplacian(&laplacian_square_phi, laplacian_phi, neighbours, n_sites); // Write (D^2)^2 phi into laplacian_square_phi
if(params->quartic_u > EPS){
laplacian_of_cube(&laplacian_phi_cubed, *phi, neighbours, n_sites); // Write D2 [phi(x)^3] into laplacian_phi_cubed
}
if(params->temperature > EPS){
generate_noise_field(&noise_field, DIM*n_sites, params); // Fill \vec{Lambda} with randomness
gradient_field(&noise_gradient, noise_field, neighbours, n_sites); // Compute gradient noise term
}
// Add together to new step d/dt phi = -a * D2 phi - b D4 phi - u D2 (phi^3) + D * noise (D is nabla)
phi_evolveB(phi, laplacian_phi, laplacian_square_phi, laplacian_phi_cubed, noise_gradient, n_sites, params, Y, mosaic);
// iv) Correction step for the colloid (with the evolved field)
y_site = closest_site(*y_colloid,L); // Compute new site of the colloid
for(i=0; i< DIM; i++){ // Evolve each of the components separately
// Compute new gradient
grad = 0;
for(j=0; j<top; j++){
r = distance(*y_colloid, mosaic[y_site][j], L);
weight = gaussian(r,params->R);
grad += 0.5 * ( (*phi)[mosaic[y_site][j]+intpow(L,i)] - (*phi)[mosaic[y_site][j]-intpow(L,i)] ) * weight;
}
// Compute corrected contribution
F2 = params->relativeD * ( params->lambda*grad -params->trap_strength*( (*y_colloid)[i]-w[i] ) );
// Sum the two contributions: y_n+1 = y_n + 1/2(F1+F2)*dt + noise
noise = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);
(*y_colloid)[i] = Y[i] + 0.5*(F1[i]+F2)*params->delta_t + noise;
}
}
// Free memory
free(laplacian_phi);
free(laplacian_square_phi);
free(laplacian_phi_cubed);
free(noise_field);
free(noise_gradient);
}
// Model A evolution
void evolveA(double** phi, double** y_colloid, long** neighbours, parameter* params, observables* obvs, long** mosaic){
// Preparing variables for field evolution (Euler-Maruyama)
long tstep, n_sites, n_timestep;
n_sites = intpow(params->system_size, DIM);
n_timestep = params->n_timestep;
double* laplacian_phi;
ALLOC(laplacian_phi, n_sites);
double* noise_field;
CALLOC(noise_field, n_sites);
int i, j, y_site;
double grad, noise, F2, r, weight;
double w[DIM], F1[DIM], Y[DIM];
long L = params->system_size;
double noise_intensity = sqrt(2.0 * params->temperature * params->relativeD * params->delta_t);
for(i=0; i<DIM; i++) w[i] = L/2; // Finds position of the harmonic well
// Preparing measurement process
int write_time_delta_step = (int) ((obvs->write_time_delta)/(params->delta_t));
int next_writing_step = 0; // Linearly distributed writing times
//int next_writing_step = write_time_delta_step; // Exponentially distributed writing times TODO
obvs->write_count = 0;
for(tstep = 0; tstep < n_timestep; tstep++){ // Time evolution
// MEASUREMENT
if(tstep == next_writing_step){
//measure(phi, y_colloid, tstep, params, obvs); // Evaluate all sorts of correlators etc. here
obvs->colloid_pos[obvs->write_count] += (*y_colloid)[0]; // Save colloid position
//for(i = 0; i < params->system_size; i++) obvs->field_average[obvs->write_count][i] += (*phi)[i]; // Save field average
//obvs->colloid_msd[obvs->write_count] += (*y_colloid)[1]; // Save colloid position of 2nd coordinate
next_writing_step += write_time_delta_step; // Linearly distributed
//next_writing_step = (int)(next_writing_step * exp( write_time_delta_step)); // Exponentially distributed TODO
obvs->write_count++;
}
// EVOLUTION
// i) Create local copy of the colloid variable
for(i=0; i<DIM; i++) Y[i] = (*y_colloid)[i];
// ii) Prediction step for the colloid
y_site = closest_site(Y,L); // Finds the lattice site closest to Y
for(i=0; i<DIM; i++){ // Evolve each of the components separately
// Compute gradient of the field under the colloid
grad = 0;
for(j=0; j<top; j++){
r = distance(Y, mosaic[y_site][j], L);
weight = gaussian(r,params->R);
grad += 0.5 * ( (*phi)[mosaic[y_site][j]+intpow(L,i)] - (*phi)[mosaic[y_site][j]-intpow(L,i)] ) * weight;
}
// Compute temporary position
noise = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);
F1[i] = params->relativeD * (params->lambda*grad -params->trap_strength*( Y[i]-w[i] ));
(*y_colloid)[i] += params->delta_t * F1[i] + noise;
}
// iii) Evolve the field with the local copy of the colloid position
laplacian(&laplacian_phi, *phi, neighbours, n_sites); // Write Laplacian of phi into laplacian_phi
if(params->temperature > EPS){
generate_noise_field(&noise_field, n_sites, params); // Fill Lambda with randomness
}
// Add together to new step d/dt phi = -r * phi + \nabla^2 phi - u * (phi^3) + l * V(x-Y) + noise
phi_evolveA(phi, laplacian_phi, noise_field, n_sites, params, Y, mosaic);
// iv) Correction step for the colloid (with the evolved field)
y_site = closest_site(*y_colloid,L); // Compute new site of the colloid
for(i=0; i< DIM; i++){ // Evolve each of the components separately
// Compute new gradient
grad = 0;
for(j=0; j<top; j++){
r = distance(*y_colloid, mosaic[y_site][j], L);
weight = gaussian(r,params->R);
grad += 0.5 * ( (*phi)[mosaic[y_site][j]+intpow(L,i)] - (*phi)[mosaic[y_site][j]-intpow(L,i)] ) * weight;
}
// Compute corrected contribution
F2 = params->relativeD * (params->lambda*grad -params->trap_strength*( (*y_colloid)[i]-w[i] ));
// Sum the two contributions: y_n+1 = y_n + 1/2(F1+F2)*dt + noise
noise = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);
(*y_colloid)[i] = Y[i] + 0.5*(F1[i]+F2)*params->delta_t + noise;
}
}
// Free memory
free(laplacian_phi);
free(noise_field);
}
// Field evolution - Model B
void phi_evolveB(double** phi, double* laplacian_phi, double* laplacian_square_phi, double* laplacian_phi_cubed, double* noise_gradient, long n_sites, parameter* params, double* Y, long** mosaic){
long i;
long L = params->system_size;
double delta_t = params->delta_t;
double r, weight;
for(i = 0; i < n_sites; i++){
(*phi)[i] += (delta_t*( -laplacian_square_phi[i] + params->mass*laplacian_phi[i] + params->quartic_u * laplacian_phi_cubed[i]) + noise_gradient[i]);
}
// Interaction with the colloid
int y_site = closest_site(Y,L); // Finds the lattice site closest to Y, the colloid
for(i=0; i<top; i++){
r = distance(Y, mosaic[y_site][i], L);
weight = laplacian_gaussian(r,params->R);
(*phi)[mosaic[y_site][i]] -= delta_t * params->lambda * weight;
}
}
// Field evolution - Model A
void phi_evolveA(double** phi, double* laplacian_phi, double* noise_field, long n_sites, parameter* params, double* Y, long** mosaic){
long i;
double delta_t = params->delta_t;
long L = params->system_size;
double r, weight;
for(i = 0; i < n_sites; i++){ // Notice noise_field contains delta_t in its variance
(*phi)[i] += delta_t*(- params->mass*(*phi)[i] + laplacian_phi[i] - params->quartic_u * floatpow((*phi)[i],3) ) + noise_field[i];
}
// Interaction with the colloid
int y_site = closest_site(Y,L); // Finds the lattice site closest to Y, the colloid
for(i=0; i<top; i++){
r = distance(Y, mosaic[y_site][i], L);
weight = gaussian(r,params->R);
(*phi)[mosaic[y_site][i]] += delta_t * params->lambda * weight;
}
}
// Returns Laplacian as calculated from cubic neighbour cells in DIM dimensions
void laplacian(double** laplacian, double* field, long** neighbours, long n_sites){
double buffer;
long pos, i;
for(pos = 0; pos < n_sites; pos++){
buffer = 0;
for(i = 0; i < 2*DIM; i++) {buffer += field[neighbours[pos][i]]; }
buffer -= (2*DIM*field[pos]);
(*laplacian)[pos] = buffer;
}
}
// Returns the Laplacian of field^3
void laplacian_of_cube(double** laplacian, double* field, long** neighbours, long n_sites){
double buffer;
long pos, i;
for(pos = 0; pos < n_sites; pos++){
buffer = 0;
for(i = 0; i < 2*DIM; i++){
buffer += pow( (field[neighbours[pos][i]]), 3);
}
buffer -= (2*DIM*field[pos]*field[pos]*field[pos]);
(*laplacian)[pos] = buffer;
}
}
// This function generates a completely uncorrelated random field on a line
void generate_noise_field(double** noise_field, long length, parameter* params){
long i;
double noise_intensity = sqrt(2.0 * params->temperature * params->delta_t);
for(i = 0; i < length; i++){
(*noise_field)[i] = noise_intensity * gsl_ran_gaussian_ziggurat(seed, 1.0);
}
}
// Computes the gradient of a (noisy) field
void gradient_field(double** grad_noise, double* noise, long** neighbours, long n_sites){
long i;
int j; // neighbour of i
double buffer;
for(i = 0; i < n_sites; i++){
buffer = 0;
for(j = 0; j < DIM; j++){
buffer += noise[neighbours[i][2*j]];
buffer -= noise[neighbours[i][2*j+1]];
}
(*grad_noise)[i] = 0.5*buffer;
}
}
// Returns the value of a Gaussian of variance R evaluated at r
double gaussian(double r, double R){
return gauss_norm * exp(-r*r/(2*R*R));
}
// Returns the value of the laplacian of a Gaussian of variance R evaluated at r
double laplacian_gaussian(double r, double R){
return gauss_norm * exp(-r*r/(2*R*R)) * (r*r - DIM*R*R) / floatpow(R,4);
}
// Translate from a list index (k) to d-th lattice index, and viceversa.
inline int ind2coord(int d, int k, int L) {return ( (int)( k/intpow(L,d) ) )%L ;}
int vec2ind(int *vec, int L){
int i, res=0;
for(i=0; i<DIM; i++) res += vec[i] * intpow(L,i);
return res;
}
void ind2vecROW(int** vec, int ind, int dim, int L)
{
// Places origin in the middle, row-major format.
int dir;
int offset = (int) ((L-1)/2.0); // So if L = 7 then the middle is at ___3___
for(dir = 0; dir < dim; dir++)
{
(*vec)[dir] = (((int) (ind / intpow(L, (dim - dir -1))) % L) - offset) ; // row format, last index is fastest moving
}
}
// Finds index of closest lattice site to the vector "vec"
// I'm using a special modulo function to avoid getting negative return values, eg -3 % 10 = -3, but modulo(-3,10) = 7.
int closest_site(double *vec, int L){
int i, site=0;
for(i=0; i<DIM; i++){
site += (int)(modulo( round(vec[i]) , L) * intpow(L,i));
}
return site;
}
// According to https://stackoverflow.com/questions/14997165/fastest-way-to-get-a-positive-modulo-in-c-c this is still fast
unsigned modulo( int value, unsigned m) {
int mod = value % (int)m;
if (mod < 0) {
mod += m;
}
return mod;
}
// Return the distance mod(L)
double modular(double a, double b, double L){
return fabs(L/2 - fmod(3*L/2 + a - b, L));
}
// Returns the distance between the position vector and a given site (in a lattice of side L)
double distance(double* pos, int site, int L){
int d;
double dist=0;
//for(d=0; d<DIM; d++) dist += floatpow( pos[d] - ind2coord(d,site,L) ,2);
for(d=0; d<DIM; d++) dist += floatpow( modular(pos[d], ind2coord(d,site,L), L) , 2);
dist = sqrt(dist);
return dist;
}
// Factorial of a number
int factorial(int n){
if (n == 0) return 1;
return n * factorial(n - 1);
}
// Double factorial of a number
int double_factorial(int n){
if (n <= 1) return 1;
return n * factorial(n - 2);
}
// The usual pow(a,b)=exp(log(a) * b) is slow AF
int intpow(int a, int b){
int i, res=1;
for(i=0; i<b; i++) res *= a;
return res;
}
// The usual pow(a,b)=exp(log(a) * b) is slow AF
double floatpow(double a, int b){
int i;
double res=1;
for(i=0; i<b; i++) res *= a;
return res;
}
// Prints observables including field
void print_observables(observables* obvs, parameter* params){
int i,j;
int system_size = params->system_size;
int write_count = obvs->write_count;
double weight = 1/((double) params->mc_runs);
for(i = 0; i < write_count; i ++){
printf("#FIELDAVG %g", i * (obvs->write_time_delta));
for(j = 0; j < system_size; j++){
printf("\t%g", weight*(obvs->field_average[i][j]));
}
printf("\n");
}
/*
for(i = 0; i < write_count; i ++){
printf("#FIELDCORR %g", i * (obvs->write_time_delta));
for(j = 0; j < system_size; j++){
printf("\t%g", weight*(obvs->field_correlation[i][j]- (obvs->field_average[i][0] * obvs->field_average[i][j]) ));
}
printf("\n");
}
// Output MSD of colloid
for(i = 0; i < write_count; i++){
printf("# COLLOIDMSD %g", i * (obvs->write_time_delta));
printf("\t%.3f",weight*(obvs->colloid_msd[i]));
printf("\n");
}
*/
// Output trajectory of colloid
for(i = 0; i < write_count; i++){
printf("#COLLOID_X %g", i * (obvs->write_time_delta));
//printf("%.4f", i * (obvs->write_time_delta));
printf("\t%.15f",weight*obvs->colloid_pos[i]- params->system_size/2);
//printf("\t%.12f",weight*(obvs->colloid_msd[i]));
printf("\n");
}
}
// Prints colloid-related observables only
void print_trajectory(observables* obvs, parameter* params)
{
int i;
int write_count = obvs->write_count;
double weight = 1/((double) params->mc_runs);
// Output trajectory of colloid
for(i = 0; i < write_count; i++){
//printf("#COLLOID_X %g", i * (obvs->write_time_delta));
printf("%.4f", i * (obvs->write_time_delta));
printf("\t%.15f", weight*obvs->colloid_pos[i]- params->system_size/2);
//printf("\t%.12f",weight*(obvs->colloid_msd[i]));
printf("\n");
}
}
// Prints out simulation parameters
void print_params(parameter* params){
printf("# Parameters\n\
# MASS %g\n\
# LAMBDA (field-colloid-coupling) %g\n\
# U (quartic coupling) %g\n\
# TEMPERATURE %g\n\
# RELATIVE MOTILITY D %g\n\
# TRAP STRENGTH %g\n\
# RNG SEED %u\n\
# L (System Size) %i\n\
# DIM %i\n\
# RADIUS %g\n\
# INITIAL DISPLACEMENT %g\n\
# DELTA T %g\n\
# TIMESTEPS %lu\n\
# MONTE CARLO RUNS %i\n",
params->mass, params->lambda, params->quartic_u, params->temperature, params->relativeD, params->trap_strength, params->rng_seed, params->system_size, DIM, params->R, params->X0, params->delta_t, params->n_timestep, params->mc_runs);
if(MOD==0) printf("# MODEL A\n");
if(MOD==2) printf("# MODEL B\n");
}
// Prints out the instructions
void printhelp(parameter* params){
printf("# Colloid in Gaussian Field\n# '%s' built %s\n\
# Use with options flags\n\
# -L Length of d-dimensional lattice (default %i)\n\
# -r Mass of Gaussian field (default %g)\n\
# -l Coupling strength between colloid and field (default %g)\n\
# -u Quartic coupling strength (default %g)\n\
# -T Temperature of bath (default %g)\n\
# -n Relative motility colloid/field (default %g)\n\
# -k Strength of harmonic trap (default %g)\n\
# -S Seed for RNG (default random)\n\
# -t Integration timestep (default %g)\n\
# -d Dimension (default %i)\n\
# -N Number of timesteps (default %lu)\n\
# -M Number of Monte Carlo samples (default %i)\n\
# -R Radius of the colloid (default %g)\n\
# -X Initial displacement of the colloid (default %g)\n\
# -m Field dynamics (model A -> 0, model B -> 2, quenched -> 1, default %i)\n\
# -h To see this helpscreen\n\
# -P Output source code\n",__FILE__,__DATE__, params->system_size, params->mass, params->lambda, params->quartic_u, params->temperature, params->relativeD, params->trap_strength, params->delta_t, DIM, params->n_timestep, params->mc_runs, params->R, params->X0, MOD);
}
// Prints out the nearest-neighbour list
// For neighbour list, size1=n_sites and size2=2*DIM. For mosaic, size1=n_sites and size2=top.
void print_lookup(long ** list, int size1, int size2){
int i,j;
for(i=0; i<size1; i++){
printf("# Around site %d : \t",i);
for(j=0; j<size2; j++) printf("%li\t", list[i][j]);
printf("\n");
}
}
// Prints out this whole code
void print_source(){
printf("/* Source Code %s, created %s */\n",__FILE__,__DATE__);
FILE *fp;
int c;
fp = fopen(__FILE__,"r");
do {
c = getc(fp);
putchar(c);
}
while(c != EOF);
fclose(fp);
} | {
"alphanum_fraction": 0.6554553284,
"avg_line_length": 38.0034453058,
"ext": "c",
"hexsha": "f7a42ccdce37cea24d4bc7c4758395b9e29b8d9b",
"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": "9a41efd53c0bfd2ae73677f394a2101450a3d81f",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "sonarventu/field_and_particle",
"max_forks_repo_path": "colloid_field.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9a41efd53c0bfd2ae73677f394a2101450a3d81f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "sonarventu/field_and_particle",
"max_issues_repo_path": "colloid_field.c",
"max_line_length": 266,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "9a41efd53c0bfd2ae73677f394a2101450a3d81f",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "sonarventu/field_and_particle",
"max_stars_repo_path": "colloid_field.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T14:53:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-30T14:53:37.000Z",
"num_tokens": 13481,
"size": 44122
} |
/**
* @file postfilter.h
* @brief implementation of post-filters for a microphone array.
The following post-filters are implemented:
[1] Zelinski post-filter
[2] APAB post-filter
[3] McCowan's post-filter
[4] Lefkimmiatis's post-filter
The correspondig references are:
[1] C.Claude Marro et al. "Analysis of noise reduction and dereverberation techniques based on microphone arrays with postfiltering", IEEE Trans. ASP, vol. 6, pp 240-259, May 1998.
[2] M.Brandstein, "Microphone Arrays", Springer, ISBN 3-540-41953-5, pp.39-60.
[3] Iain A. Mccowan et al., "Microphone array post-filter based on noise field coherence", IEEE Trans. SAP, vol. 11, pp. Nov. 709--716, 2003.
[4] Stamatios Lefkimmiatis et al., "A generalized estimation approach for linear and nonlinear microphone array post-filters", Speech Communication, 2007.
* @author Kenichi Kumatani
*/
#ifndef POSTFILTER_H
#define POSTFILTER_H
#include <stdio.h>
#include <assert.h>
#include <float.h>
#include <gsl/gsl_block.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_fft_complex.h>
#include <common/refcount.h>
#include "common/jexception.h"
#include "stream/stream.h"
#include "postfilter/spectralsubtraction.h"
#include "postfilter/binauralprocessing.h"
#include "beamformer/spectralinfoarray.h"
#include "beamformer/beamformer.h"
typedef enum {
TYPE_ZELINSKI1_REAL = 0x01,
TYPE_ZELINSKI1_ABS = 0x02,
TYPE_APAB = 0x04,
TYPE_ZELINSKI2 = 0x08,
NO_USE_POST_FILTER = 0x00
} PostfilterType;
void ZelinskiFilter(gsl_vector_complex **arrayManifold,
SnapShotArrayPtr snapShotArray,
bool halfBandShift,
gsl_vector_complex *beamformedSignal,
gsl_vector_complex **prevCSDs,
gsl_vector_complex *pfweights,
double alpha, int Ropt );
void ApabFilter( gsl_vector_complex **arrayManifold,
SnapShotArrayPtr snapShotArray,
int fftLen, int nChan, bool halfBandShift,
gsl_vector_complex *beamformedSignal,
int channelX );
/**
@class Zelinski post-filtering
@brief filter beamformer's outputs under the assumption that noise signals between sensors are uncorrelated.
@usage
1. construct an object,
2. set the array snapshot and array manifold vectors with
either setBeamformer() or setSnapShotArray() and setArrayManifold(),
3. process data at each frame by caling next().
*/
class ZelinskiPostFilter: public VectorComplexFeatureStream {
public:
ZelinskiPostFilter( VectorComplexFeatureStreamPtr &output, unsigned fftLen, double alpha=0.6, int type=2, int minFrames=0, const String& nm = "ZelinskPostFilter" );
~ZelinskiPostFilter();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
void set_beamformer(SubbandDSPtr &beamformer);
void set_snapshot_array(SnapShotArrayPtr &snapShotArray);
void set_array_manifold_vector(unsigned fbinX, gsl_vector_complex *arrayManifoldVector, bool halfBandShift, unsigned NC = 1);
const gsl_vector_complex* postfilter_weights(){
if( NULL == bf_weights_ )
return NULL;
return(bf_weights_->wp1());
}
#ifdef ENABLE_LEGACY_BTK_API
void setBeamformer(SubbandDSPtr &beamformer){ set_beamformer(beamformer); }
void setSnapShotArray(SnapShotArrayPtr &snapShotArray){ set_snapshot_array(snapShotArray); }
void setArrayManifoldVector(unsigned fbinX, gsl_vector_complex *arrayManifoldVector, bool halfBandShift, unsigned NC = 1){ set_array_manifold_vector(fbinX, arrayManifoldVector, halfBandShift, NC); }
const gsl_vector_complex* getPostFilterWeights(){ return postfilter_weights(); }
#endif
protected:
unsigned fftLen_;
VectorComplexFeatureStreamPtr samp_; /* output of the beamformer */
PostfilterType type_; /* the type of the Zelinski-postfilters */
double alpha_; /* forgetting factor */
int min_frames_;
SubbandDSPtr bf_ptr_; /* */
BeamformerWeights* bf_weights_;
bool has_bf_ptr_; /* true if bf_ptr_ is set with setBeamformer() */
SnapShotArrayPtr snapshot_array_; /* multi-channel input */
};
typedef Inherit<ZelinskiPostFilter, VectorComplexFeatureStreamPtr> ZelinskiPostFilterPtr;
/**
@class McCowan post-filtering
@brief process the beamformer's outputs with McCowan's post-filtering
@usage
1. construct an object,
2. compute the noise coherence matrix through setDiffuseNoiseModel( micPositions, ssampleRate)
3. set the array snapshot and array manifold vectors with
either setBeamformer() or setSnapShotArray() and setArrayManifold(),
4. process data at each frame by caling next().
*/
class McCowanPostFilter: public ZelinskiPostFilter {
public:
McCowanPostFilter( VectorComplexFeatureStreamPtr &output, unsigned fftLen, double alpha=0.6, int type=2, int minFrames=0, float threshold=0.99, const String& nm = "McCowanPostFilter" );
~McCowanPostFilter();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
/* micPositions[][x,y,z] */
const gsl_matrix_complex *noise_spatial_spectral_matrix( unsigned fbinX );
bool set_noise_spatial_spectral_matrix( unsigned fbinX, gsl_matrix_complex* Rnn );
bool set_diffuse_noise_model( const gsl_matrix* micPositions, double sampleRate, double sspeed = 343740.0 );
void set_all_diagonal_loading(float diagonalWeight);
void set_diagonal_looading(unsigned fbinX, float diagonalWeight);
void divide_all_nondiagonal_elements(float mu);
void divide_nondiagonal_elements(unsigned fbinX, float mu);
#ifdef ENABLE_LEGACY_BTK_API
const gsl_matrix_complex *getNoiseSpatialSpectralMatrix(unsigned fbinX){ return noise_spatial_spectral_matrix(fbinX); }
bool setNoiseSpatialSpectralMatrix(unsigned fbinX, gsl_matrix_complex* Rnn){ return set_noise_spatial_spectral_matrix(fbinX, Rnn); }
bool setDiffuseNoiseModel(const gsl_matrix* micPositions, double sampleRate, double sspeed = 343740.0){ return set_diffuse_noise_model( micPositions, sampleRate, sspeed); }
void setAllLevelsOfDiagonalLoading(float diagonalWeight){ set_all_diagonal_loading(diagonalWeight); }
void setLevelOfDiagonalLoading(unsigned fbinX, float diagonalWeight){ set_diagonal_looading(fbinX, diagonalWeight); }
void divideAllNonDiagonalElements( float mu );
void divideNonDiagonalElements( unsigned fbinX, float mu );
#endif
protected:
double estimate_average_clean_PSD_( unsigned fbinX, gsl_vector_complex* currCSDf );
virtual void post_filtering_();
protected:
gsl_matrix_complex** R_; /* Noise spatial spectral matrices */
float* diagonal_weights_;
float threshold_of_Rij_; /* to avoid the indeterminate solution*/
gsl_vector_complex* time_aligned_signal_f_; /* workspace */
bool invR_computed_;
};
typedef Inherit<McCowanPostFilter, ZelinskiPostFilterPtr> McCowanPostFilterPtr;
/**
@class Lefkimmiatis post-filtering
@brief compute a Winer filter under the the diffuse noise field assumption
@usage
1. construct an object,
2. compute the noise coherence matrix through setDiffuseNoiseModel( micPositions, ssampleRate)
3. set the array snapshot and array manifold vectors with
either setBeamformer() or setSnapShotArray() and setArrayManifold(),
4. process data at each frame by caling next().
*/
class LefkimmiatisPostFilter: public McCowanPostFilter {
public:
LefkimmiatisPostFilter( VectorComplexFeatureStreamPtr &output, unsigned fftLen, double minSV=1.0E-8, unsigned fbinX1=0, double alpha=0.6, int type=2, int minFrames=0, float threshold=0.99, const String& nm = "LefkimmiatisPostFilte" );
~LefkimmiatisPostFilter();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
/* micPositions[][x,y,z] */
void calc_inverse_noise_spatial_spectral_matrix();
#ifdef ENABLE_LEGACY_BTK_API
void calcInverseNoiseSpatialSpectralMatrix(){ calc_inverse_noise_spatial_spectral_matrix(); }
#endif
protected:
double estimate_average_noise_PSD_( unsigned fbinX, gsl_vector_complex* currCSDf );
virtual void post_filtering_();
private:
gsl_complex calcLambda( unsigned fbinX );
gsl_matrix_complex** invR_;
gsl_vector_complex* tmpH_;
double minSV_;
unsigned fbinX1_;
};
typedef Inherit<LefkimmiatisPostFilter, McCowanPostFilterPtr> LefkimmiatisPostFilterPtr;
/**
@class high pass filter
*/
class HighPassFilter: public VectorComplexFeatureStream {
public:
HighPassFilter( VectorComplexFeatureStreamPtr &output, float cutOffFreq, int sampleRate, const String& nm = "HighPassFilter" );
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset();
private:
VectorComplexFeatureStreamPtr src_;
unsigned cutoff_fbinX_;
};
typedef Inherit<HighPassFilter, VectorComplexFeatureStreamPtr> HighPassFilterPtr;
#endif
| {
"alphanum_fraction": 0.746785361,
"avg_line_length": 41.1719457014,
"ext": "h",
"hexsha": "d5acc73398cce5940e876b4d3f193b0c8175aba2",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z",
"max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "musiclvme/distant_speech_recognition",
"max_forks_repo_path": "btk20_src/postfilter/postfilter.h",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "musiclvme/distant_speech_recognition",
"max_issues_repo_path": "btk20_src/postfilter/postfilter.h",
"max_line_length": 236,
"max_stars_count": 136,
"max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "musiclvme/distant_speech_recognition",
"max_stars_repo_path": "btk20_src/postfilter/postfilter.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z",
"num_tokens": 2307,
"size": 9099
} |
/**
* @file ssygvd.c
*
* PLASMA computational routines
* Release Date: November, 15th 2009
* 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
* @author Hatem Ltaief
* @date 2010-11-15
* @generated s Tue Jan 7 11:45:09 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup float
*
* PLASMA_ssygvd - Computes all eigenvalues and, optionally,
* eigenvectors of a complex generalized Hermitian-definite
* eigenproblem of the form: A*x=(lambda)*B*x, A*Bx=(lambda)*x, or
* B*A*x=(lambda)*x.
* Here A and B are assumed to be Hermitian and B is also positive
* definite.
*
*******************************************************************************
*
* @param[in] itype
* Intended usage:
* = 1: A*x=(lambda)*B*x
* = 2: A*Bx=(lambda)*x
* = 3: B*A*x=(lambda)*x
*
* @param[in] jobz
* Intended usage:
* = PlasmaNoVec: computes eigenvalues only;
* = PlasmaVec: computes eigenvalues and eigenvectors.
*
* @param[in] uplo
* Specifies whether the matrix A is upper triangular or
* lower triangular:
* = PlasmaUpper: Upper triangle of A and B are stored;
* = PlasmaLower: Lower triangle of A and B are stored.
*
* @param[in] N
* The order of the matrix A. N >= 0.
*
* @param[in,out] A
* On entry, the symmetric (or Hermitian) 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 = PlasmaLower, 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.
* On exit, if jobz = PlasmaVec, then if return value = 0, A
* contains the matrix Z of eigenvectors.
* The eigenvectors are normalized as follows:
* if ITYPE = 1 or 2, Z**T*B*Z = I;
* if ITYPE = 3, Z**T*inv(B)*Z = I.
* If jobz = PlasmaNoVec, then on exit the lower triangle (if
* uplo = PlasmaLower) or the upper triangle (if uplo =
* PlasmaUpper) of A, including the diagonal, is destroyed.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,N).
*
* @param[in,out] B
* On entry, the symmetric (or Hermitian) positive definite
* matrix B.
* If uplo = PlasmaUpper, the leading N-by-N upper triangular
* part of B contains the upper triangular part of the matrix
* B, and the strictly lower triangular part of B is not
* referenced.
* If uplo = PlasmaLower, the leading N-by-N lower triangular
* part of B contains the lower triangular part of the matrix
* B, and the strictly upper triangular part of B is not
* referenced.
* On exit, if return value <= N, the part of B containing
* the matrix is overwritten by the triangular factor U or L
* from the Cholesky factorization B = U**T*U or B = L*L**T.
*
* @param[in] LDB
* The leading dimension of the array B. LDA >= max(1,N).
*
* @param[out] W
* On exit, if info = 0, the eigenvalues.
*
* @param[in, out] descT
* On entry, descriptor as return by PLASMA_Alloc_Workspace_ssygvd
* On exit, contains auxiliary factorization data.
*
* @param[out] Q
* On exit, if jobz = PlasmaVec and info = 0, the eigenvectors.
*
* @param[in] LDQ
* The leading dimension of Q.
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
* \retval <=N if INFO = i, plasma_ssygvd failed to converge; i
* off-diagonal elements of an intermediate tridiagonal
* form did not converge to zero.
* \retval >N if INFO = N + i, for 1 <= i <= N, then the leading
* minor of order i of B is not positive definite.
* The factorization of B could not be completed and
* no eigenvalues or eigenvectors were computed.
*
*******************************************************************************
*
* @sa PLASMA_ssygvd_Tile
* @sa PLASMA_ssygvd_Tile_Async
* @sa PLASMA_chegvd
* @sa PLASMA_dsygvd
* @sa PLASMA_ssygvd
*
******************************************************************************/
int PLASMA_ssygvd(PLASMA_enum itype, PLASMA_enum jobz, PLASMA_enum uplo, int N,
float *A, int LDA,
float *B, int LDB,
float *W,
PLASMA_desc *descT,
float *Q, int LDQ)
{
int NB;
int status;
plasma_context_t *plasma;
PLASMA_sequence *sequence = NULL;
PLASMA_request request = PLASMA_REQUEST_INITIALIZER;
PLASMA_desc descA, descB, descQ;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA_ssygvd", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
/* Check input arguments */
if (itype != 1 && itype != 2 && itype != 3) {
plasma_error("PLASMA_ssygvd", "Illegal value of itype");
return -1;
}
if (jobz != PlasmaNoVec && jobz != PlasmaVec) {
plasma_error("PLASMA_ssygvd", "illegal value of jobz");
return -2;
}
if (uplo != PlasmaLower && uplo!= PlasmaUpper) {
plasma_error("PLASMA_ssygvd", "only PlasmaLower supported");
return -3;
}
if (N < 0) {
plasma_error("PLASMA_ssygvd", "illegal value of N");
return -4;
}
if (LDA < max(1, N)) {
plasma_error("PLASMA_ssygvd", "illegal value of LDA");
return -6;
}
if (LDB < max(1, N)) {
plasma_error("PLASMA_ssygvd", "illegal value of LDB");
return -8;
}
if (LDQ < max(1, N)) {
plasma_error("PLASMA_ssygvd", "illegal value of LDQ");
return -12;
}
/* Quick return */
if (N == 0)
return PLASMA_SUCCESS;
/* Tune NB & IB depending on N; Set NBNB */
status = plasma_tune(PLASMA_FUNC_SSYGV, N, N, 0);
if (status != PLASMA_SUCCESS) {
plasma_error("PLASMA_ssygvd", "plasma_tune() failed");
return status;
}
/* Set NT */
NB = PLASMA_NB;
plasma_sequence_create(plasma, &sequence);
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_sooplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N, sequence, &request,
plasma_desc_mat_free(&(descA)) );
plasma_sooplap2tile( descB, B, NB, NB, LDB, N, 0, 0, N, N, sequence, &request,
plasma_desc_mat_free(&(descA)); plasma_desc_mat_free(&(descB)) );
/* No conversion for Q */
} else {
plasma_siplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N,
sequence, &request);
plasma_siplap2tile( descB, B, NB, NB, LDB, N, 0, 0, N, N,
sequence, &request);
}
/* Q is used only as an output */
descQ = plasma_desc_init(
PlasmaRealFloat, NB, NB, NB*NB,
LDQ, N, 0, 0, N, N);
descQ.mat = Q;
/* Call the tile interface */
PLASMA_ssygvd_Tile_Async(itype, jobz, uplo,
&descA, &descB, W,
descT, &descQ,
sequence, &request);
plasma_siptile2lap( descQ, Q, NB, NB, LDQ, N, sequence, &request);
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_sooptile2lap( descA, A, NB, NB, LDA, N, sequence, &request);
plasma_sooptile2lap( descB, B, NB, NB, LDB, N, sequence, &request);
plasma_dynamic_sync();
plasma_desc_mat_free(&descA);
plasma_desc_mat_free(&descB);
} else {
plasma_siptile2lap( descA, A, NB, NB, LDA, N, sequence, &request);
plasma_siptile2lap( descB, B, NB, NB, LDB, N, sequence, &request);
plasma_dynamic_sync();
}
status = sequence->status;
plasma_sequence_destroy(plasma, sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup float_Tile
*
* PLASMA_ssygvd_Tile - Computes all eigenvalues and, optionally,
* eigenvectors of a complex generalized Hermitian-definite
* eigenproblem of the form: A*x=(lambda)*B*x, A*Bx=(lambda)*x, or
* B*A*x=(lambda)*x.
* Here A and B are assumed to be Hermitian and B is also
* positive definite.
*
* Tile equivalent of PLASMA_ssygvd().
* Operates on matrices stored by tiles.
* All matrices are passed through descriptors.
* All dimensions are taken from the descriptors.
*
*******************************************************************************
*
* @param[in] itype
* Intended usage:
* = 1: A*x=(lambda)*B*x
* = 2: A*Bx=(lambda)*x
* = 3: B*A*x=(lambda)*x
*
* @param[in] jobz
* Intended usage:
* = PlasmaNoVec: computes eigenvalues only;
* = PlasmaVec: computes eigenvalues and eigenvectors.
*
* @param[in] uplo
* Specifies whether the matrix A is upper triangular or
* lower triangular:
* = PlasmaUpper: Upper triangle of A and B are stored;
* = PlasmaLower: Lower triangle of A and B are stored.
*
* @param[in,out] A
* On entry, the symmetric (or Hermitian) 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 = PlasmaLower, 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.
* On exit, if jobz = PlasmaVec, then if return value = 0, A
* contains the matrix Z of eigenvectors.
* The eigenvectors are normalized as follows:
* if ITYPE = 1 or 2, Z**T*B*Z = I;
* if ITYPE = 3, Z**T*inv(B)*Z = I.
* If jobz = PlasmaNoVec, then on exit the lower triangle (if
* uplo = PlasmaLower) or the upper triangle (if uplo =
* PlasmaUpper) of A, including the diagonal, is destroyed.
*
* @param[in,out] B
* On entry, the symmetric (or Hermitian) positive definite
* matrix B.
* If uplo = PlasmaUpper, the leading N-by-N upper triangular
* part of B contains the upper triangular part of the matrix
* B, and the strictly lower triangular part of B is not
* referenced.
* If uplo = PlasmaLower, the leading N-by-N lower triangular
* part of B contains the lower triangular part of the matrix
* B, and the strictly upper triangular part of B is not
* referenced.
* On exit, if return value <= N, the part of B containing
* the matrix is overwritten by the triangular factor U or L
* from the Cholesky factorization B = U**T*U or B = L*L**T.
*
* @param[in,out] T
* On entry, descriptor as return by
* PLASMA_Alloc_Workspace_ssygvd
* On exit, contains auxiliary factorization data.
*
* @param[out] W
* On exit, if info = 0, the eigenvalues.
*
* @param[out] Q
* On exit, if jobz = PlasmaVec and info = 0, the eigenvectors.
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
* \retval <=N if INFO = i, plasma_ssygvd failed to converge; i
* off-diagonal elements of an intermediate tridiagonal
* form did not converge to zero.
* \retval >N if INFO = N + i, for 1 <= i <= N, then the leading
* minor of order i of B is not positive definite.
* The factorization of B could not be completed and
* no eigenvalues or eigenvectors were computed.
*
*******************************************************************************
*
* @sa PLASMA_ssygvd
* @sa PLASMA_ssygvd_Tile_Async
* @sa PLASMA_chegvd_Tile
* @sa PLASMA_dsygvd_Tile
* @sa PLASMA_ssygvd_Tile
*
******************************************************************************/
int PLASMA_ssygvd_Tile(PLASMA_enum itype, PLASMA_enum jobz, PLASMA_enum uplo,
PLASMA_desc *A, PLASMA_desc *B, float *W,
PLASMA_desc *T, PLASMA_desc *Q)
{
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_ssygvd_Tile", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
plasma_sequence_create(plasma, &sequence);
PLASMA_ssygvd_Tile_Async(itype, jobz, uplo, A, B, W, T, Q, sequence, &request);
plasma_dynamic_sync();
status = sequence->status;
plasma_sequence_destroy(plasma, sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup float_Tile_Async
*
* PLASMA_ssygvd_Tile - Computes all eigenvalues and, optionally,
* eigenvectors of a complex generalized Hermitian-definite
* eigenproblem of the form: A*x=(lambda)*B*x, A*Bx=(lambda)*x, or
* B*A*x=(lambda)*x.
* Here A and B are assumed to be Hermitian and B is also
* positive definite.
*
* Non-blocking equivalent of PLASMA_ssygvd_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_ssygvd
* @sa PLASMA_ssygvd_Tile
* @sa PLASMA_chegvd_Tile_Async
* @sa PLASMA_dsygvd_Tile_Async
* @sa PLASMA_ssygvd_Tile_Async
*
******************************************************************************/
int PLASMA_ssygvd_Tile_Async(PLASMA_enum itype, PLASMA_enum jobz, PLASMA_enum uplo,
PLASMA_desc *A, PLASMA_desc *B, float *W,
PLASMA_desc *T, PLASMA_desc *Q,
PLASMA_sequence *sequence, PLASMA_request *request)
{
int status;
PLASMA_desc descA;
PLASMA_desc descB;
PLASMA_desc descQ;
PLASMA_enum trans;
plasma_context_t *plasma;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_ssygvd_Tile_Async", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
if (sequence == NULL) {
plasma_fatal_error("PLASMA_ssygvd_Tile_Async", "NULL sequence");
return PLASMA_ERR_UNALLOCATED;
}
if (request == NULL) {
plasma_fatal_error("PLASMA_ssygvd_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_ssygvd_Tile_Async", "invalid first descriptor");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
} else {
descA = *A;
}
if (plasma_desc_check(B) != PLASMA_SUCCESS) {
plasma_error("PLASMA_ssygvd_Tile_Async", "invalid second descriptor");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
} else {
descB = *B;
}
if (plasma_desc_check(T) != PLASMA_SUCCESS) {
plasma_error("PLASMA_ssygvd_Tile_Async", "invalid T descriptor");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
}
if (plasma_desc_check(Q) != PLASMA_SUCCESS) {
plasma_error("PLASMA_ssygvd_Tile_Async", "invalid Q descriptor");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
} else {
descQ = *Q;
}
/* Check input arguments */
if (itype != 1 && itype != 2 && itype != 3) {
plasma_error("PLASMA_ssygvd_Tile_Async", "Illegal value of itype");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
}
if (jobz != PlasmaNoVec && jobz != PlasmaVec) {
plasma_error("PLASMA_ssygvd_Tile_Async", "illegal value of jobz");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
}
if (uplo != PlasmaLower && uplo != PlasmaUpper) {
plasma_error("PLASMA_ssygvd_Tile_Async", "illegal value of uplo");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
}
if (descA.nb != descA.mb) {
plasma_error("PLASMA_ssygvd_Tile_Async", "only square tiles supported");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
}
if ( (jobz == PlasmaVec) && (descA.nb != descA.mb) ) {
plasma_error("PLASMA_ssygv_Tile_Async", "only square tiles supported");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
}
/*
* Form a Cholesky factorization of B.
*/
plasma_parallel_call_4(plasma_pspotrf,
PLASMA_enum, uplo,
PLASMA_desc, descB,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
status = sequence->status;
if (status != 0){
status = descA.n + status;
return status;
}
/*
* Transform problem to standard eigenvalue problem and solve.
*/
plasma_dynamic_call_6(plasma_pssygst,
PLASMA_enum, itype,
PLASMA_enum, uplo,
PLASMA_desc, descA,
PLASMA_desc, descB,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/*
* Call Eigensolver
*/
status = PLASMA_ssyevd_Tile_Async( jobz, uplo,
A, W, T,
(float*)(Q->mat), Q->lm,
sequence, request );
/*
* Backtransform eigenvectors to the original problem.
*/
if( jobz == PlasmaVec ) {
if ( status != PLASMA_SUCCESS ) {
plasma_error("PLASMA_sheegvd", "ssygvd");
return status;
}
/*
* Convert back the lapack layout used in ssyev to tile layout
*/
plasma_siplap2tile( descQ, (float*)Q->mat, descQ.mb, descQ.nb, descQ.lm, descQ.ln,
0, 0, descQ.m, descQ.n, sequence, request );
if( (itype == 1) || (itype == 2) ) {
/*
* For A*x=(lambda)*B*x and A*B*x=(lambda)*x;
* backtransform eigenvectors: x = inv(L)**T *y or inv(U)*y
*/
if( uplo == PlasmaUpper )
trans = PlasmaNoTrans;
else
trans = PlasmaTrans;
plasma_parallel_call_9(plasma_pstrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, uplo,
PLASMA_enum, trans,
PLASMA_enum, PlasmaNonUnit,
float, 1.0,
PLASMA_desc, descB,
PLASMA_desc, descQ,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
else if( itype == 3 ) {
/*
* For B*A*x=(lambda)*x;
* backtransform eigenvectors: x = L*y or U**T *y
*/
if( uplo == PlasmaUpper )
trans = PlasmaTrans;
else
trans = PlasmaNoTrans;
plasma_dynamic_call_9(plasma_pstrmm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, uplo,
PLASMA_enum, trans,
PLASMA_enum, PlasmaNonUnit,
float, 1.0,
PLASMA_desc, descB,
PLASMA_desc, descQ,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
}
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.5603131189,
"avg_line_length": 37.5992907801,
"ext": "c",
"hexsha": "82a86c8ed38656bfc198bbc5d4f6edba33ed19fe",
"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/ssygvd.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/ssygvd.c",
"max_line_length": 94,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "compute/ssygvd.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5535,
"size": 21206
} |
/* multiroots/test_funcs.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_multiroots.h>
#include "test_funcs.h"
/* For information on testing see the following paper,
J.J More, B.S. Garbow, K.E. Hillstrom, "Testing Unconstrained
Optimization Software", ACM Transactions on Mathematical Software,
Vol 7, No 1, (1981) p 17-41
*/
/* Rosenbrock Function */
gsl_multiroot_function_fdf rosenbrock =
{&rosenbrock_f,
&rosenbrock_df,
&rosenbrock_fdf,
2, 0};
void
rosenbrock_initpt (gsl_vector * x)
{
gsl_vector_set (x, 0, -1.2);
gsl_vector_set (x, 1, 1.0);
}
int
rosenbrock_f (const gsl_vector * x, void *params, gsl_vector * f)
{
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double y0 = 1 - x0;
double y1 = 10 * (x1 - x0 * x0);
gsl_vector_set (f, 0, y0);
gsl_vector_set (f, 1, y1);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
rosenbrock_df (const gsl_vector * x, void *params, gsl_matrix * df)
{
double x0 = gsl_vector_get (x, 0);
double df00 = -1;
double df01 = 0;
double df10 = -20 * x0;
double df11 = 10;
gsl_matrix_set (df, 0, 0, df00);
gsl_matrix_set (df, 0, 1, df01);
gsl_matrix_set (df, 1, 0, df10);
gsl_matrix_set (df, 1, 1, df11);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
rosenbrock_fdf (const gsl_vector * x, void *params,
gsl_vector * f, gsl_matrix * df)
{
rosenbrock_f (x, params, f);
rosenbrock_df (x, params, df);
return GSL_SUCCESS;
}
/* Freudenstein and Roth function */
gsl_multiroot_function_fdf roth =
{&roth_f,
&roth_df,
&roth_fdf,
2, 0};
void
roth_initpt (gsl_vector * x)
{
gsl_vector_set (x, 0, 4.5); /* changed from the value in the paper */
gsl_vector_set (x, 1, 3.5); /* otherwise the problem is too hard */
}
int
roth_f (const gsl_vector * x, void *params, gsl_vector * f)
{
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double y0 = -13.0 + x0 + ((5.0 - x1)*x1 - 2.0)*x1;
double y1 = -29.0 + x0 + ((x1 + 1.0)*x1 - 14.0)*x1;
gsl_vector_set (f, 0, y0);
gsl_vector_set (f, 1, y1);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
roth_df (const gsl_vector * x, void *params, gsl_matrix * df)
{
double x1 = gsl_vector_get (x, 1);
double df00 = 1;
double df01 = -3 * x1 * x1 + 10 * x1 - 2;
double df10 = 1;
double df11 = 3 * x1 * x1 + 2 * x1 - 14;
gsl_matrix_set (df, 0, 0, df00);
gsl_matrix_set (df, 0, 1, df01);
gsl_matrix_set (df, 1, 0, df10);
gsl_matrix_set (df, 1, 1, df11);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
roth_fdf (const gsl_vector * x, void *params,
gsl_vector * f, gsl_matrix * df)
{
roth_f (x, params, f);
roth_df (x, params, df);
return GSL_SUCCESS;
}
/* Powell badly scaled function */
gsl_multiroot_function_fdf powellscal =
{&powellscal_f,
&powellscal_df,
&powellscal_fdf,
2, 0};
void
powellscal_initpt (gsl_vector * x)
{
gsl_vector_set (x, 0, 0.0);
gsl_vector_set (x, 1, 1.0);
}
int
powellscal_f (const gsl_vector * x, void *params, gsl_vector * f)
{
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double y0 = 10000.0 * x0 * x1 - 1.0;
double y1 = exp (-x0) + exp (-x1) - 1.0001;
gsl_vector_set (f, 0, y0);
gsl_vector_set (f, 1, y1);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
powellscal_df (const gsl_vector * x, void *params, gsl_matrix * df)
{
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double df00 = 10000.0 * x1, df01 = 10000.0 * x0;
double df10 = -exp (-x0), df11 = -exp (-x1);
gsl_matrix_set (df, 0, 0, df00);
gsl_matrix_set (df, 0, 1, df01);
gsl_matrix_set (df, 1, 0, df10);
gsl_matrix_set (df, 1, 1, df11);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
powellscal_fdf (const gsl_vector * x, void *params,
gsl_vector * f, gsl_matrix * df)
{
powellscal_f (x, params, f);
powellscal_df (x, params, df);
return GSL_SUCCESS;
}
/* Brown badly scaled function */
gsl_multiroot_function_fdf brownscal =
{&brownscal_f,
&brownscal_df,
&brownscal_fdf,
2, 0};
void
brownscal_initpt (gsl_vector * x)
{
gsl_vector_set (x, 0, 1.0);
gsl_vector_set (x, 1, 1.0);
}
int
brownscal_f (const gsl_vector * x, void *params, gsl_vector * f)
{
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double y0 = x0 - 1e6;
double y1 = x0 * x1 - 2;
gsl_vector_set (f, 0, y0);
gsl_vector_set (f, 1, y1);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
brownscal_df (const gsl_vector * x, void *params, gsl_matrix * df)
{
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double df00 = 1.0, df01 = 0.0;
double df10 = x1, df11 = x0;
gsl_matrix_set (df, 0, 0, df00);
gsl_matrix_set (df, 0, 1, df01);
gsl_matrix_set (df, 1, 0, df10);
gsl_matrix_set (df, 1, 1, df11);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
brownscal_fdf (const gsl_vector * x, void *params,
gsl_vector * f, gsl_matrix * df)
{
brownscal_f (x, params, f);
brownscal_df (x, params, df);
return GSL_SUCCESS;
}
/* Powell Singular Function */
gsl_multiroot_function_fdf powellsing =
{&powellsing_f,
&powellsing_df,
&powellsing_fdf,
4, 0};
void
powellsing_initpt (gsl_vector * x)
{
gsl_vector_set (x, 0, 3.0);
gsl_vector_set (x, 1, -1.0);
gsl_vector_set (x, 2, 0.0);
gsl_vector_set (x, 3, 1.0);
}
int
powellsing_f (const gsl_vector * x, void *params, gsl_vector * f)
{
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double x2 = gsl_vector_get (x, 2);
double x3 = gsl_vector_get (x, 3);
double y0 = x0 + 10 * x1;
double y1 = sqrt (5.0) * (x2 - x3);
double y2 = pow (x1 - 2 * x2, 2.0);
double y3 = sqrt (10.0) * pow (x0 - x3, 2.0);
gsl_vector_set (f, 0, y0);
gsl_vector_set (f, 1, y1);
gsl_vector_set (f, 2, y2);
gsl_vector_set (f, 3, y3);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
powellsing_df (const gsl_vector * x, void *params, gsl_matrix * df)
{
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double x2 = gsl_vector_get (x, 2);
double x3 = gsl_vector_get (x, 3);
double df00 = 1, df01 = 10, df02 = 0, df03 = 0;
double df10 = 0, df11 = 0, df12 = sqrt (5.0), df13 = -df12;
double df20 = 0, df21 = 2 * (x1 - 2 * x2), df22 = -2 * df21, df23 = 0;
double df30 = 2 * sqrt (10.0) * (x0 - x3), df31 = 0, df32 = 0, df33 = -df30;
gsl_matrix_set (df, 0, 0, df00);
gsl_matrix_set (df, 0, 1, df01);
gsl_matrix_set (df, 0, 2, df02);
gsl_matrix_set (df, 0, 3, df03);
gsl_matrix_set (df, 1, 0, df10);
gsl_matrix_set (df, 1, 1, df11);
gsl_matrix_set (df, 1, 2, df12);
gsl_matrix_set (df, 1, 3, df13);
gsl_matrix_set (df, 2, 0, df20);
gsl_matrix_set (df, 2, 1, df21);
gsl_matrix_set (df, 2, 2, df22);
gsl_matrix_set (df, 2, 3, df23);
gsl_matrix_set (df, 3, 0, df30);
gsl_matrix_set (df, 3, 1, df31);
gsl_matrix_set (df, 3, 2, df32);
gsl_matrix_set (df, 3, 3, df33);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
powellsing_fdf (const gsl_vector * x, void *params,
gsl_vector * f, gsl_matrix * df)
{
powellsing_f (x, params, f);
powellsing_df (x, params, df);
return GSL_SUCCESS;
}
/* Wood function */
gsl_multiroot_function_fdf wood =
{&wood_f,
&wood_df,
&wood_fdf,
4, 0};
void
wood_initpt (gsl_vector * x)
{
gsl_vector_set (x, 0, -3.0);
gsl_vector_set (x, 1, -1.0);
gsl_vector_set (x, 2, -3.0);
gsl_vector_set (x, 3, -1.0);
}
int
wood_f (const gsl_vector * x, void *params, gsl_vector * f)
{
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double x2 = gsl_vector_get (x, 2);
double x3 = gsl_vector_get (x, 3);
double t1 = x1 - x0 * x0;
double t2 = x3 - x2 * x2;
double y0 = -200.0 * x0 * t1 - (1 - x0);
double y1 = 200.0 * t1 + 20.2 * (x1 - 1) + 19.8 * (x3 - 1);
double y2 = -180.0 * x2 * t2 - (1 - x2);
double y3 = 180.0 * t2 + 20.2 * (x3 - 1) + 19.8 * (x1 - 1);
gsl_vector_set (f, 0, y0);
gsl_vector_set (f, 1, y1);
gsl_vector_set (f, 2, y2);
gsl_vector_set (f, 3, y3);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
wood_df (const gsl_vector * x, void *params, gsl_matrix * df)
{
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double x2 = gsl_vector_get (x, 2);
double x3 = gsl_vector_get (x, 3);
double t1 = x1 - 3 * x0 * x0;
double t2 = x3 - 3 * x2 * x2;
double df00 = -200.0 * t1 + 1, df01 = -200.0 * x0, df02 = 0, df03 = 0;
double df10 = -400.0*x0, df11 = 200.0 + 20.2, df12 = 0, df13 = 19.8;
double df20 = 0, df21 = 0, df22 = -180.0 * t2 + 1, df23 = -180.0 * x2;
double df30 = 0, df31 = 19.8, df32 = -2 * 180 * x2, df33 = 180.0 + 20.2;
gsl_matrix_set (df, 0, 0, df00);
gsl_matrix_set (df, 0, 1, df01);
gsl_matrix_set (df, 0, 2, df02);
gsl_matrix_set (df, 0, 3, df03);
gsl_matrix_set (df, 1, 0, df10);
gsl_matrix_set (df, 1, 1, df11);
gsl_matrix_set (df, 1, 2, df12);
gsl_matrix_set (df, 1, 3, df13);
gsl_matrix_set (df, 2, 0, df20);
gsl_matrix_set (df, 2, 1, df21);
gsl_matrix_set (df, 2, 2, df22);
gsl_matrix_set (df, 2, 3, df23);
gsl_matrix_set (df, 3, 0, df30);
gsl_matrix_set (df, 3, 1, df31);
gsl_matrix_set (df, 3, 2, df32);
gsl_matrix_set (df, 3, 3, df33);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
wood_fdf (const gsl_vector * x, void *params,
gsl_vector * f, gsl_matrix * df)
{
wood_f (x, params, f);
wood_df (x, params, df);
return GSL_SUCCESS;
}
/* Helical Valley Function */
gsl_multiroot_function_fdf helical =
{&helical_f,
&helical_df,
&helical_fdf,
3, 0};
void
helical_initpt (gsl_vector * x)
{
gsl_vector_set (x, 0, -1.0);
gsl_vector_set (x, 1, 0.0);
gsl_vector_set (x, 2, 0.0);
}
int
helical_f (const gsl_vector * x, void *params, gsl_vector * f)
{
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double x2 = gsl_vector_get (x, 2);
double t1, t2;
double y0, y1, y2;
if (x0 > 0)
{
t1 = atan(x1/x0) / (2.0 * M_PI);
}
else if (x0 < 0)
{
t1 = 0.5 + atan(x1/x0) / (2.0 * M_PI);
}
else
{
t1 = 0.25 * (x1 > 0 ? +1 : -1);
}
t2 = sqrt(x0*x0 + x1*x1) ;
y0 = 10 * (x2 - 10 * t1);
y1 = 10 * (t2 - 1);
y2 = x2 ;
gsl_vector_set (f, 0, y0);
gsl_vector_set (f, 1, y1);
gsl_vector_set (f, 2, y2);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
helical_df (const gsl_vector * x, void *params, gsl_matrix * df)
{
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double t = x0 * x0 + x1 * x1 ;
double t1 = 2 * M_PI * t ;
double t2 = sqrt(t) ;
double df00 = 100*x1/t1, df01 = -100.0 * x0/t1, df02 = 10.0;
double df10 = 10*x0/t2, df11 = 10*x1/t2, df12 = 0;
double df20 = 0, df21 = 0, df22 = 1.0;
gsl_matrix_set (df, 0, 0, df00);
gsl_matrix_set (df, 0, 1, df01);
gsl_matrix_set (df, 0, 2, df02);
gsl_matrix_set (df, 1, 0, df10);
gsl_matrix_set (df, 1, 1, df11);
gsl_matrix_set (df, 1, 2, df12);
gsl_matrix_set (df, 2, 0, df20);
gsl_matrix_set (df, 2, 1, df21);
gsl_matrix_set (df, 2, 2, df22);
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
helical_fdf (const gsl_vector * x, void *params,
gsl_vector * f, gsl_matrix * df)
{
helical_f (x, params, f);
helical_df (x, params, df);
return GSL_SUCCESS;
}
/* Discrete Boundary Value Function */
#define N 10
gsl_multiroot_function_fdf dbv =
{&dbv_f,
&dbv_df,
&dbv_fdf,
N, 0};
void
dbv_initpt (gsl_vector * x)
{
size_t i;
double h = 1.0 / (N + 1.0);
for (i = 0; i < N; i++)
{
double t = (i + 1) * h;
double z = t * (t - 1);
gsl_vector_set (x, i, z);
}
}
int
dbv_f (const gsl_vector * x, void *params, gsl_vector * f)
{
size_t i;
double h = 1.0 / (N + 1.0);
for (i = 0; i < N; i++)
{
double z, ti = (i + 1) * h;
double xi = 0, xim1 = 0, xip1 = 0;
xi = gsl_vector_get (x, i);
if (i > 0)
xim1 = gsl_vector_get (x, i - 1);
if (i < N - 1)
xip1 = gsl_vector_get (x, i + 1);
z = 2 * xi - xim1 - xip1 + h * h * pow(xi + ti + 1, 3.0) / 2.0;
gsl_vector_set (f, i, z);
}
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
dbv_df (const gsl_vector * x, void *params, gsl_matrix * df)
{
size_t i, j;
double h = 1.0 / (N + 1.0);
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
gsl_matrix_set (df, i, j, 0.0);
for (i = 0; i < N; i++)
{
double dz_dxi, ti = (i + 1) * h;
double xi = gsl_vector_get (x, i);
dz_dxi = 2.0 + (3.0 / 2.0) * h * h * pow(xi + ti + 1, 2.0) ;
gsl_matrix_set (df, i, i, dz_dxi);
if (i > 0)
gsl_matrix_set (df, i, i-1, -1.0);
if (i < N - 1)
gsl_matrix_set (df, i, i+1, -1.0);
}
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
dbv_fdf (const gsl_vector * x, void *params,
gsl_vector * f, gsl_matrix * df)
{
dbv_f (x, params, f);
dbv_df (x, params, df);
return GSL_SUCCESS;
}
/* Trigonometric Function */
gsl_multiroot_function_fdf trig =
{&trig_f,
&trig_df,
&trig_fdf,
N, 0};
void
trig_initpt (gsl_vector * x)
{
size_t i;
for (i = 0; i < N; i++) /* choose an initial point which converges */
{
gsl_vector_set (x, i, 0.05);
}
}
int
trig_f (const gsl_vector * x, void *params, gsl_vector * f)
{
size_t i;
double sum = 0;
for (i = 0; i < N; i++)
{
sum += cos(gsl_vector_get(x,i));
}
for (i = 0; i < N; i++)
{
double xi = gsl_vector_get (x,i);
double z = N - sum + (i + 1) * (1 - cos(xi)) - sin(xi);
gsl_vector_set (f, i, z);
}
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
trig_df (const gsl_vector * x, void *params, gsl_matrix * df)
{
size_t i, j;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
double dz;
double xi = gsl_vector_get(x, i);
double xj = gsl_vector_get(x, j);
if (j == i)
dz = sin(xi) + (i + 1) * sin(xi) - cos(xi);
else
dz = sin(xj);
gsl_matrix_set(df, i, j, dz);
}
}
params = 0; /* avoid warning about unused parameters */
return GSL_SUCCESS;
}
int
trig_fdf (const gsl_vector * x, void *params,
gsl_vector * f, gsl_matrix * df)
{
trig_f (x, params, f);
trig_df (x, params, df);
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.6052031903,
"avg_line_length": 21.2053691275,
"ext": "c",
"hexsha": "319b3fd106986e2be87e2f00a5975397a82ed5d2",
"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/multiroots/test_funcs.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/multiroots/test_funcs.c",
"max_line_length": 78,
"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/multiroots/test_funcs.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": 6019,
"size": 15798
} |
/* StdVarTrajs_Sampling.c
Simulation for calculating allele trajectories, adaptation from standing variation
To be fed into MSMS
Simulation uses routines found with the GNU Scientific Library (GSL)
(http://www.gnu.org/software/gsl/)
Since GSL is distributed under the GNU General Public License
(http://www.gnu.org/copyleft/gpl.html), you must download it
separately from this file.
This program can be compiled with e.g. GCC using a command like:
gcc StdVarTrajs_Sampling -lm -lgsl -lgslcblas -I/usr/local/include -L/usr/local/lib StdVarTrajs_Sampling.c
Then run by executing:
./StdVarTrajs_Sampling N s h x0 reps cutoff
Where:
- N is the (haploid) size
- s is the selection coefficient of the beneficial allele
- h is dominance of the beneficial allele
- x0 is frequency of the allele when it started to be selected for
- reps is how many times the second allele should FIX before simulation stops
(the number of actual runs is greater due to stochastic loss)
- cutoff denotes how high the derived allele can be in the neutral phase ('0' for fixation, '1' for x0 + 1/2N)
*/
/* Preprocessor statements */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <stddef.h>
#include <string.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <sys/stat.h>
#include <sys/types.h>
#define INITTS 310000
/* Function prototypes */
void geninit(double *geninit, double pee);
void selection(double *geninit, double h, double s);
void reproduction(double *geninit);
void bentraj(double *XFreq, unsigned int *btime, double *genotype, double x0, unsigned int rep, unsigned int N, double s, double h, const gsl_rng *r);
void neutraj(double *NFreq, unsigned int *ntime, double *genotype, double x0, unsigned int rep, unsigned int N, unsigned int cutoff, const gsl_rng *r);
void trajprint(double **AFreq, unsigned int *ttime, unsigned int rep);
void Wait();
/* Initialising genotypes */
void geninit(double *geninit, double pee){
*(geninit + 0) = (1-pee)*(1-pee);
*(geninit + 1) = 2*pee*(1-pee);
*(geninit + 2) = pee*pee;
} /* End of gen initiation routine */
/* Selection routine (single locus) */
void selection(double *geninit, double h, double s){
/* Fitness of each genotype */
double WAA, WAa, Waa;
double Wmean; /* Mean fitness */
Waa = 1;
WAa = 1 + h*s;
WAA = 1 + s;
/* Mean fitness calculation */
Wmean = ((*(geninit + 0))*Waa) + ((*(geninit + 1))*WAa) + ((*(geninit + 2))*WAA);
/* Changing frequencies by selection */
*(geninit + 0) = ((*(geninit + 0))*Waa)/Wmean;
*(geninit + 1) = ((*(geninit + 1))*WAa)/Wmean;
*(geninit + 2) = ((*(geninit + 2))*WAA)/Wmean;
} /* End of selection routine */
/* Reproduction routine */
void reproduction(double *geninit){
/* Fed-in genotype frequencies (for ease of programming) */
double gaas, gAas, gAAs;
/* Haplotypes */
double xA, xa;
/* Initial definition of genotypes */
gaas = *(geninit + 0);
gAas = *(geninit + 1);
gAAs = *(geninit + 2);
/* Baseline change in haplotype frequencies with obligate outcrossing */
xA = gAAs + (gAas)/2.0;
xa = gaas + (gAas)/2.0;
/* Change in frequencies (HWE) */
*(geninit + 0) = pow(xa,2);
*(geninit + 1) = 2.0*xA*xa;
*(geninit + 2) = pow(xA,2);
} /* End of reproduction routine */
/* Routine to simulate beneficial allele trajectory */
void bentraj(double *XFreq, unsigned int *btime, double *genotype, double x0, unsigned int rep, unsigned int N, double s, double h, const gsl_rng *r){
unsigned int gt = 1; /* Generation time */
unsigned int done = 0; /* Counter if routine done or not */
unsigned int exitl = 0; /* Decide if exit loop or not */
unsigned int i; /* Genotype counter */
double x = 0; /* Beneficial allele frequency */
unsigned int *gensamp = calloc(3,sizeof(unsigned int)); /* New population samples */
while(done == 0){
exitl = 0;
gt = 1;
x = x0;
*(XFreq + 0) = x0;
/* Initiating genotypes */
geninit(genotype,x0);
while(exitl == 0){
/* Selection routine */
selection(genotype,h,s);
/* Reproduction routine */
reproduction(genotype);
/* Sampling based on new frequencies */
gsl_ran_multinomial(r,3,N,genotype,gensamp);
for(i = 0; i < 3; i++){
*(genotype + i) = (*(gensamp + i))/(1.0*N);
}
x = 0.5*(*(genotype + 1)) + (*(genotype + 2));
*(XFreq + gt) = x;
gt += 1;
if(gt > INITTS){
fprintf(stderr,"Number of generations in selection trajectory exceed vector length (INITTS).\n");
exit(1);
}
if( (x == 1) || (x == 0) ){
exitl = 1;
}
}
if(x == 1){
done = 1;
*(btime + rep) = (gt - 1);
}
}
free(gensamp);
}
/* Routine to simulate neutral allele trajectory */
void neutraj(double *NFreq, unsigned int *ntime, double *genotype, double x0, unsigned int rep, unsigned int N, unsigned int cutoff, const gsl_rng *r){
unsigned int gt = 1; /* Generation time */
unsigned int done = 0; /* Counter if routine done or not */
unsigned int exitl = 0; /* Decide if exit loop or not */
unsigned int i; /* Genotype counter */
double x = 0; /* Neutral allele frequency */
double xmax = 1; /* Value of x to use as maximum cutoff */
unsigned int *gensamp = calloc(3,sizeof(unsigned int)); /* New population samples */
if(cutoff == 0){
xmax = 1;
}else if(cutoff == 1){
xmax = x0 + (1.0/(2.0*N));
if(xmax > 1){
xmax = 1;
}
}
/* printf("xmax is %lf\n",xmax); */
while(done == 0){
exitl = 0;
gt = 0; /* Note start from zero here since x0 case defined in selection trajectory */
x = x0;
/* Initiating genotypes */
geninit(genotype,x0);
while(exitl==0){
/* Reproduction routine */
reproduction(genotype);
/* Random sampling of allele frequencies (drift) */
gsl_ran_multinomial(r,3,N,genotype,gensamp);
for(i = 0; i < 3; i++){
*(genotype + i) = (*(gensamp + i))/(1.0*N);
}
x = 0.5*(*(genotype + 1)) + (*(genotype + 2));
*(NFreq + gt) = x;
gt++;
if(gt > INITTS){
printf("Number of generations in neutral trajectory exceed vector length (INITTS).\n");
exit(1);
}
if( (x == 0) || (x >= xmax) ){
exitl = 1;
}
}
if(x == 0){
done = 1;
*(ntime + rep) = (gt - 1);
}
}
free(gensamp);
}
/* Print out trajectories to file */
void trajprint(double **AFreq, unsigned int *ttime, unsigned int rep){
unsigned int j;
char filename[32];
FILE *ofp_tr; /* Pointer for file output */
sprintf(filename,"Traj/ATraj%d.dat",(rep + 1));
ofp_tr = fopen(filename,"w");
for(j = 0; j < *(ttime + rep); j++){
fprintf(ofp_tr,"%lf %lf %lf\n",*((*(AFreq + 0)) + j),*((*(AFreq + 1)) + j),*((*(AFreq + 2)) + j));
}
fclose(ofp_tr);
}
void Wait(){
printf("Press Enter to Continue");
while( getchar() != '\n' );
printf("\n");
}
/* Main program */
int main(int argc, char *argv[]){
/* Declare variables here */
unsigned int i, a; /* Rep counter, memory counter */
unsigned int N = 0; /* Population Size */
unsigned int Nreps = 0; /* Number of repetitions */
unsigned int acc = 0; /* Accumulator (when merging two trajectories) */
unsigned int es = 10; /* How many extra steps to put in the trajectory files */
unsigned int cutoff = 0; /* What kind of back-in-time cutoff to use */
int j; /* Timestep counter */
double s = 0; /* Strength of selection */
double h = 0; /* Dominance level */
double x0 = 0; /* Initial allele frequency */
double lim = 0; /* Limit of acceptable allele frequencies */
double dx = 0; /* Rescaled timestep so can be used by MSMS */
FILE *ofp_sd; /* Pointer for seed output */
/* GSL random number definitions */
const gsl_rng_type * T;
gsl_rng * r;
/* Reading in data from command line */
/* <Program> N s h x0 NReps cutoff */
if(argc != 7){
fprintf(stderr,"Six inputs are needed (N s h x0 Reps cutoff).\n");
exit(1);
}
N = atoi(argv[1]);
if(N <= 0){
fprintf(stderr,"Total Population size N is zero or negative, not allowed.\n");
exit(1);
}
/* Defining min frequency limit ** based on unscaled N ** */
lim = (1.0/(1.0*N));
/* Defining timestep, dx = 1/4N since that's what MSMS uses */
dx = (1.0/(4.0*N));
s = strtod(argv[2],NULL);
if(s < 0){
fprintf(stderr,"Allele strength s is negative, not allowed.\n");
exit(1);
}
h = strtod(argv[3],NULL);
if(h < 0 || h > 1){
fprintf(stderr,"Dominance value must lie between 0 and 1.\n");
exit(1);
}
x0 = strtod(argv[4],NULL);
if(x0 < lim || x0 > (1-lim)){
fprintf(stderr,"Initial mutant frequency must lie between %0.5lf and %0.5lf.\n",lim,1-lim);
exit(1);
}
/* Number of samples/reps to take */
Nreps = atoi(argv[5]);
if(Nreps <= 0){
fprintf(stderr,"Must set positive number of repetitions.\n");
exit(1);
}
/* Determining cutoff */
cutoff = atoi(argv[6]);
if(!(cutoff == 0 || cutoff == 1)){
fprintf(stderr,"'Cutoff' switch must equal 0 or 1.\n");
exit(1);
}
unsigned int *btime = calloc(Nreps,sizeof(unsigned int)); /* Number of generations needed for ben allele fixation */
unsigned int *ntime = calloc(Nreps,sizeof(unsigned int)); /* Number of generations needed for neut allele loss */
unsigned int *ttime = calloc(Nreps,sizeof(unsigned int)); /* Number of generations needed for whole processes */
double *genotype = calloc(3,sizeof(double)); /* Genotype frequencies */
/* create a generator chosen by the
environment variable GSL_RNG_TYPE */
gsl_rng_env_setup();
if (!getenv("GSL_RNG_SEED")) gsl_rng_default_seed = time(0);
T = gsl_rng_default;
r = gsl_rng_alloc(T);
ofp_sd = fopen("Seed.dat","w");
fprintf(ofp_sd,"%lu\n",gsl_rng_default_seed);
fclose(ofp_sd);
mkdir("Traj/", 0777);
/* Executing simulation */
for(i = 0; i < Nreps; i++){
if(Nreps > 100){
if(i%100 == 0){
printf("Starting run %d\n",i);
}
}
double *XFreq = calloc(INITTS,sizeof(double)); /* Beneficial allele frequency */
double *NFreq = calloc(INITTS,sizeof(double)); /* Neutral allele frequency */
/* Simulating beneficial trajectories */
bentraj(XFreq, btime, genotype, x0, i, N, s, h, r);
/* Simulation neutral trajectory */
neutraj(NFreq, ntime, genotype, x0, i, N, cutoff, r);
*(ttime + i) = (*(btime+i)) + (*(ntime+i) + 2 + es);
/* printf("%d %d %d\n",*(btime+i),*(ntime+i),*(ttime+i)); */
/* Defining memory for AFreq */
double **AFreq = calloc(3,sizeof(double *)); /* Allele frequency over time */
for(a = 0; a < 3; a++){ /* Assigning space for each run */
AFreq[a] = calloc(*(ttime + i),sizeof(double));
}
/* Merging trajectories
Timing is set up so tfix = 0
And discrete generations is scaled by timestep, dx
*/
/* First add ten timesteps for x = 0
So trajectory fully covered in MSMS */
acc = 0;
for(j = 0; j < es; j++){
*((*(AFreq + 0)) + j) = ((*(ttime + i) - es - 1)*dx) + (es - j);
*((*(AFreq + 1)) + j) = 1.0;
*((*(AFreq + 2)) + j) = 0.0;
}
for(j = *(ntime + i); j >= 0; j--){
*((*(AFreq + 0)) + acc + es) = (*(ttime + i) - acc - es - 1)*dx;
*((*(AFreq + 1)) + acc + es) = 1.0-(*(NFreq + j));
*((*(AFreq + 2)) + acc + es) = *(NFreq + j);
acc++;
}
for(j = 0; j <= *(btime + i); j++){
*((*(AFreq + 0)) + acc + es) = (*(ttime + i) - acc - es - 1)*dx;
*((*(AFreq + 1)) + acc + es) = 1.0-(*(XFreq + j));
*((*(AFreq + 2)) + acc + es) = *(XFreq + j);
acc++;
}
/*
*(ttime + i) = (acc-1);
printf("%d\n",*(ttime+i));
*/
free(NFreq);
free(XFreq);
/* Printout of trajectories */
trajprint(AFreq, ttime, i);
for(a = 0; a < 3; a++){
free(AFreq[a]);
}
free(AFreq);
}
gsl_rng_free(r);
free(genotype);
free(ttime);
free(ntime);
free(btime);
return 0;
} /* End of main program */
/* End of File */ | {
"alphanum_fraction": 0.6072629455,
"avg_line_length": 28.3914081146,
"ext": "c",
"hexsha": "cfd4fc49f9b516a5bd4bb0c64fdca5ef4be9d858",
"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": "473915781ba2a180ef54234e8adbd8cdf2ea81d8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MattHartfield/SweepDomSelf",
"max_forks_repo_path": "StdVarTrajs_Sampling.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "473915781ba2a180ef54234e8adbd8cdf2ea81d8",
"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": "MattHartfield/SweepDomSelf",
"max_issues_repo_path": "StdVarTrajs_Sampling.c",
"max_line_length": 151,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "473915781ba2a180ef54234e8adbd8cdf2ea81d8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MattHartfield/SweepDomSelf",
"max_stars_repo_path": "StdVarTrajs_Sampling.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3791,
"size": 11896
} |
/*
#################################################################
## Private MATRIX Library ver 0.3 ##
## Made by "Gun Woo Park", Email : gunwoo.park@unina.it ##
## Fellow of SUPOLEN, Marie Curie Actions ##
## DICMaPI, University of Naples Federico II ##
#################################################################
*/
// all the integer is converted to MKL_LONG
// @ denoted for tested function
// Lots of functions are based on Call by Reference.
// Notice that for matrix operation, we have to put &.
// Vector can use by rows = 1.
// Note that I seperated library for linear algebra and matrix.
// If some error occurs during compiling, please check to include linear algebra code.
#ifndef MATRIX_H
#define MATRIX_H
#define TRUE 1
#define FALSE 0
#define BIT 64
#include <iostream>
#include <fstream>
#include <mkl.h>
#include <math.h>
//#include <omp.h>
extern "C" {
#include <gsl/gsl_sort_double.h>
}
class MATRIX
{
public:
MKL_LONG rows;
MKL_LONG cols;
MKL_LONG size;
double *data; // 1-dimensional array
bool VECTOR;
bool INITIALIZATION;
bool DIAGONALIZATION;
double *eigen_value;
MKL_LONG DIAGONALIZATION_INITIAL() //@
{
/* eigen_value = new double [rows]; */
/* eigen_value = (double*) mkl_malloc(rows*sizeof(double), BIT); */
eigen_value = new double [rows];
DIAGONALIZATION = TRUE;
return 0;
}
MKL_LONG
print_eigen();
MKL_LONG
print_eigen
(MKL_LONG n_ele); //@
// Public Member Function
MKL_LONG
p_self(); //@
MKL_LONG
initial();
MKL_LONG
initial
(MKL_LONG N_r, MKL_LONG N_c); //@
MKL_LONG
initial
(MKL_LONG N_r, MKL_LONG N_c, double x);
MKL_LONG
print(); //@
MKL_LONG
print
(MKL_LONG n_row, MKL_LONG n_col); //@
MKL_LONG
fprint_skip
(std::ofstream& file, MKL_LONG N_skip);
MKL_LONG
fprint_skip_transpose
(std::ofstream& file, MKL_LONG N_skip);
MKL_LONG
fprint_LONG_skip
(std::ofstream& file, MKL_LONG N_skip);
MKL_LONG
fprint_LONG_skip_transpose
(std::ofstream& file, MKL_LONG N_skip);
MKL_LONG
fprint_LONG_skip_transpose_LIMROWS
(std::ofstream& file, MKL_LONG N_skip, MKL_LONG N_lim_rows);
MKL_LONG
fprint
(std::ofstream& file); // ???
MKL_LONG
fprint_transpose
(std::ofstream& file); // ???
MKL_LONG
fprint_LONG
(std::ofstream& file); // ???
MKL_LONG
fprint_LONG_transpose
(std::ofstream& file); // ???
MKL_LONG
fprint_row
(std::ofstream& file, MKL_LONG given_row);
MKL_LONG
fprint_out_skip
(std::ofstream& file, MKL_LONG N_skip);
MKL_LONG
fprint_out
(std::ofstream& file); // ???
MKL_LONG
test_arr(); //@
MKL_LONG
test_arr_symm(); //@
MKL_LONG
nonzero();
MKL_LONG
ABS_cond
(double x);
double
ABS_sum();
MKL_LONG
force_clean(double TOLERANCE);
double
sum();
double
average();
MKL_LONG
add(MATRIX& given_MAT);
MKL_LONG
read_exist_data(const char* fn_given_array);
// Constructor
MATRIX(); //@
MATRIX
(MKL_LONG N_r, MKL_LONG N_c); //@
MATRIX
(MKL_LONG N_r, MKL_LONG N_c, double x); //@
// Copy Constructor
MKL_LONG
copy_obj
(const MATRIX& Mat);
MATRIX
(const MATRIX& Mat); //@
/* int connect_copy_constructor(const MATRIX& Mat); */
// Destructor
virtual
~MATRIX(); //@
MKL_LONG
data_delete(); //@
MKL_LONG
undefined_error(); //@
/* MKL_LONG index(MKL_LONG i, MKL_LONG j); //@ */ // inlined
MKL_LONG
sort();
MKL_LONG
sort2
(MATRIX& given_index);
/* MKL_LONG sort2(size_t* index); */
// inlined functions
// note that function inside class definition is inlined
// these are frequently called function that have small amount of computation
double
norm()
{
double result = 0.0;
for(MKL_LONG i=0; i<size; i++)
{
result += pow(data[i],2.0);
}
return sqrt(result);
}
MKL_LONG
set_value
(double x)
{
if(INITIALIZATION)
{
for(MKL_LONG i=0; i<size; i++)
{
data[i] = x;
} // i
}
else
{
undefined_error();
}
return 0;
}
MKL_LONG
index
(MKL_LONG i, MKL_LONG j)
{
return i*cols+j;
}
// operator
// inlined operator overloading
MATRIX&
operator=
(const MATRIX &Mat)
{
copy_obj(Mat);
return *this;
}
MATRIX&
operator+=
(const MATRIX &Mat)
{
// std::cout << "the operator += for MATRIX class is in buggy status\n";
// std::cout << "if this operator is called, to check the internal problems\n";
if (size != Mat.size)
std::cout << "The += operator must happen when two size are the same\n";
// copy_obj(Mat);
// for(MKL_LONG i=0; i<size; i++)
// {
// data[i] += Mat.data[i];
// }
cblas_daxpy(size, 1.0, Mat.data, 1, data, 1);
return *this;
}
double&
operator()
(MKL_LONG i, MKL_LONG j)
{
return data[i*cols+j];
}
double&
operator()
(MKL_LONG i)
{
return data[i];
}
};
inline MKL_LONG
make_unit_vector
(MATRIX& given_vec)
{
double norm = 0.;
for(MKL_LONG i=0; i<given_vec.size; i++)
{
norm += pow(given_vec.data[i], 2.0);
}
norm = sqrt(norm);
for(MKL_LONG i=0; i<given_vec.size; i++)
{
given_vec.data[i] /= norm;
}
return norm;
}
inline MKL_LONG
matrix_mul
(MATRIX& given_vec, double val)
{
cblas_dscal(given_vec.size, val, given_vec.data, 1);
return 0;
}
MKL_LONG
nonzero
(const MATRIX &A);
#endif
| {
"alphanum_fraction": 0.5306187371,
"avg_line_length": 22.0596491228,
"ext": "h",
"hexsha": "cc7c2167c6c4e8cc00a3bdd65e395b184f84a201",
"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": "0b0a3687533379ec75171ae6b906aeff5bedfbba",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gwpark-git/dynamics_of_networks_and_colloids",
"max_forks_repo_path": "lib/matrix.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0b0a3687533379ec75171ae6b906aeff5bedfbba",
"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": "gwpark-git/dynamics_of_networks_and_colloids",
"max_issues_repo_path": "lib/matrix.h",
"max_line_length": 87,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0b0a3687533379ec75171ae6b906aeff5bedfbba",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gwpark-git/dynamics_of_networks_and_colloids",
"max_stars_repo_path": "lib/matrix.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1701,
"size": 6287
} |
#ifndef PITCH_H
#define PITCH_H
#include <cstring>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#define DECL_PITCH(name) bool pitch_ ## name (gsl_vector *frame, double *f0res, double *T0res)
DECL_PITCH(AMDF);
#endif // PITCH_H
| {
"alphanum_fraction": 0.7205882353,
"avg_line_length": 14.3157894737,
"ext": "h",
"hexsha": "1935a6dc0b8a864c2262dace4e41d589847c5965",
"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/pitch.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/pitch.h",
"max_line_length": 95,
"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/pitch.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": 86,
"size": 272
} |
/* roots/steffenson.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Reid Priedhorsky, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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.
*/
/* steffenson.c -- steffenson root finding algorithm
This is Newton's method with an Aitken "delta-squared"
acceleration of the iterates. This can improve the convergence on
multiple roots where the ordinary Newton algorithm is slow.
x[i+1] = x[i] - f(x[i]) / f'(x[i])
x_accelerated[i] = x[i] - (x[i+1] - x[i])**2 / (x[i+2] - 2*x[i+1] + x[i])
We can only use the accelerated estimate after three iterations,
and use the unaccelerated value until then.
*/
#include <config.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include "roots.h"
typedef struct
{
double f, df;
double x;
double x_1;
double x_2;
int count;
}
steffenson_state_t;
static int steffenson_init (void * vstate, gsl_function_fdf * fdf, double * root);
static int steffenson_iterate (void * vstate, gsl_function_fdf * fdf, double * root);
static int
steffenson_init (void * vstate, gsl_function_fdf * fdf, double * root)
{
steffenson_state_t * state = (steffenson_state_t *) vstate;
const double x = *root ;
state->f = GSL_FN_FDF_EVAL_F (fdf, x);
state->df = GSL_FN_FDF_EVAL_DF (fdf, x) ;
state->x = x;
state->x_1 = 0.0;
state->x_2 = 0.0;
state->count = 1;
return GSL_SUCCESS;
}
static int
steffenson_iterate (void * vstate, gsl_function_fdf * fdf, double * root)
{
steffenson_state_t * state = (steffenson_state_t *) vstate;
double x_new, f_new, df_new;
double x_1 = state->x_1 ;
double x = state->x ;
if (state->df == 0.0)
{
GSL_ERROR("derivative is zero", GSL_EZERODIV);
}
x_new = x - (state->f / state->df);
GSL_FN_FDF_EVAL_F_DF(fdf, x_new, &f_new, &df_new);
state->x_2 = x_1 ;
state->x_1 = x ;
state->x = x_new;
state->f = f_new ;
state->df = df_new ;
if (!finite (f_new))
{
GSL_ERROR ("function value is not finite", GSL_EBADFUNC);
}
if (state->count < 3)
{
*root = x_new ;
state->count++ ;
}
else
{
double u = (x - x_1) ;
double v = (x_new - 2 * x + x_1);
if (v == 0)
*root = x_new; /* avoid division by zero */
else
*root = x_1 - u * u / v ; /* accelerated value */
}
if (!finite (df_new))
{
GSL_ERROR ("derivative value is not finite", GSL_EBADFUNC);
}
return GSL_SUCCESS;
}
static const gsl_root_fdfsolver_type steffenson_type =
{"steffenson", /* name */
sizeof (steffenson_state_t),
&steffenson_init,
&steffenson_iterate};
const gsl_root_fdfsolver_type * gsl_root_fdfsolver_steffenson = &steffenson_type;
| {
"alphanum_fraction": 0.6532577904,
"avg_line_length": 24.3448275862,
"ext": "c",
"hexsha": "e4169f6f28d2d7b0c6c44842b023361e475438b1",
"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/roots/steffenson.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/roots/steffenson.c",
"max_line_length": 85,
"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/roots/steffenson.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": 1064,
"size": 3530
} |
//
// C++ Interface: %{MODULE}
//
// Description:
//
//
// Author: %{AUTHOR} <%{EMAIL}>, (C) %{YEAR}
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef TNet_Vector_h
#define TNet_Vector_h
#include <cstddef>
#include <cstdlib>
#include <stdexcept>
#include <iostream>
#ifdef HAVE_ATLAS
extern "C"{
#include <cblas.h>
#include <clapack.h>
}
#endif
#include "Common.h"
#include "MathAux.h"
#include "Types.h"
#include "Error.h"
namespace TNet
{
template<typename _ElemT> class Vector;
template<typename _ElemT> class SubVector;
template<typename _ElemT> class Matrix;
template<typename _ElemT> class SpMatrix;
// we need to declare the friend functions here
template<typename _ElemT>
std::ostream & operator << (std::ostream & rOut, const Vector<_ElemT> & rV);
template<typename _ElemT>
std::istream & operator >> (std::istream & rIn, Vector<_ElemT> & rV);
template<typename _ElemT>
_ElemT
BlasDot(const Vector<_ElemT>& rA, const Vector<_ElemT>& rB);
/** **************************************************************************
** **************************************************************************
* @brief Provides a matrix abstraction class
*
* This class provides a way to work with matrices in TNet.
* It encapsulates basic operations and memory optimizations.
*
*/
template<typename _ElemT>
class Vector
{
public:
/// defines a type of this
typedef Vector<_ElemT> ThisType;
Vector(): mpData(NULL)
#ifdef STK_MEMALIGN_MANUAL
,mpFreeData(NULL)
#endif
, mDim(0)
{}
/**
* @brief Copy constructor
* @param rV
*/
Vector(const Vector<_ElemT>& rV)
{ mpData=NULL; Init(rV.Dim()); Copy(rV); }
/* Type conversion constructor. */
template<typename _ElemU>
explicit Vector(const Vector<_ElemU>& rV)
{ mpData=NULL; Init(rV.Dim()); Copy(rV); }
Vector(const _ElemT* ppData, const size_t s)
{ mpData=NULL; Init(s); Copy(ppData); }
explicit Vector(const size_t s, bool clear=true)
{ mpData=NULL; Init(s,clear); }
~Vector()
{ Destroy(); }
Vector<_ElemT> &operator = (const Vector <_ElemT> &other)
{ Init(other.Dim()); Copy(other); return *this; } // Needed for inclusion in std::vector
Vector<_ElemT>&
Init(size_t length, bool clear=true);
/**
* @brief Dealocates the window from memory and resets the dimensions to (0)
*/
void
Destroy();
/**
* @brief Returns @c true if vector is initialized
*/
bool
IsInitialized() const
{ return mpData != NULL; }
/**
* @brief Sets all elements to 0
*/
void
Zero();
void
Set(_ElemT f);
inline size_t
Dim() const
{ return mDim; }
/**
* @brief Returns size of matrix in memory (in bytes)
*/
inline size_t
MSize() const
{
return (mDim + (((16 / sizeof(_ElemT)) - mDim%(16 / sizeof(_ElemT)))
% (16 / sizeof(_ElemT)))) * sizeof(_ElemT);
}
/**
* @brief Gives access to the vector memory area
* @return pointer to the first field
*/
inline _ElemT*
pData()
{ return mpData; }
/**
* @brief Gives access to the vector memory area
* @return pointer to the first field (const version)
*/
inline const _ElemT*
pData() const
{ return mpData; }
/**
* @brief Gives access to a specified vector element (const).
*/
inline _ElemT
operator [] (size_t i) const
{
#ifdef PARANOID
assert(i<mDim);
#endif
return *(mpData + i);
}
/**
* @brief Gives access to a specified vector element (non-const).
*/
inline _ElemT &
operator [] (size_t i)
{
#ifdef PARANOID
assert(i<mDim);
#endif
return *(mpData + i);
}
/**
* @brief Gives access to a specified vector element (const).
*/
inline _ElemT
operator () (size_t i) const
{
#ifdef PARANOID
assert(i<mDim);
#endif
return *(mpData + i);
}
/**
* @brief Gives access to a specified vector element (non-const).
*/
inline _ElemT &
operator () (size_t i)
{
#ifdef PARANOID
assert(i<mDim);
#endif
return *(mpData + i);
}
/**
* @brief Returns a matrix sub-range
* @param o Origin
* @param l Length
* See @c SubVector class for details
*/
SubVector<_ElemT>
Range(const size_t o, const size_t l)
{ return SubVector<_ElemT>(*this, o, l); }
/**
* @brief Returns a matrix sub-range
* @param o Origin
* @param l Length
* See @c SubVector class for details
*/
const SubVector<_ElemT>
Range(const size_t o, const size_t l) const
{ return SubVector<_ElemT>(*this, o, l); }
//########################################################################
//########################################################################
/// Copy data from another vector
Vector<_ElemT>&
Copy(const Vector<_ElemT>& rV);
/// Copy data from another vector of a different type.
template<typename _ElemU> Vector<_ElemT>&
Copy(const Vector<_ElemU>& rV);
/// Load data into the vector
Vector<_ElemT>&
Copy(const _ElemT* ppData);
Vector<_ElemT>&
CopyVectorizedMatrixRows(const Matrix<_ElemT> &rM);
Vector<_ElemT>&
RemoveElement(size_t i);
Vector<_ElemT>&
ApplyLog();
Vector<_ElemT>&
ApplyLog(const Vector<_ElemT>& rV);//ApplyLog to rV and put the result in (*this)
Vector<_ElemT>&
ApplyExp();
Vector<_ElemT>&
ApplySoftMax();
Vector<_ElemT>&
Invert();
Vector<_ElemT>&
DotMul(const Vector<_ElemT>& rV); // Multiplies each element (*this)(i) by rV(i).
Vector<_ElemT>&
BlasAxpy(const _ElemT alpha, const Vector<_ElemT>& rV);
Vector<_ElemT>&
BlasGemv(const _ElemT alpha, const Matrix<_ElemT>& rM, const MatrixTrasposeType trans, const Vector<_ElemT>& rV, const _ElemT beta = 0.0);
//########################################################################
//########################################################################
Vector<_ElemT>&
Add(const Vector<_ElemT>& rV)
{ return BlasAxpy(1.0, rV); }
Vector<_ElemT>&
Subtract(const Vector<_ElemT>& rV)
{ return BlasAxpy(-1.0, rV); }
Vector<_ElemT>&
AddScaled(_ElemT alpha, const Vector<_ElemT>& rV)
{ return BlasAxpy(alpha, rV); }
Vector<_ElemT>&
Add(_ElemT c);
Vector<_ElemT>&
MultiplyElements(const Vector<_ElemT>& rV);
// @brief elementwise : rV.*rR+beta*this --> this
Vector<_ElemT>&
MultiplyElements(_ElemT alpha, const Vector<_ElemT>& rV, const Vector<_ElemT>& rR,_ElemT beta);
Vector<_ElemT>&
DivideElements(const Vector<_ElemT>& rV);
/// @brief elementwise : rV./rR+beta*this --> this
Vector<_ElemT>&
DivideElements(_ElemT alpha, const Vector<_ElemT>& rV, const Vector<_ElemT>& rR,_ElemT beta);
Vector<_ElemT>&
Subtract(_ElemT c);
Vector<_ElemT>&
Scale(_ElemT c);
//########################################################################
//########################################################################
/// Performs a row stack of the matrix rMa
Vector<_ElemT>&
MatrixRowStack(const Matrix<_ElemT>& rMa);
// Extracts a row of the matrix rMa. .. could also do this with vector.Copy(rMa[row]).
Vector<_ElemT>&
Row(const Matrix<_ElemT>& rMa, size_t row);
// Extracts a column of the matrix rMa.
Vector<_ElemT>&
Col(const Matrix<_ElemT>& rMa, size_t col);
// Takes all elements to a power.
Vector<_ElemT>&
Power(_ElemT power);
_ElemT
Max() const;
_ElemT
Min() const;
/// Returns sum of the elements
_ElemT
Sum() const;
/// Returns sum of the elements
Vector<_ElemT>&
AddRowSum(const Matrix<_ElemT>& rM);
/// Returns sum of the elements
Vector<_ElemT>&
AddColSum(const Matrix<_ElemT>& rM);
/// Returns log(sum(exp())) without exp overflow
_ElemT
LogSumExp() const;
//########################################################################
//########################################################################
friend std::ostream &
operator << <> (std::ostream& rOut, const Vector<_ElemT>& rV);
friend _ElemT
BlasDot<>(const Vector<_ElemT>& rA, const Vector<_ElemT>& rB);
/**
* Computes v1^T * M * v2.
* Not as efficient as it could be where v1==v2 (but no suitable blas
* routines available).
*/
_ElemT
InnerProduct(const Vector<_ElemT> &v1, const Matrix<_ElemT> &M, const Vector<_ElemT> &v2) const;
//##########################################################################
//##########################################################################
//protected:
public:
/// data memory area
_ElemT* mpData;
#ifdef STK_MEMALIGN_MANUAL
/// data to be freed (in case of manual memalignment use, see common.h)
_ElemT* mpFreeData;
#endif
size_t mDim; ///< Number of elements
}; // class Vector
/**
* @brief Represents a non-allocating general vector which can be defined
* as a sub-vector of higher-level vector
*/
template<typename _ElemT>
class SubVector : public Vector<_ElemT>
{
protected:
/// Constructor
SubVector(const Vector<_ElemT>& rT,
const size_t origin,
const size_t length)
{
assert(origin+length <= rT.mDim);
Vector<_ElemT>::mpData = rT.mpData+origin;
Vector<_ElemT>::mDim = length;
}
//only Vector class can call this protected constructor
friend class Vector<_ElemT>;
public:
/// Constructor
SubVector(Vector<_ElemT>& rT,
const size_t origin,
const size_t length)
{
assert(origin+length <= rT.mDim);
Vector<_ElemT>::mpData = rT.mpData+origin;
Vector<_ElemT>::mDim = length;
}
/**
* @brief Constructs a vector representation out of a standard array
*
* @param pData pointer to data array to associate with this vector
* @param length length of this vector
*/
inline
SubVector(_ElemT *ppData,
size_t length)
{
Vector<_ElemT>::mpData = ppData;
Vector<_ElemT>::mDim = length;
}
/**
* @brief Destructor
*/
~SubVector()
{
Vector<_ElemT>::mpData = NULL;
}
};
// Useful shortcuts
typedef Vector<BaseFloat> BfVector;
typedef SubVector<BaseFloat> BfSubVector;
//Adding two vectors of different types
template <typename _ElemT, typename _ElemU>
void Add(Vector<_ElemT>& rDst, const Vector<_ElemU>& rSrc)
{
assert(rDst.Dim() == rSrc.Dim());
const _ElemU* p_src = rSrc.pData();
_ElemT* p_dst = rDst.pData();
for(size_t i=0; i<rSrc.Dim(); i++) {
*p_dst++ += (_ElemT)*p_src++;
}
}
//Scales adding two vectors of different types
template <typename _ElemT, typename _ElemU>
void AddScaled(Vector<_ElemT>& rDst, const Vector<_ElemU>& rSrc, _ElemT scale)
{
assert(rDst.Dim() == rSrc.Dim());
Vector<_ElemT> tmp(rSrc);
rDst.BlasAxpy(scale, tmp);
/*
const _ElemU* p_src = rSrc.pData();
_ElemT* p_dst = rDst.pData();
for(size_t i=0; i<rDst.Dim(); i++) {
*p_dst++ += *p_src++ * scale;
}
*/
}
} // namespace TNet
//*****************************************************************************
//*****************************************************************************
// we need to include the implementation
#include "Vector.tcc"
/******************************************************************************
******************************************************************************
* The following section contains specialized template definitions
* whose implementation is in Vector.cc
*/
#endif // #ifndef TNet_Vector_h
| {
"alphanum_fraction": 0.5259636827,
"avg_line_length": 25.2635814889,
"ext": "h",
"hexsha": "384c5d20eae10a3fc9a4a680f527ed357446683a",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "troylee/nnet-asr",
"max_forks_repo_path": "src/KaldiLib/Vector.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "troylee/nnet-asr",
"max_issues_repo_path": "src/KaldiLib/Vector.h",
"max_line_length": 144,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "troylee/nnet-asr",
"max_stars_repo_path": "src/KaldiLib/Vector.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3106,
"size": 12556
} |
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <gsl_vector.h>
#include "svm_main.h"
#include "test_main.h"
PyObject* __opt(PyObject* self, PyObject* args) {
PyObject* elements;
int k_type; // 1 if RBF kernel is used 0 for my kernel
double C; // hyperparameter for optimization
if (!PyArg_ParseTuple(args, "Oid", &elements, &k_type, &C))
return NULL;
return __get_w_b(elements, k_type, C);
}
PyObject* __test(PyObject* self, PyObject* args) {
PyObject* training;
PyObject* testing;
PyObject* alphas;
double b;
int rbf;
if (!PyArg_ParseTuple(args, "OOOdi", &training, &testing, &alphas, &b, &rbf))
return NULL;
return __test_t(training, testing, alphas, b, rbf);
}
static PyMethodDef methods[] = {
{"opt", __opt, METH_VARARGS, ""},
{"test", __test, METH_VARARGS, ""},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef c_opt = {
PyModuleDef_HEAD_INIT,
"C OPT",
"C interop to optimize a custom implementation of an SVM",
-1,
methods
};
PyMODINIT_FUNC PyInit_c_opt() {
return PyModule_Create(&c_opt);
} | {
"alphanum_fraction": 0.6978967495,
"avg_line_length": 23.2444444444,
"ext": "c",
"hexsha": "125e6729d6b2f26830a202790fdffb17e65ce036",
"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": "f86c8eafa78ca241919d12134afe796c665f8021",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "HARDIntegral/ADHD_Classifier",
"max_forks_repo_path": "Source/SVM/Source/py_wrapper.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021",
"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": "HARDIntegral/ADHD_Classifier",
"max_issues_repo_path": "Source/SVM/Source/py_wrapper.c",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "HARDIntegral/ADHD_Classifier",
"max_stars_repo_path": "Source/SVM/Source/py_wrapper.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 309,
"size": 1046
} |
#include <stdlib.h>
#include <cblas.h>
#include "tasks.h"
void syrk_task_par_reconfigure(int nth)
{
// empty
}
void syrk_task_par_finalize(void)
{
// empty
}
void syrk_task_par(void *ptr, int nth, int me)
{
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;
// Balance the load by flops.
int part[nth + 1];
const int total_work = n * (n + 1) / 2;
const int ideal_part_work = total_work / nth;
part[0] = 0;
part[nth] = n;
for (int k = 1; k < nth; ++k) {
part[k] = part[k - 1];
int work = 0;
while (work < ideal_part_work && part[k] < n) {
work += n - part[k];
part[k] += 1;
}
}
const int my_first_col = part[me];
const int my_num_cols = part[me + 1] - part[me];
const int i1 = my_first_col;
const int i2 = i1 + my_num_cols;
const int m2 = n - i2;
// TODO Insert picture (see krnl_syrk in task_chol_par).
if (my_num_cols > 0) {
cblas_dsyrk(CblasColMajor, CblasLower, CblasNoTrans,
my_num_cols, k,
-1.0, A21 + i1, ldA,
1.0, A22 + i1 + my_first_col * ldA, ldA);
}
if (m2 > 0) {
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,
m2, my_num_cols, k,
-1.0, A21 + i2, ldA,
A21 + my_first_col, ldA,
1.0, A22 + i2 + my_first_col * ldA, ldA);
}
}
| {
"alphanum_fraction": 0.4924834636,
"avg_line_length": 24.4558823529,
"ext": "c",
"hexsha": "fe0e5b500142a56769daf35c0fe03739074a6abc",
"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-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-syrk-par.c",
"max_line_length": 67,
"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-par.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 522,
"size": 1663
} |
/* -----------------------------------------------------------------------------
* Copyright 2021 Jonathan Haigh
* SPDX-License-Identifier: MIT
* ---------------------------------------------------------------------------*/
#ifndef SQ_INCLUDE_GUARD_system_schema_h_
#define SQ_INCLUDE_GUARD_system_schema_h_
#include "core/Primitive.h"
#include "core/typeutil.h"
#include <cstddef>
#include <gsl/gsl>
#include <optional>
#include <string_view>
namespace sq::system {
class SchemaImpl;
/**
* Represents the schema for a primitive type.
*/
class PrimitiveTypeSchema {
public:
constexpr explicit PrimitiveTypeSchema(std::string_view name,
std::string_view doc)
: name_{name}, doc_{doc} {}
SQ_ND std::string_view name() const;
SQ_ND std::string_view doc() const;
private:
std::string_view name_;
std::string_view doc_;
};
/**
* Represents the schema for a parameter of field of a system object.
*/
class ParamSchema {
public:
constexpr ParamSchema(std::string_view name, std::string_view doc,
std::size_t index, std::size_t type_index,
bool required, std::string_view default_value_str,
std::string_view default_value_doc)
: name_{name}, doc_{doc}, index_{index}, type_index_{type_index},
required_{required}, default_value_str_{default_value_str},
default_value_doc_{default_value_doc} {}
SQ_ND std::string_view name() const;
SQ_ND std::string_view doc() const;
SQ_ND std::size_t index() const;
SQ_ND const PrimitiveTypeSchema &type() const;
SQ_ND bool required() const;
SQ_ND std::optional<Primitive> default_value() const;
SQ_ND std::string_view default_value_doc() const;
private:
std::string_view name_;
std::string_view doc_;
std::size_t index_;
std::size_t type_index_;
bool required_;
std::string_view default_value_str_;
std::string_view default_value_doc_;
};
class TypeSchema;
/**
* Represents the schema for a field of a system object.
*/
class FieldSchema {
public:
constexpr FieldSchema(std::string_view name, std::string_view doc,
std::size_t params_begin_index,
std::size_t params_end_index,
std::size_t return_type_index, bool return_list,
bool null)
: name_{name}, doc_{doc}, params_begin_index_{params_begin_index},
params_end_index_{params_end_index},
return_type_index_{return_type_index},
return_list_{return_list}, null_{null} {}
SQ_ND std::string_view name() const;
SQ_ND std::string_view doc() const;
SQ_ND gsl::span<const ParamSchema> params() const;
SQ_ND const TypeSchema &return_type() const;
SQ_ND bool return_list() const;
SQ_ND bool null() const;
private:
std::string_view name_;
std::string_view doc_;
std::size_t params_begin_index_;
std::size_t params_end_index_;
std::size_t return_type_index_;
bool return_list_;
bool null_;
};
/**
* Represents the schema for a system object.
*/
class TypeSchema {
public:
constexpr TypeSchema(std::string_view name, std::string_view doc,
std::size_t fields_begin_index,
std::size_t fields_end_index)
: name_{name}, doc_{doc}, fields_begin_index_{fields_begin_index},
fields_end_index_{fields_end_index} {}
SQ_ND std::string_view name() const;
SQ_ND std::string_view doc() const;
SQ_ND gsl::span<const FieldSchema> fields() const;
private:
std::string_view name_;
std::string_view doc_;
std::size_t fields_begin_index_;
std::size_t fields_end_index_;
};
/**
* Represents the whole SQ schema.
*/
struct Schema {
public:
SQ_ND gsl::span<const TypeSchema> types() const;
SQ_ND gsl::span<const PrimitiveTypeSchema> primitive_types() const;
SQ_ND const TypeSchema &root_type() const;
};
/**
* Get the whole SQ schema.
*/
const Schema &schema();
} // namespace sq::system
#endif // SQ_INCLUDE_GUARD_system_schema_h_
| {
"alphanum_fraction": 0.664599355,
"avg_line_length": 28.1888111888,
"ext": "h",
"hexsha": "c4f6a972a0930230c846193b17b00007048de980",
"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": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jonathanhaigh/sq",
"max_forks_repo_path": "src/system/include/system/schema.h",
"max_issues_count": 44,
"max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jonathanhaigh/sq",
"max_issues_repo_path": "src/system/include/system/schema.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jonathanhaigh/sq",
"max_stars_repo_path": "src/system/include/system/schema.h",
"max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z",
"num_tokens": 921,
"size": 4031
} |
/* filter/test_rmedian.c
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_statistics.h>
/* slow/dumb rmedian which constructs actual window for each sample, sorts
* it and finds median */
static int
slow_rmedian(const gsl_filter_end_t endtype, const gsl_vector * x, gsl_vector * y, const int K)
{
const int n = (int) x->size;
const int H = K / 2;
double *window = malloc(K * sizeof(double));
int i;
for (i = 0; i < n; ++i)
{
size_t wsize = gsl_movstat_fill(endtype, x, i, H, H, window);
double yi;
int j;
/* fill first half of window with previous filter output values */
for (j = i - H; j < i; ++j)
{
if (j < 0)
{
if (endtype == GSL_FILTER_END_PADVALUE)
window[j - i + H] = gsl_vector_get(x, 0);
else if (endtype == GSL_FILTER_END_PADZERO)
window[j - i + H] = 0.0;
}
else
{
window[j - i + H] = gsl_vector_get(y, j);
}
}
yi = gsl_stats_median(window, 1, wsize);
gsl_vector_set(y, i, yi);
}
free(window);
return GSL_SUCCESS;
}
/* test square wave input (root signal) */
static void
test_rmedian_root(const gsl_filter_end_t etype, const size_t n, const size_t k)
{
const double tol = 1.0e-12;
gsl_filter_rmedian_workspace *w = gsl_filter_rmedian_alloc(k);
gsl_vector *x = gsl_vector_alloc(n);
gsl_vector *y = gsl_vector_alloc(n);
char buf[2048];
size_t i;
/* test a root sequence (square input): x = [zero one zero] */
gsl_vector_set_all(x, 0.0);
for (i = n / 3; i <= n / 2; ++i)
gsl_vector_set(x, i, 1.0);
/* compute y = rmedian(x) and test y = x */
gsl_filter_rmedian(etype, x, y, w);
sprintf(buf, "n=%zu k=%zu RMF square wave root sequence", n, k);
compare_vectors(tol, y, x, buf);
gsl_vector_free(x);
gsl_vector_free(y);
gsl_filter_rmedian_free(w);
}
/* test random input and in-place */
static void
test_rmedian_random(const gsl_filter_end_t etype, const size_t n, const int K, gsl_rng * r)
{
const double tol = 1.0e-12;
gsl_filter_rmedian_workspace *w = gsl_filter_rmedian_alloc(K);
gsl_vector *x = gsl_vector_alloc(n);
gsl_vector *y = gsl_vector_alloc(n);
gsl_vector *z = gsl_vector_alloc(n);
char buf[2048];
/* test filter with random input against slow algorithm */
random_vector(x, r);
/* y = rmedian(x) */
gsl_filter_rmedian(etype, x, y, w);
/* y = rmedian(x) with slow algorithm */
slow_rmedian(etype, x, z, K);
/* test y = z */
sprintf(buf, "n=%zu K=%d RMF symmetric random slow test", n, K);
compare_vectors(tol, y, z, buf);
/* test in-place filter */
/* z = rmedian(x) in-place */
gsl_vector_memcpy(z, x);
gsl_filter_rmedian(etype, z, z, w);
sprintf(buf, "n=%zu K=%d RMF symmetric random in-place", n, K);
compare_vectors(tol, z, y, buf);
gsl_vector_free(x);
gsl_vector_free(y);
gsl_vector_free(z);
gsl_filter_rmedian_free(w);
}
void
test_rmedian(gsl_rng * rng_p)
{
/* test root sequences */
test_rmedian_root(GSL_FILTER_END_PADZERO, 1000, 3);
test_rmedian_root(GSL_FILTER_END_PADZERO, 2000, 101);
test_rmedian_root(GSL_FILTER_END_PADVALUE, 1000, 3);
test_rmedian_root(GSL_FILTER_END_PADVALUE, 2000, 101);
/* test random input */
test_rmedian_random(GSL_FILTER_END_PADZERO, 10, 1, rng_p);
test_rmedian_random(GSL_FILTER_END_PADZERO, 100, 3, rng_p);
test_rmedian_random(GSL_FILTER_END_PADZERO, 1000, 3, rng_p);
test_rmedian_random(GSL_FILTER_END_PADZERO, 100, 1001, rng_p);
test_rmedian_random(GSL_FILTER_END_PADZERO, 5, 7, rng_p);
test_rmedian_random(GSL_FILTER_END_PADVALUE, 10, 1, rng_p);
test_rmedian_random(GSL_FILTER_END_PADVALUE, 100, 3, rng_p);
test_rmedian_random(GSL_FILTER_END_PADVALUE, 1000, 3, rng_p);
test_rmedian_random(GSL_FILTER_END_PADVALUE, 100, 1001, rng_p);
test_rmedian_random(GSL_FILTER_END_PADVALUE, 5, 7, rng_p);
}
| {
"alphanum_fraction": 0.6761268781,
"avg_line_length": 29.95,
"ext": "c",
"hexsha": "f64d75aeaeb4fc0f0ae7df2ee0f07e97dcc50603",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/filter/test_rmedian.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/filter/test_rmedian.c",
"max_line_length": 95,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/filter/test_rmedian.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z",
"num_tokens": 1414,
"size": 4792
} |
#ifndef QDM_GSL_H
#define QDM_GSL_H 1
#include <stdio.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <osqp/osqp.h>
gsl_vector *
qdm_vector_seq(double from, double to, double by);
void
qdm_vector_set_seq(gsl_vector *v, double from, double to);
size_t
qdm_vector_search(const gsl_vector *v, double needle);
void
qdm_vector_csv_fwrite(FILE *f, const gsl_vector *v);
void
qdm_matrix_csv_fwrite(FILE *f, const gsl_matrix *m);
int
qdm_matrix_tmm(gsl_matrix *m, gsl_matrix *result);
int
qdm_matrix_det_tmm(gsl_matrix *m, double *det);
gsl_vector *
qdm_vector_sorted(const gsl_vector *v);
gsl_vector *
qdm_vector_quantile(gsl_vector *data, gsl_vector *probs);
double
qdm_vector_rss(const gsl_vector *y, const gsl_vector *fx);
double
qdm_vector_sum(gsl_vector *v);
size_t
qdm_vector_greater_than(const gsl_vector *v, double value);
void
qdm_matrix_select_upper_triangle(gsl_matrix *m);
int
qdm_matrix_to_csc_matrix(csc **result, gsl_matrix *m);
gsl_vector *
qdm_vector_copy(const gsl_vector *src);
gsl_matrix *
qdm_matrix_copy(const gsl_matrix *src);
int
qdm_vector_hd5_read(
hid_t id,
const char *name,
gsl_vector **v
);
int
qdm_vector_hd5_write(
hid_t id,
const char *name,
const gsl_vector *v
);
int
qdm_matrix_hd5_read(
hid_t id,
const char *name,
gsl_matrix **m
);
int
qdm_matrix_hd5_write(
hid_t id,
const char *name,
const gsl_matrix *m
);
gsl_vector *
qdm_matrix_filter(
const gsl_matrix *m,
size_t needle_column,
double needle_value,
size_t select_column
);
#endif /* QDM_GSL_H */
| {
"alphanum_fraction": 0.7477987421,
"avg_line_length": 16.7368421053,
"ext": "h",
"hexsha": "a3e14652c2bbc00a100db26d5f83162cb1d98e97",
"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": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "include/qdm/gsl.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "include/qdm/gsl.h",
"max_line_length": 59,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "include/qdm/gsl.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 467,
"size": 1590
} |
/*
* specialfunctionsmodule.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 SPECIALFUNCTIONSMODULE_H
#define SPECIALFUNCTIONSMODULE_H
/*
SLI Module implementing functions from the GNU Science Library.
The GSL is available from sources.redhat.com/gsl.
*/
/*
NOTE: Special functions are available only if the GSL is installed.
If no GSL is available, calling special functions will result
in a SLI error message. HEP 2002-09-19.
*/
// Generated includes:
#include "config.h"
// Includes from sli:
#include "slifunction.h"
#include "slimodule.h"
#ifdef HAVE_GSL
// External include:
#include <gsl/gsl_integration.h>
#endif
// NOTE: all gsl headers are included in specialfunctionsmodule.cc
class SpecialFunctionsModule : public SLIModule
{
// Part 1: Methods pertaining to the module ----------------------
public:
SpecialFunctionsModule( void ){};
// ~SpecialFunctionsModule(void);
// The Module is registered by a call to this Function:
void init( SLIInterpreter* );
// This function will return the name of our module:
const std::string name( void ) const;
// Part 2: Classes for the implemented functions -----------------
public:
/**
* Classes which implement the GSL Funktions.
* These must be public, since we want to export
* objects of these.
*/
class GammaIncFunction : public SLIFunction
{
public:
GammaIncFunction()
{
}
void execute( SLIInterpreter* ) const;
};
class LambertW0Function : public SLIFunction
{
public:
LambertW0Function()
{
}
void execute( SLIInterpreter* ) const;
};
class LambertWm1Function : public SLIFunction
{
public:
LambertWm1Function()
{
}
void execute( SLIInterpreter* ) const;
};
class ErfFunction : public SLIFunction
{
public:
ErfFunction()
{
}
void execute( SLIInterpreter* ) const;
};
class ErfcFunction : public SLIFunction
{
public:
ErfcFunction()
{
}
void execute( SLIInterpreter* ) const;
};
class GaussDiskConvFunction : public SLIFunction
{
public:
void execute( SLIInterpreter* ) const;
// need constructor and destructor to set up integration workspace
GaussDiskConvFunction( void );
~GaussDiskConvFunction( void );
private:
// quadrature parameters, see GSL Reference
static const int MAX_QUAD_SIZE;
static const double QUAD_ERR_LIM;
static const double QUAD_ERR_SCALE;
// integration workspace
#ifdef HAVE_GSL
gsl_integration_workspace* w_;
/**
* Integrand function.
* @note This function must be static with C linkage so that it can
* be passed to the GSL. Alternatively, one could define it
* outside the class.
*/
static double f_( double, void* );
static gsl_function F_; // GSL wrapper struct for it
#endif
};
// Part 3: One instatiation of each new function class -----------
public:
const GammaIncFunction gammaincfunction;
const LambertW0Function lambertw0function;
const LambertWm1Function lambertwm1function;
const ErfFunction erffunction;
const ErfcFunction erfcfunction;
const GaussDiskConvFunction gaussdiskconvfunction;
// Part 3b: Internal variables
private:
};
// Part 4: Documentation for all functions -------------------------
/* BeginDocumentation
Name: Gammainc - incomplete gamma function
Synopsis: x a Gammainc -> result
Description: Computes the incomplete Gamma function
int(t^(a-1)*exp(-t), t=0..x) / Gamma(a)
Parameters: x (double): upper limit of integration
a (double): order of Gamma function
Examples: 2.2 1.5 Gammainc -> 0.778615
Author: H E Plesser
FirstVersion: 2001-07-26
Remarks: This is the incomplete Gamma function P(a,x) defined as no. 6.5.1
in Abramowitz&Stegun. Requires the GSL.
References: http://sources.redhat.com/gsl/ref
*/
/* BeginDocumentation
Name: Erf - error function
Synopsis: x Erf -> result
Description: Computes the error function
erf(x) = 2/sqrt(pi) int_0^x dt exp(-t^2)
Parameters: x (double): error function argument
Examples: 0.5 erf -> 0.5205
Author: H E Plesser
FirstVersion: 2001-07-30
Remarks: Requires the GSL.
References: http://sources.redhat.com/gsl/ref
SeeAlso: Erfc
*/
/* BeginDocumentation
Name: Erfc - complementary error function
Synopsis: x Erfc -> result
Description: Computes the error function
erfc(x) = 1 - erf(x) = 2/sqrt(pi) int_x^inf dt exp(-t^2)
Parameters: x (double): error function argument
Examples: 0.5 erfc -> 0.4795
Author: H E Plesser
FirstVersion: 2001-07-30
Remarks: Requires the GSL.
References: http://sources.redhat.com/gsl/ref
SeeAlso: Erf
*/
/* BeginDocumentation
Name:GaussDiskConv - Convolution of a Gaussian with an excentric disk
Synopsis:R r0 GaussDiskConv -> result
Description:Computes the convolution of an excentric normalized Gaussian
with a disk
C[R, r0] = IInt[ disk(rvec; R) * Gauss(rvec - r_0vec) d^2rvec ]
= 2 Int[ r Exp[-r0^2-r^2] I_0[2 r r_0] dr, r=0..R]
Parameters:R radius of the disk, centered at origin
r0 distance of Gaussian center from origin
Examples:SLI ] 3.2 2.3 GaussDiskConv =
0.873191
Author:H E Plesser
FirstVersion: 2002-07-12
Remarks:This integral is needed to compute the response of a DOG model to
excentric light spots, see [1]. For technicalities, see [2]. Requires GSL.
References: [1] G. T. Einevoll and P. Heggelund, Vis Neurosci 17:871-885 (2000).
[2] Hans E. Plesser, Convolution of an Excentric Gaussian with a Disk,
Technical Report, arken.nlh.no/~itfhep, 2002
*/
#endif
| {
"alphanum_fraction": 0.6925510043,
"avg_line_length": 23.5055762082,
"ext": "h",
"hexsha": "d1bc798c4aaa9d2f2a616a101dcd5ea63a0c6cd8",
"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/sli/specialfunctionsmodule.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/sli/specialfunctionsmodule.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/sli/specialfunctionsmodule.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": 1682,
"size": 6323
} |
/* interpolation/gsl_spline2d.h
*
* Copyright 2012 David Zaslavsky
*
* 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_SPLINE2D_H__
#define __GSL_SPLINE2D_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <gsl/gsl_interp.h>
#include <gsl/gsl_interp2d.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
/*
* A 2D interpolation object which stores the arrays defining the function.
* In all other respects, this is just like a gsl_interp2d object.
*/
typedef struct
{
gsl_interp2d interp_object; /* low-level interpolation object */
double * xarr; /* x data array */
double * yarr; /* y data array */
double * zarr; /* z data array */
} gsl_spline2d;
GSL_FUN gsl_spline2d * gsl_spline2d_alloc(const gsl_interp2d_type * T, size_t xsize, size_t ysize);
GSL_FUN int gsl_spline2d_init(gsl_spline2d * interp, const double xa[],
const double ya[], const double za[],
size_t xsize, size_t ysize);
GSL_FUN void gsl_spline2d_free(gsl_spline2d * interp);
GSL_FUN double gsl_spline2d_eval(const gsl_spline2d * interp, const double x,
const double y, gsl_interp_accel* xa, gsl_interp_accel* ya);
GSL_FUN int gsl_spline2d_eval_e(const gsl_spline2d * interp, const double x,
const double y, gsl_interp_accel* xa, gsl_interp_accel* ya,
double * z);
GSL_FUN double gsl_spline2d_eval_deriv_x(const gsl_spline2d * interp, const double x,
const double y, gsl_interp_accel* xa, gsl_interp_accel* ya);
GSL_FUN int gsl_spline2d_eval_deriv_x_e(const gsl_spline2d * interp, const double x,
const double y, gsl_interp_accel* xa,
gsl_interp_accel* ya, double * z);
GSL_FUN double gsl_spline2d_eval_deriv_y(const gsl_spline2d * interp, const double x,
const double y, gsl_interp_accel* xa,
gsl_interp_accel* ya);
GSL_FUN int gsl_spline2d_eval_deriv_y_e(const gsl_spline2d * interp, const double x,
const double y, gsl_interp_accel* xa,
gsl_interp_accel* ya, double * z);
GSL_FUN double gsl_spline2d_eval_deriv_xx(const gsl_spline2d * interp, const double x,
const double y, gsl_interp_accel* xa, gsl_interp_accel* ya);
GSL_FUN int gsl_spline2d_eval_deriv_xx_e(const gsl_spline2d * interp, const double x,
const double y, gsl_interp_accel* xa,
gsl_interp_accel* ya, double * z);
GSL_FUN double gsl_spline2d_eval_deriv_yy(const gsl_spline2d * interp, const double x,
const double y, gsl_interp_accel* xa, gsl_interp_accel* ya);
GSL_FUN int gsl_spline2d_eval_deriv_yy_e(const gsl_spline2d * interp, const double x,
const double y, gsl_interp_accel* xa,
gsl_interp_accel* ya, double * z);
GSL_FUN double gsl_spline2d_eval_deriv_xy(const gsl_spline2d * interp, const double x,
const double y, gsl_interp_accel* xa, gsl_interp_accel* ya);
GSL_FUN int gsl_spline2d_eval_deriv_xy_e(const gsl_spline2d * interp, const double x,
const double y, gsl_interp_accel* xa,
gsl_interp_accel* ya, double * z);
GSL_FUN size_t gsl_spline2d_min_size(const gsl_spline2d * interp);
GSL_FUN const char * gsl_spline2d_name(const gsl_spline2d * interp);
GSL_FUN int gsl_spline2d_set(const gsl_spline2d * interp, double zarr[],
const size_t i, const size_t j, const double z);
GSL_FUN double gsl_spline2d_get(const gsl_spline2d * interp, const double zarr[],
const size_t i, const size_t j);
__END_DECLS
#endif /* __GSL_SPLINE2D_H__ */
| {
"alphanum_fraction": 0.6617323465,
"avg_line_length": 40.314516129,
"ext": "h",
"hexsha": "afe781808a346223a929517ea1d84cc7906b568c",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_spline2d.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_spline2d.h",
"max_line_length": 99,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_spline2d.h",
"max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z",
"num_tokens": 1213,
"size": 4999
} |
#pragma once
#include <gsl/gsl>
#include <vector>
#include <memory>
#include <mutex>
struct AVFrame;
namespace video_streamer
{
class StreamSession;
class FrameEncoder;
class GroupStreamSession
{
public:
explicit GroupStreamSession(std::shared_ptr<FrameEncoder> frameEncoder);
void addStream(std::unique_ptr<StreamSession> streamSession);
void pushFrame(gsl::not_null<const AVFrame*> frame);
private:
std::shared_ptr<FrameEncoder> m_frameEncoder;
std::vector<std::unique_ptr<StreamSession>> m_streamSession;
mutable std::mutex m_mtx;
};
} // video_streamer | {
"alphanum_fraction": 0.7589134126,
"avg_line_length": 19,
"ext": "h",
"hexsha": "156240c7821fe8f43d7db97da6d1d3c40b246e30",
"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/GroupStreamSession.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/GroupStreamSession.h",
"max_line_length": 76,
"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/GroupStreamSession.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 139,
"size": 589
} |
// Copyright (c) 2021 SmartPolarBear
//
// 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.
//
// Created by cleve on 9/1/2021.
//
#pragma once
#include <base/iterable_stack.h>
#include <interpreter/vm/opcode.h>
#include <interpreter/vm/chunk.h>
#include <interpreter/vm/value.h>
#include <interpreter/vm/exceptions.h>
#include <interpreter/vm/heap.h>
#include <interpreter/vm/heap_allocator.h>
#include <interpreter/vm/garbage_collector.h>
#include <interpreter/vm/string_object.h>
#include <interpreter/vm/closure_object.h>
#include <interpreter/vm/instance_object.h>
#include <memory>
#include <map>
#include <ranges>
#include <gsl/gsl>
#include "class_object.h"
namespace clox::interpreting::vm
{
enum class virtual_machine_status
{
OK,
RUNTIME_ERROR,
};
template<typename F, typename R, class ...Args>
concept BinaryOperator=
requires(F&& f, Args&& ... args) {
{ std::invoke(std::forward<F>(f), std::forward<Args>(args)...) }->std::same_as<R>;
};
class virtual_machine final
{
public:
friend class garbage_collector;
static inline constexpr size_t CALL_STACK_RESERVED_SIZE = 64;
static inline constexpr size_t STACK_RESERVED_SIZE = 16384;
using value_list_type = std::vector<value>;
using global_table_type = std::unordered_map<std::string, value>;
using function_table_type = std::unordered_map<full_opcode_type, value>;
using ip_type = chunk::iterator_type;
using index_type = gsl::index;
class call_frame final
{
public:
public:
explicit call_frame(closure_object_raw_pointer closure, ip_type ip, size_t offset)
: closure_(closure), ip_(ip), stack_offset_(offset)
{
}
[[nodiscard]] size_t stack_offset() const
{
return stack_offset_;
}
[[nodiscard]] function_object_raw_pointer function() const
{
return closure_->function();
}
[[nodiscard]] closure_object_raw_pointer closure() const
{
return closure_;
}
[[nodiscard]] ip_type& ip()
{
return ip_;
}
private:
closure_object_raw_pointer closure_{};
ip_type ip_{};
size_t stack_offset_{};
};
using call_frame_list_type = std::vector<call_frame>;
public:
virtual_machine() = delete;
~virtual_machine();
explicit virtual_machine(helper::console& cons,
std::shared_ptr<object_heap> heap);
virtual_machine_status run(clox::interpreting::vm::closure_object* closure);
private:
virtual_machine_status run();
// {return status, exit}
std::tuple<std::optional<virtual_machine_status>, bool> run_code(chunk::code_type instruction, call_frame& frame);
template<class ...TArgs>
void runtime_error(std::string_view fmt, const TArgs& ...args)
{
cons_->error() << std::format("[Line {}] in file {}:",
top_call_frame().function()->body()->line_of(top_call_frame().ip()),
top_call_frame().function()->body()->filename()) << std::endl;
cons_->error() << std::format(fmt, args...) << "\n";
cons_->error() << "Call stack:" << std::endl;
for (auto& frm: call_frames_ | std::ranges::views::reverse)
{
auto func = frm.function();
auto line = func->body()->line_of(frm.ip() - 1);
cons_->error() << std::format("[Line {}] in ", line);
if (func->name().empty())
{
cons_->error() << "script" << std::endl;
}
else
{
cons_->error() << func->name() << std::endl;
}
}
reset_stack();
}
template<typename TOp>
requires BinaryOperator<TOp, floating_value_type, floating_value_type, floating_value_type>
inline void binary_op(TOp op)
{
try
{
auto l = peek(0), r = peek(1);
auto right = get_number_promoted(l);
auto left = get_number_promoted(r);
auto ret = op(left, right);
if (std::holds_alternative<floating_value_type>(l) ||
std::holds_alternative<floating_value_type>(r))
{
pop_two_and_push(ret);
}
else if (std::holds_alternative<integer_value_type>(l) ||
std::holds_alternative<integer_value_type>(r))
{
pop_two_and_push(static_cast<integer_value_type>(ret));
}
else if (std::holds_alternative<boolean_value_type>(l) ||
std::holds_alternative<boolean_value_type>(r))
{
pop_two_and_push(static_cast<scanning::boolean_literal_type>(ret));
}
else
{
pop_two_and_push(
static_cast<integer_value_type>(ret)); // cannot combine for the sake of the rules of type promoting
}
}
catch (const std::exception& e)
{
this->runtime_error("Invalid operands for binary operator: {}", e.what());
throw e;
}
}
template<typename TOp>
requires BinaryOperator<TOp, object_raw_pointer, string_object_raw_pointer, string_object_raw_pointer>
inline void binary_op(TOp op)
{
try
{
auto right = get_string(peek(0));
auto left = get_string(peek(1));
pop_two_and_push(op(left, right));
}
catch (const std::exception& e)
{
this->runtime_error("Invalid operands for binary operator: {}", e.what());
throw e;
}
}
// for comparing, whose op returns bool value
template<typename TOp>
requires BinaryOperator<TOp, bool, floating_value_type, floating_value_type>
inline void binary_op(TOp op)
{
try
{
auto right = get_number_promoted(peek(0));
auto left = get_number_promoted(peek(1));
pop_two_and_push(op(left, right));
}
catch (const std::exception& e)
{
this->runtime_error("Invalid operands for binary operator: {}", e.what());
throw e;
}
}
template<typename TOp>
requires BinaryOperator<TOp, bool, string_object_raw_pointer, string_object_raw_pointer>
inline void binary_op(TOp op)
{
try
{
auto right = get_string(peek(0));
auto left = get_string(peek(1));
pop_two_and_push(op(left, right));
}
catch (const std::exception& e)
{
this->runtime_error("Invalid operands for binary operator: {}", e.what());
throw e;
}
}
void call_value(const value& val, size_t arg_count);
void call(closure_object_raw_pointer closure, size_t arg_count);
bool is_false(const value& val);
[[maybe_unused]] bool is_true(const value& val)
{
return !is_false(val);
}
// stack modification
void reset_stack();
template<object_pointer T>
T peek_object(size_t offset = 0)
{
return std::visit([](auto&& val) -> T
{
using TV = std::decay_t<decltype(val)>;
if constexpr (std::is_same_v<TV, object_raw_pointer>)
{
if (auto func = dynamic_cast<T>(val);func)
{
return func;
}
else
{
throw invalid_value{ val };
}
}
else
{
throw invalid_value{ val };
}
}, peek(offset));
}
value peek(size_t offset = 0);
value pop();
void push(const value& val);
inline void pop_two_and_push(const value& val);
//
// instruction reading
value next_constant();
std::string next_variable_name();
chunk::code_type next_code();
value& slot_at(const call_frame& frame, size_t slot);
upvalue_object_raw_pointer capture_upvalue(value* val, index_type stack_index);
void close_upvalues(index_type last);
// call frame
call_frame& top_call_frame()
{
return *call_frames_.rbegin();
}
void push_call_frame(closure_object_raw_pointer closure, chunk::iterator_type ip, size_t stack_offset)
{
call_frames_.emplace_back(closure, ip, stack_offset);
}
void pop_call_frame()
{
call_frames_.pop_back();
}
//
// method
bool bind_method(class_object_raw_pointer class_obj, resolving::function_id_type id);
bool bind_method(instance_object_raw_pointer class_obj, resolving::function_id_type id);
std::shared_ptr<object_heap> heap_{};
value_list_type stack_{};
global_table_type globals_{};
function_table_type functions_{};
call_frame_list_type call_frames_{};
std::map<index_type, upvalue_object_raw_pointer> open_upvalues_{}; // it should be ordered
mutable helper::console* cons_{ nullptr };
};
}
| {
"alphanum_fraction": 0.7075949367,
"avg_line_length": 23.8082191781,
"ext": "h",
"hexsha": "1c8d55d1c94d4303f0aa3efe5c3d9a6665c29e27",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-10-15T10:14:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-10-15T10:14:06.000Z",
"max_forks_repo_head_hexsha": "e5d4b890f480c7ee6cf2fd74f8167634ea49fa9c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SmartPolarBear/clox",
"max_forks_repo_path": "interpreter/include/interpreter/vm/vm.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "e5d4b890f480c7ee6cf2fd74f8167634ea49fa9c",
"max_issues_repo_issues_event_max_datetime": "2021-09-09T16:21:47.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-09-09T16:21:47.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SmartPolarBear/clox",
"max_issues_repo_path": "interpreter/include/interpreter/vm/vm.h",
"max_line_length": 115,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "e5d4b890f480c7ee6cf2fd74f8167634ea49fa9c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SmartPolarBear/clox",
"max_stars_repo_path": "interpreter/include/interpreter/vm/vm.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-17T13:06:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-02T15:49:20.000Z",
"num_tokens": 2220,
"size": 8690
} |
/*
Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com>
Licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
#include "morn_tensor.h"
struct TensorReshapePara
{
MLayer *prev;
int channel;
int height;
int width;
int res_valid;
};
void *mTensorReshapePara(MList *ini,char *name)
{
struct TensorReshapePara *para = (struct TensorReshapePara *)mMalloc(sizeof(struct TensorReshapePara));
char *value = mINIRead(ini,name,"prev");
para->prev = mNetworkLayer(ini,value);
mException((para->prev == NULL),EXIT,"invalid prev");
para->res_valid = (strcmp("Input",mLayerType(para->prev))!=0);
value = mINIRead(ini,name,"height");
if(value != NULL) para->height= atoi(value);else para->height= DFLT;
value = mINIRead(ini,name,"width");
if(value != NULL) para->width = atoi(value);else para->width = DFLT;
value = mINIRead(ini,name,"channel");
if(value != NULL) para->channel = atoi(value);else para->channel = DFLT;
return para;
}
void TensorReshapeSet(MLayer *layer)
{
if(layer->state != DFLT) return;
struct TensorReshapePara *para = (struct TensorReshapePara *)(layer->para);
MTensor *in = para->prev->tns;
MTensor *res= para->prev->res;
MTensor *out= layer->tns;
int size = in->height*in->width*in->channel;
if(para->height <=0) para->height = size/(para->width *para->channel);
if(para->width <=0) para->width = size/(para->height*para->channel);
if(para->channel<=0) para->channel= size/(para->height*para->width );
mException((para->height<0)||(para->width<0)||(para->channel<0)||(para->height*para->width*para->channel!=size),EXIT,"invalid input shape, with shape input is %d,%d,%d",in->channel,in->height,in->width);
mTensorRedefine(out,in->batch,para->channel,para->height,para->width,in->data);
if(morn_network_flag==MORN_TRAIN)
{
if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data);
else mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);
}
}
void mTensorReshapeForward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
mException(strcmp("Reshape",mLayerType(layer)),EXIT,"invalid layer type");
TensorReshapeSet(layer);
layer->state = MORN_FORWARD;
}
void mTensorReshapeBackward(MLayer *layer)
{
mException(INVALID_POINTER(layer),EXIT,"invalid input");
mException(strcmp("Reshape",mLayerType(layer)),EXIT,"invalid layer type");
struct TensorReshapePara *para = (struct TensorReshapePara *)(layer->para);
if(para->res_valid==0) return;
MTensor *res= para->prev->res;
MTensor *out= layer->res;
int size = res->height*res->width*res->channel;
for(int b=0;b<res->batch;b++)if(res->data[b]!=out->data[b]) memcpy(res->data[b],out->data[b],size*sizeof(float));
para->prev->state = MORN_BACKWARD;
}
| {
"alphanum_fraction": 0.6797274276,
"avg_line_length": 37.0736842105,
"ext": "c",
"hexsha": "f6e20eb32183b4e967de2a30bb2bc9ba45022c52",
"lang": "C",
"max_forks_count": 35,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T11:34:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-26T05:09:23.000Z",
"max_forks_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ishine/Morn",
"max_forks_repo_path": "src/deep_learning/morn_tensor_reshape.c",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0",
"max_issues_repo_issues_event_max_datetime": "2020-04-07T15:05:18.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-29T02:52:41.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ishine/Morn",
"max_issues_repo_path": "src/deep_learning/morn_tensor_reshape.c",
"max_line_length": 501,
"max_stars_count": 121,
"max_stars_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ishine/Morn",
"max_stars_repo_path": "src/deep_learning/morn_tensor_reshape.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:23:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-24T05:53:42.000Z",
"num_tokens": 962,
"size": 3522
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_roots.h>
#include "ccl.h"
/*
* convert_concentration_single finds the concentration c'
* for a mass definition with overdensity Delta' given
* the concentration c for a mass definition with overdensity
* Delta assuming an NFW density profile.
*
* To do so, it solves the following equation numerically:
* c^3 * f(c) = Delta' f(c')
* where f(x) = x^3 * (x + 1) / ((1+x) * log(x + 1) - x).
*
* The equation is solved using a Newton-Raphson approach.
* The functions nfw_fx, nfw_f, nfw_df and nfw_fdf implement
* the function whose zero we try to find and its derivative.
*
* ccl_convert_concentration does the same thing for an
* array of input concentrations.
*/
static double nfw_fx(double x)
{
if(x>0.01) {
double xp1=1+x;
double lxp1=log(xp1);
double den=1./(xp1*lxp1-x);
return xp1*x*x*x*den;
}
else {
return 2*x;
}
}
static double nfw_f(double x,void *params)
{
double offset = *((double *)params);
return nfw_fx(x)-offset;
}
static double nfw_df(double x,void *params)
{
if(x>0.01) {
double xp1=1+x;
double lxp1=log(xp1);
double den=1./(xp1*lxp1-x);
return x*x*(3*xp1*xp1*lxp1-x*(4*x+3))*den*den;
}
else {
return 2;
}
}
static void nfw_fdf(double x,void *params,
double *y, double *dy)
{
double offset = *((double *)params);
if(x>0.01) {
double xp1=1+x;
double lxp1=log(xp1);
double den=1./(xp1*lxp1-x);
*y=xp1*x*x*x*den-offset;
*dy=x*x*(3*xp1*xp1*lxp1-x*(4*x+3))*den*den;
}
else {
*y=2*x-offset;
*dy=2;
}
}
static int convert_concentration_single(double d_factor, double c_old,
double *c_new, double c_start)
{
double c0, offset = d_factor * nfw_fx(c_old);
int status, iter=0, max_iter=100;
gsl_function_fdf FDF;
gsl_root_fdfsolver *s=NULL;
FDF.f = &nfw_f;
FDF.df = &nfw_df;
FDF.fdf = &nfw_fdf;
FDF.params = &offset;
s=gsl_root_fdfsolver_alloc(gsl_root_fdfsolver_newton);
if (s==NULL)
return CCL_ERROR_MEMORY;
gsl_root_fdfsolver_set (s, &FDF, c_start);
*c_new = c_start;
do
{
iter++;
c0 = *c_new;
status = gsl_root_fdfsolver_iterate (s);
*c_new = gsl_root_fdfsolver_root (s);
status = gsl_root_test_delta (*c_new, c0, 0, 1e-4);
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_root_fdfsolver_free (s);
return status;
}
void ccl_convert_concentration(ccl_cosmology *cosmo,
double delta_old, int nc, double c_old[],
double delta_new, double c_new[],int *status)
{
if(nc<=0)
return;
int ii,st=0;
double d_factor = delta_old/delta_new;
for(ii=0;ii<nc;ii++) {
double c_new_h;
st=convert_concentration_single(d_factor, c_old[ii], &(c_new[ii]), c_old[ii]);
if(st!=GSL_SUCCESS) {
*status=CCL_ERROR_ROOT;
ccl_cosmology_set_status_message(cosmo,
"ccl_mass_conversion.c: NR solver failed to find a root\n");
return;
}
}
}
| {
"alphanum_fraction": 0.6455944972,
"avg_line_length": 23.3053435115,
"ext": "c",
"hexsha": "58d34bbec0991a4631cd086d192fe93f38724a72",
"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": "src/ccl_mass_conversion.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3a5f9dec72c6ce602ac8b11ceed0ee6c0460a926",
"max_issues_repo_issues_event_max_datetime": "2020-07-28T12:22:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-28T12:22:35.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "benediktdiemer/CCL",
"max_issues_repo_path": "src/ccl_mass_conversion.c",
"max_line_length": 82,
"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": "src/ccl_mass_conversion.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 987,
"size": 3053
} |
#pragma once
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include <DirectXMath.h>
#include <gsl\gsl>
#include "DrawableGameComponent.h"
#include "MatrixHelper.h"
namespace Library
{
class SkyboxMaterial;
class Skybox final : public DrawableGameComponent
{
RTTI_DECLARATIONS(Skybox, DrawableGameComponent)
public:
Skybox(Game& game, const std::shared_ptr<Camera>& camera, const std::wstring& cubeMapFileName, float scale);
Skybox(const Skybox&) = delete;
Skybox(Skybox&&) = default;
Skybox& operator=(const Skybox&) = delete;
Skybox& operator=(Skybox&&) = default;
~Skybox() = default;
virtual void Initialize() override;
virtual void Draw(const GameTime& gameTime) override;
private:
std::wstring mCubeMapFileName;
DirectX::XMFLOAT4X4 mWorldMatrix{ MatrixHelper::Identity };
float mScale;
std::shared_ptr<SkyboxMaterial> mMaterial;
winrt::com_ptr<ID3D11Buffer> mVertexBuffer;
winrt::com_ptr<ID3D11Buffer> mIndexBuffer;
std::uint32_t mIndexCount{ 0 };
bool mUpdateMaterial{ true };
};
} | {
"alphanum_fraction": 0.7456978967,
"avg_line_length": 26.8205128205,
"ext": "h",
"hexsha": "57884b60fef9a418a099ac30261f0d90d399cf9e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_forks_repo_path": "source/Library.Shared/Skybox.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_issues_repo_path": "source/Library.Shared/Skybox.h",
"max_line_length": 110,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_stars_repo_path": "source/Library.Shared/Skybox.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 298,
"size": 1046
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gbpInterpolate.h>
double interpolate(interp_info *interp, double x) {
return (gsl_interp_eval(interp->interp, interp->x, interp->y, x, interp->accel));
}
| {
"alphanum_fraction": 0.71886121,
"avg_line_length": 25.5454545455,
"ext": "c",
"hexsha": "c55e6f0c9541c1e209f64cb0165a35107b6d3e98",
"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/gbpInterpolate/interpolate.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/gbpInterpolate/interpolate.c",
"max_line_length": 85,
"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/gbpInterpolate/interpolate.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": 79,
"size": 281
} |
#pragma once
#include <gsl/span>
#include "halley/text/halleystring.h"
#include "halley/resources/resource.h"
#include "halley/maths/range.h"
#include "halley/maths/vector4.h"
#include "halley/data_structures/maybe.h"
#include <map>
#include <vector>
#include "halley/utils/type_traits.h"
#if defined(DEV_BUILD)
#define STORE_CONFIG_NODE_PARENTING
#endif
namespace Halley {
class Serializer;
class Deserializer;
class ConfigNode;
template<typename T>
struct HasToConfigNode
{
private:
typedef std::true_type yes;
typedef std::false_type no;
template<typename U> static auto test(int) -> decltype(std::declval<U>().toConfigNode(), yes());
template<typename> static no test(...);
public:
static constexpr bool value = std::is_same<decltype(test<T>(0)),yes>::value;
};
template<typename T>
struct HasConfigNodeConstructor
{
private:
typedef std::true_type yes;
typedef std::false_type no;
template<typename U> static auto test(int) -> decltype(U(std::declval<ConfigNode>()), yes());
template<typename> static no test(...);
public:
static constexpr bool value = std::is_same<decltype(test<T>(0)),yes>::value;
};
enum class ConfigNodeType
{
Undefined,
String,
Sequence,
Map,
Int,
Float,
Int2,
Float2,
Int3,
Float3,
Int4,
Float4,
Bytes,
DeltaSequence, // For delta coding
DeltaMap, // For delta coding
Noop, // For delta coding
Idx, // For delta coding
Del // For delta coding
};
template <>
struct EnumNames< ConfigNodeType >
{
constexpr std::array< const char*, 17 > operator()() const
{
return { { "undefined",
"string",
"sequence",
"map",
"int",
"float",
"int2",
"float2",
"int3",
"float3",
"int4",
"float4",
"bytes",
"deltaSequence",
"deltaMap",
"noop",
"idx"
"del" } };
}
};
class ConfigFile;
class ConfigNode
{
friend class ConfigFile;
public:
using MapType = std::map< String, ConfigNode >;
using SequenceType = std::vector< ConfigNode >;
struct NoopType
{
};
struct DelType
{
};
struct IdxType
{
int start;
int len;
IdxType() = default;
IdxType( int start, int len ) :
start( start ), len( len ) { }
};
ConfigNode();
explicit ConfigNode( const ConfigNode& other );
ConfigNode( ConfigNode&& other ) noexcept;
ConfigNode( MapType entryMap );
ConfigNode( SequenceType entryList );
explicit ConfigNode( String value );
explicit ConfigNode( const char* value );
explicit ConfigNode( bool value );
explicit ConfigNode( int value );
explicit ConfigNode( float value );
explicit ConfigNode( Angle1f value );
explicit ConfigNode( Vector2i value );
explicit ConfigNode( Vector2f value );
explicit ConfigNode( Vector3i value );
explicit ConfigNode( Vector3f value );
explicit ConfigNode( Vector4i value );
explicit ConfigNode( Vector4f value );
explicit ConfigNode( Bytes value );
explicit ConfigNode( NoopType value );
explicit ConfigNode( DelType value );
explicit ConfigNode( IdxType value );
template <typename T>
explicit ConfigNode(const std::vector<T>& sequence)
{
SequenceType seq;
seq.reserve(sequence.size());
for (auto& e: sequence) {
if constexpr (HasToConfigNode<T>::value) {
seq.push_back(e.toConfigNode());
} else {
seq.push_back(ConfigNode(e));
}
}
*this = seq;
}
~ConfigNode();
ConfigNode& operator=( const ConfigNode& other );
ConfigNode& operator=( ConfigNode&& other ) noexcept;
ConfigNode& operator=( bool value );
ConfigNode& operator=( int value );
ConfigNode& operator=( float value );
ConfigNode& operator=( Angle1f value );
ConfigNode& operator=( Vector2i value );
ConfigNode& operator=( Vector2f value );
ConfigNode& operator=( Vector3i value );
ConfigNode& operator=( Vector3f value );
ConfigNode& operator=( Vector4i value );
ConfigNode& operator=( Vector4f value );
ConfigNode& operator=( MapType entryMap );
ConfigNode& operator=( SequenceType entryList );
ConfigNode& operator=( String value );
ConfigNode& operator=( Bytes value );
ConfigNode& operator=( gsl::span< const gsl::byte > bytes );
ConfigNode& operator=( const char* value );
ConfigNode& operator=( NoopType value );
ConfigNode& operator=( DelType value );
ConfigNode& operator=( IdxType value );
template <typename T>
ConfigNode& operator=(const std::vector<T>& sequence)
{
SequenceType seq;
seq.reserve(sequence.size());
for (auto& e: sequence) {
if constexpr (HasToConfigNode<T>::value) {
seq.push_back(e.toConfigNode());
} else {
seq.push_back(ConfigNode(e));
}
}
return *this = seq;
}
bool operator==( const ConfigNode& other ) const;
bool operator!=( const ConfigNode& other ) const;
ConfigNodeType getType() const;
void serialize( Serializer& s ) const;
void deserialize( Deserializer& s );
int asInt() const;
float asFloat() const;
bool asBool() const;
Angle1f asAngle1f() const;
Vector2i asVector2i() const;
Vector2f asVector2f() const;
Vector3i asVector3i() const;
Vector3f asVector3f() const;
Vector4i asVector4i() const;
Vector4f asVector4f() const;
Range< float > asFloatRange() const;
String asString() const;
const Bytes& asBytes() const;
int asInt( int defaultValue ) const;
float asFloat( float defaultValue ) const;
bool asBool( bool defaultValue ) const;
String asString( const String& defaultValue ) const;
Angle1f asAngle1f( Angle1f defaultValue ) const;
Vector2i asVector2i( Vector2i defaultValue ) const;
Vector2f asVector2f( Vector2f defaultValue ) const;
Vector3i asVector3i( Vector3i defaultValue ) const;
Vector3f asVector3f( Vector3f defaultValue ) const;
Vector4i asVector4i( Vector4i defaultValue ) const;
Vector4f asVector4f( Vector4f defaultValue ) const;
template <typename T>
std::vector<T> asVector() const
{
if (type == ConfigNodeType::Sequence) {
std::vector<T> result;
result.reserve(asSequence().size());
for (const auto& e : asSequence()) {
if constexpr (HasConfigNodeConstructor<T>::value) {
result.emplace_back(T(e));
} else {
result.emplace_back(e.convertTo(Tag<T>()));
}
}
return result;
} else {
throw Exception("Can't convert " + getNodeDebugId() + " from " + toString(getType()) + " to std::vector<T>.", HalleyExceptions::Resources);
}
}
template <typename T>
std::vector<T> asVector(const std::vector<T>& defaultValue) const
{
if (type == ConfigNodeType::Sequence) {
return asVector<T>();
} else {
return defaultValue;
}
}
const SequenceType& asSequence() const;
const MapType& asMap() const;
SequenceType& asSequence();
MapType& asMap();
void ensureType( ConfigNodeType type );
bool hasKey( const String& key ) const;
void removeKey( const String& key );
ConfigNode& operator[]( const String& key );
ConfigNode& operator[]( size_t idx );
const ConfigNode& operator[]( const String& key ) const;
const ConfigNode& operator[]( size_t idx ) const;
SequenceType::iterator begin();
SequenceType::iterator end();
SequenceType::const_iterator begin() const;
SequenceType::const_iterator end() const;
void reset();
void setOriginalPosition( int line, int column );
void setParent( const ConfigNode* parent, int idx );
void propagateParentingInformation( const ConfigFile* parentFile );
inline void assertValid() const
{
Expects( intData != 0xCDCDCDCD );
Expects( intData != 0xDDDDDDDD );
}
struct BreadCrumb
{
const BreadCrumb* prev = nullptr;
String key;
OptionalLite< int > idx;
int depth = 0;
BreadCrumb() = default;
BreadCrumb( const BreadCrumb& prev, String key ) :
prev( &prev ), key( std::move( key ) ), depth( prev.depth + 1 ) { }
BreadCrumb( const BreadCrumb& prev, int index ) :
prev( &prev ), idx( index ), depth( prev.depth + 1 ) { }
bool hasKeyAt( const String& key, int depth ) const;
bool hasIndexAt( int idx, int depth ) const;
};
class IDeltaCodeHints
{
public:
virtual ~IDeltaCodeHints() = default;
virtual std::optional< size_t > getSequenceMatch( const SequenceType& seq, const ConfigNode& newValue, size_t curIdx, const BreadCrumb& breadCrumb ) const = 0;
virtual bool doesSequenceOrderMatter( const BreadCrumb& breadCrumb ) const { return true; }
virtual bool canDeleteKey( const String& key, const BreadCrumb& breadCrumb ) const { return true; }
virtual bool canDeleteAnyKey() const { return true; }
virtual bool shouldBypass( const BreadCrumb& breadCrumb ) const { return false; }
virtual bool areNullAndEmptyEquivalent( const BreadCrumb& breadCrumb ) const { return false; }
};
static ConfigNode createDelta( const ConfigNode& from, const ConfigNode& to, const IDeltaCodeHints* hints = nullptr );
static ConfigNode applyDelta( const ConfigNode& from, const ConfigNode& delta );
void applyDelta( const ConfigNode& delta );
void decayDeltaArtifacts();
private:
template < typename T >
class Tag
{
};
union {
String* strData;
MapType* mapData;
SequenceType* sequenceData;
Bytes* bytesData;
void* rawPtrData;
int intData;
float floatData;
Angle1f ang1fData;
Vector2i vec2iData;
Vector2f vec2fData;
Vector3i vec3iData;
Vector3f vec3fData;
Vector4i vec4iData;
Vector4f vec4fData;
};
ConfigNodeType type = ConfigNodeType::Undefined;
int auxData = 0; // Used by delta coding
#if defined(STORE_CONFIG_NODE_PARENTING)
struct ParentingInfo
{
int line = 0;
int column = 0;
int idx = 0;
const ConfigNode* node = nullptr;
const ConfigFile* file = nullptr;
};
std::unique_ptr< ParentingInfo > parent;
#endif
static ConfigNode undefinedConfigNode;
static String undefinedConfigNodeName;
template < typename T >
void deserializeContents( Deserializer& s )
{
T v;
s >> v;
*this = std::move( v );
}
String getNodeDebugId() const;
String backTrackFullNodeName() const;
int convertTo( Tag< int > tag ) const;
float convertTo( Tag< float > tag ) const;
bool convertTo( Tag< bool > tag ) const;
Angle1f convertTo( Tag< Angle1f > tag ) const;
Vector2i convertTo( Tag< Vector2i > tag ) const;
Vector2f convertTo( Tag< Vector2f > tag ) const;
Vector3i convertTo( Tag< Vector3i > tag ) const;
Vector3f convertTo( Tag< Vector3f > tag ) const;
Vector4i convertTo( Tag< Vector4i > tag ) const;
Vector4f convertTo( Tag< Vector4f > tag ) const;
Range< float > convertTo( Tag< Range< float > > tag ) const;
String convertTo( Tag< String > tag ) const;
const Bytes& convertTo( Tag< Bytes& > tag ) const;
bool isNullOrEmpty() const;
static ConfigNode doCreateDelta( const ConfigNode& from, const ConfigNode& to, const BreadCrumb& breadCrumb, const IDeltaCodeHints* hints );
static ConfigNode createMapDelta( const ConfigNode& from, const ConfigNode& to, const BreadCrumb& breadCrumb, const IDeltaCodeHints* hints );
static ConfigNode createSequenceDelta( const ConfigNode& from, const ConfigNode& to, const BreadCrumb& breadCrumb, const IDeltaCodeHints* hints );
void applyMapDelta( const ConfigNode& delta );
void applySequenceDelta( const ConfigNode& delta );
bool isEquivalent( const ConfigNode& other ) const;
bool isEquivalentStrictOrder( const ConfigNode& other ) const;
};
} // namespace Halley
| {
"alphanum_fraction": 0.5978442387,
"avg_line_length": 32.2102689487,
"ext": "h",
"hexsha": "e0f9f1701ff2bc594cbeac6fe1590c5dcafa4faf",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "chidddy/halley",
"max_forks_repo_path": "src/engine/utils/include/halley/data_structures/config_node.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "chidddy/halley",
"max_issues_repo_path": "src/engine/utils/include/halley/data_structures/config_node.h",
"max_line_length": 171,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f828b74a6bbe7f172a7dba84e72429d3163bd61c",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "chidddy/halley",
"max_stars_repo_path": "src/engine/utils/include/halley/data_structures/config_node.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3091,
"size": 13174
} |
/* sum/test.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_sum.h>
#include <gsl/gsl_ieee_utils.h>
#define N 50
void check_trunc (double * t, double expected, const char * desc);
void check_full (double * t, double expected, const char * desc);
int
main (void)
{
gsl_ieee_env_setup ();
{
double t[N];
int n;
const double zeta_2 = M_PI * M_PI / 6.0;
/* terms for zeta(2) */
for (n = 0; n < N; n++)
{
double np1 = n + 1.0;
t[n] = 1.0 / (np1 * np1);
}
check_trunc (t, zeta_2, "zeta(2)");
check_full (t, zeta_2, "zeta(2)");
}
{
double t[N];
double x, y;
int n;
/* terms for exp(10.0) */
x = 10.0;
y = exp(x);
t[0] = 1.0;
for (n = 1; n < N; n++)
{
t[n] = t[n - 1] * (x / n);
}
check_trunc (t, y, "exp(10)");
check_full (t, y, "exp(10)");
}
{
double t[N];
double x, y;
int n;
/* terms for exp(-10.0) */
x = -10.0;
y = exp(x);
t[0] = 1.0;
for (n = 1; n < N; n++)
{
t[n] = t[n - 1] * (x / n);
}
check_trunc (t, y, "exp(-10)");
check_full (t, y, "exp(-10)");
}
{
double t[N];
double x, y;
int n;
/* terms for -log(1-x) */
x = 0.5;
y = -log(1-x);
t[0] = x;
for (n = 1; n < N; n++)
{
t[n] = t[n - 1] * (x * n) / (n + 1.0);
}
check_trunc (t, y, "-log(1/2)");
check_full (t, y, "-log(1/2)");
}
{
double t[N];
double x, y;
int n;
/* terms for -log(1-x) */
x = -1.0;
y = -log(1-x);
t[0] = x;
for (n = 1; n < N; n++)
{
t[n] = t[n - 1] * (x * n) / (n + 1.0);
}
check_trunc (t, y, "-log(2)");
check_full (t, y, "-log(2)");
}
{
double t[N];
int n;
double result = 0.192594048773;
/* terms for an alternating asymptotic series */
t[0] = 3.0 / (M_PI * M_PI);
for (n = 1; n < N; n++)
{
t[n] = -t[n - 1] * (4.0 * (n + 1.0) - 1.0) / (M_PI * M_PI);
}
check_trunc (t, result, "asymptotic series");
check_full (t, result, "asymptotic series");
}
{
double t[N];
int n;
/* Euler's gamma from GNU Calc (precision = 32) */
double result = 0.5772156649015328606065120900824;
/* terms for Euler's gamma */
t[0] = 1.0;
for (n = 1; n < N; n++)
{
t[n] = 1/(n+1.0) + log(n/(n+1.0));
}
check_trunc (t, result, "Euler's constant");
check_full (t, result, "Euler's constant");
}
{
double t[N];
int n;
/* eta(1/2) = sum_{k=1}^{\infty} (-1)^(k+1) / sqrt(k)
From Levin, Intern. J. Computer Math. B3:371--388, 1973.
I=(1-sqrt(2))zeta(1/2)
=(2/sqrt(pi))*integ(1/(exp(x^2)+1),x,0,inf) */
double result = 0.6048986434216305; /* approx */
/* terms for eta(1/2) */
for (n = 0; n < N; n++)
{
t[n] = (n%2 ? -1 : 1) * 1.0 /sqrt(n + 1.0);
}
check_trunc (t, result, "eta(1/2)");
check_full (t, result, "eta(1/2)");
}
exit (gsl_test_summary ());
}
void
check_trunc (double * t, double expected, const char * desc)
{
double sum_accel, prec;
gsl_sum_levin_utrunc_workspace * w = gsl_sum_levin_utrunc_alloc (N);
gsl_sum_levin_utrunc_accel (t, N, w, &sum_accel, &prec);
gsl_test_rel (sum_accel, expected, 1e-8, "trunc result, %s", desc);
/* No need to check precision for truncated result since this is not
a meaningful number */
gsl_sum_levin_utrunc_free (w);
}
void
check_full (double * t, double expected, const char * desc)
{
double sum_accel, err_est, sd_actual, sd_est;
gsl_sum_levin_u_workspace * w = gsl_sum_levin_u_alloc (N);
gsl_sum_levin_u_accel (t, N, w, &sum_accel, &err_est);
gsl_test_rel (sum_accel, expected, 1e-8, "full result, %s", desc);
sd_est = -log10 (err_est/fabs(sum_accel));
sd_actual = -log10 (DBL_EPSILON + fabs ((sum_accel - expected)/expected));
/* Allow one digit of slop */
gsl_test (sd_est > sd_actual + 1.0, "full significant digits, %s (%g vs %g)", desc, sd_est, sd_actual);
gsl_sum_levin_u_free (w);
}
| {
"alphanum_fraction": 0.5537055838,
"avg_line_length": 20.9574468085,
"ext": "c",
"hexsha": "d40384055f79369c7482ae8558bc39b41d72d330",
"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/sum/test.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/sum/test.c",
"max_line_length": 105,
"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/sum/test.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": 1758,
"size": 4925
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_cdf.h>
unsigned int k;
unsigned int n1;
unsigned int n2;
unsigned int t;
static void usage(int argc, char *argv[]) {
printf (
"Usage: %s k n1 n2 t\n"
"\n"
"If a population contains n1 elements of \"type 1\" and n2 elements\n"
"of \"type 2\" then the hypergeometric distribution gives the probability\n"
"of obtaining k elements of \"type 1\" in t samples from the population\n"
"without replacement.\n"
"This program computes the Pvalue of such a distribution\n", argv[0]);
exit (-1);
}
int main(int argc, char *argv[]) {
if (argc != 5)
usage(argc, argv);
k = atoi(argv[1]);
n1 = atoi(argv[2]);
n2 = atoi(argv[3]);
t = atoi(argv[4]);
double Q = gsl_cdf_hypergeometric_Q (k, n1, n2, t);
double P = gsl_cdf_hypergeometric_P (k, n1, n2, t);
printf("%g\n", Q);
if (P < Q)
fprintf(stderr, "Warning: P < Q, %g < %g\n", P, Q);
}
| {
"alphanum_fraction": 0.6311907271,
"avg_line_length": 23.1463414634,
"ext": "c",
"hexsha": "439e3e5037e11f26df5087894065726888665575",
"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": "452f1dd17a42ac3e7b99e14b84b9a35c160833b3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "scovit/nust-helico",
"max_forks_repo_path": "randomizzatore/hyper.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "452f1dd17a42ac3e7b99e14b84b9a35c160833b3",
"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": "scovit/nust-helico",
"max_issues_repo_path": "randomizzatore/hyper.c",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "452f1dd17a42ac3e7b99e14b84b9a35c160833b3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "scovit/nust-helico",
"max_stars_repo_path": "randomizzatore/hyper.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 306,
"size": 949
} |
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <gsl/gsl_sf_result.h>
#include <gsl/gsl_sf_gamma.h>
#include <fftw3.h>
//#include "fftlog.h"
#define PI 3.14159265358979323846
#define PI_2 1.5707963267948966 /// pi/2
#define PI_times_2 6.28318530718 // 2*pi
#define inv_PI 0.31830988618 // 1/pi
#define log2 0.6931471805599453 //ln(2)
#define PI2cubed 248.05021344239853 //(2*pi)^3
/* Compute the discrete Hankel transform of the function a(r). See the FFTLog
* documentation (or the Fortran routine of the same name in the FFTLog
* sources) for a description of exactly what this function computes.
* If u is NULL, the transform coefficients will be computed anew and discarded
* afterwards. If you plan on performing many consecutive transforms, it is
* more efficient to pre-compute the u coefficients. */
void fht(int N, const double r[], const double complex a[], double k[],
double complex b[], double mu,
double q, double kcrc, int noring, double complex* u);
// double q = 0, double kcrc = 1, bool noring = true,
// double complex* u = NULL);
/* Pre-compute the coefficients that appear in the FFTLog implementation of
* the discrete Hankel transform. The parameters N, mu, and q here are the
* same as for the function fht(). The parameter L is defined (for whatever
* reason) to be N times the logarithmic spacing of the input array, i.e.
* L = N * log(r[N-1]/r[0])/(N-1) */
void compute_u_coefficients(int N, double mu, double q, double L, double kcrc,
double complex u[]);
/* This code is FFTLog, which is described in arXiv:astro-ph/9905191 */
static double complex lngamma_fftlog(double complex z)
{
gsl_sf_result lnr, phi;
gsl_sf_lngamma_complex_e(creal(z), cimag(z), &lnr, &phi);
return lnr.val + I*phi.val;
}
/* Unused function -- commenting out to prevent clang warnings
static double complex gamma_fftlog(double complex z)
{
return cexp(lngamma_fftlog(z));
}
*/
static double complex polar (double r, double phi)
{
return (r*cos(phi) +I*(r*sin(phi)));
}
static void lngamma_4(double x, double y, double* lnr, double* arg)
{
double complex w = lngamma_fftlog(x+y*I);
if(lnr) *lnr = creal(w);
if(arg) *arg = cimag(w);
}
static double goodkr(int N, double mu, double q, double L, double kr)
{
double N_L = N/L;
double xp = (mu+1+q)/2;
double xm = (mu+1-q)/2;
double y = PI_2*N_L;
double lnr, argm, argp;
lngamma_4(xp, y, &lnr, &argp);
lngamma_4(xm, y, &lnr, &argm);
double arg = log(2./kr) * N_L + (argp + argm)*inv_PI;
double iarg = round(arg);
if(arg != iarg)
kr *= exp((arg - iarg)/N_L);
return kr;
}
void compute_u_coefficients(int N, double mu, double q, double L,
double kcrc, double complex u[])
{
double y = PI/L;
double k0r0 = kcrc * exp(-L);
double t = -2*y*log(k0r0*0.5);
if(q == 0) {
double x = (mu+1)*0.5;
double lnr, phi;
for(int m = 0; m <= N/2; m++) {
lngamma_4(x, m*y, &lnr, &phi);
u[m] = polar(1.0,m*t + 2*phi);
}
}
else {
double xp = (mu+1+q)*0.5;
double xm = (mu+1-q)*0.5;
double lnrp, phip, lnrm, phim;
for(int m = 0; m <= N/2; m++) {
lngamma_4(xp, m*y, &lnrp, &phip);
lngamma_4(xm, m*y, &lnrm, &phim);
u[m] = polar(exp(q*log2 + lnrp - lnrm), m*t + phip - phim);
}
}
for(int m = N/2+1; m < N; m++)
u[m] = conj(u[N-m]);
if((N % 2) == 0)
u[N/2] = (creal(u[N/2]) + I*0.0);
}
void fht(int N, const double r[], const double complex a[], double k[],
double complex b[], double mu, double q, double kcrc,
int noring, double complex* u)
{
double L = log(r[N-1]/r[0]) * N/(N-1.);
double complex* ulocal = NULL;
if(u == NULL) {
if(noring)
kcrc = goodkr(N, mu, q, L, kcrc);
ulocal = malloc(sizeof(complex double)*N);
compute_u_coefficients(N, mu, q, L, kcrc, ulocal);
u = ulocal;
}
/* Compute the convolution b = a*u using FFTs */
fftw_plan forward_plan = fftw_plan_dft_1d(N, (fftw_complex*) a,
(fftw_complex*) b, -1,
FFTW_ESTIMATE);
fftw_plan reverse_plan = fftw_plan_dft_1d(N, (fftw_complex*) b,
(fftw_complex*) b, +1,
FFTW_ESTIMATE);
fftw_execute(forward_plan);
for(int m = 0; m < N; m++)
b[m] *= u[m] / (double)(N); // divide by N since FFTW doesn't normalize the inverse FFT
fftw_execute(reverse_plan);
fftw_destroy_plan(forward_plan);
fftw_destroy_plan(reverse_plan);
/* Reverse b array */
double complex tmp;
for(int n = 0; n < N/2; n++) {
tmp = b[n];
b[n] = b[N-n-1];
b[N-n-1] = tmp;
}
/* Compute k's corresponding to input r's */
double k0r0 = kcrc * exp(-L);
k[0] = k0r0/r[0];
for(int n = 1; n < N; n++)
k[n] = k[0] * exp(n*L/N);
free(ulocal);
}
void fftlog_ComputeXi2D(double bessel_order,int N,const double l[],
const double cl[], double th[], double xi[])
{
double complex* a = malloc(sizeof(complex double)*N);
double complex* b = malloc(sizeof(complex double)*N);
for(int i=0;i<N;i++)
a[i]=l[i]*cl[i];
fht(N,l,a,th,b,bessel_order,0,1,1,NULL);
for(int i=0;i<N;i++)
xi[i]=creal(b[i]/(2*PI*th[i]));
free(a);
free(b);
}
void fftlog_ComputeXiLM(double l, double m, int N, const double k[],
const double pk[], double r[], double xi[],
double q)
{
static int init_flag = 0;
static int N_old = -99999;
static double complex* a = NULL;
static double complex* b = NULL;
if ((init_flag == 0) || (N != N_old)){
if (a!=NULL) free(a);
if (b!=NULL) free(b);
a = malloc(sizeof(complex double)*N);
b = malloc(sizeof(complex double)*N);
N_old = N;
init_flag = 1;
}
for(int i = 0; i < N; i++)
a[i] = pow(k[i], m-0.5) * pk[i];
fht(N, k, a, r, b, l + 0.5, q, 1, 1, NULL);
for(int i = 0; i < N; i++)
xi[i] = creal(pow(PI_times_2*r[i], 0.5-m) * b[i]);
}
void pk2xi(int N, const double k[], const double pk[], double r[], double xi[])
{
fftlog_ComputeXiLM(0, 2, N, k, pk, r, xi, 0);
}
void xi2pk(int N, const double r[], const double xi[], double k[], double pk[])
{
//static const double TwoPiCubed = 8*PI*PI*PI;
fftlog_ComputeXiLM(0, 2, N, r, xi, k, pk, 0);
for(int j = 0; j < N; j++)
pk[j] *= PI2cubed;
}
| {
"alphanum_fraction": 0.6120772947,
"avg_line_length": 29.2924528302,
"ext": "c",
"hexsha": "7f6e09c1f7e513d0bd7ade66de13bdce4a704233",
"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": "b2100c3c7f3866a4063a78cb3bcd205e7c5672fb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tmcclintock/FastCorr",
"max_forks_repo_path": "src/fftlog.c",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "b2100c3c7f3866a4063a78cb3bcd205e7c5672fb",
"max_issues_repo_issues_event_max_datetime": "2016-12-14T17:10:12.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-14T23:22:15.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tmcclintock/Bessel_Quadrature_Integrator",
"max_issues_repo_path": "src/fftlog.c",
"max_line_length": 97,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "b2100c3c7f3866a4063a78cb3bcd205e7c5672fb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tmcclintock/Bessel_Quadrature_Integrator",
"max_stars_repo_path": "src/fftlog.c",
"max_stars_repo_stars_event_max_datetime": "2019-05-15T19:55:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-15T19:55:06.000Z",
"num_tokens": 2134,
"size": 6210
} |
/* multiset/init.c
* based on combination/init.c by Szymon Jaroszewicz
* based on permutation/init.c by Brian Gough
*
* Copyright (C) 2001 Szymon Jaroszewicz
* Copyright (C) 2009 Brian Gough
* Copyright (C) 2009 Rhys Ulerich
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_multiset.h>
gsl_multiset *
gsl_multiset_alloc (const size_t n, const size_t k)
{
gsl_multiset * c;
if (n == 0)
{
GSL_ERROR_VAL ("multiset parameter n must be positive integer",
GSL_EDOM, 0);
}
if (k > n)
{
GSL_ERROR_VAL ("multiset length k must be an integer less than or equal to n",
GSL_EDOM, 0);
}
c = (gsl_multiset *) malloc (sizeof (gsl_multiset));
if (c == 0)
{
GSL_ERROR_VAL ("failed to allocate space for multiset struct",
GSL_ENOMEM, 0);
}
if (k > 0)
{
c->data = (size_t *) malloc (k * sizeof (size_t));
if (c->data == 0)
{
free (c); /* exception in constructor, avoid memory leak */
GSL_ERROR_VAL ("failed to allocate space for multiset data",
GSL_ENOMEM, 0);
}
}
else
{
c->data = 0;
}
c->n = n;
c->k = k;
return c;
}
gsl_multiset *
gsl_multiset_calloc (const size_t n, const size_t k)
{
size_t i;
gsl_multiset * c = gsl_multiset_alloc (n, k);
if (c == 0)
return 0;
/* initialize multiset to repeated first element */
for (i = 0; i < k; i++)
{
c->data[i] = 0;
}
return c;
}
void
gsl_multiset_init_first (gsl_multiset * c)
{
const size_t k = c->k ;
size_t i;
/* initialize multiset to repeated first element */
for (i = 0; i < k; i++)
{
c->data[i] = 0;
}
}
void
gsl_multiset_init_last (gsl_multiset * c)
{
const size_t k = c->k ;
size_t i;
size_t n = c->n;
/* initialize multiset to repeated last element */
for (i = 0; i < k; i++)
{
c->data[i] = n - 1;
}
}
void
gsl_multiset_free (gsl_multiset * c)
{
RETURN_IF_NULL (c);
if (c->k > 0) free (c->data);
free (c);
}
| {
"alphanum_fraction": 0.606993007,
"avg_line_length": 21.8320610687,
"ext": "c",
"hexsha": "b71b7369c7c0cf76174882b6535dbe8ac898c834",
"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/multiset/init.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/multiset/init.c",
"max_line_length": 84,
"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/multiset/init.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 836,
"size": 2860
} |
#pragma once
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include <gsl/gsl>
#include "RTTI.h"
namespace Library
{
class Shader : public RTTI
{
RTTI_DECLARATIONS(Shader, RTTI)
public:
Shader(const Shader&) = default;
Shader& operator=(const Shader&) = default;
Shader(Shader&&) = default;
Shader& operator=(Shader&&) = default;
virtual ~Shader() = default;
static winrt::com_ptr<ID3D11ClassLinkage> CreateClassLinkage(gsl::not_null<ID3D11Device*> device);
protected:
Shader() = default;
};
} | {
"alphanum_fraction": 0.7062146893,
"avg_line_length": 20.4230769231,
"ext": "h",
"hexsha": "8e9c0a2cb31673e135d894bedec27f9dbb425afd",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_forks_repo_path": "source/Library.Shared/Shader.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_issues_repo_path": "source/Library.Shared/Shader.h",
"max_line_length": 100,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_stars_repo_path": "source/Library.Shared/Shader.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 156,
"size": 531
} |
#include <stdio.h>
#include <stdlib.h>
#include <gbpLib.h>
#include <gbpMisc.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_roots.h>
double bisect_array_function(double x_interp, void *params) {
double interp;
double r_val;
interp = interpolate(((bisect_af_params *)params)->interp, x_interp);
r_val = interp - ((bisect_af_params *)params)->value;
return (r_val);
}
double bisect_array(interp_info *interp, double value, double threshold) {
double * x;
double * y;
double * d2y;
double x_lo;
double x_hi;
double r_val;
int i;
int alloc_flag = GBP_FALSE;
int iter = 0;
int max_iter = 500;
int status = GSL_CONTINUE;
bisect_af_params params;
gsl_function F;
const gsl_root_fsolver_type *T;
gsl_root_fsolver * s;
params.interp = interp;
params.value = value;
F.function = bisect_array_function;
F.params = (void *)(¶ms);
x_lo = interp->x[0];
x_hi = interp->x[interp->n - 1];
if(fabs(bisect_array_function(x_lo, ¶ms)) < threshold)
return (x_lo);
if(fabs(bisect_array_function(x_hi, ¶ms)) < threshold)
return (x_hi);
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc(T);
gsl_root_fsolver_set(s, &F, x_lo, x_hi);
while(status == GSL_CONTINUE && iter < max_iter) {
status = gsl_root_fsolver_iterate(s);
r_val = 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, threshold);
iter++;
}
// Clean-up
gsl_root_fsolver_free(s);
return (r_val);
}
| {
"alphanum_fraction": 0.5469061876,
"avg_line_length": 30.8307692308,
"ext": "c",
"hexsha": "0afe24ff7d874819c145e69963788aace0c39365",
"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/gbpMisc/bisect_array.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/gbpMisc/bisect_array.c",
"max_line_length": 74,
"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/gbpMisc/bisect_array.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": 493,
"size": 2004
} |
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <nlopt.h>
#include <unistd.h>
#include <sys/time.h>
void quadbezier(const double *a, const double *b, const double *c,
double t, double *out)
{
double onemt = 1.0 - t;
out[0] = onemt * (onemt * a[0] + t * b[0]) + t * (onemt * b[0] + t * c[0]);
out[1] = onemt * (onemt * a[1] + t * b[1]) + t * (onemt * b[1] + t * c[1]);
}
void linearinterp(const double *a, const double *b,
double t, double *out)
{
out[0] = (b[0] - a[0]) * t + a[0];
out[1] = (b[1] - a[1]) * t + a[1];
}
typedef struct {
int N;
int steps;
double *starts;
double *stops;
double *scratch;
} problem_t;
double randd()
{
int n = rand() % (1<<24);
return ((double)n) / ((double)(1<<24));
}
double distance(const double *a, const double *b)
{
return sqrt((b[0] - a[0]) * (b[0] - a[0]) +
(b[1] - a[1]) * (b[1] - a[1]));
}
#define RADIUS 5.0
double errorf(unsigned n, const double *pts, double *grad,
void *data)
{
problem_t *setup = (problem_t *)data;
double error = 0.0;
for(int step=0; step<setup->steps; step++) {
double t = (1.0+step) / (1.0+setup->steps);
for(int i=0; i<setup->N; i++)
quadbezier(&setup->starts[2*i],
&pts[2*i],
&setup->stops[2*i],
t,
&setup->scratch[2*i]);
for(int i=0; i<setup->N; i++)
for(int j=i+1; j<setup->N; j++) {
double d = distance(&setup->scratch[2*i],
&setup->scratch[2*j]);
d /= RADIUS;
error += (1.0/d) * (1.0/d);
}
}
return error / setup->steps;
}
int main(int argc, char *argv[])
{
int N = 12;
double *starts = (double *)malloc(sizeof(double)*N*2);
double *stops = (double *)malloc(sizeof(double)*N*2);
srand(2);
nlopt_srand(1);
double scaling = 100.0;
for(int i=0; i<N; i++) {
starts[2*i+0] = scaling * randd();
starts[2*i+1] = scaling * randd();
stops[2*i+0] = scaling * randd();
stops[2*i+1] = scaling * randd();
}
double hs = scaling / 2.0;
for(int i=0; i<N; i++) {
double theta = ((double)i)/N * 2 * 3.141592;
starts[2*i+0] = hs * cos(theta) + hs;
starts[2*i+1] = hs * sin(theta) + hs;
stops[2*i+0] = hs * cos(theta + 3.141592) + hs;
stops[2*i+1] = hs * sin(theta + 3.141592) + hs;
}
struct timeval start, stop;
double *guesses = (double *)malloc(sizeof(double)*N*2);
gettimeofday(&start, NULL);
for(int i=0; i<N; i++) {
linearinterp(&starts[2*i], &stops[2*i], 0.5, &guesses[2*i]);
}
nlopt_opt global = nlopt_create(NLOPT_GN_ISRES, 2*N);
nlopt_opt local = nlopt_create(NLOPT_LN_SBPLX, 2*N);
problem_t *setup = (problem_t *)malloc(sizeof(problem_t));
setup->N = N;
setup->starts = starts;
setup->stops = stops;
setup->steps = 50;
setup->scratch = (double *)malloc(sizeof(double)*N*2);
nlopt_result res;
res = nlopt_set_min_objective(global, errorf, setup);
if(res!=1) { exit(-1); }
res = nlopt_set_lower_bounds1(global, -25.0);
if(res!=1) { exit(-1); }
res = nlopt_set_upper_bounds1(global, 125.0);
if(res!=1) { exit(-1); }
res = nlopt_set_stopval(global, 1.0);
if(res!=1) { exit(-1); }
res = nlopt_set_maxeval(global, 100);
if(res!=1) { exit(-1); }
double final_error;
res = nlopt_optimize(global, guesses, &final_error);
res = nlopt_set_min_objective(local, errorf, setup);
if(res!=1) { exit(-1); }
res = nlopt_set_lower_bounds1(local, -25.0);
if(res!=1) { exit(-1); }
res = nlopt_set_upper_bounds1(local, 125.0);
if(res!=1) { exit(-1); }
res = nlopt_set_stopval(local, 1.0);
if(res!=1) { exit(-1); }
res = nlopt_set_maxeval(local, 1000);
if(res!=1) { exit(-1); }
res = nlopt_optimize(local, guesses, &final_error);
gettimeofday(&stop, NULL);
fprintf(stderr, "final: %f\n", final_error);
for(int i=0; i<N; i++) {
printf("%f %f %f %f %f %f\n",
starts[2*i+0], starts[2*i+1],
guesses[2*i+0], guesses[2*i+1],
stops[2*i+0], stops[2*i+1]);
}
double startd, stopd;
startd = start.tv_sec;
startd += ((double)(start.tv_usec)) / 1e6;
stopd = stop.tv_sec;
stopd += ((double)(stop.tv_usec)) / 1e6;
//printf("%f\n", stopd - startd);
}
| {
"alphanum_fraction": 0.5741684875,
"avg_line_length": 23.8092485549,
"ext": "c",
"hexsha": "dfb138a07781e91a0347fb1a6e00fadeeaa5133d",
"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": "349177e38fae31eff407c7188b243c641807dc16",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "jkominek/discs",
"max_forks_repo_path": "discs.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "349177e38fae31eff407c7188b243c641807dc16",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "jkominek/discs",
"max_issues_repo_path": "discs.c",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "349177e38fae31eff407c7188b243c641807dc16",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "jkominek/discs",
"max_stars_repo_path": "discs.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1534,
"size": 4119
} |
//popGen stuff for Next Gen Sequencing Data
#include "pgSummaryStats.h"
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "vector.h"
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_matrix.h>
//Sampling Probability stuff
//prob_i returns the probability under SNM of a snp freq i
double prob_i(int i, int n){
double tmp;
tmp = 1.0 / (double) i;
return(tmp/ a1f(n));
}
double prob_km(int k, int m, int n){
double sum = 0.0;
int i;
double tmpFreq;
for(i=1;i<n;i++){
tmpFreq = (double) i / (double) n;
sum += gsl_ran_binomial_pdf(k,tmpFreq,m) * prob_i(i,n);
}
return(sum);
}
//achaz system stuff
double achazSFS(gsl_matrix *sfsCount, gsl_matrix *weightMat){
int i, j;
double theta = 0.0;
double weightSum, tmpTheta;
//rows = sampleSizes
for(i = 2; i < sfsCount->size1; i++){
weightSum = 0.0;
tmpTheta = 0.0;
for(j = 1; j < i; j++){
//size i freq j
tmpTheta += gsl_matrix_get(sfsCount, i, j) * j * gsl_matrix_get(weightMat,i,j);
weightSum += gsl_matrix_get(weightMat,i,j);
}
if(weightSum > 0){ theta += tmpTheta / weightSum; }
}
return(theta);
}
double achazSFSCorrected(gsl_matrix *sfsCount, gsl_matrix *weightMat,int nPool){
int i, j;
double theta = 0.0;
double weightSum, tmpTheta;
//rows = sampleSizes
for(i = 2; i < sfsCount->size1; i++){
weightSum = 0.0;
tmpTheta = 0.0;
for(j = 1; j < i; j++){
//size i freq j
tmpTheta += gsl_matrix_get(sfsCount, i, j) * gsl_matrix_get(weightMat,i,j) * (1.0/prob_km(j,i,nPool));
weightSum += gsl_matrix_get(weightMat,i,j);
}
if(weightSum > 0){
theta += tmpTheta / weightSum / a1f(nPool);
}
}
return(theta);
}
// fillPiWeights -- returns the weight matrix for theta_pi
void fillPiWeights(gsl_matrix *weightMat, int minFreq){
int i, j;
gsl_matrix_set_zero(weightMat);
for(i=minFreq+1; i < weightMat->size1; i++){
for(j=minFreq;j<i;j++){
gsl_matrix_set(weightMat,i,j,i-j);
}
}
}
// fillHWeights -- returns the weight matrix for theta_H
void fillHWeights(gsl_matrix *weightMat, int minFreq){
int i, j;
gsl_matrix_set_zero(weightMat);
for(i=minFreq+1; i < weightMat->size1; i++){
for(j=minFreq;j<i;j++){
gsl_matrix_set(weightMat,i,j,j);
}
}
}
// fillWWeights -- returns the weight matrix for theta_w
void fillWWeights(gsl_matrix *weightMat, int minFreq){
int i, j;
gsl_matrix_set_zero(weightMat);
for(i=minFreq+1; i < weightMat->size1; i++){
for(j=minFreq;j<i;j++){
gsl_matrix_set(weightMat,i,j,1/(double)j);
}
}
}
| {
"alphanum_fraction": 0.6647127784,
"avg_line_length": 22.4473684211,
"ext": "c",
"hexsha": "247d63406b4fa77639c6ba4c855d2a3618f56595",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-09-15T10:37:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-15T10:37:33.000Z",
"max_forks_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "andrewkern/pgLib",
"max_forks_repo_path": "ngsPopGenTools.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "andrewkern/pgLib",
"max_issues_repo_path": "ngsPopGenTools.c",
"max_line_length": 105,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "andrewkern/pgLib",
"max_stars_repo_path": "ngsPopGenTools.c",
"max_stars_repo_stars_event_max_datetime": "2018-09-16T05:43:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-09-15T10:37:29.000Z",
"num_tokens": 841,
"size": 2559
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#ifndef NOMPI
#include <mpi.h>
#endif
#include <gsl/gsl_math.h>
#include "allvars.h"
#include "proto.h"
/*! \file predict.c
* \brief drift particles by a small time interval
*
* This function contains code to implement a drift operation on all the
* particles, which represents one part of the leapfrog integration scheme.
*/
/*! This function drifts all particles from the current time to the future:
* time0 - > time1
*
* If there is no explicit tree construction in the following timestep, the
* tree nodes are also drifted and updated accordingly. Note: For periodic
* boundary conditions, the mapping of coordinates onto the interval
* [0,All.BoxSize] is only done before the domain decomposition, or for
* outputs to snapshot files. This simplifies dynamic tree updates, and
* allows the domain decomposition to be carried out only every once in a
* while.
*/
void move_particles(int time0, int time1)
{
int i, j;
double dt_drift, dt_gravkick, dt_hydrokick, dt_entr;
double t0, t1;
t0 = second();
if(All.ComovingIntegrationOn)
{
dt_drift = get_drift_factor(time0, time1);
dt_gravkick = get_gravkick_factor(time0, time1);
dt_hydrokick = get_hydrokick_factor(time0, time1);
}
else
{
dt_drift = dt_gravkick = dt_hydrokick = (time1 - time0) * All.Timebase_interval;
}
for(i = 0; i < NumPart; i++)
{
for(j = 0; j < 3; j++)
P[i].Pos[j] += P[i].Vel[j] * dt_drift;
if(P[i].Type == 0)
{
#ifdef PMGRID
for(j = 0; j < 3; j++)
SphP[i].VelPred[j] +=
(P[i].GravAccel[j] + P[i].GravPM[j]) * dt_gravkick + SphP[i].HydroAccel[j] * dt_hydrokick;
#else
for(j = 0; j < 3; j++)
SphP[i].VelPred[j] += P[i].GravAccel[j] * dt_gravkick + SphP[i].HydroAccel[j] * dt_hydrokick;
#endif
SphP[i].Density *= exp(-SphP[i].DivVel * dt_drift);
SphP[i].Hsml *= exp(0.333333333333 * SphP[i].DivVel * dt_drift);
if(SphP[i].Hsml < All.MinGasHsml)
SphP[i].Hsml = All.MinGasHsml;
dt_entr = (time1 - (P[i].Ti_begstep + P[i].Ti_endstep) / 2) * All.Timebase_interval;
SphP[i].Pressure = (SphP[i].Entropy + SphP[i].DtEntropy * dt_entr) * pow(SphP[i].Density, GAMMA);
#ifdef MORRIS97VISC
SphP[i].Alpha += SphP[i].DAlphaDt * dt_drift;
#endif
}
}
/* if domain-decomp and tree are not going to be reconstructed, update dynamically. */
if(All.NumForcesSinceLastDomainDecomp < All.TotNumPart * All.TreeDomainUpdateFrequency)
{
for(i = 0; i < Numnodestree; i++)
for(j = 0; j < 3; j++)
Nodes[All.MaxPart + i].u.d.s[j] += Extnodes[All.MaxPart + i].vs[j] * dt_drift;
force_update_len();
force_update_pseudoparticles();
}
t1 = second();
All.CPU_Predict += timediff(t0, t1);
}
/*! This function makes sure that all particle coordinates (Pos) are
* periodically mapped onto the interval [0, BoxSize]. After this function
* has been called, a new domain decomposition should be done, which will
* also force a new tree construction.
*/
#ifdef PERIODIC
void do_box_wrapping(void)
{
int i, j;
double boxsize[3];
for(j = 0; j < 3; j++)
boxsize[j] = All.BoxSize;
#ifdef LONG_X
boxsize[0] *= LONG_X;
#endif
#ifdef LONG_Y
boxsize[1] *= LONG_Y;
#endif
#ifdef LONG_Z
boxsize[2] *= LONG_Z;
#endif
for(i = 0; i < NumPart; i++)
for(j = 0; j < 3; j++)
{
while(P[i].Pos[j] < 0)
P[i].Pos[j] += boxsize[j];
while(P[i].Pos[j] >= boxsize[j])
P[i].Pos[j] -= boxsize[j];
}
}
#endif
| {
"alphanum_fraction": 0.645505618,
"avg_line_length": 25.7971014493,
"ext": "c",
"hexsha": "bec03d609501e025fddbeacb306b24625474e82f",
"lang": "C",
"max_forks_count": 102,
"max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z",
"max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "rieder/amuse",
"max_forks_repo_path": "src/amuse/community/gadget2/src/predict.c",
"max_issues_count": 690,
"max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "rknop/amuse",
"max_issues_repo_path": "src/amuse/community/gadget2/src/predict.c",
"max_line_length": 100,
"max_stars_count": 131,
"max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "rknop/amuse",
"max_stars_repo_path": "src/amuse/community/gadget2/src/predict.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z",
"num_tokens": 1153,
"size": 3560
} |
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
int
main (void)
{
int i;
double x = 0, y = 0, dx, dy;
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
printf ("%g %g\n", x, y);
for (i = 0; i < 10; i++)
{
gsl_ran_dir_2d (r, &dx, &dy);
x += dx; y += dy;
printf ("%g %g\n", x, y);
}
gsl_rng_free (r);
return 0;
}
| {
"alphanum_fraction": 0.5237020316,
"avg_line_length": 14.7666666667,
"ext": "c",
"hexsha": "588aa502619872a9f31175fdbbdd105f1f0445de",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/randwalk.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/randwalk.c",
"max_line_length": 35,
"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/randwalk.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": 170,
"size": 443
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
#include "ccl.h"
#ifdef HAVE_ANGPOW
#include "Angpow/angpow_ccl.h"
#endif
#define CCL_FRAC_RELEVANT 5E-4
//#define CCL_FRAC_RELEVANT 1E-3
//Gets the x-interval where the values of y are relevant
//(meaning, that the values of y for those x are at least above a fraction frac of its maximum)
static void get_support_interval(int n,double *x,double *y,double frac,
double *xmin_out,double *xmax_out)
{
int ix;
double ythr=-1000;
//Initialize as the original edges in case we don't find an interval
*xmin_out=x[0];
*xmax_out=x[n-1];
//Find threshold
for(ix=0;ix<n;ix++) {
if(y[ix]>ythr) ythr=y[ix];
}
ythr*=frac;
//Find minimum
for(ix=0;ix<n;ix++) {
if(y[ix]>=ythr) {
*xmin_out=x[ix];
break;
}
}
//Find maximum
for(ix=n-1;ix>=0;ix--) {
if(y[ix]>=ythr) {
*xmax_out=x[ix];
break;
}
}
}
//Wrapper around spline_eval with GSL function syntax
static double speval_bis(double x,void *params)
{
return ccl_spline_eval(x,(SplPar *)params);
}
void ccl_cl_workspace_free(CCL_ClWorkspace *w)
{
free(w->l_arr);
free(w);
}
CCL_ClWorkspace *ccl_cl_workspace_new(int lmax,int l_limber,
double l_logstep,int l_linstep,int *status)
{
int i_l,l0,increment;
CCL_ClWorkspace *w=(CCL_ClWorkspace *)malloc(sizeof(CCL_ClWorkspace));
if(w==NULL)
*status=CCL_ERROR_MEMORY;
if(*status==0) {
//Set params
w->lmax=lmax;
w->l_limber=l_limber;
w->l_logstep=l_logstep;
w->l_linstep=l_linstep;
//Compute number of multipoles
i_l=0; l0=0;
increment=CCL_MAX(((int)(l0*(w->l_logstep-1.))),1);
while((l0 < w->lmax) && (increment < w->l_linstep)) {
i_l++;
l0+=increment;
increment=CCL_MAX(((int)(l0*(w->l_logstep-1))),1);
}
increment=w->l_linstep;
while(l0 < w->lmax) {
i_l++;
l0+=increment;
}
//Allocate array of multipoles
w->n_ls=i_l+1;
w->l_arr=(int *)malloc(w->n_ls*sizeof(int));
if(w->l_arr==NULL)
*status=CCL_ERROR_MEMORY;
}
if(*status==0) {
//Redo the computation above and store values of ell
i_l=0; l0=0;
increment=CCL_MAX(((int)(l0*(w->l_logstep-1.))),1);
while((l0 < w->lmax) && (increment < w->l_linstep)) {
w->l_arr[i_l]=l0;
i_l++;
l0+=increment;
increment=CCL_MAX(((int)(l0*(w->l_logstep-1))),1);
}
increment=w->l_linstep;
while(l0 < w->lmax) {
w->l_arr[i_l]=l0;
i_l++;
l0+=increment;
}
//Don't go further than lmaw
w->l_arr[w->n_ls-1]=w->lmax;
}
return w;
}
CCL_ClWorkspace *ccl_cl_workspace_new_limber(int lmax,double l_logstep,int l_linstep,int *status)
{
return ccl_cl_workspace_new(lmax,-1,l_logstep,l_linstep,status);
}
//Params for lensing kernel integrand
typedef struct {
double chi;
SplPar *spl_pz;
ccl_cosmology *cosmo;
int *status;
} IntLensPar;
//Integrand for lensing kernel
static double integrand_wl(double chip,void *params)
{
IntLensPar *p=(IntLensPar *)params;
double chi=p->chi;
double a=ccl_scale_factor_of_chi(p->cosmo,chip, p->status);
double z=1./a-1;
double pz=ccl_spline_eval(z,p->spl_pz);
double h=p->cosmo->params.h*ccl_h_over_h0(p->cosmo,a, p->status)/CLIGHT_HMPC;
if(chi==0)
return h*pz;
else
return h*pz*ccl_sinn(p->cosmo,chip-chi,p->status)/ccl_sinn(p->cosmo,chip,p->status);
}
//Integral to compute lensing window function
//chi -> comoving distance
//cosmo -> ccl_cosmology object
//spl_pz -> normalized N(z) spline
//chi_max -> maximum comoving distance to which the integral is computed
//win -> result is stored here
static int window_lensing(double chi,ccl_cosmology *cosmo,SplPar *spl_pz,double chi_max,double *win)
{
int gslstatus =0, status =0;
double result,eresult;
IntLensPar ip;
gsl_function F;
gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION);
ip.chi=chi;
ip.cosmo=cosmo;
ip.spl_pz=spl_pz;
ip.status = &status;
F.function=&integrand_wl;
F.params=&ip;
// This conputes the lensing kernel:
// w_L(chi) = Integral[ dN/dchi(chi') * f(chi'-chi)/f(chi') , chi < chi' < chi_horizon ]
// Where f(chi) is the comoving angular distance (which is just chi for zero curvature).
gslstatus=gsl_integration_qag(&F, chi, chi_max, 0,
ccl_gsl->INTEGRATION_EPSREL, ccl_gsl->N_ITERATION,
ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS,
w, &result, &eresult);
*win=result;
gsl_integration_workspace_free(w);
if(gslstatus!=GSL_SUCCESS || *ip.status) {
ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: window_lensing():");
return 1;
}
//TODO: chi_max should be changed to chi_horizon
//we should precompute this quantity and store it in cosmo by default
return 0;
}
//Params for lensing kernel integrand
typedef struct {
double chi;
SplPar *spl_pz;
SplPar *spl_sz;
ccl_cosmology *cosmo;
int *status;
} IntMagPar;
//Integrand for magnification kernel
static double integrand_mag(double chip,void *params)
{
IntMagPar *p=(IntMagPar *)params;
double chi=p->chi;
double a=ccl_scale_factor_of_chi(p->cosmo,chip, p->status);
double z=1./a-1;
double pz=ccl_spline_eval(z,p->spl_pz);
double sz=ccl_spline_eval(z,p->spl_sz);
double h=p->cosmo->params.h*ccl_h_over_h0(p->cosmo,a, p->status)/CLIGHT_HMPC;
if(chi==0)
return h*pz*(1-2.5*sz);
else
return h*pz*(1-2.5*sz)*ccl_sinn(p->cosmo,chip-chi,p->status)/ccl_sinn(p->cosmo,chip,p->status);
}
//Integral to compute magnification window function
//chi -> comoving distance
//cosmo -> ccl_cosmology object
//spl_pz -> normalized N(z) spline
//spl_pz -> magnification bias s(z)
//chi_max -> maximum comoving distance to which the integral is computed
//win -> result is stored here
static int window_magnification(double chi,ccl_cosmology *cosmo,SplPar *spl_pz,SplPar *spl_sz,
double chi_max,double *win)
{
int gslstatus =0, status =0;
double result,eresult;
IntMagPar ip;
gsl_function F;
gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION);
ip.chi=chi;
ip.cosmo=cosmo;
ip.spl_pz=spl_pz;
ip.spl_sz=spl_sz;
ip.status = &status;
F.function=&integrand_mag;
F.params=&ip;
// This conputes the magnification lensing kernel:
// w_M(chi) = Integral[ dN/dchi(chi') * (1-5/2 * s(chi)) * f(chi'-chi)/f(chi') , chi < chi' < chi_horizon ]
// Where f(chi) is the comoving angular distance (which is just chi for zero curvature)
// and s(chi) is the magnification bias parameter.
gslstatus=gsl_integration_qag(&F, chi, chi_max, 0,
ccl_gsl->INTEGRATION_EPSREL, ccl_gsl->N_ITERATION,
ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS,
w, &result, &eresult);
*win=result;
gsl_integration_workspace_free(w);
if(gslstatus!=GSL_SUCCESS || *ip.status) {
ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: window_magnification():");
return 1;
}
//TODO: chi_max should be changed to chi_horizon
//we should precompute this quantity and store it in cosmo by default
return 0;
}
static void clt_init_nz(CCL_ClTracer *clt,ccl_cosmology *cosmo,
int nz_n,double *z_n,double *n,int *status)
{
int gslstatus;
gsl_function F;
double nz_norm,nz_enorm;
double *nz_normalized;
//Find redshift range where the N(z) has support
get_support_interval(nz_n,z_n,n,CCL_FRAC_RELEVANT,&(clt->zmin),&(clt->zmax));
clt->chimax=ccl_comoving_radial_distance(cosmo,1./(1+clt->zmax),status);
clt->chimin=ccl_comoving_radial_distance(cosmo,1./(1+clt->zmin),status);
clt->spl_nz=ccl_spline_init(nz_n,z_n,n,0,0);
if(clt->spl_nz==NULL) {
*status=CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: clt_init_nz(): error initializing spline for N(z)\n");
}
if(*status==0) {
//Normalize n(z)
nz_normalized=(double *)malloc(nz_n*sizeof(double));
if(nz_normalized==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: clt_init_nz(): memory allocation\n");
return;
}
}
if(*status==0) {
gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION);
F.function=&speval_bis;
F.params=clt->spl_nz;
//Here we're just integrating the N(z) to normalize it to unit probability.
gslstatus=gsl_integration_qag(&F, z_n[0], z_n[nz_n-1], 0,
ccl_gsl->INTEGRATION_EPSREL, ccl_gsl->N_ITERATION,
ccl_gsl->INTEGRATION_GAUSS_KRONROD_POINTS,
w, &nz_norm, &nz_enorm);
gsl_integration_workspace_free(w);
if(gslstatus!=GSL_SUCCESS) {
ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: clt_init_nz():");
*status=CCL_ERROR_INTEG;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: clt_init_nz(): integration error when normalizing N(z)\n");
}
}
if(*status==0) {
for(int ii=0;ii<nz_n;ii++)
nz_normalized[ii]=n[ii]/nz_norm;
ccl_spline_free(clt->spl_nz);
clt->spl_nz=ccl_spline_init(nz_n,z_n,nz_normalized,0,0);
if(clt->spl_nz==NULL) {
*status=CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: clt_init_nz(): error initializing normalized spline for N(z)\n");
}
}
free(nz_normalized);
}
static void clt_init_bz(CCL_ClTracer *clt,ccl_cosmology *cosmo,
int nz_b,double *z_b,double *b,int *status)
{
//Initialize bias spline
clt->spl_bz=ccl_spline_init(nz_b,z_b,b,b[0],b[nz_b-1]);
if(clt->spl_bz==NULL) {
*status=CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: clt_init_bz(): error initializing spline for b(z)\n");
}
}
static void clt_init_wM(CCL_ClTracer *clt,ccl_cosmology *cosmo,
int nz_s,double *z_s,double *s,int *status)
{
//Compute magnification kernel
int nchi;
double *x,*y;
double dchi_here=5.;
double zmax=clt->spl_nz->xf;
double chimax=ccl_comoving_radial_distance(cosmo,1./(1+zmax),status);
//TODO: The interval in chi (5. Mpc) should be made a macro
//In this case we need to integrate all the way to z=0. Reset zmin and chimin
clt->zmin=0;
clt->chimin=0;
clt->spl_sz=ccl_spline_init(nz_s,z_s,s,s[0],s[nz_s-1]);
if(clt->spl_sz==NULL) {
*status=CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(cosmo,
"ccl_cls.c: clt_init_wM(): error initializing spline for s(z)\n");
}
if(*status==0) {
nchi=(int)(chimax/dchi_here)+1;
x=ccl_linear_spacing(0.,chimax,nchi);
dchi_here=chimax/nchi;
if(x==NULL || (fabs(x[0]-0)>1E-5) || (fabs(x[nchi-1]-chimax)>1e-5)) {
*status=CCL_ERROR_LINSPACE;
ccl_cosmology_set_status_message(cosmo,
"ccl_cls.c: clt_init_wM(): Error creating linear spacing in chi\n");
}
}
if(*status==0) {
y=(double *)malloc(nchi*sizeof(double));
if(y==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: clt_init_wM(): memory allocation\n");
}
}
if(*status==0) {
int clstatus=0;
for(int j=0;j<nchi;j++)
clstatus|=window_magnification(x[j],cosmo,clt->spl_nz,clt->spl_sz,chimax,&(y[j]));
if(clstatus) {
*status=CCL_ERROR_INTEG;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: clt_init_wM(): error computing lensing window\n");
}
}
if(*status==0) {
clt->spl_wM=ccl_spline_init(nchi,x,y,y[0],0);
if(clt->spl_wM==NULL) {
*status=CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(cosmo,
"ccl_cls.c: clt_init_wM(): error initializing spline for lensing window\n");
}
}
free(x); free(y);
}
//CCL_ClTracer initializer for number counts
static void clt_nc_init(CCL_ClTracer *clt,ccl_cosmology *cosmo,
int has_rsd,int has_magnification,
int nz_n,double *z_n,double *n,
int nz_b,double *z_b,double *b,
int nz_s,double *z_s,double *s,int *status)
{
clt->has_rsd=has_rsd;
clt->has_magnification=has_magnification;
if ( ((cosmo->params.N_nu_mass)>0) && clt->has_rsd){
*status=CCL_ERROR_NOT_IMPLEMENTED;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer_new(): Number counts tracers with RSD not yet implemented in cosmologies with massive neutrinos.");
return;
}
clt_init_nz(clt,cosmo,nz_n,z_n,n,status);
clt_init_bz(clt,cosmo,nz_b,z_b,b,status);
if(clt->has_magnification)
clt_init_wM(clt,cosmo,nz_s,z_s,s,status);
}
static void clt_init_wL(CCL_ClTracer *clt,ccl_cosmology *cosmo,
int *status)
{
//Compute weak lensing kernel
int nchi;
double *x,*y;
double dchi_here=5.;
double zmax=clt->spl_nz->xf;
double chimax=ccl_comoving_radial_distance(cosmo,1./(1+zmax),status);
//TODO: The interval in chi (5. Mpc) should be made a macro
//In this case we need to integrate all the way to z=0. Reset zmin and chimin
clt->zmin=0;
clt->chimin=0;
nchi=(int)(chimax/dchi_here)+1;
x=ccl_linear_spacing(0.,chimax,nchi);
dchi_here=chimax/nchi;
if(x==NULL || (fabs(x[0]-0)>1E-5) || (fabs(x[nchi-1]-chimax)>1e-5)) {
*status=CCL_ERROR_LINSPACE;
ccl_cosmology_set_status_message(cosmo,
"ccl_cls.c: clt_init_wL(): Error creating linear spacing in chi\n");
}
if(*status==0) {
y=(double *)malloc(nchi*sizeof(double));
if(y==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: clt_init_wL(): memory allocation\n");
}
}
if(*status==0) {
int clstatus=0;
for(int j=0;j<nchi;j++)
clstatus|=window_lensing(x[j],cosmo,clt->spl_nz,chimax,&(y[j]));
if(clstatus) {
*status=CCL_ERROR_INTEG;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: clt_init_wL(): error computing lensing window\n");
}
}
if(*status==0) {
clt->spl_wL=ccl_spline_init(nchi,x,y,y[0],0);
if(clt->spl_wL==NULL) {
*status=CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(cosmo,
"ccl_cls.c: clt_init_wL(): error initializing spline for lensing window\n");
}
}
free(x); free(y);
}
static void clt_init_rf(CCL_ClTracer *clt,ccl_cosmology *cosmo,
int nz_rf,double *z_rf,double *rf,int *status)
{
//Initialize bias spline
clt->spl_rf=ccl_spline_init(nz_rf,z_rf,rf,rf[0],rf[nz_rf-1]);
if(clt->spl_rf==NULL) {
*status=CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: clt_init_rf(): error initializing spline for b(z)\n");
}
}
static void clt_init_ba(CCL_ClTracer *clt,ccl_cosmology *cosmo,
int nz_ba,double *z_ba,double *ba,int *status)
{
//Initialize bias spline
clt->spl_ba=ccl_spline_init(nz_ba,z_ba,ba,ba[0],ba[nz_ba-1]);
if(clt->spl_ba==NULL) {
*status=CCL_ERROR_SPLINE;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: clt_init_ba(): error initializing spline for b(z)\n");
}
}
static void clt_wl_init(CCL_ClTracer *clt,ccl_cosmology *cosmo,
int has_intrinsic_alignment,
int nz_n,double *z_n,double *n,
int nz_ba,double *z_ba,double *ba,
int nz_rf,double *z_rf,double *rf,int *status)
{
clt->has_intrinsic_alignment=has_intrinsic_alignment;
clt_init_nz(clt,cosmo,nz_n,z_n,n,status);
clt_init_wL(clt,cosmo,status);
if(clt->has_intrinsic_alignment) {
clt_init_rf(clt,cosmo,nz_rf,z_rf,rf,status);
clt_init_ba(clt,cosmo,nz_ba,z_ba,ba,status);
}
}
//CCL_ClTracer creator
//cosmo -> ccl_cosmology object
//tracer_type -> type of tracer. Supported: ccl_number_counts_tracer, ccl_weak_lensing_tracer
//nz_n -> number of points for N(z)
//z_n -> array of z-values for N(z)
//n -> corresponding N(z)-values. Normalization is irrelevant
// N(z) will be set to zero outside the range covered by z_n
//nz_b -> number of points for b(z)
//z_b -> array of z-values for b(z)
//b -> corresponding b(z)-values.
// b(z) will be assumed constant outside the range covered by z_n
static CCL_ClTracer *cl_tracer(ccl_cosmology *cosmo,int tracer_type,
int has_rsd,int has_magnification,int has_intrinsic_alignment,
int nz_n,double *z_n,double *n,
int nz_b,double *z_b,double *b,
int nz_s,double *z_s,double *s,
int nz_ba,double *z_ba,double *ba,
int nz_rf,double *z_rf,double *rf,
double z_source, int * status)
{
int clstatus=0;
CCL_ClTracer *clt=(CCL_ClTracer *)malloc(sizeof(CCL_ClTracer));
if(clt==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): memory allocation\n");
}
if(*status==0) {
clt->tracer_type=tracer_type;
double hub=cosmo->params.h*ccl_h_over_h0(cosmo,1.,status)/CLIGHT_HMPC;
clt->prefac_lensing=1.5*hub*hub*cosmo->params.Omega_m;
if(tracer_type==ccl_number_counts_tracer)
clt_nc_init(clt,cosmo,has_rsd,has_magnification,
nz_n,z_n,n,nz_b,z_b,b,nz_s,z_s,s,status);
else if(tracer_type==ccl_weak_lensing_tracer)
clt_wl_init(clt,cosmo,has_intrinsic_alignment,
nz_n,z_n,n,nz_ba,z_ba,ba,nz_rf,z_rf,rf,status);
else if(tracer_type==ccl_cmb_lensing_tracer) {
clt->chi_source=ccl_comoving_radial_distance(cosmo,1./(1+z_source),status);
clt->chimax=clt->chi_source;
clt->chimin=0;
}
else {
free(clt);
*status=CCL_ERROR_INCONSISTENT;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_tracer(): unknown tracer type\n");
return NULL;
}
}
if(*status) {
free(clt);
clt=NULL;
}
return clt;
}
//CCL_ClTracer constructor with error checking
//cosmo -> ccl_cosmology object
//tracer_type -> type of tracer. Supported: ccl_number_counts_tracer, ccl_weak_lensing_tracer
//nz_n -> number of points for N(z)
//z_n -> array of z-values for N(z)
//n -> corresponding N(z)-values. Normalization is irrelevant
// N(z) will be set to zero outside the range covered by z_n
//nz_b -> number of points for b(z)
//z_b -> array of z-values for b(z)
//b -> corresponding b(z)-values.
// b(z) will be assumed constant outside the range covered by z_n
CCL_ClTracer *ccl_cl_tracer(ccl_cosmology *cosmo,int tracer_type,
int has_rsd,int has_magnification,int has_intrinsic_alignment,
int nz_n,double *z_n,double *n,
int nz_b,double *z_b,double *b,
int nz_s,double *z_s,double *s,
int nz_ba,double *z_ba,double *ba,
int nz_rf,double *z_rf,double *rf,
double z_source, int * status)
{
CCL_ClTracer *clt=cl_tracer(cosmo,tracer_type,has_rsd,has_magnification,has_intrinsic_alignment,
nz_n,z_n,n,nz_b,z_b,b,nz_s,z_s,s,
nz_ba,z_ba,ba,nz_rf,z_rf,rf,z_source,status);
ccl_check_status(cosmo,status);
return clt;
}
//CCL_ClTracer destructor
void ccl_cl_tracer_free(CCL_ClTracer *clt)
{
if((clt->tracer_type==ccl_number_counts_tracer) || (clt->tracer_type==ccl_weak_lensing_tracer))
ccl_spline_free(clt->spl_nz);
if(clt->tracer_type==ccl_number_counts_tracer) {
ccl_spline_free(clt->spl_bz);
if(clt->has_magnification) {
ccl_spline_free(clt->spl_sz);
ccl_spline_free(clt->spl_wM);
}
}
else if(clt->tracer_type==ccl_weak_lensing_tracer) {
ccl_spline_free(clt->spl_wL);
if(clt->has_intrinsic_alignment) {
ccl_spline_free(clt->spl_ba);
ccl_spline_free(clt->spl_rf);
}
}
free(clt);
}
CCL_ClTracer *ccl_cl_tracer_cmblens(ccl_cosmology *cosmo,double z_source,int *status)
{
return ccl_cl_tracer(cosmo,ccl_cmb_lensing_tracer,
0,0,0,
0,NULL,NULL,0,NULL,NULL,0,NULL,NULL,
0,NULL,NULL,0,NULL,NULL,z_source,status);
}
CCL_ClTracer *ccl_cl_tracer_number_counts(ccl_cosmology *cosmo,
int has_rsd,int has_magnification,
int nz_n,double *z_n,double *n,
int nz_b,double *z_b,double *b,
int nz_s,double *z_s,double *s, int * status)
{
return ccl_cl_tracer(cosmo,ccl_number_counts_tracer,has_rsd,has_magnification,0,
nz_n,z_n,n,nz_b,z_b,b,nz_s,z_s,s,
-1,NULL,NULL,-1,NULL,NULL,0, status);
}
CCL_ClTracer *ccl_cl_tracer_number_counts_simple(ccl_cosmology *cosmo,
int nz_n,double *z_n,double *n,
int nz_b,double *z_b,double *b, int * status)
{
return ccl_cl_tracer(cosmo,ccl_number_counts_tracer,0,0,0,
nz_n,z_n,n,nz_b,z_b,b,-1,NULL,NULL,
-1,NULL,NULL,-1,NULL,NULL,0, status);
}
CCL_ClTracer *ccl_cl_tracer_lensing(ccl_cosmology *cosmo,
int has_alignment,
int nz_n,double *z_n,double *n,
int nz_ba,double *z_ba,double *ba,
int nz_rf,double *z_rf,double *rf, int * status)
{
return ccl_cl_tracer(cosmo,ccl_weak_lensing_tracer,0,0,has_alignment,
nz_n,z_n,n,-1,NULL,NULL,-1,NULL,NULL,
nz_ba,z_ba,ba,nz_rf,z_rf,rf,0, status);
}
CCL_ClTracer *ccl_cl_tracer_lensing_simple(ccl_cosmology *cosmo,
int nz_n,double *z_n,double *n, int * status)
{
return ccl_cl_tracer(cosmo,ccl_weak_lensing_tracer,0,0,0,
nz_n,z_n,n,-1,NULL,NULL,-1,NULL,NULL,
-1,NULL,NULL,-1,NULL,NULL,0, status);
}
static double f_dens(double a,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status)
{
double z=1./a-1;
double pz=ccl_spline_eval(z,clt->spl_nz);
double bz=ccl_spline_eval(z,clt->spl_bz);
double h=cosmo->params.h*ccl_h_over_h0(cosmo,a,status)/CLIGHT_HMPC;
return pz*bz*h;
}
static double f_rsd(double a,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status)
{
double z=1./a-1;
double pz=ccl_spline_eval(z,clt->spl_nz);
double fg=ccl_growth_rate(cosmo,a,status);
double h=cosmo->params.h*ccl_h_over_h0(cosmo,a,status)/CLIGHT_HMPC;
return pz*fg*h;
}
static double f_mag(double a,double chi,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status)
{
double wM=ccl_spline_eval(chi,clt->spl_wM);
if(wM<=0)
return 0;
else
return wM/(a*chi);
}
//Transfer function for number counts
//l -> angular multipole
//k -> wavenumber modulus
//cosmo -> ccl_cosmology object
//w -> CCL_ClWorskpace object
//clt -> CCL_ClTracer object (must be of the ccl_number_counts_tracer type)
static double transfer_nc(int l,double k,
ccl_cosmology *cosmo,CCL_ClWorkspace *w,CCL_ClTracer *clt, int * status)
{
double ret=0;
double x0=(l+0.5);
double chi0=x0/k;
if(chi0<=clt->chimax) {
double a0=ccl_scale_factor_of_chi(cosmo,chi0,status);
double f_all=f_dens(a0,cosmo,clt,status);
if(clt->has_rsd) {
double x1=(l+1.5);
double chi1=x1/k;
if(chi1<=clt->chimax) {
double a1=ccl_scale_factor_of_chi(cosmo,chi1,status);
double pk0=ccl_nonlin_matter_power(cosmo,k,a0,status);
double pk1=ccl_nonlin_matter_power(cosmo,k,a1,status);
double fg0=f_rsd(a0,cosmo,clt,status);
double fg1=f_rsd(a1,cosmo,clt,status);
f_all+=fg0*(1.-l*(l-1.)/(x0*x0))-fg1*2.*sqrt((l+0.5)*pk1/((l+1.5)*pk0))/x1;
}
}
if(clt->has_magnification)
f_all+=-2*clt->prefac_lensing*l*(l+1)*f_mag(a0,chi0,cosmo,clt,status)/(k*k);
ret=f_all;
}
return ret;
}
static double f_lensing(double a,double chi,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status)
{
double wL=ccl_spline_eval(chi,clt->spl_wL);
if(wL<=0)
return 0;
else
return clt->prefac_lensing*wL/(a*chi);
}
static double f_IA_NLA(double a,double chi,ccl_cosmology *cosmo,CCL_ClTracer *clt, int * status)
{
if(chi<=1E-10)
return 0;
else {
double a=ccl_scale_factor_of_chi(cosmo,chi, status);
double z=1./a-1;
double pz=ccl_spline_eval(z,clt->spl_nz);
double ba=ccl_spline_eval(z,clt->spl_ba);
double rf=ccl_spline_eval(z,clt->spl_rf);
double h=cosmo->params.h*ccl_h_over_h0(cosmo,a,status)/CLIGHT_HMPC;
return pz*ba*rf*h/(chi*chi);
}
}
//Transfer function for shear
//l -> angular multipole
//k -> wavenumber modulus
//cosmo -> ccl_cosmology object
//w -> CCL_ClWorskpace object
//clt -> CCL_ClTracer object (must be of the ccl_weak_lensing_tracer type)
static double transfer_wl(int l,double k,
ccl_cosmology *cosmo,CCL_ClWorkspace *w,CCL_ClTracer *clt, int * status)
{
double ret=0;
double chi=(l+0.5)/k;
if(chi<=clt->chimax) {
double a=ccl_scale_factor_of_chi(cosmo,chi,status);
double f_all=f_lensing(a,chi,cosmo,clt,status);
if(clt->has_intrinsic_alignment)
f_all+=f_IA_NLA(a,chi,cosmo,clt,status);
ret=f_all;
}
return sqrt((l+2.)*(l+1.)*l*(l-1.))*ret/(k*k);
//return (l+1.)*l*ret/(k*k);
}
static double transfer_cmblens(int l,double k,ccl_cosmology *cosmo,CCL_ClTracer *clt,int *status)
{
double chi=(l+0.5)/k;
if(chi>=clt->chi_source)
return 0;
if(chi<=clt->chimax) {
double a=ccl_scale_factor_of_chi(cosmo,chi,status);
double w=1-chi/clt->chi_source;
return clt->prefac_lensing*l*(l+1.)*w/(a*chi*k*k);
}
return 0;
}
//Wrapper for transfer function
//l -> angular multipole
//k -> wavenumber modulus
//cosmo -> ccl_cosmology object
//clt -> CCL_ClTracer object
static double transfer_wrap(int il,double lk,ccl_cosmology *cosmo,
CCL_ClWorkspace *w,CCL_ClTracer *clt, int * status)
{
double transfer_out=0;
double k=pow(10.,lk);
if(clt->tracer_type==ccl_number_counts_tracer)
transfer_out=transfer_nc(w->l_arr[il],k,cosmo,w,clt,status);
else if(clt->tracer_type==ccl_weak_lensing_tracer)
transfer_out=transfer_wl(w->l_arr[il],k,cosmo,w,clt,status);
else if(clt->tracer_type==ccl_cmb_lensing_tracer)
transfer_out=transfer_cmblens(w->l_arr[il],k,cosmo,clt,status);
else
transfer_out=-1;
return transfer_out;
}
//Params for power spectrum integrand
typedef struct {
int il;
ccl_cosmology *cosmo;
CCL_ClWorkspace *w;
CCL_ClTracer *clt1;
CCL_ClTracer *clt2;
int *status;
} IntClPar;
//Integrand for integral power spectrum
static double cl_integrand(double lk,void *params)
{
double d1,d2;
IntClPar *p=(IntClPar *)params;
d1=transfer_wrap(p->il,lk,p->cosmo,p->w,p->clt1,p->status);
if(d1==0)
return 0;
d2=transfer_wrap(p->il,lk,p->cosmo,p->w,p->clt2,p->status);
if(d2==0)
return 0;
double k=pow(10.,lk);
double chi=(p->w->l_arr[p->il]+0.5)/k;
double a=ccl_scale_factor_of_chi(p->cosmo,chi,p->status);
double pk=ccl_nonlin_matter_power(p->cosmo,k,a,p->status);
return k*pk*d1*d2;
}
//Figure out k intervals where the Limber kernel has support
//clt1 -> tracer #1
//clt2 -> tracer #2
//l -> angular multipole
//lkmin, lkmax -> log10 of the range of scales where the transfer functions have support
static void get_k_interval(ccl_cosmology *cosmo,CCL_ClWorkspace *w,
CCL_ClTracer *clt1,CCL_ClTracer *clt2,int l,
double *lkmin,double *lkmax)
{
double chimin,chimax;
int cut_low_1=0,cut_low_2=0;
//Define a minimum distance only if no lensing is needed
if((clt1->tracer_type==ccl_number_counts_tracer) && (clt1->has_magnification==0)) cut_low_1=1;
if((clt2->tracer_type==ccl_number_counts_tracer) && (clt2->has_magnification==0)) cut_low_2=1;
if(cut_low_1) {
if(cut_low_2) {
chimin=fmax(clt1->chimin,clt2->chimin);
chimax=fmin(clt1->chimax,clt2->chimax);
}
else {
chimin=clt1->chimin;
chimax=clt1->chimax;
}
}
else if(cut_low_2) {
chimin=clt2->chimin;
chimax=clt2->chimax;
}
else {
chimin=0.5*(l+0.5)/ccl_splines->K_MAX;
chimax=2*(l+0.5)/ccl_splines->K_MIN;
}
if(chimin<=0)
chimin=0.5*(l+0.5)/ccl_splines->K_MAX;
*lkmax=log10(fmin( ccl_splines->K_MAX ,2 *(l+0.5)/chimin));
*lkmin=log10(fmax( ccl_splines->K_MIN ,0.5*(l+0.5)/chimax));
}
//Compute angular power spectrum between two bins
//cosmo -> ccl_cosmology object
//il -> index in angular multipole array
//clt1 -> tracer #1
//clt2 -> tracer #2
static double ccl_angular_cl_native(ccl_cosmology *cosmo,CCL_ClWorkspace *cw,int il,
CCL_ClTracer *clt1,CCL_ClTracer *clt2,int * status)
{
int clastatus=0, gslstatus;
IntClPar ipar;
double result=0,eresult;
double lkmin,lkmax;
gsl_function F;
gsl_integration_workspace *w=gsl_integration_workspace_alloc(ccl_gsl->N_ITERATION);
ipar.il=il;
ipar.cosmo=cosmo;
ipar.w=cw;
ipar.clt1=clt1;
ipar.clt2=clt2;
ipar.status = &clastatus;
F.function=&cl_integrand;
F.params=&ipar;
get_k_interval(cosmo,cw,clt1,clt2,cw->l_arr[il],&lkmin,&lkmax);
// This computes the angular power spectra in the Limber approximation between two quantities a and b:
// C_ell^ab = 2/(2*ell+1) * Integral[ Delta^a_ell(k) Delta^b_ell(k) * P(k) , k_min < k < k_max ]
// Note that we use log10(k) as an integration variable, and the ell-dependent prefactor is included
// at the end of this function.
gslstatus=gsl_integration_qag(&F, lkmin, lkmax, 0,
ccl_gsl->INTEGRATION_LIMBER_EPSREL, ccl_gsl->N_ITERATION,
ccl_gsl->INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS,
w, &result, &eresult);
gsl_integration_workspace_free(w);
// Test if a round-off error occured in the evaluation of the integral
// If so, try another integration function, more robust but potentially slower
if(gslstatus == GSL_EROUND) {
ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: ccl_angular_cl_native(): Default GSL integration failure, attempting backup method.");
gsl_integration_cquad_workspace *w_cquad= gsl_integration_cquad_workspace_alloc (ccl_gsl->N_ITERATION);
size_t nevals=0;
gslstatus=gsl_integration_cquad(&F, lkmin, lkmax, 0,
ccl_gsl->INTEGRATION_LIMBER_EPSREL,
w_cquad, &result, &eresult, &nevals);
gsl_integration_cquad_workspace_free(w_cquad);
}
if(gslstatus!=GSL_SUCCESS || *ipar.status) {
ccl_raise_gsl_warning(gslstatus, "ccl_cls.c: ccl_angular_cl_native():");
// If an error status was already set, don't overwrite it.
if(*status == 0){
*status=CCL_ERROR_INTEG;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_angular_cl_native(): error integrating over k\n");
}
return -1;
}
ccl_check_status(cosmo,status);
return result*M_LN10/(cw->l_arr[il]+0.5);
}
void ccl_angular_cls(ccl_cosmology *cosmo,CCL_ClWorkspace *w,
CCL_ClTracer *clt1,CCL_ClTracer *clt2,
int nl_out,int *l_out,double *cl_out,int *status)
{
int ii,do_angpow;
double *l_nodes,*cl_nodes;
SplPar *spcl_nodes;
//First check if ell range is within workspace
for(ii=0;ii<nl_out;ii++) {
if(l_out[ii]>w->lmax) {
*status=CCL_ERROR_SPLINE_EV;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_angular_cls(); "
"requested l beyond range allowed by workspace\n");
return;
}
}
if(*status==0) {
//Allocate array for power spectrum at interpolation nodes
l_nodes=(double *)malloc(w->n_ls*sizeof(double));
if(l_nodes==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_angular_cls(); memory allocation\n");
}
}
if(*status==0) {
cl_nodes=(double *)malloc(w->n_ls*sizeof(double));
if(cl_nodes==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_angular_cls(); memory allocation\n");
}
}
if(*status==0) {
for(ii=0;ii<w->n_ls;ii++)
l_nodes[ii]=(double)(w->l_arr[ii]);
do_angpow=0;
//Now check if angpow is needed at all
if(w->l_limber>0) {
for(ii=0;ii<w->n_ls;ii++) {
if(w->l_arr[ii]<=w->l_limber)
do_angpow=1;
}
}
#ifndef HAVE_ANGPOW
do_angpow=0;
#endif //HAVE_ANGPOW
//Resort to Limber if we have lensing (this will hopefully only be temporary)
if(clt1->tracer_type==ccl_weak_lensing_tracer || clt2->tracer_type==ccl_weak_lensing_tracer ||
clt1->has_magnification || clt2->has_magnification) {
do_angpow=0;
}
//Use angpow if non-limber is needed
if(do_angpow)
ccl_angular_cls_angpow(cosmo,w,clt1,clt2,cl_nodes,status);
ccl_check_status(cosmo,status);
}
if(*status==0) {
//Compute limber nodes
for(ii=0;ii<w->n_ls;ii++) {
if((!do_angpow) || (w->l_arr[ii]>w->l_limber))
cl_nodes[ii]=ccl_angular_cl_native(cosmo,w,ii,clt1,clt2,status);
}
//Interpolate into ells requested by user
spcl_nodes=ccl_spline_init(w->n_ls,l_nodes,cl_nodes,0,0);
if(spcl_nodes==NULL) {
*status=CCL_ERROR_MEMORY;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: ccl_cl_angular_cls(); memory allocation\n");
}
}
if(*status==0) {
for(ii=0;ii<nl_out;ii++)
cl_out[ii]=ccl_spline_eval((double)(l_out[ii]),spcl_nodes);
}
//Cleanup
ccl_spline_free(spcl_nodes);
free(cl_nodes);
free(l_nodes);
}
static int check_clt_fa_inconsistency(CCL_ClTracer *clt,int func_code)
{
if(((func_code==ccl_trf_nz) && (clt->tracer_type==ccl_cmb_lensing_tracer)) || //lensing has no n(z)
(((func_code==ccl_trf_bz) || (func_code==ccl_trf_sz) || (func_code==ccl_trf_wM)) &&
(clt->tracer_type!=ccl_number_counts_tracer)) || //bias and magnification only for clustering
(((func_code==ccl_trf_rf) || (func_code==ccl_trf_ba) || (func_code==ccl_trf_wL)) &&
(clt->tracer_type!=ccl_weak_lensing_tracer))) //IAs only for weak lensing
return 1;
if((((func_code==ccl_trf_sz) || (func_code==ccl_trf_wM)) &&
(clt->has_magnification==0)) || //correct combination, but no magnification
(((func_code==ccl_trf_rf) || (func_code==ccl_trf_ba)) &&
(clt->has_intrinsic_alignment==0))) //Correct combination, but no IAs
return 1;
return 0;
}
double ccl_get_tracer_fa(ccl_cosmology *cosmo,CCL_ClTracer *clt,double a,int func_code,int *status)
{
SplPar *spl;
if(check_clt_fa_inconsistency(clt,func_code)) {
*status=CCL_ERROR_INCONSISTENT;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: inconsistent combination of tracer and internal function to be evaluated");
return -1;
}
switch(func_code) {
case ccl_trf_nz :
spl=clt->spl_nz;
break;
case ccl_trf_bz :
spl=clt->spl_bz;
break;
case ccl_trf_sz :
spl=clt->spl_sz;
break;
case ccl_trf_rf :
spl=clt->spl_rf;
break;
case ccl_trf_ba :
spl=clt->spl_ba;
break;
case ccl_trf_wL :
spl=clt->spl_wL;
break;
case ccl_trf_wM :
spl=clt->spl_wM;
break;
}
double x;
if((func_code==ccl_trf_wL) || (func_code==ccl_trf_wM))
x=ccl_comoving_radial_distance(cosmo,a,status); //x-variable is comoving distance for lensing kernels
else
x=1./a-1; //x-variable is redshift by default
return ccl_spline_eval(x,spl);
}
int ccl_get_tracer_fas(ccl_cosmology *cosmo,CCL_ClTracer *clt,int na,double *a,double *fa,
int func_code,int *status)
{
SplPar *spl;
if(check_clt_fa_inconsistency(clt,func_code)) {
*status=CCL_ERROR_INCONSISTENT;
ccl_cosmology_set_status_message(cosmo, "ccl_cls.c: inconsistent combination of tracer and internal function to be evaluated");
return -1;
}
switch(func_code) {
case ccl_trf_nz :
spl=clt->spl_nz;
break;
case ccl_trf_bz :
spl=clt->spl_bz;
break;
case ccl_trf_sz :
spl=clt->spl_sz;
break;
case ccl_trf_rf :
spl=clt->spl_rf;
break;
case ccl_trf_ba :
spl=clt->spl_ba;
break;
case ccl_trf_wL :
spl=clt->spl_wL;
break;
case ccl_trf_wM :
spl=clt->spl_wM;
break;
}
int compchi = (func_code==ccl_trf_wL) || (func_code==ccl_trf_wM);
int ia;
for(ia=0;ia<na;ia++) {
double x;
if(compchi) //x-variable is comoving distance for lensing kernels
x=ccl_comoving_radial_distance(cosmo,a[ia],status);
else //x-variable is redshift by default
x=1./a[ia]-1;
fa[ia]=ccl_spline_eval(x,spl);
}
return 0;
}
| {
"alphanum_fraction": 0.684490015,
"avg_line_length": 31.0552631579,
"ext": "c",
"hexsha": "150d658deb579139badcf9efc59c9de2e94a2b84",
"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": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "vrastil/CCL",
"max_forks_repo_path": "src/ccl_cls.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3",
"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": "vrastil/CCL",
"max_issues_repo_path": "src/ccl_cls.c",
"max_line_length": 169,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b3bd184b516212b51bdf7ceacab70b2b7afeffb3",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "vrastil/CCL",
"max_stars_repo_path": "src/ccl_cls.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 11787,
"size": 35403
} |
#define MAIN_FILE
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_spline.h>
#include "global.h"
#include "eos_pres.h"
#include "eos_rho.h"
#include "param.h"
int
main (void)
{
spline = NULL;
acc = NULL;
int i, status;
double r, r1, y[2];
// bounds for making grid of m(R) vs. rho(0)
const double rho_min = 1.0e+13, rho_max = 9.0e+14;
const int MAX = 100;
// pressure/density arrays from tabulated EOS data
int n_eos_pts;
FILE *fp = NULL;
double (*pres) (double, void *); // EOS pressure pointer
double (*rho) (double, void *); // EOS density pointer
double tmp;
// pointers to tabulated EOS data
double *eos_tab_pres = NULL, *eos_tab_dens = NULL;
/* this is the "third arm" of the EOS inversion routine. GSL calls
the function whose root is being found several times during
initialization and if we leave the pressure here uninitialized,
it might be 0 or something crazy, which will be out of bounds of
the "forward" EOS, and since the forward EOS uses interpolation,
an out-of-bounds value of pressure will make it crash. */
tmp_pres = 1.0e+25;
pres = &eos_pres;
rho = &eos_rho;
// fp = fopen("bck.eos", "r");
// fp = fopen("eosC", "r");
// fp = fopen("timmes.eos", "r");
fp = fopen ("../EOS/helmholtz.eos", "r");
if (fp == NULL)
{
fprintf (stderr, "Can't open file!\n");
exit (1);
}
// read in # of EOS data points
fscanf (fp, "%i", &n_eos_pts);
eos_tab_dens = (double *) malloc (n_eos_pts * sizeof (double));
eos_tab_pres = (double *) malloc (n_eos_pts * sizeof (double));
// read in density and pressure data
for (i = 0; i < n_eos_pts; i++)
{
fscanf (fp, "%le %le", &eos_tab_dens[i], &eos_tab_pres[i]);
}
fclose (fp);
// set up interpolation machinery for EOS
acc = gsl_interp_accel_alloc ();
spline = gsl_spline_alloc (gsl_interp_cspline, n_eos_pts);
gsl_spline_init (spline, eos_tab_dens, eos_tab_pres, n_eos_pts);
// now make grid
r = 1.0; // the integrator will go nuts if we start right at r=0
r1 = 1.0e+10; // some final 'radius' (much larger than actual radius)
printf ("%12s %12s %12s\n", "R", "M(r=R)", "rho(r=0)");
params.single_star = 1;
for (i = 0; i < MAX; i++)
{
// rho(0) evenly spaced in log
params.rho_init = log10 (rho_min) +
(double) i *((log10 (rho_max) - log10 (rho_min)) / (double) MAX);
params.rho_init = pow (10.0, params.rho_init);
y[1] = pres (params.rho_init, ¶ms);
y[0] = (4.0 / 3.0) * M_PI * pow (r, 3.0) * rho (y[1], ¶ms);
params.pinit = y[1];
// This function is useful if you want to plot, e.g., central
// pressure vs. total mass. You can also hang onto the run of
// pressure with radius, which can be interesting when compared to
// the Newtonian case.
status = make_grid (params, r, r1, y);
}
/*
params.single_star = 0;
printf("\nnow for a single star!\n");
printf("%12s %12s %12s %12s\n", "r", "M(r)", "P(r)", "rho(r)");
// print P and M vs r for Chandrasekhar-mass star
params.rho_init = 1.0e+13;
y[1] = pres(params.rho_init, ¶ms); // rho(0) (roughly) for maximum mass
y[0] = (4.0/3.0) * M_PI * pow(r, 3.0) * rho(y[1], ¶ms);
params.pinit = y[1];
status = make_grid(params, r, r1, y);
*/
gsl_spline_free (spline);
gsl_interp_accel_free (acc);
free (eos_tab_pres);
free (eos_tab_dens);
eos_tab_dens = NULL;
eos_tab_pres = NULL;
fp = NULL;
pres = NULL;
rho = NULL;
return 0;
}
| {
"alphanum_fraction": 0.6203418324,
"avg_line_length": 28.7822580645,
"ext": "c",
"hexsha": "e35615534acdcbf59eaac735dd3a399e1eec8c4c",
"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": "5288ad6972b47143e1ce57e282f516143f07b158",
"max_forks_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_forks_repo_name": "bcfriesen/TOV_solver",
"max_forks_repo_path": "src/main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_issues_repo_name": "bcfriesen/TOV_solver",
"max_issues_repo_path": "src/main.c",
"max_line_length": 77,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158",
"max_stars_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_stars_repo_name": "bcfriesen/TOV_solver",
"max_stars_repo_path": "src/main.c",
"max_stars_repo_stars_event_max_datetime": "2015-11-14T02:27:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-14T02:27:58.000Z",
"num_tokens": 1168,
"size": 3569
} |
/* Xrecon.h */
/*---------------------------------------------------------------------------*/
/* */
/* Xrecon.h: Global includes and defines */
/* */
/* Copyright (C) 2012 Paul Kinchesh */
/* 2012 Martyn Klassen */
/* 2012 Margaret Kritzer */
/* */
/* This file is part of Xrecon. */
/* */
/* Xrecon 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. */
/* */
/* Xrecon 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 Xrecon. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*---------------------------------------------------------------------------*/
/**/
/*--------------------------------------------------------*/
/*---- Wrap the header to prevent multiple inclusions ----*/
/*--------------------------------------------------------*/
#ifndef _H_Xrecon_H
#define _H_Xrecon_H
/*------------------------------------------------------------*/
/*---- If C++ compiler is used it needs to know this is C ----*/
/*------------------------------------------------------------*/
//#ifdef __cplusplus
//extern "C" {
//#endif
/*----------------------------------*/
/*---- Include standard headers ----*/
/*----------------------------------*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <stddef.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
/*-----------------------------*/
/*---- Include GSL Headers ----*/
/*-----------------------------*/
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_sf_bessel.h>
/*-----------------------------*/
/*---- Include fftw header ----*/
/*-----------------------------*/
#include <fftw3.h>
/*--------------------------------*/
/*---- Include complex header ----*/
/*--------------------------------*/
/* NB If you have a C compiler, such as gcc, that supports the recent C99 standard,
and you #include <complex.h> before <fftw3.h>, then fftw_complex is the native
double-precision complex type and you can manipulate it with ordinary arithmetic.
Otherwise, FFTW defines its own complex type, which is bit-compatible with the
C99 complex type. */
/* We will wait for C99 standard to become a bit more standard */
//#include <complex.h>
#ifdef DOTIFF
/*---------------------------------*/
/*---- Include tiff I/O header ----*/
/*---------------------------------*/
#include <tiffio.h>
#endif
/*------------------------------------------*/
/*---- Include Varian data file handler ----*/
/*------------------------------------------*/
#include "data.h"
/*-------------------------------------------*/
/*---- Make sure __FUNCTION__ is defined ----*/
/*-------------------------------------------*/
#ifndef __FUNCTION__
#define __FUNCTION__ __func__
#endif
/*------------------------------*/
/*---- Include bool headers ----*/
/*------------------------------*/
#ifdef _STDC_C99
#include <stdbool.h>
#else
#ifndef bool
#define bool int
#endif
#ifndef true
#define true 1
#endif
#ifndef false
#define false 0
#endif
#endif
/*----------------------------*/
/*---- Some basic defines ----*/
/*----------------------------*/
#define TRUE 1
#define FALSE 0
#define ACTIVE 1
#define NACTIVE 0
#define NACQ 2
/* image scaling */
#define FFT_SCALE 0.5e-6
/*-------------------------*/
/*---- Some data types ----*/
/*-------------------------*/
#define INT16 1 /* 16 bit integer */
#define INT32 2 /* 32 bit integer */
#define FLT32 3 /* 32 bit float */
#define DBL64 4 /* 64 bit double */
/*-------------------------*/
/*---- Some data modes ----*/
/*-------------------------*/
#define NONE 0 /* No data */
#define FID 1 /* Raw */
#define IMAGE 2 /* Image */
#define RE 3 /* Real */
#define IM 4 /* Imaginary */
#define MG 5 /* Magnitude */
#define PH 6 /* Phase */
#define CX 7 /* Complex */
#define STD 8 /* Standard */
#define READ 9 /* Read */
#define PHASE 10 /* Phase */
#define PHASE2 11 /* 2nd Phase */
#define REF 12 /* Reference */
#define REFREAD 13 /* Reference Read */
#define REFPHASE 14 /* Reference Phase */
#define REFPHASE2 15 /* Reference Phase 2 */
#define MK 16 /* Mask */
#define MKREAD 17 /* Mask Read */
#define MKPHASE 18 /* Mask Phase */
#define MKPHASE2 19 /* Mask Phase 2 */
#define RMK 20 /* Reverse Mask of magnitude */
#define MKROI 21 /* Mask ROI */
#define SM 22 /* Sensitivity map */
#define SMREAD 23 /* Sensitivity Map Read */
#define SMPHASE 24 /* Sensitivity Map Phase */
#define SMPHASE2 25 /* Sensitivity Map Phase 2 */
#define GF 26 /* Geometry Factor */
#define RS 27 /* Relative SNR */
#define EPIREF 28 /* EPI reference */
#define VJ 29 /* Defined by VnmrJ parameters */
#define SPATIAL 30 /* for csi */
#define SPECTRAL 31 /* for csi */
#define SPATSPECT 32 /* for csi */
#define PHASE3 33 /* for 3D CSI */
/*---------------------------------------------------------*/
/*---- Some data status bits (0-15) for each dimension ----*/
/*---------------------------------------------------------*/
#define DATA 0x1 /* 0 = no data, 1= data */
#define SHIFT 0x2 /* 0 = no shift, 1 = shift */
#define ZEROFILL 0x4 /* 0 = no zerofill, 1 = zerofill */
#define FFT 0x8 /* 0 = no FFT, 1 = FFT */
/* Bits 4-15 are currently unused */
/*-----------------------------*/
/*---- Some sequence modes ----*/
/*-----------------------------*/
/* For 1D */
#define IM1D 100
#define IM0DCSI 101 /* single voxel csi */
/* For 2D multislice 200 < seqmode < 300 */
#define IM2D 200
#define IM2DCC 201 /* seqcon = "*ccnn" */
#define IM2DCS 202 /* seqcon = "*csnn" */
#define IM2DSC 203 /* seqcon = "*scnn" */
#define IM2DSS 204 /* seqcon = "*ssnn" */
#define IM2DCCFSE 205 /* apptype = "im2Dfse", seqcon = "nccnn" */
#define IM2DCSFSE 206 /* apptype = "im2Dfse", seqcon = "ncsnn" */
#define IM2DSCFSE 207 /* apptype = "im2Dfse", seqcon = "nscnn" */
#define IM2DSSFSE 208 /* apptype = "im2Dfse", seqcon = "nssnn" */
#define IM2DEPI 209 /* apptype = "im2Depi" */
#define IM1DCSI 210 /* csi has one extra dimension */
#define IM2DCCLL 211 /* looklocker seqcon = "*ccnn" */
#define IM2DCSLL 212 /* looklocker seqcon = "*csnn" */
#define IM2DSCLL 213 /* looklocker seqcon = "*scnn" */
#define IM2DSSLL 214 /* looklocker seqcon = "*ssnn" */
/* For 3D 300 < seqmode < 400 */
#define IM3D 300
#define IM3DCC 301 /* seqcon = "**ccn" */
#define IM3DCS 302 /* seqcon = "**csn" */
#define IM3DSC 303 /* seqcon = "**scn" */
#define IM3DSS 304 /* seqcon = "**ssn" */
#define IM3DCFSE 305 /* apptype = "im3Dfse", seqcon = "ncccn" */
#define IM3DSFSE 306 /* apptype = "im3Dfse", seqcon = "nccsn" */
#define IM2DCSCSI 307 /* apptype = "im2DCSI", seqcon = "nncsn" */
#define IM2DSCCSI 308 /* apptype = "im2DCSI", seqcon = "nnscn" */
#define IM2DSSCSI 309 /* apptype = "im2DCSI", seqcon = "ncssn" */
#define IM2DCCCSI 310 /* apptype = "im2DCSI", seqcon = "nnccn" */
/* For 4D */
#define IM4D 400
#define IM3DCCCCSI 401 /* csi has one extra dimension */
#define IM3DCCSCSI 402
#define IM3DCSCCSI 403
#define IM3DCSSCSI 404
#define IM3DSCCCSI 405
#define IM3DSCSCSI 406
#define IM3DSSCCSI 407
#define IM3DSSSCSI 408
/* max dimensions */
#define MAXDIM 500
/*-------------------------*/
/*---- For TIF scaling ----*/
/*-------------------------*/
#define NSCALE 0 /* Don't scale data */
#define SCALE -1 /* Scale to maximum of data in each volume */
#define NOISE -2 /* Scale to see noise */
/*--------------------------------*/
/*---- For NIFTI-1/Analyze7.5 ----*/
/*--------------------------------*/
#define NIFTI 1 /* NIFTI-1 format */
#define ANALYZE 2 /* Analyze7.5 format */
/*---------------------------------------------------------------------------*/
/* Modes for DC correction using dbh.lvl and dbh.tlt in getvol(d,index,mode) */
/*---------------------------------------------------------------------------*/
#define NDCC 0 /* No DC correction using dbh.lvl and dbh.tlt */
#define DCC 1 /* DC correction using dbh.lvl and dbh.tlt */
/*-----------------------------------------------------------------------------------------*/
/* Modes for writing raw data in wrawbin3D(struct data *d,int mode,int type,int precision) */
/*-----------------------------------------------------------------------------------------*/
#define D1 1 /* 1D data mode, data[nr][dim3][dim1] */
#define D12 2 /* 2D/3D data mode, data[nr][dim3][dim2*dim1] */
#define D3 3 /* 3D block processing mode, data[nr][dim2*dim1][dim3] */
/*-------------------*/
/*---- Constants ----*/
/*-------------------*/
#ifndef M_PI
#define M_PI 3.14159265358979323846 /* pi */
#endif
#define DEG2RAD 0.017453292 /* convert degrees to radians */
#define MAXRCVRS 2048 /* maximum number of receivers */
/*------------------------------------------------------*/
/*---- Floating point comparison macros (as in SGL) ----*/
/*------------------------------------------------------*/
/* EPSILON is the largest allowable deviation due to floating point storage */
#define EPSILON 1e-9
#define FP_LT(A,B) (((A)<(B)) && (fabs((A)-(B))>EPSILON)) /* A less than B */
#define FP_GT(A,B) (((A)>(B)) && (fabs((A)-(B))>EPSILON)) /* A greater than B */
#define FP_EQ(A,B) (fabs((A)-(B))<=EPSILON) /* A equal to B */
#define FP_NEQ(A,B) (!FP_EQ(A,B)) /* A not equal to B */
#define FP_GTE(A,B) (FP_GT(A,B) || FP_EQ(A,B)) /* A greater than or equal to B */
#define FP_LTE(A,B) (FP_LT(A,B) || FP_EQ(A,B)) /* A less than or equal to B */
/*-------------------------------------------------------*/
/*---- So we can simply include Xrecon.h in Xrecon.c ----*/
/*-------------------------------------------------------*/
#ifdef LOCAL
#define EXTERN
#else
#define EXTERN extern
#endif
int interupt; // for killing the process
/*-------------------------------------------*/
/*---- Structure to hold input filenames ----*/
/*-------------------------------------------*/
struct file
{
int nfiles; /* number of files */
char **fid; /* fid files */
char **procpar; /* procpar files */
};
/*------------------------------------------------*/
/*---- Structure to hold 'procpar' parameters ----*/
/*------------------------------------------------*/
struct pars
{
int npars; /* number of parameters in structure */
char **name; /* parameter name */
int *type; /* parameter type */
int *active; /* parameter state */
int *nvals; /* number of values of parameters */
int **i; /* integer values */
double **d; /* real values */
char ***s; /* strings */
};
/*---------------------------------------------------------*/
/*---- Structure to hold maximum value and coordinates ----*/
/*---------------------------------------------------------*/
struct max
{
int data; /* Data flag 0/FALSE=no data, or 1/TRUE=data */
double Mval; /* Maximum magnitude value */
double Rval; /* Maximum real value */
double Ival; /* Maximum imaginary value */
int np; /* position of maximum along np */
int nv; /* position of maximum along nv */
int nv2; /* position of maximum along nv2 */
int nv3; /* position of maximum along nv3 */
};
/*----------------------------------------------*/
/*---- Structure to hold noise measurements ----*/
/*----------------------------------------------*/
struct noise
{
int data; /* Data flag 0/FALSE=no data, or 1/TRUE=data */
int zero; /* Zero data flag 0/FALSE=noise data not zero, or 1/TRUE=noise data is zero */
int equal; /* Equalize flag 0/FALSE=not equal, or 1/TRUE=equal */
int samples; /* Number of noise samples */
double *M; /* Mean magnitude */
double *M2; /* Mean magnitude^2 */
double *Re; /* Mean real */
double *Im; /* Mean imaginary */
double avM; /* Averaged over all receivers */
double avM2; /* Averaged over all receivers */
double avRe; /* Averaged over all receivers */
double avIm; /* Averaged over all receivers */
gsl_matrix_complex **mat; /* Noise matrix */
};
/*--------------------------------*/
/*---- Structure to hold data ----*/
/*--------------------------------*/
struct data
{
FILE *fp; /* fid file pointer */
FILE *datafp; /* data file pointer */
FILE *phasfp; /* phasefile file pointer */
FILE *fidfp; /* for writing in fid format */
char *file; /* fid file */
char *procpar; /* procpar file */
struct datafilehead fh; /* data file header */
struct datablockhead bh; /* data block header */
struct hypercmplxbhead hcbh; /* hypercomplex block header */
struct stat buf; /* data file info */
int nvols; /* number of volumes at end of expt */
int startvol; /* start volume for processing */
int endvol; /* end volume for processing */
int vol; /* current volume counter */
int outvol; /* output volume (not counting reference volumes) */
int nblocks; /* number of blocks */
int startpos; /* start position of block for processing */
int endpos; /* end position of block for processing */
int block; /* current block counter */
int np,nv,nv2,nv3; /* number of points and views including nv3 for CSI */
int nseg,etl; /* number of segments and echo train length */
int ne; /* number of echoes */
int fn,fn1,fn2,fn3; /* zerofilling */
int nr,ns; /* number of receivers and slices */
int korder; /* for csi, indicates elliptical or otherwise acquired */
int synclist[3]; /* indicates which dimensions are part of sync'ed lists such as pelist, pe2list, etc. */
int startd1, startd2, startd3; // for csi cropping
int cropd1, cropd2, cropd3; // for csi cropping
int profile; /* profile flag, 0/FALSE=not profile, 1/TRUE=profile */
int proj2D; /* 2D projection flag, 0/FALSE=not 2D projection, 1/TRUE=2D projection */
int nav; /* navigator flag, 0/FALSE=none, 1/TRUE=navigators */
int nnav; /* number of navigators */
int *navpos; /* position(s) of navigator data amongst actual data */
int seqmode; /* sequence mode depends on seqcon and apptype */
int *dim2order; /* dim2 order in fid file */
int *dim3order; /* dim3 order in fid file */
int *dim4order; /* dim4 order in fid file */
int *pssorder; /* slice order in fid file */
int *dim2orderR; /* Table for reduced dim2 order */
int *dim3orderR; /* Table for reduced dim3 order */
int *dim4orderR; /* Table for reduced dim4 order */
int dim2R,dim3R, dim4R; /* Size of dim2 and dim3 and dim4 BEFORE reduction */
int d1rev, d2rev, d3rev; /* flag for csi dimension reversal */
fftw_complex ***data; /* actual data */
fftw_complex **csi_data; /* different organization */
int **mask; /* data mask */
int ndim; /* number of data dimensions */
int *dimstatus; /* status of each dimension */
int datamode; /* data mode to flag different types of data, eg. see default EPI recon */
struct max max; /* maximum value and coordinates */
struct noise noise; /* noise measurement data */
struct pars p; /* 'procpar' parameters */
struct pars a; /* 'array' parameters */
struct pars s; /* 'sviblist' parameters */
char *fdfhdr; /* fdf header */
};
/*-------------------------------------*/
/*---- Structure to hold dimstatus ----*/
/*-------------------------------------*/
struct dimstatus
{
int ndim; /* number of data dimensions */
int *dimstatus; /* status of each dimension */
};
/*-------------------------------------------------*/
/*---- Structure to hold segment scaling (EPI) ----*/
/*-------------------------------------------------*/
struct segscale
{
int data;
double ***value;
};
/*------------------------------*/
/*---- Main recon functions ----*/
/*------------------------------*/
void recon1D(struct data *d); /* recon1D.c */
void recon2D(struct data *d); /* recon2D.c */
void reconEPI(struct data *d); /* reconEPI.c */
void recon3D(struct data *d); /* recon3D.c */
void recon2DCSI(struct data *d);
/*---------------------------------*/
/*---- Default recon functions ----*/
/*---------------------------------*/
void default1D(struct data *d); /* default1D.c */
void default2D(struct data *d); /* default2D.c */
void defaultEPI(struct data *d); /* defaultEPI.c */
void default3D(struct data *d); /* default3D.c */
/*-------------------------------*/
/*---- default1D.c functions ----*/
/*-------------------------------*/
void refcorr1D(struct data *d,struct data *ref);
void combine1D(struct data *d);
/*-------------------------------*/
/*---- profile1D.c functions ----*/
/*-------------------------------*/
void profile1D(struct data *d);
/*----------------------------*/
/*---- proj2D.c functions ----*/
/*----------------------------*/
void proj2D(struct data *d);
/*------------------------*/
/*---- CSI functions ----*/
/*------------------------*/
void reconCSI(struct data *d);
void reconCSI2D(struct data *d);
void reconCSI3D(struct data *d);
void dimorderCSI2D(struct data *d);
void dimorderCSI3D(struct data *d);
void getblockCSI2D(struct data *d,int volindex,int DCCflag);
void getblockCSI3D(struct data *d,int volindex,int DCCflag);
void w2DCSI(struct data *d,int receiver,int d4, int d3, int d2,int fileid);
void wdfhCSI(struct data *d,int fileid);
void zerofill2DCSI(struct data *d, int mode);
void phaseramp2DCSI(struct data *d, int d4index, int mode);
void shiftdim3dataCSI(struct data *d,int shft);
void phaserampdim3CSI(struct data *d, int mode);
void regridEPSI(struct data *d);
/*----------------------------*/
/*---- mask2D.c functions ----*/
/*----------------------------*/
void mask2D(struct data *d);
void add2mask2D(struct data *d);
int read2Dmask(struct data *d,int mode);
void mask2Ddata(struct data *d1,struct data *d2);
/*-----------------------------*/
/*---- sense2D.c functions ----*/
/*-----------------------------*/
void sense2D(struct data *d);
void sense2Dunfold(struct data *d,struct data *ref);
void svd2Dinmem(struct data *ref);
void setref2Dmatrix(struct data *ref,struct data *d);
int checksenseref(struct data *d,struct data *ref);
/*-----------------------------*/
/*---- sensi2D.c functions ----*/
/*-----------------------------*/
void sensibility2D(struct data *d);
void gmap2D(struct data *d);
/*----------------------------*/
/*---- smap2D.c functions ----*/
/*----------------------------*/
void smap2D(struct data *d,int mode);
int smap2Dvcoil(struct data *d,struct data *ref,int mode);
int smap2Dacoil(struct data *d,int mode);
int setvcoil2D(struct data *d,struct data *ref,struct file *fref);
void gen2Dsmapsos(struct data *d);
void gen2Dsmapsuper(struct data *d);
void gen2Dsmapvcoil(struct data *d,struct data *ref);
/*-------------------------------*/
/*---- asltest2D.c functions ----*/
/*-------------------------------*/
void asltest2D(struct data *d);
/*-----------------------------------*/
/*---- multiblock3D.c functions ----*/
/*-----------------------------------*/
void multiblock3D(struct data *d);
/*------------------------------*/
/*---- dprocEPI.c functions ----*/
/*------------------------------*/
void addscaledEPIref(struct data *d,struct data *ref1,struct data *ref2);
void addEPIref(struct data *d,struct data *ref);
void ftnvEPI(struct data *d);
void nvfillEPI(struct data *d);
void ftnpEPI(struct data *d);
void zoomEPI(struct data *d);
void revreadEPI(struct data *d);
void prepEPIref(struct data *ref1,struct data *ref2);
void phaseEPIref(struct data *ref1,struct data *ref2,struct data *ref3);
void phaseEPI(struct data *d,struct data *ref);
void phaserampEPI(struct data *d,int mode);
void navcorrEPI(struct data *d);
void stripEPInav(struct data *d);
void weightnavs(struct data *d,double gf);
void setsegscale(struct data *d,struct segscale *scale);
void segscale(struct data *d,struct segscale *scale);
void analyseEPInav(struct data *d);
void getblockEPI(struct data *d,int volindex,int DCCflag);
void setblockEPI(struct data *d);
void setoutvolEPI(struct data *d);
int outvolEPI(struct data *d);
void setnvolsEPI(struct data *d);
void setblockSGE(struct data *d);
/*---------------------------------*/
/*---- prescanEPI.c functions -----*/
/*---------------------------------*/
void prescanEPI(struct data *d);
void settep(struct data *d, int mode);
/*---------------------------*/
/*---- dproc.c functions ----*/
/*---------------------------*/
int *sliceorder(struct data *d,int dim,char *par);
int *phaseorder(struct data *d,int views,int dim,char *par);
int *phaselist(struct data *d,char *par);
void getmax(struct data *d);
void getnoise(struct data *d,int mode);
void equalizenoise(struct data *d,int mode);
void dccorrect(struct data *d);
void scaledata(struct data *d,double factor);
void combine_channels(struct data *d);
void opti_comb(struct data *d, int offset);
double *unwrap1D(double *angles, int nangles);
/*-----------------------------*/
/*---- dproc1D.c functions ----*/
/*-----------------------------*/
void fft1D(struct data *d,int dataorder);
void shiftdata1D(struct data *d,int mode,int dataorder);
void shift1Ddata(struct data *d,int shft,int dataorder);
void weightdata1D(struct data *d,int mode,int dataorder);
void zerofill1D(struct data *d,int mode,int dataorder);
void phaseramp1D(struct data *d,int mode);
void phasedata1D(struct data *d,int mode,int dataorder);
void getmaxtrace1D(struct data *d,int trace);
/*-----------------------------*/
/*---- dproc2D.c functions ----*/
/*-----------------------------*/
void dimorder2D(struct data *d);
void fft2D(struct data *d,int mode);
void ifft2D(struct data *d,int mode);
void shiftdata2D(struct data *d,int mode);
void shift2Ddata(struct data *d,int npshft,int nvshft);
void shift2DCSIdata(struct data *d,int nvshft,int nv2shft);
void weightdata2D(struct data *d,int mode);
void zerofill2D(struct data *d,int mode);
void phaseramp2D(struct data *d,int mode);
void phasedata2D(struct data *d,int mode);
void zoomdata2D(struct data *d,int startdim1, int widthdim1, int startdim2, int widthdim2);
void revread(struct data *d);
void navcorr(struct data *d,struct data *nav);
/*-----------------------------*/
/*---- dproc3D.c functions ----*/
/*-----------------------------*/
void dimorder3D(struct data *d);
void getblock3D(struct data *d,int volindex,int DCCflag);
void getnavblock3D(struct data *d,int volindex,int DCCflag);
void shiftdatadim3(struct data *d,int dataorder,int mode);
void shiftdim3data(struct data *d,int dim3shft);
void shiftD3data(struct data *d,int dim3shft);
void weightdatadim3(struct data *d,int mode);
void zerofilldim3(struct data *d,int mode);
void fftdim3(struct data *d);
void phaserampdim3(struct data *d,int mode);
void phasedatadim3(struct data *d,int mode);
/*-----------------------------*/
/*---- noise2D.c functions ----*/
/*-----------------------------*/
void get2Dnoisematrix(struct data *d,int mode);
void zero2Dnoisematrix(struct data *d);
void print2Dnoisematrix(struct data *d);
/*-----------------------------*/
/*---- dmask2D.c functions ----*/
/*-----------------------------*/
void get2Dmask(struct data *d,int mode);
void fill2Dmask(struct data *d,int mode);
/*---------------------------*/
/*---- dread.c functions ----*/
/*---------------------------*/
void setblock(struct data *d,int dim);
void getblock(struct data *d,int volindex,int DCCflag);
int readfblock(struct data *d,int volindex,int DCCflag);
int readlblock(struct data *d,int volindex,int DCCflag);
int readsblock(struct data *d,int volindex,int DCCflag);
int setoffset(struct data *d,int volindex,int receiver,int dim3index,int dim2index);
void getnavblock(struct data *d,int volindex,int DCCflag);
int readnavfblock(struct data *d,int volindex,int DCCflag);
int readnavlblock(struct data *d,int volindex,int DCCflag);
int readnavsblock(struct data *d,int volindex,int DCCflag);
int setnavoffset(struct data *d,int volindex,int receiver,int dim3index,int seg,int nav);
int sliceindex(struct data *d,int slice);
int segindex(struct data *d,int phase);
int phaseindex(struct data *d,int phase);
int phase2index(struct data *d,int phase2);
int phase3index(struct data *d,int phase3);
void synctablesort2D(struct data *d, int d2, int d3, int *p2, int *p3);
int synctablesort3D(struct data *d, int d2, int d3, int d4, int *p2, int *p3, int *p4);
/*-----------------------------*/
/*---- dread1D.c functions ----*/
/*-----------------------------*/
void getblock1D(struct data *d,int volindex,int DCCflag);
/*-----------------------------*/
/*---- dread2D.c functions ----*/
/*-----------------------------*/
void getblock2D(struct data *d,int volindex,int DCCflag);
void getnavblock2D(struct data *d,int volindex,int DCCflag);
int process2Dblock(struct data *d,char *startpar,char *endpar);
/*---------------------------*/
/*---- dhead.c functions ----*/
/*---------------------------*/
void getdfh(struct data *d);
void getdbh(struct data *d,int blockindex);
void gethcbh(struct data *d,int blockindex);
void reversedfh(struct datafilehead *dfh);
void reversedbh(struct datablockhead *dbh);
void reversehcbh(struct hypercmplxbhead *hcbh);
void printfileheader(struct datafilehead *dfh);
void printfilestatus(struct datafilehead *dfh);
void printblockheader(struct datablockhead *dbh,int blockindex);
void printhcblockheader(struct hypercmplxbhead *hcbh,int blockindex);
/*----------------------------*/
/*---- dutils.c functions ----*/
/*----------------------------*/
void opendata(char *datafile,struct data *d);
void setnvols(struct data *d);
void setstartendvol(struct data *d);
void setdatapars(struct data *d);
void setseqmode(struct data *d);
void setdim(struct data *d);
int spar(struct data *d,char *par,char *str);
int im1D(struct data *d);
int im2D(struct data *d);
int im2DLL(struct data *d);
int im3D(struct data *d);
int im4D(struct data *d);
int imCSI(struct data *d);
double getelem(struct data *d,char *par,int image);
int wprocpar(struct data *d,char *filename);
void copydbh(struct datablockhead *dbh1,struct datablockhead *dbh2);
void setfile(struct file *datafile,char *datadir);
void setreffile(struct file *datafile,struct data *d,char *refpar);
void setfn(struct data *d1,struct data *d2,double multiplier);
void setfn1(struct data *d1,struct data *d2,double multiplier);
void setdimstatus(struct data *d,struct dimstatus *status,int block);
void copynblocks(struct data *d1,struct data *d2);
void copymaskpars(struct data *d1,struct data *d2);
void copysmappars(struct data *d1,struct data *d2);
void copysensepars(struct data *d1,struct data *d2);
int checkequal(struct data *d1,struct data *d2,char *par,char *comment);
void initdatafrom(struct data *d1, struct data *d2);
void initdata(struct data *d);
void nulldata(struct data *d);
void cleardimorder(struct data *d);
void clearstatus(struct data *d);
void zeromax(struct data *d);
void zeronoise(struct data *d);
void initnoise(struct data *d);
void nullnoise(struct data *d);
void closedata(struct data *d);
/*------------------------------*/
/*---- dutils1D.c functions ----*/
/*------------------------------*/
void clear1Dall(struct data *d);
void clear1Ddata(struct data *d);
void clearnoise1D(struct data *d);
void clear1Dmask(struct data *d);
/*------------------------------*/
/*---- dutils2D.c functions ----*/
/*------------------------------*/
int check2Dref(struct data *d,struct data *ref);
void copy2Ddata(struct data *d1,struct data *d2);
void clear2Dall(struct data *d);
void clear2Ddata(struct data *d);
void clearCSIdata(struct data *d);
void clearnoise2D(struct data *d);
void clear2Dmask(struct data *d);
void checkCrop(struct data *d);
void checkCrop3D(struct data *d);
/*------------------------------------*/
/*---- pars.c 'procpar' functions ----*/
/*------------------------------------*/
void getpars(char *procpar,struct data *d);
void getprocparpars(char *procpar,struct pars *p);
void skipprocparvals(FILE *fp,struct pars *p,int type,int nvals);
void procparerror(const char *function,char *par,char *str);
void setarray(struct pars *p,struct pars *a);
int list2array(char *par,struct pars *p1,struct pars *p2);
void setval(struct pars *p,char *par,double value);
void setsval(struct pars *p,char *par,char *svalue);
void cppar(char *par1,struct pars *p1,char *par2,struct pars *p2);
void copypar(char *par,struct pars *p1,struct pars *p2);
void copypars(struct pars *p1, struct pars *p2);
void copyvalues(struct pars *p1,int ix1,struct pars *p2,int ix2);
void mallocnpars(struct pars *p);
void freenpars(struct pars *p);
void printarray(struct pars *a,char *array);
void printprocpar(struct pars *p);
int ptype(char *par,struct pars *p);
int nvals(char *par,struct pars *p);
int *ival(char *par,struct pars *p);
double *val(char *par,struct pars *p);
char **sval(char *par,struct pars *p);
int parindex(char *par,struct pars *p);
int arraycheck(char *par,struct pars *a);
int getcycle(char *par,struct pars *a);
int cyclefaster(char *par1,char *par2,struct pars *a);
void clearpars(struct pars *p);
void cleararray(struct pars *a);
void nullpars(struct pars *p);
/*-------------------------------------*/
/*---- utils.c utilities functions ----*/
/*-------------------------------------*/
int check_CPU_type();
void complexmatrixmultiply(gsl_matrix_complex *A,gsl_matrix_complex *B,gsl_matrix_complex *C);
void complexmatrixconjugate(gsl_matrix_complex *A);
int round2int(double dval);
void reverse2ByteOrder(int nele,char *ptr);
void reverse4ByteOrder(int nele,char *ptr);
void reverse8ByteOrder(int nele,char *ptr);
int doublecmp(const void *double1,const void *double2);
int nomem(char *file,const char *function,int line);
int createdir(char *dirname);
int checkdir(char *dirname);
int checkfile(char *filename);
/*-----------------------------*/
/*---- write1D.c functions ----*/
/*-----------------------------*/
void w1Dtrace(struct data *d,int receiver,int trace,int fileid);
void w1Dblock(struct data *d,int receiver,int fileid);
void wdfh(struct data *d,int fileid);
void wdbh(struct data *d,int fileid);
void openfpw(struct data *d,int fileid);
void closefp(struct data *d,int fileid);
/*--------------------------------*/
/*---- fdfwrite2D.c functions ----*/
/*--------------------------------*/
void w2Dfdfs(struct data *d,int type,int scalevalue,int volindex);
int magnitude2Dfdfs(struct data *d,char *par,char *parIR,char *outdir,int type,int precision,int volindex);
void other2Dfdfs(struct data *d,char *par,char *outdir,int type,int precision,int volindex);
void gen2Dfdfs(struct data *d,int mode,char *outdir,int type,int precision,int volindex);
void w2Dfdf(char *filename,struct data *d,int image,int slice,int sliceindex,int echo,int receiver,int type,int precision);
void wcomb2Dfdf(char *filename,struct data *d,int image,int slice,int sliceindex,int echo,int type,int precision);
void gen2Dfdfhdr(struct data *d,int image,int slice,int echo,int receiver,int type,int precision);
int validtype(int type);
int addpar2hdr(struct pars *p,int ix);
double sliceposition(struct data *d,int slice);
/*--------------------------------*/
/*---- fdfwrite3D.c functions ----*/
/*--------------------------------*/
void w3Dfdfs(struct data *d,int type,int scalevalue,int volindex);
int magnitude3Dfdfs(struct data *d,char *par,char *parIR,char *outdir,int type,int precision,int volindex);
void other3Dfdfs(struct data *d,char *par,char *outdir,int type,int precision,int volindex);
void gen3Dfdfs(struct data *d,int mode,char *outdir,int type,int precision,int volindex);
void w3Dfdf(char *filename,struct data *d,int image,int slab,int echo,int receiver,int type,int precision);
void wcomb3Dfdf(char *filename,struct data *d,int image,int slab,int echo,int type,int precision);
void gen3Dfdfhdr(struct data *d,int image,int slice,int echo,int receiver,int type,int precision);
/*-----------------------------*/
/*---- rawIO3D.c functions ----*/
/*-----------------------------*/
void wrawbin3D(struct data *d,int dataorder,int type,int precision);
void gen3Draw(struct data *d,int output,char *outdir,int dataorder,int type,int precision);
void w3Draw(char *filename,struct data *d,int receiver,int type,int precision);
void w3DrawD3(char *filename,struct data *d,int receiver);
void wcomb3Draw(char *filename,struct data *d,int type,int precision);
void cleardim3data(struct data *d);
void rrawbin3D(struct data *d,int dataorder,int type,int precision);
void get3Draw(struct data *d,int mode,char *indir,int dataorder);
void r3Draw(char *filename,struct data *d,int receiver);
void r3DrawD3(char *filename,struct data *d,int receiver);
void delrawbin3D(struct data *d,int dataorder,int type);
void del3Draw(struct data *d,char *dir);
/*--------------------------------*/
/*---- niftiwrite.c functions ----*/
/*--------------------------------*/
void wnifti(struct data *d,int type,int precision,int volindex);
void writenifti(struct data *d,int type,int precision,int format,int volindex);
int magnifti(struct data *d,char *par,char *parIR,char *outdir,int type,int precision,int format,int volindex);
void othernifti(struct data *d,char *par,char *outdir,int type,int precision,int format,int volindex);
void gennifti(struct data *d,int mode,char *outdir,int type,int precision,int format,int volindex);
void wniftihdr(char *filebase,struct data *d,int precision,int format,int image);
void wniftidata(char *filebase,struct data *d,int receiver,int type,int precision,int format,int newfile);
void wcombniftidata(char *filebase,struct data *d,int type,int precision,int format,int newfile);
/*--------------------------------*/
/*---- tifwrite2D.c functions ----*/
/*--------------------------------*/
int wtifs2D(struct data *d,int type,int scalevalue,int volindex);
int wtif2D(char *filename,struct data *d,int receiver,int slice,int type,double scale);
/*--------------------------------*/
/*---- rawwrite2D.c functions ----*/
/*--------------------------------*/
int wrawbin2D(struct data *d,int type,int precision,int volindex);
int wraw2D(char *filename,struct data *d,int receiver,int slice,int type,int precision);
/*-----------------------------*/
/*---- options.c functions ----*/
/*-----------------------------*/
void getoptions(struct file *f,int argc,char *argv[]);
/*---------------------------*/
/*---- For byte swapping ----*/
/*---------------------------*/
EXTERN int reverse_byte_order;
/*-------------------------*/
/*---- For VnmrJ recon ----*/
/*-------------------------*/
EXTERN int vnmrj_recon;
EXTERN char vnmrj_path[MAXPATHLEN];
/*-------------------------------------------------------------*/
/*---- If C++ compiler is used it needs to know above is C ----*/
/*-------------------------------------------------------------*/
//#ifdef __cplusplus
//}
//#endif
/*----------------------------*/
/*---- End of header wrap ----*/
/*----------------------------*/
#endif
| {
"alphanum_fraction": 0.5423989397,
"avg_line_length": 38.8117283951,
"ext": "h",
"hexsha": "ad1dded940eb9186d1fbdb0977200cad38f4721f",
"lang": "C",
"max_forks_count": 102,
"max_forks_repo_forks_event_max_datetime": "2022-03-20T05:41:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-01-23T15:27:16.000Z",
"max_forks_repo_head_hexsha": "0db324603dbd8f618a6a9526b9477a999c5a4cc3",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "DanIverson/OpenVnmrJ",
"max_forks_repo_path": "src/xrecon/Xrecon.h",
"max_issues_count": 128,
"max_issues_repo_head_hexsha": "0db324603dbd8f618a6a9526b9477a999c5a4cc3",
"max_issues_repo_issues_event_max_datetime": "2022-03-28T17:53:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-07-13T17:09:02.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "DanIverson/OpenVnmrJ",
"max_issues_repo_path": "src/xrecon/Xrecon.h",
"max_line_length": 128,
"max_stars_count": 32,
"max_stars_repo_head_hexsha": "0db324603dbd8f618a6a9526b9477a999c5a4cc3",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "DanIverson/OpenVnmrJ",
"max_stars_repo_path": "src/xrecon/Xrecon.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-28T17:54:44.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-06-17T05:04:26.000Z",
"num_tokens": 9166,
"size": 37725
} |
#pragma once
#include <utility>
#include <array>
#include <vector>
#include <unordered_map>
#include <DirectXMathExtend.h>
#include <gsl.h>
#include <VertexTraits.h>
#include <minmax>
namespace Geometrics
{
template <typename IndexType>
struct Triangle
{
static constexpr size_t VertexCount = 3;
typedef std::array<IndexType, VertexCount> container_type;
container_type v;
typedef IndexType value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef IndexType *pointer;
typedef const IndexType *const_pointer;
typedef IndexType& reference;
typedef const IndexType& const_reference;
typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator;
typedef typename container_type::reverse_iterator reverse_iterator;
typedef typename container_type::const_reverse_iterator const_reverse_iterator;
Triangle() {}
Triangle(const IndexType &v0, const IndexType &v1, const IndexType &v2)
{
v[0] = v0; v[1] = v1; v[2] = v2;
}
Triangle(const IndexType *v_)
{
v[0] = v_[0]; v[1] = v_[1]; v[2] = v_[2];
}
template <class S> explicit Triangle(const S &x)
{
v[0] = x[0]; v[1] = x[1]; v[2] = x[2];
}
IndexType &operator[] (int i) { return v[i]; }
const IndexType &operator[] (int i) const { return v[i]; }
operator const IndexType * () const { return &(v[0]); }
operator IndexType * () { return &(v[0]); }
void rewind() {
std::swap(v[0], v[2]);
}
int indexof(IndexType v_) const
{
return (v[0] == v_) ? 0 :
(v[1] == v_) ? 1 :
(v[2] == v_) ? 2 : -1;
}
// contrainer access
auto begin() { return v.begin(); }
auto end() { return v.end(); }
auto begin() const { return v.begin(); }
auto end() const { return v.end(); }
auto rbegin() { return v.rbegin(); }
auto rend() { return v.rend(); }
auto rbegin() const { return v.rbegin(); }
auto rend() const { return v.rend(); }
size_t size() const { return VertexCount; }
};
// generate per vertex normal for given triangle mesh
template <typename VertexType, typename IndexType>
bool generate_normal(gsl::span<VertexType> vertices, gsl::span<const Triangle<IndexType>> facets)
{
using namespace DirectX::VertexTraits;
using namespace DirectX;
if (!has_normal<VertexType>::value)
return false;
//static_assert(has_normal<VertexType>::value, "The vertex type dose not contains normal field");
std::vector<XMVECTOR, XMAllocator> normals(vertices.size());
// set zero
std::memset(normals.data(), 0, normals.size() * sizeof(XMVECTOR));
XMVECTOR v0, v1, v2, n;
for (const auto& face : facets)
{
v0 = get_position(vertices[face[0]]);
v1 = get_position(vertices[face[1]]);
v2 = get_position(vertices[face[2]]);
v1 -= v0;
v2 -= v0;
v1 = XMVector3Normalize(v1);
v2 = XMVector3Normalize(v2);
n = XMVector3Cross(v1, v2); // weighted normal
normals[face[0]] += n;
normals[face[1]] += n;
normals[face[2]] += n;
}
for (size_t i = 0; i < vertices.size(); i++)
{
n = XMVector3Normalize(normals[i]);
set_normal(vertices[i], n);
}
return true;
}
// generate per vertex tangent for given triangle mesh
template <typename VertexType, typename IndexType>
bool generate_tangent(gsl::span<VertexType> vertices, gsl::span<const Triangle<IndexType>> facets)
{
using namespace DirectX::VertexTraits;
using namespace DirectX;
if (!has_tangent<VertexType>::value)
return false;
//static_assert(has_tangent<VertexType>::value, "The vertex type dose not contains tangent field");
std::vector<XMVECTOR, XMAllocator> tan1(vertices.size() * 2);
XMVECTOR* tan2 = &tan1[vertices.size()];
std::memset(tan1.data(), 0, tan1.size() * sizeof(XMVECTOR));
for (const auto& face : facets)
{
{
XMVECTOR v0, v1, v2, w0, w1, w2;
v0 = get_position(vertices[face[0]]);
w0 = get_uv(vertices[face[0]]);
v1 = get_position(vertices[face[1]]);
w1 = get_uv(vertices[face[1]]);
v2 = get_position(vertices[face[2]]);
w2 = get_uv(vertices[face[2]]);
}
XMFLOAT4A v_1, v_2, w_1, w_2;
XMStoreA(v_1, v1 - v0);
XMStoreA(v_2, v2 - v0);
XMStoreA(w_1, w1 - w0);
XMStoreA(w_2, w2 - w0);
float x1 = v_1.x; float x2 = v_2.x;
float y1 = v_1.y; float y2 = v_2.y;
float z1 = v_1.z; float z2 = v_2.z;
float s1 = w_1.x; float s2 = w_2.x;
float t1 = w_1.y; float t2 = w_2.y;
float r = 1.0F / (s1 * t2 - s2 * t1);
XMVECTOR sdir = XMVectorSet(
(t2 * x1 - t1 * x2) * r,
(t2 * y1 - t1 * y2) * r,
(t2 * z1 - t1 * z2) * r, .0f);
XMVECTOR tdir = XMVectorSet(
(s1 * x2 - s2 * x1) * r,
(s1 * y2 - s2 * y1) * r,
(s1 * z2 - s2 * z1) * r, .0f);
tan1[face[0]] += sdir;
tan1[face[1]] += sdir;
tan1[face[2]] += sdir;
tan2[face[0]] += tdir;
tan2[face[1]] += tdir;
tan2[face[2]] += tdir;
}
for (size_t i = 0; i < vertices.size(); i++)
{
XMVECTOR n = get_normal(vertices[i], n);
XMVECTOR t = tan1[i];
// Gram-Schmidt orthogonalize
XMVECTOR nt = XMVector3Normalize(t - n * XMVector3Dot(n, t));
XMVECTOR w = XMVectorLess(XMVector3Dot(XMVector3Cross(n, t), tan2[i]), XMVectorZero());
w = XMVectorSelect(g_XMNegativeOne.v, g_XMOne.v, w);
nt = _DXMEXT XMVectorSelect<0, 0, 0, 1>(nt, w);
set_tangent(vertices[i], nt);
}
return true;
}
template <typename _VertexType, typename _IndexType = uint16_t, typename _FaceType = Triangle<_IndexType>>
class PolygonSoup
{
public:
typedef _VertexType VertexType;
typedef _IndexType IndexType;
typedef _FaceType FaceType;
static constexpr size_t PolygonVertex = FaceType::VertexCount;
PolygonSoup() {}
bool empty() const {
return vertices.empty() || indices.empty();
}
void clear()
{
vertices.clear();
indices.clear();
}
inline const FaceType& facet(int idx) const
{
return reinterpret_cast<const FaceType&>(indices[idx * FaceType::VertexCount]);
}
inline FaceType& facet(int idx)
{
return reinterpret_cast<FaceType&>(indices[idx * FaceType::VertexCount]);
}
void add_facet(const FaceType& new_facet)
{
indices.insert(indices.end(), new_facet.begin(), new_facet.end());
}
template <class... _TIndecies>
std::enable_if_t<sizeof...(_TIndecies) == FaceType::VertexCount> add_facet(_TIndecies... _indices)
{
indices.insert(indices.end(), { static_cast<IndexType>(_indices)... });
}
gsl::span<FaceType> facets() {
return gsl::span<FaceType>(
reinterpret_cast<FaceType*>(indices.data()),
indices.size() / FaceType::VertexCount);
}
gsl::span<const FaceType> facets() const {
return gsl::span<const FaceType>(
reinterpret_cast<const FaceType*>(indices.data()),
indices.size() / FaceType::VertexCount);
}
const VertexType& vertex(int facet, int vidx) const
{
return this->vertices[facet * FaceType::VertexCount + vidx];
}
VertexType& vertex(int facet, int vidx)
{
return this->vertices[facet * FaceType::VertexCount + vidx];
}
// flip all the polygons' winding and vertices' normal
void flip()
{
using namespace DirectX::VertexTraits;
if (has_normal<VertexType>::value)
{
for (auto& v : vertices)
set_normal(v, -get_normal(v));
}
static constexpr int vc = FaceType::VertexCount;
for (int i = 0; i < indices.size() / vc; i++)
std::reverse(indices.begin() + i * vc, indices.begin() + (i + 1)* vc);
}
void generate_normal()
{
static_assert(PolygonVertex == 3, "This mesh is not trigle mesh, please trianglize it first");
generate_normal<VertexType,IndexType>(this->vertices, this->facets());
}
void generate_tangent()
{
static_assert(PolygonVertex == 3, "This mesh is not trigle mesh, please trianglize it first");
generate_tangent<VertexType, IndexType>(this->vertices, this->facets());
}
// applies an uniform transform to all vertices in the mesh
void XM_CALLCONV transform(DirectX::FXMMATRIX M)
{
using namespace DirectX::VertexTraits;
for (auto& v : vertices)
{
XMVECTOR p = get_position(v);
p = _DXMEXT XMVector3TransformCoord(p, M);
set_position(v, p);
if (has_normal<VertexType>::value)
{
p = get_normal(v);
p = _DXMEXT XMVector3TransformNormal(p, M);
set_normal(v, p);
if (has_tangent<VertexType>::value)
{
p = get_tangent(v);
p = _DXMEXT XMVector3TransformNormal(p, M);
set_tangent(v, p);
}
}
}
}
std::vector<VertexType> vertices;
std::vector<IndexType> indices;
};
template <class _VertexType, class _IndexType>
int XM_CALLCONV intersect(const PolygonSoup<_VertexType, _IndexType, Triangle<_IndexType>> &Mesh, DirectX::FXMVECTOR Origin, DirectX::FXMVECTOR Direction, std::vector<float>* distances = nullptr)
{
using namespace DirectX;
using namespace DirectX::VertexTraits;
int count = 0;
XMVECTOR vDir = XMVector3Normalize(Direction);
for (const auto& tri : Mesh.facets())
{
float distance;
XMVECTOR v0 = get_position(&Mesh.vertices[tri[0]]);
XMVECTOR v1 = get_position(&Mesh.vertices[tri[1]]);
XMVECTOR v2 = get_position(&Mesh.vertices[tri[2]]);
bool hr = DirectX::TriangleTests::Intersects(Origin, vDir, v0, v1, v2, distance);
if (hr) {
++count;
if (distances) {
distances->push_back(distances);
}
}
}
return count;
}
struct MeshRayIntersectionInfo
{
using Vector3 = DirectX::Vector3;
Vector3 position;
float distance;
Vector3 barycentric;
int facet; // facet id
inline bool operator < (const MeshRayIntersectionInfo& rhs)
{
return this->distance < rhs.distance;
}
};
/// <summary>
/// Basic triangle mesh, each index represent an edge, which is the edge oppsite to the vertex in it's owner triangle
/// </summary>
template <typename _VertexType, typename _IndexType = uint16_t>
class TriangleMesh : public PolygonSoup<_VertexType, _IndexType, Triangle<_IndexType>>
{
public:
static const size_t VertexCount = FaceType::VertexCount;
public:
// edge's reverse edge
// stores the adjacent edges of a edge in a triangle
std::vector<IndexType> revedges;
// vertex's first adjacant edge
// std::vector<IndexType> vedges;
union EdgeType
{
_IndexType v[2];
struct {
_IndexType v0, v1;
};
};
inline EdgeType edge(int facet, int edge) const
{
EdgeType e;
auto& tri = this->facet(facet);
switch (edge)
{
case 0:
e.v0 = tri[1];
e.v1 = tri[2];
break;
case 1:
e.v0 = tri[2];
e.v1 = tri[0];
break;
case 2:
e.v0 = tri[0];
e.v1 = tri[1];
break;
default:
e.v0 = -1;
e.v1 = -1;
break;
}
return e;
}
inline EdgeType edge(int eid) const
{
return edge(eid / VertexCount, eid % VertexCount);
}
inline int adjacentFacet(int facet, int edge) const
{
return revedges[facet * VertexCount + edge] / VertexCount;
}
inline int adjacentFacet(int eid) const
{
return revedges[eid] / VertexCount;
}
// build the adjacent map so we can access all the 1 rings
void build()
{
// intialize all adjacant edges to -1
revedges.resize(this->indices.size(), -1);
_IndexType vsize = this->vertices.size();
int esize = this->indices.size();
using hash_type = uint64_t;
// make sure int for hash is enough
assert(vsize*vsize < std::numeric_limits<hash_type>::max());
std::unordered_map<hash_type, _IndexType> edges(esize * 2);
// max items inside this table should be less than (esize / 2)
_IndexType fid = 0;
for (const Triangle<_IndexType>& tri : this->facets())
{
for (_IndexType i = 0; i < VertexCount; i++)
{
_IndexType eid = i + fid * 3;
auto e = edge(fid, i);
hash_type ehash = e.v0 * vsize + e.v1;
hash_type revehash = e.v0 + e.v1 * vsize;
auto revItr = edges.find(revehash);
if (revItr == edges.end())
{
edges[ehash] = fid + 0;
}
else // find reversed edge, remove from edges map
{
auto revEid = revItr->second;
revedges[eid] = revEid;
revedges[revEid] = eid;
edges.erase(revItr);
}
}
++fid;
}
}
int XM_CALLCONV intersect(DirectX::FXMVECTOR Origin, DirectX::FXMVECTOR Direction, std::vector<MeshRayIntersectionInfo>* output) const
{
//assert(revedges.size() == indices.size());
using namespace DirectX;
using namespace DirectX::VertexTraits;
size_t count = 0;
XMVECTOR vDir = XMVector3Normalize(Direction);
auto fid = 0;
for (const auto& tri : this->facets())
{
float distance;
XMVECTOR v0 = get_position(&this->vertices[tri[0]]);
XMVECTOR v1 = get_position(&this->vertices[tri[1]]);
XMVECTOR v2 = get_position(&this->vertices[tri[2]]);
bool hr = DirectX::TriangleTests::Intersects(Origin, vDir, v0, v1, v2, distance);
if (hr) {
++count;
if (output) {
output->emplace_back();
auto& info = output->back();
XMVECTOR pos = distance * vDir + Origin;
XMVECTOR bc = DirectX::TriangleTests::BarycentricCoordinate(pos, v0, v1, v2);
info.facet = fid;
info.position = pos;
info.distance = distance;
info.barycentric = bc;
}
}
++fid;
}
if (output)
std::sort(output->begin(), output->end());
return count;
}
};
namespace Internal
{
#ifndef min
template <typename T>
inline T clamp(T value, T minV, T maxV)
{
return std::max(std::min(value, maxV), minV);
}
#else
template <typename T>
inline T clamp(T value, T minV, T maxV)
{
return max(min(value, maxV), minV);
}
#endif
}
/// <summary>
/// Compute the closest projection point from P0 to triangle(V0,V1,V2).
/// </summary>
/// <param name="P0">The p0.</param>
/// <param name="V0">The v0.</param>
/// <param name="V1">The v1.</param>
/// <param name="V2">The v2.</param>
/// <returns></returns>
inline DirectX::XMVECTOR XM_CALLCONV Projection(DirectX::FXMVECTOR P0, DirectX::FXMVECTOR V0, DirectX::FXMVECTOR V1, DirectX::GXMVECTOR V2)
{
using namespace DirectX;
using namespace Geometrics::Internal;
XMVECTOR edge0 = V1 - V0;
XMVECTOR edge1 = V2 - V0;
XMVECTOR p0 = V0 - P0;
//XMVectorBaryCentric();
float a = XMVectorGetX(_DXMEXT XMVector3LengthSq(edge0));
float b = XMVectorGetX(_DXMEXT XMVector3Dot(edge0, edge1));
float c = XMVectorGetX(_DXMEXT XMVector3LengthSq(edge1));
float d = XMVectorGetX(_DXMEXT XMVector3Dot(edge0, p0));
float e = XMVectorGetX(_DXMEXT XMVector3Dot(edge1, p0));
float det = a*c - b*b;
float s = b*e - c*d;
float t = b*d - a*e;
if (s + t < det)
{
if (s < 0.f)
{
if (t < 0.f)
{
if (d < 0.f)
{
s = clamp(-d / a, 0.f, 1.f);
t = 0.f;
}
else
{
s = 0.f;
t = clamp(-e / c, 0.f, 1.f);
}
}
else
{
s = 0.f;
t = clamp(-e / c, 0.f, 1.f);
}
}
else if (t < 0.f)
{
s = clamp(-d / a, 0.f, 1.f);
t = 0.f;
}
else
{
float invDet = 1.f / det;
s *= invDet;
t *= invDet;
}
}
else
{
if (s < 0.f)
{
float tmp0 = b + d;
float tmp1 = c + e;
if (tmp1 > tmp0)
{
float numer = tmp1 - tmp0;
float denom = a - 2 * b + c;
s = clamp(numer / denom, 0.f, 1.f);
t = 1 - s;
}
else
{
t = clamp(-e / c, 0.f, 1.f);
s = 0.f;
}
}
else if (t < 0.f)
{
if (a + d > b + e)
{
float numer = c + e - b - d;
float denom = a - 2 * b + c;
s = clamp(numer / denom, 0.f, 1.f);
t = 1 - s;
}
else
{
s = clamp(-e / c, 0.f, 1.f);
t = 0.f;
}
}
else
{
float numer = c + e - b - d;
float denom = a - 2 * b + c;
s = clamp(numer / denom, 0.f, 1.f);
t = 1.f - s;
}
}
return V0 + s * edge0 + t * edge1;
}
inline float XM_CALLCONV Distance(DirectX::FXMVECTOR P0, DirectX::FXMVECTOR V0, DirectX::FXMVECTOR V1, DirectX::GXMVECTOR V2)
{
using namespace DirectX;
XMVECTOR vProj = Projection(P0, V0, V1, V2);
vProj -= P0;
return XMVectorGetX(_DXMEXT XMVector3Length(vProj));
}
template <typename _VertexType, typename _IndexType>
inline float XM_CALLCONV Distance(const TriangleMesh<_VertexType, _IndexType> &Mesh, DirectX::FXMVECTOR Point)
{
using namespace DirectX;
float minDis = numeric_limits<float>::max();
for (const auto& tri : Mesh.facets())
{
float dis;
XMVECTOR v0 = XMLoadFloat3(&Mesh.vertices[tri[0]].position);
XMVECTOR v1 = XMLoadFloat3(&Mesh.vertices[tri[1]].position);
XMVECTOR v2 = XMLoadFloat3(&Mesh.vertices[tri[2]].position);
dis = Distance(Point, v0, v1, v2);
if (dis < minDis) minDis = dis;
//minDis = std::min(dis,minDis);
}
//XMVECTOR vDis = XMVectorReplicate(numeric_limits<float>::max());
//for (const auto& vertex : Mesh.vertices)
//{
// XMVECTOR vPos = XMLoadFloat3(&vertex.position);
// vPos -= Point;
// XMVECTOR dis = XMVector3Length(vPos);
// vDis = XMVectorMin(vDis,dis);
//}
//float minDisV = XMVectorGetX(vDis);
//assert(minDisV >= minDis);
return minDis;
//return XMVectorGetX(minDis);
}
template <typename _VertexType, typename _IndexType>
bool XM_CALLCONV Inside(const TriangleMesh<_VertexType, _IndexType> &Mesh, DirectX::FXMVECTOR Point)
{
XMFLOAT3A Direction;
Direction.x = (float)std::rand() / (RAND_MAX + 1);
Direction.y = (float)std::rand() / (RAND_MAX + 1);
Direction.z = (float)std::rand() / (RAND_MAX + 1);
XMVECTOR vDir = XMLoadFloat3A(&Direction);
auto count = intersect(Mesh, Point, vDir, nullptr);
return count & 1; //count % 2
}
} | {
"alphanum_fraction": 0.6275736549,
"avg_line_length": 25.1891117479,
"ext": "h",
"hexsha": "60333707730a3a4d8df108ff59ada3993253807b",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2017-06-12T16:15:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-01-16T14:25:28.000Z",
"max_forks_repo_head_hexsha": "8e22e3f20a90a22940218c243b7fe5e24e754e5b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ArcEarth/PPARM",
"max_forks_repo_path": "Geometrics/TriangleMesh.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8e22e3f20a90a22940218c243b7fe5e24e754e5b",
"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": "ArcEarth/PPARM",
"max_issues_repo_path": "Geometrics/TriangleMesh.h",
"max_line_length": 196,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "8e22e3f20a90a22940218c243b7fe5e24e754e5b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ArcEarth/PPARM",
"max_stars_repo_path": "Geometrics/TriangleMesh.h",
"max_stars_repo_stars_event_max_datetime": "2020-03-31T22:20:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-07-13T18:30:33.000Z",
"num_tokens": 5700,
"size": 17582
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
//THESE ARE GSL FUNCTIONS
//YOU DO NOT NEED TO INCLUDE ALL THESE HEADER FILES IN YOUR CODE
//JUST THE ONES YOU ACTUALLY NEED;
//IN THIS APPLICATION, WE ONLY NEED gsl/gsl_matrix.h
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_sort_double.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/gsl_errno.h>
void printmatrix(const char* filename,gsl_matrix* m);
gsl_matrix* transposematrix(gsl_matrix* m);
void matrixproduct(gsl_matrix* m1,gsl_matrix* m2,gsl_matrix* m);
void getInverse(gsl_matrix* K, gsl_matrix* inverse);
gsl_matrix* MakeSubmatrix(gsl_matrix* M,
int* IndRow,int lenIndRow,
int* IndColumn,int lenIndColumn);
double logdet(gsl_matrix* K);
gsl_matrix* diagMatrix(int n);
gsl_matrix* getcholesky(gsl_matrix* m);
gsl_matrix* getsimusample(int size, int p, gsl_rng* r, gsl_matrix* mat_chol);
gsl_vector* getInverseLogit(gsl_vector* x);
gsl_vector* getInverseLogit2(gsl_vector* x);
gsl_vector* getPi(gsl_vector* x, gsl_vector* beta);
gsl_vector* getPi2(gsl_vector* x, gsl_vector* beta);
double getLoglik(gsl_vector* y, gsl_vector* x, gsl_vector* beta);
double getLstar(gsl_vector* y, gsl_vector* x, gsl_vector* beta);
void getGradient(gsl_vector* y, gsl_vector* x, gsl_vector* beta, gsl_matrix* Gradient);
void getHessian(gsl_vector* y, gsl_vector* x, gsl_vector* beta, gsl_matrix* Hessian);
double getMaxBetaDiff(gsl_vector* betaCurrent, gsl_vector* betaNew);
gsl_vector* getcoefNR(int response, int explanatory, gsl_matrix* data, double error);
gsl_vector* getMHinteration(gsl_rng* r, gsl_vector* y, gsl_vector* x, gsl_vector* betaCurrent, gsl_matrix* NegInvHessian);
double getLaplace(int response, int explanatory, gsl_matrix* data, gsl_vector* betaMode);
double getMonteCarlo(int NumIterations, gsl_rng* r, int response, int explanatory, gsl_matrix* data);
gsl_vector* getcoefMH(int NumIterations, gsl_rng* r, int response, int explanatory, gsl_matrix* data, gsl_vector* betaMode);
| {
"alphanum_fraction": 0.7765957447,
"avg_line_length": 44.2352941176,
"ext": "h",
"hexsha": "95be7aa5fe727a59c000872305ec85f3d3fd4ace",
"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": "c75a90ebb1ef4f70597b9d28173d469d1d0b320b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "qifanhuang/ParallelComputingBayesianInference",
"max_forks_repo_path": "matrices.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c75a90ebb1ef4f70597b9d28173d469d1d0b320b",
"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": "qifanhuang/ParallelComputingBayesianInference",
"max_issues_repo_path": "matrices.h",
"max_line_length": 124,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c75a90ebb1ef4f70597b9d28173d469d1d0b320b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "qifanhuang/ParallelComputingBayesianInference",
"max_stars_repo_path": "matrices.h",
"max_stars_repo_stars_event_max_datetime": "2019-02-22T21:04:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-02-22T21:04:49.000Z",
"num_tokens": 660,
"size": 2256
} |
#pragma once
/*
* (C) Copyright 2020-2021 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
/*! \addtogroup ioda_cxx_variable
*
* @{
* \file Has_Variables.h
* \brief Interfaces for ioda::Has_Variables and related classes.
*/
#include <cstring>
#include <gsl/gsl-lite.hpp>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "ioda/Attributes/Attribute_Creator.h"
#include "ioda/Exception.h"
#include "ioda/Layout.h"
#include "ioda/Misc/Eigen_Compat.h"
#include "ioda/Misc/MergeMethods.h"
#include "ioda/Types/Type.h"
#include "ioda/Variables/FillPolicy.h"
#include "ioda/Variables/Variable.h"
#include "ioda/defs.h"
namespace ioda {
class Has_Variables;
class ObsGroup;
struct Named_Variable;
namespace detail {
class Has_Variables_Backend;
class Has_Variables_Base;
class DataLayoutPolicy;
class Group_Base;
} // namespace detail
/// \brief A few chunking strategies for Variables
namespace chunking {
/// Convenience function for setting default chunking parameters.
inline bool Chunking_Max(const std::vector<Dimensions_t>& in, std::vector<Dimensions_t>& out) {
out = in;
return true;
}
} // namespace chunking
/// \brief Used to specify Variable creation-time properties.
/// \ingroup ioda_cxx_variable
struct IODA_DL VariableCreationParameters {
private:
std::vector<std::pair<unsigned int, Variable> > dimsToAttach_;
std::string dimScaleName_;
public:
/// @name Fill Value
/// @{
detail::FillValueData_t fillValue_;
template <class DataType>
VariableCreationParameters& setFillValue(DataType fill) {
detail::assignFillValue<DataType>(fillValue_, fill);
return *this;
}
inline VariableCreationParameters& unsetFillValue() {
fillValue_.set_ = false;
return *this;
}
/// @}
/// @name Chunking and compression
/// @{
/// \brief Do we chunk this variable? Required for extendible / compressible Variables.
/// \details Requires a chunking strategy.
bool chunk = false;
/// \brief Manually specify the chunks. Never directly use. Use getChunks(...) instead.
std::vector<Dimensions_t> chunks;
/// Set variable chunking strategy. Used only if chunk == true and chunks.size() == 0.
std::function<bool(const std::vector<Dimensions_t>&, std::vector<Dimensions_t>&)>
fChunkingStrategy = chunking::Chunking_Max;
/// Figure out the chunking size
/// \param cur_dims are the current dimensions
std::vector<Dimensions_t> getChunks(const std::vector<Dimensions_t>& cur_dims) const {
if (chunks.size()) return chunks;
std::vector<Dimensions_t> res;
if (fChunkingStrategy(cur_dims, res)) return res;
throw Exception("Cannot figure out an appropriate chunking size.", ioda_Here());
}
bool gzip_ = false;
bool szip_ = false;
int gzip_level_ = 6; // 1 (fastest) - 9 (most compression)
unsigned int szip_PixelsPerBlock_ = 16;
unsigned int szip_options_ = 4; // Defined as H5_SZIP_EC_OPTION_MASK in hdf5.h;
void noCompress();
void compressWithGZIP(int level = 6);
void compressWithSZIP(unsigned PixelsPerBlock = 16, unsigned options = 4);
/// @}
/// @name General Functions
/// @{
/// Set any initial attributes here
Attribute_Creator_Store atts;
VariableCreationParameters();
VariableCreationParameters(const VariableCreationParameters&);
VariableCreationParameters& operator=(const VariableCreationParameters&);
template<class DataType>
static VariableCreationParameters defaulted() {
VariableCreationParameters ret;
ret.chunk = true;
ret.compressWithGZIP();
FillValuePolicies::applyFillValuePolicy<DataType>(FillValuePolicy::NETCDF4, ret.fillValue_);
return ret;
}
template <class DataType>
static VariableCreationParameters defaults() {
return defaulted<DataType>();
}
/// Finalize routine to make sure struct members are intact (e.g. for fill values)
detail::FillValueData_t::FillValueUnion_t finalize() const { return fillValue_.finalize(); }
detail::python_bindings::VariableCreationFillValues<VariableCreationParameters> _py_setFillValue;
private:
friend class detail::Has_Variables_Base;
/// Apply the properties to a Variable (second pass; after Variable is created).
Variable applyImmediatelyAfterVariableCreation(Variable h) const;
/// @}
};
typedef std::vector<Variable> NewVariables_Scales_t;
/// \brief Used to specify a new variable with the collective createWithScales function.
struct IODA_DL NewVariable_Base : std::enable_shared_from_this<NewVariable_Base> {
/// Name of the variable.
std::string name_;
/// Type of the new dimension. Int, char, etc. Used if a type is not passed directly.
std::type_index dataType_;
/// Type of the new dimension. Used if a type is passed directly.
Type dataTypeKnown_;
/// Dimension scales
NewVariables_Scales_t scales_;
/// Var creation params
VariableCreationParameters vcp_;
virtual ~NewVariable_Base() {}
NewVariable_Base(const std::string& name, const Type& dataType,
const NewVariables_Scales_t& scales,
const VariableCreationParameters& params)
: name_(name), dataType_(typeid(void)), dataTypeKnown_(dataType),
scales_(scales),
vcp_(params) {}
NewVariable_Base(const std::string& name, const std::type_index& dataType,
const NewVariables_Scales_t& scales,
const VariableCreationParameters& params)
: name_(name),
dataType_(dataType),
scales_(scales),
vcp_(params) {}
};
typedef std::vector<std::shared_ptr<NewVariable_Base>> NewVariables_t;
template <class DataType>
inline std::shared_ptr<NewVariable_Base> NewVariable(
const std::string& name, const NewVariables_Scales_t& scales,
const VariableCreationParameters& params = VariableCreationParameters::defaulted<DataType>()) {
return std::make_shared<NewVariable_Base>(name, typeid(DataType), scales, params);
}
inline std::shared_ptr<NewVariable_Base> NewVariable(const std::string& name,
const Type& DataType,
const NewVariables_Scales_t& scales,
const VariableCreationParameters& params
= VariableCreationParameters()) {
return std::make_shared<NewVariable_Base>(name, DataType, scales, params);
}
namespace detail {
/// \ingroup ioda_cxx_variable
class IODA_DL Has_Variables_Base {
// friend class Group_Base;
private:
/// Using an opaque object to implement the backend.
std::shared_ptr<Has_Variables_Backend> backend_;
/// Set by ObsGroup.
std::shared_ptr<const detail::DataLayoutPolicy> layout_;
std::vector<ComplementaryVariableCreationParameters> complementaryVariables_;
/// \brief FillValuePolicy helper
/// \details Hides the template function calls, so that the headers are smaller.
static void _py_fvp_helper(BasicTypes dataType, FillValuePolicy& fvp,
VariableCreationParameters& params);
ComplementaryVariableCreationParameters createDerivedVariableParameters(
const std::string &inputName, const std::string &outputName, size_t position);
std::vector<std::vector<std::string>> loadComponentVariableData(
const ComplementaryVariableCreationParameters& derivedVariableParams);
protected:
Has_Variables_Base(std::shared_ptr<Has_Variables_Backend>,
std::shared_ptr<const DataLayoutPolicy> = nullptr);
public:
virtual ~Has_Variables_Base();
/// Set the mapping policy to determine the Layout of Variables stored under this Group.
/// Usually only set by ObsGroup when we create / open.
virtual void setLayout(std::shared_ptr<const detail::DataLayoutPolicy>);
/// Query the backend and get the type provider.
virtual Type_Provider* getTypeProvider() const;
/// \brief Get the fill value policy used for Variables within this Group
/// \details The backend has to be consulted for this operation. Storage of this policy is
/// backend-dependent.
virtual FillValuePolicy getFillValuePolicy() const;
/// @name General Functions
/// @{
///
/// \brief Does a Variable with the specified name exist?
/// \param name is the name of the Variable that we are looking for.
/// \returns true if it exists.
/// \returns false otherwise.
virtual bool exists(const std::string& name) const;
/// \brief Delete an Attribute with the specified name.
/// \param attname is the name of the Variable that we are deleting.
/// \throws ioda::Exception if no such attribute exists.
virtual void remove(const std::string& name);
/// \brief Open a Variable by name
/// \param name is the name of the Variable to be opened.
/// \returns An instance of a Variable that can be queried (with getDimensions()) and read.
virtual Variable open(const std::string& name) const;
/// \brief Open a Variable by name
/// \param name is the name of the Variable to be opened.
/// \returns An instance of a Variable that can be queried (with getDimensions()) and read.
inline Variable operator[](const std::string& name) const { return open(name); }
/// List all Variables under this group (one-level search).
/// \see Group_Base::listObjects if you need to enumerate both Groups and Variables, or
/// if you need recursion.
virtual std::vector<std::string> list() const;
/// Convenience function to list all Variables under this group (one-level search).
/// \see Group_Base::listObjects if you need to enumerate both Groups and Variables, or
/// if you need recursion.
inline std::vector<std::string> operator()() const { return list(); }
/// \brief Combines all complementary variables as specified in the mapping file, opens them,
/// and optionally removes the originals from the ObsGroup.
///
/// \p removeOriginals determines if the original complementary variables should be removed from
/// the ObsGroup. Later functionality will ensure that the original complementary variables can
/// be recreated on writing back to the original file.
void stitchComplementaryVariables(bool removeOriginals = true);
/// \brief Converts unit to SI for all eligible variables. If conversion function not defined,
/// stores unit as attribute.
///
/// Makes the conversion if the variable's unit is defined in the mapping file and the unit conversion
/// is defined in UnitConversions.h.
void convertVariableUnits(std::ostream &out = std::cerr);
/// \brief Create a Variable without setting its data.
/// \param attrname is the name of the Variable.
/// \param dimensions is a vector representing the size of the metadata.
/// Each element of the vector is a dimension with a certain size.
/// \param in_memory_datatype is the runtime description of the Attribute's data type.
/// \returns A Variable that can be written to.
virtual Variable create(const std::string& name, const Type& in_memory_dataType,
const std::vector<Dimensions_t>& dimensions = {1},
const std::vector<Dimensions_t>& max_dimensions = {},
const VariableCreationParameters& params = VariableCreationParameters());
/// Python compatability function
/// \note Multiple ways to specify dimensions to match possible
/// Python function signatures.
Variable _create_py(const std::string& name, BasicTypes dataType,
const std::vector<Dimensions_t>& cur_dimensions = {1},
const std::vector<Dimensions_t>& max_dimensions = {},
const std::vector<Variable>& dimension_scales = {},
const VariableCreationParameters& params
= VariableCreationParameters());
inline Variable create(const std::string& name, const Type& in_memory_dataType,
const ioda::Dimensions& dims,
const VariableCreationParameters& params = VariableCreationParameters()) {
return create(name, in_memory_dataType, dims.dimsCur, dims.dimsMax, params);
}
/// \brief Create a Variable without setting its data.
/// \tparam DataType is the type of the data. I.e. float, int32_t, uint16_t, std::string, etc.
/// \param name is the name of the Variable.
/// \param dimensions is a vector representing the size of the metadata. Each element of the
/// vector is a dimension with a certain size.
/// \returns A Variable that can be written to.
template <class DataType>
Variable create(const std::string& name, const std::vector<Dimensions_t>& dimensions = {1},
const std::vector<Dimensions_t>& max_dimensions = {},
const VariableCreationParameters& params = VariableCreationParameters::defaulted<DataType>()) {
try {
VariableCreationParameters params2 = params;
FillValuePolicies::applyFillValuePolicy<DataType>(getFillValuePolicy(), params2.fillValue_);
Type in_memory_dataType = Types::GetType<DataType>(getTypeProvider());
auto var = create(name, in_memory_dataType, dimensions,
max_dimensions, params2);
return var;
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
}
template <class DataType>
Variable create(const std::string& name, const ioda::Dimensions& dims,
const VariableCreationParameters& params
= VariableCreationParameters::defaulted<DataType>()) {
try {
VariableCreationParameters params2 = params;
FillValuePolicies::applyFillValuePolicy<DataType>(getFillValuePolicy(), params2.fillValue_);
return create<DataType>(name, dims.dimsCur, dims.dimsMax, params2);
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
}
/// \brief Convenience function to create a Variable from certain dimension scales.
/// \tparam DataType is the type of the data. I.e. int, int32_t, uint16_t, std::string, etc.
/// \param name is the name of the Variable.
/// \param dimensions is a vector representing the size of the metadata. Each element of the
/// vector is a dimension with a certain size.
/// \returns A Variable that can be written to.
template <class DataType>
Variable createWithScales(const std::string& name,
const std::vector<Variable>& dimension_scales,
const VariableCreationParameters& params
= VariableCreationParameters::defaulted<DataType>()) {
try {
Type in_memory_dataType = Types::GetType<DataType>(getTypeProvider());
NewVariables_t newvars{NewVariable(name, in_memory_dataType, dimension_scales, params)};
createWithScales(newvars);
return open(name);
} catch (...) {
std::throw_with_nested(Exception(ioda_Here()));
}
}
/// @brief Collective function optimized to mass-construct variables and attach scales.
/// @param newvars is a vector of the new variables to be created.
/// @see NewVariable for the signature of the objects to add.
void createWithScales(const NewVariables_t& newvars);
/// @}
/// @name Collective functions
/// @brief These functions apply the an operation to a *set* of variables in situations where
/// such an operation would produce better performance results than a loop of serial
/// function calls.
/// @{
/// @brief Attach dimension scales to many Dimension Numbers in a set of Variables.
/// @param DimensionNumber
/// @param mapping is the scale mappings for each variable. The first part of the pair refers
/// to the variable that you are attaching scales to. The second part is a sequence of
/// scales that are attached along each dimension (indexed by the vector).
/// @details
/// For some backends, particularly HDF5, attaching a dimension scale to a variable is a slow
/// procedure when you have many variables. This function batches low-level calls and avoids
/// loops.
virtual void attachDimensionScales(
const std::vector<std::pair<Variable, std::vector<Variable>>>& mapping);
/// @}
};
class IODA_DL Has_Variables_Backend : public detail::Has_Variables_Base {
protected:
Has_Variables_Backend();
public:
virtual ~Has_Variables_Backend();
FillValuePolicy getFillValuePolicy() const override;
void attachDimensionScales(
const std::vector<std::pair<Variable, std::vector<Variable>>>& mapping) override;
};
} // namespace detail
/// \brief This class exists inside of ioda::Group and provides the interface to manipulating
/// Variables.
/// \ingroup ioda_cxx_variable
///
/// \note It should only be constructed inside of a Group. It has no meaning elsewhere.
/// \see ioda::Variable for the class that represents individual variables.
/// \throws ioda::Exception on all exceptions.
class IODA_DL Has_Variables : public detail::Has_Variables_Base {
public:
virtual ~Has_Variables();
Has_Variables();
Has_Variables(std::shared_ptr<detail::Has_Variables_Backend>,
std::shared_ptr<const detail::DataLayoutPolicy> = nullptr);
};
} // namespace ioda
/// @}
| {
"alphanum_fraction": 0.7021557161,
"avg_line_length": 41.3317535545,
"ext": "h",
"hexsha": "b33570cd8f5d32132a53d816b2aadd5e14626aab",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "NOAA-EMC/ioda",
"max_forks_repo_path": "src/engines/ioda/include/ioda/Variables/Has_Variables.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "NOAA-EMC/ioda",
"max_issues_repo_path": "src/engines/ioda/include/ioda/Variables/Has_Variables.h",
"max_line_length": 120,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "366ce1aa4572dde7f3f15862a2970f3dd3c82369",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "NOAA-EMC/ioda",
"max_stars_repo_path": "src/engines/ioda/include/ioda/Variables/Has_Variables.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3871,
"size": 17442
} |
/*
* 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 2d rm analysis.
*/
#ifdef SpecAstro
#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_sa2d;
int dnest_sa2d(int argc, char **argv)
{
int i;
double logz_sa2d;
if(parset.flag_sa_par_mutual == 0) /* SA and RM have the same BLR */
{
set_blr_model2d();
num_params_sa_blr_model = 0;
}
else if(parset.flag_sa_par_mutual == 1) /* SA and RM have different BLRs but share the same mbh and inc. */
{
set_blr_model2d();
set_sa_blr_model();
}
else
{
set_blr_model2d();
set_sa_blr_model();
}
/* parameter order: RM BLR, SA BLR, RM continuum */
/* RM */
num_params_blr = num_params_blr_model + num_params_nlr
+ num_params_res + num_params_linecenter + 1; /* include and line sys err */
num_params_rm = parset.n_con_recon + num_params_blr + num_params_var;
/* 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;
idx_linecenter = num_params_blr_model + num_params_nlr + num_params_res;
rnd_frac = fmax(0.2, 1.0*(num_params_blr_tot+num_params_var)/num_params);
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_sa2d = dnest_malloc_fptrset();
/* setup functions used for dnest*/
fptrset_sa2d->from_prior = from_prior_sa2d;
fptrset_sa2d->print_particle = print_particle_sa2d;
fptrset_sa2d->restart_action = restart_action_sa;
fptrset_sa2d->accept_action = accept_action_sa2d;
fptrset_sa2d->kill_action = kill_action_sa2d;
fptrset_sa2d->perturb = perturb_sa2d;
fptrset_sa2d->read_particle = read_particle_sa2d;
fptrset_sa2d->log_likelihoods_cal_initial = log_likelihoods_cal_initial_sa2d;
fptrset_sa2d->log_likelihoods_cal_restart = log_likelihoods_cal_restart_sa2d;
fptrset_sa2d->log_likelihoods_cal = log_likelihoods_cal_sa2d;
set_par_range_sa2d();
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 mbh and inc of SA BLR if SA and RM have different BLR */
if(parset.flag_sa_par_mutual == 1)
{
/* get the index for mbh and inclination parameters */
set_idx_par_mutual();
/* mbh */
par_fix[num_params_blr + idx_sa_par_mutual[0]] = 1;
par_fix_val[num_params_blr + idx_sa_par_mutual[0]] = 0.0;
/* 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;
}
else if(parset.flag_sa_par_mutual == 2)
{
/* get the index for mbh and inclination parameters */
set_idx_par_mutual();
/* inc and opening angle */
par_fix[num_params_blr + idx_sa_par_mutual[1]] = 1;
par_fix_val[num_params_blr + idx_sa_par_mutual[1]] = 0.0;
par_fix[num_params_blr + idx_sa_par_mutual[2]] = 1;
par_fix_val[num_params_blr + idx_sa_par_mutual[2]] = 0.0;
/* dynamical parameters from mass on */
for(i=idx_sa_par_mutual[0]; i<num_params_sa_blr_model; i++)
{
par_fix[num_params_blr + i] = 1;
par_fix_val[num_params_blr + i] = 0.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_sa2d();
force_update = parset.flag_force_update;
if(parset.flag_para_name != 1)
logz_sa2d = dnest(argc, argv, fptrset_sa2d, num_params, NULL, NULL, NULL, "data/", dnest_options_file, NULL, NULL);
dnest_free_fptrset(fptrset_sa2d);
return 0;
}
void set_par_range_sa2d()
{
int i, j, i1, i2;
/* setup parameter range, 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;
}
/* cope with narrow line */
for(i=num_params_blr_model; i<num_params_blr_model + num_params_nlr; i++)
{
par_range_model[i][0] = nlr_range_model[i - num_params_blr_model][0];
par_range_model[i][1] = nlr_range_model[i - num_params_blr_model][1];
par_prior_model[i] = nlr_prior_model[i - num_params_blr_model];
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 1.0; /* note that for logarithm prior of flux, this value is not used, so does not matter */
}
/* cope with spectral broadening */
for(i=num_params_blr_model + num_params_nlr; i<num_params_blr_model + num_params_nlr + num_params_res; i++)
{
par_range_model[i][0] = -10.0;
par_range_model[i][1] = 10.0;
par_prior_model[i] = GAUSSIAN;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 1.0;
}
/* cope with line center */
for(i=num_params_blr-num_params_linecenter-1; i< num_params_blr-1; i++)
{
par_range_model[i][0] = -10.0;
par_range_model[i][1] = 10.0;
par_prior_model[i] = GAUSSIAN;
par_prior_gaussian[i][0] = 0.0;
par_prior_gaussian[i][1] = 1.0;
}
/* the last is systematic 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;
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 of continuum */
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 in continuum and line */
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 ligth curve values */
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_sa2d()
{
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_sa2d.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]);
}
for(j=0; j<num_params_nlr; j++)
{
i++;
fprintf(fp, str_fmt, i, "narrow 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_res; j++)
{
i++;
fprintf(fp, str_fmt, i, "line broaden", 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_linecenter; j++)
{
i++;
fprintf(fp, str_fmt, i, "line center", 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_sa2d(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_sa2d(const void *model)
{
double logL;
logL = prob_initial_sa2d(model);
return logL;
}
/*!
* this function calculates likelihood at initial step.
*/
double log_likelihoods_cal_restart_sa2d(const void *model)
{
double logL;
logL = prob_initial_sa2d(model);
return logL;
}
/*!
* this function calculates likelihood.
*/
double log_likelihoods_cal_sa2d(const void *model)
{
double logL;
logL = prob_sa2d(model);
return logL;
}
/*!
* this function prints out parameters.
*/
void print_particle_sa2d(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_sa2d(FILE *fp, void *model)
{
int j;
double *psample = (double *)model;
for(j=0; j < num_params; j++)
{
if(fscanf(fp, "%lf", psample+j) < 1)
{
printf("%f\n", *psample);
fprintf(stderr, "#Error: Cannot read file sample_sa2d.txt.\n");
exit(0);
}
}
return;
}
/*!
* this function perturbs parameters.
*/
double perturb_sa2d(void *model)
{
double *pm = (double *)model;
double logH = 0.0, limit1, limit2, width, rnd;
int which, which_level, size_levels, count_saves;
/*
* fixed parameters need not to update
* perturb important parameters more frequently
*/
do
{
rnd = dnest_rand();
if(rnd < rnd_frac)
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();
size_levels = dnest_get_size_levels();
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_sa2d_exam(const void *model)
{
return 0.0;
}
void accept_action_sa2d()
{
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;
}
else if((
param < num_params_blr_model ||
(param >= num_params_blr && param < num_params_blr_tot)
) && 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, Trans2D, 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 = Trans2D_at_veldata_particles[which_particle_update];
Trans2D_at_veldata_particles[which_particle_update] = Trans2D_at_veldata_particles_perturb[which_particle_update];
Trans2D_at_veldata_particles_perturb[which_particle_update] = ptemp;
prob_sa_particles[which_particle_update] = prob_sa_particles_perturb[which_particle_update];
}
//Fline is always updated except param = num_params_blr - 1
if( param != num_params_blr-1 && 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;
}
return;
}
/*
* action when particle i is killed in cdnest sampling.
* particle i_copy's properties is copyed to particle i.
*/
void kill_action_sa2d(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 * n_vel_data_ext * sizeof(double));
memcpy(TransTau_particles[i], TransTau_particles[i_copy], parset.n_tau*sizeof(double));
memcpy(Trans2D_at_veldata_particles[i], Trans2D_at_veldata_particles[i_copy], parset.n_tau * n_vel_data_ext * sizeof(double));
prob_sa_particles[i] = prob_sa_particles[i_copy];
return;
}
#endif | {
"alphanum_fraction": 0.6595764662,
"avg_line_length": 29.8695652174,
"ext": "c",
"hexsha": "3691d2332de7831f058f3740c3dbb46d32622027",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-11-22T12:54:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-12T13:51:29.000Z",
"max_forks_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/BRAINS",
"max_forks_repo_path": "src/dnest_sa2d.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "LiyrAstroph/BRAINS",
"max_issues_repo_path": "src/dnest_sa2d.c",
"max_line_length": 128,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/BRAINS",
"max_stars_repo_path": "src/dnest_sa2d.c",
"max_stars_repo_stars_event_max_datetime": "2021-05-18T07:46:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-16T13:37:42.000Z",
"num_tokens": 6499,
"size": 21297
} |
/* -*- c -*- */
/*
* Copyright (C) 2017 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
/*
* generate MMSE interpolating differentiator FIR table values
*/
#include <math.h>
#include <assert.h>
#include <gsl/gsl_integration.h>
#define MU 0.5 /* the MU for which we're computing coeffs */
#define Ts (1.0) /* sampling period */
#define B (1.0/(4*Ts)) /* one-sided signal bandwidth */
//#define B (1.0/(8./3*Ts)) /* one-sided signal bandwidth */
static unsigned global_n;
static double *global_h;
double global_mu = MU;
double global_B = B;
gsl_integration_workspace *global_gsl_int_workspace = NULL;
/*
* This function computes the difference squared between the ideal
* interpolating differentiator frequency response at frequency OMEGA and the
* approximation defined by the FIR coefficients in global_h[]
*
* See eqn (9-7), "Digital Communication Receivers", Meyr, Moeneclaey
* and Fechtel, Wiley, 1998. for the jist of what going on here.
*
* See eqns (7.99) and (7.100), "Discrete Time Signal Processing",
* Oppenheim, Alan V., Schafer, Ronald W., Prentice Hall 1989. for the
* (non-bandlimited) ideal differentiator.
*
* Andy Walls derived the expression for the h[n] for the bandlimited
* differentiator by performing an Inverse DTFT on the bandlimited ideal
* response. (Integration by parts.)
*/
static double
integrand (double omega, void *params)
{
double real_ideal;
double real_approx;
double real_diff;
double imag_ideal;
double imag_approx;
double imag_diff;
int i, n;
int I1;
double *h;
/*
* Ideal differentiator frequency response,
* with freq modulation to effect a time shift left (advance),
* and band limited to (-fc, fc).
* N.B. fc is global_B, mu is global_mu, Fs is 1/Ts, 2*pi*f is omega.
* fc and Fs are in Hz, and omega is in radians/second.
*
* H(f) = j*2*pi*f*Ts * exp(j*2*pi*f*Ts*mu) for |f| <= fc <= Fs/2
*/
real_ideal = -omega * Ts * sin (omega * Ts * global_mu);
imag_ideal = omega * Ts * cos (omega * Ts * global_mu);
n = global_n;
h = global_h;
I1 = -(n / 2);
real_approx = 0;
imag_approx = 0;
for (i = 0; i < n; i++){
real_approx += h[i] * cos (-omega * Ts * (i + I1));
imag_approx += h[i] * sin (-omega * Ts * (i + I1));
}
real_diff = real_ideal - real_approx;
imag_diff = imag_ideal - imag_approx;
return real_diff * real_diff + imag_diff * imag_diff;
}
/*
* Integrate the difference squared over all frequencies of interest.
*/
double
c_fcn (double *x, int n)
{
gsl_function F;
double result, error;
F.function = integrand;
F.params = NULL;
assert ((n & 1) == 0); /* assert n is even */
global_n = n;
global_h = x;
// global_B is fc, the cutoff frequency in Hz. It defaults to Fs/4.0.
gsl_integration_qag(&F, -2 * M_PI * global_B, 2 * M_PI * global_B,
0.0, 1e-12, 1000, GSL_INTEG_GAUSS61,
global_gsl_int_workspace, &result, &error);
return result;
}
/* this is the interface expected by the calling fortran code */
double
objective (double x[], int *ndim)
{
return c_fcn (x, *ndim);
}
/*
* starting guess for optimization
*/
void initpt (double x[], int ndim)
{
int i;
double w_c;
double start;
double t;
double arg;
double denom;
/* Bandlimited, time shifted, differentiator filter (infinitely long)
*
* Andy Walls derived the expression for the h[n] for the bandlimited
* differentiator by performing an Inverse DTFT on the bandlimited ideal
* response. (Integration by parts.)
*
* Ideal differentiator frequency response,
* with freq modulation to effect a time shift left (advance),
* and band limited to (-fc, fc).
* N.B. fc is global_B, mu is global_mu, Fs is 1/Ts.
* fc and Fs are in Hz, and omega is in radians/second.
*
* H(f) = j*2*pi*f*Ts * exp(j*2*pi*f*Ts*mu) for |f| <= fc <= Fs/2
* H(f) = 0 for |f| > fc <= Fs/2
*
* Substituting normalized radian frequency, w, for 2*pi*f*Ts, we get:
*
* H(w) = j*w * exp(j*w*mu) for |w| <= w_c = 2*pi*fc*Ts <= pi
* H(w) = 0 for |w| > w_c = 2*pi*fc*Ts <= pi
*
* and the Inverse Discrete Time Fourier Transform is:
*
* h[n] = (1/(2*pi)) * integral(-pi,pi)[ H(w)*exp(j*w*n)*dw ]
*
* Performing integration by parts of the above expression, using these hints:
* integral [u*dv] = u*v - integral [v*du]
* u = j*w
* dv = exp(j*w*(n+mu))*dw
*
* We eventually get an infinitely long, but decaying impulse response:
*
* h[n] = (w_c/pi)/(n+mu) * [cos(pi*(w_c/pi)*(n+mu)) - sinc((w_c/pi)*(n+mu))]
*
* = [ w_c*(n+mu)*cos(w_c*(n+mu)) - sin(w_c*(n+mu)) ] / (pi*(n+mu)^2)
*
* w_c is the normalized radian cutoff frequency:
* 2*pi*fc*Ts, with fc <= Fs/2 and Fs = 1/Ts, so w_c <= pi
*
* For the case of w_c = pi and mu = 0, the cos() term alternates
* between +/- 1 and the sinc() term goes to 0 except at n == 0, so
* we get the following:
*
* h[n] = (-1)^n / n for n != 0
* = 0 for n == 0
* or
*
* h[n] = ..., 1/5, -1/4, 1/3, -1/2, 1, 0, -1, 1/2, -1/3, 1/4, -1/5, ...
*
* Compare with:
* Eqns (7.99) and (7.100), "Discrete Time Signal Processing",
* Oppenheim, Alan V., Schafer, Ronald W., Prentice Hall 1989. for the
* non-bandlimited (w_c = pi) ideal differentiator.
*/
/* Truncated, bandlimited, time shifted, differentiator filter */
w_c = 2.0 * M_PI * global_B * Ts;
start = (double)(-ndim/2) + global_mu;
for (i = 0; i < ndim; i++){
t = (double)(i) + start;
arg = w_c * t;
denom = M_PI*t*t; /* always >= 0.0 */
if (denom < 1e-9)
x[i] = 0.0;
else
x[i] = (arg * cos(arg) - sin(arg))/denom;
}
}
| {
"alphanum_fraction": 0.6192301794,
"avg_line_length": 30.3302325581,
"ext": "c",
"hexsha": "367aeeb3566a547f9b4d574f3142b5dce48fddc5",
"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": "64c149520ac6a7d44179c3f4a38f38add45dd5dc",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "v1259397/cosmic-gnuradio",
"max_forks_repo_path": "gnuradio-3.7.13.4/gr-filter/lib/gen_interpolator_taps/diff_objective_fct.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc",
"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": "v1259397/cosmic-gnuradio",
"max_issues_repo_path": "gnuradio-3.7.13.4/gr-filter/lib/gen_interpolator_taps/diff_objective_fct.c",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "v1259397/cosmic-gnuradio",
"max_stars_repo_path": "gnuradio-3.7.13.4/gr-filter/lib/gen_interpolator_taps/diff_objective_fct.c",
"max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z",
"num_tokens": 2052,
"size": 6521
} |
/* SO3.c */
// SO(3) Lie group implemented with GNU GSL
// cf. wikipedia, "Rotation_group_SO(3)#Infinitesimal_rotations"
// EY note : 20160519 Bizarrely, matrix multiplication isn't implemented in a straightforward manner with the gsl_matrix class; see blas (which I don't know what it is yet) and dgemm for the libraries, and SO3blas.c in this repo for that implementation
#include <stdio.h>
#include <gsl/gsl_matrix.h>
// Function prototype
// gsl_matrix commute(gsl_matrix, gsl_matrix);
int main(void)
{
gsl_matrix *L_x = gsl_matrix_calloc(3,3);
gsl_matrix *L_y = gsl_matrix_calloc(3,3);
gsl_matrix *L_z = gsl_matrix_calloc(3,3);
gsl_matrix_set(L_x,1,2,-1);
gsl_matrix_set(L_x,2,1,1);
gsl_matrix_set(L_y,0,2,1);
gsl_matrix_set(L_y,2,0,-1);
gsl_matrix_set(L_z,0,1,-1);
gsl_matrix_set(L_z,1,0,1);
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
printf("m(%d,%d) = %g\n", i, j,
gsl_matrix_get(L_x,i,j));
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
printf("m(%d,%d) = %g\n", i, j,
gsl_matrix_get(L_y,i,j));
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
printf("m(%d,%d) = %g\n", i, j,
gsl_matrix_get(L_z,i,j));
gsl_matrix_free(L_x);
gsl_matrix_free(L_y);
gsl_matrix_free(L_z);
return 0;
}
//gsl_matrix commute(gsl_matrix x, gsl_matrix y)
//{
//}
| {
"alphanum_fraction": 0.6486891386,
"avg_line_length": 23.4210526316,
"ext": "c",
"hexsha": "59cd92d3edab1f8ba913c6007503f0435ce4bd20",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2021-03-01T07:13:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-01-24T19:18:42.000Z",
"max_forks_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ernestyalumni/CompPhys",
"max_forks_repo_path": "gslExamples/SO3.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855",
"max_issues_repo_issues_event_max_datetime": "2019-01-29T22:37:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-01-16T22:34:47.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ernestyalumni/CompPhys",
"max_issues_repo_path": "gslExamples/SO3.c",
"max_line_length": 252,
"max_stars_count": 70,
"max_stars_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ernestyalumni/CompPhys",
"max_stars_repo_path": "gslExamples/SO3.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-24T16:00:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-07-24T04:09:27.000Z",
"num_tokens": 453,
"size": 1335
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_errno.h>
/* Setup */
gsl_rng *mgsl_rng_setup(int type)
{
const gsl_rng_type *types[] = {
gsl_rng_borosh13, gsl_rng_coveyou, gsl_rng_cmrg, gsl_rng_fishman18, gsl_rng_fishman20,
gsl_rng_fishman2x, gsl_rng_gfsr4, gsl_rng_knuthran, gsl_rng_knuthran2, gsl_rng_knuthran2002,
gsl_rng_lecuyer21, gsl_rng_minstd, gsl_rng_mrg, gsl_rng_mt19937, gsl_rng_mt19937_1999,
gsl_rng_mt19937_1998, gsl_rng_r250, gsl_rng_ran0, gsl_rng_ran1, gsl_rng_ran2, gsl_rng_ran3,
gsl_rng_rand, gsl_rng_rand48, gsl_rng_random128_bsd, gsl_rng_random128_glibc2,
gsl_rng_random128_libc5, gsl_rng_random256_bsd, gsl_rng_random256_glibc2,
gsl_rng_random256_libc5, gsl_rng_random32_bsd, gsl_rng_random32_glibc2,
gsl_rng_random32_libc5, gsl_rng_random64_bsd, gsl_rng_random64_glibc2,
gsl_rng_random64_libc5, gsl_rng_random8_bsd, gsl_rng_random8_glibc2, gsl_rng_random8_libc5,
gsl_rng_random_bsd, gsl_rng_random_glibc2, gsl_rng_random_libc5, gsl_rng_randu,
gsl_rng_ranf, gsl_rng_ranlux, gsl_rng_ranlux389, gsl_rng_ranlxd1, gsl_rng_ranlxd2,
gsl_rng_ranlxs0, gsl_rng_ranlxs1, gsl_rng_ranlxs2, gsl_rng_ranmar, gsl_rng_slatec,
gsl_rng_taus, gsl_rng_taus2, gsl_rng_taus113, gsl_rng_transputer, gsl_rng_tt800,
gsl_rng_uni, gsl_rng_uni32, gsl_rng_vax, gsl_rng_waterman14, gsl_rng_zuf, gsl_rng_default
};
const gsl_rng_type *T;
gsl_rng *r;
gsl_rng_env_setup();
T = types[type];
r = gsl_rng_alloc(T);
return r;
}
/* RNG IO*/
int mgsl_rng_fwrite(const char *filename, const gsl_rng *r)
{
FILE *fp;
if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED;
if(gsl_rng_fwrite(fp, r) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
int mgsl_rng_fread(const char *filename, gsl_rng *r)
{
FILE *fp;
if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED;
if(gsl_rng_fread(fp, r) != GSL_SUCCESS) return GSL_EFAILED;
fclose(fp);
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.7817817818,
"avg_line_length": 39.1764705882,
"ext": "c",
"hexsha": "d49ac98f6ca9035b2e6770b9732eb695e5fbd836",
"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": "609e76adadf462f8cb18c348b4700487df6f36ed",
"max_forks_repo_licenses": [
"Artistic-2.0"
],
"max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Random",
"max_forks_repo_path": "src/random.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "609e76adadf462f8cb18c348b4700487df6f36ed",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Artistic-2.0"
],
"max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Random",
"max_issues_repo_path": "src/random.c",
"max_line_length": 96,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "609e76adadf462f8cb18c348b4700487df6f36ed",
"max_stars_repo_licenses": [
"Artistic-2.0"
],
"max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Random",
"max_stars_repo_path": "src/random.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 674,
"size": 1998
} |
#include <stdio.h>
#include <time.h>
#include <cblas.h>// libatlas-dev (3.10.2-7)
#include "include/Matrix.h"
#include "include/HelpFunctions.h"
// file output
char* RESULT_FOLDER_PATH = "results/";
struct stat ST = {0};
int main(int argc, const char **argv) {
// VARIABLES
clock_t start, end; // measure time
bool calc_correct[3] = {false, false, false}; // correct calculations? (cache, avx, blas)
double overall_times[4] = {0,0,0,0}; // save different overall times in array
// arguments from command line, a.out = argv[0]
unsigned int N = (unsigned int) atoi(argv[1]); // dimension (N x N)
unsigned int BS = (unsigned int) atoi(argv[2]); // block size
int REPETITIONS = atoi(argv[3]);
printf("cmd args: %d %d %d\n",N,BS,REPETITIONS);
// INIT.
float* m1_f = createRandomizedMatrix_f(N);
float* m2_f = createRandomizedMatrix_f(N);
float* stdAlgorithm_F = calloc(N * N, sizeof (float));
// TEST FOR DIMENSIONS
if (N % AVX_VECTOR_SIZE != 0 || N < AVX_VECTOR_SIZE) {
printf("> ERROR! dimension N (%d) has to be: N mod %d == 0\n",N,AVX_VECTOR_SIZE);
return EXIT_FAILURE;
}
else if (BS % 2 != 0 || BS < 2 || BS > N) {
printf("> ERROR! block size BS (%d) has to be: BS mod 2 == 0\n && <= N",BS);
return EXIT_FAILURE;
}
else if (REPETITIONS <= 0) {
printf("> ERROR! REPETITIONS (%d) has to be > 0 \n",REPETITIONS);
return EXIT_FAILURE;
}
printHeader(N, BS, REPETITIONS);
// === CALCULATIONS ==================================================================
// STANDARD ALGORITHM
printf("executing standard algorithm multiplications …\n");
for (int i = 0; i < REPETITIONS; ++i) {
float* result_f = calloc(N * N, sizeof (float));
// one multiplication
start = clock();
standardMatrixMul_f(m1_f, m2_f, result_f, N);
end = clock();
// copy values from other matrix (later: comparison)
if (i == 0) {
for (unsigned int j = 0; j < N; ++j) {
for (unsigned int k = 0; k < N; ++k) {
stdAlgorithm_F[(N * j) + k] = result_f[(N * j) + k];
}
}
}
overall_times[0] += ((double) (end - start)) / CLOCKS_PER_SEC;
free(result_f);
}
// CACHE OPTIMIZED
printf("executing cache optimized multiplications …\n");
for (int i = 0; i < REPETITIONS; ++i) {
float* result_cache_f = calloc(N * N, sizeof (float));
start = clock();
optimizedMatrixMul_f(m1_f, m2_f, result_cache_f, N, BS);
end = clock();
overall_times[1] += ((double) (end - start)) / CLOCKS_PER_SEC;
calc_correct[0] = compareResultMatrices_f(stdAlgorithm_F, result_cache_f, N);
free(result_cache_f);
}
// PARALLEL (AVX)
printf("executing parallel multiplications …\n");
for (int i = 0; i < REPETITIONS; ++i) {
float* result_para_f = calloc(N * N, sizeof (float));
start = clock();
parallelMatrixMul_AVX_f(m1_f, m2_f, result_para_f, N);
end = clock();
overall_times[2] += ((double) (end - start)) / CLOCKS_PER_SEC;
calc_correct[1] = compareResultMatrices_f(stdAlgorithm_F, result_para_f, N);
free(result_para_f);
}
// BLAS (ATLAS)
printf("executing multiplications using BLAS …\n");
float ALPHA = 1;
float BETA = 0;
// matrix dimensions
int LDA=N;
int LDB=N;
int LDC=N;
// Single Precision, General Matrix Multiplication
for (int i = 0; i < REPETITIONS; ++i) {
float* result_cblas_f = calloc(N * N, sizeof (float));
start = clock();
cblas_sgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans,N,N,N,ALPHA,
m1_f,LDA,
m2_f,LDB,BETA,
result_cblas_f,LDC);
end = clock();
overall_times[3] += ((double) (end - start)) / CLOCKS_PER_SEC;
calc_correct[2] = compareResultMatrices_f(stdAlgorithm_F, result_cblas_f, N);
free(result_cblas_f);
}
// ===== cleanup allocated memory ===================================
free(m1_f);
free(m2_f);
free(stdAlgorithm_F);
// === FILE OUTPUT ===================================================================
createResultFolder(RESULT_FOLDER_PATH, ST);
char* filename =
createResultFile(RESULT_FOLDER_PATH, N, BS, REPETITIONS, overall_times, calc_correct);
printf("\nwriting results to %s …\n", filename);
printf("done.\n");
free(filename);
return 0;
} | {
"alphanum_fraction": 0.5584668688,
"avg_line_length": 28.6832298137,
"ext": "c",
"hexsha": "e190d121ab6a4d4213c4e981e55e568416f3a5db",
"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": "271a0044b278917d8220ffc70999ebd75a365af2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "matthiastz/FPS-Matrixmultiplikation",
"max_forks_repo_path": "src/main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "271a0044b278917d8220ffc70999ebd75a365af2",
"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": "matthiastz/FPS-Matrixmultiplikation",
"max_issues_repo_path": "src/main.c",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "271a0044b278917d8220ffc70999ebd75a365af2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "matthiastz/FPS-Matrixmultiplikation",
"max_stars_repo_path": "src/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1259,
"size": 4618
} |
/**
*
* @file core_zgetrf_incpiv.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.8.0
* @author Hatem Ltaief
* @author Mathieu Faverge
* @author Jakub Kurzak
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup dplasma_cores_complex64
*
* CORE_zgetrf_incpiv computes an LU factorization of a general M-by-N tile A
* using partial pivoting with row interchanges.
*
* The factorization has the form
*
* A = P * L * U
*
* where P is a permutation matrix, L is lower triangular with unit
* diagonal elements (lower trapezoidal if m > n), and U is upper
* triangular (upper trapezoidal if m < n).
*
* This is the right-looking Level 2.5 BLAS version of the algorithm.
*
*******************************************************************************
*
* @param[in] M
* The number of rows of the tile A. M >= 0.
*
* @param[in] N
* The number of columns of the tile A. N >= 0.
*
* @param[in] IB
* The inner-blocking size. IB >= 0.
*
* @param[in,out] A
* On entry, the M-by-N tile to be factored.
* On exit, the factors L and U from the factorization
* A = P*L*U; the unit diagonal elements of L are not stored.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,M).
*
* @param[out] IPIV
* The pivot indices; for 1 <= i <= min(M,N), row i of the
* tile was interchanged with row IPIV(i).
*
* @param[out] INFO
* See returned value.
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if INFO = -k, the k-th argument had an illegal value
* \retval >0 if INFO = k, U(k,k) is exactly zero. The factorization
* has been completed, but the factor U is exactly
* singular, and division by zero will occur if it is used
* to solve a system of equations.
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zgetrf_incpiv = PCORE_zgetrf_incpiv
#define CORE_zgetrf_incpiv PCORE_zgetrf_incpiv
#define CORE_zgessm PCORE_zgessm
int CORE_zgessm(int M, int N, int K, int IB,
int *IPIV,
const PLASMA_Complex64_t *L, int LDL,
PLASMA_Complex64_t *A, int LDA);
#endif
int CORE_zgetrf_incpiv(int M, int N, int IB,
PLASMA_Complex64_t *A, int LDA,
int *IPIV, int *INFO)
{
int i, j, k, sb;
int iinfo;
/* Check input arguments */
*INFO = 0;
if (M < 0) {
coreblas_error(1, "Illegal value of M");
return -1;
}
if (N < 0) {
coreblas_error(2, "Illegal value of N");
return -2;
}
if (IB < 0) {
coreblas_error(3, "Illegal value of IB");
return -3;
}
if ((LDA < max(1,M)) && (M > 0)) {
coreblas_error(5, "Illegal value of LDA");
return -5;
}
/* Quick return */
if ((M == 0) || (N == 0) || (IB == 0))
return PLASMA_SUCCESS;
k = min(M, N);
for(i =0 ; i < k; i += IB) {
sb = min(IB, k-i);
/*
* Factor diagonal and subdiagonal blocks and test for exact singularity.
*/
iinfo = LAPACKE_zgetf2_work(LAPACK_COL_MAJOR, M-i, sb, &A[LDA*i+i], LDA, &IPIV[i]);
/*
* Adjust INFO and the pivot indices.
*/
if((*INFO == 0) && (iinfo > 0))
*INFO = iinfo + i;
if (i+sb < N) {
CORE_zgessm(
M-i, N-(i+sb), sb, sb,
&IPIV[i],
&A[LDA*i+i], LDA,
&A[LDA*(i+sb)+i], LDA);
}
for(j = i; j < i+sb; j++) {
IPIV[j] = i + IPIV[j];
}
}
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.5053294574,
"avg_line_length": 29.2765957447,
"ext": "c",
"hexsha": "3e7968825d5b9aae2e19a22ae2bcd0d33a13e7e2",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z",
"max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "therault/dplasma",
"max_forks_repo_path": "src/cores/core_zgetrf_incpiv.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "therault/dplasma",
"max_issues_repo_path": "src/cores/core_zgetrf_incpiv.c",
"max_line_length": 91,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "therault/dplasma",
"max_stars_repo_path": "src/cores/core_zgetrf_incpiv.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z",
"num_tokens": 1176,
"size": 4128
} |
/*
* Copyright (c) 2016-2021 lymastee, All rights reserved.
* Contact: lymastee@hotmail.com
*
* This file is part of the gslib project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#ifndef style_ac50d5be_0f99_48dc_908f_ab8a309b2a27_h
#define style_ac50d5be_0f99_48dc_908f_ab8a309b2a27_h
#include <gslib/string.h>
#include <gslib/std.h>
#include <ariel/type.h>
#include <ariel/painter.h>
__ariel_begin__
enum style_sheet_type
{
sst_unknown = -1,
sst_color = 0,
sst_integer,
sst_boolean,
sst_float,
sst_string,
sst_capacity,
};
extern const string& get_style_sheet_type_name(style_sheet_type sst);
typedef std::pair<style_sheet_type, string> style_sheet_def;
typedef unordered_map<string, int> style_sheet_info_map;
struct accel_key;
class __gs_novtable style_sheet abstract
{
public:
static const int npos = -1;
public:
style_sheet(const style_sheet_def* ssp, int len);
virtual ~style_sheet() {}
virtual bool get_value(const string& name, string& value) = 0;
virtual void set_value(const string& name, const string& value) = 0;
virtual int get_content_size() const { return _ss_length; }
virtual style_sheet_type get_content_type(int index) const;
virtual const string& get_content_name(int index) const;
virtual void flush_style() = 0;
protected:
const style_sheet_def* _ss_pairs;
int _ss_length;
style_sheet_info_map _ss_info;
public:
void initialize_style_sheet(const style_sheet_def* ssp, int len);
int get_style_sheet_index(const string& name) const;
protected:
static bool from_color(string& str, const color& cr);
static bool to_color(color& cr, const string& str);
static bool from_integer(string& str, int i);
static bool to_integer(int& i, const string& str);
static bool from_boolean(string& str, bool b);
static bool to_boolean(bool& b, const string& str);
static bool from_float(string& str, float f);
static bool to_float(float& f, const string& str);
static bool from_accel_key(string& str, const accel_key& k);
static bool to_accel_key(accel_key& k, const string& str);
static void setup_brush_by_color(painter_brush& brush, const color& cr);
static void setup_pen_by_color(painter_pen& pen, const color& cr);
static void setup_font(font& ft, const string& name, int size);
};
__ariel_end__
#endif
| {
"alphanum_fraction": 0.7201240135,
"avg_line_length": 36.2040816327,
"ext": "h",
"hexsha": "020997dbdc30042ada61929e47f83a256ac7da32",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/ariel/style.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/ariel/style.h",
"max_line_length": 82,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/ariel/style.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z",
"num_tokens": 854,
"size": 3548
} |
//Gets cepstral coefficients (CCs). This is the same as dct + lifter.
//This computes "the" DCT (discrete cosine transformation) along one dimension of matrix X.
//This uses fftw3 to compute the DCT-II.
//Then it applies a lifter (cepstral domain window) to the same dimension of X.
//The lifter has a single parameter, Q, which is default 22.0 in HTK, Kaldi and Ellis.
//Only the first K CCs are output.
#include <stdio.h>
#include <float.h>
#include <math.h>
#include <cblas.h>
#include <fftw3.h>
#ifndef M_PIf
#define M_PIf 3.141592653589793238462643383279502884f
#endif
#ifndef M_PI
#define M_PI 3.141592653589793238462643383279502884
#endif
#ifdef __cplusplus
namespace ov {
extern "C" {
#endif
int get_ccs_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int ndct, const float Q, const int K);
int get_ccs_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim, const int ndct, const double Q, const int K);
int get_ccs_s (float *Y, const float *X, const int iscolmajor, const int R, const int C, const int dim, const int ndct, const float Q, const int K)
{
const float z = 0.0f;
const float Q2 = 0.5f*Q, PQ = M_PIf/Q;
int r, c, k;
float *X1, *Y1; //*lift;
fftwf_plan plan;
//struct timespec tic, toc;
//Checks
if (R<1) { fprintf(stderr,"error in get_ccs_s: R (nrows X) must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in get_ccs_s: C (ncols X) must be positive\n"); return 1; }
if (ndct<R && dim==0) { fprintf(stderr,"error in get_ccs_s: ndct must be >= R for dim==0\n"); return 1; }
if (ndct<C && dim==1) { fprintf(stderr,"error in get_ccs_s: ndct must be >= C for dim==1\n"); return 1; }
if (Q<0.0f) { fprintf(stderr,"error in get_ccs_s: Q must be positive (or 0 to skip lifter)\n"); return 1; }
if (K<1) { fprintf(stderr,"error in get_ccs_s: K must be positive\n"); return 1; }
if (K>ndct) { fprintf(stderr,"error in get_ccs_s: K must be <= ndct>\n"); return 1; }
//Initialize fftwf
X1 = fftwf_alloc_real((size_t)ndct);
Y1 = fftwf_alloc_real((size_t)ndct);
plan = fftwf_plan_r2r_1d(ndct,X1,Y1,FFTW_REDFT10,FFTW_ESTIMATE);
if (!plan) { fprintf(stderr,"error in get_ccs_s: problem creating fftw plan\n"); return 1; }
cblas_scopy(ndct,&z,0,&X1[0],1); //zero-pad
//clock_gettime(CLOCK_REALTIME,&tic);
//Initialize lifter
//if (!(lift=(float *)malloc((size_t)K*sizeof(float)))) { fprintf(stderr,"error in get_ccs_s: problem with malloc for lifter. "); perror("malloc"); return 1; }
//for (k=0; k<K; k++) { lift[k] = fmaf(Q2,sinf(k*PQ),1.0f); }
if (dim==0)
{
if (iscolmajor)
{
for (c=0; c<C; c++)
{
cblas_scopy(R,&X[c*R],1,&X1[0],1);
fftwf_execute(plan);
//cblas_ssbmv(CblasColMajor,CblasUpper,K,0,1.0f,&lift[0],1,&Y1[0],1,0.0f,&Y[c*K],1);
cblas_scopy(K,&Y1[0],1,&Y[c*K],1);
}
if (Q>FLT_EPSILON)
{
for (k=0; k<K; k++) { cblas_sscal(C,fmaf(Q2,sinf(PQ*k),1.0f),&Y[k],K); }
}
}
else
{
for (c=0; c<C; c++)
{
cblas_scopy(R,&X[c],C,&X1[0],1);
fftwf_execute(plan);
//cblas_ssbmv(CblasRowMajor,CblasUpper,K,0,1.0f,&lift[0],1,&Y1[0],1,0.0f,&Y[c],C);
cblas_scopy(K,&Y1[0],1,&Y[c],C);
}
if (Q>FLT_EPSILON)
{
for (k=0; k<K; k++) { cblas_sscal(C,fmaf(Q2,sinf(PQ*k),1.0f),&Y[k*C],1); }
}
}
}
else if (dim==1)
{
if (iscolmajor)
{
for (r=0; r<R; r++)
{
cblas_scopy(C,&X[r],R,&X1[0],1);
fftwf_execute(plan);
//cblas_ssbmv(CblasColMajor,CblasUpper,K,0,1.0f,&lift[0],1,&Y1[0],1,0.0f,&Y[r],R);
cblas_scopy(K,&Y1[0],1,&Y[r],R);
}
if (Q>FLT_EPSILON)
{
for (k=0; k<K; k++) { cblas_sscal(R,fmaf(Q2,sinf(PQ*k),1.0f),&Y[k*R],1); }
}
}
else
{
for (r=0; r<R; r++)
{
cblas_scopy(C,&X[r*C],1,&X1[0],1);
fftwf_execute(plan);
//cblas_ssbmv(CblasRowMajor,CblasUpper,K,0,1.0f,&lift[0],1,&Y1[0],1,0.0f,&Y[r*K],1);
cblas_scopy(K,&Y1[0],1,&Y[r*K],1);
}
if (Q>FLT_EPSILON)
{
for (k=0; k<K; k++) { cblas_sscal(R,fmaf(Q2,sinf(PQ*k),1.0f),&Y[k],K); }
}
}
}
else
{
fprintf(stderr,"error in get_ccs_s: dim must be 0 or 1.\n"); return 1;
}
//clock_gettime(CLOCK_REALTIME,&toc); fprintf(stderr,"elapsed time = %f ms\n",(toc.tv_sec-tic.tv_sec)*1e3+(toc.tv_nsec-tic.tv_nsec)/1e6);
fftwf_destroy_plan(plan); fftwf_free(X1); fftwf_free(Y1);
return 0;
}
int get_ccs_d (double *Y, const double *X, const int iscolmajor, const int R, const int C, const int dim, const int ndct, const double Q, const int K)
{
const double z = 0.0;
const double Q2 = 0.5*Q, PQ = M_PI/Q;
int r, c, k;
double *X1, *Y1;
fftw_plan plan;
//Checks
if (R<1) { fprintf(stderr,"error in get_ccs_d: R (nrows X) must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in get_ccs_d: C (ncols X) must be positive\n"); return 1; }
if (ndct<R && dim==0) { fprintf(stderr,"error in get_ccs_d: ndct must be >= R for dim==0\n"); return 1; }
if (ndct<C && dim==1) { fprintf(stderr,"error in get_ccs_d: ndct must be >= C for dim==1\n"); return 1; }
if (Q<0.0) { fprintf(stderr,"error in get_ccs_d: Q must be positive (or 0 to skip lifter)\n"); return 1; }
if (K<1) { fprintf(stderr,"error in get_ccs_d: K must be positive\n"); return 1; }
if (K>ndct) { fprintf(stderr,"error in get_ccs_d: K must be <= ndct>\n"); return 1; }
//Initialize fftw
X1 = fftw_alloc_real((size_t)ndct);
Y1 = fftw_alloc_real((size_t)ndct);
plan = fftw_plan_r2r_1d(ndct,X1,Y1,FFTW_REDFT10,FFTW_ESTIMATE);
if (!plan) { fprintf(stderr,"error in get_ccs_s: problem creating fftw plan\n"); return 1; }
cblas_dcopy(ndct,&z,0,&X1[0],1); //zero-pad
if (dim==0)
{
if (iscolmajor)
{
for (c=0; c<C; c++)
{
cblas_dcopy(R,&X[c*R],1,&X1[0],1);
fftw_execute(plan);
cblas_dcopy(K,&Y1[0],1,&Y[c*K],1);
}
if (Q>DBL_EPSILON)
{
for (k=0; k<K; k++) { cblas_dscal(C,fma(Q2,sin(PQ*k),1.0),&Y[k],K); }
}
}
else
{
for (c=0; c<C; c++)
{
cblas_dcopy(R,&X[c],C,&X1[0],1);
fftw_execute(plan);
cblas_dcopy(K,&Y1[0],1,&Y[c],C);
}
if (Q>DBL_EPSILON)
{
for (k=0; k<K; k++) { cblas_dscal(C,fma(Q2,sin(PQ*k),1.0),&Y[k*C],1); }
}
}
}
else if (dim==1)
{
if (iscolmajor)
{
for (r=0; r<R; r++)
{
cblas_dcopy(C,&X[r],R,&X1[0],1);
fftw_execute(plan);
cblas_dcopy(K,&Y1[0],1,&Y[r],R);
}
if (Q>DBL_EPSILON)
{
for (k=0; k<K; k++) { cblas_dscal(R,fma(Q2,sin(PQ*k),1.0),&Y[k*R],1); }
}
}
else
{
for (r=0; r<R; r++)
{
cblas_dcopy(C,&X[r*C],1,&X1[0],1);
fftw_execute(plan);
cblas_dcopy(K,&Y1[0],1,&Y[r*K],1);
}
if (Q>DBL_EPSILON)
{
for (k=0; k<K; k++) { cblas_dscal(R,fma(Q2,sin(PQ*k),1.0),&Y[k],K); }
}
}
}
else
{
fprintf(stderr,"error in get_ccs_d: dim must be 0 or 1.\n"); return 1;
}
fftw_destroy_plan(plan); fftw_free(X1); fftw_free(Y1);
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.5202519141,
"avg_line_length": 34.9051724138,
"ext": "c",
"hexsha": "5dfc490d62273c0eeb4a2596d4569be7f8fce6dc",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/aud",
"max_forks_repo_path": "c/get_ccs.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "erikedwards4/aud",
"max_issues_repo_path": "c/get_ccs.c",
"max_line_length": 163,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/aud",
"max_stars_repo_path": "c/get_ccs.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2742,
"size": 8098
} |
#include <stdio.h>
#include <gsl/gsl_linalg.h>
double A[] =
{
-1.0, 0.0, 2.0, 1.0,
0.0, -1.0, 3.0, 2.0,
1.0, 2.0, 3.0, 0.0,
-3.0, 1.0, 4.0, 2.0
};
double y[] = { 0.0, 1.0, 2.0, 1.0 };
int main() {
gsl_matrix_view m = gsl_matrix_view_array(A, 4, 4);
gsl_vector_view b = gsl_vector_view_array(y, 4);
gsl_vector* x = gsl_vector_alloc(4);
int s;
gsl_permutation* p = gsl_permutation_alloc(4);
gsl_linalg_LU_decomp(&m.matrix, p, &s);
gsl_linalg_LU_solve(&m.matrix, p, &b.vector, x);
printf("x = \n");
gsl_vector_fprintf(stdout, x, "%5.1f");
gsl_permutation_free(p);
gsl_vector_free(x);
return 0;
}
| {
"alphanum_fraction": 0.6148969889,
"avg_line_length": 20.3548387097,
"ext": "c",
"hexsha": "f466e06136b6eb53c937e32ddafe8500c5ad2c5e",
"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": "ed0cbb5f62d54af5ca4691d18db09069097c064a",
"max_forks_repo_licenses": [
"FSFAP"
],
"max_forks_repo_name": "julnamoo/practice-linux",
"max_forks_repo_path": "src_book0/ex10/list1032/list1032B.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"FSFAP"
],
"max_issues_repo_name": "julnamoo/practice-linux",
"max_issues_repo_path": "src_book0/ex10/list1032/list1032B.c",
"max_line_length": 53,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a",
"max_stars_repo_licenses": [
"FSFAP"
],
"max_stars_repo_name": "julnamoo/practice-linux",
"max_stars_repo_path": "src_book0/ex10/list1032/list1032B.c",
"max_stars_repo_stars_event_max_datetime": "2018-09-14T05:43:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-09-14T05:43:58.000Z",
"num_tokens": 275,
"size": 631
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** 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 <petscmat.h>
#include <petscvec.h>
#include <petscksp.h>
#include <petscpc.h>
#include <StGermain/StGermain.h>
#include <StgDomain/StgDomain.h>
#include <StgFEM/StgFEM.h>
#include <PICellerator/PICellerator.h>
#include <Underworld/Underworld.h>
#include "Solvers/KSPSolvers/KSPSolvers.h"
#include "common-driver-utils.h"
#include "BSSCR.h" /* includes StokesBlockKSPInterface.h */
#define KSPBSSCR "bsscr"
void bsscr_summary(KSP_BSSCR * bsscrp_self, KSP ksp_S, KSP ksp_inner,
Mat K,Mat K2,Mat D,Mat G,Mat C,Vec u,Vec p,Vec f,Vec h,Vec t,
double penaltyNumber,PetscTruth KisJustK,
double mgSetupTime,
double RHSSolveTime,
double scrSolveTime,
double a11SingleSolveTime){
PetscTruth flg, found;
PetscInt uSize, pSize, lmax, lmin, iterations;
PetscReal rNorm, fNorm, uNorm, uNormInf, pNorm, pNormInf, p_sum, min, max;
Vec q, qq, t2, t3;
double solutionAnalysisTime;
PetscPrintf( PETSC_COMM_WORLD, "\n\nSCR Solver Summary:\n\n");
if(bsscrp_self->mg)
PetscPrintf( PETSC_COMM_WORLD, " Multigrid setup: = %.4g secs \n", mgSetupTime);
iterations = bsscrp_self->solver->stats.velocity_presolve_its;
PetscPrintf( PETSC_COMM_WORLD, " RHS V Solve: = %.4g secs / %d its\n", RHSSolveTime, iterations);
KSPGetIterationNumber( ksp_S, &iterations);
bsscrp_self->solver->stats.pressure_its = iterations;
PetscPrintf( PETSC_COMM_WORLD, " Pressure Solve: = %.4g secs / %d its\n", scrSolveTime, iterations);
KSPGetIterationNumber( ksp_inner, &iterations);
bsscrp_self->solver->stats.velocity_backsolve_its = iterations;
PetscPrintf( PETSC_COMM_WORLD, " Final V Solve: = %.4g secs / %d its\n\n", a11SingleSolveTime, iterations);
/***************************************************************************************************************/
flg = PETSC_FALSE; /* Off by default */
PetscOptionsGetTruth( PETSC_NULL, "-scr_ksp_solution_summary", &flg, &found );
if(flg) {
PetscScalar KuNorm;
solutionAnalysisTime = MPI_Wtime();
VecGetSize( u, &uSize );
VecGetSize( p, &pSize );
VecDuplicate( u, &t2 );
VecDuplicate( u, &t3 );
MatMult( K, u, t3); VecNorm( t3, NORM_2, &KuNorm );
double angle, kdot;
if(penaltyNumber > 1e-10){/* should change this to ifK2built maybe */
MatMult( K2, u, t2); VecNorm( t2, NORM_2, &rNorm );
VecDot(t2,t3,&kdot);
angle = (kdot/(rNorm*KuNorm));
PetscPrintf( PETSC_COMM_WORLD, " <K u, K2 u>/(|K u| |K2 u|) = %.6e\n", angle);
}
VecNorm( t, NORM_2, &rNorm ); /* t = f- G p should be the formal residual vector, calculated on line 267 in auglag-driver-DGTGD.c */
VecDot(t3,t,&kdot);
angle = (kdot/(rNorm*KuNorm));
PetscPrintf( PETSC_COMM_WORLD, " <K u, (f-G p)>/(|K u| |f- G p|) = %.6e\n\n", angle);
MatMult( K, u, t2); VecNorm(t2, NORM_2, &KuNorm);
VecAYPX( t2, -1.0, t ); /* t2 <- -t2 + t : t = f- G p should be the formal residual vector, calculated on line 267 in auglag-driver-DGTGD.c*/
VecNorm( t2, NORM_2, &rNorm );
VecNorm( f, NORM_2, &fNorm );
if(KisJustK){
PetscPrintf( PETSC_COMM_WORLD,"Velocity back-solve with original K matrix\n");
PetscPrintf( PETSC_COMM_WORLD,"Solved K u = G p -f\n");
PetscPrintf( PETSC_COMM_WORLD,"Residual with original K matrix\n");
PetscPrintf( PETSC_COMM_WORLD, " |f - K u - G p| = %.12e\n", rNorm);
PetscPrintf( PETSC_COMM_WORLD, " |f - K u - G p|/|f| = %.12e\n", rNorm/fNorm);
if(penaltyNumber > 1e-10){/* means the restore_K flag was used */
//if(K2 && f2){
MatAXPY(K,penaltyNumber,K2,DIFFERENT_NONZERO_PATTERN);/* Computes K = penaltyNumber*K2 + K */
//VecAXPY(f,penaltyNumber,f2); /* f = penaltyNumber*f2 + f */
KisJustK=PETSC_FALSE;
MatMult( K, u, t2);
MatMult( G, p, t);
VecAYPX( t, -1.0, f ); /* t <- -t + f */
VecAYPX( t2, -1.0, t ); /* t2 <- -t2 + t */
VecNorm( t2, NORM_2, &rNorm );
PetscPrintf( PETSC_COMM_WORLD,"Residual with K+K2 matrix and f rhs vector\n");
PetscPrintf( PETSC_COMM_WORLD, " |(f) - (K + K2) u - G p| = %.12e\n", rNorm);
//}
}
}
else{
PetscPrintf( PETSC_COMM_WORLD,"Velocity back-solve with K+K2 matrix\n");
PetscPrintf( PETSC_COMM_WORLD,"Solved (K + K2) u = G p - (f)\n");
PetscPrintf( PETSC_COMM_WORLD,"Residual with K+K2 matrix and f rhs vector\n");
PetscPrintf( PETSC_COMM_WORLD, " |(f) - (K + K2) u - G p| = %.12e\n", rNorm);
PetscReal KK2Norm,KK2Normf;
MatNorm(K,NORM_1,&KK2Norm);
MatNorm(K,NORM_FROBENIUS,&KK2Normf);
penaltyNumber = -penaltyNumber;
MatAXPY(K,penaltyNumber,K2,DIFFERENT_NONZERO_PATTERN);/* Computes K = penaltyNumber*K2 + K */
//VecAXPY(f,penaltyNumber,f2); /* f = penaltyNumber*f2 + f */
KisJustK=PETSC_FALSE;
MatMult( K, u, t2); /* t2 = K*u */
MatMult( G, p, t); /* t = G*p */
VecAYPX( t, -1.0, f ); /* t <- f - t ; t = f - G*p */
VecAYPX( t2, -1.0, t ); /* t2 <- t - t2; t2 = f - G*p - K*u */
VecNorm( t2, NORM_2, &rNorm );
PetscPrintf( PETSC_COMM_WORLD,"Residual with original K matrix\n");
PetscPrintf( PETSC_COMM_WORLD, " |f - K u - G p| = %.12e\n", rNorm);
PetscPrintf( PETSC_COMM_WORLD, " |f - K u - G p|/|f| = %.12e\n", rNorm/fNorm);
PetscReal KNorm, K2Norm;
MatNorm(K,NORM_1,&KNorm); MatNorm(K2,NORM_1,&K2Norm);
PetscPrintf( PETSC_COMM_WORLD,"K and K2 norm_1 %.12e %.12e ratio %.12e\n",KNorm,K2Norm,K2Norm/KNorm);
MatNorm(K,NORM_INFINITY,&KNorm); MatNorm(K2,NORM_INFINITY,&K2Norm);
PetscPrintf( PETSC_COMM_WORLD,"K and K2 norm_inf %.12e %.12e ratio %.12e\n",KNorm,K2Norm,K2Norm/KNorm);
MatNorm(K,NORM_FROBENIUS,&KNorm); MatNorm(K2,NORM_FROBENIUS,&K2Norm);
PetscPrintf( PETSC_COMM_WORLD,"K and K2 norm_frob %.12e %.12e ratio %.12e\n",KNorm,K2Norm,K2Norm/KNorm);
PetscPrintf( PETSC_COMM_WORLD,"K+r*K2 norm_1 %.12e\n",KK2Norm);
PetscPrintf( PETSC_COMM_WORLD,"K+r*K2 norm_frob %.12e\n",KK2Normf);
penaltyNumber = -penaltyNumber;
MatAXPY(K,penaltyNumber,K2,DIFFERENT_NONZERO_PATTERN);/* Computes K = penaltyNumber*K2 + K */
}
PetscPrintf( PETSC_COMM_WORLD,"\n");
PetscPrintf( PETSC_COMM_WORLD, " |K u| = %.12e\n", KuNorm);
if(penaltyNumber > 1e-10){
MatMult( K2, u, t2); VecNorm( t2, NORM_2, &rNorm );
PetscPrintf( PETSC_COMM_WORLD, " |K2 u| = %.12e\n", rNorm);
PetscPrintf( PETSC_COMM_WORLD,"\n");
}
VecDuplicate( p, &q );
MatMult( D, u, q ); /* q = G'*u = D*u */
VecNorm( u, NORM_2, &uNorm );
VecNorm( q, NORM_2, &rNorm );
PetscPrintf( PETSC_COMM_WORLD, " |G^T u|_2 = %.6e\n", rNorm );
PetscPrintf( PETSC_COMM_WORLD, " |G^T u|_2/|u|_2 = %.6e\n", sqrt( (double) uSize / (double) pSize ) * rNorm / uNorm);
VecDuplicate( p, &qq );
MatMultTranspose( G, u, qq );
VecNorm( qq, NORM_2, &rNorm );
PetscPrintf( PETSC_COMM_WORLD, " |G^T u|/|u| = %.8e\n", rNorm/uNorm ); /* to compare directly with Uzawa */
VecNorm( q, NORM_INFINITY, &rNorm );
PetscPrintf( PETSC_COMM_WORLD, " |G^T u|_infty/|u|_2 = %.6e\n", sqrt( (double) uSize ) * rNorm / uNorm);
/* create G'*u+C*p-h to check on this constraint */
/* already have q = D*u */
VecZeroEntries(qq);
if(C){
MatMult( C, p, qq );
}
VecAYPX( q, 1.0, qq ); /* q = q+qq; G'*u + C*p*/
VecAXPY( q, -1.0, h ); /* q = q-h; G'*u + C*p - h */
VecNorm( q, NORM_2, &rNorm );
PetscPrintf( PETSC_COMM_WORLD, " |G^T u + C p - h| = %.8e :constraint\n", rNorm );
VecNorm( u, NORM_INFINITY, &uNormInf );
VecNorm( u, NORM_2, &uNorm );
VecGetSize( u, &uSize );
VecNorm( p, NORM_INFINITY, &pNormInf );
VecNorm( p, NORM_2, &pNorm );
PetscPrintf( PETSC_COMM_WORLD, " |u|_{\\infty} = %.6e , u_rms = %.6e\n",
uNormInf, uNorm / sqrt( (double) uSize ) );
PetscPrintf( PETSC_COMM_WORLD, " |p|_{\\infty} = %.6e , p_rms = %.6e\n",
pNormInf, pNorm / sqrt( (double) pSize ) );
VecMax( u, &lmax, &max );
VecMin( u, &lmin, &min );
PetscPrintf( PETSC_COMM_WORLD, " min/max(u) = %.6e [%d] / %.6e [%d]\n",min,lmin,max,lmax);
bsscrp_self->solver->stats.vmin = min;
bsscrp_self->solver->stats.vmax = max;
VecMax( p, &lmax, &max );
VecMin( p, &lmin, &min );
PetscPrintf( PETSC_COMM_WORLD, " min/max(p) = %.6e [%d] / %.6e [%d]\n",min,lmin,max,lmax);
bsscrp_self->solver->stats.pmin = min;
bsscrp_self->solver->stats.pmax = max;
VecSum( p, &p_sum );
PetscPrintf( PETSC_COMM_WORLD, " \\sum_i p_i = %.6e \n", p_sum );
bsscrp_self->solver->stats.p_sum=p_sum;
solutionAnalysisTime = MPI_Wtime() - solutionAnalysisTime;
PetscPrintf( PETSC_COMM_WORLD, "\n Time for this analysis = %.4g secs\n\n",solutionAnalysisTime);
Stg_VecDestroy(&t2 );
Stg_VecDestroy(&t3 );
Stg_VecDestroy(&q );
Stg_VecDestroy(&qq );
}
}
| {
"alphanum_fraction": 0.5457971014,
"avg_line_length": 48.3644859813,
"ext": "c",
"hexsha": "77d513d9dd55664db1b61adb8ea02056260d9f18",
"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/summary.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/summary.c",
"max_line_length": 148,
"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/summary.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": 3446,
"size": 10350
} |
#include <gsl/gsl_spline.h>
#include "eos_pres.h"
#include "global.h"
// "forward" EOS. input: rho, T. output: P
double
eos_pres (double rho, void *params)
{
struct param *eos_pres_params = (struct param *) params;
return (gsl_spline_eval (spline, rho, acc));
// return (pow(rho, 1.0/params.Gamma)); // polytrope
}
| {
"alphanum_fraction": 0.6832298137,
"avg_line_length": 24.7692307692,
"ext": "c",
"hexsha": "5f3b02b965c8c7b43d04f044a159708c0f09b4bc",
"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": "5288ad6972b47143e1ce57e282f516143f07b158",
"max_forks_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_forks_repo_name": "bcfriesen/TOV_solver",
"max_forks_repo_path": "src/eos_pres.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_issues_repo_name": "bcfriesen/TOV_solver",
"max_issues_repo_path": "src/eos_pres.c",
"max_line_length": 58,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158",
"max_stars_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_stars_repo_name": "bcfriesen/TOV_solver",
"max_stars_repo_path": "src/eos_pres.c",
"max_stars_repo_stars_event_max_datetime": "2015-11-14T02:27:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-14T02:27:58.000Z",
"num_tokens": 103,
"size": 322
} |
/**
*
* @file dsungesv.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
* @generated ds Tue Jan 7 11:45:09 2014
*
**/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <lapacke.h>
#include "common.h"
#define PLASMA_dlag2s(_descA, _descSB) \
plasma_parallel_call_4(plasma_pdlag2s, \
PLASMA_desc, (_descA), \
PLASMA_desc, (_descSB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
#define PLASMA_slag2d(_descSA, _descB) \
plasma_parallel_call_4(plasma_pslag2d, \
PLASMA_desc, (_descSA), \
PLASMA_desc, (_descB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
#define PLASMA_dlange(_norm, _descA, _result, _work) \
_result = 0; \
plasma_parallel_call_6(plasma_pdlange, \
PLASMA_enum, (_norm), \
PLASMA_desc, (_descA), \
double*, (_work), \
double*, &(_result), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request);
#define PLASMA_dlacpy(_descA, _descB) \
plasma_parallel_call_5(plasma_pdlacpy, \
PLASMA_enum, PlasmaUpperLower, \
PLASMA_desc, (_descA), \
PLASMA_desc, (_descB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
#define PLASMA_dgeadd(_alpha, _descA, _descB) \
plasma_parallel_call_5(plasma_pdgeadd, \
double, (_alpha), \
PLASMA_desc, (_descA), \
PLASMA_desc, (_descB), \
PLASMA_sequence*, sequence, \
PLASMA_request*, request)
/***************************************************************************//**
*
* @ingroup double
*
* PLASMA_dsungesv - Solves overdetermined or underdetermined linear systems involving an M-by-N
* matrix A using the QR or the LQ factorization of A. It is assumed that A has full rank.
* The following options are provided:
*
* # trans = PlasmaNoTrans and M >= N: find the least squares solution of an overdetermined
* system, i.e., solve the least squares problem: minimize || B - A*X ||.
*
* # trans = PlasmaNoTrans and M < N: find the minimum norm solution of an underdetermined
* system A * X = B.
*
* Several right hand side vectors B and solution vectors X can be handled in a single call;
* they are stored as the columns of the M-by-NRHS right hand side matrix B and the N-by-NRHS
* solution matrix X.
*
* PLASMA_dsungesv 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.
*
* We follow Bjorck's algorithm proposed in "Iterative Refinement of Linear
* Least Squares solutions I", BIT, 7:257-278, 1967.4
*
*******************************************************************************
*
* @param[in] trans
* Intended usage:
* = PlasmaNoTrans: the linear system involves A;
* = PlasmaTrans: the linear system involves A**H.
* Currently only PlasmaNoTrans is supported.
*
* @param[in] N
* The number of columns of the matrix A. N >= 0.
*
* @param[in] NRHS
* The number of right hand sides, i.e., the number of columns of the matrices B and X.
* NRHS >= 0.
*
* @param[in] A
* The M-by-N matrix A. This matrix is not modified.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,M).
*
* @param[in] B
* The M-by-NRHS matrix B of right hand side vectors, stored columnwise. Not modified.
*
* @param[in] LDB
* The leading dimension of the array B. LDB >= MAX(1,M,N).
*
* @param[out] X
* If return value = 0, the solution vectors, stored columnwise.
* if M >= N, rows 1 to N of B contain the least squares solution vectors; the residual
* sum of squares for the solution in each column is given by the sum of squares of the
* modulus of elements N+1 to M in that column;
* if M < N, rows 1 to N of B contain the minimum norm solution vectors;
*
* @param[in] LDX
* The leading dimension of the array B. LDB >= MAX(1,M,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
*
*******************************************************************************
*
* @sa PLASMA_dsungesv_Tile
* @sa PLASMA_dsungesv_Tile_Async
* @sa PLASMA_dsungesv
* @sa PLASMA_dgels
*
******************************************************************************/
int PLASMA_dsungesv(PLASMA_enum trans, int N, int NRHS,
double *A, int LDA,
double *B, int LDB,
double *X, int LDX, int *ITER)
{
int NB;
int status;
PLASMA_desc descA;
PLASMA_desc descB;
PLASMA_desc *descT;
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_dsungesv", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
*ITER = 0;
/* Check input arguments */
if (trans != PlasmaNoTrans &&
trans != PlasmaTrans &&
trans != PlasmaTrans )
{
plasma_error("PLASMA_dsungesv", "illegal value of trans");
return -1;
}
if (trans != PlasmaNoTrans) {
plasma_error("PLASMA_dsungesv", "only PlasmaNoTrans supported");
return PLASMA_ERR_NOT_SUPPORTED;
}
if (N < 0) {
plasma_error("PLASMA_dsungesv", "illegal value of N");
return -2;
}
if (NRHS < 0) {
plasma_error("PLASMA_dsungesv", "illegal value of NRHS");
return -3;
}
if (LDA < max(1, N)) {
plasma_error("PLASMA_dsungesv", "illegal value of LDA");
return -5;
}
if (LDB < max(1, N)) {
plasma_error("PLASMA_dsungesv", "illegal value of LDB");
return -7;
}
if (LDX < max(1, N)) {
plasma_error("PLASMA_dsungesv", "illegal value of LDX");
return -9;
}
/* Quick return */
if ( N == 0 )
return PLASMA_SUCCESS;
/* Tune NB & IB depending on M, N & NRHS; Set NBNB */
status = plasma_tune(PLASMA_FUNC_DSGELS, N, N, NRHS);
if (status != PLASMA_SUCCESS) {
plasma_error("PLASMA_dsungesv", "plasma_tune() failed");
return status;
}
NB = PLASMA_NB;
plasma_sequence_create(plasma, &sequence);
/* DOUBLE PRECISION INITIALIZATION */
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_dooplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N, sequence, &request,
plasma_desc_mat_free(&(descA)) );
plasma_dooplap2tile( descB, B, NB, NB, LDB, NRHS, 0, 0, N, NRHS, sequence, &request,
plasma_desc_mat_free(&(descA)); plasma_desc_mat_free(&(descB)) );
plasma_ddesc_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_diplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N,
sequence, &request);
plasma_diplap2tile( descB, B, NB, NB, LDB, NRHS, 0, 0, N, NRHS,
sequence, &request);
descX = plasma_desc_init(
PlasmaRealDouble, NB, NB, (NB*NB),
LDX, NRHS, 0, 0, N, NRHS);
descX.mat = X;
}
/* Allocate workspace */
PLASMA_Alloc_Workspace_dgels_Tile(N, N, &descT);
/* Call the native interface */
status = PLASMA_dsungesv_Tile_Async(PlasmaNoTrans, &descA, descT, &descB, &descX, ITER,
sequence, &request);
if (status == PLASMA_SUCCESS) {
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_dooptile2lap( 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_diptile2lap( descA, A, NB, NB, LDA, N, sequence, &request);
plasma_diptile2lap( descB, B, NB, NB, LDB, NRHS, sequence, &request);
plasma_diptile2lap( descX, X, NB, NB, LDX, NRHS, sequence, &request);
plasma_dynamic_sync();
}
}
PLASMA_Dealloc_Handle_Tile(&descT);
plasma_sequence_destroy(plasma, sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup double_Tile
*
* PLASMA_dsungesv_Tile - Solves symmetric linear system of equations using the tile QR
* or the tile LQ factorization and mixed-precision iterative refinement.
* Tile equivalent of PLASMA_dsungesv().
* Operates on matrices stored by tiles.
* All matrices are passed through descriptors.
* All dimensions are taken from the descriptors.
*
*******************************************************************************
*
* @param[in] trans
* Intended usage:
* = PlasmaNoTrans: the linear system involves A;
* = PlasmaTrans: the linear system involves A**H.
* Currently only PlasmaNoTrans is supported.
*
* @param[in,out] A
* - If the iterative refinement converged, A is not modified;
* - otherwise, it fell back to double precision solution, and
* on exit the M-by-N matrix A contains:
* if M >= N, A is overwritten by details of its QR factorization as returned by
* PLASMA_dgeqrf;
* if M < N, A is overwritten by details of its LQ factorization as returned by
* PLASMA_dgelqf.
*
* @param[out] T
* On exit:
* - if the iterative refinement converged, T is not modified;
* - otherwise, it fell back to double precision solution,
* and then T is an auxiliary factorization data.
*
* @param[in,out] B
* On entry, the M-by-NRHS matrix B of right hand side vectors, stored columnwise;
* @param[in] B
* The N-by-NRHS matrix of right hand side matrix B.
*
* @param[out] X
* If return value = 0, X is the solution vectors, stored columnwise:
* if M >= N, rows 1 to N of X contain the least squares solution vectors; the residual
* sum of squares for the solution in each column is given by the sum of squares of the
* modulus of elements N+1 to M in that column;
* if M < N, rows 1 to N of X contain the minimum norm solution vectors;
*
* @param[out] ITER
* The number of the current iteration in the iterative refinement process
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
*
*******************************************************************************
*
* @sa PLASMA_dsungesv
* @sa PLASMA_dsungesv_Tile_Async
* @sa PLASMA_dsungesv_Tile
* @sa PLASMA_dgels_Tile
*
******************************************************************************/
int PLASMA_dsungesv_Tile(PLASMA_enum trans, PLASMA_desc *A, PLASMA_desc *T,
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_dsungesv_Tile", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
plasma_sequence_create(plasma, &sequence);
status = PLASMA_dsungesv_Tile_Async(trans, A, T, 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 double_Tile_Async
*
* PLASMA_dsungesv_Tile_Async - Solves symmetric linear system of equations using
* the tile QR or the tile LQ factorization and mixed-precision iterative refinement.
* Non-blocking equivalent of PLASMA_dsungesv_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_dsungesv
* @sa PLASMA_dsungesv_Tile
* @sa PLASMA_dsungesv_Tile_Async
* @sa PLASMA_dgels_Tile_Async
*
******************************************************************************/
int PLASMA_dsungesv_Tile_Async(PLASMA_enum trans, PLASMA_desc *A, PLASMA_desc *T,
PLASMA_desc *B, PLASMA_desc *X, int *ITER,
PLASMA_sequence *sequence, PLASMA_request *request)
{
int N, NB, IB;
PLASMA_desc descA;
PLASMA_desc descT;
PLASMA_desc descB;
PLASMA_desc descX;
PLASMA_desc descR, descSA, descST, descSX;
plasma_context_t *plasma;
double *work;
const int itermax = 30;
const double bwdmax = 1.0;
const double negone = -1.0;
const double one = 1.0;
int iiter;
double Anorm, cte, eps, Rnorm, Xnorm;
*ITER=0;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_dsungesv_Tile", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
if (sequence == NULL) {
plasma_fatal_error("PLASMA_dsungesv_Tile", "NULL sequence");
return PLASMA_ERR_UNALLOCATED;
}
if (request == NULL) {
plasma_fatal_error("PLASMA_dsungesv_Tile", "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_dsungesv_Tile", "invalid first descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descA = *A;
}
if (plasma_desc_check(T) != PLASMA_SUCCESS) {
plasma_error("PLASMA_dsungesv_Tile", "invalid second descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descT = *T;
}
if (plasma_desc_check(B) != PLASMA_SUCCESS) {
plasma_error("PLASMA_dsungesv_Tile", "invalid third descriptor");
return PLASMA_ERR_ILLEGAL_VALUE;
} else {
descB = *B;
}
if (plasma_desc_check(X) != PLASMA_SUCCESS) {
plasma_error("PLASMA_dsungesv_Tile", "invalid fourth 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) ||
(descA.mb != descB.mb) || (descB.mb != descX.mb) ) {
plasma_error("PLASMA_dsungesv_Tile", "only square tiles of same size are supported");
return PLASMA_ERR_ILLEGAL_VALUE;
}
if (trans != PlasmaNoTrans) {
plasma_error("PLASMA_dsungesv_Tile", "only PlasmaNoTrans supported");
return PLASMA_ERR_NOT_SUPPORTED;
}
/* Set N, NRHS, NB */
N = descA.m;
NB = descA.nb;
IB = descT.mb;
work = (double *)plasma_shared_alloc(plasma, PLASMA_SIZE, PlasmaRealDouble);
if (work == NULL) {
plasma_error("PLASMA_dsungesv", "plasma_shared_alloc() failed");
plasma_shared_free(plasma, work);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
plasma_ddesc_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_sdesc_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_sdesc_alloc( descST, IB, NB, descT.m, descT.n, 0, 0, descT.m, descT.n, plasma_shared_free( plasma, work ); plasma_desc_mat_free(&descR); plasma_desc_mat_free(&descSA); plasma_desc_mat_free(&descST) );
plasma_sdesc_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(&descST); plasma_desc_mat_free(&descSX) );
/* Compute some constants */
PLASMA_dlange(PlasmaInfNorm, descA, Anorm, work);
eps = LAPACKE_dlamch_work('e');
/* Convert B from double precision to single precision and store
the result in SX. */
PLASMA_dlag2s(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_dlag2s(descA, descSA);
if (sequence->status != PLASMA_SUCCESS)
return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED);
/* Compute the QR factorization of SA */
plasma_parallel_call_4(plasma_psgeqrf,
PLASMA_desc, descSA,
PLASMA_desc, descST,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Compute the solve in simple */
plasma_parallel_call_7(plasma_psormqr,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaTrans,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_desc, descST,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_9(plasma_pstrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaUpper,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
float, 1.0,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* Convert SX back to double precision */
PLASMA_slag2d(descSX, descX);
/* Compute R = B - AX. */
PLASMA_dlacpy(descB, descR);
plasma_parallel_call_9(plasma_pdgemm,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNoTrans,
double, negone,
PLASMA_desc, descA,
PLASMA_desc, descX,
double, 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_dlange(PlasmaInfNorm, descX, Xnorm, work);
PLASMA_dlange(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(&descST);
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_dlag2s(descR, descSX);
plasma_parallel_call_7(plasma_psormqr,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaTrans,
PLASMA_desc, descSA,
PLASMA_desc, descSX,
PLASMA_desc, descST,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_9(plasma_pstrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaUpper,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
float, (float)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_slag2d(descSX, descR);
PLASMA_dgeadd(one, descR, descX);
/* Compute R = B - AX. */
PLASMA_dlacpy(descB,descR);
plasma_parallel_call_9(plasma_pdgemm,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNoTrans,
double, negone,
PLASMA_desc, descA,
PLASMA_desc, descX,
double, 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_dlange(PlasmaInfNorm, descX, Xnorm, work);
PLASMA_dlange(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(&descST);
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(&descST);
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 restart to double precision. */
PLASMA_dlacpy(descB, descX);
plasma_parallel_call_4(plasma_pdgeqrf,
PLASMA_desc, descA,
PLASMA_desc, descT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_7(plasma_pdormqr,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaTrans,
PLASMA_desc, descA,
PLASMA_desc, descX,
PLASMA_desc, descT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_parallel_call_9(plasma_pdtrsm,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaUpper,
PLASMA_enum, PlasmaNoTrans,
PLASMA_enum, PlasmaNonUnit,
double, (double)1.0,
PLASMA_desc, descA,
PLASMA_desc, descX,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.5925490657,
"avg_line_length": 37.8177777778,
"ext": "c",
"hexsha": "c19684a62d0b3922f431660a42a703fc17aa434f",
"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/dsungesv.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/dsungesv.c",
"max_line_length": 242,
"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/dsungesv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6609,
"size": 25527
} |
/* bst/gsl_bst_avl.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_BST_AVL_H__
#define __GSL_BST_AVL_H__
#include <gsl/gsl_math.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
#ifndef GSL_BST_AVL_MAX_HEIGHT
#define GSL_BST_AVL_MAX_HEIGHT 32
#endif
/* AVL node */
struct gsl_bst_avl_node
{
struct gsl_bst_avl_node *avl_link[2]; /* subtrees */
void *avl_data; /* pointer to data */
signed char avl_balance; /* balance factor */
};
/* tree data structure */
typedef struct
{
struct gsl_bst_avl_node *avl_root; /* tree's root */
gsl_bst_cmp_function *avl_compare; /* comparison function */
void *avl_param; /* extra argument to |avl_compare| */
const gsl_bst_allocator *avl_alloc; /* memory allocator */
size_t avl_count; /* number of items in tree */
unsigned long avl_generation; /* generation number */
} gsl_bst_avl_table;
/* AVL traverser structure */
typedef struct
{
const gsl_bst_avl_table *avl_table; /* tree being traversed */
struct gsl_bst_avl_node *avl_node; /* current node in tree */
struct gsl_bst_avl_node *avl_stack[GSL_BST_AVL_MAX_HEIGHT]; /* all the nodes above |avl_node| */
size_t avl_height; /* number of nodes in |avl_parent| */
unsigned long avl_generation; /* generation number */
} gsl_bst_avl_traverser;
__END_DECLS
#endif /* __GSL_BST_AVL_H__ */
| {
"alphanum_fraction": 0.6663957741,
"avg_line_length": 33.7123287671,
"ext": "h",
"hexsha": "6560777ce27a479a16e81f1842ea1e9d67cf318d",
"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": "115c007926ca80d51a37cdf887b5252338d8bc8d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "vinej/sml",
"max_forks_repo_path": "include/gsl/gsl_bst_avl.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "vinej/sml",
"max_issues_repo_path": "include/gsl/gsl_bst_avl.h",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "115c007926ca80d51a37cdf887b5252338d8bc8d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "vinej/sml",
"max_stars_repo_path": "include/gsl/gsl_bst_avl.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 594,
"size": 2461
} |
#ifndef COORDINATE_H_Y7FJINQO
#define COORDINATE_H_Y7FJINQO
#include <gsl/gsl>
#include <sens_loc/math/eigen_types.h>
#include <type_traits>
namespace sens_loc::math {
/// This enum allows to discrimate in which coordinate system or frame of
/// reference a vector lives. It is solely for code readability and correctness
/// evaluation.
enum class frame {
world, ///< 3D, Global, World Coordinate System. \f$(U, V, W)\f$.
camera, ///< 3D, Camera coordinate system, but the camera center is the
///< frame reference. \f$(X, Y, Z)\f$
sphere, ///< 3D, projection from image into space. \f$(X_s, Y_s, Z_s)\f$.
///< Equivalent to the direction of a lightray for a pixel.
image, ///< 2D, coordinate in an image as floating point. \f$(x, y)\f$
pixel, ///< 2D, usually a discrete coordinate system that refers to pixels
///< in an image. \f$(u, v)\f$
};
namespace detail {
/// Helper type-traits to examine if a reference frame is 2D. If its is not
/// 2D, the coordinate system is 3D.
/// \sa math::frame
template <frame Frame>
struct is_2d
: std::bool_constant<Frame == frame::image || Frame == frame::pixel> {};
/// Small helper class that holds the data for 2 dimensional coordinates.
/// \sa math::coordinate
template <typename Real>
struct coordinate2d {
static_assert(std::is_arithmetic_v<Real>);
coordinate2d()
: d(Real(0.), Real(0.)) {}
coordinate2d(Real x1, Real x2)
: d(x1, x2) {}
vec<Real, 2> d;
};
/// Small helper class that holds the data for 3 dimensional coordinates.
/// \sa math::coordinate
template <typename Real>
struct coordinate3d {
static_assert(std::is_arithmetic_v<Real>);
coordinate3d()
: d(Real(0.), Real(0.), Real(0.)) {}
coordinate3d(Real x1, Real x2, Real x3)
: d(x1, x2, x3) {}
vec<Real, 3> d;
};
} // namespace detail
/// This class is a strongly typed coordinate class to ensure the implemented
/// math does not mix up reference frames.
///
/// The overall goal of this slightly complicated construct is to increase
/// readability of the code **USING** this class and to improve correctness.
///
/// This class allows only access with the coordinate conventions for each
/// frame.
/// It prevents mixing different coordinates while assignment or other
/// operations and therefore forces conversion functions. Such conversions
/// are well defined through camera intrinsics for example.
///
/// There are helper typedefs, for easier writing:
/// \c pixel_coord<Real>, \c image_coord<Real>, \c sphere_coord<Real>,
/// \c camera_coord<Real> and \c world_coord<Real>.
///
/// \code
/// const pixel_coord<int> pixel(42, 32);
/// pixel.u(); // Accessing the u-coordinate for that pixel.
/// pixel.x(); // DOES NOT COMPILE - WRONG CONVENTION!
///
/// // Changing coordinate systems requires an explicit transformation, for
/// // example with the camera calibration as in this case.
/// const camera_models::pinhole<float> i;
/// const image_coord<float> transformed = i.transform_to_image(pixel);
/// transformed.x() // Accessing x-coordinate for that pixel.
/// // Same point but different coordinate system.
/// transformed.u() // DOES NOT COMPILE - WRONG CONVENTION!
///
/// // It is not possible to mix coordinates up.
/// pixel_coord<float> sub_pixel(42.42, 42.42);
/// image_coord<float> transformed = sub_pixel; // DOES NOT COMPILE
/// // TYPE MISSMATCH!!
/// \endcode
///
/// \tparam Real underlying type of the coordinates
/// \tparam Frame type of reference frame, results in either 2 or 3 dimensional
/// vectors. The vector data is inherited.
template <typename Real, frame Frame>
class coordinate
: private std::conditional_t<detail::is_2d<Frame>::value,
detail::coordinate2d<Real>,
detail::coordinate3d<Real>> {
static_assert(std::is_arithmetic_v<Real>,
"Arithmetic type for Real required!");
using base_class = std::conditional_t<detail::is_2d<Frame>::value,
detail::coordinate2d<Real>,
detail::coordinate3d<Real>>;
public:
using real = Real;
// Reuse constructors of baseclass
using base_class::base_class;
/// Calculate the euclidean norm for the coordinate.
/// \note This function is only enabled if the \p Real type is a floating
/// point number.
template <typename T = Real,
typename = std::enable_if_t<!std::is_integral_v<T>>>
[[nodiscard]] Real norm() const noexcept {
return base_class::d.norm();
}
/// Return the normalized vector of this coordinate.
/// \note This function is only enabled if the \p Real type is a floating
/// point number and the vector is in 3 dimensional space.
template <typename T = Real,
typename U = frame,
typename = std::enable_if_t<!std::is_integral_v<T> &&
!detail::is_2d<Frame>::value>>
[[nodiscard]] coordinate<Real, Frame> normalized() const noexcept {
const auto res = base_class::d.normalized();
return {res[0], res[1], res[2]};
}
/// Calculate the dot product with \p other.
[[nodiscard]] Real dot(const coordinate<Real, Frame>& other) const
noexcept {
return base_class::d.dot(other.d);
}
/// Calculate the cross product with \p other.
template <
typename T = frame,
typename = std::enable_if_t<!(Frame == T::pixel || Frame == T::image)>>
[[nodiscard]] coordinate<Real, Frame>
cross(const coordinate<Real, Frame>& other) const noexcept {
const auto res = base_class::d.cross(other.d);
return {res[0], res[1], res[2]};
}
// clang-format off
template <typename T = frame,
typename = std::enable_if_t<Frame == T::pixel>>
[[nodiscard]] Real u() const noexcept { return base_class::d[0]; }
template <typename T = frame,
typename = typename std::enable_if<Frame == T::pixel>>
[[nodiscard]] Real v() const noexcept { return base_class::d[1]; }
template <typename T = frame,
typename = typename std::enable_if_t<Frame == T::image>>
[[nodiscard]] Real x() const noexcept { return base_class::d[0]; }
template <typename T = frame,
typename = typename std::enable_if<Frame == T::image>>
[[nodiscard]] Real y() const noexcept { return base_class::d[1]; }
template <typename T = frame,
typename = typename std::enable_if_t<Frame == T::sphere>>
[[nodiscard]] Real Xs() const noexcept { return base_class::d[0]; }
template <typename T = frame,
typename = typename std::enable_if<Frame == T::sphere>>
[[nodiscard]] Real Ys() const noexcept { return base_class::d[1]; }
template <typename T = frame,
typename = typename std::enable_if<Frame == T::sphere>>
[[nodiscard]] Real Zs() const noexcept { return base_class::d[2]; }
template <typename T = frame,
typename = typename std::enable_if_t<Frame == T::camera>>
[[nodiscard]] Real X() const noexcept { return base_class::d[0]; }
template <typename T = frame,
typename = typename std::enable_if<Frame == T::camera>>
[[nodiscard]] Real Y() const noexcept { return base_class::d[1]; }
template <typename T = frame,
typename = typename std::enable_if<Frame == T::camera>>
[[nodiscard]] Real Z() const noexcept { return base_class::d[2]; }
template <typename T = frame,
typename = typename std::enable_if_t<Frame == T::world>>
[[nodiscard]] Real U() const noexcept { return base_class::d[0]; }
template <typename T = frame,
typename = typename std::enable_if<Frame == T::world>>
[[nodiscard]] Real V() const noexcept { return base_class::d[1]; }
template <typename T = frame,
typename = typename std::enable_if<Frame == T::world>>
[[nodiscard]] Real W() const noexcept { return base_class::d[2]; }
// clang-format on
coordinate<Real, Frame> operator-(const coordinate<Real, Frame>& p) const
noexcept {
coordinate<Real, Frame> res;
auto difference = base_class::d - p.d;
res.d = difference;
return res;
}
};
template <typename Real>
coordinate<Real, frame::camera>
operator*(Real factor, const coordinate<Real, frame::camera>& pt) noexcept {
static_assert(std::is_floating_point_v<Real>,
"Real must be a floating point type for scaling operations!");
coordinate<Real, frame::camera> result{factor * pt.X(), factor * pt.Y(),
factor * pt.Z()};
Ensures(std::abs(factor * pt.norm() - result.norm()) < Real(0.0001));
return result;
}
/// Scaling spherical coordinates results in camera coordinates.
template <typename Real>
coordinate<Real, frame::camera>
operator*(Real factor, const coordinate<Real, frame::sphere>& pt) noexcept {
static_assert(std::is_floating_point_v<Real>,
"Real must be a floating point type for scaling operations!");
coordinate<Real, frame::camera> result{factor * pt.Xs(), factor * pt.Ys(),
factor * pt.Zs()};
Ensures(std::abs(factor * pt.norm() - result.norm()) < Real(0.0001));
return result;
}
template <typename Real = int>
using pixel_coord = coordinate<Real, frame::pixel>;
template <typename Real = float>
using image_coord = coordinate<Real, frame::image>;
template <typename Real = float>
using sphere_coord = coordinate<Real, frame::sphere>;
template <typename Real = float>
using camera_coord = coordinate<Real, frame::camera>;
template <typename Real = float>
using world_coord = coordinate<Real, frame::world>;
} // namespace sens_loc::math
#endif /* end of include guard: COORDINATE_H_Y7FJINQO */
| {
"alphanum_fraction": 0.6295377901,
"avg_line_length": 40.1673306773,
"ext": "h",
"hexsha": "f2cd0cef1397027a3c08893bb8147e8214e7592b",
"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": "5c8338276565d846c07673e83f94f6841006872b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "JonasToth/depth-conversions",
"max_forks_repo_path": "src/include/sens_loc/math/coordinate.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"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": "JonasToth/depth-conversions",
"max_issues_repo_path": "src/include/sens_loc/math/coordinate.h",
"max_line_length": 80,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "JonasToth/depth-conversions",
"max_stars_repo_path": "src/include/sens_loc/math/coordinate.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z",
"num_tokens": 2396,
"size": 10082
} |
/* bspline/test.c
*
* Copyright (C) 2006, 2007, 2009 Brian Gough
* Copyright (C) 2008, 2011 Rhys Ulerich
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_nan.h>
void
test_bspline(gsl_bspline_workspace * bw, gsl_bspline_deriv_workspace * dbw)
{
gsl_vector *B;
gsl_matrix *dB;
size_t i, j;
size_t n = 100;
size_t ncoeffs = gsl_bspline_ncoeffs(bw);
size_t order = gsl_bspline_order(bw);
size_t nbreak = gsl_bspline_nbreak(bw);
double a = gsl_bspline_breakpoint(0, bw);
double b = gsl_bspline_breakpoint(nbreak - 1, bw);
B = gsl_vector_alloc(ncoeffs);
dB = gsl_matrix_alloc(ncoeffs, 1);
/* Ensure B-splines form a partition of unity */
for (i = 0; i < n; i++)
{
double xi = a + (b - a) * (i / (n - 1.0));
double sum = 0;
gsl_bspline_eval(xi, B, bw);
for (j = 0; j < ncoeffs; j++)
{
double Bj = gsl_vector_get(B, j);
int s = (Bj < 0 || Bj > 1);
gsl_test(s,
"basis-spline coefficient %u is in range [0,1] for x=%g",
j, xi);
sum += Bj;
}
gsl_test_rel(sum, 1.0, order * GSL_DBL_EPSILON,
"basis-spline order %u is normalized for x=%g", order,
xi);
}
/* Ensure B-splines 0th derivatives agree with regular evaluation */
for (i = 0; i < n; i++)
{
double xi = a + (b - a) * (i / (n - 1.0));
gsl_bspline_eval(xi, B, bw);
gsl_bspline_deriv_eval(xi, 0, dB, bw, dbw);
for (j = 0; j < ncoeffs; j++)
{
gsl_test_abs(gsl_matrix_get(dB, j, 0), gsl_vector_get(B, j),
GSL_DBL_EPSILON,
"b-spline order %d basis #%d evaluation and 0th derivative consistent for x=%g",
order, j, xi);
}
}
gsl_vector_free(B);
gsl_matrix_free(dB);
}
int
main(int argc, char **argv)
{
size_t order, breakpoints, i;
gsl_ieee_env_setup();
argc = 0; /* prevent warnings about unused parameters */
argv = 0;
for (order = 1; order < 10; order++)
{
for (breakpoints = 2; breakpoints < 100; breakpoints++)
{
double a = -1.23 * order, b = 45.6 * order;
gsl_bspline_workspace *bw = gsl_bspline_alloc(order, breakpoints);
gsl_bspline_deriv_workspace *dbw = gsl_bspline_deriv_alloc(order);
gsl_bspline_knots_uniform(a, b, bw);
test_bspline(bw, dbw);
gsl_bspline_deriv_free(dbw);
gsl_bspline_free(bw);
}
}
for (order = 1; order < 10; order++)
{
for (breakpoints = 2; breakpoints < 100; breakpoints++)
{
double a = -1.23 * order, b = 45.6 * order;
gsl_bspline_workspace *bw = gsl_bspline_alloc(order, breakpoints);
gsl_bspline_deriv_workspace *dbw = gsl_bspline_deriv_alloc(order);
gsl_vector *k = gsl_vector_alloc(breakpoints);
for (i = 0; i < breakpoints; i++)
{
double f, x;
f = sqrt(i / (breakpoints - 1.0));
x = (1 - f) * a + f * b;
gsl_vector_set(k, i, x);
};
gsl_bspline_knots(k, bw);
test_bspline(bw, dbw);
gsl_vector_free(k);
gsl_bspline_deriv_free(dbw);
gsl_bspline_free(bw);
}
}
/* Spot check known 0th, 1st, 2nd derivative
evaluations for a particular k = 2 case. */
{
size_t i, j; /* looping */
const double xloc[4] = { 0.0, 1.0, 6.0, 7.0};
const double deriv[4][3] =
{
{ -1.0/2.0, 1.0/2.0, 0.0 },
{ -1.0/2.0, 1.0/2.0, 0.0 },
{ 0.0, -1.0/5.0, 1.0/5.0 },
{ 0.0, -1.0/5.0, 1.0/5.0 }
};
gsl_bspline_workspace *bw = gsl_bspline_alloc(2, 3);
gsl_bspline_deriv_workspace *dbw = gsl_bspline_deriv_alloc(2);
gsl_matrix *dB = gsl_matrix_alloc(gsl_bspline_ncoeffs(bw),
gsl_bspline_order(bw) + 1);
gsl_vector *breakpts = gsl_vector_alloc(3);
gsl_vector_set(breakpts, 0, 0.0);
gsl_vector_set(breakpts, 1, 2.0);
gsl_vector_set(breakpts, 2, 7.0);
gsl_bspline_knots(breakpts, bw);
for (i = 0; i < 4; ++i) /* at each location */
{
/* Initialize dB with poison to ensure we overwrite it */
gsl_matrix_set_all(dB, GSL_NAN);
gsl_bspline_deriv_eval(xloc[i], gsl_bspline_order(bw), dB, bw, dbw);
for (j = 0; j < gsl_bspline_ncoeffs(bw) ; ++j)
{
/* check basis function 1st deriv */
gsl_test_abs(gsl_matrix_get(dB, j, 1), deriv[i][j], GSL_DBL_EPSILON,
"b-spline k=%d basis #%d derivative %d at x = %f",
gsl_bspline_order(bw), j, 1, xloc[i]);
}
for (j = 0; j < gsl_bspline_ncoeffs(bw); ++j)
{
/* check k order basis function has k-th deriv equal to 0 */
gsl_test_abs(gsl_matrix_get(dB, j, gsl_bspline_order(bw)), 0.0,
GSL_DBL_EPSILON,
"b-spline k=%d basis #%d derivative %d at x = %f",
gsl_bspline_order(bw), j, gsl_bspline_order(bw),
xloc[i]);
}
}
gsl_matrix_free(dB);
gsl_bspline_deriv_free(dbw);
gsl_bspline_free(bw);
gsl_vector_free(breakpts);
}
/* Spot check known 0th, 1st, 2nd derivative
evaluations for a particular k = 3 case. */
{
size_t i, j; /* looping */
const double xloc[5] = { 0.0, 5.0, 9.0, 12.0, 15.0 };
const double eval[5][6] =
{
{ 4./25., 69./100., 3./ 20. , 0. , 0. , 0. },
{ 0. , 4./21. , 143./210. , 9./70., 0. , 0. },
{ 0. , 0. , 3./ 10. , 7./10., 0. , 0. },
{ 0. , 0. , 0. , 3./4. , 1./4., 0. },
{ 0. , 0. , 0. , 1./3. , 5./9., 1./9. }
};
const double deriv[5][6] =
{
{ -4./25., 3./50., 1./ 10., 0. , 0. , 0. },
{ 0. , -2./21., 1./105., 3./35., 0. , 0. },
{ 0. , 0. , -1./5. , 1./ 5., 0. , 0. },
{ 0. , 0. , 0. , -1./ 6., 1./6. , 0. },
{ 0. , 0. , 0. , -1./ 9., 1./27., 2./27. }
};
const double deriv2[5][6] =
{
{ 2./25., -17./150., 1.0/30.0 , 0.0 , 0. , 0. },
{ 0. , 1./ 42., -11.0/210.0, 1.0/35.0, 0. , 0. },
{ 0. , 0. , 1.0/15.0 ,-11.0/90.0, 1./18. , 0. },
{ 0. , 0. , 0.0 , 1.0/54.0, -7./162., 2./81. },
{ 0. , 0. , 0.0 , 1.0/54.0, -7./162., 2./81. }
};
gsl_bspline_workspace *bw = gsl_bspline_alloc(3, 5);
gsl_bspline_deriv_workspace *dbw = gsl_bspline_deriv_alloc(3);
gsl_matrix *dB = gsl_matrix_alloc(gsl_bspline_ncoeffs(bw),
gsl_bspline_order(bw) + 1);
gsl_vector *breakpts = gsl_vector_alloc(5);
gsl_vector_set(breakpts, 0, -3.0);
gsl_vector_set(breakpts, 1, 2.0);
gsl_vector_set(breakpts, 2, 9.0);
gsl_vector_set(breakpts, 3, 12.0);
gsl_vector_set(breakpts, 4, 21.0);
gsl_bspline_knots(breakpts, bw);
for (i = 0; i < 5; ++i) /* at each location */
{
/* Initialize dB with poison to ensure we overwrite it */
gsl_matrix_set_all(dB, GSL_NAN);
gsl_bspline_deriv_eval(xloc[i], gsl_bspline_order(bw), dB, bw, dbw);
/* check basis function evaluation */
for (j = 0; j < gsl_bspline_ncoeffs(bw); ++j)
{
gsl_test_abs(gsl_matrix_get(dB, j, 0), eval[i][j], GSL_DBL_EPSILON,
"b-spline k=%d basis #%d derivative %d at x = %f",
gsl_bspline_order(bw), j, 0, xloc[i]);
}
/* check 1st derivative evaluation */
for (j = 0; j < gsl_bspline_ncoeffs(bw); ++j)
{
gsl_test_abs(gsl_matrix_get(dB, j, 1), deriv[i][j], GSL_DBL_EPSILON,
"b-spline k=%d basis #%d derivative %d at x = %f",
gsl_bspline_order(bw), j, 1, xloc[i]);
}
/* check 2nd derivative evaluation */
for (j = 0; j < gsl_bspline_ncoeffs(bw); ++j)
{
gsl_test_abs(gsl_matrix_get(dB, j, 2), deriv2[i][j], GSL_DBL_EPSILON,
"b-spline k=%d basis #%d derivative %d at x = %f",
gsl_bspline_order(bw), j, 2, xloc[i]);
}
}
gsl_matrix_free(dB);
gsl_bspline_deriv_free(dbw);
gsl_bspline_free(bw);
gsl_vector_free(breakpts);
}
/* Check Greville abscissae functionality on a non-uniform k=1 */
{
size_t i; /* looping */
/* Test parameters */
const size_t k = 1;
const double bpoint_data[] = { 0.0, 0.2, 0.5, 0.75, 1.0 };
const size_t nbreak = sizeof(bpoint_data)/sizeof(bpoint_data[0]);
/* Expected results */
const double abscissae_data[] = { 0.1, 0.35, 0.625, 0.875 };
const size_t nabscissae = sizeof(abscissae_data)/sizeof(abscissae_data[0]);
gsl_vector_const_view bpoints = gsl_vector_const_view_array(bpoint_data, nbreak);
gsl_bspline_workspace *w = gsl_bspline_alloc(k, nbreak);
gsl_bspline_knots((const gsl_vector *) &bpoints, w);
gsl_test_int(nabscissae, gsl_bspline_ncoeffs(w),
"b-spline k=%d number of abscissae", k);
for (i = 0; i < nabscissae; ++i)
{
gsl_test_abs(gsl_bspline_greville_abscissa(i, w), abscissae_data[i], 2*k*GSL_DBL_EPSILON,
"b-spline k=%d Greville abscissa #%d at x = %f", k, i, abscissae_data[i]);
}
gsl_bspline_free(w);
}
/* Check Greville abscissae functionality on a non-uniform k=2 */
{
size_t i; /* looping */
/* Test parameters */
const size_t k = 2;
const double bpoint_data[] = { 0.0, 0.2, 0.5, 0.75, 1.0 };
const size_t nbreak = sizeof(bpoint_data)/sizeof(bpoint_data[0]);
/* Expected results */
const double abscissae_data[] = { 0.0, 0.2, 0.5, 0.75, 1.0 };
const size_t nabscissae = sizeof(abscissae_data)/sizeof(abscissae_data[0]);
gsl_vector_const_view bpoints = gsl_vector_const_view_array(bpoint_data, nbreak);
gsl_bspline_workspace *w = gsl_bspline_alloc(k, nbreak);
gsl_bspline_knots((const gsl_vector *) &bpoints, w);
gsl_test_int(nabscissae, gsl_bspline_ncoeffs(w),
"b-spline k=%d number of abscissae", k);
for (i = 0; i < nabscissae; ++i)
{
gsl_test_abs(gsl_bspline_greville_abscissa(i, w), abscissae_data[i], 2*k*GSL_DBL_EPSILON,
"b-spline k=%d Greville abscissa #%d at x = %f", k, i, abscissae_data[i]);
}
gsl_bspline_free(w);
}
/* Check Greville abscissae functionality on non-uniform k=3 */
{
size_t i; /* looping */
/* Test parameters */
const size_t k = 3;
const double bpoint_data[] = { 0.0, 0.2, 0.5, 0.75, 1.0 };
const size_t nbreak = sizeof(bpoint_data)/sizeof(bpoint_data[0]);
/* Expected results */
const double abscissae_data[] = { 0.0, 1.0/10.0, 7.0/20.0,
5.0/ 8.0, 7.0/ 8.0, 1.0 };
const size_t nabscissae = sizeof(abscissae_data)/sizeof(abscissae_data[0]);
gsl_vector_const_view bpoints = gsl_vector_const_view_array(bpoint_data, nbreak);
gsl_bspline_workspace *w = gsl_bspline_alloc(k, nbreak);
gsl_bspline_knots((const gsl_vector *) &bpoints, w);
gsl_test_int(nabscissae, gsl_bspline_ncoeffs(w),
"b-spline k=%d number of abscissae", k);
for (i = 0; i < nabscissae; ++i)
{
gsl_test_abs(gsl_bspline_greville_abscissa(i, w), abscissae_data[i], 2*k*GSL_DBL_EPSILON,
"b-spline k=%d Greville abscissa #%d at x = %f", k, i, abscissae_data[i]);
}
gsl_bspline_free(w);
}
/* Check Greville abscissae functionality on non-uniform k=4 */
{
size_t i; /* looping */
/* Test parameters */
const size_t k = 4;
const double bpoint_data[] = { 0.0, 0.2, 0.5, 0.75, 1.0 };
const size_t nbreak = sizeof(bpoint_data)/sizeof(bpoint_data[0]);
/* Expected results */
const double abscissae_data[] = { 0.0, 1.0/15.0, 7.0/30.0, 29.0/60.0,
3.0/ 4.0, 11.0/12.0, 1.0 };
const size_t nabscissae = sizeof(abscissae_data)/sizeof(abscissae_data[0]);
gsl_vector_const_view bpoints = gsl_vector_const_view_array(bpoint_data, nbreak);
gsl_bspline_workspace *w = gsl_bspline_alloc(k, nbreak);
gsl_bspline_knots((const gsl_vector *) &bpoints, w);
gsl_test_int(nabscissae, gsl_bspline_ncoeffs(w),
"b-spline k=%d number of abscissae", k);
for (i = 0; i < nabscissae; ++i)
{
gsl_test_abs(gsl_bspline_greville_abscissa(i, w), abscissae_data[i], 2*k*GSL_DBL_EPSILON,
"b-spline k=%d Greville abscissa #%d at x = %f", k, i, abscissae_data[i]);
}
gsl_bspline_free(w);
}
/* Knots computed from prescribed Greville abscissae for k = 4 */
{
size_t i; /* looping */
/* Test parameters */
const size_t k = 4;
const double abscissae_data[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 };
const size_t nabscissae = sizeof(abscissae_data)/sizeof(abscissae_data[0]);
/* Expected results */
const double bpoint_data[] = { 1.0, 4.0, 4.0, 4.0, 7.0 };
const size_t nbreak = sizeof(bpoint_data)/sizeof(bpoint_data[0]);
/* Compute knots from Greville abscissae */
double abserr;
gsl_vector_const_view abscissae
= gsl_vector_const_view_array(abscissae_data, nabscissae);
gsl_bspline_workspace *w = gsl_bspline_alloc(k, nbreak);
gsl_bspline_knots_greville(&abscissae.vector, w, &abserr);
for (i = 0; i < nbreak; ++i)
{
gsl_test_abs(gsl_bspline_breakpoint(i,w), bpoint_data[i], GSL_DBL_EPSILON*50,
"b-spline k=%d knots_greville breakpoint #%d", k, i);
}
gsl_test_abs(abserr, 0.0, GSL_DBL_EPSILON*15,
"b-spline k=%d nbreak=%d knots_greville abserr", k, nbreak);
gsl_bspline_free(w);
}
/* Knots computed from prescribed Greville abscissae for k = 8 */
{
size_t i; /* looping */
/* Test parameters */
const size_t k = 8;
const double abscissae_data[] = { 1.0, 10.0/7, 13.0/7, 16.0/7, 22.0/7,
4.0, 34.0/7, 40.0/7, 43.0/7, 46.0/7, 7.0 };
const size_t nabscissae = sizeof(abscissae_data)/sizeof(abscissae_data[0]);
/* Expected results */
const double bpoint_data[] = { 1.0, 4.0, 4.0, 4.0, 7.0 };
const size_t nbreak = sizeof(bpoint_data)/sizeof(bpoint_data[0]);
/* Compute knots from Greville abscissae */
double abserr;
gsl_vector_const_view abscissae
= gsl_vector_const_view_array(abscissae_data, nabscissae);
gsl_bspline_workspace *w = gsl_bspline_alloc(k, nbreak);
gsl_bspline_knots_greville(&abscissae.vector, w, &abserr);
for (i = 0; i < nbreak; ++i)
{
gsl_test_abs(gsl_bspline_breakpoint(i,w), bpoint_data[i], GSL_DBL_EPSILON*50,
"b-spline k=%d knots_greville breakpoint #%d", k, i);
}
gsl_test_abs(abserr, 0.0, GSL_DBL_EPSILON*15,
"b-spline k=%d nbreak=%d knots_greville abserr", k, nbreak);
gsl_bspline_free(w);
}
/* Knots computed from prescribed Greville abscissae for k = 2 */
/* Not an interesting calculation but checks the k = 2 edge case */
{
size_t i; /* looping */
/* Test parameters */
const size_t k = 2;
const double abscissae_data[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 };
const size_t nabscissae = sizeof(abscissae_data)/sizeof(abscissae_data[0]);
/* Expected results */
const double bpoint_data[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 };
const size_t nbreak = sizeof(bpoint_data)/sizeof(bpoint_data[0]);
/* Compute knots from Greville abscissae */
double abserr;
gsl_vector_const_view abscissae
= gsl_vector_const_view_array(abscissae_data, nabscissae);
gsl_bspline_workspace *w = gsl_bspline_alloc(k, nbreak);
gsl_bspline_knots_greville(&abscissae.vector, w, &abserr);
for (i = 0; i < nbreak; ++i)
{
gsl_test_abs(gsl_bspline_breakpoint(i,w), bpoint_data[i], GSL_DBL_EPSILON,
"b-spline k=%d knots_greville breakpoint #%d", k, i);
}
gsl_test_abs(abserr, 0.0, GSL_DBL_EPSILON,
"b-spline k=%d nbreak=%d knots_greville abserr", k, nbreak);
gsl_bspline_free(w);
}
/* Knots computed from prescribed abscissae for edge case when nbreak = 2 */
{
size_t i; /* looping */
/* Test parameters */
const size_t k = 4;
double abscissae_data[] = { 1.0, 3.0, 5.0, 7.0 };
const size_t nabscissae = sizeof(abscissae_data)/sizeof(abscissae_data[0]);
/* Expected results */
const double bpoint_data[] = { 1.0, 7.0 };
const size_t nbreak = sizeof(bpoint_data)/sizeof(bpoint_data[0]);
/* Compute knots from Greville abscissae where abscissae are recoverable */
double abserr;
gsl_vector_view abscissae
= gsl_vector_view_array(abscissae_data, nabscissae);
gsl_bspline_workspace *w = gsl_bspline_alloc(k, nbreak);
gsl_bspline_knots_greville(&abscissae.vector, w, &abserr);
/* Check recovery of breakpoints and abscissae */
for (i = 0; i < nbreak; ++i)
{
gsl_test_abs(gsl_bspline_breakpoint(i,w), bpoint_data[i], GSL_DBL_EPSILON,
"b-spline k=%d knots_greville breakpoint #%d", k, i);
}
gsl_test_abs(abserr, 0.0, GSL_DBL_EPSILON,
"b-spline k=%d nbreak=%d knots_greville abserr", k, nbreak);
/* Modify interior abscissae so they cannot be recovered with nbreak = 2 */
/* Then recompute breakpoints and check that abserr is as expected */
abscissae_data[1] -= 1;
abscissae_data[2] += 1;
gsl_bspline_knots_greville(&abscissae.vector, w, &abserr);
for (i = 0; i < nbreak; ++i)
{
gsl_test_abs(gsl_bspline_breakpoint(i,w), bpoint_data[i], GSL_DBL_EPSILON,
"b-spline k=%d knots_greville breakpoint #%d", k, i);
}
gsl_test_abs(abserr, /* deliberate error */ 2.0, GSL_DBL_EPSILON,
"b-spline k=%d nbreak=%d knots_greville abserr large", k, nbreak);
gsl_bspline_free(w);
}
exit(gsl_test_summary());
}
| {
"alphanum_fraction": 0.5767386091,
"avg_line_length": 36.3984819734,
"ext": "c",
"hexsha": "e214beca2a4011e4d29d8eccb423cc19aa974f91",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z",
"max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ruslankuzmin/julia",
"max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/bspline/test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "ruslankuzmin/julia",
"max_issues_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/bspline/test.c",
"max_line_length": 103,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/bspline/test.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": 6366,
"size": 19182
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C header for functions windowing and computing FFT/IFFT of time/frequency series.
*
*/
#ifndef __GENERATEWAVEFORM_H__
#define __GENERATEWAVEFORM_H__ 1
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#include "struct.h"
#include "waveform.h"
#include "EOBNRv2HMROMstruct.h"
#include "EOBNRv2HMROM.h"
#include "fft.h"
/********************************** Structures ******************************************/
typedef enum GenWavetag {
hlm,
h22TD,
hphcFD,
hphcTD
} GenWavetag;
/* Parameters for the generation of a LISA waveform (in the form of a list of modes) */
typedef struct tagGenWaveParams {
double tRef; /* reference time (s) - GPS time at the frequency representing coalescence */
double phiRef; /* reference phase (rad) - phase at the frequency representing coalescence (or at fRef if specified) */
double fRef; /* reference frequency at which phiRef is set (Hz, default 0 which is interpreted as Mf=0.14) */
double m1; /* mass of companion 1 (solar masses, default 2e6) */
double m2; /* mass of companion 2 (solar masses, default 1e6) */
double distance; /* distance of source (Mpc, default 1e3) */
double inclination; /* inclination of source (rad, default pi/3) */
double minf; /* Minimal frequency, ignore if 0 (Hz, default=0) - will use first frequency covered by the ROM if higher */
double maxf; /* Maximal frequency, ignore if 0 (Hz, default=0) - will use last frequency covered by the ROM if lower */
double deltatobs; /* Observation duration (years, default=2) */
int tagextpn; /* Tag to allow PN extension of the waveform at low frequencies */
double Mfmatch; /* When PN extension allowed, geometric matching frequency: will use ROM above this value. If <=0, use ROM down to the lowest covered frequency */
int nbmode; /* Number of modes to generate (starting with 22) - defaults to 1 (22 only) */
int taggenwave; /* Tag selecting the desired output format */
double f1windowbeg; /* If generating h22TD/hphcTD, start frequency for windowing at the beginning - set to 0 to ignore and use max(fstartobs, fLowROM, minf), where fLowROM is either the lowest frequency covered by the ROM or simply minf if PN extension is used (Hz, default=0) */
double f2windowbeg; /* If generating h22TD/hphcTD, stop frequency for windowing at the beginning - set to 0 to ignore and use 1.1*f1windowbeg (Hz, default=0) */
double f1windowend; /* If generating h22TD/hphcTD, start frequency for windowing at the end - set to 0 to ignore and use 0.995*f2windowend (Hz, default=0) */
double f2windowend; /* If generating h22TD/hphcTD, stop frequency for windowing at the end - set to 0 to ignore and use min(maxf, fHighROM), where fHighROM is the highest frequency covered by the ROM (Hz, default=0) */
int tagh22fromfile; /* Tag choosing wether to load h22 FD downsampled Amp/Phase from file (default 0) */
int nsamplesinfile; /* Number of lines of inputs file */
int binaryin; /* Tag for loading the data in gsl binary form instead of text (default false) */
char indir[256]; /* Input directory */
char infile[256]; /* Input file name */
int binaryout; /* Tag for outputting the data in gsl binary form instead of text (default 0) */
char outdir[256]; /* Path for the output directory */
char outfile[256]; /* Path for the output file */
} GenWaveParams;
#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif
#endif /* _GENERATEWAVEFORM_H */
| {
"alphanum_fraction": 0.6669815777,
"avg_line_length": 47.5730337079,
"ext": "h",
"hexsha": "78a4fabb92263cc8acde03f1267dfe024e219e6b",
"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": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "EOBNRv2HMROM/GenerateWaveform.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "titodalcanton/flare",
"max_issues_repo_path": "EOBNRv2HMROM/GenerateWaveform.h",
"max_line_length": 288,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "EOBNRv2HMROM/GenerateWaveform.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1094,
"size": 4234
} |
#include <Python.h>
#include <arrayobject.h>
#include <time.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_sf_erf.h>
static PyObject* g_engineError;
static gsl_rng* g_rng;
/** low level helpers **/
/** numpy helpers **/
/**
* Check that PyArrayObject is a double (Float) type and a vector
* return 1 if an error and raise exception.
*/
static int not_doublevector(PyArrayObject *vec) {
if (vec->descr->type_num != NPY_DOUBLE || vec->nd != 1) {
PyErr_SetString(PyExc_ValueError,
"In not_doublevector: array must be of type Float and 1 dimensional (n).");
return 1;
}
return 0;
}
static double lognormal(double m, double stddev) {
/*
m: mean of x
stddev: std of x
*/
return gsl_ran_lognormal(g_rng,
log(m) - 0.5 * log(1.0 + (stddev*stddev)/(m*m)),
sqrt(log((stddev*stddev)/(m*m) + 1)) );
}
/** python callables **/
static PyObject* engine_bivariate_gaussian(PyObject *self, PyObject *args) {
float sx, sy;
if (!PyArg_ParseTuple(args, "ff", &sx, &sy))
return NULL;
double x, y;
gsl_ran_bivariate_gaussian(g_rng, sx, sy, 0.0, &x, &y);
return Py_BuildValue("(ff)", (float)x, (float)y);
}
static PyObject* engine_beta(PyObject *self, PyObject *args) {
float a = 0;
float b = 0;
if (!PyArg_ParseTuple(args, "ff", &a, &b))
return NULL;
double sample = (float)gsl_ran_beta(g_rng, a, b);
return Py_BuildValue("f", (float)sample);
}
static PyObject* engine_lognormal(PyObject *self, PyObject *args) {
float m = 0;
float stddev = 0;
if (!PyArg_ParseTuple(args, "ff", &m, &stddev))
return NULL;
return Py_BuildValue("f", (float)lognormal(m, stddev));
}
static PyObject* engine_lognormal_cdf(PyObject *self, PyObject *args) {
float m = 0;
float stddev = 0;
float x = 0;
if (!PyArg_ParseTuple(args, "fff", &x, &m, &stddev))
return NULL;
double m2 = log(m) - 0.5 * log(1.0 + (stddev*stddev)/(m*m));
double s2 = sqrt(log((stddev*stddev)/(m*m) + 1));
return Py_BuildValue("f", (float)gsl_cdf_lognormal_P(x, m2, s2));
}
static PyObject* engine_lognormal_cdf_inv(PyObject *self, PyObject *args) {
float m = 0;
float stddev = 0;
float p = 0;
if (!PyArg_ParseTuple(args, "fff", &p, &m, &stddev))
return NULL;
double m2 = log(m) - 0.5 * log(1.0 + (stddev*stddev)/(m*m));
double s2 = sqrt(log((stddev*stddev)/(m*m) + 1));
return Py_BuildValue("f", (float)gsl_cdf_lognormal_Pinv(p, m2, s2));
}
static PyObject* engine_percentileofscore(PyObject *self, PyObject *args) {
// python: engine.percentileofscore([scores], score)
double score = 0;
PyObject* listObj;
if (!PyArg_ParseTuple(args, "O!d", &PyList_Type, &listObj, &score))
return NULL;
// loop through python list of doubles, counting scores less than or equal to score
int arrsz = PyList_Size(listObj);
if (arrsz == 0)
return NULL;
int i;
int count=0;
for (i=0; i<arrsz; i++) {
double aScore = PyFloat_AsDouble(PyList_GetItem(listObj, i));
if (aScore <= score)
count++;
}
float percentile = count / (float)arrsz;
return Py_BuildValue("f", percentile);
}
static PyObject* engine_percentileofscore_array(PyObject *self, PyObject *args) {
// python: engine.percentileofscore(numpy.array[scores], score)
double score = 0;
PyArrayObject* arrayObj;
if (!PyArg_ParseTuple(args, "O!d", &PyArray_Type, &arrayObj, &score))
return NULL;
if (not_doublevector(arrayObj)) {
printf("invalid type!\n");
return NULL;
}
// loop through python list of doubles, counting scores less than or equal to score
double* cin = (double *)arrayObj->data;
int arrsz = arrayObj->dimensions[0];
if (arrsz == 0)
return NULL;
int i;
int count=0;
for (i=0; i<arrsz; i++) {
double aScore = cin[i];
printf("score: %lf\n", aScore);
if (aScore <= score)
count++;
}
float percentile = count / (float)arrsz;
return Py_BuildValue("f", percentile);
}
static PyObject* engine_erf(PyObject *self, PyObject *args) {
float x = 0;
if (!PyArg_ParseTuple(args, "f", &x))
return NULL;
double sample = gsl_sf_erf(x);
return Py_BuildValue("f", (float)sample);
}
static PyObject* engine_poisson(PyObject *self, PyObject *args) {
float mean = 0;
if (!PyArg_ParseTuple(args, "f", &mean))
return NULL;
unsigned int sample = gsl_ran_poisson(g_rng, mean);
return Py_BuildValue("i", (int)sample);
}
static PyObject* engine_seed(PyObject *self, PyObject *args) {
long seed = 0;
if (!PyArg_ParseTuple(args, "l", &seed))
return NULL;
gsl_rng_set(g_rng, seed);
Py_INCREF(Py_None);
return Py_None;
}
/** debris module **/
static PyObject* debris_generate_item(PyObject* self, PyObject* args) {
int typeid;
float V, xord, yord, flighttime_mean, flighttime_stddev, cdav, mass_mean, mass_stddev, fa_mean, fa_stddev;
if (!PyArg_ParseTuple(args, "fffffifffff",
&V,
&xord, &yord,
&flighttime_mean,
&flighttime_stddev,
&typeid,
&cdav,
&mass_mean, &mass_stddev,
&fa_mean, &fa_stddev))
return NULL;
double mass = lognormal(mass_mean, mass_stddev);
double fa = lognormal(fa_mean, fa_stddev);
double flight_time = lognormal(flighttime_mean, flighttime_stddev);
double t = 9.81 * flight_time / V;
double k = (1.2 * V * V) / (2 * 9.81 * (mass/fa) );
double flight_distance=0;
switch (typeid) {
case 0:
flight_distance = (V*V/9.81) * (1.0/k) * (0.2060*pow(k*t, 2) + 0.011*k*t);
break;
case 1:
flight_distance = (V*V/9.81) * (1.0/k) * (0.072*pow(k*t, 2) + 0.3456*k*t);
break;
case 2:
flight_distance = (V*V/9.81) * (1.0/k) * (0.0723*pow(k*t, 2) + 0.2376*k*t);
break;
}
// Sample Impact Location
double sigma_x = flight_distance / 3.0;
double sigma_y = flight_distance / 12.0;
double x, y;
gsl_ran_bivariate_gaussian(g_rng, sigma_x, sigma_y, 1.0, &x, &y);
// translate to footprint coords
double item_X = xord - flight_distance + x;
double item_Y = yord + y;
// calculate momentum
double pa = 1.2;
double b = sqrt( (pa * cdav * fa) / (mass) );
double beta_mean = 1 - exp(-b * sqrt(flight_distance));
double dispersion = 0;
if (beta_mean == 1.0) {
dispersion = 1/beta_mean + 3.0;
beta_mean -= 0.001;
}
else if (beta_mean == 0) {
dispersion = 4.0;
}
else {
dispersion = fmax(1.0/beta_mean, 1.0/(1.0 - beta_mean)) + 3.0;
}
double beta_a = beta_mean * dispersion;
double beta_b = dispersion * (1 - beta_mean);
double sampled = gsl_ran_beta(g_rng, beta_a, beta_b);
float item_momentum = (float)(sampled * V * mass);
/* output: (item_momentum, item_X, item_Y)
*/
return Py_BuildValue("(fff)", item_momentum, item_X, item_Y);
}
/** Module setup **/
static PyMethodDef EngineMethods[] = {
{"beta", engine_beta, METH_VARARGS, "Draw from Beta using given a,b"},
{"lognormal", engine_lognormal, METH_VARARGS, "Draw from Lognormal using given mean, cov"},
{"lognormal_cdf", engine_lognormal_cdf, METH_VARARGS, "lognormal cdf"},
{"lognormal_cdf_inv", engine_lognormal_cdf_inv, METH_VARARGS, "lognormal inv cdf"},
{"erf", engine_erf, METH_VARARGS, "erf"},
{"bivariate_gaussian", engine_bivariate_gaussian, METH_VARARGS, "Bivariate normal distribution"},
{"poisson", engine_poisson, METH_VARARGS, "Draw from Poisson using given mean"},
{"percentileofscore", engine_percentileofscore, METH_VARARGS, "Return a quantile value of sorted_data"},
{"percentileofscore_array", engine_percentileofscore_array, METH_VARARGS, "Return a quantile value of sorted_data"},
{"seed", engine_seed, METH_VARARGS, "Set random number seed"},
{"debris_generate_item", debris_generate_item, METH_VARARGS, "Generate debris item for source"},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC initengine(void) {
PyObject* m = Py_InitModule("engine", EngineMethods);
if (m == NULL)
return;
import_array();
g_engineError = PyErr_NewException("engine.error", NULL, NULL);
Py_INCREF(g_engineError);
PyModule_AddObject(m, "error", g_engineError);
// setup GSL random number generators
const gsl_rng_type* T;
gsl_rng_env_setup();
T = gsl_rng_default;
g_rng = gsl_rng_alloc(T);
gsl_rng_set(g_rng, (long)time(NULL));
}
| {
"alphanum_fraction": 0.6792057227,
"avg_line_length": 29.4836363636,
"ext": "c",
"hexsha": "33da6ae6b92cfb55b96c09ce522d836432d47495",
"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/engine.c",
"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/engine.c",
"max_line_length": 117,
"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/engine.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2509,
"size": 8108
} |
#ifndef REMESHER_GSL_HELPERS_HEADER
#define REMESHER_GSL_HELPERS_HEADER
#include <iostream>
#include <iomanip>
#include <string>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
namespace GSL
{
void
pretty_print_matrix (gsl_matrix* m, std::string const& name)
{
std::cout << name << " = [";
for (std::size_t i = 0; i < m->size2; ++i)
{
if (i != 0) std::cout << ";" << std::endl << " ";
for (std::size_t j = 0; j < m->size1; ++j)
{
if (j != 0) std::cout << ", ";
std::cout << std::setw(6) << std::fixed << std::setprecision(2)
<< gsl_matrix_get(m, i, j);
}
}
std::cout << "];" << std::endl;
}
void
pretty_print_vector (gsl_vector* v, std::string const& name)
{
std::cout << name << " = [";
for (std::size_t i = 0; i < v->size; ++i)
{
if (i != 0) std::cout << "; ";
std::cout << std::setw(6) << std::fixed << std::setprecision(2)
<< gsl_vector_get(v, i);
}
std::cout << "];" << std::endl;
}
}
#endif /* REMESHER_GSL_HELPERS_HEADER */
| {
"alphanum_fraction": 0.5222222222,
"avg_line_length": 24,
"ext": "h",
"hexsha": "394853f562fe52e117415e47b6854f2be1e0494e",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-05-31T14:43:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-22T19:16:01.000Z",
"max_forks_repo_head_hexsha": "ec4a001b3082ba4079191ca8aae37be8e790aac2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jjt20/scripts",
"max_forks_repo_path": "remesher/libremesh/gslhelpers.h",
"max_issues_count": 29,
"max_issues_repo_head_hexsha": "ec4a001b3082ba4079191ca8aae37be8e790aac2",
"max_issues_repo_issues_event_max_datetime": "2020-09-17T06:06:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-08-20T15:22:03.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jjt20/scripts",
"max_issues_repo_path": "remesher/libremesh/gslhelpers.h",
"max_line_length": 71,
"max_stars_count": 24,
"max_stars_repo_head_hexsha": "ec4a001b3082ba4079191ca8aae37be8e790aac2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jjt20/scripts",
"max_stars_repo_path": "remesher/libremesh/gslhelpers.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-05T10:24:44.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-05-16T01:49:23.000Z",
"num_tokens": 356,
"size": 1080
} |
/* gmres.c
*
* Copyright (C) 2014 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_spmatrix.h>
#include <gsl/gsl_spblas.h>
#include <gsl/gsl_splinalg.h>
/*
* The code in this module is based on the Householder GMRES
* algorithm described in
*
* [1] H. F. Walker, Implementation of the GMRES method using
* Householder transformations, SIAM J. Sci. Stat. Comput.
* 9(1), 1988.
*
* [2] Y. Saad, Iterative methods for sparse linear systems,
* 2nd edition, SIAM, 2003.
*/
typedef struct
{
size_t n; /* size of linear system */
size_t m; /* dimension of Krylov subspace K_m */
gsl_vector *r; /* residual vector r = b - A*x */
gsl_matrix *H; /* Hessenberg matrix n-by-(m+1) */
gsl_vector *tau; /* householder scalars */
gsl_vector *y; /* least squares rhs and solution vector */
double *c; /* Givens rotations */
double *s;
double normr; /* residual norm ||r|| */
} gmres_state_t;
static void gmres_free(void *vstate);
static int gmres_iterate(const gsl_spmatrix *A, const gsl_vector *b,
const double tol, gsl_vector *x, void *vstate);
/*
gmres_alloc()
Allocate a GMRES workspace for solving an n-by-n system A x = b
Inputs: n - size of system
krylov_m - size of Krylov subspace (ie: number of inner iterations)
if this parameter is 0, the value GSL_MIN(n,10) is
used
Return: pointer to workspace
*/
static void *
gmres_alloc(const size_t n, const size_t m)
{
gmres_state_t *state;
if (n == 0)
{
GSL_ERROR_NULL("matrix dimension n must be a positive integer",
GSL_EINVAL);
}
state = calloc(1, sizeof(gmres_state_t));
if (!state)
{
GSL_ERROR_NULL("failed to allocate gmres state", GSL_ENOMEM);
}
state->n = n;
/* compute size of Krylov subspace */
if (m == 0)
state->m = GSL_MIN(n, 10);
else
state->m = GSL_MIN(n, m);
state->r = gsl_vector_alloc(n);
if (!state->r)
{
gmres_free(state);
GSL_ERROR_NULL("failed to allocate r vector", GSL_ENOMEM);
}
state->H = gsl_matrix_alloc(n, state->m + 1);
if (!state->H)
{
gmres_free(state);
GSL_ERROR_NULL("failed to allocate H matrix", GSL_ENOMEM);
}
state->tau = gsl_vector_alloc(state->m + 1);
if (!state->tau)
{
gmres_free(state);
GSL_ERROR_NULL("failed to allocate tau vector", GSL_ENOMEM);
}
state->y = gsl_vector_alloc(state->m + 1);
if (!state->y)
{
gmres_free(state);
GSL_ERROR_NULL("failed to allocate y vector", GSL_ENOMEM);
}
state->c = malloc(state->m * sizeof(double));
state->s = malloc(state->m * sizeof(double));
if (!state->c || !state->s)
{
gmres_free(state);
GSL_ERROR_NULL("failed to allocate Givens vectors", GSL_ENOMEM);
}
state->normr = 0.0;
return state;
} /* gmres_alloc() */
static void
gmres_free(void *vstate)
{
gmres_state_t *state = (gmres_state_t *) vstate;
if (state->r)
gsl_vector_free(state->r);
if (state->H)
gsl_matrix_free(state->H);
if (state->tau)
gsl_vector_free(state->tau);
if (state->y)
gsl_vector_free(state->y);
if (state->c)
free(state->c);
if (state->s)
free(state->s);
free(state);
} /* gmres_free() */
/*
gmres_iterate()
Solve A*x = b using GMRES algorithm
Inputs: A - sparse square matrix
b - right hand side vector
tol - stopping tolerance (see below)
x - (input/output) on input, initial estimate x_0;
on output, solution vector
work - workspace
Return:
GSL_SUCCESS if converged to solution (solution stored in x). In
this case the following will be true:
||b - A*x|| <= tol * ||b||
GSL_CONTINUE if not yet converged; in this case x contains the
most recent solution vector and calling this function more times
with the input x could result in convergence (ie: restarted GMRES)
Notes:
1) Based on algorithm 2.2 of (Walker, 1998 [1]) and algorithm 6.10 of
(Saad, 2003 [2])
2) On output, work->normr contains ||b - A*x||
*/
static int
gmres_iterate(const gsl_spmatrix *A, const gsl_vector *b,
const double tol, gsl_vector *x,
void *vstate)
{
const size_t N = A->size1;
gmres_state_t *state = (gmres_state_t *) vstate;
if (N != A->size2)
{
GSL_ERROR("matrix must be square", GSL_ENOTSQR);
}
else if (N != b->size)
{
GSL_ERROR("matrix does not match right hand side", GSL_EBADLEN);
}
else if (N != x->size)
{
GSL_ERROR("matrix does not match solution vector", GSL_EBADLEN);
}
else if (N != state->n)
{
GSL_ERROR("matrix does not match workspace", GSL_EBADLEN);
}
else
{
int status = GSL_SUCCESS;
const size_t maxit = state->m;
const double normb = gsl_blas_dnrm2(b); /* ||b|| */
const double reltol = tol * normb; /* tol*||b|| */
double normr; /* ||r|| */
size_t m, k;
double tau; /* householder scalar */
gsl_matrix *H = state->H; /* Hessenberg matrix */
gsl_vector *r = state->r; /* residual vector */
gsl_vector *w = state->y; /* least squares RHS */
gsl_matrix_view Rm; /* R_m = H(1:m,2:m+1) */
gsl_vector_view ym; /* y(1:m) */
gsl_vector_view h0 = gsl_matrix_column(H, 0);
/*
* The Hessenberg matrix will have the following structure:
*
* H = [ ||r_0|| | v_1 v_2 ... v_m ]
* [ u_1 | u_2 u_3 ... u_{m+1} ]
*
* where v_j are the orthonormal vectors spanning the Krylov
* subpsace of length j + 1 and u_{j+1} are the householder
* vectors of length n - j - 1.
* In fact, u_{j+1} has length n - j since u_{j+1}[0] = 1,
* but this 1 is not stored.
*/
gsl_matrix_set_zero(H);
/* Step 1a: compute r = b - A*x_0 */
gsl_vector_memcpy(r, b);
gsl_spblas_dgemv(CblasNoTrans, -1.0, A, x, 1.0, r);
/* Step 1b */
gsl_vector_memcpy(&h0.vector, r);
tau = gsl_linalg_householder_transform(&h0.vector);
/* store tau_1 */
gsl_vector_set(state->tau, 0, tau);
/* initialize w (stored in state->y) */
gsl_vector_set_zero(w);
gsl_vector_set(w, 0, gsl_vector_get(&h0.vector, 0));
for (m = 1; m <= maxit; ++m)
{
size_t j = m - 1; /* C indexing */
double c, s; /* Givens rotation */
/* v_m */
gsl_vector_view vm = gsl_matrix_column(H, m);
/* v_m(m:end) */
gsl_vector_view vv = gsl_vector_subvector(&vm.vector, j, N - j);
/* householder vector u_m for projection P_m */
gsl_vector_view um = gsl_matrix_subcolumn(H, j, j, N - j);
/* Step 2a: form v_m = P_m e_m = e_m - tau_m w_m */
gsl_vector_set_zero(&vm.vector);
gsl_vector_memcpy(&vv.vector, &um.vector);
tau = gsl_vector_get(state->tau, j); /* tau_m */
gsl_vector_scale(&vv.vector, -tau);
gsl_vector_set(&vv.vector, 0, 1.0 - tau);
/* Step 2a: v_m <- P_1 P_2 ... P_{m-1} v_m */
for (k = j; k > 0 && k--; )
{
gsl_vector_view uk =
gsl_matrix_subcolumn(H, k, k, N - k);
gsl_vector_view vk =
gsl_vector_subvector(&vm.vector, k, N - k);
tau = gsl_vector_get(state->tau, k);
gsl_linalg_householder_hv(tau, &uk.vector, &vk.vector);
}
/* Step 2a: v_m <- A*v_m */
gsl_spblas_dgemv(CblasNoTrans, 1.0, A, &vm.vector, 0.0, r);
gsl_vector_memcpy(&vm.vector, r);
/* Step 2a: v_m <- P_m ... P_1 v_m */
for (k = 0; k <= j; ++k)
{
gsl_vector_view uk = gsl_matrix_subcolumn(H, k, k, N - k);
gsl_vector_view vk = gsl_vector_subvector(&vm.vector, k, N - k);
tau = gsl_vector_get(state->tau, k);
gsl_linalg_householder_hv(tau, &uk.vector, &vk.vector);
}
/* Steps 2c,2d: find P_{m+1} and set v_m <- P_{m+1} v_m */
if (m < N)
{
/* householder vector u_{m+1} for projection P_{m+1} */
gsl_vector_view ump1 = gsl_matrix_subcolumn(H, m, m, N - m);
tau = gsl_linalg_householder_transform(&ump1.vector);
gsl_vector_set(state->tau, j + 1, tau);
}
/* Step 2e: v_m <- J_{m-1} ... J_1 v_m */
for (k = 0; k < j; ++k)
{
gsl_linalg_givens_gv(&vm.vector, k, k + 1,
state->c[k], state->s[k]);
}
if (m < N)
{
/* Step 2g: find givens rotation J_m for v_m(m:m+1) */
gsl_linalg_givens(gsl_vector_get(&vm.vector, j),
gsl_vector_get(&vm.vector, j + 1),
&c, &s);
/* store givens rotation for later use */
state->c[j] = c;
state->s[j] = s;
/* Step 2h: v_m <- J_m v_m */
gsl_linalg_givens_gv(&vm.vector, j, j + 1, c, s);
/* Step 2h: w <- J_m w */
gsl_linalg_givens_gv(w, j, j + 1, c, s);
}
/*
* Step 2i: R_m = [ R_{m-1}, v_m ] - already taken care
* of due to our memory storage scheme
*/
/* Step 2j: check residual w_{m+1} for convergence */
normr = fabs(gsl_vector_get(w, j + 1));
if (normr <= reltol)
{
/*
* method has converged, break out of loop to compute
* update to solution vector x
*/
break;
}
}
/*
* At this point, we have either converged to a solution or
* completed all maxit iterations. In either case, compute
* an update to the solution vector x and test again for
* convergence.
*/
/* rewind m if we exceeded maxit iterations */
if (m > maxit)
m--;
/* Step 3a: solve triangular system R_m y_m = w, in place */
Rm = gsl_matrix_submatrix(H, 0, 1, m, m);
ym = gsl_vector_subvector(w, 0, m);
gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit,
&Rm.matrix, &ym.vector);
/*
* Step 3b: update solution vector x; the loop below
* uses a different but equivalent formulation from
* Saad, algorithm 6.10, step 14; store Krylov projection
* V_m y_m in 'r'
*/
gsl_vector_set_zero(r);
for (k = m; k > 0 && k--; )
{
double ymk = gsl_vector_get(&ym.vector, k);
gsl_vector_view uk = gsl_matrix_subcolumn(H, k, k, N - k);
gsl_vector_view rk = gsl_vector_subvector(r, k, N - k);
/* r <- n_k e_k + r */
gsl_vector_set(r, k, gsl_vector_get(r, k) + ymk);
/* r <- P_k r */
tau = gsl_vector_get(state->tau, k);
gsl_linalg_householder_hv(tau, &uk.vector, &rk.vector);
}
/* x <- x + V_m y_m */
gsl_vector_add(x, r);
/* compute new residual r = b - A*x */
gsl_vector_memcpy(r, b);
gsl_spblas_dgemv(CblasNoTrans, -1.0, A, x, 1.0, r);
normr = gsl_blas_dnrm2(r);
if (normr <= reltol)
status = GSL_SUCCESS; /* converged */
else
status = GSL_CONTINUE; /* not yet converged */
/* store residual norm */
state->normr = normr;
return status;
}
} /* gmres_iterate() */
static double
gmres_normr(const void *vstate)
{
const gmres_state_t *state = (const gmres_state_t *) vstate;
return state->normr;
} /* gmres_normr() */
static const gsl_splinalg_itersolve_type gmres_type =
{
"gmres",
&gmres_alloc,
&gmres_iterate,
&gmres_normr,
&gmres_free
};
const gsl_splinalg_itersolve_type * gsl_splinalg_itersolve_gmres =
&gmres_type;
| {
"alphanum_fraction": 0.5631465184,
"avg_line_length": 29.7110091743,
"ext": "c",
"hexsha": "bfdfa39b4fccb992a1ef0a15ea847deab42c2fa2",
"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/splinalg/gmres.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/splinalg/gmres.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/splinalg/gmres.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": 3670,
"size": 12954
} |
#include <stdio.h>
#include <gsl/gsl_rstat.h>
int
main(void)
{
double data[5] = {17.2, 18.1, 16.5, 18.3, 12.6};
double mean, variance, largest, smallest, sd,
rms, sd_mean, median, skew, kurtosis;
gsl_rstat_workspace *rstat_p = gsl_rstat_alloc();
size_t i, n;
/* add data to rstat accumulator */
for (i = 0; i < 5; ++i)
gsl_rstat_add(data[i], rstat_p);
mean = gsl_rstat_mean(rstat_p);
variance = gsl_rstat_variance(rstat_p);
largest = gsl_rstat_max(rstat_p);
smallest = gsl_rstat_min(rstat_p);
median = gsl_rstat_median(rstat_p);
sd = gsl_rstat_sd(rstat_p);
sd_mean = gsl_rstat_sd_mean(rstat_p);
skew = gsl_rstat_skew(rstat_p);
rms = gsl_rstat_rms(rstat_p);
kurtosis = gsl_rstat_kurtosis(rstat_p);
n = gsl_rstat_n(rstat_p);
printf ("The dataset is %g, %g, %g, %g, %g\n",
data[0], data[1], data[2], data[3], data[4]);
printf ("The sample mean is %g\n", mean);
printf ("The estimated variance is %g\n", variance);
printf ("The largest value is %g\n", largest);
printf ("The smallest value is %g\n", smallest);
printf( "The median is %g\n", median);
printf( "The standard deviation is %g\n", sd);
printf( "The root mean square is %g\n", rms);
printf( "The standard devation of the mean is %g\n", sd_mean);
printf( "The skew is %g\n", skew);
printf( "The kurtosis %g\n", kurtosis);
printf( "There are %zu items in the accumulator\n", n);
gsl_rstat_reset(rstat_p);
n = gsl_rstat_n(rstat_p);
printf( "There are %zu items in the accumulator\n", n);
gsl_rstat_free(rstat_p);
return 0;
}
| {
"alphanum_fraction": 0.6481942715,
"avg_line_length": 30.8846153846,
"ext": "c",
"hexsha": "645507de8ec8f17319372db6f140ea73561f732a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/rstat.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/rstat.c",
"max_line_length": 64,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/doc/examples/rstat.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": 527,
"size": 1606
} |
#ifndef LOGGER_INCLUDE
#define LOGGER_INCLUDE
#include <gsl/string_span>
#include "log/log.h"
BOOST_LOG_GLOBAL_LOGGER(exec_helper_core_logger, execHelper::log::LoggerType);
static const gsl::czstring<> LOG_CHANNEL = "core";
#define LOG(x) \
BOOST_LOG_STREAM_CHANNEL_SEV(exec_helper_core_logger::get(), LOG_CHANNEL, \
execHelper::log::x) \
<< boost::log::add_value(fileLog, __FILE__) \
<< boost::log::add_value(lineLog, __LINE__)
#endif /* LOGGER_INCLUDE */
| {
"alphanum_fraction": 0.5585443038,
"avg_line_length": 37.1764705882,
"ext": "h",
"hexsha": "759bdfc9006344971208530ea022ebba3c1b3acc",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z",
"max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "exec-helper/source",
"max_forks_repo_path": "src/core/include/core/logger.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "exec-helper/source",
"max_issues_repo_path": "src/core/include/core/logger.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "exec-helper/source",
"max_stars_repo_path": "src/core/include/core/logger.h",
"max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z",
"num_tokens": 121,
"size": 632
} |
#pragma once
#include "halley/text/halleystring.h"
#include <thread>
#include <gsl/span>
#include <atomic>
#include "halley/data_structures/hash_map.h"
#include "halley/time/halleytime.h"
namespace Halley {
enum class ProfilerEventType {
CorePumpEvents,
CoreDevConClient,
CorePumpAudio,
CoreFixedUpdate,
CoreVariableUpdate,
CoreUpdateSystem,
CoreUpdatePlatform,
CoreUpdate,
CoreStartRender,
CoreRender,
CoreVSync,
PainterDrawCall,
PainterEndRender,
PainterUpdateProjection,
WorldVariableUpdate,
WorldFixedUpdate,
WorldRender,
WorldSystemUpdate,
WorldSystemRender,
AudioGenerateBuffer,
DiskIO,
StatsView,
Game
};
class ProfilerData {
public:
using TimePoint = std::chrono::steady_clock::time_point;
using Duration = std::chrono::duration<int64_t, std::nano>;
class Event {
public:
String name;
std::thread::id threadId;
ProfilerEventType type;
int depth;
uint64_t id;
TimePoint startTime;
TimePoint endTime;
};
class ThreadInfo {
public:
std::thread::id id;
int maxDepth = 0;
String name;
TimePoint startTime;
TimePoint endTime;
Duration totalTime;
bool operator< (const ThreadInfo& other) const;
};
ProfilerData() = default;
ProfilerData(TimePoint frameStartTime, TimePoint frameEndTime, std::vector<Event> events);
TimePoint getStartTime() const;
TimePoint getEndTime() const;
const std::vector<Event>& getEvents() const;
Duration getTotalElapsedTime() const;
Duration getElapsedTime(ProfilerEventType eventType) const;
gsl::span<const ThreadInfo> getThreads() const;
private:
TimePoint frameStartTime;
TimePoint frameEndTime;
std::vector<Event> events;
std::vector<ThreadInfo> threads;
void processEvents();
};
class ProfilerCapture {
public:
using EventId = uint64_t;
ProfilerCapture(size_t maxEvents = 16384);
[[nodiscard]] static ProfilerCapture& get();
[[nodiscard]] EventId recordEventStart(ProfilerEventType type, std::string_view name);
void recordEventEnd(EventId id);
[[nodiscard]] bool isRecording() const;
void startFrame(bool record);
void endFrame();
ProfilerData getCapture();
Time getFrameTime() const;
private:
enum class State {
Idle,
FrameStarted,
FrameEnded
};
std::atomic<bool> recording;
std::atomic<uint64_t> curId;
uint64_t startId;
std::atomic<uint64_t> endId;
State state = State::Idle;
std::chrono::steady_clock::time_point frameStartTime;
std::chrono::steady_clock::time_point frameEndTime;
std::vector<ProfilerData::Event> events;
};
class ProfilerEvent {
public:
ProfilerEvent(ProfilerEventType type, std::string_view name = "");
~ProfilerEvent() noexcept;
ProfilerEvent(const ProfilerEvent& other) = delete;
ProfilerEvent(ProfilerEvent&& other) = delete;
ProfilerEvent& operator=(const ProfilerEvent& other) = delete;
ProfilerEvent& operator=(ProfilerEvent&& other) = delete;
private:
ProfilerCapture::EventId id;
};
}
| {
"alphanum_fraction": 0.6766615147,
"avg_line_length": 22.3103448276,
"ext": "h",
"hexsha": "f4f230547265d3c42da67e5849aa48fac8f9f3d6",
"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": "895e5ae482787eb09185928625e1ee9be3845fbc",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "pinguin999/halley",
"max_forks_repo_path": "src/engine/utils/include/halley/support/profiler.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "895e5ae482787eb09185928625e1ee9be3845fbc",
"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": "pinguin999/halley",
"max_issues_repo_path": "src/engine/utils/include/halley/support/profiler.h",
"max_line_length": 95,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "895e5ae482787eb09185928625e1ee9be3845fbc",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "pinguin999/halley",
"max_stars_repo_path": "src/engine/utils/include/halley/support/profiler.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 802,
"size": 3235
} |
#include <math.h>
#include <gsl/gsl_sf_bessel.h>
#include <galpy_potentials.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
//Double exponential disk potential
double DoubleExponentialDiskPotentialEval(double R,double z, double phi,
double t,
struct potentialArg * potentialArgs){
double * args= potentialArgs->args;
double amp, alpha;
int nzeros, glorder;
if ( R > 6. ) { //Approximate as Keplerian
nzeros= (int) *(args+4);
glorder= (int) *(args+5);
amp= *(args + 6 + 2 * glorder + 4 * (nzeros + 1));
alpha= *(args + 7 + 2 * glorder + 4 * (nzeros + 1));
return - *args * amp * pow(R*R+z*z,1.-0.5*alpha) / (alpha - 2.);
}
//Get args
amp= *args++;
alpha= *args++;
double beta= *args++;
double kmaxFac= *args++;
double kmax= kmaxFac * beta;
nzeros= (int) *args++;
glorder= (int) *args++;
double * glx= args;
double * glw= args + glorder;
double * j0zeros= args + 2 * glorder;
double * dj0zeros= args + 2 * glorder + nzeros + 1;
//Calculate potential
double out= 0.;
double k;
int ii, jj;
if ( R < 1. ) kmax= kmax/R;
for (ii=0; ii < ( nzeros + 1 ); ii++) {
for (jj=0; jj < glorder; jj++) {
k= 0.5 * ( *(glx+jj) + 1. ) * *(dj0zeros+ii+1) + *(j0zeros+ii);
out+= *(glw+jj) * *(dj0zeros+ii+1) * gsl_sf_bessel_J0(k*R)
* pow(alpha * alpha + k * k,-1.5)
* (beta * exp(-k * fabs(z) ) - k * exp(-beta * fabs(z) ))
/ (beta * beta - k * k);
}
if ( k > kmax ) break;
}
return - amp * 2 * M_PI * alpha * out;
}
double DoubleExponentialDiskPotentialRforce(double R,double z, double phi,
double t,
struct potentialArg * potentialArgs){
double * args= potentialArgs->args;
double amp, alpha;
int nzeros,glorder;
if ( R > 6. ) { //Approximate as Keplerian
nzeros= (int) *(args+4);
glorder= (int) *(args+5);
amp= *(args + 6 + 2 * glorder + 4 * (nzeros + 1));
alpha= *(args + 7 + 2 * glorder + 4 * (nzeros + 1));
return - *args * amp * R * pow(R*R+z*z,-0.5*alpha);
}
//Get args
amp= *args++;
alpha= *args++;
double beta= *args++;
double kmaxFac= *args++;
double kmax= 2. * kmaxFac * beta;
nzeros= (int) *args++;
glorder= (int) *args++;
double * glx= args;
double * glw= args + glorder;
double * j1zeros= args + 2 * glorder + 2 * (nzeros + 1);
double * dj1zeros= args + 2 * glorder + 3 * (nzeros + 1);
//Calculate potential
double out= 0.;
double k;
int ii, jj;
if ( R < 1. ) kmax= kmax/R;
for (ii=0; ii < ( nzeros + 1 ); ii++) {
for (jj=0; jj < glorder; jj++) {
k= 0.5 * ( *(glx+jj) + 1. ) * *(dj1zeros+ii+1) + *(j1zeros+ii);
out+= *(glw+jj) * *(dj1zeros+ii+1) * k * gsl_sf_bessel_J1(k*R)
* pow(alpha * alpha + k * k,-1.5)
* (beta * exp(-k * fabs(z) ) - k * exp(-beta * fabs(z) ))
/ (beta * beta - k * k);
}
if ( k > kmax ) break;
}
return - amp * 2 * M_PI * alpha * out;
}
double DoubleExponentialDiskPotentialPlanarRforce(double R,double phi,
double t,
struct potentialArg * potentialArgs){
double * args= potentialArgs->args;
double amp, alpha;
int nzeros, glorder;
if ( R > 6. ) { //Approximate as Keplerian
nzeros= (int) *(args+4);
glorder= (int) *(args+5);
amp= *(args + 6 + 2 * glorder + 4 * (nzeros + 1));
alpha= *(args + 7 + 2 * glorder + 4 * (nzeros + 1));
return - *args * amp * pow(R,-alpha + 1.);
}
//Get args
amp= *args++;
alpha= *args++;
double beta= *args++;
double kmaxFac= *args++;
double kmax= 2. * kmaxFac * beta;
nzeros= (int) *args++;
glorder= (int) *args++;
double * glx= args;
double * glw= args + glorder;
double * j1zeros= args + 2 * glorder + 2 * (nzeros + 1);
double * dj1zeros= args + 2 * glorder + 3 * (nzeros + 1);
//Calculate potential
double out= 0.;
double k;
int ii, jj;
if ( R < 1. ) kmax= kmax/R;
for (ii=0; ii < ( nzeros + 1 ); ii++) {
for (jj=0; jj < glorder; jj++) {
k= 0.5 * ( *(glx+jj) + 1. ) * *(dj1zeros+ii+1) + *(j1zeros+ii);
out+= *(glw+jj) * *(dj1zeros+ii+1) * k * gsl_sf_bessel_J1(k*R)
* pow(alpha * alpha + k * k,-1.5)
/ (beta + k);
}
if ( k > kmax ) break;
}
return - amp * 2 * M_PI * alpha * out;
}
double DoubleExponentialDiskPotentialzforce(double R,double z,double phi,
double t,
struct potentialArg * potentialArgs){
double * args= potentialArgs->args;
double amp, alpha;
int nzeros, glorder;
if ( R > 6. ) { //Approximate as Keplerian
nzeros= (int) *(args+4);
glorder= (int) *(args+5);
amp= *(args + 6 + 2 * glorder + 4 * (nzeros + 1));
alpha= *(args + 7 + 2 * glorder + 4 * (nzeros + 1));
return - *args * amp * z * pow(R*R+z*z,-0.5*alpha);
}
//Get args
amp= *args++;
alpha= *args++;
double beta= *args++;
double kmaxFac= *args++;
double kmax= kmaxFac * beta;
nzeros= (int) *args++;
glorder= (int) *args++;
double * glx= args;
double * glw= args + glorder;
double * j0zeros= args + 2 * glorder;
double * dj0zeros= args + 2 * glorder + nzeros + 1;
//Calculate potential
double out= 0.;
double k;
int ii, jj;
if ( R < 1. ) kmax= kmax/R;
for (ii=0; ii < ( nzeros + 1 ); ii++) {
for (jj=0; jj < glorder; jj++) {
k= 0.5 * ( *(glx+jj) + 1. ) * *(dj0zeros+ii+1) + *(j0zeros+ii);
out+= *(glw+jj) * *(dj0zeros+ii+1) * k * gsl_sf_bessel_J0(k*R)
* pow(alpha * alpha + k * k,-1.5)
* (exp(-k * fabs(z) ) - exp(-beta * fabs(z) ))
/ (beta * beta - k * k);
}
if ( k > kmax ) break;
}
if ( z > 0. )
return - amp * 2 * M_PI * alpha * beta * out;
else
return amp * 2 * M_PI * alpha * beta * out;
}
double DoubleExponentialDiskPotentialDens(double R,double z, double phi,
double t,
struct potentialArg * potentialArgs){
double * args= potentialArgs->args;
//Get args
double amp= *args++;
double alpha= *args++;
double beta= *args;
// calculate density
return amp * exp ( - alpha * R - beta * fabs ( z ) );
}
| {
"alphanum_fraction": 0.5546940839,
"avg_line_length": 31.3915343915,
"ext": "c",
"hexsha": "e634b1ef24f1d8168982463c6eb195407d1c684b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "gusbeane/galpy",
"max_forks_repo_path": "galpy/potential/potential_c_ext/DoubleExponentialDiskPotential.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "gusbeane/galpy",
"max_issues_repo_path": "galpy/potential/potential_c_ext/DoubleExponentialDiskPotential.c",
"max_line_length": 74,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d6db971285f163456c81775fc2fdc7d75189762c",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "gusbeane/galpy",
"max_stars_repo_path": "galpy/potential/potential_c_ext/DoubleExponentialDiskPotential.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2204,
"size": 5933
} |
#pragma once
#include <gsl.h>
#include <QmitkAbstractView.h>
#include "ui_SolverSetupView.h"
#include "ui_BoundaryConditionTypeSelectionDialog.h"
#include <HierarchyManager.h>
#include <ImmutableRanges.h>
#include "SolverStudyUIDsTableModel.h"
namespace crimson
{
class ISolverSetupManager;
}
/*! \brief SolverSetupView allows the user to set up the solver and to write the prepared simulation to disk. */
class SolverSetupView : public QmitkAbstractView
{
Q_OBJECT
public:
static const std::string VIEW_ID;
SolverSetupView();
~SolverSetupView();
void OnSelectionChanged(berry::IWorkbenchPart::Pointer source, const QList<mitk::DataNode::Pointer>& nodes) override;
void NodeRemoved(const mitk::DataNode* node) override;
void NodeChanged(const mitk::DataNode* node) override;
private slots:
void writeSolverSetup();
void runSimulation();
void loadSolution();
void showSolution(bool show);
void createSolverRoot();
void createSolverParameters();
void createSolverStudy();
void createBoundaryConditionSet();
void createBoundaryCondition();
void createMaterial();
void showMaterial();
void exportMaterials();
void setMeshNodeForStudy(const mitk::DataNode*);
void setSolverParametersNodeForStudy(const mitk::DataNode*);
private:
void CreateQtPartControl(QWidget* parent) override;
void SetFocus() override;
void _updateUI();
template <class T, class... Args>
void createSolverObject(mitk::DataNode* ownerNode, Args... additionalArgs);
private:
// Ui and main widget of this view
Ui::SolverSetupWidget _UI;
void _setCurrentRootNode(mitk::DataNode* node);
void _setCurrentSolverRootNode(mitk::DataNode* node);
void _findCurrentSolverSetupManager();
void _setCurrentBoundaryConditionSetNode(mitk::DataNode* node);
void _setCurrentBoundaryConditionNode(mitk::DataNode* node);
void _setCurrentMaterialNode(mitk::DataNode* node);
void _setCurrentSolverParametersNode(mitk::DataNode* node);
void _setCurrentSolverStudyNode(mitk::DataNode* node);
void _setupSolverStudyComboBoxes();
void _selectDataNode(mitk::DataNode* node);
void _serviceChanged(const us::ServiceEvent event);
void _solverStudyNodeModified();
unsigned long _solverStudyObserverTag = -1;
void _ensureApplyToAllWalls(mitk::DataNode* node) const;
gsl::cstring_span<> _getTypeNameToCreate(crimson::ImmutableValueRange<gsl::cstring_span<>> options);
mitk::DataNode* _currentSolverRootNode = nullptr;
mitk::DataNode* _currentRootNode = nullptr;
crimson::HierarchyManager::NodeType _currentRootNodeType;
mitk::DataNode* _currentVesselTreeNode = nullptr;
mitk::DataNode* _currentBoundaryConditionSetNode = nullptr;
mitk::DataNode* _currentBoundaryConditionNode = nullptr;
mitk::DataNode* _currentMaterialNode = nullptr;
mitk::DataNode* _currentSolverStudyNode = nullptr;
mitk::DataNode* _currentSolverParametersNode = nullptr;
mitk::DataNode* _currentSolidNode = nullptr;
crimson::ISolverSetupManager* _currentSolverSetupManager = nullptr;
struct RemoveNodeDeleter {
void operator()(mitk::DataNode* node);
};
std::unique_ptr<mitk::DataNode, RemoveNodeDeleter> _materialVisNodePtr;
Ui::boundaryConditionTypeSelectionDialog _typeSelectionDialogUi;
QDialog _typeSelectionDialog;
crimson::SolverStudyUIDsTableModel _solverStudyBCSetsModel;
crimson::SolverStudyUIDsTableModel _solverStudyMaterialsModel;
};
| {
"alphanum_fraction": 0.7570093458,
"avg_line_length": 31.2477876106,
"ext": "h",
"hexsha": "55caa98b39d4c40df33472d02d0d57c64a1ab343",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z",
"max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "carthurs/CRIMSONGUI",
"max_forks_repo_path": "Plugins/uk.ac.kcl.SolverSetupView/src/internal/SolverSetupView.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "carthurs/CRIMSONGUI",
"max_issues_repo_path": "Plugins/uk.ac.kcl.SolverSetupView/src/internal/SolverSetupView.h",
"max_line_length": 121,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "carthurs/CRIMSONGUI",
"max_stars_repo_path": "Plugins/uk.ac.kcl.SolverSetupView/src/internal/SolverSetupView.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z",
"num_tokens": 854,
"size": 3531
} |
/*
* Barcode
* Copyright E.G.P. Bos and F.S. Kitaura
*
* Distributed under the terms of the MIT License.
* The full license is in the file LICENSE, distributed with this software.
*/
#pragma once
#include "struct_main.h"
#include <gsl/gsl_rng.h>
#include "define_opt.h"
void barcoderunner(struct DATA *data,gsl_rng * gBaseRand);
void load_initial_fields(struct DATA *data, int resnum, gsl_rng *gBaseRand);
unsigned int initial_iteration_number(struct DATA *data);
void setup_random_test(struct DATA *data, real_prec *delta_lag, real_prec *delta_eul, unsigned int facL,
real_prec *posx, real_prec *posy, real_prec *posz, gsl_rng *gBaseRand);
void make_initial_guess(struct DATA *data, gsl_rng *gBaseRand);
| {
"alphanum_fraction": 0.7435549525,
"avg_line_length": 35.0952380952,
"ext": "h",
"hexsha": "faeefd5a63244df4a52a0fc03c8996d4f40e9388",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-02-11T06:56:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-11T06:56:47.000Z",
"max_forks_repo_head_hexsha": "1127e12fa80075389c1d247d30b430b77becbbc8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "egpbos/barcode",
"max_forks_repo_path": "barlib/include/barcoderunner.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "1127e12fa80075389c1d247d30b430b77becbbc8",
"max_issues_repo_issues_event_max_datetime": "2018-12-13T10:44:12.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-13T10:44:12.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "egpbos/barcode",
"max_issues_repo_path": "barlib/include/barcoderunner.h",
"max_line_length": 104,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1127e12fa80075389c1d247d30b430b77becbbc8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "egpbos/barcode",
"max_stars_repo_path": "barlib/include/barcoderunner.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 185,
"size": 737
} |
/*! \file grid_fft.c
* \brief Function definitions for dealing with FFT's on grids.
*
* Note that FFTW3 fftws are unnormalized, and are therefore multiplied by N
* In fftw3, plans are apparently intended to be local. They will be created
* and destroyed within the functions that perform the forward and reverse transforms.
* Real arrays have n elements, while complex arrays have n/2+1 (rounded down) elements
* for out of place transforms. For inplace transforms, real arrays have 2*(n/2+1) elements.
*
* An nx x ny x nz array (in row major order) array will have an output array of size
* nx x ny x (nz/2+1) after an r2c transform. For an inplace transform, the input array
* must be padded to size nx x ny x 2*(nz/2+1)
*
* Section 4.8 of the fftw3 manual has what FFTW3 really computes.*/
#include <mpi.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <fftw3-mpi.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_sf_trig.h>
#include "grid_fft.h"
/*! \fn void Copy_FFTW_Grid_Info(FFTW_Grid_Info source, FFTW_Grid_Info *dest)
* \brief Copy an FFTW_Grid_info struct. */
void Copy_FFTW_Grid_Info(FFTW_Grid_Info source, FFTW_Grid_Info *dest)
{
//save grid dimensions
(*dest).nx = source.nx;
(*dest).ny = source.ny;
(*dest).nz = source.nz;
(*dest).nz_complex = source.nz_complex;
//save this process's local sizes
(*dest).nx_local = source.nx_local;
(*dest).nx_local_start = source.nx_local_start;
(*dest).n_local_real_size = source.n_local_real_size;
(*dest).n_local_complex_size = source.n_local_complex_size;
//save physical grid info
(*dest).BoxSize = source.BoxSize;
(*dest).dx = source.dx;
(*dest).dy = source.dy;
(*dest).dz = source.dz;
(*dest).dV = source.dV;
(*dest).dVk = source.dVk;
//save number of dimensions
(*dest).ndim = source.ndim;
//save fftw3 plans
(*dest).plan = source.plan;
(*dest).iplan = source.iplan;
}
/*! \fn int grid_ijk(int i, int j, int k, FFTW_Grid_Info grid_info)
* \brief Array index for fftw grid based on coordinates i,j,k. */
int grid_ijk(int i, int j, int k, FFTW_Grid_Info grid_info)
{
int jj; //wrap safe y index
int kk; //wrap safe z index
int ijk;
//wrap safely in y and z
jj = j;
if(jj<0)
jj += grid_info.ny;
if(jj>(grid_info.ny-1))
jj -= grid_info.ny;
kk = k;
if(kk<0)
kk += grid_info.nz;
if(kk>(grid_info.nz-1))
kk -= grid_info.nz;
switch(grid_info.ndim)
{
case 2: ijk = i*(2*(grid_info.ny/2+1)) + jj;
break;
case 3: ijk = (i*grid_info.ny + jj)*(2*(grid_info.nz/2+1)) + kk;
}
//see page 61 of fftw3 manual
//checked 04/27/2016
return ijk;
}
/*! \fn int grid_complex_ijk(int i, int j, int k, FFTW_Grid_Info grid_info)
* \brief Array index for complex fftw grid based on coordinates i,j,k. */
int grid_complex_ijk(int i, int j, int k, FFTW_Grid_Info grid_info)
{
//complex data is stored as n_0 x n_1 x (n_d-1/2+1)
int ijk;
int jj = j;
int kk = k;
int nx = grid_info.nx;
int ny = grid_info.ny;
int nz = grid_info.nz;
switch(grid_info.ndim)
{
case 2: if(j>ny/2)
j -= ny/2;
ijk = i*(grid_info.ny/2 +1) + jj;;
break;
case 3: if(k>nz/2)
k -= nz/2;
ijk = (i*grid_info.ny + jj)*(grid_info.nz/2 +1) + kk;
}
return ijk;
}
/*! \fn int grid_transposed_ijk(int i, int j, int k, FFTW_Grid_Info grid_info)
* \brief Array index for fftw grid based on coordinates i,j,k. */
int grid_transposed_ijk(int i, int j, int k, FFTW_Grid_Info grid_info)
{
//#error fix this
int jj; //wrap safe y index
int kk; //wrap safe z index
if(grid_info.ndim==2)
{
}else{
}
/*
//wrap safely in y and z
jj = j;
if(jj<0)
jj += grid_info.ny;
if(jj>(grid_info.ny-1))
jj -= grid_info.ny;
kk = k;
if(kk<0)
kk += grid_info.nz;
if(kk>(grid_info.nz-1))
kk -= grid_info.nz;
//see page 61 of fftw3 manual
return (i*grid_info.ny + jj)*(2*(grid_info.nz/2+1)) + kk;
*/
return 0;
}
/*! \fn int grid_index(double x, double y, double z, FFTW_Grid_Info grid_info)
* \brief Given a position, return the grid index. */
int grid_index(double x, double y, double z, FFTW_Grid_Info grid_info)
{
int i = (int) (x/grid_info.dx) - grid_info.nx_local_start; //integer index along x direction
int j = (int) (y/grid_info.dy); //integer index along y direction
int k = (int) (z/grid_info.dz); //integer index along z direction
//if the position is not within this slab, then
//return -1
if(i < 0 || i >= grid_info.nx_local)
return -1;
//return the ijk of this position
return grid_ijk(i,j,k,grid_info);
}
/*! \fn int grid_complex_from_real_ijk(int i, int j, int k, FFTW_Grid_Info grid_info)
* \brief Array index for complex fftw grid created from r2c based on coordinates i,j,k. */
int grid_complex_from_real_ijk(int i, int j, int k, FFTW_Grid_Info grid_info)
{
//no wrapping, p60 of fftw3 manual
//complex are nx x ny x (nz/2 +1)
return (i*grid_info.ny + j)*(grid_info.nz/2+1) + k;
}
/*! \fn void initialize_mpi_local_sizes(FFTW_Grid_Info *grid_info, MPI_Comm world);
* \brief Function to determine local grid sizes for parallel FFT. */
void initialize_mpi_local_sizes(FFTW_Grid_Info *grid_info, MPI_Comm world)
{
ptrdiff_t nx_local;
ptrdiff_t nx_local_start;
//ptrdiff_t ny_local;
//ptrdiff_t ny_local_start;
//ptrdiff_t nx_local_transposed;
//ptrdiff_t nx_local_start_transposed;
//ptrdiff_t ny_local_transposed;
//ptrdiff_t ny_local_start_transposed;
//ptrdiff_t n_local_complex_size;
ptrdiff_t n_local_size;
//find the local sizes for *****complex arrays******
switch(grid_info->ndim)
{
case 2: n_local_size = fftw_mpi_local_size_2d(grid_info->nx, grid_info->ny/2+1, world, &nx_local, &nx_local_start);
break;
case 3: n_local_size = fftw_mpi_local_size_3d(grid_info->nx, grid_info->ny, grid_info->nz/2+1, world, &nx_local, &nx_local_start);
break;
default: printf("Only 2 or 3 dimensions\n");
MPI_Abort(world,-1);
exit(-1);
}
//remember the size
grid_info->nx_local = nx_local;
grid_info->nx_local_start = nx_local_start;
grid_info->n_local_complex_size = n_local_size;
//grid_info->nx_local_transposed = nx_local_transposed;
//grid_info->nx_local_start_transposed = nx_local_start_transposed;
//grid_info->ny_local_transposed = ny_local_transposed;
//grid_info->ny_local_start_transposed = ny_local_start_transposed;
grid_info->n_local_real_size = 2*grid_info->n_local_complex_size;
printf("nx_local %ld (nx_local) %ld\n",nx_local,(nx_local));
if(nx_local<=0)
{
printf("A*****************************************\n");
printf("WARNING!\n");
printf("nx_local = %ld on at least 1 processor\n",(ptrdiff_t) nx_local);
printf("Many functions implicitly assume nx_local>0\n");
printf("Try a different (lower) nprocs if possible.\n");
printf("*****************************************\n");
fflush(stdout);
}
}
/*! \fn double *allocate_real_fftw_grid_sized(int n_size)
* \brief Allocates a pre-sized 3-d real grid for use with fftw.*/
double *allocate_real_fftw_grid_sized(int n_size)
{
double *data;
//allocate data
data = fftw_alloc_real(n_size);
//return data
return data;
}
/*! \fn double *allocate_real_fftw_grid(FFTW_Grid_Info grid_info)
* \brief Allocates a 3-d real grid for use with fftw.*/
double *allocate_real_fftw_grid(FFTW_Grid_Info grid_info)
{
double *data;
//allocate data
data = fftw_alloc_real(grid_info.n_local_real_size);
//return data
return data;
}
/*! \fn fftw_complex *allocate_complex_fftw_grid(FFTW_Grid_Info grid_info)
* \brief Allocates a 3-d complex grid for use with fftw.*/
fftw_complex *allocate_complex_fftw_grid(FFTW_Grid_Info grid_info)
{
fftw_complex *cdata;
//allocate data
cdata = fftw_alloc_complex(grid_info.n_local_complex_size);
//return data
return cdata;
}
/*! \fn double **allocate_field_fftw_grid(int nd, FFTW_Grid_Info grid_info);
* \brief Allocates a field[ndim][n_local_real_size] (of dimension ndim) of 3-d real grids for use with fftw.*/
double **allocate_field_fftw_grid(int nd, FFTW_Grid_Info grid_info)
{
double **data;
//allocate the field
data = new double *[nd];
//each field element is an fftw grid
for(int i=0;i<nd;i++)
data[i] = allocate_real_fftw_grid(grid_info);
//return the field
return data;
}
/*! \fn void deallocate_field_fftw_grid(double **field, int nd, FFTW_Grid_Info grid_info)
* \brief De-allocates a field[ndim][n_local_size] (of dimension ndim) of 3-d real grids for use with fftw.*/
void deallocate_field_fftw_grid(double **field, int nd, FFTW_Grid_Info grid_info)
{
//free field elements
for(int i=0;i<nd;i++)
fftw_free(field[i]);
//free field pointer
delete field;
}
/*! \fn double ***allocate_tensor_fftw_grid(FFTW_Grid_Info grid_info)
* \brief Allocates a tensor[ndim][ndim][n_local_real_size] (of dimension ndim*ndim) of 3-d real grids for use with fftw.*/
double ***allocate_tensor_fftw_grid(FFTW_Grid_Info grid_info)
{
//tensor data
double ***data;
//allocate the tensor
data = new double **[grid_info.ndim];
for(int i=0;i<grid_info.ndim;i++)
{
data[i] = new double *[grid_info.ndim];
for(int j=0;j<grid_info.ndim;j++)
data[i][j] = allocate_real_fftw_grid(grid_info);
}
//return the tensor
return data;
}
/*! \fn void deallocate_tensor_fftw_grid(double ***tensor, FFTW_Grid_Info grid_info)
* \brief De-allocates a tensor[ndim][n_local_size] (of dimension ndim) of 3-d real grids for use with fftw.*/
void deallocate_tensor_fftw_grid(double ***tensor, FFTW_Grid_Info grid_info)
{
//free tensor elements
for(int i=0;i<grid_info.ndim;i++)
{
for(int j=0;j<grid_info.ndim;j++)
free(tensor[i][j]);
delete[] tensor[i];
}
//free tensor pointer
delete tensor;
}
/*! \fn void inverse_transform_fftw_grid(double *work, fftw_complex *cdata, FFTW_Grid_Info grid_info)
* \brief Takes a forward transform, already re-normalized by 1./(nx*ny*nz), and returns a properly normalized inverse transform */
void inverse_transform_fftw_grid(double *work, fftw_complex *cwork, FFTW_Grid_Info grid_info)
{
//do inverse transform
fftw_execute(grid_info.iplan);
}
/*! \fn void forward_transform_fftw_grid(double *work, fftw_complex *cwork, FFTW_Grid_Info grid_info)
* \brief Produces a forward transform normalized by 1./(nx*ny*nz). */
void forward_transform_fftw_grid(double *work, fftw_complex *cwork, FFTW_Grid_Info grid_info)
{
//grid index
int ijk;
//normalization
double scale = 1./( ((double) grid_info.nx)*((double) grid_info.ny)*((double) grid_info.nz) );
//the fftw plan is contained within grid_info
//perform forward fftw
fftw_execute(grid_info.plan);
//normalize transform
for(int i=0;i<grid_info.nx_local_transposed;++i)
for(int j=0;j<grid_info.ny_local_transposed;++j)
for(int k=0;k<grid_info.nz;++k)
{
//find i,j,k element
ijk = grid_complex_ijk(i,j,k,grid_info);
//rescale the complex data
cwork[ijk][0]*=scale;
cwork[ijk][1]*=scale;
}
}
void output_fft_grid(char *output_fname, double *data, FFTW_Grid_Info grid_info, int ixmin, int ixmax, int iymin, int iymax, int izmin, int izmax, int myid, int numprocs, MPI_Comm world)
{
//in this version, all processors send their data to the root process, who then outputs the data
FILE *fp;
int ijk;
int ijk_out;
double *xout;
int initial_flag = 0;
int total_initial = 0;
int error_flag = 0;
int nx_max;
int nx_min;
int ny_max;
int ny_min;
int nz_max;
int nz_min;
int nx_out;
int ny_out;
int nz_out;
int yes_flag = 0;
//copy info from grid_info
int nx = grid_info.nx;
int ny = grid_info.ny;
int nz = grid_info.nz;
int n_local_size = grid_info.n_local_real_size;
int nx_local = grid_info.nx_local;
int nx_local_start = grid_info.nx_local_start;
//some simple array boundary checks
if(ixmax>nx)
ixmax = nx;
if(iymax>ny)
iymax = ny;
if(izmax>nz)
izmax = nz;
if(ixmin<0)
ixmin = 0;
if(iymin<0)
iymin = 0;
if(izmin<0)
izmin = 0;
//restrict the output to the data available on each process
nx_min = ixmin;
nx_max = ixmax;
if(nx_min<nx_local_start)
{
nx_min = nx_local_start;
}
if((nx_max-nx_local_start)>nx_local)
{
nx_max = nx_local + nx_local_start;
}
//each process should have the complete y and z range
ny_min = iymin;
ny_max = iymax;
nz_min = izmin;
nz_max = izmax;
nx_out = nx_max - nx_min;
ny_out = ny_max - ny_min;
nz_out = nz_max - nz_min;
if( (ixmin<nx_local_start+nx_local)&&(ixmax>=nx_local_start) )
yes_flag = 1;
//loop over number of processors
for(int ip=0;ip<numprocs;ip++)
{
MPI_Barrier(world);
//check to see if the output strides over this process
if( (ixmin<nx_local_start+nx_local)&&(ixmax>=nx_local_start)&&(ip==myid) )
{
if(!initial_flag)
{
//printf("processor %d initiated for file %s\n",myid,output_fname);
//fflush(stdout);
//this processor is the first
//to write to the file
initial_flag = 1;
//open a new file
if(!(fp = fopen(output_fname,"w")))
{
printf("Error opening %s by process %d\n",output_fname,myid);
fflush(stdout);
error_flag = 1;
}else{
//printf("File %s opened by %d.\n",output_fname,myid);
//printf("nx %d ny %d nz %d\n",nx,ny,nz);
//printf("ixmin %d ixmax %d\n",ixmin,ixmax);
//printf("iymin %d iymax %d\n",iymin,iymax);
//printf("izmin %d izmax %d\n",izmin,izmax);
//printf("nxmin %d nxmax %d\n",nx_min,nx_max);
//printf("nymin %d nymax %d\n",ny_min,ny_max);
//printf("nzmin %d nzmax %d\n",nz_min,nz_max);
//printf("nxout %d nyout %d nzyout %d\n",nx_out,ny_out,nz_out);
//fflush(stdout);
}
//the data file has opened correctly, so continue
if(!error_flag)
{
//write the grid dimensions
fwrite(&nx,1,sizeof(int),fp);
fwrite(&ny,1,sizeof(int),fp);
fwrite(&nz,1,sizeof(int),fp);
//write the restricted grid dimensions
fwrite(&ixmin,1,sizeof(int),fp);
fwrite(&ixmax,1,sizeof(int),fp);
fwrite(&iymin,1,sizeof(int),fp);
fwrite(&iymax,1,sizeof(int),fp);
fwrite(&izmin,1,sizeof(int),fp);
fwrite(&izmax,1,sizeof(int),fp);
//write this process's data to file
//allocate the output buffer
if(!(xout = (double *) malloc(nx_out*ny_out*nz_out*sizeof(double))))
{
printf("Error allocating output array xout on process %d (nx_out %d ny_out %d nz_out %d).\n",myid,nx_out,ny_out,nz_out);
fflush(stdout);
error_flag = 1;
}
if(!error_flag)
{
for(int i=nx_min;i<nx_max;i++)
{
for(int j=ny_min;j<ny_max;j++)
{
for(int k=nz_min;k<nz_max;k++)
{
ijk_out = ( (i-nx_min)*ny_out + (j-ny_min) )*nz_out + (k-nz_min);
if(grid_info.ndim==2)
{
//ijk = ( (i-nx_local_start) )*(2*(ny/2+1)) + j;
}else{
//ijk = ( (i-nx_local_start)*ny + j )*(2*(nz/2+1)) + k;
}
ijk = grid_ijk(i,j,k,grid_info);
if(ijk_out>=(nx_out*ny_out*nz_out))
{
printf("error here i %d j %d k %d nx_min %d nx_max %d ny_min %d ny_max %d nz_min %d nz_max %d ijk %d max %d\n",i,j,k,nx_min,nx_max,ny_min,ny_max,nz_min,nz_max,ijk_out,nx_out*ny_out*nz_out);
fflush(stdout);
}
if(ijk>=n_local_size)
{
printf("second error here i %d j %d k %d nx_min %d nx_max %d ny_min %d ny_max %d nz_min %d nz_max %d ijk %d max %d\n",i,j,k,nx_min,nx_max,ny_min,ny_max,nz_min,nz_max,ijk,nx_local*ny*nz);
fflush(stdout);
}
xout[ijk_out] = data[ijk];
}
}
}
//write the data
fwrite(xout,nx_out*ny_out*nz_out,sizeof(double),fp);
//close the data file
fclose(fp);
//free the output buffer
free(xout);
}
}
}else{
//printf("processor %d continuing for file %s\n",myid,output_fname);
//fflush(stdout);
//here, we're not the first processsor to output our data
//so the file should be appended, not created
//open the file to append
if(!(fp = fopen(output_fname,"a")))
{
printf("Error opening %s by process %d\n",output_fname,myid);
fflush(stdout);
error_flag = 1;
}else{
//printf("File %s appended by %d.\n",output_fname,myid);
//printf("nx %d ny %d nz %d\n",nx,ny,nz);
//printf("ixmin %d ixmax %d\n",ixmin,ixmax);
//printf("iymin %d iymax %d\n",iymin,iymax);
//printf("izmin %d izmax %d\n",izmin,izmax);
//printf("nxmin %d nxmax %d\n",nx_min,nx_max);
//printf("nymin %d nymax %d\n",ny_min,ny_max);
//printf("nzmin %d nzmax %d\n",nz_min,nz_max);
//printf("nxout %d nyout %d nzyout %d\n",nx_out,ny_out,nz_out);
//fflush(stdout);
}
//the data file has opened correctly, so continue
if(!error_flag)
{
//write this process's data to file
nx_out = nx_max - nx_min;
ny_out = ny_max - ny_min;
nz_out = nz_max - nz_min;
//allocate the output buffer
if(!(xout = (double *) malloc(nx_out*ny_out*nz_out*sizeof(double))))
{
printf("Error allocating alt output array xout on process %d (nx %d ny %d nz %d).\n",myid,nx_out,ny_out,nz_out);
fflush(stdout);
error_flag = 1;
}
if(!error_flag)
{
for(int i=nx_min;i<nx_max;++i)
for(int j=ny_min;j<ny_max;++j)
for(int k=nz_min;k<nz_max;++k)
{
ijk_out = ( (i-nx_min)*ny_out + (j-ny_min) )*nz_out + (k-nz_min);
/*if(grid_info.ndim==2)
{
ijk = ( (i-nx_local_start) )*(2*(ny/2+1)) + j;
}else{
ijk = ( (i-nx_local_start)*ny + j )*(2*(nz/2+1)) + k;
}*/
ijk = grid_ijk(i,j,k,grid_info);
if(ijk_out>=(nx_out*ny_out*nz_out))
{
printf("alt error here i %d j %d k %d nx_min %d nx_max %d ny_min %d ny_max %d nz_min %d nz_max %d ijk %d max %d\n",i,j,k,nx_min,nx_max,ny_min,ny_max,nz_min,nz_max,ijk_out,nx_out*ny_out*nz_out);
fflush(stdout);
}
if(ijk>=n_local_size)
{
printf("alt second error here i %d j %d k %d nx_min %d nx_max %d ny_min %d ny_max %d nz_min %d nz_max %d ijk %d max %d\n",i,j,k,nx_min,nx_max,ny_min,ny_max,nz_min,nz_max,ijk,nx_local*ny*nz);
fflush(stdout);
}
xout[ijk_out] = data[ijk];
}
//write the data
fwrite(xout,nx_out*ny_out*nz_out,sizeof(double),fp);
//close the data file
fclose(fp);
//free the output buffer
free(xout);
}
}
}
}
//Check to see if previous processors wrote some data
//and created the output file
MPI_Allreduce(&initial_flag,&total_initial,1,MPI_INT,MPI_SUM,world);
initial_flag = total_initial;
if(initial_flag>0)
{
initial_flag = 1;
total_initial = 1;
}
//Check for errors, and if there is an error abort
//AllCheckError(error_flag,myid,numprocs,world);
MPI_Barrier(world);
}
}
/*
void convolve_complex_fftw_grid(fftw_complex *C_transposed, fftw_complex *A_transposed, fftw_complex *B_transposed, FFTW_Grid_Info grid_info, int local_ny_after_transpose, int nx, int ny, int nzi, int myid, int numprocs, MPI_Comm world)
{
int ijk;
//transform normalization
//is handled in forward_transform_fftw_grid
double scale = 1.;
int nz = nzi;
int nzl = nz/2+1;
if(grid_info.ndim==2)
{
nz=1;
nzl=1;
}
for(int j=0;j<local_ny_after_transpose;++j)
for(int i=0;i<nx;++i)
for(int k=0;k<nzl;++k)
{
//ijk = (j*nx + i)*(nz/2+1) + k;
ijk = grid_transpose_ijk(i,j,k,grid_info);
C_transposed[ijk][0] = scale*(A_transposed[ijk][0]*B_transposed[ijk][0] - A_transposed[ijk][1]*B_transposed[ijk][1]);
C_transposed[ijk][1] = scale*(A_transposed[ijk][0]*B_transposed[ijk][1] + A_transposed[ijk][1]*B_transposed[ijk][0]);
}
}
void output_fft_grid_procs(char *output_fname, double *data, int nx, int ny, int nz, int ixmin, int ixmax, int iymin, int iymax, int izmin, int izmax, int nx_local_start, int nx_local, int n_local_size, int myid, int numprocs, MPI_Comm world)
{
//in this version
//each process outputs its own data
FILE *fp;
int ijk;
int ijk_out;
double *xout;
int initial_flag = 0;
int total_initial = 0;
int error_flag = 0;
int nx_max;
int nx_min;
int ny_max;
int ny_min;
int nz_max;
int nz_min;
int nx_out;
int ny_out;
int nz_out;
int yes_flag = 0;
//some simple array boundary checks
if(ixmax>nx)
ixmax = nx;
if(iymax>ny)
iymax = ny;
if(izmax>nz)
izmax = nz;
if(ixmin<0)
ixmin = 0;
if(iymin<0)
iymin = 0;
if(izmin<0)
izmin = 0;
//restrict the output to the data available on each process
nx_min = ixmin;
nx_max = ixmax;
//if(nx_min>=nx_local_start)
if(nx_min<nx_local_start)
{
nx_min = nx_local_start;
}
if((nx_max-nx_local_start)>nx_local)
{
//nx_max = nx_local;
nx_max = nx_local + nx_local_start;
}
//each process should have the complete y and z range
ny_min = iymin;
ny_max = iymax;
nz_min = izmin;
nz_max = izmax;
nx_out = nx_max - nx_min;
ny_out = ny_max - ny_min;
nz_out = nz_max - nz_min;
if( (ixmin<nx_local_start+nx_local)&&(ixmax>=nx_local_start) )
yes_flag = 1;
if(myid==0)
printf("testing output\n");
fflush(stdout);
for(int ip=0;ip<numprocs;ip++)
if(myid==ip)
printf("id %d nxmin %d nxmax %d nymin %d nymax %d nzmin %d nzmax %d ixmin %d ixmax %d iymin %d iymax %d izmin %d izmax %d nxout %d nyout %d nzout %d lxs %d lnx %d lxs+lnx %d yf %d\n",ip,nx_min,nx_max,ny_min,ny_max,nz_min,nz_max,ixmin,ixmax,iymin,iymax,izmin,izmax,nx_out,ny_out,nz_out,nx_local_start,nx_local,nx_local_start+nx_local,yes_flag);
//loop over number of processors
for(int ip=0;ip<numprocs;ip++)
{
//check to see if the output strides over this process
if( (ixmin<nx_local_start+nx_local)&&(ixmax>=nx_local_start)&&(ip==myid) )
{
if(!initial_flag)
{
//this processor is the first
//to write to the file
initial_flag = 1;
//open a new file
if(!(fp = fopen(output_fname,"w")))
{
printf("Error opening %s by process %d\n",output_fname,myid);
fflush(stdout);
error_flag = 1;
}else{
//printf("File %s opened by %d.\n",output_fname,myid);
//printf("nx %d ny %d nz %d\n",nx,ny,nz);
//printf("ixmin %d ixmax %d\n",ixmin,ixmax);
//printf("iymin %d iymax %d\n",iymin,iymax);
//printf("izmin %d izmax %d\n",izmin,izmax);
//printf("nxmin %d nxmax %d\n",nx_min,nx_max);
//printf("nymin %d nymax %d\n",ny_min,ny_max);
//printf("nzmin %d nzmax %d\n",nz_min,nz_max);
//printf("nxout %d nyout %d nzyout %d\n",nx_out,ny_out,nz_out);
//fflush(stdout);
}
//the data file has opened correctly, so continue
if(!error_flag)
{
//write the grid dimensions
fwrite(&nx,1,sizeof(int),fp);
fwrite(&ny,1,sizeof(int),fp);
fwrite(&nz,1,sizeof(int),fp);
//write the restricted grid dimensions
fwrite(&ixmin,1,sizeof(int),fp);
fwrite(&ixmax,1,sizeof(int),fp);
fwrite(&iymin,1,sizeof(int),fp);
fwrite(&iymax,1,sizeof(int),fp);
fwrite(&izmin,1,sizeof(int),fp);
fwrite(&izmax,1,sizeof(int),fp);
//write this process's data to file
//allocate the output buffer
if(!(xout = (double *) malloc(nx_out*ny_out*nz_out*sizeof(double))))
{
printf("Error allocating output array xout on process %d (nx_out %d ny_out %d nz_out %d).\n",myid,nx_out,ny_out,nz_out);
fflush(stdout);
error_flag = 1;
}
if(!error_flag)
{
for(int i=nx_min;i<nx_max;++i)
for(int j=ny_min;j<ny_max;++j)
{
for(int k=nz_min;k<nz_max;++k)
{
ijk_out = ( (i-nx_min)*ny_out + (j-ny_min) )*nz_out + (k-nz_min);
ijk = ( (i-nx_local_start)*ny + j )*(2*(nz/2+1)) + k;
if(ijk_out>=(nx_out*ny_out*nz_out))
{
printf("error here i %d j %d k %d nx_min %d nx_max %d ny_min %d ny_max %d nz_min %d nz_max %d ijk %d max %d\n",i,j,k,nx_min,nx_max,ny_min,ny_max,nz_min,nz_max,ijk_out,nx_out*ny_out*nz_out);
fflush(stdout);
}
if(ijk>=n_local_size)
{
printf("second error here i %d j %d k %d nx_min %d nx_max %d ny_min %d ny_max %d nz_min %d nz_max %d ijk %d max %d\n",i,j,k,nx_min,nx_max,ny_min,ny_max,nz_min,nz_max,ijk,nx_local*ny*nz);
fflush(stdout);
}
xout[ijk_out] = data[ijk];
}
}
//write the data
fwrite(xout,nx_out*ny_out*nz_out,sizeof(double),fp);
//close the data file
fclose(fp);
//free the output buffer
free(xout);
}
}
}else{
//here, we're not the first processsor to output our data
//so the file should be appended, not created
//open the file to append
if(!(fp = fopen(output_fname,"a")))
{
printf("Error opening %s by process %d\n",output_fname,myid);
fflush(stdout);
error_flag = 1;
}else{
//printf("File %s appended by %d.\n",output_fname,myid);
//printf("nx %d ny %d nz %d\n",nx,ny,nz);
//printf("ixmin %d ixmax %d\n",ixmin,ixmax);
//printf("iymin %d iymax %d\n",iymin,iymax);
//printf("izmin %d izmax %d\n",izmin,izmax);
//printf("nxmin %d nxmax %d\n",nx_min,nx_max);
//printf("nymin %d nymax %d\n",ny_min,ny_max);
//printf("nzmin %d nzmax %d\n",nz_min,nz_max);
//printf("nxout %d nyout %d nzyout %d\n",nx_out,ny_out,nz_out);
//fflush(stdout);
}
//the data file has opened correctly, so continue
if(!error_flag)
{
//write this process's data to file
nx_out = nx_max - nx_min;
ny_out = ny_max - ny_min;
nz_out = nz_max - nz_min;
//allocate the output buffer
if(!(xout = (double *) malloc(nx_out*ny_out*nz_out*sizeof(double))))
{
printf("Error allocating alt output array xout on process %d (nx %d ny %d nz %d).\n",myid,nx_out,ny_out,nz_out);
fflush(stdout);
error_flag = 1;
}
if(!error_flag)
{
for(int i=nx_min;i<nx_max;++i)
for(int j=ny_min;j<ny_max;++j)
for(int k=nz_min;k<nz_max;++k)
{
ijk_out = ( (i-nx_min)*ny_out + (j-ny_min) )*nz_out + (k-nz_min);
ijk = ( (i-nx_local_start)*ny + j )*(2*(nz/2+1)) + k;
if(ijk_out>=(nx_out*ny_out*nz_out))
{
printf("alt error here i %d j %d k %d nx_min %d nx_max %d ny_min %d ny_max %d nz_min %d nz_max %d ijk %d max %d\n",i,j,k,nx_min,nx_max,ny_min,ny_max,nz_min,nz_max,ijk_out,nx_out*ny_out*nz_out);
fflush(stdout);
}
if(ijk>=n_local_size)
{
printf("alt second error here i %d j %d k %d nx_min %d nx_max %d ny_min %d ny_max %d nz_min %d nz_max %d ijk %d max %d\n",i,j,k,nx_min,nx_max,ny_min,ny_max,nz_min,nz_max,ijk,nx_local*ny*nz);
fflush(stdout);
}
xout[ijk_out] = data[ijk];
}
//write the data
fwrite(xout,nx_out*ny_out*nz_out,sizeof(double),fp);
//close the data file
fclose(fp);
//free the output buffer
free(xout);
}
}
}
}
//Check to see if previous processors wrote some data
//and created the output file
MPI_Allreduce(&initial_flag,&total_initial,1,MPI_INT,MPI_SUM,world);
initial_flag = total_initial;
//Check for errors, and if there is an error abort
AllCheckError(error_flag,myid,numprocs,world);
}
}
void output_fft_grid_complex(char *output_fname, fftw_complex *data, int nx, int ny, int nz, int ixmin, int ixmax, int iymin, int iymax, int izmin, int izmax, int local_y_start_after_transpose, int local_ny_after_transpose, int n_local_size, int myid, int numprocs, MPI_Comm world)
{
//output the complex data
//but remember that the data is transposed
//and that the slabs are split across the
//y dimension
// Also remember that we performed
// a transform of real data.
// For real data, F(-k) = F(k)*
// and the nz/2 element is the
// same as the -nz/2 element
// the format of the gridded complex
// data will be
//
// nx
// {
// re(ny,nz)
// im(ny,nz)
// }
// the duplicative information in
// the z-direction *will be included*
// and note that for simplicity
// izmin = 0;
// izmax = nz;
// always
FILE *fp;
MPI_Status status;
int jk;
int jk_out;
int jtot;
double *xout_imaginary, *xout_real;
double *y_block_imaginary, *y_block_real;
int initial_flag = 0;
int total_initial = 0;
int error_flag = 0;
int nx_max;
int nx_min;
int ny_max;
int ny_min;
int nz_max;
int nz_min;
int nx_out;
int ny_out;
int nz_out;
int *all_local_ny, *all_local_y_start;
int yes_flag = 0;
//some simple array boundary checks
if(ixmax>nx)
ixmax = nx;
if(iymax>ny)
iymax = ny;
if(ixmin<0)
ixmin = 0;
if(iymin<0)
iymin = 0;
//enforce full z coverage
izmin = 0;
izmax = nz;
//each process should have the complete x and z range
//we will pretend the whole y range is available
ny_min = iymin;
ny_max = iymax;
nx_min = ixmin;
nx_max = ixmax;
nx_out = nx_max - nx_min;
ny_out = ny_max - ny_min;
//The data is transposed and is complex, so the output method differs from that for real data:
//First, the root process opens a new file and outputs the essential
//info about the data
if(myid==0)
{
//open a new file
if(!(fp = fopen(output_fname,"w")))
{
printf("Error opening %s by process %d\n",output_fname,myid);
fflush(stdout);
error_flag = 1;
}
if(!error_flag)
{
//the data file has opened correctly, so continue
//write the grid dimensions
fwrite(&nx,1,sizeof(int),fp);
fwrite(&ny,1,sizeof(int),fp);
fwrite(&nz,1,sizeof(int),fp);
//write the restricted grid dimensions
fwrite(&ixmin,1,sizeof(int),fp);
fwrite(&ixmax,1,sizeof(int),fp);
fwrite(&iymin,1,sizeof(int),fp);
fwrite(&iymax,1,sizeof(int),fp);
fwrite(&izmin,1,sizeof(int),fp);
fwrite(&izmax,1,sizeof(int),fp);
fclose(fp);
}
}
//Check for errors, and if there is an error abort
AllCheckError(error_flag,myid,numprocs,world);
//The data is transposed, so to output
//in row-major format with the x-direction
//as primary, we're gonna do some funky outputing
//First, figure out the y-direction extent of each
//processor and share that with the other processes
//allocate arrays to hold local y extent info
if(!(all_local_ny = (int *) malloc(numprocs*sizeof(int))))
{
printf("Error allocating all_local_y on process %d.\n",myid);
error_flag = 1;
}
if(!(all_local_y_start = (int *) malloc(numprocs*sizeof(int))))
{
printf("Error allocating all_local_y_start on process %d.\n",myid);
error_flag = 1;
}
//Check for errors, and if there is an error abort
AllCheckError(error_flag,myid,numprocs,world);
//Share local y extent info
MPI_Allgather(&local_ny_after_transpose,1,MPI_INT,all_local_ny,1,MPI_INT,world);
MPI_Allgather(&local_y_start_after_transpose,1,MPI_INT,all_local_y_start,1,MPI_INT,world);
if(myid==0)
{
for(int i=0;i<numprocs;i++)
printf("proc %d lny %d lys %d\n",i,all_local_ny[i],all_local_y_start[i]);
fflush(stdout);
}
//Check for errors, and if there is an error abort
AllCheckError(error_flag,myid,numprocs,world);
//Second, begin a loop after the x-direction.
//The root process will allocate a page of size ny_out*nz_out
if(myid==0)
{
if(!(xout_real = (double *) malloc(ny_out*nz*sizeof(double))))
{
printf("Error allocating xout_real page on root process.\n");
fflush(stdout);
error_flag = 1;
}
if(!(xout_imaginary = (double *) malloc(ny_out*nz*sizeof(double))))
{
printf("Error allocating xout_imaginary page on root process.\n");
fflush(stdout);
error_flag = 1;
}
}
//Check for errors, and if there is an error abort
AllCheckError(error_flag,myid,numprocs,world);
//begin the loop over the x-direction
//for the real part of the complex data
for(int i=nx_min;i<nx_max;++i)
{
jtot = ny_min;
//begin the loop over the number of processes
for(int ip=0;ip<numprocs;ip++)
{
//Check to see if this processor contributes to the y-direction
//extent of the output.
//
//Otherwise, just skip it
if( (iymin<all_local_y_start[ip]+all_local_ny[ip])&&(iymax>=all_local_y_start[ip]) )
{
//printf("i %d j %d ip %d processor %d entered\n",i,jtot,ip,myid);
//fflush(stdout);
//This processor contributes to the y-direction extent of the output
if(ip==0)
{
if(ip==myid)
{
//it is time for the root process
//to copy its y-direction info
//into the xout page
for(int j=0;(j<local_ny_after_transpose)&&(jtot<ny_max);++j)
{
//DC component
jk_out = ( (jtot-ny_min) )*nz;
jk = (j*nx + i)*(nz/2+1);
xout_real[jk_out] = data[jk].re;
for(int k=1;k<(nz/2+1);++k)
{
// do the real part of the positive frequencies first
jk_out = ( (jtot-ny_min) )*nz + k;
jk = (j*nx + i)*(nz/2+1) + k;
xout_real[jk_out] = data[jk].re;
// do the real part of the negative frequencies second
jk_out = ( (jtot-ny_min) )*nz + (nz-k);
jk = ( (jtot-ny_min) )*nz + k;
xout_real[jk_out] = xout_real[jk];
// do the imaginary part of the positive frequencies third
jk_out = ( (jtot-ny_min) )*nz + k;
jk = (j*nx + i)*(nz/2+1) + k;
//jk = (j*nx + i)*(nz/2+1) + (nz-k);
xout_imaginary[jk_out] = data[jk].im;
// do the imaginary part of the negative frequencies fourth
jk_out = ( (jtot-ny_min) )*nz + (nz-k);
jk = ( (jtot-ny_min) )*nz + k;
xout_imaginary[jk_out] = (-xout_imaginary[jk]);
}
if((nz%2)==0)
{
//nz is even
jk_out = ( (jtot-ny_min) )*nz + (nz/2);
jk = (j*nx + i)*(nz/2+1) + (nz/2);
xout_real[jk_out] = data[jk].re;
xout_imaginary[jk_out] = 0;
}
jtot++;
}
}//end if(ip==myid)
}else{
//Some other processor contributes to the y-extent of the output data
if((myid==0)||(ip==myid))
{
//first, we have to allocate a block for the y
//data on the current process
if(!(y_block_real = (double *) malloc(all_local_ny[ip]*nz*sizeof(double))))
{
printf("Error allocating y_block_real on process %d.\n",myid);
fflush(stdout);
error_flag = 1;
}
if(!(y_block_imaginary = (double *) malloc(all_local_ny[ip]*nz*sizeof(double))))
{
printf("Error allocating y_block_imaginary on process %d.\n",myid);
fflush(stdout);
error_flag = 1;
}
}
//Check for errors, and if there is an error abort
AllCheckError(error_flag,myid,numprocs,world);
//printf("i %d j %d ip %d proc %d about to exchange data\n",i,jtot,ip,myid);
//fflush(stdout);
if(myid==0)
{
//printf("i %d j %d ip %d root waiting for exchange data\n",i,jtot,ip);
//fflush(stdout);
//Receive the data from the active process
MPI_Recv(y_block_real,all_local_ny[ip]*nz,MPI_DOUBLE,ip,ip,world,&status);
MPI_Recv(y_block_imaginary,all_local_ny[ip]*nz,MPI_DOUBLE,ip,ip,world,&status);
//copy the data from processor ip to the output buffers
for(int j=0;(j<all_local_ny[ip])&&(jtot<ny_max);++j)
{
for(int k=0;k<nz;++k)
{
// simply copy the blocks
jk_out = ( (jtot-ny_min) )*nz + k;
jk = ( (jtot-all_local_y_start[ip]) )*nz + k;
xout_real[jk_out] = y_block_real[jk];
xout_imaginary[jk_out] = y_block_imaginary[jk];
}
jtot++;
}
//free y_blocks
free(y_block_real);
free(y_block_imaginary);
}else{
//Check to see if this is the contributing process
//printf("i %d j %d ip %d proc %d exchange data\n",i,jtot,ip,myid);
//fflush(stdout);
if(ip==myid)
{
//copy the data to a buffer to send to the root process for output
for(int j=0;j<all_local_ny[ip];++j)
{
//DC Component
jk_out = ( j*nz );
jk = ( j*nx + i)*(nz/2+1);
y_block_real[jk_out] = data[jk].re;
y_block_imaginary[jk_out] = 0;
for(int k=1;k<(nz/2+1);++k)
{
// do the real part of the positive frequencies first
jk_out = ( j*nz + k );
jk = (j*nx + i)*(nz/2+1) + k;
y_block_real[jk_out] = data[jk].re;
// do the real part of the negative frequencies second
// note this is the complex conjugate
jk_out = ( j*nz + (nz-k) );
jk = (j*nx + i)*(nz/2+1) + k;
y_block_real[jk_out] = data[jk].re;
// do the imaginary part of the positive frequencies third
jk_out = ( j*nz + k );
jk = (j*nx + i)*(nz/2+1) + k;
y_block_imaginary[jk_out] = data[jk].im;
// do the imaginary part of the negative frequencies fourth
// note this is the complex conjugate
jk_out = ( j*nz + (nz-k) );
jk = (j*nx + i)*(nz/2+1) + k;
y_block_imaginary[jk_out] = -(data[jk].im);
}
if((nz%2)==0)
{
jk_out = ( j*nz + nz/2);
jk = ( j*nx + i)*(nz/2+1) + nz/2;
y_block_real[jk_out] = data[jk].re;
y_block_imaginary[jk_out] = data[jk].im;
}
}
//printf("i %d j %d ip %d about to send exchange data\n",i,jtot,ip);
//fflush(stdout);
//Send the data to the root process
MPI_Send(y_block_real,all_local_ny[ip]*nz,MPI_DOUBLE,0,ip,world);
MPI_Send(y_block_imaginary,all_local_ny[ip]*nz,MPI_DOUBLE,0,ip,world);
//free y_blocks
free(y_block_real);
free(y_block_imaginary);
}//end if(ip==myid)
}//end if(imyid==0)
}//end if((ip==0)&&(ip==myid))
}//end yes_flag
//Check for errors, and if there is an error abort
AllCheckError(error_flag,myid,numprocs,world);
//Share jtot
MPI_Bcast(&jtot,1,MPI_DOUBLE,0,world);
} //end loop over nproc
if(myid==0)
{
//append the real part of the data to the data file
//printf("i %d outputting data\n");
//fflush(stdout);
if(!(fp = fopen(output_fname,"a")))
{
printf("Error opening %s by process %d\n",output_fname,myid);
fflush(stdout);
error_flag = 1;
}
if(!error_flag)
{
fwrite(xout_real,ny_out*nz,sizeof(double),fp);
fwrite(xout_imaginary,ny_out*nz,sizeof(double),fp);
fclose(fp);
}
}
//Check for errors, and if there is an error abort
AllCheckError(error_flag,myid,numprocs,world);
} //end loop over x
//free some data
free(all_local_ny);
free(all_local_y_start);
//free the grid pages
if(myid==0)
{
free(xout_real);
free(xout_imaginary);
}
//done!
}
void grid_particle_data(int npart, float *pos, double *data, int nx_local_start, int nx_local, int n_local_size, int nx, int ny, int nz, int npart_total, double BoxSize, int myid, int numprocs, MPI_Comm world)
{
double BS = BoxSize*1000.0; //in kpc/h
#ifdef CLOUD_IN_CELL
grid_particle_data_cloud_in_cell( npart, pos, data, nx_local_start, nx_local, n_local_size, nx, ny, nz, npart_total, BS, myid, numprocs, world);
#else //CLOUD_IN_CELL
grid_particle_data_nearest_grid( npart, pos, data, nx_local_start, nx_local, n_local_size, nx, ny, nz, npart_total, BS, myid, numprocs, world);
#endif //CLOUD_IN_CELL
}
void grid_particle_data_cloud_in_cell(int npart, float *pos, double *data, int nx_local_start, int nx_local, int n_local_size, int nx, int ny, int nz, int npart_total, double BoxSize, int myid, int numprocs, MPI_Comm world)
{
//grid particle data using the cloud in cell method
//need to adjust CIC to deal with different grid sizes
int error_flag = 0;
int i,j,k;
int ic, jc, kc;
int ijk;
double xc, yc, zc;
double xp, yp, zp;
double dx;
double dy;
double dz;
double tx;
double ty;
double tz;
double value;
int u_dest = myid+1;
int u_source = myid-1;
int l_dest = myid-1;
int l_source = myid+1;
char variable_name[200];
//this buffer allows for imperfect CIC
//assignments for varying grid cells
int nxb = 10;
int sbuf_size = nxb*ny*(2*(nz/2+1));
double *x_u, *x_ur;
double *x_l, *x_lr;
double x_u_count = 0;
double x_l_count = 0;
MPI_Request requests[4];
MPI_Status statuses[4];
//wrap destinations and sources
if(u_dest>=numprocs)
u_dest-=numprocs;
if(u_source<0)
u_source+=numprocs;
if(l_dest<0)
l_dest+=numprocs;
if(l_source>=numprocs)
l_source-=numprocs;
//first, initialize the grid to zero
for(i=0;i<nx_local;++i)
for(j=0;j<ny;++j)
for(k=0;k<nz;++k)
data[ (i*ny + j) * (2*(nz/2+1)) + k] = 0.0;
//we need to allocate the x-direction grid buffers
if(myid==0)
{
printf("\n");
fflush(stdout);
}
// grid for densities interpolated on grid slab before this slab
sprintf(variable_name,"x_l");
//x_l = allocate_real_fftw_grid(nxb*ny*(2*(nz/2+1)), "x_l", myid, numprocs, world,0);
x_l = allocate_real_fftw_grid(nxb*ny*(2*(nz/2+1)), variable_name, myid, numprocs, world,0);
//x_lr = allocate_real_fftw_grid(nxb*ny*(2*(nz/2+1)), "x_lr", myid, numprocs, world,0);
sprintf(variable_name,"x_lr");
x_lr = allocate_real_fftw_grid(nxb*ny*(2*(nz/2+1)), variable_name, myid, numprocs, world,0);
// grid for densities interpolated on grid slab after this slab
sprintf(variable_name,"x_u");
x_u = allocate_real_fftw_grid(nxb*ny*(2*(nz/2+1)), variable_name, myid, numprocs, world,0);
sprintf(variable_name,"x_ur");
x_ur = allocate_real_fftw_grid(nxb*ny*(2*(nz/2+1)), variable_name, myid, numprocs, world,0);
for(i=0;i<nxb;++i)
for(j=0;j<ny;++j)
for(k=0;k<nz;++k)
{
x_u[ (i*ny + j) * (2*(nz/2+1)) + k] = 0.0;
x_ur[ (i*ny + j) * (2*(nz/2+1)) + k] = 0.0;
x_l[ (i*ny + j) * (2*(nz/2+1)) + k] = 0.0;
x_lr[ (i*ny + j) * (2*(nz/2+1)) + k] = 0.0;
}
for(int ip=0;ip<npart;ip++)
{
xp = ((double) pos[3*ip + 0])*((double) nx)/BoxSize;
yp = ((double) pos[3*ip + 1])*((double) ny)/BoxSize;
zp = ((double) pos[3*ip + 2])*((double) nz)/BoxSize;
i = iifloor(xp);
j = iifloor(yp);
k = iifloor(zp);
//check to see if this particle is actually located
//in this slab
if( (i>=nx_local_start)&&(i<(nx_local_start+nx_local)) )
{
wrap_particle(&i,&j,&k,nx,ny,nz,&xp,&yp,&zp);
// cell centers
xc = ((double) i);
yc = ((double) j);
zc = ((double) k);
dx = xp - xc;
dy = yp - yc;
dz = zp - zc;
tx = 1 - dx;
ty = 1 - dy;
tz = 1 - dz;
//first do cell containing particle
ic = i-nx_local_start;
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error A on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = tx*ty*tz;
if(fabs(value)>=3.0)
{
printf("Error AA on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d tx %e ty %e tz %e value %e.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size,tx,ty,tz,value);
fflush(stdout);
error_flag = 1;
}
data[ijk] += value;
//do i,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error B on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = tx*dy*tz;
if(fabs(value)>=3.0)
{
printf("Error AB on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d tx %e dy %e tz %e value %e.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size,tx,dy,tz,value);
fflush(stdout);
error_flag = 1;
}
data[ijk] += value;
//do i,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error C on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = tx*ty*dz;
if(fabs(value)>=3.0)
{
printf("Error AC on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d tx %e dy %e tz %e value %e.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size,tx,dy,tz,value);
fflush(stdout);
error_flag = 1;
}
data[ijk] += value;
//do i,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error D on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = tx*dy*dz;
if(fabs(value)>=3.0)
{
printf("Error AD on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d tx %e dy %e dz %e value %e.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size,tx,dy,dz,value);
fflush(stdout);
error_flag = 1;
}
data[ijk] += value;
if(i+1<nx_local_start+nx_local)
{
//particle is completely on this processor
//do i+1,j,k
ic = i+1-nx_local_start;
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error E on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = dx*ty*tz;
data[ijk] += value;
//do i+1,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error F on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = dx*dy*tz;
data[ijk] += value;
//do i+1,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error G on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = dx*ty*dz;
data[ijk] += value;
//do i+1,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error H on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = dx*dy*dz;
data[ijk] += value;
}else{
//particle is shared between processors
//so add it to the x_u grid
//do i+1,j,k
ic = i+1-nx_local_start-nx_local;
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
value = dx*ty*tz;
x_u[ijk] += value;
//do i+1,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
value = dx*dy*tz;
x_u[ijk] += value;
//do i+1,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
value = dx*ty*dz;
x_u[ijk] += value;
//do i+1,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
value = dx*dy*dz;
x_u[ijk] += value;
}
}else{
//OK this particle isn't actually on the slab
//so we need to place it in one of the grid buffers
//but, if it's i coordinate is nx_local_start-1, then it will still be partially on
//this slab. So check for that case first
wrap_particle(&i,&j,&k,nx,ny,nz,&xp,&yp,&zp);
// cell centers
xc = ((double) i);
yc = ((double) j);
zc = ((double) k);
dx = xp - xc;
dy = yp - yc;
dz = zp - zc;
tx = 1 - dx;
ty = 1 - dy;
tz = 1 - dz;
if(i==(nx_local_start-1))
{
//particle is split between the previous slab and this slab
//do i,j,k, which are on the previous slab
ic = nxb-1;
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error BA on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = tx*ty*tz;
x_l[ijk] += value;
//do i,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error BB on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = tx*dy*tz;
x_l[ijk] += value;
//do i,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error BC on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = tx*ty*dz;
x_l[ijk] += value;
//do i,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error BD on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = tx*dy*dz;
x_l[ijk] += value;
//do the i+1,j,k values, which are on this slab
ic = 0;
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error BE on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = dx*ty*tz;
data[ijk] += value;
//do i+1,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error BF on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = dx*dy*tz;
data[ijk] += value;
//do i+1,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error BG on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = dx*ty*dz;
data[ijk] += value;
//do i+1,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error BH on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = dx*dy*dz;
data[ijk] += value;
}else{
//particle is completely on another slab
//if the particle is at i>=nx_local_start+nx_local
//then it belongs in x_u
if(i>=(nx_local_start+nx_local))
{
//particle belongs in x_u
//do i,j,k
ic = i-nx_local-nx_local_start;
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error CA on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d BS %e.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size,BoxSize);
printf("nx %d ny %d nz %d local_x %d nx_local_start %d\n",nx,ny,nz,nx_local, nx_local_start);
fflush(stdout);
error_flag = 1;
}
value = tx*ty*tz;
x_u[ijk] += value;
//do i,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error CB on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = tx*dy*tz;
x_u[ijk] += value;
//do i,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error CC on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = tx*ty*dz;
x_u[ijk] += value;
//do i,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error CD on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = tx*dy*dz;
x_u[ijk] += value;
//do i+1,j,k
ic = i+1-nx_local-nx_local_start;
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error CE on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d i %d j %d k %d lxs %d nx %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size,i,j,k,nx_local_start,nx_local);
fflush(stdout);
error_flag = 1;
}
value = dx*ty*tz;
x_u[ijk] += value;
//do i,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error CF on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = dx*dy*tz;
x_u[ijk] += value;
//do i,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error CG on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = dx*ty*dz;
x_u[ijk] += value;
//do i,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error CH on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = dx*dy*dz;
x_u[ijk] += value;
}else{
//particle belongs in x_l
//do i,j,k
ic = nxb+(i-nx_local_start);
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error DA on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = tx*ty*tz;
x_l[ijk] += value;
//do i,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error DB on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = tx*dy*tz;
x_l[ijk] += value;
//do i,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error DC on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = tx*ty*dz;
x_l[ijk] += value;
//do i,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error DD on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = tx*dy*dz;
x_l[ijk] += value;
//do i+1,j,k
ic = nxb+1+(i-nx_local_start);
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error DE on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = dx*ty*tz;
x_l[ijk] += value;
//do i,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error DF on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = dx*dy*tz;
x_l[ijk] += value;
//do i,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error DG on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = dx*ty*dz;
x_l[ijk] += value;
//do i,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=sbuf_size)
{
printf("Error DH on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nxb,ijk,sbuf_size);
fflush(stdout);
error_flag = 1;
}
value = dx*dy*dz;
x_l[ijk] += value;
}
}
}
}
MPI_Isend(x_u, nxb*ny*(2*(nz/2+1))*sizeof(double), MPI_BYTE, u_dest, myid, world, &requests[0]);
MPI_Irecv(x_ur, nxb*ny*(2*(nz/2+1))*sizeof(double), MPI_BYTE, u_source, u_source, world, &requests[1]);
MPI_Isend(x_l, nxb*ny*(2*(nz/2+1))*sizeof(double), MPI_BYTE, l_dest, myid, world, &requests[2]);
MPI_Irecv(x_lr, nxb*ny*(2*(nz/2+1))*sizeof(double), MPI_BYTE, l_source, l_source, world, &requests[3]);
MPI_Waitall(4, &requests[0], &statuses[0]);
MPI_Barrier(world);
if(myid==0)
{
printf("Done with grid overlap buffer exchange.\n");
fflush(stdout);
}
//add exchanged particles to grid
//do x_ur
for(i=0;i<nxb;++i)
for(j=0;j<ny;++j)
for(k=0;k<nz;++k)
data[ (i*ny + j) * (2*(nz/2+1)) + k] += x_ur[ (i*ny + j) * (2*(nz/2+1)) + k];
//do x_lr
for(i=0;i<nxb;++i)
for(j=0;j<ny;++j)
for(k=0;k<nz;++k)
data[ ((nx_local-1-(nxb-1-i))*ny + j) * (2*(nz/2+1)) + k] += x_lr[ (i*ny + j) * (2*(nz/2+1)) + k];
//Check for errors
AllCheckError(error_flag,myid,numprocs,world);
//done, so free x_l and x_u
free(x_l);
free(x_lr);
free(x_u);
free(x_ur);
}
double *interpolate_grid_data_cloud_in_cell_conditional(int npart, double *pos, double *data, double *condition, int nx_local_start, int nx_local, int n_local_size, int nx, int ny, int nz, int npart_total, double BoxSize, int myid, int numprocs, MPI_Comm world)
{
//#define SIGMA_CORRECTION
//grid particle data using the cloud in cell method
//need to adjust CIC to deal with different grid sizes
int error_flag = 0;
int i,j,k;
int ic, jc, kc;
int ijk;
double xc, yc, zc;
double xp, yp, zp;
double dx;
double dy;
double dz;
double tx;
double ty;
double tz;
double value;
double *answer; //array containing interpolated values
double *total_answer; //array containing interpolated values
double *count; //array containing interpolated values
double *total_count; //array containing interpolated values
int u_dest = myid+1;
int u_source = myid-1;
int l_dest = myid-1;
int l_source = myid+1;
int yes_flag;
char variable_name[200];
//this buffer allows for imperfect CIC
//assignments for varying grid cells
int nxb = 10;
int sbuf_size = nxb*ny*(2*(nz/2+1));
MPI_Request requests[4];
MPI_Status statuses[4];
#ifdef SIGMA_CORRECTION
double sigma_correction;
double threshold = 99.0;
#endif
//wrap destinations and sources
if(u_dest>=numprocs)
u_dest-=numprocs;
if(u_source<0)
u_source+=numprocs;
if(l_dest<0)
l_dest+=numprocs;
if(l_source>=numprocs)
l_source-=numprocs;
//we need to allocate the x-direction grid buffers
if(myid==0)
{
printf("\n");
fflush(stdout);
}
//allocate interpolated values
sprintf(variable_name,"answer");
answer = allocate_double_array(npart, variable_name, myid, numprocs, world, 0);
sprintf(variable_name,"total_answer");
total_answer = allocate_double_array(npart, variable_name, myid, numprocs, world, 0);
sprintf(variable_name,"count");
count = allocate_double_array(npart, variable_name, myid, numprocs, world, 0);
sprintf(variable_name,"total_count");
total_count = allocate_double_array(npart, variable_name, myid, numprocs, world, 0);
//initialize interpolated values
for(i=0;i<npart;++i)
{
answer[i] = 0;
total_answer[i] = 0;
}
//loop over the number of particles
//and interpolate
for(int ip=0;ip<npart;ip++)
{
xp = ((double) pos[3*ip + 0])*((double) nx)/BoxSize;
yp = ((double) pos[3*ip + 1])*((double) ny)/BoxSize;
zp = ((double) pos[3*ip + 2])*((double) nz)/BoxSize;
i = iifloor(xp);
j = iifloor(yp);
k = iifloor(zp);
//check to see if the i values of the CIC are
//in this slab
wrap_position(&i,&j,&k,nx,ny,nz,&xp,&yp,&zp);
yes_flag = 0;
if( (i>=nx_local_start)&&(i<(nx_local_start+nx_local)) )
yes_flag = 1;
#ifdef SIGMA_CORRECTION
sigma_correction = 0;
#endif
if(yes_flag)
{
count[ip]+=1.0;
// cell centers
xc = ((double) i);
yc = ((double) j);
zc = ((double) k);
dx = xp - xc;
dy = yp - yc;
dz = zp - zc;
tx = 1 - dx;
ty = 1 - dy;
tz = 1 - dz;
//first do cell containing particle
ic = i-nx_local_start;
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error A on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
#ifndef SIGMA_CORRECTION
value = tx*ty*tz*data[ijk];
#else //SIGMA_CORRECTION
if(condition[ijk]>=threshold)
{
value = 0;
}else{
sigma_correction += tx*ty*tz;
value = tx*ty*tz*data[ijk];
}
#endif //SIGMA_CORRECTION
answer[ip] += value;
//do i,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error B on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
#ifndef SIGMA_CORRECTION
value = tx*dy*tz*data[ijk];
#else //SIGMA_CORRECTION
if(condition[ijk]>=threshold)
{
value = 0;
}else{
sigma_correction += tx*dy*tz;
value = tx*dy*tz*data[ijk];
}
#endif //SIGMA_CORRECTION
answer[ip] += value;
//do i,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error C on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
#ifndef SIGMA_CORRECTION
value = tx*ty*dz*data[ijk];
#else //SIGMA_CORRECTION
if(condition[ijk]>=threshold)
{
value = 0;
}else{
sigma_correction += tx*ty*dz;
value = tx*ty*dz*data[ijk];
}
#endif //SIGMA_CORRECTION
answer[ip] += value;
//do i,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error D on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
#ifndef SIGMA_CORRECTION
value = tx*dy*dz*data[ijk];
#else //SIGMA_CORRECTION
if(condition[ijk]>=threshold)
{
value = 0;
}else{
sigma_correction += tx*dy*dz;
value = tx*dy*dz*data[ijk];
}
#endif //SIGMA_CORRECTION
answer[ip] += value;
}
//check the i+1 values in the CIC interpolation
yes_flag = 0;
if( ((i+1)>=nx_local_start)&&((i+1)<(nx_local_start+nx_local)) )
yes_flag = 1;
if((i+1==nx)&&(nx_local_start==0))
yes_flag = 1;
if((i+1==nx)&&(nx_local_start!=0))
yes_flag = 0;
if(yes_flag)
{
count[ip]+=1.0;
if((i+1)==nx)
{
xp -= ((double) nx);
i = -1;
}
// cell centers
xc = ((double) i);
yc = ((double) j);
zc = ((double) k);
dx = xp - xc;
dy = yp - yc;
dz = zp - zc;
tx = 1 - dx;
ty = 1 - dy;
tz = 1 - dz;
//first do cell containing particle
ic = (i+1)-nx_local_start;
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error BA on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
#ifndef SIGMA_CORRECTION
value = dx*ty*tz*data[ijk];
#else //SIGMA_CORRECTION
if(condition[ijk]>=threshold)
{
value = 0;
}else{
sigma_correction += dx*ty*tz;
value = dx*ty*tz*data[ijk];
}
#endif //SIGMA_CORRECTION
answer[ip] += value;
//do i,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error BB on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
#ifndef SIGMA_CORRECTION
value = dx*dy*tz*data[ijk];
#else //SIGMA_CORRECTION
if(condition[ijk]>=threshold)
{
value = 0;
}else{
sigma_correction += dx*dy*tz;
value = dx*dy*tz*data[ijk];
}
#endif //SIGMA_CORRECTION
answer[ip] += value;
//do i,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error BC on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
#ifndef SIGMA_CORRECTION
value = dx*ty*dz*data[ijk];
#else //SIGMA_CORRECTION
if(condition[ijk]>=threshold)
{
value = 0;
}else{
sigma_correction += dx*ty*dz;
value = dx*ty*dz*data[ijk];
}
#endif //SIGMA_CORRECTION
answer[ip] += value;
//do i,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error BD on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
#ifndef SIGMA_CORRECTION
value = dx*dy*dz*data[ijk];
#else //SIGMA_CORRECTION
if(condition[ijk]>=threshold)
{
value = 0;
}else{
sigma_correction += dx*dy*dz;
value = dx*dy*dz*data[ijk];
}
#endif //SIGMA_CORRECTION
answer[ip] += value;
}
#ifdef SIGMA_CORRECTION
if(sigma_correction!=0.0)
{
answer[ip]/=(sigma_correction);
}else{
answer[ip]=0.0;
}
#endif //SIGMA_CORRECTION
}//end loop over npart
//Check for errors
AllCheckError(error_flag,myid,numprocs,world);
//now sum up all contributions to each particle
MPI_Allreduce(answer,total_answer,npart,MPI_DOUBLE,MPI_SUM,world);
//now sum up all contributions to each particle
MPI_Allreduce(count,total_count,npart,MPI_DOUBLE,MPI_SUM,world);
for(int ip=0;ip<npart;ip++)
{
xp = ((double) pos[3*ip + 0])*((double) nx)/BoxSize;
yp = ((double) pos[3*ip + 1])*((double) ny)/BoxSize;
zp = ((double) pos[3*ip + 2])*((double) nz)/BoxSize;
i = iifloor(xp);
j = iifloor(yp);
k = iifloor(zp);
if(total_count[ip]>=3)
if(myid==0)
{
printf("Error XX on proc %d in x direction ip %d count %e x %e y %e z %e i %d j %d k %d.\n",myid,ip,total_count[ip],xp,yp,zp,i,j,k);
fflush(stdout);
}
}
//free processor slab data
free(answer);
free(total_count);
free(count);
return total_answer;
}
#ifdef PARTICLE_FLOAT
double *interpolate_grid_data_cloud_in_cell(int npart, float *pos, double *data, int nx_local_start, int nx_local, int n_local_size, int nx, int ny, int nz, int npart_total, double BoxSize, int myid, int numprocs, MPI_Comm world)
#else
double *interpolate_grid_data_cloud_in_cell(int npart, double *pos, double *data, int nx_local_start, int nx_local, int n_local_size, int nx, int ny, int nz, int npart_total, double BoxSize, int myid, int numprocs, MPI_Comm world)
#endif
{
//grid particle data using the cloud in cell method
//need to adjust CIC to deal with different grid sizes
int error_flag = 0;
int i,j,k;
int ic, jc, kc;
int ijk;
double xc, yc, zc;
double xp, yp, zp;
double dx;
double dy;
double dz;
double tx;
double ty;
double tz;
double value;
double *answer; //array containing interpolated values
double *total_answer; //array containing interpolated values
int u_dest = myid+1;
int u_source = myid-1;
int l_dest = myid-1;
int l_source = myid+1;
int yes_flag;
//this buffer allows for imperfect CIC
//assignments for varying grid cells
int nxb = 10;
int sbuf_size = nxb*ny*(2*(nz/2+1));
char variable_name[200];
MPI_Request requests[4];
MPI_Status statuses[4];
//wrap destinations and sources
if(u_dest>=numprocs)
u_dest-=numprocs;
if(u_source<0)
u_source+=numprocs;
if(l_dest<0)
l_dest+=numprocs;
if(l_source>=numprocs)
l_source-=numprocs;
//we need to allocate the x-direction grid buffers
if(myid==0)
{
printf("\n");
fflush(stdout);
}
//allocate interpolated values
sprintf(variable_name,"answer");
answer = allocate_double_array(npart, variable_name, myid, numprocs, world, 0);
sprintf(variable_name,"total_answer");
total_answer = allocate_double_array(npart, variable_name, myid, numprocs, world, 0);
//initialize interpolated values
for(i=0;i<npart;++i)
{
answer[i] = 0;
total_answer[i] = 0;
}
//loop over the number of particles
//and interpolate
for(int ip=0;ip<npart;ip++)
{
xp = ((double) pos[3*ip + 0])*((double) nx)/BoxSize;
yp = ((double) pos[3*ip + 1])*((double) ny)/BoxSize;
zp = ((double) pos[3*ip + 2])*((double) nz)/BoxSize;
i = iifloor(xp);
j = iifloor(yp);
k = iifloor(zp);
//check to see if the i values of the CIC are
//in this slab
wrap_position(&i,&j,&k,nx,ny,nz,&xp,&yp,&zp);
yes_flag = 0;
if( (i>=nx_local_start)&&(i<(nx_local_start+nx_local)) )
yes_flag = 1;
if(yes_flag)
{
// cell centers
xc = ((double) i);
yc = ((double) j);
zc = ((double) k);
dx = xp - xc;
dy = yp - yc;
dz = zp - zc;
tx = 1 - dx;
ty = 1 - dy;
tz = 1 - dz;
//first do cell containing particle
ic = i-nx_local_start;
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error A on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = tx*ty*tz*data[ijk];
answer[ip] += value;
//do i,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error B on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = tx*dy*tz*data[ijk];
answer[ip] += value;
//do i,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error C on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = tx*ty*dz*data[ijk];
answer[ip] += value;
//do i,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error D on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = tx*dy*dz*data[ijk];
answer[ip] += value;
}
//check the i+1 values in the CIC interpolation
yes_flag = 0;
if( ((i+1)>=nx_local_start)&&((i+1)<(nx_local_start+nx_local)) )
yes_flag = 1;
if((i+1==nx)&&(nx_local_start==0))
yes_flag = 1;
if((i+1==nx)&&(nx_local_start!=0))
yes_flag = 0;
if(yes_flag)
{
if((i+1)==nx)
{
xp -= ((double) nx);
i = -1;
}
// cell centers
xc = ((double) i);
yc = ((double) j);
zc = ((double) k);
dx = xp - xc;
dy = yp - yc;
dz = zp - zc;
tx = 1 - dx;
ty = 1 - dy;
tz = 1 - dz;
//first do cell containing particle
ic = (i+1)-nx_local_start;
jc = j;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error BA on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = dx*ty*tz*data[ijk];
answer[ip] += value;
//do i,j+1,k
jc = j+1;
kc = k;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error BB on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = dx*dy*tz*data[ijk];
answer[ip] += value;
//do i,j,k+1
jc = j;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error BC on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = dx*ty*dz*data[ijk];
answer[ip] += value;
//do i,j+1,k+1
jc = j+1;
kc = k+1;
wrap_indices(&ic,&jc,&kc,nx,ny,nz);
ijk = (ic*ny + jc) * (2*(nz/2+1)) + kc;
if(ijk>=n_local_size)
{
printf("Error BD on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d ijk %d tls %d.\n",myid,ip,xp,yp,zp,ic,jc,kc,nx_local,ijk,n_local_size);
fflush(stdout);
error_flag = 1;
}
value = dx*dy*dz*data[ijk];
answer[ip] += value;
}
}//end loop over npart
//Check for errors
AllCheckError(error_flag,myid,numprocs,world);
//now sum up all contributions to each particle
MPI_Allreduce(answer,total_answer,npart,MPI_DOUBLE,MPI_SUM,world);
//free processor slab data
free(answer);
return total_answer;
}
void grid_particle_data_nearest_grid(int npart, float *pos, double *data, int nx_local_start, int nx_local, int n_local_size, int nx, int ny, int nz, int npart_total, double BoxSize, int myid, int numprocs, MPI_Comm world)
{
//grid particle data using nearest grid point method
int error_flag = 0;
int i,j,k;
int ijk;
double x, y, z;
//first, initialize the grid to zero
for(i=0;i<nx_local;++i)
for(j=0;j<ny;++j)
for(k=0;k<nz;++k)
data[ (i*ny + j) * (2*(nz/2+1)) + k] = 0.0;
for(int ip=0;ip<npart;ip++)
{
x = ((double) pos[3*ip + 0])*((double) nx)/BoxSize;
y = ((double) pos[3*ip + 1])*((double) ny)/BoxSize;
z = ((double) pos[3*ip + 2])*((double) nz)/BoxSize;
i = iifloor(x) - nx_local_start;
j = iifloor(y);
k = iifloor(z);
wrap_indices(&i,&j,&k,nx,ny,nz);
if((i<0)||(i>=nx_local))
{
printf("Error on proc %d in x direction ip %d x %e y %e z %e i %d j %d k %d nxl %d.\n",myid,ip,x,y,z,i,j,k,nx_local);
fflush(stdout);
error_flag = 1;
}
ijk = (i*ny + j) * (2*(nz/2+1)) + k;
if(!error_flag)
if(ijk>n_local_size)
{
printf("Error on proc %d ip %d x %e y %e z %e i %d j %d k %d nxl %d.\n",myid,ip,x,y,z,i,j,k,nx_local);
fflush(stdout);
error_flag = 1;
}else{
data[ijk] += 1.0;
}
}
//Check for errors
AllCheckError(error_flag,myid,numprocs,world);
//done
}
void grid_to_overdensity(double *data, int total_npart, int nx, int ny, int nz, int nx_local_start, int nx_local)
{
double rho_mean = ((double) total_npart)/( ((double) nx) * ((double) ny) * ((double) nz) );
for(int i=0;i<nx_local;++i)
for(int j=0;j<ny;++j)
for(int k=0;k<nz;++k)
data[ (i*ny + j)*(2*(nz/2+1)) + k] = (data[ (i*ny + j)*(2*(nz/2+1)) + k]/rho_mean) - 1.0;
}
int iifloor(double x)
{
return ((int) floor(x));
}
void wrap_indices(int *ii, int *jj, int *kk, int nx, int ny, int nz)
{
//printf("wi ii %d jj %d kk %d N %d\n",*ii,*jj,*kk,N);
if(*jj<0)
{
*jj+=ny;
}else{
if(*jj>=ny)
*jj-=ny;
}
if(*kk<0)
{
*kk+=nz;
}else{
if(*kk>=nz)
{
*kk-=nz;
//printf("wi ii %d jj %d kk %d nx %d ny %d nz %d\n",*ii,*jj,*kk,nx,ny,nz);
//fflush(stdout);
}
}
}
void wrap_position(int *ii, int *jj, int *kk, int nx, int ny, int nz, double *xp, double *yp, double *zp)
{
if(*ii<0)
{
*ii+=nx;
*xp+=((double) nx);
}else{
if(*ii>=nx)
{
*ii-=nx;
*xp-=((double) nx);
}
}
if(*jj<0)
{
*jj+=ny;
*yp+=((double) ny);
}else{
if(*jj>=ny)
{
*jj-=ny;
*yp-=((double) ny);
}
}
if(*kk<0)
{
*kk+=nz;
*zp+=((double) nz);
}else{
if(*kk>=nz)
{
*kk-=nz;
*zp-=((double) nz);
//printf("wi ii %d jj %d kk %d nx %d ny %d nz %d\n",*ii,*jj,*kk,nx,ny,nz);
//fflush(stdout);
}
}
}
void wrap_particle(int *ii, int *jj, int *kk, int nx, int ny, int nz, double *xp, double *yp, double *zp)
{
//printf("wi ii %d jj %d kk %d N %d\n",*ii,*jj,*kk,N);
if(*jj<0)
{
*jj+=ny;
*yp+=((double) ny);
}else{
if(*jj>=ny)
{
*jj-=ny;
*yp-=((double) ny);
}
}
if(*kk<0)
{
*kk+=nz;
*zp+=((double) nz);
}else{
if(*kk>=nz)
{
*kk-=nz;
*zp-=((double) nz);
//printf("wi ii %d jj %d kk %d nx %d ny %d nz %d\n",*ii,*jj,*kk,nx,ny,nz);
//fflush(stdout);
}
}
}
float *get_particle_data(char *fname_particle_data, int *npart, int *total_npart, int myid, int numprocs, MPI_Comm world)
{
FILE *fp_particle_data;
float *pos;
int error_flag = 0;
int flag_tot = 0;
//printf("myid %d particle data %s\n",myid,fname_particle_data);
//fflush(stdout);
if(!(fp_particle_data = fopen(fname_particle_data,"r")))
{
printf("Error opening %s on process %d.\n",fname_particle_data,myid);
fflush(stdout);
error_flag=1;
}
AllCheckError(error_flag,myid,numprocs,world);
fread(npart,sizeof(int),1,fp_particle_data);
if(!(pos = (float *) malloc(3*(*npart)*sizeof(float))))
{
printf("Error allocating pos on process %d.\n",myid);
error_flag = 1;
}
//check for errors
AllCheckError(error_flag,myid,numprocs,world);
fread(pos,sizeof(float),3*(*npart),fp_particle_data);
fclose(fp_particle_data);
MPI_Allreduce(npart,total_npart,1,MPI_INT,MPI_SUM,world);
return pos;
}
void AllCheckError(int error_flag, int myid, int numprocs, MPI_Comm world)
{
int total_error = 0;
MPI_Allreduce(&error_flag,&total_error,1,MPI_INT,MPI_SUM,world);
if(total_error)
{
if(myid==0)
{
printf("Aborting...\n");
fflush(stdout);
}
MPI_Abort(world,total_error);
exit(-1);
}
}
void check_window_function(char *window_function_fname, double *window_data, fftw_complex *cwindow_data, double *work, double BoxSize, double R, int nx, int ny, int nz, int ixmin, int ixmax, int iymin, int iymax, int izmin, int izmax, int nx_local_start, int nx_local, int n_local_size, int local_ny_after_transpose, int myid, int numprocs, MPI_Comm world)
{
FFTW_Grid_Info grid_info;
int x, y, z;
//make the units easy
BoxSize = 120.0;
R = 10.0;
//initialize window function
for(x=0;x<nx_local;++x)
for(y=0;y<ny;++y)
for(z=0;z<nz;++z)
window_data[(x*ny + y) * (2*(nz/2+1)) + z] = window_function(R,BoxSize,x+nx_local_start,y,z,nx,ny,nz);
if(myid==0)
{
printf("Outputting real window function...\n");
fflush(stdout);
}
//output the real space window function
sprintf(window_function_fname,"window_function.real_space.dat");
grid_info.nx = nx;
grid_info.ny = ny;
grid_info.nz = nz;
grid_info.n_local_size = n_local_size;
grid_info.nx_local = nx_local;
grid_info.local_ny_after_transpose = local_ny_after_transpose ;
grid_info.nx_local_start = nx_local_start;
//grid_info.local_y_start_after_transpose = local_y_start_after_transpose ;
//output_fft_grid(window_function_fname, window_data, nx, ny, nz, ixmin, ixmax, iymin, iymax, izmin, izmax, nx_local_start, nx_local, n_local_size, myid, numprocs, world);
output_fft_grid(window_function_fname, window_data, grid_info, ixmin, ixmax, iymin, iymax, izmin, izmax, myid, numprocs, world);
//Do the forward transform on the window function
if(myid==0)
{
printf("Performing forward transform on window function...\n");
fflush(stdout);
}
//perform forward transform here
forward_transform_fftw_grid(window_data, work, cwindow_data, grid_info, myid, numprocs, world);
//the window function is now complex, so typecast a pointer
cwindow_data = (fftw_complex *) window_data;
//output the k-space window function
if(myid==0)
{
printf("Outputting complex window function transform...\n");
fflush(stdout);
}
sprintf(window_function_fname,"window_function.k_space.complex.dat");
output_fft_grid_complex(window_function_fname, cwindow_data, nx, ny, nz, ixmin, ixmax, iymin, iymax, izmin, izmax, nx_local_start, nx_local, n_local_size, myid, numprocs, world);
//if we are just checking the window function, we are done.
if(myid==0)
{
printf("Done checking window function; exiting.\n");
fflush(stdout);
}
//done
}
double *input_fft_grid(char *input_fname, int *nx, int *ny, int *nz, int *ixmin, int *ixmax, int *iymin, int *iymax, int *izmin, int *izmax, int *nx_local_start, int *nx_local, int *local_y_start_after_transpose, int *local_ny_after_transpose, int *n_local_size, int myid, int numprocs, MPI_Comm world)
{
//read in an fft grid file
FILE *fp;
FFTW_Grid_Info grid_info;
int ijk;
int ijk_in;
double *xbuf;
int error_flag = 0;
int itot;
int *nx_local_array;
int *nx_local_start_array;
char variable_name[200];
int nzl;
double *data;
MPI_Status status;
//open the data file
if(myid==0)
{
if(!(fp = fopen(input_fname,"r")))
{
printf("Error opening %s by process %d\n",input_fname,myid);
fflush(stdout);
error_flag = 1;
}
}
AllCheckError(error_flag,myid,numprocs,world);
if(myid==0)
{
//read in the essential info about the file
//read the grid dimensions
fread(nx,1,sizeof(int),fp);
fread(ny,1,sizeof(int),fp);
fread(nz,1,sizeof(int),fp);
//read the restricted grid dimensions
fread(ixmin,1,sizeof(int),fp);
fread(ixmax,1,sizeof(int),fp);
fread(iymin,1,sizeof(int),fp);
fread(iymax,1,sizeof(int),fp);
fread(izmin,1,sizeof(int),fp);
fread(izmax,1,sizeof(int),fp);
}
//send the file info to all the processors
MPI_Bcast(nx,1,MPI_INT,0,world);
MPI_Bcast(ny,1,MPI_INT,0,world);
MPI_Bcast(nz,1,MPI_INT,0,world);
MPI_Bcast(ixmin,1,MPI_INT,0,world);
MPI_Bcast(ixmax,1,MPI_INT,0,world);
MPI_Bcast(iymin,1,MPI_INT,0,world);
MPI_Bcast(iymax,1,MPI_INT,0,world);
MPI_Bcast(izmin,1,MPI_INT,0,world);
MPI_Bcast(izmax,1,MPI_INT,0,world);
//initialize fttw grid
grid_info.nx = *nx;
grid_info.ny = *ny;
grid_info.nz = *nz;
if(grid_info.nz==1)
{
grid_info.ndim=2;
grid_info.nz=0;
nzl=1;
}else{
grid_info.ndim=3;
nzl=grid_info.nz;
}
initialize_fftw_grid(&grid_info, myid, numprocs, world);
//establish local sizes for the fftw
initialize_mpi_local_sizes(&grid_info, myid, numprocs, world);
*nx_local = grid_info.nx_local;
*local_ny_after_transpose = grid_info.local_ny_after_transpose;
*nx_local_start = grid_info.nx_local_start;
*local_y_start_after_transpose = grid_info.local_y_start_after_transpose;
*n_local_size = grid_info.n_local_size;
//Allocate the grid data for each processor
sprintf(variable_name,"data");
data = allocate_real_fftw_grid(*n_local_size, variable_name, myid, numprocs, world, 0);
//exchange the nx_local and nx_local_start arrays
sprintf(variable_name,"nx_local_array");
nx_local_array = allocate_int_array(numprocs, variable_name, myid, numprocs, world, 0);
sprintf(variable_name,"nx_local_start_array");
nx_local_start_array = allocate_int_array(numprocs, variable_name, myid, numprocs, world, 0);
nx_local_array[myid] = *nx_local;
nx_local_start_array[myid] = *nx_local_start;
MPI_Allgather(nx_local, 1,MPI_INT,nx_local_array, 1,MPI_INT,world);
MPI_Allgather(nx_local_start, 1,MPI_INT,nx_local_start_array,1,MPI_INT,world);
//read in the data for the root process
if(myid==0)
{
printf("Reading in grid data...\n");
fflush(stdout);
}
for(int ip=0;ip<numprocs;ip++)
{
sprintf(variable_name,"xbuf");
xbuf = allocate_double_array(nx_local_array[ip]*(*ny)*(*nz), variable_name, myid, numprocs, world, 0);
if(ip==myid)
{
if(myid==0)
{
fread(xbuf,nx_local_array[ip]*(*ny)*(*nz),sizeof(double),fp);
}else{
MPI_Recv(xbuf,nx_local_array[ip]*(*ny)*(*nz),MPI_DOUBLE,0,ip,world,&status);
}
for(int i=0;i<nx_local_array[myid];++i)
for(int j=0;j<(*ny);++j)
for(int k=0;k<(*nz);++k)
{
ijk_in = ( i*(*ny) + j )*(*nz) + k;
//ijk = ( i*(*ny) + j )*(2*((*nz)/2+1)) + k;
ijk = grid_ijk(i,j,k,grid_info);
data[ijk] = xbuf[ijk_in];
}
}else{
if(myid==0)
{
fread( xbuf,nx_local_array[ip]*(*ny)*(*nz),sizeof(double),fp);
MPI_Send(xbuf,nx_local_array[ip]*(*ny)*(*nz),MPI_DOUBLE,ip,ip,world);
}
}
free(xbuf);
MPI_Barrier(world);
}
if(myid==0)
{
printf("done!\n");
fflush(stdout);
}
if(myid==0)
fclose(fp);
free(nx_local_array);
free(nx_local_start_array);
return data;
}
double window_function(double Rw, double BoxSize, int x, int y, int z, int nx, int ny, int nz)
{
#ifdef GAUSSIAN
//use a gaussian window function
return gaussian_window(Rw, BoxSize, x, y, z, nx, ny, nz);
#else //GAUSSIAN
#ifdef REAL_SPACE_TOPHAT
//use a real space tophat window function
return real_space_tophat_window(Rw, BoxSize, x, y, z, nx, ny, nz);
#else //REAL_SPACE_TOPHAT
//use the default
//which is a gaussian window function
return gaussian_window(Rw, BoxSize, x, y, z, nx, ny, nz);
#endif //REAL_SPACE_TOPHAT
#endif //GAUSSIAN
}
double real_space_tophat_window(double Rw, double BoxSize, int x, int y, int z, int nx, int ny, int nz)
{
double R;
double dx;
double dy;
double dz;
double W;
if(x>nx/2)
{
dx = (double) (x-nx);
}else{
dx = (double) x;
}
if(y>ny/2)
{
dy = (double) (y-ny);
}else{
dy = (double) y;
}
if(z>nz/2)
{
dz = (double) (z-nz);
}else{
dz = (double) z;
}
dx*=BoxSize/((double) nx);
dy*=BoxSize/((double) ny);
dz*=BoxSize/((double) nz);
R = sqrt( dx*dx + dy*dy + dz*dz);
if(R<=Rw)
{
#ifdef TEST_ONE_DIMENSION
W = 1.0/(2.*Rw);
#else //TEST_ONE_DIMENSION
W = 1.0/(4.*M_PI*Rw*Rw*Rw/3.0);
#endif //TEST_ONE_DIMENSION
}else{
W = 0.0;
}
return W;
}
double gaussian_window(double Rw, double BoxSize, int x, int y, int z, int nx, int ny, int nz)
{
double R;
double dx;
double dy;
double dz;
double W;
if(x>nx/2)
{
dx = (double) (x-nx);
}else{
dx = (double) x;
}
if(y>ny/2)
{
dy = (double) (y-ny);
}else{
dy = (double) y;
}
if(z>nz/2)
{
dz = (double) (z-nz);
}else{
dz = (double) z;
}
dx*=BoxSize/((double) nx );
dy*=BoxSize/((double) ny );
dz*=BoxSize/((double) nz );
R = sqrt( dx*dx + dy*dy + dz*dz);
#ifdef TEST_ONE_DIMENSION
W = exp(-R*R/(2*Rw*Rw))/sqrt(2*C.pi*Rw*Rw);
#else //TEST_ONE_DIMENSION
W = exp(-R*R/(2*Rw*Rw))/pow(2*M_PI*Rw*Rw,1.5);
#endif //TEST_ONE_DIMENSION
return W;
}
double vector_magnitude(double *x, int ndim)
{
double dp = 0.;
for(int i=0;i<ndim;i++)
dp += x[i] * x[i];
return sqrt(dp);
}
double vector_dot_product(double *x, double *y, int ndim)
{
double dp = 0.;
for(int i=0;i<ndim;i++)
dp += x[i] * y[i];
return dp;
}
double *vector_cross_product(double *x, double *y, int ndim)
{
double *cp;
if(ndim==2)
{
cp = (double *) calloc(1,sizeof(double));
cp[0] = x[0]*y[1] - x[1]*y[0];
}else{
cp = (double *) calloc(3,sizeof(double));
cp[0] = x[1]*y[2] - x[2]*y[1];
cp[1] = x[2]*y[0] - x[0]*y[2];
cp[2] = x[0]*y[1] - x[1]*y[0];
}
return cp;
}
*/
| {
"alphanum_fraction": 0.5956011349,
"avg_line_length": 22.218960539,
"ext": "c",
"hexsha": "c72bdfe758f65aaaa12cbcca41c524ad89fd81c7",
"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": "729b3336c5f1e734d7307ac83ea2306af32761cc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "brantr/grid-fft",
"max_forks_repo_path": "grid_fft.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "729b3336c5f1e734d7307ac83ea2306af32761cc",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "brantr/grid-fft",
"max_issues_repo_path": "grid_fft.c",
"max_line_length": 356,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "729b3336c5f1e734d7307ac83ea2306af32761cc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "brantr/grid-fft",
"max_stars_repo_path": "grid_fft.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 32584,
"size": 92342
} |
#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 read_MCMC_state(MCMC_info *MCMC) {
char filename_output_dir[SID_MAX_FILENAME_LENGTH];
char filename_chain_dir[SID_MAX_FILENAME_LENGTH];
char filename_results_dir[SID_MAX_FILENAME_LENGTH];
char filename_plots_dir[SID_MAX_FILENAME_LENGTH];
char filename_run[SID_MAX_FILENAME_LENGTH];
char filename_chain[SID_MAX_FILENAME_LENGTH];
char filename_chain_config[SID_MAX_FILENAME_LENGTH];
char filename_stats[SID_MAX_FILENAME_LENGTH];
char filename_coverage[SID_MAX_FILENAME_LENGTH];
char filename_chain_covariance[SID_MAX_FILENAME_LENGTH];
char filename_covariance[SID_MAX_FILENAME_LENGTH];
char filename_histograms[SID_MAX_FILENAME_LENGTH];
char filename_results[SID_MAX_FILENAME_LENGTH];
char filename_stop[SID_MAX_FILENAME_LENGTH];
char format_string[32];
int my_chain;
int i_P, i_DS, i_M, i_array;
double * V_read;
FILE * fp_run;
FILE * fp_chain;
FILE * fp_chain_config;
FILE * fp_stats;
FILE * fp_coverage;
FILE * fp_chain_covariance;
FILE * fp_covariance;
FILE * fp_histograms;
FILE * fp_results;
FILE * fp_stop;
MCMC_DS_info *current_DS;
set_MCMC_mode(MCMC, MCMC_MODE_DEFAULT);
my_chain = MCMC->my_chain;
SID_log("Reading MCMC state from {%s}...", SID_LOG_OPEN, MCMC->filename_output_dir);
// Set directories
sprintf(filename_output_dir, "%s/", MCMC->filename_output_dir);
sprintf(filename_chain_dir, "%s/chains/", MCMC->filename_output_dir);
sprintf(filename_results_dir, "%s/results/", MCMC->filename_output_dir);
sprintf(filename_plots_dir, "%s/plots/", MCMC->filename_output_dir);
// Set filenames
sprintf(filename_run, "%s/run.dat", MCMC->filename_output_dir);
sprintf(filename_chain, "%s/chain_trace_%06d.dat", filename_chain_dir, my_chain);
sprintf(filename_chain_config, "%s/chain_config_%06d.dat", filename_chain_dir, my_chain);
sprintf(filename_chain_covariance, "%s/chain_covariance_%06d.dat", filename_chain_dir, my_chain);
sprintf(filename_stats, "%s/chain_stats_%06d.dat", filename_chain_dir, my_chain);
sprintf(filename_coverage, "%s/coverage.dat", filename_results_dir);
sprintf(filename_histograms, "%s/histograms.dat", filename_results_dir);
sprintf(filename_covariance, "%s/covariance.dat", filename_results_dir);
MCMC->map_P_to_M = NULL;
MCMC->compute_MCMC_ln_likelihood = compute_MCMC_ln_likelihood_default;
MCMC->params = NULL;
MCMC->temperature = 1.0;
MCMC->n_P = 0;
MCMC->n_thin = 1;
MCMC->n_DS = 0;
MCMC->n_M_total = 0;
MCMC->n_arrays = 0;
MCMC->n_M = NULL;
MCMC->array = NULL;
MCMC->V = NULL;
MCMC->m = NULL;
MCMC->b = NULL;
MCMC->RNG = NULL;
MCMC->flag_integrate_on = GBP_TRUE;
MCMC->flag_analysis_on = GBP_TRUE;
MCMC->first_map_call = GBP_TRUE;
MCMC->mode = MCMC_MODE_DEFAULT;
MCMC->DS = NULL;
MCMC->last = NULL;
// Read/Write Header file
if((fp_run = fopen(filename_run, "rb")) != NULL) {
fp_run = fopen(filename_run, "rb");
SID_fread_verify(MCMC->problem_name, sizeof(char), MCMC_NAME_SIZE, fp_run);
SID_fread_verify(&(MCMC->n_chains), sizeof(int), 1, fp_run);
SID_fread_verify(&(MCMC->n_avg), sizeof(int), 1, fp_run);
SID_fread_verify(&(MCMC->flag_autocor_on), sizeof(int), 1, fp_run);
SID_fread_verify(&(MCMC->flag_no_map_write), sizeof(int), 1, fp_run);
SID_fread_verify(&(MCMC->n_P), sizeof(int), 1, fp_run);
SID_log("Problem name ={%s}", SID_LOG_COMMENT, MCMC->problem_name);
SID_log("n_avg ={%d}", SID_LOG_COMMENT, MCMC->n_avg);
SID_log("flag_autocor_on ={%d}", SID_LOG_COMMENT, MCMC->flag_autocor_on);
MCMC->P_names = (char **)SID_malloc(sizeof(char *) * MCMC->n_P);
MCMC->P_init = (double *)SID_malloc(sizeof(double) * MCMC->n_P);
MCMC->P_new = (double *)SID_malloc(sizeof(double) * MCMC->n_P);
MCMC->P_last = (double *)SID_malloc(sizeof(double) * MCMC->n_P);
MCMC->P_chain = (double *)SID_malloc(sizeof(double) * MCMC->n_P);
MCMC->P_limit_min = (double *)SID_malloc(sizeof(double) * MCMC->n_P);
MCMC->P_limit_max = (double *)SID_malloc(sizeof(double) * MCMC->n_P);
for(i_P = 0; i_P < MCMC->n_P; i_P++)
MCMC->P_limit_min[i_P] = -DBL_MAX * 1e-3;
for(i_P = 0; i_P < MCMC->n_P; i_P++)
MCMC->P_limit_max[i_P] = DBL_MAX * 1e-3;
SID_log("Parameters (name, initial_value,limit min,limit max):", SID_LOG_OPEN);
MCMC->P_name_length = 0;
for(i_P = 0; i_P < MCMC->n_P; i_P++) {
MCMC->P_names[i_P] = (char *)SID_malloc(sizeof(char) * MCMC_NAME_SIZE);
SID_fread_verify(MCMC->P_names[i_P], sizeof(char), MCMC_NAME_SIZE, fp_run);
SID_fread_verify(&(MCMC->P_init[i_P]), sizeof(double), 1, fp_run);
SID_fread_verify(&(MCMC->P_limit_min[i_P]), sizeof(double), 1, fp_run);
SID_fread_verify(&(MCMC->P_limit_max[i_P]), sizeof(double), 1, fp_run);
MCMC->P_name_length = GBP_MAX((size_t)(MCMC->P_name_length), strlen(MCMC->P_names[i_P]));
}
sprintf(MCMC->P_name_format, "%%-%ds", MCMC->P_name_length);
sprintf(format_string, "%s %%13.6le %%13.6le %%13.6le", MCMC->P_name_format);
for(i_P = 0; i_P < MCMC->n_P; i_P++)
SID_log(format_string, SID_LOG_COMMENT, MCMC->P_names[i_P], MCMC->P_init[i_P], MCMC->P_limit_min[i_P], MCMC->P_limit_max[i_P]);
SID_log(NULL, SID_LOG_CLOSE | SID_LOG_NOPRINT);
SID_fread_verify(&(MCMC->n_arrays), sizeof(int), 1, fp_run);
SID_log("n_arrays=%d", SID_LOG_OPEN, MCMC->n_arrays);
MCMC->array = (double **)SID_malloc(sizeof(double *) * MCMC->n_arrays);
MCMC->array_name = (char **)SID_malloc(sizeof(char *) * MCMC->n_arrays);
for(i_array = 0; i_array < MCMC->n_arrays; i_array++) {
MCMC->array[i_array] = (double *)SID_malloc(sizeof(double) * MCMC->n_P);
MCMC->array_name[i_array] = (char *)SID_malloc(sizeof(char) * MCMC_NAME_SIZE);
SID_fread_verify(MCMC->array_name[i_array], sizeof(char), MCMC_NAME_SIZE, fp_run);
SID_fread_verify(MCMC->array[i_array], sizeof(double), MCMC->n_P, fp_run);
SID_log("array #%03d name ={%s}", SID_LOG_COMMENT, i_array, MCMC->array_name[i_array]);
}
SID_log(NULL, SID_LOG_CLOSE | SID_LOG_NOPRINT);
SID_fread_verify(&(MCMC->n_DS), sizeof(int), 1, fp_run);
SID_log("Reading %d datasets...", SID_LOG_OPEN, MCMC->n_DS);
for(i_DS = 0; i_DS < MCMC->n_DS; i_DS++) {
SID_log("Dataset #%03d:", SID_LOG_OPEN, i_DS);
current_DS = (MCMC_DS_info *)SID_malloc(sizeof(MCMC_DS_info));
SID_fread_verify(current_DS->name, sizeof(char), MCMC_NAME_SIZE, fp_run);
SID_fread_verify(&(current_DS->n_M), sizeof(int), 1, fp_run);
MCMC->n_M_total += current_DS->n_M;
SID_log("name ={%s}", SID_LOG_COMMENT, current_DS->name);
SID_log("n_M =%d", SID_LOG_COMMENT, current_DS->n_M);
current_DS->M_target = (double *)SID_malloc(sizeof(double) * current_DS->n_M);
current_DS->dM_target = (double *)SID_malloc(sizeof(double) * current_DS->n_M);
current_DS->params = NULL;
SID_fread_verify(current_DS->M_target, sizeof(double), current_DS->n_M, fp_run);
SID_fread_verify(current_DS->dM_target, sizeof(double), current_DS->n_M, fp_run);
SID_fread_verify(&(current_DS->n_arrays), sizeof(int), 1, fp_run);
SID_log("n_arrays=%d", SID_LOG_OPEN, current_DS->n_arrays);
current_DS->array = (double **)SID_malloc(sizeof(double *) * current_DS->n_arrays);
current_DS->array_name = (char **)SID_malloc(sizeof(char *) * current_DS->n_arrays);
for(i_array = 0; i_array < current_DS->n_arrays; i_array++) {
current_DS->array[i_array] = (double *)SID_malloc(sizeof(double) * current_DS->n_M);
current_DS->array_name[i_array] = (char *)SID_malloc(sizeof(char) * MCMC_NAME_SIZE);
SID_fread_verify(current_DS->array_name[i_array], sizeof(char), MCMC_NAME_SIZE, fp_run);
SID_fread_verify(current_DS->array[i_array], sizeof(double), current_DS->n_M, fp_run);
SID_log("array #%03d name={%s}", SID_LOG_COMMENT, i_array, current_DS->array_name[i_array]);
}
SID_log(NULL, SID_LOG_CLOSE | SID_LOG_NOPRINT);
current_DS->next = NULL;
if(MCMC->DS == NULL)
MCMC->DS = current_DS;
else
MCMC->last->next = current_DS;
MCMC->last = current_DS;
SID_log(NULL, SID_LOG_CLOSE | SID_LOG_NOPRINT);
}
SID_log("Done.", SID_LOG_CLOSE);
fclose(fp_run);
}
// ... fetch the number of intervals that have already been computed ...
fp_chain_config = fopen(filename_chain_config, "rb");
V_read = (double *)SID_malloc(sizeof(double) * MCMC->n_P * MCMC->n_P);
SID_fread_verify(&(MCMC->n_iterations), sizeof(int), 1, fp_chain_config);
SID_fread_verify(&(MCMC->n_iterations_burn), sizeof(int), 1, fp_chain_config);
// ... fetch the temperature and covariance matrix that was being used
SID_fread_verify(&(MCMC->temperature), sizeof(double), 1, fp_chain_config);
SID_fread_verify(V_read, sizeof(double), MCMC->n_P * MCMC->n_P, fp_chain_config);
set_MCMC_covariance(MCMC, V_read);
SID_free(SID_FARG V_read);
// Initialize dataset arrays
init_MCMC_arrays(MCMC);
SID_log("# burn iterations = %d", SID_LOG_COMMENT, MCMC->n_iterations_burn);
SID_log("# total iterations = %d", SID_LOG_COMMENT, MCMC->n_iterations);
SID_log("Temperature = %le", SID_LOG_COMMENT, MCMC->temperature);
fclose(fp_chain_config);
SID_log("Done.", SID_LOG_CLOSE);
}
| {
"alphanum_fraction": 0.6166234728,
"avg_line_length": 54.8426395939,
"ext": "c",
"hexsha": "51c2981794894dc829ed9c9b70bbba0e49b4de7c",
"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/read_MCMC_state.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/read_MCMC_state.c",
"max_line_length": 139,
"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/read_MCMC_state.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": 2974,
"size": 10804
} |
/**
*
* @file core_dgbtype2cb.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:50 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_dgbtype2cb is a kernel that will operate on a region (triangle) of data
* bounded by st and ed. This kernel apply the right update remaining from the
* type1 and this later will create a bulge so it eliminate the first column of
* the created bulge and do the corresponding Left update.
*
* 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[in, out] V
* double array, dimension N if eigenvalue only
* requested or (LDV*blkcnt*Vblksiz) if Eigenvectors requested
* The Householder reflectors of the previous type 1 are used here
* to continue update then new one are generated to eliminate the
* bulge and stored in this array.
*
* @param[in, out] TAU
* double array, dimension (N).
* The scalar factors of the Householder reflectors of the previous
* type 1 are used here to continue update then new one are generated
* to eliminate the bulge and 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 2-BAND-bidiag Lower/Upper columnwise-Householder
***************************************************************************/
void
CORE_dgbtype2cb(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, J1, J2, len, lem, LDX;
int blkid, vpos, taupos, tpos;
LDX = LDA-1;
J1 = ed+1;
J2 = min(ed+NB,N-1);
lem = ed-st+1;
len = J2-J1+1;
if( uplo == PlasmaUpper ) {
/* ========================
* UPPER CASE
* ========================*/
if( len > 0 ) {
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);
}
/* Apply remaining Left commming from type1/3_upper */
ctmp = (*TAUQ(taupos));
LAPACKE_dlarfx_work(LAPACK_COL_MAJOR, lapack_const(PlasmaLeft),
lem, len, VQ(vpos), ctmp, AU(st, J1), LDX, WORK);
}
if( len > 1 ) {
if( WANTZ == 0 ) {
vpos = ((sweep+1)%2)*N + J1;
taupos = ((sweep+1)%2)*N + J1;
} else {
findVTpos(N,NB,Vblksiz,sweep,J1, &vpos, &taupos, &tpos, &blkid);
}
/* Remove the top row of the created bulge */
*VP(vpos) = 1.;
for(i=1; i<len; i++){
*VP(vpos+i) = (*AU(st, J1+i));
*AU(st, J1+i) = 0.;
}
/* Eliminate the row at st */
ctmp = (*AU(st, J1));
LAPACKE_dlarfg_work(len, &ctmp, VP(vpos+1), 1, TAUP(taupos) );
*AU(st, J1) = ctmp;
/*
* Apply Right on A(J1:J2,st+1:ed)
* We decrease len because we start at row st+1 instead of st.
* row st is the row that has been revomved;
*/
lem = lem-1;
ctmp = *TAUP(taupos);
LAPACKE_dlarfx_work(LAPACK_COL_MAJOR, lapack_const(PlasmaRight),
lem, len, VP(vpos), ctmp, AU(st+1, J1), LDX, WORK);
}
}else{
/* ========================
* LOWER CASE
* ========================*/
if( len > 0 ) {
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);
}
/* Apply remaining Right commming from type1/3_lower */
ctmp = (*TAUP(taupos));
LAPACKE_dlarfx_work(LAPACK_COL_MAJOR, lapack_const(PlasmaRight),
len, lem, VP(vpos), ctmp, AL(J1, st), LDX, WORK);
}
if( len > 1 ) {
if( WANTZ == 0 ) {
vpos = ((sweep+1)%2)*N + J1;
taupos = ((sweep+1)%2)*N + J1;
} else {
findVTpos(N,NB,Vblksiz,sweep,J1, &vpos, &taupos, &tpos, &blkid);
}
/* Remove the first column of the created bulge */
*VQ(vpos) = 1.;
memcpy(VQ(vpos+1), AL(J1+1, st), (len-1)*sizeof(double));
memset(AL(J1+1, st), 0, (len-1)*sizeof(double));
/* Eliminate the col at st */
LAPACKE_dlarfg_work(len, AL(J1, st), VQ(vpos+1), 1, TAUQ(taupos) );
/*
* Apply left on A(J1:J2,st+1:ed)
* We decrease len because we start at col st+1 instead of st.
* col st is the col that has been revomved;
*/
lem = lem-1;
ctmp = (*TAUQ(taupos));
LAPACKE_dlarfx_work(LAPACK_COL_MAJOR, lapack_const(PlasmaLeft),
len, lem, VQ(vpos), ctmp, AL(J1, st+1), LDX, WORK);
}
}
/* end of uplo case */
return;
}
/***************************************************************************/
#undef AU
#undef AL
#undef VQ
#undef VP
#undef TAUQ
#undef TAUP
| {
"alphanum_fraction": 0.4819937695,
"avg_line_length": 36.4772727273,
"ext": "c",
"hexsha": "ead017677a2cd61a6f53814f18ccf69044b1be01",
"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_dgbtype2cb.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_dgbtype2cb.c",
"max_line_length": 83,
"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_dgbtype2cb.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2201,
"size": 8025
} |
/******************************** Inclusions. ********************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/******************************** Definitions. *******************************/
#define MAX(x, y) ((x)>(y) ? (x) : (y))
#define MIN(x, y) ((x)<(y) ? (x) : (y))
| {
"alphanum_fraction": 0.3837837838,
"avg_line_length": 30.8333333333,
"ext": "h",
"hexsha": "fae780686c6e0229c4149362f2d12213b1ca7048",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-02-12T11:09:41.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-12T11:09:41.000Z",
"max_forks_repo_head_hexsha": "d5eb2828b31f139ff79e9aaac072dd15c707772e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "mgastner/impact-of-hypocrisy",
"max_forks_repo_path": "hypocrisy.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d5eb2828b31f139ff79e9aaac072dd15c707772e",
"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": "mgastner/impact-of-hypocrisy",
"max_issues_repo_path": "hypocrisy.h",
"max_line_length": 79,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "d5eb2828b31f139ff79e9aaac072dd15c707772e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mgastner/impact-of-hypocrisy",
"max_stars_repo_path": "hypocrisy.h",
"max_stars_repo_stars_event_max_datetime": "2021-10-04T18:22:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-10-09T15:29:18.000Z",
"num_tokens": 90,
"size": 370
} |
// Copyright (c) 2021 Stig Rune Sellevag
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.
#ifndef SCILIB_LINALG_LSTSQ_H
#define SCILIB_LINALG_LSTSQ_H
#ifdef USE_MKL
#include <mkl.h>
#else
#include <lapacke.h>
#endif
#include <scilib/mdarray.h>
#include <scilib/linalg_impl/lapack_types.h>
#include <experimental/mdspan>
#include <exception>
#include <algorithm>
#include <type_traits>
namespace Sci {
namespace Linalg {
// Compute the minimum norm-solution to a real linear least squares problem.
template <class Layout>
inline void lstsq(Sci::Matrix_view<double, Layout> a,
Sci::Matrix_view<double, Layout> b)
{
namespace stdex = std::experimental;
static_assert(a.is_contiguous());
static_assert(b.is_contiguous());
BLAS_INT m = static_cast<BLAS_INT>(a.extent(0));
BLAS_INT n = static_cast<BLAS_INT>(a.extent(1));
BLAS_INT nrhs = static_cast<BLAS_INT>(b.extent(1));
BLAS_INT rank;
double rcond = -1.0; // use machine epsilon
Sci::Vector<double, Layout> s(std::min(m, n)); // singular values of a
auto matrix_layout = LAPACK_ROW_MAJOR;
BLAS_INT lda = n;
BLAS_INT ldb = nrhs;
if constexpr (std::is_same_v<Layout, stdex::layout_left>) {
matrix_layout = LAPACK_COL_MAJOR;
lda = m;
ldb = n;
}
BLAS_INT info = LAPACKE_dgelsd(matrix_layout, m, n, nrhs, a.data(), lda,
b.data(), ldb, s.data(), rcond, &rank);
if (info != 0) {
throw std::runtime_error("dgelsd failed");
}
}
template <class Layout, class Allocator>
inline void lstsq(Sci::Matrix<double, Layout, Allocator>& a,
Sci::Matrix<double, Layout, Allocator>& b)
{
lstsq(a.view(), b.view());
}
} // namespace Linalg
} // namespace Sci
#endif // SCILIB_LINALG_LSTSQ_H
| {
"alphanum_fraction": 0.6600306279,
"avg_line_length": 27.5915492958,
"ext": "h",
"hexsha": "769b39659dbc8b5d4d69137a84e1fe6ff4400d5f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "stigrs/scilib",
"max_forks_repo_path": "include/scilib/linalg_impl/lstsq.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "stigrs/scilib",
"max_issues_repo_path": "include/scilib/linalg_impl/lstsq.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "stigrs/scilib",
"max_stars_repo_path": "include/scilib/linalg_impl/lstsq.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 520,
"size": 1959
} |
/* eigen/nonsymmv.c
*
* Copyright (C) 2006 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 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_vector_complex.h>
#include <gsl/gsl_matrix.h>
/*
* This module computes the eigenvalues and eigenvectors of a real
* nonsymmetric matrix.
*
* This file contains routines based on original code from LAPACK
* which is distributed under the modified BSD license. The LAPACK
* routines used are DTREVC and DLALN2.
*/
#define GSL_NONSYMMV_SMLNUM (2.0 * GSL_DBL_MIN)
#define GSL_NONSYMMV_BIGNUM ((1.0 - GSL_DBL_EPSILON) / GSL_NONSYMMV_SMLNUM)
static void nonsymmv_get_right_eigenvectors(gsl_matrix *T, gsl_matrix *Z,
gsl_vector_complex *eval,
gsl_matrix_complex *evec,
gsl_eigen_nonsymmv_workspace *w);
static inline void nonsymmv_solve_equation(gsl_matrix *A, double z,
gsl_vector *b, gsl_vector *x,
double *s, double *xnorm,
double smin);
static inline void nonsymmv_solve_equation_z(gsl_matrix *A, gsl_complex *z,
gsl_vector_complex *b,
gsl_vector_complex *x,
double *s, double *xnorm,
double smin);
static void nonsymmv_normalize_eigenvectors(gsl_vector_complex *eval,
gsl_matrix_complex *evec);
/*
gsl_eigen_nonsymmv_alloc()
Allocate a workspace for solving the nonsymmetric eigenvalue problem.
The size of this workspace is O(5n).
Inputs: n - size of matrices
Return: pointer to workspace
*/
gsl_eigen_nonsymmv_workspace *
gsl_eigen_nonsymmv_alloc(const size_t n)
{
gsl_eigen_nonsymmv_workspace *w;
if (n == 0)
{
GSL_ERROR_NULL ("matrix dimension must be positive integer",
GSL_EINVAL);
}
w = (gsl_eigen_nonsymmv_workspace *)
malloc (sizeof (gsl_eigen_nonsymmv_workspace));
if (w == 0)
{
GSL_ERROR_NULL ("failed to allocate space for workspace", GSL_ENOMEM);
}
w->size = n;
w->Z = NULL;
w->nonsymm_workspace_p = gsl_eigen_nonsymm_alloc(n);
if (w->nonsymm_workspace_p == 0)
{
GSL_ERROR_NULL ("failed to allocate space for nonsymm workspace", GSL_ENOMEM);
}
/*
* set parameters to compute the full Schur form T and balance
* the matrices
*/
gsl_eigen_nonsymm_params(1, 1, w->nonsymm_workspace_p);
w->work = gsl_vector_alloc(n);
w->work2 = gsl_vector_alloc(n);
w->work3 = gsl_vector_alloc(n);
if (w->work == 0 || w->work2 == 0 || w->work3 == 0)
{
GSL_ERROR_NULL ("failed to allocate space for nonsymmv additional workspace", GSL_ENOMEM);
}
return (w);
} /* gsl_eigen_nonsymmv_alloc() */
/*
gsl_eigen_nonsymmv_free()
Free workspace w
*/
void
gsl_eigen_nonsymmv_free (gsl_eigen_nonsymmv_workspace * w)
{
gsl_eigen_nonsymm_free(w->nonsymm_workspace_p);
gsl_vector_free(w->work);
gsl_vector_free(w->work2);
gsl_vector_free(w->work3);
free(w);
} /* gsl_eigen_nonsymmv_free() */
/*
gsl_eigen_nonsymmv()
Solve the nonsymmetric eigensystem problem
A x = \lambda x
for the eigenvalues \lambda and right eigenvectors x
Inputs: A - general real matrix
eval - where to store eigenvalues
evec - where to store eigenvectors
w - workspace
Return: success or error
*/
int
gsl_eigen_nonsymmv (gsl_matrix * A, gsl_vector_complex * eval,
gsl_matrix_complex * evec,
gsl_eigen_nonsymmv_workspace * w)
{
const size_t N = A->size1;
/* check matrix and vector sizes */
if (N != A->size2)
{
GSL_ERROR ("matrix must be square to compute eigenvalues", GSL_ENOTSQR);
}
else if (eval->size != N)
{
GSL_ERROR ("eigenvalue vector must match matrix size", GSL_EBADLEN);
}
else if (evec->size1 != evec->size2)
{
GSL_ERROR ("eigenvector matrix must be square", GSL_ENOTSQR);
}
else if (evec->size1 != N)
{
GSL_ERROR ("eigenvector matrix has wrong size", GSL_EBADLEN);
}
else
{
int s;
gsl_matrix Z;
/*
* We need a place to store the Schur vectors, so we will
* treat evec as a real matrix and store them in the left
* half - the factor of 2 in the tda corresponds to the
* complex multiplicity
*/
Z.size1 = N;
Z.size2 = N;
Z.tda = 2 * N;
Z.data = evec->data;
Z.block = 0;
Z.owner = 0;
/* compute eigenvalues, Schur form, and Schur vectors */
s = gsl_eigen_nonsymm_Z(A, eval, &Z, w->nonsymm_workspace_p);
if (w->Z)
{
/*
* save the Schur vectors in user supplied matrix, since
* they will be destroyed when computing eigenvectors
*/
gsl_matrix_memcpy(w->Z, &Z);
}
/* only compute eigenvectors if we found all eigenvalues */
if (s == GSL_SUCCESS)
{
/* compute eigenvectors */
nonsymmv_get_right_eigenvectors(A, &Z, eval, evec, w);
/* normalize so that Euclidean norm is 1 */
nonsymmv_normalize_eigenvectors(eval, evec);
}
return s;
}
} /* gsl_eigen_nonsymmv() */
/*
gsl_eigen_nonsymmv_Z()
Compute eigenvalues and eigenvectors of a real nonsymmetric matrix
and also save the Schur vectors. See comments in gsl_eigen_nonsymm_Z
for more information.
Inputs: A - real nonsymmetric matrix
eval - where to store eigenvalues
evec - where to store eigenvectors
Z - where to store Schur vectors
w - nonsymmv workspace
Return: success or error
*/
int
gsl_eigen_nonsymmv_Z (gsl_matrix * A, gsl_vector_complex * eval,
gsl_matrix_complex * evec, gsl_matrix * Z,
gsl_eigen_nonsymmv_workspace * w)
{
/* check matrix and vector sizes */
if (A->size1 != A->size2)
{
GSL_ERROR ("matrix must be square to compute eigenvalues/eigenvectors", GSL_ENOTSQR);
}
else if (eval->size != A->size1)
{
GSL_ERROR ("eigenvalue vector must match matrix size", GSL_EBADLEN);
}
else if (evec->size1 != evec->size2)
{
GSL_ERROR ("eigenvector matrix must be square", GSL_ENOTSQR);
}
else if (evec->size1 != A->size1)
{
GSL_ERROR ("eigenvector matrix has wrong size", GSL_EBADLEN);
}
else if ((Z->size1 != Z->size2) || (Z->size1 != A->size1))
{
GSL_ERROR ("Z matrix has wrong dimensions", GSL_EBADLEN);
}
else
{
int s;
w->Z = Z;
s = gsl_eigen_nonsymmv(A, eval, evec, w);
w->Z = NULL;
return s;
}
} /* gsl_eigen_nonsymmv_Z() */
/********************************************
* INTERNAL ROUTINES *
********************************************/
/*
nonsymmv_get_right_eigenvectors()
Compute the right eigenvectors of the Schur form T and then
backtransform them using the Schur vectors to get right eigenvectors of
the original matrix.
Inputs: T - Schur form
Z - Schur vectors
eval - where to store eigenvalues (to ensure that the
correct eigenvalue is stored in the same position
as the eigenvectors)
evec - where to store eigenvectors
w - nonsymmv workspace
Return: none
Notes: 1) based on LAPACK routine DTREVC - the algorithm used is
backsubstitution on the upper quasi triangular system T
followed by backtransformation by Z to get vectors of the
original matrix.
2) The Schur vectors in Z are destroyed and replaced with
eigenvectors stored with the same storage scheme as DTREVC.
The eigenvectors are also stored in 'evec'
3) The matrix T is unchanged on output
4) Each eigenvector is normalized so that the element of
largest magnitude has magnitude 1; here the magnitude of
a complex number (x,y) is taken to be |x| + |y|
*/
static void
nonsymmv_get_right_eigenvectors(gsl_matrix *T, gsl_matrix *Z,
gsl_vector_complex *eval,
gsl_matrix_complex *evec,
gsl_eigen_nonsymmv_workspace *w)
{
const size_t N = T->size1;
const double smlnum = GSL_DBL_MIN * N / GSL_DBL_EPSILON;
const double bignum = (1.0 - GSL_DBL_EPSILON) / smlnum;
int i; /* looping */
size_t iu, /* looping */
ju,
ii;
gsl_complex lambda; /* current eigenvalue */
double lambda_re, /* Re(lambda) */
lambda_im; /* Im(lambda) */
gsl_matrix_view Tv, /* temporary views */
Zv;
gsl_vector_view y, /* temporary views */
y2,
ev,
ev2;
double dat[4], /* scratch arrays */
dat_X[4];
double scale; /* scale factor */
double xnorm; /* |X| */
gsl_vector_complex_view ecol, /* column of evec */
ecol2;
int complex_pair; /* complex eigenvalue pair? */
double smin;
/*
* Compute 1-norm of each column of upper triangular part of T
* to control overflow in triangular solver
*/
gsl_vector_set(w->work3, 0, 0.0);
for (ju = 1; ju < N; ++ju)
{
gsl_vector_set(w->work3, ju, 0.0);
for (iu = 0; iu < ju; ++iu)
{
gsl_vector_set(w->work3, ju,
gsl_vector_get(w->work3, ju) +
fabs(gsl_matrix_get(T, iu, ju)));
}
}
for (i = (int) N - 1; i >= 0; --i)
{
iu = (size_t) i;
/* get current eigenvalue and store it in lambda */
lambda_re = gsl_matrix_get(T, iu, iu);
if (iu != 0 && gsl_matrix_get(T, iu, iu - 1) != 0.0)
{
lambda_im = sqrt(fabs(gsl_matrix_get(T, iu, iu - 1))) *
sqrt(fabs(gsl_matrix_get(T, iu - 1, iu)));
}
else
{
lambda_im = 0.0;
}
GSL_SET_COMPLEX(&lambda, lambda_re, lambda_im);
smin = GSL_MAX(GSL_DBL_EPSILON * (fabs(lambda_re) + fabs(lambda_im)),
smlnum);
smin = GSL_MAX(smin, GSL_NONSYMMV_SMLNUM);
if (lambda_im == 0.0)
{
int k, l;
gsl_vector_view bv, xv;
/* real eigenvector */
/*
* The ordering of eigenvalues in 'eval' is arbitrary and
* does not necessarily follow the Schur form T, so store
* lambda in the right slot in eval to ensure it corresponds
* to the eigenvector we are about to compute
*/
gsl_vector_complex_set(eval, iu, lambda);
/*
* We need to solve the system:
*
* (T(1:iu-1, 1:iu-1) - lambda*I)*X = -T(1:iu-1,iu)
*/
/* construct right hand side */
for (k = 0; k < i; ++k)
{
gsl_vector_set(w->work,
(size_t) k,
-gsl_matrix_get(T, (size_t) k, iu));
}
gsl_vector_set(w->work, iu, 1.0);
for (l = i - 1; l >= 0; --l)
{
size_t lu = (size_t) l;
if (lu == 0)
complex_pair = 0;
else
complex_pair = gsl_matrix_get(T, lu, lu - 1) != 0.0;
if (!complex_pair)
{
double x;
/*
* 1-by-1 diagonal block - solve the system:
*
* (T_{ll} - lambda)*x = -T_{l(iu)}
*/
Tv = gsl_matrix_submatrix(T, lu, lu, 1, 1);
bv = gsl_vector_view_array(dat, 1);
gsl_vector_set(&bv.vector, 0,
gsl_vector_get(w->work, lu));
xv = gsl_vector_view_array(dat_X, 1);
nonsymmv_solve_equation(&Tv.matrix,
lambda_re,
&bv.vector,
&xv.vector,
&scale,
&xnorm,
smin);
/* scale x to avoid overflow */
x = gsl_vector_get(&xv.vector, 0);
if (xnorm > 1.0)
{
if (gsl_vector_get(w->work3, lu) > bignum / xnorm)
{
x /= xnorm;
scale /= xnorm;
}
}
if (scale != 1.0)
{
gsl_vector_view wv;
wv = gsl_vector_subvector(w->work, 0, iu + 1);
gsl_blas_dscal(scale, &wv.vector);
}
gsl_vector_set(w->work, lu, x);
if (lu > 0)
{
gsl_vector_view v1, v2;
/* update right hand side */
v1 = gsl_matrix_column(T, lu);
v1 = gsl_vector_subvector(&v1.vector, 0, lu);
v2 = gsl_vector_subvector(w->work, 0, lu);
gsl_blas_daxpy(-x, &v1.vector, &v2.vector);
} /* if (l > 0) */
} /* if (!complex_pair) */
else
{
double x11, x21;
/*
* 2-by-2 diagonal block
*/
Tv = gsl_matrix_submatrix(T, lu - 1, lu - 1, 2, 2);
bv = gsl_vector_view_array(dat, 2);
gsl_vector_set(&bv.vector, 0,
gsl_vector_get(w->work, lu - 1));
gsl_vector_set(&bv.vector, 1,
gsl_vector_get(w->work, lu));
xv = gsl_vector_view_array(dat_X, 2);
nonsymmv_solve_equation(&Tv.matrix,
lambda_re,
&bv.vector,
&xv.vector,
&scale,
&xnorm,
smin);
/* scale X(1,1) and X(2,1) to avoid overflow */
x11 = gsl_vector_get(&xv.vector, 0);
x21 = gsl_vector_get(&xv.vector, 1);
if (xnorm > 1.0)
{
double beta;
beta = GSL_MAX(gsl_vector_get(w->work3, lu - 1),
gsl_vector_get(w->work3, lu));
if (beta > bignum / xnorm)
{
x11 /= xnorm;
x21 /= xnorm;
scale /= xnorm;
}
}
/* scale if necessary */
if (scale != 1.0)
{
gsl_vector_view wv;
wv = gsl_vector_subvector(w->work, 0, iu + 1);
gsl_blas_dscal(scale, &wv.vector);
}
gsl_vector_set(w->work, lu - 1, x11);
gsl_vector_set(w->work, lu, x21);
/* update right hand side */
if (lu > 1)
{
gsl_vector_view v1, v2;
v1 = gsl_matrix_column(T, lu - 1);
v1 = gsl_vector_subvector(&v1.vector, 0, lu - 1);
v2 = gsl_vector_subvector(w->work, 0, lu - 1);
gsl_blas_daxpy(-x11, &v1.vector, &v2.vector);
v1 = gsl_matrix_column(T, lu);
v1 = gsl_vector_subvector(&v1.vector, 0, lu - 1);
gsl_blas_daxpy(-x21, &v1.vector, &v2.vector);
}
--l;
} /* if (complex_pair) */
} /* for (l = i - 1; l >= 0; --l) */
/*
* At this point, w->work is an eigenvector of the
* Schur form T. To get an eigenvector of the original
* matrix, we multiply on the left by Z, the matrix of
* Schur vectors
*/
ecol = gsl_matrix_complex_column(evec, iu);
y = gsl_matrix_column(Z, iu);
if (iu > 0)
{
gsl_vector_view x;
Zv = gsl_matrix_submatrix(Z, 0, 0, N, iu);
x = gsl_vector_subvector(w->work, 0, iu);
/* compute Z * w->work and store it in Z(:,iu) */
gsl_blas_dgemv(CblasNoTrans,
1.0,
&Zv.matrix,
&x.vector,
gsl_vector_get(w->work, iu),
&y.vector);
} /* if (iu > 0) */
/* store eigenvector into evec */
ev = gsl_vector_complex_real(&ecol.vector);
ev2 = gsl_vector_complex_imag(&ecol.vector);
scale = 0.0;
for (ii = 0; ii < N; ++ii)
{
double a = gsl_vector_get(&y.vector, ii);
/* store real part of eigenvector */
gsl_vector_set(&ev.vector, ii, a);
/* set imaginary part to 0 */
gsl_vector_set(&ev2.vector, ii, 0.0);
if (fabs(a) > scale)
scale = fabs(a);
}
if (scale != 0.0)
scale = 1.0 / scale;
/* scale by magnitude of largest element */
gsl_blas_dscal(scale, &ev.vector);
} /* if (GSL_IMAG(lambda) == 0.0) */
else
{
gsl_vector_complex_view bv, xv;
size_t k;
int l;
gsl_complex lambda2;
/* complex eigenvector */
/*
* Store the complex conjugate eigenvalues in the right
* slots in eval
*/
GSL_SET_REAL(&lambda2, GSL_REAL(lambda));
GSL_SET_IMAG(&lambda2, -GSL_IMAG(lambda));
gsl_vector_complex_set(eval, iu - 1, lambda);
gsl_vector_complex_set(eval, iu, lambda2);
/*
* First solve:
*
* [ T(i:i+1,i:i+1) - lambda*I ] * X = 0
*/
if (fabs(gsl_matrix_get(T, iu - 1, iu)) >=
fabs(gsl_matrix_get(T, iu, iu - 1)))
{
gsl_vector_set(w->work, iu - 1, 1.0);
gsl_vector_set(w->work2, iu,
lambda_im / gsl_matrix_get(T, iu - 1, iu));
}
else
{
gsl_vector_set(w->work, iu - 1,
-lambda_im / gsl_matrix_get(T, iu, iu - 1));
gsl_vector_set(w->work2, iu, 1.0);
}
gsl_vector_set(w->work, iu, 0.0);
gsl_vector_set(w->work2, iu - 1, 0.0);
/* construct right hand side */
for (k = 0; k < iu - 1; ++k)
{
gsl_vector_set(w->work, k,
-gsl_vector_get(w->work, iu - 1) *
gsl_matrix_get(T, k, iu - 1));
gsl_vector_set(w->work2, k,
-gsl_vector_get(w->work2, iu) *
gsl_matrix_get(T, k, iu));
}
/*
* We must solve the upper quasi-triangular system:
*
* [ T(1:i-2,1:i-2) - lambda*I ] * X = s*(work + i*work2)
*/
for (l = i - 2; l >= 0; --l)
{
size_t lu = (size_t) l;
if (lu == 0)
complex_pair = 0;
else
complex_pair = gsl_matrix_get(T, lu, lu - 1) != 0.0;
if (!complex_pair)
{
gsl_complex bval;
gsl_complex x;
/*
* 1-by-1 diagonal block - solve the system:
*
* (T_{ll} - lambda)*x = work + i*work2
*/
Tv = gsl_matrix_submatrix(T, lu, lu, 1, 1);
bv = gsl_vector_complex_view_array(dat, 1);
xv = gsl_vector_complex_view_array(dat_X, 1);
GSL_SET_COMPLEX(&bval,
gsl_vector_get(w->work, lu),
gsl_vector_get(w->work2, lu));
gsl_vector_complex_set(&bv.vector, 0, bval);
nonsymmv_solve_equation_z(&Tv.matrix,
&lambda,
&bv.vector,
&xv.vector,
&scale,
&xnorm,
smin);
if (xnorm > 1.0)
{
if (gsl_vector_get(w->work3, lu) > bignum / xnorm)
{
gsl_blas_zdscal(1.0/xnorm, &xv.vector);
scale /= xnorm;
}
}
/* scale if necessary */
if (scale != 1.0)
{
gsl_vector_view wv;
wv = gsl_vector_subvector(w->work, 0, iu + 1);
gsl_blas_dscal(scale, &wv.vector);
wv = gsl_vector_subvector(w->work2, 0, iu + 1);
gsl_blas_dscal(scale, &wv.vector);
}
x = gsl_vector_complex_get(&xv.vector, 0);
gsl_vector_set(w->work, lu, GSL_REAL(x));
gsl_vector_set(w->work2, lu, GSL_IMAG(x));
/* update the right hand side */
if (lu > 0)
{
gsl_vector_view v1, v2;
v1 = gsl_matrix_column(T, lu);
v1 = gsl_vector_subvector(&v1.vector, 0, lu);
v2 = gsl_vector_subvector(w->work, 0, lu);
gsl_blas_daxpy(-GSL_REAL(x), &v1.vector, &v2.vector);
v2 = gsl_vector_subvector(w->work2, 0, lu);
gsl_blas_daxpy(-GSL_IMAG(x), &v1.vector, &v2.vector);
} /* if (lu > 0) */
} /* if (!complex_pair) */
else
{
gsl_complex b1, b2, x1, x2;
/*
* 2-by-2 diagonal block - solve the system
*/
Tv = gsl_matrix_submatrix(T, lu - 1, lu - 1, 2, 2);
bv = gsl_vector_complex_view_array(dat, 2);
xv = gsl_vector_complex_view_array(dat_X, 2);
GSL_SET_COMPLEX(&b1,
gsl_vector_get(w->work, lu - 1),
gsl_vector_get(w->work2, lu - 1));
GSL_SET_COMPLEX(&b2,
gsl_vector_get(w->work, lu),
gsl_vector_get(w->work2, lu));
gsl_vector_complex_set(&bv.vector, 0, b1);
gsl_vector_complex_set(&bv.vector, 1, b2);
nonsymmv_solve_equation_z(&Tv.matrix,
&lambda,
&bv.vector,
&xv.vector,
&scale,
&xnorm,
smin);
x1 = gsl_vector_complex_get(&xv.vector, 0);
x2 = gsl_vector_complex_get(&xv.vector, 1);
if (xnorm > 1.0)
{
double beta;
beta = GSL_MAX(gsl_vector_get(w->work3, lu - 1),
gsl_vector_get(w->work3, lu));
if (beta > bignum / xnorm)
{
gsl_blas_zdscal(1.0/xnorm, &xv.vector);
scale /= xnorm;
}
}
/* scale if necessary */
if (scale != 1.0)
{
gsl_vector_view wv;
wv = gsl_vector_subvector(w->work, 0, iu + 1);
gsl_blas_dscal(scale, &wv.vector);
wv = gsl_vector_subvector(w->work2, 0, iu + 1);
gsl_blas_dscal(scale, &wv.vector);
}
gsl_vector_set(w->work, lu - 1, GSL_REAL(x1));
gsl_vector_set(w->work, lu, GSL_REAL(x2));
gsl_vector_set(w->work2, lu - 1, GSL_IMAG(x1));
gsl_vector_set(w->work2, lu, GSL_IMAG(x2));
/* update right hand side */
if (lu > 1)
{
gsl_vector_view v1, v2, v3, v4;
v1 = gsl_matrix_column(T, lu - 1);
v1 = gsl_vector_subvector(&v1.vector, 0, lu - 1);
v4 = gsl_matrix_column(T, lu);
v4 = gsl_vector_subvector(&v4.vector, 0, lu - 1);
v2 = gsl_vector_subvector(w->work, 0, lu - 1);
v3 = gsl_vector_subvector(w->work2, 0, lu - 1);
gsl_blas_daxpy(-GSL_REAL(x1), &v1.vector, &v2.vector);
gsl_blas_daxpy(-GSL_REAL(x2), &v4.vector, &v2.vector);
gsl_blas_daxpy(-GSL_IMAG(x1), &v1.vector, &v3.vector);
gsl_blas_daxpy(-GSL_IMAG(x2), &v4.vector, &v3.vector);
} /* if (lu > 1) */
--l;
} /* if (complex_pair) */
} /* for (l = i - 2; l >= 0; --l) */
/*
* At this point, work + i*work2 is an eigenvector
* of T - backtransform to get an eigenvector of the
* original matrix
*/
y = gsl_matrix_column(Z, iu - 1);
y2 = gsl_matrix_column(Z, iu);
if (iu > 1)
{
gsl_vector_view x;
/* compute real part of eigenvectors */
Zv = gsl_matrix_submatrix(Z, 0, 0, N, iu - 1);
x = gsl_vector_subvector(w->work, 0, iu - 1);
gsl_blas_dgemv(CblasNoTrans,
1.0,
&Zv.matrix,
&x.vector,
gsl_vector_get(w->work, iu - 1),
&y.vector);
/* now compute the imaginary part */
x = gsl_vector_subvector(w->work2, 0, iu - 1);
gsl_blas_dgemv(CblasNoTrans,
1.0,
&Zv.matrix,
&x.vector,
gsl_vector_get(w->work2, iu),
&y2.vector);
}
else
{
gsl_blas_dscal(gsl_vector_get(w->work, iu - 1), &y.vector);
gsl_blas_dscal(gsl_vector_get(w->work2, iu), &y2.vector);
}
/*
* Now store the eigenvectors into evec - the real parts
* are Z(:,iu - 1) and the imaginary parts are
* +/- Z(:,iu)
*/
/* get views of the two eigenvector slots */
ecol = gsl_matrix_complex_column(evec, iu - 1);
ecol2 = gsl_matrix_complex_column(evec, iu);
/*
* save imaginary part first as it may get overwritten
* when copying the real part due to our storage scheme
* in Z/evec
*/
ev = gsl_vector_complex_imag(&ecol.vector);
ev2 = gsl_vector_complex_imag(&ecol2.vector);
scale = 0.0;
for (ii = 0; ii < N; ++ii)
{
double a = gsl_vector_get(&y2.vector, ii);
scale = GSL_MAX(scale,
fabs(a) + fabs(gsl_vector_get(&y.vector, ii)));
gsl_vector_set(&ev.vector, ii, a);
gsl_vector_set(&ev2.vector, ii, -a);
}
/* now save the real part */
ev = gsl_vector_complex_real(&ecol.vector);
ev2 = gsl_vector_complex_real(&ecol2.vector);
for (ii = 0; ii < N; ++ii)
{
double a = gsl_vector_get(&y.vector, ii);
gsl_vector_set(&ev.vector, ii, a);
gsl_vector_set(&ev2.vector, ii, a);
}
if (scale != 0.0)
scale = 1.0 / scale;
/* scale by largest element magnitude */
gsl_blas_zdscal(scale, &ecol.vector);
gsl_blas_zdscal(scale, &ecol2.vector);
/*
* decrement i since we took care of two eigenvalues at
* the same time
*/
--i;
} /* if (GSL_IMAG(lambda) != 0.0) */
} /* for (i = (int) N - 1; i >= 0; --i) */
} /* nonsymmv_get_right_eigenvectors() */
/*
nonsymmv_solve_equation()
Solve the equation which comes up in the back substitution
when computing eigenvectors corresponding to real eigenvalues.
The equation that is solved is:
(A - z*I)*x = s*b
where
A is n-by-n with n = 1 or 2
b and x are n-by-1 real vectors
s is a scaling factor set by this function to prevent overflow in x
Inputs: A - square matrix (n-by-n)
z - real scalar (eigenvalue)
b - right hand side vector
x - (output) where to store solution
s - (output) scale factor
xnorm - (output) infinity norm of X
smin - lower bound on singular values of A - if A - z*I
is less than this value, we'll use smin*I instead.
This value should be a safe distance above underflow.
Notes: 1) A and b are not changed on output
2) Based on lapack routine DLALN2
*/
static inline void
nonsymmv_solve_equation(gsl_matrix *A, double z, gsl_vector *b,
gsl_vector *x, double *s, double *xnorm,
double smin)
{
size_t N = A->size1;
double bnorm;
double scale = 1.0;
if (N == 1)
{
double c, /* denominator */
cnorm; /* |c| */
/*
* we have a 1-by-1 (real) scalar system to solve:
*
* (a - z)*x = b
* with z real
*/
/* c = a - z */
c = gsl_matrix_get(A, 0, 0) - z;
cnorm = fabs(c);
if (cnorm < smin)
{
/* set c = smin*I */
c = smin;
cnorm = smin;
}
/* check scaling for x = b / c */
bnorm = fabs(gsl_vector_get(b, 0));
if (cnorm < 1.0 && bnorm > 1.0)
{
if (bnorm > GSL_NONSYMMV_BIGNUM*cnorm)
scale = 1.0 / bnorm;
}
/* compute x */
gsl_vector_set(x, 0, gsl_vector_get(b, 0) * scale / c);
*xnorm = fabs(gsl_vector_get(x, 0));
} /* if (N == 1) */
else
{
double cr[2][2];
double *crv;
double cmax;
size_t icmax, j;
double bval1, bval2;
double ur11, ur12, ur22, ur11r;
double cr21, cr22;
double lr21;
double b1, b2, bbnd;
double x1, x2;
double temp;
size_t ipivot[4][4] = { { 0, 1, 2, 3 },
{ 1, 0, 3, 2 },
{ 2, 3, 0, 1 },
{ 3, 2, 1, 0 } };
int rswap[4] = { 0, 1, 0, 1 };
int zswap[4] = { 0, 0, 1, 1 };
/*
* we have a 2-by-2 real system to solve:
*
* [ A11 - z A12 ] [ x1 ] = [ b1 ]
* [ A21 A22 - z ] [ x2 ] [ b2 ]
*
* (z real)
*/
crv = (double *) cr;
/*
* compute the real part of C = A - z*I - use column ordering
* here since porting from lapack
*/
cr[0][0] = gsl_matrix_get(A, 0, 0) - z;
cr[1][1] = gsl_matrix_get(A, 1, 1) - z;
cr[0][1] = gsl_matrix_get(A, 1, 0);
cr[1][0] = gsl_matrix_get(A, 0, 1);
/* find the largest element in C */
cmax = 0.0;
icmax = 0;
for (j = 0; j < 4; ++j)
{
if (fabs(crv[j]) > cmax)
{
cmax = fabs(crv[j]);
icmax = j;
}
}
bval1 = gsl_vector_get(b, 0);
bval2 = gsl_vector_get(b, 1);
/* if norm(C) < smin, use smin*I */
if (cmax < smin)
{
bnorm = GSL_MAX(fabs(bval1), fabs(bval2));
if (smin < 1.0 && bnorm > 1.0)
{
if (bnorm > GSL_NONSYMMV_BIGNUM*smin)
scale = 1.0 / bnorm;
}
temp = scale / smin;
gsl_vector_set(x, 0, temp * bval1);
gsl_vector_set(x, 1, temp * bval2);
*xnorm = temp * bnorm;
*s = scale;
return;
}
/* gaussian elimination with complete pivoting */
ur11 = crv[icmax];
cr21 = crv[ipivot[1][icmax]];
ur12 = crv[ipivot[2][icmax]];
cr22 = crv[ipivot[3][icmax]];
ur11r = 1.0 / ur11;
lr21 = ur11r * cr21;
ur22 = cr22 - ur12 * lr21;
/* if smaller pivot < smin, use smin */
if (fabs(ur22) < smin)
ur22 = smin;
if (rswap[icmax])
{
b1 = bval2;
b2 = bval1;
}
else
{
b1 = bval1;
b2 = bval2;
}
b2 -= lr21 * b1;
bbnd = GSL_MAX(fabs(b1 * (ur22 * ur11r)), fabs(b2));
if (bbnd > 1.0 && fabs(ur22) < 1.0)
{
if (bbnd >= GSL_NONSYMMV_BIGNUM * fabs(ur22))
scale = 1.0 / bbnd;
}
x2 = (b2 * scale) / ur22;
x1 = (scale * b1) * ur11r - x2 * (ur11r * ur12);
if (zswap[icmax])
{
gsl_vector_set(x, 0, x2);
gsl_vector_set(x, 1, x1);
}
else
{
gsl_vector_set(x, 0, x1);
gsl_vector_set(x, 1, x2);
}
*xnorm = GSL_MAX(fabs(x1), fabs(x2));
/* further scaling if norm(A) norm(X) > overflow */
if (*xnorm > 1.0 && cmax > 1.0)
{
if (*xnorm > GSL_NONSYMMV_BIGNUM / cmax)
{
temp = cmax / GSL_NONSYMMV_BIGNUM;
gsl_blas_dscal(temp, x);
*xnorm *= temp;
scale *= temp;
}
}
} /* if (N == 2) */
*s = scale;
} /* nonsymmv_solve_equation() */
/*
nonsymmv_solve_equation_z()
Solve the equation which comes up in the back substitution
when computing eigenvectors corresponding to complex eigenvalues.
The equation that is solved is:
(A - z*I)*x = s*b
where
A is n-by-n with n = 1 or 2
b and x are n-by-1 complex vectors
s is a scaling factor set by this function to prevent overflow in x
Inputs: A - square matrix (n-by-n)
z - complex scalar (eigenvalue)
b - right hand side vector
x - (output) where to store solution
s - (output) scale factor
xnorm - (output) infinity norm of X
smin - lower bound on singular values of A - if A - z*I
is less than this value, we'll use smin*I instead.
This value should be a safe distance above underflow.
Notes: 1) A and b are not changed on output
2) Based on lapack routine DLALN2
*/
static inline void
nonsymmv_solve_equation_z(gsl_matrix *A, gsl_complex *z,
gsl_vector_complex *b, gsl_vector_complex *x,
double *s, double *xnorm, double smin)
{
size_t N = A->size1;
double scale = 1.0;
double bnorm;
if (N == 1)
{
double cr, /* denominator */
ci,
cnorm; /* |c| */
gsl_complex bval, c, xval, tmp;
/*
* we have a 1-by-1 (complex) scalar system to solve:
*
* (a - z)*x = b
* (z is complex, a is real)
*/
/* c = a - z */
cr = gsl_matrix_get(A, 0, 0) - GSL_REAL(*z);
ci = -GSL_IMAG(*z);
cnorm = fabs(cr) + fabs(ci);
if (cnorm < smin)
{
/* set c = smin*I */
cr = smin;
ci = 0.0;
cnorm = smin;
}
/* check scaling for x = b / c */
bval = gsl_vector_complex_get(b, 0);
bnorm = fabs(GSL_REAL(bval)) + fabs(GSL_IMAG(bval));
if (cnorm < 1.0 && bnorm > 1.0)
{
if (bnorm > GSL_NONSYMMV_BIGNUM*cnorm)
scale = 1.0 / bnorm;
}
/* compute x */
GSL_SET_COMPLEX(&tmp, scale*GSL_REAL(bval), scale*GSL_IMAG(bval));
GSL_SET_COMPLEX(&c, cr, ci);
xval = gsl_complex_div(tmp, c);
gsl_vector_complex_set(x, 0, xval);
*xnorm = fabs(GSL_REAL(xval)) + fabs(GSL_IMAG(xval));
} /* if (N == 1) */
else
{
double cr[2][2], ci[2][2];
double *civ, *crv;
double cmax;
gsl_complex bval1, bval2;
gsl_complex xval1, xval2;
double xr1, xi1;
size_t icmax;
size_t j;
double temp;
double ur11, ur12, ur22, ui11, ui12, ui22, ur11r, ui11r;
double ur12s, ui12s;
double u22abs;
double lr21, li21;
double cr21, cr22, ci21, ci22;
double br1, bi1, br2, bi2, bbnd;
gsl_complex b1, b2;
size_t ipivot[4][4] = { { 0, 1, 2, 3 },
{ 1, 0, 3, 2 },
{ 2, 3, 0, 1 },
{ 3, 2, 1, 0 } };
int rswap[4] = { 0, 1, 0, 1 };
int zswap[4] = { 0, 0, 1, 1 };
/*
* complex 2-by-2 system:
*
* [ A11 - z A12 ] [ X1 ] = [ B1 ]
* [ A21 A22 - z ] [ X2 ] [ B2 ]
*
* (z complex)
*
* where the X and B values are complex.
*/
civ = (double *) ci;
crv = (double *) cr;
/*
* compute the real part of C = A - z*I - use column ordering
* here since porting from lapack
*/
cr[0][0] = gsl_matrix_get(A, 0, 0) - GSL_REAL(*z);
cr[1][1] = gsl_matrix_get(A, 1, 1) - GSL_REAL(*z);
cr[0][1] = gsl_matrix_get(A, 1, 0);
cr[1][0] = gsl_matrix_get(A, 0, 1);
/* compute the imaginary part */
ci[0][0] = -GSL_IMAG(*z);
ci[0][1] = 0.0;
ci[1][0] = 0.0;
ci[1][1] = -GSL_IMAG(*z);
cmax = 0.0;
icmax = 0;
for (j = 0; j < 4; ++j)
{
if (fabs(crv[j]) + fabs(civ[j]) > cmax)
{
cmax = fabs(crv[j]) + fabs(civ[j]);
icmax = j;
}
}
bval1 = gsl_vector_complex_get(b, 0);
bval2 = gsl_vector_complex_get(b, 1);
/* if norm(C) < smin, use smin*I */
if (cmax < smin)
{
bnorm = GSL_MAX(fabs(GSL_REAL(bval1)) + fabs(GSL_IMAG(bval1)),
fabs(GSL_REAL(bval2)) + fabs(GSL_IMAG(bval2)));
if (smin < 1.0 && bnorm > 1.0)
{
if (bnorm > GSL_NONSYMMV_BIGNUM*smin)
scale = 1.0 / bnorm;
}
temp = scale / smin;
xval1 = gsl_complex_mul_real(bval1, temp);
xval2 = gsl_complex_mul_real(bval2, temp);
gsl_vector_complex_set(x, 0, xval1);
gsl_vector_complex_set(x, 1, xval2);
*xnorm = temp * bnorm;
*s = scale;
return;
}
/* gaussian elimination with complete pivoting */
ur11 = crv[icmax];
ui11 = civ[icmax];
cr21 = crv[ipivot[1][icmax]];
ci21 = civ[ipivot[1][icmax]];
ur12 = crv[ipivot[2][icmax]];
ui12 = civ[ipivot[2][icmax]];
cr22 = crv[ipivot[3][icmax]];
ci22 = civ[ipivot[3][icmax]];
if (icmax == 0 || icmax == 3)
{
/* off diagonals of pivoted C are real */
if (fabs(ur11) > fabs(ui11))
{
temp = ui11 / ur11;
ur11r = 1.0 / (ur11 * (1.0 + temp*temp));
ui11r = -temp * ur11r;
}
else
{
temp = ur11 / ui11;
ui11r = -1.0 / (ui11 * (1.0 + temp*temp));
ur11r = -temp*ui11r;
}
lr21 = cr21 * ur11r;
li21 = cr21 * ui11r;
ur12s = ur12 * ur11r;
ui12s = ur12 * ui11r;
ur22 = cr22 - ur12 * lr21;
ui22 = ci22 - ur12 * li21;
}
else
{
/* diagonals of pivoted C are real */
ur11r = 1.0 / ur11;
ui11r = 0.0;
lr21 = cr21 * ur11r;
li21 = ci21 * ur11r;
ur12s = ur12 * ur11r;
ui12s = ui12 * ur11r;
ur22 = cr22 - ur12 * lr21 + ui12 * li21;
ui22 = -ur12 * li21 - ui12 * lr21;
}
u22abs = fabs(ur22) + fabs(ui22);
/* if smaller pivot < smin, use smin */
if (u22abs < smin)
{
ur22 = smin;
ui22 = 0.0;
}
if (rswap[icmax])
{
br2 = GSL_REAL(bval1);
bi2 = GSL_IMAG(bval1);
br1 = GSL_REAL(bval2);
bi1 = GSL_IMAG(bval2);
}
else
{
br1 = GSL_REAL(bval1);
bi1 = GSL_IMAG(bval1);
br2 = GSL_REAL(bval2);
bi2 = GSL_IMAG(bval2);
}
br2 += li21*bi1 - lr21*br1;
bi2 -= li21*br1 + lr21*bi1;
bbnd = GSL_MAX((fabs(br1) + fabs(bi1)) *
(u22abs * (fabs(ur11r) + fabs(ui11r))),
fabs(br2) + fabs(bi2));
if (bbnd > 1.0 && u22abs < 1.0)
{
if (bbnd >= GSL_NONSYMMV_BIGNUM*u22abs)
{
scale = 1.0 / bbnd;
br1 *= scale;
bi1 *= scale;
br2 *= scale;
bi2 *= scale;
}
}
GSL_SET_COMPLEX(&b1, br2, bi2);
GSL_SET_COMPLEX(&b2, ur22, ui22);
xval2 = gsl_complex_div(b1, b2);
xr1 = ur11r*br1 - ui11r*bi1 - ur12s*GSL_REAL(xval2) + ui12s*GSL_IMAG(xval2);
xi1 = ui11r*br1 + ur11r*bi1 - ui12s*GSL_REAL(xval2) - ur12s*GSL_IMAG(xval2);
GSL_SET_COMPLEX(&xval1, xr1, xi1);
if (zswap[icmax])
{
gsl_vector_complex_set(x, 0, xval2);
gsl_vector_complex_set(x, 1, xval1);
}
else
{
gsl_vector_complex_set(x, 0, xval1);
gsl_vector_complex_set(x, 1, xval2);
}
*xnorm = GSL_MAX(fabs(GSL_REAL(xval1)) + fabs(GSL_IMAG(xval1)),
fabs(GSL_REAL(xval2)) + fabs(GSL_IMAG(xval2)));
/* further scaling if norm(A) norm(X) > overflow */
if (*xnorm > 1.0 && cmax > 1.0)
{
if (*xnorm > GSL_NONSYMMV_BIGNUM / cmax)
{
temp = cmax / GSL_NONSYMMV_BIGNUM;
gsl_blas_zdscal(temp, x);
*xnorm *= temp;
scale *= temp;
}
}
} /* if (N == 2) */
*s = scale;
} /* nonsymmv_solve_equation_z() */
/*
nonsymmv_normalize_eigenvectors()
Normalize eigenvectors so that their Euclidean norm is 1
Inputs: eval - eigenvalues
evec - eigenvectors
*/
static void
nonsymmv_normalize_eigenvectors(gsl_vector_complex *eval,
gsl_matrix_complex *evec)
{
const size_t N = evec->size1;
size_t i; /* looping */
gsl_complex ei;
gsl_vector_complex_view vi;
gsl_vector_view re, im;
double scale; /* scaling factor */
for (i = 0; i < N; ++i)
{
ei = gsl_vector_complex_get(eval, i);
vi = gsl_matrix_complex_column(evec, i);
re = gsl_vector_complex_real(&vi.vector);
if (GSL_IMAG(ei) == 0.0)
{
scale = 1.0 / gsl_blas_dnrm2(&re.vector);
gsl_blas_dscal(scale, &re.vector);
}
else if (GSL_IMAG(ei) > 0.0)
{
im = gsl_vector_complex_imag(&vi.vector);
scale = 1.0 / gsl_hypot(gsl_blas_dnrm2(&re.vector),
gsl_blas_dnrm2(&im.vector));
gsl_blas_zdscal(scale, &vi.vector);
vi = gsl_matrix_complex_column(evec, i + 1);
gsl_blas_zdscal(scale, &vi.vector);
}
}
} /* nonsymmv_normalize_eigenvectors() */
| {
"alphanum_fraction": 0.4682937604,
"avg_line_length": 30.778382053,
"ext": "c",
"hexsha": "bcd258916f556dc3407693e716a828d71e99cdaa",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/eigen/nonsymmv.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/eigen/nonsymmv.c",
"max_line_length": 96,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/eigen/nonsymmv.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": 12148,
"size": 45275
} |
/////////////////////////////////////////////////////////////////////
// = NMatrix
//
// A linear algebra library for scientific computation in Ruby.
// NMatrix is part of SciRuby.
//
// NMatrix was originally inspired by and derived from NArray, by
// Masahiro Tanaka: http://narray.rubyforge.org
//
// == Copyright Information
//
// SciRuby is Copyright (c) 2010 - 2014, Ruby Science Foundation
// NMatrix is Copyright (c) 2012 - 2014, John Woods and the Ruby Science Foundation
//
// Please see LICENSE.txt for additional copyright notices.
//
// == Contributing
//
// By contributing source code to SciRuby, you agree to be bound by
// our Contributor Agreement:
//
// * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement
//
// == gemm.h
//
// Header file for interface with ATLAS's CBLAS gemm functions and
// native templated version of LAPACK's gemm function.
//
#ifndef GEMM_H
# define GEMM_H
#if !(defined(HAVE_CBLAS_H) || defined(HAVE_ATLAS_CBLAS_H))
#include "cblas_enums.h"
#endif
extern "C" { // These need to be in an extern "C" block or you'll get all kinds of undefined symbol errors.
#if defined HAVE_CBLAS_H
#include <cblas.h>
#elif defined HAVE_ATLAS_CBLAS_H
#include <atlas/cblas.h>
#endif
}
namespace nm { namespace math {
/*
* GEneral Matrix Multiplication: based on dgemm.f from Netlib.
*
* This is an extremely inefficient algorithm. Recommend using ATLAS' version instead.
*
* Template parameters: LT -- long version of type T. Type T is the matrix dtype.
*
* This version throws no errors. Use gemm<DType> instead for error checking.
*/
template <typename DType>
inline void gemm_nothrow(const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,
const DType* alpha, const DType* A, const int lda, const DType* B, const int ldb, const DType* beta, DType* C, const int ldc)
{
typename LongDType<DType>::type temp;
// Quick return if possible
if (!M or !N or ((*alpha == 0 or !K) and *beta == 1)) return;
// For alpha = 0
if (*alpha == 0) {
if (*beta == 0) {
for (int j = 0; j < N; ++j)
for (int i = 0; i < M; ++i) {
C[i+j*ldc] = 0;
}
} else {
for (int j = 0; j < N; ++j)
for (int i = 0; i < M; ++i) {
C[i+j*ldc] *= *beta;
}
}
return;
}
// Start the operations
if (TransB == CblasNoTrans) {
if (TransA == CblasNoTrans) {
// C = alpha*A*B+beta*C
for (int j = 0; j < N; ++j) {
if (*beta == 0) {
for (int i = 0; i < M; ++i) {
C[i+j*ldc] = 0;
}
} else if (*beta != 1) {
for (int i = 0; i < M; ++i) {
C[i+j*ldc] *= *beta;
}
}
for (int l = 0; l < K; ++l) {
if (B[l+j*ldb] != 0) {
temp = *alpha * B[l+j*ldb];
for (int i = 0; i < M; ++i) {
C[i+j*ldc] += A[i+l*lda] * temp;
}
}
}
}
} else {
// C = alpha*A**DType*B + beta*C
for (int j = 0; j < N; ++j) {
for (int i = 0; i < M; ++i) {
temp = 0;
for (int l = 0; l < K; ++l) {
temp += A[l+i*lda] * B[l+j*ldb];
}
if (*beta == 0) {
C[i+j*ldc] = *alpha*temp;
} else {
C[i+j*ldc] = *alpha*temp + *beta*C[i+j*ldc];
}
}
}
}
} else if (TransA == CblasNoTrans) {
// C = alpha*A*B**T + beta*C
for (int j = 0; j < N; ++j) {
if (*beta == 0) {
for (int i = 0; i < M; ++i) {
C[i+j*ldc] = 0;
}
} else if (*beta != 1) {
for (int i = 0; i < M; ++i) {
C[i+j*ldc] *= *beta;
}
}
for (int l = 0; l < K; ++l) {
if (B[j+l*ldb] != 0) {
temp = *alpha * B[j+l*ldb];
for (int i = 0; i < M; ++i) {
C[i+j*ldc] += A[i+l*lda] * temp;
}
}
}
}
} else {
// C = alpha*A**DType*B**T + beta*C
for (int j = 0; j < N; ++j) {
for (int i = 0; i < M; ++i) {
temp = 0;
for (int l = 0; l < K; ++l) {
temp += A[l+i*lda] * B[j+l*ldb];
}
if (*beta == 0) {
C[i+j*ldc] = *alpha*temp;
} else {
C[i+j*ldc] = *alpha*temp + *beta*C[i+j*ldc];
}
}
}
}
return;
}
template <typename DType>
inline void gemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,
const DType* alpha, const DType* A, const int lda, const DType* B, const int ldb, const DType* beta, DType* C, const int ldc)
{
if (Order == CblasRowMajor) {
if (TransA == CblasNoTrans) {
if (lda < std::max(K,1)) {
rb_raise(rb_eArgError, "lda must be >= MAX(K,1): lda=%d K=%d", lda, K);
}
} else {
if (lda < std::max(M,1)) { // && TransA == CblasTrans
rb_raise(rb_eArgError, "lda must be >= MAX(M,1): lda=%d M=%d", lda, M);
}
}
if (TransB == CblasNoTrans) {
if (ldb < std::max(N,1)) {
rb_raise(rb_eArgError, "ldb must be >= MAX(N,1): ldb=%d N=%d", ldb, N);
}
} else {
if (ldb < std::max(K,1)) {
rb_raise(rb_eArgError, "ldb must be >= MAX(K,1): ldb=%d K=%d", ldb, K);
}
}
if (ldc < std::max(N,1)) {
rb_raise(rb_eArgError, "ldc must be >= MAX(N,1): ldc=%d N=%d", ldc, N);
}
} else { // CblasColMajor
if (TransA == CblasNoTrans) {
if (lda < std::max(M,1)) {
rb_raise(rb_eArgError, "lda must be >= MAX(M,1): lda=%d M=%d", lda, M);
}
} else {
if (lda < std::max(K,1)) { // && TransA == CblasTrans
rb_raise(rb_eArgError, "lda must be >= MAX(K,1): lda=%d K=%d", lda, K);
}
}
if (TransB == CblasNoTrans) {
if (ldb < std::max(K,1)) {
rb_raise(rb_eArgError, "ldb must be >= MAX(K,1): ldb=%d N=%d", ldb, K);
}
} else {
if (ldb < std::max(N,1)) { // NOTE: This error message is actually wrong in the ATLAS source currently. Or are we wrong?
rb_raise(rb_eArgError, "ldb must be >= MAX(N,1): ldb=%d N=%d", ldb, N);
}
}
if (ldc < std::max(M,1)) {
rb_raise(rb_eArgError, "ldc must be >= MAX(M,1): ldc=%d N=%d", ldc, M);
}
}
/*
* Call SYRK when that's what the user is actually asking for; just handle beta=0, because beta=X requires
* we copy C and then subtract to preserve asymmetry.
*/
if (A == B && M == N && TransA != TransB && lda == ldb && beta == 0) {
rb_raise(rb_eNotImpError, "syrk and syreflect not implemented");
/*syrk<DType>(CblasUpper, (Order == CblasColMajor) ? TransA : TransB, N, K, alpha, A, lda, beta, C, ldc);
syreflect(CblasUpper, N, C, ldc);
*/
}
if (Order == CblasRowMajor) gemm_nothrow<DType>(TransB, TransA, N, M, K, alpha, B, ldb, A, lda, beta, C, ldc);
else gemm_nothrow<DType>(TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc);
}
#if (defined(HAVE_CBLAS_H) || defined(HAVE_ATLAS_CBLAS_H))
template <>
inline void gemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,
const float* alpha, const float* A, const int lda, const float* B, const int ldb, const float* beta, float* C, const int ldc) {
cblas_sgemm(Order, TransA, TransB, M, N, K, *alpha, A, lda, B, ldb, *beta, C, ldc);
}
template <>
inline void gemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, 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) {
cblas_dgemm(Order, TransA, TransB, M, N, K, *alpha, A, lda, B, ldb, *beta, C, ldc);
}
template <>
inline void gemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,
const Complex64* alpha, const Complex64* A, const int lda, const Complex64* B, const int ldb, const Complex64* beta, Complex64* C, const int ldc) {
cblas_cgemm(Order, TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc);
}
template <>
inline void gemm(const enum CBLAS_ORDER Order, const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,
const Complex128* alpha, const Complex128* A, const int lda, const Complex128* B, const int ldb, const Complex128* beta, Complex128* C, const int ldc) {
cblas_zgemm(Order, TransA, TransB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc);
}
#endif
}} // end of namespace nm::math
#endif // GEMM_H
| {
"alphanum_fraction": 0.5507394767,
"avg_line_length": 31.618705036,
"ext": "h",
"hexsha": "ec74b7fa414ffe154095d3d72e1fa2a4e4f7f44b",
"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": "de9c8ea1d42da57b0a23ce1c2ab9614fa2a65e6d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "cjfuller/nmatrix",
"max_forks_repo_path": "ext/nmatrix/math/gemm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "de9c8ea1d42da57b0a23ce1c2ab9614fa2a65e6d",
"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": "cjfuller/nmatrix",
"max_issues_repo_path": "ext/nmatrix/math/gemm.h",
"max_line_length": 162,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "de9c8ea1d42da57b0a23ce1c2ab9614fa2a65e6d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "cjfuller/nmatrix",
"max_stars_repo_path": "ext/nmatrix/math/gemm.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2858,
"size": 8790
} |
/* min/test_funcs.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <gsl/gsl_math.h>
#include <gsl/gsl_min.h>
#include "test.h"
gsl_function create_function (double (*f)(double, void *))
{
gsl_function F ;
F.function = f ;
F.params = 0 ;
return F ;
}
double
f_cos (double x, void * p)
{
p = 0; /* avoid warning about unused parameter */
return cos(x);
}
/* f(x) = x^4 - 1 */
/* minimum at x = 0 */
double
func1 (double x, void * p)
{
p = 0; /* avoid warning about unused parameter */
return pow (x, 4.0) - 1;
}
/* f(x) = sqrt(|x|) */
/* minimum at x = 0 */
double
func2 (double x, void * p)
{
p = 0; /* avoid warning about unused parameter */
return sqrt(fabs(x));
}
/* f(x) = 1 for x < 1 and -exp(-x) for x >= 1 */
/* minimum at x = 1 */
double
func3 (double x, void * p)
{
p = 0; /* avoid warning about unused parameter */
if (x < 1)
return 1 ;
else
return - exp(-x) ;
}
/* f(x) = x - 30/(1+1e5*(x-0.8)**2) */
/* minimum near x = 0.8 */
double
func4 (double x, void * p)
{
p = 0; /* avoid warning about unused parameter */
return x - 30.0 / (1.0 + 1e5 * pow(x-0.8, 2.0));
}
| {
"alphanum_fraction": 0.6311605723,
"avg_line_length": 21.9418604651,
"ext": "c",
"hexsha": "9d45be21292e4444b961a2e1ed50b0fc678100ce",
"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/min/test_funcs.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/min/test_funcs.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/min/test_funcs.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": 592,
"size": 1887
} |
#pragma once
#include <cblas.h>
#include <stdlib.h>
#include <immintrin.h>
#include <faiss/IndexIVF.h>
#include <faiss/utils/Heap.h>
#ifdef OPT_DTYPE_UTILS
namespace faiss {
//==================================Convertion================================
inline const float* convert_x_T_impl (size_t, const float* x, float*) {
return x;
}
template <typename T>
const T* convert_x_T_impl (size_t d, const float* x, T*) {
T* conv_x = new T[d];
for (size_t i = 0; i < d; i++) {
conv_x[i] = static_cast<T> (x[i]);
}
return conv_x;
}
template <typename T>
inline const T* convert_x_T (size_t d, const float* x) {
return convert_x_T_impl (d, x, (T*)nullptr);
}
inline void del_converted_x_T (size_t, const float*) {
}
template <typename T>
inline void del_converted_x_T (size_t, const T* conv_x) {
delete[] conv_x;
}
template <typename T>
struct Converter_T {
const size_t d;
const T* const x;
Converter_T (size_t d, const float* x):
d (d), x (convert_x_T<T> (d, x)) {
}
~Converter_T () {
del_converted_x_T (d, x);
}
};
//==============================Distance Function=============================
template <typename Tdis, typename T>
Tdis vec_IP_ref_T (const T* x, const T* y, size_t d, Tdis sum = 0) {
for (size_t i = 0; i < d; i++) {
sum += static_cast<Tdis> (x[i]) * static_cast<Tdis> (y[i]);
}
return sum;
}
inline float vec_IP_ref_T (const float* x, const float* y, size_t d) {
return vec_IP_ref_T<float> (x, y, d);
}
inline float vec_IP_ref_T (const bfp16_t* x, const bfp16_t* y,
size_t d) {
return vec_IP_ref_T<float> (x, y, d);
}
template <typename Tdis, typename T>
Tdis vec_L2Sqr_ref_T (const T* x, const T* y, size_t d, Tdis sum = 0) {
for (size_t i = 0; i < d; i++) {
Tdis diff = static_cast<Tdis> (x[i]) - static_cast<Tdis> (y[i]);
sum += diff * diff;
}
return sum;
}
inline float vec_L2Sqr_ref_T (const float* x, const float* y, size_t d) {
return vec_L2Sqr_ref_T<float> (x, y, d);
}
inline float vec_L2Sqr_ref_T (const bfp16_t* x, const bfp16_t* y,
size_t d) {
return vec_L2Sqr_ref_T<float> (x, y, d);
}
#ifdef __SSE4_1__
#define USE_SIMD_128
inline __m128 _mm_loadu_ps_T (const float* x) {
return _mm_loadu_ps (x);
}
inline __m128 _mm_loadu_ps_T (const bfp16_t* x) {
return _mm_castsi128_ps (_mm_unpacklo_epi16 (
_mm_setzero_si128 (),
_mm_loadl_epi64 ((const __m128i*)x)));
}
template <typename T>
float vec_IP_fp_128b_T (const T* x, const T* y, size_t d,
__m128 msum = _mm_setzero_ps ()) {
while (d >= 4) {
__m128 mx = _mm_loadu_ps_T (x);
x += 4;
__m128 my = _mm_loadu_ps_T (y);
y += 4;
msum = _mm_add_ps (msum, _mm_mul_ps (mx, my));
d -= 4;
}
msum = _mm_hadd_ps (msum, msum);
msum = _mm_hadd_ps (msum, msum);
float sum = _mm_cvtss_f32 (msum);
return d == 0 ? sum : vec_IP_ref_T<float> (x, y, d, sum);
}
inline float vec_IP_128b_T (const float* x, const float* y, size_t d) {
return vec_IP_fp_128b_T (x, y, d);
}
inline float vec_IP_128b_T (const bfp16_t* x, const bfp16_t* y,
size_t d) {
return vec_IP_fp_128b_T (x, y, d);
}
template <typename T>
float vec_L2Sqr_fp_128b_T (const T* x, const T* y, size_t d,
__m128 msum = _mm_setzero_ps ()) {
while (d >= 4) {
__m128 mx = _mm_loadu_ps_T (x);
x += 4;
__m128 my = _mm_loadu_ps_T (y);
y += 4;
__m128 mdiff = _mm_sub_ps (mx, my);
msum = _mm_add_ps (msum, _mm_mul_ps (mdiff, mdiff));
d -= 4;
}
msum = _mm_hadd_ps (msum, msum);
msum = _mm_hadd_ps (msum, msum);
float sum = _mm_cvtss_f32 (msum);
return d == 0 ? sum : vec_L2Sqr_ref_T<float> (x, y, d, sum);
}
inline float vec_L2Sqr_128b_T (const float* x, const float* y, size_t d) {
return vec_L2Sqr_fp_128b_T (x, y, d);
}
inline float vec_L2Sqr_128b_T (const bfp16_t* x, const bfp16_t* y,
size_t d) {
return vec_L2Sqr_fp_128b_T (x, y, d);
}
#endif
#ifdef __AVX2__
#ifndef USE_SIMD_128
#error "SIMD 256 must have SIMD 128 enabled"
#endif
#define USE_SIMD_256
inline __m256 _mm256_loadu_ps_T (const float* x) {
return _mm256_loadu_ps (x);
}
inline __m256 _mm256_loadu_ps_T (const bfp16_t* x) {
return
_mm256_castsi256_ps (
_mm256_unpacklo_epi16 (
_mm256_setzero_si256 (),
_mm256_insertf128_si256 (
_mm256_castsi128_si256 (
_mm_loadl_epi64 ((const __m128i*)x)),
_mm_loadl_epi64 ((const __m128i*)(x + 4)),
1)));
}
template <typename T>
float vec_IP_fp_256b_T (const T* x, const T* y, size_t d,
__m256 msum = _mm256_setzero_ps ()) {
while (d >= 8) {
__m256 mx = _mm256_loadu_ps_T (x);
x += 8;
__m256 my = _mm256_loadu_ps_T (y);
y += 8;
msum = _mm256_add_ps (msum, _mm256_mul_ps (mx, my));
d -= 8;
}
__m128 msum2 = _mm256_extractf128_ps (msum, 1);
msum2 = _mm_add_ps (msum2, _mm256_extractf128_ps (msum, 0));
return vec_IP_fp_128b_T (x, y, d, msum2);
}
inline float vec_IP_256b_T (const float* x, const float* y, size_t d) {
return vec_IP_fp_256b_T (x, y, d);
}
inline float vec_IP_256b_T (const bfp16_t* x, const bfp16_t* y,
size_t d) {
return vec_IP_fp_256b_T (x, y, d);
}
template <typename T>
float vec_L2Sqr_fp_256b_T (const T* x, const T* y, size_t d,
__m256 msum = _mm256_setzero_ps ()) {
while (d >= 8) {
__m256 mx = _mm256_loadu_ps_T (x);
x += 8;
__m256 my = _mm256_loadu_ps_T (y);
y += 8;
__m256 mdiff = _mm256_sub_ps (mx, my);
msum = _mm256_add_ps (msum, _mm256_mul_ps (mdiff, mdiff));
d -= 8;
}
__m128 msum2 = _mm256_extractf128_ps (msum, 1);
msum2 = _mm_add_ps (msum2, _mm256_extractf128_ps (msum, 0));
return vec_L2Sqr_fp_128b_T (x, y, d, msum2);
}
inline float vec_L2Sqr_256b_T (const float* x, const float* y, size_t d) {
return vec_L2Sqr_fp_256b_T (x, y, d);
}
inline float vec_L2Sqr_256b_T (const bfp16_t* x, const bfp16_t* y,
size_t d) {
return vec_L2Sqr_fp_256b_T (x, y, d);
}
#endif
#if defined (__AVX512F__) && defined(__AVX512DQ__) && defined(__AVX512BW__) \
&& defined(__AVX512VL__)
#ifndef USE_SIMD_256
#error "SIMD 512 must have SIMD 256 enabled"
#endif
#define USE_SIMD_512
inline __m512 _mm512_loadu_ps_T (const float* x) {
return _mm512_loadu_ps (x);
}
inline __m512 _mm512_loadu_ps_T (const bfp16_t* x) {
return
_mm512_castsi512_ps (
_mm512_unpacklo_epi16 (
_mm512_setzero_si512 (),
_mm512_inserti64x4 (
_mm512_castsi256_si512 (
_mm256_inserti32x4 (
_mm256_castsi128_si256 (
_mm_loadl_epi64 ((const __m128i*)x)),
_mm_loadl_epi64 ((const __m128i*)(x + 4)),
1)),
_mm256_inserti32x4 (
_mm256_castsi128_si256 (
_mm_loadl_epi64 ((const __m128i*)(x + 8))),
_mm_loadl_epi64 ((const __m128i*)(x + 12)),
1),
1)));
}
template <typename T>
float vec_IP_fp_512b_T (const T* x, const T* y, size_t d,
__m512 msum = _mm512_setzero_ps ()) {
while (d >= 16) {
__m512 mx = _mm512_loadu_ps_T (x);
x += 16;
__m512 my = _mm512_loadu_ps_T (y);
y += 16;
msum = _mm512_add_ps (msum, _mm512_mul_ps (mx, my));
d -= 16;
}
__m256 msum2 = _mm512_extractf32x8_ps (msum, 1);
msum2 = _mm256_add_ps (msum2, _mm512_extractf32x8_ps (msum, 0));
return vec_IP_fp_256b_T (x, y, d, msum2);
}
inline float vec_IP_512b_T (const float* x, const float* y, size_t d) {
return vec_IP_fp_512b_T (x, y, d);
}
inline float vec_IP_512b_T (const bfp16_t* x, const bfp16_t* y,
size_t d) {
return vec_IP_fp_512b_T (x, y, d);
}
template <typename T>
float vec_L2Sqr_fp_512b_T (const T* x, const T* y, size_t d,
__m512 msum = _mm512_setzero_ps ()) {
while (d >= 16) {
__m512 mx = _mm512_loadu_ps_T (x);
x += 16;
__m512 my = _mm512_loadu_ps_T (y);
y += 16;
__m512 mdiff = _mm512_sub_ps (mx, my);
msum = _mm512_add_ps (msum, _mm512_mul_ps (mdiff, mdiff));
d -= 16;
}
__m256 msum2 = _mm512_extractf32x8_ps (msum, 1);
msum2 = _mm256_add_ps (msum2, _mm512_extractf32x8_ps (msum, 0));
return vec_L2Sqr_fp_256b_T (x, y, d, msum2);
}
inline float vec_L2Sqr_512b_T (const float* x, const float* y, size_t d) {
return vec_L2Sqr_fp_512b_T (x, y, d);
}
inline float vec_L2Sqr_512b_T (const bfp16_t* x, const bfp16_t* y,
size_t d) {
return vec_L2Sqr_fp_512b_T (x, y, d);
}
#endif
#if defined (USE_SIMD_512)
template <typename T>
inline float vec_IP_T (const T* x, const T* y, size_t d) {
return vec_IP_512b_T (x, y, d);
}
template <typename T>
inline float vec_L2Sqr_T (const T* x, const T* y, size_t d) {
return vec_L2Sqr_512b_T (x, y, d);
}
#elif defined (USE_SIMD_256)
template <typename T>
inline float vec_IP_T (const T* x, const T* y, size_t d) {
return vec_IP_256b_T (x, y, d);
}
template <typename T>
inline float vec_L2Sqr_T (const T* x, const T* y, size_t d) {
return vec_L2Sqr_256b_T (x, y, d);
}
#elif defined (USE_SIMD_128)
template <typename T>
inline float vec_IP_T (const T* x, const T* y, size_t d) {
return vec_IP_128b_T (x, y, d);
}
template <typename T>
inline float vec_L2Sqr_T (const T* x, const T* y, size_t d) {
return vec_L2Sqr_128b_T (x, y, d);
}
#else
template <typename T>
inline float vec_IP_T (const T* x, const T* y, size_t d) {
return vec_IP_ref_T (x, y, d);
}
template <typename T>
inline float vec_L2Sqr_T (const T* x, const T* y, size_t d) {
return vec_L2Sqr_ref_T (x, y, d);
}
#endif
}
#endif
#ifdef OPT_FLAT_DTYPE
#define FLAT_BATCH_THRESHOLD 4
namespace faiss {
//=================================KNN Routine================================
template <typename T, typename D>
void knn_less_better_alone_T (const T* x, const T* y, size_t d,
size_t nx, size_t ny, float_maxheap_array_t* res, D& distance) {
size_t k = res->k;
size_t check_period = InterruptCallback::get_period_hint (ny * d);
check_period *= omp_get_max_threads ();
for (size_t i0 = 0; i0 < nx; i0 += check_period) {
size_t i1 = std::min (i0 + check_period, nx);
#pragma omp parallel for
for (size_t i = i0; i < i1; i++) {
const T* x_i = x + i * d;
const T* y_j = y;
float* simi = res->get_val (i);
int64_t* idxi = res->get_ids (i);
maxheap_heapify (k, simi, idxi);
for (size_t j = 0; j < ny; j++) {
float dis = distance (i, j, x_i, y_j, d);
if (dis < simi[0]) {
maxheap_pop (k, simi, idxi);
maxheap_push (k, simi, idxi, dis, j);
}
y_j += d;
}
maxheap_reorder (k, simi, idxi);
}
InterruptCallback::check ();
}
}
template <typename T, typename D>
void knn_greater_better_alone_T (const T* x, const T* y, size_t d,
size_t nx, size_t ny, float_minheap_array_t* res, D& distance) {
size_t k = res->k;
size_t check_period = InterruptCallback::get_period_hint (ny * d);
check_period *= omp_get_max_threads ();
for (size_t i0 = 0; i0 < nx; i0 += check_period) {
size_t i1 = std::min (i0 + check_period, nx);
#pragma omp parallel for
for (size_t i = i0; i < i1; i++) {
const T* x_i = x + i * d;
const T* y_j = y;
float* simi = res->get_val (i);
int64_t* idxi = res->get_ids (i);
minheap_heapify (k, simi, idxi);
for (size_t j = 0; j < ny; j++) {
float dis = distance (i, j, x_i, y_j, d);
if (dis > simi[0]) {
minheap_pop (k, simi, idxi);
minheap_push (k, simi, idxi, dis, j);
}
y_j += d;
}
minheap_reorder (k, simi, idxi);
}
InterruptCallback::check ();
}
}
template <typename T>
inline void knn_inner_product_alone_T (const T* x, const T* y, size_t d,
size_t nx, size_t ny, float_minheap_array_t* res) {
struct IP {
inline float operator () (size_t /*ix*/, size_t /*jy*/,
const T* xi, const T* yj, size_t d) const {
return vec_IP_T (xi, yj, d);
}
}
distance;
knn_greater_better_alone_T (x, y, d, nx, ny, res, distance);
}
template <typename T>
inline void knn_L2Sqr_alone_T (const T* x, const T* y, size_t d,
size_t nx, size_t ny, float_maxheap_array_t* res) {
struct L2Sqr {
inline float operator () (size_t /*ix*/, size_t /*jy*/,
const T* xi, const T* yj, size_t d) const {
return vec_L2Sqr_T (xi, yj, d);
}
}
distance;
knn_less_better_alone_T (x, y, d, nx, ny, res, distance);
}
template <typename T>
inline void knn_L2Sqr_expand_alone_T (const T* x, const T* y, size_t d,
size_t nx, size_t ny, float_maxheap_array_t* res,
const float* y_norm) {
struct L2SqrExpand {
const float* y_norm_sqr;
inline float operator () (size_t /*ix*/, size_t jy,
const T* xi, const T* yj, size_t d) const {
return y_norm_sqr[jy] - 2 * vec_IP_T (xi, yj, d);
}
}
distance = {
.y_norm_sqr = y_norm,
};
knn_less_better_alone_T (x, y, d, nx, ny, res, distance);
}
template <typename T>
inline void knn_inner_product_batch_T (const T* x, const T* y, size_t d,
size_t nx, size_t ny, float_minheap_array_t* res) {
knn_inner_product_alone_T (x, y, d, nx, ny, res);
}
template <typename T>
inline void knn_L2Sqr_batch_T (const T* x, const T* y, size_t d,
size_t nx, size_t ny, float_maxheap_array_t* res) {
knn_L2Sqr_alone_T (x, y, d, nx, ny, res);
}
template <typename T>
inline void knn_L2Sqr_expand_batch_T (const T* x, const T* y, size_t d,
size_t nx, size_t ny, float_maxheap_array_t* res,
const float* y_norm) {
knn_L2Sqr_expand_alone_T (x, y, d, nx, ny, res, y_norm);
}
template <typename H, typename D>
void knn_batch_T (const float* x, const float* y,
size_t d, size_t nx, size_t ny, H* heap, D& distance) {
heap->heapify ();
if (nx == 0 || ny == 0) {
return;
}
float* distances = new float [nx * ny];
distance (x, y, d, nx, ny, distances);
heap->addn (ny, distances, 0, 0, nx);
delete[] distances;
InterruptCallback::check ();
heap->reorder ();
}
inline void knn_inner_product_batch_T (const float* x, const float* y,
size_t d, size_t nx, size_t ny, float_minheap_array_t* res) {
struct IP {
inline void operator () (const float* x, const float* y,
size_t d, size_t nx, size_t ny, float* distances) const {
cblas_sgemm (CblasRowMajor, CblasNoTrans, CblasTrans, nx, ny, d,
1.0f, x, d, y, d, 0.0f, distances, ny);
}
}
distance;
knn_batch_T (x, y, d, nx, ny, res, distance);
}
inline void knn_L2Sqr_expand_batch_T (const float* x, const float* y,
size_t d, size_t nx, size_t ny, float_maxheap_array_t* res,
const float* y_norm) {
struct L2SqrExpand {
const float* y_norm;
inline void operator () (const float* x, const float* y,
size_t d, size_t nx, size_t ny, float* distances) const {
float* distances_i = distances;
size_t step = ny * sizeof(float);
for (size_t i = 0; i < nx; i++) {
memcpy (distances_i, y_norm, step);
distances_i += ny;
}
cblas_sgemm (CblasRowMajor, CblasNoTrans, CblasTrans, nx, ny, d,
-2.0f, x, d, y, d, 1.0f, distances, ny);
}
}
distance = {
.y_norm = y_norm,
};
knn_batch_T (x, y, d, nx, ny, res, distance);
}
template <typename T>
inline void knn_inner_product_T (const T* x, const T* y, size_t d,
size_t nx, size_t ny, float_minheap_array_t* res) {
if (nx < FLAT_BATCH_THRESHOLD) {
knn_inner_product_alone_T (x, y, d, nx, ny, res);
}
else {
knn_inner_product_batch_T (x, y, d, nx, ny, res);
}
}
template <typename T>
inline void knn_L2Sqr_T (const T* x, const T* y, size_t d,
size_t nx, size_t ny, float_maxheap_array_t* res) {
if (nx < FLAT_BATCH_THRESHOLD) {
knn_L2Sqr_alone_T (x, y, d, nx, ny, res);
}
else {
knn_L2Sqr_batch_T (x, y, d, nx, ny, res);
}
}
template <typename T>
inline void knn_L2Sqr_expand_T (const T* x, const T* y, size_t d,
size_t nx, size_t ny, float_maxheap_array_t* res,
const float* y_norm) {
if (nx < FLAT_BATCH_THRESHOLD) {
knn_L2Sqr_expand_alone_T (x, y, d, nx, ny, res, y_norm);
}
else {
knn_L2Sqr_expand_batch_T (x, y, d, nx, ny, res, y_norm);
}
}
}
#endif
#ifdef OPT_IVFFLAT_DTYPE
#define SCANNER_USE_BATCH false
namespace faiss {
//===========================Inverted List Scanner============================
template <typename T>
class InvertedListScanner_T : public InvertedListScanner {
using idx_t = InvertedListScanner::idx_t;
protected:
size_t d;
size_t code_size;
bool store_pairs;
const T* converted_x;
idx_t list_no;
public:
InvertedListScanner_T (size_t d, bool store_pairs):
d (d), code_size (sizeof(T) * d), store_pairs (store_pairs),
converted_x(nullptr), list_no(-1) {
}
virtual ~InvertedListScanner_T () {
if (converted_x) {
del_converted_x_T (d, converted_x);
}
}
virtual void set_query (const float* query) override {
if (converted_x) {
del_converted_x_T (d, converted_x);
}
converted_x = convert_x_T<T> (d, query);
}
virtual void set_list (idx_t lidx, float) override {
list_no = lidx;
}
virtual float distance_to_code (const uint8_t*) const override {
FAISS_THROW_MSG ("not implemented");
}
virtual size_t scan_codes (size_t list_size, const uint8_t* codes,
const idx_t* ids, float* simi, idx_t* idxi, size_t k)
const = 0;
};
template <typename T, typename C, typename D>
class AloneInvertedListScanner_T : public InvertedListScanner_T<T> {
using idx_t = InvertedListScanner::idx_t;
using Scanner = InvertedListScanner_T<T>;
private:
D* distance;
public:
AloneInvertedListScanner_T (size_t d, bool store_pairs, D* distance):
Scanner (d, store_pairs), distance (distance) {
}
virtual ~AloneInvertedListScanner_T () {
delete distance;
}
virtual size_t scan_codes (size_t list_size, const uint8_t* codes,
const idx_t* ids, float* simi, idx_t* idxi,
size_t k) const override {
size_t nup = 0;
for (size_t i = 0; i < list_size; i++) {
float dis = (*distance) (Scanner::list_no, i,Scanner::converted_x,
(const T*)codes, Scanner::d);
codes += Scanner::code_size;
if (C::cmp (simi[0], dis)) {
heap_pop<C> (k, simi, idxi);
int64_t id = Scanner::store_pairs ?
lo_build (Scanner::list_no, i) :
ids[i];
heap_push<C> (k, simi, idxi, dis, id);
nup++;
}
}
return nup;
}
};
template <typename T>
InvertedListScanner* get_IP_alone_scanner_T (size_t d, bool store_pairs) {
struct IP {
inline float operator () (size_t /*ilist*/, size_t /*jy*/,
const T* x, const T* yj, size_t d) const {
return vec_IP_T (x, yj, d);
}
}
*distance = new IP;
return new AloneInvertedListScanner_T<T, CMin<float, int64_t>, IP> (d,
store_pairs, distance);
}
template <typename T>
InvertedListScanner* get_L2Sqr_alone_scanner_T (size_t d, bool store_pairs) {
struct L2Sqr {
inline float operator () (size_t /*ilist*/, size_t /*jy*/,
const T* x, const T* yj, size_t d) const {
return vec_L2Sqr_T (x, yj, d);
}
}
*distance = new L2Sqr;
return new AloneInvertedListScanner_T<T, CMax<float, int64_t>, L2Sqr> (d,
store_pairs, distance);
}
template <typename T, typename TNorm>
InvertedListScanner* get_L2Sqr_expand_alone_scanner_T (size_t d,
bool store_pairs, const TNorm y_norm) {
struct L2SqrExpand {
const TNorm y_norm;
inline float operator () (size_t ilist, size_t jy,
const T* x, const T* yj, size_t d) {
return y_norm [ilist] [jy] - 2 * vec_IP_T (x, yj, d);
}
}
*distance = new L2SqrExpand {
.y_norm = y_norm,
};
return new AloneInvertedListScanner_T<T, CMax<float, int64_t>,
L2SqrExpand> (d, store_pairs, distance);
}
template <typename T, typename C, typename D>
class BatchInvertedListScanner_T : public InvertedListScanner_T<T> {
using idx_t = InvertedListScanner::idx_t;
using Scanner = InvertedListScanner_T<T>;
private:
D* distance;
public:
BatchInvertedListScanner_T (size_t d, bool store_pairs, D* distance):
Scanner (d, store_pairs), distance (distance) {
}
virtual ~BatchInvertedListScanner_T () {
delete distance;
}
virtual size_t scan_codes (size_t list_size, const uint8_t* codes,
const idx_t* ids, float* simi, idx_t* idxi,
size_t k) const override {
float* distances = new float [list_size];
(*distance) (Scanner::converted_x, Scanner::list_no, list_size,
(const T*)codes, Scanner::d, distances);
size_t nup = 0;
for (size_t i = 0; i < list_size; i++) {
float dis = distances [i];
if (C::cmp (simi[0], dis)) {
heap_pop<C> (k, simi, idxi);
int64_t id = Scanner::store_pairs ?
lo_build (Scanner::list_no, i) : ids[i];
heap_push<C> (k, simi, idxi, dis, id);
nup++;
}
}
delete[] distances;
return nup;
}
};
template <typename T>
inline InvertedListScanner* get_IP_batch_scanner_T (size_t d, bool store_pairs,
T*) {
return get_IP_alone_scanner_T<T> (d, store_pairs);
}
inline InvertedListScanner* get_IP_batch_scanner_T (size_t d, bool store_pairs,
float*) {
struct IP {
inline void operator () (const float* x, size_t /*ilist*/,
size_t list_size, const float* y, size_t d, float* distances)
const {
cblas_sgemv (CblasRowMajor, CblasNoTrans, list_size, d, 1.0f,
y, d, x, 1, 0.0f, distances, 1);
}
}
*distance = new IP;
return new BatchInvertedListScanner_T<float, CMin<float, int64_t>, IP> (d,
store_pairs, distance);
}
template <typename T>
inline InvertedListScanner* get_L2Sqr_batch_scanner_T (size_t d,
bool store_pairs, T*) {
return get_L2Sqr_alone_scanner_T<T> (d, store_pairs);
}
template <typename T, typename TNorm>
inline InvertedListScanner* get_L2Sqr_expand_batch_scanner_T (size_t d,
bool store_pairs, const TNorm y_norm, T*) {
return get_L2Sqr_expand_alone_scanner_T<T> (d, store_pairs,
y_norm);
}
template <typename TNorm>
inline InvertedListScanner* get_L2Sqr_expand_batch_scanner_T (size_t d,
bool store_pairs, const TNorm y_norm, float*) {
struct L2SqrExpand {
const TNorm y_norm;
inline void operator () (const float* x, size_t ilist,
size_t list_size, const float* y, size_t d, float* distances)
const {
memcpy (distances, &(y_norm [ilist] [0]),
list_size * sizeof(float));
cblas_sgemv (CblasRowMajor, CblasNoTrans, list_size, d, -2.0f,
y, d, x, 1, 1.0f, distances, 1);
}
}
*distance = new L2SqrExpand {
.y_norm = y_norm,
};
return new BatchInvertedListScanner_T<float, CMax<float, int64_t>,
L2SqrExpand> (d, store_pairs, distance);
}
template <typename T>
inline InvertedListScanner* get_IP_scanner_T (size_t d, bool store_pairs) {
if (!SCANNER_USE_BATCH) {
return get_IP_alone_scanner_T<T> (d, store_pairs);
}
else {
return get_IP_batch_scanner_T (d, store_pairs, (T*)nullptr);
}
}
template <typename T>
inline InvertedListScanner* get_L2Sqr_scanner_T (size_t d, bool store_pairs) {
if (!SCANNER_USE_BATCH) {
return get_L2Sqr_alone_scanner_T<T> (d, store_pairs);
}
else {
return get_L2Sqr_batch_scanner_T (d, store_pairs, (T*)nullptr);
}
}
template <typename T, typename TNorm>
inline InvertedListScanner* get_L2Sqr_expand_scanner_T (size_t d,
bool store_pairs, const TNorm y_norm) {
if (!SCANNER_USE_BATCH) {
return get_L2Sqr_expand_alone_scanner_T<T> (d, store_pairs, y_norm);
}
else {
return get_L2Sqr_expand_batch_scanner_T (d, store_pairs, y_norm,
(T*)nullptr);
}
}
}
#endif | {
"alphanum_fraction": 0.5929231251,
"avg_line_length": 28.4816053512,
"ext": "h",
"hexsha": "c731edafa41a8c33233216dbc8bc267ea85c112d",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-06-07T08:20:22.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-07T02:42:46.000Z",
"max_forks_repo_head_hexsha": "f91b08ac28140e4f640fe3aa6fe1109cbf288edc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zhou-yuxin/faiss",
"max_forks_repo_path": "utils/dtype.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f91b08ac28140e4f640fe3aa6fe1109cbf288edc",
"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": "zhou-yuxin/faiss",
"max_issues_repo_path": "utils/dtype.h",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "f91b08ac28140e4f640fe3aa6fe1109cbf288edc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zhou-yuxin/faiss",
"max_stars_repo_path": "utils/dtype.h",
"max_stars_repo_stars_event_max_datetime": "2020-10-11T21:48:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-11T21:48:28.000Z",
"num_tokens": 7963,
"size": 25548
} |
/* specfunc/test_mathieu.c
*
* Copyright (C) 2003 Lowell Johnson
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: L. Johnson */
#include <gsl/gsl_test.h>
#include <gsl/gsl_sf.h>
#include "test_sf.h"
#define NVAL 100
static double c[NVAL];
int test_mathieu(void)
{
gsl_sf_result r;
gsl_sf_mathieu_workspace *work;
int s = 0;
int sa;
TEST_SF(s, gsl_sf_mathieu_ce_e, (0, 0.0, 0.0, &r),
0.7071067811865475, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (0, 0.0, M_PI_2, &r),
0.7071067811865475, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (0, 5.0, 0.0, &r),
0.04480018165188902, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (0, 5.0, M_PI_2, &r),
1.334848674698019, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (0, 10.0, 0.0, &r),
0.007626517570935782, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (0, 10.0, M_PI_2, &r),
1.468660470712856, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (0, 15.0, 0.0, &r),
0.001932508315204592, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (0, 15.0, M_PI_2, &r),
1.550108146686649, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (0, 20.0, 0.0, &r),
0.0006037438292242197, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (0, 20.0, M_PI_2, &r),
1.609890857395926, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (0, 25.0, 0.0, &r),
0.0002158630184146612, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (0, 25.0, M_PI_2, &r),
1.657510298323475, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (1, 0.0, 0.0, &r),
1.00000000, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (1, 5.0, 0.0, &r),
0.2565428793223637, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (1, 10.0, 0.0, &r),
0.05359874774717657, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (1, 15.0, 0.0, &r),
0.01504006645382623, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (1, 20.0, 0.0, &r),
0.005051813764712904, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (1, 25.0, 0.0, &r),
0.001911051506657645, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (1, 0.0, M_PI_2, &r),
1.0000000, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (1, 5.0, M_PI_2, &r),
1.337433887022345, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (1, 10.0, M_PI_2, &r),
1.468755664102938, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (1, 15.0, M_PI_2, &r),
1.550115074357552, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (1, 20.0, M_PI_2, &r),
1.609891592603772, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (1, 25.0, M_PI_2, &r),
1.657510398374516, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (2, 0.0, 0.0, &r),
1.00000000, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (2, 0.0, M_PI_2, &r),
-1.00000000, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (2, 5.0, 0.0, &r),
0.7352943084006845, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (2, 5.0, M_PI_2, &r),
-0.7244881519676682, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (2, 10.0, 0.0, &r),
0.2458883492913189, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (2, 10.0, M_PI_2, &r),
-0.9267592641263211, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (2, 15.0, 0.0, &r),
0.07879282784639313, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (2, 15.0, M_PI_2, &r),
-1.019966226030262, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (2, 20.0, 0.0, &r),
0.02864894314707431, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (2, 20.0, M_PI_2, &r),
-1.075293228779687, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (2, 25.0, 0.0, &r),
0.0115128663308875, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (2, 25.0, M_PI_2, &r),
-1.116278953295253, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (5, 0.0, 0.0, &r),
1.00000000, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (5, 5.0, 0.0, &r),
1.12480725063848, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (5, 10.0, 0.0, &r),
1.258019941308287, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (5, 15.0, 0.0, &r),
1.193432230413072, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (5, 20.0, 0.0, &r),
0.9365755314226215, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (5, 25.0, 0.0, &r),
0.6106943100506986, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (5, 0.0, M_PI_2, &r),
1.0000000, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (5, 5.0, M_PI_2, &r),
0.9060779302023551, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (5, 10.0, M_PI_2, &r),
0.8460384335355106, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (5, 15.0, M_PI_2, &r),
0.837949340012484, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (5, 20.0, M_PI_2, &r),
0.8635431218533667, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (5, 25.0, M_PI_2, &r),
0.8992683245108413, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (10, 0.0, 0.0, &r),
1.00000000, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (10, 0.0, M_PI_2, &r),
-1.00000000, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (10, 5.0, 0.0, &r),
1.025995027089438, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (10, 5.0, M_PI_2, &r),
-0.975347487235964, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (10, 10.0, 0.0, &r),
1.053815992100935, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (10, 10.0, M_PI_2, &r),
-0.9516453181789554, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (10, 15.0, 0.0, &r),
1.084106311839221, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (10, 15.0, M_PI_2, &r),
-0.9285480638845388, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (10, 20.0, 0.0, &r),
1.117788631259397, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (10, 20.0, M_PI_2, &r),
-0.9057107845940974, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (10, 25.0, 0.0, &r),
1.156239918632239, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (10, 25.0, M_PI_2, &r),
-0.8826919105636903, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (15, 0.0, 0.0, &r),
1.00000000, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (15, 5.0, 0.0, &r),
1.011293732529566, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (15, 10.0, 0.0, &r),
1.022878282438181, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (15, 15.0, 0.0, &r),
1.034793652236873, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (15, 20.0, 0.0, &r),
1.047084344162887, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_ce_e, (15, 25.0, 0.0, &r),
1.059800441813937, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (15, 0.0, M_PI_2, &r),
-1.0000000, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (15, 5.0, M_PI_2, &r),
-0.9889607027406357, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (15, 10.0, M_PI_2, &r),
-0.9781423471832157, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (15, 15.0, M_PI_2, &r),
-0.9675137031854538, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (15, 20.0, M_PI_2, &r),
-0.9570452540612817, TEST_SNGL, GSL_SUCCESS);
TEST_SF(s, gsl_sf_mathieu_se_e, (15, 25.0, M_PI_2, &r),
-0.9467086958780897, TEST_SNGL, GSL_SUCCESS);
work = gsl_sf_mathieu_alloc(NVAL, 20.0);
sa = 0;
gsl_sf_mathieu_ce_array(0, 5, 0.0, M_PI_2, work, c);
sa += (test_sf_frac_diff(c[0], 0.7071067811865475) > TEST_SNGL);
sa += (test_sf_frac_diff(c[2], -1.0) > TEST_SNGL);
sa += (test_sf_frac_diff(c[4], 1.0) > TEST_SNGL);
gsl_test(sa, "gsl_sf_mathieu_ce_array");
s += sa;
sa = 0;
gsl_sf_mathieu_ce_array(0, 15, 20.0, 0.0, work, c);
sa += (test_sf_frac_diff(c[0], 0.0006037438292242197) > TEST_SNGL);
sa += (test_sf_frac_diff(c[1], 0.005051813764712904) > TEST_SNGL);
sa += (test_sf_frac_diff(c[2], 0.02864894314707431) > TEST_SNGL);
sa += (test_sf_frac_diff(c[5], 0.9365755314226215) > TEST_SNGL);
sa += (test_sf_frac_diff(c[10], 1.117788631259397) > TEST_SNGL);
sa += (test_sf_frac_diff(c[15], 1.047084344162887) > TEST_SNGL);
gsl_test(sa, "gsl_sf_mathieu_ce_array");
s += sa;
sa = 0;
gsl_sf_mathieu_se_array(1, 15, 20.0, M_PI_2, work, c);
sa += (test_sf_frac_diff(c[0], 1.609891592603772) > TEST_SNGL);
sa += (test_sf_frac_diff(c[4], 0.8635431218533667) > TEST_SNGL);
sa += (test_sf_frac_diff(c[14], -0.9570452540612817) > TEST_SNGL);
gsl_test(sa, "gsl_sf_mathieu_se_array");
s += sa;
gsl_sf_mathieu_free(work);
return s;
}
| {
"alphanum_fraction": 0.6648568608,
"avg_line_length": 47.558685446,
"ext": "c",
"hexsha": "fc3f90f5e1aee6d789bc3a27f7fa8b28bce83960",
"lang": "C",
"max_forks_count": 224,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z",
"max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "utdsimmons/ohpc",
"max_forks_repo_path": "tests/libs/gsl/tests/specfunc/test_mathieu.c",
"max_issues_count": 1096,
"max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "utdsimmons/ohpc",
"max_issues_repo_path": "tests/libs/gsl/tests/specfunc/test_mathieu.c",
"max_line_length": 72,
"max_stars_count": 692,
"max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "utdsimmons/ohpc",
"max_stars_repo_path": "tests/libs/gsl/tests/specfunc/test_mathieu.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z",
"num_tokens": 4012,
"size": 10130
} |
/**
*
* @file qwrapper_zlaswp.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mathieu Faverge
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_zlaswp(Quark *quark, Quark_Task_Flags *task_flags,
int n, PLASMA_Complex64_t *A, int lda,
int i1, int i2, const int *ipiv, int inc)
{
DAG_CORE_LASWP;
QUARK_Insert_Task(
quark, CORE_zlaswp_quark, task_flags,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex64_t)*lda*n, A, INOUT | LOCALITY,
sizeof(int), &lda, VALUE,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*n, ipiv, INPUT,
sizeof(int), &inc, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlaswp_quark = PCORE_zlaswp_quark
#define CORE_zlaswp_quark PCORE_zlaswp_quark
#endif
void CORE_zlaswp_quark(Quark *quark)
{
int n, lda, i1, i2, inc;
int *ipiv;
PLASMA_Complex64_t *A;
quark_unpack_args_7(quark, n, A, lda, i1, i2, ipiv, inc);
LAPACKE_zlaswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc );
}
/***************************************************************************//**
*
**/
void QUARK_CORE_zlaswp_f2(Quark *quark, Quark_Task_Flags *task_flags,
int n, PLASMA_Complex64_t *A, int lda,
int i1, int i2, const int *ipiv, int inc,
PLASMA_Complex64_t *fake1, int szefake1, int flag1,
PLASMA_Complex64_t *fake2, int szefake2, int flag2)
{
DAG_CORE_LASWP;
QUARK_Insert_Task(
quark, CORE_zlaswp_f2_quark, task_flags,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex64_t)*lda*n, A, INOUT | LOCALITY,
sizeof(int), &lda, VALUE,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*n, ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(PLASMA_Complex64_t)*szefake1, fake1, flag1,
sizeof(PLASMA_Complex64_t)*szefake2, fake2, flag2,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlaswp_f2_quark = PCORE_zlaswp_f2_quark
#define CORE_zlaswp_f2_quark PCORE_zlaswp_f2_quark
#endif
void CORE_zlaswp_f2_quark(Quark* quark)
{
int n, lda, i1, i2, inc;
int *ipiv;
PLASMA_Complex64_t *A;
void *fake1, *fake2;
quark_unpack_args_9(quark, n, A, lda, i1, i2, ipiv, inc, fake1, fake2);
LAPACKE_zlaswp_work(LAPACK_COL_MAJOR, n, A, lda, i1, i2, ipiv, inc );
}
/***************************************************************************//**
*
**/
void QUARK_CORE_zlaswp_ontile(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_desc descA, PLASMA_Complex64_t *Aij,
int i1, int i2, const int *ipiv, int inc, PLASMA_Complex64_t *fakepanel)
{
DAG_CORE_LASWP;
if (fakepanel == Aij) {
QUARK_Insert_Task(
quark, CORE_zlaswp_ontile_quark, task_flags,
sizeof(PLASMA_desc), &descA, VALUE,
sizeof(PLASMA_Complex64_t)*1, Aij, INOUT | LOCALITY,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(PLASMA_Complex64_t)*1, fakepanel, SCRATCH,
0);
} else {
QUARK_Insert_Task(
quark, CORE_zlaswp_ontile_quark, task_flags,
sizeof(PLASMA_desc), &descA, VALUE,
sizeof(PLASMA_Complex64_t)*1, Aij, INOUT | LOCALITY,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(PLASMA_Complex64_t)*1, fakepanel, INOUT,
0);
}
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlaswp_ontile_quark = PCORE_zlaswp_ontile_quark
#define CORE_zlaswp_ontile_quark PCORE_zlaswp_ontile_quark
#endif
void CORE_zlaswp_ontile_quark(Quark *quark)
{
int i1, i2, inc;
int *ipiv;
PLASMA_Complex64_t *A, *fake;
PLASMA_desc descA;
quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake);
CORE_zlaswp_ontile(descA, i1, i2, ipiv, inc);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_zlaswp_ontile_f2(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_desc descA, PLASMA_Complex64_t *Aij,
int i1, int i2, const int *ipiv, int inc,
PLASMA_Complex64_t *fake1, int szefake1, int flag1,
PLASMA_Complex64_t *fake2, int szefake2, int flag2)
{
DAG_CORE_LASWP;
QUARK_Insert_Task(
quark, CORE_zlaswp_ontile_f2_quark, task_flags,
sizeof(PLASMA_desc), &descA, VALUE,
sizeof(PLASMA_Complex64_t)*1, Aij, INOUT | LOCALITY,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(PLASMA_Complex64_t)*szefake1, fake1, flag1,
sizeof(PLASMA_Complex64_t)*szefake2, fake2, flag2,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlaswp_ontile_f2_quark = PCORE_zlaswp_ontile_f2_quark
#define CORE_zlaswp_ontile_f2_quark PCORE_zlaswp_ontile_f2_quark
#endif
void CORE_zlaswp_ontile_f2_quark(Quark *quark)
{
int i1, i2, inc;
int *ipiv;
PLASMA_Complex64_t *A;
PLASMA_desc descA;
void *fake1, *fake2;
quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, fake1, fake2);
CORE_zlaswp_ontile(descA, i1, i2, ipiv, inc);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_zswptr_ontile(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_desc descA, PLASMA_Complex64_t *Aij,
int i1, int i2, const int *ipiv, int inc,
const PLASMA_Complex64_t *Akk, int ldak)
{
DAG_CORE_TRSM;
QUARK_Insert_Task(
quark, CORE_zswptr_ontile_quark, task_flags,
sizeof(PLASMA_desc), &descA, VALUE,
sizeof(PLASMA_Complex64_t)*1, Aij, INOUT | LOCALITY,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(PLASMA_Complex64_t)*ldak, Akk, INPUT,
sizeof(int), &ldak, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zswptr_ontile_quark = PCORE_zswptr_ontile_quark
#define CORE_zswptr_ontile_quark PCORE_zswptr_ontile_quark
#endif
void CORE_zswptr_ontile_quark(Quark *quark)
{
int i1, i2, inc, ldak;
int *ipiv;
PLASMA_Complex64_t *A, *Akk;
PLASMA_desc descA;
quark_unpack_args_8(quark, descA, A, i1, i2, ipiv, inc, Akk, ldak);
CORE_zswptr_ontile(descA, i1, i2, ipiv, inc, Akk, ldak);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_zlaswpc_ontile(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_desc descA, PLASMA_Complex64_t *Aij,
int i1, int i2, const int *ipiv, int inc, PLASMA_Complex64_t *fakepanel)
{
DAG_CORE_LASWP;
if (fakepanel == Aij) {
QUARK_Insert_Task(
quark, CORE_zlaswpc_ontile_quark, task_flags,
sizeof(PLASMA_desc), &descA, VALUE,
sizeof(PLASMA_Complex64_t)*1, Aij, INOUT | LOCALITY,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(PLASMA_Complex64_t)*1, fakepanel, SCRATCH,
0);
} else {
QUARK_Insert_Task(
quark, CORE_zlaswpc_ontile_quark, task_flags,
sizeof(PLASMA_desc), &descA, VALUE,
sizeof(PLASMA_Complex64_t)*1, Aij, INOUT | LOCALITY,
sizeof(int), &i1, VALUE,
sizeof(int), &i2, VALUE,
sizeof(int)*(i2-i1+1)*abs(inc), ipiv, INPUT,
sizeof(int), &inc, VALUE,
sizeof(PLASMA_Complex64_t)*1, fakepanel, INOUT,
0);
}
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlaswpc_ontile_quark = PCORE_zlaswpc_ontile_quark
#define CORE_zlaswpc_ontile_quark PCORE_zlaswpc_ontile_quark
#endif
void CORE_zlaswpc_ontile_quark(Quark *quark)
{
int i1, i2, inc;
int *ipiv;
PLASMA_Complex64_t *A, *fake;
PLASMA_desc descA;
quark_unpack_args_7(quark, descA, A, i1, i2, ipiv, inc, fake);
CORE_zlaswpc_ontile(descA, i1, i2, ipiv, inc);
}
| {
"alphanum_fraction": 0.4969319362,
"avg_line_length": 37.5638297872,
"ext": "c",
"hexsha": "7c1e764c97faa21f4bec8c7ff286a764b172d5db",
"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_zlaswp.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_zlaswp.c",
"max_line_length": 103,
"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_zlaswp.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2970,
"size": 10593
} |
//====---- Sudoku/Value.h ----====//
//
// Strongly typed Value type.
// Unsigned for use as a bit-mask.
//====--------------------------------------------------------------------====//
#pragma once
#include "Size.h"
#include <gsl/gsl>
#include <vector>
#include <algorithm> // all_of
#include <limits>
#include <stdexcept>
#include <type_traits> // is_same
#include <cstddef> // size_t
namespace Sudoku
{
class Value
{
public:
Value() noexcept = default;
explicit constexpr Value(size_t val) noexcept : value_(val) {}
explicit constexpr operator size_t() const noexcept { return value_; }
explicit constexpr operator bool() const noexcept { return value_ != 0; }
// note: static_assert performs an explicit conversion to bool
friend constexpr bool operator==(const Value& a, const Value& b) noexcept
{ // Friend definitions: https://abseil.io/tips/99
return a.value_ == b.value_;
}
friend constexpr bool operator<(const Value& a, const Value& b) noexcept
{
return a.value_ < b.value_;
}
constexpr Value& operator++() noexcept;
constexpr Value operator++(int) noexcept;
private:
size_t value_{0};
};
//====--------------------------------------------------------------------====//
// Free-function declarations
constexpr bool operator!=(const Value&, const Value&) noexcept;
constexpr bool operator>(const Value&, const Value&) noexcept;
constexpr bool operator<=(const Value&, const Value&) noexcept;
constexpr bool operator>=(const Value&, const Value&) noexcept;
template<typename T, int N>
constexpr Value to_Value(T val);
template<int N>
constexpr bool is_valid(const Value&) noexcept;
template<int E>
inline constexpr bool is_valid_option(const Value&) noexcept;
template<int N>
bool is_valid(const std::vector<Value>&) noexcept;
//====--------------------------------------------------------------------====//
// Test input value
template<int N>
inline constexpr bool is_valid(const Value& value) noexcept
{
return is_valid_option<elem_size<N>>(value);
}
// Test input value, for use with Options<E>
template<int E>
inline constexpr bool is_valid_option(const Value& value) noexcept
{
return value > Value{0} && value <= Value{E};
}
// Test input values
template<int N>
bool is_valid(const std::vector<Value>& values) noexcept
{
return (
!values.empty() &&
std::all_of(values.cbegin(), values.cend(), [](Value i) {
return is_valid<N>(i);
}));
}
//====--------------------------------------------------------------------====//
// Checked conversion to Value
template<int N, typename T>
inline constexpr Value to_Value(T val)
{
if constexpr (std::is_same_v<Value, T>)
{
if (val > static_cast<Value>(elem_size<N>))
{
throw std::domain_error("Value input too large");
}
return val;
}
else if constexpr (std::is_unsigned_v<T>)
{
static_assert(elem_size<N> < std::numeric_limits<T>::max());
return to_Value<N>(static_cast<Value>(val));
}
else
{
static_assert(std::is_integral_v<T>);
static_assert(std::numeric_limits<T>::max() > elem_size<N>);
if (val < 0)
{
throw std::domain_error("Value can not be negative");
}
return to_Value<N>(gsl::narrow_cast<size_t>(val));
}
}
//====--------------------------------------------------------------------====//
constexpr Value& Value::operator++() noexcept
{ // pre-increment
++value_;
return *this;
}
// NOLINTNEXTLINE(readability/casting) false-positive cpplint
constexpr Value Value::operator++(int) noexcept
{ // post-increment
const Value pre{*this};
operator++();
return pre;
}
inline constexpr bool operator!=(const Value& left, const Value& right) noexcept
{
return !(left == right);
}
inline constexpr bool operator<=(const Value& left, const Value& right) noexcept
{
return !(right < left);
}
inline constexpr bool operator>(const Value& left, const Value& right) noexcept
{
return right < left;
}
inline constexpr bool operator>=(const Value& left, const Value& right) noexcept
{
return !(left < right);
}
static_assert(Value{4} == Value{4}); //-V501 //-V112
static_assert(Value{1} != Value{0});
static_assert(Value{3} > Value{2});
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
static_assert(Value{10} >= Value{7}); // NOLINT(readability-magic-numbers)
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
static_assert(Value{8} <= Value{9}); // NOLINT(readability-magic-numbers)
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
static_assert(Value{5} < Value{6}); // NOLINT(readability-magic-numbers)
} // namespace Sudoku
| {
"alphanum_fraction": 0.6449482721,
"avg_line_length": 27.5333333333,
"ext": "h",
"hexsha": "63733766816b12bac22250e46c10351c778cc100",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "FeodorFitsner/fwkSudoku",
"max_forks_repo_path": "Sudoku/Sudoku/Value.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "FeodorFitsner/fwkSudoku",
"max_issues_repo_path": "Sudoku/Sudoku/Value.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "FeodorFitsner/fwkSudoku",
"max_stars_repo_path": "Sudoku/Sudoku/Value.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1067,
"size": 4543
} |
#include <cblas.h>
#include "tasks.h"
void gemm_task_seq(void *ptr)
{
struct gemm_task_arg *arg = (struct gemm_task_arg*) ptr;
int m = arg->m;
int n = arg->n;
int k = arg->k;
double *A21 = arg->A21;
double *A21T = arg->A21T;
double *A22 = arg->A22;
int ldA = arg->ldA;
// Compute A22 := A22 - A21 * A21T'.
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans,
m, n, k,
-1.0, A21, ldA,
A21T, ldA,
1.0, A22, ldA);
}
| {
"alphanum_fraction": 0.481216458,
"avg_line_length": 22.36,
"ext": "c",
"hexsha": "ebf16ec6f9e4e54d35a5ecccc2d2b8ea3a114213",
"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-gemm-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-gemm-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-gemm-seq.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 192,
"size": 559
} |
/*--------------------------------------------------------------------
* $Id$
*
* This file is part of libRadtran.
* Copyright (c) 1997-2012 by Arve Kylling, Bernhard Mayer,
* Claudia Emde, Robert Buras
*
* ######### Contact info: http://www.libradtran.org #########
*
* 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 <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include "errors.h"
#include "uvspecrandom.h"
#if HAVE_LIBGSL
#include <gsl/gsl_rng.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_randist.h>
#endif
/* global variable: random number generator */
#if HAVE_LIBGSL
gsl_rng* uvspecrng;
#endif
/*****************************************************************/
/* uvspec random number generator; either the highly-recommended */
/* MT19937 if GSL is available, or random() otherwise. */
/*****************************************************************/
double uvspec_random() {
#if HAVE_LIBGSL
return gsl_rng_uniform (uvspecrng);
#else
return (double)random();
#endif
}
double uvspec_random_gauss (double sigma) {
#if HAVE_LIBGSL
return gsl_ran_gaussian (uvspecrng, sigma);
#else
return (double)random();
#endif
}
int init_uvspec_random (int* randomseed, int need_mt19937, int quiet) {
int rseed = 0;
/* global variable, defined in uvspec_lex.l */
#if HAVE_LIBGSL
/* extern gsl_rng *uvspecrng; */ /* global random number generator */
const gsl_rng_type* T;
#endif
/* always initialize standard rng */
srandom (rseed);
if (*randomseed > 0)
rseed = *randomseed;
else
rseed = (int)time (NULL) + (int)getpid();
#if HAVE_LIBGSL
T = gsl_rng_mt19937;
gsl_rng_default_seed = rseed;
uvspecrng = gsl_rng_alloc (T);
if (!quiet && need_mt19937)
fprintf (stderr, " ... using %s random number generator\n", gsl_rng_name (uvspecrng));
#else
if (need_mt19937) {
fprintf (stderr, "Error, GSL not found. The MT19937 random number generator is\n");
fprintf (stderr, "required for MYSTIC simulations. Please install GSL and recompile!\n");
return -1;
}
#endif
return rseed;
}
/***********************************************************************************/
/* Function: read_and_write_random_status @62_30i@ */
/* Description: */
/* check whether to read/write random status. */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
#if HAVE_LIBGSL
int read_and_write_random_status (char* randomstatusfilename,
int* ili,
int* backward_is,
int* backward_js,
int photoncounter,
int* readrandomstatus) {
FILE* randomstatusfile = NULL;
int status = 0;
/************************************+**************************/
/* starting with the randomseed is nice, but starting with the */
/* actual photon that produced the problem is even nicer... */
/* here we read and write the status of the random number */
/* generator */
/* this only works with the gsl !!! */
/************************************+**************************/
/* read randomstatusfile if asked for */
if (*readrandomstatus && photoncounter == 1) {
if ((randomstatusfile = fopen (randomstatusfilename, "r")) != NULL) {
status = gsl_rng_fread (randomstatusfile, uvspecrng);
if (status)
return err_out ("Error %d returned by gsl_rng_fread()\n", status);
if (!fscanf (randomstatusfile, "%d %d %d", ili, backward_is, backward_js)) {
fprintf (stderr, "Error reading file %s\n", randomstatusfilename);
return -1;
}
(void)fclose (randomstatusfile);
fprintf (stderr, "reading random status for photon...\n");
} else
return err_out ("Error %d, could not open randomstatusfile\n", -1);
}
#ifdef WRITERANDOMSTATUS
/* write status every 10 photons, starting with photon 1 */
if (photoncounter % 10 == 1 && !(*readrandomstatus)) {
if ((randomstatusfile = fopen (randomstatusfilename, "w")) != NULL) {
status = gsl_rng_fwrite (randomstatusfile, uvspecrng);
if (status)
return err_out ("Error %d returned by gsl_rng_fwrite()\n", status);
fprintf (randomstatusfile, "%d %d %d\n", *ili, *backward_is, *backward_js);
(void)fclose (randomstatusfile);
} else
return err_out ("Error %d, could not open randomstatusfile\n", -1);
}
#endif
*readrandomstatus = 0;
return 0;
}
#endif
| {
"alphanum_fraction": 0.5066859997,
"avg_line_length": 37.8475609756,
"ext": "c",
"hexsha": "ab951c81fff492ef2529bd47be4554eda19d2ab9",
"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": "0182f991db6a13e0cacb3bf9f43809e6850593e4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "AmberCrafter/docker-compose_libRadtran",
"max_forks_repo_path": "ubuntu20/projects/libRadtran-2.0.4/libsrc_c/uvspecrandom.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4",
"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": "AmberCrafter/docker-compose_libRadtran",
"max_issues_repo_path": "ubuntu20/projects/libRadtran-2.0.4/libsrc_c/uvspecrandom.c",
"max_line_length": 93,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "AmberCrafter/docker-compose_libRadtran",
"max_stars_repo_path": "ubuntu20/projects/libRadtran-2.0.4/libsrc_c/uvspecrandom.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1298,
"size": 6207
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sort.h>
#include "cosmocalc.h"
static double deltaTm[9] = {200.0, 300.0, 400.0, 600.0, 800.0, 1200.0, 1600.0, 2400.0, 3200.0};
static double ATm[9] = {0.186, 0.2, 0.212, 0.218, 0.248, 0.255, 0.260, 0.260, 0.260};
static double aTm[9] = {1.47, 1.52, 1.56, 1.61, 1.87, 2.13, 2.30, 2.53, 2.66};
static double bTm[9] = {2.57, 2.25, 2.05, 1.87, 1.59, 1.51, 1.46, 1.44, 1.41};
static double cTm[9] = {1.19, 1.27, 1.34, 1.45, 1.58, 1.80, 1.97, 2.24, 2.44};
double mass_function(double m, double a)
{
return tinker2008_mass_function(m,a,cosmoData.delta);
}
double tinker2008_mass_function(double m, double a, double delta)
{
double A,am,b,c,alpha;
static int init = 1;
static gsl_spline *ATm_spline,*aTm_spline,*bTm_spline,*cTm_spline;
static gsl_interp_accel *ATm_acc,*aTm_acc,*bTm_acc,*cTm_acc;
if(init)
{
#define TINKERCODEPARMS
#ifdef TINKERCODEPARMS
//first parameter
ATm[0] = 1.858659e-01 ;
ATm[1] = 1.995973e-01 ;
ATm[2] = 2.115659e-01 ;
ATm[3] = 2.184113e-01 ;
ATm[4] = 2.480968e-01 ;
ATm[5] = 2.546053e-01 ;
ATm[6] = 2.600000e-01 ;
ATm[7] = 2.600000e-01 ;
ATm[8] = 2.600000e-01 ;
//second parameter
aTm[0] = 1.466904e+00 ;
aTm[1] = 1.521782e+00 ;
aTm[2] = 1.559186e+00 ;
aTm[3] = 1.614585e+00 ;
aTm[4] = 1.869936e+00 ;
aTm[5] = 2.128056e+00 ;
aTm[6] = 2.301275e+00 ;
aTm[7] = 2.529241e+00 ;
aTm[8] = 2.661983e+00 ;
//third parameter
bTm[0] = 2.571104e+00 ;
bTm[1] = 2.254217e+00 ;
bTm[2] = 2.048674e+00 ;
bTm[3] = 1.869559e+00 ;
bTm[4] = 1.588649e+00 ;
bTm[5] = 1.507134e+00 ;
bTm[6] = 1.464374e+00 ;
bTm[7] = 1.436827e+00 ;
bTm[8] = 1.405210e+00 ;
//fourth parameter
cTm[0] = 1.193958e+00;
cTm[1] = 1.270316e+00;
cTm[2] = 1.335191e+00;
cTm[3] = 1.446266e+00;
cTm[4] = 1.581345e+00;
cTm[5] = 1.795050e+00;
cTm[6] = 1.965613e+00;
cTm[7] = 2.237466e+00;
cTm[8] = 2.439729e+00;
#endif
ATm_spline = gsl_spline_alloc(gsl_interp_cspline,9);
aTm_spline = gsl_spline_alloc(gsl_interp_cspline,9);
bTm_spline = gsl_spline_alloc(gsl_interp_cspline,9);
cTm_spline = gsl_spline_alloc(gsl_interp_cspline,9);
gsl_spline_init(ATm_spline,deltaTm,ATm,9);
gsl_spline_init(aTm_spline,deltaTm,aTm,9);
gsl_spline_init(bTm_spline,deltaTm,bTm,9);
gsl_spline_init(cTm_spline,deltaTm,cTm,9);
ATm_acc = gsl_interp_accel_alloc();
aTm_acc = gsl_interp_accel_alloc();
bTm_acc = gsl_interp_accel_alloc();
cTm_acc = gsl_interp_accel_alloc();
init = 0;
}
A = gsl_spline_eval(ATm_spline,delta,ATm_acc);
#ifdef TINKERCODEPARMS
if(delta > 1600.0)
A = 0.26;
#endif
am = gsl_spline_eval(aTm_spline,delta,aTm_acc);
b = gsl_spline_eval(bTm_spline,delta,bTm_acc);
c = gsl_spline_eval(cTm_spline,delta,cTm_acc);
double onepz = 1.0/a;
#ifdef TINKERCODEPARMS
if(onepz > 4.0)
onepz = 4.0;
#endif
A *= pow(onepz,-0.14);
am *= pow(onepz,-0.06);
alpha = pow(10.0,-1.0*pow(0.75/log10(delta/75.0),1.2));
b *= pow(onepz,-1.0*alpha);
//fprintf(stderr,"A = %f, a = %f, b = %f, c = %f\n",A,am,b,c);
double sigma = sigmaMtophat(m,a);
double fsigma = A*(pow(sigma/b,-1.0*am) + 1.0)*exp(-1.0*c/sigma/sigma);
double dm = 1e-6*m;
double dlnsiginvdm = log(sigmaMtophat(m-dm/2.0,a)/sigmaMtophat(m+dm/2.0,a))/dm;
return fsigma*RHO_CRIT*cosmoData.OmegaM/m*dlnsiginvdm;
}
static double alphaTm[9] = {0.368, 0.363, 0.385, 0.389, 0.393, 0.365, 0.379, 0.355, 0.327};
static double betaTm[9] = {0.589, 0.585, 0.544, 0.543, 0.564, 0.623, 0.637, 0.673, 0.702};
static double gammaTm[9] = {0.864, 0.922, 0.987, 1.09, 1.20, 1.34, 1.50, 1.68, 1.81};
static double phiTm[9] = {-0.729, -0.789, -0.910, -1.05, -1.20, -1.26, -1.45, -1.50, -1.49};
static double etaTm[9] = {-0.243, -0.261, -0.261, -0.273, -0.278, -0.301, -0.301, -0.319, -0.336};
static double tinker2010_mf_norm_integ(double lnnu, void *p)
{
double *params = (double*) p;
double nu = exp(lnnu);
double fnu,bnu;
double y = log10(params[4]);
double A = 1.0 + 0.24*y*exp(-1.0*pow(4.0/y,4.0));
double _a = 0.44*y - 0.88;
double B = 0.183;
double b = 1.5;
double C = 0.019 + 0.107*y + 0.19*exp(-1.0*pow(4.0/y,4.0));
double c = 2.4;
if(nu == 0.0)
return 0.0;
else
{
fnu = (1.0 + pow(params[0]*nu,-2.0*params[1]))*pow(nu,2.0*params[2])*exp(-1.0*params[3]*nu*nu/2.0);
bnu = 1.0 - A*pow(nu,_a)/(pow(nu,_a) + pow(1.686,_a)) + B*pow(nu,b) + C*pow(nu,c);
return bnu*fnu*nu;
}
}
double tinker2010_mass_function(double m, double a, double delta)
{
double z,gsigma,nu,dlnsiginvdm;
double dm = 1e-6*m;
double alpha,beta,gamma,phi,eta;
static int init = 1;
static gsl_spline *alphaTm_spline,*betaTm_spline,*gammaTm_spline,*phiTm_spline,*etaTm_spline;
static gsl_interp_accel *alphaTm_acc,*betaTm_acc,*gammaTm_acc,*phiTm_acc,*etaTm_acc;
//static gsl_integration_glfixed_table *gltab;
static gsl_integration_workspace *w;
static double aprev = -1.0;
static double alphaprev = -1.0;
gsl_function f;
size_t limit = 1000;
double epsabs,epsrel;
double abserr;
double numin,numax;
//int i,Nnu,dnu;
double params[5];
if(init)
{
alphaTm_spline = gsl_spline_alloc(gsl_interp_cspline,9);
betaTm_spline = gsl_spline_alloc(gsl_interp_cspline,9);
gammaTm_spline = gsl_spline_alloc(gsl_interp_cspline,9);
phiTm_spline = gsl_spline_alloc(gsl_interp_cspline,9);
etaTm_spline = gsl_spline_alloc(gsl_interp_cspline,9);
gsl_spline_init(alphaTm_spline,deltaTm,alphaTm,9);
gsl_spline_init(betaTm_spline,deltaTm,betaTm,9);
gsl_spline_init(gammaTm_spline,deltaTm,gammaTm,9);
gsl_spline_init(phiTm_spline,deltaTm,phiTm,9);
gsl_spline_init(etaTm_spline,deltaTm,etaTm,9);
alphaTm_acc = gsl_interp_accel_alloc();
betaTm_acc = gsl_interp_accel_alloc();
gammaTm_acc = gsl_interp_accel_alloc();
phiTm_acc = gsl_interp_accel_alloc();
etaTm_acc = gsl_interp_accel_alloc();
//gltab = gsl_integration_glfixed_table_alloc((size_t) 500);
w = gsl_integration_workspace_alloc(limit);
init = 0;
}
alpha = gsl_spline_eval(alphaTm_spline,delta,alphaTm_acc);
beta = gsl_spline_eval(betaTm_spline,delta,betaTm_acc);
gamma = gsl_spline_eval(gammaTm_spline,delta,gammaTm_acc);
phi = gsl_spline_eval(phiTm_spline,delta,phiTm_acc);
eta = gsl_spline_eval(etaTm_spline,delta,etaTm_acc);
nu = 1.686/sigmaMtophat(m,a);
z = 1.0/a - 1.0;
if(z > 3.0)
z = 3.0;
beta = beta*pow(1.0+z,0.20);
phi = phi*pow(1.0+z,-0.08);
eta = eta*pow(1.0+z,0.27);
gamma = gamma*pow(1.0+z,-0.01);
//determine alpha by normalization condition
if(a != aprev)
{
aprev = a;
params[0] = beta;
params[1] = phi;
params[2] = eta;
params[3] = gamma;
params[4] = delta;
f.function = &tinker2010_mf_norm_integ;
f.params = params;
numin = 1e-10;
numax = 1e10;
epsabs = 1e-6;
epsrel = 1e-6;
gsl_integration_qag(&f,log(numin),log(numax),epsabs,epsrel,limit,GSL_INTEG_GAUSS61,w,&alphaprev,&abserr);
//alphaprev = gsl_integration_glfixed(&f,log(numin),log(numax),gltab);
/*
alphaprev = 0.0;
Nnu = 100;
dnu = log(numax/numin)/Nnu;
for(i=0;i<Nnu;++i)
alphaprev += tinker2010_mf_norm_integ(log(numin)+dnu*i,f.params)*dnu;
*/
//fprintf(stderr,"alpha = %g, norm = %g, alpha_norm = %g\n",alpha,alphaprev,1.0/alphaprev);
alphaprev = 1.0/alphaprev;
}
alpha = alphaprev;
gsigma = alpha*(1.0 + pow(beta*nu,-2.0*phi))*pow(nu,2.0*eta)*exp(-1.0*gamma*nu*nu/2.0)*nu;
dlnsiginvdm = log(sigmaMtophat(m-dm/2.0,a)/sigmaMtophat(m+dm/2.0,a))/dm;
return gsigma*RHO_CRIT*cosmoData.OmegaM/m*dlnsiginvdm;
}
double bias_function(double m, double a)
{
return tinker2010_bias(m,a,cosmoData.delta);
}
double tinker2010_bias(double m, double a, double delta)
{
double nu;
nu = 1.686/sigmaMtophat(m,a);
double y = log10(delta);
double A = 1.0 + 0.24*y*exp(-1.0*pow(4.0/y,4.0));
double _a = 0.44*y - 0.88;
double B = 0.183;
double b = 1.5;
double C = 0.019 + 0.107*y + 0.19*exp(-1.0*pow(4.0/y,4.0));
double c = 2.4;
return 1.0 - A*pow(nu,_a)/(pow(nu,_a) + pow(1.686,_a)) + B*pow(nu,b) + C*pow(nu,c);
}
| {
"alphanum_fraction": 0.6192387067,
"avg_line_length": 30.7112676056,
"ext": "c",
"hexsha": "93a9af61569d70436e7915fd0c4658f88da648f4",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z",
"max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "beckermr/cosmocalc",
"max_forks_repo_path": "src/mass_bias_functions.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "beckermr/cosmocalc",
"max_issues_repo_path": "src/mass_bias_functions.c",
"max_line_length": 111,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "beckermr/cosmocalc",
"max_stars_repo_path": "src/mass_bias_functions.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3659,
"size": 8722
} |
#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_tpmv (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 2;
float A[] = { -0.587f, 0.14f, 0.841f };
float X[] = { -0.213f, 0.885f };
int incX = -1;
float x_expected[] = { -0.179133f, -0.549315f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 974)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 2;
float A[] = { -0.587f, 0.14f, 0.841f };
float X[] = { -0.213f, 0.885f };
int incX = -1;
float x_expected[] = { -0.213f, 0.85518f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 975)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 2;
float A[] = { -0.587f, 0.14f, 0.841f };
float X[] = { -0.213f, 0.885f };
int incX = -1;
float x_expected[] = { -0.055233f, -0.519495f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 976)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 2;
float A[] = { -0.587f, 0.14f, 0.841f };
float X[] = { -0.213f, 0.885f };
int incX = -1;
float x_expected[] = { -0.0891f, 0.885f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 977)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 2;
float A[] = { -0.587f, 0.14f, 0.841f };
float X[] = { -0.213f, 0.885f };
int incX = -1;
float x_expected[] = { -0.179133f, -0.549315f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 978)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 2;
float A[] = { -0.587f, 0.14f, 0.841f };
float X[] = { -0.213f, 0.885f };
int incX = -1;
float x_expected[] = { -0.213f, 0.85518f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 979)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 2;
float A[] = { -0.587f, 0.14f, 0.841f };
float X[] = { -0.213f, 0.885f };
int incX = -1;
float x_expected[] = { -0.055233f, -0.519495f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 980)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 2;
float A[] = { -0.587f, 0.14f, 0.841f };
float X[] = { -0.213f, 0.885f };
int incX = -1;
float x_expected[] = { -0.0891f, 0.885f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 981)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 2;
float A[] = { -0.765f, 0.968f, -0.956f };
float X[] = { 0.243f, -0.274f };
int incX = -1;
float x_expected[] = { -0.49754f, 0.20961f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 982)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 2;
float A[] = { -0.765f, 0.968f, -0.956f };
float X[] = { 0.243f, -0.274f };
int incX = -1;
float x_expected[] = { -0.022232f, -0.274f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 983)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 2;
float A[] = { -0.765f, 0.968f, -0.956f };
float X[] = { 0.243f, -0.274f };
int incX = -1;
float x_expected[] = { -0.232308f, 0.444834f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 984)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 2;
float A[] = { -0.765f, 0.968f, -0.956f };
float X[] = { 0.243f, -0.274f };
int incX = -1;
float x_expected[] = { 0.243f, -0.038776f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 985)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 2;
float A[] = { -0.765f, 0.968f, -0.956f };
float X[] = { 0.243f, -0.274f };
int incX = -1;
float x_expected[] = { -0.49754f, 0.20961f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 986)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 2;
float A[] = { -0.765f, 0.968f, -0.956f };
float X[] = { 0.243f, -0.274f };
int incX = -1;
float x_expected[] = { -0.022232f, -0.274f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 987)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 2;
float A[] = { -0.765f, 0.968f, -0.956f };
float X[] = { 0.243f, -0.274f };
int incX = -1;
float x_expected[] = { -0.232308f, 0.444834f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 988)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 2;
float A[] = { -0.765f, 0.968f, -0.956f };
float X[] = { 0.243f, -0.274f };
int incX = -1;
float x_expected[] = { 0.243f, -0.038776f };
cblas_stpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "stpmv(case 989)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 2;
double A[] = { 0.393, -0.221, 0.356 };
double X[] = { -0.062, -0.221 };
int incX = -1;
double x_expected[] = { -0.022072, -0.073151 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 990)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 2;
double A[] = { 0.393, -0.221, 0.356 };
double X[] = { -0.062, -0.221 };
int incX = -1;
double x_expected[] = { -0.062, -0.207298 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 991)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 2;
double A[] = { 0.393, -0.221, 0.356 };
double X[] = { -0.062, -0.221 };
int incX = -1;
double x_expected[] = { 0.026769, -0.086853 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 992)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 2;
double A[] = { 0.393, -0.221, 0.356 };
double X[] = { -0.062, -0.221 };
int incX = -1;
double x_expected[] = { -0.013159, -0.221 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 993)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 2;
double A[] = { 0.393, -0.221, 0.356 };
double X[] = { -0.062, -0.221 };
int incX = -1;
double x_expected[] = { -0.022072, -0.073151 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 994)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 2;
double A[] = { 0.393, -0.221, 0.356 };
double X[] = { -0.062, -0.221 };
int incX = -1;
double x_expected[] = { -0.062, -0.207298 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 995)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 2;
double A[] = { 0.393, -0.221, 0.356 };
double X[] = { -0.062, -0.221 };
int incX = -1;
double x_expected[] = { 0.026769, -0.086853 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 996)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 2;
double A[] = { 0.393, -0.221, 0.356 };
double X[] = { -0.062, -0.221 };
int incX = -1;
double x_expected[] = { -0.013159, -0.221 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 997)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 2;
double A[] = { 0.694, 0.501, 0.019 };
double X[] = { -0.928, 0.365 };
int incX = -1;
double x_expected[] = { 0.165233, 0.25331 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 998)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 2;
double A[] = { 0.694, 0.501, 0.019 };
double X[] = { -0.928, 0.365 };
int incX = -1;
double x_expected[] = { -0.745135, 0.365 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 999)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 2;
double A[] = { 0.694, 0.501, 0.019 };
double X[] = { -0.928, 0.365 };
int incX = -1;
double x_expected[] = { -0.017632, -0.211618 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 1000)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 2;
double A[] = { 0.694, 0.501, 0.019 };
double X[] = { -0.928, 0.365 };
int incX = -1;
double x_expected[] = { -0.928, -0.099928 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 1001)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 2;
double A[] = { 0.694, 0.501, 0.019 };
double X[] = { -0.928, 0.365 };
int incX = -1;
double x_expected[] = { 0.165233, 0.25331 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 1002)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 2;
double A[] = { 0.694, 0.501, 0.019 };
double X[] = { -0.928, 0.365 };
int incX = -1;
double x_expected[] = { -0.745135, 0.365 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 1003)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 2;
double A[] = { 0.694, 0.501, 0.019 };
double X[] = { -0.928, 0.365 };
int incX = -1;
double x_expected[] = { -0.017632, -0.211618 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 1004)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 2;
double A[] = { 0.694, 0.501, 0.019 };
double X[] = { -0.928, 0.365 };
int incX = -1;
double x_expected[] = { -0.928, -0.099928 };
cblas_dtpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtpmv(case 1005)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 2;
float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };
float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };
int incX = -1;
float x_expected[] = { 0.880215f, -0.602509f, -0.225207f, -0.564235f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1006) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1006) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 2;
float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };
float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };
int incX = -1;
float x_expected[] = { 0.904f, 0.461f, -0.58925f, -0.778204f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1007) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1007) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 2;
float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };
float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };
int incX = -1;
float x_expected[] = { 1.21467f, -0.432639f, -0.002957f, 0.366969f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1008) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1008) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 2;
float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };
float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };
int incX = -1;
float x_expected[] = { 1.23846f, 0.63087f, -0.367f, 0.153f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1009) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1009) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 2;
float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };
float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };
int incX = -1;
float x_expected[] = { 0.880215f, -0.602509f, -0.225207f, -0.564235f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1010) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1010) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 2;
float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };
float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };
int incX = -1;
float x_expected[] = { 0.904f, 0.461f, -0.58925f, -0.778204f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1011) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1011) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 2;
float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };
float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };
int incX = -1;
float x_expected[] = { 1.21467f, -0.432639f, -0.002957f, 0.366969f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1012) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1012) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 2;
float A[] = { 0.362f, -0.849f, -0.612f, -0.718f, 0.503f, -0.923f };
float X[] = { 0.904f, 0.461f, -0.367f, 0.153f };
int incX = -1;
float x_expected[] = { 1.23846f, 0.63087f, -0.367f, 0.153f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1013) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1013) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 2;
float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };
float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };
int incX = -1;
float x_expected[] = { -0.281591f, -0.161308f, -0.9103f, 0.34578f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1014) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1014) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 2;
float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };
float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };
int incX = -1;
float x_expected[] = { -0.05924f, -0.5178f, 0.444f, -0.748f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1015) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1015) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 2;
float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };
float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };
int incX = -1;
float x_expected[] = { 0.115649f, -0.450508f, -1.26568f, 0.689239f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1016) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1016) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 2;
float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };
float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };
int incX = -1;
float x_expected[] = { 0.338f, -0.807f, 0.088617f, -0.404541f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1017) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1017) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 2;
float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };
float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };
int incX = -1;
float x_expected[] = { -0.281591f, -0.161308f, -0.9103f, 0.34578f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1018) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1018) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 2;
float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };
float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };
int incX = -1;
float x_expected[] = { -0.05924f, -0.5178f, 0.444f, -0.748f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1019) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1019) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 2;
float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };
float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };
int incX = -1;
float x_expected[] = { 0.115649f, -0.450508f, -1.26568f, 0.689239f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1020) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1020) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 2;
float A[] = { -0.876f, -0.697f, -0.519f, -0.223f, 0.526f, -0.077f };
float X[] = { 0.338f, -0.807f, 0.444f, -0.748f };
int incX = -1;
float x_expected[] = { 0.338f, -0.807f, 0.088617f, -0.404541f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1021) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1021) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 121;
int diag = 131;
int N = 2;
float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };
float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };
int incX = -1;
float x_expected[] = { -0.295592f, 1.11591f, 0.610498f, -0.779458f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1022) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1022) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 121;
int diag = 132;
int N = 2;
float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };
float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };
int incX = -1;
float x_expected[] = { -0.646798f, 0.455824f, 0.602f, -0.96f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1023) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1023) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 122;
int diag = 131;
int N = 2;
float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };
float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };
int incX = -1;
float x_expected[] = { 0.229206f, 0.296082f, 0.712384f, -0.465806f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1024) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1024) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 122;
int diag = 132;
int N = 2;
float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };
float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };
int incX = -1;
float x_expected[] = { -0.122f, -0.364f, 0.703886f, -0.646348f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1025) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1025) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 121;
int diag = 131;
int N = 2;
float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };
float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };
int incX = -1;
float x_expected[] = { -0.295592f, 1.11591f, 0.610498f, -0.779458f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1026) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1026) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 121;
int diag = 132;
int N = 2;
float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };
float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };
int incX = -1;
float x_expected[] = { -0.646798f, 0.455824f, 0.602f, -0.96f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1027) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1027) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 122;
int diag = 131;
int N = 2;
float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };
float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };
int incX = -1;
float x_expected[] = { 0.229206f, 0.296082f, 0.712384f, -0.465806f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1028) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1028) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 122;
int diag = 132;
int N = 2;
float A[] = { 0.869f, -0.091f, -0.859f, 0.008f, -0.921f, -0.321f };
float X[] = { -0.122f, -0.364f, 0.602f, -0.96f };
int incX = -1;
float x_expected[] = { -0.122f, -0.364f, 0.703886f, -0.646348f };
cblas_ctpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctpmv(case 1029) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctpmv(case 1029) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 2;
double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };
double X[] = { -0.042, -0.705, -0.255, -0.854 };
int incX = -1;
double x_expected[] = { -0.466116, 0.156534, -0.248261, -0.067936 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1030) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1030) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 2;
double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };
double X[] = { -0.042, -0.705, -0.255, -0.854 };
int incX = -1;
double x_expected[] = { -0.042, -0.705, -0.663093, -0.637955 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1031) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1031) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 2;
double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };
double X[] = { -0.042, -0.705, -0.255, -0.854 };
int incX = -1;
double x_expected[] = { -0.905141, 0.539693, 0.159832, -0.283981 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1032) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1032) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 2;
double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };
double X[] = { -0.042, -0.705, -0.255, -0.854 };
int incX = -1;
double x_expected[] = { -0.481025, -0.321841, -0.255, -0.854 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1033) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1033) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 2;
double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };
double X[] = { -0.042, -0.705, -0.255, -0.854 };
int incX = -1;
double x_expected[] = { -0.466116, 0.156534, -0.248261, -0.067936 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1034) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1034) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 2;
double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };
double X[] = { -0.042, -0.705, -0.255, -0.854 };
int incX = -1;
double x_expected[] = { -0.042, -0.705, -0.663093, -0.637955 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1035) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1035) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 2;
double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };
double X[] = { -0.042, -0.705, -0.255, -0.854 };
int incX = -1;
double x_expected[] = { -0.905141, 0.539693, 0.159832, -0.283981 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1036) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1036) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 2;
double A[] = { 0.254, 0.263, -0.271, -0.595, -0.182, -0.672 };
double X[] = { -0.042, -0.705, -0.255, -0.854 };
int incX = -1;
double x_expected[] = { -0.481025, -0.321841, -0.255, -0.854 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1037) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1037) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 2;
double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };
double X[] = { -0.008, 0.904, -0.689, -0.679 };
int incX = -1;
double x_expected[] = { 0.590302, 1.473768, -0.566422, -0.005436 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1038) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1038) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 2;
double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };
double X[] = { -0.008, 0.904, -0.689, -0.679 };
int incX = -1;
double x_expected[] = { 0.139182, 1.574648, -0.689, -0.679 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1039) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1039) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 2;
double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };
double X[] = { -0.008, 0.904, -0.689, -0.679 };
int incX = -1;
double x_expected[] = { 0.44312, 0.80312, -0.211814, -0.54022 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1040) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1040) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 2;
double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };
double X[] = { -0.008, 0.904, -0.689, -0.679 };
int incX = -1;
double x_expected[] = { -0.008, 0.904, -0.334392, -1.213784 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1041) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1041) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 2;
double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };
double X[] = { -0.008, 0.904, -0.689, -0.679 };
int incX = -1;
double x_expected[] = { 0.590302, 1.473768, -0.566422, -0.005436 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1042) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1042) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 2;
double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };
double X[] = { -0.008, 0.904, -0.689, -0.679 };
int incX = -1;
double x_expected[] = { 0.139182, 1.574648, -0.689, -0.679 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1043) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1043) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 2;
double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };
double X[] = { -0.008, 0.904, -0.689, -0.679 };
int incX = -1;
double x_expected[] = { 0.44312, 0.80312, -0.211814, -0.54022 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1044) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1044) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 2;
double A[] = { 0.421, -0.407, -0.595, -0.387, 0.884, -0.498 };
double X[] = { -0.008, 0.904, -0.689, -0.679 };
int incX = -1;
double x_expected[] = { -0.008, 0.904, -0.334392, -1.213784 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1045) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1045) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 121;
int diag = 131;
int N = 2;
double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };
double X[] = { -0.641, 0.565, -0.406, -0.948 };
int incX = -1;
double x_expected[] = { -1.449087, -1.068251, 0.375602, 0.672696 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1046) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1046) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 121;
int diag = 132;
int N = 2;
double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };
double X[] = { -0.641, 0.565, -0.406, -0.948 };
int incX = -1;
double x_expected[] = { -1.43236, 0.04007, -0.406, -0.948 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1047) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1047) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 122;
int diag = 131;
int N = 2;
double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };
double X[] = { -0.641, 0.565, -0.406, -0.948 };
int incX = -1;
double x_expected[] = { -0.657727, -0.543321, 0.167357, 1.431451 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1048) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1048) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 122;
int diag = 132;
int N = 2;
double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };
double X[] = { -0.641, 0.565, -0.406, -0.948 };
int incX = -1;
double x_expected[] = { -0.641, 0.565, -0.614245, -0.189245 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1049) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1049) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 121;
int diag = 131;
int N = 2;
double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };
double X[] = { -0.641, 0.565, -0.406, -0.948 };
int incX = -1;
double x_expected[] = { -1.449087, -1.068251, 0.375602, 0.672696 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1050) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1050) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 121;
int diag = 132;
int N = 2;
double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };
double X[] = { -0.641, 0.565, -0.406, -0.948 };
int incX = -1;
double x_expected[] = { -1.43236, 0.04007, -0.406, -0.948 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1051) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1051) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 122;
int diag = 131;
int N = 2;
double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };
double X[] = { -0.641, 0.565, -0.406, -0.948 };
int incX = -1;
double x_expected[] = { -0.657727, -0.543321, 0.167357, 1.431451 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1052) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1052) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 122;
int diag = 132;
int N = 2;
double A[] = { -0.743, -0.078, 0.77, 0.505, 0.157, -0.986 };
double X[] = { -0.641, 0.565, -0.406, -0.948 };
int incX = -1;
double x_expected[] = { -0.641, 0.565, -0.614245, -0.189245 };
cblas_ztpmv(order, uplo, trans, diag, N, A, X, incX);
{
int i;
for (i = 0; i < 2; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztpmv(case 1053) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztpmv(case 1053) imag");
};
};
};
}
| {
"alphanum_fraction": 0.5048550537,
"avg_line_length": 25.6222891566,
"ext": "c",
"hexsha": "43a4926951ee2cc7a406f6c76563f4e1b7cf8638",
"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_tpmv.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_tpmv.c",
"max_line_length": 82,
"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_tpmv.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": 18369,
"size": 42533
} |
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/*
* =====================================================================================
*
* Filename: Reg_s0.c
*
* Description:
*
* Version: 1.0
* Created: 15/03/2014 21:10:30
* Revision: none
* Compiler: gcc
*
* Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it
* Organization:
*
* =====================================================================================
*/
#include <gsl/gsl_integration.h>
#include "funcs.h"
/*
We split the interval of integration (0,+inf) into three parts:
1) (0, O/2)
and we use the diffeomorphism k -> 1/k to cope with the singularity
in k = 0 ;
2) (O/2, 3*O/2)
and we calculate the Cauchy principal value around k = O ;
3) (3*O/2, +inf)
*/
/*
* === FUNCTION ======================================================================
* Name: fu_inv
* Description: To integrate on the 1) interval we make the change of variable
* k -> 1/k
* =====================================================================================
*/
double fu_inv ( double k, void* params )
{
struct f_params* pars = (struct f_params*) params ;
double o_c, b, O, o_1, alpha ;
assign_p ( pars, &o_c, &b, &O, &o_1 ) ;
alpha = pars->alpha ;
double temp = alpha*O*exp(-1/(k*o_c))/(1-(O*O*k*k)) ;
double val = temp/(k*tanh(b/(k*2))) ;
return val ;
}
/*
* === FUNCTION ======================================================================
* Name: fu_coth
* Description: The function to be integrated around the singularity O, by calculating
* the Cauchy principal value. We use qawc and therefore we multiply by
* (k-O).
* =====================================================================================
*/
double fu_cau ( double k, void* params )
{
struct f_params* pars = (struct f_params*) params ;
double o_c, b, O, o_1, alpha ;
assign_p ( pars, &o_c, &b, &O, &o_1 ) ;
alpha = pars->alpha ;
double temp = alpha*O*k*exp(-k/o_c)/(k+O) ;
double val = temp/tanh(b*k/2) ;
return val ;
}
/*
* === FUNCTION ======================================================================
* Name: fu_coth
* Description: Function to be integrated on the tail (3*O/2 , +inf)
* =====================================================================================
*/
double fu_coth ( double k, void* params )
{
struct f_params* pars = (struct f_params*) params ;
double o_c, b, O, o_1, alpha ;
assign_p ( pars, &o_c, &b, &O, &o_1 ) ;
alpha = pars->alpha ;
double temp = alpha*O*k*exp(-k/o_c)/(k*k-O*O) ;
double val = temp/tanh(b*k/2) ;
return val ;
}
/*
* === FUNCTION ======================================================================
* Name: re_gs0
* Description: Re g_s0
* =====================================================================================
*/
int re_gs0 ( void* params, double* val, double* error )
{
struct f_params* pars = (struct f_params*) params ;
double O ;
O = pars->Omega ;
double r, err ;
double r1, r2, r3, err1, err2, err3 ;
gsl_function f, F, G ;
f.function = &fu_coth ; F.function = &fu_cau ; G.function = &fu_inv ;
f.params = pars ; F.params = pars ; G.params = pars ;
gsl_integration_workspace *fu_fin_ws =
gsl_integration_workspace_alloc (WS_SZ) ;
gsl_integration_workspace *fu_inv_ws =
gsl_integration_workspace_alloc (WS_SZ) ;
gsl_integration_workspace *fu_inf_ws =
gsl_integration_workspace_alloc (WS_SZ) ;
int status1 ;
status1 = gsl_integration_qagiu ( &G, 2/O, 1e-9, .001, WS_SZ,
fu_inv_ws, &r1, &err1 ) ;
int status2 ;
status2 = gsl_integration_qawc ( &F, O/2, 3*O/2, O, 1e-9, .001, WS_SZ,
fu_fin_ws, &r2, &err2 ) ;
int status3 ;
status3 = gsl_integration_qagiu ( &f, 3*O/2, 1e-9, .001, WS_SZ,
fu_inf_ws, &r3, &err3 ) ;
r = r1 + r2 + r3 ; err = err1 + err2 + err3 ;
*val = r ; *error = err ;
gsl_integration_workspace_free(fu_fin_ws) ;
gsl_integration_workspace_free(fu_inv_ws) ;
gsl_integration_workspace_free(fu_inf_ws) ;
int status = status1 + status2 + status3 ;
return status ;
}
| {
"alphanum_fraction": 0.5639870224,
"avg_line_length": 31.7028571429,
"ext": "c",
"hexsha": "874dea6a2f160d2da06e77683bf7d51a17f7a33e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "j-silver/quantum_dots",
"max_forks_repo_path": "Reg_s0.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "j-silver/quantum_dots",
"max_issues_repo_path": "Reg_s0.c",
"max_line_length": 88,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "j-silver/quantum_dots",
"max_stars_repo_path": "Reg_s0.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1429,
"size": 5548
} |
/* rng/gsl_rng.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2007 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_RNG_H__
#define __GSL_RNG_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
const char *name;
unsigned long int max;
unsigned long int min;
size_t size;
void (*set) (void *state, unsigned long int seed);
unsigned long int (*get) (void *state);
double (*get_double) (void *state);
}
gsl_rng_type;
typedef struct
{
const gsl_rng_type * type;
void *state;
}
gsl_rng;
/* These structs also need to appear in default.c so you can select
them via the environment variable GSL_RNG_TYPE */
GSL_VAR const gsl_rng_type *gsl_rng_borosh13;
GSL_VAR const gsl_rng_type *gsl_rng_coveyou;
GSL_VAR const gsl_rng_type *gsl_rng_cmrg;
GSL_VAR const gsl_rng_type *gsl_rng_fishman18;
GSL_VAR const gsl_rng_type *gsl_rng_fishman20;
GSL_VAR const gsl_rng_type *gsl_rng_fishman2x;
GSL_VAR const gsl_rng_type *gsl_rng_gfsr4;
GSL_VAR const gsl_rng_type *gsl_rng_knuthran;
GSL_VAR const gsl_rng_type *gsl_rng_knuthran2;
GSL_VAR const gsl_rng_type *gsl_rng_knuthran2002;
GSL_VAR const gsl_rng_type *gsl_rng_lecuyer21;
GSL_VAR const gsl_rng_type *gsl_rng_minstd;
GSL_VAR const gsl_rng_type *gsl_rng_mrg;
GSL_VAR const gsl_rng_type *gsl_rng_mt19937;
GSL_VAR const gsl_rng_type *gsl_rng_mt19937_1999;
GSL_VAR const gsl_rng_type *gsl_rng_mt19937_1998;
GSL_VAR const gsl_rng_type *gsl_rng_r250;
GSL_VAR const gsl_rng_type *gsl_rng_ran0;
GSL_VAR const gsl_rng_type *gsl_rng_ran1;
GSL_VAR const gsl_rng_type *gsl_rng_ran2;
GSL_VAR const gsl_rng_type *gsl_rng_ran3;
GSL_VAR const gsl_rng_type *gsl_rng_rand;
GSL_VAR const gsl_rng_type *gsl_rng_rand48;
GSL_VAR const gsl_rng_type *gsl_rng_random128_bsd;
GSL_VAR const gsl_rng_type *gsl_rng_random128_glibc2;
GSL_VAR const gsl_rng_type *gsl_rng_random128_libc5;
GSL_VAR const gsl_rng_type *gsl_rng_random256_bsd;
GSL_VAR const gsl_rng_type *gsl_rng_random256_glibc2;
GSL_VAR const gsl_rng_type *gsl_rng_random256_libc5;
GSL_VAR const gsl_rng_type *gsl_rng_random32_bsd;
GSL_VAR const gsl_rng_type *gsl_rng_random32_glibc2;
GSL_VAR const gsl_rng_type *gsl_rng_random32_libc5;
GSL_VAR const gsl_rng_type *gsl_rng_random64_bsd;
GSL_VAR const gsl_rng_type *gsl_rng_random64_glibc2;
GSL_VAR const gsl_rng_type *gsl_rng_random64_libc5;
GSL_VAR const gsl_rng_type *gsl_rng_random8_bsd;
GSL_VAR const gsl_rng_type *gsl_rng_random8_glibc2;
GSL_VAR const gsl_rng_type *gsl_rng_random8_libc5;
GSL_VAR const gsl_rng_type *gsl_rng_random_bsd;
GSL_VAR const gsl_rng_type *gsl_rng_random_glibc2;
GSL_VAR const gsl_rng_type *gsl_rng_random_libc5;
GSL_VAR const gsl_rng_type *gsl_rng_randu;
GSL_VAR const gsl_rng_type *gsl_rng_ranf;
GSL_VAR const gsl_rng_type *gsl_rng_ranlux;
GSL_VAR const gsl_rng_type *gsl_rng_ranlux389;
GSL_VAR const gsl_rng_type *gsl_rng_ranlxd1;
GSL_VAR const gsl_rng_type *gsl_rng_ranlxd2;
GSL_VAR const gsl_rng_type *gsl_rng_ranlxs0;
GSL_VAR const gsl_rng_type *gsl_rng_ranlxs1;
GSL_VAR const gsl_rng_type *gsl_rng_ranlxs2;
GSL_VAR const gsl_rng_type *gsl_rng_ranmar;
GSL_VAR const gsl_rng_type *gsl_rng_slatec;
GSL_VAR const gsl_rng_type *gsl_rng_taus;
GSL_VAR const gsl_rng_type *gsl_rng_taus2;
GSL_VAR const gsl_rng_type *gsl_rng_taus113;
GSL_VAR const gsl_rng_type *gsl_rng_transputer;
GSL_VAR const gsl_rng_type *gsl_rng_tt800;
GSL_VAR const gsl_rng_type *gsl_rng_uni;
GSL_VAR const gsl_rng_type *gsl_rng_uni32;
GSL_VAR const gsl_rng_type *gsl_rng_vax;
GSL_VAR const gsl_rng_type *gsl_rng_waterman14;
GSL_VAR const gsl_rng_type *gsl_rng_zuf;
const gsl_rng_type ** gsl_rng_types_setup(void);
GSL_VAR const gsl_rng_type *gsl_rng_default;
GSL_VAR unsigned long int gsl_rng_default_seed;
gsl_rng *gsl_rng_alloc (const gsl_rng_type * T);
int gsl_rng_memcpy (gsl_rng * dest, const gsl_rng * src);
gsl_rng *gsl_rng_clone (const gsl_rng * r);
void gsl_rng_free (gsl_rng * r);
void gsl_rng_set (const gsl_rng * r, unsigned long int seed);
unsigned long int gsl_rng_max (const gsl_rng * r);
unsigned long int gsl_rng_min (const gsl_rng * r);
const char *gsl_rng_name (const gsl_rng * r);
int gsl_rng_fread (FILE * stream, gsl_rng * r);
int gsl_rng_fwrite (FILE * stream, const gsl_rng * r);
size_t gsl_rng_size (const gsl_rng * r);
void * gsl_rng_state (const gsl_rng * r);
void gsl_rng_print_state (const gsl_rng * r);
const gsl_rng_type * gsl_rng_env_setup (void);
INLINE_DECL unsigned long int gsl_rng_get (const gsl_rng * r);
INLINE_DECL double gsl_rng_uniform (const gsl_rng * r);
INLINE_DECL double gsl_rng_uniform_pos (const gsl_rng * r);
INLINE_DECL unsigned long int gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n);
#ifdef HAVE_INLINE
INLINE_FUN unsigned long int
gsl_rng_get (const gsl_rng * r)
{
return (r->type->get) (r->state);
}
INLINE_FUN double
gsl_rng_uniform (const gsl_rng * r)
{
return (r->type->get_double) (r->state);
}
INLINE_FUN double
gsl_rng_uniform_pos (const gsl_rng * r)
{
double x ;
do
{
x = (r->type->get_double) (r->state) ;
}
while (x == 0) ;
return x ;
}
/* Note: to avoid integer overflow in (range+1) we work with scale =
range/n = (max-min)/n rather than scale=(max-min+1)/n, this reduces
efficiency slightly but avoids having to check for the out of range
value. Note that range is typically O(2^32) so the addition of 1
is negligible in most usage. */
INLINE_FUN unsigned long int
gsl_rng_uniform_int (const gsl_rng * r, unsigned long int n)
{
unsigned long int offset = r->type->min;
unsigned long int range = r->type->max - offset;
unsigned long int scale;
unsigned long int k;
if (n > range || n == 0)
{
GSL_ERROR_VAL ("invalid n, either 0 or exceeds maximum value of generator",
GSL_EINVAL, 0) ;
}
scale = range / n;
do
{
k = (((r->type->get) (r->state)) - offset) / scale;
}
while (k >= n);
return k;
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_RNG_H__ */
| {
"alphanum_fraction": 0.7737530545,
"avg_line_length": 31.9128440367,
"ext": "h",
"hexsha": "d80e763494ac2b774ba375b441838b0c9d1ddd4c",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z",
"max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ielomariala/Hex-Game",
"max_forks_repo_path": "gsl-2.6/gsl/gsl_rng.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/gsl/gsl_rng.h",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/gsl/gsl_rng.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2091,
"size": 6957
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_cblas.h>
#include <lapacke.h>
#include "allvars.h"
#include "proto.h"
/*
* note that for a matrix A(mxn) in the row-major order, the first dimension is n.
*/
/* C(nxn) = A(nxn)*B(nxn) */
void multiply_mat(double * a, double *b, double *c, int n)
{
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1.0f
, a, n, b, n, 0.0f, c, n);
}
/* C(nxn) = A^T(nxn)*B(nxn) */
void multiply_mat_transposeA(double * a, double *b, double *c, int n)
{
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, n, n, 1.0f
, a, n, b, n, 0.0f, c, n);
}
/* C(nxn) = A(nxn)*B^T(nxn) */
void multiply_mat_transposeB(double * a, double *b, double *c, int n)
{
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0f
, a, n, b, n, 0.0f, c, n);
}
/* C(m*n) = A(m*k) * B(k*n) */
void multiply_mat_MN(double * a, double *b, double *c, int m, int n, int k)
{
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0f
, a, k, b, n, 0.0f, c, n);
}
/* C(m*n) = A^T(m*k) * B(k*n) */
void multiply_mat_MN_transposeA(double * a, double *b, double *c, int m, int n, int k)
{
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, m, n, k, 1.0f
, a, m, b, n, 0.0f, c, n);
}
/* C(m*n) = A(m*k) * B^T(k*n) */
void multiply_mat_MN_transposeB(double * a, double *b, double *c, int m, int n, int k)
{
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, m, n, k, 1.0f
, a, k, b, k, 0.0f, c, n);
}
/* y(n) = A(nxn)* x(n) */
void multiply_matvec(double *a, double *x, int n, double *y)
{
cblas_dgemv(CblasRowMajor, CblasNoTrans, n, n, 1.0f, a, n, x, 1, 0.0f, y, 1);
}
/* y(n) = A^T(nxn)* x(n) */
void multiply_matvec_transposeA(double *a, double *x, int n, double *y)
{
cblas_dgemv(CblasRowMajor, CblasTrans, n, n, 1.0f, a, n, x, 1, 0.0f, y, 1);
}
/* y(m) = A(m, n) * x(n) */
void multiply_matvec_MN(double * a, int m, int n, double *x, double *y)
{
cblas_dgemv(CblasRowMajor, CblasNoTrans, m, n, 1.0f, a, n, x, 1, 0.0f, y, 1);
}
/* A(mxm)^-1 * B(mxn), store the output in B
* note that A will be changed on exit. */
int multiply_mat_MN_inverseA(double * a, double *b, int m, int n)
{
int * ipiv, info;
ipiv=malloc(m*sizeof(int));
info=LAPACKE_dgetrf(LAPACK_ROW_MAJOR, m, m, a, m, ipiv);
if(info!=0)
{
strcpy(str_error_exit, "multiply_mat_MN_inverseA 1.\n this usually caused by improper nc.\n increase the low limit of nc");
error_exit(9);
}
info = LAPACKE_dgetrs(LAPACK_ROW_MAJOR, 'N', m, n, a, m, ipiv, b, n);
if(info!=0)
{
strcpy(str_error_exit, "multiply_mat_MN_inverseA 2\n this usually caused by improper nc.\n increase the low limit of nc");
error_exit(9);
}
free(ipiv);
return info;
}
/* A^-1 */
void inverse_mat(double * a, int n, int *info)
{
int * ipiv;
ipiv=malloc(n*sizeof(int));
// dgetrf_(&n, &n, a, &n, ipiv, info);
// dgetri_(&n, a, &n, ipiv, work, &lwork, info);
*info = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, a, n, ipiv);
if(*info!=0)
{
strcpy(str_error_exit, "inverse_mat");
error_exit(9);
}
*info = LAPACKE_dgetri(LAPACK_ROW_MAJOR, n, a, n, ipiv);
if(*info!=0)
{
strcpy(str_error_exit, "inverse_mat");
error_exit(9);
}
free(ipiv);
return;
}
/* eigen vector and eigen values */
void eigen_sym_mat(double *a, int n, double *val, int *info)
{
char jobz='V', uplo='U';
/* store the eigenvectors in a by rows.
* store the eigenvalues in val in ascending order.
*/
// dsyev_(&jobz, &uplo, &n, a, &n, val, work, &lwork, info);
/* store the eigenvectors in a by columns.
* store the eigenvalues in val in ascending order.
*/
LAPACKE_dsyev(LAPACK_ROW_MAJOR, jobz, uplo, n, a, n, val);
return;
}
/* A(nxn) = x^T(n) * x(n) */
void multiply_vec2mat(double * x, double * a, int n)
{
// cblas_dsyr(CblasRowMajor, CblasUpper, n, 1.0f, x, 1, a, n);
int i, j;
for(i=0; i<n; i++)
for(j=0; j<=i; j++)
{
a[i*n+j] = a[j*n+i] = x[i]*x[j];
}
}
/* determinant of matrix A
* note that A is changed on exit. */
double det_mat(double *a, int n, int *info)
{
int *ipiv;
int i;
double det;
ipiv = workspace_ipiv;
// dgetrf_(&n, &n, a, &n, ipiv, info);
*info=LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, a, n, ipiv);
if(*info!=0)
{
strcpy(str_error_exit, "det_mat");
error_exit(9);
}
det = 1.0;
for(i=0; i<n; i++)
{
det *= a[i*n+i];
if (ipiv[i] != i+1)
{
det = -det;
}
}
return det;
}
/* natural logarithm of determinant of A
* note that A is changed on exit. */
double lndet_mat(double *a, int n, int *info)
{
int * ipiv;
int i;
double lndet;
ipiv=workspace_ipiv;
// dgetrf_(&n, &n, a, &n, ipiv, info);
*info=LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, a, n, ipiv);
if(*info!=0)
{
strcpy(str_error_exit, "lndet_mat");
error_exit(9);
}
lndet = 0.0;
for(i=0; i<n; i++)
{
lndet += log(fabs(a[i*n+i]));
}
return lndet;
}
/* natural logarithm of determinant of A
* if any sign of the eigen values is negtive, return sign=-1
* note that A is changed on exit
*/
double lndet_mat2(double *a, int n, int *info, int *sign)
{
int * ipiv;
int i, *sign_all;
double lndet;
//ipiv=malloc(n*sizeof(int));
//sign_all=malloc(n*sizeof(int));
ipiv = workspace_ipiv;
sign_all = ipiv + n;
// dgetrf_(&n, &n, a, &n, ipiv, info);
*info=LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, a, n, ipiv);
if(*info!=0)
{
strcpy(str_error_exit, "lndet_mat2");
error_exit(9);
}
lndet = 0.0;
for(i=0; i<n; i++)
{
lndet += log(fabs(a[i*n+i]));
//*sign *= (a[i*n+i]>=0?1:-1);
sign_all[i] = (a[i*n+i]>=0?1:-1);
if(ipiv[i]!=i+1)
{
//printf("%e %d\n", a[i*n+i], n);
//ipiv[ipiv[i]] = ipiv[i];
//*sign *= -1;
sign_all[i] *= -1;
}
}
for(i=0; i<n;i++)
{
if(sign_all[i]==-1)
{
*sign=-1; // if any sign is negtive, return sign=-1
break;
}
}
return lndet;
}
/* natural logarithm of determinant of A
* sign of all the eigen values
* note that A is changed on exit
*/
double lndet_mat3(double *a, int n, int *info, int *sign)
{
int *ipiv;
int i;
double lndet;
//ipiv=malloc(n*sizeof(int));
//sign_all=malloc(n*sizeof(int));
ipiv = workspace_ipiv;
// dgetrf_(&n, &n, a, &n, ipiv, info);
*info=LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, a, n, ipiv);
if(*info!=0)
{
strcpy(str_error_exit, "lndet_mat3");
error_exit(9);
}
lndet = 0.0;
*sign = 1;
for(i=0; i<n; i++)
{
lndet += log(fabs(a[i*n+i]));
*sign *= (a[i*n+i]>=0?1:-1);
if(ipiv[i]!=i+1)
{
//printf("%e %d\n", a[i*n+i], n);
//ipiv[ipiv[i]] = ipiv[i];
*sign *= -1;
}
}
return lndet;
}
/* Cholesky decomposition of A, i.e., A = M^T* M
* store M in A */
void Chol_decomp_U(double *a, int n, int *info)
{
int i,j;
char uplo = 'L';
// dpotrf_(&uplo, &n, a, &n, info);
*info=LAPACKE_dpotrf(LAPACK_ROW_MAJOR, uplo, n, a, n);
if(*info<0)
{
strcpy(str_error_exit, "Chol_decomp_U");
fprintf(stderr, "The %d-th argument had an illegal value!\n", *info);
error_exit(9);
}
else if (*info>0)
{
strcpy(str_error_exit, "Chol_decomp_U");
fprintf(stderr, "The leading minor of order %d is not positive definite, and the factorization could not be completed.\n", *info);
error_exit(9);
}
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
a[i*n+j] = 0.0;
return;
}
void display_mat(double *a, int m, int n)
{
int i, j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%f\t", a[i*n+j]);
}
printf("\n");
}
}
double ** matrix_malloc(int n1, int n2)
{
double **mat;
int i;
if(!(mat = malloc(n1*sizeof(double*))))
{
fprintf(stderr, "Unable to allocate the matrix!\n");
error_exit(7);
}
for(i=0; i<n1; i++)
{
if(!(mat[i] = malloc(n2*sizeof(double))))
{
strcpy(str_error_exit, "matrix");
error_exit(7);
}
}
return mat;
}
double * array_malloc(int n)
{
double *array;
if(!(array = malloc(n*sizeof(double))))
{
strcpy(str_error_exit, "array");
error_exit(7);
}
return array;
}
| {
"alphanum_fraction": 0.5705889409,
"avg_line_length": 23.7521367521,
"ext": "c",
"hexsha": "474d0804a719b358cd90ca5771b4fe0489fa9779",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-04-12T11:48:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-12-29T06:04:13.000Z",
"max_forks_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/MICA",
"max_forks_repo_path": "src/mathfunc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "LiyrAstroph/MICA",
"max_issues_repo_path": "src/mathfunc.c",
"max_line_length": 134,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/MICA",
"max_stars_repo_path": "src/mathfunc.c",
"max_stars_repo_stars_event_max_datetime": "2016-10-25T06:32:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-25T06:32:33.000Z",
"num_tokens": 3102,
"size": 8337
} |
/* File description : Implementation of neural networks
* Author : Bruno Faria
* Year : 2014
* Work place : University of Aveiro
*/
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "neural_network.h"
//#include "mkl.h"
//#include <atlas_enum.h>
//#include <lapacke.h>
//#include <lapacke.h>
const char * nn_error_strings[19] = { "API succeed",
"API could not allocate memory for network object",
"API could not evaluate network object",
"API could not rescale data",
"neural network not initialized",
"API bad input",
"API weight initialization",
"API could not duplicate network",
"API could not copy data from src to dest, networks are different",
"API could not copy data :s",
"API could not solve system of equations (lapack least squares)",
"API lapack error",
"API could not free memory (what?)",
"API train",
"API train 2",
"API train 3",
"API could not duplicate network",
"API could not get inverse",
"API could not compute J, G, and H"
};
#define log2(x) log(x)/0.30102999566
/* Random number generator vars */
unsigned long mt_state[MT_N];
unsigned long mt_constants[2];
int mt_state_idx;
bool rand_state = false;
/* global stack error */
int32_t NN_API_ERROR = 0;
/* =======================================
* = Allocate and destroy neural network =
* =======================================
*/
net_t * create_nn(int32_t num_layers, int32_t * layers_conf, int32_t * layers_func )
{
int32_t i = 0, j = 0;
net_t * nn = NULL;
C_CHECK_CONDITION( num_layers == 0 || num_layers > 200 || num_layers < 1, NN_API_BAD_INPUT);
/* allocate a neural network object */
C_SAFE_CALL( nn = (net_t *)mem_alloc(sizeof(net_t), true ) );
/* allocate the layers field pointers */
C_SAFE_CALL( nn->layer = (net_layer_t **)mem_alloc(num_layers * sizeof(net_layer_t *), true) );
/* set num layers */
nn -> num_layers = num_layers;
nn -> init_state = false;
/* allocate layers vector */
C_SAFE_CALL( nn->layer[0] = (net_layer_t *)mem_alloc(num_layers * sizeof(net_layer_t), true) );
/* generate layers pointers */
for(i = 1; i < num_layers; i++) { nn->layer[i] = nn->layer[0] + i; }
/* allocate space for the layers */
for(i = 0; i < num_layers; i++)
{
C_CHECK_CONDITION( layers_conf[i] <= 0 || layers_conf[i] > 400, NN_API_BAD_INPUT );
/* insert number of inputs and outputs of the layer */
if(i == 0)
{
C_CHECK_CONDITION( layers_func[i] != NN_NONE || layers_func[i] > net_func_nelem, NN_API_BAD_INPUT );
/* input layer */
nn->layer[i]->num_inputs = 0;
nn->layer[i]->num_outputs = layers_conf[i];
nn->layer[i]->eval_funct = NN_NONE;
nn->layer[i]->weights = NULL;
nn->layer[i]->bias = NULL;
C_SAFE_CALL( nn->layer[i]->results = (double*)mem_alloc( layers_conf[i] * sizeof(double), true ));
/* allocate memory for input and output mapping */
C_SAFE_CALL( nn->xmin = (double *)mem_alloc(layers_conf[i] * sizeof(double),true ));
C_SAFE_CALL( nn->xmax = (double *)mem_alloc(layers_conf[i] * sizeof(double),true ));
}else{
C_CHECK_CONDITION( layers_func[i] == NN_NONE || layers_func[i] > net_func_nelem, NN_API_BAD_INPUT );
/* allocate memory for input and output mapping */
C_SAFE_CALL( nn->ymin = (double *)mem_alloc(layers_conf[i] * sizeof(double),true ));
C_SAFE_CALL( nn->ymax = (double *)mem_alloc(layers_conf[i] * sizeof(double),true ));
/* remaining layers */
nn->layer[i]->num_inputs = layers_conf[i-1];
nn->layer[i]->num_outputs = layers_conf[i];
nn->layer[i]->eval_funct = layers_func[i];
C_SAFE_CALL( nn->layer[i]->weights = (double**)mem_alloc( layers_conf[i] * sizeof(double *), true ) );
C_SAFE_CALL( nn->layer[i]->results = (double *)mem_alloc( layers_conf[i] * sizeof(double ), true ) );
C_SAFE_CALL( nn->layer[i]->bias = (double *)mem_alloc( layers_conf[i] * sizeof(double ), true ) );
C_SAFE_CALL( nn->layer[i]->weights[0] = (double *)mem_alloc( layers_conf[i-1] * layers_conf[i] * sizeof(double ), true ) );
for(j = 1; j < layers_conf[i]; j++)
{
nn->layer[i]->weights[j] = nn->layer[i]->weights[0] + j * layers_conf[i-1];
}
}
}
nn -> init_state = true;
nn -> use_mapping = true;
return nn;
error:
/* something went wrong so clean memory and exit */
destroy_nn( nn );
return NULL;
}
int32_t destroy_nn(net_t * nn)
{
int32_t i = 0;
net_layer_t * layer;
C_CHECK_CONDITION( nn == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( nn->num_layers == 0, NN_API_BAD_INPUT );
/* first deallocate the layers */
if(nn->layer != NULL)
{
if(nn->layer[0] != NULL)
{
layer = nn->layer[0];
mem_free(layer->results);
for(i = 1; i < nn->num_layers; i++ )
{
layer = nn->layer[i];
if(layer->weights != NULL)
{
mem_free( layer->weights[0] );
mem_free( layer->weights );
}
mem_free( layer->results );
mem_free( layer->bias );
}
/* now free the main object */
mem_free( nn->layer[0] );
}
mem_free( nn->layer );
}
mem_free( nn->xmin );
mem_free( nn->xmax );
mem_free( nn->ymin );
mem_free( nn->ymax );
mem_free( nn );
return 0;
error:
/* what? cannot deallocate memory? why? */
return -1;
}
void * mem_alloc(int32_t size, bool zero_set)
{
void * p = malloc(size);
if( p == NULL){ NN_API_ERROR = NN_API_NETWORK_ALLOC_ERROR; return NULL;}
if(zero_set == true)
{
memset(p, 0, size);
}
NN_API_ERROR = NN_API_SUCCESS;
return p;
}
void mem_free(void * ptr)
{
C_CHECK_CONDITION(ptr == NULL, NN_API_BAD_INPUT);
free( ptr );
ptr = NULL;
NN_API_ERROR = NN_API_SUCCESS;
return;
error:
NN_API_ERROR = NN_API_FREE;
return;
}
/* get the neural network response for a given input */
int32_t get_nn_response(net_t * nn)
{
int32_t i = 0, n = 0, l = 0;
double w_sum = 0.0f;
net_layer_t * layer = NULL, * prev_layer = NULL;
C_CHECK_CONDITION( nn == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( nn -> init_state == false, NN_API_BAD_INPUT );
C_CHECK_CONDITION( nn -> layer == NULL, NN_API_MALFORMED_NN );
memcpy(nn->layer[0]->results, nn->in_layer,nn->layer[0]->num_outputs * sizeof(double));
/* first layer hols the data to be evaluated */
if(nn->use_mapping){
C_SAFE_CALL( transform_in_out_data(nn, nn->layer[0]->results, nn->layer[0]->num_outputs, false) );
}
for(l = 1; l < nn->num_layers; l++)
{
C_CHECK_CONDITION( nn -> layer[l] == NULL, NN_API_MALFORMED_NN );
C_CHECK_CONDITION( nn -> layer[l-1] == NULL, NN_API_MALFORMED_NN );
/* remap layer (to increase readibility) */
layer = nn->layer[l];
prev_layer = nn->layer[l-1];
C_CHECK_CONDITION( layer -> bias == NULL, NN_API_MALFORMED_NN );
C_CHECK_CONDITION( layer -> weights == NULL, NN_API_MALFORMED_NN );
C_CHECK_CONDITION( layer -> weights[0] == NULL, NN_API_MALFORMED_NN );
for(n = 0; n < layer->num_outputs; n++)
{
w_sum = layer->bias[n];
for( i = 0; i < layer->num_inputs; i++)
w_sum += prev_layer->results[i] * layer->weights[n][i];
// apply layer function
switch( layer->eval_funct )
{
case NN_LOGSIG: { w_sum = 1 / (1 + exp(-w_sum)); break; }
case NN_TANSIG: { w_sum = 2 / (1 + exp(-2 * w_sum)) - 1; break; }
default: { break; }
}
layer->results[n] = w_sum;
}
}
/* transform the data and output it to the outer layer */
layer = nn->layer[nn->num_layers-1];
memcpy(nn->out_layer, layer->results, layer->num_outputs * sizeof(double));
if(nn->use_mapping)
{
C_SAFE_CALL( transform_in_out_data(nn, nn->out_layer, layer->num_outputs, true) );
}
NN_API_ERROR = NN_API_SUCCESS;
return 0;
error:
NN_API_ERROR = NN_API_RESCALE_DATA;
return -1;
}
inline double map_min_max( double x, double xmin, double xmax, double ymin, double ymax, bool reverse )
{
if(reverse)
{
return (ymax-ymin)*(x+1.0f)/2.0f + ymin;
}else{
return 2.0f * (x - xmin)/(xmax-xmin) - 1.0f;
}
}
int32_t transform_in_out_data(net_t * nn, double * in_out, int32_t size, bool Mode)
{
int32_t i = 0;
C_CHECK_CONDITION( size == 0, NN_API_BAD_INPUT);
for(i = 0; i < size; i++){
if(Mode){
in_out[i] = map_min_max(in_out[i], 0, 0, nn->ymin[i], nn->ymax[i], Mode);
}else{
in_out[i] = map_min_max(in_out[i], nn->xmin[i], nn->xmax[i], 0, 0, Mode);
}
}
NN_API_ERROR = NN_API_SUCCESS;
return 0;
error:
NN_API_ERROR = NN_API_RESCALE_DATA;
return -1;
}
/*
* Compute stuff
*/
double compute_JGH(net_t * nn, double **J, double *G, double **H, double ** samples, double ** targets, double * errors, double * nn_out, double * nn_temp_out,
int32_t * perm, int32_t num_samples, int32_t num_outputs, int32_t G_length)
{
double sse = 0;
int32_t i = 0, j = 0, k = 0, l = 0, s = 0, ct = 0;
net_layer_t * layer = NULL;
double weight_s = 0;
/* verify conditions */
C_CHECK_CONDITION( nn == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( J == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( G == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( samples == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( targets == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( errors == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( nn_out == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( nn_temp_out == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( num_samples == 0, NN_API_BAD_INPUT );
C_CHECK_CONDITION( num_outputs == 0, NN_API_BAD_INPUT );
C_CHECK_CONDITION( G_length == 0, NN_API_BAD_INPUT );
/* compute sample errors and jacobian */
for(s = 0; s < num_samples; s++)
{
ct = 0;
/* short circuit the pointers */
nn->in_layer = samples[perm[s]]; nn->out_layer = nn_out;
/* first evaluate the network for this sample without any perturbation*/
C_SAFE_CALL( get_nn_response( nn ) );
/* compute errors and sse */
for(i = 0; i < num_outputs; i++)
{
errors[i*num_samples + s] = targets[perm[s]][i] - nn_out[i];
sse += errors[i*num_samples + s]*errors[i*num_samples + s];
}
nn->out_layer = nn_temp_out;
/* the lines of the jacobian for this sample are computed here */
for(l = 1; l < nn->num_layers; l++)
{
layer = nn->layer[l];
for(i = 0; i < layer->num_outputs; i++)
{
/* weights perturbation */
for(j = 0; j < layer->num_inputs; j++)
{
weight_s = layer->weights[i][j];
/* apply perturbation parameter */
layer->weights[i][j] += (PERTURBATION * ( 1 + abs(weight_s)));
/* get neural network response */
C_SAFE_CALL( get_nn_response( nn ) );
/* restore weight */
layer->weights[i][j] = weight_s;
/* compute derivative */
for(k = 0; k < num_outputs; k++){
J[k*num_samples+s][ct] = (nn_out[k] - nn_temp_out[k]) / (PERTURBATION * ( 1 + abs(weight_s)));
}
ct++;
}
/* bias perturbation */
weight_s = layer->bias[i];
/* apply perturbation parameter */
layer->bias[i] += (PERTURBATION * ( 1 + abs(weight_s)));
/* get neural network response */
C_SAFE_CALL( get_nn_response( nn ) );
/* restore weight */
layer->bias[i] = weight_s;
/* compute derivative */
for(k = 0; k < num_outputs; k++)
J[k*num_samples+s][ct] = (nn_out[k] - nn_temp_out[k]) / (PERTURBATION * ( 1 + abs(weight_s)));
ct++;
}
}
}
/* compute gradient and aproximation to the hessian matrix */
memset(G, 0, G_length * sizeof(double));
memset(H[0], 0, G_length * G_length * sizeof(double));
for(i = 0; i < num_samples * num_outputs; i++ )
{
for(j = 0; j < G_length; j++)
{
G[j] += J[i][j] * errors[i];
}
}
/* symmetric matrix ??? Do we have singularities? */
for(i = 0; i < G_length; i++)
{
for(j = 0; j < G_length; j++)
{
for(k = 0; k < num_samples * num_outputs; k++)
H[i][j] += J[k][i]*J[k][j];
}
}
NN_API_ERROR = NN_API_SUCCESS;;
return sse;
error:
NN_API_ERROR = NN_API_COMPUTE_JGH;
return 0;
}
/* =====================================
* = Neural network training functions =
* =====================================
*/
int32_t nn_train(net_t * nn, double **samples, double ** targets, int32_t num_samples, int32_t max_epochs, double min_error )
{
double ** J = NULL, ** A = NULL, * A_temp = NULL, * G = NULL, * errors = NULL, * nn_out = NULL, * nn_t_out = NULL, * work = NULL, * S = NULL;
double niu = 0.01, current_error = 1e20, new_error = 0;
double **r_samples = NULL, **r_targets = NULL;
int32_t * iwork = NULL;
int32_t l = 0, J_ydim = 0, nlvl = 0, epoch = 0, *perm = NULL, lwork = 0, s = 0, num_outputs = 0, num_inputs = 0;
int32_t i = 0;
net_layer_t *layer = NULL;
net_t * test_nn = NULL;
/* memory for rescaled samples */
/* conditions check */
C_CHECK_CONDITION( nn == NULL, NN_API_NOT_INIT );
C_CHECK_CONDITION( nn->init_state == false, NN_API_NOT_INIT );
C_CHECK_CONDITION( num_samples <= 0, NN_API_BAD_INPUT );
C_CHECK_CONDITION( max_epochs < 0 && max_epochs > 10000, NN_API_BAD_INPUT );
C_CHECK_CONDITION( min_error < 0 && min_error > 1000, NN_API_BAD_INPUT );
C_CHECK_CONDITION( samples == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( targets == NULL, NN_API_BAD_INPUT );
/* init weights */
C_SAFE_CALL( init_nn_weights(nn) );
/* first and last layer : required to know the number of inputs and outputs and so allocate memory */
layer = nn->layer[nn->num_layers-1];
num_outputs = layer->num_outputs;
layer = nn->layer[0];
num_inputs = layer->num_outputs;
/* compute jacobian number of lines */
for(l = 1; l < nn->num_layers; l++)
{
layer = nn->layer[l];
J_ydim += (layer->num_inputs + 1) * layer-> num_outputs;
}
printf("J_ydim %d\n",J_ydim);
/* initialize required memory */
C_SAFE_CALL( J = (double **)mem_alloc(num_outputs * num_samples * sizeof(double *), true) );
C_SAFE_CALL( A = (double **)mem_alloc(J_ydim * sizeof(double *), true) );
C_SAFE_CALL( G = (double *)mem_alloc(J_ydim * sizeof(double ), true) );
C_SAFE_CALL( errors = (double *)mem_alloc(num_outputs * num_samples * sizeof(double ), true) );
C_SAFE_CALL( perm = (int32_t *)mem_alloc(num_samples * sizeof(int32_t ), true) );
C_SAFE_CALL( nn_out = (double *)mem_alloc(num_outputs * sizeof(double ), true) );
C_SAFE_CALL( nn_t_out = (double *)mem_alloc(num_outputs * sizeof(double ), true) );
C_SAFE_CALL( J[0] = (double *)mem_alloc(num_outputs * num_samples * J_ydim * sizeof(double ), true) );
C_SAFE_CALL( A[0] = (double *)mem_alloc(J_ydim * J_ydim * sizeof(double ), true) );
C_SAFE_CALL( A_temp = (double *)mem_alloc(J_ydim * J_ydim * sizeof(double ), true) );
C_SAFE_CALL( r_samples = (double **)mem_alloc(num_samples * sizeof(double*), true) );
C_SAFE_CALL( r_samples[0] = (double *)mem_alloc(num_samples * num_inputs * sizeof(double*), true) );
C_SAFE_CALL( r_targets = (double **)mem_alloc(num_samples * sizeof(double*), true) );
C_SAFE_CALL( r_targets[0] = (double *)mem_alloc(num_samples * num_outputs * sizeof(double*), true) );
/* calculate pointers address */
for(l = 1; l < J_ydim; l++)
A[l] = A[0] + l * J_ydim;
for(l = 1; l < num_outputs * num_samples; l++)
J[l] = J[0] + l * J_ydim;
for(l=1; l < num_samples; l++){
r_samples[l] = r_samples[0] + l * num_inputs;
r_targets[l] = r_targets[0] + l * num_outputs;
}
/* query lapack for the best size of the work area */
nlvl = (int32_t)(floor(log2((double)J_ydim/(25.0f+1.0f)))+1.0f);
C_SAFE_CALL( S = (double *) mem_alloc( J_ydim * sizeof(double ), true) );
C_SAFE_CALL( iwork = (int32_t *) mem_alloc( ( 3 * J_ydim * nlvl + 11 * J_ydim ) * sizeof(int32_t), true) );
lwork = lpck_solve_ls_svd_pivot(J_ydim, -1, NULL, 0, S, iwork, A[0], G);
C_SAFE_CALL( work = (double *)mem_alloc(lwork * sizeof(double), true) );
/* grab scalling parameters */
nn_grab_rescale_params( nn, samples, targets, num_samples );
/* rescale samples and targets to -1, 1 range */
for(l = 0; l < num_samples; l++){
memcpy(r_samples[l], samples[l], num_inputs * sizeof(double));
C_SAFE_CALL( transform_in_out_data(nn, r_samples[l], num_inputs, false) );
memcpy(r_targets[l], targets[l], num_outputs * sizeof(double));
for(i = 0; i < num_outputs; i++){
r_targets[l][i] = map_min_max(r_targets[l][i], nn->ymin[i], nn->ymax[i], 0, 0, false);
}
}
/* generate a duplicate network */
C_SAFE_CALL( test_nn = duplicate_network( nn ) );
/* disable rescaling */
nn->use_mapping = false;
/* generate random presentation */
random_perm(num_samples, perm);
C_SAFE_CALL( copy_nn_data( test_nn, nn ) );
/* compute jacobian, hessian and stuff */
current_error = compute_JGH(test_nn, J, G, A, r_samples, r_targets, errors, nn_out, nn_t_out, perm, num_samples, num_outputs, J_ydim);
/* lets train the neural network */
while(sqrt(current_error) > min_error && epoch < max_epochs && niu < 1e20)
{
/* copy network to a safe place */
C_SAFE_CALL( copy_nn_data( test_nn, nn ) );
memcpy(A_temp, A[0], J_ydim * J_ydim * sizeof(double));
/* apply niu */
for(i = 0; i < J_ydim; i++)
A_temp[i*J_ydim+i] += niu ;
/* call lapack to solve our system of equations */
C_SAFE_CALL( lpck_solve_ls_svd_pivot(J_ydim, 0, work, lwork, S, iwork, A_temp, G) );
/* apply changes to neural network weights (lapack gives solution in G) */
nn_change_weights_bias(test_nn, G);
/* compute new error */
new_error = 0.0f;
for(s = 0; s < num_samples; s++)
{
/* short circuit the pointers */
test_nn->in_layer = r_samples[perm[s]]; test_nn->out_layer = nn_out;
/* compute neural network response for this input */
C_SAFE_CALL( get_nn_response( test_nn ) );
/* compute sample errors */
for(i = 0; i < num_outputs; i++)
new_error += (r_targets[perm[s]][i] - nn_out[i]) * (r_targets[perm[s]][i] - nn_out[i]);
}
/* check wether or not we should accept this network */
if(new_error < current_error )
{
/* copy network */
C_SAFE_CALL( copy_nn_data( nn, test_nn ) );
current_error = new_error;
niu *= 0.1;
random_perm(num_samples, perm);
/* compute new hessian, jacobian and gradient */
current_error = compute_JGH(test_nn, J, G, A, r_samples, r_targets, errors, nn_out, nn_t_out, perm, num_samples, num_outputs, J_ydim);
}else{
niu *= 10;
}
printf("epoch: %d error : %f niu : %f\n",epoch,sqrt(current_error),niu);
epoch++;
}
/* clean memory and exit */
destroy_nn( test_nn );
/* enable rescaling */
nn->use_mapping = true;
if(r_samples != NULL)
{
mem_free(r_samples[0]);
mem_free(r_samples);
}
if(r_targets != NULL)
{
mem_free(r_targets[0]);
mem_free(r_targets);
}
if(J != NULL)
{
mem_free( J[0] );
mem_free( J );
}
if(A != NULL)
{
mem_free( A[0] );
mem_free( A );
}
mem_free( A_temp );
mem_free( G );
mem_free( errors );
mem_free( perm );
mem_free( nn_out );
mem_free( nn_t_out );
mem_free( work );
mem_free( iwork );
mem_free( S );
NN_API_ERROR = NN_API_SUCCESS;
return 0;
error:
destroy_nn( test_nn );
/* clean memory and exit */
if(r_samples != NULL)
{
mem_free(r_samples[0]);
mem_free(r_samples);
}
if(r_targets != NULL)
{
mem_free(r_targets[0]);
mem_free(r_targets);
}
if(J != NULL)
{
mem_free( J[0] );
mem_free( J );
}
if(A != NULL)
{
mem_free( A[0] );
mem_free( A );
}
mem_free( G );
mem_free( errors );
mem_free( perm );
mem_free( nn_out );
mem_free( nn_t_out );
mem_free( work );
mem_free( iwork );
mem_free( S );
NN_API_ERROR = NN_API_TRAIN;
return -1;
}
/* =====================================
* = Neural network training functions =
* =====================================
*/
int32_t nn_train2(net_t * nn, double **samples, double ** targets, int32_t num_samples, int32_t max_epochs, double min_error, double train_perc )
{
double ** J = NULL, ** A = NULL, * A_temp = NULL, * G = NULL, * errors = NULL, * nn_out = NULL, * nn_t_out = NULL, * work = NULL, * S = NULL;
double niu = 0.001, current_error = 1e20, new_error = 0, error_perc = 1- train_perc, grb = 0;
double **r_samples = NULL, **r_targets = NULL;
int32_t * iwork = NULL;
int32_t l = 0, J_ydim = 0, nlvl = 0, epoch = 0, *perm = NULL, lwork = 0, s = 0, num_outputs = 0, num_inputs = 0;
int32_t i = 0, train_s_index = 0, error_e_index = 0;
net_layer_t *layer = NULL;
net_t * test_nn = NULL;
/* conditions check */
C_CHECK_CONDITION( nn == NULL, NN_API_NOT_INIT );
C_CHECK_CONDITION( nn->init_state == false, NN_API_NOT_INIT );
C_CHECK_CONDITION( num_samples <= 0, NN_API_BAD_INPUT );
C_CHECK_CONDITION( max_epochs < 0 && max_epochs > 10000, NN_API_BAD_INPUT );
C_CHECK_CONDITION( min_error < 0 && min_error > 1000, NN_API_BAD_INPUT );
C_CHECK_CONDITION( samples == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( targets == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( train_perc <= 0 || train_perc >= 1, NN_API_BAD_INPUT );
C_CHECK_CONDITION( train_perc*num_samples < 10, NN_API_BAD_INPUT );
C_CHECK_CONDITION( error_perc*num_samples < 10, NN_API_BAD_INPUT );
/* init weights */
C_SAFE_CALL( init_nn_weights(nn) );
/* compute jacobian number of lines */
for(l = 1; l < nn->num_layers; l++){
layer = nn->layer[l];
J_ydim += (layer->num_inputs + 1) * layer-> num_outputs;
}
/* first and last layer : required to know the number of inputs and outputs and so allocate memory */
layer = nn->layer[nn->num_layers-1];
num_outputs = layer->num_outputs;
layer = nn->layer[0];
num_inputs = layer->num_outputs;
/* initialize required memory */
C_SAFE_CALL( J = (double **)mem_alloc(num_outputs * num_samples * sizeof(double *), true) );
C_SAFE_CALL( A = (double **)mem_alloc(J_ydim * sizeof(double *), true) );
C_SAFE_CALL( G = (double *)mem_alloc(J_ydim * sizeof(double ), true) );
C_SAFE_CALL( errors = (double *)mem_alloc(num_outputs * num_samples * sizeof(double ), true) );
C_SAFE_CALL( perm = (int32_t *)mem_alloc(num_samples * sizeof(int32_t ), true) );
C_SAFE_CALL( nn_out = (double *)mem_alloc(num_outputs * sizeof(double ), true) );
C_SAFE_CALL( nn_t_out = (double *)mem_alloc(num_outputs * sizeof(double ), true) );
C_SAFE_CALL( J[0] = (double *)mem_alloc(num_outputs * num_samples * J_ydim * sizeof(double ), true) );
C_SAFE_CALL( A[0] = (double *)mem_alloc(J_ydim * J_ydim * sizeof(double ), true) );
C_SAFE_CALL( A_temp = (double *)mem_alloc(J_ydim * J_ydim * sizeof(double ), true) );
C_SAFE_CALL( r_samples = (double **)mem_alloc(num_samples * sizeof(double*), true) );
C_SAFE_CALL( r_samples[0] = (double *)mem_alloc(num_samples * num_inputs * sizeof(double*), true) );
C_SAFE_CALL( r_targets = (double **)mem_alloc(num_samples * sizeof(double*), true) );
C_SAFE_CALL( r_targets[0] = (double *)mem_alloc(num_samples * num_outputs * sizeof(double*), true) );
/* calculate pointers address */
for(l = 1; l < J_ydim; l++)
A[l] = A[0] + l * J_ydim;
for(l = 1; l < num_outputs * num_samples; l++)
J[l] = J[0] + l * J_ydim;
for(l=1; l < num_samples; l++){
r_samples[l] = r_samples[0] + l * num_inputs;
r_targets[l] = r_targets[0] + l * num_outputs;
}
/* query lapack for the best size of the work area */
nlvl = (int32_t)(floor(log2((double)J_ydim/(25.0f+1.0f)))+1.0f);
C_SAFE_CALL( S = (double *) mem_alloc( J_ydim * sizeof(double ), true) );
C_SAFE_CALL( iwork = (int32_t *) mem_alloc( ( 3 * J_ydim * nlvl + 11 * J_ydim ) * sizeof(int32_t), true) );
lwork = lpck_solve_ls_svd_pivot(J_ydim, -1, NULL, 0, S, iwork, A[0], G);
C_SAFE_CALL( work = (double *)mem_alloc(lwork * sizeof(double), true) );
/* grab scalling parameters */
nn_grab_rescale_params( nn, samples, targets, num_samples );
/* rescale samples and targets to -1, 1 range */
for(l = 0; l < num_samples; l++){
memcpy(r_samples[l], samples[l], num_inputs * sizeof(double));
C_SAFE_CALL( transform_in_out_data(nn, r_samples[l], num_inputs, false) );
memcpy(r_targets[l], targets[l], num_outputs * sizeof(double));
for(i = 0; i < num_outputs; i++){
r_targets[l][i] = map_min_max(r_targets[l][i], nn->ymin[i], nn->ymax[i], 0, 0, false);
}
}
/* generate a duplicate network */
C_SAFE_CALL( test_nn = duplicate_network( nn ) );
/* copy network to a safe place */
C_SAFE_CALL( copy_nn_data( test_nn, nn ) );
/* generate a random permutation */
random_perm(num_samples, perm);
/* training start index and error end index */
train_s_index = num_samples * error_perc + 1;
error_e_index = num_samples * error_perc;
/* disable rescaling */
nn->use_mapping = false;
/* ASSUMPTION: FIRST SAMPLES ON PERM ARE FOR ERROR CALCULATION*/
C_SAFE_CALL( current_error = compute_JGH(test_nn, J, G, A, r_samples, r_targets, errors, nn_out, nn_t_out, perm, error_e_index, num_outputs, J_ydim) );
/* compute new hessian, jacobian and gradient */
C_SAFE_CALL( grb = compute_JGH(test_nn, J, G, A, r_samples, r_targets,
&errors[train_s_index*num_outputs], nn_out, nn_t_out,
&perm[train_s_index],
num_samples - train_s_index,
num_outputs, J_ydim);
);
/* lets train the neural network */
while(sqrt(current_error) > min_error && epoch < max_epochs && niu < 1e20)
{
/* copy network to a safe place */
C_SAFE_CALL( copy_nn_data( test_nn, nn ) );
memcpy(A_temp, A[0], J_ydim * J_ydim * sizeof(double));
/* apply niu */
for(i = 0; i < J_ydim; i++)
A_temp[i*J_ydim+i] += niu ;
/* call lapack to solve our system of equations */
C_SAFE_CALL( lpck_solve_ls_svd_pivot(J_ydim, 0, work, lwork, S, iwork, A_temp, G) );
/* apply changes to neural network weights (lapack gives solution in G) */
nn_change_weights_bias(test_nn, G);
/* compute new error */
new_error = 0.0f;
for(s = 0; s < error_e_index; s++)
{
/* short circuit the pointers */
test_nn->in_layer = r_samples[perm[s]]; test_nn->out_layer = nn_out;
/* compute neural network response for this input */
C_SAFE_CALL( get_nn_response( test_nn ) );
/* compute sample errors */
for(i = 0; i < num_outputs; i++)
{
new_error += (r_targets[perm[s]][i] - nn_out[i]) * (r_targets[perm[s]][i] - nn_out[i]);
}
}
/* check wether or not we should accept this network */
if(new_error < current_error )
{
/* copy network */
C_SAFE_CALL( copy_nn_data( nn, test_nn ) );
current_error = new_error;
/* compute new hessian, jacobian and gradient */
C_SAFE_CALL(
grb = compute_JGH(test_nn, J, G, A, r_samples, r_targets,
&errors[train_s_index*num_outputs], nn_out, nn_t_out,
&perm[train_s_index],
num_samples - train_s_index,
num_outputs, J_ydim);
);
niu *= 0.1;
}else{
niu *= 10;
}
printf("epoch: %d error : %f niu : %f\n",epoch,sqrt(current_error),niu);
epoch++;
}
/* clean memory and exit */
destroy_nn( test_nn );
/* enable rescaling */
nn->use_mapping = true;
if(r_samples != NULL)
{
mem_free(r_samples[0]);
mem_free(r_samples);
}
if(r_targets != NULL)
{
mem_free(r_targets[0]);
mem_free(r_targets);
}
if(J != NULL)
{
mem_free( J[0] );
mem_free( J );
}
if(A != NULL)
{
mem_free( A[0] );
mem_free( A );
}
mem_free( A_temp );
mem_free( G );
mem_free( errors );
mem_free( perm );
mem_free( nn_out );
mem_free( nn_t_out );
mem_free( work );
mem_free( iwork );
mem_free( S );
NN_API_ERROR = NN_API_SUCCESS;
return 0;
error:
destroy_nn( test_nn );
/* clean memory and exit */
if(r_samples != NULL)
{
mem_free(r_samples[0]);
mem_free(r_samples);
}
if(r_targets != NULL)
{
mem_free(r_targets[0]);
mem_free(r_targets);
}
if(J != NULL)
{
mem_free( J[0] );
mem_free( J );
}
if(A != NULL)
{
mem_free( A[0] );
mem_free( A );
}
mem_free( A_temp );
mem_free( G );
mem_free( errors );
mem_free( perm );
mem_free( nn_out );
mem_free( nn_t_out );
mem_free( work );
mem_free( iwork );
mem_free( S );
NN_API_ERROR = NN_API_TRAIN2;
return -1;
}
int32_t nn_train3(net_t * nn, double **samples, double ** targets, int32_t num_samples, int32_t max_epochs, double min_error )
{
double ** J = NULL, ** A = NULL, *A_temp = NULL, * G = NULL, * errors = NULL, * nn_out = NULL, * nn_t_out = NULL, * work = NULL, * S = NULL, * inv_ipiv = NULL, * inv_work = NULL;
double niu = 0.01, current_error = 1e20, new_error = 0, alpha = 0, beta = 1, gamma = 0, Ew = 0, Ed = 0, trace = 0;
double **r_samples = NULL, **r_targets = NULL;
int32_t * iwork = NULL;
int32_t l = 0, J_ydim = 0, nlvl = 0, epoch = 0, *perm = NULL, lwork = 0, s = 0, num_outputs = 0, num_inputs =0;
int32_t i = 0;
net_layer_t *layer = NULL;
net_t * test_nn = NULL;
/* conditions check */
C_CHECK_CONDITION( nn == NULL, NN_API_NOT_INIT );
C_CHECK_CONDITION( nn->init_state == false, NN_API_NOT_INIT );
C_CHECK_CONDITION( num_samples <= 0, NN_API_BAD_INPUT );
C_CHECK_CONDITION( max_epochs < 0 && max_epochs > 10000, NN_API_BAD_INPUT );
C_CHECK_CONDITION( min_error < 0 && min_error > 1000, NN_API_BAD_INPUT );
C_CHECK_CONDITION( samples == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( targets == NULL, NN_API_BAD_INPUT );
/* init weights */
C_SAFE_CALL( init_nn_weights(nn) );
/* compute jacobian number of lines */
for(l = 1; l < nn->num_layers; l++){
layer = nn->layer[l];
J_ydim += (layer->num_inputs + 1) * layer-> num_outputs;
}
/* first and last layer : required to know the number of inputs and outputs and so allocate memory */
layer = nn->layer[nn->num_layers-1];
num_outputs = layer->num_outputs;
layer = nn->layer[0];
num_inputs = layer->num_outputs;
/* initialize required memory */
C_SAFE_CALL( J = (double **)mem_alloc(num_outputs * num_samples * sizeof(double *), true) );
C_SAFE_CALL( A = (double **)mem_alloc(J_ydim * sizeof(double *), true) );
C_SAFE_CALL( G = (double *)mem_alloc(J_ydim * sizeof(double ), true) );
C_SAFE_CALL( errors = (double *)mem_alloc(num_outputs * num_samples * sizeof(double ), true) );
C_SAFE_CALL( perm = (int32_t *)mem_alloc(num_samples * sizeof(int32_t ), true) );
C_SAFE_CALL( nn_out = (double *)mem_alloc(num_outputs * sizeof(double ), true) );
C_SAFE_CALL( nn_t_out = (double *)mem_alloc(num_outputs * sizeof(double ), true) );
C_SAFE_CALL( J[0] = (double *)mem_alloc(num_outputs * num_samples * J_ydim * sizeof(double ), true) );
C_SAFE_CALL( A[0] = (double *)mem_alloc(J_ydim * J_ydim * sizeof(double ), true) );
C_SAFE_CALL( A_temp = (double *)mem_alloc(J_ydim * J_ydim * sizeof(double ), true) );
C_SAFE_CALL( r_samples = (double **)mem_alloc(num_samples * sizeof(double*), true) );
C_SAFE_CALL( r_samples[0] = (double *)mem_alloc(num_samples * num_inputs * sizeof(double*), true) );
C_SAFE_CALL( r_targets = (double **)mem_alloc(num_samples * sizeof(double*), true) );
C_SAFE_CALL( r_targets[0] = (double *)mem_alloc(num_samples * num_outputs * sizeof(double*), true) );
/* calculate pointers address */
for(l = 1; l < J_ydim; l++)
A[l] = A[0] + l * J_ydim;
for(l = 1; l < num_outputs * num_samples; l++)
J[l] = J[0] + l * J_ydim;
for(l=1; l < num_samples; l++){
r_samples[l] = r_samples[0] + l * num_inputs;
r_targets[l] = r_targets[0] + l * num_outputs;
}
/* query lapack for the best size of the work area */
nlvl = (int32_t)(floor(log2((double)J_ydim/(25.0f+1.0f)))+1.0f);
C_SAFE_CALL( S = (double *) mem_alloc( J_ydim * sizeof(double ), true) );
C_SAFE_CALL( iwork = (int32_t *) mem_alloc( ( 3 * J_ydim * nlvl + 11 * J_ydim ) * sizeof(int32_t), true) );
lwork = lpck_solve_ls_svd_pivot(J_ydim, -1, NULL, 0, S, iwork, A[0], G);
C_SAFE_CALL( work = (double *)mem_alloc(lwork * sizeof(double), true) );
/* allocate space for matrix inversion */
C_SAFE_CALL( inv_ipiv = (double *) mem_alloc( (J_ydim + 1) * sizeof(double), true ) );
C_SAFE_CALL( inv_work = (double *) mem_alloc( J_ydim * J_ydim * sizeof(double), true ) );
/* grab scalling parameters */
nn_grab_rescale_params( nn, samples, targets, num_samples );
/* rescale samples and targets to -1, 1 range */
for(l = 0; l < num_samples; l++){
memcpy(r_samples[l], samples[l], num_inputs * sizeof(double));
C_SAFE_CALL( transform_in_out_data(nn, r_samples[l], num_inputs, false) );
memcpy(r_targets[l], targets[l], num_outputs * sizeof(double));
for(i = 0; i < num_outputs; i++){
r_targets[l][i] = map_min_max(r_targets[l][i], nn->ymin[i], nn->ymax[i], 0, 0, false);
}
}
/* generate a duplicate network */
C_SAFE_CALL( test_nn = duplicate_network( nn ) );
/* copy network to a safe place */
C_SAFE_CALL( copy_nn_data( test_nn, nn ) );
/* generate a random permutation */
random_perm(num_samples, perm);
C_SAFE_CALL( Ed = compute_JGH(test_nn, J, G, A, r_samples, r_targets, errors, nn_out, nn_t_out, perm, num_samples, num_outputs, J_ydim) );
/* compute Ew */
Ew = 0.0;
for( l = 1; l < test_nn -> num_layers; l++){
layer = test_nn -> layer[l];
for(i = 0; i < layer -> num_inputs * layer -> num_outputs; i++)
Ew += layer -> weights[0][i] * layer -> weights[0][i];
for(i = 0; i < layer->num_outputs; i++)
Ew += layer->bias[i];
}
current_error = alpha * Ew + beta *Ed;
/* disable rescaling */
nn->use_mapping = false;
/* lets train the neural network */
while(sqrt(current_error) > min_error && epoch < max_epochs && niu < 1e10)
{
/* copy network to a safe place */
C_SAFE_CALL( copy_nn_data( test_nn, nn ) );
memcpy(A_temp, A[0], J_ydim * J_ydim * sizeof(double) );
for(i=0; i < J_ydim * J_ydim; i++)
A_temp[i] *= 2.0f * beta;
/* apply niu and alpha regularization parameter */
for(i = 0; i < J_ydim; i++)
A_temp[i*J_ydim+i] += 2.0f*niu + 2.0f*alpha;
/* call lapack to solve our system of equations */
C_SAFE_CALL( lpck_solve_ls_svd_pivot(J_ydim, 0, work, lwork, S, iwork, A_temp, G) );
/* apply changes to neural network weights (lapack gives solution in G) */
nn_change_weights_bias(test_nn, G);
/* compute new error */
Ed = 0.0f;
for(s = 0; s < num_samples; s++)
{
/* short circuit the pointers */
test_nn->in_layer = r_samples[s]; test_nn->out_layer = nn_out;
/* compute neural network response for this input */
C_SAFE_CALL( get_nn_response( test_nn ) );
/* compute sample errors */
for(i = 0; i < num_outputs; i++)
Ed += (r_targets[s][i] - nn_out[i])*(r_targets[s][i] - nn_out[i]);
}
/* compute Ew */
Ew = 0.0;
for( l = 1; l < test_nn -> num_layers; l++){
layer = test_nn -> layer[l];
for(i = 0; i < layer -> num_inputs * layer -> num_outputs; i++)
Ew += layer -> weights[0][i] * layer -> weights[0][i];
for(i = 0; i < layer->num_outputs; i++)
Ew += layer->bias[i];
}
new_error = alpha * Ew + beta * Ed;
/* check wether or not we should accept this network */
if(new_error < current_error )
{
/* copy network */
C_SAFE_CALL( copy_nn_data( nn, test_nn ) );
current_error = new_error;
niu *= 0.1;
/* update parameters */
memcpy(A_temp, A[0], J_ydim * J_ydim * sizeof(double) );
//for(i=0; i < J_ydim * J_ydim; i++)
// A_temp[i] *= 2.0f * beta;
/* apply niu and alpha regularization parameter */
//for(i = 0; i < J_ydim; i++)
// A_temp[i*J_ydim+i] += 2.0f*alpha;
C_SAFE_CALL( lpck_get_inv(J_ydim, inv_work, J_ydim * J_ydim, inv_ipiv, A_temp) );
/* compute trace of the inverse */
trace = 0.0;
for(i = 0; i < J_ydim; i++)
trace += A_temp[i*J_ydim+i];
gamma = (double)(J_ydim) - (alpha * trace);
beta =fabs(((double)(num_samples) - gamma)/(2.0f*Ed));
alpha = (double)J_ydim /(2.0f*Ew+trace);
/* compute new hessian, jacobian and gradient */
C_SAFE_CALL( current_error = compute_JGH(test_nn, J, G, A, r_samples, r_targets,
errors, nn_out, nn_t_out, perm, num_samples, num_outputs, J_ydim);
);
}else{
niu *= 10;
}
printf("epoch: %d alpha : %f beta : %f gamma : (%f ,%d, %d) trace : %f error : %f (%f, %f) niu : %f\n",epoch,alpha, beta, gamma, J_ydim,num_samples, trace,sqrt(current_error), Ed, Ew,niu);
epoch++;
}
/* clean memory and exit */
destroy_nn( test_nn );
/* enable rescaling */
nn->use_mapping = true;
if(r_samples != NULL)
{
mem_free(r_samples[0]);
mem_free(r_samples);
}
if(r_targets != NULL)
{
mem_free(r_targets[0]);
mem_free(r_targets);
}
if(J != NULL)
{
mem_free( J[0] );
mem_free( J );
}
if(A != NULL)
{
mem_free( A[0] );
mem_free( A );
}
mem_free( A_temp );
mem_free( G );
mem_free( errors );
mem_free( perm );
mem_free( nn_out );
mem_free( nn_t_out );
mem_free( work );
mem_free( iwork );
mem_free( S );
mem_free( inv_ipiv );
mem_free( inv_work );
NN_API_ERROR = NN_API_SUCCESS;
return 0;
error:
destroy_nn( test_nn );
/* clean memory and exit */
if(r_samples != NULL)
{
mem_free(r_samples[0]);
mem_free(r_samples);
}
if(r_targets != NULL)
{
mem_free(r_targets[0]);
mem_free(r_targets);
}
if(J != NULL)
{
mem_free( J[0] );
mem_free( J );
}
if(A != NULL)
{
mem_free( A[0] );
mem_free( A );
}
mem_free( G );
mem_free( errors );
mem_free( perm );
mem_free( nn_out );
mem_free( nn_t_out );
mem_free( work );
mem_free( iwork );
mem_free( S );
NN_API_ERROR = NN_API_TRAIN3;
return -1;
}
/* create a network with the same characteristics of the one that has been given */
net_t * duplicate_network(net_t * nn )
{
int32_t * layers_func = NULL, * layers_conf = NULL;
int32_t i = 0;
net_t * new_nn = NULL;
net_layer_t * layer;
C_CHECK_CONDITION( nn == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( nn -> layer == NULL, NN_API_BAD_INPUT );
C_CHECK_CONDITION( nn -> init_state == false, NN_API_BAD_INPUT );
C_CHECK_CONDITION( nn -> num_layers == 0, NN_API_BAD_INPUT );
/* first allocate temporary memory */
C_SAFE_CALL( layers_func = (int32_t *) mem_alloc( nn->num_layers * sizeof(int32_t), true ) );
C_SAFE_CALL( layers_conf = (int32_t *) mem_alloc( nn->num_layers * sizeof(int32_t), true ) );
/* get the parameters from this network */
for(i = 0; i < nn->num_layers; i++)
{
layer = nn -> layer[i];
C_CHECK_CONDITION( layer == NULL, NN_API_MALFORMED_NN );
layers_conf[i] = layer->num_outputs;
layers_func[i] = layer->eval_funct;
}
/* call network initializer */
C_SAFE_CALL( new_nn = create_nn(nn->num_layers, layers_conf, layers_func ) );
/* should we also copy the information? */
/* input layer rescale parameters */
for(i = 0; i < (nn->layer[0])->num_outputs; i++){
new_nn -> xmin[i] = nn -> xmin[i];
new_nn -> xmax[i] = nn -> xmax[i];
}
for(i = 0; i < (nn->layer[nn->num_layers-1])->num_outputs; i++){
new_nn -> ymin[i] = nn -> ymin[i];
new_nn -> ymax[i] = nn -> ymax[i];
}
/* free auxiliary memory areas */
mem_free(layers_func);
mem_free(layers_conf);
NN_API_ERROR = NN_API_SUCCESS;
return new_nn;
error:
/* free auxiliary memory areas */
mem_free(layers_func);
mem_free(layers_conf);
NN_API_ERROR = NN_API_DUPLICATE_NN;
return NULL;
}
/* copy data from one network into another */
int32_t copy_nn_data(net_t *dest, net_t *src)
{
net_layer_t * l_src = NULL, * l_dest = NULL;
int32_t l = 0;
C_CHECK_CONDITION( dest -> num_layers != src -> num_layers, NN_API_COPY_DIFF );
C_CHECK_CONDITION( src -> num_layers == 0, NN_API_COPY_DIFF );
for( l = 1; l < src -> num_layers; l++)
{
l_src = src->layer[l];
l_dest = dest->layer[l];
C_CHECK_CONDITION( l_src->num_inputs != l_dest->num_inputs, NN_API_COPY_DIFF );
C_CHECK_CONDITION( l_src->num_outputs != l_dest->num_outputs, NN_API_COPY_DIFF );
/* proceed with the copy */
memcpy(l_dest->weights[0], l_src->weights[0], l_src->num_inputs * l_src->num_outputs * sizeof(double));
memcpy(l_dest->bias, l_src->bias, l_src->num_outputs * sizeof(double));
}
dest->use_mapping = src->use_mapping;
NN_API_ERROR = NN_API_SUCCESS;
return 0;
error:
NN_API_ERROR = NN_API_COPY;
return -1;
}
void nn_grab_rescale_params(net_t * nn, double ** samples, double ** targets, int32_t num_samples )
{
int32_t i = 0, j = 0;
net_layer_t * layer = NULL;
double min = 0, max = 0;
layer = nn->layer[0];
/* first find maximum and minimum of samples */
min = samples[0][0]; max = min;
for(i = 0; i < layer->num_outputs; i++)
{
for(j = 0; j < num_samples; j++ )
{
if(max < samples[j][i])
max = samples[j][i];
if(min > samples[j][i])
min = samples[j][i];
}
/* store input parameters */
nn->xmin[i] = min;
nn->xmax[i] = max;
}
/* do it for targets*/
layer = nn->layer[nn->num_layers-1];
min = targets[0][0]; max = min;
for(i = 0; i < layer->num_outputs; i++)
{
for(j = 0; j < num_samples; j++ )
{
if(max < targets[j][i])
max = targets[j][i];
if(min > targets[j][i])
min = targets[j][i];
}
/* store output parameters */
nn->ymin[i] = min;
nn->ymax[i] = max;
}
}
/*
* Change weights and bias based on the values provided in G
*/
void nn_change_weights_bias(net_t * nn, double * G)
{
net_layer_t * layer = NULL;
int32_t l = 0, i = 0, j = 0, ct = 0;
/* for each layer */
for(l = 1; l < nn->num_layers; l++)
{
layer = nn->layer[l];
for(i = 0; i < layer->num_outputs; i++)
{
/* weights */
for(j = 0; j < layer->num_inputs; j++)
{
layer->weights[i][j] -= G[ct++];
}
/* bias */
layer->bias[i] -= G[ct++];
}
}
}
int32_t init_nn_weights(net_t * nn)
{
int32_t i = 0, l = 0, n = 0;
net_layer_t * layer = NULL;
double norm_weights = 0.0f, norm_bias = 0.0f, beta = 0.0f;
double f_range_up = 0.0f, f_range_down = 0.0f;
C_CHECK_CONDITION( nn->num_layers == 0, NN_API_BAD_INPUT );
for(l = 1; l < nn->num_layers; l++)
{
layer = nn->layer[l];
/* scale random values according to the function used */
switch(layer->eval_funct)
{
case NN_LOGSIG: { f_range_up = 1.0f; f_range_down = 0.0f; break; }
case NN_TANSIG: { f_range_up = 1.0f; f_range_down = -1.0f; break; }
default: { f_range_up = 1.0f; f_range_down = -1.0f; break; }
}
beta = 0.7f*pow((double)layer->num_outputs, 1/(double)layer->num_inputs);
/* for each neuron in the layer */
norm_weights = 0.0f; norm_bias = 0.0f;
for( n = 0; n < layer->num_outputs; n++)
{
for(i = 0; i < layer->num_inputs; i++ )
{
layer->weights[n][i] = (double)(mt_random()) * RANDMAXV * (f_range_up - f_range_down) - f_range_down;
norm_weights += layer->weights[n][i] * layer->weights[n][i];
}
/* randomize bias */
norm_weights = sqrt(norm_weights);
norm_bias = sqrt(norm_bias);
for(i = 0; i < layer->num_inputs; i++ )
layer->weights[n][i] *= (beta/norm_weights);
// generate bias
if(layer->weights[n][0]>0)
layer->bias[n] = beta * (-1.0f + (double)n*2/(double)(layer->num_outputs));
else
layer->bias[n] = -1.0*beta * (-1.0f + (double)n*2/(double)(layer->num_outputs));
}
}
NN_API_ERROR = NN_API_SUCCESS;
return 0;
error:
NN_API_ERROR = NN_API_WEIGHT_INIT;
return -1;
}
int32_t lpck_solve_nxn_ls(int32_t J_ydim, int32_t query, int32_t * work, int32_t lwork, double *eq_matrix, double * eq_sol)
{
int32_t col_size = J_ydim;
int32_t car = 1;
int32_t info = 0;
if(query == -1)
{
return J_ydim;
}else{
dgesv_( &col_size, &car, eq_matrix, &col_size, work, eq_sol, &col_size, &info );
/* Check for the exact singularity */
C_CHECK_CONDITION(info != 0, NN_API_LS_SOLVE);
}
NN_API_ERROR = NN_API_SUCCESS;
return info;
error:
if( info > 0 ) {
printf( "\t\tThe diagonal element of the triangular factor of A,\n" );
printf( "\t\tU(%i,%i) is zero, so that A is singular;\n", info, info );
printf( "\t\tthe solution could not be computed.\n" );
exit( 1 );
}
NN_API_ERROR = NN_API_LS;
return -1;
}
int32_t lpck_solve_ls_svd_pivot(int32_t J_ydim, int32_t query, double * work, int32_t lwork, double * S, int32_t * iwork, double *eq_matrix, double * eq_sol)
{
int32_t col_size = J_ydim;
int32_t nrhs = 1;
int32_t info = 0;
int32_t rank = 0;
double work_size = 0;
double rcond = -1; /* default machine precision */
if(query == -1)
{
dgelsd_( &col_size, /* m dimension */
&col_size, /* n dimension */
&nrhs, /* number of right hand sided */
eq_matrix, /* A matrix */
&col_size, /* leading dimension of A */
eq_sol, /* B vector */
&col_size, /* leading dimension of B */
S, /* array with M columns */
&rcond, /* which precision? */
&rank, /* the matrix rank */
&work_size, /* query workspace size */
&query, /* the query */
iwork, /* workspace array */
&info );
return (int32_t)work_size;
}else{
dgelsd_( &col_size, /* m dimension */
&col_size, /* n dimension */
&nrhs, /* number of right hand sided */
eq_matrix, /* A matrix */
&col_size, /* leading dimension of A */
eq_sol, /* B vector */
&col_size, /* leading dimension of B */
S, /* array with M columns */
&rcond, /* which precision? */
&rank, /* the matrix rank */
work, /* query workspace size */
&lwork, /* the query */
iwork, /* workspace array */
&info );
/* Check for the exact singularity */
C_CHECK_CONDITION(info != 0, NN_API_LS_SOLVE);
}
NN_API_ERROR = NN_API_SUCCESS;
return info;
error:
if( info > 0 ) {
printf( "\t\tThe diagonal element of the triangular factor of A,\n" );
printf( "\t\tU(%i,%i) is zero, so that A is singular;\n", info, info );
printf( "\t\tthe solution could not be computed.\n" );
}
NN_API_ERROR = NN_API_LS;
return -1;
}
int32_t lpck_solve_ls(int32_t J_ydim, int32_t query, double * work, int32_t lwork, double * eq_matrix, double * eq_sol)
{
char N = 'N';
int32_t col_size = J_ydim;
int32_t car = 1;
int32_t info = 0;
double work_size = 7000;
if (query==-1)
{
dgels_( &N, /* use matrix M or its transpose */
&col_size, /* number of lines of matrix M */
&col_size, /* number of rows of matrix M */
&car, /* number of colums of B and x */
eq_matrix, /* matrix M */
&col_size, /* size -> max(1,vector_size) */
eq_sol, /* sol vector / out vector */
&col_size, /* LDB */
&work_size, /* work array */
&query, /* LWORK */
&info);
return (int32_t)work_size;
}else{
dgels_( &N, /* use matrix M or its transpose */
&col_size, /* number of lines of matrix M */
&col_size, /* number of rows of matrix M */
&car, /* number of colums of B and x */
eq_matrix, /* matrix M */
&col_size, /* size -> max(1,vector_size) */
eq_sol, /* sol vector / out vector */
&col_size, /* LDB */
work, /* work array */
&lwork, /* LWORK */
&info);
C_CHECK_CONDITION(info != 0, NN_API_LS_SOLVE);
}
NN_API_ERROR = NN_API_SUCCESS;
return info;
error:
if( info > 0 )
{
printf( "\t\tThe diagonal element %i of the triangular factor ", info );
printf( "\t\tof A is zero, so that A does not have full rank;\n" );
printf( "\t\tthe least squares solution could not be computed.\n" );
}else{
printf("Lwork value %d\n", lwork);
}
NN_API_ERROR = NN_API_LS;
return -1;
}
int32_t lpck_get_inv(int32_t J_ydim, double * work, int32_t lwork, double * ipiv, double * eq_matrix)
{
int32_t col_size = J_ydim;
int32_t info = 0;
int32_t i = 0;
dgetrf_(&col_size,&col_size, eq_matrix, &col_size, ipiv, &info);
if(info!= 0){
goto error;
}
dgetri_(&col_size, eq_matrix, &col_size, ipiv, work, &lwork, &info);
if(info!= 0){
goto error;
}
if(info!= 0)
goto error;
NN_API_ERROR = NN_API_SUCCESS;
return info;
error:
if(info > 0)
printf("decomposition successful but U is singular, u_%d%d=0\n", i,i);
else
printf("decomposition not successful %dth parameter has an illegal value\n", i);
NN_API_ERROR = NN_API_GET_INV;
return -1;
}
void random_perm(int32_t num_p, int32_t * ranpat)
{
unsigned int p, np, op;
unsigned int r;
for( p = 0 ; p < (unsigned int)num_p; p++ ) { ranpat[p] = (unsigned int)p; }
for( p = 0 ; p < (unsigned int)num_p; p++)
{
r = (unsigned int)( mt_random() * 1.0 * ( RANDMAXV * (num_p - p )));
np = p + r ;
op = ranpat[p];
ranpat[p] = ranpat[np];
ranpat[np] = op;
}
}
void init_mt(void)
{
int32_t i = 0;
srand((int32_t)time(NULL));
/* init mersenne twister */
mt_state[0]= rand() & 0xffffffffUL;
for (i = 1; i < MT_N; i++)
{
mt_state[i] = (1812433253UL * (mt_state[i - 1] ^ (mt_state[i-1] >> 30)) + i);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
mt_state[i] &= 0xffffffffUL;
/* for >32 bit machines */
}
mt_constants[0] = 0x0L;
mt_constants[1] = 0x9908b0dfUL;
mt_state_idx = MT_N+1;
}
unsigned long mt_random(void){
unsigned long y;
if(rand_state == false){ init_mt(); rand_state = true; }
/* Updating state */
if( mt_state_idx >= MT_N){
int k;
for(k = 0; k < MT_N - MT_M; k++)
{
y = ( mt_state[ k ] & MT_UPPER_MASK ) | ( mt_state[ k + 1 ] & MT_LOWER_MASK );
mt_state[ k ] = mt_state[ k + MT_M ] ^ ( y>> 1) ^ mt_constants[ y & 0x1UL ];
}
for(; k < MT_N - 1; k++){
y = ( mt_state[ k ] & MT_UPPER_MASK ) | ( mt_state[ k + 1 ] & MT_LOWER_MASK );
mt_state[ k ] = mt_state[ k + ( MT_M - MT_N ) ] ^ ( y>> 1) ^ mt_constants[ y & 0x1UL ];
}
y = (mt_state[ MT_N - 1 ] & MT_UPPER_MASK ) | ( mt_state[0] & MT_LOWER_MASK );
mt_state[ MT_N - 1 ] = mt_state[ MT_M - 1 ] ^ (y >> 1) ^ mt_constants[ y & 0x1UL ];
mt_state_idx = 0;
}
/* Generating */
y = mt_state[ mt_state_idx++ ];
/* tempering */
y ^= (y >> 11);
y ^= (y << 7 ) & 0x9d2c5680UL;
y ^= (y << 15 ) & 0xefc60000UL;
y ^= (y >> 18);
return y;
}
| {
"alphanum_fraction": 0.604972001,
"avg_line_length": 30.4119033589,
"ext": "c",
"hexsha": "96f9c451133c5bcd42984aeae5798768339af668",
"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": "75417ecc97bfe1d1500f715acd4ea45c1a067423",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "BrunoFFaria/neural-networks",
"max_forks_repo_path": "neural_network.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "75417ecc97bfe1d1500f715acd4ea45c1a067423",
"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": "BrunoFFaria/neural-networks",
"max_issues_repo_path": "neural_network.c",
"max_line_length": 191,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "75417ecc97bfe1d1500f715acd4ea45c1a067423",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "BrunoFFaria/neural-networks",
"max_stars_repo_path": "neural_network.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 16219,
"size": 51609
} |
#ifndef QDM_CONFIG_H
#define QDM_CONFIG_H 1
#include <gsl/gsl_vector.h>
typedef struct {
unsigned long int rng_seed;
int acc_check;
int burn_discovery;
int iter_discovery;
int burn_analysis;
int iter_analysis;
int knot_try;
int spline_df;
int thin;
gsl_vector *months;
gsl_vector *knots;
gsl_vector *tau_highs;
gsl_vector *tau_lows;
double theta_min;
double theta_tune_sd;
double xi_high;
double xi_low;
double xi_prior_mean;
double xi_prior_var;
double xi_tune_sd;
double bound;
int debug;
int tau_table;
} qdm_config;
int
qdm_config_read(
qdm_config **config,
const char *file_path,
const char *group_path
);
void
qdm_config_fwrite(
FILE *f,
const qdm_config *cfg
);
#endif /* QDM_CONFIG_H */
| {
"alphanum_fraction": 0.7152061856,
"avg_line_length": 13.8571428571,
"ext": "h",
"hexsha": "ac87f7457db956153ad35d6baf6ad5d4e55c9386",
"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": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "include/qdm/config.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "include/qdm/config.h",
"max_line_length": 29,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "include/qdm/config.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 221,
"size": 776
} |
#ifndef SOURCE_PRINTTOFILE_H_
#define SOURCE_PRINTTOFILE_H_
// *** release/print_to_file.h ***
// Author: Kevin Wolz, date: 08/2018
//
// Utilities to write the results obtained by robustness_main into files.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <stdlib.h>
#include <sys/stat.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "utils.h"
#include "md5hash.h"
// Appends the robustness (and, if analytical output, pdf) value to a file.
void WriteData(std::ofstream& datafile, double& robustness, double& pdf);
// Appends the initial conditions of a run (e.g. dimensions of data, covariance
// matrix etc.) to a file.
void WriteMetadata(std::ofstream& metafile, const unsigned& datdim,
gsl_matrix* covar_matrix, const unsigned& pardim,
gsl_vector* prior_param_values, gsl_matrix* prior_matrix,
gsl_matrix* g_matrix, const unsigned& num_samplings);
// Appends the metadata about a run (e.g. data hash ID, filepaths, timestamp,
// etc) to a file.
void WriteLogs(std::ofstream& logfile, std::string& meta_filepath,
const int& op_mode, std::string& data_filepath,
const int& success);
#endif // SOURCE_PRINTTOFILE_H_
| {
"alphanum_fraction": 0.7034529452,
"avg_line_length": 30.7708333333,
"ext": "h",
"hexsha": "0708587b33a011ab90d8a9dfdcbcb25d1dbf6e1b",
"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": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kevguitar/Robustness",
"max_forks_repo_path": "source/print_to_file.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac",
"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": "kevguitar/Robustness",
"max_issues_repo_path": "source/print_to_file.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ab83a09a82fcc7f8ee10027b3ccb24194731b4ac",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kevguitar/Robustness",
"max_stars_repo_path": "source/print_to_file.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 380,
"size": 1477
} |
/***************************************************************************/
/* */
/* LU_decomp.h - LU Decomposition class for mruby */
/* Copyright (C) 2015 Paolo Bosetti */
/* paolo[dot]bosetti[at]unitn.it */
/* Department of Industrial Engineering, University of Trento */
/* */
/* This library is free software. You can redistribute it and/or */
/* modify it under the terms of the GNU GENERAL PUBLIC LICENSE 2.0. */
/* */
/* This library is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* Artistic License 2.0 for more details. */
/* */
/* See the file LICENSE */
/* */
/***************************************************************************/
#ifndef LU_DECOMP_H
#define LU_DECOMP_H
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/param.h>
#include <time.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_permutation.h>
#include "mruby.h"
#include "mruby/variable.h"
#include "mruby/string.h"
#include "mruby/data.h"
#include "mruby/class.h"
#include "mruby/value.h"
#include "mruby/array.h"
#include "mruby/numeric.h"
#include "mruby/compile.h"
#define E_LU_DECOMP_ERROR (mrb_class_get(mrb, "LUDecompError"))
/***********************************************\
LU Decomposition
\***********************************************/
typedef struct {
gsl_matrix *mat;
gsl_permutation *p;
int sgn;
size_t size;
} lu_decomp_data_s;
// Garbage collector handler, for play_data struct
// if play_data contains other dynamic data, free it too!
// Check it with GC.start
void lu_decomp_destructor(mrb_state *mrb, void *p_);
// Utility function for getting the struct out of the wrapping IV @data
void mrb_lu_decomp_get_data(mrb_state *mrb, mrb_value self, lu_decomp_data_s **data);
void mrb_gsl_lu_decomp_init(mrb_state *mrb);
#endif // LU_DECOMP_H | {
"alphanum_fraction": 0.4915190351,
"avg_line_length": 37.9,
"ext": "h",
"hexsha": "5c7aa3d0a2820eda163b0f2570902b36faf582b2",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "UniTN-Mechatronics/mruby-gsl",
"max_forks_repo_path": "src/LU_decomp.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "UniTN-Mechatronics/mruby-gsl",
"max_issues_repo_path": "src/LU_decomp.h",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "UniTN-Mechatronics/mruby-gsl",
"max_stars_repo_path": "src/LU_decomp.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 508,
"size": 2653
} |
/**
*
* @file sgebrd.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 Azzam Haidar
* @date 2010-11-15
* @generated s Tue Jan 7 11:45:10 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup float
*
* PLASMA_sgebrd - reduces a general complex M-by-N matrix A to upper or lower
* bidiagonal form B using a two-stage approach
* First stage: reduction to band bidiagonal form (orthogonal matrices Q1 and P1);
* Second stage: reduction from band to bidiagonal form (orthogonal matrices
* Q2 and P2).
* Let Q = Q1 * Q2 be the global left unitary transformation;
* Let P = P1 * P2 be the global right unitary transformation;
* Q**T * A * P = B.
* If M >= N, B is upper bidiagonal; if M < N, B is lower bidiagonal.
* Not LAPACK Compliant for now!
* Note: T is incomplete and contains only the block reflectors of the first stage.
* Therefore, Q and P can not be built completely.
*
*******************************************************************************
*
* @param[in] jobq
* Specifies options for computing all or part of the matrix Q.
* Intended usage:
* = PlasmaVec: all M columns of Q are returned in array Q;
* = PlasmaNoVec: not referenced.
*
* @param[in] jobp
* Specifies options for computing all or part of the matrix V**T.
* Intended usage:
* = PlasmaVec: all N columns of P are returned in array P;
* = PlasmaNoVec: not referenced.
*
* @param[in] M
* The number of rows of the matrix A. M >= 0.
*
* @param[in] N
* The number of columns of the matrix A. N >= 0.
*
* @param[in,out] A
* On entry, the M-by-N matrix A.
* On exit,
* if M >= N, the diagonal and the first superdiagonal are
* overwritten with the upper bidiagonal matrix B; the
* elements below the diagonal, with the array T, represent
* the unitary matrix Q as a product of elementary
* reflectors, and the elements above the first superdiagonal,
* with the array T, represent the unitary matrix P as
* a product of elementary reflectors;
* if M < N, the diagonal and the first subdiagonal are
* overwritten with the lower bidiagonal matrix B; the
* elements below the first subdiagonal, with the array T,
* represent the unitary matrix Q as a product of
* elementary reflectors, and the elements above the diagonal,
* with the array T, represent the unitary matrix P as
* a product of elementary reflectors.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,M).
*
* @param[out] D
* On exit, the diagonal elements of the bidiagonal matrix:
* D(i) = A(i,i).
* Dimension (min(M,N)).
*
* @param[out] E
* On exit, the off-diagonal elements of the bidiagonal matrix:
* if M >= N, E(i) = A(i,i+1) for i = 1,2,...,N-1;
* if M < N, E(i) = A(i+1,i) for i = 1,2,...,M-1.
* Dimension (min(M,N)-1).
*
* @param[out] descT
* On entry, descriptor as return by PLASMA_Alloc_Workspace_sgebrd
* On exit, contains auxiliary factorization data.
*
* @param[out] Q
* On exit, if jobz = PlasmaVec, then if return value = 0,
* Q contains the M-by-M unitary matrix Q.
* If jobz = PlasmaNoVec, then it is not referenced.
*
* @param[in] LDQ
* The leading dimension of the array Q. LDQ >= M.
*
* @param[out] P
* On exit, if jobz = PlasmaVec, then if return value = 0,
* P contains the N-by-N unitary matrix P.
* If jobz = PlasmaNoVec, then it is not referenced.
*
* @param[in] LDP
* The leading dimension of the array P. LDP >= N.
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
*
*******************************************************************************
*
* @sa PLASMA_sgebrd_Tile
* @sa PLASMA_sgebrd_Tile_Async
* @sa PLASMA_cgebrd
* @sa PLASMA_dgebrd
* @sa PLASMA_sgebrd
*
******************************************************************************/
int PLASMA_sgebrd(PLASMA_enum jobq, PLASMA_enum jobp,
int M, int N,
float *A, int LDA,
float *D,
float *E,
PLASMA_desc *descT,
float *Q, int LDQ,
float *P, int LDP)
{
int NB;
int status;
plasma_context_t *plasma;
PLASMA_sequence *sequence = NULL;
PLASMA_request request = PLASMA_REQUEST_INITIALIZER;
PLASMA_desc descA;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_sgebrd", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
/* Check input arguments */
if (jobq != PlasmaNoVec && jobq !=PlasmaVec) {
plasma_error("PLASMA_sgebrd", "illegal value of jobq");
return -1;
}
if (jobp != PlasmaNoVec && jobp != PlasmaVec) {
plasma_error("PLASMA_sgebrd", "illegal value of jobp");
return -2;
}
if (M < 0) {
plasma_error("PLASMA_sgebrd", "illegal value of M");
return -3;
}
if (N < 0) {
plasma_error("PLASMA_sgebrd", "illegal value of N");
return -4;
}
if (LDA < max(1, M)) {
plasma_error("PLASMA_sgebrd", "illegal value of LDA");
return -6;
}
if (LDQ < 1) {
plasma_error("PLASMA_sgebrd", "illegal value of LDQ");
return -9;
}
if (LDP < 1) {
plasma_error("PLASMA_sgebrd", "illegal value of LDP");
return -11;
}
/* Quick return */
if (min(M, N) == 0) {
return PLASMA_SUCCESS;
}
/* Tune NB & IB depending on M & N; Set NBNB */
status = plasma_tune(PLASMA_FUNC_SGEBRD, M, N, 0);
if (status != PLASMA_SUCCESS) {
plasma_error("PLASMA_sgebrd", "plasma_tune() failed");
return status;
}
/* Set NT */
NB = PLASMA_NB;
plasma_sequence_create(plasma, &sequence);
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_sooplap2tile( descA, A, NB, NB, LDA, N, 0, 0, M, N, sequence, &request,
plasma_desc_mat_free(&(descA)) );
} else {
plasma_siplap2tile( descA, A, NB, NB, LDA, N, 0, 0, M, N,
sequence, &request);
}
/* Call the tile interface */
PLASMA_sgebrd_Tile_Async(jobq, jobp, &descA, D, E, descT, Q, LDQ, P, LDP, sequence, &request);
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_sooptile2lap( descA, A, NB, NB, LDA, N, sequence, &request);
plasma_dynamic_sync();
plasma_desc_mat_free(&descA);
} else {
plasma_siptile2lap( descA, A, NB, NB, LDA, N, sequence, &request);
plasma_dynamic_sync();
}
status = sequence->status;
plasma_sequence_destroy(plasma, sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup float_Tile
*
* PLASMA_sgebrd_Tile - reduces a general complex M-by-N matrix A to upper or lower
* bidiagonal form B using a two-stage approach
* First stage: reduction to band bidiagonal form (orthogonal matrices Q1 and P1);
* Second stage: reduction from band to bidiagonal form (orthogonal matrices
* Q2 and P2).
* Let Q = Q1 * Q2 be the global left unitary transformation;
* Let P = P1 * P2 be the global right unitary transformation;
* Q**T * A * P = B.
* If M >= N, B is upper bidiagonal; if M < N, B is lower bidiagonal.
* Note: T is incomplete and contains only the block reflectors of the first stage.
* Therefore, Q and P can not be built completely.
* Tile equivalent of PLASMA_sgebrd().
* Operates on matrices stored by tiles.
* All matrices are passed through descriptors.
* All dimensions are taken from the descriptors.
*
*******************************************************************************
*
* @param[in] jobq
* Specifies options for computing all or part of the matrix Q.
* Intended usage:
* = PlasmaVec: all M columns of Q are returned in array Q;
* = PlasmaNoVec: not referenced.
*
* @param[in] jobp
* Specifies options for computing all or part of the matrix V**T.
* Intended usage:
* = PlasmaVec: all M columns of Q are returned in array Q;
* = PlasmaNoVec: not referenced.
*
* @param[in,out] A
* On entry, the M-by-N matrix A.
* On exit,
* if M >= N, the diagonal and the first superdiagonal are
* overwritten with the upper bidiagonal matrix B; the
* elements below the diagonal, with the array T, represent
* the unitary matrix Q as a product of elementary
* reflectors, and the elements above the first superdiagonal,
* with the array T, represent the unitary matrix P as
* a product of elementary reflectors;
* if M < N, the diagonal and the first subdiagonal are
* overwritten with the lower bidiagonal matrix B; the
* elements below the first subdiagonal, with the array T,
* represent the unitary matrix Q as a product of
* elementary reflectors, and the elements above the diagonal,
* with the array T, represent the unitary matrix P as
* a product of elementary reflectors.
*
* @param[out] D
* The real array containing the diagonal elements
* of the bidiagonal matrix B:
* D(i) = A(i,i).
* Dimension (min(M,N)).
*
* @param[out] E
* The real array containing the off-diagonal elements
* of the bidiagonal matrix B:
* if M >= N, E(i) = A(i,i+1) for i = 1,2,...,N-1;
* if M < N, E(i) = A(i+1,i) for i = 1,2,...,M-1.
* Dimension (min(M,N)-1).
*
* @param[out] T
* On exit, contains auxiliary factorization data.
*
* @param[out] Q
* On exit, if jobz = PlasmaVec, then if return value = 0,
* Q contains the M-by-M unitary matrix Q.
* If jobz = PlasmaNoVec, then it is not referenced.
*
* @param[in] LDQ
* The leading dimension of the array Q. LDQ >= M.
*
* @param[out] P
* On exit, if jobz = PlasmaVec, then if return value = 0,
* P contains the N-by-N unitary matrix P.
* If jobz = PlasmaNoVec, then it is not referenced.
*
* @param[in] LDP
* The leading dimension of the array P. LDP >= N.
*
*******************************************************************************
*
* @return
* \return PLASMA_SUCCESS successful exit
*
*******************************************************************************
*
* @sa PLASMA_sgebrd
* @sa PLASMA_sgebrd_Tile_Async
* @sa PLASMA_cgebrd_Tile
* @sa PLASMA_dgebrd_Tile
* @sa PLASMA_sgebrd_Tile
*
******************************************************************************/
int PLASMA_sgebrd_Tile(PLASMA_enum jobq, PLASMA_enum jobp,
PLASMA_desc *A,
float *D, float *E,
PLASMA_desc *T,
float *Q, int LDQ,
float *P, int LDP)
{
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_sgebrd_Tile", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
plasma_sequence_create(plasma, &sequence);
PLASMA_sgebrd_Tile_Async(jobq, jobp, A, D, E, T, Q, LDQ, P, LDP, sequence, &request);
plasma_dynamic_sync();
status = sequence->status;
plasma_sequence_destroy(plasma, sequence);
return status;
}
/***************************************************************************//**
*
* @ingroup float_Tile_Async
*
* PLASMA_sgebrd_Tile_Async - reduces a general complex M-by-N matrix A to upper or lower
* bidiagonal form B using a two-stage approach
* First stage: reduction to band bidiagonal form (orthogonal matrices Q1 and P1);
* Second stage: reduction from band to bidiagonal form (orthogonal matrices
* Q2 and P2).
* Let Q = Q1 * Q2 be the global left unitary transformation;
* Let P = P1 * P2 be the global right unitary transformation;
* Q**T * A * P = B.
* If M >= N, B is upper bidiagonal; if M < N, B is lower bidiagonal.
* Note: T is incomplete and contains only the block reflectors of the first stage.
* Therefore, Q and P can not be built completely.
* Non-blocking equivalent of PLASMA_sgebrd_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_sgebrd
* @sa PLASMA_sgebrd_Tile
* @sa PLASMA_cgebrd_Tile_Async
* @sa PLASMA_dgebrd_Tile_Async
* @sa PLASMA_sgebrd_Tile_Async
*
******************************************************************************/
int PLASMA_sgebrd_Tile_Async(PLASMA_enum jobu, PLASMA_enum jobvt,
PLASMA_desc *A,
float *S, float *E,
PLASMA_desc *T,
float *U, int LDU,
float *VT, int LDVT,
PLASMA_sequence *sequence, PLASMA_request *request)
{
PLASMA_desc descA ;
PLASMA_desc descT ;
PLASMA_desc descU, descVT;
float *AB;
int M ;
int N ;
int MINMN ;
int NB ;
int LDAB ;
int i;
int status;
plasma_context_t *plasma;
plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA_sgebrd_Tile_Async", "PLASMA not initialized");
return PLASMA_ERR_NOT_INITIALIZED;
}
if (sequence == NULL) {
plasma_fatal_error("PLASMA_sgebrd_Tile_Async", "NULL sequence");
return PLASMA_ERR_UNALLOCATED;
}
if (request == NULL) {
plasma_fatal_error("PLASMA_sgebrd_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_sgebrd_Tile_Async", "invalid first descriptor");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
} else {
descA = *A;
}
if (plasma_desc_check(T) != PLASMA_SUCCESS) {
plasma_error("PLASMA_sgebrd_Tile_Async", "invalid fourth descriptor");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
} else {
descT = *T;
}
/* Check input arguments */
if (jobu != PlasmaNoVec && jobu != PlasmaVec) {
plasma_error("PLASMA_sgebrd_Tile_Async", "illegal value of jobu");
return PLASMA_ERR_NOT_SUPPORTED;
}
if (jobvt != PlasmaNoVec && jobvt != PlasmaVec) {
plasma_error("PLASMA_sgebrd_Tile_Async", "illegal value of jobvt");
return PLASMA_ERR_NOT_SUPPORTED;
}
if (descA.nb != descA.mb) {
plasma_error("PLASMA_sgebrd_Tile_Async", "only square tiles supported");
return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);
}
#if defined(ENABLE_TIMER)
PLASMA_Double_t timelpk=0.0,timeaplQ2=0.0, timeT=0.0;
PLASMA_Double_t timeB=0.0,timeblg=0.0,timeaplQ1=0.0,timeconv1=0.0,timeconv2=0.0,timeall=0.0;
timeall = PLASMA_Wtime();
#endif
PLASMA_enum uplo = descA.m >= descA.n ? PlasmaUpper : PlasmaLower;
M = descA.m;
N = descA.n;
MINMN = min(M,N);
NB = min(descA.mb,MINMN);
LDAB = 3*NB+1;
/*=======================================
* case M<NB or N<NB call lapack
*=======================================*/
if( ( M<= NB) || ( N <=NB ) ){
/* convert the tile descA to lapack A */
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
AB = (float *) plasma_shared_alloc(plasma, M*N, PlasmaRealFloat);
if (AB == NULL) {
plasma_error("PLASMA_sgesvd_Tile_Async", "plasma_shared_alloc(AB-0-) failed");
plasma_shared_free(plasma, AB);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
plasma_sooptile2lap( descA, AB, NB, NB, M, N, sequence, request);
} else {
AB = descA.mat;
plasma_siptile2lap( descA, AB, NB, NB, M, N, sequence, request);
}
plasma_dynamic_sync();
/*=======================================
* calling LAPACK SGESVD
*=======================================*/
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timelpk = PLASMA_Wtime();
#endif
plasma_setlapack_multithreads(plasma->world_size);
/* call SVD solver using lapack routine */
float *TAUQ = (float *) plasma_shared_alloc(plasma, MINMN, PlasmaRealFloat);
float *TAUP = (float *) plasma_shared_alloc(plasma, MINMN, PlasmaRealFloat);
status = LAPACKE_sgebrd(LAPACK_COL_MAJOR, M, N, AB, M, S, E, TAUQ, TAUP);
if(jobu == PlasmaVec){
LAPACKE_slacpy(LAPACK_COL_MAJOR, lapack_const(PlasmaLower), M, MINMN, AB, M, U, LDU );
LAPACKE_sorgbr(LAPACK_COL_MAJOR, 'Q', M, M, N, U, LDU, TAUQ );
}
if(jobvt == PlasmaVec){
LAPACKE_slacpy(LAPACK_COL_MAJOR, lapack_const(PlasmaUpper), MINMN, N, AB, M, VT, LDVT );
LAPACKE_sorgbr(LAPACK_COL_MAJOR, 'P', N, N, MINMN, VT, LDVT, TAUP );
}
if(status != 0){
plasma_error("PLASMA_sgesvd","SGESVD");
}
sequence->status = status;
plasma_setlapack_sequential(plasma);
#if defined(ENABLE_TIMER)
timelpk = PLASMA_Wtime()-timelpk;
printf(" Finish Eigensolver-lpkonly timing= %lf threads %d\n" ,timelpk, plasma->world_size);
#endif
/*=======================================
* END of calling SVD solver
*=======================================*/
/* convert the lapack to the tile descA */
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
//plasma_sooplap2tile_noalloc( descA, AB, NB, NB, M, N, 0, 0, M, N, sequence, request);
plasma_parallel_call_5( plasma_pslapack_to_tile,
float*, AB,
int, M,
PLASMA_desc, descA,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_dynamic_sync();
free(AB);
} else {
plasma_siplap2tile( descA, AB, NB, NB, M, N, 0, 0, M, N,
sequence, request);
}
plasma_dynamic_sync();
free(TAUQ);
free(TAUP);
return PLASMA_SUCCESS;
}
/*=======================================
* END OF case M<NB or N<NB
*=======================================*/
/*
* Allocate workspace for band storage of the band matrix A
* AB looks like:
* __________________________________
* NB | zero |
* ----------------------------------
* NB+1 | band A |
* ----------------------------------
* NB |_______________zero_______________|
*
* */
AB = (float *)plasma_shared_alloc(plasma, LDAB*MINMN, PlasmaRealFloat);
memset( AB, 0, LDAB * MINMN * sizeof(float) );
if (AB == NULL) {
plasma_error("PLASMA_sgebrd_Tile_Async", "plasma_shared_alloc(AB) failed");
plasma_shared_free(plasma, AB);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
/*=======================================
* calling Reduction from DENSE to BAND
* then convert matrix to band form
*=======================================*/
//plasma_dynamic_sync();
#if defined(ENABLE_TIMER)
timeB = PLASMA_Wtime();
#endif
/*
* Reduction to BAND bidiagonal form
* May be further optimized using the algo described in Trefethen
*/
/* if (plasma->householder == PLASMA_FLAT_HOUSEHOLDER) { */
plasma_dynamic_call_4(plasma_psgebrd_ge2gb,
PLASMA_desc, descA,
PLASMA_desc, descT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* } */
/* else { */
/* plasma_dynamic_call_4(plasma_psgebrd_ge2gb_rh, */
/* PLASMA_desc, descA, */
/* PLASMA_desc, descT, */
/* PLASMA_sequence*, sequence, */
/* PLASMA_request*, request); */
/* } */
//plasma_dynamic_sync();
plasma_dynamic_call_6( plasma_psgbcpy_t2bl,
PLASMA_enum, descA.m >= descA.n ? PlasmaUpper : PlasmaLower,
PLASMA_desc, descA,
float*, &(AB[NB]),
int, LDAB,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
plasma_dynamic_sync();
status = sequence->status;
if (status != PLASMA_SUCCESS) {
plasma_error("PLASMA_sgebrd","psgebrd_ge2gb+pzcopy");
return status;
}
#if defined(ENABLE_TIMER)
timeB = PLASMA_Wtime()-timeB;
printf("\n Finish Band red timing= %lf \n",timeB);
#endif
/*=======================================
* END of calling Reduction to BAND
*=======================================*/
/*=======================================
* calling Reduction from BAND to bidiag
*=======================================*/
float *VQ2 = NULL;
float *VP2 = NULL;
float *TAUQ2 = NULL;
float *TAUP2 = NULL;
float *TQ2 = NULL;
float *TP2 = NULL;
int Vblksiz, blkcnt, LDT, LDV;
int WANTZ = 0;
if( jobu == PlasmaNoVec )
WANTZ=0;
else
WANTZ=1;
/* Vblksiz correspond to the blocking used when applying V2 to the matrix U
* it is similar to IB in LAPACK SORMQR.
* blkcnt is the number of diamond or tile of Vs */
/* Note that in case PlamaVec requested, the V2 and T2 are stored by the
* bulgechasing function in a special format:
* for V2s: it store the V2(LDV,Vblksiz) of each diamond in a tile storage meaning
* that V2_1 is stored then V2_2,..., V2_blkcnt.
* blkcnt is the number of diamond.
* */
Vblksiz = min(NB,48);
LDT = Vblksiz;
/* data for U */
if( jobu == PlasmaVec ) {
findVTsiz(MINMN, NB, Vblksiz, &blkcnt, &LDV);
TAUQ2 = (float *) plasma_shared_alloc(plasma, blkcnt*Vblksiz, PlasmaRealFloat);
VQ2 = (float *) plasma_shared_alloc(plasma, LDV*blkcnt*Vblksiz, PlasmaRealFloat);
TQ2 = (float *) plasma_shared_alloc(plasma, LDT*blkcnt*Vblksiz, PlasmaRealFloat);
if ( (TAUQ2 == NULL) || (VQ2 == NULL) || (TQ2 == NULL) ) {
plasma_error("PLASMA_sgebrd", "plasma_shared_alloc() failed");
plasma_shared_free(plasma, TAUQ2);
plasma_shared_free(plasma, VQ2);
plasma_shared_free(plasma, TQ2);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
memset(TAUQ2, 0, blkcnt*Vblksiz*sizeof(float));
memset(VQ2, 0, LDV*blkcnt*Vblksiz*sizeof(float));
memset(TQ2, 0, LDT*blkcnt*Vblksiz*sizeof(float));
}
else {
TAUQ2 = (float *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaRealFloat);
VQ2 = (float *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaRealFloat);
if ( (TAUQ2 == NULL) || (VQ2 == NULL) ) {
plasma_error("PLASMA_sgebrd", "plasma_shared_alloc() failed");
plasma_shared_free(plasma, TAUQ2);
plasma_shared_free(plasma, VQ2);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
memset(TAUQ2, 0, 2*MINMN*sizeof(float));
memset(VQ2, 0, 2*MINMN*sizeof(float));
}
/* data for VT */
if( jobvt == PlasmaVec ) {
findVTsiz(MINMN, NB, Vblksiz, &blkcnt, &LDV);
TAUP2 = (float *) plasma_shared_alloc(plasma, blkcnt*Vblksiz, PlasmaRealFloat);
VP2 = (float *) plasma_shared_alloc(plasma, LDV*blkcnt*Vblksiz, PlasmaRealFloat);
TP2 = (float *) plasma_shared_alloc(plasma, LDT*blkcnt*Vblksiz, PlasmaRealFloat);
if ( (TAUP2 == NULL) || (VP2 == NULL) || (TP2 == NULL) ) {
plasma_error("PLASMA_sgebrd", "plasma_shared_alloc() failed");
plasma_shared_free(plasma, TAUP2);
plasma_shared_free(plasma, VP2);
plasma_shared_free(plasma, TP2);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
memset(TAUP2, 0, blkcnt*Vblksiz*sizeof(float));
memset(VP2, 0, LDV*blkcnt*Vblksiz*sizeof(float));
memset(TP2, 0, LDT*blkcnt*Vblksiz*sizeof(float));
}
else {
TAUP2 = (float *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaRealFloat);
VP2 = (float *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaRealFloat);
if ( (TAUP2 == NULL) || (VP2 == NULL) ) {
plasma_error("PLASMA_sgebrd", "plasma_shared_alloc() failed");
plasma_shared_free(plasma, TAUQ2);
plasma_shared_free(plasma, VQ2);
return PLASMA_ERR_OUT_OF_RESOURCES;
}
memset(TAUP2, 0, 2*MINMN*sizeof(float));
memset(VP2, 0, 2*MINMN*sizeof(float));
}
/*=======================================
* calling bulge chasing
*=======================================*/
#if defined(ENABLE_TIMER)
timeblg = PLASMA_Wtime();
#endif
plasma_parallel_call_16(plasma_psgebrd_gb2bd_v1,
PLASMA_enum, uplo,
int, MINMN,
int, NB,
int, Vblksiz,
float*, AB,
int, LDAB,
float*, VQ2,
float*, TAUQ2,
float*, VP2,
float*, TAUP2,
float*, S,
float*, E,
int, WANTZ,
int, WANTZ,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
/* WARNING: If plasma_psgebrd_gb2bd is implemented through a dynamic call, don't
* forget to synchronize */
plasma_dynamic_sync();
#if defined(ENABLE_TIMER)
timeblg = PLASMA_Wtime()-timeblg;
printf(" Finish Bulge timing= %lf \n" ,timeblg);
#endif
/*=======================================
* END of calling bulge chasing
*=======================================*/
/*=======================================
* generate U from the bulge
*=======================================*/
if (jobu == PlasmaVec){
memset(U, 0, M*LDU*sizeof(float));
/* Initialize U to Identity */
for(i=0; i<M; i++){
U[i+i*LDU] = 1.0;
}
#if defined(ENABLE_TIMER)
timeT = PLASMA_Wtime();
#endif
/* compute T2 */
plasma_static_call_8(plasma_pslarft_blgtrd,
int, MINMN,
int, NB,
int, Vblksiz,
float*, VQ2,
float*, TQ2,
float*, TAUQ2,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeT = PLASMA_Wtime()-timeT;
printf(" Finish compute TU2 timing= %lf \n" ,timeT);
timeaplQ2 = PLASMA_Wtime();
#endif
/* apply Q2 from Left */
plasma_static_call_14(plasma_psormqr_blgtrd,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaNoTrans,
int, MINMN,
int, NB,
int, MINMN,
int, Vblksiz,
int, WANTZ,
float*, VQ2,
float*, TQ2,
float*, TAUQ2,
float*, U,
int, LDU,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeaplQ2 = PLASMA_Wtime()-timeaplQ2;
printf(" Finish compute U2 timing= %lf \n" ,timeaplQ2);
#endif
/*=======================================
* apply Q1 from the reduction to band
*=======================================*/
/* CASE NB>N, Q1 doesn't need to be applied, only bulge chasing has been done */
if( NB < N ){
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeconv1 = PLASMA_Wtime();
#endif
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_sooplap2tile( descU, U, NB, NB, LDU, M, 0, 0, M, M, sequence, request, plasma_desc_mat_free(&(descU)) );
} else {
plasma_siplap2tile( descU, U, NB, NB, LDU, M, 0, 0, M, M, sequence, request);
}
#if defined(ENABLE_TIMER)
timeconv1 = PLASMA_Wtime()-timeconv1;
timeaplQ1 = PLASMA_Wtime();
#endif
/* Accumulate the transformations from the first stage */
if(M<N){
plasma_dynamic_call_7(plasma_psormqr,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaNoTrans,
PLASMA_desc, plasma_desc_submatrix(descA, descA.mb, 0, descA.m-descA.mb, descA.n-descA.nb),
PLASMA_desc, plasma_desc_submatrix(descU, descU.mb, 0, descU.m-descU.mb, descU.n),
PLASMA_desc, plasma_desc_submatrix(descT, descT.mb, 0, descT.m-descT.mb, descT.n-descT.nb),
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
else {
plasma_dynamic_call_7(plasma_psormqr,
PLASMA_enum, PlasmaLeft,
PLASMA_enum, PlasmaNoTrans,
PLASMA_desc, descA,
PLASMA_desc, descU,
PLASMA_desc, descT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeaplQ1 = PLASMA_Wtime()-timeaplQ1;
printf(" Finish compute U1 timing= %lf \n" ,timeaplQ1);
timeconv2 = PLASMA_Wtime();
#endif
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_sooptile2lap( descU, U, NB, NB, LDU, M, sequence, request );
plasma_dynamic_sync();
plasma_desc_mat_free(&descU);
} else {
plasma_siptile2lap( descU, U, NB, NB, LDU, M, sequence, request );
plasma_dynamic_sync();
}
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeconv2 = PLASMA_Wtime()-timeconv2;
printf(" Finish convert U timing= %lf \n" ,timeconv1+timeconv2);
#endif
} /* END of ( NB < N ) */
}
/*=======================================
* END of calling computing U
*=======================================*/
/*=======================================
* generate VT from the bulge
*=======================================*/
if (jobvt == PlasmaVec){
memset(VT, 0, N*LDVT*sizeof(float));
/* Initialize VT to Identity */
for(i=0; i<N; i++){
VT[i+i*LDVT] = 1.0;
}
#if defined(ENABLE_TIMER)
timeT = PLASMA_Wtime();
#endif
/* compute T2 */
plasma_static_call_8(plasma_pslarft_blgtrd,
int, MINMN,
int, NB,
int, Vblksiz,
float*, VP2,
float*, TP2,
float*, TAUP2,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeT = PLASMA_Wtime()-timeT;
printf(" Finish compute TV2 timing= %lf \n" ,timeT);
timeaplQ2 = PLASMA_Wtime();
#endif
/* apply Q2 from Left */
plasma_static_call_14(plasma_psormqr_blgtrd,
PLASMA_enum, PlasmaRight,
PLASMA_enum, PlasmaTrans,
int, MINMN,
int, NB,
int, MINMN,
int, Vblksiz,
int, WANTZ,
float*, VP2,
float*, TP2,
float*, TAUP2,
float*, VT,
int, LDVT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeaplQ2 = PLASMA_Wtime()-timeaplQ2;
printf(" Finish compute V2 timing= %lf \n" ,timeaplQ2);
#endif
/*=======================================
* apply Q1 from the reduction to band
*=======================================*/
/* CASE NB>N, Q1 doesn't need to be applied, only bulge chasing has been done */
if( NB < N ){
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeconv1 = PLASMA_Wtime();
#endif
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_sooplap2tile( descVT, VT, NB, NB, LDVT, N, 0, 0, N, N, sequence, request, plasma_desc_mat_free(&(descVT)) );
} else {
plasma_siplap2tile( descVT, VT, NB, NB, LDVT, N, 0, 0, N, N, sequence, request);
}
#if defined(ENABLE_TIMER)
timeconv1 = PLASMA_Wtime()-timeconv1;
timeaplQ1 = PLASMA_Wtime();
#endif
/* Accumulate the transformations from the first stage */
if(M<N){
plasma_dynamic_call_7(plasma_psormlq,
PLASMA_enum, PlasmaRight,
PLASMA_enum, PlasmaNoTrans,
PLASMA_desc, descA,
PLASMA_desc, descVT,
PLASMA_desc, descT,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
else {
plasma_dynamic_call_7(plasma_psormlq,
PLASMA_enum, PlasmaRight,
PLASMA_enum, PlasmaNoTrans,
PLASMA_desc, plasma_desc_submatrix(descA, 0, descA.nb, descA.m-descA.mb, descA.n-descA.nb),
PLASMA_desc, plasma_desc_submatrix(descVT,0, descVT.nb, descVT.m, descVT.n-descVT.nb),
PLASMA_desc, plasma_desc_submatrix(descT, 0, descT.nb, descT.m-descT.mb, descT.n-descT.nb),
PLASMA_sequence*, sequence,
PLASMA_request*, request);
}
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeaplQ1 = PLASMA_Wtime()-timeaplQ1;
printf(" Finish compute V1 timing= %lf \n" ,timeaplQ1);
timeconv2 = PLASMA_Wtime();
#endif
if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {
plasma_sooptile2lap( descVT, VT, NB, NB, LDVT, N, sequence, request );
plasma_dynamic_sync();
plasma_desc_mat_free(&descVT);
} else {
plasma_siptile2lap( descVT, VT, NB, NB, LDVT, N, sequence, request );
plasma_dynamic_sync();
}
#if defined(ENABLE_TIMER)
plasma_dynamic_sync();
timeconv2 = PLASMA_Wtime()-timeconv2;
printf(" Finish convert VT timing= %lf \n" ,timeconv1+timeconv2);
#endif
} /* END of ( NB < N ) */
}
/*=======================================
* END of calling computing VT
*=======================================*/
#if defined(ENABLE_TIMER)
timeall = PLASMA_Wtime()-timeall;
printf(" Finish full Bidiagonalisation threads %d N %d timeall= %lf \n", plasma->world_size, N, timeall);
#endif
if( jobu == PlasmaVec )
plasma_shared_free(plasma, TQ2);
if( jobvt == PlasmaVec )
plasma_shared_free(plasma, TP2);
plasma_shared_free(plasma, VQ2);
plasma_shared_free(plasma, TAUQ2);
plasma_shared_free(plasma, VP2);
plasma_shared_free(plasma, TAUP2);
plasma_shared_free(plasma, AB);
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.531492712,
"avg_line_length": 39.5331230284,
"ext": "c",
"hexsha": "7fcb7ab70b759eb0e6cbf4ef9f8f8a92b33820e6",
"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/sgebrd.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/sgebrd.c",
"max_line_length": 131,
"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/sgebrd.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 9860,
"size": 37596
} |
#if !defined(THDM_H)
#define THDM_H
#include "SM.h"
#include <complex>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_matrix.h>
#include "CouplingFunctionTypeI.h"
#include "CouplingFunctionTypeII.h"
#include "CouplingFunctionTypeLS.h"
#include "CouplingFunctionTypeFL.h"
using namespace std;
/**
* \mainpage 2HDMC Class documentation
* 2HDMC is a general-purpose calculator for the two-Higgs doublet model.
* It allows parametrization of the Higgs potential in many different ways,
* convenient specification of generic Yukawa sectors, the evaluation of decay
* widths, theoretical constraints and much more.
*/
/**
* @brief Specifies a general two-Higgs doublet model
*
* This class implements a description of a general two-Higgs doublet model
* in terms of the potential parameters and Yukawa couplings necessary for
* a full specification of the model. Several methods are available to set
* the model parameters to various special cases.
*
* From a THDM object, all the couplings between physical states can be
* accessed, including Higgs-fermion, Higgs-Vector, Higgs-Higgs, 3H and 4H
* couplings.
*/
//static int thdmc_set_param(int key, int npara, double *para, double *res);
int thdmc_set_param(int key, double smpara[], double para[], double res[], int slha);
typedef ComplexType (*CFunc_NLO)(double, double, double, double, double, double, double, double, double, double, SM);
ComplexType ZEROCOUPLING(double MHL2, double MHH2, double MHA2, double MHp2, double M2, double beta, double alpha, double m12, double m22, double m32, SM sm);
// For simplicity, even though SVV, SSV and SSS coupling is independent of the Yukawa type, I still use them to indicate the formula.
#define UPID 10
#define DOID 20
#define LEID 30
#define NUID 40
enum NLOSTATUS
{
NLOGOOD = 1,
NOTIMPLEMENT = 0
};
int GetNLOFuncSFF(int S1,int F1,int F2,int type,CFunc_NLO &func);
int GetNLOFuncSFFC(int S1,int F1,int F2,int type,CFunc_NLO &func_PL, CFunc_NLO &func_PR);
int GetNLOFuncSVV(int S1,int V1,int V2,int type,CFunc_NLO &func_gmunu, CFunc_NLO &func_kmuqnu);
int GetNLOFuncSSV(int S1,int S2,int V1,int type,CFunc_NLO &func);
int GetNLOFuncSSS(int S1,int S2,int S3,int type,CFunc_NLO &func);
class THDM {
public:
/**
* @brief Default constructor.
*
* Empty default constructor which does nothing except initialization of this
* THDM object. The model is not specified in any way by using this constructor.
*/
THDM();
// ~THDM();
/**
* @brief Sets the underlying SM
*
* This method can be used to specify the SM parameters which this 2HDM
* is using.
*
* @param sm_in SM object specifying the parameters to use in this 2HDM
*/
void set_SM(SM sm_in);
/**
* @brief Returns the underlying SM
*
* @returns The SM object specifying the parameters used in this 2HDM
*/
SM get_SM();
/**
* @brief Specifies 2HDM using generic potential
*
* This method lets the user specify the 2HDM using a generic basis.
* For details on the basis choices available for the Higgs potential, we
* refer to the complete <a href="http://arxiv.org/abs/0902.0851">manual</a>.
*
* @param lambda1 Value of \f$ \lambda_1 \f$
* @param lambda2 Value of \f$ \lambda_2 \f$
* @param lambda3 Value of \f$ \lambda_3 \f$
* @param lambda4 Value of \f$ \lambda_4 \f$
* @param lambda5 Value of \f$ \lambda_5 \f$
* @param lambda6 Value of \f$ \lambda_6 \f$
* @param lambda7 Value of \f$ \lambda_7 \f$
* @param m12_2 Soft \f$ Z_2 \f$-breaking parameter
* @param tan_beta Ratio of vevs, \f$ \tan\beta=v_2/v_1 \f$
*
* @returns Boolean \a true if all parameters were set correctly, \a false otherwise
*/
bool set_param_gen(double lambda1, double lambda2, double lambda3,
double lambda4, double lambda5, double lambda6,
double lambda7, double m12_2, double tan_beta);
/**
* @brief Specifies 2HDM in the Higgs basis
*
* This method lets the user specify the 2HDM in the Higgs basis \f$ (v_2\equiv 0) \f$.
* For details on the basis choices available for the Higgs potential, we
* refer to the complete <a href="http://arxiv.org/abs/0902.0851">manual</a>.
*
* @param Lambda1 Value of \f$ \Lambda_1 \f$
* @param Lambda2 Value of \f$ \Lambda_2 \f$
* @param Lambda3 Value of \f$ \Lambda_3 \f$
* @param Lambda4 Value of \f$ \Lambda_4 \f$
* @param Lambda5 Value of \f$ \Lambda_5 \f$
* @param Lambda6 Value of \f$ \Lambda_6 \f$
* @param Lambda7 Value of \f$ \Lambda_7 \f$
* @param m_Hp Mass of the charged Higgs
*
* @returns Boolean \a true if all parameters were set correctly, \a false otherwise
*/
bool set_param_higgs(double Lambda1, double Lambda2, double Lambda3,
double Lambda4, double Lambda5, double Lambda6,
double Lambda7, double m_Hp);
/**
* @brief Specifies 2HDM in the hybrid basis of 1507.04281
*
* @param mh Value of light CP-even Higgs mass \f$ m_h \f$
* @param mH Value of heavy CP-even Higgs mass \f$ m_H \f$
* @param cba Mixing parameter \f$ \cos(\beta-\alpha) \f$. Valid range: -1 < cba <= 1.
* @param Z_4 Value of \f$ Z_4 \f$
* @param Z_5 Value of \f$ Z_5 \f$
* @param Z_7 Value of \f$ Z_7 \f$
* @param tanb Ratio of vevs, \f$ \tan\beta=v_2/v_1 \f$
*
* @returns Boolean \a true if all parameters were set correctly, \a false otherwise
*/
bool set_param_hybrid(double mh, double mH, double cba, double Z4,double Z5, double Z7, double tanb);
/**
* @brief Specifies 2HDM in the hybrid basis of 1507.04281, but with sba instead of cba
*
* @param mh Value of light CP-even Higgs mass \f$ m_h \f$
* @param mH Value of heavy CP-even Higgs mass \f$ m_H \f$
* @param sba Mixing parameter \f$ \sin(\beta-\alpha) \f$. Valid range: -1 < cba <= 1.
* @param Z_4 Value of \f$ Z_4 \f$
* @param Z_5 Value of \f$ Z_5 \f$
* @param Z_7 Value of \f$ Z_7 \f$
* @param tanb Ratio of vevs, \f$ \tan\beta=v_2/v_1 \f$
*
* @returns Boolean \a true if all parameters were set correctly, \a false otherwise
*/
bool set_param_hybrid_sba(double mh, double mH, double sba, double Z4,double Z5, double Z7, double tanb);
/**
* @brief Specifies 2HDM using potential from the Higgs Hunter's Guide
*
* This method lets the user specify the 2HDM using the CP-conserving form
* of the potential given by Eq. (4.8) in "The Higgs Hunter's Guide".
* For details on the basis choices available for the Higgs potential, we
* refer to the complete <a href="http://arxiv.org/abs/0902.0851">manual</a>.
*
* @param lambda1 Value of \f$ \lambda_1 \f$
* @param lambda2 Value of \f$ \lambda_2 \f$
* @param lambda3 Value of \f$ \lambda_3 \f$
* @param lambda4 Value of \f$ \lambda_4 \f$
* @param lambda5 Value of \f$ \lambda_5 \f$
* @param lambda6 Value of \f$ \lambda_6 \f$
* @param tan_beta Ratio of vevs, \f$ \tan\beta=v_2/v_1 \f$
*
* @returns Boolean \a true if all parameters were set correctly, \a false otherwise
*/
bool set_param_HHG(double lambda1, double lambda2, double lambda3,
double lambda4, double lambda5, double lambda6,
double tan_beta);
/**
* @brief Specifies 2HDM in the physical basis
*
* This method lets the user specify the 2HDM using the basis of physical
* Higgs masses. For details on the basis choices available for the Higgs
* potential, we refer to the complete <a href="http://arxiv.org/abs/0902.0851">manual</a>.
*
* @param m_h Mass of lightest CP-even Higgs \f$ h \f$
* @param m_H Mass of heavier CP-even Higgs \f$ H \f$
* @param m_A Mass of CP-odd Higgs \f$ A \f$
* @param m_Hp Mass of charged Higgs
* @param sba Mixing parameter \f$ \sin(\beta-\alpha) \f$. NB: Correct sign on \f$ \sin(\beta-\alpha) \f$ must be determined from the condition \f$ \cos(\beta-\alpha) \geq 0 \f$
* @param lambda6 Value of \f$ \lambda_6 \f$ in generic potential
* @param lambda7 Value of \f$ \lambda_7 \f$ in generic potential
* @param m12_2 Soft \f$ Z_2 \f$-breaking parameter
* @param tan_beta Ratio of vevs, \f$ \tan\beta=v_2/v_1 \f$
*
* @returns Boolean \a true if all parameters were set correctly, \a false otherwise
*/
bool set_param_phys(double m_h,double m_H, double m_A, double m_Hp,
double sba, double lambda6, double lambda7,
double m12_2, double tan_beta);
bool set_param_sm(double mh);
/**
* @brief Specifies the 2HDM of the tree-level MSSM
*
* This method lets the user specify a 2HDM with the properties of the tree-level
* MSSM in terms of masses and coupling relations. The Yukawa sector is also
* automatically selected to be of type II.
*
* @param m_A Mass of CP-odd Higgs \f$ A \f$
* @param tan_beta Ratio of vevs, \f$ \tan\beta=v_2/v_1 \f$
*
* @returns Boolean \a true if all parameters were set correctly, \a false otherwise
*/
bool set_MSSM(double m_A, double tan_beta);
/**
* @brief Specifies the 2HDM of the tree-level MSSM + mass corrections to h ("hMSSM")
*
* This method lets the user specify a 2HDM with the properties of the tree-level
* MSSM, with additional mass corrections from the lambda_2 contribution to the (2,2)
* element of the mass matrix. These can be identified as the leading (mt^4) MSSM
* corrections. The Yukawa sector is automatically selected to be of type II.
*
* @param m_h Mass of light CP-even Higgs \f$ h \f$
* @param m_A Mass of CP-odd Higgs \f$ A \f$
* @param tan_beta Ratio of vevs, \f$ \tan\beta=v_2/v_1 \f$
*
* @returns Boolean \a true if all parameters were set correctly, \a false otherwise
*/
bool set_hMSSM(double mh, double mA, double tanb);
/**
* @brief Specifies the 2HDM with one "inert Higgs" doublet
*
* This method lets the user specify a 2HDM with special properties as follows:
* only one of the doublets acquires a vev, there is an exact \f$ Z_2 \f$-symmetry,
* preventing interdoublet mixing, and the doublet without a vev has no Yukawa
* couplings. This results in one doublet being "inert" (or dark). The lightest
* Higgs originating from this doublet is then stable, thus a dark matter candidate.
* The conventions used for specifying the parameters for this model are the same as
* in <a href="http://arxiv.org/abs/0810.3924">arXiv:0810.3924</a>.
*
* @param m_h Mass of "SM-like" Higgs - NB: Changed meaning compared to "physical" basis
* @param m_H Mass of CP-even "inert" Higgs - NB: Changed meaning compared to "physical" basis
* @param m_A Mass of CP-odd "inert" Higgs
* @param m_Hp Mass of charged "inert" Higgs
* @param lambda2 Value of \f$ \lambda_2 \f$ parameter
* @param lambda3 Value of \f$ \lambda_2 \f$ parameter
*
* @returns Boolean \a true if all parameters were set correctly, \a false otherwise
*/
bool set_inert(double m_h,double m_H, double m_A, double m_Hp, double lambda2, double lambda3);
/**
* @brief Returns parameter set in the generic basis
*
* This method returns a consistent set of parameter values describing the
* current model in the generic basis.
*
* @param lambda1 Returned value of \f$ \lambda_1 \f$
* @param lambda2 Returned value of \f$ \lambda_2 \f$
* @param lambda3 Returned value of \f$ \lambda_3 \f$
* @param lambda4 Returned value of \f$ \lambda_4 \f$
* @param lambda5 Returned value of \f$ \lambda_5 \f$
* @param lambda6 Returned value of \f$ \lambda_6 \f$
* @param lambda7 Returned value of \f$ \lambda_7 \f$
* @param m12_2 Returned value of \f$ m_{12}^2 \f$
* @param tan_beta Returned value of \f$ \tan\beta \f$
*/
void get_param_gen(double &lambda1, double &lambda2, double &lambda3,
double &lambda4, double &lambda5, double &lambda6,
double &lambda7, double &m12_2, double &tan_beta);
/**
* @brief Returns parameter set in the Higgs basis
*
* This method returns a consistent set of parameter values describing the
* current model in the Higgs basis.
*
* @param Lambda1 Returned value of \f$ \Lambda_1 \f$
* @param Lambda2 Returned value of \f$ \Lambda_2 \f$
* @param Lambda3 Returned value of \f$ \Lambda_3 \f$
* @param Lambda4 Returned value of \f$ \Lambda_4 \f$
* @param Lambda5 Returned value of \f$ \Lambda_5 \f$
* @param Lambda6 Returned value of \f$ \Lambda_6 \f$
* @param Lambda7 Returned value of \f$ \Lambda_7 \f$
* @param m_Hp Returned value of the charged Higgs mass
*/
void get_param_higgs(double &Lambda1, double &Lambda2, double &Lambda3,
double &Lambda4, double &Lambda5, double &Lambda6,
double &Lambda7, double &m_Hp);
void get_param_hybrid(double &m_h, double &m_H, double &sba,
double &Z4, double &Z5, double &Z7, double &tan_beta);
/**
* @brief Returns parameter set in Higgs Hunter's Guide basis
*
* This method returns a consistent set of parameter values describing the
* current model in the basis used in the Higgs Hunter's Guide. NB: The use
* of this method assumes \f$ \lambda_6=\lambda_7=0 \f$ in the generic basis.
*
* @param lambda1 Returned value of \f$ \lambda_1 \f$
* @param lambda2 Returned value of \f$ \lambda_2 \f$
* @param lambda3 Returned value of \f$ \lambda_3 \f$
* @param lambda4 Returned value of \f$ \lambda_4 \f$
* @param lambda5 Returned value of \f$ \lambda_5 \f$
* @param lambda6 Returned value of \f$ \lambda_6 \f$
* @param tan_beta Returned value of \f$ \tan\beta \f$
*/
void get_param_HHG(double &lambda1, double &lambda2, double &lambda3,
double &lambda4, double &lambda5, double &lambda6,
double &tan_beta);
/**
* @brief Returns parameter set in physical basis
*
* This method returns a consistent set of parameter values describing the
* current model in the "physical" basis.
*
* @param m_h Returned value of lightest CP-even Higgs mass
* @param m_H Returned value of heaviest CP-even Higgs mass
* @param m_A Returned value of CP-odd Higgs mass
* @param m_Hp Returned value of charged Higgs mass
* @param sba Returned value of \f$ \sin(\beta-\alpha) \f$
* @param lambda6 Returned value of \f$ \lambda_6 \f$
* @param lambda7 Returned value of \f$ \lambda_7 \f$
* @param m12_2 Returned value of \f$ m_{12}^2 \f$
* @param tan_beta Returned value of \f$ \tan\beta \f$
*/
void get_param_phys(double &m_h,double &m_H, double &m_A, double &m_Hp,
double &sba, double &lambda6, double &lambda7,
double &m12_2, double &tan_beta);
/**
* @brief Changes basis for the Higgs doublets
*
* This method performs a change of basis, changing the value of
* \f$ \tan\beta \f$. This results in a recalculation of all the other
* potential parameters, but the physical couplings remain unchanged.
* Yukawa couplings are not modified.
*
* @param tan_beta Value of \f$ \tan\beta \f$ to use in the new basis
*/
void recalc_tan_beta(double tan_beta);
/**
* @brief Returns the mass of physical Higgs bosons
*
* This method returns the mass of a physical Higgs Boson. The numbering
* convention corresponds to (1,2,3,4 = h,H,A,H+) where always \f$ m_h < m_H \f$.
*
* @param h Index of Higgs boson
*
* @returns The mass of Higgs boson \a h
*/
double get_hmass(int h);
/**
* @brief Returns invariant \f$ \sin(\beta-\alpha) \f$
*
* @returns Value of \f$ \sin(\beta-\alpha) \f$ in model
*/
double get_sba();
/**
* @brief Returns invariant \f$ \cos(\beta-\alpha) \f$
*
* @returns Value of \f$ \cos(\beta-\alpha) \f$ in model
*/
double get_cba();
/**
* @brief Higgs coupling \f$ q_{ki} \f$ factors
*
* This method returns the invariants \f$ q_{ki} \f$ (<a href="
* http://arxiv.org/abs/hep-ph/0602242">hep-ph/0602242</a>) which are used
* for the triple and quartic Higgs couplings.
*
* @param k Higgs index (1--4)
* @param i Coupling index (1--2)
*
* @returns The value of the coefficient \f$ q_{ki} \f$
*/
complex <double> get_qki(int k, int i);
/**
* @brief Initializes complete Yukawa sector to a specific type
*
* This method is used to specify a type of Yukawa sector for the 2HDM.
* The types (1-4) implemented follow the convention of <a href=""></a>.
*
* @param type Type of Yukawa sector (1--4)
*/
void set_yukawas_type(int type);
/**
* @brief Initializes and sets diagonal Yukawa couplings for down-type quarks
*
* This method initializes and sets the Yukawa couplings for the down-type quarks.
* The diagonal matrix \f$ \kappa^D \f$ is automatically specified to comply with
* the quark pole masses, whereas the diagonal elements of \f$ \rho^D \f$ can be
* specified as input.
*
* @param rhod Diagonal element of \f$ \rho^D \f$ for the \f$ d \f$ quark
* @param rhos Diagonal element of \f$ \rho^D \f$ for the \f$ s \f$ quark
* @param rhob Diagonal element of \f$ \rho^D \f$ for the \f$ b \f$ quark
*
* @see set_yukawas_up, set_yukawas_lepton
*/
void set_yukawas_down(double rhod, double rhos, double rhob);
/**
* @brief Initializes and sets diagonal Yukawa couplings for up-type quarks
*
* This method initializes and sets the Yukawa couplings for the up-type quarks.
* The diagonal matrix \f$ \kappa^U \f$ is automatically specified to comply with
* the quark pole masses, whereas the diagonal elements of \f$ \rho^U \f$ can be
* specified as input.
*
* @param rhou Diagonal element of \f$ \rho^U \f$ for the \f$ u \f$ quark
* @param rhoc Diagonal element of \f$ \rho^U \f$ for the \f$ c \f$ quark
* @param rhot Diagonal element of \f$ \rho^U \f$ for the \f$ t \f$ quark
*
* @see set_yukawas_down, set_yukawas_lepton
*/
void set_yukawas_up(double rhou, double rhoc, double rhot);
/**
* @brief Initializes and sets diagonal Yukawa couplings for the charged leptons
*
* This method initializes and sets the Yukawa couplings for the leptons.
* The diagonal matrix \f$ \kappa^L \f$ is automatically specified to comply with
* the lepton pole masses, whereas the diagonal element of \f$ \rho^L \f$ can be
* specified as input.
*
* @param rhoe Diagonal element of \f$ \rho^L \f$ for \f$ e \f$
* @param rhomu Diagonal element of \f$ \rho^L \f$ for \f$ \mu \f$
* @param rhotau Diagonal element of \f$ \rho^L \f$ for \f$ \tau \f$
*
* @see set_yukawas_down, set_yukawas_up
*/
void set_yukawas_lepton(double rhoe, double rhomu, double rhotau);
/**
* @brief Initializes and sets Yukawa couplings for down-type quarks
*
* This method initializes and sets the Yukawa couplings for the down-type quarks.
* The diagonal matrix \f$ \kappa^D \f$ is automatically specified to comply with
* the quark pole masses, whereas the symmetric matrix \f$ \rho^D \f$ is given by
* the six elements specified as input.
*
* @param rho11 Yukawa coupling \f$ \rho^D_{dd} \f$
* @param rho22 Yukawa coupling \f$ \rho^D_{ss} \f$
* @param rho33 Yukawa coupling \f$ \rho^D_{bb} \f$
* @param rho12 Yukawa coupling \f$ \rho^D_{ds} \f$
* @param rho13 Yukawa coupling \f$ \rho^D_{db} \f$
* @param rho23 Yukawa coupling \f$ \rho^D_{sb} \f$
*/
void set_yukawas_down(double rho11,double rho22,double rho33,double rho12,double rho13,double rho23);
/**
* @brief Initializes and sets Yukawa couplings for up-type quarks
*
* This method initializes and sets the Yukawa couplings for the up-type quarks.
* The diagonal matrix \f$ \kappa^U \f$ is automatically specified to comply with
* the quark pole masses, whereas the symmetric matrix \f$ \rho^U \f$ is given by
* the six elements specified as input.
*
* @param rho11 Yukawa coupling \f$ \rho^U_{uu} \f$
* @param rho22 Yukawa coupling \f$ \rho^U_{cc} \f$
* @param rho33 Yukawa coupling \f$ \rho^U_{tt} \f$
* @param rho12 Yukawa coupling \f$ \rho^U_{uc} \f$
* @param rho13 Yukawa coupling \f$ \rho^U_{ut} \f$
* @param rho23 Yukawa coupling \f$ \rho^U_{ct} \f$
*/
void set_yukawas_up(double rho11,double rho22,double rho33,double rho12,double rho13,double rho23);
/**
* @brief Initializes and sets Yukawa couplings for leptons
*
* This method initializes and sets the Yukawa couplings for the leptons.
* The diagonal matrix \f$ \kappa^L \f$ is automatically specified to comply with
* the lepton masses, whereas the symmetric matrix \f$ \rho^L \f$ is given by
* the six elements specified as input.
*
* @param rho11 Yukawa coupling \f$ \rho^L_{ee} \f$
* @param rho22 Yukawa coupling \f$ \rho^L_{\mu\mu} \f$
* @param rho33 Yukawa coupling \f$ \rho^L_{\tau\tau} \f$
* @param rho12 Yukawa coupling \f$ \rho^L_{e\mu} \f$
* @param rho13 Yukawa coupling \f$ \rho^L_{e\tau} \f$
* @param rho23 Yukawa coupling \f$ \rho^L_{\mu\tau} \f$
*/
void set_yukawas_lepton(double rho11,double rho22,double rho33,double rho12,double rho13,double rho23);
/**
* @brief Initializes and sets Yukawa couplings for the inert 2HDM
*
* This method initializes and sets the Yukawa couplings for the "inert"
* model. That means there are no Yukawa couplings of any type, except what
* is necessary for the mass terms, i.e. all \f$ \rho = 0 \f$.
*/
void set_yukawas_inert();
/**
* @brief Returns diagonal elements of Yukawa matrix for down-type quarks
*
* @param rhod Returned value of \f$ \rho^D_{dd} \f$
* @param rhos Returned value of \f$ \rho^D_{ss} \f$
* @param rhob Returned value of \f$ \rho^D_{bb} \f$
*/
void get_yukawas_down(double &rhod, double &rhos, double &rhob);
/**
* @brief Returns diagonal elements of Yukawa matrix for up-type quarks
*
* @param rhou Returned value of \f$ \rho^U_{uu} \f$
* @param rhoc Returned value of \f$ \rho^U_{cc} \f$
* @param rhot Returned value of \f$ \rho^U_{tt} \f$
*/
void get_yukawas_up(double &rhou, double &rhoc, double &rhot);
/**
* @brief Returns diagonal elements of Yukawa matrix for leptons
*
* @param rhoe Returned value of \f$ \rho^L_{ee} \f$
* @param rhomu Returned value of \f$ \rho^L_{\mu\mu} \f$
* @param rhotau Returned value of \f$ \rho^L_{\tau\tau} \f$
*/
void get_yukawas_lepton(double &rhoe, double &rhomu, double &rhotau);
void get_kappa_down(double &kd, double &ks, double &kb);
void get_kappa_up(double &ku, double &kc, double &kt);
void get_kappa_lepton(double &ke, double &kmu, double &ktau);
void get_kappa_down(double mu, double &kd, double &ks, double &kb);
void get_kappa_up(double mu, double &ku, double &kc, double &kt);
void get_kappa_lepton(double mu, double &ke, double &kmu, double &ktau);
void get_rho_down(double mu, double &rd, double &rs, double &rb);
void get_rho_up(double mu, double &ru, double &rc, double &rt);
void get_rho_lepton(double mu, double &re, double &rmu, double &rtau);
/**
* @brief Returns Yukawa matrix for down-type quarks
*
* @param rho_D_out Returned Yukawa matrix \f$ \rho^D \f$
*/
void get_yukawas_down(gsl_matrix *rho_D_out);
/**
* @brief Returns Yukawa matrix for up-type quarks
*
* @param rho_U_out Returned Yukawa matrix \f$ \rho^U \f$
*/
void get_yukawas_up(gsl_matrix *rho_U_out);
/**
* @brief Returns Yukawa matrix for leptons
*
* @param rho_L_out Returned Yukawa matrix \f$ \rho^L \f$
*/
void get_yukawas_lepton(gsl_matrix *rho_L_out);
/**
* @brief Couplings of Higgses to down-type fermions
*
* Calculates the coupling \f$ hdd \f$ between one physical Higgs state, specified
* by \a h, and two down-type quarks \a f1 and \a f2.
*
* @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)
* @param f1 First fermion (1,2,3 = d,s,b)
* @param f2 Second fermion (1,2,3 = d,s,b)
* @param cs Returned (complex) value for scalar coupling
* @param cp Returned (complex) value for pseudoscalar coupling
*/
void get_coupling_hdd(int h,int f1,int f2,complex <double> &cs, complex <double> &cp);
void get_coupling_hdd_NLO(int h,int f1,int f2,complex <double> &cs, complex <double> &cp);
/**
* @brief Couplings of Higgses to up-type fermions
*
* Calculates the coupling \f$ huu \f$ between one physical Higgs state, specified
* by \a h, and two up-type quarks \a f1 and \a f2.
*
* @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)
* @param f1 First fermion (1,2,3 = u,c,t)
* @param f2 Second fermion (1,2,3 = u,c,t)
* @param cs Returned (complex) value for scalar coupling
* @param cp Returned (complex) value for pseudoscalar coupling
*/
void get_coupling_huu(int h,int f1,int f2,complex <double> &cs, complex <double> &cp);
void get_coupling_huu_NLO(int h,int f1,int f2,complex <double> &cs, complex <double> &cp);
/**
* @brief Couplings of Higgses to mixed type fermions
*
* Calculates the coupling \f$ hdu \f$ between one physical Higgs state, specified
* by \a h (only relevant one is charged Higgs), and two quarks \a f1 and \a f2.
*
* @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)
* @param d Down-type fermion (1,2,3 = d,s,b)
* @param u Up-type fermion (1,2,3 = u,c,t)
* @param cs Returned (complex) value for scalar coupling
* @param cp Returned (complex) value for pseudoscalar coupling
*/
void get_coupling_hdu(int h,int d,int u,complex <double> &cs, complex <double> &cp);
void get_coupling_hdu_NLO(int h,int d,int u,complex <double> &cs, complex <double> &cp);
/**
* @brief Couplings of Higgses to charged leptons
*
* Calculates the coupling \f$ hll \f$ between one physical Higgs state, specified
* by \a h, and two leptons \a f1 and \a f2.
*
* @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)
* @param f1 First fermion (1,2,3 = \f$ e,\mu,\tau \f$)
* @param f2 Second fermion (1,2,3 = \f$ e,\mu,\tau \f$)
* @param cs Returned (complex) value for scalar coupling
* @param cp Returned (complex) value for pseudoscalar coupling
*/
void get_coupling_hll(int h,int f1,int f2,complex <double> &cs, complex <double> &cp);
void get_coupling_hll_NLO(int h,int f1,int f2,complex <double> &cs, complex <double> &cp);
/**
* @brief Couplings of Higgses to mixed leptons
*
* Calculates the coupling \f$ hl\nu_l \f$ between one physical Higgs state, specified
* by \a h (only relevant one is charged Higgs), and two leptons \a f1 and \a f2.
*
* @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)
* @param l Charged lepton (1,2,3 = \f$ e,\mu,\tau \f$)
* @param n Neutrino (1,2,3 = \f$ \nu_e,\nu_\mu,\nu_\tau \f$)
* @param cs Returned (complex) value for scalar coupling
* @param cp Returned (complex) value for pseudoscalar coupling
*/
void get_coupling_hln(int h,int l,int n,complex <double> &cs, complex <double> &cp);
void get_coupling_hln_NLO(int h,int l,int n,complex <double> &cs, complex <double> &cp);
/**
* @brief Couplings of Higgses to pairs of vector bosons
*
* Calculates the coupling \f$ hV_1 V_2 \f$ between one physical Higgs state, specified
* by \a h , and two vector bosons \a v1 and \a v2. NB: Neutral Higgses have no coupling
* to photons implemented, but the loop mediated decays \f$ h\to \gamma \gamma \f$ can
* nevertheless be calculated using the DecayTable class. Conventions are according to hep-ph/0602242.
*
* @param v1 Index of first vector boson (1,2,3 = \f$ \gamma,Z,W^+ \f$)
* @param v2 Index of second vector boson (1,2,3 = \f$ \gamma,Z,W^+ \f$)
* @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)
* @param c Returned (complex) value for coupling
*/
void get_coupling_vvh(int v1,int v2,int h,complex <double> &c);
void get_coupling_vvh_NLO(int v1,int v2,int h,complex <double> &c_gmunu,complex <double> &c_kmuqnu);
/**
* @brief Couplings of vector bosons to pairs of Higgses
*
* Calculates the coupling \f$ Vh_1 h_2 \f$ between two physical Higgs states, specified
* by \a h1 and \a h2, and one vector boson \a v. Conventions are according to hep-ph/0602242.
*
* @param h1 Index of first Higgs boson (1,2,3,4 = h,H,A,H+)
* @param h2 Index of second Higgs boson (1,2,3,4 = h,H,A,H+)
* @param v Index of vector boson (1,2,3 = \f$ \gamma,Z,W^+ \f$)
* @param c Returned (complex) value for coupling
*/
void get_coupling_vhh(int v,int h1,int h2,complex <double> &c);
void get_coupling_vhh_NLO(int v,int h1,int h2,complex <double> &c);
/**
* @brief Triple Higgs couplings
*
* Calculates the coupling \f$ h_1 h_2 h_3 \f$ between three physical Higgs states.
* Conventions are according to hep-ph/0602242
*
* @param h1 Index of first Higgs boson (1,2,3,4 = h,H,A,H+)
* @param h2 Index of second Higgs boson (1,2,3,4 = h,H,A,H+)
* @param h3 Index of third Higgs boson (1,2,3,4 = h,H,A,H+)
* @param c Returned (complex) value for coupling
*/
void get_coupling_hhh(int h1,int h2,int h3,complex <double> &c);
void get_coupling_hhh_NLO(int h1,int h2,int h3,complex <double> &c);
/**
* @brief Couplings of two vector bosons and two Higgses
*
* Calculates the coupling \f$ V_1 V_2 h_1 h_2 \f$ between two vector bosons and
* two physical Higgs states. Conventions are according to hep-ph/0602242
*
* @param v1 Index of first vector boson (1,2,3 = \f$ \gamma,Z,W^+ \f$)
* @param v2 Index of second vector boson (1,2,3 = \f$ \gamma,Z,W^+ \f$)
* @param h1 Index of first Higgs boson (1,2,3,4 = h,H,A,H+)
* @param h2 Index of second Higgs boson (1,2,3,4 = h,H,A,H+)
* @param c Returned (complex) value for coupling
*/
void get_coupling_vvhh(int v1,int v2,int h1,int h2,complex <double> &c);
/**
* @brief Quartic Higgs couplings
*
* Calculates the coupling \f$ h_1 h_2 h_3 h_4 \f$ between four physical Higgs states.
* Conventions are according to hep-ph/0602242
*
* @param h1 Index of first Higgs boson (1,2,3,4 = h,H,A,H+)
* @param h2 Index of second Higgs boson (1,2,3,4 = h,H,A,H+)
* @param h3 Index of third Higgs boson (1,2,3,4 = h,H,A,H+)
* @param h4 Index of fourth Higgs boson (1,2,3,4 = h,H,A,H+)
* @param c Returned (complex) value for coupling
*/
void get_coupling_hhhh(int h1,int h2,int h3,int h4,complex <double> &c);
/**
* @brief Calculates tree-level unitarity constraints
*
* This method calculates the eigenvalues of the S-matrix for Higgs-Higgs scattering
* as defined in <a href="http://xxx.lanl.gov/abs/hep-ph/0508020">hep-ph/0508020</a>.
*
* @returns Value of largest eigenvalue
*/
double calc_unitarity();
/**
* @brief Checks tree-level unitarity constraints
*
* This method checks whether the parameters of the Higgs potential results
* in an S-matrix for Higgs-Higgs scattering that fullfills tree-level unitarity,
* as discussed in <a href="http://xxx.lanl.gov/abs/hep-ph/0508020">hep-ph/0508020</a>.
*
* @param unitarity_limit optional value to be used for unitarity limit (default = \f$ 16\pi \f$)
*
* @returns Boolean \a true if the unitarity constraint is satisfied, \a false otherwise
*/
bool check_unitarity(double unitarity_limit = 16*M_PI);
/**
* @brief Calculates largest quartic Higgs coupling
*
* This method calculates all the quartic Higgs boson couplings and returns the largest one as well as the indices of the four Higgs bosons
*
* @param gmax Returned (complex) value for coupling
* @param imax Returned index of first Higgs boson (1,2,3,4 = h,H,A,H+)
* @param jmax Returned index of second boson (1,2,3,4 = h,H,A,H+)
* @param kmax Returned index of third boson (1,2,3,4 = h,H,A,H+)
* @param lmax Returned index of fourth boson (1,2,3,4 = h,H,A,H+)
*/
void calc_perturbativity(complex <double> &gmax,int &imax,int &jmax,int &kmax,int &lmax);
/**
* @brief Checks perturbativity
*
* This method checks whether the couplings of the Higgs and Gauge bosons fullfills perturbativity
*
* @param perturbativity_limit optional value to be used for perturbativity limit (default = \f$ 4\pi \f$)
*
* @returns Boolean \a true if the perturbativity constraint is satisfied, \a false otherwise
*/
bool check_perturbativity(double perturbativity_limit = 4*M_PI);
/**
* @brief Checks the stability of the Higgs potential
*
* This method checks whether the Higgs potential is stable, i.e. if no
* directions exist in field space for which \f$ V\to -\infty \f$ for large
* values of the fields. This is done through a combination of analytical and numerical
* algorithms, depending on the generality of the specified potential.
*
* @returns Boolean \a true if the potential is deemed stable, \a false otherwise
*/
bool check_stability();
/**
* @brief Prints the potential parameters in the generic basis to stdout
*/
void print_param_gen();
/**
* @brief Prints the potential parameters in the Higgs basis to stdout
*/
void print_param_higgs();
/**
* @brief Prints the potential parameters in the hybrid basis to stdout
*/
void print_param_hybrid();
/**
* @brief Prints the potential parameters in the physical basis to stdout
*/
void print_param_phys();
/**
* @brief Prints the potential parameters in the Higgs Hunter's Guide basis to stdout
*/
void print_param_HHG();
/**
* @brief Prints the Yukawa matrices to stdout
*/
void print_yukawas();
void print_hdecay();
/**
* @brief Reads the 2HDM parameters from a LesHouches compliant file
*
* This method reads the parameters necessary to specify the 2HDM (and the %SM)
* from a file complying with the LesHouches standard. There are several options
* for how to prepare this file (see <a href="http://arxiv.org/abs/0902.0851">manual</a> for details,
* or the code distribution for examples).
*
* @param file The name of the file to read
*
* @returns Boolean \a true if the file could be opened and read correctly AND
* a 2HDM was correctly specified in the file, \a false otherwise
*/
bool read_LesHouches(const char* file);
/**
* @brief Writes output in a LesHouches compliant file format
*
* This method writes the potential parameters and other selected output to
* a specified file in LesHouches-compliant file format which can then be
* further processed by other codes.
*
* @param file The name of the file which is to be written
* @param fulldecay If \a true, decay modes of the Higgs bosons in LesHouches
* format are written to the file
* @param couplings If \a true, all couplings (> 200 values) for the Higgs bosons
* are written to the file. Should be used when supplying input
* for MadGraph/MadEvent 2HDMC model
* @param qcd_on Turns QCD corrections on or off, default is on. Should be
* turned off when supplying input for MadGraph/MadEvent 2HDMC model
*/
void write_LesHouches(const char* file, bool fulldecay, bool couplings, bool qcd_on=true, bool HBHS=true);
void write_model(const char* file);
double get_alpha();
/**
* @brief Small value
*
* Minimum value used for widths, branching ratios etc. to determine when
* something should be considered zero.
*/
const static double EPS = 1E-15;
private:
double lambda[8];
double beta;
double m22_2;
double sinba;
bool params_set;
double v2;
gsl_matrix *kappa_D;
gsl_matrix *kappa_U;
gsl_matrix *kappa_L;
gsl_matrix *rho_D;
gsl_matrix *rho_U;
gsl_matrix *rho_L;
gsl_matrix *rho_N;
int yukawas_type;
static bool first_run;
const static char *version;
SM sm;
void init();
double get_m12_2();
void set_kappa();
void set_kappa_D();
void set_kappa_U();
void set_kappa_L();
void print_info();
// Added by Y.Wu
bool Updated;
bool HpmUpdated;
double L_MHL2, L_MHH2, L_MHA2, L_MHP2;
double L_MHL, L_MHH, L_MHA, L_MHP, L_sba, L_L6, L_L7, L_M122, L_tb;
double L_beta, L_alp;
double L_M2;
gsl_matrix *rho_D_NLO;
gsl_matrix *rho_U_NLO;
gsl_matrix *RD_NLO;// = gsl_matrix_alloc(3,3);
gsl_matrix *RU_NLO;// = gsl_matrix_alloc(3,3);
// To save time, we can first check `Updated` to see if we need to rerun this function
void store_param_phys();
// void store_Hpmff_Couplings();
};
#endif
| {
"alphanum_fraction": 0.673050992,
"avg_line_length": 38.9068522484,
"ext": "h",
"hexsha": "7e063ee43f14cfe0f2eeed4d814a64c6d4bc91e3",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-11-27T14:59:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-11-27T14:59:29.000Z",
"max_forks_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "shiggs90/2HDMC-NLO-master-wei",
"max_forks_repo_path": "src/THDM.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb",
"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": "shiggs90/2HDMC-NLO-master-wei",
"max_issues_repo_path": "src/THDM.h",
"max_line_length": 179,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "76de26638d30e2840bbb6c680e4108b81a2a8feb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "shiggs90/2HDMC-NLO-master-wei",
"max_stars_repo_path": "src/THDM.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 11642,
"size": 36339
} |
/*
* projcl_run.c
* Magic Maps
*
* Created by Evan Miller on 2/12/11.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
*/
#include <projcl/projcl.h>
#include <projcl/projcl_warp.h>
#include "projcl_run.h"
#include "projcl_kernel.h"
#include "projcl_util.h"
#include "projcl_spheroid.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#endif
#ifdef __linux__
#include <cblas.h>
typedef int __CLPK_integer;
typedef double __CLPK_doublereal;
extern int dgetrf_(__CLPK_integer *, __CLPK_integer *, __CLPK_doublereal *, __CLPK_integer *, __CLPK_integer *, __CLPK_integer *);
extern int dgetri_(__CLPK_integer *, __CLPK_doublereal *, __CLPK_integer *, __CLPK_integer *, __CLPK_doublereal *, __CLPK_integer *, __CLPK_integer *);
#endif
#define EPS7 1.e-7
#define SEC_TO_RAD 4.84813681109535993589914102357e-6
static cl_int pl_enqueue_kernel_albers_equal_area(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count);
static cl_int pl_enqueue_kernel_american_polyconic(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count);
static cl_int pl_enqueue_kernel_lambert_azimuthal_equal_area(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count);
static cl_int pl_enqueue_kernel_lambert_conformal_conic(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count);
static cl_int pl_enqueue_kernel_mercator(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count);
static cl_int pl_enqueue_kernel_oblique_stereographic(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count);
static cl_int pl_enqueue_kernel_robinson(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count);
static cl_int pl_enqueue_kernel_transverse_mercator(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count);
static cl_int pl_enqueue_kernel_winkel_tripel(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count);
struct pl_projection_info {
PLProjection proj;
char name[80];
cl_int (*func)(PLContext *pl_ctx,
cl_kernel kernel,
PLProjectionParams *params,
cl_mem xy_in,
cl_mem xy_out,
size_t count);
};
static struct pl_projection_info _pl_projection_info[] = {
{
.proj = PL_PROJECT_ALBERS_EQUAL_AREA,
.name = "albers_equal_area",
.func = &pl_enqueue_kernel_albers_equal_area,
},
{
.proj = PL_PROJECT_AMERICAN_POLYCONIC,
.name = "american_polyconic",
.func = &pl_enqueue_kernel_american_polyconic,
},
{
.proj = PL_PROJECT_LAMBERT_AZIMUTHAL_EQUAL_AREA,
.name = "lambert_azimuthal_equal_area",
.func = &pl_enqueue_kernel_lambert_azimuthal_equal_area,
},
{
.proj = PL_PROJECT_LAMBERT_CONFORMAL_CONIC,
.name = "lambert_conformal_conic",
.func = &pl_enqueue_kernel_lambert_conformal_conic,
},
{
.proj = PL_PROJECT_MERCATOR,
.name = "mercator",
.func = &pl_enqueue_kernel_mercator,
},
{
.proj = PL_PROJECT_OBLIQUE_STEREOGRAPHIC,
.name = "oblique_stereographic",
.func = &pl_enqueue_kernel_oblique_stereographic,
},
{
.proj = PL_PROJECT_ROBINSON,
.name = "robinson",
.func = &pl_enqueue_kernel_robinson,
},
{
.proj = PL_PROJECT_TRANSVERSE_MERCATOR,
.name = "transverse_mercator",
.func = &pl_enqueue_kernel_transverse_mercator,
},
{
.proj = PL_PROJECT_WINKEL_TRIPEL,
.name = "winkel_tripel",
.func = &pl_enqueue_kernel_winkel_tripel,
}
};
struct pl_datum_info {
double dx;
double dy;
double dz;
double ex;
double ey;
double ez;
double ppm;
};
/* Source: "WGS 84 Implementation Manual" */
static struct pl_datum_info pl_datum_params[] = {
/* Dx Dy Dz Ex Ey Ez m */
{ /* PL_DATUM_WGS_84 */
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_WGS_72 */
0.0, 0.0, 4.5, 0.0, 0.0, -0.554, 0.22 },
{ /* PL_DATUM_ED_50 */
-87.0, -98.0, -121.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_ED_79 */
-86.0, -98.0, -119.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_ED_87 */
-82.5, -91.7, -117.7, 0.1338, -0.0625, -0.047, 0.045 },
{ /* PL_DATUM_AUSTRIA_NS */
595.6, 87.3, 473.3, 4.7994, 0.0671, 5.7850, 2.555 },
{ /* PL_DATUM_BELGIUM_50 */
-55.0, 49.0, -158.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_BERNE_1873 */
649.0, 9.0, 376.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_CH_1903 */
660.1, 13.1, 369.2, 0.8048, 0.5777, 0.9522, 5.660 },
{ /* PL_DATUM_DANISH_GI_1934 */
662.0, 18.0, 734.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_NOUV_TRIG_DE_FRANCE_GREENWICH */
-168.0, -60.0, 320.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_NOUV_TRIG_DE_FRANCE_PARIS */
-168.0, -60.0, 320.0, 0.0, 0.0, 8414.03, 0.0 },
{ /* PL_DATUM_POTSDAM */
587.0, 16.0, 393.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_GGRS_87 */
199.6, -75.1, -246.3, 0.0202, 0.0034, 0.0135, -0.015 },
{ /* PL_DATUM_HJORSEY_55 */
-73.0, 46.0, -86.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_IRELAND_65 */
506.0, -122.0, 611.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_ITALY_1940 */
-133.0, -50.0, 97.0, 0.0, 0.0, 44828.40, 0.0 },
{ /* PL_DATUM_NOUV_TRIG_DE_LUX */
-262.0, 75.0, 25.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_NETHERLANDS_1921 */
719.0, 47.0, 640.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_OSGB_36 */
375.0, -111.0, 431.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_PORTUGAL_DLX */
504.1, -220.9, 563.0, 0.0, 0.0, -0.554, 0.220 },
{ /* PL_DATUM_PORTUGAL_1973 */
227.0, 97.5, 35.4, 0.0, 0.0, -0.554, 0.220 },
{ /* PL_DATUM_RNB_72 */
-104.0, 80.0, -75.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_RT_90 */
424.3, -80.5, 613.1, 4.3965, -1.9866, 5.1846, 0.0 },
{ /* PL_DATUM_NAD_27 */
-8.0, 160.0, 176.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_NAD_83 */
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
{ /* PL_DATUM_ETRS_89 */
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }
};
struct pl_matrix {
double elements[4][4];
};
static struct pl_matrix pl_affine_transform_make(
double Rx, double Ry, double Rz, double M,
double Dx, double Dy, double Dz) {
/* store in column-major order */
struct pl_matrix matrix = {
.elements = {
{ M, M * Rz, -M * Ry, 0.f },
{-M * Rz, M, M * Rx, 0.f },
{ M * Ry, -M * Rx, M, 0.f },
{ Dx, Dy, Dz, 1.f }
}
};
return matrix;
}
static const char *_pl_proj_name(PLProjection proj) {
int i=0;
const char *name = NULL;
for (i=0; i<sizeof(_pl_projection_info)/sizeof(_pl_projection_info[0]); i++) {
if (_pl_projection_info[i].proj == proj) {
name = _pl_projection_info[i].name;
break;
}
}
return name;
}
static double _pl_mlfn(double phi, double sphi, double cphi, double *en) {
cphi *= sphi;
sphi *= sphi;
return(en[0] * phi - cphi * (en[1] + sphi*(en[2] + sphi*(en[3] + sphi*en[4]))));
}
static double _pl_qsfn(double sinphi, double e, double one_es) {
double con = e * sinphi;
return (one_es * (sinphi / (1.0 - con * con) - (.5 / e) * (log1p(-con) - log1p(con))));
}
static double _pl_msfn(double sinphi, double cosphi, double es) {
return (cosphi / sqrt(1.0 - es * sinphi * sinphi));
}
static double _pl_tsfn(double phi, double sinphi, double e) {
double con = e * sinphi;
return (tan(.5 * (M_PI_2 - phi)) /
pow((1.0 - con) / (1.0 + con), .5 * e));
}
static cl_int _pl_set_projection_kernel_args(PLContext *ctx, cl_kernel kernel,
cl_mem xy_in, cl_mem xy_out, size_t count, PLSpheroidInfo *info, int *offset_ptr) {
cl_int error = 0;
cl_uint vec_count = ck_padding(count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
int offset = *offset_ptr;
error |= pl_set_kernel_arg_mem(ctx, kernel, offset++, xy_in);
error |= pl_set_kernel_arg_mem(ctx, kernel, offset++, xy_out);
error |= pl_set_kernel_arg_uint(ctx, kernel, offset++, vec_count);
if (!_pl_spheroid_is_spherical(info->tag)) {
error |= pl_set_kernel_arg_float(ctx, kernel, offset++, info->ecc);
error |= pl_set_kernel_arg_float(ctx, kernel, offset++, info->ecc2);
error |= pl_set_kernel_arg_float(ctx, kernel, offset++, info->one_ecc2);
}
*offset_ptr = offset;
return error;
}
cl_kernel pl_find_projection_kernel(PLContext *pl_ctx, PLProjection proj, int fwd, PLSpheroid ell) {
char requested_name[128];
if (fwd) {
sprintf(requested_name, "pl_project_%s_%c", _pl_proj_name(proj), _pl_spheroid_is_spherical(ell) ? 's' : 'e');
} else {
sprintf(requested_name, "pl_unproject_%s_%c", _pl_proj_name(proj), _pl_spheroid_is_spherical(ell) ? 's' : 'e');
}
return pl_find_kernel(pl_ctx, requested_name);
}
static cl_int _pl_enqueue_kernel_1d(cl_command_queue queue, cl_kernel kernel, size_t dim_count) {
cl_int error = CL_SUCCESS;
error = clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &dim_count, NULL, 0, NULL, NULL);
return error;
}
cl_int pl_read_buffer(cl_command_queue queue, cl_mem xy_out_buf, float *xy_out, size_t out_count) {
cl_int error;
error = clEnqueueReadBuffer(queue, xy_out_buf, CL_TRUE, 0, out_count, xy_out, 0, NULL, NULL);
if (error != CL_SUCCESS)
return error;
error = clFinish(queue);
if (error != CL_SUCCESS)
return error;
return CL_SUCCESS;
}
static cl_int _pl_enqueue_projection_kernel(PLContext *pl_ctx, cl_kernel kernel, PLProjection proj, PLProjectionParams *params,
cl_mem xy_in, cl_mem xy_out, size_t count) {
cl_int error = CL_SUCCESS;
int i;
for (i=0; i<sizeof(_pl_projection_info)/sizeof(_pl_projection_info[0]); i++) {
if (_pl_projection_info[i].proj == proj) {
error = _pl_projection_info[i].func(pl_ctx, kernel, params, xy_in, xy_out, count);
break;
}
}
return error;
}
cl_int pl_enqueue_projection_kernel_points(PLContext *pl_ctx, cl_kernel kernel, PLProjection proj, PLProjectionParams *params,
PLProjectionBuffer *pl_buf) {
return _pl_enqueue_projection_kernel(pl_ctx, kernel, proj, params, pl_buf->xy_in, pl_buf->xy_out, pl_buf->count);
}
cl_int pl_enqueue_projection_kernel_grid(PLContext *pl_ctx, cl_kernel kernel, PLProjection proj, PLProjectionParams *params,
PLPointGridBuffer *src, PLPointGridBuffer *dst) {
return _pl_enqueue_projection_kernel(pl_ctx, kernel, proj, params, src->grid, dst->grid, src->width * src->height);
}
cl_int pl_enqueue_kernel_albers_equal_area(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count) {
cl_int error = CL_SUCCESS;
cl_int argc = 0;
size_t vec_count = ck_padding(count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
PLSpheroidInfo info = _pl_get_spheroid_info(params->spheroid);
error = _pl_set_projection_kernel_args(pl_ctx, kernel, xy_in, xy_out, count, &info, &argc);
double phi1 = params->rlat1 * DEG_TO_RAD;
double phi2 = params->rlat2 * DEG_TO_RAD;
double phi0 = params->lat0 * DEG_TO_RAD;
double rho0;
double c, n;
double sinphi, cosphi;
n = sinphi = sin(phi1);
cosphi = cos(phi1);
if (_pl_spheroid_is_spherical(params->spheroid)) {
n = .5 * (sinphi + sin(phi2));
c = 1.0 + sin(phi2) * sinphi;
rho0 = sqrt(c - 2.f * n * sin(phi0));
} else {
double ml1, m1;
m1 = _pl_msfn(sinphi, cosphi, info.ecc2);
ml1 = _pl_qsfn(sinphi, info.ecc, info.one_ecc2);
if (fabs(phi1 - phi2) >= EPS7) {
double ml2, m2;
sinphi = sin(phi2);
cosphi = cos(phi2);
m2 = _pl_msfn(sinphi, cosphi, info.ecc2);
ml2 = _pl_qsfn(sinphi, info.ecc, info.one_ecc2);
n = (m1 * m1 - m2 * m2) / (ml2 - ml1);
}
c = m1 * m1 + ml1 * n;
rho0 = sqrt(c - n * _pl_qsfn(sin(phi0), info.ecc, info.one_ecc2));
}
if (!_pl_spheroid_is_spherical(params->spheroid)) {
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, info.ec);
}
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->scale * info.major_axis / n);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->x0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->y0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->lon0 * DEG_TO_RAD);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, rho0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, c);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, n);
if (error != CL_SUCCESS)
return error;
return _pl_enqueue_kernel_1d(pl_ctx->queue, kernel, vec_count);
}
cl_int pl_enqueue_kernel_american_polyconic(PLContext *pl_ctx,cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count) {
cl_int error;
cl_int offset = 0;
size_t vec_count = ck_padding(count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
PLSpheroidInfo info = _pl_get_spheroid_info(params->spheroid);
error = _pl_set_projection_kernel_args(pl_ctx, kernel, xy_in, xy_out, count, &info, &offset);
double phi0 = params->lat0 * DEG_TO_RAD;
double ml0 = _pl_mlfn(phi0, sin(phi0), cos(phi0), info.en);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->scale * info.major_axis);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->x0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->y0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, phi0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->lon0 * DEG_TO_RAD);
if (!_pl_spheroid_is_spherical(params->spheroid)) {
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, ml0);
error |= pl_set_kernel_arg_float8(pl_ctx, kernel, offset++, info.en);
}
if (error != CL_SUCCESS) {
return error;
}
return _pl_enqueue_kernel_1d(pl_ctx->queue, kernel, vec_count);
}
cl_int pl_enqueue_kernel_lambert_azimuthal_equal_area(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count) {
cl_int error;
cl_int offset = 0;
size_t vec_count = ck_padding(count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
PLSpheroidInfo info = _pl_get_spheroid_info(params->spheroid);
error = _pl_set_projection_kernel_args(pl_ctx, kernel, xy_in, xy_out, count, &info, &offset);
double phi0 = params->lat0 * DEG_TO_RAD;
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->scale * info.major_axis);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->x0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->y0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, phi0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->lon0 * DEG_TO_RAD);
if (_pl_spheroid_is_spherical(params->spheroid)) {
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, sin(phi0));
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, cos(phi0));
} else {
double qp = _pl_qsfn(1.0, info.ecc, info.one_ecc2);
double sinPhi = sin(phi0);
double sinB1 = _pl_qsfn(sinPhi, info.ecc, info.one_ecc2) / qp;
double cosB1 = sqrt(1.0 - sinB1 * sinB1);
double rq = sqrt(0.5 * qp);
double dd = cos(phi0) / (sqrt(1.0 - info.ecc2 * sinPhi * sinPhi) * rq * cosB1);
double ymf = rq / dd;
double xmf = rq * dd;
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, qp);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, sinB1);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, cosB1);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, rq);
error |= pl_set_kernel_arg_float4(pl_ctx, kernel, offset++, info.apa);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, dd);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, xmf);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, ymf);
}
if (error != CL_SUCCESS) {
return error;
}
return _pl_enqueue_kernel_1d(pl_ctx->queue, kernel, vec_count);
}
cl_int pl_enqueue_kernel_lambert_conformal_conic(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count) {
cl_int error;
cl_int offset = 0;
size_t vec_count = ck_padding(count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
PLSpheroidInfo info = _pl_get_spheroid_info(params->spheroid);
error = _pl_set_projection_kernel_args(pl_ctx, kernel, xy_in, xy_out, count, &info, &offset);
double phi0 = params->lat0 * DEG_TO_RAD;
double phi1 = params->rlat1 * DEG_TO_RAD;
double phi2 = params->rlat2 * DEG_TO_RAD;
double rho0, c, n, sinphi1, cosphi1, sinphi2;
int secant = 0;
sinphi1 = sin(phi1);
cosphi1 = cos(phi1);
if (fabs(phi1 - phi2) < 1.e-7) {
n = sinphi1;
} else {
secant = 1;
}
if (_pl_spheroid_is_spherical(params->spheroid)) {
if (secant)
n = log(cosphi1 / cos(phi2)) / (asinh(tan(phi2)) - asinh(tan(phi1)));
c = cosphi1 * pow(tan(M_PI_4 + .5 * phi1), n) / n;
rho0 = c * pow(tan(M_PI_4 + .5 * phi0), -n);
} else {
double m1, ml1;
m1 = _pl_msfn(sinphi1, cosphi1, info.ecc2);
ml1 = _pl_tsfn(phi1, sinphi1, info.ecc);
if (secant) {
sinphi2 = sin(phi2);
n = log(m1 / _pl_msfn(sinphi2, cos(phi2), info.ecc2));
n /= log(ml1 / _pl_tsfn(phi2, sinphi2, info.ecc));
}
c = m1 * pow(ml1, -n) / n;
rho0 = c * pow(_pl_tsfn(phi0, sin(phi0), info.ecc), n);
}
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->scale * info.major_axis);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->x0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->y0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->lon0 * DEG_TO_RAD);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, rho0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, c);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, n);
if (error != CL_SUCCESS) {
return error;
}
return _pl_enqueue_kernel_1d(pl_ctx->queue, kernel, vec_count);
}
cl_int pl_enqueue_kernel_mercator(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count) {
cl_int error;
cl_int offset = 0;
size_t vec_count = ck_padding(count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
PLSpheroidInfo info = _pl_get_spheroid_info(params->spheroid);
error = _pl_set_projection_kernel_args(pl_ctx, kernel, xy_in, xy_out, count, &info, &offset);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->scale * info.major_axis);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->x0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, offset++, params->y0);
if (error != CL_SUCCESS) {
return error;
}
return _pl_enqueue_kernel_1d(pl_ctx->queue, kernel, vec_count);
}
cl_int pl_enqueue_kernel_oblique_stereographic(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count) {
cl_int error = CL_SUCCESS;
cl_int argc = 0;
size_t vec_count = ck_padding(count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
PLSpheroidInfo info = _pl_get_spheroid_info(params->spheroid);
error = _pl_set_projection_kernel_args(pl_ctx, kernel, xy_in, xy_out, count, &info, &argc);
double phi0 = params->lat0 * DEG_TO_RAD;
double sinPhi0, cosPhi0;
sinPhi0 = sin(phi0);
cosPhi0 = cos(phi0);
double sinPhiC0, cosPhiC0;
double scale_r2 = 2.0 * params->scale * info.major_axis * sqrt(info.one_ecc2) / (1.0 - info.ecc2 * sinPhi0 * sinPhi0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, scale_r2);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->x0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->y0);
if (!_pl_spheroid_is_spherical(params->spheroid)) {
double c0 = sqrt(1.0 + info.ecc2 * cosPhi0 * cosPhi0 * cosPhi0 * cosPhi0 / info.one_ecc2);
double phiC0 = asin(sinPhi0 / c0);
sinPhiC0 = sin(phiC0);
cosPhiC0 = cos(phiC0);
double k0 = tan(0.5 * phiC0 + M_PI_4) / (
pow(tan(0.5 * phi0 + M_PI_4), c0) *
pow((1.-info.ecc * sinPhi0)/(1.+info.ecc*sinPhi0), 0.5 * c0 * info.ecc) );
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, c0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, log(k0));
} else {
sinPhiC0 = sinPhi0;
cosPhiC0 = cosPhi0;
}
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->lon0 * DEG_TO_RAD);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, sinPhiC0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, cosPhiC0);
if (error != CL_SUCCESS)
return error;
return _pl_enqueue_kernel_1d(pl_ctx->queue, kernel, vec_count);
}
cl_int pl_enqueue_kernel_robinson(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count) {
cl_int error = CL_SUCCESS;
cl_int argc = 0;
PLSpheroidInfo info = _pl_get_spheroid_info(PL_SPHEROID_SPHERE);
error |= pl_set_kernel_arg_mem(pl_ctx, kernel, argc++, xy_in);
error |= pl_set_kernel_arg_mem(pl_ctx, kernel, argc++, xy_out);
error |= pl_set_kernel_arg_uint(pl_ctx, kernel, argc++, count);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->scale * info.major_axis);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->x0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->y0);
if (error != CL_SUCCESS)
return error;
return _pl_enqueue_kernel_1d(pl_ctx->queue, kernel, count);
}
cl_int pl_enqueue_kernel_transverse_mercator(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count) {
cl_int error = CL_SUCCESS;
cl_int argc = 0;
size_t vec_count = ck_padding(count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
PLSpheroidInfo info = _pl_get_spheroid_info(params->spheroid);
error = _pl_set_projection_kernel_args(pl_ctx, kernel, xy_in, xy_out, count, &info, &argc);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->scale * info.major_axis * info.krueger_A);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->x0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->y0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->lon0 * DEG_TO_RAD);
if (!_pl_spheroid_is_spherical(params->spheroid)) {
error |= pl_set_kernel_arg_float8(pl_ctx, kernel, argc++, info.krueger_alpha);
error |= pl_set_kernel_arg_float8(pl_ctx, kernel, argc++, info.krueger_beta);
}
if (error != CL_SUCCESS)
return error;
return _pl_enqueue_kernel_1d(pl_ctx->queue, kernel, vec_count);
}
cl_int pl_enqueue_kernel_winkel_tripel(PLContext *pl_ctx, cl_kernel kernel,
PLProjectionParams *params, cl_mem xy_in, cl_mem xy_out, size_t count) {
cl_int error = CL_SUCCESS;
int argc = 0;
size_t vec_count = ck_padding(count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
PLSpheroidInfo info = _pl_get_spheroid_info(PL_SPHEROID_SPHERE);
double cosphi1 = isnan(params->rlat1) ? M_2_PI : cos(params->rlat1 * DEG_TO_RAD);
error |= pl_set_kernel_arg_mem(pl_ctx, kernel, argc++, xy_in);
error |= pl_set_kernel_arg_mem(pl_ctx, kernel, argc++, xy_out);
error |= pl_set_kernel_arg_uint(pl_ctx, kernel, argc++, vec_count);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->scale * info.major_axis);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->x0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->y0);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, params->lon0 * DEG_TO_RAD);
error |= pl_set_kernel_arg_float(pl_ctx, kernel, argc++, cosphi1);
if (error != CL_SUCCESS)
return error;
return _pl_enqueue_kernel_1d(pl_ctx->queue, kernel, vec_count);
}
cl_int pl_run_kernel_inverse_geodesic( PLContext *pl_ctx, cl_kernel inv_kernel,
PLInverseGeodesicBuffer *pl_buf, float *dist_out, PLSpheroid pl_ell, double scale) {
int argc = 0;
cl_int error = CL_SUCCESS;
PLSpheroidInfo info = _pl_get_spheroid_info(pl_ell);
size_t xy2VecCount = ck_padding(pl_buf->xy2_count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
error |= pl_set_kernel_arg_mem(pl_ctx, inv_kernel, argc++, pl_buf->xy1_in);
error |= pl_set_kernel_arg_mem(pl_ctx, inv_kernel, argc++, pl_buf->xy2_in);
error |= pl_set_kernel_arg_mem(pl_ctx, inv_kernel, argc++, pl_buf->dist_out);
error |= pl_set_kernel_arg_float(pl_ctx, inv_kernel, argc++, info.major_axis);
if (error != CL_SUCCESS) {
return error;
}
const size_t dim[2] = { pl_buf->xy1_count, xy2VecCount };
error = clEnqueueNDRangeKernel(pl_ctx->queue, inv_kernel, 2, NULL, dim, NULL, 0, NULL, NULL);
if (error != CL_SUCCESS) {
return error;
}
float *dist_pad_out;
size_t pad_count = 2 * pl_buf->xy1_count * ck_padding(pl_buf->xy2_count, PL_FLOAT_VECTOR_SIZE);
if ((dist_pad_out = malloc(sizeof(float) * pad_count)) == NULL) {
return CL_OUT_OF_HOST_MEMORY;
}
error = clEnqueueReadBuffer(pl_ctx->queue, pl_buf->dist_out, CL_TRUE, 0, pad_count * sizeof(cl_float),
dist_pad_out, 0, NULL, NULL);
if (error != CL_SUCCESS) {
free(dist_pad_out);
return error;
}
error = clFinish(pl_ctx->queue);
if (error != CL_SUCCESS) {
free(dist_pad_out);
return error;
}
int j_size = ck_padding(pl_buf->xy2_count, PL_FLOAT_VECTOR_SIZE);
int i, j;
for (i=0; i<pl_buf->xy1_count; i++) {
for (j=0; j<pl_buf->xy2_count; j++) {
dist_out[i*pl_buf->xy2_count+j] = dist_pad_out[i*j_size+j] * scale;
}
}
free(dist_pad_out);
return CL_SUCCESS;
}
cl_int pl_run_kernel_forward_geodesic_fixed_distance(PLContext *pl_ctx, cl_kernel fwd_kernel,
PLForwardGeodesicFixedDistanceBuffer *pl_buf, float *xy_out, PLSpheroid pl_ell, double distance) {
PLSpheroidInfo info = _pl_get_spheroid_info(pl_ell);
int argc = 0;
cl_int error = CL_SUCCESS;
double D, sinD, cosD;
D = distance / info.major_axis;
sinD = sin(D);
cosD = cos(D);
error |= pl_set_kernel_arg_mem(pl_ctx, fwd_kernel, argc++, pl_buf->xy_in);
error |= pl_set_kernel_arg_mem(pl_ctx, fwd_kernel, argc++, pl_buf->phi_sincos);
error |= pl_set_kernel_arg_mem(pl_ctx, fwd_kernel, argc++, pl_buf->az_sincos);
error |= pl_set_kernel_arg_mem(pl_ctx, fwd_kernel, argc++, pl_buf->xy_out);
error |= pl_set_kernel_arg_float(pl_ctx, fwd_kernel, argc++, D);
error |= pl_set_kernel_arg_float(pl_ctx, fwd_kernel, argc++, sinD);
error |= pl_set_kernel_arg_float(pl_ctx, fwd_kernel, argc++, cosD);
if (!_pl_spheroid_is_spherical(pl_ell)) {
double flattening = 1.f/info.inverse_flattening;
error |= pl_set_kernel_arg_float(pl_ctx, fwd_kernel, argc++, flattening);
}
if (error != CL_SUCCESS) {
return error;
}
const size_t dim[2] = { pl_buf->xy_count,
ck_padding(pl_buf->az_count, PL_FLOAT_VECTOR_SIZE)/PL_FLOAT_VECTOR_SIZE };
error = clEnqueueNDRangeKernel(pl_ctx->queue, fwd_kernel, 2, NULL,
dim, NULL, 0, NULL, NULL);
if (error != CL_SUCCESS) {
return error;
}
error = clEnqueueReadBuffer(pl_ctx->queue, pl_buf->xy_out, CL_TRUE, 0,
2 * pl_buf->xy_count * pl_buf->az_count * sizeof(cl_float),
xy_out, 0, NULL, NULL);
if (error != CL_SUCCESS) {
return error;
}
error = clFinish(pl_ctx->queue);
if (error != CL_SUCCESS) {
return error;
}
return CL_SUCCESS;
}
cl_int pl_run_kernel_forward_geodesic_fixed_angle(PLContext *pl_ctx, cl_kernel fwd_kernel,
PLForwardGeodesicFixedAngleBuffer *pl_buf, double xy_in[2], float *xy_out, PLSpheroid pl_ell, double angle) {
int argc = 0;
size_t distVecCount = ck_padding(pl_buf->dist_count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
cl_int error = CL_SUCCESS;
double sinAzimuth = sin(angle);
double cosAzimuth = cos(angle);
error |= pl_set_kernel_arg_float2(pl_ctx, fwd_kernel, argc++, xy_in);
error |= pl_set_kernel_arg_mem(pl_ctx, fwd_kernel, argc++, pl_buf->dist_in);
error |= pl_set_kernel_arg_mem(pl_ctx, fwd_kernel, argc++, pl_buf->xy_out);
error |= pl_set_kernel_arg_float(pl_ctx, fwd_kernel, argc++, angle);
error |= pl_set_kernel_arg_float(pl_ctx, fwd_kernel, argc++, sinAzimuth);
error |= pl_set_kernel_arg_float(pl_ctx, fwd_kernel, argc++, cosAzimuth);
if (error != CL_SUCCESS) {
return error;
}
error = clEnqueueNDRangeKernel(pl_ctx->queue, fwd_kernel, 1, NULL, &distVecCount,
NULL, 0, NULL, NULL);
if (error != CL_SUCCESS) {
return error;
}
error = clEnqueueReadBuffer(pl_ctx->queue, pl_buf->xy_out, CL_TRUE, 0,
2 * pl_buf->dist_count * sizeof(cl_float),
xy_out, 0, NULL, NULL);
if (error != CL_SUCCESS) {
return error;
}
error = clFinish(pl_ctx->queue);
if (error != CL_SUCCESS) {
return error;
}
return CL_SUCCESS;
}
cl_int pl_run_kernel_geodesic_to_cartesian(PLContext *pl_ctx, cl_kernel g2c_kernel,
PLDatumShiftBuffer *pl_buf, PLSpheroid pl_ell) {
PLSpheroidInfo info = _pl_get_spheroid_info(pl_ell);
int argc = 0;
cl_int error = CL_SUCCESS;
size_t vec_count = ck_padding(pl_buf->count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
error |= pl_set_kernel_arg_mem(pl_ctx, g2c_kernel, argc++, pl_buf->xy_in);
error |= pl_set_kernel_arg_mem(pl_ctx, g2c_kernel, argc++, pl_buf->x_rw);
error |= pl_set_kernel_arg_mem(pl_ctx, g2c_kernel, argc++, pl_buf->y_rw);
error |= pl_set_kernel_arg_mem(pl_ctx, g2c_kernel, argc++, pl_buf->z_rw);
error |= pl_set_kernel_arg_float(pl_ctx, g2c_kernel, argc++, info.ecc);
error |= pl_set_kernel_arg_float(pl_ctx, g2c_kernel, argc++, info.ecc2);
error |= pl_set_kernel_arg_float(pl_ctx, g2c_kernel, argc++, info.one_ecc2);
error |= pl_set_kernel_arg_float(pl_ctx, g2c_kernel, argc++, info.major_axis);
error |= pl_set_kernel_arg_float(pl_ctx, g2c_kernel, argc++, info.minor_axis);
if (error != CL_SUCCESS)
return error;
error = clEnqueueNDRangeKernel(pl_ctx->queue, g2c_kernel, 1, NULL, &vec_count, NULL, 0, NULL, NULL);
if (error != CL_SUCCESS)
return error;
error = clFinish(pl_ctx->queue);
if (error != CL_SUCCESS)
return error;
return CL_SUCCESS;
}
/* We cut the computations in half by doing some matrix algebra beforehand.
* Each datum shift is essentially an affine transformation in 3D cartesian
* coordinates. So to get from on datum to another, instead of transforming
* to/from WGS 84, we concatenate the transformation matrix of the source
* datum to the inverse transformation matrix of the destination matrix, and
* then just do a single matrix multiplication on each point instead of two
* in order to transform it.
*/
cl_int pl_run_kernel_transform_cartesian(PLContext *pl_ctx, cl_kernel transform_kernel,
PLDatumShiftBuffer *pl_buf, PLDatum src_datum, PLDatum dst_datum) {
double Rx1, Ry1, Rz1, M1, Dx1, Dy1, Dz1;
double Rx2, Ry2, Rz2, M2, Dx2, Dy2, Dz2;
cl_int error = CL_SUCCESS;
int argc = 0;
size_t vec_count = ck_padding(pl_buf->count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
Dx1 = pl_datum_params[src_datum].dx;
Dy1 = pl_datum_params[src_datum].dy;
Dz1 = pl_datum_params[src_datum].dz;
M1 = pl_datum_params[src_datum].ppm*1.e-6 + 1;
Rx1 = pl_datum_params[src_datum].ex * SEC_TO_RAD;
Ry1 = pl_datum_params[src_datum].ey * SEC_TO_RAD;
Rz1 = pl_datum_params[src_datum].ez * SEC_TO_RAD;
Dx2 = pl_datum_params[dst_datum].dx;
Dy2 = pl_datum_params[dst_datum].dy;
Dz2 = pl_datum_params[dst_datum].dz;
M2 = pl_datum_params[dst_datum].ppm*1.e-6 + 1;
Rx2 = pl_datum_params[dst_datum].ex * SEC_TO_RAD;
Ry2 = pl_datum_params[dst_datum].ey * SEC_TO_RAD;
Rz2 = pl_datum_params[dst_datum].ez * SEC_TO_RAD;
struct pl_matrix matrix1 = pl_affine_transform_make(Rx1, Ry1, Rz1, M1, Dx1, Dy1, Dz1);
struct pl_matrix matrix2 = pl_affine_transform_make(Rx2, Ry2, Rz2, M2, Dx2, Dy2, Dz2);
/* Invert the destination matrix */
__CLPK_integer n = 4;
__CLPK_integer info;
__CLPK_integer ipiv[4];
__CLPK_doublereal work[4];
__CLPK_integer work_n = 4;
dgetrf_(&n, &n, &matrix2.elements[0][0], &n, ipiv, &info);
if (info != 0) {
return info;
}
dgetri_(&n, &matrix2.elements[0][0], &n, ipiv, work, &work_n, &info);
if (info != 0) {
return info;
}
__CLPK_doublereal alpha = 1.0;
__CLPK_doublereal beta = 0.0;
__CLPK_doublereal result_matrix[4][4];
/* Multiply the source matrix with the inverse destination matrix */
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, alpha,
&matrix2.elements[0][0], n,
&matrix1.elements[0][0], n,
beta, &result_matrix[0][0], n);
/* transpose the result and store single-precision */
double tmatrix[4][4];
int i, j;
for (i=0; i<4; i++) {
for (j=0; j<4; j++) {
tmatrix[i][j] = result_matrix[j][i];
}
}
error |= pl_set_kernel_arg_mem(pl_ctx, transform_kernel, argc++, pl_buf->x_rw);
error |= pl_set_kernel_arg_mem(pl_ctx, transform_kernel, argc++, pl_buf->y_rw);
error |= pl_set_kernel_arg_mem(pl_ctx, transform_kernel, argc++, pl_buf->z_rw);
error |= pl_set_kernel_arg_float16(pl_ctx, transform_kernel, argc++, &tmatrix[0][0]);
if (error != CL_SUCCESS)
return error;
error = clEnqueueNDRangeKernel(pl_ctx->queue, transform_kernel, 1, NULL,
&vec_count, NULL, 0, NULL, NULL);
if (error != CL_SUCCESS)
return error;
return error;
}
cl_int pl_run_kernel_cartesian_to_geodesic(PLContext *pl_ctx, cl_kernel c2g_kernel,
PLDatumShiftBuffer *pl_buf, float *xy_out, PLSpheroid pl_ell) {
PLSpheroidInfo info = _pl_get_spheroid_info(pl_ell);
int argc = 0;
cl_int error = CL_SUCCESS;
size_t vec_count = ck_padding(pl_buf->count, PL_FLOAT_VECTOR_SIZE) / PL_FLOAT_VECTOR_SIZE;
error |= pl_set_kernel_arg_mem(pl_ctx, c2g_kernel, argc++, pl_buf->x_rw);
error |= pl_set_kernel_arg_mem(pl_ctx, c2g_kernel, argc++, pl_buf->y_rw);
error |= pl_set_kernel_arg_mem(pl_ctx, c2g_kernel, argc++, pl_buf->z_rw);
error |= pl_set_kernel_arg_mem(pl_ctx, c2g_kernel, argc++, pl_buf->xy_out);
error |= pl_set_kernel_arg_float(pl_ctx, c2g_kernel, argc++, info.ecc);
error |= pl_set_kernel_arg_float(pl_ctx, c2g_kernel, argc++, info.ecc2);
error |= pl_set_kernel_arg_float(pl_ctx, c2g_kernel, argc++, info.one_ecc2);
error |= pl_set_kernel_arg_float(pl_ctx, c2g_kernel, argc++, info.major_axis);
error |= pl_set_kernel_arg_float(pl_ctx, c2g_kernel, argc++, info.minor_axis);
if (error != CL_SUCCESS)
return error;
error = clEnqueueNDRangeKernel(pl_ctx->queue, c2g_kernel, 1, NULL,
&vec_count, NULL, 0, NULL, NULL);
if (error != CL_SUCCESS)
return error;
if (xy_out != NULL) {
error = clEnqueueReadBuffer(pl_ctx->queue, pl_buf->xy_out, CL_TRUE, 0,
2 * pl_buf->count * sizeof(cl_float), xy_out, 0, NULL, NULL);
if (error != CL_SUCCESS)
return error;
}
error = clFinish(pl_ctx->queue);
if (error != CL_SUCCESS)
return error;
return CL_SUCCESS;
}
| {
"alphanum_fraction": 0.6579385094,
"avg_line_length": 39.1945320715,
"ext": "c",
"hexsha": "59a9b28c67bbaa395586e5d74ef3974b408fc516",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2020-09-22T00:23:34.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-13T20:42:42.000Z",
"max_forks_repo_head_hexsha": "d5f06df59bb6814a1c2742eb5f4e9692390dbf1b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "evanmiller/ProjCL",
"max_forks_repo_path": "src/projcl_run.c",
"max_issues_count": 14,
"max_issues_repo_head_hexsha": "d5f06df59bb6814a1c2742eb5f4e9692390dbf1b",
"max_issues_repo_issues_event_max_datetime": "2020-09-04T15:58:31.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-04-09T19:25:03.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "evanmiller/ProjCL",
"max_issues_repo_path": "src/projcl_run.c",
"max_line_length": 151,
"max_stars_count": 50,
"max_stars_repo_head_hexsha": "d5f06df59bb6814a1c2742eb5f4e9692390dbf1b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "evanmiller/ProjCL",
"max_stars_repo_path": "src/projcl_run.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-29T05:04:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-08T19:38:25.000Z",
"num_tokens": 11465,
"size": 37274
} |
/* Internal header file for cminpack, by Frederic Devernay. */
#ifndef __CMINPACKP_H__
#define __CMINPACKP_H__
#ifndef __CMINPACK_H__
#error "cminpackP.h in an internal cminpack header, and must be included after all other headers (including cminpack.h)"
#endif
#if (defined (USE_CBLAS) || defined (USE_LAPACK)) && !defined (__cminpack_double__)
#error "cminpack can use cblas and lapack only in double precision mode"
#endif
#ifdef USE_CBLAS
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#else
#include <cblas.h>
#endif
#define __cminpack_enorm__(n,x) cblas_dnrm2(n,x,1)
#else
#define __cminpack_enorm__(n,x) __cminpack_func__(enorm)(n,x)
#endif
#ifdef USE_LAPACK
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#else
#if defined(__LP64__) /* In LP64 match sizes with the 32 bit ABI */
typedef int __CLPK_integer;
typedef int __CLPK_logical;
typedef float __CLPK_real;
typedef double __CLPK_doublereal;
typedef __CLPK_logical (*__CLPK_L_fp)();
typedef int __CLPK_ftnlen;
#else
typedef long int __CLPK_integer;
typedef long int __CLPK_logical;
typedef float __CLPK_real;
typedef double __CLPK_doublereal;
typedef __CLPK_logical (*__CLPK_L_fp)();
typedef long int __CLPK_ftnlen;
#endif
//extern void dlartg_(double *f, double *g, double *cs, double *sn, double *r__);
int dlartg_(__CLPK_doublereal *f, __CLPK_doublereal *g, __CLPK_doublereal *cs,
__CLPK_doublereal *sn, __CLPK_doublereal *r__)
//extern void dgeqp3_(int *m, int *n, double *a, int *lda, int *jpvt, double *tau, double *work, int *lwork, int *info);
int dgeqp3_(__CLPK_integer *m, __CLPK_integer *n, __CLPK_doublereal *a, __CLPK_integer *
lda, __CLPK_integer *jpvt, __CLPK_doublereal *tau, __CLPK_doublereal *work, __CLPK_integer *lwork,
__CLPK_integer *info)
//extern void dgeqrf_(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
int dgeqrf_(__CLPK_integer *m, __CLPK_integer *n, __CLPK_doublereal *a, __CLPK_integer *
lda, __CLPK_doublereal *tau, __CLPK_doublereal *work, __CLPK_integer *lwork, __CLPK_integer *info)
#endif
#endif
#define real_mp __cminpack_real__
#define minpack_min(a,b) ((a) <= (b) ? (a) : (b))
#define minpack_max(a,b) ((a) >= (b) ? (a) : (b))
#define TRUE_ (1)
#define FALSE_ (0)
#endif /* !__CMINPACKP_H__ */
| {
"alphanum_fraction": 0.7409482759,
"avg_line_length": 36.8253968254,
"ext": "h",
"hexsha": "d2aa28f962ac69056f4d31262b95a75d6a0895a0",
"lang": "C",
"max_forks_count": 291,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T17:51:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-27T21:52:50.000Z",
"max_forks_repo_head_hexsha": "2b7e44716d022e2f62140073dd078c5deeb8bf0a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ptrbortolotti/WISDEM",
"max_forks_repo_path": "wisdem/pymap/src/cminpack/cminpackP.h",
"max_issues_count": 802,
"max_issues_repo_head_hexsha": "2b7e44716d022e2f62140073dd078c5deeb8bf0a",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:32:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-04-17T15:19:30.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ptrbortolotti/WISDEM",
"max_issues_repo_path": "wisdem/pymap/src/cminpack/cminpackP.h",
"max_line_length": 120,
"max_stars_count": 384,
"max_stars_repo_head_hexsha": "2b7e44716d022e2f62140073dd078c5deeb8bf0a",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ptrbortolotti/WISDEM",
"max_stars_repo_path": "wisdem/pymap/src/cminpack/cminpackP.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T22:33:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-13T18:41:22.000Z",
"num_tokens": 777,
"size": 2320
} |
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_chebyshev.h>
double
f (double x, void *p)
{
p = 0;
if (x < 0.5)
return 0.25;
else
return 0.75;
}
int
main (void)
{
double x;
gsl_cheb_series *cs = gsl_cheb_alloc (40);
gsl_function F;
F.function = f;
F.params = 0;
gsl_cheb_init (cs, &F, 0.0, 1.0);
for (x = -1; x < 2; x += 0.001)
{
double r10 = gsl_cheb_eval_n (cs, 10, x);
double r40 = gsl_cheb_eval (cs, x);
printf ("%g %g %g %g\n", x, GSL_FN_EVAL (&F, x), r5, r40);
}
gsl_cheb_free (cs);
}
| {
"alphanum_fraction": 0.5551663748,
"avg_line_length": 14.641025641,
"ext": "c",
"hexsha": "df32f7325363fcc9c30979123ec6b64211a07a9b",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/cheb/demo.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/cheb/demo.c",
"max_line_length": 64,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/cheb/demo.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z",
"num_tokens": 230,
"size": 571
} |
#include <petsc.h>
#include <petsc/private/fortranimpl.h>
#include <omp.h>
//#include <papi.h>
/*
Global Variables
*/
double gradTime; // Gradient calculation time
double fluxTime; // Flux evaluation timing
int nThreads; // Number of threads at each MPI process
int rank; // MPI process ID
int size; // MPI number of running processes
#ifdef HW_COUNTER
int eventset; // PAPI counter context
long long handler; // PAPI counter return value
#endif
/*
FORTRAN routine definitions
*/
#if defined(PETSC_HAVE_FORTRAN_UNDERSCORE)
#define f77name(ucase,lcase,lcbar) lcbar
#elif defined(PETSC_HAVE_FORTRAN_CAPS)
#define f77name(ucase,lcase,lcbar) ucase
#else
#define f77name(ucase,lcase,lcbar) lcase
#endif
/*
Node coordinates in a 3D mesh
*/
struct COORD
{
double *x; // X component
double *y; // Y component
double *z; // Z component
};
/*
Normal to faces and length
*/
struct NORMAL
{
double *len; // Length
struct COORD coord; // X, Y, and Z components
};
/*
Weights for calculating the gradients using least square
*/
struct WEIGHT
{
double *r11; // w11
double *r12; // r12r11
double *r13; // r13r11
double *r22; // w22
double *r23; // r23r22
double *r33; // w33
double *r44; // rmess
};
/*
MeTiS partitioning using for OpenMP
*/
struct THREAD
{
int nedge; // Number edge for all threads with replication
int *partitions; // MeTiS nodes partitioning
int *nedgeLoc; // Number of edges local for each thread
int *eptr; // Edge pointers
struct NORMAL normal; // Normal to faces and length
};
/*
A boundary's elements
*/
struct BOUNDELM
{
int nnode; // Number of nodes
int nfacet; // Number of facets
int *f2nt; // Facet to tetrahedron indices
int *inode; // nodes pointers
struct COORD normal; // Normal to faces
};
/*
Boundaries
*/
struct BOUND
{
int nsbound; // Number of solid boundaries
int nvbound; // Number of viscous boundaries
int nfbound; // Number of free boundaries
struct BOUNDELM solid; // Solid boundary elements
struct BOUNDELM viscs; // Viscous boundary elements
struct BOUNDELM ffild; // Free boundary elements
};
/*
Grid information
*/
typedef struct grid_t
{
int nnodes; // Number of mesh nodes
int nedge; // Number of mesh edges
int *eptr; // Edge pointers array
struct NORMAL normal; // Normal to faces and length
struct COORD coord; // Node Coordinates
struct THREAD thread; // MeTiS subdomain partitioning elements
struct BOUND bound; // Boundaries elements
struct WEIGHT weight; // Least square weights
double *area; // Area of control volumes
double *cdt; // Pseudo-time step for each cell
} GRID;
/*
PETSc data structures
*/
typedef struct gridPETSc_t
{
Vec qnode; // Global distributed solution vector
Vec qnodeLoc; // Local sequential solution vector
Vec res; // Residual vector
Vec grad; // Gradient vector
Mat A; // Left hand side matrix
} GRIDPETSc;
/*
Time step context
*/
typedef struct tstepctx_t
{
/*
A vector state at which to evaluate residual (x) at every
time step (hold the old x vector before proceeding to the
next SNES time step)
*/
Vec qnode;
/*
A vector to put residual (function value) (f) used at every
time step calculation
*/
Vec res;
/*
Courant–Friedrichs–Lewy stability restriction condition
*/
double CFL;
double CFLInit;
double CFLMax;
/*
2-norm of function at current iterate
*/
double fnorm;
double fnormInit;
double fnormRatio;
/*
A flag to indicate that the formFunction is called to compute the
pseudo time step
*/
int isPseudoTimeStep;
/*
Time step counting variable: time step loop iterator (i)
*/
int iTimeStep;
/*
Maximum time steps for the nonlinear solve
*/
int maxTimeSteps;
/*
A flag for local or global time step
*/
int isLocal;
} TstepCtx;
/*
Encapsulate the grid data structure information and time step
data structure information
*/
typedef struct appctx_t
{
GRID *grid; // Pointer to grid info
GRIDPETSc *gridPETSc; // PETSc data structure context
TstepCtx *tsCtx; // Pointer to time stepping context
PetscBool isPreLoading; // Preloading flag (single time step)
} AppCtx;
| {
"alphanum_fraction": 0.6352228473,
"avg_line_length": 25.9662921348,
"ext": "h",
"hexsha": "9db0ba247e2369d87acc2b2650188846a923e531",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-11-04T08:15:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-04T08:15:43.000Z",
"max_forks_repo_head_hexsha": "90d1f221198dbbc980d33532a175127d3735b4e0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ecrc/kfun3d",
"max_forks_repo_path": "archive/base0/defs.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "90d1f221198dbbc980d33532a175127d3735b4e0",
"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": "ecrc/kfun3d",
"max_issues_repo_path": "archive/base0/defs.h",
"max_line_length": 73,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "90d1f221198dbbc980d33532a175127d3735b4e0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ecrc/kfun3d",
"max_stars_repo_path": "archive/base0/defs.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-21T08:38:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-30T01:09:28.000Z",
"num_tokens": 1276,
"size": 4622
} |
#ifndef KGS_GSLSVD_H
#define KGS_GSLSVD_H
#include "math/SVD.h"
#include <gsl/gsl_matrix.h>
class SVDGSL: public SVD {
public:
SVDGSL(gsl_matrix* M): SVD(M){}
protected:
void UpdateFromMatrix() override;
};
#endif //KGS_GSLSVD_H
| {
"alphanum_fraction": 0.7148760331,
"avg_line_length": 12.7368421053,
"ext": "h",
"hexsha": "39b3f414bcec1e054b83c30c400cc3038af9a46b",
"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/SVDGSL.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/SVDGSL.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/SVDGSL.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": 84,
"size": 242
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <pthread.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include "LNAbundance.h"
static int verbose = FALSE;
static int nLines = 9;
static char *usage[] = {"LNAbundance - \n",
"Required parameters:\n",
" -a abundance data\n",
" -in filename parameter file \n",
"Optional:\n",
" -b integer length of sample file to ignore\n",
" -s integer sampling frequency\n",
" -seed long seed random number generator\n",
" -v verbose\n"};
void updateExpectations(double* adExpect, int nMax, double dMDash, double dV, int nS, t_Data *ptData)
{
int i = 0;
for(i = 1; i <= nMax; i++){
int nA = i;
double dLog = 0.0, dP = 0.0;
if(nA < MAX_QUAD){
dLog = logLikelihoodQuad(nA, dMDash, dV);
}
else{
dLog = logLikelihoodRampal(nA, dMDash, dV);
}
dP = exp(dLog);
adExpect[i - 1]+= dP*nS;
}
}
int main(int argc, char* argv[]){
t_Params tParams;
t_LNParams* atLNParams;
int i = 0, nSamples = 0, nMax = 0;
t_Data tData;
double* adExpect = NULL;
gsl_set_error_handler_off();
getCommandLineParams(&tParams, argc, argv);
/*allocate memory for samples*/
atLNParams = (t_LNParams *) malloc(MAX_SAMPLES*sizeof(t_LNParams));
if(!atLNParams)
goto memoryError;
/*read in Monte-Carlo samples*/
readSamples(&tParams, atLNParams, &nSamples);
readAbundanceData(tParams.szAbundFile, &tData);
nMax = tData.aanAbund[tData.nNA - 1][0];
nMax = floor(pow(2.0,ceil(log((double) nMax)/log(2.0)) + 2.0) + 1.0e-7);
adExpect = (double *) malloc(sizeof(double)*nMax);
for(i = 0; i < nMax; i++){
adExpect[i] = 0.0;
}
for(i = 0; i < nSamples; i++){
updateExpectations(adExpect, nMax,
atLNParams[i].dMDash,
atLNParams[i].dV,
atLNParams[i].nS,
&tData);
}
for(i = 1; i <= nMax; i++){
printf("%d %f\n",i,adExpect[i - 1]/((double) nSamples));
}
free(adExpect);
exit(EXIT_SUCCESS);
memoryError:
fprintf(stderr, "Failed to allocate memory in main aborting ...\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
int intCompare(const void *pvA, const void *pvB)
{
int* pnA = (int *) pvA, *pnB = (int *) pvB;
if(*pnA < *pnB)
return +1;
else if(*pnA == *pnB){
return 0;
}
else{
return -1;
}
}
int doubleCompare(const void *pvA, const void *pvB)
{
double* pnA = (double *) pvA, *pnB = (double *) pvB;
if(*pnA < *pnB)
return +1;
else if(*pnA == *pnB){
return 0;
}
else{
return -1;
}
}
void writeUsage(FILE* ofp)
{
int i = 0;
char *line;
for(i = 0; i < nLines; i++){
line = usage[i];
fputs(line,ofp);
}
}
char *extractParameter(int argc, char **argv, char *param,int when)
{
int i = 0;
while((i < argc) && (strcmp(param,argv[i]))){
i++;
}
if(i < argc - 1){
return(argv[i + 1]);
}
if((i == argc - 1) && (when == OPTION)){
return "";
}
if(when == ALWAYS){
fprintf(stdout,"Can't find asked option %s\n",param);
}
return (char *) NULL;
}
void getCommandLineParams(t_Params *ptParams,int argc,char *argv[])
{
char *szTemp = NULL;
char *cError = NULL;
/*get parameter file name*/
ptParams->szInputFile = extractParameter(argc,argv, INPUT_FILE,ALWAYS);
if(ptParams->szInputFile == NULL)
goto error;
/*get abundance file name*/
ptParams->szAbundFile = extractParameter(argc,argv, ABUND_FILE,ALWAYS);
if(ptParams->szAbundFile == NULL)
goto error;
/*get long seed*/
szTemp = extractParameter(argc,argv,SEED,OPTION);
if(szTemp != NULL){
ptParams->lSeed = strtol(szTemp,&cError,10);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->lSeed = 0;
}
/*get burn*/
szTemp = extractParameter(argc, argv, BURN, OPTION);
if(szTemp != NULL){
ptParams->nBurn = strtol(szTemp,&cError,10);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->nBurn = DEF_BURN;
}
/*get long seed*/
szTemp = extractParameter(argc, argv, SAMPLE, OPTION);
if(szTemp != NULL){
ptParams->nSample = strtol(szTemp,&cError,10);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->nSample = DEF_SAMPLE;
}
/*verbosity*/
szTemp = extractParameter(argc, argv, VERBOSE, OPTION);
if(szTemp != NULL){
verbose = TRUE;
}
return;
error:
writeUsage(stdout);
exit(EXIT_FAILURE);
}
void readSamples(t_Params *ptParams, t_LNParams *atLNParams, int *pnSamples)
{
int nSamples = 0;
char *szInputFile = ptParams->szInputFile;
char szLine[MAX_LINE_LENGTH];
FILE *ifp = NULL;
ifp = fopen(szInputFile, "r");
if(ifp){
while(fgets(szLine, MAX_LINE_LENGTH, ifp)){
char *szTok = NULL, *szBrk = NULL, *pcError = NULL;
int nTime = 0;
/*remove trailing new line*/
szBrk = strpbrk(szLine, "\n"); (*szBrk) = '\0';
szTok = strtok(szLine, DELIM);
nTime = strtol(szTok, &pcError, 10);
if(*pcError != '\0') goto fileFormatError;
if(nTime > ptParams->nBurn && nTime % ptParams->nSample == 0){
szTok = strtok(NULL,DELIM);
atLNParams[nSamples].dMDash = strtod(szTok, &pcError);
if(*pcError != '\0') goto fileFormatError;
szTok = strtok(NULL,DELIM);
atLNParams[nSamples].dV = strtod(szTok, &pcError);
if(*pcError != '\0') goto fileFormatError;
szTok = strtok(NULL,DELIM);
atLNParams[nSamples].nS = strtol(szTok, &pcError, 10);
if(*pcError != '\0') goto fileFormatError;
nSamples++;
}
}
fclose(ifp);
}
else{
fprintf(stderr, "Failed to open file %s aborting\n", szInputFile);
fflush(stderr);
exit(EXIT_FAILURE);
}
(*pnSamples) = nSamples;
return;
fileFormatError:
fprintf(stderr, "Incorrectly formatted input file aborting\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
double f1(double x, void *pvParams)
{
t_LNParams *ptLNParams = (t_LNParams *) pvParams;
double dMDash = ptLNParams->dMDash, dV = ptLNParams->dV, n = ptLNParams->n;
double dTemp = (x - dMDash);
double dExp = x*((double) n) - exp(x) - 0.5*((dTemp*dTemp)/dV);
double dRet = exp(dExp);
return dRet;
}
double logLikelihoodRampal(int n, double dMDash, double dV)
{
double dN = (double) n;
double dLogLik = 0.0, dTemp = gsl_pow_int(log(dN) - dMDash,2), dTemp3 = gsl_pow_int(log(dN) - dMDash,3);
dLogLik = -0.5*log(2.0*M_PI*dV) - log(dN) - (dTemp/(2.0*dV));
dLogLik += log(1.0 + 1.0/(2.0*dN*dV)*(dTemp/dV + log(dN) - dMDash - 1.0)
+ 1.0/(6.0*dN*dN*dV*dV*dV)*(3.0*dV*dV - (3.0*dV - 2.0*dV*dV)*(dMDash - log(dN))
- 3.0*dV*dTemp + dTemp3));
return dLogLik;
}
double logLikelihoodQuad(int n, double dMDash, double dV)
{
gsl_integration_workspace *ptGSLWS =
gsl_integration_workspace_alloc(1000);
double dLogFac1 = 0.0, dLogFacN = 0.0;
double dResult = 0.0, dError = 0.0, dPrecision = 0.0;
gsl_function tGSLF;
t_LNParams tLNParams;
double dEst = dMDash + ((double)n)*dV, dA = 0.0, dB = 0.0;
tLNParams.n = n; tLNParams.dMDash = dMDash; tLNParams.dV = dV;
tGSLF.function = &f1;
tGSLF.params = (void *) &tLNParams;
dLogFac1 = log(2.0*M_PI*dV);
if(n < 50){
dLogFacN = gsl_sf_fact(n);
dLogFacN = log(dLogFacN);
}
else{
dLogFacN = gsl_sf_lngamma(((double) n) + 1.0);
}
if(dEst > dV){
double dMax = 0.0;
double dUpper = (((double) n) + (dMDash/dV) - 1.0)/(1.0 + 1.0/dV);
double dVar = 0.0;
solveF(0.0, dUpper, derivExponent, (void *) &tLNParams, 1.0e-5, &dMax);
dVar = sqrt(1.0/((1.0/dV) + exp(dMax)));
dA = dMax - V_MULT*dVar; dB = dMax + V_MULT*dVar;
}
else{
double dMax = 0.0;
double dLower = dEst - dV;
double dUpper = (((double) n) + (dMDash/dV) - 1.0)/(1.0 + 1.0/dV);
double dVar = 0.0;
solveF(dLower, dUpper, derivExponent, (void *) &tLNParams, 1.0e-5, &dMax);
dVar = sqrt(1.0/((1.0/dV) + exp(dMax)));
dA = dMax - V_MULT*dVar; dB = dMax + V_MULT*dVar;
}
if(n < 10){
dPrecision = HI_PRECISION;
}
else{
dPrecision = LO_PRECISION;
}
gsl_integration_qag(&tGSLF, dA, dB, dPrecision, 0.0, 1000, GSL_INTEG_GAUSS61, ptGSLWS, &dResult, &dError);
gsl_integration_workspace_free(ptGSLWS);
return log(dResult) - dLogFacN -0.5*dLogFac1;
}
double derivExponent(double x, void *pvParams)
{
t_LNParams *ptLNParams = (t_LNParams *) pvParams;
double dMDash = ptLNParams->dMDash, dV = ptLNParams->dV, n = ptLNParams->n;
double dTemp = (x - dMDash)/dV, dRet = 0.0;
dRet = ((double) n) - exp(x) - dTemp;
return dRet;
}
int solveF(double x_lo, double x_hi, double (*f)(double, void*),
void* params, double tol, double *xsolve)
{
int status, iter = 0, max_iter = 100;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
double r = 0;
gsl_function F;
F.function = f;
F.params = params;
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc (T);
gsl_root_fsolver_set (s, &F, x_lo, x_hi);
do{
iter++;
status = gsl_root_fsolver_iterate (s);
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, tol);
}
while (status == GSL_CONTINUE && iter < max_iter);
(*xsolve) = gsl_root_fsolver_root (s);
gsl_root_fsolver_free (s);
return status;
}
void readAbundanceData(const char *szFile, t_Data *ptData)
{
int **aanAbund = NULL;
int i = 0, nNA = 0, nA = 0, nC = 0;
int nL = 0, nJ = 0;
char szLine[MAX_LINE_LENGTH];
FILE* ifp = NULL;
ifp = fopen(szFile, "r");
if(ifp){
char* szTok = NULL;
char* pcError = NULL;
fgets(szLine, MAX_LINE_LENGTH, ifp);
szTok = strtok(szLine, DELIM2);
nNA = strtol(szTok,&pcError,10);
if(*pcError != '\0'){
goto formatError;
}
aanAbund = (int **) malloc(nNA*sizeof(int*));
for(i = 0; i < nNA; i++){
aanAbund[i] = (int *) malloc(sizeof(int)*2);
fgets(szLine, MAX_LINE_LENGTH, ifp);
szTok = strtok(szLine, DELIM2);
nA = strtol(szTok,&pcError,10);
if(*pcError != '\0'){
goto formatError;
}
szTok = strtok(NULL, DELIM2);
nC = strtol(szTok,&pcError,10);
if(*pcError != '\0'){
goto formatError;
}
nL += nC;
nJ += nC*nA;
aanAbund[i][0] = nA;
aanAbund[i][1] = nC;
}
}
else{
fprintf(stderr, "Failed to open abundance data file %s aborting\n", szFile);
fflush(stderr);
exit(EXIT_FAILURE);
}
ptData->nJ = nJ;
ptData->nL = nL;
ptData->aanAbund = aanAbund;
ptData->nNA = nNA;
return;
formatError:
fprintf(stderr, "Incorrectly formatted abundance data file\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
| {
"alphanum_fraction": 0.598134227,
"avg_line_length": 22.5326530612,
"ext": "c",
"hexsha": "0700d4362e761e306e9ca66b40d58656a620b6ea",
"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": "f8ce1a8afd10311420227a6259739c7938695b79",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "chrisquince/DiversityEstimates",
"max_forks_repo_path": "LNAbundance/LNAbundance.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79",
"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": "chrisquince/DiversityEstimates",
"max_issues_repo_path": "LNAbundance/LNAbundance.c",
"max_line_length": 108,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "chrisquince/DiversityEstimates",
"max_stars_repo_path": "LNAbundance/LNAbundance.c",
"max_stars_repo_stars_event_max_datetime": "2019-03-19T13:22:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-18T17:56:16.000Z",
"num_tokens": 3810,
"size": 11041
} |
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_fit.h>
#include "cosmocalc.h"
double transfer_function(double k)
{
static int initFlag = 1;
static int currCosmoNum;
static gsl_spline *cosmocalc_transfer_function_spline = NULL;
static gsl_interp_accel *cosmocalc_transfer_function_acc = NULL;
static double c0,c1;
double transfer_function_table[COSMOCALC_TRANSFER_FUNCTION_TABLE_LENGTH];
double k_table[COSMOCALC_TRANSFER_FUNCTION_TABLE_LENGTH];
long i;
double cov00,cov01,cov11,sumsq;
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
for(i=0;i<COSMOCALC_TRANSFER_FUNCTION_TABLE_LENGTH;++i)
{
k_table[i] = log(K_MAX/K_MIN)/(COSMOCALC_TRANSFER_FUNCTION_TABLE_LENGTH-1.0)*((double) i) + log(K_MIN);
if(cosmoData.useSmoothTransFunc)
transfer_function_table[i] = log(transfunct_eh98_smooth(exp(k_table[i])));
else if(cosmoData.useNoTransFunc)
transfer_function_table[i] = 0.0;
else
transfer_function_table[i] = log(transfunct_eh98(exp(k_table[i])));
}
//init the spline and accelerators
if(cosmocalc_transfer_function_spline != NULL)
gsl_spline_free(cosmocalc_transfer_function_spline);
cosmocalc_transfer_function_spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_TRANSFER_FUNCTION_TABLE_LENGTH));
gsl_spline_init(cosmocalc_transfer_function_spline,k_table,transfer_function_table,(size_t) (COSMOCALC_TRANSFER_FUNCTION_TABLE_LENGTH));
if(cosmocalc_transfer_function_acc != NULL)
gsl_interp_accel_reset(cosmocalc_transfer_function_acc);
else
cosmocalc_transfer_function_acc = gsl_interp_accel_alloc();
gsl_fit_linear(k_table+COSMOCALC_TRANSFER_FUNCTION_TABLE_LENGTH-COSMOCALC_TRANSFER_FUNCTION_FIT_LENGTH,(size_t) 1,
transfer_function_table+COSMOCALC_TRANSFER_FUNCTION_TABLE_LENGTH-COSMOCALC_TRANSFER_FUNCTION_FIT_LENGTH,(size_t) 1,
(size_t) COSMOCALC_TRANSFER_FUNCTION_FIT_LENGTH,&c0,&c1,&cov00,&cov01,&cov11,&sumsq);
}
if(k < K_MIN)
return 1.0;
else if(k < K_MAX)
return exp(gsl_spline_eval(cosmocalc_transfer_function_spline,log(k),cosmocalc_transfer_function_acc));
else
return exp(c0+c1*log(k));
}
#define USEPAPER_EH98
double transfunct_eh98(double kin)
{
//vars
double k;
double Tk,Tb,Tc,T0t,T0t11,T0t1bc;
double omb,om0,omc,h;
double theta2p7,f,ac,bc,s,q;
double C,C11,C1bc,st,bb,ab,ksilk,bnode,Gy,y,zeq;
double a1,a2,b1,b2,keq,Rd,zd,Req,b1d,b2d;
//get cosmoparms
omb = cosmoData.OmegaB;
om0 = cosmoData.OmegaM;
omc = cosmoData.OmegaM - cosmoData.OmegaB;
h = cosmoData.h;
//convert k from hMpc^-1 to Mpc^-1
k = kin*h;
//-----------
//input parms
//-----------
theta2p7 = TCMB/2.7;
//eqn 2
zeq = 2.50e4*om0*h*h/(theta2p7*theta2p7*theta2p7*theta2p7);
//eqn 3
keq = 7.46e-2*om0*h*h/(theta2p7*theta2p7); //Mpc^-{1} (NOT h/Mpc)
//eqn 4
b1d = 0.313*pow(om0*h*h,-0.419)*(1.0 + 0.607*pow(om0*h*h,0.674));
b2d = 0.238*pow(om0*h*h,0.223);
zd = 1291.0*pow(om0*h*h,0.251)/(1.0 + 0.659*pow(om0*h*h,0.828))
*(1.0 + b1d*pow(omb*h*h,b2d));
//eqn 5
#ifdef USEPAPER_EH98
Rd = 31.5*omb*h*h
/(theta2p7*theta2p7*theta2p7*theta2p7)
/((zd)/1e3); //matches wayne's paper, but not the code (zd -> 1+zd)
//fprintf(stderr,"paper eh 98 1\n");
#else
Rd = 31.5*omb*h*h
/(theta2p7*theta2p7*theta2p7*theta2p7)
/((1.0+zd)/1e3);
#endif
Req = 31.5*omb*h*h/(theta2p7*theta2p7*theta2p7*theta2p7)/(zeq/1e3);
//eqn 6
s = 2.0/3.0/keq*sqrt(6.0/Req)*
log((sqrt(1.0 + Rd) + sqrt(Rd + Req))/(1.0 + sqrt(Req)));
//eqn 7
ksilk = 1.6*pow(omb*h*h,0.52)*pow(om0*h*h,0.73)*(1.0 + pow(10.4*om0*h*h,-0.95));
//eqn 10
q = k/13.41/keq;
//eqn 11
a1 = pow(46.9*om0*h*h,0.670)*(1.0 + pow(32.1*om0*h*h,-0.532));
a2 = pow(12.0*om0*h*h,0.424)*(1.0 + pow(45.0*om0*h*h,-0.582));
ac = pow(a1,-1.0*omb/om0)*pow(a2,-1.0*(omb/om0)*(omb/om0)*(omb/om0));
//eqn 12
b1 = 0.944/(1.0 + pow(458.0*om0*h*h,-0.708));
b2 = pow(0.395*om0*h*h,-0.0266);
bc = 1.0/(1.0 + b1*(pow(omc/om0,b2) - 1.0));
//eqn 15
#ifdef USEPAPER_EH98
y = (1.0 + zeq)/(1.0 + zd); //matches wayne's paper, but not the code (1+zeq -> zeq)
//fprintf(stderr,"paper eh 98 2\n");
#else
y = (zeq)/(1.0 + zd);
#endif
Gy = y*(-6.0*sqrt(1.0 + y) + (2.0 + 3.0*y)*log((sqrt(1.0 + y) + 1.0)/(sqrt(1.0 + y) - 1.0)));
//eqn 14
ab = 2.07*keq*s*pow(1.0 + Rd,-3.0/4.0)*Gy;
//----------------------------------
// Get CDM part of transfer function
//----------------------------------
//eqn 18
f = 1.0/(1.0 + (k*s/5.4)*(k*s/5.4)*(k*s/5.4)*(k*s/5.4));
//eqn 20
C = 14.2/ac + 386.0/(1.0 + 69.9*pow(q,1.08));
//eqn 19
T0t = log(M_E + 1.8*bc*q)/(log(M_E + 1.8*bc*q) + C*q*q);
//eqn 17
C1bc = 14.2 + 386.0/(1.0 + 69.9*pow(q,1.08));
T0t1bc = log(M_E + 1.8*bc*q)/(log(M_E + 1.8*bc*q) + C1bc*q*q);
Tc = f*T0t1bc + (1.0 - f)*T0t;
//-------------------------------------
// Get baryon part of transfer function
//-------------------------------------
//eqn 24
bb = 0.5 + omb/om0 + (3.0 - 2.0*omb/om0)*sqrt((17.2*om0*h*h)*(17.2*om0*h*h) + 1.0);
//eqn 23
bnode = 8.41*pow(om0*h*h,0.435);
//eqn 22
st = s/pow(1.0 + (bnode/k/s)*(bnode/k/s)*(bnode/k/s),1.0/3.0);
//eqn 21
C11 = 14.2 + 386.0/(1.0 + 69.9*pow(q,1.08));
T0t11 = log(M_E + 1.8*q)/(log(M_E + 1.8*q) + C11*q*q);
Tb = (T0t11/(1.0 + (k*s/5.2)*(k*s/5.2))
+ ab/(1.0 + (bb/k/s)*(bb/k/s)*(bb/k/s))/exp(pow(k/ksilk,1.4)))*sin(k*st)/(k*st);
//------------------------
// total transfer function
//------------------------
Tk = omb/om0*Tb + omc/om0*Tc;
return Tk;
}
double transfunct_eh98_smooth(double kin)
{
//vars
double k,Tk;
double omb,om0,omc,h;
double theta2p7,s,q;
double Gamma,alphaGamma,L0,C0;
//get cosmoparms
omb = cosmoData.OmegaB;
om0 = cosmoData.OmegaM;
omc = cosmoData.OmegaM - cosmoData.OmegaB;
h = cosmoData.h;
//convert k from hMpc^-1 to Mpc^-1
k = kin*h;
//-----------
//input parms
//-----------
theta2p7 = TCMB/2.7;
//eqn 26
s = 44.5*log(9.83/om0/h/h)/sqrt(1.0 + 10.0*pow(omb*h*h,0.75));
//eqn 31
alphaGamma = 1.0 - 0.328*log(431.0*om0*h*h)*omb/om0 + 0.38*log(22.3*om0*h*h)*(omb/om0)*(omb/om0);
//eqn 30
Gamma = om0*h*(alphaGamma + (1.0 - alphaGamma)/(1.0 + pow(0.43*k*s,4.0)));
//eqn 28
q = kin*theta2p7*theta2p7/Gamma;
//eqns 29
C0 = 14.2 + 731.0/(1.0 + 62.5*q);
L0 = log(2.0*exp(1.0) + 1.8*q);
Tk = L0/(L0 + C0*q*q);
return Tk;
}
| {
"alphanum_fraction": 0.5930627306,
"avg_line_length": 29.329004329,
"ext": "c",
"hexsha": "81c616fafd3b75978fec8cf9c138c03d967d6b9e",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z",
"max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "beckermr/cosmocalc",
"max_forks_repo_path": "src/transfer_function.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "beckermr/cosmocalc",
"max_issues_repo_path": "src/transfer_function.c",
"max_line_length": 142,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "beckermr/cosmocalc",
"max_stars_repo_path": "src/transfer_function.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2790,
"size": 6775
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.